{"name": "trpc", "version": "0.1.0", "hash": "sha256:6b981539cef2777a96f647d740f2cec8937e2889fdb23dbed9e0f1b2930f761f", "files": {"ABSORB_REPORT.md": "# Absorb report: trpc\n\n- **Source:** https://github.com/trpc/trpc at `ee3e8f2ef9f3`\n- **Licence:** MIT\n- **Project names searched for:** trpc, root\n\n## What was absorbed\n\n| Piece | Kind | Class | Project names | Project paths |\n|---|---|---|---|---|\n| pr-agent-callout | skill | mechanics |  |  |\n| principle-boundary-discipline | skill | mechanics |  |  |\n| principle-encode-lessons-in-structure | skill | mechanics |  |  |\n| principle-type-system-discipline | skill | mechanics |  |  |\n| tdd | skill | mechanics |  |  |\n| trpc-conventions | skill | mixed | trpc ×4, root ×1 | packages/react-query/test/regression, tooling/oxlint-plugin |\n| typescript-best-practices | skill | mechanics |  |  |\n\n## Needs review before sharing\n\nThese pieces mention the project by name or lean on its files. Move those facts into configuration, or keep the piece out of a shared starter.\n\n- **trpc-conventions** (skill): names trpc, root; paths packages/react-query/test/regression, tooling/oxlint-plugin\n\n## Not absorbed\n\n- instruction files (AGENTS.md): they describe the project, so they stay with it. Pass --with-instructions to absorb them for review\n\n## Self-test\n\nNo case could be generated.\n", "ATTRIBUTION.md": "# Attribution: trpc\n\nThis harness was absorbed from https://github.com/trpc/trpc at commit `ee3e8f2ef9f3ae8a7ef5f40c89dea4802da3200d` on 2026-11-27 with `baudrier absorb`.\n\n- **Licence:** MIT. Licence and notice files kept unchanged in this folder: `LICENSE`.\n- **Credit:** every file listed below is the work of the source repository's authors. Files were copied unchanged, except that hook commands name their folder as `${HARNESS_HOOKS}` and slash commands were wrapped as skills.\n\n## Absorbed files\n\n- `skills/pr-agent-callout/SKILL.md` (skill)\n- `skills/pr-agent-callout/callout.sh` (skill)\n- `skills/principle-boundary-discipline/SKILL.md` (skill)\n- `skills/principle-encode-lessons-in-structure/SKILL.md` (skill)\n- `skills/principle-type-system-discipline/SKILL.md` (skill)\n- `skills/tdd/SKILL.md` (skill)\n- `skills/trpc-conventions/SKILL.md` (skill)\n- `skills/typescript-best-practices/SKILL.md` (skill)\n- `skills/typescript-best-practices/references/patterns.md` (skill)\n", "LICENSE": "MIT License\n\nCopyright (c) 2023 Alex Johansson\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n", "harness.yaml": "$schema: https://harnessprotocol.io/schema/v1/harness.schema.json\nversion: '1'\nkind: profile\nmetadata:\n  name: trpc\n  description: 'The tRPC repository''s agent skills: conventions, TDD, and type-system and boundary discipline.'\n  version: 0.1.0\n  license: MIT\nskills:\n- name: pr-agent-callout\n  source: ./skills/pr-agent-callout\n- name: principle-boundary-discipline\n  source: ./skills/principle-boundary-discipline\n- name: principle-encode-lessons-in-structure\n  source: ./skills/principle-encode-lessons-in-structure\n- name: principle-type-system-discipline\n  source: ./skills/principle-type-system-discipline\n- name: tdd\n  source: ./skills/tdd\n- name: trpc-conventions\n  source: ./skills/trpc-conventions\n- name: typescript-best-practices\n  source: ./skills/typescript-best-practices\nx-origin:\n  repository: https://github.com/trpc/trpc\n  commit: ee3e8f2ef9f3ae8a7ef5f40c89dea4802da3200d\n  license: MIT\n  license_basis: detected\n  license_files:\n  - LICENSE\n  absorbed_at: '2026-11-27'\n", "skills/pr-agent-callout/SKILL.md": "---\nname: pr-agent-callout\ndescription: Put a callout at the top of a PR body while an agent is working on the PR, and remove it once the agent no longer plans to push. Use when starting or stopping work on any PR you push to, including other people's.\n---\n\n# PR agent callout\n\nWhile you work on a PR you push to, its body starts with a callout saying what you're doing. Use `callout.sh` beside this file, from the repository with the PR's branch checked out:\n\n```sh\n<skill-dir>/callout.sh set \"<what you're doing>\" [run-url]\n<skill-dir>/callout.sh clear\n```\n\n- **Start of each round of work** (first push, review fixes, a CI fix): `set` once with a one-line summary of the round. Don't update it step by step.\n- **When you stop planning to push** (done, handed off, or waiting on a human): `clear`, before your final message.\n- If `gh`'s token can't edit pull requests, set `GH_TOKEN` (`GH_ENTERPRISE_TOKEN` on GitHub Enterprise Server) to one that can. If none can, say so in your final message.\n- When a tool writes the whole body, such as when opening the PR, run `set` right after it.\n", "skills/pr-agent-callout/callout.sh": "#!/usr/bin/env bash\n# Sets or clears the callout at the top of the current branch's PR body that\n# says an agent is working on it. See SKILL.md beside this file.\n#\n#   callout.sh set \"<activity>\" [run-url]\n#   callout.sh clear\n#\n# Run it inside the repository, on the PR's branch. Needs bash 3.2+, gh and\n# coreutils; gh uses GH_TOKEN and GH_REPO when they are set.\nset -euo pipefail\nexport LC_ALL=C\n\nreadonly START='<!-- agent-callout:start -->'\nreadonly END='<!-- agent-callout:end -->'\n\ndie() {\n  printf 'callout.sh: %s\\n' \"$*\" >&2\n  exit 1\n}\n\nusage() {\n  die 'usage: callout.sh set \"<activity>\" [run-url] | callout.sh clear'\n}\n\ncount() {\n  local s=$1 n=0\n  while [[ $s == *\"$2\"* ]]; do\n    s=${s#*\"$2\"}\n    n=$((n + 1))\n  done\n  echo \"$n\"\n}\n\ntmp=$(mktemp -d)\ntrap 'rm -rf \"$tmp\"' EXIT\n\n# Sets $pr_url, $host, $repo and $pr from the current branch's PR. Later calls\n# use them, so they reach the same PR even on a GitHub Enterprise host.\nfind_pr() {\n  command -v gh >/dev/null || die 'gh (the GitHub CLI) is not installed'\n  pr_url=$(gh pr view --json url --jq .url 2>\"$tmp/err\") ||\n    die \"could not find a PR for the current branch: $(cat \"$tmp/err\")\"\n  local pattern='^https?://([^/]+)/([^/]+/[^/]+)/pull/([0-9]+)$'\n  [[ $pr_url =~ $pattern ]] || die \"gh pr view printed an unexpected PR URL: $pr_url\"\n  host=${BASH_REMATCH[1]}\n  repo=${BASH_REMATCH[2]}\n  pr=${BASH_REMATCH[3]}\n}\n\nread_body() {\n  gh pr view \"$pr_url\" --json body --template '{{.body}}' >\"$tmp/body\" 2>\"$tmp/err\" ||\n    die \"could not read the body of PR #$pr: $(cat \"$tmp/err\")\"\n  # $(...) drops trailing newlines; the sentinel keeps them.\n  body=$(\n    cat \"$tmp/body\"\n    printf x\n  )\n  body=${body%x}\n}\n\n# Splits $body around the callout into $before and $after; sets $has to 0 or 1.\nsplit_body() {\n  local starts ends\n  starts=$(count \"$body\" \"$START\")\n  ends=$(count \"$body\" \"$END\")\n  if [[ $starts == 0 && $ends == 0 ]]; then\n    has=0\n    return\n  fi\n  [[ $starts == 1 && $ends == 1 ]] ||\n    die \"PR #$pr has $starts start and $ends end callout markers; fix its body by hand\"\n  before=${body%%\"$START\"*}\n  [[ $before != *\"$END\"* ]] ||\n    die \"PR #$pr has the end callout marker before the start one; fix its body by hand\"\n  after=${body#*\"$END\"}\n  has=1\n}\n\n# Writes $new unless it equals $body.\nwrite_body() {\n  if [[ $new == \"$body\" ]]; then\n    echo \"PR #$pr: unchanged, $1\"\n    exit 0\n  fi\n  printf '%s' \"$new\" >\"$tmp/new\"\n  # Not `gh pr edit`: it also reads the PR's reviewers, which some tokens\n  # that may edit the body can't.\n  gh api --hostname \"$host\" --method PATCH \"repos/$repo/pulls/$pr\" \\\n    -F \"body=@$tmp/new\" >/dev/null 2>\"$tmp/err\" ||\n    die \"could not update the body of PR #$pr; gh's token needs to be able to edit pull requests (set GH_TOKEN, or GH_ENTERPRISE_TOKEN on GitHub Enterprise Server, to use another): $(cat \"$tmp/err\")\"\n}\n\n[[ $# -ge 1 ]] || usage\n\ncase $1 in\n  set)\n    [[ $# -ge 2 && $# -le 3 ]] || usage\n    activity=$2\n    run_url=${3:-}\n    [[ -n ${activity//[[:space:]]/} ]] || die 'the activity is empty'\n    [[ $activity != *$'\\n'* && $activity != *$'\\r'* ]] ||\n      die 'the activity must be one line'\n    [[ $activity != *agent-callout:* ]] ||\n      die 'the activity must not contain a callout marker'\n    url_pattern='^https?://[^[:space:]<>()]+$'\n    [[ -z $run_url || $run_url =~ $url_pattern ]] ||\n      die \"the run URL must be an http(s) URL without spaces, <, >, ( or ): $run_url\"\n\n    find_pr\n    read_body\n    split_body\n    # Match the body's line endings: CRLF if its first line ends with one.\n    nl=$'\\n'\n    first_line=${body%%$'\\n'*}\n    if [[ $body == *$'\\n'* && $first_line == *$'\\r' ]]; then\n      nl=$'\\r\\n'\n    fi\n    now=\"> **Now:** $activity\"\n    [[ -z $run_url ]] || now+=\" · [agent run]($run_url)\"\n    title='> 🤖 🚧 **An agent is working on this PR** 🚧'\n    block=\"$START$nl> [!NOTE]$nl$title$nl>$nl$now$nl$END\"\n    if [[ $has == 1 ]]; then\n      new=\"$before$block$after\"\n    else\n      new=\"$block$nl$nl$body\"\n    fi\n    write_body 'callout set'\n\n    read_body\n    [[ $body == *\"$block\"* ]] ||\n      die \"PR #$pr was edited, but its body does not show the new callout\"\n    echo \"PR #$pr: callout set\"\n    ;;\n  clear)\n    [[ $# -eq 1 ]] || usage\n    find_pr\n    read_body\n    split_body\n    if [[ $has == 0 ]]; then\n      echo \"PR #$pr: unchanged, no callout\"\n      exit 0\n    fi\n    # `set` adds the callout and two line breaks; remove at most those.\n    for _ in 1 2; do\n      if [[ $after == $'\\r\\n'* ]]; then\n        after=${after:2}\n      elif [[ $after == $'\\n'* ]]; then\n        after=${after:1}\n      fi\n    done\n    new=\"$before$after\"\n    write_body 'no callout'\n\n    read_body\n    [[ $body != *\"$START\"* ]] ||\n      die \"PR #$pr was edited, but its body still has the callout\"\n    echo \"PR #$pr: callout cleared\"\n    ;;\n  *)\n    usage\n    ;;\nesac\n", "skills/principle-boundary-discipline/SKILL.md": "---\nname: principle-boundary-discipline\ndescription: \"Apply when wiring validation, error handling, or framework adapters. Concentrate guards at system boundaries (CLI, config, network, external APIs); trust internal types and keep business logic in pure functions.\"\ndisable-model-invocation: true\n---\n\n# Boundary Discipline\n\nPlace validation, type narrowing, and error handling at system boundaries. Trust internal code unconditionally. Business logic lives in pure functions. The shell is thin and mechanical.\n\n**Why:** Scattered validation is noisy, redundant, and gives a false sense of safety. Keep logic out of framework wiring so it can be tested without the framework.\n\n**The pattern:**\n- **At boundaries** (CLI args, config files, external APIs, network protocols): validate, return errors, handle defensively.\n- **Inside the system:** typed data, error propagation, no re-validation. Trust the types.\n- **Across the boundary.** Expose domain concepts, not the boundary's private representation. Keep general-purpose mechanism inside and special-purpose policy at the edge.\n\n**Applications:**\n\nValidation and error handling:\n- Validate config at parse time (the boundary), not inside business logic\n- Parse raw data into domain types at the boundary\n- Do not re-export transport, storage, framework, or wire types through the public surface\n- No redundant nil checks deep in call chains if the boundary already validated\n\nCode organization:\n- Business logic in pure functions with no framework dependencies\n- Parse functions: pure transforms from raw bytes to typed state\n- Prompt construction: structured state in, string out\n- Scoring and assessment: pure transforms from state to results\n\n**The tests:**\n- \"Is this data crossing a system boundary right now?\" If not, validation is redundant.\n- \"Can this be a pure function that the shell just calls?\" If yes, extract it.\n", "skills/principle-encode-lessons-in-structure/SKILL.md": "---\nname: principle-encode-lessons-in-structure\ndescription: \"Apply when you catch yourself writing the same instruction a second time, or notice a recurring correction. Encode the rule as a lint, metadata flag, runtime check, or script instead of more text.\"\ndisable-model-invocation: true\n---\n\n# Encode Lessons in Structure\n\nIf the lesson needs judgment and cannot be encoded, make the instruction more prominent and add an example of the failure mode.\n\n**Corollary:** If the fix is structural, only use the structural fix. The instruction is the symptom.\n", "skills/principle-type-system-discipline/SKILL.md": "---\nname: principle-type-system-discipline\ndescription: \"Apply when designing types, reviewing a function signature, or writing code in any statically-typed language. Make illegal states unrepresentable, brand semantic primitives, parse external data at boundaries, exhaust variants, derive from authoritative schemas.\"\ndisable-model-invocation: true\n---\n\n# Type System Discipline\n\nMake the compiler reject impossible states, mismatched primitives, and unhandled variants. Prefer defining errors and special cases out of existence over proliferating handlers. For TypeScript syntax, see the `typescript-best-practices` skill.\n\n- **Brand semantic primitives.** `UserId` and `OrderId` are strings underneath but should not be interchangeable. Give each its own type, such as a branded intersection in TypeScript or a newtype elsewhere. Validate once at creation, trust the type downstream. If two arguments share a primitive type but mean different things, brand them.\n- **External data is untyped until parsed.** RPC payloads, JSON, IPC messages, CLI args, config files, environment variables, database rows. Have a parse function at every boundary that turns unstructured input into the typed model. The **boundary-discipline** principle skill says where to put validation.\n- **Derive types from authoritative schemas.** When a protocol buffer, OpenAPI spec, GraphQL schema, database migration, design-token file, or another file owns a shape, derive from it instead of hand-rolling a parallel type. See the **encode-lessons-in-structure** principle skill.\n", "skills/tdd/SKILL.md": "---\nname: tdd\ndescription: \"Use only when the user explicitly asks for TDD, a failing test, or a regression test, OR when the bug has an obvious cheap local test target. Skip when the test path is unclear, expensive, integration-heavy, or not requested.\"\ndisable-model-invocation: true\n---\n\n# TDD Bug Fix\n\nWhen fixing a bug with a clear, cheap test path, make the broken behavior executable before changing production code. The goal is a focused regression test that fails before the fix and passes after it.\n\nDo not force a test when it would be impractical. If the available test would require broad harness setup, brittle mocks, slow end-to-end infrastructure, production-only state, vague reproduction steps, or large unrelated fixture churn, skip adding a new test and use the closest useful verification instead.\n\n## Workflow\n\n1. **Understand the bug.** Identify the intended behavior, current behavior, affected path, and smallest observable reproduction.\n2. **Choose the narrowest executable check.** Prefer the closest unit, component, integration, or regression test already used for that codepath. If no practical test path is obvious, do not create one from scratch just to satisfy the workflow.\n3. **Write the failing test first.** Add the smallest focused test that would have caught the bug. The test should encode intended behavior, not mirror the current implementation.\n4. **Run the new test before fixing.** Confirm it fails for the intended reason. If it passes or fails for an unrelated reason, correct the test or reproduction before editing the implementation.\n5. **Fix the bug.** Make the smallest production change that satisfies the intended behavior while preserving nearby contracts.\n6. **Rerun the regression test.** Confirm the test now passes.\n\n## If a Failing Test Is Impractical\n\nUse the closest executable regression check instead: a targeted script, manual reproduction command, browser automation, snapshot comparison, log assertion, or focused integration check.\n\nPrefer no new test over a bad test. A bad test is one that mostly tests mocks, encodes current implementation details, depends on timing or unrelated global state, needs expensive infrastructure for a small fix, or would be deleted immediately after proving the fix.\n\n## Guardrails\n\n- Do not change tests merely to match a wrong implementation.\n- Do not weaken existing assertions unless the expected behavior has genuinely changed and the reason is clear.\n- Keep the regression test focused on the bug. Avoid broad fixture churn or unrelated coverage expansion.\n- If the bug is flaky, make the test deterministic where possible and document the signal being locked down.\n- If the bug exposes a broader class of failures, first land the focused regression path, then consider additional sibling coverage.\n\n## Final Response\n\nReport the evidence, not just the outcome:\n\n- Name the failing-before test or executable check and the failure it produced.\n- Name the passing-after test run and any nearby validation performed.\n- If failing-before evidence could not be demonstrated, state why and describe the closest regression check used instead.\n", "skills/trpc-conventions/SKILL.md": "---\nname: trpc-conventions\ndescription: tRPC's test setup and TypeScript conventions, which win where the generic pstack tdd, typescript-best-practices and principle-type-system-discipline skills disagree. Use when fixing a bug, writing or changing tests, or writing or reviewing TypeScript in packages/.\n---\n\n# tRPC conventions\n\n## Tests\n\n- Every bug fix gets a regression test that fails without the fix, even when the test path is an integration test. Put it in `packages/tests/server/regression/issue-<number>-<slug>.test.ts`, or beside the code's existing tests (the legacy React package has `packages/react-query/test/regression/`).\n- Test through a real client and server. `testServerAndClientResource` is in `@trpc/client/__tests__/testClientResource`; the React packages have their own helpers, so copy the setup from the nearest test.\n\n  ```ts\n  await using ctx = testServerAndClientResource(router);\n  ```\n\n- Watch it fail, then pass: `pnpm vitest run <file>` from the repo root.\n- The PR's `Regression check:` line names the test and what it catches without the fix.\n- In new tests, wait on a condition with `vi.waitFor` rather than a fixed sleep.\n- No `beforeEach`, `beforeAll`, `afterEach` or `afterAll` (`vitest/no-hooks`). Each test sets up what it needs with `using`/`await using`: a helper returns a disposable that undoes its setup, such as `using _timers = fakeTimersResource()`. Share expensive read-only setup with a memoised getter instead of `beforeAll`.\n- Add tests; don't rewrite or weaken existing ones unless the expected behaviour changed and the PR says why.\n\n## TypeScript\n\n- Internal (non-exported) parameters, properties and options are required. Pass absence explicitly as `null`, `undefined`, a literal or a symbol, whichever fits: `x: T | undefined` that every caller passes is fine, but not `x?: T` or an optional or defaulted parameter. Optionals are only conveniences on public APIs; normalise a public options object once at the boundary into a fully required internal shape.\n\n  ```ts\n  function connect(url: string, retry?: RetryOptions); // before\n  function connect(url: string, retry: RetryOptions | null); // after\n  ```\n\n- Take one options object, `opts`, and read its members. Destructure only keys read three or more times.\n- Clean up with `await using` and `makeResource()` or `makeAsyncResource()`, not `try`/`finally`.\n- Brands use `__brand`, as in `stream/tracked.ts`. `any` is fine in generic constraints such as `AnyRouter`. Declare return types only on public APIs.\n- Lint (`.oxlintrc.json`, `tooling/oxlint-plugin/`) already enforces type imports, at most three parameters, type-parameter names, no non-null assertions and exhaustive switches.\n", "skills/typescript-best-practices/SKILL.md": "---\nname: typescript-best-practices\ndescription: TypeScript best practices. Use when reading or editing any .ts or .tsx file.\npaths: [\"**/*.ts\", \"**/*.tsx\"]\ndisable-model-invocation: true\n---\n\n# TypeScript best practices\n\nApply the **type-system-discipline** principle skill first.\n\n| Rule | Summary |\n|------|---------|\n| Discriminated unions | Model variants with a `kind` literal discriminant so impossible states can't be represented. No optional-field bags. |\n| Branded types | Brand primitives with `& { readonly __brand: \"X\" }` so they can't be mixed up. Validate once at the boundary. A brand comes from a verifying type guard (`input is AgentId`), never from `as`. |\n| Constructive modeling | Build the shape so the illegal value can't be constructed. `[T, ...T[]]` for non-empty, `[T, T][]` for even length, `start` plus `duration` for a range. Not a runtime guard, not a wish for refinement types. |\n| Simplest total type | Keep `T[]` while every operation on it stays total. Strengthen to `NonEmpty<T>` only where the loose type forces `!`, a cast, or a \"should never happen\" throw. |\n| `unknown` over `any` | External data is `unknown`. |\n| Schemas before guards | Before hand-writing a property-by-property type guard, use the repository's runtime schema library and infer the type from the schema, such as `z.infer`. |\n| No `as` casts | Every `as` is a runtime crash waiting. Cast only after validation. |\n| Narrowing hierarchy | Discriminant switch > `in` operator > `typeof`/`instanceof` > user-defined type guard > `as`. |\n| Type guards | Must verify the claim. A lying guard is worse than `as` because the bug hides behind a name that says it's safe. Name them `isX` or `hasX`. |\n| Exhaustiveness | Inline `const _exhaustive: never = x;` in default arms so the compiler errors when a new variant is added. |\n| `satisfies` over `as` | Validates the value without widening literal types. |\n| Boundary validation | Parse where data crosses in, into a named domain type. `Record<string, unknown>` (however spelled) stops at that parse. Trust types inside. See the **boundary-discipline** principle skill. |\n| Schema-derived types | Reach for `Pick`/`Omit`/`Parameters`/`ReturnType`/`Awaited`/`typeof` before declaring a new interface. |\n| Object args | Pass objects, not positional, so argument order is self-documenting. Skip on hot paths (per-frame render, tokenizers, parsers). |\n| Real tests | Don't mock what you can run. Prefer the framework's real test primitives with leak/disposable checks, and verify UI in a running build. Mock only what you can't run locally. |\n| Structured telemetry | Prefer structured logger diagnostics with enough context to debug from an id. No `console.log` in shipped code. |\n\nExamples: `references/patterns.md`.\n", "skills/typescript-best-practices/references/patterns.md": "# TypeScript patterns\n\nCode examples for each rule in `SKILL.md`. The underlying principles are language-agnostic. See the **type-system-discipline** and **boundary-discipline** principle skills.\n\n## Branded types\n\nBrand primitives so they can't be mixed up. Validate once at the boundary. Downstream code trusts the type.\n\n```ts\ntype AgentId = string & { readonly __brand: \"AgentId\" };\n\nfunction isAgentId(input: string): input is AgentId {\n  return isUUID(input);\n}\n\nfunction parseAgentId(input: string): AgentId {\n  if (!isAgentId(input)) throw new Error(`Invalid agent id: ${input}`);\n  return input;\n}\n\nfunction focusAgent(id: AgentId): void {\n  /* input is trusted */\n}\n```\n\nMatch the `readonly __brand: 'X'` shape. Don't invent a new convention.\n\n## Discriminated unions\n\nModel variants with a literal discriminant. Every variant shares the field name and each variant's value is unique, so impossible combos can't be represented.\n\n```ts\n// Don't. Boolean + optionals lets contradictory states exist.\ntype DiffState = { loading: boolean; diff?: GitDiff; error?: string };\n\n// Do. Only valid states exist.\ntype DiffState =\n  | { kind: \"loading\" }\n  | { kind: \"ready\"; diff: GitDiff }\n  | { kind: \"error\"; error: string };\n```\n\nPick one discriminant name (`kind`, `type`, `tag`) and stick to it.\n\n## Constructive modeling\n\nBuild the type from parts that are all legal instead of restricting a loose type with runtime checks.\n\nNon-empty, via a variadic tuple:\n\n```ts\ntype NonEmpty<T> = [T, ...T[]];\n\n// Don't: T[] plus a length check every caller must repeat\nfunction pickWinner(entries: string[]): string {\n  if (entries.length === 0) throw new Error(\"no entries\");\n  return entries[Math.floor(Math.random() * entries.length)];\n}\n\n// Do: an empty value of the type can't exist\nfunction pickWinner(entries: NonEmpty<string>): string {\n  return entries[Math.floor(Math.random() * entries.length)];\n}\n```\n\nWhere a plain `T[]` arrives, narrow once with a guard. The fact then travels in the type:\n\n```ts\nconst isNonEmpty = <T>(arr: T[]): arr is NonEmpty<T> => arr.length > 0;\n```\n\nEven length, as pairs:\n\n```ts\ntype Pairs<T> = [T, T][];\n```\n\nA time range, as start plus duration:\n\n```ts\n// Don't: a comment holds the invariant\ntype TimeRange = { start: Date; end: Date }; // start <= end\n\n// Do: a negative range can't be written; derive end when needed\ntype TimeRange = { start: Date; durationMs: number };\n```\n\nKeep `durationMs` a plain number. Brand it (per Branded types) only if a raw number could be passed where a duration is expected, not by reflex. Pick the representation that makes the bad state unconstructable, then expose the reading you need on top (`pairs.flat()`, a `rangeEnd()` helper).\n\n## Simplest total type\n\nDon't strengthen everything. Keep `T[]` when every operation on it is total:\n\n```ts\nconst sum = (xs: number[]) => xs.reduce((a, b) => a + b, 0); // [] is 0, fine\n```\n\nStrengthen when the loose type forces a lie at a use site. The tells are `!`, `arr[0] as T`, and a \"should never happen\" throw:\n\n```ts\n// Don't: partiality smuggled past the compiler\nfunction newestSession(sessions: Session[]): Session {\n  return sessions.at(0)!;\n}\n\n// Do: strengthen the input; the assertion disappears\nfunction newestSession(sessions: NonEmpty<Session>): Session {\n  return sessions[0];\n}\n```\n\nWeakening the result to `Session | undefined` is the other total signature.\n\n## `unknown` over `any`\n\nExternal data is always `unknown`. Narrow before use.\n\n```ts\n// Don't\nfunction handle(input: any) {\n  return input.foo.bar;\n}\n\n// Do\nfunction handle(input: unknown) {\n  if (typeof input === \"object\" && input !== null && \"foo\" in input) {\n    // narrowed; compiler verifies access\n  }\n}\n```\n\nExternal sources include RPC payloads, `JSON.parse`, `postMessage`, IPC, file contents, environment variables, database results.\n\n## Schemas before hand-rolled guards\n\nBefore writing a property-by-property type guard for external data, look for the repository's runtime schema library and existing schemas. Let one schema own validation and derive the TypeScript type from it. Do not maintain a schema, a duplicate interface, and a guard that can drift apart.\n\n```ts\nimport { z } from \"zod\";\n\nconst UserSchema = z.object({\n  id: z.string().uuid(),\n  role: z.enum([\"admin\", \"member\"]),\n});\n\ntype User = z.infer<typeof UserSchema>;\n\nfunction parseUser(input: unknown): User {\n  return UserSchema.parse(input);\n}\n```\n\nUse `safeParse` when failure is an expected branch. Use the equivalent inference helper when the repository uses another schema library. Do not add a new schema dependency for one guard. This rule prefers the schema system the codebase already trusts.\n\n## No `as` casts\n\nEvery `as` is a potential runtime crash. Cast only after the type system has verified the claim.\n\n```ts\nimport { z } from \"zod\";\n\n// Don't\nconst user = data as User;\n\n// Don't\nfunction isUser(data: unknown): data is User {\n  return typeof data === \"object\" && data !== null && \"id\" in data;\n}\n\n// Do\nconst userSchema = z.object({ id: z.string(), name: z.string() });\ntype User = z.infer<typeof userSchema>;\n\nfunction parseUser(data: unknown): User {\n  return userSchema.parse(data);\n}\n```\n\nWhen the type comes first, annotate the validator with the type it proves. The compiler then rejects a validator that proves less than the type. Remove `name` from the object below and the assignment fails to compile.\n\n```ts\ntype User = { id: string; name: string };\n\nconst userSchema: z.ZodType<User> = z.object({ id: z.string(), name: z.string() });\n```\n\nWhen refactoring an `as` out of existing code, identify why TypeScript can't infer:\n\n- Missing discriminant: add one, switch to a discriminated union.\n- Overly wide source type (e.g. `Record<string, unknown>`): narrow it.\n- Untyped boundary: parse with the schema that owns the shape. Add a schema only where none exists.\n- Genuinely inexpressible: use a branded type or `satisfies`.\n\n## Narrowing hierarchy\n\nFrom best to last-resort:\n\n1. **Discriminated union switch / if.** Compiler narrows automatically.\n2. **`in` operator.** `\"key\" in obj` narrows to variants containing that key.\n3. **`typeof` / `instanceof`.** For primitives and class instances.\n4. **User-defined type guard.** When the above aren't enough.\n5. **`as` cast.** Only after validation.\n\n```ts\nfunction area(s: Shape): number {\n  if (\"radius\" in s) return Math.PI * s.radius ** 2; // narrowed to circle\n  return s.width * s.height; // narrowed to rect\n}\n```\n\n## Type guards\n\nA guard must actually verify the claim. A lying guard is worse than `as`.\n\n```ts\nfunction isCircle(s: Shape): s is Shape & { kind: \"circle\" } {\n  return s.kind === \"circle\";\n}\n```\n\nPrefer discriminant narrowing when possible.\n\n## Exhaustiveness\n\nIn default arms, assign the discriminant to a `never`-typed local.\n\n```ts\n// Value-returning switch\nfunction area(s: Shape): number {\n  switch (s.kind) {\n    case \"circle\":\n      return Math.PI * s.radius ** 2;\n    case \"rect\":\n      return s.width * s.height;\n    default: {\n      const _exhaustive: never = s;\n      return _exhaustive;\n    }\n  }\n}\n\n// Void switch\nfunction handle(s: Shape): void {\n  switch (s.kind) {\n    case \"circle\":\n      drawCircle(s);\n      break;\n    case \"rect\":\n      drawRect(s);\n      break;\n    default: {\n      const _exhaustive: never = s;\n      void _exhaustive;\n    }\n  }\n}\n```\n\nReturn-style in value-returning switches, void-style in statement switches.\n\n## `satisfies` over `as`\n\n`satisfies` validates without widening literal types.\n\n```ts\n// Don't. Widens, loses literal types.\nconst config = { theme: \"dark\", cols: 3 } as Config;\n\n// Do. Validates AND preserves literal types.\nconst config = { theme: \"dark\", cols: 3 } satisfies Config;\n// config.theme is \"dark\" (literal), not string\n```\n\n## Boundary validation\n\nValidate once where data crosses in. Trust types inside. See the **boundary-discipline** principle skill.\n\n- **Wire formats** (proto, JSON-RPC): parse with `ignoreUnknownFields` so forward-compatible changes don't break old clients.\n- **Persisted JSON:** versioned blob with a try/catch around the parse.\n- **Don't re-validate** deep in call chains.\n\n## Schema-derived types\n\nWhen a `.proto`, OpenAPI spec, GraphQL schema, or database migration already defines a shape, derive from the generated types instead of duplicating them.\n\n```ts\n// Don't. Duplicate shape, drifts when the schema changes.\ntype CheckSummary = {\n  totalCount: number;\n  checks: { name: string; status: string }[];\n};\nfunction renderChecks(s: CheckSummary) {\n  /* ... */\n}\n\n// Do. Derive from the generated schema type.\nimport type { ChecksMessage } from \"<generated module>\";\nfunction renderChecks(s: Pick<ChecksMessage, \"totalCount\" | \"checks\">) {\n  /* ... */\n}\n```\n\nReach for `Pick`, `Omit`, `Parameters`, `ReturnType`, `Awaited`, `typeof` before writing a new interface.\n\n## Object args\n\n```ts\n// Don't. Swap two args, still compiles.\nopenFile(uri, {\n  startLineNumber: 10,\n  startColumn: 1,\n  endLineNumber: 10,\n  endColumn: 1,\n});\n\n// Do. Order-independent, self-documenting.\nopenFile({\n  uri,\n  selection: {\n    startLineNumber: 10,\n    startColumn: 1,\n    endLineNumber: 10,\n    endColumn: 1,\n  },\n});\n```\n\nSkip on hot paths: per-frame render, tokenizers, parsers, anything in a tight loop where the allocation cost matters.\n"}}
