From 8081b9b9d9d776443d385d0a59cd388fb9f50eb9 Mon Sep 17 00:00:00 2001 From: Timothy Date: Sat, 29 Aug 2026 01:53:08 +0200 Subject: [PATCH] fix(819): make the scope restatement closed-form, and state that as the criterion MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Round 5's cold review found the class a fifth time, and it was a BLOCKER rather than a narrowing. The restatement inlined both documented components but computed its filename with `basename(path)` — the same helper `isInScopeSourcePath` calls — so `basename` sat on both sides of the comparison and cancelled, exactly as the filename predicate did in round 4 and the path table in round 3. MEASURED on the previous head: teaching `basename` to return '' for paths four segments deep removed 15 real tracked files, and a `pageSize: 100` planted in one of them (`src/builder/rules/compile.ts`) went completely unseen — 36/36 green. Reproduced here before fixing. The guard did not merely see less; it stopped working and reported success. An `index.ts` variant hid 3 more. What actually terminates this, and why the previous four attempts did not: each one restated something and left something else SHARED, and "restate the scope" gives no way to tell whether you are done. The criterion is now a checkable property, written where the next author will edit: the restatement must be CLOSED FORM over the raw path — it may share NO helper, at ANY depth, with `isInScopeSourcePath`. `basename` is why it is phrased that way: it reads as plumbing rather than as policy, which is precisely why it got shared. The inlined `lastIndexOf` carries a "do not tidy this into basename(path)" note for the same reason. Both mutations above now redden `the shared scope predicate is EXACTLY its two documented components`, including with the rogue site planted. The previous head also ASSERTED that its residuals were complete, which this blocker falsifies — a single-site edit to a shared helper narrowed scope invisibly. Both the code comment and `docs/guard-inventory.md` now record the three retracted mechanisms with what each one measured, and state the two residuals as residuals rather than as closure. Also from round 5: - The anti-vacuity floor fired at 15 unstaged in-scope deletions with a bare assertion message, inside a test whose own failure text tells the reader to rename files or widen the glob. Wrong cause, and the #806 shape. It now carries its own message naming deletions first and a degenerate plugin result second. - The Dockerfile's `docs_only` claim stated an accident as the rule. `ci-detect-docs-only.sh` classifies by PATH SHAPE (`docs/` or `*.md`), not by directory, so "any `web/**` path is not docs-only" is true only because no `web/*.md` is tracked. Restated, with `design-system/` named too. - `ABSENT_FROM_DISK` emptied is an uncaught mutation. Recorded as a residual with its DIRECTION, which is what makes it tolerable: an empty set makes the guard red on an unstaged deletion, never blind. - The decision record's `signals:` line carried neither the bounded exception's vocabulary nor #819, so the record's discovery surface did not carry the change its `rule:` makes. - A worked example still named `src/api/generated/v1.ts`; the tracked file is `v1.d.ts`. Swept both tables this time rather than the one site. Refs: #819 Decisions-Edit: yes --- docker/Dockerfile | 7 ++- .../guard-derives-population-from-source.md | 2 +- docs/guard-inventory.md | 2 +- web/src/api/pageSizeCallSites.guard.test.ts | 63 ++++++++++++++----- 4 files changed, 54 insertions(+), 20 deletions(-) diff --git a/docker/Dockerfile b/docker/Dockerfile index 3fae769e6..16f6b0542 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -21,8 +21,11 @@ WORKDIR /source/web # on a push to `main` whose tree is byte-identical to an already-green head, the suite is skipped # and the image still builds — the property holds there via #420's byte-identical-tree argument, # not via the dependency edge. The `docs_only` arm holds by a different argument again: -# `scripts/ci-detect-docs-only.sh` classifies any `web/**` path as NOT docs-only, so a tree that -# takes that skip has an SPA subtree identical to one already tested. Either way the suite ran against that tree; running it a second time +# `scripts/ci-detect-docs-only.sh` treats a path as docs only when it is under `docs/` or ends +# `.md`, so any change to a `.ts`/`.tsx`/`.css` file under `web/` (or to `design-system/`, also in +# this stage's context) defeats the skip. A tree that takes it therefore has a build input subtree +# identical to one already tested. Note the rule is by PATH SHAPE, not by directory: a `web/*.md` +# would count as docs — there are none today, but do not restate this as "any `web/**` path". Either way the suite ran against that tree; running it a second time # here only duplicated the work. Building the image by hand still lints, typechecks and builds; run # `npm test` in a checkout for the rest. RUN npm run lint && npm run typecheck && npm run build diff --git a/docs/decisions/records/testing/guard-derives-population-from-source.md b/docs/decisions/records/testing/guard-derives-population-from-source.md index ee69c6fe9..67d1d4d53 100644 --- a/docs/decisions/records/testing/guard-derives-population-from-source.md +++ b/docs/decisions/records/testing/guard-derives-population-from-source.md @@ -6,7 +6,7 @@ since: '2026-08-13' supersedes: none superseded-by: none rule: 'A guard that asserts a COMPLETENESS property enumerates its population from a machine-readable authoritative source — the enum, the generated OpenAPI document, the parsed workflow YAML, the provider list — and asserts SET EQUALITY in BOTH directions against it. It may not narrow that population with a filter, a `Where`, a `grep` or an early `continue` before the assertion, because a filter cannot see the member that is MISSING: the member whose absence is the defect is precisely the one the predicate excludes. A hand-written literal list of members is the same defect in slower motion — a filter frozen at authoring time, correct on the day it was written and unable to report the day it stopped being. Two boundaries bound the rule rather than weaken it. FIRST, filtering to select the SUBJECT of a PER-MEMBER property is legitimate and is not this defect: the excluded members satisfy the property vacuously, so the filtered walk and the whole walk assert the same thing (`ToolCatalogTests.Every_Query_Parameter_Should_Be_A_Declared_Property` filters to tools that declare query parameters, and a tool declaring none has nothing to check). The defect is filtering the population before a COMPLETENESS claim, which is what makes an absent member unrepresentable (#757 filtered on `QueryParameters is {Count: > 0}` and so could not see a tool that should have declared one and did not). SECOND, a population of VALUES always has an external authoritative source and this rule applies directly; a population of SITES IN CODE has no such list, needs find-all-references tooling, and is tracked separately in #777 — do not stretch a set-equality assertion over it. Distinguish the guard SCOPE (which subsystems it covers — a reviewed policy choice, legitimately hand-written) from the guard POPULATION (the members inside that scope — always derived). When the scope itself MIRRORS an authoritative source, the mirror needs its own equality check against that source, or the guard is complete within a scope that has silently gone stale. A DATED STALENESS MARKER does not discharge this and is no longer offered as an alternative (#787): a date records when someone last looked, so it goes stale in exactly the circumstance it exists to report, and nothing reddens when it does. The canonical worked example in this repo is `ToolCatalogTests.Every_Tool_Should_Declare_Exactly_Its_OpenApi_Query_Parameters`. When a scope mirrors an authoritative source across a CREDENTIAL BOUNDARY, split the invariant at that boundary rather than dating a comment: commit the mirror verbatim, derive the scope from it offline, and reconcile the mirror against the live source wherever a credential exists — `MARKED_JOBS` in `scripts/tests/test_ci_dropped_step_guard.py` was this repo''s residual gap until #787 closed it that way. WHEN THE POPULATION IS FILES (#806), the authoritative source is the GIT INDEX and never a filesystem walk. A walk is not merely a weaker enumerator, it answers a question about the MACHINE rather than about the repo: it reports build output, generated shims and editor droppings, and it differs between CI and every checkout, so the same guard asserts a different population in each place. Derive with `git ls-files`, take direct children only unless a nested population is stated and wanted, and assert existence rather than filtering on it, because filtering is what makes a missing member unrepresentable. ONE BOUNDED EXCEPTION to that existence half (#819): a guard MAY filter on existence where the OTHER direction reports the on-disk hole — where a tracked path that never reached the walk is itself compared and NAMED — since what makes filtering dangerous is the absent member becoming unrepresentable, and a paired assertion represents it. That buys tolerance of a state the assert-existence form cannot distinguish, which matters where the population is large and edited continuously and an unstaged deletion is routine rather than remarkable. Filtering on existence WITHOUT that paired direction stays the original defect. This is an instantiation and not a blanket rewrite: the question per guard remains whether it makes a COMPLETENESS claim over TRACKED files, and a walk that assembles a fixture or selects the SUBJECT of a per-member property stays a walk with its reason written down.' -signals: 'guard derives population · set equality both directions · never filter never sample · a filter cannot see the missing member · hardcoded list is a frozen filter · missing vs phantom · unreachable vs phantom query parameter · anti-vacuity count guard · accumulate drift do not fail fast · scope versus population · dated mirror of branch protection · `status_check_contexts` · `MARKED_JOBS` · scope mirror across a credential boundary · split the invariant at the boundary · synthesise contexts do not parse them · one classifier two callers · paths: `.gitea/required-status-contexts.json`, `scripts/check-required-contexts.sh`, `scripts/lib/branch-rule-classifier.jq` · values versus sites-in-code · paths: `ErsatzTV.Mcp.Tests/ToolCatalogTests.cs`, `scripts/tests/test_ci_dropped_step_guard.py`, `web/src/api/pageSizeCallSites.guard.test.ts` · file population from the git index · never a filesystem walk · untracked shims redden every checkout · `.husky/_/` · direct children not rglob · paths: `scripts/tests/tracked_files.py`, `scripts/tests/test_guard_populations_derive_from_git.py`, `docs/guard-inventory.md` · issues: #806, #778, #774, #773, #757, #671, #650, #644, #633, #616, #503, #403' +signals: 'guard derives population · set equality both directions · never filter never sample · a filter cannot see the missing member · hardcoded list is a frozen filter · missing vs phantom · unreachable vs phantom query parameter · anti-vacuity count guard · accumulate drift do not fail fast · scope versus population · dated mirror of branch protection · `status_check_contexts` · `MARKED_JOBS` · scope mirror across a credential boundary · split the invariant at the boundary · synthesise contexts do not parse them · one classifier two callers · paths: `.gitea/required-status-contexts.json`, `scripts/check-required-contexts.sh`, `scripts/lib/branch-rule-classifier.jq` · values versus sites-in-code · paths: `ErsatzTV.Mcp.Tests/ToolCatalogTests.cs`, `scripts/tests/test_ci_dropped_step_guard.py`, `web/src/api/pageSizeCallSites.guard.test.ts` · file population from the git index · never a filesystem walk · bounded exception: filter on existence only when the other direction NAMES the on-disk hole · unstaged deletion is routine in a large edited population · a restatement proving a scope must be CLOSED FORM, sharing no helper with the predicate it checks · untracked shims redden every checkout · `.husky/_/` · direct children not rglob · paths: `scripts/tests/tracked_files.py`, `scripts/tests/test_guard_populations_derive_from_git.py`, `docs/guard-inventory.md` · issues: #819, #806, #778, #774, #773, #757, #671, #650, #644, #633, #616, #503, #403' mechanics: 'Both directions are named separately in the failure message — `missing`/`unreachable` (in the source, absent from the guarded set) and `phantom` (in the guarded set, absent from the source) — because the two are different defects and a single "sets differ" line invites fixing one and re-running.' --- diff --git a/docs/guard-inventory.md b/docs/guard-inventory.md index ea927e9ca..3b276b60f 100644 --- a/docs/guard-inventory.md +++ b/docs/guard-inventory.md @@ -164,7 +164,7 @@ The audit #806 asked for, recorded whichever way it came out, because "we looked | `test_workflow_job_guards.py` | `.gitea/workflows/*.y*ml` | **yes** — every tracked workflow's jobs must each declare a `CI_JOB_ROLE`, and the guard-declaring ones must match `## Workflow-job guards` both ways | index-derived from the start (ersatztv#786); registered in `test_guard_populations_derive_from_git.py` so the shared proof covers it | | `test_pr_changed_files.py` | `.gitea/workflows/*.y*ml` | **yes** — "no OTHER workflow writes the review-verdict status", and since ersatztv#748 "every tracked workflow declares a `permissions:` block", with NO exemption list (the one `ci-image.yml` briefly needed was deleted when #744 landed, per #835) | converted. Not on #806's list and found by cold review on the pushed head: an untracked `.yaml` dropped in `.gitea/workflows/` reddened two guards while absent from the index — the issue's list of files to assess was a starting point, not the population | | `test_workflow_persist_credentials.py` | `.gitea/workflows/*.yml` + `*.yaml` | **yes** — every `actions/checkout` in every workflow must drop the persisted credential | derived from the index from the start (#835). Shipped with NO exemption list, which is why it waited for #744: the one non-compliant checkout would otherwise have bought a permanent entry that keeps passing after its reason expires | -| `web/src/api/pageSizeCallSites.guard.test.ts` | `import.meta.glob` over `web/src/**/*.{ts,tsx,mts,cts}`, INTERSECTED with the git index | **yes** — an unregistered discovered site fails | converted under #819. The population is the glob INTERSECTED with the git index, and the walk/index divergence is asserted in BOTH directions WITHIN a shared scope: a key the index does not carry is dropped, and a tracked, on-disk, in-scope path that never reached the scanner FAILS rather than shrinking the population silently (that direction catches a dotfile, which the glob cannot match, and a disk/index spelling divergence, which `core.ignorecase` and NFD/NFC normalisation make permanent). The SCOPE itself cancels out of that equality — both sides call one `isInScopeSourcePath` — so narrowing it moves both sets together and no assertion comparing the two sides can see it. That is closed separately, by re-deriving the predicate from its two components over the whole tracked index (`the shared scope predicate is EXACTLY its two documented components`). BOTH components are restated there rather than called: delegating either half puts it on both sides of that comparison too, where it cancels the same way — measured, a term added to the filename half dropped 11 real files with the whole suite green. A table of example paths was tried as the proof first and retracted: it named four of `src/`'s eight directories, so it missed a 23-file narrowing. The residual is a coordinated edit of the predicate and its restatement, which is a fixed-size pair that does not decay as the SPA grows. The index is read by `web/vite-plugins/trackedSourceFiles.ts` in Vite's own Node context and handed to the app project as the virtual module `virtual:etv-tracked-source-files`. That is what reaches the index without admitting `@types/node` to `tsconfig.app.json` — the obstacle that deferred this, since wiring those types in was tried and reverted (it leaked Node's `setTimeout` into the app project and broke three unrelated tests). The plugin throws rather than falling back to the unfiltered walk when git fails, reports zero files, or cannot learn the Vite root. Residual, stated: a file tracked but DELETED in the working tree is subtracted deliberately, since an unstaged deletion is a normal developer state and a guard red on one gets ignored (#806); it is distinguished from the hole cases above by an on-disk existence check, not conflated with them | +| `web/src/api/pageSizeCallSites.guard.test.ts` | `import.meta.glob` over `web/src/**/*.{ts,tsx,mts,cts}`, INTERSECTED with the git index | **yes** — an unregistered discovered site fails | converted under #819. The population is the glob INTERSECTED with the git index, and the walk/index divergence is asserted in BOTH directions WITHIN a shared scope: a key the index does not carry is dropped, and a tracked, on-disk, in-scope path that never reached the scanner FAILS rather than shrinking the population silently (that direction catches a dotfile, which the glob cannot match, and a disk/index spelling divergence, which `core.ignorecase` and NFD/NFC normalisation make permanent). The SCOPE itself cancels out of that equality — both sides call one `isInScopeSourcePath` — so narrowing it moves both sets together and no assertion comparing the two sides can see it. That is closed separately, by re-deriving the predicate from its two components over the whole tracked index (`the shared scope predicate is EXACTLY its two documented components`). The criterion that restatement has to meet is CLOSED FORM over the raw path — it may share no helper, at any depth, with the predicate it checks — because anything shared sits on both sides of that comparison and cancels. Three mechanisms were tried and retracted before that was stated as a checkable property, each measured going green while removing real files: a table of example paths (named four of `src/`'s eight directories, missed a 23-file narrowing), a decomposition delegating its filename half to `isScannableSourceFileName` (11 files), and one still sharing `basename` (15 files, and blind to a planted unregistered call site). Two residuals, NOT a claim of closure: a coordinated edit of the predicate and its restatement passes, the two-site edit being the signal; and a term matching no tracked path today survives until the day it first matches one. What makes the form terminate is that the restated predicate is FIXED-SIZE and re-checked against its subject every run, unlike a member list whose size tracks the population. The index is read by `web/vite-plugins/trackedSourceFiles.ts` in Vite's own Node context and handed to the app project as the virtual module `virtual:etv-tracked-source-files`. That is what reaches the index without admitting `@types/node` to `tsconfig.app.json` — the obstacle that deferred this, since wiring those types in was tried and reverted (it leaked Node's `setTimeout` into the app project and broke three unrelated tests). The plugin throws rather than falling back to the unfiltered walk when git fails, reports zero files, or cannot learn the Vite root. Residual, stated: a file tracked but DELETED in the working tree is subtracted deliberately, since an unstaged deletion is a normal developer state and a guard red on one gets ignored (#806); it is distinguished from the hole cases above by an on-disk existence check, not conflated with them | | `test_ci_release_path_scan_job.py` | `.gitea/workflows/*.y*ml` + `scripts/**` | **no** — a fixture assembling a tmp harness, asserted about behaviour not membership | takes its file LIST from the index anyway, for hermeticity not completeness: `shutil.copytree` copied whatever was on disk, including untracked files and `scripts/__pycache__`, into a tree whose behaviour the probes then measure. Content still comes from the working tree. The copy is not a git repo, so the two files this step RUNS may not use the helper — see the fixture docstring | | `test_ci_dropped_step_guard.py` | the parsed workflow document (its OWN subject only — the release-path `scan` job runs it in a non-git copy, so it may not derive from the index) | **no filesystem population at all** | unchanged by #806; the SCOPE residual it left open — `MARKED_JOBS` as a hand-written mirror of the required contexts on `main` — was closed by #787, which derives it from `.gitea/required-status-contexts.json` and reconciles that snapshot against the server in `scripts/check-required-contexts.sh`. The cross-workflow half of that claim lives in `test_ci_status_context_uniqueness.py`, which CAN use the index | diff --git a/web/src/api/pageSizeCallSites.guard.test.ts b/web/src/api/pageSizeCallSites.guard.test.ts index 8ccc55895..28b7c9d0e 100644 --- a/web/src/api/pageSizeCallSites.guard.test.ts +++ b/web/src/api/pageSizeCallSites.guard.test.ts @@ -371,7 +371,14 @@ const rawSourceModules = import.meta.glob('/src/**/*.{ts,tsx,mts,cts}', { */ const TRACKED_SOURCE_PATHS: ReadonlySet = new Set(trackedSources.tracked); -/** Tracked paths with no file on disk — see `expectedTrackedSources` for why they are separated. */ +/** + * Tracked paths with no readable file — see `expectedTrackedSources` for why they are separated. + * + * Residual, stated: emptying this set is NOT caught by any test here, because on a clean checkout it + * is already empty and nothing observes the difference. That is tolerable only because of which way + * it fails — an empty set makes the guard RED on an unstaged deletion, never blind. Every mutation + * that could make it blind runs through `expectedTrackedSources`, which the fixture test pins. + */ const ABSENT_FROM_DISK: ReadonlySet = new Set(trackedSources.absentFromDisk); /** `import.meta.glob` keys are root-absolute (`/src/...`); the index is root-relative. */ @@ -603,7 +610,7 @@ describe('pageSize call-site guard (#650)', () => { ['builder/libraryBrowse.test.mts', false], ['api/pageSizeScan.test.cts', false], ['api/pageSizeCallSites.guard.test.ts', false], - ['api/generated/v1.ts', true], // the predicate itself is filename-only; the 'generated' DIRECTORY exclusion lives in isInScopeSourcePath, tested separately below. + ['api/generated/v1.d.ts', true], // the predicate itself is filename-only; the 'generated' DIRECTORY exclusion lives in isInScopeSourcePath, tested separately below. ['components.js', false], ['data.json', false], ['README.md', false], @@ -676,7 +683,7 @@ describe('pageSize call-site guard (#650)', () => { ['src/screens/TrashScreen.tsx', true], ['src/components/forms.tsx', true], ['src/builder/libraryBrowse.mts', true], - ['src/api/generated/v1.ts', false], + ['src/api/generated/v1.d.ts', false], ['src/api/pageSizeScan.test.ts', false], ['src/api/pageSizeCallSites.guard.test.ts', false], ['src/shell.css', false] @@ -707,19 +714,36 @@ describe('pageSize call-site guard (#650)', () => { // function `isInScopeSourcePath` calls — which put it on both sides of the comparison, where it // cancels algebraically. MEASURED: adding `&& !name.endsWith('.d.ts')` to that predicate // dropped a real tracked file and adding a term that skips lowercase-initial `.tsx` dropped - // eleven, both with the whole 1259-test suite green. Delegating half a decomposition proves + // eleven, both with the whole suite green. Delegating half a decomposition proves // half of it. // - // What this is and is not. It is a verbatim restatement of a FIXED-SIZE predicate, checked - // against itself on every run — the shape the record already blesses for `MARKED_JOBS`, and it - // does not decay as the SPA grows, which is exactly how a hand-written list of members or - // example paths does. The accepted residual, stated rather than implied: an author who edits - // the predicate AND this restatement together passes, deliberately, because the two-site edit - // is the signal. And a term matching zero tracked paths today survives until the day it first - // matches one — at which point it reddens here. So: a term becomes visible the moment it - // affects a tracked path, not the moment it is written. + // THE CRITERION, stated as a checkable property because four rounds of "restate the scope" were + // each defeated by something the restatement still SHARED with its subject: the filename half + // (delegated to `isScannableSourceFileName`), and before that a table of example paths. Anything + // shared sits on both sides of the `toEqual` below and cancels algebraically. + // + // The restatement must be CLOSED-FORM over the raw path: it may share NO helper, at ANY + // depth, with `isInScopeSourcePath`. Not `isScannableSourceFileName`, and not `basename`. + // + // `basename` is why this is spelled out rather than left as "restate both halves". It looks like + // plumbing rather than policy, and it was shared. MEASURED on the previous head: teaching it to + // return `''` for paths four segments deep removed 15 real tracked files, and a `pageSize: 100` + // planted in one of them went entirely unseen — 36/36 green. The inlined `lastIndexOf` below is + // that fix, and it is the whole reason the criterion is phrased as "no helper at any depth". + // + // What this form is, and why it terminates where a member list does not: a verbatim restatement + // of a FIXED-SIZE predicate, re-checked against its subject over the whole derived index on + // every run — the shape the record already blesses for `MARKED_JOBS`. A list of members or + // example paths decays because its size tracks a growing population; four regex clauses do not. + // + // Two residuals, and they are NOT a claim of closure — the previous head asserted closure here + // and was wrong: (1) an author editing the predicate AND this restatement together passes, + // deliberately, the two-site edit being the signal; (2) a term matching zero tracked paths today + // survives until the day it first matches one, at which point it reddens. So a term becomes + // visible the moment it AFFECTS a tracked path, not the moment it is written. const byComponents = trackedSources.tracked.filter((path) => { - const name = basename(path); + // Inlined deliberately — see the criterion above. Do not "tidy" this into `basename(path)`. + const name = path.slice(path.lastIndexOf('/') + 1); return ( !path.includes('/generated/') && /\.(ts|tsx|mts|cts)$/.test(name) && @@ -767,10 +791,17 @@ describe('pageSize call-site guard (#650)', () => { // stays meaningful as the SPA grows instead of pinning a number that was true once. // Bounded against the IN-SCOPE tracked count, not against every tracked path: the numerator is // source files, so a denominator counting tests and CSS too would slacken as the suite grows. - // At most a tenth of the in-scope files may be absent from disk before this reads as a - // degenerate plugin result rather than as a developer mid-edit. + // Carries its OWN message: this fires on a large number of unstaged deletions, which is a real + // developer state, and the shortfall message below would then blame a dotfile or a case + // divergence and send the reader looking for the wrong thing. const inScope = trackedSources.tracked.filter(isInScopeSourcePath).length; - expect(expected.length).toBeGreaterThan(inScope * 0.9); + expect( + expected.length, + `Only ${expected.length} of ${inScope} tracked in-scope source files are present on disk. ` + + `If you have deleted a batch of files, stage the deletions — the population follows the ` + + `index. Otherwise the plugin's absent-from-disk set is degenerate (a sparse checkout, or an ` + + `unreadable tree), and every completeness claim below is running on a shrunken population.` + ).toBeGreaterThan(inScope * 0.9); const missing = expected.filter((path) => !produced.has(path));