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

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.
package/LICENSE-APACHE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/LICENSE-MIT ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Evobug
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,16 @@
1
- # Temporary Holding Version
1
+ # @evobug_com/safe-ts-skill
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ An agent skill (Claude Code / Agent Skills format) for migrating an existing project to SAFE-TS: the target architecture first, a census script, a pattern catalogue with before and after, gates, behaviour checks and a review checklist. `npx @evobug_com/safe-ts-skill` copies it into .claude/skills/.
4
+
5
+ **Documentation: [safe-ts.evobug-pages.com/guide/migration-skill](https://safe-ts.evobug-pages.com/guide/migration-skill)**
6
+
7
+ ```sh
8
+ npx @evobug_com/safe-ts-skill
9
+ ```
10
+
11
+ Part of [SAFE-TS](https://safe-ts.evobug-pages.com/), a strict, Rust-flavoured subset of TypeScript. The website has the
12
+ guides, a page per rule, and a playground that runs the checker in your browser.
13
+
14
+ Changes in each version: [CHANGELOG.md](https://git.evobug.com/Evobug/Safe-Ts/src/branch/main/CHANGELOG.md).
15
+
16
+ Source: https://git.evobug.com/Evobug/Safe-Ts. Licensed under MIT OR Apache-2.0.
package/install.mjs ADDED
@@ -0,0 +1,62 @@
1
+ #!/usr/bin/env node
2
+ // Copies the safe-ts-migrate agent skill into a project:
3
+ //
4
+ // npx @evobug_com/safe-ts-skill -> ./.claude/skills/safe-ts-migrate
5
+ // npx @evobug_com/safe-ts-skill --to <skills dir> -> <skills dir>/safe-ts-migrate
6
+ // npx @evobug_com/safe-ts-skill --force replace a copy that differs
7
+ //
8
+ // Use the version that matches the project's other @evobug_com packages
9
+ // (`npx @evobug_com/safe-ts-skill@0.4.0`): the skill describes that version's APIs.
10
+ import { cpSync, existsSync, readdirSync, readFileSync, rmSync, statSync } from "node:fs";
11
+ import { dirname, join, relative, resolve } from "node:path";
12
+ import { fileURLToPath } from "node:url";
13
+
14
+ const here = dirname(fileURLToPath(import.meta.url));
15
+ // Published: next to this file. In the SAFE-TS repository: skills/ at the root.
16
+ const source = [join(here, "safe-ts-migrate"), join(here, "..", "..", "skills", "safe-ts-migrate")].find((dir) =>
17
+ existsSync(join(dir, "SKILL.md")),
18
+ );
19
+
20
+ const args = process.argv.slice(2);
21
+ if (args.includes("--help") || args.includes("-h")) {
22
+ console.log("usage: safe-ts-skill [--to <skills dir>] [--force]\n copies the safe-ts-migrate skill to <skills dir>/safe-ts-migrate (default: .claude/skills)");
23
+ process.exit(0);
24
+ }
25
+ const toIndex = args.indexOf("--to");
26
+ const skills = resolve(toIndex === -1 ? ".claude/skills" : (args[toIndex + 1] ?? ".claude/skills"));
27
+ const target = join(skills, "safe-ts-migrate");
28
+ const shown = relative(process.cwd(), target) || ".";
29
+
30
+ if (source === undefined) {
31
+ console.error("safe-ts-skill: the skill's files are missing from this package");
32
+ process.exit(2);
33
+ }
34
+
35
+ /** Every file under `dir`, relative to it. */
36
+ function files(dir) {
37
+ return readdirSync(dir, { recursive: true })
38
+ .map(String)
39
+ .filter((f) => statSync(join(dir, f)).isFile())
40
+ .sort();
41
+ }
42
+
43
+ const same = (a, b) => {
44
+ const left = files(a);
45
+ const right = files(b);
46
+ return left.length === right.length && left.every((f, i) => f === right[i] && readFileSync(join(a, f)).equals(readFileSync(join(b, f))));
47
+ };
48
+
49
+ if (existsSync(target)) {
50
+ if (same(source, target)) {
51
+ console.log(`safe-ts-skill: ${shown} is already this version`);
52
+ process.exit(0);
53
+ }
54
+ if (!args.includes("--force")) {
55
+ console.error(`safe-ts-skill: ${shown} exists and differs (another version, or edited). --force replaces it; edits there are lost.`);
56
+ process.exit(1);
57
+ }
58
+ rmSync(target, { recursive: true, force: true });
59
+ }
60
+ cpSync(source, target, { recursive: true });
61
+ console.log(`safe-ts-skill: installed ${shown}`);
62
+ console.log("Ask your agent to migrate the project to SAFE-TS; it reads SKILL.md first.");
package/package.json CHANGED
@@ -1,6 +1,37 @@
1
1
  {
2
2
  "name": "@evobug_com/safe-ts-skill",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.4.0",
4
+ "description": "An agent skill (Claude Code / Agent Skills format) for migrating an existing project to SAFE-TS: the target architecture first, a census script, a pattern catalogue with before and after, gates, behaviour checks and a review checklist. `npx @evobug_com/safe-ts-skill` copies it into .claude/skills/.",
5
+ "keywords": [
6
+ "safe-ts",
7
+ "typescript",
8
+ "migration",
9
+ "agent-skill",
10
+ "claude-code",
11
+ "codemod"
12
+ ],
13
+ "license": "MIT OR Apache-2.0",
14
+ "homepage": "https://safe-ts.evobug-pages.com/guide/migration-skill",
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "git+https://git.evobug.com/Evobug/Safe-Ts.git",
18
+ "directory": "skills/safe-ts-migrate"
19
+ },
20
+ "bugs": "https://git.evobug.com/Evobug/Safe-Ts/issues",
21
+ "type": "module",
22
+ "bin": {
23
+ "safe-ts-skill": "install.mjs"
24
+ },
25
+ "files": [
26
+ "install.mjs",
27
+ "safe-ts-migrate",
28
+ "LICENSE-MIT",
29
+ "LICENSE-APACHE"
30
+ ],
31
+ "publishConfig": {
32
+ "access": "public"
33
+ },
34
+ "engines": {
35
+ "node": ">=22.18.0"
36
+ }
37
+ }
@@ -0,0 +1,111 @@
1
+ ---
2
+ name: safe-ts-migrate
3
+ description: Migrate an existing TypeScript, Vue or React project to SAFE-TS (the @evobug_com/safe-ts-* packages) toward its target architecture, not only a passing checker. Use when asked to adopt SAFE-TS in a code base, plan or run a SAFE-TS migration, convert an area or remove `// @safe-ts legacy` markers, take a census of what is left, or review a SAFE-TS migration change.
4
+ ---
5
+
6
+ # Migrating a project to SAFE-TS
7
+
8
+ Written for SAFE-TS 0.4.0. Check the installed version (`npx safe-ts --version`); if it is
9
+ newer, read its CHANGELOG entries first and prefer what they say over
10
+ [references/tool-gaps.md](references/tool-gaps.md).
11
+
12
+ **The goal is the target architecture, and the checker is one gate among several.** Without the
13
+ idiomatic layer, `safe-ts check` accepts a `.tag === 'Ready'` chain, an `if (isErr(x)) return
14
+ x`, an `unwrapOr(x, undefined)` and a guard that tests one field of twenty; with it, they are
15
+ warnings, and a run with only warnings still exits 0. Even then it accepts a boolean flag set
16
+ beside an `Enum`, a `''` that means "none" and a string if-chain. A migration that aims at "no
17
+ findings" converts `null` and `throw` and stops there. This skill aims at the architecture
18
+ SAFE-TS is built for: `Result` for failures, `Option` for absence, `useTask` and `AsyncState` for
19
+ async work, `Enum` and `match` for closed sets, validated boundaries, no module state.
20
+
21
+ ## Rules for the whole migration
22
+
23
+ - **Only real APIs.** Every function, rule, option and command you write must exist in the
24
+ installed packages (read the `.d.ts` files in `node_modules/@evobug_com/`) or the guide
25
+ (https://safe-ts.evobug-pages.com). Don't invent wrappers around std; the architecture
26
+ document lists the project's sanctioned helpers.
27
+ - **Behaviour stays the same**, unless the architecture document says otherwise: same request
28
+ bodies, same messages in the same places. Static gates don't prove it
29
+ ([references/behaviour.md](references/behaviour.md)).
30
+ - **A gate is never fixed by weakening it**: no new legacy marker, `safe-ts-ignore` comment,
31
+ rule set to `"off"` or `"warn"`, cast, `trust`, `void` or baseline rewrite without a line in
32
+ the architecture document's exception list.
33
+ - **"The checker passes" means `safe-ts check <entries> --deny-warnings` exits 0**, with
34
+ `"idiomatic": true` in package.json. Warnings alone exit 0, and the idiomatic rules are
35
+ warnings: never read a plain `check` run's exit code as done. Run it this way in your own loop,
36
+ not only in CI.
37
+ - **The CLI is the `safe-ts` command** (`npx safe-ts check src/main.ts`, `npx safe-ts migrate
38
+ throw-to-result src/`, `safe-ts ...` in package.json scripts). It comes with the transform and
39
+ the oxlint plugin; with pnpm, add `@evobug_com/safe-ts-native` as a dev dependency.
40
+ `scripts/safe-ts.mjs` finds the binary without a bin link (the census uses it).
41
+ - **Ask the user once, at the architecture document.** It holds the decisions only the project
42
+ can make. After it is approved, work through the steps without asking again unless a decision
43
+ in it turns out wrong.
44
+
45
+ ## Workflow
46
+
47
+ 1. **Read the project.** Package manager, framework, build, test runner, tsconfig (and its
48
+ `paths` aliases), the HTTP layer, the state library, the processes that run TypeScript
49
+ directly. Note what [references/tool-gaps.md](references/tool-gaps.md) says about each.
50
+ 2. **Take the census** before anything is marked legacy:
51
+ `node <this skill>/scripts/census.mjs > census-before.txt`
52
+ ([references/census.md](references/census.md)). It counts the checker's findings per rule
53
+ and directory, the root causes, the patterns the checker doesn't report, the escape hatches,
54
+ and how much of SAFE-TS the code already uses.
55
+ 3. **Write the target architecture document** from
56
+ [references/architecture.md](references/architecture.md), with the census as its evidence:
57
+ absence policy, errors and requests, state, async work, closed sets, boundaries, tooling,
58
+ escape-hatch budget, sanctioned helpers, exceptions, areas and order. Get it approved.
59
+ 4. **Set up** ([references/templates.md](references/templates.md)): packages, tsconfig flags
60
+ (`strict`, `noUncheckedIndexedAccess`, `exactOptionalPropertyTypes`), the oxlint preset,
61
+ the Vite plugin (or the Bun plugin), the loader for Node, `"idiomatic": true`, the feature
62
+ packs, `"requestFunctions"` for the project's request wrapper, the scripts, the CI job, the
63
+ conventions section in `CLAUDE.md` / `AGENTS.md`. Mark the files that don't pass yet with
64
+ `// @safe-ts legacy`, then write the census baseline (`--write-baseline safe-ts-census.json`):
65
+ from here the counts may only fall.
66
+ 5. **Migrate in order** ([references/order-and-gates.md](references/order-and-gates.md)): the
67
+ shared foundation (transport, requests, error types, stores), then utilities and the component
68
+ library, then the feature areas in parallel by dependency, then the removal of bridges and the
69
+ last markers. For each change:
70
+ - rewrite with the catalogue: [references/patterns-core.md](references/patterns-core.md),
71
+ [references/patterns-vue.md](references/patterns-vue.md),
72
+ [references/patterns-react.md](references/patterns-react.md). For the repetitive part,
73
+ `safe-ts migrate <codemod> src/` (prints a diff; `--write` applies it): it rewrites `.ts`
74
+ files and Vue components together, so give it the whole source folder;
75
+ - pass every gate in [references/order-and-gates.md](references/order-and-gates.md#gates-per-step);
76
+ - run the behaviour checks for the area ([references/behaviour.md](references/behaviour.md));
77
+ - list every exported signature that changed, and read every caller of each, in every area;
78
+ - write the hand-off report ([references/templates.md](references/templates.md#hand-off-report-per-area)).
79
+ 6. **Final pass**: [references/final-pass.md](references/final-pass.md). Run the census and
80
+ replace the hand-rolled state, sentinels and if-chains that remain with `useTask`,
81
+ `AsyncState`, `Enum`, `match`, `Option` and `q`, or record why each one stays.
82
+ 7. **Review and hand off** with [references/review-checklist.md](references/review-checklist.md)
83
+ and the escape-hatch counts ([references/escape-hatches.md](references/escape-hatches.md)):
84
+ census before and after, what remains, and why.
85
+
86
+ ## When several agents migrate at once
87
+
88
+ Give each builder this skill, the approved architecture document, and the foundation's exported
89
+ signatures. Builders don't edit the foundation. The integrator merges the areas, runs every gate
90
+ on the whole tree, searches every caller of every signature an area changed (the checker follows
91
+ a `Result` through store members and factories, not through parameters, class fields or a
92
+ `Map`, and a caller's leftover `try` still compiles), and runs the browser smoke on every page.
93
+
94
+ ## References
95
+
96
+ | File | Holds |
97
+ |---|---|
98
+ | [architecture.md](references/architecture.md) | the target architecture document, section by section, with SAFE-TS's defaults |
99
+ | [census.md](references/census.md) | running and reading `scripts/census.mjs`; the pattern table; the baseline gate |
100
+ | [patterns-core.md](references/patterns-core.md) | before and after for TypeScript idioms: throws, requests, sentinels, enums, casts, JSON, null on the wire, optional keys, `Patch`, `Open`, base64 and `Ascii`, `trust`, `LegacyNull`, `parseArgs`, IndexedDB |
101
+ | [patterns-vue.md](references/patterns-vue.md) | Vue: the loading trio, `useTask`, `<Match>`, `useElement`, stores, props, `v-html` and `Html`, URLs and `SafeUrl` |
102
+ | [patterns-react.md](references/patterns-react.md) | React: the loading trio, `useTask`, module state, props, handlers, HTML |
103
+ | [order-and-gates.md](references/order-and-gates.md) | the order of work, legacy markers as scaffolding, parallel builders, the gates |
104
+ | [behaviour.md](references/behaviour.md) | contract checks, network bodies, browser smoke, regressions a real migration produced |
105
+ | [tool-gaps.md](references/tool-gaps.md) | the tools' known limits in this version, and their workarounds |
106
+ | [escape-hatches.md](references/escape-hatches.md) | when each hatch is allowed (`unsafe`, `trust`, `LegacyNull`, `safe-ts-ignore`, legacy markers, ...), the reason, the budget |
107
+ | [review-checklist.md](references/review-checklist.md) | for reviewers: correctness and architecture |
108
+ | [templates.md](references/templates.md) | tsconfig, package.json, oxlint, Vite, CI, the conventions section, the hand-off report |
109
+ | [final-pass.md](references/final-pass.md) | the "use every feature" pass |
110
+ | `scripts/census.mjs` | the census and the architecture gate |
111
+ | `scripts/safe-ts.mjs` | finds and runs the `safe-ts` binary in `node_modules` (used by the census) |
@@ -0,0 +1,139 @@
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
+ - Sets of booleans of which at most one is true are one `Enum`. Unions told apart by key
78
+ presence (`'k' in o`) get a tag.
79
+ - A string the server fills from a list it may extend (a status, a type) is an `Open<K>`, read
80
+ with `match` (an `Unknown` handler) and `lookup(table, value, fallback)`. List those fields.
81
+
82
+ ## 6. Boundaries
83
+
84
+ - Every value from outside (responses, storage, `postMessage`, URL and query parameters,
85
+ `history.state`, server-rendered data in the page) is read with `validate<T>` /
86
+ `parseJson<T>` or a pack's safe version.
87
+ - No `as` on such values, and no hand-written `value is T` guard that tests less than `T`
88
+ promises (`partial-type-guard`). A trusted boundary that can't be validated (a worker's message
89
+ of the same build, a type `validate` refuses) is a `trust<T>(value)` call, listed here by name
90
+ with the reason.
91
+ - Types that `validate<T>` reads are declared in the project: project files, namespaces of
92
+ generated model layers (`Backend.Models.User`), workspace packages, imported relatively or
93
+ through tsconfig `paths`. Not a package's types: where the wire type comes from a package,
94
+ decide where the project's copy lives.
95
+ - Element refs (Vue) go through `useElement` / `useOptionalElement` / `useElements`; DOM lookups
96
+ outside Vue through the browser pack's `querySelector(root, selector, Class)`.
97
+ - Bound URLs go through `safeHref` (list here the extra schemes the app needs, passed as
98
+ `{ schemes }`), and props that take a URL are typed `SafeUrl`. HTML goes through the one
99
+ sanitizer declared with `defineSanitizer` (name its module here), and props that take markup
100
+ are typed `Html`. Brands are made only by their constructors (`brand-constructor`).
101
+
102
+ ## 7. Tooling
103
+
104
+ - `tsconfig.json`: `strict`, `noUncheckedIndexedAccess` and `exactOptionalPropertyTypes` on from
105
+ the first step, in the tsconfig every tool reads (tsc, vue-tsc, type-aware oxlint).
106
+ - `"safe-ts": { "idiomatic": true }` in package.json from the first step, the feature packs the
107
+ code needs (`"features": [...]`), and the project's request wrappers (`"requestFunctions"`).
108
+ - `safe-ts check` runs with `--deny-warnings` wherever a gate reads its exit code, CI and the
109
+ builders' own loop alike. Rule levels changed in package.json (`"rules"`, `"overrides"`) are
110
+ exceptions (section 10), each with its reason.
111
+ - The gates, and where they run (local script, CI): [order-and-gates.md](order-and-gates.md).
112
+ - Runtime: which processes run TypeScript directly (Node scripts, tests, workers, Bun) and how
113
+ they get the transform (`--import @evobug_com/safe-ts-transform/register`, the Bun preload
114
+ `@evobug_com/safe-ts-transform/bun`, or `safe-ts emit`).
115
+ - The build's `exclude` list (vendored and generated code only), and what it leaves out.
116
+
117
+ ## 8. Escape hatches
118
+
119
+ Policy and budget: [escape-hatches.md](escape-hatches.md). Copy the table, fill in the budget per
120
+ area: legacy files, `unsafe`, `panic`, `trust`, `LegacyNull`, `safe-ts-ignore` comments, casts.
121
+
122
+ ## 9. Sanctioned helpers
123
+
124
+ The project's own helpers around SAFE-TS (a request wrapper, a test factory), each with one line
125
+ on what it does and why std doesn't cover it. Check std first: `getOwn(table, key, fallback)`,
126
+ `toBase64`, `describeError`, `omit`, `trust` and `LegacyNull` exist. A builder who
127
+ wants a new one adds it here first. A helper that hides a pattern this document rules out (an
128
+ `orNone` that wraps `unwrapOr(x, undefined)`, a `must()` that turns any failure into one error)
129
+ doesn't go in.
130
+
131
+ ## 10. Exceptions
132
+
133
+ Each deliberate deviation: what, where, why, until when. The census baseline is reviewed against
134
+ this list.
135
+
136
+ ## 11. Order of work and areas
137
+
138
+ The areas (directories or modules), who migrates each, what each depends on, and the order
139
+ ([order-and-gates.md](order-and-gates.md)). The census per directory is the starting count.