Skip to content

feat(api): one wire contract for server, CLI and docs, with --json on every command - #82

Merged
allisonmahmood merged 3 commits into
mainfrom
feat/api-package
Aug 28, 2026
Merged

allisonmahmood merged 3 commits into
mainfrom
feat/api-package

Conversation

@allisonmahmood

Copy link
Copy Markdown
Owner

Request and response shapes lived only implicitly in apps/server/src/app.ts; the CLI and its test stubs re-typed them by hand, only status had --json, and there was no API reference an agent could read before calling a route. Closes #71.

Now there is one place the wire is described. packages/api (@patchy/api) holds one Schema.Class per wire shape, the HttpApi (auth and patches groups under /api), the bearer middleware definition with today's 401 body, and the derived client. Fastify decodes bodies and encodes responses through those schemas at the route boundary (apps/server/src/wire.ts, interim until the router ports); the CLI decodes through the same schemas. The wire renames draft → patch here — paths, fields, codes, messages — so agents see one break, not two; tables, code and CLI text keep draft until the patches port. Every CLI command takes --json: one stdout document on success, { ok: false, error } on stderr on failure. docs/API.md is rendered from OpenApi.fromApi(PatchyApi) and pinned by a test that fails on drift; ADR-0002 records why the contract lives beside neither context.

Verified with lint, typecheck, the full suite and the packed-CLI e2e against a real server.

Written by Claude Fable 5 in Claude Code.

allisonmahmood and others added 2 commits August 29, 2026 01:22
New packages/api (@patchy/api): one Schema.Class per wire shape, the HttpApi
with its auth and patches groups under /api, the bearer middleware definition
with today's 401 body, and the derived HttpApiClient. The wire renames
draft -> patch here (paths, fields, codes, messages); tables and code keep
draft until the patches port.

Fastify decodes bodies and encodes responses through the schemas at the route
boundary (apps/server/src/wire.ts); no handler is rewritten. The CLI decodes
through the same schemas, caches patchId in drafts.json, and takes --json on
every command: one stdout document on success, { ok: false, error } on stderr
on failure.

docs/API.md is rendered from OpenApi.fromApi(PatchyApi) by a small renderer in
packages/api and pinned by a test. ADR-0002 records why the contract lives
beside neither context.

Closes #71.

Co-Authored-By: Claude Fable 5 <[email protected]>
Review follow-up on #71: the body-limit 413 and malformed-JSON 400 left the
error handler raw while every route went through @patchy/api; now they use
PayloadTooLarge and BadRequest. Also folds the repeated optional-text field
schema into one OptionalText.

Co-Authored-By: Claude Fable 5 <[email protected]>
@github-actions github-actions Bot added area:server Touches the server area area:ci CI, shared testing infrastructure, development scripts and tooling area:cli Touches the cli area area:docs Touches the docs area size:l 501-1,000 changed lines labels Aug 28, 2026
@allisonmahmood

Copy link
Copy Markdown
Owner Author

Code review (PR 82 × #71)

Two-axis review of origin/main...feat/api-package (170582c, 293febf), plus the extra questions: does this match #71's intent, is the method right, and is it YAGNI-shaped.

Intent vs what shipped

#71's bet: stop the wire living as implied Fastify JSON with CLI/stub copies. One @patchy/api contract, used by server, CLI, and docs; one draft → patch break; --json uniform; Fastify a thin decode/encode seam so the Effect router can drop in later.

That bet mostly landed. Agents get docs/API.md generated from PatchyApi, --json on every existing command, and a single wire rename. Tables and human CLI copy still say draft, as asked.

Where intent and checklist diverge even though the ticket can still be ticked:

  • HttpApi is a specification the live server does not run. Traffic is still Fastify. That is the ticket's interim, not a surprise — but docs/API.md will lie anywhere the spec and Fastify disagree (see Spec).
  • CLI still fetches. makeClient is inventory for the CLI port. Correct for this ticket; it is not "the CLI now speaks the HttpApi."
  • --json is not "exactly the api shape" except on whoami and upload. auth set / validate print CLI-local documents. Mint still reads body.token by hand.
  • Existing drafts.json entries with draftId become invalid with no migration. Republish of a cached file fails until the operator deletes the cache.

A publishing agent got machine-readable stdout/stderr and a real API reference. It did not get a typed client, a single noun, or delete (#41 still open — out of scope here). #35 is already closed; "close as superseded" is a no-op.

Method

Sound, with caveats. This is the method #71 asked for, not a lookalike.

Defining the full HttpApi now, unused by the live router, is the right cut. Schemas-only would starve OpenApi.fromApi and the derived client, and the handler port would invent a second contract. CurrentIdentity / Authorization are the prototype's middleware definition (requires: never), not live services with a fake make.

Adapter thickness is right. wire.ts sendWire / decodeBody sit at the route boundary; business logic stayed. They used decodeUnknownResult instead of the ticket's decodeUnknownSync so a bad html vs patchId keeps today's 400 copy — slightly thicker than the one-liner, better. Keeping CLI on fetch is correct; switching to HttpApiClient would pull runPromise into Commander, which is the CLI port.

Caveats on method, not nits: the markdown renderer lives in src/markdown.ts with a thin scripts/ writer (ticket said scripts/); every /api/* return was retargeted onto sendWire (the route surface moved, the handlers did not); protectedErrors is copied onto every protected operation, so OpenAPI over-declares 414/403/404 on routes Fastify never answers that way; path PatchId implies 400 on a bad id, Fastify still 404s.

YAGNI

This is the smallest step that makes the contract unsurprising. Dual sources of truth (HttpApi spec vs Fastify) are the cost of the interim, not extra architecture.

What to leave alone: unused makeClient (~30 lines, ticket-required), failure() for refusals as structs (keeps _tag off the wire), UploadCreated/UploadUpdated sharing fields, OptionalText, the drift test on docs/API.md.

What not to grow: the markdown renderer (METHOD_ORDER already lists unused put/patch), a live Effect server beside Fastify, collapsing sendUnauthorized et al. into a status/message table.

The jsonOutput module let is fine for a one-shot process. The real hole is Commander errors before the action, which never set it, so patchy upload --json with a missing file is still plaintext. That is the YAGNI-adjacent bug: a flag that claims uniformity and then doesn't cover parse failures.


Standards

(a) Documented standards

  • packages/api/src/client.ts (hard) — named import of Authorization at a service boundary. [effect-service-conventions: Imports and module namespaces]. Expected: namespace-import the module (import * as Api from "./api.js", then Api.Authorization). Named @patchy/api imports are for package consumers, not this internal seam.

  • packages/api/src/api.ts (CurrentIdentity / Authorization) (judgement) — they share api.ts with PatchyApi; no make/layer. [Service definition / File layout]. ADR-0002 overrides splitting/construction: this is the bearer definition (requires: never); the server still authenticates in Fastify. Do not add a dummy make.

  • packages/cli/src/index.ts (mintPublishingToken) (hard) — mint success is typeof body.token === "string", not MintedToken. [ADR-0002 §1]: the CLI decodes what it reads through the schemas. Decode with MintedToken like whoami/upload.

  • apps/server/src/app.ts error handler (judgement) — 400/413 go through schemas, then reply.status(statusCode).send({ ok: false, error: message }) for other /api/* failures (500, 415, …). ADR-0002 §1 wants every /api/* body encoded through schemas.ts. Comment claims the carve-out; add a refusal struct or leave until the router port.

  • packages/api/src/*.test.ts (judgement) — from "vitest" not @effect/vitest. [Port shapes / Tests]. Sync schema/docs pins have no layer; it.effect would be ceremony. Import from @effect/vitest only if the package is held to the port test shape.

Suppressed (repo wins): no Schema.TaggedError on wire refusals (ADR-0002 §3 + skill wire rule); unused makeClient (ADR-0002 includes the derived client; CLI port is later); new packages/api (#56 / ADR, two consumers).

(b) Baseline smells (always judgement)

  • Duplicated Code — decodeBody (apps/server/src/wire.ts) and decodeWire (packages/cli/src/index.ts) both wrap Schema.decodeUnknownResult. Same for protection/paths: Authorization on PatchyApi vs Fastify protectedApi(). Accept until HttpApiBuilder deletes wire.ts.

Spec

Quoted against #71.

(a) Missing / partial

  • Renderer location. Spec: "docs/API.md rendered … by a small local markdown renderer in packages/api/scripts/." The writer is packages/api/scripts/render-api-md.ts; the renderer is packages/api/src/markdown.ts. Drift test exists.

  • Named adapter APIs. Spec: "Schema.decodeUnknownSync / encodeSync at the route boundary." Encode is encodeSync; decode is decodeUnknownResult in wire.ts and the CLI.

  • Round-trips don't pin every shape. Spec: "pin schemas with decode/encode round-trip tests." schemas.test.ts covers UploadRequest, PatchId, UploadCreated, Identity, InvalidHtml, RateLimited, PatchQuotaExceeded, ModeratedPatch — not MintedToken, CreatedToken, RevokedToken, PatchView, PrincipalPatches, Ok, Pinned, Unauthorized, etc.

  • CLI uses three schemas only. Spec: "one schema per wire shape used by server, CLI and docs"; "printing exactly the api shape." whoami/upload encode Identity / UploadCreated|Updated. auth set is { ok: true, instanceUrl }, validate is { ok: true, warnings }. Failures flatten to { ok: false, error } (kind deferred, as specified). HttpApiClient is exported, unused by the CLI (allowed this ticket). Commander parse errors never set jsonOutput, so they stay plaintext even with --json.

  • #35. Done-when: "feat: --json on every command with shared Effect Schema wire types and docs/API.md #35 closed as superseded." Already closed; this PR only closes feat(api): wire schemas, HttpApi and --json on every command #71. delete not required (feat(cli): patchy delete #41 still open).

(b) Scope creep

  • CONTEXT-MAP.md — one extra "Contract" bullet; spec asked only for the ADR.
  • 414 on the contract. Spec listed error codes "400/401/403/404/409/413/429." RequestTargetTooLong (414) is on every protected HttpApi operation. Live Fastify 414s only overlong /api/patches/:patchId…. OpenAPI therefore over-declares.

(c) Looks implemented, looks wrong

  • 401 string not in the schema. Spec: "the 401 body pinned as today's { ok: false, error: \"Missing or invalid API token.\" } (plain Schema.Struct + HttpApiSchema.status(401), no _tag)." Shape matches the prototype (error: Schema.String); the literal lives only in sendUnauthorized in app.ts. Docs don't pin the sentence.

  • Not every JSON reply is schemed. Spec: "Fastify decodes and encodes through these schemas." Route replies and Fastify's own 400/413 use sendWire; setErrorHandler still raw-sends other statuses (e.g. 500).

  • drafts.json rename is fail-closed. Spec: "update the CLI (drafts.json cache keys included)." Cache requires patchId only; an existing draftId file is "invalid," so re-upload of cached pages breaks with no migration.

  • Path params vs live 404. params: { patchId: PatchId } implies 400 on a bad id. Fastify does not decode path params; unknown/malformed ids 404 "Patch not found." The generated API.md will teach the HttpApi answer, not the live one.

  • Stricter bodies than today. Non-string filename / metadata / token name/scopes / disable reason used to coerce; now 400. Extra draftId on upload is dropped, so an old client creates instead of updating (the intended wire break, but a silent one if anyone still sends draftId).


Summary: Standards 2 hard + 4 judgement (worst: mint still hand-reads body.token, against ADR-0002). Spec ~5 partial + 2 creep + 5 wrong-looking (worst: existing drafts.json with draftId fail-closes, so republish of a cached file breaks). Method is sound; YAGNI holds. I would not block on the named-import or vitest harness, I would want the cache break and the HttpApi-vs-Fastify 414/path-id drift called out or fixed before merge.

Reviewed by Grok 4.6 in Grok Build.

Review follow-up on #82: the mint reply decodes through MintedToken instead
of reading body.token by hand; a Commander parse error under --json is one
stderr document like every other failure; a drafts.json entry still keyed
draftId keeps updating its page and is rewritten as patchId; a client still
sending draftId gets a 400 naming the rename instead of a silent create; the
401 sentence is pinned in the schema; 414 is declared only on the routes
Fastify answers it from, and path ids are plain strings so the reference
matches the live 404; client.ts namespace-imports its own module; every wire
shape has a round-trip test.

Co-Authored-By: Claude Fable 5 <[email protected]>
@allisonmahmood

Copy link
Copy Markdown
Owner Author

Thanks — worked through the review. Fixed in d43449c:

  • Mint hand-read body.token → decodes through MintedToken like whoami/upload.
  • Commander parse errors bypassed --json → jsonOutput is read from argv before parsing, so patchy upload --json with no file is { ok: false, error } on stderr like every other failure. Test added.
  • Old drafts.json entries fail-closed → an entry still keyed draftId is read as the same page and rewritten as patchId on the next upload, so nothing already published stops updating. Test added.
  • A client still sending draftId silently created a new patch → 400 naming the rename instead. Test added.
  • 414 / path PatchId over-declared vs the live server → 414 now only on the /api/patches/:patchId… routes Fastify answers it from; path params are plain strings, so API.md matches the live 404 rather than implying a 400.
  • 401 sentence lived only in app.ts → pinned as a Schema.Literal in Unauthorized; the reference now shows it and nothing else can go out at 401.
  • Named import in client.ts → namespace import of its own module.
  • Round-trips didn't pin every shape → every wire shape now has one.

Left as is, on purpose:

  • Renderer in src/, writer in scripts/ — the drift test has to import the renderer, which it can't do from scripts/. The ticket's intent (small, local, pinned) holds.
  • decodeUnknownResult rather than decodeUnknownSync — same seam, but the failing field is what keeps today's separate 400 copy for a bad html vs a bad patchId.
  • Raw setErrorHandler for other statuses (500, 415) — those are Fastify's, not the contract's; the router port deletes this handler along with wire.ts.
  • vitest rather than @effect/vitest in packages/api — sync schema pins with no layer; it.effect would be ceremony.
  • Stricter bodies (non-string filename, scopes, reason now 400 instead of coercing) — that's the contract doing its job; the accepted wire break.
  • CONTEXT-MAP.md entry — one line so the map doesn't omit a package both contexts import.
  • feat: --json on every command with shared Effect Schema wire types and docs/API.md #35 — already closed; nothing to do.

CI green on the first two commits; waiting on the run for d43449c before merge.

@allisonmahmood
allisonmahmood merged commit 4e43ef5 into main Aug 28, 2026
7 checks passed
@allisonmahmood
allisonmahmood deleted the feat/api-package branch August 28, 2026 23:57
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:ci CI, shared testing infrastructure, development scripts and tooling area:cli Touches the cli area area:docs Touches the docs area area:server Touches the server area size:l 501-1,000 changed lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(api): wire schemas, HttpApi and --json on every command

1 participant