# `db2kit` CLI

```sh
npx db2kit <command> [options]
```

## Common options

| Option      | Purpose                                                                                          |
| :---------- | :----------------------------------------------------------------------------------------------- |
| `-c <file>` | Configuration file. Default: `db2kit.config.mts` at the project root (then `.ts`, `.mjs`, `.js`) |
| `-e <file>` | Environment file loaded before the configuration, for instance `.env`. Replaces `cli.envFile`    |
| `-h`        | Help                                                                                             |
| `-v`        | Version of the installed db2kit, also `npx db2kit version`: the one the application really loads |

`add`, `probe`, `status`, `sheet` and the help also take `--language <en|fr>`: see [Language](#language).

Options may come before or after the object names. The environment file does not replace the configuration file: it only sets the variables the configuration reads. An option given to a command that does not take it (`-t` to `doctor`, `-n` to `generate`) stops with exit code 2, an unknown option with exit code 1.

`npx db2kit help` and the `AGENTS.md` that `generate` writes for code assistants ([code-assistants.md](code-assistants.md)) list the same commands and options: both come from one list in db2kit, so a new option shows in both.

To stop typing `-e .env` at each command, name the file once in the configuration file, relative to it:

```ts
export default defineConfig({
  connection: connectionFromEnv('DB_APP'),
  // ...
  cli: { envFile: '.env' },
});
```

| Case                                      | Behavior                                                                                                                                                                               |
| :---------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| A variable already set in the shell or CI | Kept: neither file overrides it                                                                                                                                                        |
| `-e other.env` given                      | Loaded instead of `cli.envFile`, before the configuration file. Stops when the file does not exist                                                                                     |
| The file of `cli.envFile` does not exist  | The command goes on with the environment of the process, as in a CI job that sets the variables itself. A variable still missing is refused, and the error says the file was not found |
| A variable missing                        | The error says where it was looked for: the environment of the process, and the file with its origin (`-e` or `cli.envFile`), or that no file was loaded                               |
| A variable read with `env()` in the file  | Read while the configuration file loads, before `cli.envFile`: pass the file with `-e`, or read the connection with `connectionFromEnv`, which reads its variables at each connection  |

The application ignores `cli`: `createDb2` never loads a file, the application loads its own environment ([configuration.md](configuration.md#from-environment-variables-read-at-each-new-connection)).

### The files of the project

The CLI imports TypeScript files of the project: the configuration file, and for `probe` the outcome rule and the result set types of a procedure, with what they import. It reads them as the project compiles them, so that the files `generate` writes and the files of the team need no change:

- a relative import without extension, `./MYSCHEMA.MY_PROC.generated`, or with `.js`, is resolved as TypeScript resolves it: `.ts`, then `/index.ts`;
- a `.ts` file of the project is compiled by the TypeScript the project installed, when it offers the JavaScript API of TypeScript 5 and 6 (`transpileModule`). Otherwise, without TypeScript or with TypeScript 7, the native compiler, which ships no such API, by the type stripping of Node.js in its transform mode (`module.stripTypeScriptTypes`). Either way an `enum` of the team is accepted, and Node.js gives no warning, neither `MODULE_TYPELESS_PACKAGE_JSON` in a CommonJS project (NestJS) nor the experimental one of type stripping.

This needs Node.js 22.15 or later, which runs these hooks; on an earlier 22, a relative import of these files needs its extension. Path aliases of a `tsconfig.json` (`@app/...`) stay unknown: a file the CLI reads imports by relative paths. Only the process of the CLI does this, never the application.

## Names and patterns

Every Db2 object has a two-part name, `SCHEMA.NAME`. The schema is the part before the dot, like a folder: in the catalog, `CREATOR` in `SYSIBM.SYSTABLES` and `SCHEMA` in `SYSIBM.SYSROUTINES`. A prefix shared by object names (all tables of an application starting with the same letters) is only a naming convention inside the part after the dot: Db2 gives it no meaning.

A query written without a schema (`SELECT * FROM CONTRACT`) reads it from the current schema of the session (`doctor` shows it on the `Server` line), so the schema of a table you read every day may never appear in your SQL. `npx db2kit list NAME` tells: if `NAME` is a schema, its objects are listed.

`list` and `generate` take a pattern, `SCHEMA.PREFIX*`, where `*` stands for any characters, anywhere in the object name (`*_HIST`, `T*V`). The schema is always written in full: a run never spans schemas. `_` is an ordinary character, not a wildcard. Names are upper-cased like Db2 does, quoted names are refused. An object whose name is not an ordinary identifier (created quoted, as `"Orders"` or `"A/B"`) is reported as refused by a pattern, and the others are generated: such a name could hold a path or a quote. Column and parameter names of any form are kept as data in the generated files, and a control character in a name is shown as `?` in the terminal.

Quote a pattern in bash, zsh and Git Bash: `npx db2kit generate 'MYSCHEMA.*'`. Unquoted, the shell may replace it with file names, and zsh stops with `no matches found`. PowerShell and `cmd` pass it as is.

Write a list of names (`-t`, `--status`) without space after its commas, and in quotes: `-t "table,view"`, `--status "RETURN_CODE,SQL_CODE"`. PowerShell passes an unquoted `a,b` as two arguments, and a space after the comma does the same in every shell. The option may also be repeated: `--status RETURN_CODE --status SQL_CODE`. A list split this way is refused with exit code 2, saying so: the second name would otherwise be taken for an object.

## Exit codes

| Code | Meaning                                                                                      |
| :--- | :------------------------------------------------------------------------------------------- |
| 0    | Success                                                                                      |
| 1    | Failure (a failed `doctor` check, invalid configuration, an object refused by `generate`...) |
| 2    | Unknown command, or wrong usage                                                              |

## Colors

In a terminal, the output is colored: green for what is right (`OK`, `success`, `created`), yellow for what needs a look (`WARN`, a draft rule, `unknown`, a warning), red for what failed (`FAIL`, `error`, a refused object), cyan for what to type or open (a command, a path, an address), dim for what is secondary (a heading, a detail line). A color only repeats what the words say: without it, the text and its alignment are the same.

The output is plain when it goes to a file or a pipe, or when `TERM` is `dumb`. `NO_COLOR` set to any value turns the colors off, even in a terminal. `FORCE_COLOR` turns them on in a pipe, and off with `0` or `false`.

`add` and `probe` show the object they work on in a frame at the top, and `add` and `status` end with the board of a procedure in a frame: rounded lines, the same characters with or without colors, so that a text without its colors is the same text. Its lines take the color of the whole: green when every step is done, yellow while one is left, red when one failed.

## Language

`add`, `probe` and `status` print what they say about a procedure in English or in French, and so do the help and the sheet for the team that owns the program: its steps, questions, stops, the board and the `Next:` block. The language is, in order:

| Source                    | Scope                                                                                                                           |
| :------------------------ | :------------------------------------------------------------------------------------------------------------------------------ |
| `--language en` or `fr`   | One command                                                                                                                     |
| `DB2KIT_LANGUAGE=fr`      | One person, in their shell or in the file of `cli.envFile`. The help reads it from the shell only, as it loads no configuration |
| `cli: { language: 'fr' }` | The project, in `db2kit.config.mts`                                                                                             |
| none                      | English                                                                                                                         |

Another value is refused, with exit code 1. In French, a question ends with `(o/N)`, and `o` or `oui` is a yes, as `y` is: `okay` or `ouais` stay a no. A space before `:` or `?` is a no-break space, so that a wrapped line never starts with one.

What stays in English, whatever the language: the error messages (they reach the logs, the audit trail and the 422 and 502 bodies of an application, and are searched as they are), the generated files and their comments, the keys of the configuration, the names of the commands, options and files, and what `add` prints for a table or a view. The English text is the reference: each French sentence sits next to it in `src/cli/words/`, typed as it is, so that a sentence missing in one language is a TypeScript error.

## Questions and next steps

A command that waits on a person says so: each yes or no question stands between two blank lines, marked with `?`, in bold and the accent color, then `(y/N)`. Only an answer that starts with `y` is a yes, or `o` and `oui` alone ([Language](#language)). Without a terminal (a pipe, a script, a code assistant), nothing is asked, and the line printed instead says what was not written and how to write it.

What is left to do comes last, in a block of its own, `Next:` and the steps numbered, each a command to run or a file to edit, in the accent color: `init` when it wrote the configuration, `doctor` when a check failed, `generate` when an outcome rule is a draft, `probe` when cases are left to fill in, values or types left unwritten or a rule left to check, `add` when its rule is left to check. A command with nothing left prints no such block. The `?` and the word `Next:` keep their meaning without colors. Every line of both fits in 100 characters.

## `init`

The first command after the install, before the configuration exists. It writes the db2kit section into the instruction file that code assistants read, `AGENTS.md` at the root of the project by default (`codegen.projectInstructions`, [configuration.md](configuration.md#codegen)). An assistant then knows db2kit before anything is generated: it reads the rules it must never break (open `.env` or any file holding the password, try a login again after a refused one, generate more than the objects a person named), and where `code-assistants.md` and the guide of `generate` are.

```sh
npx db2kit init
```

| Case                                      | Behavior                                                                                                      |
| :---------------------------------------- | :------------------------------------------------------------------------------------------------------------ |
| No configuration file yet                 | Writes `db2kit.config.mts` at the root of the current folder, then says what comes next                       |
| A configuration file                      | Its `codegen.outDir` and `codegen.projectInstructions`. Its connection is not read: `.env` may still be empty |
| The file does not exist                   | Created after a yes in a terminal. Without a terminal (CI, a pipe): exit code 1                               |
| The file exists, without the section      | The section is added at the end. The rest of the file is never touched                                        |
| The section of an earlier version         | Brought up to date. `generate` does the same at each run                                                      |
| Markers broken by hand, two start markers | Left untouched, exit code 1                                                                                   |
| `codegen.projectInstructions: false`      | Nothing written                                                                                               |

The configuration file it writes is valid as it is: the connection read from `DB2_DATABASE`, `DB2_HOST`, `DB2_PORT`, `DB2_USERNAME` and `DB2_PASSWORD` (`connectionFromEnv('DB2')`, a prefix to change for the one of the application), a pool of 2, an audit name to change, and `cli.envFile: '.env'`. The options to decide are comments, each said in one line: `codegen.outDir`, `procedures.defaultInputs` and `procedures.fieldStatus`. The success values of each procedure go in its outcome rule, written by `probe`. It never overwrites a configuration file, whatever its name (`db2kit.config.mts`, `.ts`, `.mjs` or `.js`).

It also adds `/db2kit-cases/` to the `.gitignore` of the project when it has one and does not ignore that folder yet: the cases files of [`probe`](#probe), whose values may identify a person, stay out of git from the start. It never creates a `.gitignore`.

`init` opens no connection and reads no catalog.

## `doctor`

Checks, in order, everything that must work before writing a single line of code. It stops at the first blocking failure.

```sh
npx db2kit doctor -e .env
```

| Check            | What is checked                                                                                                                                                                                                         | On failure                                                                                     |
| :--------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------------------- |
| Configuration    | Every required key and its value. Shows the environment file loaded and its origin (`-e` or `cli.envFile`), and the connection string with the password masked, and any extra keyword whose name holds PWD or PASSWORD  | Fix the listed keys. A missing variable comes with where it was looked for                     |
| Node.js          | Version 22.12 or later                                                                                                                                                                                                  | Upgrade Node                                                                                   |
| Threadpool libuv | `UV_THREADPOOL_SIZE` at least `pool.max + 2`                                                                                                                                                                            | Set the variable at startup, see [production.md](production.md)                                |
| Code assistants  | The db2kit section in the instruction file of the project (`codegen.projectInstructions`), as `init` writes it. Nothing is written. No row when the setting is `false`                                                  | A warning: run `npx db2kit init`                                                               |
| Module ibm_db    | The native driver loads                                                                                                                                                                                                 | `npm install ibm_db` in the application                                                        |
| Network          | A plain TCP connection to `host:port`, without Db2 protocol or credentials                                                                                                                                              | The message tells timeout (VPN, firewall), refused port or unknown host. The doctor stops here |
| Connection       | A `SELECT 1 FROM SYSIBM.SYSDUMMY1` query succeeds                                                                                                                                                                       | The `Hint:` line explains common errors (network, authentication, license)                     |
| Server           | Location (`CURRENT SERVER`), version (`DSN13011`), APPLCOMPAT, SQLID, current schema                                                                                                                                    | Informational                                                                                  |
| Catalog          | Read access to `SYSROUTINES`, `SYSPARMS`, `SYSTABLES`, `SYSCOLUMNS`, `SYSINDEXES`, `SYSKEYS`, `SYSCOLDIST`, `SYSRELS`, `SYSFOREIGNKEYS`, `SYSVIEWDEP`, `SYSVIEWS`, with the columns `list` and code generation will use | Ask the DBA for read access, or report the missing column                                      |

Sample report:

```
OK   Configuration     /app/db2kit.config.mts
                       DATABASE=TESTDB;HOSTNAME=db2.example.local;PORT=5000;PROTOCOL=TCPIP;UID=TESTUSER;PWD=***;RECEIVETIMEOUT=60;QUERYTIMEOUT=60;
OK   Node.js           v22.23.0 (22.12 minimum)
WARN Threadpool libuv  UV_THREADPOOL_SIZE is 4 while pool.max is 8: ...
OK   Code assistants   AGENTS.md holds the db2kit section
OK   Module ibm_db     loaded
OK   Network           TCP connection to db2.example.local:5000 in 12 ms
OK   Connection        184 ms
OK   Server            location SSTEST, version DSN13011, APPLCOMPAT V11R1, SQLID TESTUSER, schema TESTUSER
OK   Catalog SYSIBM.SYSROUTINES  read allowed, expected columns present
...
Result: 0 failure(s), 1 warning(s)
```

## `list`

```sh
npx db2kit list MYSCHEMA -e .env                    # tables, views and procedures of a schema
npx db2kit list 'MYSCHEMA.CONTRACT*' -e .env        # those whose names start with CONTRACT
npx db2kit list MYSCHEMA -t view -n 200 -e .env     # views only, up to 200
```

| Option       | Purpose                                                                                      |
| :----------- | :------------------------------------------------------------------------------------------- |
| `-t <kinds>` | `table`, `view`, `procedure`, comma-separated or repeated. Default: all three                |
| `-n <count>` | Objects shown from each catalog table (`SYSTABLES`, `SYSROUTINES`). Default 50, at most 1000 |

Writes nothing. Shows exactly what `generate` with the same pattern and `-t` would select, one line per object:

```
KIND       NAME           SIZE         ROWS     GENERATE
view       CASES_JOIN     6 columns    -        no: over 2 object(s) of type(s) T, T in SYSVIEWDEP, not one table
view       CASES_V        1 column     -        yes, over MYSCHEMA.T_CASES
table      CONTRACT       11 columns   2500000  yes
table      T_CASES        1 column     unknown  yes
procedure  CONTRACT_SAVE  1 parameter  -        yes

2 tables, 2 views, 1 procedure in schema MYSCHEMA matching *. 1 refused by generate.
npx db2kit generate MYSCHEMA.* generates the objects marked yes.
```

- Tables and views first, in catalog order, then procedures. Aliases and other table types are never listed nor generated: for an alias, name its table.
- `ROWS` is `CARDF`, the row count of the last `RUNSTATS`, an estimate. `unknown`: statistics never collected. A view has none of its own.
- `GENERATE` for a view comes from `SYSVIEWDEP` and the view text, read for the whole page in a few queries: `no` with the reason for a view `generate` refuses (join, `WHERE`, expression, a column shown twice), `no, catalog mismatch` when the catalog contradicts itself. `generate` then reads the columns too, and may still report a mismatch. A procedure with several versions and not exactly one active is marked `no`, and so is any object whose name was created quoted (not an ordinary identifier). A control character in a name is shown as `?`.
- Bounded reads only: rows in `NAME` order, which follows the catalog indexes on the schema and the name, at most `-n` per catalog table plus one to tell that more match. Never a count of the whole schema: on a large catalog, a `GROUP BY` over one schema was observed to take more than 7 s.
- When nothing matches, the output says whether to check the schema or the pattern.

## `generate`

```sh
npx db2kit generate MYSCHEMA.MY_PROC MYSCHEMA.CONTRACT   # generate these objects
npx db2kit generate table:MYSCHEMA.CONTRACT              # say the kind when a name is both
npx db2kit generate 'MYSCHEMA.*'                         # every table, view and procedure of a schema
npx db2kit generate 'MYSCHEMA.CONTRACT*' -t view         # the views whose names start with CONTRACT
npx db2kit generate 'MYSCHEMA.*' -y                      # more than 50 objects, confirmed
npx db2kit generate                                      # regenerate every object of the manifest
```

| Option       | Purpose                                                                                                                  |
| :----------- | :----------------------------------------------------------------------------------------------------------------------- |
| `-t <kinds>` | With a pattern: `table`, `view`, `procedure`, comma-separated or repeated. Default: all three. Refused without a pattern |
| `-y`         | With a pattern: generates more than 50 objects (at most 1000)                                                            |

Finds in the catalog whether each name is a table (`SYSIBM.SYSTABLES`) or a stored procedure (`SYSIBM.SYSROUTINES`). A name found on both sides is refused: prefix it with `table:` or `procedure:`. These are the only two prefixes: a view or an alias goes without one, or with `table:` (never `view:`, refused with the command to type).

- A procedure gives its own folder `<codegen.outDir>/procedures/SCHEMA.NAME/` with `SCHEMA.NAME.generated.ts`, and the first time only a draft outcome rule `SCHEMA.NAME.outcome.ts`, then owned by the team. `procedures/README.md` is rewritten at each run: how to configure a procedure, and the state of each one. So is `<codegen.outDir>/AGENTS.md`, the instructions for code assistants, with the configuration in effect and the rules still to write. The instruction file of the project (`AGENTS.md` at the root by default, `codegen.projectInstructions`) gets a short section that points to it, between db2kit markers: added or brought up to date when the file exists, created after a yes when it does not and a terminal can ask, mentioned in one line otherwise. It is left untouched when its markers are not one start followed by one end, or when it is the generated guide itself, whatever the path that reaches it. Details: [procedures.md](procedures.md#generated-files).
- A table gives `<codegen.outDir>/tables/SCHEMA.NAME.generated.ts`. A view gives the same when it is a plain projection of one table, other views and aliases are refused by name. Details: [models.md](models.md).

A pattern selects objects like `list` with the same `-t`, and names and patterns can be mixed. Before anything is written:

- Above 50 matched objects, all patterns together, `generate` stops and writes nothing, unless `-y` is given. Above 1000, it stops even with `-y`: narrow the pattern or keep one kind with `-t`. `list` shows what a pattern matches.
- A pattern that matches nothing stops the run, with a hint on the schema.
- An object named and matched, or matched by two patterns, is generated once.

An object a pattern matched that `generate` refuses (a view with a join, a procedure with several versions) is printed as `refused` with the reason, and the others are generated. The exit code is then 1. An object named one by one that is refused still stops the run, as before.

Each procedure gets its draft outcome rule, to write and validate before it can modify data inside a transaction: `-t procedure` over a schema creates as many drafts as procedures, all listed by `check` until validated.

Every generated object is recorded in `<codegen.outDir>/manifest.json`, one by one, never the pattern: a table added to the schema later is not picked up by `generate` without arguments nor by `check`. Run the pattern again to add it. Prints one line per object (`created`, `updated`, `unchanged` or `refused`) followed by its warnings and, while a procedure's outcome rule is not validated, a line about it. With more than one object, a last line sums them up: `55 object(s): 2 created, 50 unchanged, 3 refused, 4 warning(s).`

## `add`

```sh
npx db2kit add MYSCHEMA.FIND_CLIENT                            # a procedure that reads
npx db2kit add table:MYSCHEMA.CONTRACT                         # a table or a view
npx db2kit add MYSCHEMA.FIND_CLIENT --status "RETURN_CODE,SQL_CODE"
npx db2kit add MYSCHEMA.FIND_CLIENT --external                 # a COBOL, PL/I or C program
npx db2kit add MYSCHEMA.SAVE_ORDER --rollback                  # modifies data: tried, then rolled back
```

Brings one object as far as the files of the project allow, on one read-only connection, and asks only what they do not hold: each step the files already hold is skipped, so that `add` can run again at any time, after an interruption, a catalog change or a new version of db2kit. Run it in a terminal: the questions are for the person who knows the answers, and a code assistant never answers them (rules in [code-assistants.md](code-assistants.md#never)). One object named in full, `SCHEMA.NAME`: a pattern is the work of `generate`.

A table, a view or an alias:

| Step       | What `add` does                                                                                                                                                                                                                                                                                                                                                                                                      |
| :--------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| same table | Before writing a new model: when a model already reads the same table (the table itself, or a view over it, read from the first line of each generated model), it says which and asks whether to generate this one as well. Without a terminal, it stops, exit code 1, with the `generate` command that writes it all the same                                                                                       |
| model      | `generate` of the object: the model, `tables/index.ts`, the manifest and the guides. The points `generate` notes, one short line each (the first sentence), in full at the top of the model                                                                                                                                                                                                                          |
| keys       | The unique keys, by column: `findUnique` and cursor paging take one. None: said                                                                                                                                                                                                                                                                                                                                      |
| relations  | The first time the model is written only: the relations its columns suggest with the models already generated, in both directions. A column with the name and the kind of type of every column of a unique key of another model, a hint, never a fact: a question for each, at most 12 in one run. Left out: two models of one table, a key matched by a unique key of the model itself, a relation declared already |
| writes     | The relations accepted, to one row on one side and to many rows on the other, checked by `defineRelations` before writing, then written in `relations.ts` while it holds exactly what db2kit writes (whatever a formatter changed). A comment or a relation written by hand: `add` leaves the file as it is and shows the lines to add. Without a terminal, it lists the relations proposed and writes none          |

A stored procedure. The files first, one row each under the title `Files`, then one section per phase under its heading, in this order, each shown only when it has something to do or say. A line says one thing: `✓` before what was written or found right, `!` before what needs a look, `✗` before what was refused. Each question stands between two blank lines, right under the lines that explain it:

```
  Files  generated/procedures/MYSCHEMA.FIND_CLIENT/
    descriptor  created
    rule        created, a draft without success values
    sheet       created db2kit-sheets/MYSCHEMA.FIND_CLIENT.html
                the questions for the team that owns the program

  ── Status outputs ──────────────────────────────────────────

  RETURN_CODE looks like a status code.
  Its value on a call that succeeds becomes the success value of the rule.

  ? Judge the calls by RETURN_CODE? (y/N)

  ── Test cases ──────────────────────────────────────────────

  2 case(s) to give, saved in db2kit-cases/MYSCHEMA.FIND_CLIENT.json (kept out of git).
  Type one value per input, as Db2 takes it, or paste a JSON object at the first input.
  Enter on the first input skips the case.
  Every case at once: { "found": { ... }, "empty": { ... } }

  Case found: a call that returns rows
    CLIENT_ID  CHAR(10), or null        >
    OPENED_ON  DATE YYYY-MM-DD, or null >
               ✗ DATE takes 'YYYY-MM-DD', got the form 99999999
```

| Phase          | What `add` does                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| :------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Files          | `generate` of the procedure: its descriptor, and the first time its draft outcome rule. The state of the rule: validated, a draft with its success values, with values not written yet, or without any. The result set types when written, and the sheet for the team that owns the program                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
| Convention     | On the draft of the rule, when `procedures.conventions` holds conventions whose outputs the procedure has: each proposed in turn with its values, and after a yes the rule written with `convention: 'name'` in place of the draft ([procedures.md](procedures.md#conventions)). Then nothing is asked of its codes. Without a terminal: what to write                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| Success values | Success values on outputs that come one per field, with no status per field for them: why they go, and the draft written again with the success values of the other outputs only, after a yes; a rule edited by hand is never written again, `add` says what to remove. For a procedure never called (it modifies data or commits on return, without `--rollback`): its success values come from the team that owns the program. After the status outputs, `add` asks whether the person has them, then each value, typed or pasted as JSON and checked against the type of its output, and writes them after a yes, the rule saying where they come from                                                                                                                                                                                                                                                                                                                                                               |
| Status outputs | When the rule names no status output yet: those of `--status`, else the outputs whose name looks like a status code, proposed and confirmed with the question `Judge the calls by NAME?` (many named by their count, `RETURN_CODE, SQL_CODE and 3 ending in _RC`; a message is never one, a text can hold data; those a status per field groups, or that come one per field without one, are left out and named), else typed by catalog name (Enter: none, then no success value is proposed). A person names them, never a guess                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| The program    | A COBOL, PL/I or C program: the person confirms its owners say it acts only on Db2, or passes `--external`. A no: no call                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| Test cases     | The cases file of the procedure, `db2kit-cases/SCHEMA.NAME.json`, keyed by the names of the catalog. When it does not exist, even once the rule and the types are written (`verify` and `probe` call with it), the inputs of `found` then `empty` are asked in the terminal, each case under its title, each input with its type, the answers lined up after `>`. Each line is read as its type (`null` for none where the input takes it, a text in double quotes as JSON) and checked as `db.call` checks it: refused under the type, asked again, never shown again. Enter on the first input skips a case. At the first input, a JSON object pasted, over as many lines as it takes, gives the case (keys by property or catalog name, a number in a text read as a number for an integer type, said), or every case at once (`{ "found": { ... }, "empty": { ... } }`): what it does not give is asked one by one, what it gives is never printed back. Inputs left to give in an existing file: asked, those only |
| Calls          | Never for a procedure that modifies data or commits on return: said, with why. Otherwise the number of cases and the location the connection reaches (`CURRENT SERVER`), then a yes before the first `CALL`. Each case twice, as `probe` does, with the same report of the cases. Only for what is missing, success values or result set types: once the rule and the types are written, `add` says no call is needed and names `npx db2kit probe SCHEMA.NAME`, which calls the cases at each run, each judged by the rule, before `validated: true`                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| Rule and types | The status values every case returned, proposed as the success values of the rule, written after a yes, as `probe` does. Then the columns of the result sets, proposed as `SCHEMA.NAME.results.ts`, written after a yes. For a procedure never called: its result set types to write by hand                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |

`add` makes a call only when something is left that a call gives: success values not written, result set types missing. Once the files hold them, it reads the catalog, says so and calls nothing: `probe` tries the cases again. It never sets `validated: true`.

It ends with the board of the procedure, where it stands now, read from its files, the same as `npx db2kit status SCHEMA.NAME` prints ([status](#status)):

```
╭─ MYSCHEMA.FIND_CLIENT ───────────────────────────────────────────────────────────── 4 of 6 done ─╮
│                                                                                                  │
│   OK      Descriptor      created from the catalog                                               │
│   OK      Cases           found and empty, in db2kit-cases/MYSCHEMA.FIND_CLIENT.json             │
│   OK      Success values  returnCode "000"                                                       │
│   TO DO   Refusal codes   ask which values of RETURN_CODE mean a refusal. Until then: unknown,   │
│                           HTTP 502                                                               │
│   OK      Result types    MYSCHEMA.FIND_CLIENT.results.ts                                        │
│   LATER   Validation      validated: true, by a person, once the rows above are done             │
│                                                                                                  │
╰──────────────────────────────────────────────────────────────────────────────────────────────────╯
```

| Row            | Shown                                                            | `OK` when                                                                                                  |
| :------------- | :--------------------------------------------------------------- | :--------------------------------------------------------------------------------------------------------- |
| Descriptor     | always                                                           | generate wrote it (`status` reads the files only: `npx db2kit check` compares it with the catalog)         |
| Outcome rule   | only when it is missing (`TO DO`) or cannot be loaded (`FAILED`) | never shown when it loads                                                                                  |
| Cases          | a procedure that reads                                           | its cases file holds every input                                                                           |
| Success values | a procedure with outputs                                         | every success value of the rule is written, or the team wrote a rule without any, or the rule is validated |
| Field messages | outputs that come one per field                                  | a status per field judges them, the default of the configuration or the rule's own                         |
| Refusal codes  | a rule with global status outputs, not validated                 | the rule has its own `evaluate`: until then a refusal of the program reads as unknown, HTTP 502            |
| Result types   | a procedure that declares result sets                            | `SCHEMA.NAME.results.ts` exists                                                                            |
| Validation     | a rule that loads                                                | `validated: true`, written by a person. `LATER` while another row is left                                  |

The calls in a service and their test are not on the board: nothing in the files tells whether they exist. They are in the last lines, `Next:`, one short step each, in order: the sheet to send to the team that owns the program and the command that reads its answers back, the call in a service with its test, `npx db2kit probe SCHEMA.NAME` when the cases are filled in and `add` did not call them, then `validated: true`, and one line on where the details are. The questions only that team answers (the codes of its fields, what its one-character output per field says, the values of its global codes that mean a refusal) are on the board and in the sheet, never repeated there.

### Trying a procedure that modifies data

```sh
npx db2kit add MYSCHEMA.SAVE_ORDER --rollback
```

With `--rollback`, `add` calls a procedure that modifies data, each case once, in a transaction that always ends with `ROLLBACK`: its status values and the columns of its result sets give its success values and types, as for a procedure that reads. A `ROLLBACK` undoes the writes of Db2 only, and only when the program never ends the transaction itself. So:

| Guard        | Rule                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| :----------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| Location     | `cli.rollbackServers` in `db2kit.config.mts` lists the locations of test subsystems. `CURRENT SERVER` is read on the connection that writes, before any call: another location is refused, no list and nothing is called                                                                                                                                                                                                                                                                                                                                            |
| The team     | A question each time: the team that owns the program confirms it never commits nor rolls back by itself. A COBOL, PL/I or C program: its owners confirm it acts only on Db2 (a file, a message, no `ROLLBACK` undoes them), or `--external`                                                                                                                                                                                                                                                                                                                         |
| The calls    | The cases `accepted` and `refused`, typed or pasted as JSON as for a procedure that reads, then a yes on the location shown                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| The witness  | A row in a declared temporary table (`SESSION.DB2KIT_WITNESS`, `ON COMMIT DELETE ROWS`), inserted before the `CALL` and read after it, before the `ROLLBACK`. Kept: the program left the transaction open, the `ROLLBACK` undid its writes. Gone: it committed or rolled back by itself, its writes may be committed: `add` says so in red, proposes nothing, exit code 1. A failed call leaves it not checked                                                                                                                                                      |
| The proposal | The status values of the cases side by side, one output per row, the usual value counted once, the codes of the fields too (never success values), so that a code saying `accepted` was refused shows. Then a question: did the program accept the case `accepted`? Yes: its values become the success values of the rule. No: nothing written, and its codes say what to correct. The same values in every case: nothing proposed, they cannot tell an accepted call from a refused one. The result set types of the first case that returned, written after a yes |

The witness reports a commit after it happened, it never prevents one: a program that commits writes on the test subsystem. It needs a work file space for declared temporary tables: without one, nothing is called. One connection, its own, with read-only mode off and nothing sent to the audit sinks.

Without a terminal (a script, a pipe, a code assistant), `add` does every step that needs no answer, then stops at the first one that does, with exit code 1 and what is missing: the status outputs (`--status`), the cases file (written to fill in), the owners of an external program (`--external`), the calls (they need a yes: in a script, `npx db2kit probe`). Answers typed in a terminal are never stored by db2kit but in the files they are for: the cases file, the rule, the types, `relations.ts`.

## `describe`

```sh
npx db2kit describe MYSCHEMA.CONTRACT -e .env
npx db2kit describe MYSCHEMA.MY_PROC -e .env > MY_PROC.md
npx db2kit describe table:MYSCHEMA.CONTRACT -e .env      # say the kind when a name is both
```

Prints the Markdown documentation of a procedure (catalog facts, parameters with their JavaScript types, warnings) or of a table (row count and statistics date, size class, columns with their JavaScript types, indexes, warnings). Writes no file and leaves the manifest untouched: redirect the output to keep it.

Finds the kind of each name like `generate`, and refuses a name found on both sides: prefix it with `table:` or `procedure:`, which also skips the catalog lookup. Names are upper-cased like Db2 does, quoted names are refused. A view is described only when it is a plain projection of one table, an alias is refused with the name of the table it points to: see [models.md](models.md#views).

## `probe`

```sh
npx db2kit probe MYSCHEMA.FIND_CLIENT -e .env
npx db2kit probe MYSCHEMA.FIND_CLIENT --status "RETURN_CODE,SQL_CODE" # values of these outputs
npx db2kit probe MYSCHEMA.FIND_CLIENT --columns       # lists the columns of its result sets
npx db2kit probe MYSCHEMA.FIND_CLIENT --external      # a COBOL, PL/I or C program
npx db2kit probe MYSCHEMA.FIND_CLIENT --write-types   # writes the result set types without asking
npx db2kit probe MYSCHEMA.FIND_CLIENT -i other.json   # another cases file
```

Calls a procedure that reads, once per case of its cases file, twice in a row, and reports what it returned: the first step with a new procedure, before writing its outcome rule or reading its result sets in code.

### The cases file

Each procedure has its own cases file, at a path db2kit knows: `db2kit-cases/SCHEMA.NAME.json`, at the root of the project (next to the configuration file). Nobody guesses a name, and a file of one procedure is never read for another.

1. **First run: the file is written, no call is made.** When it does not exist, probe writes it with two cases, `found` (inputs that return rows) and `empty` (inputs that find nothing), and every input to give. Each value is an explanation of what to write, its catalog type and its form in JSON:

   ```json
   {
     "_help": "One cases file per procedure. Each case is the inputs of one call...",
     "found": {
       "CLIENT_ID": "<CHAR(10), a text of at most 10 characters, or null>",
       "SINCE": "<DATE, a text 'YYYY-MM-DD', or null>",
       "LIMIT": "<DECIMAL(11,2), a number without quotes, at most 2 decimals>"
     },
     "empty": { "...": "the same inputs" }
   }
   ```

   The inputs of `procedures.defaultInputs` are left out: db2kit fills them in at every call. A procedure without any other input gets one case, `call: {}`, and runs at once. Exit code 1 while the file holds inputs to fill in.

2. **A person fills it in.** Replace each `<...>` with a value of the test subsystem. Keys are the names of the inputs in the catalog, exactly as `SYSPARMS` and DBeaver show them (`CLIENT_ID`), the same form in every procedure whatever their properties in the generated descriptor: probe gives each value to `db.call` by property. A key that is a property name (`clientId`) or a catalog name in another case (`client_id`) is refused before any call, with the name to write instead: rename the key, the value stays. A parameter without a name in the catalog keeps its property. A key that starts with `_` is a note, not a case. Add or rename cases at will: each name is shown in the report.

3. **Next run: the calls.** Refused before any `CALL`, with exit code 1 and the line to fix: an explanation left in place, an input the procedure does not take (a file written for another procedure, with the list of the inputs it takes), and a number between quotes for a type that takes no text (`SMALLINT`, `INTEGER`, `REAL`, `DOUBLE`, `DECFLOAT`): in JSON, `100` is a number, `"100"` a text. A `DECIMAL` or a `BIGINT` takes either, the text being exact beyond what a JavaScript number holds.

The values of the cases may identify a person: probe adds `/db2kit-cases/` to the `.gitignore` of the project when it has one (`npx db2kit init` does it from the start), and says so when the project has none. It never creates a `.gitignore`, and never overwrites a cases file.

With `-i FILE`, probe reads that file instead. It must exist: a wrong path is refused before any connection, never filled with a template.

### What probe reports

The report reads from top to bottom: the procedure, the outcome rule and the cases file, one line per case, then what the cases told, each thing once.

```text
MYSCHEMA.FIND_CLIENT  READS SQL DATA, LANGUAGE SQL, PARAMETER STYLE SQL, 1 result set(s) at most

outcome rule  src/db2/generated/procedures/MYSCHEMA.FIND_CLIENT/MYSCHEMA.FIND_CLIENT.outcome.ts
              a draft, not validated yet
cases         db2kit-cases/MYSCHEMA.FIND_CLIENT.json

case      verdict  status                       rows  first   warm
found     success  returnCode "000", sqlCode 0  12    412 ms  38 ms
empty     success  returnCode "000", sqlCode 0  0     45 ms   31 ms
refused   unknown  returnCode "100", sqlCode 0  -     40 ms   29 ms
bad-date  error    -                            -     52 ms   30 ms

unknown       refused: the status differs from the success values {"returnCode":"000","sqlCode":0}.
              The outcome rule is a draft (validated: false).
error         bad-date: INVALID_DATETIME, SQLCODE -180, SQLSTATE 22007
hint          bad-date: A text converted to a DATE, TIME or TIMESTAMP does not have its form...
outputs       RETURN_CODE CHAR(3): text, SQL_CODE INTEGER: number
result set 1  20 column(s), the same in every case: --columns lists them
```

- `rows` gives the rows of each result set, comma-separated, `-` when the case returned none. `first` is the time of the first call, `warm` of the same call again.
- An error, a reason or a refused field is written once, with the cases it applies to. A case whose second call ended otherwise than the first is marked `*`, and a last line names it.
- The outputs: each with its catalog type and the kinds of value the cases received (`text or null`).
- The columns of a result set are listed when they differ from one case to another: then they are information. Otherwise, `--columns` lists them in a grid, each with its type and, when a case returned rows, the kinds of value received (`text`, `number`, `null`...).
- `success`: the success values of the rule against what the cases returned, or those of the outputs named with `--status` while the rule has none. When every case agrees on other values than the rule, a draft, probe asks in a terminal before writing them in the rule, one constant per output: `Write them as the success values of <file>? (y/N)`. Nothing is written without a yes, nor without a terminal, nor in a validated rule ([procedures.md](procedures.md#success-values-written-by-probe)).

| Point       | Rule                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| :---------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Refused     | Before any `CALL`: a procedure that modifies data (`MODIFIES SQL DATA`, a program may commit by itself), one that commits on return, and a program in an external language without `--external` (even declared to read, it can write a file or send a message). The connection stays read-only                                                                                                                                                                                                                                                                                                                                                        |
| Shown       | Per case: the verdict, the values of the status outputs, each output with its catalog type and the kind of value received (`text`, `number`, `bytes`, `null`), and each result set with its row count and its columns, their type as the driver describes them and the kind of their values. The time of the first call and of the same call again                                                                                                                                                                                                                                                                                                    |
| Status      | The outputs whose values are shown: those of the outcome rule (`success`, `statusParameters`), plus those named by `--status` (catalog names, OUT or INOUT, comma-separated). When none is known, a note lists the outputs whose name reads like a status code (`RC`, `RETURN`, `STATUS`, `SQL_CODE`, `ERR`...), never a message (`MSG`, `MESSAGE`): a text can hold data. More than three status values, or a long line of them, come apart from the line of each case: case beside case, one output per row, the outputs that are not one per field first (`returnCode`, `sqlCode`), those holding the usual value in every case counted on one row |
| Never shown | Any other value: neither the inputs, nor an output, nor a row, nor the text of a Db2 error (its code, SQLCODE and SQLSTATE only). Nothing goes to the audit sinks                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| Verdict     | `success`, `rejected` (with the fields it names) or `unknown` (with its reason) from the outcome rule of the application (`procedures/<NAME>/<NAME>.outcome.ts` under `codegen.outDir`) when its descriptor matches the catalog; `unchecked` without one. `refused`: an input db2kit refused before sending, with its field and reason. `error`: Db2 failed                                                                                                                                                                                                                                                                                           |
| Stops       | On a refusal that is not about an input (a default input that throws, a rule that does not fit the procedure), with exit code 1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |

Each call runs without the outcome rule, which then judges what it returned, as `db.call` would. A draft rule that answers `unknown` thus hides nothing: the outputs, the result sets and the reason of the verdict are all reported, and `--write-types` writes the types of what the calls returned.

The columns of the result sets, which the catalog does not describe, also come with every call in the application: `result.columns` ([procedures.md](procedures.md)).

For a procedure that declares result sets and was generated, probe compares the columns its cases returned with `procedures/<NAME>/<NAME>.results.ts` (line `result types`). The same: it says so. Other columns, or no file yet, every case agreeing: it asks in a terminal, `Write the result set types in <file>? (y/N)`, and after a yes writes them, then the descriptor, which imports them: `resultSets` of `db.call` is then typed, and each call compares what it receives with that file ([procedures.md](procedures.md#result-set-types)). A column stays nullable until a person marks it `nullable: false` there, a mark probe keeps. 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: the line says why.

`--write-types` writes them without asking, for a script or without a terminal. It then refuses before any `CALL`, with exit code 1, a procedure without result set or a descriptor missing or different from the catalog, and ends with exit code 1 when nothing could be written. The report gives each file written and its status (`created`, `updated`, `unchanged`).

## `status`

```sh
npx db2kit status                        # every procedure of the manifest
npx db2kit status MYSCHEMA.FIND_CLIENT   # the board of one, as add ends
npx db2kit status FIND_CLIENT            # the same, when one schema of the manifest has it
```

Where each procedure of the manifest stands, read from the files of the project alone: no connection, so it runs without the VPN. One line per procedure, what it does to the data (`reads` or `writes`), how many steps of its board are done, and the first one left:

```
procedure             access  state        next step
MYSCHEMA.FIND_CLIENT  reads   4 of 6 done  Refusal codes: ask which values of RETURN_CODE mean a ref...
MYSCHEMA.SAVE_ORDER   writes  ready to call
```

With a name, the board of that procedure ([add](#add)). A name the manifest does not hold, or a descriptor that is missing or exports no `defineProcedure`, is refused with what to run. The descriptor row reads `written`: whether it still matches the catalog is the work of `check`.

## `sheet`

```sh
npx db2kit sheet MYSCHEMA.SAVE_ORDER                  # db2kit-sheets/MYSCHEMA.SAVE_ORDER.html
npx db2kit sheet MYSCHEMA.SAVE_ORDER --language fr    # the same, in French
npx db2kit sheet MYSCHEMA.SAVE_ORDER --answers reply.html   # the sheet the team returned, read back
npx db2kit sheet MYSCHEMA.SAVE_ORDER --answers reply.html --json > answers.json   # its values as JSON
npx db2kit sheet MYSCHEMA.SAVE_ORDER --answers answers.json  # the JSON, corrected, read back
```

The questions only the team that owns the program answers, in a sheet for a person who does not know db2kit. `add` writes it too, as soon as it reads a rule that is not validated, and again at its end with what the calls found. Read from the files of the project alone: no connection.

One HTML file, its styles inline, no script and no other file: open it in a browser, select all, copy, and paste it into a mail (Outlook) or a Confluence page, which keep its headings and tables. The team writes in the yellow cells, then replies or completes the page. It holds:

| Part           | What it says                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| :------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Why            | Db2 can report a success while the program refused the request, so the application needs the meaning of its outputs. An unknown answer can stay empty: that value is then an anomaly, never a success. No production data is asked for                                                                                                                                                                                                                                 |
| The program    | The procedure, its language, its data access in plain words, its result sets, `COMMIT ON RETURN`                                                                                                                                                                                                                                                                                                                                                                       |
| Its parameters | Each with its direction and Db2 type, its declaration in the language of the program (PL/I: `BIN FIXED(31)`, `DEC FIXED(11,2)`, `CHAR(60) VAR`. COBOL: `PIC S9(9) COMP-5`, `PIC S9(9)V9(2) COMP-3`, the two level-49 items of a `VARCHAR`), and what db2kit understood of it: a status code to confirm, a message, the code, message or flag of a field                                                                                                                |
| The questions  | Numbered, each with what it is about and an empty answer cell, only those the outputs raise (below). Under a heading of their own, What the program does beyond its outputs: whether it ends the transaction itself, and its effects outside Db2, which a rollback leaves done                                                                                                                                                                                         |
| Test data      | Only when the procedure takes inputs to give: one row per input with its Db2 type, two columns kept for the values, an accepted call and a refused call, never the values the calls should give back, which the grid of the status outputs and the error codes already ask. Test values only                                                                                                                                                                           |
| Error codes    | On a page of its own when printed, after a page break: one row per value of a status output that is no success, numbered 1, 2, 3 (never a letter: a code may start with one): its output, its code, its kind (business refusal, HTTP 422, or technical error, HTTP 502) and its meaning, in words the application can show to its user. The codes the rule holds are already written, then 10 empty rows. More codes than rows: the team adds rows, or copies the page |
| Who and when   | Answered by, on                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| After          | What the answers become: the rule in the code, 422 for a refusal, 502 for an unknown value, `validated: true` only once they are in                                                                                                                                                                                                                                                                                                                                    |

| Question                                                                                                                                                                                                  | Asked when                                                                                                                                                    |
| :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| One row per status output and its success value, next to its Db2 type, the value the rule holds already written in the answer cell, for the team to confirm or correct. Its error codes on their own page | The outputs the rule judges, and those read like a status code it does not judge yet: an answer left empty is asked again in the next sheet                   |
| The code of an accepted field, the flag of a refusal and of a warning, an empty flag                                                                                                                      | Outputs come one per field and no status per field of the configuration or of the rule judges them yet. Each asked once for every field, never field by field |
| What an empty slot holds, what the program does with more errors than slots                                                                                                                               | Those fields are numbered error slots (`ERR1_RC`, `ERR2_RC`...)                                                                                               |
| Whether the messages can hold personal data                                                                                                                                                               | The procedure has message outputs                                                                                                                             |
| Whether the program ends the transaction itself, with a `COMMIT` or a `ROLLBACK`: it would also commit what the application wrote before it                                                               | It modifies data, without `COMMIT ON RETURN`                                                                                                                  |
| Its effects beyond the tables of Db2 (a file, an MQ message, a mail, a call to another system), and whether its MQ messages are put under syncpoint: a rollback leaves the others done                    | An external program: COBOL, PL/I, C...                                                                                                                        |

The answers come back by mail or on the page. The sheet is the same for the same files, so it can be committed. A validated rule gets none.

### Reading the answers back

`--answers <file>` reads the sheet the team returned: the reply saved as HTML by the mail client (Outlook: Save As, HTML), or the page saved by the browser. Mail clients and wikis rewrite the markup but keep the tables, so db2kit reads the tables alone, each row by what its first cells say (`Q1` and the name of the output, the text of a question, the heads of the table of the error codes, the name of an input, a label), in English or in French whatever the language of the command. A reply that quotes the sheet below the answers is read up to the quote: a second table of the program ends the reading. The rows of the error codes are read by their content, whatever their number: a page copied for more rows, or a row added without a number, counts, and a row written twice the same is one code. A sheet sent before the page of the error codes is read too, its codes from the two columns of its grid. No connection.

| Answers                      | What happens                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| :--------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| The grid and the error codes | Each value typed as the output reads it, a text or a number. The success value of each output, its refused codes and their meanings go into the rule, after a yes, as `success` constants and a `refused` key, each code with its meaning when it has one ([procedures.md](procedures.md#the-parts-of-a-rule)): the meaning becomes the reason of the HTTP 422 answer. Only into a draft db2kit wrote: a rule a person edited, or a validated one, gets the lines to write by hand. The technical errors are shown only: any value neither a success nor a refusal is already unknown |
| The test data                | The accepted and refused calls, each input typed and checked as `db.call` checks it, go into `db2kit-cases/SCHEMA.NAME.json` after a yes, as the cases `accepted` and `refused`, the other cases of the file kept. A value refused is never printed                                                                                                                                                                                                                                                                                                                                   |
| The other questions          | Printed with what to do with each answer: the status per field, `auditMessages`, a call outside a transaction. A person decides                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| Answered by, on              | Printed: the source of `validated: true`, which db2kit never writes                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |

What the rule holds is never lost: a success value the sheet comes back without stays in the rule, said under `Not read`, since a rule with one success value less would judge a call a success on fewer outputs. An output whose answer gives nothing to take keeps its success and refused values the same way. A refused value removed by the team is removed: the call is then unknown, never a success.

Refused, said under `Not read`, and the exit code 1: a row whose output or question is not the one the sheet asks now (the sheet changed since it was sent: write it again), several success values for one output (a rule takes one: ask which, or write an `evaluate`), a success value also given as an error code, an error code given as two kinds or with two meanings, an error code without its output when the sheet asks several, without its code or without a kind db2kit can read (the label of the sheet, or words with `refus` or `422`, `techn` or `502`), a value that is not of the type of the output, a call with an input left empty. A file that is the sheet of another procedure, or holds no table of the sheet, stops before anything is read.

### The answers as JSON

`--json` prints the answers as JSON on the standard output, and writes nothing nor asks anything: those of the file of `--answers`, or, without it, what the sheet holds before the team writes in it (the values of the rule in the grid, every other answer empty), to fill in by hand when the HTML cannot be read or the answers came another way. The same JSON goes back to `--answers`, which tells it from HTML by its first character: a person extracts, corrects what was not read, and gives it again. The questions in the language of the command. The problems of the extraction come under `problems`, never read back, and make the exit code 1.

```json
{
  "procedure": "MYSCHEMA.SAVE_ORDER",
  "status": {
    "RETURN_CODE": { "success": ["000"] },
    "SQL_CODE": { "success": ["0"] }
  },
  "codes": [
    {
      "output": "RETURN_CODE",
      "code": "NOK",
      "kind": "refusal",
      "meaning": "The order does not exist"
    },
    { "output": "RETURN_CODE", "code": "999", "kind": "technical", "meaning": "" }
  ],
  "questions": {
    "personal": {
      "number": 3,
      "question": "Can the messages (ERROR_MSG) hold personal data ...",
      "answer": "No"
    }
  },
  "tests": {
    "accepted": { "ORDER_ID": "A1", "AMOUNT": "10.50" },
    "refused": { "ORDER_ID": "", "AMOUNT": "" }
  },
  "answeredBy": "J. Doe",
  "answeredOn": "2026-10-20"
}
```

| Key                        | What it holds                                                                                                                                                                                                                                                                                          |
| :------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `status`                   | By catalog name of each status output the grid asks of: its success value, a list or one text. A number reads as the text typed in a cell                                                                                                                                                              |
| `codes`                    | The error codes, one entry each: `output` (left out when the sheet asks one status output), `code` (several separated by commas share the rest), `kind` (`refusal` or `technical`, or the words of the sheet) and `meaning`. Given, the list replaces the codes of the rule whole; left out, they stay |
| `questions`                | By kind of question (`convention`, `fieldAccepted`, `flag`, `fieldWarning`, `slotsEmpty`, `slotsMore`, `personal`, `commit`, `external`): its number and text on the sheet, read for a person only, and the answer                                                                                     |
| `tests`                    | The calls `accepted` and `refused`, by catalog name of each input: a text as typed in a cell, a number, or `null`. A call left all empty is not written                                                                                                                                                |
| `answeredBy`, `answeredOn` | Who answered, and when                                                                                                                                                                                                                                                                                 |

An output left out of `status` keeps what the rule holds, an empty list removes it as an empty cell does. Read back, a key the sheet does not ask now (an output, a kind of question, an input, a key unknown) is refused under `Not read`, never guessed. Its test values are those of the cases file: the JSON is never committed.

## `check`

```sh
npx db2kit check
```

For CI. Regenerates every table and procedure of the manifest in memory and compares it with the files: `unchanged`, `outdated` (the catalog changed) or `missing`. Exit code 1 when a file differs. Writes nothing. A table model only changes with its columns, its indexes, or a row count that crosses `codegen.largeTableRows`.

It also lists the outcome rules still at `validated: false`, and the missing ones. These lines are information: they do not change the exit code. A rule counts as validated only when its file contains `validated: true` literally.

With `procedures.conventions`, a `Conventions` block names, for each convention, the rules that name it. `generate` records a fingerprint of each convention in `manifest.json` (its values, its outputs, its field status with the code of its classification): when a convention changed since, the block says so, names the validated rules among those it reaches, checked against the former values, to check again with the team, and `generate` records the new fingerprint. A convention removed from the configuration is named too. A rule whose convention cannot judge it (a name the configuration does not hold, an output the procedure does not return) makes the exit code 1: every call of that procedure is refused.

```
Conventions
  standard  2 rule(s): MYSCHEMA.FIND_ORDER, MYSCHEMA.SAVE_ORDER
    changed since generate recorded it: it changes the verdicts of every rule above. Validated against the former values: MYSCHEMA.SAVE_ORDER. Check them again with the team that owns the programs. npx db2kit generate records it.
```

Then every `allowScan` of the code of the application, with its file, line and reason: each is a scan of a large table at every call, decided by a person, to review before a release. Read on the disk of the project (every `.ts`, `.js`, `.mts`... file, never `node_modules`, a build folder, a hidden folder nor `codegen.outDir`), nothing sent:

```
allowScan in the code (1): each is a scan of a large table at every call, decided by a person with its reason. Check that each one still holds.
  src/contracts/statuses.service.ts:42  allowScan: 'reference list, read once a day',
```

Then every `unchecked(` call, read the same way: a procedure called without its outcome rule, so a rejection the program reports in its outputs reads as a result ([procedures.md](procedures.md#a-call-without-its-outcome-rule)). Each call shows whole on one line, its reason included, even when it spans several lines in the file:

```
unchecked() calls in the code (1): each calls a procedure without its outcome rule, so a rejection the program reports in its outputs reads as a result. Decided by a person with its reason: check that each one still holds.
  src/orders/orders.service.ts:18  db.call(unchecked(readOrder, 'the program has no status output')
```

Neither list changes the exit code.

## `verify`

```sh
npx db2kit verify              # the first run writes db2kit-verify.json
npx db2kit verify              # the next ones compare with it
npx db2kit verify --update     # writes it again, once a change is understood
npx db2kit verify --external   # also calls programs in COBOL, PL/I, C...
```

Runs again, read only, what the application defined, and compares it with a reference: a contract test, next to the unit tests of the application. Those check its logic on a fake driver; this one checks that the programs, the views and the generated files still agree, on the test subsystem.

1. **Where.** Only on a location listed in `cli.verifyServers` ([configuration.md](configuration.md#cli)), compared with `CURRENT SERVER` before any call. Without the setting, or on another location, nothing is called.
2. **The generated files**, compared with the catalog as `check` compares them: a file that differs fails the run, with `npx db2kit generate` to run.
3. **Every procedure of the manifest that reads**, with each case of its cases file (`db2kit-cases/SCHEMA.NAME.json`), through its outcome rule, as `probe` calls it: twice per case, on the read-only connection. A procedure without a cases file, one that modifies data or commits on return, and an external program without `--external` are listed as not called, with the reason.
4. **Every table model**: three rows read through the object API, without `where` nor `orderBy`, which the index guard accepts. The rows are never shown: the read proves that the object exists, that the account may read it, and that its columns are those of the model. A refusal (`NOT_AUTHORIZED`, `UNDEFINED_OBJECT`...) fails the run.
5. **The read cases**, `db2kit-cases/reads.ts`, to try the object API and the library with the reads the application makes. The first run that finds models writes it: for each model, an example of every method that reads (`findMany`, `findFirst`, `findUnique`, `count`, `exists`, `aggregate`, `groupBy`, `findPages`, `db.compile`), and `query` and `queryOne`, the relations and a named query as comments. It runs as written, nothing to type: the values of its filters come from the **sample**, the second argument of a case.

   - `await sample.key(Tables.contract)`: the `where` of the first unique key of the model, from a row whose key columns are all set.
   - `await sample.row(Tables.contract)`: a row of the model, for any column of a `where` or a parameter of a named query.

   The sample is read once per model and per run, on first use: 20 rows without `where` nor `orderBy`, which the index guard accepts and where Db2 stops. Its values stay in the memory of the process: never shown, never written in a file nor in the reference, sent to Db2 only as the parameters of the cases. A model without such a row lists its cases as `no sample` with the reason, an empty table or no row read with every column of its first unique key set (a key on nullable columns), nothing else sent, and the run does not fail on it.

   The file is yours once written: delete a case, write others, any read of the application, with its own models and named queries. A value of your own goes in as a literal. One still to give can be written `'<fill: ...>' as never`: a case that holds one is listed `to fill`, never sent.

   ```ts
   import { defineReadCases } from 'db2kit';
   import { Models } from '../src/db2/generated/relations';
   import { Tables } from '../src/db2/generated/tables';

   export default defineReadCases({
     'contracts of a branch': async (db, sample) =>
       db.findMany(Models.contract, {
         where: { branchCode: (await sample.row(Tables.contract)).branchCode },
         take: 20,
       }),
     'contract with its payments': (db) =>
       db.findMany(Models.contract, { include: { payments: { take: 2 } }, take: 3 }),
   });
   ```

   Each case gets the read-only client of verify: a case passes when it runs, fails with the code of what refused it (`INDEX_GUARD`, `USAGE` for a write, `NOT_AUTHORIZED`...). What it returns is never kept nor compared, and shown only as a count of rows or a kind. The file sits in `db2kit-cases/`, which `init` keeps out of git: the values written in its filters may be identifiers of the test subsystem.

6. **The reference**, `db2kit-verify.json` next to the configuration file, written by the first run: for each case its verdict, the values of the status outputs (codes chosen by the team, never data), the names and types of the columns of each result set, the code of a Db2 error; for each model, readable or the code that refused it. It holds no value: commit it, so that every developer and the CI compare with the same one. The next runs list each change, one line each:

```
reference  1 change(s) since db2kit-verify.json:
  MYSCHEMA.FIND_CLIENT, case found: result set 1, gone NAME VARCHAR(40), new NAME VARCHAR(60)
  Once understood, npx db2kit verify --update writes the reference again.
```

A change is a result: a program changed, a code nobody named, a view altered, a right withdrawn. Find out why first, with the team that owns the program or the DBA; `--update` takes it as the new reference once it is understood, never to make a run pass.

Exit code 1 when a generated file differs, a model cannot be read or loaded, a read case fails, or something changed since the reference; 0 otherwise. The report ends with the calls and reads sent to Db2, the sample reads included and the catalog reads aside: the load put on the subsystem. Run it after `generate`, after a change announced by the team that owns a program, and in a CI job that can reach the test subsystem.

Not yet: calls in parallel through the pool, and connections cut on purpose through a local relay (roadmap, Next steps).

Every command, like `doctor`, connects in read-only mode.
