How-to › Describe your API

How to repair a spec that a generator rejects with a coding agent#

Turn each generator complaint into a Spectral rule, hand a coding agent the findings instead of a stack trace, and guard the repair against deleted operations.

Audience
API producer
Level
intermediate
Topic
Author or repair a spec with a coding agent
Languages
TypeScript
Verified

Read first: Set up a Spectral lint loop for an agent editing OpenAPI

Your OpenAPI document passes its structural check, but the SDK build fails. openapi-typescript stops with a Node stack trace about a $ref. NSwag prints a .NET one and exits 255. sdkgen exits 0 and types a field any. You paste a trace into a coding agent, and it deletes the operation the trace names.

What you get

You will end up with a Spectral ruleset that reproduces each generator complaint, a prompt that hands an agent the findings, and a guard that fails a destructive repair. This is for you if a generator rejects a spec you own.

Short answer

To repair an OpenAPI document that an SDK generator rejects, write a Spectral rule for each complaint the generator made. Give a coding agent the lint findings instead of the stack trace. Each finding carries a line, a rule, and a path, so the agent edits the document where the fault is. Before merging, run a guard that fails when an operation or a required field is gone, then regenerate and compile the SDK.

You will need

Node 22.12 or later, an OpenAPI 3 document that a generator rejects, and a coding agent such as Claude Code. The hook that lints every edit the agent makes is covered in set up a Spectral lint loop for an agent editing OpenAPI.

No model was called for this page: the three candidate repairs under candidates/ were written by hand. The Spectral packages report each install to Scarf, and Redocly CLI sends usage data on each run. The sample turns both off, in package.json and redocly.yaml.

Approaches compared

ApproachWhen it fitsWhat it costs youWhen to pick something else
NSwagC# or TypeScript clients, and a hard stop on a dangling reference with no configurationNo command that checks a document, one dangling reference reported per run, and a duplicated id renamed without commentAn agent or a person edits the document by hand, so a linter has to run first
openapi-typescript and openapi-fetchTypeScript callers, and you want the generator itself to refuse a bad documentRedocly rules only, and a duplicated id is accepted until redocly.yaml raises that rule to errorYou ship clients in more languages than TypeScript
Redocly CLI lintYou bundle with Redocly already, or openapi-typescript writes your types and reads the same fileIts one-line format reports a dangling reference as Can't resolve $ref, with no target to search forThe agent’s hook already runs Spectral, or you extend published Spectral rulesets
sdkgenYou want the build to survive a rough document, with warnings in a file to read afterwardsExit status 0 on all three faults here, so a field typed any ships unless another check runsThe generator run is your only gate, where a tool that stops is safer
SpectralOne ruleset has to stand in for several generators, with findings an agent can act onA second statement of what each generator accepts, which drifts when a generator changesYou run one generator and it reads lint rules itself, as openapi-typescript does

Voxgig maintains sdkgen. It is one of five options here, not the recommendation.

The three generators disagree about one document. openapi-typescript and NSwag stop on a dangling reference, though NSwag reports a single one per run. sdkgen stops on nothing, which keeps a build alive and hides a fault. By default, no generator here objects to a duplicated id. A linter states all of that in one place, at the price of a ruleset that tracks each generator.

Capture what sdkgen says and what it leaves out

openapi.yaml describes a Billing API with seven operations and three faults. The payments list refers to a parameter component invoiceId, which is spelled InvoiceId. GET /customers/{customerId} carries the operationId of the invoice fetch. The third fault is a schema that was renamed:

    Invoice:
      type: object
      required: [id, customer, total, status]
      properties:
        id:
          type: string
        customer:
          $ref: '#/components/schemas/Client'

Scaffold an sdkgen project from the document, then run npm run generate in .sdk. generate.sh did that once, and what each run logged and wrote is committed under sdkgen/, because generating installs packages.

npx --yes @voxgig/create-sdkgen@0.31.9 billing --def openapi.yaml --target ts
cd billing-sdk/.sdk

inspect.mjs reads the recorded log and the types that run wrote.

node inspect.mjs openapi.yaml
sdkgen 4.44.3 with apidef 8.32.4, recorded by generate.sh
document      exit  warnings  operations  Invoice.customer  apidef finished with
openapi.yaml  0     2         7           any               PARTIAL BUILD! There were 2 warnings (see above).

openapi.yaml, the warnings apidef logged
  Parameter with no name on entity=payment op=list path=/invoices/{invoiceId}/payments is dropped: `$ref` "#/components/parameters/invoiceId" resolves to nothing. A parameter needs a `name`, or a reference that resolves to one.
  Path placeholder {invoiceId} on entity=payment op=list path=/invoices/{invoiceId}/payments has no declared parameter, so it is taken as a required string.

sdkgen did not reject the document. Its model step, apidef, is built to fail soft. It logged two warnings for the dangling parameter, called the run a partial build, wrote both to .sdk/apidef-warnings.txt, and exited 0. The dangling schema reference appears in no log, only in the output, where Invoice.customer is any. The duplicated id changed nothing: sdkgen named this SDK’s entities and methods from its paths, and the types it wrote are identical with the duplicate and without it.1

That run reported one fault in three.

Write one rule for each complaint

A rule runs without the generator. The OpenAPI ruleset that Spectral ships covers two of the three faults, so the file switches that ruleset off and turns back on only what a generator trips over. The third fault gets a rule of its own.

extends: [[spectral:oas, off]]
rules:
  # The structural check. A dangling $ref needs no entry beside it: Spectral's resolver
  # reports one as invalid-ref whatever rules are on.
  oas3-schema: error
  # NSwag names the second method getInvoice2, and openapi-typescript writes the key twice.
  operation-operationId-unique: error
  # sdkgen: "Path placeholder {invoiceId} ... has no declared parameter".
  path-params: error
  # No generator objects to a property with no type. sdkgen and NSwag emit any for it and
  # openapi-typescript emits unknown, which is how a schema loosened to {} gets through.
  property-declares-a-type:
    description: A property schema names a type, a $ref or a composition
    message: "{{property}} names no type, $ref or composition, so no generator can type it; describe the value instead of emptying the schema"
    given: "$..properties[*]"
    resolved: false
    severity: error
    then:
      function: schema
      functionOptions:
        schema:
          type: object
          anyOf:
            - required: [type]
            - required: ["$ref"]
            - required: [oneOf]
            - required: [anyOf]
            - required: [allOf]
npx spectral lint openapi.yaml
  66:20  error  operation-operationId-unique  Every operation must have unique "operationId".                                                      paths./invoices/{invoiceId}.get.operationId
  78:9   error  path-params                   Operation must define parameter "{invoiceId}" as expected by path "/invoices/{invoiceId}/payments".  paths./invoices/{invoiceId}/payments.get
  82:17  error  invalid-ref                   '#/components/parameters/invoiceId' does not exist                                                   paths./invoices/{invoiceId}/payments.get.parameters[0].$ref
 143:17  error  invalid-ref                   '#/components/schemas/Client' does not exist                                                         components.schemas.Invoice.properties.customer.$ref

✖ 4 problems (4 errors, 0 warnings, 0 infos, 0 hints)

Four findings cover three faults, because lines 78 and 82 are the same parameter. invalid-ref is nowhere in the file: the Spectral resolver reports it with every rule switched off. Each invalid-ref line names its missing target, such as #/components/schemas/Client, which an agent can search the document for. resolved: false makes the custom rule read the document as written.

Redocly CLI reaches the same four findings from redocly.yaml, under no-unresolved-refs, operation-operationId-unique, and path-parameters-defined. Its configurable rule for an untyped schema is shorter than the Spectral one, because it selects every Schema node by type instead of by JSONPath. Its default format prints the source lines around each finding, at ten lines or more apiece. Its one-line format prints Can't resolve $ref with no target.

Hand the agent the findings and guard what comes back

The prompt names two commands and what the agent may not do.

Repair `openapi.yaml`. A generator rejects it, and the fault is in the document.

1. Run `npx spectral lint openapi.yaml`. Each finding gives a line, a rule, and a path. The rules
   are in `.spectral.yaml`. Read that file; it is the only statement of them.
2. Fix each finding in the document, at its cause. A `$ref` that does not exist points at a
   name that moved, so find the name it has today. Of two operations sharing an `operationId`,
   one is misnamed: read both paths and summaries before you rename either.
3. Do not delete an operation, a property, or a `required` entry, and do not empty a schema
   to `{}`. If a finding cannot be fixed any other way, stop and say which one.
4. Lint again until no error is left. Then run `node guard.mjs base.yaml openapi.yaml`, where
   `base.yaml` is the document as committed. If the guard fails, put back what it names.

The agent runs the linter itself, so it reads fresh findings after each edit. What it returns is checked twice: by the ruleset, and by a guard that deleting cannot satisfy. guard.mjs reads both files as data, resolves nothing, and compares what they declare.

export function compare(base, candidate) {
  const ops = { base: new Set(operations(base)), candidate: new Set(operations(candidate)) }
  const req = { base: new Set(requiredFields(base)), candidate: new Set(requiredFields(candidate)) }
  const missingOps = [...ops.base].filter((op) => !ops.candidate.has(op))
  const missingReq = [...req.base].filter((field) => !req.candidate.has(field))
  return {
    operations: { before: ops.base.size, after: ops.candidate.size, missing: missingOps },
    required: { before: req.base.size, after: req.candidate.size, missing: missingReq },
    ok: missingOps.length === 0 && req.candidate.size >= req.base.size,
  }
}

check.mjs runs both checks on the three candidates. partial.yaml is where generator output alone leads: both references repaired, the duplicated id untouched. destructive.yaml makes the errors go away. It deletes the operation that line 66 points at, empties customer to {}, and drops it from required. repaired.yaml changes three lines.

node check.mjs openapi.yaml candidates/*.yaml
candidate                    spectral                                guard
candidates/destructive.yaml  property-declares-a-type (line 129)     FAIL: lost GET /invoices/{invoiceId}, required fields 10 -> 9
candidates/partial.yaml      operation-operationId-unique (line 66)  ok
candidates/repaired.yaml     no errors                               ok

1 of 3 candidates passes both checks

Each check sees what the other cannot. The guard passes a property emptied to {} when required is left alone, because nothing was removed. The ruleset passes a deleted operation, because what remains is valid. Two tests hold both blind spots in place.

Make openapi-typescript refuse the document itself

openapi-typescript validates its input with Redocly’s engine before it writes types. ots.mjs runs it on a document, then compiles an openapi-fetch caller of GET /invoices/{invoiceId} against the types it wrote.

node ots.mjs openapi.yaml candidates/partial.yaml
openapi-typescript 7.13.0, typescript 5.9.3, no redocly.yaml

openapi.yaml
  generate: exit 1
    Can't resolve $ref at #/components/schemas/Invoice/properties/customer
    Can't resolve $ref at #/paths/~1invoices~1{invoiceId}~1payments/get/parameters/0
    and a Node stack trace

candidates/partial.yaml
  generate: exit 0, no message
  tsc caller.ts: exit 2
    caller.ts(9,82): error TS2353: Object literal may only specify known properties, and 'invoiceId' does not exist in type '{ customerId: string; }'.
    caller.ts(10,16): error TS2339: Property 'total' does not exist on type '{ id: string; name: string; email: string; }'.

It names both dangling references as JSON Pointers and stops.2 The duplicated id passes: the generator writes the getInvoice key twice. With skipLibCheck on, as tsc --init sets it, the only errors are in a caller that did nothing wrong. Its documentation says a redocly.yaml in the project root, or one named with --redocly, supplies the validation rules. So raise the rule there:

rules:
  struct: error
  no-unresolved-refs: error
  operation-operationId-unique: error
  path-parameters-defined: error
  rule/schema-declares-a-type:
    subject:
      type: Schema
    assertions:
      requireAny: [type, oneOf, anyOf, allOf]
    message: A schema names no type or composition, so no generator can type it
    severity: error
node ots.mjs --redocly redocly.yaml candidates/partial.yaml
openapi-typescript 7.13.0, typescript 5.9.3, --redocly redocly.yaml

candidates/partial.yaml
  generate: exit 1
    Every operation must have a unique `operationId`. at #/paths/~1invoices~1{invoiceId}/get/getInvoice
    and a Node stack trace

With that file the generator is its own gate, and npx redocly lint gives the agent the same findings with line numbers. A rule left at warn prints its message and still writes the types.

Lint before NSwag generates

NSwag has no command that checks a document. nswag help lists nine commands, and its command line page describes generators and a runner for configuration files, so the generator run is the only signal. record.sh ran NSwag once and kept what it printed.

$ nswag openapi2tsclient /input:openapi.yaml /output:openapi.ts
System.InvalidOperationException: Could not resolve the path '#/components/parameters/invoiceId'.
   at NJsonSchema.JsonReferenceResolver.ResolveDocumentReference(Object rootObject, String jsonPath, Type targetType, IContractResolver contractResolver)
   [23 more stack frames]
exit status 255

$ sed 's|parameters/invoiceId|parameters/InvoiceId|' openapi.yaml > second-run.yaml

$ nswag openapi2tsclient /input:second-run.yaml /output:second-run.ts
System.InvalidOperationException: Could not resolve the path '#/components/schemas/Client'.
   at NJsonSchema.JsonReferenceResolver.ResolveDocumentReference(Object rootObject, String jsonPath, Type targetType, IContractResolver contractResolver)
   [22 more stack frames]
exit status 255

Each message names a missing target, not the line that refers to it, and each run stops at the first.3 On partial.yaml NSwag exits 0 and settles the duplicate itself, with getInvoice(customerId: string) and getInvoice2(invoiceId: string). The C# client gets GetInvoice2Async. OperationGenerationMode decides where method names come from. All three of its documented values exit 0 on the duplicate.

So with NSwag the check has to run before the generator, and either ruleset here does it.

Check it worked

Regenerate, and read the row for each document.

node inspect.mjs
sdkgen 4.44.3 with apidef 8.32.4, recorded by generate.sh
document                     exit  warnings  operations  Invoice.customer     apidef finished with
openapi.yaml                 0     2         7           any                  PARTIAL BUILD! There were 2 warnings (see above).
candidates/partial.yaml      0     0         7           Record<string, any>  success
candidates/destructive.yaml  0     0         6           any                  success
candidates/repaired.yaml     0     0         7           Record<string, any>  success

sdkgen exits 0 on every row, the destructive one included, and the partial and repaired rows are identical. So a row confirms a repair only beside a clean lint and a passing guard: 0 warnings, 7 operations, Record<string, any> in place of any, and success. The SDK from the last run compiled with npm run build and passed the suite sdkgen generated with it. demo.mjs calls it against a stand-in server.

node demo.mjs
Customer().load({ id: 'cu_7' })         GET /v1/customers/cu_7          Ada Lovelace
Invoice().load({ id: 'in_1' })          GET /v1/invoices/in_1           open, 1200 cents, customer cu_7
Payment().list({ invoice_id: 'in_1' })  GET /v1/invoices/in_1/payments  2 payments, 1200 cents
node --test repair.test.mjs
1..27
# tests 27
# suites 0
# pass 27
# fail 0

When it goes wrong

The agent renames the wrong operation. Spectral and Redocly both point at line 66, the second use of getInvoice, which is the invoice fetch and correctly named. The misnamed operation is on line 24, so the prompt tells the agent to read both paths and summaries first.

apidef-warnings.txt is still there after the repair. A clean sdkgen run here left the earlier file in place, unchanged. Delete it before regenerating, and trust the generate-end line of the log.

oasdiff cannot review the repair. oasdiff breaking with openapi.yaml as its base exited 102, because it cannot load a document with a dangling reference. The guard covers this one change. From the repaired document on, --fail-on ERR takes over: against repaired.yaml, oasdiff reported 11 errors for the destructive candidate and exited 1.

When not to do this

Do not hand an agent a repair you can see whole. The fix here is three changed lines, and the lint output locates two of them outright. An agent earns its place when the findings run to dozens across several files.

Do not read sdkgen’s exit status as a verdict on the document. It exited 0 on all four documents here. If the generator run has to be the gate, openapi-typescript with a redocly.yaml is the better choice, because it stops and the linter reads the same rules. NSwag is the better choice on an ASP.NET Core API, where one toolchain writes the document from the controllers and the client from the document.

Do not weaken the guard to get a repair through. An operation that has to go is an API change for a person to approve, with a deprecation, not a lint fix.

Last verified

Verified 2026-11-19 against Node 22.23.5, @voxgig/create-sdkgen 0.31.9, @voxgig/sdkgen 4.44.3, @voxgig/apidef 8.32.4, @stoplight/spectral-cli 6.17.1, @redocly/cli 2.82.0, openapi-typescript 7.13.0, openapi-fetch 0.17.0, and TypeScript 5.9.3. Every output block is what the preceding command printed in the page’s code directory after npm ci. sdkgen was run by generate.sh: its logs, generated types, and compiled SDK are committed, and inspect.mjs and demo.mjs read them. NSwag 14.8.0 was run once on the .NET 10 runtime and its output committed as recorded/nswag.txt. oasdiff 1.39.0 was run once and its output committed as recorded/oasdiff.txt. No model was called.

Footnotes

  1. The OpenAPI Specification says an operationId MUST be unique among all operations described in the API. Three generators read a document that broke the MUST. One ignored the field, one appended a 2, and one wrote the key down twice. ↩︎ Back to text

  2. RFC 6901 writes a slash inside a key as ~1 and a tilde as ~0, which is how /invoices/{invoiceId}/payments becomes ~1invoices~1{invoiceId}~1payments. Section 4 tells the decoder to undo ~1 first, so that ~01 comes out as ~1 and never as a slash. ↩︎ Back to text

  3. NSwag’s command processor catches every exception, prints it, and returns -1. POSIX keeps the least significant 8 bits of an exit status, so the shell sees 255 whatever went wrong. ↩︎ Back to text

Read this page as markdown · All how-to guides

Generate the client instead of writing it#

Retries, timeouts, pagination and auth are the same problems in every client. Voxgig generates them from your OpenAPI description, in 23 languages, from one model.

Listen to Fireside, the Voxgig podcast

Since 2018, Richard Rodger has talked with developer advocates, event organizers, and the people who build developer-facing companies about the specifics of the work.