@evobug_com/safe-ts-skill 0.0.0-stage → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,146 @@
1
+ # The target architecture document
2
+
3
+ Write this document before any code changes, from the census and from reading the code, and get
4
+ it approved. Every builder reads it; reviewers check changes against it. Keep it in the
5
+ repository (for example `docs/safe-ts-architecture.md`) and link it from the project's
6
+ `CLAUDE.md` / `AGENTS.md` (template in [templates.md](templates.md)).
7
+
8
+ Each section below gives SAFE-TS's answer as the default. Keep the default unless the project
9
+ has a reason, and write the reason down. "The checker passes" is not a reason: the checker
10
+ accepts most of what this document rules out.
11
+
12
+ ---
13
+
14
+ ## 1. Absence
15
+
16
+ - Inside the app, a missing value is `undefined`, typed `Option<T>`. `null` is not written.
17
+ - `null` from outside is converted where it comes in: `validate<T>` / `parseJson<T>` turn a JSON
18
+ `null` into `undefined` for `Option<T>` and optional fields; the feature packs' safe versions
19
+ give `Option` for DOM and storage lookups (`querySelector(document, sel)`,
20
+ `getItem(localStorage, key)`).
21
+ - **Not loaded** and **none** are different names. Loading is an `AsyncState` (kept by
22
+ `useTask`); "asked, and there is none" is `Option<T>` inside `Ready`, or an `Enum` variant when
23
+ it carries meaning. Never `Option<Option<T>>`, never `Option<T | JsonNull>`.
24
+ - `jsonNull` / `JsonNull` appear only in data that goes out or in a type the protocol defines
25
+ with a meaningful `null`. A body that changes a record is a `Patch<T>`: each field left out,
26
+ `clear` (sent as `null`) or set, one spelling each.
27
+ - Decide and write down, per API: does the server tell a missing key from `null` in request
28
+ bodies? List the fields where a clear is sent as `null`. These become contract checks
29
+ ([behaviour.md](behaviour.md)).
30
+ - If a transport adapter converts `null`↔`undefined` for every request, write down that it is a
31
+ bridge, which code it covers, and the step that removes it.
32
+ - Strict code that legacy callers still pass `null` to takes `Option<T> | LegacyNull` (std's
33
+ bridge, counted by `safe-ts check`), not a project-local nullable type. Write down which
34
+ callers, and the step that removes each.
35
+
36
+ ## 2. Errors
37
+
38
+ - A function that can fail returns `Result<T, E>`. `E` is a named type, usually an `Enum` of the
39
+ kinds the caller handles differently.
40
+ - Every request function returns `Promise<Result<T, RequestError>>`, takes an `AbortSignal`, adds
41
+ a time limit, and validates the body with `validate<T>`. Name the module that holds them.
42
+ - Store members (actions) that can fail return a `Result` too. A store doesn't throw "not
43
+ loaded yet": it exposes an `AsyncState` or an `Option`.
44
+ - `PropagateError` subclasses are for failures that end a whole request, job or command, caught
45
+ once at its top. List those tops.
46
+ - `panic` is for invariants nothing can handle. Never for data from a request or a loading flag.
47
+ - A throw from your own code is a bug, not an `Err`: don't wrap your own functions in
48
+ `unsafeAsync` to turn bugs into failures. Where a call can both return an `Err` and throw,
49
+ `unsafeAsync(fn, Panic)` keeps them apart.
50
+
51
+ ## 3. State
52
+
53
+ - No mutable module state. Vue: Pinia setup stores (or a `createX()` provided at startup and read
54
+ with `injectRequired`). React: component state, a common parent, or a context whose provider
55
+ creates the value. Node: a context created at startup and passed down.
56
+ - A cache that can be thrown away and computed again is a `/** @cache */` constant or field;
57
+ anything else is state.
58
+ - Events between modules that must not import each other go through a small store (a counter the
59
+ writer bumps, a `watch` in the reader), not through another store's action hooks.
60
+
61
+ ## 4. Async work
62
+
63
+ - Every load and every action a user waits for goes through `useTask` (Vue: in a component or a
64
+ setup store; React: in a component), shown with `<Match>` or `match`. No `loading` / `error` /
65
+ `data` refs or states, no hand-written latest-wins counters.
66
+ - Every task's work passes its `signal` on to the request.
67
+ - Name the cases where the last answer stays on screen during a refresh, and how
68
+ ([patterns-vue.md](patterns-vue.md#a-refresh-that-blanks-the-list)).
69
+
70
+ ## 5. Closed sets of states
71
+
72
+ - A value that is one of a few kinds is an `Enum` with `constructors`, handled with `match`
73
+ (every variant decides) or `is` / `variant` / `_` (one variant, "everything else").
74
+ - One style for reading an enum: `match`, `is`, `variant` in TypeScript; `<Match :value>`, or an
75
+ exhaustive `v-if` chain of `is(...)`, in templates. `prefer-is-over-tag` (idiomatic) holds it:
76
+ no raw `.tag` anywhere.
77
+ - What a screen or a flow is doing is one `Enum` that names every state it can be in, the
78
+ first one included: `Editing | Rejected { error } | Published`, the way `useTask`'s
79
+ `AsyncState` is `Idle | Loading | Ready | Failed`. Not an `Option` of the error, where
80
+ `undefined` stands for "not tried yet" and for "it worked" alike, so success leaves no
81
+ trace and the template can't say it. `Option<T>` is for a value that is there or not (the
82
+ selected item, the signed-in user), not for the outcome of a step.
83
+ - Sets of booleans of which at most one is true are one `Enum`. Unions told apart by key
84
+ presence (`'k' in o`) get a tag.
85
+ - A string the server fills from a list it may extend (a status, a type) is an `Open<K>`, read
86
+ with `match` (an `Unknown` handler) and `lookup(table, value, fallback)`. List those fields.
87
+
88
+ ## 6. Boundaries
89
+
90
+ - Every value from outside (responses, storage, `postMessage`, URL and query parameters,
91
+ `history.state`, server-rendered data in the page) is read with `validate<T>` /
92
+ `parseJson<T>` or a pack's safe version.
93
+ - No `as` on such values, no hand-written `value is T` guard or assertion signature
94
+ (`no-type-predicate`) and no overload over a looser implementation (`no-overload`). A trusted boundary that can't be validated (a worker's message
95
+ of the same build, a type `validate` refuses) is a `trust<T>(value)` call, listed here by name
96
+ with the reason.
97
+ - Types that `validate<T>` reads are declared in the project: project files, namespaces of
98
+ generated model layers (`Backend.Models.User`), workspace packages, imported relatively or
99
+ through tsconfig `paths`. Not a package's types: where the wire type comes from a package,
100
+ decide where the project's copy lives.
101
+ - Element refs (Vue) go through `useElement` / `useOptionalElement` / `useElements`; DOM lookups
102
+ outside Vue through the browser pack's `querySelector(root, selector, Class)`.
103
+ - Bound URLs go through `safeHref` (list here the extra schemes the app needs, passed as
104
+ `{ schemes }`), and props that take a URL are typed `SafeUrl`. HTML goes through the one
105
+ sanitizer declared with `defineSanitizer` (name its module here), and props that take markup
106
+ are typed `Html`. Brands are made only by their constructors (`brand-constructor`).
107
+
108
+ ## 7. Tooling
109
+
110
+ - `tsconfig.json`: `strict`, `noUncheckedIndexedAccess` and `exactOptionalPropertyTypes` on from
111
+ the first step, in the tsconfig every tool reads (tsc, vue-tsc, type-aware oxlint), with
112
+ `"@evobug_com/safe-ts-std/strict-lib"` in `"types"`.
113
+ - `"safe-ts": { "idiomatic": true }` in package.json from the first step, the feature packs the
114
+ code needs (`"features": [...]`), and the project's request wrappers (`"requestFunctions"`).
115
+ - `safe-ts check` runs with `--deny-warnings` wherever a gate reads its exit code, CI and the
116
+ builders' own loop alike. Rule levels changed in package.json (`"rules"`, `"overrides"`) are
117
+ exceptions (section 10), each with its reason.
118
+ - The gates, and where they run (local script, CI): [order-and-gates.md](order-and-gates.md).
119
+ - Runtime: which processes run TypeScript directly (Node scripts, tests, workers, Bun) and how
120
+ they get the transform (`--import @evobug_com/safe-ts-transform/register`, the Bun preload
121
+ `@evobug_com/safe-ts-transform/bun`, or `safe-ts emit`).
122
+ - The build's `exclude` list (vendored and generated code only), and what it leaves out.
123
+
124
+ ## 8. Escape hatches
125
+
126
+ Policy and budget: [escape-hatches.md](escape-hatches.md). Copy the table, fill in the budget per
127
+ area: legacy files, `unsafe`, `panic`, `trust`, `LegacyNull`, `safe-ts-ignore` comments, casts.
128
+
129
+ ## 9. Sanctioned helpers
130
+
131
+ The project's own helpers around SAFE-TS (a request wrapper, a test factory), each with one line
132
+ on what it does and why std doesn't cover it. Check std first: `getOwn(table, key, fallback)`,
133
+ `toBase64`, `describeError`, `omit`, `trust` and `LegacyNull` exist. A builder who
134
+ wants a new one adds it here first. A helper that hides a pattern this document rules out (an
135
+ `orNone` that wraps `unwrapOr(x, undefined)`, a `must()` that turns any failure into one error)
136
+ doesn't go in.
137
+
138
+ ## 10. Exceptions
139
+
140
+ Each deliberate deviation: what, where, why, until when. The census baseline is reviewed against
141
+ this list.
142
+
143
+ ## 11. Order of work and areas
144
+
145
+ The areas (directories or modules), who migrates each, what each depends on, and the order
146
+ ([order-and-gates.md](order-and-gates.md)). The census per directory is the starting count.
@@ -0,0 +1,86 @@
1
+ # Behaviour preservation
2
+
3
+ The type checker, the linter and `safe-ts check` can all pass while the app behaves differently:
4
+ a request body loses a key, a failure that was shown is now dropped, a dialog closes on an
5
+ error. The checks below find what they don't. Plan them in the setup step, record the "before"
6
+ then, and run them for every area.
7
+
8
+ ## Contract checks: what goes on the wire
9
+
10
+ Moving from `null` to `undefined` changes what `JSON.stringify` writes: a field that was `null`
11
+ is now missing from the body. A server that tells the two apart (a missing key leaves a field
12
+ alone, `null` clears it) now ignores a clear.
13
+
14
+ - From the architecture document's list of fields that clear with `null`, write one test per
15
+ request builder: build the body for "clear this field" and assert the serialized text has
16
+ `"field":null`.
17
+ - Search for code that tests a hydrated value by value (`record[field] === undefined`,
18
+ `x === null`): after the conversion, `undefined` may mean "not loaded" where `null` meant
19
+ "none".
20
+ - Removing `?? undefined` bridges after a type change is safe where the type is precise, and not
21
+ where it is `any` (an editor library's attributes, a value read inside `unsafe`, `$el`):
22
+ `tsc` reports nothing there. Read each one.
23
+
24
+ ## Network bodies, before and after
25
+
26
+ Record the requests the app sends for each write flow (method, URL, body), on the baseline build
27
+ and on the branch, against the same data, and compare them. A Playwright script that clicks
28
+ through the flows and logs `request.method()`, `request.url()` and `request.postData()` is
29
+ enough; so is a HAR export from the browser for a short list of flows. Any difference is either
30
+ intended (and written in the hand-off report) or a regression.
31
+
32
+ ## Browser smoke
33
+
34
+ A list of every page and every write flow, run on the branch:
35
+
36
+ - each page loads, with no console errors and no framework warnings (Vue warns in development);
37
+ - each write flow sends what it sent before (above) and shows its result;
38
+ - each failure path still shows what it showed: block a request or make it answer 422 or 500
39
+ (route interception in Playwright), and check that inline messages are still inline;
40
+ - an enum value the build doesn't know, by rewriting one response: the page shows a fallback,
41
+ it doesn't crash;
42
+ - a slow response followed by a fast one (an id changed quickly): the newer answer stays.
43
+
44
+ Running the baseline build and the branch side by side against the same database, and comparing
45
+ the rendered text of each page (dates, numbers, lists), catches what no rule sees.
46
+
47
+ ## Regressions a real migration produced
48
+
49
+ All of these passed every static gate:
50
+
51
+ - **A dialog closed and lost the typed input** when its submit handler started returning an `Err`
52
+ instead of throwing: the dialog closed on any return and stayed open only on a throw. Change
53
+ the caller's contract with the handler's.
54
+ - **A failure was dropped silently** because a store member started returning a `Result` and a
55
+ caller in another area kept its `try`/`catch`. The checker now reports a dropped store
56
+ `Result` (`must-use-result`) and, with the idiomatic layer, the dead `try` (`catch-on-result`);
57
+ it still doesn't follow a store passed as a parameter or kept in a `ref`. Search every caller
58
+ of every changed member.
59
+ - **A toast replaced an inline message**: three dialogs showed the server's 422 sentence inline by
60
+ testing the HTTP library's error class; when the store began to reject with its own error
61
+ type, the test stopped matching and a generic toast appeared. Match on the new error kinds.
62
+ - **A reload blanked a list**: a list rendered only in the `Ready` slot disappeared during every
63
+ refresh (`run()` sets `Loading`). Keep the last answer on screen
64
+ ([patterns-vue.md](patterns-vue.md#a-refresh-that-blanks-the-list)).
65
+ - **A cross-module refresh stopped**: a page refreshed through another store's `$onAction` hook;
66
+ once the call moved to a plain request function, the hook never fired. Use an explicit event
67
+ (a counter in a small store).
68
+ - **A load started in setup read element refs before they existed**: moving a `load` from
69
+ `onMounted` to setup made it read a `useElement` before mount, the task went back to `Idle`,
70
+ and the page stayed on its loading mark.
71
+ - **An autofix changed a number another language reads**: `unicorn/numeric-separators-style`
72
+ wrote `47_474` in a constant that a server-side regex parsed as `47`. The preset no longer
73
+ turns that rule on; if the project's own config does, check where a constant is read before
74
+ accepting its fix.
75
+ - **A startup check validated data another module decorates at import time**, and a legacy file
76
+ used a prelude name without an import (`ReferenceError` at runtime, in a setup that kept legacy
77
+ files away from the transform): both passed `tsc`, the checker and the Node tests, and only
78
+ the browser showed them. Don't `exclude` legacy files from the plugin.
79
+ - **An unknown server value crashed a page**: a table indexed by a state the build didn't know
80
+ gave `undefined`, and a property read on it threw. Look up wire keys with
81
+ `getOwn(table, key, fallback)` ([patterns-core.md](patterns-core.md#a-table-keyed-by-server-data)).
82
+ - **An `Open<K>` sent back as the object**: `JSON.stringify` writes `{"tag":…,"value":…}`
83
+ where the server expects the string. Send `.value`; the request-body comparison catches it.
84
+ - **Base64 of non-ASCII text changes with `toBase64`**: it encodes UTF-8 where `btoa` wrote
85
+ Latin-1 bytes. Compare the encoded values a flow sends before and after
86
+ ([patterns-core.md](patterns-core.md#base64)).
@@ -0,0 +1,136 @@
1
+ # The census
2
+
3
+ `scripts/census.mjs` (in this skill) counts two things per rule, per pattern and per directory:
4
+
5
+ 1. what `safe-ts check --json --idiomatic` reports, errors and warnings, with the idiomatic
6
+ rules on whether or not package.json turns them on yet: several of them (`prefer-is-over-tag`,
7
+ `prefer-q`, `key-presence-union`, `no-swallowed-error`,
8
+ `json-null-in-app`, `cast-in-test`, ...) report the hand-rolled forms a checker-driven
9
+ migration leaves behind;
10
+ 2. the hand-rolled patterns no rule reports, found by regular expressions over the source
11
+ text.
12
+
13
+ It also lists the escape hatches and how often the code already uses each SAFE-TS feature.
14
+
15
+ ## Running it
16
+
17
+ From the project root (the folder with `package.json` and `tsconfig.json`):
18
+
19
+ ```sh
20
+ node .claude/skills/safe-ts-migrate/scripts/census.mjs # the report
21
+ node .claude/skills/safe-ts-migrate/scripts/census.mjs src app # only these folders
22
+ node .claude/skills/safe-ts-migrate/scripts/census.mjs --depth 3 # finer directory grouping
23
+ node .claude/skills/safe-ts-migrate/scripts/census.mjs --show trio-files # every place of one pattern
24
+ node .claude/skills/safe-ts-migrate/scripts/census.mjs --show no-unchecked-cast # every finding of one rule
25
+ node .claude/skills/safe-ts-migrate/scripts/census.mjs --json > census.json
26
+ ```
27
+
28
+ - Files: `.ts`, `.tsx`, `.mts`, `.cts`, `.vue`, `.jsx`, from `git ls-files` (so `.gitignore`
29
+ applies), without `.d.ts` files. Outside git, `node_modules`, `dist`, `build` and the like
30
+ are skipped. The skill's own folder is never scanned.
31
+ - The scripts run before SAFE-TS is installed, so they don't import std. They pass oxlint with
32
+ the SAFE-TS preset (and the Node pack): a project that lints every file needn't exclude
33
+ `.claude/`. When a step fails (a file it can't read, a baseline that isn't JSON), the census
34
+ prints `census: <what failed>: <why>` and exits 2.
35
+ - The checker: the `safe-ts` binary from the project's `node_modules` (`SAFE_TS_BIN=<path>`
36
+ overrides it; `--no-check` skips it, `--no-idiomatic` leaves the idiomatic rules out). Every
37
+ scanned file is passed as an entry, so tests, scripts and files nothing imports are counted
38
+ like the patterns are (`check` follows imports, tsconfig aliases included, from its entries).
39
+ `--entry src/main.ts` (repeatable) checks from given entries instead.
40
+ - Files marked `// @safe-ts legacy` report nothing. Run the first census **before** marking
41
+ anything, so the counts cover the whole code base.
42
+
43
+ ## Reading it
44
+
45
+ - **Checker findings by rule**, errors and warnings (`(warn)`), with the directories that have
46
+ the most and, for the rules a migration meets most, the catalogue entry to read. Start with
47
+ the **root causes**: one origin (a `throw` in a helper, a `JSON.parse`) behind many
48
+ `unhandled-failure` findings. Fixing it there clears them all. `safe-ts check src/main.ts
49
+ --summary` gives the same table by rule and directory without the patterns.
50
+ - **Patterns** are a map of where to look, not findings. Each line names the catalogue entry with
51
+ the target form. Read every place before changing it: `=== ''` is often a real empty-input
52
+ check, and `-1` is sometimes a real number.
53
+ - **Escape hatches** are the budget's starting point ([escape-hatches.md](escape-hatches.md)).
54
+ - **Features in use**: a migration that ends with `useTask`, `AsyncState`, `Enum`, `match` or
55
+ `<Match>` near zero has converted the code, not adopted the architecture
56
+ ([final-pass.md](final-pass.md)).
57
+ - **Per directory**: findings and the most frequent patterns. This is the input for the areas
58
+ and their order ([order-and-gates.md](order-and-gates.md)).
59
+
60
+ ## The patterns
61
+
62
+ | Pattern | Finds | Target |
63
+ |---|---|---|
64
+ | `loading-flag` | `const loading = ref(false)`, `useState(false)`, `let busy = false` (names like loading, busy, pending, saving, submitting) | `useTask` |
65
+ | `error-state` | an error kept in its own state: `ref('')`, `ref(null)`, `ref<E>()`, `shallowRef<Option<E>>()`, `useState('')` named error, failed, problem | `useTask`'s `Failed`, or one state `Enum` with a failed variant |
66
+ | `error-or-undefined` | a state set to `isErr(r) ? r.error : undefined`: `undefined` is both "not tried yet" and "it worked" | one state `Enum` that names every state (`Editing \| Rejected \| Published`) |
67
+ | `trio-files` | files with a loading flag and an error state | `useTask` + `<Match>` |
68
+ | `empty-string-sentinel` | `=== ''`, `!== ''`, `return ''` | `Option<string>`, `Result<void, E>` |
69
+ | `minus-one-sentinel` | `=== -1`, `return -1`, `= -1`; a named constant (`const NONE = -1`) once, at its declaration ([below](#a-named-sentinel)) | `Option<T>`, `indexIn` |
70
+ | `zero-sentinel` | an id or index that starts at `0` | `Option<T>` |
71
+ | `string-if-chain` | one value compared with 3 or more string literals in a file | `Enum` + `match`, or a union parsed once ([patterns-core.md](patterns-core.md#a-closed-set-of-states)); the checker's rules: `string-dispatch` (a plain `string`, idiomatic), `exhaustive-dispatch` and `exhaustive-switch` (a closed set) |
72
+ | `boolean-state`, `boolean-flag-files` | boolean refs/states; files with 3 or more | one `Enum` |
73
+ | `raw-fetch` | `fetch(`, `axios(`/`axios.get(`, `new XMLHttpRequest` | a request function returning a `Result` |
74
+ | `try-catch`, `promise-catch` | `try {`, `.catch(` | a `Result`; `unsafe` for code that throws |
75
+ | `as-cast`, `double-cast` | `x as T` (not `as const`), `as unknown as`, `as never`, `as any`; not the renames in import and export lists (`type Building as SimBuilding,` on a line of its own too) or a mapped type's `[E in Events as E['type']]` | `validate<T>`, an annotation, `satisfies` |
76
+ | `json-parse`, `raw-storage` | `JSON.parse(`, `localStorage.getItem(` and friends | `parseJson<T>`, the browser pack's `getItem` / `setItem` |
77
+ | `unsafe`, `unsafe-async`, `unexplained-unsafe`, `panic`, `void-call` | escape hatches; `unsafe(` without a comment on its line or the line above | [escape-hatches.md](escape-hatches.md) |
78
+ | `trust`, `legacy-null`, `safe-ts-ignore` | `trust<T>(...)`, `LegacyNull`, `// safe-ts-ignore` (and `-file`, `<!-- -->`) comments | [escape-hatches.md](escape-hatches.md) |
79
+ | `module-let` | a `let` at the top of a `.ts` module, not in a test file | a store, a context |
80
+
81
+ Comment lines are skipped (except for `safe-ts-ignore`); strings are not, so a pattern inside a
82
+ string literal counts.
83
+
84
+ `module-let` skips test files, the ones the checker calls test files: named `*.test.*` or
85
+ `*.spec.*`, in a `test`, `tests`, `__tests__` or `__mocks__` folder, or importing a test runner
86
+ (`vitest`, `node:test`, `bun:test`, `@jest/globals`, `mocha`). A test file's `let errors:
87
+ string[]` that `beforeEach` resets is the runner's idiom: each test file is its own module, so
88
+ it isn't state the app shares. The checker's `no-mutable-global` still reports it, when the
89
+ project lints tests.
90
+
91
+ ### A named sentinel
92
+
93
+ Not every `-1` means "not found". An index that typed arrays or a file format store can't be
94
+ `undefined`, so a project names it once: `const NONE = -1`. The census counts that
95
+ declaration (also `export const`, `static readonly`, with a type or `as const`), and not the
96
+ comparisons or arguments that use the name (`=== NONE`, `.fill(NONE)`), so the sentinel is one
97
+ entry, not one per use. To mark one, write every use with its name: a literal `-1` that means
98
+ the same thing still counts, and is the place to replace. Record the sentinel in the
99
+ architecture document's exceptions, with why `Option` can't hold it.
100
+
101
+ The forms the idiomatic rules see are counted as their findings, not as patterns:
102
+
103
+ | Rule (idiomatic) | Finds | Target |
104
+ |---|---|---|
105
+ | `prefer-is-over-tag` | `x.tag === '...'`, `switch (x.tag)`, in code and templates | `is`, `variant`, `match`, `<Match>` |
106
+ | `prefer-constructor-tag` | `is(x, "Published")` where the enum has constructors in scope | `is(x, Status.Published)` |
107
+ | `prefer-q`, `prefer-map-err` | `if (isErr(x)) return x`, an error re-wrapped by hand | `q(x)`, `q(x, map)`, `mapErr` |
108
+ | `key-presence-union` | `'key' in x` telling a project union's members apart | a tagged `Enum` |
109
+ | `no-swallowed-error` | `unwrapOr(x, undefined)`, `.catch(() => {})`, helpers around them | the `Result` itself |
110
+ | `json-null-in-app` | `JsonNull` as app state (`Ref<T \| JsonNull>`, `Option<T \| JsonNull>`) | `Option`, an `Enum`, `AsyncState<Option<T>, E>` |
111
+ | `catch-on-result` | `.catch` / `try` around calls that return a `Result` | the `Result` checked |
112
+ | `latest-wins-counter`, `unused-task-signal` | a hand-written "latest run wins" ticket; a task that ignores its `signal` | `useTask` (outside components, std's `latest`), the `signal` passed on |
113
+ | `cast-in-test` | `as unknown as T`, `as never` in tests where `no-unchecked-cast` is off for them (otherwise that rule reports the cast) | `fixture`, `testDouble`, `unchecked` |
114
+ | `panic-on-loading` | `panic` under a loading flag | a state the page shows |
115
+
116
+ `--show <rule>` lists every finding of a rule, like `--show <pattern>` for a pattern.
117
+
118
+ ## The census as a gate
119
+
120
+ A baseline records, for each gated pattern and each rule, the count in every file. The gate
121
+ fails when any file's count rises, and names the file:
122
+
123
+ ```sh
124
+ node scripts/census.mjs --write-baseline safe-ts-census.json # once, and after a reviewed change
125
+ node scripts/census.mjs --baseline safe-ts-census.json # in CI: exit 1 if a count rose
126
+ ```
127
+
128
+ This is the ratchet: the counts may only fall, so a new `loading` flag, `as` cast, `trust` or
129
+ `safe-ts-ignore` in any file fails the build, while the old ones are burned down area by area.
130
+ It holds rules too, warnings included, so a rule you aren't ready to make an error stays at
131
+ its level in package.json and can't grow: ratchet it rather than setting it `"off"`. A legacy
132
+ file reports nothing, so its findings count from the change that removes its marker: remove it
133
+ in the change that makes the file pass. Rewrite the baseline only in
134
+ a commit that says why (a decided exception, a moved file). Commit the baseline next to the
135
+ architecture document. For CI, copy `census.mjs` and `safe-ts.mjs` into the project's
136
+ `scripts/` folder (they import each other by relative path), or commit the skill folder.
@@ -0,0 +1,72 @@
1
+ # Escape hatches: policy and budget
2
+
3
+ Every escape hatch is allowed somewhere, and each one is visible and counted. The policy says
4
+ where; the budget says how many; the hand-off report says how many are left. `safe-ts check`
5
+ counts most of them after each run, and names what package.json weakens below the defaults
6
+ (rule levels, `infer`, `infer.exclude`, `testRunners`, `vue.sanitizers`):
7
+
8
+ ```text
9
+ escape hatches: 2 unsafe() block(s), 0 panic() call(s), 1 trust() call(s), 3 LegacyNull use(s), 0 @cache mark(s), 1 safe-ts-ignore comment(s), 0 legacy file(s), 1 std file(s) (src/protocol/trusted.ts), 0 @ts-ignore, 1 @ts-expect-error (and 12 in test files), 0 @ts-nocheck comment(s)
10
+ weakened below the defaults: no-mutable-global off for src/stores/** (package.json)
11
+ ```
12
+
13
+ `safe-ts check --baseline safe-ts-baseline.json` fails when any of those counts rose, something
14
+ was newly weakened, a setting got weaker than the baseline recorded (`"idiomatic"` off, a pack
15
+ out of `"features"`, an entry out of `"emitters"` or `"requestFunctions"`, Vue SSR off), or the
16
+ files not checked, the unresolved imports or the warnings of a rule rose (`--write-baseline`
17
+ records them). The census counts the rest (`unsafeAsync`, `void` calls,
18
+ casts, `unsafe` without a reason comment), per file, and its baseline keeps each count from
19
+ rising. Treat a rising count as a review question, the way Rust projects treat a new `unsafe`
20
+ block.
21
+
22
+ ## When each is allowed
23
+
24
+ | Escape hatch | Allowed for | Not for |
25
+ |---|---|---|
26
+ | `unsafe(() => ...)`, `unsafeAsync(...)` | a call into code that throws or rejects and has no safe version (std, a feature pack): a built-in, a library, legacy code | your own functions (make them return a `Result`); a call std or a pack has a safe version of (`toBase64`, the browser pack's `fetch`, `getItem`, IndexedDB, the Node pack's `parseArgs`) |
27
+ | `unsafeAsync(fn, Panic)` | a call that returns an `Err` and may also throw by mistake | turning bugs into user-visible failures |
28
+ | `panic(message)` | an invariant nothing can handle: a table built at load time with a duplicate name | data from a request, a store not loaded yet, a missing element |
29
+ | `defineSanitizer(fn)` | the one sanitizer the project vouches for, in one module, configured and reviewed | a function that doesn't sanitize; one per component |
30
+ | `trust<T>(value)` | a value no check fits that another part of the same program made (a worker of the same build), listed in the architecture document's boundaries | data from the network, storage, a file, a message from another origin: `validate<T>` |
31
+ | `LegacyNull` | strict code whose legacy callers still pass `null`, until they are migrated | a `null` that means something on the wire (`JsonNull`); the end state |
32
+ | `// safe-ts-ignore <rule>: <reason>` | one line in a migrated file that is right as it is, or that the rule gets wrong (a package's type that tells `null` from `undefined`) | a file that isn't migrated yet (the legacy marker); a finding the code should fix |
33
+ | `// safe-ts-ignore-file <rule>: <reason>` | a generated file the project can't change | hand-written code |
34
+ | `"off"` / `"warn"` in package.json `"rules"` / `"overrides"` | a directory whose code the rule doesn't fit (generated types), decided in the architecture document | silencing an area's findings to pass a gate: the census baseline ratchets them instead. `check` names each one, and its `--baseline` fails on a new one |
35
+ | `// @ts-expect-error <reason>` | one line TypeScript can't type yet (a package's wrong declaration), with the reason; a compile-time test's "this must not compile" | data from outside (`validate<T>`); `@ts-ignore` and `@ts-nocheck`, which `no-ts-suppression` reports, like a `@ts-expect-error` without a reason |
36
+ | `void f()` | a `Result` or promise whose failure really doesn't matter (best-effort telemetry) | anything the user started, or any write |
37
+ | `// @safe-ts legacy` | a file that waits its turn in the burn-down, listed under `"legacyFiles"` in package.json (`unlisted-marker` reports the marker anywhere else, and the file is checked) | the end state; a file that "doesn't fit"; a marker without the list entry |
38
+ | `// @safe-ts std` | low-level helpers like the std library itself, reviewed line by line, listed under `"trustedFiles"` | application code |
39
+ | `// eslint-disable-next-line <rule> -- <reason>` | another linter's rule that is wrong on this line, named | a blanket `eslint-disable` / `oxlint-disable`, or one naming a `safe-ts/` rule: `no-lint-suppression` reports them; write `// safe-ts-ignore <rule>: <reason>` |
40
+ | `declare const X: unknown` (validated where read), `declare module "*.svg" { ... }`, a global the project sets typed `Option<T>`, optional members added to a library's interface | a constant a bundler injects, an asset module, an expando field the project writes itself | `declare const X: Config`, `declare function`, `declare module "pkg" { export function ... }`, a `declare module "virtual:x"` with a typed value (export it `unknown` and `trust<T>` it once in a wrapper module), a required member added to `Window`, a class field `declare x: T`: `no-unchecked-declare` reports them, a cast with no `as` |
41
+ | `/** @cache */` | a memo that can be thrown away and computed again | state |
42
+ | `safeTs({ exclude })` | vendored or generated code the build should leave alone entirely | the project's own code waiting its turn (it loses its prelude imports): the legacy marker |
43
+ | `as T`, `x!` | nowhere on outside data. `x[i]!` under a bound the checker accepts; `as const` | data from a request, storage, a message, the DOM; a brand (`as Html`, `as SafeUrl` are `brand-constructor` errors) |
44
+ | An overload over a loose implementation, a `value is T` guard, `asserts value is T` | nowhere: `no-overload` and `no-type-predicate` report them. A guard whose body is one test drops its annotation (TypeScript infers it); overloads that only narrow the implementation (same result, each parameter a member of its union) and `asserts ok` with exactly `if (!ok) throw` are allowed. A claim no check can make is `trust<T>(value)` | a way around `validate<T>` |
45
+ | A catch-all `catch` | a harness boundary that runs independent units of work and reports each failure | anywhere below it |
46
+
47
+ ## The reason
48
+
49
+ Every `unsafe`, `unsafeAsync`, `panic`, `trust`, `LegacyNull`, `void`, `@cache` and cast carries
50
+ a comment on its line or the line above that says why it is safe here, in terms a reviewer can
51
+ check:
52
+
53
+ ```ts
54
+ // The pattern comes from the admin's saved search: a bad one is shown as "invalid filter".
55
+ const filter = unsafe(() => new RegExp(saved.pattern));
56
+ ```
57
+
58
+ A `safe-ts-ignore` has its reason built in, after the colon, and the checker enforces it: the
59
+ `safe-ts-ignore` rule (an error in the preset) reports one without a rule or a reason, with a
60
+ rule that doesn't exist, or one that silences nothing (the finding was fixed or moved). In a
61
+ Vue template it is an HTML comment before the element:
62
+ `<!-- safe-ts-ignore vue-unsafe-url: the server checks every link it sends -->`.
63
+
64
+ The census's `unexplained-unsafe` pattern counts the `unsafe` calls without a comment; the
65
+ baseline gate keeps it from growing.
66
+
67
+ ## The budget
68
+
69
+ The architecture document sets, per area: the legacy files allowed at each milestone (zero at the
70
+ end), the `LegacyNull` uses allowed (zero once the area's callers are migrated), and the number
71
+ of each other hatch the area may keep. The hand-off report of each area gives the counts before
72
+ and after, from the census, and lists each hatch that remains with its reason.
@@ -0,0 +1,46 @@
1
+ # The final pass: use every feature
2
+
3
+ When the gates pass and the markers are gone, run the census again and read its last two
4
+ sections: the patterns that remain, and how often each SAFE-TS feature is used. A migration that
5
+ aimed at "the checker passes" ends with converted code: no `null`, no `throw`, `Result`s at the
6
+ boundaries, and the old state machines still hand-written around them. This pass looks for the
7
+ places where a feature would replace hand-rolled code, area by area.
8
+
9
+ ```sh
10
+ node scripts/census.mjs --show trio-files
11
+ node scripts/census.mjs --show loading-flag
12
+ node scripts/census.mjs --show string-if-chain
13
+ ```
14
+
15
+ | Look for | Census (pattern or rule) | Replace with |
16
+ |---|---|---|
17
+ | loading / error / data state, a lone busy flag, an error string | `trio-files`, `loading-flag`, `error-state`, `error-or-undefined`, `vue-split-state` | `useTask` + `<Match :value>` (or `match` in a `computed`) |
18
+ | hand-written `AsyncState` assignments, latest-wins counters, tasks that ignore their signal | `latest-wins-counter`, `unused-task-signal`, a search for `AsyncState.` outside `useTask` | `useTask`, in the component or the setup store; std's `latest` outside Vue and React |
19
+ | an answer or error the user dismisses by hand | a search for `dismissed`, `clearError` | `useTask`'s `reset()` |
20
+ | a blank `Idle` after a bug | `<Match>` without `#Idle` / `#_` | a slot that reads the task's `panic` |
21
+ | string unions in if-chains, boolean sets, unions told apart by keys | `string-if-chain`, `exhaustive-dispatch`, `string-dispatch`, `boolean-flag-files`, `key-presence-union` | `Enum` + `constructors` + `match`; a string parsed once into a union |
22
+ | raw tag reads | `prefer-is-over-tag` | `is`, `variant`, `match`, `<Match>` |
23
+ | variants named by strings where the enum has constructors | `prefer-constructor-tag` | `is(x, Status.Published)` |
24
+ | `if (isErr(x)) return x`, hand re-wraps of an error | `prefer-q`, `prefer-map-err` | `q(x)`, `q(x, map)`, `mapErr` |
25
+ | `.catch` or `try` around calls that return a `Result` | `catch-on-result`, `promise-catch`, `try-catch` | the `Result` checked |
26
+ | `''`, `-1`, `0` sentinels | `empty-string-sentinel`, `minus-one-sentinel`, `zero-sentinel`, `sentinel-error` | `Option<T>`, `indexIn`, an `Enum` variant |
27
+ | `unwrapOr(x, undefined)` and helpers around it | `no-swallowed-error` | the `Result`; `Result<Option<T>, E>` |
28
+ | `JsonNull` as app state, every `undefined` written as `null` | `json-null-in-app`, `undefined-to-null` | `Option`, an `Enum`, `AsyncState<Option<T>, E>`; `jsonNull` only where a body needs it |
29
+ | `JSON.parse`, direct storage, casts, guards and overloads on outside data | `json-parse`, `raw-storage`, `as-cast`, `no-type-predicate`, `no-overload` | `parseJson<T>`, `validate<T>`, the browser pack |
30
+ | `btoa` / `atob` of text | `unhandled-failure` | `toBase64`, `fromBase64` |
31
+ | `ref<HTMLElement \| null>(null)` | (checker: `no-null`) | `useElement` / `useOptionalElement` / `useElements` |
32
+ | `addEventListener` / `setInterval` in components | (checker: `listener-cleanup`) | `useListener`, `useInterval` (Vue); `listen` elsewhere |
33
+ | tables indexed by wire data | `no-object-dictionary`, a search for `[` on `Record` constants | `getOwn(table, key, fallback)`; for a server field from a list, `Open<K>` + `lookup` |
34
+ | `null` in request bodies, `undefined` turned into `null` on the way out | `json-null-in-app`, `undefined-to-null`, a search for `jsonNull` | `Patch<T>` with `keep` / `clear` |
35
+ | markup and URLs passed around as `string` | `vue-v-html`, `vue-unsafe-url`, `Html/SafeUrl` in the features | `defineSanitizer`, props typed `Html` / `SafeUrl` |
36
+ | numbers and strings tested for truth | `strict-truthiness`, `compare-misses-undefined` | `> 0`, `!== ""` on a value that can't be `undefined`; on one that can (`x?: string`, `Option<string>`, `a?.b`, `map.get(k)`) both halves, `x !== undefined && x !== ""`, or `x !== undefined` alone; never a lone `x !== ""` |
37
+ | codes numbered by hand, lists kept sorted by a comment | `duplicate-code-value`, `list-invariant` | codes derived from an append-only list of names (the `codesOf` pattern of the JSON guide); `/** @sorted */`, `/** @unique */` |
38
+ | casts in tests | `no-unchecked-cast` in test files (`cast-in-test` where that is off for tests) | `fixture`, `testDouble`, `unchecked`, `expectPresent` |
39
+ | bridges left from the migration | `legacy-null`, `trust`, `safe-ts-ignore` | gone, or each one in the exception list with its reason |
40
+
41
+ For each area, the hand-off report of this pass gives the feature counts before and after, and
42
+ for each remaining hand-rolled pattern either the change or the reason it stays (a line in the
43
+ architecture document's exception list).
44
+
45
+ The pass is done when every remaining pattern is an exception someone decided, not one nobody
46
+ looked at.
@@ -0,0 +1,87 @@
1
+ # Fix the design, not the finding
2
+
3
+ A finding is a symptom. It points at one line, but the bug it stands for is a property of the
4
+ design: a type that lets a bad value exist, a set of cases that lives only in `if` chains, state
5
+ that two places own. Patching the line clears the finding and keeps the design that produced
6
+ it, so the same bug comes back at the next line someone writes, where no rule looks.
7
+
8
+ Rust works the same way. A borrow-checker error is rarely fixed by moving a variable or adding a
9
+ `clone()` until it compiles. The fix is a different ownership: who holds the data, who may change
10
+ it, how long it lives. Migrate to SAFE-TS the same way. For each group of findings, ask which
11
+ design would make that class of bug impossible to write, change the design, and let the
12
+ compiler list the places that have to follow.
13
+
14
+ ## The procedure
15
+
16
+ 1. **Group before you edit.** Take the census for the area (`--show <rule>`) and group the
17
+ findings by cause, not by file. Twenty `unhandled-failure` findings behind one throwing helper
18
+ are one cause. So are fourteen `strict-truthiness` findings on ids that may be `''`. A
19
+ `string-if-chain` in five files on the same field is one closed set without a type.
20
+ 2. **Name the class of bug.** Write one sentence about what can go wrong at runtime, not which
21
+ rule fired: "a phase added later is silently treated as idle", "an empty id passes as a
22
+ real one", "a failure is shown as an empty list".
23
+ 3. **Find the representation that rules it out.** Usually it is one of:
24
+ - a type that can't hold the bad value: `Option<T>` instead of a `''` or `-1` sentinel, an
25
+ `Enum` instead of three booleans, a brand that only its constructor makes;
26
+ - a closed set with one definition, handled by `match` or a `Record<Key, …>` table, so a new
27
+ member fails to compile everywhere it is handled;
28
+ - a boundary that parses once: outside data becomes a typed value in one place
29
+ (`validate<T>`, a `parseX(raw): Option<X>`), and the code behind it never re-checks the
30
+ raw form;
31
+ - one owner for each piece of state (a store, a context made at startup), and data passed
32
+ to the code that needs it, not read from wherever it happens to be;
33
+ - a failure in the return type (`Result`) at its origin, not handled at each caller.
34
+ 4. **Change the representation first, then follow the compiler.** Change the type, the
35
+ definition of the set, or the owner, and let `tsc` and `safe-ts check` list the call sites.
36
+ Fix each one with the new design. A long error list at this step is the design change
37
+ working: each entry is a place that depended on the bad representation.
38
+ 5. **Record the cause, not the lines.** The hand-off report lists each cause removed, the design
39
+ that replaced it, and the findings it cleared ([templates.md](templates.md#hand-off-report-per-area)).
40
+
41
+ ## Patch or design?
42
+
43
+ A change is a patch, not a design fix, when it:
44
+
45
+ - adds a guard, a `??` default, a `!` or an early return at the line the finding names, while
46
+ the type still lets the bad value reach the next caller;
47
+ - adds the missing branch to one `if` chain while other chains on the same value stay as they
48
+ are;
49
+ - adds `!== ''` or `!== 0` next to a value that can also be `undefined`, or tests one half of
50
+ an `Option`;
51
+ - copies a check into a second place instead of moving it to where the value is made;
52
+ - wraps the failing call in `unsafe` at every caller instead of returning a `Result` from the
53
+ function that fails;
54
+ - moves code, splits a function, or renames something until the checker stops following it;
55
+ - adds a comment explaining why this case can't happen, where a type could say it;
56
+ - adds a cast, `trust`, `void`, `safe-ts-ignore` or a rule level (these also need the exception
57
+ list: [escape-hatches.md](escape-hatches.md)).
58
+
59
+ A local fix is right when the cause really is local: one function's own logic, a value parsed
60
+ once at its boundary, a message to reword. Say so in the hand-off report. "It was the fastest"
61
+ is not a reason.
62
+
63
+ ## Examples
64
+
65
+ | Finding or bug | The patch | The design fix |
66
+ |---|---|---|
67
+ | A phase added to a code table (`codesOf([...])`) is missing from two `if`/`else if` chains and falls to `: 0` | add the branch to the two chains | `match` on an `Enum`, or a `Record<PhaseName, …>` table, so the next phase fails to compile in every place that handles phases |
68
+ | `strict-truthiness` on `unitId` (`string \| undefined`) | `unitId !== ''` (forgets `undefined`) | decide what absence is: `Option<UnitId>` with a brand whose constructor refuses `''`, then test `!== undefined` only |
69
+ | `unhandled-failure` at 20 callers of a helper that throws | `unsafe(...)` at each caller | the helper returns a `Result`; callers pass it on with `q` |
70
+ | `string-if-chain`: a command word compared with `'open'`, `'urls'`, `'help'`, `'?'` | a `switch` | a `parseCommand(word): Option<Command>` table at the boundary (aliases included) and `match` on `Command`; help text made from the same table |
71
+ | `loading` and `error` refs beside the data | rename them, add a reset | `useTask`, shown with `<Match>` |
72
+ | an admin "reset" built on the loader that fails for broken records | catch the load failure in reset | the repair path takes the stored row, not the loaded aggregate: what must work on broken data doesn't depend on the code that refuses it |
73
+ | a rectangle in world coordinates passed where local ones are expected | subtract the offset at the call site | a `LocalRect` brand made only by `toLocal(rect, origin)`, so the wrong frame doesn't compile |
74
+ | `no-mutable-global` on a cache several modules write | turn the `let` into a `const` object and mutate its fields | one owner: a store or a context made at startup, passed to the code that uses it |
75
+
76
+ The first row is a real bug that reached production after a checker-clean migration: the code
77
+ had no finding, because the chains compared numeric codes, which no rule checks. Look for the
78
+ design problem even where the checker is silent. The census's patterns
79
+ ([census.md](census.md#the-patterns)) are where to start.
80
+
81
+ ## In the architecture document
82
+
83
+ Each section of the architecture document ([architecture.md](architecture.md)) is a design
84
+ decision of this kind, made once for the whole project: what absence is, where failures are
85
+ returned, who owns state, where outside data is parsed, how closed sets are defined. When a
86
+ group of findings doesn't fit any of them, the document is missing a decision. Add it there and
87
+ get it approved, instead of deciding it again in each area.