# Stored procedures

db2kit reads each procedure from the Db2 catalog and generates a typed descriptor. The descriptor holds the catalog facts a `CALL` needs: parameter order, mode, type, exact length, nullability, data access, commit behavior. `db.call` uses it to build the `CALL`, check the input before any network call, and read the outputs. An outcome rule, written by the application team, decides from the outputs whether the call succeeded.

## Workflow

```sh
npx db2kit describe MYSCHEMA.MY_PROC            # read the catalog, print Markdown, write nothing
npx db2kit generate MYSCHEMA.MY_PROC OTHER.PROC # write the descriptors, record them in the manifest
npx db2kit generate 'MYSCHEMA.*' -t procedure   # every procedure of the schema (-y above 50)
npx db2kit generate                             # regenerate everything the manifest lists
npx db2kit check                                # CI: exit code 1 if a file differs from the catalog
```

Every command connects in read-only mode: only `SYSIBM.SYSROUTINES` and `SYSIBM.SYSPARMS` are read, the procedure is never called.

A name without schema works when exactly one schema holds a procedure with that name. Otherwise the command lists the schemas and stops: qualify the name.

## Generated files

```
<codegen.outDir>/                         default src/db2/generated, relative to the configuration file
  manifest.json                           procedures generated so far
  AGENTS.md                               instructions for code assistants
  procedures/
    README.md                             guide: how to configure a procedure, state of each one
    MYSCHEMA.MY_PROC/                     one folder per procedure
      MYSCHEMA.MY_PROC.generated.ts       its descriptor
      MYSCHEMA.MY_PROC.outcome.ts         its outcome rule, created once as a draft
```

- `*.generated.ts` files are rewritten by every `generate`. Never edit them.
- `*.outcome.ts` files are created once, then owned by the application team: `generate` never rewrites them. See [Outcome rules](#outcome-rules).
- `README.md` is rewritten by every `generate` (not by `check`). It gives the steps that lead to an outcome rule (calls to make on a test subsystem, what to log and what never to log, when to set `validated: true`), then one row per procedure of the manifest: data access, commit on return, state of its rule (`validated`, draft, missing).
- `AGENTS.md` is rewritten by every `generate` (not by `check`), for the code assistants that write calls and outcome rules: the files of the folder and who owns them, the configuration in effect (field status, inputs every procedure takes), how to write a rule (evidence for every value, enums rather than strings, a test per rule, `validated` left to a person), and the procedures whose rule is not validated, with whether the field status fits each one. It holds the names of the procedures: it belongs to the application. `generate` also keeps a short section that points to it in the instruction file of the project, `AGENTS.md` at the root by default (`codegen.projectInstructions`): between two db2kit markers, the rest of the file untouched, updated when `codegen.outDir` moves. When the file does not exist, `generate` asks in a terminal before creating it, and only says so in CI. An assistant that reads another file gets the section there: set `codegen.projectInstructions` to that file (`CLAUDE.md`, `.github/copilot-instructions.md`), or to `false` to leave every file alone.
- Before 0.2.0, the two files of a procedure were written directly in `procedures/`. `generate` refuses a procedure still in that layout and says what to do: move its `.outcome.ts` into its folder and update the imports, delete the old `.generated.ts`. It never moves a file the team owns.
- Commit both: code review then shows every catalog change that reaches the application.
- Output is deterministic (no date, stable order), so `check` compares files byte for byte.

Example, for a procedure with three parameters:

```ts
// Generated by db2kit from the Db2 catalog. Do not edit: run `npx db2kit generate` again.
// Procedure MYSCHEMA.MY_PROC
// Warning: PARAMETER STYLE GENERAL: Db2 refuses a null input (SQLCODE -470).

import { defineProcedure } from 'db2kit';

export interface MyProcInput {
  /** CUSTOMER_ID CHAR(10), IN */
  customerId: string;
  /** AMOUNT DECIMAL(11,2), INOUT */
  amount: number;
}

export interface MyProcOutput {
  /** AMOUNT DECIMAL(11,2), INOUT */
  amount: number;
  /** RETURN_CODE CHAR(3), OUT */
  returnCode: string;
}

export const myProc = defineProcedure<MyProcInput, MyProcOutput>({
  schema: 'MYSCHEMA',
  name: 'MY_PROC',
  language: 'COBOL',
  sqlDataAccess: 'MODIFIES SQL DATA',
  parameterStyle: 'GENERAL',
  commitOnReturn: false,
  resultSets: 0,
  alteredAt: '2026-01-05 10:30:00.000000',
  parameters: [
    // ordinal, catalog name, property, mode, type, length, scale, nullable
  ],
});
```

## Calling a procedure

```ts
import { unchecked } from 'db2kit';
import { myProc } from './db2/generated/procedures/MYSCHEMA.MY_PROC/MYSCHEMA.MY_PROC.generated';
import {
  myProcWithOutcome,
  type MyProcInput,
} from './db2/generated/procedures/MYSCHEMA.MY_PROC/MYSCHEMA.MY_PROC.outcome';

// With its outcome rule: throws unless the rule concludes to a success.
const input: MyProcInput = { customerId: '0001', amount: 12.5 };
const { output, notice } = await db.call(myProcWithOutcome, input);

// Without a rule, on purpose and with its reason: the result is 'unchecked', the caller reads
// the outputs itself.
const { output: raw } = await db.call(unchecked(myProc, 'first try on the test subsystem'), input);
```

| Argument  | Content                                                                                                                                                                        |
| :-------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| procedure | The descriptor with its outcome rule (`...WithOutcome`, `defineOutcome`), or `unchecked(descriptor, reason)`. A descriptor alone is refused (below)                            |
| input     | IN and INOUT values by property name, typed from the descriptor                                                                                                                |
| options   | `tag` (audit label, a string), `maxRows` (rows per result set, a positive integer, default `query.defaultMaxRows`). Checked before any network call, an unknown option refused |

Result:

| Field        | Content                                                                                                                                                                                                                             |
| :----------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `output`     | OUT and INOUT values, normalized from their catalog type (below)                                                                                                                                                                    |
| `resultSets` | Rows of each result set, in order, bounded like `query`. Typed once `probe` wrote the columns ([Result set types](#result-set-types))                                                                                               |
| `columns`    | Columns of each result set, `{ name, type }` as the driver describes them (`VARCHAR(40)`, `DECIMAL(11,2)`), even without any row: the catalog does not describe result sets. `npx db2kit probe` shows them ([cli.md](cli.md#probe)) |
| `outcome`    | `'success'` (accepted by the rule) or `'unchecked'` (called without a rule)                                                                                                                                                         |
| `notice`     | Message the rule returned with a success. Never an error                                                                                                                                                                            |

### A call without its outcome rule

Since 0.30.0, `db.call` and `tx.call` take a procedure in two forms only: the `...WithOutcome` export of its `.outcome.ts` file, or `unchecked(descriptor, reason)`. The descriptor alone, the export of `.generated.ts`, is refused.

#### Why

A program can refuse an operation and still end with `SQL_CODE` at 0: the refusal is only in its outputs, a code or a message per field. Called with its descriptor alone, nothing reads those outputs. The rejection comes back as a normal result, `outcome: 'unchecked'`, and nothing in the code shows that the call was never checked. It was observed in an application: a service called the descriptor of a procedure that modifies data inside `db.$transaction(fn, { rollback: true })`, and a rejection of the program read as a success. The descriptor must stay exported, since the rule imports it: the call is what changed.

#### What is refused, and what it says

The refusal comes twice, with the same advice:

- **In the types.** `db.call(myProc, input)` does not compile, whatever the type of the input: an object, `{}`, `unknown`, `any`. `No overload matches this call`, and the last line of the error of TypeScript is the advice itself:

  ```
  Type '{ customerId: string; amount: number; }' is not assignable to type '"A descriptor alone
  checks nothing: call the ...WithOutcome export of its .outcome.ts file, or
  unchecked(descriptor, 'the reason')"'.
  ```

  An input typed `any` gets a shorter line, `Argument of type 'any' is not assignable to parameter of type 'never'`: the same refusal.

- **At run time**, for JavaScript, a cast or `as never`: a `Db2UsageError`, `code: 'USAGE'`, before any network call. Its message: `call() was given the descriptor of MYSCHEMA.MY_PROC alone: it checks nothing, and a rejection the program reports in its outputs would read as a result. Call the ...WithOutcome export of its .outcome.ts file, or unchecked(descriptor, 'the reason') for a call without its rule, on purpose.` With `audit.refusals: true`, the refusal is an audit event too (`source: 'call'`, `error.code: 'USAGE'`), counted by the sinks.

Hovering the descriptor in the editor says the same: the generated `.generated.ts` holds its hover help, which names the `...WithOutcome` export and the `unchecked` form.

#### `unchecked(descriptor, reason)`

```ts
import { unchecked } from 'db2kit';
import { myProc } from './db2/generated/procedures/MYSCHEMA.MY_PROC/MYSCHEMA.MY_PROC.generated';

const firstTry = unchecked(myProc, 'first try on the test subsystem, until the rule is written');
const { output, outcome } = await db.call(firstTry, input); // outcome: 'unchecked'
```

| Point           | What holds                                                                                                                                                                                                                                      |
| :-------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `descriptor`    | A descriptor `generate` wrote, or the same with its input codecs (`defineInputs`). Anything else is refused when `unchecked()` runs: a rule, a name, an object of another shape                                                                 |
| `reason`        | One line of 1 to 200 characters, trimmed. Empty, on two lines or longer: refused when `unchecked()` runs, so at the start of the module that declares it                                                                                        |
| What it returns | A frozen object, `{ descriptor, unchecked: reason }`, recognized by its shape: built by another copy of db2kit, it is accepted the same                                                                                                         |
| The call        | The same checks as with a rule: inputs, default inputs, codecs, read-only mode, transactions. The outputs normalized, never judged: `outcome: 'unchecked'`, no `notice`, never `Db2ProcedureRejectedError` nor `Db2ProcedureStatusUnknownError` |
| Its types       | Inputs and outputs typed from the descriptor, `resultSets` from `.results.ts`, as with the rule                                                                                                                                                 |

A reason says why this call goes without a rule, for the person who reviews it in a year: `'first try on the test subsystem'`, `'the program has no status output: the caller reads the row it wrote'`, `'read-only lookup, its outputs are data, no status'`. Not `'todo'` nor `'temp'`: the length is checked, the meaning is the review's.

#### What the audit trail and check show

The reason goes into the audit event of each call, in clear like the status values: it is the text of a person, never a value of the application.

```json
"procedure": { "name": "MYSCHEMA.MY_PROC", "outcome": "unchecked", "unchecked": "first try on the test subsystem" }
```

`npx db2kit check` lists every `unchecked(` of the code of the application after the `allowScan`, the call shown whole on one line even when prettier wraps it, its reason included ([cli.md](cli.md#check)). Neither list changes its exit code: they are for the review before a release, as the drafts of rules are.

#### Inside a transaction

`unchecked()` changes nothing to the rules of [transactions.md](transactions.md#procedures-in-a-transaction): a procedure declared `MODIFIES SQL DATA` without a validated rule is refused inside `db.$transaction`, `unchecked` or not, since a rejection would be committed with the rest. With `rollback: true` it is accepted: nothing is ever committed. A procedure that only reads can be called through `unchecked()` in any transaction.

#### In tests

A test calls the procedure as the service does, through its `...WithOutcome` export, so that the rule is tested with it: `FakeDriver.onCall` answers by property name ([testing.md](testing.md#procedures-by-property-name)). A test of what a program returns before its rule exists writes `unchecked(myProc, 'unit test')`. A test that checks the refusal passes the descriptor under `// @ts-expect-error`.

`probe` and `add --rollback` call through `unchecked()` themselves, with their own reason: they try a procedure before its rule holds anything.

#### Upgrading from 0.29

Every `db.call(descriptor, input)` of the application becomes a TypeScript error at the next build: `tsc` (or `npm run build`) lists them all, none can be forgotten.

| Situation                                                                    | What to write                                                                                                                        |
| :--------------------------------------------------------------------------- | :----------------------------------------------------------------------------------------------------------------------------------- |
| The procedure has a rule (its `.outcome.ts`)                                 | `db.call(myProcWithOutcome, input)`, imported from `.outcome.ts` with its types: the same inputs, and now a rejection throws         |
| No rule yet, and the call must be checked (a write, a status in its outputs) | Write the rule first: `npx db2kit add SCHEMA.NAME`, or its draft completed by hand ([below](#outcome-rules))                         |
| No rule on purpose (a first try, a program without any status output)        | `db.call(unchecked(myProc, 'the reason'), input)`, `unchecked` imported from `db2kit`, the reason given by the person who decides it |
| A test with `FakeDriver`                                                     | The `...WithOutcome` export, so that the rule is tested; `unchecked(myProc, 'unit test')` for a test without rule                    |

Then `npx db2kit generate`, so that the descriptors carry their new hover help (`check` reports them `outdated` until then). A code assistant lists the calls without a rule for the developer and waits: it never wraps them all in `unchecked()` to make the build pass.

#### Not chosen

- **A warning first, the refusal later.** A warning in a log is read after the harm: the rejection taken for a success has already been answered to the user. The TypeScript error lists every call to migrate at once.
- **Renaming the export of the descriptor.** Every rule the teams own imports it, and `generate` never rewrites a rule: each would break.
- **Refusing every call without a rule.** A first try, a program with no status output and the tools of db2kit itself need one: the escape is kept, written down and reviewed.

### Types to import

Every type is generated: the application declares none by hand. Import the call and its types from the rule, one import:

| File            | Exports                                                                     | Import it for                                                    |
| :-------------- | :-------------------------------------------------------------------------- | :--------------------------------------------------------------- |
| `.outcome.ts`   | `myProcWithOutcome`, and `MyProcInput`, `MyProcOutput` re-exported          | The call with its rule and its types: what a service imports     |
| `.generated.ts` | `myProc`, `MyProcInput`, `MyProcOutput`                                     | `unchecked(myProc, reason)`, a call without its rule on purpose  |
| `.results.ts`   | `MyProcResultSets`, `MyProcRow` (first result set), `MyProcRow2` (the next) | Mapping the rows of the result sets ([below](#result-set-types)) |

`MyProcInput` holds the IN and INOUT inputs, `MyProcOutput` the OUT and INOUT outputs, by property name, each with its catalog name and type in its hover help. The rule re-exports them since 0.29.0: a rule written before has no such line, since `generate` never rewrites it. Add it by hand, `export type { MyProcInput, MyProcOutput } from './MYSCHEMA.MY_PROC.generated';`, or import them from `.generated.ts`. `add` and `probe` still read such a rule as a draft.

### Result set types

The catalog describes the parameters of a procedure, never the columns of its result sets: a program opens its cursors while it runs. Without more, `result.resultSets[0]` is a list of `Record<string, unknown>`, and a misspelled column name compiles and reads `undefined`. `npx db2kit probe SCHEMA.PROC` calls the procedure with the cases of its cases file, `db2kit-cases/SCHEMA.PROC.json`, which the first run writes for a person to fill in (a procedure that reads only, [cli.md](cli.md#probe)), and proposes the columns it returned: after a yes in the terminal, it writes them next to the descriptor:

```ts
// generated/procedures/MYSCHEMA.FIND_CLIENT/MYSCHEMA.FIND_CLIENT.results.ts
export const findClientResultSets = defineResultSets([
  // Result set 1
  [
    { name: 'NAME', type: 'VARCHAR(40)', value: 'string', nullable: true },
    { name: 'OPENED', type: 'DATE', value: 'string', nullable: false },
  ],
]);
export type FindClientResultSets = ResultSetRows<typeof findClientResultSets>;

/** One row of result set 1, each column with its type. */
export type FindClientRow = NonNullable<FindClientResultSets[0]>[number];
```

The descriptor then imports it (`probe` rewrites it, and `generate` keeps the import while the file exists), so that `db.call(findClient, input)` gives `resultSets` of type `[Array<{ NAME: string | null; OPENED: string }>?]`. `FindClientRow` names one row, `{ NAME: string | null; OPENED: string }`, for a function that maps it to a type of the application: `(resultSets[0] ?? []).map(clientFromRow)`. A second result set gets `FindClientRow2`, and the first keeps its name when the program returns more.

The type of each column comes from the driver: its length for a character or binary column, its precision and scale for a `DECIMAL`. ibm_db 4.0.1 reads the precision into a field that its next read overwrites, so that `SQL_DESC_PRECISION` is 0 for every column: db2kit reads the length (`SQL_DESC_LENGTH`) and, for a `DECIMAL`, the display size, its precision plus 2 as ODBC defines it. Before 0.17.2, `probe` showed `CHAR(0)` and `DECIMAL(0,2)`: a `.results.ts` written then is written again by `--write-types`.

| Point                       | Rule                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| :-------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| An observation              | What the cases showed, not a guarantee: a branch of the program no case reaches can return other columns. One case for each branch. Each result set is optional in the type, since a branch can return fewer                                                                                                                                                                                                                                                        |
| `nullable`                  | Neither ibm_db nor the catalog tells whether a column can be null, so every column starts at `true`. Set `false` where a person knows a column is never null (the table the cursor reads, the program): `probe --write-types` keeps that mark while the column keeps its name and type                                                                                                                                                                              |
| `value`                     | What the driver gives, from the type it describes: `number` for `SMALLINT`, `INTEGER`, `REAL`, `DOUBLE`, `DECIMAL`, `NUMERIC`, `DECFLOAT`; `string` for characters, `BIGINT`, `DATE`, `TIME`, `TIMESTAMP`; `bytes` (a `Buffer`) for `BINARY`, `VARBINARY`, `BLOB` and `FOR BIT DATA`; `unknown` for any other type                                                                                                                                                  |
| Decimals                    | ibm_db reads a `DECIMAL`, `NUMERIC` or `DECFLOAT` of a result set as a floating-point number: beyond 15 digits, the last ones can be wrong. The file says so above such a column. For an exact value, the program returns it as text                                                                                                                                                                                                                                |
| Check at each call          | `db.call` compares the result sets received with the file and adds the differences to its audit event (`procedure.resultSets`): a result set more or fewer, a column missing, added or of another type, a null in a column marked `nullable: false`. Names and types only, never a value. The call never fails for it. The console sink writes such a line as a warning. It catches an external program changed (a new load module) without a change in the catalog |
| Written after a yes         | `probe` compares the columns the cases returned with the file: the same, it says so; other columns or no file, it asks before writing. `--write-types` writes without asking. Nothing is written when two cases return other columns for the same result set, when no case returned one, when the descriptor differs from the catalog (run `generate` first), or when the file no longer exports what `probe` wrote                                                 |
| Input codecs, outcome rules | `defineInputs` and `defineOutcome` keep the result set types of the descriptor                                                                                                                                                                                                                                                                                                                                                                                      |

### Checked before any network call

`db.call` refuses with `Db2UsageError`, without contacting Db2, an input property the procedure does not have (a typo would otherwise be ignored), or a missing one. It refuses the values below with `Db2InputError`, a `Db2UsageError` that lists every refused value of the call at once (`issues`: property, catalog name, type, reason), never the values themselves, so that an application can answer them all in one response (HTTP 400):

- `null` for a procedure in `PARAMETER STYLE GENERAL` (Db2 would answer -470);
- a value of the wrong type, a string longer than the parameter, an integer out of range;
- a `DATE`, `TIME` or `TIMESTAMP` text in another form than `YYYY-MM-DD`, `HH:MM:SS` or `HH.MM.SS`, `YYYY-MM-DD-HH.MM.SS.FFFFFF` or `YYYY-MM-DD HH:MM:SS.FFFFFF` (fraction optional, at most 12 digits), or a date or a time that does not exist. Db2 would answer -180 or -181 (`INVALID_DATETIME`), whose message names neither the parameter nor the value. These forms are read by Db2 whatever the date and time formats of the subsystem, so db2kit sends no other: `20260105`, `01/05/2026` or `05.01.2026` are refused, with their form only (`the form 99999999`), never the value;
- a value an input codec refuses ([Input codecs](#input-codecs));
- a number with more decimals than the `DECIMAL` scale. Db2 would change it silently: Db2 13 for z/OS rounds such text half to even (`0.125` gives `0.12`, `0.135` gives `0.14`), a rule the application did not choose: `1.005` gives `1.00`, where commercial rounding expects `1.01`, and `0.1 + 0.2` is `0.30000000000000004` in JavaScript. Round the value first, with the rule the business expects;
  Also refused with `Db2UsageError`:

- inside `db.$transaction`, a procedure declared `COMMIT ON RETURN YES`, or one declared `MODIFIES SQL DATA` without a validated outcome rule (see [transactions.md](transactions.md#procedures-in-a-transaction));
- a `CALL` to a procedure declared `MODIFIES SQL DATA` in read-only mode. A procedure declared `READS SQL DATA`, `CONTAINS SQL` or `NO SQL` is allowed: Db2 itself refuses data changes from it.

### Input codecs

Some programs take numbers and dates as `CHAR` text in a fixed format: an identifier padded with zeros to its width, an amount in implied cents, a date as `YYYYMMDD`. Without a codec, db2kit sends the text it is given: `'42'` for a `CHAR(5)` reaches the program as `'42   '`, padded with blanks by Db2, and the program refuses it or reads something else. A codec turns the application value into the exact text, and refuses what it cannot write exactly.

Codecs are declared per parameter by the team, once, never inferred from the type, the width or the name of a parameter: in the same application, an identifier can be padded for one procedure and passed as received for another, and a `CHAR(20)` key made of digits is not a number. The source of each format is the program or the client it replaces, never a guess: see the reference cases below.

```ts
import { codecs, defineInputs, defineOutcome } from 'db2kit';
import { myProc } from './MYSCHEMA.MY_PROC.generated';

export const myProcInputs = defineInputs(myProc, {
  customerId: codecs.digits(), // '123' on CHAR(11): '00000000123'
  amount: codecs.digits({ scale: 2, absent: 'zeros' }), // 12.34 on CHAR(10): '0000001234'
  items: codecs.digits({ sign: 'leading', absent: 'zeros' }), // -3 on CHAR(6): '-00003'
  startDate: codecs.dateText('YYYYMMDD'), // '2026-01-05': '20260105'
  changedAt: codecs.timestampText('YYYY-MM-DD-HH.MM.SS.FFFFFF'),
});

export const myProcWithOutcome = defineOutcome(myProcInputs, { validated: false /* ... */ });
```

`defineInputs` returns a new descriptor whose input type takes the application values (`amount: string | number | null`), and leaves the generated one unchanged. Write it in the `.outcome.ts` file of the procedure, or in a file of your own: `generate` never touches either. At startup, it checks that each codec names an `IN` parameter of type `CHAR` or `VARCHAR`, wide enough for it.

| Codec                         | Takes                                                                         | Sends                                                      |
| :---------------------------- | :---------------------------------------------------------------------------- | :--------------------------------------------------------- |
| `codecs.digits()`             | a number, or a number text (`'12'`, `'-3'`, `'12.50'`, `'.5'`)                | digits padded with zeros on the left to the catalog length |
| `codecs.dateText('YYYYMMDD')` | `'YYYY-MM-DD'`, or a text already in the target form                          | `YYYYMMDD`                                                 |
| `codecs.timestampText(form)`  | either 26-character form, a `T` instead of the blank, up to 6 fraction digits | the form the program expects, with 6 fraction digits       |

Options of `codecs.digits`:

| Option   | Effect                                                                                                                                                                                                       |
| :------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `scale`  | Implied decimal places: with 2, `12.34` is sent as `1234` and `12` as `1200`. Default: 0                                                                                                                     |
| `sign`   | `'leading'`: a negative value starts with `-` in the first position and keeps one digit less, a positive value has no sign (`-3` on 6 characters: `-00003`). Without it, a negative value is refused (below) |
| `absent` | What `null` sends: `'null'` (default, NULL) or `'zeros'` (the full width of zeros). Also an option of `dateText`                                                                                             |
| `pad`    | `false`: the value is a text that already has the full width, checked (digits only, exact width) and sent unchanged, for a value passed as received. Default: `true`                                         |

Refused, with `Db2InputError`, rather than guessed:

| Value                                       | Why                                                                                                                                                                                          |
| :------------------------------------------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `'12,50'`                                   | A comma: write the decimal separator as a point                                                                                                                                              |
| `'12.345'` with `scale: 2`                  | More decimals than the scale: round the value first, with the rule the business expects. A trailing zero (`'12.340'`) is accepted                                                            |
| `-12.5` without `sign`                      | The form of a negative value depends on the program (sign leading, trailing, or carried by the last digit). Set `sign` once the form is confirmed with the program or the client it replaces |
| `'100000000'` with `scale: 2` on `CHAR(10)` | Too wide: 11 digits for 10. With `sign: 'leading'`, a negative value has one position less                                                                                                   |
| `''`, `' 12'`, `'12a'`, `'1e3'`             | An empty text (pass `null` for an absent value), blanks, letters, an exponent                                                                                                                |
| a number beyond 2^53, `NaN`, `0.1 + 0.2`    | Not exact as a number: pass a text, or round first (`0.1 + 0.2` has 17 decimals)                                                                                                             |
| `'2026-02-30'`, a `Date`                    | Not a calendar date. A `Date` carries a time zone: pass the text                                                                                                                             |
| `'2026-10-02T14:30:00Z'`                    | A time zone is not part of a Db2 `TIMESTAMP`                                                                                                                                                 |

The two timestamp forms have the same width, 26 characters: Db2 writes `YYYY-MM-DD-HH.MM.SS.FFFFFF`, and ibm_db gives `YYYY-MM-DD HH:MM:SS.FFFFFF` in result sets. A value read from a table and passed back to a procedure has the second form; only a format check tells them apart, which `timestampText` does in both directions.

Reference cases. Before relying on a codec, check its output against the program or the client it replaces, with invented values and invented widths, as in the cases below, which are also tests of the codecs.

| Value                       | Codec, catalog length                    | Text sent                             |
| :-------------------------- | :--------------------------------------- | :------------------------------------ |
| `'12345'`                   | `digits()`, `CHAR(12)`                   | `000000012345`                        |
| `'42'`                      | `digits()`, `CHAR(4)`                    | `0042`                                |
| `'12'`, `'12.3'`, `'12.34'` | `digits({ scale: 2 })`, `CHAR(9)`        | `000001200`, `000001230`, `000001234` |
| `null`                      | `digits({ scale: 2, absent: 'zeros' })`  | `000000000`                           |
| `'-3'`                      | `digits({ sign: 'leading' })`, `CHAR(5)` | `-0003`                               |

A program in control-only mode, when it has one, is the test bench of a format: one call per case, on a test subsystem, reading the status the program gives the field. A form it accepts is not yet proven: the program may read it with another sign or scale. When the echo output of the field does not show the value as the program read it, one write on a test subsystem, read back, proves it.

### Inputs every procedure takes

Some applications give every procedure the same inputs, for instance a header that names the user of the request. Instead of repeating them at each call, set them once in `procedures.defaultInputs` of `db2kit.config.mts`, by catalog name of the parameter: `generate` makes them optional, and the application, which reads the same file ([configuration.md](configuration.md#the-configuration-file)), fills them in at each call, as `probe` does:

```ts
procedures: {
  defaultInputs: {
    REQUEST_HEADER: ({ context }) => buildHeader(context.user), // called at each call
    CHANNEL: 'WEB',
  },
},
```

- A default applies to every procedure with an `IN` or `INOUT` parameter of that name, when the call leaves the property out (or `undefined`). A value given by the call wins, and an explicit `null` sends NULL.
- A function receives `{ procedure, parameter, context }` at each call, and may be `async`. `context` holds `tag`, `correlationId` and `user` of the current context: set `user` with `db.withContext({ user }, fn)`, or let the NestJS interceptor set it. The user is never written to the audit trail. A function that throws, or returns anything but a text, a number or `null`, stops the call before it is sent (`Db2UsageError`, its error as `cause`).
- The value then goes through the same checks as any input, and through the codec of the parameter if it has one. It is written to the audit trail like any input, following `audit.params`.
- `generate` writes these properties as optional (`requestHeader?: string | null`), with `Default: procedures.defaultInputs` in their comment. Changing the keys changes the generated files: `check` reports them until `generate` runs again.

When a legacy client built such a header, read how it did before writing the function: the format is the program's, and a header sent empty can hide who made the call.

### Output normalization

Outputs are normalized from their catalog type before any rule sees them: `CHAR` and `GRAPHIC` lose their trailing blanks (`types.trimChar`), `DECIMAL` up to 15 digits becomes an exact number, beyond 15 digits a string with exactly `scale` decimals, `BIGINT` a string. A value that does not match its type gives `Db2ProcedureStatusUnknownError`: a rule never classifies a value db2kit could not read.

## Outcome rules

A procedure can refuse a request while Db2 reports success (SQLCODE 0): only its OUT parameters tell, and their shape differs from one procedure to another. The outcome rule turns them into a verdict.

What a rule protects depends on what the procedure does:

| Procedure (catalog data access)               | Without a rule                                                                                                                                                    | Rule                                                                                                                                                                      |
| :-------------------------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| Modifies data (`MODIFIES SQL DATA`)           | A rejection reported in the outputs passes as a success: the application answers as if the write was done, and inside a transaction the rest is committed with it | **Required** inside `db.$transaction`, validated (`validated: true`), or the call is refused. Outside a transaction, strongly advised: it is the case the rule exists for |
| Reads only (`READS SQL DATA`, `CONTAINS SQL`) | An error reported in the outputs, with an empty result set, reads as "no data"                                                                                    | Advised: an error then throws instead of showing an empty list. Never required, `validated` changes nothing for these                                                     |
| `NO SQL`                                      | Same as a read, when it has status outputs                                                                                                                        | Advised when it has status outputs                                                                                                                                        |
| Without OUT parameter                         | Nothing to classify: Db2 errors already throw                                                                                                                     | The draft accepts every call                                                                                                                                              |

`npx db2kit check` lists every rule still at `validated: false`, whatever the procedure does.

| Verdict                                      | Meaning                                                        | `db.call`                                                         | NestJS |
| :------------------------------------------- | :------------------------------------------------------------- | :---------------------------------------------------------------- | :----- |
| `{ status: 'success', notice?, warnings? }`  | Every success criterion holds. Some fields may carry a warning | Returns the result, with `notice` and `warnings`                  | 200    |
| `{ status: 'rejected', reasons, warnings? }` | A known failure signal, with a reason per field                | Throws `Db2ProcedureRejectedError`, with `reasons` and `warnings` | 422    |
| `{ status: 'unknown' }`                      | Anything else                                                  | Throws `Db2ProcedureStatusUnknownError`                           | 502    |
| `evaluate` throws, or returns another shape  | The rule cannot conclude                                       | Throws `Db2ProcedureStatusUnknownError`, cause attached           | 502    |

A reason or a warning is a text written by `evaluate`, or the parts of a field found by a field status (`{ code: 'E12', message: '...' }`), or a list of them when several groups report the same field.

**Write an allowlist, not a denylist.** A call succeeds only when every success criterion holds. A rule that only detects known failure codes lets every unknown failure through as a success.

### The parts of a rule

A rule combines up to four parts. It needs at least one.

| Key                | Form                                                       | Purpose                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| :----------------- | :--------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `success`          | data: output to value                                      | When the call is a success: every listed output holds its value, one constant per output, which `probe` writes (below). `null`: not written yet, the call is refused before it is sent. Checked at startup: an output name or a type that cannot match stops the application. Written in clear to the audit trail                                                                                                                                                                                                                                                                                                                                                                                                                      |
| `fieldStatus`      | a field status, or `null` for the one of the configuration | Why a call failed, field by field, and the warnings of a success, without code ([Status per field](#status-per-field))                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| `refused`          | data: output to values, or to each value and its meaning   | The values of a status output that mean the program refused the request: such a value, the success values not matching, makes the call rejected (HTTP 422), the output, its value and its meaning the reason: `{ returnCode: { NOK: 'The order does not exist' } }` gives `RETURN_CODE "NOK": The order does not exist`. A list when no value has a meaning, `{ returnCode: ['NOK', 'E01'] }`; a number written as a key, `{ sqlCode: { '-911': 'Locked' } }`. Any value neither a success nor a refusal stays unknown (HTTP 502). Checked at startup like `success`, and a refused value equal to the success value stops the application. `npx db2kit sheet --answers` writes it from the sheet of the team, its page of error codes |
| `evaluate`         | code: `(output, context) => verdict`                       | The last word, for what the others cannot say                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| `statusParameters` | output names                                               | Other outputs that carry the status. Written in clear to the audit trail and to `Db2ProcedureStatusUnknownError`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| `validated`        | `true` or `false`                                          | A statement by a person: `true` once the rule was checked against the program, by test calls or by the team that owns it. Nothing checks it automatically. `check` lists the rules at `false`, and a procedure that modifies data is refused inside `db.$transaction` while its rule is at `false`                                                                                                                                                                                                                                                                                                                                                                                                                                     |

The verdict is built in this order, failing closed at each step:

1. **The success values.** They all match, or the rule has none.
2. **The field status**, when the rule has one. A field no classification rule matches makes the outcome unknown. Otherwise:

   | Fields                     | Success values | Verdict                                                              |
   | :------------------------- | :------------- | :------------------------------------------------------------------- |
   | at least one rejected      | do not match   | rejected: every rejected field, and the warnings                     |
   | at least one rejected      | match          | unknown: the program contradicts itself, the write may have happened |
   | only accepted, or warnings | match          | success, with the warnings                                           |
   | only accepted, or warnings | do not match   | unknown: a failure without explanation                               |

   Without success values, only the fields decide.

3. **The refused values**, when the rule has some: a refused value, the success values not matching, makes the verdict rejected, the reasons of the fields kept with it.
4. **`evaluate`**, when the rule has one, runs at every call. It receives the normalized output and `{ successMatched, verdict }`, the verdict of the steps before, and returns its own. It has the last word with one limit: when the success values do not match, a `success` it returns counts as unknown. It must be synchronous: a returned promise is not a verdict, and gives an unknown status.

```ts
// MYSCHEMA.MY_PROC.outcome.ts, owned by the application team
import { defineOutcome } from 'db2kit';
import { myProc } from './MYSCHEMA.MY_PROC.generated';

export const myProcWithOutcome = defineOutcome(myProc, {
  validated: true,
  success: { returnCode: '000' },
  evaluate(output, { successMatched }) {
    if (successMatched) return { status: 'success', notice: output.message };
    if (output.returnCode === 'E01') {
      return { status: 'rejected', reasons: { customerId: output.message } };
    }
    return { status: 'unknown' };
  },
});
```

### Success values written by probe

Each rule holds its own success values, one constant per status output, in its file: what a person reads is what `db.call` compares, with no value elsewhere to look up. For a procedure that reads, `npx db2kit probe` finds them:

```sh
npx db2kit probe MYSCHEMA.MY_PROC --status "RETURN_CODE,SQL_CODE"
```

`npx db2kit add MYSCHEMA.MY_PROC` makes the same calls in a terminal, after asking which outputs hold the status and the inputs of the cases, and writes the same values after a yes ([cli.md](cli.md#add)). A procedure that modifies data is never called: `add` asks for the values the team that owns the program gave, typed or pasted as JSON, checks each against the type of its output, and writes them after a yes, the rule saying they come from that team.

When every case that ran returned the same values for these outputs, probe proposes them, and asks in a terminal before writing them in the rule:

```ts
// MYSCHEMA.MY_PROC.outcome.ts, as probe writes it after a yes
const successReturnCode: string | null = '000'; // RETURN_CODE CHAR(3)
const successSqlCode: number | null = 0; // SQL_CODE INTEGER

export const myProcWithOutcome = defineOutcome(myProc, {
  validated: false,
  success: { returnCode: successReturnCode, sqlCode: successSqlCode },
});
```

| The cases                                             | probe                                                                                                                                                                              |
| :---------------------------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Return the success values of the rule                 | Says so, writes nothing                                                                                                                                                            |
| Agree on other values, the rule a draft               | Proposes them and asks. A yes rewrites the constants, the rest of the file kept, or the draft `generate` wrote when nobody changed its code. No terminal to ask in: writes nothing |
| Disagree, return `null`, or none ran                  | Proposes nothing and says why: keep in the cases file the cases that should succeed (`found` and `empty` both succeed for most procedures that read)                               |
| Agree on other values, the rule `validated: true`     | Never changes it: says the values differ                                                                                                                                           |
| Agree, the rule written by hand without the constants | Gives the lines to write                                                                                                                                                           |

- **Once per procedure.** Without a rule that names them, `--status` names the outputs that carry the status. Then the rule names them, and every run of probe compares what the cases return with them.
- **Fail closed.** Any other value gives an unknown status, never a success. A constant left at `null` is not written yet: `db.call` refuses the call before it is sent, probe judges it unknown and proposes the value.
- **A procedure that modifies data**: probe refuses to call it. Its values come from the team that owns the program, written in the constants by a person.
- **Still a draft.** probe never sets `validated: true`: the team that owns the program confirms the values first.
- **Before 0.22.0**, the configuration held `procedures.outcomeConvention`, values shared by every rule that left a constant at `null`. Removed: a value changed there changed every procedure without a trace in their files. A configuration that still has it is refused with where its values go: write them in the constants of each rule, or let probe propose them.

### Status per field

Many programs report a status per field: a code, a message, a severity for each field of the request. A field status describes once how the outputs form one group per field, and how a group is classified. db2kit then builds the reasons of a rejection and the warnings of a success, without `evaluate`. Nothing is hard-coded: the markers, the roles and the values are the project's.

```ts
// src/db2/field-status.ts, in the application
import { defineFieldStatus, FieldGrouping, FieldVerdict } from 'db2kit';

enum FieldCode {
  Accepted = '00',
}
enum Severity {
  Blocking = 'E',
  Warning = 'W',
}

export const fieldStatus = defineFieldStatus({
  group: {
    by: FieldGrouping.Suffix,
    parts: { code: '_CODE', message: '_TEXT', severity: '_LEVEL' },
  },
  classify: [
    { when: { severity: [Severity.Blocking] }, then: FieldVerdict.Reject },
    { when: { severity: [Severity.Warning] }, then: FieldVerdict.Warn },
    { when: { code: [FieldCode.Accepted, null] }, then: FieldVerdict.Ok },
  ],
});
```

**Grouping.** `group.by` takes a value of `FieldGrouping`:

| `FieldGrouping` | Outputs                              | Configuration                                                         |
| :-------------- | :----------------------------------- | :-------------------------------------------------------------------- |
| `Suffix`        | `CUSTOMER_CODE`, `CUSTOMER_TEXT`     | `parts: { code: '_CODE', message: '_TEXT' }`                          |
| `Prefix`        | `CODE_CUSTOMER`, `TEXT_CUSTOMER`     | `parts: { code: 'CODE_', message: 'TEXT_' }`                          |
| `Contains`      | `CUSTOMER_CODE_OUT`, the marker once | `parts: { code: '_CODE' }`: the field is the name without the marker  |
| `List`          | irregular names                      | `fields: { customer: { code: 'CUST_STATUS', message: 'CUST_TEXT' } }` |

The roles (`code`, `message`, `severity`...) are names of your choice. The field is the camelCase of the name without its marker. The outputs of `success` and `statusParameters` are left out. When several markers match a name, the longest wins if the others lie inside it (`_STATUS_CODE` before `_CODE`).

**Classification.** The rules of `classify` are tried in order, the first that matches decides: `FieldVerdict.Ok` (nothing to report), `Warn` (reported in `warnings`, the call can still succeed) or `Reject` (reported in `reasons`). A group no rule matches makes the outcome unknown. A condition is:

- a list of values, compared with `===` after output normalization (`CHAR` without trailing blanks): `{ severity: [Severity.Blocking] }`. Several roles in one `when` must all match. `{}` matches every group;
- `{ startsWith: 'W' }`, for a text;
- a function of the parts, for anything else: `(parts) => Number(parts.code) < 0`. It must return a boolean.

A part the field does not have counts as `null`.

**Refused rather than guessed**, before the first call of a procedure (at startup for a field status given by the rule): a grouping that finds no field, a name that matches two roles or holds a marker twice, two outputs for one role of a field, and a group that lacks a role. A short marker can match by chance (`_L` in `NB_LINES_OUT`): such a group lacks its other parts and is refused, never classified. List in `optional` the roles a field may lack.

**Numbered error slots.** Some programs return a few slots (`ERROR1_FIELD`, `ERROR1_CODE`... `ERROR5_...`) rather than a group per field. Group them by suffix, and set `key` to the role that names the field: each report is then filed under that value rather than under `error1`. Several slots naming one field give a list.

```ts
defineFieldStatus({
  group: { by: FieldGrouping.Suffix, parts: { field: '_FIELD', code: '_CODE', text: '_TEXT' } },
  key: 'field',
  classify: [
    { when: { code: [null] }, then: FieldVerdict.Ok }, // empty slot
    { when: (parts) => Number(parts.code) < 0, then: FieldVerdict.Reject },
    { when: (parts) => Number(parts.code) > 0, then: FieldVerdict.Warn },
  ],
});
```

**No magic string.** The choices of db2kit are enums (`FieldGrouping`, `FieldVerdict`), the values are yours, as enums or constants. The roles come from the keys of `parts`: a role misspelt in `when`, `key` or `optional` is a TypeScript error, and a configuration built at runtime is checked by `defineFieldStatus` too.

**A default, and an override per procedure.** The field status belongs to the application. The default of every procedure goes in `db2kit.config.mts`, as `procedures.fieldStatus`: the application reads the same file, and uses it at each call. Each rule then says which one it takes:

| In the rule                             | Field status used                                                                                       |
| :-------------------------------------- | :------------------------------------------------------------------------------------------------------ |
| `fieldStatus: null`                     | The default, `procedures.fieldStatus` of the configuration. Refused at startup when none is configured  |
| `fieldStatus: defineFieldStatus({...})` | Its own, for this procedure only: it overrides the default, for a program whose outputs or codes differ |
| no `fieldStatus` key                    | None: the success values and `evaluate` judge the call alone, whatever the configuration holds          |

A default never applies to a rule that does not ask for it: a rule written before it, or for a procedure it does not fit, keeps working the same. What the draft rule written by `generate` and `add` holds:

| The procedure                                       | The draft                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| :-------------------------------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| The default groups its outputs                      | `fieldStatus: null`, with the number of fields it groups and how to override it                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| Its outputs come one per field, and no default fits | An example in a comment, built from its outputs: `defineFieldStatus` with the markers of its codes and messages (`_CODE` and `_TEXT` for `CUSTOMER_CODE` and `CUSTOMER_TEXT`), checked as the application checks it at startup, the code of an accepted field left to write. Uncommented, it is its own; moved to the configuration, it is the default of every procedure. An output of one character in every field (`CHAR(1)`, a flag or a severity) is proposed as a third role, `flag`, in commented lines with the first rule of `classify`, its value left to write. The other outputs that come one per field are named, a role to add when one carries a status |
| A default that does not fit                         | Why, in a comment at the top, and the example above when there is one                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| None of these                                       | No field status                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |

An output is a success value or part of a field, never both: `add` proposes as status outputs only those the default does not group (`RETURN_CODE`, `SQL_CODE`), and without a default, not those the example groups either. A draft whose success values cover outputs the example groups says to remove them, and `add` writes it again without them after a yes; a rule edited by hand, `add` never rewrites, and says what to remove. The skeleton of `npx db2kit init` holds a commented default with the three roles, a code, a message and a flag.

**Step by step, for programs that report a code and a message per field:**

1. **Read the example.** `npx db2kit generate SCHEMA.PROC` (or `add`) writes the draft rule. When the outputs come one per field, it shows a `defineFieldStatus` built from their names, the markers found, `'...'` in place of the code of an accepted field.
2. **Ask the team that owns the program** for the code of an accepted field, and for what the other outputs per field mean (a severity, a flag): never guessed from a name or a value seen once.
3. **Write the default** in `db2kit.config.mts`, `procedures: { fieldStatus: defineFieldStatus({ ... }) }`, the example with its codes. The other procedures of the same programs take it too.
4. **Have the rule take it.** A draft still untouched: delete it and run `generate` or `add` again, which writes `fieldStatus: null`, then the success values of the codes that are not per field (`RETURN_CODE`, `SQL_CODE`) after a yes. The questions of step 2 are in the `Next:` block of `add`, named for the procedure. A rule the team wrote: add `fieldStatus: null` by hand, and remove from `success` the outputs the field status groups.
5. **Override for a program that differs**: in its rule, replace `null` with its own `defineFieldStatus({ ... })`. Do it once its success values are written: `add` no longer reads a rule edited by hand as a draft, and proposes nothing more.
6. **Check it on the test subsystem**: `add --rollback` or `probe` with a case refused for a field. The reasons name that field, and `validated: true` waits for the team.

#### A complete example

A program, `ORDERS.SAVE_ORDER`, invented here, saves an order. For each field of the request it reports three outputs, then two global codes. What the team that owns the program said:

| Outputs                                           | Type          | Meaning                                                                                       |
| :------------------------------------------------ | :------------ | :-------------------------------------------------------------------------------------------- |
| `CUSTOMER_CODE`, `AMOUNT_CODE`, `START_DATE_CODE` | `CHAR(2)`     | `00`: the field is accepted                                                                   |
| `CUSTOMER_TEXT`, `AMOUNT_TEXT`, `START_DATE_TEXT` | `VARCHAR(60)` | A text for the person who sent the order, empty when there is nothing to say. Can hold a name |
| `CUSTOMER_FLAG`, `AMOUNT_FLAG`, `START_DATE_FLAG` | `CHAR(1)`     | `E`: the field is refused. `W`: a warning, the order is saved anyway. A blank: nothing        |
| `RETURN_CODE`                                     | `CHAR(3)`     | `000` when the order is saved                                                                 |
| `SQL_CODE`                                        | `INTEGER`     | `0` when the program met no Db2 error                                                         |

**1. The default, in `db2kit.config.mts`**, for every procedure of these programs:

```ts
import {
  connectionFromEnv,
  defineConfig,
  defineFieldStatus,
  FieldGrouping,
  FieldVerdict,
} from 'db2kit';

// The values of the programs, from their team.
const FieldFlag = { Error: 'E', Warning: 'W' } as const;
const ACCEPTED = '00';

export default defineConfig({
  // connection, pool, audit...
  procedures: {
    fieldStatus: defineFieldStatus({
      group: {
        by: FieldGrouping.Suffix,
        parts: { code: '_CODE', message: '_TEXT', flag: '_FLAG' },
      },
      classify: [
        { when: { flag: [FieldFlag.Error] }, then: FieldVerdict.Reject },
        { when: { flag: [FieldFlag.Warning] }, then: FieldVerdict.Warn },
        { when: { code: [ACCEPTED, null] }, then: FieldVerdict.Ok },
      ],
    }),
  },
});
```

The first rule that matches decides: the flag first, so that a field flagged `E` is refused whatever its code. A field whose code is not `00` and which carries no flag matches no rule: the outcome is unknown, a failure, never a success by default.

**2. The rule takes it**, in `ORDERS.SAVE_ORDER.outcome.ts`: `fieldStatus: null`, and as success values only the codes that are not per field.

```ts
export const saveOrderWithOutcome = defineOutcome(saveOrder, {
  validated: true,
  success: { returnCode: '000', sqlCode: 0 },
  fieldStatus: null,
});
```

**3. A program that differs overrides it**, in its own rule. `ORDERS.CHECK_ORDER` reports `_RC` and `_MSG` per field, and `OK` for an accepted field:

```ts
export const checkOrderWithOutcome = defineOutcome(checkOrder, {
  validated: true,
  success: { returnCode: '000' },
  fieldStatus: defineFieldStatus({
    group: { by: FieldGrouping.Suffix, parts: { code: '_RC', message: '_MSG' } },
    classify: [
      { when: { code: ['OK'] }, then: FieldVerdict.Ok },
      { when: {}, then: FieldVerdict.Reject },
    ],
  }),
});
```

**4. What the application receives.** The program saved the order with a warning on the amount: `RETURN_CODE` `000`, `SQL_CODE` 0, `AMOUNT_FLAG` `W`. The call succeeds, and `result.warnings` holds that field alone: an accepted field is reported nowhere, a warning goes to `warnings`, a rejection to the reasons.

```ts
const result = await db.call(saveOrderWithOutcome, { orderId });
// result.outcome: 'success'
// result.warnings: { amount: { code: '00', message: 'Rounded to cents', flag: 'W' } }
```

The program refused the customer: `RETURN_CODE` `E01`, `CUSTOMER_FLAG` `E`, the warning on the amount still there. The call throws `Db2ProcedureRejectedError`, its `reasons` the refused fields and its `warnings` the others to report. `db2kit/nestjs` answers:

```json
{
  "statusCode": 422,
  "error": "Unprocessable Entity",
  "code": "PROC_REJECTED",
  "message": "The request was rejected.",
  "reasons": { "customer": { "code": "12", "message": "Unknown customer", "flag": "E" } },
  "warnings": { "amount": { "code": "00", "message": "Rounded to cents", "flag": "W" } }
}
```

The parts are what the program wrote: the application decides what to show. A message can hold a name or an identifier.

**5. The line to log**: the outcome, the fields, their codes and flags. Never a message nor a value.

```ts
/** The codes and flags of the reported fields: never a message nor a value. */
function codesOf(reasons: Readonly<Record<string, unknown>> = {}) {
  return Object.fromEntries(
    Object.entries(reasons).map(([field, reason]) => {
      const parts = (reason ?? {}) as { code?: unknown; flag?: unknown };
      return [field, { code: parts.code ?? null, flag: parts.flag ?? null }];
    }),
  );
}

try {
  await db.call(saveOrderWithOutcome, { orderId });
} catch (error) {
  if (error instanceof Db2ProcedureRejectedError) {
    logger.warn(
      JSON.stringify({
        outcome: 'rejected',
        procedure: error.procedure,
        reasons: codesOf(error.reasons),
        warnings: codesOf(error.warnings),
      }),
    );
  }
  throw error;
}
// {"outcome":"rejected","procedure":"ORDERS.SAVE_ORDER","reasons":{"customer":{"code":"12","flag":"E"}},"warnings":{"amount":{"code":"00","flag":"W"}}}
```

The audit trail already holds the outcome and the names of the fields of every call (`procedure.fields`, `procedure.warnings`), the messages only with `audit.params: 'full'` ([Audit](#audit)). This example runs as a test of db2kit, `test/unit/field-status-example.test.ts`: the outputs, the default, the override, the success with its warning, the rejection, its 422 body and the line to log.

### Conventions

The programs of an application come in a few families, each with the same status outputs and the same codes. A convention says once what a family means, by the catalog names of its outputs, and each rule of the family names it instead of repeating it:

```ts
// db2kit.config.mts
import { defineConfig, defineConvention } from 'db2kit';

// The values of the programs, from the team that owns them.
export default defineConfig({
  // connection, pool, audit...
  procedures: {
    conventions: {
      standard: defineConvention({
        success: { RETURN_CODE: '000', SQL_CODE: 0 },
        refused: { RETURN_CODE: ['NOK', 'E01'] },
        fieldStatus: null, // procedures.fieldStatus, or a defineFieldStatus of its own
      }),
    },
  },
});
```

```ts
// MYSCHEMA.SAVE_ORDER.outcome.ts
export const saveOrderWithOutcome = defineOutcome(saveOrder, {
  validated: true,
  convention: 'standard',
});
```

| Key of a convention | What it says                                                                                                                                                                                                          |
| :------------------ | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `success`           | The success value of each status output, by catalog name: the success values of every rule that takes it                                                                                                              |
| `refused`           | The values of a status output that mean the program refused the request, by catalog name. Such a value, with the success values not matching, makes the call rejected (HTTP 422), the output and its value its reason |
| `fieldStatus`       | Its own field status, or `null` for `procedures.fieldStatus`: the field status of every rule that takes it                                                                                                            |
| `statusParameters`  | Other outputs that carry the status, by catalog name                                                                                                                                                                  |

A value neither a success nor a refusal stays unknown (HTTP 502), as in any rule. The verdict is built as for a rule (the success values, then the field status), then a refused value makes it a rejection, the reasons of the fields kept with it, then the `evaluate` of the rule, when it has one, has the last word.

**Visible in each rule, never a default.** A rule is judged by a convention only when it names it: one without `convention` keeps its own values, whatever the configuration holds. A change of a convention changes the rules that name it, and only those. (`procedures.outcomeConvention`, removed in 0.22.0, applied to every rule without any naming it.)

**Refused rather than guessed.** `defineConvention` refuses a convention without any criterion, a value that is not a text or a number, or a refused value that is also its success value. A rule that names a convention cannot also give `success`, `refused` or `fieldStatus`. Before the first call of a procedure, its convention is resolved: a name `procedures.conventions` does not hold, or an output of the convention the procedure does not return, refuses the call before anything is sent. Such a procedure gets a rule of its own.

**With `add`.** On the draft of a procedure, `npx db2kit add` proposes, one by one, the conventions whose outputs it has (every output they read, their field status grouping its outputs), and after a yes writes the rule that names it, in place of the draft: nothing is asked then of its codes, and the sheet for the team asks only whether the program follows the convention. A convention is never chosen without a person: the outputs say it may fit, only the team says the program follows it. `probe` and `verify` judge the calls with it; `probe` never proposes other success values for such a rule, which would change every procedure of the family: it says to check the cases with the team, or to give the procedure a rule of its own.

**A change of a convention.** `npx db2kit check` and `generate` name, for each convention, the rules that name it; `generate` records its fingerprint in `manifest.json`, so that a later change is said, with the validated rules it reaches, to check again with the team. A rule its convention cannot judge makes `check` fail ([cli.md](cli.md#check)).

### The draft

`generate` creates `MYSCHEMA.MY_PROC/MYSCHEMA.MY_PROC.outcome.ts` once, with `validated: false`, and never rewrites it. With a field status that fits, it declares `fieldStatus: null`. Without it, its `evaluate` answers `unknown` to every call: until probe writes the success values or the team writes the rule, every checked call fails, never succeeds by default. A procedure without OUT parameters gets a rule that accepts every call, since Db2 errors are its only failure signal and they already throw.

The draft imports its descriptor without extension (`./MYSCHEMA.MY_PROC.generated`), which suits CommonJS projects (NestJS) and bundlers. In an ES module project resolved with `NodeNext`, add `.js`. The file belongs to the team.

### Grouping outputs by field in evaluate

`groupBySuffix` groups output values by field from suffixes, for an `evaluate` written by hand. A field status does the same, with the classification, in configuration.

```ts
import { groupBySuffix } from 'db2kit';

evaluate(output) {
  const fields = groupBySuffix(myProc, output, { code: '_CODE', message: '_MESSAGE' });
  // { customerId: { code: 'E1', message: 'Unknown customer' }, startDate: { code: '00' } }
  // ...
}
```

### Audit

The event of a `CALL` carries a `procedure` field: name, verdict (`success`, `rejected`, `unknown`, `unchecked`), status parameters in clear, the fields named by a rejection (`fields`) and the fields with a warning (`warnings`). Notices, reasons and warnings can contain identifiers: they are written, in `messages`, only with `audit.params: 'full'`. A rejection is logged as a warning by `consoleSink`, not as an error: it is a business answer. See [audit.md](audit.md).

## How parameters travel

ibm_db 4.0.1 has traps in its parameter binding, found in its source code (`lib/odbc.js`, `src/odbc.cpp`). The choices below avoid each of them. Those marked _to confirm_ have not been run against a real subsystem yet. Integration tests check them: `numeric.it.test.ts` for the conversion of `DECIMAL` and `BIGINT` IN text, `echo.it.test.ts` for the whole `CALL` path with an echo procedure, `call.it.test.ts` for any read-only procedure. Unit tests check the exact text db2kit writes and reads on thousands of generated values (`numeric-exactness.test.ts`).

| Catalog type                                    | IN                    | OUT                              | INOUT                      |
| :---------------------------------------------- | :-------------------- | :------------------------------- | :------------------------- |
| `CHAR`, `VARCHAR`, `GRAPHIC`, `VARGRAPHIC`      | string                | text buffer                      | text buffer                |
| `DATE`, `TIME`, `TIMESTAMP`                     | string                | text buffer, format _to confirm_ | text buffer                |
| `SMALLINT`, `INTEGER`                           | number                | 64-bit integer                   | 64-bit integer             |
| `BIGINT`, `DECIMAL`                             | exact text, confirmed | text, _to confirm_               | text, _to confirm_         |
| `REAL`, `DOUBLE`, `FLOAT`                       | number                | double                           | text, _to confirm_         |
| `DECFLOAT`                                      | number                | text, _to confirm_               | text, _to confirm_         |
| `CLOB`, `DBCLOB`, `BLOB`, `BINARY`, `VARBINARY` | string or Buffer      | refused, not supported yet       | refused, not supported yet |

Why:

- **DECIMAL never goes through a float.** Bound with the `DECIMAL` type, ibm_db writes a JavaScript number as text but declares a C type `DOUBLE`: the value is garbled. Bound as a plain number, it travels as a float: `0.29` is 0.28999..., and whether the driver rounds or truncates it to the scale is not established. Without a type, an output `DECIMAL` would also be described with precision 0. db2kit writes the exact decimal text and lets Db2 convert it. Text to number is confirmed on Db2 13 for z/OS when the target type is imposed, as for a `CALL` argument: exact at the limits of each type, extra decimals rounded (db2kit refuses them first). Number to text, for OUT and INOUT values, is _to confirm_.
- **OUT buffers are sized for the worst case.** A buffer too short truncates the value, and ibm_db reports no warning. Text buffers hold 4 bytes per character, enough for UTF-16 and UTF-8 builds of ibm_db. Outputs longer than 4087 characters are refused for now.
- **OUT parameters are bound empty.** The placeholder is never sent to Db2 (SQL_PARAM_OUTPUT), so no value can read as a success when the program leaves a parameter untouched.
- **Only integers keep a numeric INOUT binding.** ibm_db switches the C type of any integer-valued number to a 64-bit integer, which garbles a `DECIMAL` or `DOUBLE` output. Every other INOUT travels as text.
- **A null INOUT is refused for text types.** ibm_db binds it with no length and the narrow character type. Integers are not affected.
- **The executor passes copies.** ibm_db rewrites the parameter array and some parameter objects. The audit trail keeps the original.

## Names

Mechanical camelCase, no renaming: `CUSTOMER_ID` gives `customerId`, a procedure `MY_PROC` gives the export `myProc` and the types `MyProcInput` and `MyProcOutput`. A parameter without a name in the catalog becomes `parm<ordinal>`. Two catalog names that would give the same property stop the generation.

## Types

| Db2 type                                                     | Input                     | Output   |
| :----------------------------------------------------------- | :------------------------ | :------- |
| `CHAR`, `VARCHAR`, `GRAPHIC`, `VARGRAPHIC`, `CLOB`, `DBCLOB` | `string`                  | `string` |
| `DATE`, `TIME`, `TIMESTAMP`                                  | `string`                  | `string` |
| `SMALLINT`, `INTEGER`, `REAL`, `DOUBLE`, `FLOAT`             | `number`                  | `number` |
| `DECIMAL` up to 15 digits                                    | `number`                  | `number` |
| `DECIMAL` beyond 15 digits                                   | `string`                  | `string` |
| `BIGINT`                                                     | `bigint` or `string`      | `string` |
| `BLOB`, `BINARY`, `VARBINARY`                                | `Buffer`                  | `Buffer` |
| other                                                        | `unknown`, with a warning |          |

Nullability follows the parameter style. With `PARAMETER STYLE GENERAL`, the program receives no null indicator: types exclude `null`, and Db2 refuses a null input (SQLCODE -470). Other styles add `| null`.

## Warnings

`generate` and `describe` report what a developer must know before calling the procedure. They also appear as comments at the top of the generated file.

| Warning                   | Why it matters                                                                                                        |
| :------------------------ | :-------------------------------------------------------------------------------------------------------------------- |
| `COMMIT ON RETURN YES`    | Db2 commits when the procedure returns: `tx.call` refuses it in a transaction                                         |
| Result sets               | The catalog does not describe their columns. Once `probe` wrote `SCHEMA.NAME.results.ts`, the warning names that file |
| `PARAMETER STYLE GENERAL` | No null input                                                                                                         |
| DECIMAL beyond 15 digits  | Exchanged as a string to stay exact                                                                                   |
| `DECFLOAT`                | Read as a JavaScript number: precision beyond 15 digits is lost                                                       |
| Type without mapping      | Report it, so that the mapping can be added                                                                           |

## Refused cases

Calls: see [Checked before any network call](#checked-before-any-network-call) and [How parameters travel](#how-parameters-travel).

Generation stops with an explicit message rather than producing a doubtful descriptor:

- procedure not found, or name found in several schemas;
- several versions of the procedure (native SQL procedures with versions);
- `PARM_COUNT` different from the number of parameter rows;
- a catalog code db2kit does not know (`SQL_DATA_ACCESS`, `PARAMETER_STYLE`, `COMMIT_ON_RETURN`, parameter mode).
