# Stack A fast, small, proven core. The shipped code is TypeScript compiled to plain ESM; the verification around it (tests, spaces, fuzzers, mutation) can be as heavy as it needs to be, because none of it ships. | | Version | Role | |---|---|---| | TypeScript | 7.0.2 (native compiler, `tsc`) | types, `.d.ts`, emit to `dist/` | | oxlint + oxlint-tsgolint | 1.90.0 + 7.0.2005 | lint, type-aware rules (tsgolint runs TypeScript 7) | | vitest | 5.0.5 | test runner | | Stryker + vitest runner | 10.1.1 | mutation testing of `src/**/*.{js,ts}` | | esbuild | 0.28.2 | bundle budgets (test/bundle.test.js), the workerd test worker (test/workerd/build.mjs) | Runtime dependencies: none, ever. Node ≥ 22.18 runs `src/*.ts` directly (type stripping) for tests and fuzzers; consumers get `dist/` (plain `.js` + `.d.ts`), so `engines.node` stays `>=20`. ## Compiler settings and why `tsconfig.json` (build) is `strict` plus `noUncheckedIndexedAccess`, `exactOptionalPropertyTypes`, `noImplicitReturns`, `noImplicitOverride`, `noFallthroughCasesInSwitch`, `noPropertyAccessFromIndexSignature`, `useUnknownInCatchVariables`, `verbatimModuleSyntax`, target ES2022, `module`/`moduleResolution` `nodenext`. - `erasableSyntaxOnly`: no enums, namespaces, parameter properties or other syntax with runtime meaning. The emitted JS is the source with the types removed: zero size or speed cost, and Node can run the source as is. - **Import specifiers stay `.js`** (`import { fail } from './errors.js'` even though the file is `errors.ts`): the `nodenext` convention. `tsc` maps `./x.js` to `x.ts` and emits it unchanged into `dist/`; vitest (Vite) resolves a `.js` specifier to the `.ts` file from both `.js` and `.ts` importers; plain Node gets the same mapping from `test/ts-resolve.mjs` (a `module.registerHooks` resolve hook: a relative `./x.js` that does not exist resolves to `./x.ts`, then Node ≥ 22.18 strips the types). Run fuzzers and scripts that load `src/` as `node --import ./test/ts-resolve.mjs …`; vitest's config puts it in `NODE_OPTIONS` so every child process and worker a test starts has it; CI sets `NODE_OPTIONS` for whole jobs. Consequence: converting a module renames one file and edits no importer. (Verified on this branch: `errors`, `limits`, `errors-doc` are `.ts`, imported as `.js` from 40 JS modules, `tsc`, vitest and `node --import ./test/ts-resolve.mjs` all resolve them.) - `isolatedDeclarations`: every export has an explicit type, so declarations never depend on inference across files. TypeScript refuses it together with `allowJs` (TS5053), and TS 7.0.2 panics in declaration emit when both are set, so it runs as its own check: `tsconfig.isolated.json` (only `src/**/*.ts`, `allowJs` off). While unconverted `.js` remains, that one check has `noImplicitAny` off so an import of a `.js` file is not an error there; the main check (`tsconfig.check.json`, every flag above) is where implicit `any` is caught. - `allowJs` (migration only): `.js` and `.ts` coexist in `src/`; `checkJs` is off. The ratchet (`scripts/ts-ratchet.mjs`, part of `npm run typecheck`): the set of `.js` files under `src/` may only shrink. There is no list file to edit (a shared list is a merge conflict between parallel conversions): the base commit's tree is the list (`RATCHET_BASE` in CI, else the merge-base with `origin/main`/`github/main`). A `.js` file the base lacks fails. When none is left, the check also fails until the migration-only lint relaxations (below) are removed. - No JSDoc types, ever. Types are TypeScript. `npm run typecheck` = `tsc -p tsconfig.check.json` (src + `test/types/*.typetest.ts`, the compile-time tests: every `@ts-expect-error` there must remain an error) + `tsc -p tsconfig.isolated.json` + the TypeScript ratchet + the absence ratchet (`scripts/absence-ratchet.mjs`). `src/` is all TypeScript (the last file, `src/index.js`, became `src/index.ts`). The migration-only relaxation of `typescript/no-unsafe-{assignment,member-access,return,call,argument}` is gone with it: those rules are on, and the ratchet refuses a new `.js` under `src/` and refuses the relaxation coming back. An indexed read the compiler cannot bound goes through `absent.ts`'s checked read (`atOr`, with a domain fallback) rather than `as number`; the per-byte hot loops (inflate, sha1, delta, pkt-line, the pack parsers) keep their block suppressions. ## Lint `npm run lint` runs two profiles: - **Strict** (`.oxlintrc.json`, `--type-aware --deny-warnings`) on `src/**/*.ts`: plugins eslint, typescript, unicorn, oxc, import, promise, node; categories correctness, suspicious, pedantic, perf **and restriction** at error (364 rules on today's files), style off with picks. Turned off, each for a reason: `oxc/no-optional-chaining`, `oxc/no-rest-spread-properties`, `oxc/no-async-await` (ES5-compat restrictions; this is ES2022), `no-magic-numbers` (on only for parser and bounds files, as before), `no-undefined` (the absence ratchet is the gate: it also counts `?:`, `?.`, and `??`, and it only moves down; see Absence), `unicorn/no-null` (null is a value the wire uses), `no-plusplus`, `no-bitwise`, `no-continue` (parsers), `max-lines*`/`max-statements` (a parser is one function), `no-inline-comments` (`/* @__PURE__ */` annotations are inline by definition), `explicit-function-return-type` (isolatedDeclarations already requires it where it matters, at exports), `prefer-readonly-parameter-types` (fires on every `Uint8Array`). Style picks: `consistent-type-definitions: type`, `consistent-type-imports`, `array-type`, `no-inferrable-types`, `prefer-const`, `prefer-template`, `no-nested-ternary`, `import/no-duplicates`, `no-else-return`, `object-shorthand`, `numeric-separators-style`, `prefer-node-protocol`, `throw-new-error`, `no-array-for-each`, `prefer-at`, `import/no-default-export`, `import/extensions: always`. Type-aware rules include `no-unsafe-type-assertion`, `no-floating-promises`, `no-unsafe-*`, `switch-exhaustiveness-check`, `restrict-template-expressions`. A suppression is `// oxlint-disable-next-line -- `; there are three in the converted files, each at a type the compiler cannot follow (a union member built from a generic code; `Object.keys` of an exhaustive table; `match`). - **Loose** (`oxlint.loose.json`) on unconverted `src/*.js` and on `test/`, `scripts/`, `examples/`: the rules ply had before this stack. Verification code may be as heavy as it likes. ## Rules for code in src/ 1. **Errors are values.** A function that can fail returns `Result` (`src/result.ts`: `ok`, `err`, `map`, `mapErr`, `andThen`, `match`, `assertNever`). It does not throw. `throw` is for programmer bugs only: `assertNever`, an `internal` invariant. Platform calls that throw (`fetch`, `crypto.subtle`, a socket) are caught at the edge that makes them and turned into an `Err`. 2. **The error type is a closed, exhaustive union.** `Code` (`src/errors.ts`) is the closed set of codes; `RETRY` and `CODE_DOCS` are typed `Record`, so a code without a policy or a doc does not compile. `PlyError` is the discriminated union over `code`; `Detail` holds the fields a code always carries (`http` → `status`, `limit_exceeded` → `what`/`got`/`max`, `cas_conflict` → `expected`/`actual`, `match_count` → `matches`, `merge_conflict` → `conflicts`), and `fail(code, message, detail)` requires exactly those. A `switch` over a union lists every member and has no `default`; the next statement is `assertNever(x)`, so a new member is a type error. An `if`/`else if` chain on the same tag ends in `assertNever`. `match(u, handlers)` demands one handler per tag. Adding a code or a payload field re-checks every constructor and every match. 3. **A PlyError value is an `Error` instance** with its fields (`Object.assign(new Error(message), {code, …})`): a stack for whoever logs it, and the shape a caller that rethrows it (`if (!r.ok) throw r.error`) expects from an error. Nothing reads it as a class; its type is the union. 4. **Pure functions where possible; I/O at the edges.** Parsers, encoders, validators, planners and merges take bytes/values and return values. Network, timers, crypto and the filesystem live in the transport, http and `*-node.ts` modules, and are passed in, not imported, where a pure module needs them. 5. **State machines are tagged unions with transition functions.** A stream parser is `type State = { tag: 'header'; … } | { tag: 'body'; … } | { tag: 'done'; … }` and `step(state, input): Result`; the driver loop is the only thing with I/O. `pktStep`, `spStep`, `v2Step`, `streamStep` already have this shape in JS; converting them means typing the states, not rewriting them. 6. **Bounds before allocation**, as before: every wire-driven size is checked against a `limits.*` value (`checkLimit`/`parseLimits` return `Result`; a caller's limits record is parsed once at the entry into a `CheckedLimits`, and code past it reads plain numbers) before a buffer exists. 7. **Bundle budgets hold.** Types cost nothing; runtime helpers do. Prefer a type to a runtime check when the value is already trusted; mark unused-but-exported module-level calls `/* @__PURE__ */` so esbuild drops them. 8. **Absence is a value.** See Absence below. Do not write the platform missing value, an optional member, optional chaining, or nullish coalescing outside `src/absent.ts`. ## Absence There is one `Option`: `{ tag: 'some', value } | { tag: 'none' }` in `src/result.ts`, next to `Result`, so ply does not grow a second absence type. `Result` keeps its `ok` discriminant. Option uses `tag`. They compose through `resultToOption`, `optionToResult`, `transposeResultOption`, and `transposeOptionResult`: None carries no reason, so turning None into an Err requires the error the caller supplies. `matchOption` is exhaustive. `mapOption`, `flatMapOption`, and `getOrElse` are that match's two branches (`map` is already Result's name). The platform's missing value is spelled only in `src/absent.ts` and converted there (`fromNullable`, `fromNullish`, `at` / `atOr`, `mapGet`, `readKey`, `jsonDecode`, `byteInRange`, `asOption`, `unwrapOrAbsent`). `Oid` is `string & { brand }`. The same intersection on the platform missing value is `never` under TypeScript 7, so it cannot carry a phantom; the file is the brand, and what leaves it is `Option`. Null stays a wire value (`fromNullable` keeps it; `fromNullish` is the one collapse that `?.` and `??` used to do inline). The file is not under `src/core/` because mutation sharding refuses a subdirectory of `src/` (`scripts/mutate.mjs`). `scripts/absence-ratchet.mjs` (part of `npm run typecheck`) counts, outside that file, the identifier `undefined`, optional members and parameters (`?:`), optional chaining (`?.`), and nullish coalescing (`??`), and compares the four numbers to `scripts/absence-baseline.json`. A rise fails. A drop fails until the same change lowers the baseline (`node scripts/absence-ratchet.mjs --write`, which refuses a rise). New code cannot add any of the four. ## Public API policy Today every public function throws a `PlyError`-shaped `Error`. **Decision: the public API returns `Result`** — `Promise>` from `editFile`, `readFile`, `readLog`, `pushTree`, `checkoutTree`, `merge`, `rebase`, `fetch*`/`push`, the client. We are 0.x; the break is allowed, and ply-web (the consumer we own) is updated in the same step. Why: an exhaustive `switch (r.error.code)` at the call site is the point of the closed union; a `catch` gets `unknown`. Migration path: 1. **Foundation (done).** Toolchain; `result`, `errors`, `errors-doc`, `limits` in TypeScript. 2. **Clusters (done).** Internal functions return `Result`; a throwing wrapper (`orThrow`) bridged what the public API still called. 3. **Cut-over (done, 0.2.0).** Public entry points return `Result`; `thrown`, `orThrow` and every throwing wrapper are deleted; `index` exports `fail` (an Err) and `plyError` (the error value), not a throwing constructor. What may still raise: `assertNever`, an `internal` invariant, and a stream (a ReadableStream errors, an iterator rejects). A value the caller's own callback threw does not raise: it is returned as an `Err` (`bad_request`, or `ambiguous` once the push request was handed to the transport; `what: 'callback'`, the value as `cause`; README "`operation()`: your body's outcomes"). In ply-web, in the same window: bump the pin, replace `try { … } catch (e) { code = e.code }` with `if (!r.ok)` and a `switch (r.error.code)` with no `default` and `assertNever` after it (ply-web already maps codes to HTTP statuses; it becomes exhaustive), delete `src/ply.d.ts` (ply ships its own types). ## Build and consumers `npm run build` (= `prepare`) runs `tsc -p tsconfig.json`: `src/` → `dist/` (`.js` + `.d.ts`, imports rewritten to `.js`). `package.json` `exports` keep every subpath (`.`, `./edit`, `./read`, … `./otel`) with `types` + `default` conditions into `dist/`; `files` is `["dist"]`. `dist/` is not committed: a git-pinned consumer (`"ply": "github:ivarvong/ply#"`) gets it from npm running `prepare` while it packs the git dependency. Evidence and the alternative we rejected are in the PR description. ## Tests vitest runs every `test/**/*.test.js` file that `node --test` ran before (`vitest.config.ts`: `forks` pool, files in parallel, no default timeout, as under node:test), `test/workerd.test.js` included (the worker bundled by esbuild). The fuzzers in `test/fuzz/` stay node scripts (`node --import ./test/ts-resolve.mjs test/fuzz/.mjs`). `npm test` = vitest + the fuzzer chain. CI: `npx vitest run --shard i/4`, partitioned longest-first by measured seconds per file (`test/durations.json`, the sequencer in `vitest.config.ts`); each shard uploads its vitest JSON report. Mutation testing: `@stryker-mutator/vitest-runner` over `vitest.stryker.config.ts` (the mutation-killing files, quick sizes, push-outcome on its own thread, `test/stryker-parent-guard.cjs` preloaded to kill a test process past 3 GB), `mutate: src/**/*.{js,ts}`, per-test coverage. The gate (`scripts/mutate.mjs`) is unchanged: changed lines plus every gated parser and bounds line on a PR, everything on main, parser and bounds survivors fatal, 16 cost-balanced shards. `tsconfigFile` points at a file that does not exist on purpose: Stryker's tsconfig preprocessor calls the TypeScript JS API (`ts.parseConfigFileTextToJson`), which TypeScript 7 does not ship (`TypeError: ts.parseConfigFileTextToJson is not a function`); the rewrite only matters for `extends`/references outside the sandbox, which ply has none of. ## Converting a module (the brief for cluster agents) The rules that make parallel conversions collision-free: **a cluster touches only its own files**. Specifiers stay `.js`, so no importer changes; the ratchet has no list, so no shared file changes. The shared files are `src/errors.ts`, `src/result.ts`, `src/index.*`, `test/bundle.test.js` (budgets), `package.json` and CI: change them only when your cluster cannot work without it, in a separate small commit, and say so in the PR body (the steward merges). Branch from `stack/foundation` (or main once it lands); merge main into your branch as main moves (no rebase, no force-push). Clusters and order: the T1–T7 / A1–A7 plan in `lab_notebook/ply-core-audit-2026-10-31.md` §11. T (mechanical) PR, per file in the cluster: 1. `git mv src/x.js src/x.ts`. Nothing else outside the cluster changes; imports keep saying `./x.js`. 2. Type it. Exported declarations get explicit types (isolatedDeclarations). No `any` written by hand, no `!`, no enums/namespaces/parameter properties (erasableSyntaxOnly), class fields declared. `as` only where the compiler cannot follow, with `// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- `. Byte buffers are `Uint8Array`. No behavior change; `// TODO(A)` marks what the A pass should change. 3. Unconverted modules keep importing `thrown as fail` (the throwing constructor) from `./errors.js`; a converted file that still throws imports the same alias. Errors-as-values is the A pass. A (errors as values, ADTs, state machines) PR, after its T: 4. Replace `throw fail(code, …)` with `return fail(code, …)` (the typed constructor from `./errors.js`), make the function return `Result`, handle every `Err` in the cluster (early return, `andThen`, `match`). A payload a code always carries goes in `Detail` in `errors.ts` (a shared file: one-line change, own commit). 5. Switches over unions list every member, have no `default`, and the next statement is `assertNever(x)`; stream parsers become tagged states with a transition function. Gate, all green before opening the PR (paste the numbers into the PR body): - `npm run typecheck` (tsc check + isolated declarations + ratchet) and `npm run lint` (strict on `src/**/*.ts`). - `npx vitest run `, then the full `npx vitest run`. - The fuzzers that exercise the cluster (`node --import ./test/ts-resolve.mjs test/fuzz/.mjs …`, the same flags as `npm test`). - Bundle budgets: `npx vitest run test/bundle.test.js` passes, and the per-module bytes it prints for your files are ≤ before (types are free; a runtime helper must pay for itself). - Mutation on your files: `node scripts/mutate.mjs` (mutates only files changed against main) — no new survivors in a parser or bounds function; the score on your files does not drop. - `npm run build` and, for the A pass of an entry module, the ply-web acceptance below.