Skip to content

feat: add one error envelope and code registry - #102

Merged
keyurgolani merged 7 commits into
nextfrom
feat/01.2-envelope
Oct 20, 2026
Merged

keyurgolani merged 7 commits into
nextfrom
feat/01.2-envelope

Conversation

@keyurgolani

@keyurgolani keyurgolani commented Oct 20, 2026 •

Copy link
Copy Markdown
Owner

Implements CHECKMATE-01.2 · envelope
Refs #30

What changed

  • src/lib/api/error-envelope.ts builds { success: false, error: { code, message, details?, timestamp, correlationId } }. errorResponse sends it with the code's registry status, and server actions return errorEnvelope, the same object without a status. correlationId is generated until 02.1 sessions ([CHECKMATE-02.1] Introduce server-mediated session and assurance policies #32) passes one, and a malformed one is replaced. NOT_FOUND and CAPABILITY_INVALID take no message, details or headers, in the types and at runtime, so a NOT_FOUND for a hidden target matches one for a missing target apart from timestamp and correlationId. Outcome codes return the success body with a top-level code.
  • src/lib/api/error-codes.ts has the registry, one HTTP status and default copy per code, and the legacy map keyed by (legacy code, status, returning file, HTTP method). The map has 379 rows for all 119 codes on next: 108 *ErrorCodes members and 11 literal codes, RUN_SYNC_REMOVED included. Where one method sends one code for two meanings, each row names a reason.
  • Each service types its error code as its *ErrorCodes union, so the scan sees which codes a route forwards. Apart from types, TemplateErrorCodes gains DUPLICATE_FAILED for the literal code duplicate() returned, and three no-explicit-any errors in item.ts and llm.ts are fixed.
  • error-codes.test.ts scans src/ with the TypeScript checker. The scan is in src/test/error-code-scan.ts, with fixture tests for status switches, the JSON helpers, withAuth and forwarded codes.
  • codeless-error-bodies.ts lists the merge-time 68 codeless error bodies in 12 files, and 21.3 async states ([CHECKMATE-21.3] Standardize truthful async, stale, degraded, conflict, and recovery states #91) owns it. The test fails when a file's count changes. scripts/ci/check-shrinking-lists.mjs runs in the lint job and fails a change that raises a count or adds a file, compared with the merge base.
  • docs/architecture/decisions/denial-semantics.md records the decision.

No route moves onto the envelope. 21.3 async states does that.

Why

Denials come back in six shapes, and a code doesn't say what happened. withAuth sends TEMPLATE_003 with 401, and AUTH_001 means both a wrong password and no session. 02.1 sessions, 03.1 memberships (#35), 11.1 commands (#59) and 21.3 async states build on one envelope with one status per code.

Verification

Against origin/next at 1ff2762, the merge of 01.1 contracts (#101):

  • eslint on the 25 changed files (scripts/ci/lint-changed.mjs): 0 errors, no eslint-disable. The 13 warnings are ones next already has in those files.
  • npm run lint: 38 errors, 48 warnings. origin/next has 41 and 48, and the three fewer are the no-explicit-any fixes.
  • npx tsc --noEmit: 0 errors, same as origin/next.
  • npm test on the fixture: 665 tests in 38 files pass, none skipped, 43 of them new.
  • npm run build with PocketBase at http://127.0.0.1:9: passes.
  • CI aggregate passes with all seven jobs run.

Each of these fails a test: deleting the CIRCULAR_REFERENCE case from the items route's status switch, so ITEM_011 falls to 500; sending the visibility route's forwarded codes at 418; sending AUTH_004 at 403 through jsonResponseWithLogout; registering a code at 999; a map row for a response its file doesn't send; sending a reserved code; a live registry code nothing sends or maps to; raising a codeless count; and turning off NOT_FOUND concealment. Outside routes and the proxy, the scan skips a send whose code or status it can't pin down.

Decisions and owner steps

  1. This registers every code on next today, and the test fails on a code that's neither registered nor mapped. The registry also reserves the codes the public issues of 00.1 storage rules ([CHECKMATE-00.1] Replace permissive PocketBase rules with a default-deny authority matrix #25), 00.2 secret store ([CHECKMATE-00.2] Move provider credentials into encrypted server-custodied secret references #26), 00.4 logger ([CHECKMATE-00.4] Rotate defaults and add emergency security regression gates #28) and 18.2 ledger ([CHECKMATE-18.2] Introduce ordered schema migrations and rebuildable projections #81) define, at the statuses those issues give. Sending a reserved code fails the test until its leaf drops the reservation.
  2. Map rows where a route answers a target the actor can't see go to NOT_FOUND, per the denial semantics.
  3. AUTH_001 stays the wrong-password code because 02.1 sessions keeps it, and maps to AUTH_REQUIRED in the llm and relay routes. IMPORT_009 maps to UNSUPPORTED_VERSION, as 16.1 schemas ([CHECKMATE-16.1] Publish canonical versioned package, workflow, and proof schemas #74) says. Its copy is generic, since 08.2 schedules ([CHECKMATE-08.2] Add timezone-safe schedules, recurrence, due policy, and escalation #51) also returns it for unknown rule semantics. ITEM_011 maps to 07.1 run creation's ([CHECKMATE-07.1] Implement idempotent transactional run creation #47) REFERENCE_CYCLE (422), since the step editor branches on it.
  4. 14.1 adapters ([CHECKMATE-14.1] Create provider adapters, capability negotiation, and safe secret custody #68) and 14.3 receipts ([CHECKMATE-14.3] Add invocation receipts, budgets, cancellation, and provider health #70) define no code for a provider's rate limit, so LLM_007 and WEB_005 map to RATE_LIMITED. The record widens it to an upstream provider's limit, with details.source saying which.
  5. UNCHANGED (200) and POLICY_UNAVAILABLE (503) are reserved for 11.1 commands, and UNCHANGED gives the outcome path a real code to test. 02.1 sessions registers SESSION_EXPIRED, SESSION_REVOKED, SESSION_LEGACY, REAUTH_REQUIRED and CSRF_REJECTED, and the test pins their statuses for when it does.

No owner steps.

@sourcery-ai

sourcery-ai Bot commented Oct 20, 2026

Copy link
Copy Markdown

Sorry @keyurgolani, you've used your own review budget of 250,000 diff characters for the last 7 days.

You can request another review in 6 days and 20 hours by commenting @sourcery-ai review. Upgrade to get a review now.

@sourcery-ai

sourcery-ai Bot commented Oct 20, 2026

Copy link
Copy Markdown

Reviewer's Guide

This PR establishes the error-envelope foundation without migrating existing routes: a typed registry-driven envelope and outcome API, a file- and status-aware legacy compatibility map, source-scan enforcement for all current codes and codeless bodies, and an architecture decision defining denial semantics for follow-up migrations.

Sequence diagram for registry-driven error responses

sequenceDiagram
    participant Route
    participant ErrorEnvelope
    participant Registry
    participant Client

    Route->>ErrorEnvelope: errorResponse(code)
    ErrorEnvelope->>Registry: read ERROR_CODES[code]
    Registry-->>ErrorEnvelope: status and default message
    ErrorEnvelope->>ErrorEnvelope: generate timestamp and correlationId
    ErrorEnvelope-->>Client: HTTP response with error envelope and registry status
Loading

Sequence diagram for legacy error-code compatibility

sequenceDiagram
    participant LegacyRoute
    participant LegacyMap
    participant Registry
    participant Client

    LegacyRoute->>LegacyMap: mapLegacyCode(code, status, file)
    LegacyMap-->>LegacyRoute: registry code
    LegacyRoute->>Registry: errorResponse(registryCode)
    Registry-->>LegacyRoute: registered status and message
    LegacyRoute-->>Client: standardized error envelope
Loading

Flow diagram for concealment and outcome semantics

flowchart TD
    Input[Caller supplies code and options] --> Kind{Registry code kind}
    Kind -->|Error code| Error[Build success false envelope]
    Kind -->|Outcome code| Outcome[Build success true body with top-level code]
    Error --> Conceal{NOT_FOUND or CAPABILITY_INVALID}
    Conceal -->|Yes| DefaultCopy[Use registry copy and omit details]
    Conceal -->|No| CallerCopy[Allow caller message and details]
    DefaultCopy --> Response[Return with registry status]
    CallerCopy --> Response
    Outcome --> OutcomeResponse[Return with registry status]
Loading

File-Level Changes

Change Details Files
Introduces a typed error and outcome response builder with registry-driven status, messages, request metadata, concealment, and validation rules.
  • Builds standardized error envelopes for routes and status-free equivalents for server actions.
  • Generates timestamps and correlation IDs, while allowing supplied correlation IDs and response headers.
  • Conceals caller-provided messages and details for NOT_FOUND and CAPABILITY_INVALID.
  • Adds typed outcome bodies with top-level codes and runtime rejection of invalid or mismatched codes.
  • Adds focused tests for response shape, status, concealment, metadata, headers, outcomes, and compile-time constraints.
src/lib/api/error-envelope.ts
src/lib/api/error-envelope.test.ts
Adds a centralized registry for current error and outcome codes plus a comprehensive compatibility map for legacy usages.
  • Defines one HTTP status and default message for each registered code, including UNCHANGED and RUN_SYNC_REMOVED.
  • Maps legacy codes by code, status, and returning or producing file to preserve existing semantics.
  • Covers differing meanings for shared legacy codes such as TEMPLATE_003 and AUTH_001.
  • Separates response-carried legacy codes from codes currently produced only in process.
src/lib/api/error-codes.ts
Adds static source analysis tests that enforce registry coverage and prevent untracked changes to legacy or codeless error behavior.
  • Scans TypeScript source for ErrorCodes members, literal codes, fixed-status responses, status switches, and codeless bodies.
  • Verifies all discovered codes are registered or explicitly mapped, legacy entries are current, and mapped files exist.
  • Pins denial statuses and ownership expectations for this slice and future work.
  • Maintains the merge-time inventory of 68 permitted codeless bodies across 12 application files.
src/lib/api/error-codes.test.ts
src/test/error-code-scan.ts
src/lib/api/codeless-error-bodies.ts
Documents the accepted denial semantics and the migration boundaries for subsequent envelope adoption.
  • Records entity-neutral denial codes, fixed statuses, concealment behavior, bulk semantics, and policy failure handling.
  • Documents legacy compatibility and ownership of future proxy, route, and server-action migrations.
docs/architecture/decisions/denial-semantics.md

Possibly linked issues


Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

error-envelope.ts builds { success: false, error: { code, message,
details?, timestamp, correlationId } } and sends it with the code's one
status from error-codes.ts. Server actions return the same object
without a status, and outcome codes return the success body with a
top-level code. NOT_FOUND and CAPABILITY_INVALID bodies never vary.

The legacy map keys every code that predates the registry by (legacy
code, status, returning file), so each use of TEMPLATE_003 or AUTH_001
maps to one code.

Refs #30
error-codes.test.ts scans src/ with the TypeScript checker. Every
*ErrorCodes member and literal error code must be registered or in the
legacy map, every response that pairs a fixed code with a fixed status
must be mapped, and codeless error bodies under src/app must match the
merge-time list #91 owns, which only shrinks.

Refs #30
Each service types its error code as its *ErrorCodes union, so the scan
resolves a forwarded result.error.code, and it reads the route's status
function, default arms, braced clauses and fall-through included. Every
legacy row is keyed by (code, status, file, method), with a reason where
one method sends one code for two meanings, and must match a response
the scan finds. Not-visible rows map to NOT_FOUND.

The registry reserves the codes the public issues of 00.1, 00.2, 00.4
and 18.2 define. SIGNUP_DISABLED stays a live code.

Refs #30
…tion IDs

NOT_FOUND and CAPABILITY_INVALID take no headers, in the types and at
runtime, so only timestamp and correlationId vary. A supplied
correlationId that isn't 1 to 128 safe characters is replaced with a
generated one.

Refs #30
The lint job compares src/lib/api/codeless-error-bodies.ts with its
copy at the merge base and fails a raised count or an added file.

Refs #30
@keyurgolani
keyurgolani merged commit 113a544 into next Oct 20, 2026
10 checks passed
@keyurgolani
keyurgolani deleted the feat/01.2-envelope branch October 20, 2026 14:17
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant