negative-member-guard, code-range-compare (@ordered), inline-member-set; exhaustive-dispatch checked against an adopter's fixes #99

Merged
sionzee merged 2 commits from closed-set-guards into main 2026-11-20 16:43:35 +01:00
Owner

Stacked on #91 (closed-set-dispatch), and reuses its closed-set machinery (dispatch.rs, json::value::closed / codes).

Problem

An adopter's agent audited ~50 old bug fixes in their game. Several came from closed sets (Phase, Job, Op: codesOf(...) tables of numbers) where a member added later took the wrong branch:

  • e1ed54f8: the farmer carry. A ?: chain and an if chain on u.phase had no TEND branch, and this reached production.
  • 4c358533: a fake test server's switch (p.op) with default: return undefined lacked three opcodes.
  • 968dcf38: u.phase === Phase.INSIDE && u.job !== Job.FLEE guarded work. A WORSHIP job added later took that branch.
  • aa532bbe: the "jobs a unit keeps" set was copied by hand four times, one copy being a range of codes (afterJob >= Job.MOVE && afterJob <= Job.IGNITE). A world became unloadable.

Run against the parents of these fixes, #91's exhaustive-dispatch caught none of them.

Solution

1. exhaustive-dispatch checked against the adopter's history. I ran it on read-only copies of each fix and its parent (git archive), using the real node_modules. It missed every case, for three reasons. Each is now fixed:

  • The adopter's codesOf is declared as names: T & UniqueCodeNames<T>. Type-parameter inference read only a parameter typed exactly T, so no codesOf set resolved and Phase and Job were unknown. Now T is also inferred through an intersection where it is the only bare type parameter, which is what TypeScript does (json.rs, callee_decl).
  • CommandPacket is PacketOf<CommandOp> = O extends OpCode ? Simplify<{ op: O } & FieldsOf<Specs[O]['fields']>> : never. The evaluator can't build FieldsOf over the packet table, so p.op was unknown, and #91 fell back to every Op constant (server-to-client opcodes included). lazy_field now reads one field through generic aliases with their arguments bound (closures across files), the Simplify identity map, and a distributive conditional whose otherwise-branch is never (checked: every member of the binding matches). It no longer builds the other fields.
  • An if branch u.phase === Phase.CLEAN && … made rescheduleAbility's chain "no dispatch". A branch narrowed by && now names its member when the comparison comes first and another branch is a plain comparison. When every branch is narrowed, the chain is a filter and stays unreported.
Fix Parent Fix commit
e1ed54f8 fires at both sites: invariants.ts carryMax (?:) and sim.ts rescheduleAbility (if chain). Both list Phase.TEND among the missing members still fires at both, without TEND/DIG: the fix added those two branches and left 9–11 phases to : 0 / no branch. Silencing it would mean naming every phase (a table or unreachable), which the adopter didn't do
4c358533 fires (exhaustive-switch, since p.op is now typed): "doesn't handle Op.CmdPlaceBuilding, Op.CmdSetResearch and Op.CmdSetStudy", exactly the three the fix added no missing member any more. It still reports "without default: unreachable(...)", because the fix kept default: return undefined
968dcf38 silent, correctly: the setRules chain mixes subjects (if (s), waitsToUnload(u)). This is item 2's case: negative-member-guard fires negative-member-guard still fires: the fix's && u.job !== Job.WORSHIP is a second exclusion of the same kind

Before these changes, exhaustive-dispatch + exhaustive-switch gave 33 reports on the adopter's packages/sim (~35k lines) at e1ed54f8^. Now they give 80 (63 + 17). The extra reports come from sets that now resolve and from && branches. Of the 24 that && branches added at first, 10 remain after the "comparison first, one plain branch" restriction. All have the shape #91 already reports: two or more named members, the rest left to nothing.

2. negative-member-guard. Reports x !== E.A (or !=) on a closed set in an if test whose branch does work, when the test also compares another value with a member (u.phase === Phase.INSIDE && u.job !== Job.FLEE), or excludes two members or more. These are not reported: an early exit (return;, return <literal>, return <constant>, continue, break, throw), and one exclusion alone. I measured three triggers on the adopter's packages/sim at 968dcf38^:

trigger reports
any x !== member guarding work 34
… with any other condition in the test 16
… next to a positive member test, or ≥2 exclusions (chosen) 9

Most of the 34 are "everything but X" read as meant (if (u.phase !== Phase.IDLE) leavePhase(...), if (code !== SimError.UNREACHABLE) return code). The 9 include the real bug (sim.ts:15434) and a second copy of the same guard at sim.ts:8162 (u.phase === Phase.INSIDE && u.due !== NONE && u.job !== Job.WORSHIP && u.job !== Job.FLEE). In this repo's docs examples, fixtures and examples/, all three triggers give 0 reports (only the new fixture's own cases).

3. code-range-compare. Reports <, <=, >, >= with a constant of a numeric code table. A range x >= A && x <= B is reported once, and the message names the members it takes in today. A table is exempt when it is declared ordered with /** @ordered */ in the doc comment of its const. This follows #95's @sorted / @unique: same placement, read with the existing inline::tagged, and resolved across files via a new TypeLookup::code_table. It is documented on the rule page and in the Enums guide. On the adopter's sim it gives 47 reports at aa532bbe^. 41 are on stage tables (LifeStage 37, PanicStage 3, FieldStage/GriefTie) that @ordered exempts. The rest are Job (the real save-reader range), Weather, SimError, PileState and BuildingKind. The real one is gone at the fix.

4. inline-member-set. Groups each inline set by the value's last name (afterJob of u.afterJob and of a local afterJob) and by which closed set it is (the code table's declaration, or the union's members). A set is an || of ≥2 members of one value, a range of codes, or (…) && more. A place is reported when another function's set shares a member with it. The message names the other places and what differs: "with Job.MOVE…, without Job.MINE". A value tested in more than five functions is skipped: it is a dispatch field (u.job, u.phase) whose tests ask different questions. Measured on the adopter's sim at aa532bbe^:

criterion reports
any two places 91
near-subset pairs (all but one member shared) 86
different functions, ≥1 shared member, ≤5 functions (chosen) 18

The 18 include the real pair: invariants.ts:1496 {DEPOSIT, MINE} vs save.ts:1685 (range + names, without MINE). They also include a likely second drift that the fix's FLEE_ONLY_AFTER_JOBS confirms: codec.ts:198 {MATE, HAUL, ATTACK, DOUSE} vs invariants.ts:1019 {MATE, HAUL, ATTACK}. Other hits are copies: two identical 7-member BuildingKind lists in research.ts, and placeStorage in one copy of the placement commands but not the other. At the fix: 15, and the real pair is gone.

The rule needs the whole program, so check_entries computes it once (Run::member_sets) and hands each file its share. Levels and ignore comments then apply as usual. check_file (editor, LSP, oxlint plugin) sees only one file and its imports, and the adopter's two files don't import each other. So it is a CLI-only rule: PROGRAM_RULES in lib.rs, and the editor/CLI agreement test skips it. The rule page and the CHANGELOG say this. It is listed in the plugin's RULES and recommended.json (the preset test requires every rule), but the plugin never reports it.

5. must-use-result on match. std's match returns type Result<R, H> = unknown extends R ? MatchResult<H> : R, an alias of its own that the name-based check took for std's Result. I chose not to rename the alias in enum.ts, which #91's sibling branch closed-set-dispatch-match is editing. Instead, the fix is self-contained in the checker: a file that declares its own Result type whose shape isn't std's T | Err<E> doesn't make its functions return a Result. This also covers a library's own Result. The fixture match_statement shows a discarded match reporting must-use-result before and not after, while std's Result still does. I couldn't find the docs example that worked around it. I searched docs/, skills/, READMEs and the other open branches for void match, const _ = match, console.log(match( and their history. The closest is docs/guide/bun.md's console.log(match(job, …)), but it was written that way from its first commit. I left it as it is. If you know the example, it's a one-line revert.

6. census.mjs: RULE_SEE entries for exhaustive-dispatch, string-dispatch and the three new rules, all pointing to patterns-core.md#a-closed-set-of-states. I changed only those lines.

Docs: new rule pages with checked ✅/❌ examples. The two-file inline-member-set bad example is a plain ts block, because the docs harness checks one file. Also updated: exhaustive-dispatch.md (&& branches, what is read now), must-use-result.md, the rule tables in README.md and docs/README.md, the sidebar, docs/guide/enums.md ("Name the members, not the rest"), the skill's patterns-core.md "A closed set of states", and the CHANGELOG.

Tests

  • cargo nextest run --workspace: 280 passed. The emit CLI test needs the native addon, so I ran npm run build first.
  • New fixtures: closed_set_guards (reduced from the four fixes: a codesOf with names: T & Unique<T>, a PacketOf/Simplify packet type, the three new rules with their non-reported forms, @ordered, and a two-file inline-member-set) and match_statement.
  • npm run test:std: 367 passed. node scripts/docs-typecheck.mjs: 626 examples compile. Docs/skill examples: tests/docs.rs passes.
  • cargo clippy -p safe_ts_core: no new warnings in the changed code.
  • I ran the checker on the adopter's commits only in temp copies (git archive of each fix and its parent). The adopter repo wasn't touched.

Left out

  • negative-member-guard doesn't look at ?:, while, exclusions inside || / !(...), or [A, B].includes(x).
  • inline-member-set doesn't count a single x === A as a set. The adopter's two DEPOSIT-only copies aren't found that way; the two multi-member copies are.
  • code-range-compare skips string tables and compares with number literals. @ordered on something other than a code table isn't reported. #95 reports a misplaced @sorted, but I kept this tag minimal.

Created with Claude Opus 5.5 in Claude Code.

Stacked on #91 (`closed-set-dispatch`), and reuses its closed-set machinery (`dispatch.rs`, `json::value::closed` / `codes`). ## Problem An adopter's agent audited ~50 old bug fixes in their game. Several came from closed sets (`Phase`, `Job`, `Op`: `codesOf(...)` tables of numbers) where a member added later took the wrong branch: - `e1ed54f8`: the farmer `carry`. A `?:` chain and an `if` chain on `u.phase` had no `TEND` branch, and this reached production. - `4c358533`: a fake test server's `switch (p.op)` with `default: return undefined` lacked three opcodes. - `968dcf38`: `u.phase === Phase.INSIDE && u.job !== Job.FLEE` guarded work. A `WORSHIP` job added later took that branch. - `aa532bbe`: the "jobs a unit keeps" set was copied by hand four times, one copy being a range of codes (`afterJob >= Job.MOVE && afterJob <= Job.IGNITE`). A world became unloadable. Run against the parents of these fixes, #91's `exhaustive-dispatch` caught none of them. ## Solution **1. `exhaustive-dispatch` checked against the adopter's history.** I ran it on read-only copies of each fix and its parent (`git archive`), using the real `node_modules`. It missed every case, for three reasons. Each is now fixed: - The adopter's `codesOf` is declared as `names: T & UniqueCodeNames<T>`. Type-parameter inference read only a parameter typed exactly `T`, so no `codesOf` set resolved and `Phase` and `Job` were unknown. Now `T` is also inferred through an intersection where it is the only bare type parameter, which is what TypeScript does (`json.rs`, `callee_decl`). - `CommandPacket` is `PacketOf<CommandOp>` = `O extends OpCode ? Simplify<{ op: O } & FieldsOf<Specs[O]['fields']>> : never`. The evaluator can't build `FieldsOf` over the packet table, so `p.op` was unknown, and #91 fell back to *every* `Op` constant (server-to-client opcodes included). `lazy_field` now reads one field through generic aliases with their arguments bound (closures across files), the `Simplify` identity map, and a distributive conditional whose otherwise-branch is `never` (checked: every member of the binding matches). It no longer builds the other fields. - An `if` branch `u.phase === Phase.CLEAN && …` made `rescheduleAbility`'s chain "no dispatch". A branch narrowed by `&&` now names its member when the comparison comes first and another branch is a plain comparison. When every branch is narrowed, the chain is a filter and stays unreported. | Fix | Parent | Fix commit | |---|---|---| | `e1ed54f8` | **fires** at both sites: `invariants.ts` `carryMax` (`?:`) and `sim.ts` `rescheduleAbility` (`if` chain). Both list `Phase.TEND` among the missing members | still fires at both, without `TEND`/`DIG`: the fix added those two branches and left 9–11 phases to `: 0` / no branch. Silencing it would mean naming every phase (a table or `unreachable`), which the adopter didn't do | | `4c358533` | **fires** (`exhaustive-switch`, since `p.op` is now typed): "doesn't handle Op.CmdPlaceBuilding, Op.CmdSetResearch and Op.CmdSetStudy", exactly the three the fix added | no missing member any more. It still reports "without `default: unreachable(...)`", because the fix kept `default: return undefined` | | `968dcf38` | silent, correctly: the `setRules` chain mixes subjects (`if (s)`, `waitsToUnload(u)`). This is item 2's case: **`negative-member-guard` fires** | `negative-member-guard` still fires: the fix's `&& u.job !== Job.WORSHIP` is a second exclusion of the same kind | Before these changes, `exhaustive-dispatch` + `exhaustive-switch` gave 33 reports on the adopter's `packages/sim` (~35k lines) at `e1ed54f8^`. Now they give 80 (63 + 17). The extra reports come from sets that now resolve and from `&&` branches. Of the 24 that `&&` branches added at first, 10 remain after the "comparison first, one plain branch" restriction. All have the shape #91 already reports: two or more named members, the rest left to nothing. **2. `negative-member-guard`.** Reports `x !== E.A` (or `!=`) on a closed set in an `if` test whose branch does work, when the test also compares another value with a member (`u.phase === Phase.INSIDE && u.job !== Job.FLEE`), or excludes two members or more. These are not reported: an early exit (`return;`, `return <literal>`, `return <constant>`, `continue`, `break`, `throw`), and one exclusion alone. I measured three triggers on the adopter's `packages/sim` at `968dcf38^`: | trigger | reports | |---|---| | any `x !== member` guarding work | 34 | | … with any other condition in the test | 16 | | **… next to a positive member test, or ≥2 exclusions (chosen)** | **9** | Most of the 34 are "everything but X" read as meant (`if (u.phase !== Phase.IDLE) leavePhase(...)`, `if (code !== SimError.UNREACHABLE) return code`). The 9 include the real bug (`sim.ts:15434`) and a second copy of the same guard at `sim.ts:8162` (`u.phase === Phase.INSIDE && u.due !== NONE && u.job !== Job.WORSHIP && u.job !== Job.FLEE`). In this repo's docs examples, fixtures and `examples/`, all three triggers give 0 reports (only the new fixture's own cases). **3. `code-range-compare`.** Reports `<`, `<=`, `>`, `>=` with a constant of a numeric code table. A range `x >= A && x <= B` is reported once, and the message names the members it takes in today. A table is exempt when it is declared ordered with **`/** @ordered */`** in the doc comment of its `const`. This follows #95's `@sorted` / `@unique`: same placement, read with the existing `inline::tagged`, and resolved across files via a new `TypeLookup::code_table`. It is documented on the rule page and in the Enums guide. On the adopter's sim it gives 47 reports at `aa532bbe^`. 41 are on stage tables (`LifeStage` 37, `PanicStage` 3, `FieldStage`/`GriefTie`) that `@ordered` exempts. The rest are `Job` (the real save-reader range), `Weather`, `SimError`, `PileState` and `BuildingKind`. The real one is gone at the fix. **4. `inline-member-set`.** Groups each inline set by the value's last name (`afterJob` of `u.afterJob` and of a local `afterJob`) and by which closed set it is (the code table's declaration, or the union's members). A set is an `||` of ≥2 members of one value, a range of codes, or `(…) && more`. A place is reported when another function's set shares a member with it. The message names the other places and what differs: "with Job.MOVE…, without Job.MINE". A value tested in more than five functions is skipped: it is a dispatch field (`u.job`, `u.phase`) whose tests ask different questions. Measured on the adopter's sim at `aa532bbe^`: | criterion | reports | |---|---| | any two places | 91 | | near-subset pairs (all but one member shared) | 86 | | **different functions, ≥1 shared member, ≤5 functions (chosen)** | **18** | The 18 include the real pair: `invariants.ts:1496` `{DEPOSIT, MINE}` vs `save.ts:1685` (range + names, without `MINE`). They also include a likely second drift that the fix's `FLEE_ONLY_AFTER_JOBS` confirms: `codec.ts:198` `{MATE, HAUL, ATTACK, DOUSE}` vs `invariants.ts:1019` `{MATE, HAUL, ATTACK}`. Other hits are copies: two identical 7-member `BuildingKind` lists in `research.ts`, and `placeStorage` in one copy of the placement commands but not the other. At the fix: 15, and the real pair is gone. The rule needs the whole program, so `check_entries` computes it once (`Run::member_sets`) and hands each file its share. Levels and ignore comments then apply as usual. `check_file` (editor, LSP, oxlint plugin) sees only one file and its imports, and the adopter's two files don't import each other. So it is a CLI-only rule: `PROGRAM_RULES` in `lib.rs`, and the editor/CLI agreement test skips it. The rule page and the CHANGELOG say this. It is listed in the plugin's `RULES` and `recommended.json` (the preset test requires every rule), but the plugin never reports it. **5. `must-use-result` on `match`.** std's `match` returns `type Result<R, H> = unknown extends R ? MatchResult<H> : R`, an alias of its own that the name-based check took for std's `Result`. I chose not to rename the alias in `enum.ts`, which #91's sibling branch `closed-set-dispatch-match` is editing. Instead, the fix is self-contained in the checker: a file that declares its own `Result` type whose shape isn't std's `T | Err<E>` doesn't make its functions return a `Result`. This also covers a library's own `Result`. The fixture `match_statement` shows a discarded `match` reporting `must-use-result` before and not after, while std's `Result` still does. **I couldn't find the docs example that worked around it.** I searched `docs/`, `skills/`, READMEs and the other open branches for `void match`, `const _ = match`, `console.log(match(` and their history. The closest is `docs/guide/bun.md`'s `console.log(match(job, …))`, but it was written that way from its first commit. I left it as it is. If you know the example, it's a one-line revert. **6. `census.mjs`:** `RULE_SEE` entries for `exhaustive-dispatch`, `string-dispatch` and the three new rules, all pointing to `patterns-core.md#a-closed-set-of-states`. I changed only those lines. Docs: new rule pages with checked ✅/❌ examples. The two-file `inline-member-set` bad example is a plain `ts` block, because the docs harness checks one file. Also updated: `exhaustive-dispatch.md` (`&&` branches, what is read now), `must-use-result.md`, the rule tables in `README.md` and `docs/README.md`, the sidebar, `docs/guide/enums.md` ("Name the members, not the rest"), the skill's `patterns-core.md` "A closed set of states", and the CHANGELOG. ## Tests - `cargo nextest run --workspace`: 280 passed. The `emit` CLI test needs the native addon, so I ran `npm run build` first. - New fixtures: `closed_set_guards` (reduced from the four fixes: a `codesOf` with `names: T & Unique<T>`, a `PacketOf`/`Simplify` packet type, the three new rules with their non-reported forms, `@ordered`, and a two-file `inline-member-set`) and `match_statement`. - `npm run test:std`: 367 passed. `node scripts/docs-typecheck.mjs`: 626 examples compile. Docs/skill examples: `tests/docs.rs` passes. - `cargo clippy -p safe_ts_core`: no new warnings in the changed code. - I ran the checker on the adopter's commits only in temp copies (`git archive` of each fix and its parent). The adopter repo wasn't touched. ## Left out - `negative-member-guard` doesn't look at `?:`, `while`, exclusions inside `||` / `!(...)`, or `[A, B].includes(x)`. - `inline-member-set` doesn't count a single `x === A` as a set. The adopter's two `DEPOSIT`-only copies aren't found that way; the two multi-member copies are. - `code-range-compare` skips string tables and compares with number literals. `@ordered` on something other than a code table isn't reported. #95 reports a misplaced `@sorted`, but I kept this tag minimal. Created with Claude Opus 5.5 in Claude Code.
- exhaustive-dispatch: a branch narrowed by `&&` names its member; code tables built by a
  function taking `names: T & Check<T>`, and a field of a generic packet type built from a table
  (`PacketOf<O>`), are read, so the adopter's `codesOf` sets and `CommandPacket['op']` resolve.
- negative-member-guard: `x !== E.A` guarding work, next to another member test or with a second
  exclusion.
- code-range-compare: order compares with a code table's constants; `/** @ordered */` exempts a
  table whose order is its meaning.
- inline-member-set: overlapping member sets of one value in several functions (safe-ts check
  only, PROGRAM_RULES).
- must-use-result: a file's own `Result` type that isn't std's (`match`'s alias) is no Result.
- census.mjs maps the closed-set rules to patterns-core.md.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
sionzee changed target branch from closed-set-dispatch to main 2026-11-20 16:41:02 +01:00
sionzee force-pushed closed-set-guards from 88e987fc38
All checks were successful
Benchmarks / bench (pull_request) Successful in 3m1s
to 8a2a1e49c5
All checks were successful
Benchmarks / bench (pull_request) Successful in 3m38s
2026-11-20 16:43:31 +01:00
Compare
sionzee deleted branch closed-set-guards 2026-11-20 16:43:35 +01:00
Sign in to join this conversation.
No reviewers
No labels
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
Evobug/Safe-Ts!99
No description provided.