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>
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
-
Divergent path keys: path-keyed maps use
PathKeyedMapand 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 putpath.resolvein front of an identity key: it folds..lexically before the link resolves, so/repo/link/../f.tskeys a different file than the kernel does. Screen: does any spelling reachnormalizeMapKeyorrealpathOrResolvethrough apath.resolvefirst? Enforced bytests/config/path-identity-sweep.test.ts(partial: a raw realpath or a rawpath.resolvekey outsideclients/path-utils.ts). -
Host path functions in a shape branch: once a path is classified as Windows-shaped, use
path.win32; do not use host-defaultpathfunctions. PrefertoPosix,splitPathSegments, and the path identity helpers. -
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
pathsEqualagainst the tool's cwd, capturing only the path the tool's renderer emits. Enforced bytests/config/reported-path-attribution-sweep.test.ts(shrink-only census). ADR: docs/adr/0009-reported-path-attribution.md -
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 inclients/lsp/edits.ts, which stay distributed because a key is not a directory and must not reachrealpathOrResolve. 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) andanchorPrefixinclients/dispatch/rule-policy.ts(one level per path segment). -
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 barepath.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. -
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'swritesand not in itsnames? 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'sauthorshipcolumn marks the whole-file exceptions (recognized bash, pipeline sibling files, agent_end). -
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'sauthorshipcolumn (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 withadvanceAuthorship: false, never by leaning on UNKNOWN. Enforced atclients/mutation-bridge.tsandclients/read-guard.ts, with the F-4210-2 production bridge witness.
adding or reading a cache / durable record
-
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. Asleep(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. -
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). -
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.tsandtests/clients/bounded-telemetry-sweep.test.ts(partial: container count and telemetry only; bytes, WASM objects and timers have no detector). -
Out-of-guard mirror refresh: refresh behavior-gating mirrors before the guard releases, or validate the committed generation/object identity.
-
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.
-
Cooldown beyond caller cadence: verify both recovery suppression and promotion of values served during cooldown.
-
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. -
Cold-path work on warm path: compute expensive record fields only inside the failure or timeout branch, and measure any hot-path cost.
-
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.
-
Hot bound reached at p50: record hit rate and prefer adaptive or demotion behavior over a constant that has become the work.
-
Long-lived container without a bound: module-level
Map/Setstate is bounded, evicted, or content-keyed; a reset or TTL read is not a bound. Enforced bytests/config/bounded-container-guard.test.ts(shrink-only). -
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.
-
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
-
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 > cursorreader. Commit throughclients/durable-store.tsand stamptsinside 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 |
-
Dropped side channel: trace flags, bindings, and provenance through spreads, maps, filters, and JSON serialization.
-
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.logis 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'scheckedVerdict, both inclients/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 ofDELIVERY_SURFACESplusclients/runtime-tool-result.ts) every emitted literal, whatever its words, is a claim, finding or neutral row oftests/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 otherDELIVERY_SURFACESfile 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: afallbackForalternate (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) inunansweredPrimaries(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 registeredfallbackForalternate). Enforced bytests/clients/dispatch/runners/run-outcome-ratchet.test.ts,tests/clients/dispatch/runners/parsed-nothing-sweep.test.tsandtests/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). -
Old-role filter on a substitute: compare fallback output with the substituted surface's contract, including non-blocking findings.
-
Unredacted user content: parser messages and hand-authored strings may contain file input; normalize and redact at the shared diagnostic seam.
-
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-bodyprompts for it); a test reads a record back, and a reason is judged by the reviewer (#3875). A new or changedcatchhandler inclients/,mcp/,tools/orindex.tsis judged bytests/config/silent-catch-sweep.test.ts: a record seam on every path, an unconditionalthrow, or anone: <reason>marker, and the file's pinned set re-pinned in the same change (PI_LENS_PRINT_PINS=1prints the rows).scripts/andtests/stay outside its scope. -
Swallowed failure recorded as a different event: a
catchthat 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 saysnone: <reason>. Screen: force the failure through the real entry point and read the record it wrote. -
Prose mistaken for executable structure: define lexical states and reachability before scanning shell, workflow, or source text.
-
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
findDenyinscripts/hooks/guard-bash.mjs, pinned by the "substitution next to a rule word (#3997)" rows intests/scripts/guard-bash-hook.test.ts. -
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.
-
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).
-
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
contextlist 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 bytests/clients/prompt-cache-prefix-writers.test.ts(one tier-2 cell per writer: registration, session-start plan, activation, injection). -
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>.enabledvalue, eachtools.lazyvalue (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-toolsmissed the enabled axis). -
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
-
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 tooloptionSafeTargetArg(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.tsis an option and--fixthen 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 (detektexcludes, phpstanexcludePaths, credofiles.excluded) stay silent under a relative argument too: no argv fix exists, so the verdict isresidual. Most tools never apply an ignore to an explicit file (mypy, shfmt, typos, swiftlint, trivy, dart), so their verdict iscleared. 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)? -
Wrong argv transform: verify a command is the wrapper shape before dropping an argv element or launcher name.
-
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 isparseVitestSummary(shape 63). Enforced bytests/clients/dispatch/runners/run-outcome-ratchet.test.tsandtests/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). -
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 bytests/clients/dispatch/runners/captured-real-output.test.ts, or an exemption naming a fact about the tool; presence only, not fidelity). -
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 bytests/support/spawn-cwd-scan.tsand its runner sweep. -
Language-specific rule: use
LANGUAGESand registry facts; add a non-TypeScript row whenever the rule is language-neutral. Enforced bytests/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 factsisTypeScriptFileandisJstsFactFile; the mixed-language tables stay distributed. -
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.
-
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/catchand kills the pi host (#3375, #3383, #3389).datahandlers are enforced bytests/clients/data-handler-bounds-sweep.test.tsand socketerrorlisteners bytests/clients/socket-error-listener-sweep.test.ts, and worker or IPCmessagelisteners (typedunknown, one non-rethrowing try) bytests/clients/worker-message-boundary-ratchet.test.ts; screencloseand timer callbacks by hand. -
Serial await of independent work on a hot path: a
forloop or a run ofawaits 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 throughclients/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. -
Wasm failure outside the #3605 containment: every failure thrown out of web-tree-sitter classifies through
classifyTreeSitterWasmError, and acatchinside awithParsedTreeconsumer callsreportWasmAbortbefore 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.tsreds on a shipped grammar that imports a function the runtime does not export. -
Delete or rewrite through a dependency link: a lane's
node_modulesis a symlink to the main checkout's install, so any verb that removes or rewrites under it reaches every lane (#3173:git worktree removefollowed the link twice; #4044: a worker'snpm ci --dry-runemptied it under ~7 lanes, because npm 9.2.0 ignores--dry-runfor the clean-install family). Such a verb runs only wherenode_modulesis a real directory, or in a scratch copy. The hook's verb list (NPM_NODE_MODULES_WRITERSinscripts/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 rmandcd node_modules && rm -rf ./*empty the link target, whilerm -rf node_modules(no slash) removes only the link.classifyNodeModulesDeletedenies the first set through the samehasNodeModulesSymlinkOutsideseam; 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 eachnode_modulescomponent physically, as the kernel follows a link before..; npm's--prefixlexically; 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|-followalso 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. -
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 splitTestsfrom its counts andFAILfrom its file, so a parser reads "no tests", "no red" or the wrong class. Read a Vitest transcript only throughparseVitestSummaryinscripts/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 bytests/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. -
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. -
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 (globToRegExpin clients/file-utils.ts andmatchesPatternin 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). -
Learned attribution keyed on a name alone: tier 4 of
classifyMutatingToollearns a tool name from a disk change in its call window plus apathfield, 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'sattributioncolumn (clients/writers.ts) names how each route is attributed; itsobserved-windowrows are the ones tier 4 learns. Tier 4 is admit-by-default with enumerated exemptions (the registry names, thecursor-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. -
Failure kind checked after the generic error branch: a timeout or abort result also carries
error, so anif (result.error)placed beforefailure === "timeout"makes that branch, and the state it updates, unreachable. The autofix timeout inclients/file-utils.tswas 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
-
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 (
handleToolCallreturnsundefinedand recordstool-call-handler-throw) reads a crash as the verdict under test: call it throughrunHandlerExpectingNoThrow(tests/support/handler-verdict.ts; the pi mock does it fortool_callhooks), enforced bytests/config/handler-verdict-sweep.test.ts(#4182). Enforced bytests/config/vacuous-skip-coverage.test.ts(partial: skips and conditional tests; "fails pre-fix" is the PR body's red transcript, not scannable). -
Name heuristic: a filename skip has an observable count and a content escape hatch; never silently drop a real file.
-
Skipped CI as green: absent required checks are not passing checks.
-
Duplicate module instance: tests import the same
.jsartifact as the runtime and never reset a private.tstwin. Enforced bytests/config/module-instance-coverage.test.ts. -
Source assertion for runtime behavior: prefer a runtime probe; source scans need proof that runtime observation is impossible.
-
Spelling enumerator: detect semantic structure, not a finite list of syntactic spellings, and test an unlisted spelling.
-
Platform-only red: platform-dependent tests run under injectable
path.posixandpath.win32semantics on every authoritative lane. -
Count-based baseline laundering: maintenance tools match content identity, not occurrence counts, and refuse replacement identities.
-
Raw control byte: source fixtures encode control characters as escapes or buffers; tracked-source sweeps enforce this.
-
Data-only admission: a new exemption or baseline row requires a reason in a separate checked file and a fixture that crosses the boundary.
-
Portable entry-module check: decide the entry module only with
isMainModule(import.meta.url)fromscripts/lib/is-main-module.mjs;scripts/hooks/guard-bash.mjsis the one standalone gate. -
Root wrapper drops metadata: wrappers preserve the complete marker table and are checked against direct root resolution.
-
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. -
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).
-
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-processvi.mocktargets and hand-rolled LSP client or service doubles are ratcheted bytests/clients/flake-shape-ratchet.test.ts(in-process-mock,service-double). Its census is thein-process-mockkey oftests/support/flake-shape-baseline.json: one line per<file>::<module>row, 1009 of them on master33eac2aa1. #4709 drives that count down. -
Sink read before drain: a log sink's
log/appendonly 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 (orflushAllNdjsonWriters) right before the read with no other await in between, or inside the reading helper. Enforced bytests/config/sink-read-drain-sweep.test.ts. The removal side is the same shape: drain the queue (awaitflushAllNdjsonWriters) before removing the directory a sink writes into, or a queued row recreates it; enforcer none, judgment-only. -
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+ unaffectedline never covers it. Screen: for a mapped file's diff, list the CONSTANTS in the family's as-builtformal/<family>/*.cfgand check each against the changed branch. Enforced bytests/config/tla-switch-pins.test.tsoverformal/switch-pins.json: every constant a config assigns is pinned,notCodeChoiceordeferredwith a reason; a pin names the test that drives the real code, and everyexpect: passconfig 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. -
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. -
Fixture adopts an ancestor root: a fixture created with no project marker inherits whatever root sits above it, so one stray
.gitat 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. -
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. -
Cancellation read as failure: an aggregate that compares each shard's result against
successreds a required check when the shard finished every step and lost its race withtimeout-minutes, and no rerun recovers it, because the infra-kill classifier reads onlyfailureruns. 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 intests/config/unit-tests-shard-workflow.test.ts, andtests/scripts/ci-verdict-runtime-cap.test.ts(a measured runtime beside its cap). Instance and dates:HISTORY.md. -
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 intests/config/tmp-fixture-hygiene.test.ts, plus theJITI_FS_CACHE=0pin thattests/support/vitest-setup.tsandvitest.config.tsforce on the test process. Instance and dates:HISTORY.md. -
Synchronous native-tree walk holds every tree: a sweep that parses many files with
@ast-grep/napiin 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). Anawaiton a settled promise does not turn it. Turn the loop once per file withsetImmediate. Screen: does the loop's body parse, and does it reach asetImmediateor 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. -
One home variable pinned, the rest left at the real home: a test or probe environment that pins
PI_LENS_HOMEbut leavesHOME,USERPROFILEand 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 managedbinlets 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 unpinnednpxwrites~/.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 throughREAL_HOMEoruserInfoneeds a row intests/support/real-home-readers.ts) andtests/clients/installer/managed-bin-symlink-escape-4789.test.ts(a pinnedPI_LENS_HOMEwhosebinlinks out is refused). Instances and dates:HISTORY.md. -
Default-budget tree census: a test whose callback walks the repo tree (a whole-tree walker, a
git ls-filesspawn, 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 namedTREE_WALK_TIMEOUT_MS(the shared constant, read by name, not by binding) or ascaledTestTimeout(...)call (the reason goes in a comment the gate does not read); in vitest'sit(title, { timeout }, fn)form thetimeoutpair 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 undertests/(158 intests/config, all budgeted; 241 outside it, of which 87 are refused and admitted by name intests/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 undertests/— 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 outsidetests/, through a wrapper the test file itself declares, as a variable-bound arrow-function walker, through an enclosingdescribe.eachor loop, or through an indirect form (a dynamicimport(), an object, array, callback or.callreference, a class or object-literal member, a helper's own alias of an imported walker; no live member); a helper's own walk behind anunknown-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 Windowsis the backstop. Instances and dates:HISTORY.md. -
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 byPI_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 rulesturn-count-waitandturn-count-wait-test-hook(scripts/governance-rules/, run bynpm run astgrep:self-scan), with a reasoned baseline. It does not see a count loop with no exit besides the count (a purefor (N) await yieldflush), 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 broaderawaited-loop-waitrule, which admits an awaited loop only on a real-clock deadline or a lonewaitFor, 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. -
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.tsreturned{ error: null, failure: "timeout" }, whilesafeSpawnAsyncreturnserror: 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 throughtests/support/fake-child.ts, or written by hand?
session, turn or generation lifecycle
-
Process latch for session state: every once-latch has a session reset; session dedupe belongs in the degradation ledger where possible. Host
session_startadmission survives extension factory re-runs through the process-lifetimeWeakSet<object>inclients/session-scope.ts: pi's RPC re-delivery reuses one event object, while each genuine start allocates another, and weak identity needs nosession_shutdownrelease. Enforced bytests/config/session-scope-sweep.test.ts(partial: session state outside the store; "every once-latch has a reset" is not scanned). -
Re-derived identity: carry resolved identity or correlation across asynchronous stages; do not reconstruct it from ambiguous later inputs.
-
Staleness-only fallback: stale work is not proof of ownership; require origin provenance before claiming it.
-
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). -
Session-straddling write: capture the session generation before an await and check it before publishing. Enforced by
tests/config/session-scope-sweep.test.tsandtests/clients/session-event-guard-sweep.test.ts(partial: stale-context wrappers only; a write after an await with no captured scope is not scanned). -
Advanced cursor predicate: predicates about the starting leaf receive the starting path, not the loop cursor.
-
Module-scope uniqueness assumption: process evaluation can create multiple copies; process-wide registries and latches use
getProcessSingleton. Enforced bytests/config/module-instance-coverage.test.ts(partial: the test-side duplicate-instance half) and bytests/config/process-slot-sweep.test.ts(everyglobalThis,Symbol.for,processmember write orconsolepatch inclients/,tools/,mcp/andindex.tsoutside the seam is a reasoned baseline row; shrink-only; partial: aprocess.env.<name>write is admitted, and a module-levelletlatch 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.tsprints oneROWper site (27 on master after the fold). Consolidation verdict: folded ontogetProcessSingletonfor 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 inhandleSessionStartare the one live member left, sequenced behind the change that edits that file. -
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_EXEin jvm-runtime.ts,isWindowsin lsp/launch.ts and instance-reaper.ts,gitignoreGlobOptionsin file-utils.ts,RUNNERS.gradle.commandin test-runner-client.ts). Enforcer: none: judgment-only; a census would only pin these five. -
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.
-
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). -
Released-writer input shapes: property-test generators include the input shapes produced by older released writers (#3594 R2-F1).
-
Known identity carried forward: when a producer knows an identity, carry it through asynchronous stages instead of re-deriving it downstream (#3643 F3).
-
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.
-
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.
-
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 throughsessionCell, which names live scopes only. Enforcer: theownerKeycolumn oftests/support/session-state-registry.ts, audited bytests/clients/session-state-conformance.test.ts("owner key (#4965)"): every entry namessession,repository,projectorprocess-wide: <reason>, and asessionowner statessessionSeamException, why a scope cell cannot hold it yet. A moved store has no process container and no entry;scanScopeCellKeyspins every cell by file and key (SESSION_CELL_KEYS). The sameauditOwnerKeysreads all three lists:SESSION_STATE_REGISTRY, the file-levelEXEMPT_SESSION_STATE_FILESrows and the declaredSESSION_STORE_REGISTRYrows (#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-inMap/Set/WeakMap/WeakSetdeclaredconstwhose every use inclients/,tools/,mcp/andindex.tsis a read; and for a class field orthis.xassignment bound tonew <container or clients/ class>or[], or a depth-1key: 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 walksclients/;tools/holds no candidate today,index.tsis censused bytests/config/session-scope-sweep.test.ts(#3611), andmcp/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'sforEachcallback 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. -
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
- 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 bytests/clients/availability-policy-coverage.test.ts(shrink-onlyKNOWN_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