Skip to content

Open-source personal finance manager. Self-hosted, privacy-first.

test/api-contract-sweep-upstream: add an API contract sweep over every route (#1164)

Rogerio Camorim87faf3a883ff
diff --git a/backend/tests/api_contract/README.md b/backend/tests/api_contract/README.md
new file mode 100644
index 00000000..61715c37
--- /dev/null
+++ b/backend/tests/api_contract/README.md
@@ -0,0 +1,85 @@
+# API contract sweep
+
+Every route in the OpenAPI spec, every method, checked against an exact
+expected status code.
+
+## Safety: test data only, never a real account
+
+The sweep runs **in-process**, against the throwaway SQLite database the
+test suite creates. Its users are fakes from `tests/conftest.py`
+(`[email protected]`, an admin, a viewer). Nothing reaches Postgres, a
+running stack, or the internet.
+
+Do not point it, or a copy of it, at a real account or a deployed instance.
+About 185 of the cases write data: they delete transactions, accounts,
+categories and groups, archive workspaces, merge payees, void invoices and
+change admin settings. On real data that destroys the data.
+
+To look at a running stack, only read from it, as a disposable user on a
+local dev install. Never use prod or your own account.
+
+## Usage
+
+```bash
+cd backend
+uv run pytest tests/api_contract -n auto # run the sweep (part of the normal suite)
+uv run pytest tests/api_contract -n auto -k "ok:POST /api/budgets" # one route
+```
+
+A failure reads `METHOD path [variant] expected X, got Y: <response>`.
+Decide whether the change is intended (see "The baseline" below) before
+touching the baseline.
+
+## What runs
+
+Each operation fans out into variants (`cases.py`):
+
+| Variant | Caller | Data | Usually expects |
+|--------------|---------------------------|--------------------------|-----------------|
+| `ok` | owner (admin for `/api/admin/*`) | seeded world, generated body | 2xx, or the domain rule that applies |
+| `viewer` | viewer-role member | seeded world | 403 on writes |
+| `empty` | owner | `{}` body | 422 |
+| `unknown_id` | owner | random ids | 404 |
+| `anon` | nobody | random ids | 401 |
+
+`ok` and `viewer` run against a **world**: one business workspace seeded
+through the API (`world.py`), rebuilt per case so DELETEs can't leak. The
+other variants run in the default personal workspace without seeded data.
+
+Outbound network is blocked. Routes that call a provider answer with their
+own error handling (502/503), and that answer is part of the contract.
+
+## The baseline
+
+`baseline.json` holds the expected status per `variant` and `METHOD path`.
+A failing case means the route's behaviour changed:
+
+- **Intentional** (new validation, new field, new rule): regenerate the
+ baseline in the same PR. The JSON diff documents the change for review.
+- **Regression**: fix the code.
+
+Regenerate (serial, about 2 minutes):
+
+```bash
+UPDATE_API_CONTRACT=1 uv run pytest tests/api_contract -n 0
+# also dump why `ok` cases didn't reach a 2xx:
+UPDATE_API_CONTRACT=1 API_CONTRACT_DETAILS=/tmp/details.jsonl uv run pytest tests/api_contract -n 0
+```
+
+Review the diff before committing. The baseline may never expect a 500.
+`test_baseline_has_no_unhandled_errors` enforces that, and a new route
+with no baseline fails `test_baseline_covers_every_operation`.
+
+## Exceptions, all in `cases.py`
+
+- `KNOWN_BUGS`: a bug on the baseline branch. The baseline holds the
+ correct status and the case is a strict xfail until the fix lands.
+- `DELIBERATE_500`: routes that raise `HTTPException(500)` on purpose.
+- `POSTGRES_ONLY`: SQL SQLite can't run. These are skipped here.
+- `BODY_OVERRIDES` / `PARAM_WORLD_KEYS_*`: where the generated request
+ isn't enough to reach the happy path.
+
+## Why several test files
+
+CI runs `--dist loadfile`, which keeps a file on one worker. The cases are
+sharded over `test_contract_*.py` so the sweep runs in parallel.
diff --git a/backend/tests/api_contract/__init__.py b/backend/tests/api_contract/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/backend/tests/api_contract/baseline.json b/backend/tests/api_contract/baseline.json
new file mode 100644
index 00000000..af0acb6f
--- /dev/null
+++ b/backend/tests/api_contract/baseline.json
@@ -0,0 +1,1044 @@
+{
+ "anon": {
+ "DELETE /api/accounts/{account_id}": 401,
+ "DELETE /api/admin/settings/{key}": 401,
+ "DELETE /api/admin/users/{user_id}": 401,
+ "DELETE /api/agents/connections/{conn_id}": 401,
+ "DELETE /api/agents/conversations/{conversation_id}": 401,
+ "DELETE /api/agents/{agent_id}": 401,
+ "DELETE /api/agents/{agent_id}/knowledge/{doc_id}": 401,
+ "DELETE /api/asset-groups/{group_id}": 401,
+ "DELETE /api/assets/transactions/{tx_id}": 401,
+ "DELETE /api/assets/values/{value_id}": 401,
+ "DELETE /api/assets/{asset_id}": 401,
+ "DELETE /api/auth/passkeys/{passkey_id}": 401,
+ "DELETE /api/budgets/{budget_id}": 401,
+ "DELETE /api/categories/{category_id}": 401,
+ "DELETE /api/category-groups/{group_id}": 401,
+ "DELETE /api/collections/{collection_id}": 401,
+ "DELETE /api/connections/transfers/{pair_id}": 401,
+ "DELETE /api/connections/{connection_id}": 401,
+ "DELETE /api/goals/{goal_id}": 401,
+ "DELETE /api/groups/{group_id}": 401,
+ "DELETE /api/groups/{group_id}/members/{member_id}": 401,
+ "DELETE /api/groups/{group_id}/settlements/{settlement_id}": 401,
+ "DELETE /api/import-logs/{import_log_id}": 401,
+ "DELETE /api/invoice-schedules/{schedule_id}": 401,
+ "DELETE /api/invoice-schedules/{schedule_id}/terms/{term_id}": 401,
+ "DELETE /api/invoices/settings/logo": 401,
+ "DELETE /api/invoices/{invoice_id}": 401,
+ "DELETE /api/invoices/{invoice_id}/allocations/{allocation_id}": 401,
+ "DELETE /api/invoices/{invoice_id}/attachments/{attachment_id}": 401,
+ "DELETE /api/invoices/{invoice_id}/deductions/{deduction_id}": 401,
+ "DELETE /api/invoices/{invoice_id}/schedule": 401,
+ "DELETE /api/invoices/{invoice_id}/share": 401,
+ "DELETE /api/payees/{payee_id}": 401,
+ "DELETE /api/products/{product_id}": 401,
+ "DELETE /api/products/{product_id}/prices/{price_id}": 401,
+ "DELETE /api/reconciliation/rules/{node}/{strategy_id}": 401,
+ "DELETE /api/recurring-transactions/{recurring_id}": 401,
+ "DELETE /api/rules/{rule_id}": 401,
+ "DELETE /api/transactions/{transaction_id}": 401,
+ "DELETE /api/transactions/{transaction_id}/attachments/{attachment_id}": 401,
+ "DELETE /api/users/{id}": 401,
+ "DELETE /api/workspaces/{workspace_id}/members/{member_user_id}": 401,
+ "GET /api/accounts": 401,
+ "GET /api/accounts/{account_id}": 401,
+ "GET /api/accounts/{account_id}/balance-history": 401,
+ "GET /api/accounts/{account_id}/bills": 401,
+ "GET /api/accounts/{account_id}/summary": 401,
+ "GET /api/admin/accounting-mode": 401,
+ "GET /api/admin/date-format": 401,
+ "GET /api/admin/default-colors": 200,
+ "GET /api/admin/number-format": 401,
+ "GET /api/admin/registration-status": 200,
+ "GET /api/admin/settings/{key}": 401,
+ "GET /api/admin/timezone": 401,
+ "GET /api/admin/users": 401,
+ "GET /api/admin/users/{user_id}": 401,
+ "GET /api/agents": 401,
+ "GET /api/agents/connections": 401,
+ "GET /api/agents/connections/{conn_id}": 401,
+ "GET /api/agents/conversations": 401,
+ "GET /api/agents/conversations/{conversation_id}": 401,
+ "GET /api/agents/conversations/{conversation_id}/messages": 401,
+ "GET /api/agents/default": 401,
+ "GET /api/agents/info": 200,
+ "GET /api/agents/{agent_id}": 401,
+ "GET /api/agents/{agent_id}/knowledge": 401,
+ "GET /api/agents/{agent_id}/tools": 401,
+ "GET /api/asset-groups": 401,
+ "GET /api/assets": 401,
+ "GET /api/assets/import/template": 401,
+ "GET /api/assets/market/quote": 401,
+ "GET /api/assets/market/search": 401,
+ "GET /api/assets/portfolio-trend": 401,
+ "GET /api/assets/transactions": 401,
+ "GET /api/assets/{asset_id}": 401,
+ "GET /api/assets/{asset_id}/transactions": 401,
+ "GET /api/assets/{asset_id}/value-trend": 401,
+ "GET /api/assets/{asset_id}/values": 401,
+ "GET /api/auth/oidc/callback": 400,
+ "GET /api/auth/oidc/config": 200,
+ "GET /api/auth/oidc/login": 500,
+ "GET /api/auth/passkeys": 401,
+ "GET /api/budgets": 401,
+ "GET /api/budgets/comparison": 401,
+ "GET /api/categories": 401,
+ "GET /api/categories/{category_id}/rule-usage": 401,
+ "GET /api/categories/{category_id}/usage": 401,
+ "GET /api/category-groups": 401,
+ "GET /api/collections": 401,
+ "GET /api/connections": 401,
+ "GET /api/connections/providers": 200,
+ "GET /api/connections/{provider}/institutions": 401,
+ "GET /api/currencies": 200,
+ "GET /api/dashboard/balance-history": 401,
+ "GET /api/dashboard/monthly-trend": 401,
+ "GET /api/dashboard/projected-transactions": 401,
+ "GET /api/dashboard/spending-by-category": 401,
+ "GET /api/dashboard/summary": 401,
+ "GET /api/export/backup": 401,
+ "GET /api/fiscal/jurisdictions": 200,
+ "GET /api/fiscal/product-fields": 401,
+ "GET /api/fiscal/tax-id-kinds": 401,
+ "GET /api/fx-rates/status": 401,
+ "GET /api/goals": 401,
+ "GET /api/goals/summary": 401,
+ "GET /api/goals/{goal_id}": 401,
+ "GET /api/groups": 401,
+ "GET /api/groups/{group_id}": 401,
+ "GET /api/groups/{group_id}/balances": 401,
+ "GET /api/groups/{group_id}/members": 401,
+ "GET /api/groups/{group_id}/settlements": 401,
+ "GET /api/groups/{group_id}/transactions": 401,
+ "GET /api/health": 200,
+ "GET /api/import-logs": 401,
+ "GET /api/info": 200,
+ "GET /api/invoice-schedules": 401,
+ "GET /api/invoice-schedules/summary": 401,
+ "GET /api/invoice-schedules/{schedule_id}": 401,
+ "GET /api/invoice-schedules/{schedule_id}/invoices": 401,
+ "GET /api/invoice-schedules/{schedule_id}/periods": 401,
+ "GET /api/invoices": 401,
+ "GET /api/invoices/facets": 401,
+ "GET /api/invoices/issuer": 401,
+ "GET /api/invoices/logo/{logo_id}": 401,
+ "GET /api/invoices/settings": 401,
+ "GET /api/invoices/summary": 401,
+ "GET /api/invoices/{invoice_id}": 401,
+ "GET /api/invoices/{invoice_id}/attachments": 401,
+ "GET /api/invoices/{invoice_id}/attachments/{attachment_id}": 401,
+ "GET /api/invoices/{invoice_id}/document": 401,
+ "GET /api/invoices/{invoice_id}/pdf": 401,
+ "GET /api/invoices/{invoice_id}/statement": 401,
+ "GET /api/payees": 401,
+ "GET /api/payees/{payee_id}": 401,
+ "GET /api/payees/{payee_id}/summary": 401,
+ "GET /api/products": 401,
+ "GET /api/products/{product_id}": 401,
+ "GET /api/public/invoices/{token}": 404,
+ "GET /api/public/invoices/{token}/logo": 404,
+ "GET /api/public/invoices/{token}/pdf": 404,
+ "GET /api/reconciliation/history": 401,
+ "GET /api/reconciliation/rules": 401,
+ "GET /api/reconciliation/rules/export": 401,
+ "GET /api/reconciliation/suggestions": 401,
+ "GET /api/recurring-transactions": 401,
+ "GET /api/reports/cash-flow": 401,
+ "GET /api/reports/income-expenses": 401,
+ "GET /api/reports/net-worth": 401,
+ "GET /api/rules": 401,
+ "GET /api/rules/export": 401,
+ "GET /api/rules/packs": 401,
+ "GET /api/search": 401,
+ "GET /api/settings/attachments": 200,
+ "GET /api/setup/status": 200,
+ "GET /api/timezones": 401,
+ "GET /api/transactions": 401,
+ "GET /api/transactions/calendar": 401,
+ "GET /api/transactions/export": 401,
+ "GET /api/transactions/{transaction_id}": 401,
+ "GET /api/transactions/{transaction_id}/attachments": 401,
+ "GET /api/transactions/{transaction_id}/attachments/{attachment_id}": 401,
+ "GET /api/transactions/{transaction_id}/transfer-candidates": 401,
+ "GET /api/transactions/{transaction_id}/transfer-pair": 401,
+ "GET /api/users/directory": 401,
+ "GET /api/users/lookup": 401,
+ "GET /api/users/me": 401,
+ "GET /api/users/{id}": 401,
+ "GET /api/workspaces": 401,
+ "GET /api/workspaces/current": 401,
+ "GET /api/workspaces/{workspace_id}/members": 401,
+ "GET /api/workspaces/{workspace_id}/stats": 401,
+ "PATCH /api/accounts/{account_id}": 401,
+ "PATCH /api/admin/settings/{key}": 401,
+ "PATCH /api/admin/users/{user_id}": 401,
+ "PATCH /api/agents/connections/{conn_id}": 401,
+ "PATCH /api/agents/conversations/{conversation_id}": 401,
+ "PATCH /api/agents/{agent_id}": 401,
+ "PATCH /api/agents/{agent_id}/knowledge/{doc_id}/pin": 401,
+ "PATCH /api/asset-groups/{group_id}": 401,
+ "PATCH /api/assets/transactions/{tx_id}": 401,
+ "PATCH /api/assets/{asset_id}": 401,
+ "PATCH /api/budgets/{budget_id}": 401,
+ "PATCH /api/categories/{category_id}": 401,
+ "PATCH /api/category-groups/{group_id}": 401,
+ "PATCH /api/collections/{collection_id}": 401,
+ "PATCH /api/connections/{connection_id}/settings": 401,
+ "PATCH /api/goals/{goal_id}": 401,
+ "PATCH /api/groups/{group_id}": 401,
+ "PATCH /api/groups/{group_id}/members/{member_id}": 401,
+ "PATCH /api/groups/{group_id}/settlements/{settlement_id}": 401,
+ "PATCH /api/invoice-schedules/{schedule_id}": 401,
+ "PATCH /api/invoice-schedules/{schedule_id}/terms/{term_id}": 401,
+ "PATCH /api/invoices/issuer": 401,
+ "PATCH /api/invoices/settings": 401,
+ "PATCH /api/invoices/{invoice_id}": 401,
+ "PATCH /api/invoices/{invoice_id}/attachments/{attachment_id}": 401,
+ "PATCH /api/payees/{payee_id}": 401,
+ "PATCH /api/products/{product_id}": 401,
+ "PATCH /api/products/{product_id}/prices/{price_id}": 401,
+ "PATCH /api/reconciliation/rules/{node}/{strategy_id}": 401,
+ "PATCH /api/recurring-transactions/{recurring_id}": 401,
+ "PATCH /api/rules/{rule_id}": 401,
+ "PATCH /api/transactions/bulk-add-tags": 401,
+ "PATCH /api/transactions/bulk-add-to-group": 401,
+ "PATCH /api/transactions/bulk-categorize": 401,
+ "PATCH /api/transactions/bulk-remove-tags": 401,
+ "PATCH /api/transactions/{transaction_id}": 401,
+ "PATCH /api/transactions/{transaction_id}/attachments/{attachment_id}": 401,
+ "PATCH /api/transactions/{transaction_id}/ignore": 401,
+ "PATCH /api/transactions/{transaction_id}/unlink-recurring": 401,
+ "PATCH /api/users/me": 401,
+ "PATCH /api/users/{id}": 401,
+ "PATCH /api/workspaces/{workspace_id}": 401,
+ "PATCH /api/workspaces/{workspace_id}/members/{member_user_id}": 401,
+ "POST /api/accounts": 401,
+ "POST /api/accounts/{account_id}/close": 401,
+ "POST /api/accounts/{account_id}/reopen": 401,
+ "POST /api/admin/users": 401,
+ "POST /api/agents": 401,
+ "POST /api/agents/connections": 401,
+ "POST /api/agents/connections/{conn_id}/test": 401,
+ "POST /api/agents/conversations/{conversation_id}/generate-title": 401,
+ "POST /api/agents/mcp-tokens": 401,
+ "POST /api/agents/{agent_id}/chat": 401,
+ "POST /api/agents/{agent_id}/knowledge": 401,
+ "POST /api/asset-groups": 401,
+ "POST /api/assets": 401,
+ "POST /api/assets/buy": 401,
+ "POST /api/assets/import": 401,
+ "POST /api/assets/import/preview": 401,
+ "POST /api/assets/{asset_id}/refresh-price": 401,
+ "POST /api/assets/{asset_id}/transactions": 401,
+ "POST /api/assets/{asset_id}/values": 401,
+ "POST /api/auth/2fa/disable": 401,
+ "POST /api/auth/2fa/enable": 401,
+ "POST /api/auth/2fa/setup": 401,
+ "POST /api/auth/2fa/verify": 422,
+ "POST /api/auth/forgot-password": 202,
+ "POST /api/auth/login": 200,
+ "POST /api/auth/logout": 200,
+ "POST /api/auth/passkeys/2fa/options": 400,
+ "POST /api/auth/passkeys/2fa/verify": 422,
+ "POST /api/auth/passkeys/authenticate/options": 400,
+ "POST /api/auth/passkeys/authenticate/verify": 422,
+ "POST /api/auth/passkeys/register/options": 401,
+ "POST /api/auth/passkeys/register/verify": 401,
+ "POST /api/auth/register": 201,
+ "POST /api/auth/reset-password": 400,
+ "POST /api/budgets": 401,
+ "POST /api/categories": 401,
+ "POST /api/category-groups": 401,
+ "POST /api/collections": 401,
+ "POST /api/connections/connect-token": 401,
+ "POST /api/connections/oauth/callback": 401,
+ "POST /api/connections/oauth/url": 401,
+ "POST /api/connections/transfers/detect": 401,
+ "POST /api/connections/{connection_id}/oauth/reauth-url": 401,
+ "POST /api/connections/{connection_id}/reconnect-token": 401,
+ "POST /api/connections/{connection_id}/sync": 401,
+ "POST /api/export/backup": 401,
+ "POST /api/fx-rates/refresh": 401,
+ "POST /api/goals": 401,
+ "POST /api/groups": 401,
+ "POST /api/groups/{group_id}/members": 401,
+ "POST /api/groups/{group_id}/settlements": 401,
+ "POST /api/invoice-schedules": 401,
+ "POST /api/invoice-schedules/{schedule_id}/end": 401,
+ "POST /api/invoice-schedules/{schedule_id}/generate": 401,
+ "POST /api/invoice-schedules/{schedule_id}/link": 401,
+ "POST /api/invoice-schedules/{schedule_id}/pause": 401,
+ "POST /api/invoice-schedules/{schedule_id}/resume": 401,
+ "POST /api/invoice-schedules/{schedule_id}/terms": 401,
+ "POST /api/invoices": 401,
+ "POST /api/invoices/settings/logo": 401,
+ "POST /api/invoices/{invoice_id}/allocations": 401,
+ "POST /api/invoices/{invoice_id}/attachments": 401,
+ "POST /api/invoices/{invoice_id}/deductions": 401,
+ "POST /api/invoices/{invoice_id}/issue": 401,
+ "POST /api/invoices/{invoice_id}/make-recurring": 401,
+ "POST /api/invoices/{invoice_id}/reopen": 401,
+ "POST /api/invoices/{invoice_id}/share": 401,
+ "POST /api/invoices/{invoice_id}/uncollectible": 401,
+ "POST /api/invoices/{invoice_id}/void": 401,
+ "POST /api/payees": 401,
+ "POST /api/payees/bulk-delete": 401,
+ "POST /api/payees/merge": 401,
+ "POST /api/products": 401,
+ "POST /api/products/{product_id}/prices": 401,
+ "POST /api/reconciliation/rules": 401,
+ "POST /api/reconciliation/rules/import": 401,
+ "POST /api/reconciliation/rules/{node}/{strategy_id}/reset": 401,
+ "POST /api/reconciliation/suggestions/{suggestion_id}/accept": 401,
+ "POST /api/reconciliation/suggestions/{suggestion_id}/decline": 401,
+ "POST /api/recurring-transactions": 401,
+ "POST /api/recurring-transactions/generate": 401,
+ "POST /api/rules": 401,
+ "POST /api/rules/apply-all": 401,
+ "POST /api/rules/import": 401,
+ "POST /api/rules/packs/{pack_code}/install": 401,
+ "POST /api/rules/preview": 401,
+ "POST /api/setup/create-admin": 403,
+ "POST /api/transactions": 401,
+ "POST /api/transactions/bulk-delete": 401,
+ "POST /api/transactions/import": 401,
+ "POST /api/transactions/import/preview": 401,
+ "POST /api/transactions/installments": 401,
+ "POST /api/transactions/link-transfer": 401,
+ "POST /api/transactions/transfer": 401,
+ "POST /api/transactions/{transaction_id}/attachments": 401,
+ "POST /api/transactions/{transaction_id}/create-counterpart": 401,
+ "POST /api/workspaces": 401,
+ "POST /api/workspaces/{workspace_id}/archive": 401,
+ "POST /api/workspaces/{workspace_id}/members": 401,
+ "PUT /api/agents/{agent_id}/tools": 401,
+ "PUT /api/reconciliation/rules/{node}/order": 401
+ },
+ "empty": {
+ "PATCH /api/admin/settings/{key}": 422,
+ "PATCH /api/agents/conversations/{conversation_id}": 422,
+ "PATCH /api/transactions/bulk-add-tags": 422,
+ "PATCH /api/transactions/bulk-add-to-group": 422,
+ "PATCH /api/transactions/bulk-categorize": 422,
+ "PATCH /api/transactions/bulk-remove-tags": 422,
+ "PATCH /api/transactions/{transaction_id}/attachments/{attachment_id}": 422,
+ "PATCH /api/workspaces/{workspace_id}/members/{member_user_id}": 422,
+ "POST /api/accounts": 422,
+ "POST /api/admin/users": 422,
+ "POST /api/agents": 422,
+ "POST /api/agents/connections": 422,
+ "POST /api/agents/{agent_id}/chat": 422,
+ "POST /api/asset-groups": 422,
+ "POST /api/assets": 422,
+ "POST /api/assets/buy": 422,
+ "POST /api/assets/import": 422,
+ "POST /api/assets/{asset_id}/transactions": 422,
+ "POST /api/assets/{asset_id}/values": 422,
+ "POST /api/auth/2fa/disable": 422,
+ "POST /api/auth/2fa/enable": 422,
+ "POST /api/auth/2fa/verify": 422,
+ "POST /api/auth/forgot-password": 422,
+ "POST /api/auth/passkeys/2fa/options": 422,
+ "POST /api/auth/passkeys/2fa/verify": 422,
+ "POST /api/auth/passkeys/authenticate/verify": 422,
+ "POST /api/auth/passkeys/register/verify": 422,
+ "POST /api/auth/register": 422,
+ "POST /api/auth/reset-password": 422,
+ "POST /api/budgets": 422,
+ "POST /api/categories": 422,
+ "POST /api/category-groups": 422,
+ "POST /api/collections": 422,
+ "POST /api/connections/oauth/callback": 422,
+ "POST /api/goals": 422,
+ "POST /api/groups": 422,
+ "POST /api/groups/{group_id}/members": 422,
+ "POST /api/groups/{group_id}/settlements": 422,
+ "POST /api/invoice-schedules": 404,
+ "POST /api/invoice-schedules/{schedule_id}/link": 404,
+ "POST /api/invoice-schedules/{schedule_id}/terms": 404,
+ "POST /api/invoices/{invoice_id}/allocations": 404,
+ "POST /api/invoices/{invoice_id}/deductions": 404,
+ "POST /api/invoices/{invoice_id}/make-recurring": 404,
+ "POST /api/payees": 422,
+ "POST /api/payees/bulk-delete": 422,
+ "POST /api/payees/merge": 422,
+ "POST /api/products": 404,
+ "POST /api/products/{product_id}/prices": 404,
+ "POST /api/reconciliation/rules": 422,
+ "POST /api/reconciliation/rules/import": 422,
+ "POST /api/recurring-transactions": 422,
+ "POST /api/rules": 422,
+ "POST /api/rules/import": 422,
+ "POST /api/rules/preview": 422,
+ "POST /api/setup/create-admin": 422,
+ "POST /api/transactions": 422,
+ "POST /api/transactions/bulk-delete": 422,
+ "POST /api/transactions/import": 422,
+ "POST /api/transactions/installments": 422,
+ "POST /api/transactions/link-transfer": 422,
+ "POST /api/transactions/transfer": 422,
+ "POST /api/transactions/{transaction_id}/create-counterpart": 422,
+ "POST /api/workspaces": 422,
+ "POST /api/workspaces/{workspace_id}/members": 422,
+ "PUT /api/reconciliation/rules/{node}/order": 422
+ },
+ "ok": {
+ "DELETE /api/accounts/{account_id}": 204,
+ "DELETE /api/admin/settings/{key}": 204,
+ "DELETE /api/admin/users/{user_id}": 204,
+ "DELETE /api/agents/connections/{conn_id}": 204,
+ "DELETE /api/agents/conversations/{conversation_id}": 204,
+ "DELETE /api/agents/{agent_id}": 204,
+ "DELETE /api/agents/{agent_id}/knowledge/{doc_id}": 404,
+ "DELETE /api/asset-groups/{group_id}": 204,
+ "DELETE /api/assets/transactions/{tx_id}": 404,
+ "DELETE /api/assets/values/{value_id}": 204,
+ "DELETE /api/assets/{asset_id}": 204,
+ "DELETE /api/auth/passkeys/{passkey_id}": 404,
+ "DELETE /api/budgets/{budget_id}": 204,
+ "DELETE /api/categories/{category_id}": 409,
+ "DELETE /api/category-groups/{group_id}": 204,
+ "DELETE /api/collections/{collection_id}": 204,
+ "DELETE /api/connections/transfers/{pair_id}": 404,
+ "DELETE /api/connections/{connection_id}": 204,
+ "DELETE /api/goals/{goal_id}": 204,
+ "DELETE /api/groups/{group_id}": 409,
+ "DELETE /api/groups/{group_id}/members/{member_id}": 409,
+ "DELETE /api/groups/{group_id}/settlements/{settlement_id}": 204,
+ "DELETE /api/import-logs/{import_log_id}": 404,
+ "DELETE /api/invoice-schedules/{schedule_id}": 204,
+ "DELETE /api/invoice-schedules/{schedule_id}/terms/{term_id}": 404,
+ "DELETE /api/invoices/settings/logo": 200,
+ "DELETE /api/invoices/{invoice_id}": 204,
+ "DELETE /api/invoices/{invoice_id}/allocations/{allocation_id}": 404,
+ "DELETE /api/invoices/{invoice_id}/attachments/{attachment_id}": 404,
+ "DELETE /api/invoices/{invoice_id}/deductions/{deduction_id}": 404,
+ "DELETE /api/invoices/{invoice_id}/schedule": 200,
+ "DELETE /api/invoices/{invoice_id}/share": 204,
+ "DELETE /api/payees/{payee_id}": 409,
+ "DELETE /api/products/{product_id}": 204,
+ "DELETE /api/products/{product_id}/prices/{price_id}": 404,
+ "DELETE /api/reconciliation/rules/{node}/{strategy_id}": 400,
+ "DELETE /api/recurring-transactions/{recurring_id}": 204,
+ "DELETE /api/rules/{rule_id}": 204,
+ "DELETE /api/transactions/{transaction_id}": 204,
+ "DELETE /api/transactions/{transaction_id}/attachments/{attachment_id}": 204,
+ "DELETE /api/users/{id}": 403,
+ "DELETE /api/workspaces/{workspace_id}/members/{member_user_id}": 400,
+ "GET /api/accounts": 200,
+ "GET /api/accounts/{account_id}": 200,
+ "GET /api/accounts/{account_id}/balance-history": 200,
+ "GET /api/accounts/{account_id}/bills": 200,
+ "GET /api/accounts/{account_id}/summary": 200,
+ "GET /api/admin/accounting-mode": 200,
+ "GET /api/admin/date-format": 200,
+ "GET /api/admin/default-colors": 200,
+ "GET /api/admin/number-format": 200,
+ "GET /api/admin/registration-status": 200,
+ "GET /api/admin/settings/{key}": 404,
+ "GET /api/admin/timezone": 200,
+ "GET /api/admin/users": 200,
+ "GET /api/admin/users/{user_id}": 200,
+ "GET /api/agents": 200,
+ "GET /api/agents/connections": 200,
+ "GET /api/agents/connections/{conn_id}": 200,
+ "GET /api/agents/conversations": 200,
+ "GET /api/agents/conversations/{conversation_id}": 200,
+ "GET /api/agents/conversations/{conversation_id}/messages": 200,
+ "GET /api/agents/default": 200,
+ "GET /api/agents/info": 200,
+ "GET /api/agents/{agent_id}": 200,
+ "GET /api/agents/{agent_id}/knowledge": 200,
+ "GET /api/agents/{agent_id}/tools": 200,
+ "GET /api/asset-groups": 200,
+ "GET /api/assets": 200,
+ "GET /api/assets/import/template": 200,
+ "GET /api/assets/market/quote": 404,
+ "GET /api/assets/market/search": 200,
+ "GET /api/assets/portfolio-trend": 200,
+ "GET /api/assets/transactions": 200,
+ "GET /api/assets/{asset_id}": 200,
+ "GET /api/assets/{asset_id}/transactions": 200,
+ "GET /api/assets/{asset_id}/value-trend": 200,
+ "GET /api/assets/{asset_id}/values": 200,
+ "GET /api/auth/oidc/callback": 400,
+ "GET /api/auth/oidc/config": 200,
+ "GET /api/auth/oidc/login": 500,
+ "GET /api/auth/passkeys": 200,
+ "GET /api/budgets": 200,
+ "GET /api/budgets/comparison": 200,
+ "GET /api/categories": 200,
+ "GET /api/categories/{category_id}/rule-usage": 200,
+ "GET /api/categories/{category_id}/usage": 200,
+ "GET /api/category-groups": 200,
+ "GET /api/collections": 200,
+ "GET /api/connections": 200,
+ "GET /api/connections/providers": 200,
+ "GET /api/connections/{provider}/institutions": 400,
+ "GET /api/currencies": 200,
+ "GET /api/dashboard/balance-history": 200,
+ "GET /api/dashboard/projected-transactions": 200,
+ "GET /api/dashboard/spending-by-category": 200,
+ "GET /api/dashboard/summary": 200,
+ "GET /api/export/backup": 200,
+ "GET /api/fiscal/jurisdictions": 200,
+ "GET /api/fiscal/product-fields": 200,
+ "GET /api/fiscal/tax-id-kinds": 200,
+ "GET /api/fx-rates/status": 200,
+ "GET /api/goals": 200,
+ "GET /api/goals/summary": 200,
+ "GET /api/goals/{goal_id}": 200,
+ "GET /api/groups": 200,
+ "GET /api/groups/{group_id}": 200,
+ "GET /api/groups/{group_id}/balances": 200,
+ "GET /api/groups/{group_id}/members": 200,
+ "GET /api/groups/{group_id}/settlements": 200,
+ "GET /api/groups/{group_id}/transactions": 200,
+ "GET /api/health": 200,
+ "GET /api/import-logs": 200,
+ "GET /api/info": 200,
+ "GET /api/invoice-schedules": 200,
+ "GET /api/invoice-schedules/summary": 200,
+ "GET /api/invoice-schedules/{schedule_id}": 200,
+ "GET /api/invoice-schedules/{schedule_id}/invoices": 200,
+ "GET /api/invoice-schedules/{schedule_id}/periods": 200,
+ "GET /api/invoices": 200,
+ "GET /api/invoices/facets": 200,
+ "GET /api/invoices/issuer": 200,
+ "GET /api/invoices/logo/{logo_id}": 404,
+ "GET /api/invoices/settings": 200,
+ "GET /api/invoices/summary": 200,
+ "GET /api/invoices/{invoice_id}": 200,
+ "GET /api/invoices/{invoice_id}/attachments": 200,
+ "GET /api/invoices/{invoice_id}/attachments/{attachment_id}": 404,
+ "GET /api/invoices/{invoice_id}/document": 200,
+ "GET /api/invoices/{invoice_id}/pdf": 200,
+ "GET /api/invoices/{invoice_id}/statement": 200,
+ "GET /api/payees": 200,
+ "GET /api/payees/{payee_id}": 200,
+ "GET /api/payees/{payee_id}/summary": 200,
+ "GET /api/products": 200,
+ "GET /api/products/{product_id}": 200,
+ "GET /api/public/invoices/{token}": 404,
+ "GET /api/public/invoices/{token}/logo": 404,
+ "GET /api/public/invoices/{token}/pdf": 404,
+ "GET /api/reconciliation/history": 200,
+ "GET /api/reconciliation/rules": 200,
+ "GET /api/reconciliation/rules/export": 200,
+ "GET /api/reconciliation/suggestions": 200,
+ "GET /api/recurring-transactions": 200,
+ "GET /api/reports/cash-flow": 200,
+ "GET /api/reports/net-worth": 200,
+ "GET /api/rules": 200,
+ "GET /api/rules/export": 200,
+ "GET /api/rules/packs": 200,
+ "GET /api/search": 200,
+ "GET /api/settings/attachments": 200,
+ "GET /api/setup/status": 200,
+ "GET /api/timezones": 200,
+ "GET /api/transactions": 200,
+ "GET /api/transactions/calendar": 200,
+ "GET /api/transactions/export": 200,
+ "GET /api/transactions/{transaction_id}": 200,
+ "GET /api/transactions/{transaction_id}/attachments": 200,
+ "GET /api/transactions/{transaction_id}/attachments/{attachment_id}": 200,
+ "GET /api/transactions/{transaction_id}/transfer-candidates": 200,
+ "GET /api/transactions/{transaction_id}/transfer-pair": 200,
+ "GET /api/users/directory": 200,
+ "GET /api/users/lookup": 404,
+ "GET /api/users/me": 200,
+ "GET /api/users/{id}": 403,
+ "GET /api/workspaces": 200,
+ "GET /api/workspaces/current": 200,
+ "GET /api/workspaces/{workspace_id}/members": 200,
+ "GET /api/workspaces/{workspace_id}/stats": 200,
+ "PATCH /api/accounts/{account_id}": 200,
+ "PATCH /api/admin/settings/{key}": 200,
+ "PATCH /api/admin/users/{user_id}": 200,
+ "PATCH /api/agents/connections/{conn_id}": 200,
+ "PATCH /api/agents/conversations/{conversation_id}": 200,
+ "PATCH /api/agents/{agent_id}": 200,
+ "PATCH /api/agents/{agent_id}/knowledge/{doc_id}/pin": 404,
+ "PATCH /api/asset-groups/{group_id}": 200,
+ "PATCH /api/assets/transactions/{tx_id}": 404,
+ "PATCH /api/assets/{asset_id}": 200,
+ "PATCH /api/budgets/{budget_id}": 200,
+ "PATCH /api/categories/{category_id}": 200,
+ "PATCH /api/category-groups/{group_id}": 200,
+ "PATCH /api/collections/{collection_id}": 200,
+ "PATCH /api/connections/{connection_id}/settings": 200,
+ "PATCH /api/goals/{goal_id}": 200,
+ "PATCH /api/groups/{group_id}": 200,
+ "PATCH /api/groups/{group_id}/members/{member_id}": 200,
+ "PATCH /api/groups/{group_id}/settlements/{settlement_id}": 200,
+ "PATCH /api/invoice-schedules/{schedule_id}": 200,
+ "PATCH /api/invoice-schedules/{schedule_id}/terms/{term_id}": 404,
+ "PATCH /api/invoices/issuer": 200,
+ "PATCH /api/invoices/settings": 200,
+ "PATCH /api/invoices/{invoice_id}": 200,
+ "PATCH /api/invoices/{invoice_id}/attachments/{attachment_id}": 404,
+ "PATCH /api/payees/{payee_id}": 200,
+ "PATCH /api/products/{product_id}": 200,
+ "PATCH /api/products/{product_id}/prices/{price_id}": 404,
+ "PATCH /api/reconciliation/rules/{node}/{strategy_id}": 400,
+ "PATCH /api/recurring-transactions/{recurring_id}": 200,
+ "PATCH /api/rules/{rule_id}": 200,
+ "PATCH /api/transactions/bulk-add-tags": 200,
+ "PATCH /api/transactions/bulk-add-to-group": 200,
+ "PATCH /api/transactions/bulk-categorize": 200,
+ "PATCH /api/transactions/bulk-remove-tags": 200,
+ "PATCH /api/transactions/{transaction_id}": 200,
+ "PATCH /api/transactions/{transaction_id}/attachments/{attachment_id}": 200,
+ "PATCH /api/transactions/{transaction_id}/ignore": 200,
+ "PATCH /api/transactions/{transaction_id}/unlink-recurring": 404,
+ "PATCH /api/users/me": 200,
+ "PATCH /api/users/{id}": 403,
+ "PATCH /api/workspaces/{workspace_id}": 200,
+ "PATCH /api/workspaces/{workspace_id}/members/{member_user_id}": 400,
+ "POST /api/accounts": 201,
+ "POST /api/accounts/{account_id}/close": 200,
+ "POST /api/accounts/{account_id}/reopen": 400,
+ "POST /api/admin/users": 201,
+ "POST /api/agents": 201,
+ "POST /api/agents/connections": 201,
+ "POST /api/agents/connections/{conn_id}/test": 200,
+ "POST /api/agents/conversations/{conversation_id}/generate-title": 200,
+ "POST /api/agents/mcp-tokens": 201,
+ "POST /api/agents/{agent_id}/chat": 200,
+ "POST /api/agents/{agent_id}/knowledge": 201,
+ "POST /api/asset-groups": 201,
+ "POST /api/assets": 201,
+ "POST /api/assets/buy": 502,
+ "POST /api/assets/import": 200,
+ "POST /api/assets/import/preview": 200,
+ "POST /api/assets/{asset_id}/refresh-price": 422,
+ "POST /api/assets/{asset_id}/transactions": 201,
+ "POST /api/assets/{asset_id}/values": 201,
+ "POST /api/auth/2fa/disable": 422,
+ "POST /api/auth/2fa/enable": 422,
+ "POST /api/auth/2fa/setup": 200,
+ "POST /api/auth/2fa/verify": 422,
+ "POST /api/auth/forgot-password": 202,
+ "POST /api/auth/login": 200,
+ "POST /api/auth/logout": 200,
+ "POST /api/auth/passkeys/2fa/options": 400,
+ "POST /api/auth/passkeys/2fa/verify": 422,
+ "POST /api/auth/passkeys/authenticate/options": 400,
+ "POST /api/auth/passkeys/authenticate/verify": 422,
+ "POST /api/auth/passkeys/register/options": 400,
+ "POST /api/auth/passkeys/register/verify": 422,
+ "POST /api/auth/register": 201,
+ "POST /api/auth/reset-password": 400,
+ "POST /api/budgets": 201,
+ "POST /api/categories": 201,
+ "POST /api/category-groups": 201,
+ "POST /api/collections": 201,
+ "POST /api/connections/connect-token": 400,
+ "POST /api/connections/oauth/callback": 400,
+ "POST /api/connections/oauth/url": 400,
+ "POST /api/connections/transfers/detect": 200,
+ "POST /api/connections/{connection_id}/oauth/reauth-url": 404,
+ "POST /api/connections/{connection_id}/reconnect-token": 400,
+ "POST /api/connections/{connection_id}/sync": 503,
+ "POST /api/export/backup": 200,
+ "POST /api/fx-rates/refresh": 200,
+ "POST /api/goals": 201,
+ "POST /api/groups": 201,
+ "POST /api/groups/{group_id}/members": 201,
+ "POST /api/groups/{group_id}/settlements": 201,
+ "POST /api/invoice-schedules": 201,
+ "POST /api/invoice-schedules/{schedule_id}/end": 200,
+ "POST /api/invoice-schedules/{schedule_id}/generate": 201,
+ "POST /api/invoice-schedules/{schedule_id}/link": 400,
+ "POST /api/invoice-schedules/{schedule_id}/pause": 200,
+ "POST /api/invoice-schedules/{schedule_id}/resume": 200,
+ "POST /api/invoice-schedules/{schedule_id}/terms": 400,
+ "POST /api/invoices": 201,
+ "POST /api/invoices/settings/logo": 400,
+ "POST /api/invoices/{invoice_id}/allocations": 201,
+ "POST /api/invoices/{invoice_id}/attachments": 201,
+ "POST /api/invoices/{invoice_id}/deductions": 201,
+ "POST /api/invoices/{invoice_id}/issue": 200,
+ "POST /api/invoices/{invoice_id}/make-recurring": 201,
+ "POST /api/invoices/{invoice_id}/reopen": 400,
+ "POST /api/invoices/{invoice_id}/share": 201,
+ "POST /api/invoices/{invoice_id}/uncollectible": 200,
+ "POST /api/invoices/{invoice_id}/void": 200,
+ "POST /api/payees": 201,
+ "POST /api/payees/bulk-delete": 200,
+ "POST /api/payees/merge": 200,
+ "POST /api/products": 201,
+ "POST /api/products/{product_id}/prices": 201,
+ "POST /api/reconciliation/rules": 404,
+ "POST /api/reconciliation/rules/import": 400,
+ "POST /api/reconciliation/rules/{node}/{strategy_id}/reset": 204,
+ "POST /api/reconciliation/suggestions/{suggestion_id}/accept": 404,
+ "POST /api/reconciliation/suggestions/{suggestion_id}/decline": 404,
+ "POST /api/recurring-transactions": 201,
+ "POST /api/recurring-transactions/generate": 200,
+ "POST /api/rules": 201,
+ "POST /api/rules/apply-all": 200,
+ "POST /api/rules/import": 409,
+ "POST /api/rules/packs/{pack_code}/install": 200,
+ "POST /api/rules/preview": 200,
+ "POST /api/setup/create-admin": 403,
+ "POST /api/transactions": 201,
+ "POST /api/transactions/bulk-delete": 200,
+ "POST /api/transactions/import": 201,
+ "POST /api/transactions/import/preview": 200,
+ "POST /api/transactions/installments": 201,
+ "POST /api/transactions/link-transfer": 200,
+ "POST /api/transactions/transfer": 201,
+ "POST /api/transactions/{transaction_id}/attachments": 201,
+ "POST /api/transactions/{transaction_id}/create-counterpart": 201,
+ "POST /api/workspaces": 201,
+ "POST /api/workspaces/{workspace_id}/archive": 400,
+ "POST /api/workspaces/{workspace_id}/members": 400,
+ "PUT /api/agents/{agent_id}/tools": 200,
+ "PUT /api/reconciliation/rules/{node}/order": 400
+ },
+ "unknown_id": {
+ "DELETE /api/accounts/{account_id}": 404,
+ "DELETE /api/admin/users/{user_id}": 404,
+ "DELETE /api/agents/connections/{conn_id}": 404,
+ "DELETE /api/agents/conversations/{conversation_id}": 404,
+ "DELETE /api/agents/{agent_id}": 404,
+ "DELETE /api/agents/{agent_id}/knowledge/{doc_id}": 404,
+ "DELETE /api/asset-groups/{group_id}": 404,
+ "DELETE /api/assets/transactions/{tx_id}": 404,
+ "DELETE /api/assets/values/{value_id}": 404,
+ "DELETE /api/assets/{asset_id}": 404,
+ "DELETE /api/auth/passkeys/{passkey_id}": 404,
+ "DELETE /api/budgets/{budget_id}": 404,
+ "DELETE /api/categories/{category_id}": 404,
+ "DELETE /api/category-groups/{group_id}": 404,
+ "DELETE /api/collections/{collection_id}": 404,
+ "DELETE /api/connections/transfers/{pair_id}": 404,
+ "DELETE /api/connections/{connection_id}": 404,
+ "DELETE /api/goals/{goal_id}": 404,
+ "DELETE /api/groups/{group_id}": 404,
+ "DELETE /api/groups/{group_id}/members/{member_id}": 404,
+ "DELETE /api/groups/{group_id}/settlements/{settlement_id}": 404,
+ "DELETE /api/import-logs/{import_log_id}": 404,
+ "DELETE /api/invoice-schedules/{schedule_id}": 404,
+ "DELETE /api/invoice-schedules/{schedule_id}/terms/{term_id}": 404,
+ "DELETE /api/invoices/{invoice_id}": 404,
+ "DELETE /api/invoices/{invoice_id}/allocations/{allocation_id}": 404,
+ "DELETE /api/invoices/{invoice_id}/attachments/{attachment_id}": 404,
+ "DELETE /api/invoices/{invoice_id}/deductions/{deduction_id}": 404,
+ "DELETE /api/invoices/{invoice_id}/schedule": 404,
+ "DELETE /api/invoices/{invoice_id}/share": 404,
+ "DELETE /api/payees/{payee_id}": 404,
+ "DELETE /api/products/{product_id}": 404,
+ "DELETE /api/products/{product_id}/prices/{price_id}": 404,
+ "DELETE /api/reconciliation/rules/{node}/{strategy_id}": 400,
+ "DELETE /api/recurring-transactions/{recurring_id}": 404,
+ "DELETE /api/rules/{rule_id}": 404,
+ "DELETE /api/transactions/{transaction_id}": 404,
+ "DELETE /api/transactions/{transaction_id}/attachments/{attachment_id}": 404,
+ "DELETE /api/users/{id}": 403,
+ "DELETE /api/workspaces/{workspace_id}/members/{member_user_id}": 404,
+ "GET /api/accounts/{account_id}": 404,
+ "GET /api/accounts/{account_id}/balance-history": 404,
+ "GET /api/accounts/{account_id}/bills": 404,
+ "GET /api/accounts/{account_id}/summary": 404,
+ "GET /api/admin/users/{user_id}": 404,
+ "GET /api/agents/connections/{conn_id}": 404,
+ "GET /api/agents/conversations/{conversation_id}": 404,
+ "GET /api/agents/conversations/{conversation_id}/messages": 404,
+ "GET /api/agents/{agent_id}": 404,
+ "GET /api/agents/{agent_id}/knowledge": 404,
+ "GET /api/agents/{agent_id}/tools": 404,
+ "GET /api/assets/{asset_id}": 404,
+ "GET /api/assets/{asset_id}/transactions": 404,
+ "GET /api/assets/{asset_id}/value-trend": 404,
+ "GET /api/assets/{asset_id}/values": 404,
+ "GET /api/categories/{category_id}/rule-usage": 200,
+ "GET /api/categories/{category_id}/usage": 200,
+ "GET /api/goals/{goal_id}": 404,
+ "GET /api/groups/{group_id}": 404,
+ "GET /api/groups/{group_id}/balances": 404,
+ "GET /api/groups/{group_id}/members": 404,
+ "GET /api/groups/{group_id}/settlements": 404,
+ "GET /api/groups/{group_id}/transactions": 404,
+ "GET /api/invoice-schedules/{schedule_id}": 404,
+ "GET /api/invoice-schedules/{schedule_id}/invoices": 404,
+ "GET /api/invoice-schedules/{schedule_id}/periods": 404,
+ "GET /api/invoices/logo/{logo_id}": 404,
+ "GET /api/invoices/{invoice_id}": 404,
+ "GET /api/invoices/{invoice_id}/attachments": 404,
+ "GET /api/invoices/{invoice_id}/attachments/{attachment_id}": 404,
+ "GET /api/invoices/{invoice_id}/document": 404,
+ "GET /api/invoices/{invoice_id}/pdf": 404,
+ "GET /api/invoices/{invoice_id}/statement": 404,
+ "GET /api/payees/{payee_id}": 404,
+ "GET /api/payees/{payee_id}/summary": 404,
+ "GET /api/products/{product_id}": 404,
+ "GET /api/transactions/{transaction_id}": 404,
+ "GET /api/transactions/{transaction_id}/attachments": 404,
+ "GET /api/transactions/{transaction_id}/attachments/{attachment_id}": 404,
+ "GET /api/transactions/{transaction_id}/transfer-candidates": 404,
+ "GET /api/transactions/{transaction_id}/transfer-pair": 404,
+ "GET /api/users/{id}": 403,
+ "GET /api/workspaces/{workspace_id}/members": 404,
+ "GET /api/workspaces/{workspace_id}/stats": 404,
+ "PATCH /api/accounts/{account_id}": 404,
+ "PATCH /api/admin/users/{user_id}": 404,
+ "PATCH /api/agents/connections/{conn_id}": 404,
+ "PATCH /api/agents/conversations/{conversation_id}": 404,
+ "PATCH /api/agents/{agent_id}": 404,
+ "PATCH /api/agents/{agent_id}/knowledge/{doc_id}/pin": 404,
+ "PATCH /api/asset-groups/{group_id}": 404,
+ "PATCH /api/assets/transactions/{tx_id}": 404,
+ "PATCH /api/assets/{asset_id}": 404,
+ "PATCH /api/budgets/{budget_id}": 404,
+ "PATCH /api/categories/{category_id}": 404,
+ "PATCH /api/category-groups/{group_id}": 404,
+ "PATCH /api/collections/{collection_id}": 404,
+ "PATCH /api/connections/{connection_id}/settings": 404,
+ "PATCH /api/goals/{goal_id}": 404,
+ "PATCH /api/groups/{group_id}": 404,
+ "PATCH /api/groups/{group_id}/members/{member_id}": 404,
+ "PATCH /api/groups/{group_id}/settlements/{settlement_id}": 404,
+ "PATCH /api/invoice-schedules/{schedule_id}": 404,
+ "PATCH /api/invoice-schedules/{schedule_id}/terms/{term_id}": 404,
+ "PATCH /api/invoices/{invoice_id}": 404,
+ "PATCH /api/invoices/{invoice_id}/attachments/{attachment_id}": 404,
+ "PATCH /api/payees/{payee_id}": 404,
+ "PATCH /api/products/{product_id}": 404,
+ "PATCH /api/products/{product_id}/prices/{price_id}": 404,
+ "PATCH /api/reconciliation/rules/{node}/{strategy_id}": 400,
+ "PATCH /api/recurring-transactions/{recurring_id}": 404,
+ "PATCH /api/rules/{rule_id}": 404,
+ "PATCH /api/transactions/{transaction_id}": 404,
+ "PATCH /api/transactions/{transaction_id}/attachments/{attachment_id}": 404,
+ "PATCH /api/transactions/{transaction_id}/ignore": 404,
+ "PATCH /api/transactions/{transaction_id}/unlink-recurring": 404,
+ "PATCH /api/users/{id}": 403,
+ "PATCH /api/workspaces/{workspace_id}": 404,
+ "PATCH /api/workspaces/{workspace_id}/members/{member_user_id}": 404,
+ "POST /api/accounts/{account_id}/close": 404,
+ "POST /api/accounts/{account_id}/reopen": 404,
+ "POST /api/agents/connections/{conn_id}/test": 404,
+ "POST /api/agents/conversations/{conversation_id}/generate-title": 404,
+ "POST /api/agents/{agent_id}/chat": 404,
+ "POST /api/agents/{agent_id}/knowledge": 404,
+ "POST /api/assets/{asset_id}/refresh-price": 404,
+ "POST /api/assets/{asset_id}/transactions": 404,
+ "POST /api/assets/{asset_id}/values": 404,
+ "POST /api/connections/{connection_id}/oauth/reauth-url": 404,
+ "POST /api/connections/{connection_id}/reconnect-token": 404,
+ "POST /api/connections/{connection_id}/sync": 404,
+ "POST /api/groups/{group_id}/members": 404,
+ "POST /api/groups/{group_id}/settlements": 422,
+ "POST /api/invoice-schedules/{schedule_id}/end": 404,
+ "POST /api/invoice-schedules/{schedule_id}/generate": 404,
+ "POST /api/invoice-schedules/{schedule_id}/link": 404,
+ "POST /api/invoice-schedules/{schedule_id}/pause": 404,
+ "POST /api/invoice-schedules/{schedule_id}/resume": 404,
+ "POST /api/invoice-schedules/{schedule_id}/terms": 404,
+ "POST /api/invoices/{invoice_id}/allocations": 404,
+ "POST /api/invoices/{invoice_id}/attachments": 404,
+ "POST /api/invoices/{invoice_id}/deductions": 404,
+ "POST /api/invoices/{invoice_id}/issue": 404,
+ "POST /api/invoices/{invoice_id}/make-recurring": 404,
+ "POST /api/invoices/{invoice_id}/reopen": 404,
+ "POST /api/invoices/{invoice_id}/share": 404,
+ "POST /api/invoices/{invoice_id}/uncollectible": 404,
+ "POST /api/invoices/{invoice_id}/void": 404,
+ "POST /api/products/{product_id}/prices": 404,
+ "POST /api/reconciliation/rules/{node}/{strategy_id}/reset": 204,
+ "POST /api/reconciliation/suggestions/{suggestion_id}/accept": 404,
+ "POST /api/reconciliation/suggestions/{suggestion_id}/decline": 404,
+ "POST /api/transactions/{transaction_id}/attachments": 404,
+ "POST /api/transactions/{transaction_id}/create-counterpart": 422,
+ "POST /api/workspaces/{workspace_id}/archive": 404,
+ "POST /api/workspaces/{workspace_id}/members": 404,
+ "PUT /api/agents/{agent_id}/tools": 404
+ },
+ "viewer": {
+ "DELETE /api/accounts/{account_id}": 403,
+ "DELETE /api/agents/connections/{conn_id}": 404,
+ "DELETE /api/agents/conversations/{conversation_id}": 403,
+ "DELETE /api/agents/{agent_id}": 403,
+ "DELETE /api/agents/{agent_id}/knowledge/{doc_id}": 403,
+ "DELETE /api/asset-groups/{group_id}": 403,
+ "DELETE /api/assets/transactions/{tx_id}": 403,
+ "DELETE /api/assets/values/{value_id}": 403,
+ "DELETE /api/assets/{asset_id}": 403,
+ "DELETE /api/auth/passkeys/{passkey_id}": 404,
+ "DELETE /api/budgets/{budget_id}": 403,
+ "DELETE /api/categories/{category_id}": 403,
+ "DELETE /api/category-groups/{group_id}": 403,
+ "DELETE /api/collections/{collection_id}": 403,
+ "DELETE /api/connections/transfers/{pair_id}": 403,
+ "DELETE /api/connections/{connection_id}": 403,
+ "DELETE /api/goals/{goal_id}": 403,
+ "DELETE /api/groups/{group_id}": 403,
+ "DELETE /api/groups/{group_id}/members/{member_id}": 403,
+ "DELETE /api/groups/{group_id}/settlements/{settlement_id}": 403,
+ "DELETE /api/import-logs/{import_log_id}": 403,
+ "DELETE /api/invoice-schedules/{schedule_id}": 403,
+ "DELETE /api/invoice-schedules/{schedule_id}/terms/{term_id}": 403,
+ "DELETE /api/invoices/settings/logo": 403,
+ "DELETE /api/invoices/{invoice_id}": 403,
+ "DELETE /api/invoices/{invoice_id}/allocations/{allocation_id}": 403,
+ "DELETE /api/invoices/{invoice_id}/attachments/{attachment_id}": 403,
+ "DELETE /api/invoices/{invoice_id}/deductions/{deduction_id}": 403,
+ "DELETE /api/invoices/{invoice_id}/schedule": 403,
+ "DELETE /api/invoices/{invoice_id}/share": 403,
+ "DELETE /api/payees/{payee_id}": 403,
+ "DELETE /api/products/{product_id}": 403,
+ "DELETE /api/products/{product_id}/prices/{price_id}": 403,
+ "DELETE /api/reconciliation/rules/{node}/{strategy_id}": 403,
+ "DELETE /api/recurring-transactions/{recurring_id}": 403,
+ "DELETE /api/rules/{rule_id}": 403,
+ "DELETE /api/transactions/{transaction_id}": 403,
+ "DELETE /api/transactions/{transaction_id}/attachments/{attachment_id}": 403,
+ "DELETE /api/users/{id}": 403,
+ "DELETE /api/workspaces/{workspace_id}/members/{member_user_id}": 403,
+ "PATCH /api/accounts/{account_id}": 403,
+ "PATCH /api/agents/connections/{conn_id}": 404,
+ "PATCH /api/agents/conversations/{conversation_id}": 403,
+ "PATCH /api/agents/{agent_id}": 403,
+ "PATCH /api/agents/{agent_id}/knowledge/{doc_id}/pin": 403,
+ "PATCH /api/asset-groups/{group_id}": 403,
+ "PATCH /api/assets/transactions/{tx_id}": 403,
+ "PATCH /api/assets/{asset_id}": 403,
+ "PATCH /api/budgets/{budget_id}": 403,
+ "PATCH /api/categories/{category_id}": 403,
+ "PATCH /api/category-groups/{group_id}": 403,
+ "PATCH /api/collections/{collection_id}": 403,
+ "PATCH /api/connections/{connection_id}/settings": 403,
+ "PATCH /api/goals/{goal_id}": 403,
+ "PATCH /api/groups/{group_id}": 403,
+ "PATCH /api/groups/{group_id}/members/{member_id}": 403,
+ "PATCH /api/groups/{group_id}/settlements/{settlement_id}": 403,
+ "PATCH /api/invoice-schedules/{schedule_id}": 403,
+ "PATCH /api/invoice-schedules/{schedule_id}/terms/{term_id}": 403,
+ "PATCH /api/invoices/issuer": 403,
+ "PATCH /api/invoices/settings": 403,
+ "PATCH /api/invoices/{invoice_id}": 403,
+ "PATCH /api/invoices/{invoice_id}/attachments/{attachment_id}": 403,
+ "PATCH /api/payees/{payee_id}": 403,
+ "PATCH /api/products/{product_id}": 403,
+ "PATCH /api/products/{product_id}/prices/{price_id}": 403,
+ "PATCH /api/reconciliation/rules/{node}/{strategy_id}": 403,
+ "PATCH /api/recurring-transactions/{recurring_id}": 403,
+ "PATCH /api/rules/{rule_id}": 403,
+ "PATCH /api/transactions/bulk-add-tags": 403,
+ "PATCH /api/transactions/bulk-add-to-group": 403,
+ "PATCH /api/transactions/bulk-categorize": 403,
+ "PATCH /api/transactions/bulk-remove-tags": 403,
+ "PATCH /api/transactions/{transaction_id}": 403,
+ "PATCH /api/transactions/{transaction_id}/attachments/{attachment_id}": 403,
+ "PATCH /api/transactions/{transaction_id}/ignore": 403,
+ "PATCH /api/transactions/{transaction_id}/unlink-recurring": 403,
+ "PATCH /api/users/me": 200,
+ "PATCH /api/users/{id}": 403,
+ "PATCH /api/workspaces/{workspace_id}": 403,
+ "PATCH /api/workspaces/{workspace_id}/members/{member_user_id}": 403,
+ "POST /api/accounts": 403,
+ "POST /api/accounts/{account_id}/close": 403,
+ "POST /api/accounts/{account_id}/reopen": 403,
+ "POST /api/agents": 403,
+ "POST /api/agents/connections": 201,
+ "POST /api/agents/connections/{conn_id}/test": 404,
+ "POST /api/agents/conversations/{conversation_id}/generate-title": 403,
+ "POST /api/agents/mcp-tokens": 403,
+ "POST /api/agents/{agent_id}/chat": 403,
+ "POST /api/agents/{agent_id}/knowledge": 403,
+ "POST /api/asset-groups": 403,
+ "POST /api/assets": 403,
+ "POST /api/assets/buy": 403,
+ "POST /api/assets/import": 403,
+ "POST /api/assets/import/preview": 200,
+ "POST /api/assets/{asset_id}/refresh-price": 403,
+ "POST /api/assets/{asset_id}/transactions": 403,
+ "POST /api/assets/{asset_id}/values": 403,
+ "POST /api/auth/2fa/disable": 422,
+ "POST /api/auth/2fa/enable": 422,
+ "POST /api/auth/2fa/setup": 200,
+ "POST /api/auth/2fa/verify": 422,
+ "POST /api/auth/forgot-password": 202,
+ "POST /api/auth/login": 200,
+ "POST /api/auth/logout": 200,
+ "POST /api/auth/passkeys/2fa/options": 400,
+ "POST /api/auth/passkeys/2fa/verify": 422,
+ "POST /api/auth/passkeys/authenticate/options": 400,
+ "POST /api/auth/passkeys/authenticate/verify": 422,
+ "POST /api/auth/passkeys/register/options": 400,
+ "POST /api/auth/passkeys/register/verify": 422,
+ "POST /api/auth/register": 201,
+ "POST /api/auth/reset-password": 400,
+ "POST /api/budgets": 403,
+ "POST /api/categories": 403,
+ "POST /api/category-groups": 403,
+ "POST /api/collections": 403,
+ "POST /api/connections/connect-token": 403,
+ "POST /api/connections/oauth/callback": 403,
+ "POST /api/connections/oauth/url": 403,
+ "POST /api/connections/transfers/detect": 403,
+ "POST /api/connections/{connection_id}/oauth/reauth-url": 403,
+ "POST /api/connections/{connection_id}/reconnect-token": 403,
+ "POST /api/connections/{connection_id}/sync": 403,
+ "POST /api/export/backup": 200,
+ "POST /api/fx-rates/refresh": 200,
+ "POST /api/goals": 403,
+ "POST /api/groups": 403,
+ "POST /api/groups/{group_id}/members": 403,
+ "POST /api/groups/{group_id}/settlements": 403,
+ "POST /api/invoice-schedules": 403,
+ "POST /api/invoice-schedules/{schedule_id}/end": 403,
+ "POST /api/invoice-schedules/{schedule_id}/generate": 403,
+ "POST /api/invoice-schedules/{schedule_id}/link": 403,
+ "POST /api/invoice-schedules/{schedule_id}/pause": 403,
+ "POST /api/invoice-schedules/{schedule_id}/resume": 403,
+ "POST /api/invoice-schedules/{schedule_id}/terms": 403,
+ "POST /api/invoices": 403,
+ "POST /api/invoices/settings/logo": 403,
+ "POST /api/invoices/{invoice_id}/allocations": 403,
+ "POST /api/invoices/{invoice_id}/attachments": 403,
+ "POST /api/invoices/{invoice_id}/deductions": 403,
+ "POST /api/invoices/{invoice_id}/issue": 403,
+ "POST /api/invoices/{invoice_id}/make-recurring": 403,
+ "POST /api/invoices/{invoice_id}/reopen": 403,
+ "POST /api/invoices/{invoice_id}/share": 403,
+ "POST /api/invoices/{invoice_id}/uncollectible": 403,
+ "POST /api/invoices/{invoice_id}/void": 403,
+ "POST /api/payees": 403,
+ "POST /api/payees/bulk-delete": 403,
+ "POST /api/payees/merge": 403,
+ "POST /api/products": 403,
+ "POST /api/products/{product_id}/prices": 403,
+ "POST /api/reconciliation/rules": 403,
+ "POST /api/reconciliation/rules/import": 403,
+ "POST /api/reconciliation/rules/{node}/{strategy_id}/reset": 403,
+ "POST /api/reconciliation/suggestions/{suggestion_id}/accept": 403,
+ "POST /api/reconciliation/suggestions/{suggestion_id}/decline": 403,
+ "POST /api/recurring-transactions": 403,
+ "POST /api/recurring-transactions/generate": 403,
+ "POST /api/rules": 403,
+ "POST /api/rules/apply-all": 403,
+ "POST /api/rules/import": 403,
+ "POST /api/rules/packs/{pack_code}/install": 403,
+ "POST /api/rules/preview": 200,
+ "POST /api/setup/create-admin": 403,
+ "POST /api/transactions": 403,
+ "POST /api/transactions/bulk-delete": 403,
+ "POST /api/transactions/import": 403,
+ "POST /api/transactions/import/preview": 200,
+ "POST /api/transactions/installments": 403,
+ "POST /api/transactions/link-transfer": 403,
+ "POST /api/transactions/transfer": 403,
+ "POST /api/transactions/{transaction_id}/attachments": 403,
+ "POST /api/transactions/{transaction_id}/create-counterpart": 403,
+ "POST /api/workspaces": 201,
+ "POST /api/workspaces/{workspace_id}/archive": 403,
+ "POST /api/workspaces/{workspace_id}/members": 403,
+ "PUT /api/agents/{agent_id}/tools": 403,
+ "PUT /api/reconciliation/rules/{node}/order": 403
+ }
+}
diff --git a/backend/tests/api_contract/bodies.py b/backend/tests/api_contract/bodies.py
new file mode 100644
index 00000000..21f78202
--- /dev/null
+++ b/backend/tests/api_contract/bodies.py
@@ -0,0 +1,122 @@
+"""Build minimal, valid-looking request values from the OpenAPI schema.
+
+Only required fields are filled. `*_id` fields take ids from the seeded world
+when the name matches; everything else gets a type-based placeholder.
+"""
+from typing import Any
+
+PLACEHOLDER_STRING = "Contract test"
+PLACEHOLDER_DATE = "2026-04-28"
+PLACEHOLDER_DATETIME = "2026-04-28T12:00:00Z"
+PLACEHOLDER_EMAIL = "[email protected]"
+PLACEHOLDER_URL = "https://example.com"
+PLACEHOLDER_NUMBER = 10
+PLACEHOLDER_CURRENCY = "USD"
+
+# Field names that should resolve to a specific world id. Everything else
+# ending in `_id` falls back to the world key of the same name.
+ID_ALIASES = {
+ "group_member_id": "member_id",
+ "from_member_id": "member_id",
+ "to_member_id": "second_member_id",
+ "target_id": "payee_id",
+ "parent_id": "category_id",
+ "source_category_id": "category_id",
+ "destination_category_id": "category_id",
+ "target_category_id": "category_id",
+ "from_account_id": "account_id",
+ "to_account_id": "second_account_id",
+ "destination_account_id": "second_account_id",
+ "group_id_ref": "group_id",
+ "asset_group_id": "asset_group_id",
+ "category_group_id": "category_group_id",
+}
+
+
+def _resolve_ref(schema: dict, components: dict) -> dict:
+ while "$ref" in schema:
+ name = schema["$ref"].rsplit("/", 1)[-1]
+ schema = components["schemas"][name]
+ return schema
+
+
+def _pick_variant(schema: dict, components: dict) -> dict:
+ for key in ("anyOf", "oneOf"):
+ if key in schema:
+ options = [_resolve_ref(o, components) for o in schema[key]]
+ non_null = [o for o in options if o.get("type") != "null"]
+ return non_null[0] if non_null else options[0]
+ if "allOf" in schema:
+ merged: dict = {}
+ for part in schema["allOf"]:
+ merged.update(_resolve_ref(part, components))
+ return merged
+ return schema
+
+
+def _string_value(name: str, schema: dict) -> Any:
+ fmt = schema.get("format")
+ if fmt == "date":
+ return PLACEHOLDER_DATE
+ if fmt == "date-time":
+ return PLACEHOLDER_DATETIME
+ if fmt == "email" or "email" in name:
+ return PLACEHOLDER_EMAIL
+ if fmt in ("uri", "url") or name.endswith("url"):
+ return PLACEHOLDER_URL
+ if "currency" in name:
+ return PLACEHOLDER_CURRENCY
+ if "color" in name:
+ return "#22c55e"
+ if name == "date" or name.endswith("_date"):
+ return PLACEHOLDER_DATE
+ if schema.get("pattern") == "^\\d+(\\.\\d{1,2})?$" or name == "amount":
+ return "10.00"
+ min_length = schema.get("minLength", 1)
+ return (PLACEHOLDER_STRING + " " * min_length)[: max(min_length, len(PLACEHOLDER_STRING))]
+
+
+def value_for(name: str, schema: dict, components: dict, world: dict, depth: int = 0) -> Any:
+ schema = _pick_variant(_resolve_ref(schema, components), components)
+ if "const" in schema:
+ return schema["const"]
+ if "enum" in schema:
+ return schema["enum"][0]
+ if "default" in schema and schema["default"] is not None:
+ return schema["default"]
+
+ kind = schema.get("type")
+ if schema.get("format") == "uuid" or (kind == "string" and name.endswith("_id")):
+ key = ID_ALIASES.get(name, name)
+ return world.get(key) or world.get(name)
+ if kind == "string":
+ return _string_value(name, schema)
+ if kind in ("integer", "number"):
+ low = schema.get("minimum", schema.get("exclusiveMinimum", 0))
+ high = schema.get("maximum")
+ value = max(PLACEHOLDER_NUMBER, low + 1) if low is not None else PLACEHOLDER_NUMBER
+ if high is not None:
+ value = min(value, high)
+ return value
+ if kind == "boolean":
+ return False
+ if kind == "array":
+ if depth > 3:
+ return []
+ min_items = schema.get("minItems", 0)
+ item = value_for(name.rstrip("s"), schema.get("items", {}), components, world, depth + 1)
+ return [item] * max(min_items, 1) if min_items else []
+ if kind == "object" or "properties" in schema:
+ if depth > 3:
+ return {}
+ return object_for(schema, components, world, depth + 1)
+ return None
+
+
+def object_for(schema: dict, components: dict, world: dict, depth: int = 0) -> dict:
+ schema = _pick_variant(_resolve_ref(schema, components), components)
+ props = schema.get("properties", {})
+ out = {}
+ for field in schema.get("required", []):
+ out[field] = value_for(field, props.get(field, {}), components, world, depth)
+ return out
diff --git a/backend/tests/api_contract/cases.py b/backend/tests/api_contract/cases.py
new file mode 100644
index 00000000..5755c4d6
--- /dev/null
+++ b/backend/tests/api_contract/cases.py
@@ -0,0 +1,262 @@
+"""Turn the OpenAPI spec into contract cases.
+
+One operation (METHOD + path template) fans out into variants:
+
+- ``ok`` the owner calls it with world ids and a generated body
+- ``viewer`` a viewer-role member calls a mutating route (expect 403)
+- ``empty`` a JSON route with required fields gets ``{}`` (expect 422)
+- ``unknown_id`` every id in the path is a fresh uuid (expect 404)
+- ``anon`` no credentials at all (expect 401 unless public)
+
+Expected statuses are not written here: they live in baseline.json, so a
+behaviour change shows up as a diff of that file.
+"""
+import uuid
+from dataclasses import dataclass
+from typing import Any, Callable
+
+from app.main import app
+from app.services import reconciliation_policy
+from tests.api_contract.bodies import object_for, value_for
+from tests.api_contract.world import PNG_BYTES
+
+MUTATING = {"POST", "PUT", "PATCH", "DELETE"}
+
+VARIANT_OK = "ok"
+VARIANT_VIEWER = "viewer"
+VARIANT_EMPTY = "empty"
+VARIANT_UNKNOWN_ID = "unknown_id"
+VARIANT_ANON = "anon"
+VARIANTS = (VARIANT_OK, VARIANT_VIEWER, VARIANT_EMPTY, VARIANT_UNKNOWN_ID, VARIANT_ANON)
+
+ADMIN_PREFIXES = ("/api/admin/",)
+
+# Path parameter -> world key, where the names differ.
+PARAM_WORLD_KEYS = {
+ "tx_id": "transaction_id",
+ "conn_id": "agents_connection_id",
+ "member_user_id": "user_id",
+ "id": "user_id",
+}
+
+# Same parameter name, different resource, depending on the route prefix.
+PARAM_WORLD_KEYS_BY_PREFIX = {
+ "/api/asset-groups/": {"group_id": "asset_group_id"},
+ "/api/category-groups/": {"group_id": "category_group_id"},
+}
+
+# Path parameters that are not ids.
+STATIC_PARAMS = {
+ "pack_code": "BR",
+ "node": reconciliation_policy.MATCH_RECURRING["node"],
+ "provider": "pluggy",
+ "key": "registration_enabled",
+}
+
+# Parameters that identify a row, so the unknown_id variant swaps them out.
+NON_ID_PARAMS = set(STATIC_PARAMS) | {"token"}
+
+_INVOICE_LINES = [{"description": "Consulting", "quantity": 2, "unit_price": "100.00"}]
+
+# Routes whose generated body is not enough to reach the handler's happy
+# path. Keyed by (METHOD, path); the callable gets the world. Routes left out
+# on purpose answer a domain rule instead (a draft can't be voided, a sole
+# owner can't leave): that answer is the contract, and the baseline pins it.
+BODY_OVERRIDES: dict[tuple[str, str], Callable[[dict], Any]] = {
+ ("POST", "/api/budgets"): lambda w: {
+ "category_id": w["second_category_id"], "amount": 300, "month": "2026-05-01",
+ },
+ ("POST", "/api/payees/merge"): lambda w: {
+ "source_ids": [w["second_payee_id"]], "target_id": w["payee_id"],
+ },
+ ("POST", "/api/assets/{asset_id}/transactions"): lambda w: {
+ "kind": "buy", "quantity": 1, "price": 100, "date": "2026-04-28",
+ },
+ ("POST", "/api/agents/connections"): lambda w: {
+ "name": "Second LLM", "kind": "ollama", "base_url": "http://ollama:11434",
+ },
+ ("PUT", "/api/agents/{agent_id}/tools"): lambda w: [],
+ ("POST", "/api/invoices"): lambda w: {
+ "payee_id": w["payee_id"], "currency": "USD", "lines": _INVOICE_LINES,
+ },
+ ("POST", "/api/invoice-schedules"): lambda w: {
+ "name": "Second retainer", "frequency": "monthly", "payee_id": w["payee_id"],
+ "lines": _INVOICE_LINES,
+ },
+ ("PATCH", "/api/admin/settings/{key}"): lambda w: {"value": "true"},
+ ("POST", "/api/transactions/link-transfer"): lambda w: {
+ "transaction_ids": [w["second_transaction_id"], w["savings_transaction_id"]],
+ },
+}
+
+# Routes that need an issued (open) invoice rather than the world's draft.
+_ISSUED_INVOICE = {"invoice_id": "issued_invoice_id"}
+PARAM_WORLD_KEYS_BY_OPERATION: dict[tuple[str, str], dict[str, str]] = {
+ (method, f"/api/invoices/{{invoice_id}}/{action}"): _ISSUED_INVOICE
+ for method, action in (
+ ("POST", "void"),
+ ("POST", "uncollectible"),
+ ("POST", "make-recurring"),
+ ("POST", "allocations"),
+ ("POST", "deductions"),
+ ("POST", "share"),
+ ("GET", "statement"),
+ )
+}
+
+@dataclass(frozen=True)
+class KnownBug:
+ """A bug on the baseline branch: what the route *should* answer, and why it doesn't."""
+
+ expected: int
+ reason: str
+
+
+# The baseline records the correct status; the case is a strict xfail until
+# the fix lands, at which point the unexpected pass forces this entry out.
+KNOWN_BUGS: dict[tuple[str, str, str], KnownBug] = {
+ (VARIANT_OK, "POST", "/api/agents/{agent_id}/knowledge"): KnownBug(
+ 201,
+ "500 MissingGreenlet when the Celery dispatch fails: mark_status() commits, "
+ "expiring the doc that _serialize() then reads",
+ ),
+}
+
+# Routes that answer 500 on purpose, by an explicit HTTPException. The 500
+# guard skips these; each one is a design choice worth revisiting, not a crash.
+DELIBERATE_500: dict[tuple[str, str], str] = {
+ ("GET", "/api/auth/oidc/login"):
+ "raises HTTPException(500) when OIDC_CLIENT_ID is unset (server misconfiguration)",
+}
+
+# Routes whose SQL only runs on Postgres. The SQLite sweep skips them; the
+# live probe against a running stack covers them.
+POSTGRES_ONLY: dict[tuple[str, str], str] = {
+ ("GET", "/api/reports/income-expenses"): "to_char() is Postgres-only",
+ ("GET", "/api/dashboard/monthly-trend"): "to_char() is Postgres-only",
+}
+
+
+@dataclass(frozen=True)
+class Operation:
+ method: str
+ path: str
+ params: tuple[dict, ...]
+ content_type: str | None
+ body_schema: dict | None
+
+ @property
+ def key(self) -> str:
+ return f"{self.method} {self.path}"
+
+ @property
+ def path_params(self) -> list[str]:
+ return [p["name"] for p in self.params if p["in"] == "path"]
+
+ @property
+ def has_id_param(self) -> bool:
+ return any(name not in NON_ID_PARAMS for name in self.path_params)
+
+
+SPEC = app.openapi()
+COMPONENTS = SPEC.get("components", {})
+
+
+def _operations() -> list[Operation]:
+ ops = []
+ for path, methods in SPEC["paths"].items():
+ for method, op in methods.items():
+ content = op.get("requestBody", {}).get("content", {})
+ ctype = next(iter(content), None)
+ ops.append(
+ Operation(
+ method=method.upper(),
+ path=path,
+ params=tuple(op.get("parameters", [])),
+ content_type=ctype,
+ body_schema=content.get(ctype, {}).get("schema") if ctype else None,
+ )
+ )
+ return ops
+
+
+OPERATIONS = _operations()
+
+
+def _requires_fields(op: Operation) -> bool:
+ if op.content_type != "application/json" or not op.body_schema:
+ return False
+ schema = op.body_schema
+ while "$ref" in schema:
+ schema = COMPONENTS["schemas"][schema["$ref"].rsplit("/", 1)[-1]]
+ return bool(schema.get("required"))
+
+
+def variants_for(op: Operation) -> list[str]:
+ out = [VARIANT_OK, VARIANT_ANON]
+ if op.method in MUTATING and not op.path.startswith(ADMIN_PREFIXES):
+ out.append(VARIANT_VIEWER)
+ if _requires_fields(op):
+ out.append(VARIANT_EMPTY)
+ if op.has_id_param:
+ out.append(VARIANT_UNKNOWN_ID)
+ return out
+
+
+def _world_key(op: Operation, name: str) -> str:
+ per_operation = PARAM_WORLD_KEYS_BY_OPERATION.get((op.method, op.path), {})
+ if name in per_operation:
+ return per_operation[name]
+ for prefix, mapping in PARAM_WORLD_KEYS_BY_PREFIX.items():
+ if op.path.startswith(prefix) and name in mapping:
+ return mapping[name]
+ return PARAM_WORLD_KEYS.get(name, name)
+
+
+def fill_path(op: Operation, world: dict, unknown_ids: bool = False) -> str:
+ values = {}
+ for name in op.path_params:
+ if name in STATIC_PARAMS:
+ values[name] = STATIC_PARAMS[name]
+ elif unknown_ids:
+ values[name] = str(uuid.uuid4())
+ else:
+ values[name] = world.get(_world_key(op, name)) or str(uuid.uuid4())
+ return op.path.format(**values)
+
+
+def query_for(op: Operation, world: dict) -> dict:
+ query = {}
+ for param in op.params:
+ if param["in"] == "query" and param.get("required"):
+ query[param["name"]] = value_for(param["name"], param.get("schema", {}), COMPONENTS, world)
+ return query
+
+
+def _body(op: Operation, world: dict) -> Any:
+ override = BODY_OVERRIDES.get((op.method, op.path))
+ if override is not None:
+ try:
+ return override(world)
+ except KeyError:
+ # Cases without a seeded world: the generated body is enough,
+ # since the request is refused before the body matters.
+ pass
+ return object_for(op.body_schema or {}, COMPONENTS, world)
+
+
+def request_kwargs(op: Operation, world: dict, empty_body: bool = False) -> dict:
+ kwargs: dict = {}
+ query = query_for(op, world)
+ if query:
+ kwargs["params"] = query
+ if op.content_type == "application/json":
+ if empty_body:
+ kwargs["json"] = {}
+ else:
+ kwargs["json"] = _body(op, world)
+ elif op.content_type == "multipart/form-data":
+ kwargs["files"] = {"file": ("upload.png", PNG_BYTES, "image/png")}
+ elif op.content_type == "application/x-www-form-urlencoded":
+ kwargs["data"] = {"username": "[email protected]", "password": "testpass123"}
+ return kwargs
diff --git a/backend/tests/api_contract/conftest.py b/backend/tests/api_contract/conftest.py
new file mode 100644
index 00000000..985c7f69
--- /dev/null
+++ b/backend/tests/api_contract/conftest.py
@@ -0,0 +1,114 @@
+"""Fixtures for the API contract sweep.
+
+- Outbound network is blocked, so routes that call a provider (bank sync,
+ market quotes, OIDC, LLMs) answer with their own error handling instead
+ of reaching the internet. That handling is part of the contract.
+- With UPDATE_API_CONTRACT=1 the observed statuses are written back to
+ baseline.json at the end of the run (serial runs only). Add
+ API_CONTRACT_DETAILS=<file> to also dump why `ok` cases missed a 2xx.
+"""
+import json
+import os
+import socket
+from pathlib import Path
+
+import pytest
+import pytest_asyncio
+from httpx import AsyncClient
+
+from tests.api_contract.world import build_world
+
+BUSINESS_KIND = "business"
+BASELINE_PATH = Path(__file__).with_name("baseline.json")
+UPDATE_ENV = "UPDATE_API_CONTRACT"
+# Optional: a file path. In update mode, every `ok` case that did not reach
+# a 2xx appends its response detail there, to see why a happy path fails.
+DETAILS_ENV = "API_CONTRACT_DETAILS"
+_recorded: dict[str, dict[str, int]] = {}
+
+
+def updating_baseline() -> bool:
+ return os.environ.get(UPDATE_ENV) == "1"
+
+
+def load_baseline() -> dict[str, dict[str, int]]:
+ if not BASELINE_PATH.exists():
+ return {}
+ return json.loads(BASELINE_PATH.read_text())
+
+
+def record(variant: str, key: str, status: int, detail: str = "") -> None:
+ _recorded.setdefault(variant, {})[key] = status
+ details_path = os.environ.get(DETAILS_ENV)
+ if details_path and variant == "ok" and status >= 300:
+ with open(details_path, "a") as fh:
+ fh.write(json.dumps({"key": key, "status": status, "detail": detail}) + "\n")
+
+
+def pytest_configure(config):
+ if updating_baseline() and os.environ.get("PYTEST_XDIST_WORKER"):
+ raise pytest.UsageError(f"{UPDATE_ENV}=1 must run serially: add -n 0")
+
+
+def pytest_sessionfinish(session, exitstatus):
+ if not updating_baseline() or not _recorded:
+ return
+ merged = load_baseline()
+ for variant, statuses in _recorded.items():
+ merged.setdefault(variant, {}).update(statuses)
+ ordered = {v: dict(sorted(s.items())) for v, s in sorted(merged.items())}
+ BASELINE_PATH.write_text(json.dumps(ordered, indent=1) + "\n")
+
+
+@pytest_asyncio.fixture
+async def world(
+ client: AsyncClient,
+ session,
+ test_workspace,
+ auth_headers,
+ test_connection,
+ test_agent,
+ test_conversation,
+) -> dict:
+ # Business workspaces get every module (personal lacks invoicing), so
+ # the sweep reaches the invoice/product/schedule routes.
+ test_workspace.kind = BUSINESS_KIND
+ await session.commit()
+ return await build_world(
+ client,
+ auth_headers,
+ {
+ "connection_id": str(test_connection.id),
+ "agent_id": str(test_agent.id),
+ "conversation_id": str(test_conversation.id),
+ },
+ )
+
+
[email protected](autouse=True)
+def _contract_environment(monkeypatch, tmp_path, _mock_redis):
+ """Close the gaps between the shared test setup and a real deployment.
+
+ The shared `_mock_redis` patches the modules that existed when it was
+ written; OIDC keeps its login state in Redis too. Knowledge uploads
+ write under /app/data, which only exists in the container.
+ """
+ from app.agents.config import get_agent_settings
+
+ async def _fake_get_redis():
+ return _mock_redis
+
+ monkeypatch.setattr("app.api.oidc_auth.get_redis", _fake_get_redis)
+ monkeypatch.setattr(get_agent_settings(), "knowledge_storage_path", str(tmp_path / "knowledge"))
+
+
[email protected](autouse=True)
+def _no_outbound_network(monkeypatch):
+ real_connect = socket.socket.connect
+
+ def guarded(sock, address):
+ if sock.family in (socket.AF_INET, socket.AF_INET6):
+ raise OSError("outbound network is disabled in the API contract sweep")
+ return real_connect(sock, address)
+
+ monkeypatch.setattr(socket.socket, "connect", guarded)
diff --git a/backend/tests/api_contract/harness.py b/backend/tests/api_contract/harness.py
new file mode 100644
index 00000000..ad510d7e
--- /dev/null
+++ b/backend/tests/api_contract/harness.py
@@ -0,0 +1,102 @@
+"""Shared case runner for the contract test files.
+
+The sweep is split over several small test files on purpose: CI runs with
+`--dist loadfile`, which keeps a whole file on one worker, so one big file
+would serialize the whole sweep. `params_for` hands each file its shard.
+"""
+import pytest
+from httpx import AsyncClient
+
+from tests.api_contract.cases import (
+ ADMIN_PREFIXES,
+ DELIBERATE_500,
+ KNOWN_BUGS,
+ OPERATIONS,
+ POSTGRES_ONLY,
+ VARIANT_ANON,
+ VARIANT_EMPTY,
+ VARIANT_OK,
+ VARIANT_UNKNOWN_ID,
+ VARIANT_VIEWER,
+ Operation,
+ fill_path,
+ request_kwargs,
+ variants_for,
+)
+from tests.api_contract.conftest import load_baseline, record, updating_baseline
+
+# 500 is the one status no route may answer by design: it means an
+# unhandled exception. 502/503 are deliberate "provider unavailable" answers.
+UNHANDLED = 500
+NO_CONTENT = 204
+BASELINE = load_baseline()
+
+
+def params_for(variants: tuple[str, ...], shard: int = 0, shards: int = 1) -> list:
+ params = []
+ for index, op in enumerate(OPERATIONS):
+ if index % shards != shard:
+ continue
+ for variant in variants_for(op):
+ if variant not in variants:
+ continue
+ marks = []
+ bug = KNOWN_BUGS.get((variant, op.method, op.path))
+ if bug and not updating_baseline():
+ marks.append(pytest.mark.xfail(strict=True, reason=bug.reason))
+ sqlite_gap = POSTGRES_ONLY.get((op.method, op.path))
+ if sqlite_gap and variant == VARIANT_OK:
+ marks.append(pytest.mark.skip(reason=sqlite_gap))
+ params.append(pytest.param(variant, op, id=f"{variant}:{op.key}", marks=marks))
+ return params
+
+
+def headers_for(variant: str, op: Operation, auth: dict, admin: dict, viewer: dict | None = None) -> dict:
+ if variant == VARIANT_ANON:
+ return {}
+ if variant == VARIANT_VIEWER:
+ assert viewer is not None
+ return viewer
+ if op.path.startswith(ADMIN_PREFIXES):
+ return admin
+ return auth
+
+
+async def _send(client: AsyncClient, op: Operation, path: str, headers: dict, kwargs: dict):
+ """Send the request; an exception escaping the app counts as a 500."""
+ try:
+ resp = await client.request(op.method, path, headers=headers, **kwargs)
+ except Exception as exc: # noqa: BLE001 — any escape is the finding
+ return UNHANDLED, f"{type(exc).__name__}: {exc}", None
+ return resp.status_code, resp.text[:500], resp
+
+
+async def check_case(client: AsyncClient, variant: str, op: Operation, world: dict, headers: dict) -> None:
+ path = fill_path(op, world, unknown_ids=variant == VARIANT_UNKNOWN_ID)
+ kwargs = request_kwargs(op, world, empty_body=variant == VARIANT_EMPTY)
+
+ status, detail, resp = await _send(client, op, path, headers, kwargs)
+
+ if updating_baseline():
+ bug = KNOWN_BUGS.get((variant, op.method, op.path))
+ record(variant, op.key, bug.expected if bug else status, detail)
+ return
+
+ expected = BASELINE.get(variant, {}).get(op.key)
+ assert expected is not None, (
+ f"no baseline for {variant}:{op.key}; regenerate with UPDATE_API_CONTRACT=1"
+ )
+ if (op.method, op.path) not in DELIBERATE_500:
+ assert status != UNHANDLED, f"{op.method} {path} [{variant}] unhandled error: {detail}"
+ assert status == expected, (
+ f"{op.method} {path} [{variant}] expected {expected}, got {status}: {detail}"
+ )
+ if (
+ variant == VARIANT_OK
+ and resp is not None
+ and status < 300
+ and status != NO_CONTENT
+ and resp.content
+ and "json" in resp.headers.get("content-type", "")
+ ):
+ resp.json()
diff --git a/backend/tests/api_contract/test_api_contract.py b/backend/tests/api_contract/test_api_contract.py
new file mode 100644
index 00000000..126c2b05
--- /dev/null
+++ b/backend/tests/api_contract/test_api_contract.py
@@ -0,0 +1,44 @@
+"""API contract sweep: every route, every method, exact expected status.
+
+Expected statuses live in baseline.json. When a contract case fails, the
+route's behaviour changed: either the change is intentional (regenerate the
+baseline in the same PR so the diff documents it) or it is a regression (fix
+the code). See tests/api_contract/README.md.
+
+This file holds the checks on the sweep itself; the cases run from the
+test_contract_*.py shards.
+"""
+import pytest
+
+from tests.api_contract.cases import DELIBERATE_500, OPERATIONS, POSTGRES_ONLY, VARIANT_OK, VARIANTS
+from tests.api_contract.conftest import updating_baseline
+from tests.api_contract.harness import BASELINE, UNHANDLED
+
+
+async def test_world_builds(world):
+ failures = "\n".join(f"{key}: {why}" for key, why in world["_failed"].items())
+ assert not world["_failed"], f"world steps failed:\n{failures}"
+
+
+def test_baseline_covers_every_operation():
+ """A route added or removed without updating the baseline fails here."""
+ if updating_baseline():
+ pytest.skip("baseline is being regenerated")
+ expected = {op.key for op in OPERATIONS if (op.method, op.path) not in POSTGRES_ONLY}
+ recorded = set(BASELINE.get(VARIANT_OK, {})) - {f"{m} {p}" for m, p in POSTGRES_ONLY}
+ assert expected - recorded == set(), f"routes with no baseline: {sorted(expected - recorded)}"
+ assert recorded - expected == set(), f"baseline routes that no longer exist: {sorted(recorded - expected)}"
+
+
+def test_baseline_has_no_unhandled_errors():
+ """The baseline describes correct behaviour, so it may never expect a 500."""
+ if updating_baseline():
+ pytest.skip("baseline is being regenerated")
+ bad = {
+ f"{variant}:{key}": status
+ for variant in VARIANTS
+ for key, status in BASELINE.get(variant, {}).items()
+ if status == UNHANDLED and tuple(key.split(" ", 1)) not in DELIBERATE_500
+ }
+ assert bad == {}, f"baseline expects unhandled errors: {bad}"
diff --git a/backend/tests/api_contract/test_contract_guards_0.py b/backend/tests/api_contract/test_contract_guards_0.py
new file mode 100644
index 00000000..47c1cd83
--- /dev/null
+++ b/backend/tests/api_contract/test_contract_guards_0.py
@@ -0,0 +1,24 @@
+"""Contract cases without seeded data (anon, empty body, unknown id), shard 0 of 2.
+
+These fail before any row is read, so they skip the world fixture. See harness.py.
+"""
+import pytest
+from httpx import AsyncClient
+
+from tests.api_contract.cases import VARIANT_ANON, VARIANT_EMPTY, VARIANT_UNKNOWN_ID, Operation
+from tests.api_contract.harness import check_case, headers_for, params_for
+
+GUARD_VARIANTS = (VARIANT_ANON, VARIANT_EMPTY, VARIANT_UNKNOWN_ID)
+
+
[email protected](("variant", "op"), params_for(GUARD_VARIANTS, shard=0, shards=2))
+async def test_contract(
+ client: AsyncClient,
+ auth_headers,
+ admin_auth_headers,
+ variant: str,
+ op: Operation,
+):
+ headers = headers_for(variant, op, auth_headers, admin_auth_headers)
+ await check_case(client, variant, op, {}, headers)
diff --git a/backend/tests/api_contract/test_contract_guards_1.py b/backend/tests/api_contract/test_contract_guards_1.py
new file mode 100644
index 00000000..5ed36aab
--- /dev/null
+++ b/backend/tests/api_contract/test_contract_guards_1.py
@@ -0,0 +1,24 @@
+"""Contract cases without seeded data (anon, empty body, unknown id), shard 1 of 2.
+
+These fail before any row is read, so they skip the world fixture. See harness.py.
+"""
+import pytest
+from httpx import AsyncClient
+
+from tests.api_contract.cases import VARIANT_ANON, VARIANT_EMPTY, VARIANT_UNKNOWN_ID, Operation
+from tests.api_contract.harness import check_case, headers_for, params_for
+
+GUARD_VARIANTS = (VARIANT_ANON, VARIANT_EMPTY, VARIANT_UNKNOWN_ID)
+
+
[email protected](("variant", "op"), params_for(GUARD_VARIANTS, shard=1, shards=2))
+async def test_contract(
+ client: AsyncClient,
+ auth_headers,
+ admin_auth_headers,
+ variant: str,
+ op: Operation,
+):
+ headers = headers_for(variant, op, auth_headers, admin_auth_headers)
+ await check_case(client, variant, op, {}, headers)
diff --git a/backend/tests/api_contract/test_contract_ok_0.py b/backend/tests/api_contract/test_contract_ok_0.py
new file mode 100644
index 00000000..7848fdc8
--- /dev/null
+++ b/backend/tests/api_contract/test_contract_ok_0.py
@@ -0,0 +1,20 @@
+"""Contract cases: owner happy path, shard 0 of 4. See harness.py."""
+import pytest
+from httpx import AsyncClient
+
+from tests.api_contract.cases import VARIANT_OK, Operation
+from tests.api_contract.harness import check_case, headers_for, params_for
+
+
[email protected](("variant", "op"), params_for((VARIANT_OK,), shard=0, shards=4))
+async def test_contract(
+ client: AsyncClient,
+ world,
+ auth_headers,
+ admin_auth_headers,
+ variant: str,
+ op: Operation,
+):
+ headers = headers_for(variant, op, auth_headers, admin_auth_headers)
+ await check_case(client, variant, op, world, headers)
diff --git a/backend/tests/api_contract/test_contract_ok_1.py b/backend/tests/api_contract/test_contract_ok_1.py
new file mode 100644
index 00000000..6566ba35
--- /dev/null
+++ b/backend/tests/api_contract/test_contract_ok_1.py
@@ -0,0 +1,20 @@
+"""Contract cases: owner happy path, shard 1 of 4. See harness.py."""
+import pytest
+from httpx import AsyncClient
+
+from tests.api_contract.cases import VARIANT_OK, Operation
+from tests.api_contract.harness import check_case, headers_for, params_for
+
+
[email protected](("variant", "op"), params_for((VARIANT_OK,), shard=1, shards=4))
+async def test_contract(
+ client: AsyncClient,
+ world,
+ auth_headers,
+ admin_auth_headers,
+ variant: str,
+ op: Operation,
+):
+ headers = headers_for(variant, op, auth_headers, admin_auth_headers)
+ await check_case(client, variant, op, world, headers)
diff --git a/backend/tests/api_contract/test_contract_ok_2.py b/backend/tests/api_contract/test_contract_ok_2.py
new file mode 100644
index 00000000..2b34ac99
--- /dev/null
+++ b/backend/tests/api_contract/test_contract_ok_2.py
@@ -0,0 +1,20 @@
+"""Contract cases: owner happy path, shard 2 of 4. See harness.py."""
+import pytest
+from httpx import AsyncClient
+
+from tests.api_contract.cases import VARIANT_OK, Operation
+from tests.api_contract.harness import check_case, headers_for, params_for
+
+
[email protected](("variant", "op"), params_for((VARIANT_OK,), shard=2, shards=4))
+async def test_contract(
+ client: AsyncClient,
+ world,
+ auth_headers,
+ admin_auth_headers,
+ variant: str,
+ op: Operation,
+):
+ headers = headers_for(variant, op, auth_headers, admin_auth_headers)
+ await check_case(client, variant, op, world, headers)
diff --git a/backend/tests/api_contract/test_contract_ok_3.py b/backend/tests/api_contract/test_contract_ok_3.py
new file mode 100644
index 00000000..494ce852
--- /dev/null
+++ b/backend/tests/api_contract/test_contract_ok_3.py
@@ -0,0 +1,20 @@
+"""Contract cases: owner happy path, shard 3 of 4. See harness.py."""
+import pytest
+from httpx import AsyncClient
+
+from tests.api_contract.cases import VARIANT_OK, Operation
+from tests.api_contract.harness import check_case, headers_for, params_for
+
+
[email protected](("variant", "op"), params_for((VARIANT_OK,), shard=3, shards=4))
+async def test_contract(
+ client: AsyncClient,
+ world,
+ auth_headers,
+ admin_auth_headers,
+ variant: str,
+ op: Operation,
+):
+ headers = headers_for(variant, op, auth_headers, admin_auth_headers)
+ await check_case(client, variant, op, world, headers)
diff --git a/backend/tests/api_contract/test_contract_viewer_0.py b/backend/tests/api_contract/test_contract_viewer_0.py
new file mode 100644
index 00000000..15841cd6
--- /dev/null
+++ b/backend/tests/api_contract/test_contract_viewer_0.py
@@ -0,0 +1,21 @@
+"""Contract cases: viewer-role writes, shard 0 of 2. See harness.py."""
+import pytest
+from httpx import AsyncClient
+
+from tests.api_contract.cases import VARIANT_VIEWER, Operation
+from tests.api_contract.harness import check_case, headers_for, params_for
+
+
[email protected](("variant", "op"), params_for((VARIANT_VIEWER,), shard=0, shards=2))
+async def test_contract(
+ client: AsyncClient,
+ world,
+ auth_headers,
+ admin_auth_headers,
+ viewer_auth_headers,
+ variant: str,
+ op: Operation,
+):
+ headers = headers_for(variant, op, auth_headers, admin_auth_headers, viewer_auth_headers)
+ await check_case(client, variant, op, world, headers)
diff --git a/backend/tests/api_contract/test_contract_viewer_1.py b/backend/tests/api_contract/test_contract_viewer_1.py
new file mode 100644
index 00000000..fcf7c0be
--- /dev/null
+++ b/backend/tests/api_contract/test_contract_viewer_1.py
@@ -0,0 +1,21 @@
+"""Contract cases: viewer-role writes, shard 1 of 2. See harness.py."""
+import pytest
+from httpx import AsyncClient
+
+from tests.api_contract.cases import VARIANT_VIEWER, Operation
+from tests.api_contract.harness import check_case, headers_for, params_for
+
+
[email protected](("variant", "op"), params_for((VARIANT_VIEWER,), shard=1, shards=2))
+async def test_contract(
+ client: AsyncClient,
+ world,
+ auth_headers,
+ admin_auth_headers,
+ viewer_auth_headers,
+ variant: str,
+ op: Operation,
+):
+ headers = headers_for(variant, op, auth_headers, admin_auth_headers, viewer_auth_headers)
+ await check_case(client, variant, op, world, headers)
diff --git a/backend/tests/api_contract/world.py b/backend/tests/api_contract/world.py
new file mode 100644
index 00000000..505ab396
--- /dev/null
+++ b/backend/tests/api_contract/world.py
@@ -0,0 +1,150 @@
+"""Seed one complete workspace through the API and collect the ids.
+
+Every contract case gets its own world, so DELETE cases can't leak into
+other cases. Steps run in order. A step that fails is recorded in
+`world["_failed"]` instead of raising, so one broken create endpoint shows
+up as a clear failure in `test_world_builds` and doesn't hide every other
+case behind a fixture error.
+"""
+from dataclasses import dataclass
+from typing import Any, Callable
+
+from httpx import AsyncClient
+
+MONTH = "2026-04-01"
+DAY = "2026-04-28"
+# Smallest valid PNG (1x1 transparent pixel): attachment routes sniff the type.
+PNG_BYTES = bytes.fromhex(
+ "89504e470d0a1a0a0000000d4948445200000001000000010806000000"
+ "1f15c4890000000d49444154789c6360000002000100e5279ed80000000049454e44ae426082"
+)
+
+
+@dataclass(frozen=True)
+class Step:
+ key: str
+ method: str
+ path: str
+ body: Callable[[dict], Any] | None = None
+ files: Callable[[dict], Any] | None = None
+ id_field: str = "id"
+
+
+def _tx(account_key: str = "account_id", **extra) -> Callable[[dict], dict]:
+ def build(w: dict) -> dict:
+ return {
+ "account_id": w[account_key],
+ "description": "Groceries",
+ "amount": 60,
+ "date": DAY,
+ "type": "debit",
+ "currency": "USD",
+ **{k: (v(w) if callable(v) else v) for k, v in extra.items()},
+ }
+
+ return build
+
+
+STEPS: list[Step] = [
+ Step("account_id", "POST", "/api/accounts",
+ lambda w: {"name": "Wallet", "type": "checking", "balance": 0, "currency": "USD"}),
+ Step("second_account_id", "POST", "/api/accounts",
+ lambda w: {"name": "Savings", "type": "savings", "balance": 0, "currency": "USD"}),
+ Step("category_id", "POST", "/api/categories", lambda w: {"name": "Food", "type": "expense"}),
+ Step("second_category_id", "POST", "/api/categories",
+ lambda w: {"name": "Clothing", "type": "expense"}),
+ Step("category_group_id", "POST", "/api/category-groups", lambda w: {"name": "Essentials"}),
+ Step("payee_id", "POST", "/api/payees", lambda w: {"name": "Market"}),
+ Step("second_payee_id", "POST", "/api/payees", lambda w: {"name": "Corner shop"}),
+ Step("transaction_id", "POST", "/api/transactions", _tx(category_id=lambda w: w["category_id"])),
+ Step("second_transaction_id", "POST", "/api/transactions", _tx(description="Bakery")),
+ Step("savings_transaction_id", "POST", "/api/transactions",
+ _tx("second_account_id", description="Transfer in", type="credit")),
+ Step("group_id", "POST", "/api/groups",
+ lambda w: {"name": "Roommates", "kind": "social", "default_currency": "USD"}),
+ Step("member_id", "POST", "/api/groups/{group_id}/members", lambda w: {"name": "Ana"}),
+ Step("second_member_id", "POST", "/api/groups/{group_id}/members", lambda w: {"name": "Bruno"}),
+ Step("split_transaction_id", "POST", "/api/transactions", _tx(
+ description="Dinner",
+ splits=lambda w: {"share_type": "equal", "splits": [
+ {"group_member_id": w["member_id"]}, {"group_member_id": w["second_member_id"]},
+ ]},
+ )),
+ Step("settlement_id", "POST", "/api/groups/{group_id}/settlements", lambda w: {
+ "from_member_id": w["member_id"], "to_member_id": w["second_member_id"],
+ "amount": "15.00", "currency": "USD", "date": DAY,
+ }),
+ Step("budget_id", "POST", "/api/budgets",
+ lambda w: {"category_id": w["category_id"], "amount": 500, "month": MONTH}),
+ Step("goal_id", "POST", "/api/goals", lambda w: {"name": "Emergency fund", "target_amount": 1000}),
+ Step("recurring_id", "POST", "/api/recurring-transactions", lambda w: {
+ "description": "Rent", "amount": 900, "type": "debit", "frequency": "monthly",
+ "start_date": MONTH, "account_id": w["account_id"], "currency": "USD",
+ }),
+ Step("rule_id", "POST", "/api/rules", lambda w: {
+ "name": "Market rule",
+ "conditions": [{"field": "description", "op": "contains", "value": "Market"}],
+ "actions": [{"op": "set_category", "value": w["category_id"]}],
+ "apply_to_existing": False,
+ }),
+ Step("asset_group_id", "POST", "/api/asset-groups", lambda w: {"name": "Brokerage"}),
+ Step("asset_id", "POST", "/api/assets",
+ lambda w: {"name": "House", "type": "real_estate", "currency": "USD"}),
+ Step("value_id", "POST", "/api/assets/{asset_id}/values", lambda w: {"amount": 250000, "date": DAY}),
+ Step("collection_id", "POST", "/api/collections", lambda w: {"name": "Trip"}),
+ Step("product_id", "POST", "/api/products", lambda w: {"name": "Consulting hour"}),
+ Step("price_id", "POST", "/api/products/{product_id}/prices",
+ lambda w: {"currency": "USD", "unit_price": "100.00"}),
+ Step("invoice_id", "POST", "/api/invoices", lambda w: {
+ "as_draft": True, "payee_id": w["payee_id"], "currency": "USD",
+ "lines": [{"description": "Consulting", "quantity": 2, "unit_price": "100.00"}],
+ }),
+ Step("issued_invoice_id", "POST", "/api/invoices", lambda w: {
+ "payee_id": w["payee_id"], "currency": "USD",
+ "lines": [{"description": "Consulting", "quantity": 1, "unit_price": "250.00"}],
+ }),
+ Step("schedule_id", "POST", "/api/invoice-schedules", lambda w: {
+ "name": "Monthly retainer", "frequency": "monthly",
+ "lines": [{"description": "Retainer", "quantity": 1, "unit_price": "100.00"}],
+ }),
+ Step("attachment_id", "POST", "/api/transactions/{transaction_id}/attachments",
+ files=lambda w: {"file": ("receipt.png", PNG_BYTES, "image/png")}),
+ Step("agents_connection_id", "POST", "/api/agents/connections",
+ lambda w: {"name": "Local LLM", "kind": "ollama", "base_url": "http://ollama:11434"}),
+]
+
+
+async def _lookup(client: AsyncClient, headers: dict, world: dict) -> None:
+ me = await client.get("/api/users/me", headers=headers)
+ if me.status_code == 200:
+ world["user_id"] = world["id"] = me.json()["id"]
+ ws = await client.get("/api/workspaces/current", headers=headers)
+ if ws.status_code == 200:
+ body = ws.json()
+ world["workspace_id"] = body.get("id") or body.get("workspace", {}).get("id")
+
+
+async def build_world(client: AsyncClient, headers: dict, fixtures: dict) -> dict:
+ world: dict = {"_failed": {}, **fixtures}
+ await _lookup(client, headers, world)
+ for step in STEPS:
+ try:
+ path = step.path.format(**world)
+ except KeyError as missing:
+ world["_failed"][step.key] = f"missing {missing} for {step.path}"
+ continue
+ kwargs: dict = {"headers": headers}
+ try:
+ if step.files:
+ kwargs["files"] = step.files(world)
+ elif step.body:
+ kwargs["json"] = step.body(world)
+ except KeyError as missing:
+ world["_failed"][step.key] = f"missing {missing} for body"
+ continue
+ resp = await client.request(step.method, path, **kwargs)
+ if resp.status_code >= 300:
+ world["_failed"][step.key] = f"{resp.status_code}: {resp.text[:300]}"
+ continue
+ world[step.key] = resp.json().get(step.id_field)
+ return world