# Rules for code assistants

For an assistant, or a developer, writing application code that uses db2kit. The package ships this page.

Right after the install, `npx db2kit init` points the instructions of the project to it: it writes a db2kit section in `AGENTS.md` at the root, or creates that file after a yes in a terminal (`codegen.projectInstructions` names another file, `CLAUDE.md` or `.github/copilot-instructions.md` for instance, or `false`). The section holds the rules an assistant could break on its first task, before anything is generated (Never, below), and points here. `npx db2kit doctor` warns while it is missing or out of date.

`npx db2kit generate` then writes `AGENTS.md` in the folder of the generated files: the index of every page of this documentation, every command of the CLI with its options (the list `npx db2kit help` shows), the configuration checklist with the values in effect, the configuration of the project (status per field, inputs every procedure takes) and the outcome rules still to write. Each `generate` keeps the section of the project up to date.

db2kit refuses before sending anything to Db2 rather than guess. A refusal is information about the call, never an obstacle to work around.

## Never

- Open, read, search or attach `.env`, the file `cli.envFile` names, or any other file that holds the password of the connection: what an assistant reads leaves the machine. `npx db2kit doctor` checks the connection and never shows the password. To know which variables are set, ask the person.
- Try a login again after a refused one (`SQL30082N`, `AUTHENTICATION_FAILED`): a person checks the password first, since a few failures can revoke the account.
- Generate more than the objects a person named (Generating, below).
- Answer a question of `npx db2kit` for the person, or feed it answers (a pipe, `yes`, a scripted terminal): `add`, `probe`, `sheet` and `init` ask what only a person knows. Without a terminal, `add` does what needs no answer and says where it stopped: tell the person the command to run.
- Write `unchecked(descriptor, reason)` or `allowScan` to make a TypeScript error or a refusal of db2kit go away: each holds the reason of a person who decided it.
- Write an answer of the team that owns a program: in its sheet, in a JSON of answers or in a rule. Success values, error codes and their meanings are the words of that team (The sheet for the team that owns the program, below).

## Setting up a project, in order

Each step ends with what the person checks, before the next one starts. Say which step the project is at before proposing work, from the files of the project (the configuration file, the generated files, the rules at `validated: true`), and let the person check each step: never check one for them.

1. **`npx db2kit init`**: the section of the instruction file, and `db2kit.config.mts` when the project has none. Done when you read these rules through it.
2. **The configuration file**, `db2kit.config.mts` at the root, the one configuration of the project: the CLI reads it at each command, the application when it creates its client ([installation.md](installation.md#configure)). `connectionFromEnv` with the prefix of the variables, never their values. A value that changes with the environment (pool size, read-only mode) is read there from `process.env`. It imports `db2kit` only. The person fills in the environment file. Then `npx db2kit doctor`: no `FAIL`. Only the variables `connectionFromEnv` names are read (`_DATABASE`, `_HOST`, `_PORT`, `_USERNAME`, `_PASSWORD`, `_CURRENT_SCHEMA`, `_EXTRA_KEYWORDS`): another variable with the same prefix does nothing, unless the file reads it.
3. **The application reads that file**, never a copy of it: with NestJS, `Db2Module.forRootAsync` whose factory awaits `ConfigModule.envVariablesLoaded` when the application uses `@nestjs/config`, then returns `{ config: await loadConfigFile() }` ([nestjs.md](nestjs.md#module)); `createDb2(await loadConfigFile())` otherwise. What only the application needs (sinks with its logger) is added to what the file gives. Never `Db2Module.forRoot({ config: { ... } })` with values written in the code: they drift from the file the descriptors and rules were generated with. `UV_THREADPOOL_SIZE` at least `pool.max + 2`, set in the environment that starts the process (a script, an image), not in a file the application loads after its start. In production, the image holds `db2kit.config.mts`. Start the application once: an unknown key stops the startup, a threadpool too small is warned about.
4. **The first feature**: the objects one feature reads, added for it by the person with `npx db2kit add SCHEMA.NAME` (Generating, below), then a service that injects the client (`@Inject(DB2)`). When the feature replaces existing code, compare both on the same request: the same rows, the same count.
5. **The procedures the code calls**, one at a time: `npx db2kit add SCHEMA.NAME` in a terminal, run by the person, for the descriptor, the cases, the calls, the success values and the result set types; then the outcome rule with the team that owns each program ([installation.md](installation.md#add-a-stored-procedure)). A person sets `validated: true`.
6. **Tests**: `db2kit/testing` ([testing.md](testing.md)).

## Generating

- Generate what the code of the application uses: the objects its SQL reads, the procedures it calls, found by a search of its code and of its current descriptors. A new application has no code to search: ask the person for the first object the feature needs.
- Before any `generate`, show `npx db2kit list` of the schema with what you propose, then wait for the answer. Never a whole schema or a whole kind of objects, never a pattern the person did not choose, never `-y`: it confirms for the person.
- One model per table: a table and a view that gives its rows, or two views that give the same rows, are the same data. The person chooses which one the application reads.
- One object at a time, `npx db2kit add SCHEMA.NAME` is the command to propose: it generates, then asks the person what only a person knows (a second model of one table, each relation its columns suggest, the status outputs and cases of a procedure, the calls). Propose the command, never run it with answers.
- Run `npx db2kit generate` without arguments only to follow a catalog change: it regenerates every object of `manifest.json`.

## Configuration

- One file, `db2kit.config.mts`, for the CLI and the application: the application reads it with `loadConfigFile`, never a copy in its code (Setting up a project, step 3). To change a setting, change the file.
- After each update of db2kit, and before changing its configuration, go through the configuration checklist of the `AGENTS.md` that `generate` writes: every setting with its value in effect, `(default)` when nobody decided it, and what to decide. The whole to-do list is [checklists.md](checklists.md).
- A setting left at its default is a decision too: say which ones the developer should look at, never change one silently.

## Before writing a call

- Read the generated model or descriptor first. Hovering a property or a model shows the format of each value, the filters the index guard accepts and the unique keys.
- Result set types come from `npx db2kit probe`, run by a person on the test subsystem, who answers its question, never from a guess: never write a `.results.ts` file by hand, and set `nullable: false` there only for a column a person says is never null.
- Every type is generated: never declare one by hand that repeats it. A service imports the call and its types from the rule, `import { xxxWithOutcome, type XxxInput } from '.../<NAME>.outcome'` (the rule re-exports `XxxInput` and `XxxOutput` of its descriptor since 0.29.0, an older rule from `.generated.ts`), the rows of the result sets from `.results.ts`, a table's row and fields from its model. An entity, a DTO or a mapper starts from these types.
- Never edit a `*.generated.ts` file. When the catalog changed, run `npx db2kit generate` (add `-e .env` when the connection variables are in a file that `cli.envFile` does not name).

## Reads with the object API

- `findMany` always has `take`, at most `models.maxTake`.
- On a large table, `where` covers the leading keys of an index listed in the TSDoc of the model; a generated model checks it in its types (`ModelIndexed`). When the guard or TypeScript refuses, change the filter, read a smaller table (a reference table rather than the distinct values of a large one), or propose a cache. Never write `allowScan` to make a refusal or a TypeScript error go away: it takes the reason of the person who decided the scan, who writes it. A refusal has `code: 'INDEX_GUARD'`; log the `message` of a `Db2UsageError`, which says why and never holds a value.
- No `skip` and no `OFFSET`: page with `cursor` and an `orderBy` that includes every column of a unique key.
- A property given as a value (`by` of `groupBy`) or as a computed key comes from the `<Name>Field` constant of its generated model, a sort direction from `SortOrder`: `by: [ContractField.status]`, `orderBy: { [ContractField.startDate]: SortOrder.Desc }`. Never a text repeated across files.
- `findUnique` takes exactly the columns of one unique key. The TypeScript error "This model has no unique key" means: use `findFirst` or `findMany`.
- `contains` and `endsWith` never use an index. Prefer `startsWith` or an equality.

## Values

- Dates, times and timestamps are text, never `Date` objects: `'YYYY-MM-DD'` for a `DATE`, `'HH:MM:SS'` for a `TIME`, `'YYYY-MM-DD HH:MM:SS.FFFFFF'` for a `TIMESTAMP`. db2kit refuses any other form before sending, `'20260105'` included: a program that takes a date as `YYYYMMDD` has a `CHAR` parameter, which takes a codec (`codecs.dateText`). No time zone conversion happens in db2kit: convert at the edge of the application, with the time zone of the data.
- A decimal value with more decimals than the column scale is refused. Round it explicitly in the application, with the rounding the business expects, never by accident.
- `BIGINT` values and `DECIMAL` beyond 15 digits are strings: keep them as strings.
- A `CHAR` value is read without its trailing blanks.

## Writes with the object API

- Write a table with `create`, `update`, `updateMany`, `delete` or `deleteMany` only when `models.writable` lists it. When a stored procedure performs the same write, call the procedure: it holds the rules of the program.
- `update` and `delete` return 0 when no row has the key: check the count.
- `updateMany` and `deleteMany` take a `where` that uses an index, as reads do. Never a write of every row through the object API.

## SQL

- Every value goes through the `sql` tag: `` sql`... WHERE ID = ${id}` `` sends a marker. Never build SQL text by concatenation, never put input into `sql.raw`.
- `db.query` and `db.queryOne` read, `db.execute` writes, `db.call` calls a procedure. Each refuses the others' statements.
- Page with `FETCH FIRST n ROWS ONLY` and a keyset condition, not `OFFSET`.
- A read the object API cannot express (a join, an aggregate) becomes a named query: `defineQuery` in the queries folder of the application, with its parameters, its row type and its `columns`, called with `db.run`. Not `db.query` inline in a service.

## Stored procedures

- Call with the generated procedure, inputs by property name. An input listed in `procedures.defaultInputs` is left out of the call, and of the cases file of `probe`: db2kit fills it in.
- An input every procedure of the application takes (a header, the calling user) is declared once in `procedures.defaultInputs` of `db2kit.config.mts`, with its value or a function, then `generate` runs again. Never repeated in each call, service or cases file. When the generated procedures share one and it is not declared, propose it.
- Call the `...WithOutcome` export of its `.outcome.ts`. `db.call` refuses the descriptor alone, in the types and at run time: it checks nothing. A call without its rule is `unchecked(descriptor, reason)`, written by a person with the reason, never by an assistant to make a TypeScript error go away (`outcome: 'unchecked'`, listed by `npx db2kit check`).
- After an update to db2kit 0.30.0, each `db.call(descriptor, input)` left in the application is a TypeScript error. For each: when its procedure has a rule, call its `...WithOutcome` export, the same inputs. When it has none, list the call for the person (file, line, procedure, whether it modifies data) and wait for the choice: write the rule (`npx db2kit add`), or a call through `unchecked()` with the reason the person gives. Never wrap them all in `unchecked()` to make the build pass: the refusal exists to find them.
- A fixed-format input (padded number, implied cents, `YYYYMMDD`) gets a codec in `defineInputs`. Never format it by hand in a service.
- A procedure that modifies data needs an outcome rule (its `.outcome.ts`). Never guess which output value means success: ask the team that owns the program.
- Prefer data to code in a rule: `success` values for when a call succeeds, `refused` values for a refusal, each with the meaning the team gives it when there is one (`{ returnCode: { NOK: 'The order does not exist' } }`, the reason of the HTTP 422 answer), a status per field when the program reports a code and a message per field. Write `evaluate` only for what they cannot say, and never return `success` from it when `successMatched` is false.
- The status per field has a default and an override. The default, for every procedure, is `procedures.fieldStatus` of `db2kit.config.mts`; a rule takes it with `fieldStatus: null`, overrides it with its own `defineFieldStatus({ ... })` for a program that differs, and has none without the key. When a draft shows an example built from the outputs, the code of an accepted field comes from the program or its team, never from a guess. An output is a success value or part of a field, never both: remove from `success` the outputs a field status groups.
- Values in a rule or a field status are enums or constants of the project, never literal strings repeated across files.
- After `npx db2kit add`, its `Next:` block is what is left, in order. The first step, when there is one, is the sheet of the procedure to send to the team that owns the program (below). The questions only that team answers, named for this procedure (the codes of its fields, the values of its global codes that mean a refusal), are the `TO DO` rows of the board just above it and the sheet: give them to the person as they are, and write no code in the rule before the answers. Until then, an answer the rule does not recognize ends `unknown` (HTTP 502), never a silent success.
- When `add` says the rule holds success values for outputs that come one per field, the person answers its question: it writes the draft again without them. In a rule edited by hand, remove them from `success` with their constants.
- Never set `validated: true` in an outcome rule. It states that a person checked the rule against the program.
- A rule that names a convention (`convention: 'name'`) takes its values from `procedures.conventions` of `db2kit.config.mts`: a change of a convention changes the verdicts of every rule that names it. Never change one without the person. `npx db2kit check` then names the rules it reaches, the validated ones to check again with the team.

## Where a procedure stands

- `npx db2kit status` gives one line per procedure of the project, `npx db2kit status SCHEMA.NAME` its board, one row per step: read from the files alone, without a connection. Read it before proposing work on a procedure, and propose its first row marked `TO DO` or `FAILED`.

## The sheet for the team that owns the program

- `npx db2kit add` writes `db2kit-sheets/SCHEMA.NAME.html` while the rule is not validated, and `npx db2kit sheet SCHEMA.NAME` writes it again: the questions only that team answers, the success value of each status output as the rule holds it, and on a page of their own the error codes, each with its kind and its meaning. It holds no value of the test subsystem. Give its path to the person, to send by mail or paste into a wiki page. Never fill it in: every answer is the team's.
- The reply comes back as HTML, the mail or the page saved by the person. The person runs `npx db2kit sheet SCHEMA.NAME --answers FILE` in a terminal and answers its questions: it writes the success values, the refused values and their meanings into the rule, the test data into the cases file, each after a yes, and prints the other answers with what to do with them. Never run it with answers fed to it.
- `--json` added to it prints what was read, as JSON, and writes nothing: show it to the person. A line under `Not read` goes back to the person and the team, never fixed by guessing a value. A JSON of answers is written by a person from the reply of the team, never by an assistant.
- The meaning of an error code becomes the reason of the HTTP 422 answer: the words of the team, never words of an assistant.

## Trying a procedure with probe

- `npx db2kit probe SCHEMA.NAME` calls a procedure that reads with the inputs of its own cases file, `db2kit-cases/SCHEMA.NAME.json` at the root of the project. Each procedure has its own: never reuse the file of another, never pass another file with `-i` to work around a refusal. The keys of a case are the names of the inputs in the catalog (`CLIENT_ID`), never their properties: `db.call` takes properties, a cases file the names of the catalog.
- The first run writes that file and makes no call: cases `found` and `empty`, with every input to give, each value an explanation `<TYPE, form>`. Say so to the person: they replace each explanation with a value of the test subsystem, a number without quotes (`100`, not `"100"`). Never invent a value, never write one from a name or a guess.
- probe refuses an explanation left in place, an input the procedure does not take, and a number between quotes for a type that takes no text, before any call: give the person the line it names.
- Once filled in, the file may identify a person: never read, show, copy or commit it. Its folder is in `.gitignore` (`init` and probe add it). When the project has no `.gitignore`, say so.
- A draft rule that answers `unknown` still shows every output type and the result sets, with its reason. When no rule names a status yet, `--status "NAME,NAME"` (in quotes, without space: PowerShell splits a list at its commas) shows the values of the outputs that hold codes, never data: the note of probe lists those whose name reads like a status.
- The report is evidence for the outcome rule: its status values, confirmed with the team that owns the program, become the `success` values.
- `add` calls a procedure only for what is missing: run again once the rule and the types are written, it calls nothing. To check a rule before `validated: true`, propose `npx db2kit probe SCHEMA.NAME`: it calls the cases at each run, each judged by the rule.

## Transactions

- Inside `db.$transaction(async (tx) => ...)`, use only `tx`, and await each call.
- Keep HTTP calls, file access and any wait outside: the locks are held until the end.
- After any error inside, the transaction can only roll back, even when the callback catches the error. Do not catch and go on.
- No nested transaction.

## Errors

- Recognize errors by class (`instanceof`) and `code`, never by message.
- `Db2InputError`: the values were refused before sending. `issues` says which and why.
- `Db2TransactionCommitError` and `PROC_STATUS_UNKNOWN`: the outcome is unknown. Never retry without checking the effect first.
- In NestJS, `Db2ExceptionFilter` turns them into HTTP responses: do not wrap them into a generic 500.

## Tests

- Unit tests use `db2kit/testing` (`FakeDriver`, `onCall`), never a real subsystem.
- A test calls the procedure as the service does, through its `...WithOutcome` export, so that the rule is tested too. A test of what a program returns before its rule exists may use `unchecked(descriptor, 'unit test')`.
- No personal data in logs, fixtures or cassettes. Keep `audit.params: 'types'`.

## Never without a person deciding

- `generate` of more than the objects a person named, a pattern, `-y`.
- An answer to a question of `npx db2kit add`, `probe` or `init`, `--external`, `--rollback`, a location added to `cli.rollbackServers` (never the one of production).
- `allowScan` (its reason is written by the person who decided the scan), `unchecked(descriptor, reason)` (the same, for a call without its outcome rule), `validated: true`, `readOnly: false`, `models.indexGuard: 'warn'`, a table added to `models.writable`.
- `audit.params: 'full'`, or a longer `retentionDays`: how long audit events are kept is decided with the data protection officer.
- Credentials, hosts or user names in code or configuration: use `connectionFromEnv`.
- A login attempt with a password that may be wrong against a real subsystem: a few failures can revoke the account.

## Every page of the documentation

The package ships every page of the table below next to this one, in `node_modules/db2kit/docs/`. Read the page of a subject before writing code about it. The `AGENTS.md` that `generate` writes lists them too.

| Page                                 | Read it for                                                                             |
| :----------------------------------- | :-------------------------------------------------------------------------------------- |
| [installation.md](installation.md)   | Install, the two configurations, add a table, add a stored procedure, update            |
| [configuration.md](configuration.md) | Every key, its default and its purpose                                                  |
| [checklists.md](checklists.md)       | What an application checks or decides after an update                                   |
| [client.md](client.md)               | Every method of the client: statements, context, `ping`, `poolStats`, `health`, `close` |
| [cli.md](cli.md)                     | Commands, options, exit codes, reading the `doctor` report                              |
| [queries.md](queries.md)             | `query`, `queryOne`, `execute`, `sql`, value types, performance rules                   |
| [models.md](models.md)               | Generation, `findMany`, `findUnique`, `count`, `exists`, cursor, index guard            |
| [procedures.md](procedures.md)       | Generation, `db.call`, outcome rules, how parameters travel                             |
| [transactions.md](transactions.md)   | `db.$transaction`, rollback-only, timeout, procedures refused, audit                    |
| [errors.md](errors.md)               | Error classes, codes, what to do                                                        |
| [audit.md](audit.md)                 | Events, sinks, retention, context, statistics, N+1, correlation with the DBA            |
| [nestjs.md](nestjs.md)               | `db2kit/nestjs`: module, context interceptor, exception filter, health check            |
| [testing.md](testing.md)             | `db2kit/testing`: fake driver for unit tests, recording and replay of a test subsystem  |
| [production.md](production.md)       | Checklist before going to production                                                    |

About db2kit itself, not needed to use it and not in the package, in the repository of db2kit under `docs/`: [verification.md](verification.md) (Checking db2kit: `npm run check`, mutation testing, the integration suites), [integration-tests.md](integration-tests.md) (Tests against a test subsystem: settings, guards, how to run them), [acceptance.md](acceptance.md) (Every tool of the packed archive, tried from a throwaway project by a code assistant), [architecture.md](architecture.md) (Principles, path of a query, modules), [roadmap.md](roadmap.md) (Status, next steps, design decisions, open questions).
