GitHubivarvong

ply

main
ply6 git calls74 ms25 KiB4 cachedprotocol v2
216 lines17 KiBRaw

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.

VersionRole
TypeScript7.0.2 (native compiler, tsc)types, .d.ts, emit to dist/
oxlint + oxlint-tsgolint1.90.0 + 7.0.2005lint, type-aware rules (tsgolint runs TypeScript 7)
vitest5.0.5test runner
Stryker + vitest runner10.1.1mutation testing of src/**/*.{js,ts}
esbuild0.28.2bundle 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 <rule> -- <reason>; 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<T, E> (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<Code, …>, 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<State, PlyError>; 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<T>: { 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<Result<T, PlyError>> 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#<sha>") 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/<f>.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 -- <why>. Byte buffers are Uint8Array. No behavior change; // TODO(A<n>) 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:

  1. 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).
  2. 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 <the test files that cover the cluster>, then the full npx vitest run.
  • The fuzzers that exercise the cluster (node --import ./test/ts-resolve.mjs test/fuzz/<f>.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.
1# Stack
3A fast, small, proven core. The shipped code is TypeScript compiled to plain ESM; the verification around it
4(tests, spaces, fuzzers, mutation) can be as heavy as it needs to be, because none of it ships.
6| | Version | Role |
7|---|---|---|
8| TypeScript | 7.0.2 (native compiler, `tsc`) | types, `.d.ts`, emit to `dist/` |
9| oxlint + oxlint-tsgolint | 1.90.0 + 7.0.2005 | lint, type-aware rules (tsgolint runs TypeScript 7) |
10| vitest | 5.0.5 | test runner |
11| Stryker + vitest runner | 10.1.1 | mutation testing of `src/**/*.{js,ts}` |
12| esbuild | 0.28.2 | bundle budgets (test/bundle.test.js), the workerd test worker (test/workerd/build.mjs) |
14Runtime dependencies: none, ever. Node ≥ 22.18 runs `src/*.ts` directly (type stripping) for tests and fuzzers;
15consumers get `dist/` (plain `.js` + `.d.ts`), so `engines.node` stays `>=20`.
17## Compiler settings and why
19`tsconfig.json` (build) is `strict` plus `noUncheckedIndexedAccess`, `exactOptionalPropertyTypes`,
20`noImplicitReturns`, `noImplicitOverride`, `noFallthroughCasesInSwitch`, `noPropertyAccessFromIndexSignature`,
21`useUnknownInCatchVariables`, `verbatimModuleSyntax`, target ES2022, `module`/`moduleResolution` `nodenext`.
23- `erasableSyntaxOnly`: no enums, namespaces, parameter properties or other syntax with runtime meaning. The emitted
24 JS is the source with the types removed: zero size or speed cost, and Node can run the source as is.
25- **Import specifiers stay `.js`** (`import { fail } from './errors.js'` even though the file is `errors.ts`): the
26 `nodenext` convention. `tsc` maps `./x.js` to `x.ts` and emits it unchanged into `dist/`; vitest (Vite) resolves a
27 `.js` specifier to the `.ts` file from both `.js` and `.ts` importers; plain Node gets the same mapping from
28 `test/ts-resolve.mjs` (a `module.registerHooks` resolve hook: a relative `./x.js` that does not exist resolves to
29 `./x.ts`, then Node ≥ 22.18 strips the types). Run fuzzers and scripts that load `src/` as
30 `node --import ./test/ts-resolve.mjs …`; vitest's config puts it in `NODE_OPTIONS` so every child process and worker
31 a test starts has it; CI sets `NODE_OPTIONS` for whole jobs. Consequence: converting a module renames one file and
32 edits no importer. (Verified on this branch: `errors`, `limits`, `errors-doc` are `.ts`, imported as `.js` from
33 40 JS modules, `tsc`, vitest and `node --import ./test/ts-resolve.mjs` all resolve them.)
34- `isolatedDeclarations`: every export has an explicit type, so declarations never depend on inference across
35 files. TypeScript refuses it together with `allowJs` (TS5053), and TS 7.0.2 panics in declaration emit when both are
36 set, so it runs as its own check: `tsconfig.isolated.json` (only `src/**/*.ts`, `allowJs` off). While unconverted
37 `.js` remains, that one check has `noImplicitAny` off so an import of a `.js` file is not an error there; the main
38 check (`tsconfig.check.json`, every flag above) is where implicit `any` is caught.
39- `allowJs` (migration only): `.js` and `.ts` coexist in `src/`; `checkJs` is off. The ratchet
40 (`scripts/ts-ratchet.mjs`, part of `npm run typecheck`): the set of `.js` files under `src/` may only shrink. There
41 is no list file to edit (a shared list is a merge conflict between parallel conversions): the base commit's tree is
42 the list (`RATCHET_BASE` in CI, else the merge-base with `origin/main`/`github/main`). A `.js` file the base lacks
43 fails. When none is left, the check also fails until the migration-only lint relaxations (below) are removed.
44- No JSDoc types, ever. Types are TypeScript.
46`npm run typecheck` = `tsc -p tsconfig.check.json` (src + `test/types/*.typetest.ts`, the compile-time tests: every
47`@ts-expect-error` there must remain an error) + `tsc -p tsconfig.isolated.json` + the TypeScript ratchet + the
48absence ratchet (`scripts/absence-ratchet.mjs`).
50`src/` is all TypeScript (the last file, `src/index.js`, became `src/index.ts`). The migration-only relaxation of
51`typescript/no-unsafe-{assignment,member-access,return,call,argument}` is gone with it: those rules are on, and the
52ratchet refuses a new `.js` under `src/` and refuses the relaxation coming back. An indexed read the compiler cannot
53bound goes through `absent.ts`'s checked read (`atOr`, with a domain fallback) rather than `as number`; the per-byte
54hot loops (inflate, sha1, delta, pkt-line, the pack parsers) keep their block suppressions.
56## Lint
58`npm run lint` runs two profiles:
60- **Strict** (`.oxlintrc.json`, `--type-aware --deny-warnings`) on `src/**/*.ts`: plugins eslint, typescript, unicorn,
61 oxc, import, promise, node; categories correctness, suspicious, pedantic, perf **and restriction** at error (364
62 rules on today's files), style off with picks. Turned off, each for a reason: `oxc/no-optional-chaining`,
63 `oxc/no-rest-spread-properties`, `oxc/no-async-await` (ES5-compat restrictions; this is ES2022), `no-magic-numbers`
64 (on only for parser and bounds files, as before), `no-undefined` (the absence ratchet is the gate: it also counts
65 `?:`, `?.`, and `??`, and it only moves down; see Absence), `unicorn/no-null` (null is a value the wire uses),
66 `no-plusplus`, `no-bitwise`, `no-continue` (parsers), `max-lines*`/`max-statements` (a parser is
67 one function), `no-inline-comments` (`/* @__PURE__ */` annotations are inline by definition),
68 `explicit-function-return-type` (isolatedDeclarations already requires it where it matters, at exports),
69 `prefer-readonly-parameter-types` (fires on every `Uint8Array`). Style picks: `consistent-type-definitions: type`,
70 `consistent-type-imports`, `array-type`, `no-inferrable-types`, `prefer-const`, `prefer-template`,
71 `no-nested-ternary`, `import/no-duplicates`, `no-else-return`, `object-shorthand`, `numeric-separators-style`,
72 `prefer-node-protocol`, `throw-new-error`, `no-array-for-each`, `prefer-at`, `import/no-default-export`,
73 `import/extensions: always`.
74 Type-aware rules include `no-unsafe-type-assertion`, `no-floating-promises`, `no-unsafe-*`,
75 `switch-exhaustiveness-check`, `restrict-template-expressions`. A suppression is
76 `// oxlint-disable-next-line <rule> -- <reason>`; there are three in the converted files, each at a type the
77 compiler cannot follow (a union member built from a generic code; `Object.keys` of an exhaustive table; `match`).
78- **Loose** (`oxlint.loose.json`) on unconverted `src/*.js` and on `test/`, `scripts/`, `examples/`: the rules ply
79 had before this stack. Verification code may be as heavy as it likes.
81## Rules for code in src/
831. **Errors are values.** A function that can fail returns `Result<T, E>` (`src/result.ts`: `ok`, `err`, `map`,
84 `mapErr`, `andThen`, `match`, `assertNever`). It does not throw. `throw` is for programmer bugs only:
85 `assertNever`, an `internal` invariant. Platform calls that throw (`fetch`, `crypto.subtle`, a socket) are caught
86 at the edge that makes them and turned into an `Err`.
872. **The error type is a closed, exhaustive union.** `Code` (`src/errors.ts`) is the closed set of codes; `RETRY`
88 and `CODE_DOCS` are typed `Record<Code, …>`, so a code without a policy or a doc does not compile. `PlyError` is
89 the discriminated union over `code`; `Detail` holds the fields a code always carries (`http` → `status`,
90 `limit_exceeded` → `what`/`got`/`max`, `cas_conflict` → `expected`/`actual`, `match_count` → `matches`,
91 `merge_conflict` → `conflicts`), and `fail(code, message, detail)` requires exactly those. A `switch` over a
92 union lists every member and has no `default`; the next statement is `assertNever(x)`, so a new member is a type
93 error. An `if`/`else if` chain on the same tag ends in `assertNever`. `match(u, handlers)` demands one handler per
94 tag. Adding a code or a payload field re-checks every constructor and every match.
953. **A PlyError value is an `Error` instance** with its fields (`Object.assign(new Error(message), {code, …})`):
96 a stack for whoever logs it, and the shape a caller that rethrows it (`if (!r.ok) throw r.error`) expects from an
97 error. Nothing reads it as a class; its type is the union.
984. **Pure functions where possible; I/O at the edges.** Parsers, encoders, validators, planners and merges take
99 bytes/values and return values. Network, timers, crypto and the filesystem live in the transport, http and
100 `*-node.ts` modules, and are passed in, not imported, where a pure module needs them.
1015. **State machines are tagged unions with transition functions.** A stream parser is
102 `type State = { tag: 'header'; … } | { tag: 'body'; … } | { tag: 'done'; … }` and
103 `step(state, input): Result<State, PlyError>`; the driver loop is the only thing with I/O. `pktStep`, `spStep`,
104 `v2Step`, `streamStep` already have this shape in JS; converting them means typing the states, not rewriting them.
1056. **Bounds before allocation**, as before: every wire-driven size is checked against a `limits.*` value
106 (`checkLimit`/`parseLimits` return `Result`; a caller's limits record is parsed once at the entry into a
107 `CheckedLimits`, and code past it reads plain numbers) before a buffer exists.
1087. **Bundle budgets hold.** Types cost nothing; runtime helpers do. Prefer a type to a runtime check when the value
109 is already trusted; mark unused-but-exported module-level calls `/* @__PURE__ */` so esbuild drops them.
1108. **Absence is a value.** See Absence below. Do not write the platform missing value, an optional member, optional
111 chaining, or nullish coalescing outside `src/absent.ts`.
113## Absence
115There is one `Option<T>`: `{ tag: 'some', value } | { tag: 'none' }` in `src/result.ts`, next to `Result`, so ply
116does not grow a second absence type. `Result` keeps its `ok` discriminant. Option uses `tag`. They compose through
117`resultToOption`, `optionToResult`, `transposeResultOption`, and `transposeOptionResult`: None carries no reason, so
118turning None into an Err requires the error the caller supplies. `matchOption` is exhaustive. `mapOption`,
119`flatMapOption`, and `getOrElse` are that match's two branches (`map` is already Result's name).
121The platform's missing value is spelled only in `src/absent.ts` and converted there (`fromNullable`, `fromNullish`,
122`at` / `atOr`, `mapGet`, `readKey`, `jsonDecode`, `byteInRange`, `asOption`, `unwrapOrAbsent`). `Oid` is
123`string & { brand }`. The same intersection on the platform missing value is `never` under TypeScript 7, so it
124cannot carry a phantom; the file is the brand, and what leaves it is `Option`. Null stays a wire value
125(`fromNullable` keeps it; `fromNullish` is the one collapse that `?.` and `??` used to do inline). The file is not
126under `src/core/` because mutation sharding refuses a subdirectory of `src/` (`scripts/mutate.mjs`).
128`scripts/absence-ratchet.mjs` (part of `npm run typecheck`) counts, outside that file, the identifier `undefined`,
129optional members and parameters (`?:`), optional chaining (`?.`), and nullish coalescing (`??`), and compares the
130four numbers to `scripts/absence-baseline.json`. A rise fails. A drop fails until the same change lowers the baseline
131(`node scripts/absence-ratchet.mjs --write`, which refuses a rise). New code cannot add any of the four.
133## Public API policy
135Today every public function throws a `PlyError`-shaped `Error`. **Decision: the public API returns `Result`** —
136`Promise<Result<T, PlyError>>` from `editFile`, `readFile`, `readLog`, `pushTree`, `checkoutTree`, `merge`, `rebase`,
137`fetch*`/`push`, the client. We are 0.x; the break is allowed, and ply-web (the consumer we own) is updated in the
138same step. Why: an exhaustive `switch (r.error.code)` at the call site is the point of the closed union; a `catch`
139gets `unknown`.
141Migration path:
1431. **Foundation (done).** Toolchain; `result`, `errors`, `errors-doc`, `limits` in TypeScript.
1442. **Clusters (done).** Internal functions return `Result`; a throwing wrapper (`orThrow`) bridged what the public
145 API still called.
1463. **Cut-over (done, 0.2.0).** Public entry points return `Result`; `thrown`, `orThrow` and every throwing wrapper
147 are deleted; `index` exports `fail` (an Err) and `plyError` (the error value), not a throwing constructor. What
148 may still raise: `assertNever`, an `internal` invariant, and a stream (a ReadableStream errors, an iterator
149 rejects). A value the caller's own callback threw does not raise: it is returned as an `Err` (`bad_request`, or `ambiguous`
150 once the push request was handed to the transport; `what: 'callback'`, the value as `cause`; README "`operation()`:
151 your body's outcomes"). In ply-web,
152 in the same window: bump the pin, replace `try { … } catch (e) { code = e.code }` with `if (!r.ok)` and a
153 `switch (r.error.code)` with no `default` and `assertNever` after it (ply-web already maps codes to HTTP statuses; it becomes
154 exhaustive), delete `src/ply.d.ts` (ply ships its own types).
156## Build and consumers
158`npm run build` (= `prepare`) runs `tsc -p tsconfig.json`: `src/` → `dist/` (`.js` + `.d.ts`, imports rewritten to
159`.js`). `package.json` `exports` keep every subpath (`.`, `./edit`, `./read`, … `./otel`) with `types` + `default`
160conditions into `dist/`; `files` is `["dist"]`. `dist/` is not committed: a git-pinned consumer
161(`"ply": "github:ivarvong/ply#<sha>"`) gets it from npm running `prepare` while it packs the git dependency.
162Evidence and the alternative we rejected are in the PR description.
164## Tests
166vitest runs every `test/**/*.test.js` file that `node --test` ran before (`vitest.config.ts`: `forks` pool, files in
167parallel, no default timeout, as under node:test), `test/workerd.test.js` included (the worker bundled by esbuild). The
168fuzzers in `test/fuzz/` stay node scripts (`node --import ./test/ts-resolve.mjs test/fuzz/<f>.mjs`). `npm test` = vitest
169+ the fuzzer chain. CI: `npx vitest run --shard i/4`, partitioned longest-first by measured seconds per file
170(`test/durations.json`, the sequencer in `vitest.config.ts`); each shard uploads its vitest JSON report.
171Mutation testing: `@stryker-mutator/vitest-runner` over `vitest.stryker.config.ts` (the mutation-killing files, quick
172sizes, push-outcome on its own thread, `test/stryker-parent-guard.cjs` preloaded to kill a test process past 3 GB),
173`mutate: src/**/*.{js,ts}`, per-test coverage. The gate (`scripts/mutate.mjs`) is unchanged: changed lines plus every
174gated parser and bounds line on a PR, everything on main, parser and bounds survivors fatal, 16 cost-balanced shards.
175`tsconfigFile` points at a file that does not exist on purpose: Stryker's tsconfig preprocessor calls the TypeScript JS API
176(`ts.parseConfigFileTextToJson`), which TypeScript 7 does not ship (`TypeError: ts.parseConfigFileTextToJson is not a
177function`); the rewrite only matters for `extends`/references outside the sandbox, which ply has none of.
179## Converting a module (the brief for cluster agents)
181The rules that make parallel conversions collision-free: **a cluster touches only its own files**. Specifiers stay
182`.js`, so no importer changes; the ratchet has no list, so no shared file changes. The shared files are
183`src/errors.ts`, `src/result.ts`, `src/index.*`, `test/bundle.test.js` (budgets), `package.json` and CI: change them only
184when your cluster cannot work without it, in a separate small commit, and say so in the PR body (the steward merges).
185Branch from `stack/foundation` (or main once it lands); merge main into your branch as main moves (no rebase, no
186force-push). Clusters and order: the T1–T7 / A1–A7 plan in `lab_notebook/ply-core-audit-2026-10-31.md` §11.
188T (mechanical) PR, per file in the cluster:
1901. `git mv src/x.js src/x.ts`. Nothing else outside the cluster changes; imports keep saying `./x.js`.
1912. Type it. Exported declarations get explicit types (isolatedDeclarations). No `any` written by hand, no `!`, no
192 enums/namespaces/parameter properties (erasableSyntaxOnly), class fields declared. `as` only where the compiler
193 cannot follow, with `// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- <why>`. Byte buffers are
194 `Uint8Array`. No behavior change; `// TODO(A<n>)` marks what the A pass should change.
1953. Unconverted modules keep importing `thrown as fail` (the throwing constructor) from `./errors.js`; a converted
196 file that still throws imports the same alias. Errors-as-values is the A pass.
198A (errors as values, ADTs, state machines) PR, after its T:
2004. Replace `throw fail(code, …)` with `return fail(code, …)` (the typed constructor from `./errors.js`), make the function
201 return `Result`, handle every `Err` in the cluster (early return, `andThen`, `match`). A payload a
202 code always carries goes in `Detail` in `errors.ts` (a shared file: one-line change, own commit).
2035. Switches over unions list every member, have no `default`, and the next statement is `assertNever(x)`; stream parsers become tagged states with a transition
204 function.
206Gate, all green before opening the PR (paste the numbers into the PR body):
208- `npm run typecheck` (tsc check + isolated declarations + ratchet) and `npm run lint` (strict on `src/**/*.ts`).
209- `npx vitest run <the test files that cover the cluster>`, then the full `npx vitest run`.
210- The fuzzers that exercise the cluster (`node --import ./test/ts-resolve.mjs test/fuzz/<f>.mjs …`, the same flags as
211 `npm test`).
212- Bundle budgets: `npx vitest run test/bundle.test.js` passes, and the per-module bytes it prints for your files are
213 ≤ before (types are free; a runtime helper must pay for itself).
214- Mutation on your files: `node scripts/mutate.mjs` (mutates only files changed against main) — no new survivors in a
215 parser or bounds function; the score on your files does not drop.
216- `npm run build` and, for the A pass of an entry module, the ply-web acceptance below.
Diagnostics6 git calls · 74 ms
CallStatusSizeTime074 ms
discover200191 B2 ms
git.upload-pack discover
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=1
git.response.bytes=191
git.server.agent=git/github-9922ec520325-Linux
git.server.object_format=sha1
git.server.caps=agent ls-refs fetch server-option object-format
git.server.fetch=shallow wait-for-done filter
git.protocol.version=2
git.pkt.frames=9
git.pkt.data=7
git.pkt.flush=2
git.pkt.delim=0
git.pkt.bytes=191
git.pkt.payload.max=36
ls-refs20012 KiB · hit1 ms
git.upload-pack ls-refs
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=ls-refs
git.upstream.dur_ms=1
git.response.bytes=11990
git.response.cache=HIT
git.response.duration_ms=1
git.protocol.version=2
git.pkt.frames=152
git.pkt.data=151
git.pkt.flush=1
git.pkt.delim=0
git.pkt.bytes=11990
git.pkt.payload.max=122
git.ls_refs.count=151
git.ls_refs.head=refs/heads/main
fetchtree:0 · deepen 102004.2 KiB · hit1 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=2
git.response.bytes=4347
git.response.cache=HIT
git.response.duration_ms=1
git.fetch.filter=tree:0
git.fetch.wants=19912563f540228593df0c489082e5e2508e21e4
git.fetch.haves.count=0
git.fetch.deepen=10
git.fetch.thin_pack=false
git.fetch.ofs_delta=true
git.protocol.version=2
git.pkt.frames=7
git.pkt.data=5
git.pkt.flush=1
git.pkt.delim=1
git.pkt.bytes=4347
git.pkt.payload.max=4247
git.sideband.band1.bytes=4247
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0
git.pack.objects=10
git.pack.bytes=4247
git.pack.ofs_delta=0
git.pack.ref_delta=0
git.pack.chain.max=0
git.pack.trailer=a6caf8e129bea82c9bae4cbc7c130c9205add400
git.pack.full=10
Open pack map
fetchtree:0200919 B · hit2 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=3
git.response.bytes=919
git.response.cache=HIT
git.response.duration_ms=2
git.fetch.filter=tree:0
git.fetch.wants=800d30ba8923860bfc460ca884b7f9ba22083588
git.fetch.haves.count=0
git.fetch.deepen=0
git.fetch.thin_pack=false
git.fetch.ofs_delta=true
git.protocol.version=2
git.pkt.frames=4
git.pkt.data=3
git.pkt.flush=1
git.pkt.delim=0
git.pkt.bytes=919
git.pkt.payload.max=892
git.sideband.band1.bytes=892
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0
git.pack.objects=1
git.pack.bytes=892
git.pack.trailer=5323b9266eea5ded637285d1c5320699f12be76e
Open pack map
fetchtree:0200106 B · hit3 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=66
git.response.bytes=106
git.response.cache=HIT
git.response.duration_ms=3
git.fetch.filter=tree:0
git.fetch.wants=3b431e2dc012dfd316e782edcabdd24ef981c4bf
git.fetch.haves.count=0
git.fetch.deepen=0
git.fetch.thin_pack=false
git.fetch.ofs_delta=true
git.protocol.version=2
git.pkt.frames=4
git.pkt.data=3
git.pkt.flush=1
git.pkt.delim=0
git.pkt.bytes=106
git.pkt.payload.max=79
git.sideband.band1.bytes=79
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0
git.pack.objects=1
git.pack.bytes=79
git.pack.trailer=01dbf1597af4ff689e362a1dee5ad8142872963d
Open pack map
fetch2007.7 KiB66 ms
git.upload-pack fetch
http.response.status_code=200
git.response.bytes=7837
git.response.cache=MISS
git.response.duration_ms=66
git.fetch.wants=2b2a4565f9cb1b6b7ffc615bfaacb52eef861b5a
git.fetch.haves.count=0
git.fetch.deepen=0
git.fetch.thin_pack=false
git.fetch.ofs_delta=true
git.protocol.version=2
git.pkt.frames=4
git.pkt.data=3
git.pkt.flush=1
git.pkt.delim=0
git.pkt.bytes=7837
git.pkt.payload.max=7810
git.sideband.band1.bytes=7810
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0

Each row is one HTTP round trip ply made to the git server for this page, on one timeline. discover asks what the server speaks, ls-refs lists branch tips, fetch brings objects by id. A hit was served by Workers Cache. Tap a row for its wire details.

Remote
https://github.com/ivarvong/ply
Ref
refs/heads/main
Commit
19912563f540228593df0c489082e5e2508e21e4
cf-ray
a5e0f8281ef9332c
Request
b7678ae1…
Protocol
v2 · sha1
Agent
git/github-9922ec520325-Linux
Filter
advertised
Fetch
shallow wait-for-done filter
Capabilities
agent ls-refs fetch server-option object-format