Files
pi-lens/docs/defect-shapes.md
Apostolos MantzarisandClaude Sonnet 5.5 4b5e0b5c17 test: admit master's globalThis.Error read in the slot sweep
The merge of master brought clients/installer/download.ts, which reads
the builtin Error through globalThis. Raise the documented census to 27.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-22 09:43:47 +02:00

59 KiB

Recurring defect shapes

Screen against these before writing code. Shapes are numbered once, grouped by the surface they bite; each block loads only when its trigger applies. A shape whose open population is countable names its census in its entry. The census is one command, run at the repo root, printing one line per member or naming one baseline key. A PR that fixes members of the shape quotes that census before and after. A shape with no census in its entry is uncounted: a PR that fixes its members says so instead of quoting a before and after.

touching a path key or path spelling

  1. Divergent path keys: path-keyed maps use PathKeyedMap and normalize on write, read, delete, and rehydrate. Tests use mixed separators and casing. A normalizer change tables every writer and reader of the map with the normalizer each uses; a claim that one normalizer subsumes another is measured per transformation (separators, dot segments, case, symlinks, existence), never asserted. Never put path.resolve in front of an identity key: it folds .. lexically before the link resolves, so /repo/link/../f.ts keys a different file than the kernel does. Screen: does any spelling reach normalizeMapKey or realpathOrResolve through a path.resolve first? Enforced by tests/config/path-identity-sweep.test.ts (partial: a raw realpath or a raw path.resolve key outside clients/path-utils.ts).

  2. Host path functions in a shape branch: once a path is classified as Windows-shaped, use path.win32; do not use host-default path functions. Prefer toPosix, splitPathSegments, and the path identity helpers.

  3. Mixed path comparison: use one platform-aware containment expression; do not combine case-sensitive equality with case-folded relative paths. A tool-reported path is attributed with pathsEqual against the tool's cwd, capturing only the path the tool's renderer emits. Enforced by tests/config/reported-path-attribution-sweep.test.ts (shrink-only census). ADR: docs/adr/0009-reported-path-attribution.md

  4. Walk-up result used as eligibility: return ownership and start-directory identity separately; enumerate root-position by ambient-input cells. Consolidation verdict: folded onto walkUpDirs (clients/path-utils.ts); the loops left are the seam's own climbs and the URI-key ancestor index in clients/lsp/edits.ts, which stay distributed because a key is not a directory and must not reach realpathOrResolve. Counted climbs that go up a known number of levels instead of searching also stay: collectInstallDiagnostics (pi-lens's own install root, at most 6 levels), resolvePython (one level per leading dot of a relative import) and anchorPrefix in clients/dispatch/rule-policy.ts (one level per path segment).

  5. Split host-path resolution: a path is resolved by its provenance, at one seam per provenance. A path a host tool was given as an argument goes through resolveHostToolPath / resolveToolCallFilePath, never a bare path.resolve(base, raw), which turns ~ into <base>/~/…, a path that cannot exist, and dispatch then reports ghost findings for it. A shell operand follows shell rules (a quoted tilde stays literal; no @ strip or unicode fold), bound to the token it came from. A path recovered from disk or generated by pi-lens is an identity and is never re-resolved.

  6. Named path vs written set: a guard keyed on the path a tool NAMES must hold for every path the tool WRITES, and its permission is per call, never per path. The writer table (clients/writers.ts) states each route's named set (names) against its written set (writes), and its census (tests/clients/writers-census-5551.test.ts) reds a file-writing site no row admits. Screen: which rule answers for a path in a route's writes and not in its names? A first credit from a bridge is range-scoped to the bytes it reports (screen the next edit inside and outside that range), and settled-sweep drift never creates authorship; the table's authorship column marks the whole-file exceptions (recognized bash, pipeline sibling files, agent_end).

  7. Unknown authorship range: a producer that cannot recover a truthful range must carry UNKNOWN to ReadGuard.creditAuthorship; UNKNOWN creates no authorship. The range each writer route can state is the writer table's authorship column (clients/writers.ts). A scope after a credit is what the credit holds plus what it may keep, so no credit widens an empty or range scope past the lines it produced: not a drain, a bash write or a pipeline credit. A native write's creation read vouches for the whole file instead. UNKNOWN keeps a scope only under the writer rule (mayAdvanceAuthorship) and while a read that names a tool call bounds it after a move; otherwise it leaves an empty scope, which vouches for no line. An own oldText edit must not retire its write's authorship. A producer with no pre-write check says so with advanceAuthorship: false, never by leaning on UNKNOWN. Enforced at clients/mutation-bridge.ts and clients/read-guard.ts, with the F-4210-2 production bridge witness.

adding or reading a cache / durable record

  1. Unsettled resource: every timer, worker, child, watcher, and loser path is unref'd or cleared on every settle path. Tracked entries are removed on failure as well as success. Teardown does not await a dead resource forever. Enforced by tests/config/hook-await-bounds.test.ts (partial: hook awaits and timeout races only; timer handles have no detector). Consolidation verdict: stay distributed. Every named timer in clients/, tools/, mcp/ and index.ts is cleared or unref'd in its own file, and the anonymous awaited sleeps settle on their own timers. A sleep(ms) helper would relocate one line per site and must stay ref'd, because an unref'd awaited sleep lets a CLI exit mid-await.

  2. Incomplete freshness: use the right content, size, mtime, dependency, and existence axes. Missing finding paths are not current findings. Enforced by tests/clients/freshness-sweep.test.ts (partial: mtime comparisons must go through the kernel comparator; an mtime cache-key equality without a size or hash sibling is not scanned).

  3. One-axis bound: bound the resource axis that grows, including bytes, timers, WASM objects, and retained evidence. Enforced by tests/config/bounded-container-guard.test.ts, tests/config/bounded-eviction-idiom-sweep.test.ts and tests/clients/bounded-telemetry-sweep.test.ts (partial: container count and telemetry only; bytes, WASM objects and timers have no detector).

  4. Out-of-guard mirror refresh: refresh behavior-gating mirrors before the guard releases, or validate the committed generation/object identity.

  5. Timer versus long operation: an operation holds a counted gate for its lifetime; a background timer checks it at fire time and re-arms a fresh, bounded delay.

  6. Cooldown beyond caller cadence: verify both recovery suppression and promotion of values served during cooldown.

  7. Second writer without discriminator: enumerate all writers and add a reason/kind field before composing branches. For file writes the writer table (clients/writers.ts) is that enumeration.

  8. Cold-path work on warm path: compute expensive record fields only inside the failure or timeout branch, and measure any hot-path cost.

  9. Reset cap counter: a retire or skip records its decision where the selector reads it, so the same item cannot re-enter with a fresh count.

  10. Hot bound reached at p50: record hit rate and prefer adaptive or demotion behavior over a constant that has become the work.

  11. Long-lived container without a bound: module-level Map/Set state is bounded, evicted, or content-keyed; a reset or TTL read is not a bound. Enforced by tests/config/bounded-container-guard.test.ts (shrink-only).

  12. Retry or drain loop consumes its own work list: a bounded retry or drain loop must not remove its tracked item from the collection it iterates on the first successful pass. Later attempts must observe the resource's actual absence before untracking it; tests cover a resource recreated between attempts.

  13. Cross-request derived-state cache where a request-local pass is affordable: for a derived value on a hot path, measure a request-local bounded recompute first; persist it only when the fresh-process benchmark shows the recompute is the cost, and then the entry carries the generation it was derived from. Tool-run caches are governed by the delivery gate instead. ADR: docs/adr/0006-derived-state-benchmark-first.md

  14. Unlocked async read-modify-write of a shared record: an async read, a merge and a whole-file publish with no lock between them publish a snapshot, not a delta, so a same-tick or cross-process sibling's entries vanish. A timestamp stamped before the lock can also invert commit order against a ts > cursor reader. Commit through clients/durable-store.ts and stamp ts inside the lock. Census: not countable as one command. Enforcer: none: judgment-only, a scan would have to follow a value from its read to its publish. Instance and sweep: HISTORY.md. Screen: does the write's value come from a read of the same target with an await between, and is any ordering field assigned outside the lock?

a delivery surface or lane

Project-wide scanner delivery has one owner per live worklist. The primary session owns turn-end delivery; a concurrent secondary owns only its own file-scoped worklist and receives no project-wide scanner output.

Producer population Primary turn_end Secondary turn_end
Project-wide scanners (gitleaks, knip, jscpd, and equivalent shared stores) admit and deliver suppress at the delivery gate
Session-owned file or runner findings admit its own session admit its own session
  1. Dropped side channel: trace flags, bindings, and provenance through spreads, maps, filters, and JSON serialization.

  2. Silencing as fixing: distinguish clean, filtered, unavailable, errored, suppressed, deferred, and partial results. Any bound on an agent-facing path discloses its truncation on the rendered surface; a count recorded only in latency.log is not disclosure. Removing a false "unavailable" notice never turns the file clean: a file no analyzer applies to reads "not analyzed". Instances: HISTORY.md. A clean claim ("clean", "✓", "No issues", "all passed") renders only from a producer that proves its scope was checked: cleanVerdict (no findings, a non-empty scope, every file in it proven) or the dispatch verdict's checkedVerdict, both in clients/dispatch/types.ts. An empty answer, a stopped sweep, a lookup that never answered and a report that was never read are not proof. In the census files (8 files: the clean-verdict surfaces of DELIVERY_SURFACES plus clients/runtime-tool-result.ts) every emitted literal, whatever its words, is a claim, finding or neutral row of tests/clients/clean-claim-census.json, keyed by its source text; a claim row names its producer, and its statement must read a guard that producer set. Every other DELIVERY_SURFACES file is exempt only with a reason in the test, and a new surface with neither reds. A clean literal in a helper module that a census file calls is outside the gate (an accepted residual). Claims still decided by local logic (own) are the instance list: pinned by count, they may only fall. Screen: can this line say clean when no check completed on a file it speaks for? An out-of-session-root project edit records one bounded degradation and uses the existing advisory notice seam; intended vendor skips and pi-owned OS-temp artifacts stay silent (clients/runtime-tool-result.ts, clients/ephemeral-root.ts). A delta decides only what is new: a blocker stays pending, recorded and gating, until an observation no longer holds it. An edit-range gate decides only delivery, and a run with no verdict (failed, unanswered, in flight) observes nothing, so neither retires a recorded blocker. A skip has a verdict only with a stated not-applicable reason (RUNNER_SKIP_REASONS). not-enabled (an opt-in runner left off, #5042) is the one stated reason that stays a no-verdict: admitting it would retire recorded helm-render blockers and stop their owed ranges. A recorded blocker is still observed only at its own line, aligned to the current bytes: another occurrence of the same rule is not it. A fallback for missing evidence narrows what retires: with no alignment, its identity anywhere keeps it. It stays a per-write hold and never widens what counts as the same finding: the match still needs the entry's own line text, and owed lines are matched by content, never widened to the file. A skip that defers to another source's evidence answers only for what that evidence sees, and only when that source answered: an edit-gated primary sees the edit, so a recorded finding outside it stays, and a silent primary sees nothing. A recorded finding is judged only by a run of its own runner: one that would defer to a source whose copy has another identity runs while it holds a recorded finding there, or nothing could retire one it cannot place. A kept entry with no place in a write's bytes is recorded as such (positionStale), never inferred later from one line's hash, and a line with no word character owes nothing by its text. A non-authoritative answer never stands in for a primary that never answered: a fallbackFor alternate (python-jedi beside a pyright that was trust-refused, failed to start, sat in a breaker cool-down or was not installed) is not its owner, so the file reads unavailable with the owner named, never "confirmed clean" (#5014). The rule admits the known-good forms (a non-alternate primary acquired, an alternate standing in for an owner the operator disabled, an alternate whose owner resolved no root) in unansweredPrimaries (clients/lsp/index.ts); every other cause, listed or not, lands unconfirmed. Screen: can a file read clean when its primary never answered? Population enforcer: tests/clients/lsp/unanswered-primaries-fallback-5014.test.ts (every registered fallbackFor alternate). Enforced by tests/clients/dispatch/runners/run-outcome-ratchet.test.ts, tests/clients/dispatch/runners/parsed-nothing-sweep.test.ts and tests/clients/delivery-surface-ratchet.test.ts (the clean-claim census; partial: no detector for an agent-facing bound that omits its truncation line, for a claim assembled at runtime from neutral literals, or for a clean claim added to an exempt surface).

  3. Old-role filter on a substitute: compare fallback output with the substituted surface's contract, including non-blocking findings.

  4. Unredacted user content: parser messages and hand-authored strings may contain file input; normalize and redact at the shared diagnostic seam.

  5. Pull-only observability: new behavior emits a success or decision record in the streams that monitors and analyzers read. A new decision branch on a session, lifecycle or delivery seam names its record, cites an existing one, or says none: <reason> naming each file (check-pr-body prompts for it); a test reads a record back, and a reason is judged by the reviewer (#3875). A new or changed catch handler in clients/, mcp/, tools/ or index.ts is judged by tests/config/silent-catch-sweep.test.ts: a record seam on every path, an unconditional throw, or a none: <reason> marker, and the file's pinned set re-pinned in the same change (PI_LENS_PRINT_PINS=1 prints the rows). scripts/ and tests/ stay outside its scope.

  6. Swallowed failure recorded as a different event: a catch that drops a failure and lets the normal path continue makes the log report success or an event that never happened (an unreadable subtree counted as deleted, a rejected save counted as sent). A catch on a runtime path records the failure under its own kind, or says none: <reason>. Screen: force the failure through the real entry point and read the record it wrote.

  7. Prose mistaken for executable structure: define lexical states and reachability before scanning shell, workflow, or source text.

  8. Stand-in for unknown text stripped per consumer: when a lexer leaves a placeholder for text it cannot know (a command substitution's output), read the input under each bounding assumption rather than teaching each consumer to ignore the placeholder: empty (the text the rules matched before it existed) and opaque (no rule word matches it, no path resolves through it), denying if either reading denies. Enforced by findDeny in scripts/hooks/guard-bash.mjs, pinned by the "substitution next to a rule word (#3997)" rows in tests/scripts/guard-bash-hook.test.ts.

  9. Whitespace counted as structure when it is alignment: a leading run can be alignment, not one nesting unit (call continuations, block-comment and template-literal interiors; #3038, #3039, #3052, #3059, #3116). Name which lines carry structure and exclude the rest before counting; decline rather than pin a style when only ambiguous runs remain.

  10. One-direction filter proof: a filter that drops stale input is proven in both directions: it never passes stale input and never drops the only fresh answer. The model carries a no-drop invariant beside the safety one, and the test double emits in the real server's measured order, not the order the fix assumes (#3484).

  11. Prefix churn from a non-append write: a provider caches the request in order (tools, then system, then messages), so a write that changes bytes before the newest message re-bills the whole conversation: a returned context list that makes pi rebuild the system head, or a tool-set change on a model that folds system messages into the head. Write at the tail only, and count each tool-set change as one full rewrite on such models. A host-generation gate takes a recorded fixture per certified minor, never two. Screen: drive two real-session requests that differ only in the writer, and compare the head and pi-ai's collapsed head. Enforced by tests/clients/prompt-cache-prefix-writers.test.ts (one tier-2 cell per writer: registration, session-start plan, activation, injection).

  12. Tool-state prose blind to a posture: model-facing text (orientation, tool descriptions, nudges) that names a tool as active, inactive, available or needing activation must hold under every posture the renderer cannot see: each tools.<name>.enabled value, each tools.lazy value (true, false, auto) and each host (pi, MCP, which can call only the tools it has a name for). Derive the named set from the registry, never a hand list. Screen: render the prose under each posture combination and each host, and assert every clause is true (#4293, #4294 enabled axis; #4682 lazy axis and the hand list that dropped two tools). User docs that say which tools a script or user can call are in scope too (#5242: "every pi-lens tool" under --no-lazy-tools missed the enabled axis).

  13. Generated proof line for a step that did not run: a composer that writes a PR, issue or report body states what ran. A branch where the step failed, was skipped or timed out renders that outcome, never the success sentence (#5243). Screen: for each proof sentence a composer emits, which input proves the step ran, and does the failed branch render something else?

a runner or tool outcome

  1. Ignore-glob path spelling: a runner hands a tool an absolute dispatched path even though the tool matches its ignore globs against the argument string, so an ignored ancestor can turn a real file into a silent clean. Candidate list, not a census: grep -rnE 'ctx\.filePath|absPath|path\.resolve\(cwd, ctx\.filePath\)' clients/dispatch/runners/*.ts; probe each installed tool with the same file and config under <root>/.claude/worktrees/<lane> and a neutral ancestor, comparing relative and absolute argv. A fix hands the tool optionSafeTargetArg (clients/tool-policy.ts) at the runner's existing spawn cwd: the project-relative path, ./-prefixed unless it starts with a letter, digit, _ or ., because a bare -D.ts is an option and --fix then rewrites files nobody dispatched. The absolute dispatched path stays for attribution and for files outside that cwd. Probe a new runner's argv before it lands. Enforcer: none: a per-runner census of argv verdicts would be prose the test cannot observe. Tools that absolutize their own config glob or regex before matching (detekt excludes, phpstan excludePaths, credo files.excluded) stay silent under a relative argument too: no argv fix exists, so the verdict is residual. Most tools never apply an ignore to an explicit file (mypy, shfmt, typos, swiftlint, trivy, dart), so their verdict is cleared. Screen: does the runner hand the tool the absolute dispatched path while the tool matches its ignore globs against the argument string (probe the same file under <root>/.claude/worktrees/<lane> and a neutral ancestor, relative vs absolute argv)?

  2. Wrong argv transform: verify a command is the wrapper shape before dropping an argv element or launcher name.

  3. Wrong failure classification: derive availability and verdicts from raw evidence; preserve the classifier and evidence when a caller asserts a fact. Runner log parsers tolerate ANSI control sequences, padding, and CRLF before extracting a count; the exact Windows bytes are pinned by tests/config/windows-vitest-failure-count.test.ts, and the parser is parseVitestSummary (shape 63). Enforced by tests/clients/dispatch/runners/run-outcome-ratchet.test.ts and tests/clients/dispatch/runners/parsed-nothing-sweep.test.ts (partial: the classification choice itself is review-enforced; a latch-literal rule fires on every correct write).

  4. Unverified external-tool claim: probe the real binary before encoding exit codes, output shapes, severity names, or fixtures. For a third-party extension, server, or file format, read its source or schema at a pinned SHA and pin a test vector generated from it, citing the SHA; a double built from an issue's description encodes the same guess (#2432). Enforced by tests/clients/dispatch/smoke-fixture-coverage.test.ts (partial: every registered dispatch runner needs captured real-binary bytes replayed by tests/clients/dispatch/runners/captured-real-output.test.ts, or an exemption naming a fact about the tool; presence only, not fidelity).

  5. Tool root drift: all runner, formatter, and LSP child spawns use resolveToolCwd; mutation of the seam, log, or fallback must turn a test red. Enforced by tests/support/spawn-cwd-scan.ts and its runner sweep.

  6. Language-specific rule: use LANGUAGES and registry facts; add a non-TypeScript row whenever the rule is language-neutral. Enforced by tests/config/language-alias-constancy.test.ts, which asks the live registered rules, providers and policy lookups whether they answer alike for every extension of one language. Consolidation verdict (#5297): folded onto the registry facts isTypeScriptFile and isJstsFactFile; the mixed-language tables stay distributed.

  7. Fallback direction chosen without naming the user-facing obstruction: "fail closed" is not a universal justification. For each fallback, catch, or default, name the concrete failure that reaches the user and choose the direction from that harm; test unreadable, absent, and thrown lookup states where the seam supports both directions.

  8. Unhandled stream or process event is a host-fatal throw: every callback on a child process, socket, or stream is total (catch, bound, record); a throw there bypasses the caller's try/catch and kills the pi host (#3375, #3383, #3389). data handlers are enforced by tests/clients/data-handler-bounds-sweep.test.ts and socket error listeners by tests/clients/socket-error-listener-sweep.test.ts, and worker or IPC message listeners (typed unknown, one non-rethrowing try) by tests/clients/worker-message-boundary-ratchet.test.ts; screen close and timer callbacks by hand.

  9. Serial await of independent work on a hot path: a for loop or a run of awaits on the edit, write or turn-end path waits for each call before starting the next, though no call needs another's result. The cost is the sum of the calls instead of the slowest one. Overlapping is not always a win: some servers answer one request at a time (typescript-language-server forwards to one tsserver), and a write-ordered loop (runtime.nextWriteIndex(), a pipeline claim) must stay serial. Screen: do the calls this loop or sequence awaits one at a time need each other's results, share a write order, or go to one server that answers one request at a time? If none, overlap them through clients/map-with-concurrency.ts; if one does, a comment at the loop names it. Measure before overlapping calls to one server. Census: not countable. Enforcer: none: judgment-only; a scan cannot tell an independent await from an ordered one without reading what each call feeds. Instances and dates: HISTORY.md.

  10. Wasm failure outside the #3605 containment: every failure thrown out of web-tree-sitter classifies through classifyTreeSitterWasmError, and a catch inside a withParsedTree consumer calls reportWasmAbort before it swallows the error. An unclassified or swallowed trap is never counted, charged or recycled, and the runtime later fails elsewhere (#3996). tests/clients/grammar-runtime-imports.test.ts reds on a shipped grammar that imports a function the runtime does not export.

  11. Delete or rewrite through a dependency link: a lane's node_modules is a symlink to the main checkout's install, so any verb that removes or rewrites under it reaches every lane (#3173: git worktree remove followed the link twice; #4044: a worker's npm ci --dry-run emptied it under ~7 lanes, because npm 9.2.0 ignores --dry-run for the clean-install family). Such a verb runs only where node_modules is a real directory, or in a scratch copy. The hook's verb list (NPM_NODE_MODULES_WRITERS in scripts/hooks/guard-bash.mjs) is the catalog: a new verb alias or package manager (pnpm, yarn, bun) needs its own entry, and the hook binds Claude lanes only, so a codex worker's half is the plegma shim (apmantza/plegma#693). Deletes are the second member, measured with GNU coreutils: rm -rf node_modules/, rm -rf node_modules/*, find node_modules/ -delete, find -L|-H node_modules -delete, find node_modules/ -exec rm and cd node_modules && rm -rf ./* empty the link target, while rm -rf node_modules (no slash) removes only the link. classifyNodeModulesDelete denies the first set through the same hasNodeModulesSymlinkOutside seam; that seam follows the complete symlink chain with a fail-closed fallback when the target cannot be resolved. Sweep and instances: HISTORY.md. a lane unlinks without a slash or glob. Consolidation verdict: two rules on one classifier seam, kept apart because the npm rule judges a verb and the delete rule a path operand (deleting the delete rule relocates nothing the npm rule could absorb). Both share one path test, operandThroughNodeModulesLink (npm's is <prefix>/node_modules/, or its cwd plus the project its walk-up finds), and one rule for every value form: a directory is tested where the program lands (the holder of each node_modules component physically, as the kernel follows a link before ..; npm's --prefix lexically; npm's walk-up from the physical cwd), and a part the resolver cannot read (an unknown cwd, $( … ), backticks, an unknown variable) is the project the command runs in, failing closed in a linked lane only. find -L|-follow also counts an operand that holds the link. Unguarded, listed in the header's not-handled list: a glob that expands to the link (rm -rf */), xargs rm, rsync --delete, mv, npx rimraf.

  12. Tool console output parsed unstripped: parsing Vitest or any tool's console output: strip ANSI first, and test with FORCE_COLOR=1. CI runs Vitest with colour, and escape codes split Tests from its counts and FAIL from its file, so a parser reads "no tests", "no red" or the wrong class. Read a Vitest transcript only through parseVitestSummary in scripts/lib/vitest-summary.mjs (pure, so importing it does not make a script a workflow writer); its consumers are guarded over a real coloured run by tests/scripts/vitest-summary-consumers.test.ts. Consolidation verdict: folded onto that seam (deleting it would send seven scripts back to private regexes). Instances and sweep: HISTORY.md.

  13. Single scan root: a detector takes its population from one root while its subject can write in several, so a clean answer from the wrong root reads as a complete negative. Screen: for each detector, list the roots its subject can write in. Then show that each root gets its own verdict, or that one root provably covers them. Census: not countable yet. Instance and dates: HISTORY.md.

  14. Rule re-derived beside its owner: a consumer rebuilds a rule that a shared seam already owns (a marker list, a glob-to-RegExp matcher, a case fold) instead of calling the owner, so the copy drifts from it on spelling, anchoring, case and file-versus-directory. The copy is always plausible beside the owner, and a fix of one consumer leaves its siblings. Screen: before writing a marker, pattern, bound or normaliser, grep the tree for its literal and for the matcher that applies it; does a module already own it, and does this caller route through that module? Then list the other callers that hold their own copy and fold them or say why not. Census: not countable yet. Enforcer: none: judgment-only. A scan cannot tell a copied rule from a coincidental literal without reading what the value feeds. Instances and dates: HISTORY.md. Consolidation verdict: stay distributed for the two copies of the glob-to-RegExp rule (globToRegExp in clients/file-utils.ts and matchesPattern in clients/read-guard.ts differ in case and ? handling, and read-guard's production input is its fixed defaults) and for the inline regex-escape one-offs in scripts/ (escape-regexp-fold-sweep admits them; an unbuilt script cannot import clients/string-utils.js).

  15. Learned attribution keyed on a name alone: tier 4 of classifyMutatingTool learns a tool name from a disk change in its call window plus a path field, then classifies every later call of that name as an edit, so a tool that never wrote and a call whose work already ran both reach it on name plus path alone. The writer table's attribution column (clients/writers.ts) names how each route is attributed; its observed-window rows are the ones tier 4 learns. Tier 4 is admit-by-default with enumerated exemptions (the registry names, the cursor-replay- id prefix); a third carve-out is the trigger to redesign it fail-closed, learning only when the call, not the window, owns the change. Screen: can a call whose work already ran, or a tool that never wrote, reach the learned lookup or the arm gate on name plus path alone? Census: not countable. Enforcer: none: judgment-only, the exempt population is whatever other providers replay or mix. Instances and dates: HISTORY.md.

  16. Failure kind checked after the generic error branch: a timeout or abort result also carries error, so an if (result.error) placed before failure === "timeout" makes that branch, and the state it updates, unreachable. The autofix timeout in clients/file-utils.ts was this case: it never armed the spawn-timeout cooldown, so every edit to a wedged tool paid the full timeout (#5376). Census: not countable as one command. Sweep and fix: HISTORY.md. Enforcer: none: judgment-only, the order of checks is code shape, and a scan cannot tell a dead branch from a deliberate fallback. Screen: does every non-success exit reach the state updates the transition table gives it, or does a broader check catch it first?

a test double, ratchet or sweep

  1. Vacuous test: prove the real entry point and real fixture arm. A skip is visible, a mock has the required fields, and the test fails pre-fix. A hook handler that swallows its own throw (handleToolCall returns undefined and records tool-call-handler-throw) reads a crash as the verdict under test: call it through runHandlerExpectingNoThrow (tests/support/handler-verdict.ts; the pi mock does it for tool_call hooks), enforced by tests/config/handler-verdict-sweep.test.ts (#4182). Enforced by tests/config/vacuous-skip-coverage.test.ts (partial: skips and conditional tests; "fails pre-fix" is the PR body's red transcript, not scannable).

  2. Name heuristic: a filename skip has an observable count and a content escape hatch; never silently drop a real file.

  3. Skipped CI as green: absent required checks are not passing checks.

  4. Duplicate module instance: tests import the same .js artifact as the runtime and never reset a private .ts twin. Enforced by tests/config/module-instance-coverage.test.ts.

  5. Source assertion for runtime behavior: prefer a runtime probe; source scans need proof that runtime observation is impossible.

  6. Spelling enumerator: detect semantic structure, not a finite list of syntactic spellings, and test an unlisted spelling.

  7. Platform-only red: platform-dependent tests run under injectable path.posix and path.win32 semantics on every authoritative lane.

  8. Count-based baseline laundering: maintenance tools match content identity, not occurrence counts, and refuse replacement identities.

  9. Raw control byte: source fixtures encode control characters as escapes or buffers; tracked-source sweeps enforce this.

  10. Data-only admission: a new exemption or baseline row requires a reason in a separate checked file and a fixture that crosses the boundary.

  11. Portable entry-module check: decide the entry module only with isMainModule(import.meta.url) from scripts/lib/is-main-module.mjs; scripts/hooks/guard-bash.mjs is the one standalone gate.

  12. Root wrapper drops metadata: wrappers preserve the complete marker table and are checked against direct root resolution.

  13. Test double's fabricated identifier reaching code that acts on it: a pid, fd, port, lock path or handle invented by a mock reaches production code that registers, signals, writes or deletes by it (#2042, #3091). Verify ownership against the OS when the identifier is admitted, not its range. Pids are enforced by tests/support/kill-guard.ts; screen the other identifier kinds by hand.

  14. Generated edit with unlisted consumers: a bot edit to a value that tests pin must leave green every test that names the edited ids. Screen: apply the generator's real output to the real tree (all-eligible case included), build, and run every test that mentions the field or the registry; this sweep is manual (#3994 F1, r3). Tests take "an unmeasured server" from a class the generator never touches, never a hard-coded id. A removed or demoted CI job is the same shape: before deleting it, list every consumer of its check name, comment marker and ci-verdict line (job and gate pins, advisory and deferred allowlists, contracts, PR template) and give each a disposition in the PR body (#4005).

  15. In-process module double with a real seam: when a clients/ module has a test setter, adopter, or reset, drive that seam; keep a double only at a process or host boundary. New in-process vi.mock targets and hand-rolled LSP client or service doubles are ratcheted by tests/clients/flake-shape-ratchet.test.ts (in-process-mock, service-double). Its census is the in-process-mock key of tests/support/flake-shape-baseline.json: one line per <file>::<module> row, 1009 of them on master 33eac2aa1. #4709 drives that count down.

  16. Sink read before drain: a log sink's log/append only enqueue, so a test that reads the sink's byte offset, line count, or rows while one of its own writes is queued counts late bytes on the wrong side of its window, or misses them. Await that sink's flush (or flushAllNdjsonWriters) right before the read with no other await in between, or inside the reading helper. Enforced by tests/config/sink-read-drain-sweep.test.ts. The removal side is the same shape: drain the queue (await flushAllNdjsonWriters) before removing the directory a sink writes into, or a queued row recreates it; enforcer none, judgment-only.

  17. Model switch drift: a TLA+ config constant that mirrors a code choice (inject a read, retire on an unknown range) goes stale when the code changes and the constant does not, and TLC then proves the old design green. A PR that changes such a behaviour flips the constant in the same change; a TLA+ unaffected line never covers it. Screen: for a mapped file's diff, list the CONSTANTS in the family's as-built formal/<family>/*.cfg and check each against the changed branch. Enforced by tests/config/tla-switch-pins.test.ts over formal/switch-pins.json: every constant a config assigns is pinned, notCodeChoice or deferred with a reason; a pin names the test that drives the real code, and every expect: pass config must resolve the constant to the pinned value. Flipping the code reds the pin's test; flipping the model without the registry reds the gate. read-guard is fully pinned; the other families' code choices are deferred, and the deferred and notCodeChoice counts are pinned exactly.

  18. Enumerated detector: a scanner that lists the spellings it knows passes every spelling it does not, so the guard is green while the defect ships. Derive the rule from the seam (the specifier, the store, the sink) and fail closed on an unrecognised form. Screen: plant an alias, an indirect call and a value reached through another binding, and quote each result; every green plant is fixed or named as a residual. For a call-site scanner add a computed member key (module["require"](x)) and a renamed callee (__require). A detector's first round therefore lists its admitted forms and refuses everything else; a residual names an admitted form that is too broad, never a spelling the detector does not read.

  19. Fixture adopts an ancestor root: a fixture created with no project marker inherits whatever root sits above it, so one stray .git at the tmp root became the project root and #4559's quick-mode cell failed three pre-push runs. Plant the fixture's own marker, or assert the root it resolved before the case runs. Guard: planned in #4560, not yet running.

  20. Instrument attributes by id and order, not by the emitting subject: a probe that brackets each phase with an offset into a buffered async sink, and drains rows by subject id alone, folds a sibling's late row into its own phase. The verdict then depends on write order, so the same measurement flips between two answers and a data refresh commits the artifact as a finding. Stamp each row with the subject that emitted it, or scope the drain to that subject, and require the last writer of a verdict to be the subject's own emitter. Enforced by tests/clients/lsp/lsp-publish-trace-attribution.test.ts. Instance and dates: HISTORY.md.

  21. Cancellation read as failure: an aggregate that compares each shard's result against success reds a required check when the shard finished every step and lost its race with timeout-minutes, and no rerun recovers it, because the infra-kill classifier reads only failure runs. A shard's own step conclusions tell a teardown cancellation from a mid-check one, and every required job's measured runtime belongs beside its cap, because a cap set at the measured maximum fails the first time a runner is slow. That runtime is also a per-shard SUM, so it can never be the stale-cost verdict: only the table's rank agreement with the run's own ordering is scale-free enough to survive one shard's machine. Guard: tests/scripts/check-shard-verdict.test.ts (the seam, both fail-closed directions), the gating-step list in tests/config/unit-tests-shard-workflow.test.ts, and tests/scripts/ci-verdict-runtime-cap.test.ts (a measured runtime beside its cap). Instance and dates: HISTORY.md.

  22. A dependency's cache directory attributed to the fixture that triggered it: a loader that materialises os.tmpdir()/<tool> on the caller's own stack looks like a fixture sibling, so the creator recorded for it is accurate per process and wrong per cause, and the sweep reds a file that never created it. Pin the loader's cache off for the test process rather than admitting the directory's name, and keep a planted sibling red to prove it. Enforced by the by-path-cache case in tests/config/tmp-fixture-hygiene.test.ts, plus the JITI_FS_CACHE=0 pin that tests/support/vitest-setup.ts and vitest.config.ts force on the test process. Instance and dates: HISTORY.md.

  23. Synchronous native-tree walk holds every tree: a sweep that parses many files with @ast-grep/napi in a loop that never reaches a macrotask keeps every native tree until the case ends, because the finalizer that frees a tree runs only when the event loop turns (V8 heap stays near 40 MB while RSS reaches 1.7 to 1.9 GB). An await on a settled promise does not turn it. Turn the loop once per file with setImmediate. Screen: does the loop's body parse, and does it reach a setImmediate or a real I/O await per iteration? Enforcer: none: judgment-only. The per-file RSS budget and its 200 MB headroom warning observe the symptom, but a source scan cannot tell which loops parse without data-flow reading, so it could not fail closed. Instances and dates: HISTORY.md.

  24. One home variable pinned, the rest left at the real home: a test or probe environment that pins PI_LENS_HOME but leaves HOME, USERPROFILE and the XDG directories alone lets every child that resolves its own config from them write into the maintainer's home (~/.config/.opengrep, ~/.config/.semgrep), and a symlinked managed bin lets an installer write through to the real ~/.pi-lens/bin. The pin is the whole set, assigned once in the worker so every child inherits it. npm's cache and log directory (npm_config_cache, default ~/.npm) is in the set: an unpinned npx writes ~/.npm/_logs. Screen: which directory does the process I run resolve from, and is every variable that names it pinned? Enforcer: tests/clients/worker-home-pin-hermeticity.test.ts (a real child reports its HOME and XDG directories), tests/config/real-home-reader-registry.test.ts (a file that reads the real home through REAL_HOME or userInfo needs a row in tests/support/real-home-readers.ts) and tests/clients/installer/managed-bin-symlink-escape-4789.test.ts (a pinned PI_LENS_HOME whose bin links out is refused). Instances and dates: HISTORY.md.

  25. Default-budget tree census: a test whose callback walks the repo tree (a whole-tree walker, a git ls-files spawn, a recursive directory walk, or a suite-level population it reads) keeps vitest's 5 s default, and a walk that costs 0.7 s on Linux costs several times that on the Windows unit leg and times out there. The gate enforces that the third argument is an identifier named TREE_WALK_TIMEOUT_MS (the shared constant, read by name, not by binding) or a scaledTestTimeout(...) call (the reason goes in a comment the gate does not read); in vitest's it(title, { timeout }, fn) form the timeout pair is the budget. A raw number or a file-local constant does not follow the lane's timeout scale and is refused; a same-named local constant is admitted and an import alias of the shared one is refused (no live member either way). Screen: does this case call a walker or read a binding one produced, and is its budget one of those two forms? Census: 399 under tests/ (158 in tests/config, all budgeted; 241 outside it, of which 87 are refused and admitted by name in tests/config/tree-census-timeout.baseline.json, and 154 budgeted). Enforcer: tests/config/tree-census-timeout.test.ts (it derives the declaration callee from the file's vitest imports, resolves walker aliases, reads a walk reached through a helper module under tests/ — its verdict derived from source to a fixed point over the helper graph, an unresolvable call failing closed as a walk — and counts a test-shaped call it cannot trace as a census). It does not read a walker reached through runtime source outside tests/, through a wrapper the test file itself declares, as a variable-bound arrow-function walker, through an enclosing describe.each or loop, or through an indirect form (a dynamic import(), an object, array, callback or .call reference, a class or object-literal member, a helper's own alias of an imported walker; no live member); a helper's own walk behind an unknown-verdict call reaches the census as a member, not as its own reason record (tests/ source always parses; the fail-closed branch itself is planted). Unit tests Windows is the backstop. Instances and dates: HISTORY.md.

  26. Turn-count wait for real I/O: a test waits for a file write, a child exit or a drain by awaiting a fixed number of event-loop turns, then asserts. The count holds on an idle host and runs out on a loaded CI runner, so the red lands on an unrelated PR. Wait on waitFor (tests/clients/interleaving-kit.ts), which reads a real-clock deadline scaled by PI_LENS_TEST_TIMEOUT_SCALE, and give the test a timeout above that deadline. Screen: does the wait end on the event it waits for or on a real-clock deadline, never on a count? Enforcer: the governance ast-grep rules turn-count-wait and turn-count-wait-test-hook (scripts/governance-rules/, run by npm run astgrep:self-scan), with a reasoned baseline. It does not see a count loop with no exit besides the count (a pure for (N) await yield flush), a wait spelled as recursion, a count written as iteration over a generated range (for (const _ of Array.from({ length: N }))), or a loop that compares a clock value for some other purpose. The broader awaited-loop-wait rule, which admits an awaited loop only on a real-clock deadline or a lone waitFor, sees all of these but ships disabled (scripts/governance-rules/rules-disabled/, #4865): at least 17 of its 669 members on the tree, among the members read, were real-I/O waits. Instances and dates: HISTORY.md.

  27. Test double with a result shape the real producer never returns: a double that combines fields the real producer never returns passes for the wrong reason and pins a dead branch. The timeout double in tests/clients/spawn-timeout-cooldown.test.ts returned { error: null, failure: "timeout" }, while safeSpawnAsync returns error: Error(...) with the timeout, so the test stayed green on the broken ordering in shape 91 (#5376). Census: not countable as one command. Enforcer: none: judgment-only, a scan cannot tell which fields a producer returns without running it. Screen: was the double's result shape copied from a real run of the producer, or driven through tests/support/fake-child.ts, or written by hand?

session, turn or generation lifecycle

  1. Process latch for session state: every once-latch has a session reset; session dedupe belongs in the degradation ledger where possible. Host session_start admission survives extension factory re-runs through the process-lifetime WeakSet<object> in clients/session-scope.ts: pi's RPC re-delivery reuses one event object, while each genuine start allocates another, and weak identity needs no session_shutdown release. Enforced by tests/config/session-scope-sweep.test.ts (partial: session state outside the store; "every once-latch has a reset" is not scanned).

  2. Re-derived identity: carry resolved identity or correlation across asynchronous stages; do not reconstruct it from ambiguous later inputs.

  3. Staleness-only fallback: stale work is not proof of ownership; require origin provenance before claiming it.

  4. Late loser overwrite: concurrent writers carry a monotonic generation; mutation of the generation guard must turn a test red. Enforced by tests/clients/generation-guard-sweep.test.ts (partial: no new hand-rolled guard; an unguarded concurrent writer is not scanned).

  5. Session-straddling write: capture the session generation before an await and check it before publishing. Enforced by tests/config/session-scope-sweep.test.ts and tests/clients/session-event-guard-sweep.test.ts (partial: stale-context wrappers only; a write after an await with no captured scope is not scanned).

  6. Advanced cursor predicate: predicates about the starting leaf receive the starting path, not the loop cursor.

  7. Module-scope uniqueness assumption: process evaluation can create multiple copies; process-wide registries and latches use getProcessSingleton. Enforced by tests/config/module-instance-coverage.test.ts (partial: the test-side duplicate-instance half) and by tests/config/process-slot-sweep.test.ts (every globalThis, Symbol.for, process member write or console patch in clients/, tools/, mcp/ and index.ts outside the seam is a reasoned baseline row; shrink-only; partial: a process.env.<name> write is admitted, and a module-level let latch that guards a per-evaluation exit hook is not a slot). Census: PI_LENS_PRINT_PINS=1 npx vitest run tests/config/process-slot-sweep.test.ts prints one ROW per site (27 on master after the fold). Consolidation verdict: folded onto getProcessSingleton for the four hand-rolled slots that adopted any value under their key (spawn-timeout cooldown, opaque baseline store, probe-home memo, safe-spawn lifetime registry), which now share the seam's family version and its one bounded reset record. The rest stay distributed, each with its reason in the sweep: the cross-build bridges (the key is the API), the NDJSON logger (its own legacy-adopting protocol), the background-write-drain registry (a test reset must not drop a loaded copy's registration), class brands, platform reads and console patches. The __piLens* flags in handleSessionStart are the one live member left, sequenced behind the change that edits that file.

  8. Load-time platform constant: use a live platform read or an isolated fresh import for every platform branch test. Consolidation verdict: stay distributed, because the rule admits an isolated fresh import and the seam is the one-line read process.platform, inline at 136 production sites; a helper relocates the read. Five production module-load reads remain (JAVA_EXE in jvm-runtime.ts, isWindows in lsp/launch.ts and instance-reaper.ts, gitignoreGlobOptions in file-utils.ts, RUNNERS.gradle.command in test-runner-client.ts). Enforcer: none: judgment-only; a census would only pin these five.

  9. Field inherited across entry kinds: when a coalescing queue carries a field from a replaced entry into its replacement (a read stamp, a save flag), check every kind the replacement can be, not only the kind the fix was written for (#3491: a queued close inherited a stale touch's read stamp and the stale-read drop discarded the close). No model composes the two fixes yet; that is #3495.

  10. Subset without a population verdict: when a mechanism, policy, guard, or optimisation targets N of M members, name the excluded default and a generalization verdict; see docs/pi-lens-reviewer.md (recurrence: #3622).

  11. Released-writer input shapes: property-test generators include the input shapes produced by older released writers (#3594 R2-F1).

  12. Known identity carried forward: when a producer knows an identity, carry it through asynchronous stages instead of re-deriving it downstream (#3643 F3).

  13. Joined single flight answers for edits after it started: a caller that joins an in-flight scan gets an answer computed before its own edits. Withholding that answer and re-reading the baseline later loses findings when another writer stores the row in between. Deliver the joined answer and carry the edited files into the next scan. Screen: for a join, list the writers that can store the row between the join and the next scan, and show the finding survives each.

  14. One signal wired consumer by consumer: a detector or notifier added on one consumer's seam, while other consumers derive state from the same files. Each detector then picks its own subset, and two tools disagree about one file. Screen: for a new detector, notifier or staleness marker, list every consumer that holds state derived from the same content, and show each one receives the change or record why not.

  15. Process-global last-write-wins session field: a field that holds one session's value for the whole process answers for whichever session wrote last, so a second live session overwrites what another one read. Key the state by session identity, or decide from live membership. Instances: HISTORY.md. Screen: whose data is the store, not what its key is? Seam: a session's state lives on a scope cell (scopeCell, clients/session-scope.ts, #3609); a caller that holds only a session id reaches the cell through sessionCell, which names live scopes only. Enforcer: the ownerKey column of tests/support/session-state-registry.ts, audited by tests/clients/session-state-conformance.test.ts ("owner key (#4965)"): every entry names session, repository, project or process-wide: <reason>, and a session owner states sessionSeamException, why a scope cell cannot hold it yet. A moved store has no process container and no entry; scanScopeCellKeys pins every cell by file and key (SESSION_CELL_KEYS). The same auditOwnerKeys reads all three lists: SESSION_STATE_REGISTRY, the file-level EXEMPT_SESSION_STATE_FILES rows and the declared SESSION_STORE_REGISTRY rows (#5027); a file with several owners states the narrowest. The scan behind them (scanSessionStateCandidates) flags a file for a module-level container with or without a reset, except one admitted constant: an UPPER_SNAKE built-in Map/Set/WeakMap/WeakSet declared const whose every use in clients/, tools/, mcp/ and index.ts is a read; and for a class field or this.x assignment bound to new <container or clients/ class> or [], or a depth-1 key: new <container> member of a module-level object literal (globalState = { reads: new Map() }). An admitted constant removes the symbol, not the file: a file that also exports a reset stays a candidate with a 0 pin. One symbol-count pin counts the containers, fields and members. Partial: it walks clients/; tools/ holds no candidate today, index.ts is censused by tests/config/session-scope-sweep.test.ts (#3611), and mcp/server.ts (lspReadyCwds) is outside the scan root. A field built by a factory call, through another binding or an aliased constructor is not read, and an admitted constant's forEach callback or stored value can be mutated unseen (SWEEP_HEURISTIC_LIMITS; live population 0), and the owner value itself is a judgment the audit only forces to be stated.

  16. Factory-time read of a host value set later: pi applies an extension flag's command-line value after every factory has run, so a flag read while the factory runs answers the registered default. Screen: does any flag read run while the factory runs, and does the host test apply the value after the factory, as pi does? Read it in a handler, a command or a tool, or once in session_start. Enforcer: tests/config/factory-flag-read-sweep.test.ts (partial: a reader handed to a callee that invokes it synchronously is not seen). Instances and dates: HISTORY.md.

Expired successor hand-off: an expired successor marker may authorize its named interrupted successor only for the fixed retention window in clients/session-lifecycle.ts; the shared slot retires at that boundary and records its dropped activation count before releasing the payload. Its test-only pending-window override is accepted only in a Vitest process; production keeps the fixed 60-second pending window. The window and supersession paths are pinned by the session lifecycle and session-scope tests.

availability or installer

  1. A second store answering the same availability question: a new latch, map or cache answering "can <tool> run, at what path" beside the shared policy (availability-policy.ts, createAvailabilityLatch). A consumer the gate can see is enforced by tests/clients/availability-policy-coverage.test.ts (shrink-only KNOWN_GAPS); the named-store registry ratchet is still open in #1894, so a change touching another store moves it onto the shared policy by hand. ADR: docs/adr/0005-tool-availability-enforcement-seam.md