Skip to content

Latest commit

 

History

History
2364 lines (2183 loc) · 159 KB

HANDOFF.md

File metadata and controls

2364 lines (2183 loc) · 159 KB

Handoff

Where the work stands, what is deliberately unfinished, and what needs a person. Standing rules are in CLAUDE.md; this file is the part that changes.

Update this before finishing a session. A stale handoff is worse than none — it is read as current, and this repository has already been bitten twice by status documents that described built features as missing.

2026-11-17 — the ZCode harness lands, and the first gated change is READY

As of: 2026-11-17 · branched from main at 0043bdc (#162).

A .zcode/ harness and AGENTS.md now exist (this commit): nine role agents, five skills, eleven seeded memory records, a generated-path guard hook, and three saved workflows — printorian-gated-change, printorian-development-studio, printorian-docs-audit. Its architecture is ported from lumen's harness and rebuilt around this repo's own rules: GitHub issues stay the only tracker, the six gates replace ctest, HANDOFF.md is the session state. Owner rulings are recorded in it verbatim: the deployment shape (containers under systemd, no microservices, no host installs) and the printorian-server charter (the host layer pivots from INFRASTRUCTURE §3's Debian choice to a custom minimal Arch system — that doc amendment is still to be filed as a type:docs issue, deliberately not edited unasked).

The first gated change is READY and awaiting review: branch zcode/docs-linux-venv-layout (a519a93, +12/−7 in backend/CLAUDE.md) documents the Linux venv layout alongside the Windows one. Six gates green before and after; full suite exit 0; independent review clean with one pre-existing NOTE deferred (bare alembic paths in the Traps section; and docs/DEVELOPMENT.md carries the same Windows-only paths throughout — drift candidates). PR text is ready; nothing pushed. Execution disclosure: the run was orchestrated manually (the workflow tool was not exposed in these sessions), following the saved workflow's phases exactly.

Dev environment on the fastvm Arch VM is green, disclosed deviations and all: Python 3.14.10 (CI uses 3.13), native PostgreSQL 18 + valkey on 5433/6380 (the compose files pin postgres:17-alpine; Docker Hub blob CDNs are unreachable from this network — measured, recorded in .zcode/memories/printorian-host-layouts.md). The baseline comes from printorian-server's tools/psrv_bootstrap.py — the same script the real server hardware will run. The app's test role needed CREATEDB natively (25 suite errors → green, measured).

What needs a person: review/merge zcode/docs-linux-venv-layout; push it (SSH remote); create the GitHub iritur/printorian-server repo before its first push; decide when the harness rides to origin (committed here, pushed with your next approval).

2026-10-15 — why no issue had closed since September, and #27 closed

As of: 2026-10-15 · branched from main at 27a0c56 (#141).

Every open issue was waiting on something that is not code. The last issue to close did so on 2026-09-26, and every pull request since then delivered a slice of an issue whose "Done when" needs hardware, a server, a person's account or a decision. Only #14 and #18 said so in their labels, so the tracker looked workable when it was not. The owner chose to relabel rather than split: #15, #16, #19, #22, #24 and #25 are now needs-person, and #17 and #26 are blocked:hardware. The seven deferred issues stay open by design (WORKFLOW §3).

The owner also made the decisions three issues were waiting on:

  • #27 §5(a)–(d) — trust one named proxy, keep the refund split, a smaller anonymous upload limit, and hold late money for a person;
  • #35 — one shared stock model for packaging, consumables and spare parts;
  • #29 — webhooks through a transactional outbox.

#27 is closed by this work.

  • Held payments. contexts/payments/holding.py writes a hold when a settlement moves no order (migration 0035_payment_holds).
    • Holds are listed at GET /payments/held and shown in «Оплаты на удержании».
    • printorian_payments_held counts them for the PaymentHeld digest.
    • A person resolves each one: refund it, or release it with a reason (ISSUE_REFUND).
  • One address rule. api/client_address.py replaces the two opposite-end readers of X-Forwarded-For. The header is believed only from the proxies in trusted_proxies, which compose.prod.yml sets to the two Caddy containers at fixed addresses on a fixed subnet.
    • The YooKassa adapter is handed source= and no longer parses the header.
  • Anonymous upload limit. anonymous_upload_bytes (50 MiB) bounds both /pricing endpoints for anonymous callers. The preview's hard-coded 80 MiB is gone.
  • Filed, not decided here: #142 (where the payment credential lives), #143 (model_asset_id) and #144 (the edge review, blocked on #18).

Each fix was checked by breaking it on purpose and watching its own test fail. Seven such breakages were run, and each failed exactly the intended test.

Drift found on the way. DATABASE-REVIEW and test_referential_integrity.py's docstring both said fifty-nine foreign keys; the inventory holds seventy-seven, counted from the sets the test checks against the database. Corrected.

#35, first half: packaging, consumables and spare parts are stock.

  • The model. inventory.stock_articles holds an item and how many there are, in its own unit and at most one cell. article_movements is its ledger: the spool ledger's shape, in the article's unit. Migration 0036 creates both and backfills them from packaging_tara.stock and postproduction_consumables.remaining, with one opening-balance row each.
  • Who writes it:
    • receiving, now that packaging, consumables and spare parts are in RECEIVABLE; the receipt's stock_article_id points at the article;
    • packing, where packaging/choosing.py consumes the box and gives a replaced box back;
    • stock_tara's typed level, which becomes a stock.counted correction;
    • the store's move, issue and write-off.
  • Who reads it: the packing and post-processing catalogues, and the store's map, cell panel and feed.
  • Not one widened table. The ledger is separate from material_movements, because that table is grams-shaped. The owner chose "one shared model" in words that said "widened"; the PR says why it isn't.
  • Expand/contract. packaging_tara.stock is still written beside the article (choosing._mirror). postproduction_consumables.remaining is no longer read. A later migration drops both.
  • And the second half, which closes #35: a stocktake lines up articles in the counted cells (stocktake_article_lines, migration 0037) and corrects them at close through the article ledger, against the book at close. Turnover for articles is days of cover (on hand ÷ the window's daily use) rather than days per lot, because fungible stock has no per-item history; the unused items are counted beside the mean. Dead articles join the one VIEW_FINANCIALS total, valued at their recorded unit cost and counted as unpriced otherwise.
  • Fixed on the way: a packer who changed boxes used to take two boxes off the shelf for one parcel.

Trap. After a session restart docker is not on PATH in Git Bash, and docker.exe there has no compose plugin. Use /c/Program Files/Docker/Docker/resources/bin/docker.exe and docker-compose.exe from the same directory.

2026-10-15 — what an unreachable printer costs the worker process

As of: 2026-10-15 · branched from main at edbcef5 (#140).

#26: the mitigations are in and measured; the ceiling against real printers is not. BambuDriver.connect ran paho's synchronous connect and a threading.Event.wait on the event loop, and paho bounds the TLS handshake by the MQTT keepalive (60 s), not its five-second connect_timeout. So one printer that was switched on but silent froze the whole worker process — every loop, every heartbeat — for 60 s, and the pool retried it on every pass. That was measured with backend/tools/measure_driver_pool.py, which runs the real pool and the real driver against a silent local listener: 60.1 s for one printer, 240.2 s for four.

Now:

  • connect, disconnect and the FTPS upload run in threads.
  • The pool attempts up to eight printers at once.
  • A failed printer is retried on a jittered backoff: 30 s doubling to 5 min.
  • New details are tried at once.
  • One refresh runs at a time, because the scheduler and the poller share the pool and could otherwise give one machine two MQTT sessions.

The table is in docs/DEVELOPMENT.md. Beyond eight silent printers the passes lengthen in 60-second waves, but the loop never stalls.

test_bambu_connect_off_loop.py uses the real driver. With the fix reverted the event loop ticked zero times during the connect. The six pool properties were each removed in turn, and each failed its own test.

Two traps. Existing pool tests that assumed an immediate retry now advance the clock past the backoff. And paho leaks the SSLSocket of a handshake that times out, which CPython frees at once; the warning is filtered in that one test and the comment says why.

#35 is not code-only. Its last item is the three non-filament stock classes. Packaging stock lives in packaging.Tara, post-processing stock in postproduction.Consumable — neither with an increment — and spare parts have no stock model at all. The movement ledger is keyed on filament lots in grams. Where non-filament stock lives was a decision across three contexts; the owner made it the same day — one shared stock model that packaging, post-processing and service consume from, with the movement ledger widened to it. That is the next build.

2026-10-14 — the security review's recorded list, worked down

As of: 2026-10-14 · branched from main at 3b40583 (#129). Each pull request below names its own gates and tests; this section is what the next person needs that the pull requests do not say.

Payments: five of the second pass's recorded gaps closed (F13–F17 in docs/SECURITY-REVIEW.md). A payment the gateway cancelled is now recorded — by notification, or by asking the gateway when the customer reopens checkout — so start registers a fresh one instead of handing back a dead confirmation page; asking also settles a payment whose success notification was lost. Two concurrent starts make one payment: migration 0031_one_live_payment_per_order adds a partial unique index on the order's live payment, and the loser of a double click hits it before the gateway is called. Currency is reconciled on settlement, and PaymentProvider.refund takes currency as a required keyword, so no adapter can default it. Malformed webhook bodies are a coded refusal rather than a 500, and every notification row is linked to its payment. Each test was checked by reverting its fix and watching it fail. Refunding moved to payments/refunding.py as a mixin, because service.py passed the 400-line gate. Not done, and why: money arriving for an order the farm already cancelled is still accepted silently. Refund it, reinstate the order, or hold it for a person is the owner's call, and §5(d) of the review says so.

The web-facing items closed too (F18–F21). WebSocket handshakes from another site are refused before the cookie is read — loopback origins pass outside production only, because the Vite proxy rewrites Host and not Origin, so a dev console that loses its live stream after a config change should look there first. The session cookie is Secure when X-Forwarded-Proto says https (api/session_cookie.py); the LAN console over plain HTTP is unchanged. The storefront Caddyfile answers /api/health* and /api/metrics* with 404 — checked with caddy adapt in the pinned image, since nothing in CI validates a Caddyfile. The journal's unsubscribe token is logged as {token}, and subscribing has the auth ceiling. Registration enumeration is recorded as accepted in the review's §4 until outbound mail exists.

And the plate upload (F22). POST /jobs/{id}/plate/file builds its RecordPlate before storage.put now, so a refused plate leaves nothing in the object store, and answers an oversize part with 413. Of the second pass's recorded list, three items remain: money arriving for a cancelled order (a decision), DraftLine.model_asset_id (waits on the decision to wire it through — the review says what that change must carry), and the console's dead finance.payment_provider settings.

Three traps from this session. After a dependency pull request merges, the local virtualenv is stale until it is reinstalled the way CI does it — pip install -e ".[dev]" -c constraints.txt — and the symptom is two dozen mypy errors in files nobody touched (SQLAlchemy 2.1's variadic Select). And Docker Desktop does not start with the machine: docker compose fails with "cannot find the file specified" on the engine pipe until it is launched, and Postgres answers "the database system is starting up" for about fifteen seconds after that. And a bare python - in a Git Bash command, with no heredoc after it, waits on stdin for ever; the tool times out at ten minutes and the rest of the command never runs. Write multi-line scripts to a file and run that.

#29: API keys are built. identity.api_keys, migration 0032_api_keys, /api-keys, and settings/ApiKeysPanel.tsx on «Доступ и безопасность». A key is shown once and stored as a SHA-256, like a session token; it may hold only KEY_PERMISSIONS (the four view_* reads) and never more than its owner holds now — demote the owner and it shrinks, deactivate them or revoke it and it stops. The one design decision to know before touching api/deps.py: a key is resolved by get_caller, which both requires(...) and CurrentActor sit on, and CurrentActor refuses a key. So a key works only on a route that asks for nothing but requires(<read permission>), and every route that acts as a person — /account/*, /auth/me, /orders/mine — refuses it by default; a route that wants keys must not ask for CurrentActor. requires also refuses a key on any non-read method, so a write gated only by a view_* permission is still not a write a leaked key can make. The live stream takes a key too, which is the kit's floor-screen example. throttle_key and client_ip moved to api/client_address.py to give deps.py the room. Checked in the running console against a throwaway owner (created, used, deleted): the key shows once on its own line, «не использовался» rather than a dash, revoke stops it. Still owed on #29: the notification event matrix and webhooks.

#22: /metrics serves eleven of INFRASTRUCTURE §5's twelve series. The four database-backed ones are production.vitals (the oldest job wedged in ASSIGNED or DISPATCHING, the prep queue's depth, the variance band's 30-day mean with its sample count beside it) and payments.reconciliation (payments the gateway said were paid that are not settled — a refused settlement rolls back with its notification and cannot be counted there). The two ADR-0019 stamps come from maintenance_runs, one row per success that backup.sh (through psql) and restore_drill.py write; a job that never succeeded has no sample, so an alert on them must say absent() as well as "too old". And the alert rules are written and proven — deploy/observability/rules/printorian.yml, fifteen rules, with promtool test rules in a new CI job alerts. Each test breaks one thing and asserts its own alert fires and the others stay quiet, and thirty healthy hours page nobody. Every rule that fires on a missing series is fenced by the series proving its source was reachable (up{job="printorian-api"}, or printorian_orders_awaiting_prep for the database readings). Without that, one outage pages four times. backend/tests/unit/test_alert_rules.py fails if a rule reads a name metrics.SERVED does not hold, and scrape.yml defines the job names the rules select. Each threshold says where it came from; the two that are judgements (DISPATCHING for fifteen minutes, a payment unsettled for thirty) say so. What remains of #22: the money series, which waits for the scrape to have an identity; the worker exporter; the VictoriaMetrics/vmalert/Alertmanager/ node-exporter services themselves; the Telegram bot and chat, which are a person's; and the dead-man's watcher. Corrupting a backup cannot page within five minutes on the stamps alone, because a failed backup leaves no row and the stamp only goes stale after 26 hours. Meeting that exit criterion needs the systemd units' OnFailure= to post straight to Alertmanager. When running promtool locally from Git Bash, set MSYS_NO_PATHCONV=1 and mount $(pwd -W), or the volume path is mangled.

#16: the off-site copy is written; only the destination is missing. deploy/offsite.sh runs in the pinned restic image from printorian-offsite.timer (05:00). It copies the blob store first and the backup disk second (ADR-0019's order), skips .partial and .tmp, then runs forget --prune and a structural check. The unit's ExecStartPost writes an offsite row to maintenance_runs through the postgres container; migration 0034 widened the CHECK to allow it. /metrics serves the result as printorian_offsite_last_success_timestamp, and OffsiteCopyStale is a 26-hour digest.

Before anything is written, the script refuses an uninitialised repository (it never runs restic init itself), an unmounted source, and a backup disk with no dump on it. CI job offsite runs the script against a local repository with the same mounts and proves the refusals, the order, the exclusions, a byte-for-byte restore and that retention groups nights under one fixed host. Each of those checks was confirmed to fail when the property it guards was removed.

Two things to know before touching it. First, restic 0.17+ keeps the oldest snapshot under --keep-daily too, so two runs on one day leave two snapshots of each kind, not one. Second, the container's hostname is random, which is why --host is fixed: without it forget never forgets anything.

Still a person's: choosing the destination and its keys, rendering deploy/offsite.env (gitignored), restic init, escrowing the password, and the first restore from the off-site copy (RUNBOOK §2 and §5 have the commands).

Not done: systemd-analyze verify in CI. It parses the new unit cleanly, but in a container it fails on the host's absence (docker.service, /srv/printorian), so it needs a stubbed host before it can be a gate.

Trap: override get_caller, not get_current_actor. Since the API keys, requires(...) and CurrentActor both sit on api/deps.get_caller. A test that substitutes the caller by overriding get_current_actor alone leaves every requires gate reading the real token, and the request arrives as a 401 instead of the 403 the test expects — that is how #133's first CI run failed.

2026-10-06 (later) — code scanning: four alerts fixed, one left for a person to dismiss

As of: 2026-10-06 · on claude/trusting-brown-hfc1pu, main at #125 (aea1723) plus this session. The alert list was not readable from here — no tool reaches the code-scanning API — so it was reproduced: CodeQL 2.27.1 (the version CI's default setup ran), the default *-code-scanning.qls suite per language (the default setup's config names no other), over a clean git archive of main. Five results; after the fixes, the same scan gives python 1, javascript 0, actions 0. Frontend: typecheck, lint, build exit=0, tests 348 passed in 39 files (nine new).

  • js/xss-through-dom, design/js/kit.js — the catalogue's filter chips were an HTML string built from each checkbox's id and label. Built as elements now. Checked in Chromium against main's copy and this one: the same chip, the same un-ticking; a label planted with <img onerror=...> ran on main and renders as text here.
  • js/polynomial-redos, frontend/packages/ui/src/journal/blocks.ts — slugify trimmed ^-+|-+$ after a replace that already collapses every run to one hyphen, so it was never slow; it trims ^-|-$ now, which states the invariant. blocks.test.ts pins slugify and anchorOf with values produced by policies.py::slugify; the old pattern passes it too (equivalence), and breaking the collapse fails three cases.
  • actions/missing-workflow-permissions, ci.yml ×2 — backend and frontend ran with the repository's default token grant. The workflow defaults to contents: read; image keeps its own block.
  • Left: py/bind-socket-all-network-interfaces, backend/tools/bambu_spike.py — see §5. Binding every interface is what lets discover hear UDP broadcasts at all; the comment at the bind says so.

2026-10-06 — both Dependabot pull requests red, for two different reasons

As of: 2026-10-06 · 1 736 passed, 7 skipped, exit=0 in 598.22s (0:09:58) — pytest's own trailing summary line, read out of the redirect on claude/trusting-brown-hfc1pu, which is main at #122 (5142305) plus this session, against PostgreSQL 16 (CI runs 17). The six backend gates each exit=0: ruff check, ruff format --check, mypy --strict over 272 source files, lint-imports (6 kept, 0 broken), check_context_isolation.py, check_file_length.py; alembic upgrade head on an empty database and alembic check exit=0; pip-audit found nothing. Frontend, on Node 22 (CI runs 24): npm ci, npm audit --audit-level=high, generate:api, typecheck, lint, build each exit=0, and the suite 339 passed in 38 files.

#123 (frontend) was red because of main. Four advisories were published after main's last green run (2026-09-26) — three against brace-expansion, one against source-map-js — and the audit step fails on them. #123 touches neither package; npm audit on main fails identically. Fixed in the lockfile alone (npm audit fix under npm 11, the major CI runs): brace-expansion 5.0.9 → 5.0.12 and 2.1.4 → 2.1.7, source-map-js 1.2.1 → 1.2.2, each inside the range its parent already declares. The same three-package change on #123's own head audits clean. Once this merges, #123 needs @dependabot rebase.

#124 (backend) was red because of itself: SQLAlchemy 2.0.54 → 2.1.1. Three separate breaks, and CI showed only the first, because mypy runs before the tests:

  1. Typing. Select and Row are variadic generics in 2.1, so Select[tuple[Model]] now means "one column of type tuple" — it is Select[Model] (catalogue browse, journal). Unpacked rows are typed now, which made two type: ignore[arg-type] unused and surfaced the scorecard's operator_id as UUID | None (narrowed with an assert; the query filters nulls, the procurement/prices.py precedent). select() on a dict[str, Any] column falls through to the untyped overload, so the finance read annotates its result.
  2. Result.tuples() is deprecated in 2.1, and filterwarnings = ["error"] fails every caller. Three call sites are dict(rows.all()) now, which is what 2.1's typed Row allows.
  3. A bare postgresql:// selects psycopg 3 in 2.1, not psycopg2. The test harness built its sync admin URL by stripping +asyncpg, so every database test errored at setup with No module named 'psycopg'. It names +psycopg2 now — what test_migrations.py already did for its other engines. Application code is asyncpg-only and was never affected, and scripts/restore_drill.py already kept its driver suffix for a reason of the same shape.

The branch carries #124's seven pins with these fixes, and the pyproject.toml floor is >=2.1 because the annotations no longer type-check against 2.0. So #124 is superseded: once this merges, a rebase leaves it empty and Dependabot closes it, or it can be closed by hand. Nothing was pushed to either Dependabot branch — a push there stops Dependabot maintaining the pull request.

Trap met: addopts already carries -q. Passing -q again makes it -qq, which drops pytest's trailing summary line — the line this file quotes as evidence. Run pytest bare (or with -rfE) and read the summary out of the redirect.

2026-09-24 — main had been red for two weeks, and the fix was one pin

As of: 2026-09-24 · 1 619 passed, 7 skipped, exit=0 in 1687.95s (0:28:07) — pytest's own trailing summary line, read out of the redirect on claude/printorian-pr-fixes-1a9039, which is main at #107 (b64a664) plus this session. The six backend gates each ran separately and each exit=0: ruff check, ruff format --check, mypy --strict over 255 source files, lint-imports (6 kept, 0 broken), check_context_isolation.py, check_file_length.py. Frontend: typecheck and lint exit=0; the two screen test files this session touched ran green (SettingsPage.test.tsx 21 passed, PurchasingPage.test.tsx 9 passed); the whole frontend suite and build were not run here, and CI on the pull request is what will.

Why main was red. #106 (2026-09-09) raised anyio to 4.15.1, which deprecates anyio.abc.BlockingPortal. starlette 1.6.0 still imports it from there, in testclient.py, which tests/api/test_events_ws.py pulls in; filterwarnings = ["error"] makes that import a collection error, and pytest exits 2 before running a single test. The backend job has failed on that line on every push since, including both open Dependabot pull requests — the frontend one too (#110), which is what gave it away as a main problem rather than a PR problem. #106 merged with its backend check red because branch protection (#67) is not on; that issue is the thing that would have caught this, and it still needs a person with admin. The fix is starlette==1.7.0 in backend/constraints.txt, which imports the portal from anyio.from_thread; the comment there says why a filterwarnings ignore was refused. Once this merges, #110 and #111 need @dependabot rebase.

The suite above ran before the scorecard tests existed (it was started first); the nine unit and two API tests for the scorecard, the split test_purchasing_api.py, and #58's two intake files were then run in one further session: 28 passed, exit=0 in 54.63s. Four mutations were applied to the scorecard, run and reverted, and each failed at least one of its nine unit tests: counting RECEIVING as a delivery (1 failed), using deliveries as the denominator (2), returning 0 for an undated share (3), treating every dated delivery as on time (1).

Verified on a fresh database, not against the document: docs/DEVELOPMENT.md listed floor@printorian.example / shop-floor-pass-1 (#12). Reproduction: CREATE DATABASE printorian_fresh → alembic upgrade head (0001 → 0026) → provision_with(...) with the password owner-pass-12345 → POST /auth/sign-in through Starlette's TestClient: boss@ 200, floor@ 401 error.identity.invalid_credentials, and SELECT email, role FROM users on that database returns the one owner row. Nothing in the repository creates floor@, so the table now says what the tool does — the owner's password is whatever was typed at the prompt, the second account is made in «Сотрудники» with the role the gate being checked needs. The role decision the issue flagged as needs-person is not made here: the document no longer asserts one.

Issue #58 was built by #92 — the PR did not say Closes #58, so it stayed open with the Backend capability with no consumer milestone. The tests it names (tests/unit/test_intake_cache_hit.py, test_intake_pass_wiring.py) are re-run in this session and the output is on the issue. Two other issues describe less than the code has: #29 lists the delivery zones and postprocess operations tables as unbuilt and both exist (settings/declared.py, frontend/apps/console/src/settings/*Editor.tsx); #34 predates #96. Neither is closed — maintenance intervals, the event matrix, API keys and webhooks are still not built, and #34's scorecard is what this session adds.

The supplier scorecard (#34's last clause) is computed, and three of the kit's six columns are deliberately not there. procurement.reads.supplier_scores groups purchase_orders by supplier with three FILTER counts on one join: deliveries (reached STORED), dated (of those, the ones with an expected_at), on_time (stored_at <= expected_at). policies.on_time_share is on_time / dated, and null when nothing was dated — an undated delivery is in deliveries and in nothing else, because putting it under the line marks a supplier down for every date the buyer forgot to type and putting it over the line marks them up. «Брак» needs a rejected quantity no receipt records and would read 0% for everyone; «Оборот» is money the board never carries; «Оценка» is a composite nobody has defined. The board row carries the counts beside the share («1 из 2») so a 100% from one delivery reads as what it is. test_purchasing_api.py crossed the 400-line gate with the API test for this and was split at the responsibility seam: _purchasing_support.py (helpers, no fixtures — the _catalog_support.py rule), test_purchasing_scorecard_api.py.

#34's last row — price history per position — is a read over receipts, and that closes the issue. contexts/procurement/prices.py: one query joining purchase_receipts to their lines over a window (a year by default), and a pure fold that picks each position's earliest and latest priced receipt. A receipt with no unit_price_paid is counted (unpriced_receipts, and the panel footer says «приёмок без записанной цены: N») and moves no figure — averaging it in as 0 would drag every position towards free. A position with one priced receipt has earliest = change = null: a price, not a stable price, and not 0%. The kit's «Средневзвешенно −9% за год» slab is not served (weights nobody chose). Money, so GET /purchasing/prices sits behind VIEW_FINANCIALS like /costs, and PurchasingPage never requests it without the permission — the screen test pins that in the network log, not just in what renders. Three mutations to the fold each fail its tests (run and reverted): unpriced receipts priced at zero (3 fail), the fold trusting input order (1), a single point reported as a movement (1).

#35's second slice: «Оборачиваемость» and «Залежалое», folded from the movement ledger. contexts/inventory/store_measures.py: one query joins each lot to three instants from material_movements — its stock.received row, its first outbound row (mounted, issued or written off; a cell-to-cell move is not outbound) and its last row of any kind — and two pure folds do the rest. Turnover is the mean days between arrival and first outbound over lots that left, per family, with the ones still on the shelf counted beside the mean and never inside it. Dead stock is lots in STOCK with mass left and no movement for idle_days, costed as purchase_price × remaining / initial only where receiving recorded a price (procurement.receiving._lot_price is the only writer of that column); unpriced lots are counted and add nothing. Served as GET /store/turnover (the router's VIEW_PRODUCTION) and GET /store/dead-stock behind VIEW_FINANCIALS on top — the /jobs/variances shape §2.4 asked for — and StoreMeasures.tsx never requests the second without the permission; the screen test reads the network log to prove it. Two traps met on the way and worth knowing: record_movement does not flush and next_sequence reads the ledger, so two rows written before one flush claim the same rung (uq_material_movements_ lot_id_sequence); and lint-imports reported a broken contract twice this session while another process was writing files, and kept all six when re-run alone — run it by itself before believing it. Still owed on #35: drying state, stocktake, and the three non-filament classes.

#35's third slice: drying state, and the first reader the two drying settings have had. inventory.require_drying and inventory.drying_valid_hours sat in the catalogue since the settings screen was built with nothing reading either — the "settings row nothing reads" failure #29 names. Migration 0029_lot_dried_at adds one nullable column, material_lots.dried_at, and contexts/inventory/ drying.py computes the state from it at read time: not_required (PLA, or the rule off), drying (in the dryer), unknown (never marked — not measured, so not lapsed), dry with hours left, expired. Never stored, so a spool nobody looked at cannot go on reading as dry, and shortening the window on the settings screen shortens every mark at once — the API test proves that by editing the setting mid-test. Two writes, POST /store/lots/{id}/dry and /dried, both ledger rows (stock.to_dryer, stock.dried); the second is the only writer of dried_at and is refused for a spool that was never sent. The spool keeps its cell in the dryer so the map does not offer its slot. GET /store/cells/{a} now serves StoredLot (a LotView plus family, receipt and the state) and drying_valid_hours; CellDetail.tsx draws the kit's «Сушка» column and the two buttons, and «Высушена» is offered for anything physically in the dryer even after the rule is switched off, or the spool would be stuck there. Which families the rule is about is HYGROSCOPIC_FAMILIES in drying.py — the three the setting's own hint names plus the nylon/PVA spellings — because a per-spec flag nothing sets would leave the whole panel reading «не требуется». Trap met: FixedClock.advance past the session lifetime expires every token, so an API test that jumps the clock signs in again.

#35's fourth slice: the stocktake, and «Расхождения» with it. Migration 0030_stocktakes: stocktakes and stocktake_lines, plus st_number_seq. contexts/inventory/stocktake.py is the write half — open snapshots the book (expected_grams) for every spool in a cell (a spool in a machine or the dryer is not on a shelf to count; a lot in stock with no address is nowhere anybody could be sent), one open count at a time farm-wide; count writes what was found, refusing anything above the spool's initial_grams before the row is touched; close corrects remaining_grams to the count against the book as it is at close, not the snapshot — a write-off between opening and close is not a shortage and applying counted − expected would take it twice — with one stock.counted ledger row per spool that differed, carrying the stocktake's number in its note. This is the second and last path that changes remaining_grams; placement.write_off's docstring now says so. An uncounted line keeps a null counted_grams, stays at its book value and is reported as not checked — never zeroed. stocktake_reads.py folds the panel's figures over the lines that exist and costs «Недостача»/«Излишек» only where a price was recorded, behind VIEW_FINANCIALS on /store/stocktakes/{id}/value; the floor's routes are guarded by a money-word scan in the API test. «Следующая» is not drawn: no setting says how often the farm counts. Frontend: Stocktake.tsx (tile + panel), DeclareForms.tsx split out of StorePage.tsx at the seam to keep it under the console's four-hundred-line convention. Still owed on #35: the three non-filament classes — tara, consumables, spare parts — which need a purchasable class beside filament and are a design question before they are code.

#27, second pass of the security review — seven fixes with tests, twelve things recorded. docs/SECURITY-REVIEW.md §2b. Three surfaces were read as an attacker holding what an attacker holds — an anonymous connection, a customer account, a stolen session — and every finding was verified against the code before it was written. Fixed here, each with its test named in the document: the YooKassa webhook idempotency key was the event type, so the first payment.succeeded the farm ever received made every later one a "duplicate" for every other customer (critical, would have surfaced on day one of live payments); a manager could settle a pending card payment through the manual door and mark the order paid with no money moved; POST /account/password verified a password with no lockout and no ceiling; POST /account/close let an owner's stolen cookie deactivate the farm's only manage_users holder; a NaN in an anonymous upload was a bare 500; a ten-kilometre part was refused after its bytes were stored and never collected; the public catalogue popup re-parsed a stored model on every request, unthrottled. Not fixed and listed for filing in §5(d): the websocket Origin check, the Secure cookie flag behind the proxy, the payment lifecycle gaps (cancelled at the gateway, late settlement of a cancelled order, two concurrent starts, currency), and the hygiene items. Traps met: the test database keeps tables from whichever branch ran last, so a branch without those models cannot drop_all — DROP TABLE … CASCADE them by hand before the first run; and tests/api/test_account_api.py was two tests past the 400-line gate, so the abuse tests live in test_account_doors_api.py.

#36: a parcel now has a life after the post, and the logistics screen calls logistics built — twenty-one of twenty-one. New context contexts/logistics (migration 0028_shipments: shipments, shipment_events). A Shipment opens at the API edge when POST /packaging/parcels/{id}/ship succeeds, pinning zone_code and promised_days from the order's own rate snapshot (rates_from_dict(snapshot.payload).zones → zone_for(postcode)), so a zone edited afterwards moves the next promise and never this one (ADR-0020 for a promise); an order with no pinned rates, or a postcode no zone claims, gets a shipment with a transit time and no promise — null, never nought days. Every change of state is a shipment_events row and the status is what the last event says (policies.STATUS_AFTER); delivered_at is written by the delivered event alone, an arrival dated before the dispatch is refused, and a delivered or returned parcel takes no more events. on_time is transit_days <= promised_days in tenths of a day, and the denominator of «В срок» and «Точность» is the delivered parcels that carried a promise — «Точность» groups by the pinned promise, so a zone whose transit days changed mid-window is two rows, not one blurred average. «Повреждений» counts recorded damaged events, and the foot says so. Not served, each with its reason in the code: «Средняя цена» and «Что и почём» (money behind a production gate), «Оценка» (no chosen weights), «Отгрузка сегодня» (the packaging board's), «Куда» (the address is on the order), «Возвраты»/«География». The docs screen-inventory gate gained its zero case ("Every screen ships, public and control"); DATABASE-REVIEW.md §1 moved to 55 tables, fifteen contexts and thirty migrations. alembic upgrade, check, downgrade, re-upgrade were run against the dev database.

#33's second slice: tickets, and the service screen that calls service built. service_tickets and service_ticket_steps (migration 0027_service_tickets, sequence sv_number_seq): a ticket is the work — raised by a person or, for a driver-reported failure, by the sweep; assigned; walked through «Порядок работ»; closed — and it is a different row from the failure, which stays the measurement reliability.py reads. TicketDesk in contexts/service/tickets.py; the five lanes are lanes_of, a pure function where status wins over kind (a repair being worked is «В работе», not «Аварийные»). open_for_failure is idempotent per failure, so a sweep that has not seen its own commit cannot mint a second SV number — test_service_sweep.py drives two passes and test_service_pass_wiring.py pins that ServicePass supplies the desk. Closing refuses an unticked step (error.service.steps_pending with the positions) rather than ticking it for you. A ticket closed without ever being started keeps started_at null: nobody measured when the work began, and stamping the close there would make a job that waited twelve minutes read as one that took none — its elapsed is then the span it was open. Routes under /service/tickets take the failure record's two gates and carry minutes and counts only; ServicePage.tsx draws the board, the work order and «Надёжность» from GET /service/reliability, so DESIGN-KIT §1 now reads twenty of twenty-one. Deliberately not built, each with its reason in the code: «Последствия» (money), «Запчасти на посту» (no spare-parts stock), crew badges (no crew record), maintenance tickets raised from running hours (the service card's job, with an idempotence question of its own), and a staff picker for POST …/assign, which is the one ticket route no screen consumes and is listed in §4 as such. alembic upgrade, check, downgrade and re-upgrade were run against the dev database; DATABASE-REVIEW.md §1 moved to 53 tables and twenty-nine migrations because test_docs_table_inventory.py reads it. Two doc gates needed care: the screen-inventory test's "the N that do not are" template had no singular, and it now says "the one that does not is" when one screen remains.

#29's maintenance-intervals table is built, and it is the one of the six with a consumer. service.maintenance_defaults is the fifth Kind.TABLE field: rows of {code, interval_hours}, one per MaintenanceKind, default every kind at the 500 hours CreateServiceOperation always assumed — so an untouched table changes nothing. Its shape, validation and the seeding live in contexts/fleet/maintenance.py (the consumer owns what a valid row is, as pricing owns ZoneTariffs); settings stores, audits and resolves it (resolve_maintenance_defaults). Two readers, both at the API edge: POST /printers seeds a new machine's card from the table — a machine used to be registered with an empty card — and POST /printers/{id}/services gives an operation sent without a periodicity its kind's row, told apart from an explicit 500 by model_fields_set. Removing a kind from the table means a new machine does not get that operation; the editor draws it with a dash and «Вернуть в таблицу». The kit's «Простой» and «Расход» columns are not stored: ServiceOperation carries neither and nothing prices a service, so they would be rows nothing reads. Mutating either reader to ignore the table fails the API tests (3 and 1). The three remaining rows of #29 — event matrix, API keys, webhooks — each need a channel or a credential store that does not exist, and are left.

The three worker intervals now say on the screen that they wait for a restart (#32, the half the issue says should be done regardless). scheduler_tick_seconds, sla_sweep_seconds and telemetry_poll_seconds are passed to their loops once in workers/runner.py; their neighbours resolve at the read edge. The hint is the only place the difference is stated, and SettingsPage.test.tsx pins that each of the three carries it in its own section. Reverting the catalogue change fails that test (run). The hot reload itself stays deferred, as the issue says.

main was red twice over, and the second break was hidden behind the first. CI runs the frontend job only after the backend job passes, so once the pin above went in, the frontend job ran on main's tree for the first time since #105 (vitest 4.1.11 → 5.0.0, merged 2026-09-09 with its frontend check red) — and failed Types with 208 TS2339 errors, «Property 'toBeInTheDocument' does not exist», in every test file. Vitest 5 made Assertion<T> into Assertion<R, T>; jest-dom 7.0.1's one-parameter augmentation no longer merges with it, skipLibCheck hides the mismatch in jest-dom's own .d.ts, and the suite itself runs green because the runtime expect.extend half still works. jest-dom's fix is testing-library/jest-dom#742, open and unreleased. The bridge is frontend/types/jest-dom-vitest.d.ts, which augments vitest's documented Matchers<R, T> extension point with jest-dom's matchers in the order #742 uses; the four project tsconfig.json files include it. Delete the file and the four include entries when a jest-dom release carries #742.

A third one, from the pair vitest 5.0.1 + jsdom 30.1.0 that #110 brings in together. Rebased onto the fixed main, the frontend patch group still failed Tests: 24 configurator cases with TypeError: Cannot read properties of undefined (reading '_buffer') out of URL.createObjectURL. Vitest 5.0.1's jsdom compatibility layer builds a Node Blob by reading a private _buffer off jsdom's Blob; jsdom 30.1 renamed it (vitest-dev/vitest#11336, fixed by #11295, unreleased). frontend/vitest.setup.ts had a counter-based createObjectURL double guarded by "only if nothing provides one" — vitest 5.0.1 provides one, so the guard handed the tests the broken implementation. The guard is gone: the double is unconditional, because no test dereferences the URL (the 3D view's loader fails on blob:test/… and settles as failed, as it did under vitest 4 when the double was all there was). Reproduced from #110's lockfile: 24 failed before, 25 passed after, and the four frontend gates on that dependency set each exit=0. This is the same shape as the anyio / starlette pair above — Dependabot groups by semver, not by which packages share a private field — and the answer was again to stop depending on the pair rather than to hold either half back.

npm run typecheck said this tree was fine, and it was wrong. tsc --build trusts *.tsbuildinfo, and the build info in this worktree predated npm ci with the vitest 5 lockfile, so the incremental build re-checked nothing and reported success — the same tree fails 208 times under tsc --build --force, which is what a fresh CI runner does. After any dependency change, run the forced build once, or delete the build info. This is the frontend's version of §4's piping trap: a green result from a check that did not run.

What the suite run cost, so the next person budgets for it: the full suite here took 1 688 s (0:28:07) rather than the ~950 s recorded below. It was started while npm run typecheck, npm run lint, two vitest runs and an alembic upgrade head against a scratch database were also running on the same machine, and Postgres is a Docker Desktop container; the pace roughly quadrupled once those finished. Run it alone.

Not done, and why. #67 (branch protection) is a repository setting and an owner's action. #17's remaining half is the reboot timer, which deploy/systemd/README.md says needs a Debian host and a real print to prove. #50 was re-checked: openapi-typescript 7.13.0 still peers on typescript ^5.x, so the hold stands. #48 and #49 are on the backend CLAUDE.md's do-not-fix list. #29's four remaining tables, #33's tickets, #35 and #36 are screen-sized pieces of work that did not fit beside the above.


As of: 2026-09-01 · 1 383 passed, 8 skipped, exit=0 in 951.82s (0:15:51) on feat/58-reprice-cache-hit with main merged in through #91, alongside the six backend gates each run separately and each exit=0. That is pytest's own trailing summary line, read out of the redirect rather than counted off the progress characters. Eighteen of those tests are the fourth review's, and ten mutations were applied, run and reverted against them.

A run loses that summary line when the command adds its own -q, and it is worth knowing before it costs another twenty minutes. addopts in backend/pyproject.toml already carries -q; a second one on the command line makes it -qq, and at that level pytest prints the progress marks and then nothing — [100%], exit=0, and no counts anywhere. The line above previously credited -p no:cacheprovider --tb=short with bringing the line back. Neither flag has anything to do with it: what brought it back was dropping -q from the invocation, because the config supplies it. Run the suite as python -m pytest -p no:cacheprovider, with no -q of your own.

The figure was re-measured across the merge rather than carried over it, and the two extra tests are what makes that checkable. 1 381 was this branch over main at #89. #90 then landed and added exactly two tests to tests/unit/test_queue_position.py, and the count moved by exactly two. Had the old number been carried forward instead, that arithmetic would have proved nothing — a number copied over a merge agrees with every tree, including the ones it never saw. This is the paragraph three below in its answered form: the referent changed, so the measurement was taken again rather than re-pointed.

The frontend figures here are main's, not this branch's. #91 measured 283 tests across 29 files with all four frontend gates exit=0, and that is what main now is. This worktree has no node_modules, and nothing under frontend/ changed on this branch, so the number is repeated with its owner named rather than re-claimed. The sentence #91 left on this line — "no backend suite or gate run on this branch at all" — was true of #91 and is false of this one. It is the same referent moving under a pronoun as everything else on this page, arriving by a merge this time instead of by a copy, which is why the merge that brought it here had to be read rather than accepted.

What ran locally on the merged tree: the six backend gates, each separately and each exit=0 — ruff check, ruff format --check (386 files), mypy --strict (223 source files), lint-imports (6 contracts kept, 0 broken), check_context_isolation.py and check_file_length.py, run from this worktree's own .venv. The figures moved this session — 369 and 217 before — because the fourth review of #92 added core/geometry.py, workers/plate_admission.py and three test files; neither #90 nor #91 added a backend source file, so neither moved either count. They are quoted because a gate whose file count nobody reads is a gate that can quietly stop covering a tree.

feat/20-metrics-exposition claims no suite figure at all, and that is the honest state of it. No pytest run happened on that branch: it is one of several worktrees live on this machine, they share printorian_test, and the printorian editable install in the shared .venv points at the main tree — so a run started from a worktree reports on source the branch does not contain. What did run there, each separately and each read for its own exit code, is the five path-based gates (ruff check, ruff format --check, mypy --strict over 226 source files, check_context_isolation.py, check_file_length.py), all exit=0. lint-imports was not run, for the editable-install reason above; nor was alembic check, which touches the shared dev database — and neither is owed a result by that branch, which adds no migration and no ORM change. Everything else it states about behaviour was reproduced outside pytest against the real modules and the real documents, and the branch says so at each commit rather than borrowing this block's numbers.

alembic heads reports a single head, 0023_prepared_plate_copies. Two branches merging is the way ADR-0008's one-head rule usually breaks, so it is checked here rather than left to CI to discover.

The full-suite figure this line used to carry was never about this branch, and that is why this one names its tree. 1 333 passed / 7 skipped, exit=0, 24m43s was measured on #87's branch, said "on this branch", and travelled onto main and then onto this one unchanged — the pronoun quietly changing referent under a number, and the reason "the suite passed" and "the suite passed on this tree" are the two claims this file has already been corrected for confusing once. The 1 383 above is the second claim: this worktree, this commit, main merged in, .venv here, log kept. It replaces the "no full-suite pass is claimed here" that stood in this slot while the run was still owed.

Four local attempts, no pass, and the diagnosis was wrong once. Recorded in full because the wrong diagnosis is the useful part.

The first run failed ~200 tests across tests/api files this branch does not touch, and each of those files passed on its own seconds later. That was written down here as the concurrent-session trap backend/CLAUDE.md names — plausible, three other worktrees are live on this machine, and not measured. The second reached 19% clean and was killed by a session restart. The third was killed by a merge committed into the working tree while it ran, which left planning.py holding conflict markers; that one is nobody's fault but the author's.

The fourth errored from 5% onward, and the cause turned out to be that PostgreSQL was gone: nothing listening on 5433, docker unable to reach its daemon, a direct asyncpg.connect refused. Docker Desktop had stopped. Which makes a restarting container the better-supported explanation for run one as well — the DB dying mid-run and coming back fits both the mass failures and the single file passing immediately after, and no evidence was ever gathered for the concurrency story that was written here first.

The lesson worth keeping is not about Docker. A run whose failures land everywhere except the change has an environmental cause, and there is more than one candidate; pg_stat_activity or a bare connect settles it in one command, and guessing costs a paragraph of confident prose that has to be retracted. Check that the database is up before reading a failure list.

The farm now keeps a record of what broke (#33, first slice, branch issue-33-failure-record). contexts/service is a new context holding one table, printer_failures: a machine the driver reported in ERROR gets a failure opened by an eighth worker loop, and the observation that sees it working again closes it. GET /service/reliability divides those counts by metric_rollups.observed_seconds per machine and serves отказов/1000 ч, MTTR over repaired failures only, and the «Причины отказов» funnel with an uncategorised count beside it. Three routes behind OPERATE_PRINTER let a person open a failure, close one, and name a cause. Backend only, and deliberately no screen — §1 of docs/DESIGN-KIT.md still says service is not built, and §4 now lists all four routes as capability nothing consumes.

Two judgements a reader will otherwise re-litigate, both written into the code beside the line they govern.

OFFLINE is not a failure. FleetService.mark_unreachable writes OFFLINE for a poll that did not answer — a dropped MQTT session, a switch rebooting, this very worker restarting — so counting it would mint one failure per machine on every blip and drive MTTR from repairs nobody made. The cost is real and is not hidden: a machine unreachable half the month still contributes its offline_seconds to its own denominator and therefore reads as a reliable machine that simply never broke. Unreachability is a coverage problem and the honest answer to it is a coverage figure, not a row in this table. test_an_unreachable_printer_does_not_become_a_failure and its closing-side twin are the only two tests that notice if that changes.

A driver code is not a cause. drivers/bambu/report.py yields bambu.print_error.{code} and the farm holds no table turning one into «слом филамента», so a sweep-opened failure carries the code verbatim and a NULL cause until a person names one. The funnel counts named causes; uncategorised sits beside it rather than inside OTHER, because "nobody looked" and "we looked, and it was something else" are two facts.

What this slice deliberately did not touch. Printer.printed_hours is untouched and «Наработка» is not on the reliability response. The issue body claims наработка is already computed from metric_rollups; it is not — contexts/fleet/service.py accumulates printed_hours from the live row instead, so putting the two on one table row would be two rulers under one heading. That is written down rather than papered over, and it is the first thing to settle if the screen is built. pause_on_hms_error still has no consumer (two catalogue hits, no reader); acting on it is a machine-side action and is out of this slice.

Still owed on #33: the ticket entity with steps, assignee, priority and elapsed; spare-parts stock; the console screen. «Последствия» is not merely unbuilt but partly unmeasurable — production/models.py's grams_required, estimated_grams and prepared_grams are estimates and nothing decrements a spool, so the kit's «потеряно материала 148 г» has no source, while «Итого потеря 2 140 ₽» is money and belongs behind VIEW_FINANCIALS rather than on a response a production role reads.

What was measured on this branch, and what was not. Five path-based gates, each run separately from the main tree's interpreter against this worktree, each exit=0: ruff check (all checks passed), ruff format --check (402 files), mypy --strict (232 source files), check_context_isolation.py, check_file_length.py. lint-imports was not run and no test was run at all. printorian is an editable install pointing at the main tree, so both would have reported on source this branch does not contain; alembic upgrade/check were not run either, because they reach the shared dev database. The head is a single 0024_printer_failures read off the files — one migration declares down_revision = "0023_prepared_plate_copies" and nothing revises 0024 — rather than from alembic heads. So nothing here claims a passing test: the thirty-five new tests across five files — nine reliability, seven constraint-and-refusal, eight sweep, one wiring, ten API — are written and unproven, and a serial verification pass in the main tree is what will say whether they hold. The figures in the «As of» block at the top of this file belong to another branch and were not re-measured here.

A wait-list row now ends when the wait does, and not one pass later. planning._refresh_wait_list discarded rows only for the jobs in result.wait_list — the ones still waiting. A job wait-listed on one pass and assigned on the next fell out of that set and kept its wait_list_entries row for ever: nothing else deletes one except the owner's farm-wide clear and the cascade from the job or its order. The discard now covers the whole claimed batch (by_id.values()), which is the honest set, because the planner decides every job it looks at — assigned or wait-listed, never neither.

It was three wrong answers, not one. queue.queue_position read the stale row and told a customer whose job was assigned why it had been stuck three passes earlier. Worse, a position is counted by comparing predicted_start across the whole table, so the phantom sat one place in front of every other customer and inflated their numbers too. And reads.wait_list and schedule.wait_list_size count rows straight out of the same table, so the floor's list and the dashboard chip carried it as well. Neither of those two needed a change of their own — they were reading a table that was lying.

Both are held to tests that fail without the fix, in tests/unit/test_queue_position.py. test_a_job_that_gets_assigned_leaves_the_wait_list runs two passes — busy machine, then free — and asserts no row, no reason, and zero from wait_list_size; it failed on the row assertion before the change. test_a_job_that_stopped_waiting_stops_counting_against_others puts a second customer behind the first and asserts their position falls from 2 to 1; it failed with assert 2 == 1. The second test is the one worth keeping: a per-job assertion cannot see a defect whose damage lands on somebody else's row.

It was written against #31's branch rather than main, because the fix goes through wait_list.discard and that branch introduced it; writing a second delete here to dodge the dependency would have re-created exactly the divergence #31 exists to prevent. #31 has since merged as #89 and main is merged in here, so the dependency is now history rather than a merge order to remember.

WaitListEntry's own docstring stated the invariant that was false — "re- planning replaces the row rather than appending" describes half a rule. It now says the other half, next to the column definitions, because that is where the next person adding a reader of this table will be standing.

A paid order whose configuration is already sliced now reaches QUEUED by itself (#58). The intake sweep attaches the cached PreparedPlate and applies ADR-0013's band with nobody in the loop, so ROADMAP Phase 4's exit criterion — payment to a machine starting the job with no human action — holds for the cached half instead of ending in an engineer clicking «attach» on work the farm already has. Read the reachability paragraph below before repeating that sentence anywhere else: the mechanism is built, tested and correct, and nothing the storefront can place reaches it yet, because OrderingService.place never writes OrderLine.model_asset_id.

The whole issue was one NOT NULL column. EstimateVariance.prepared_cost had no source: pricing happens once, at quote time, and nothing in the system prices a plate. #41 stopped here rather than pass a zero. pricing/reprice.py is that source, and it is deliberately a difference rather than a fresh total — line_total + (price with the plate's minutes and grams − price with the numbers that were quoted), both under the order's own pinned RateSnapshot. Two inputs of the original quote cannot be recovered from the order and each would land on the money column: the customer tier, resolved from spend at checkout and held by no column, and the per-line quote, which does not exist at all, because place prices the order and apportions the total by quantity. A difference cancels both. Do not "simplify" it into price(spec).total.

The tier half of that argument was overstated and has been corrected. This file, reprice.py and ADR-0013 all used to say that rebuilding the tier from price_breakdown "is a second loyalty ladder". It is not: the applied percents land on Basis.percent — tier.discount_percent on the discount line, the effective margin on the margin line — and breakdown_from_dict reads them back. The per-line quote is the input that really is unrecoverable, and it is the whole argument on its own. The difference stays; the sentence defending it is now the true one. Its cost is recorded too: a tier whose margin_percent_override is above the snapshot margin makes the difference understate an overrun, so one that should have gone to PRICE_REVIEW can land inside the band — 15.48% true against 13.88% recorded on the farm's own defaults. tests/unit/test_reprice_tier.py pins the sign and that straddle.

How many copies are on the plate is now a column, and the guard that stood in for it was one-sided. Nothing on a PreparedPlate recorded it — layout_hash is opaque — and two things depend on it: attach_plate takes the plate's minutes and grams as the job's whole work, and the reprice divides those same totals by the line's quantity. A one-up plate on a line of three therefore under-prints and underprices at once, comfortably inside the band.

The first answer was to refuse any line whose quantity was not one. That covered one direction and left the other wide open, and the other is the normal one: a PrintJob is one plate holding a whole line's work, so the first order for two keychains leaves a two-up plate in the library, and the repeat order for one attached it, repriced against the whole bed, came out 4.26% over — inside the band — printed two, shipped one, and recorded an accurate estimate. Reviewed and reproduced end to end against real PostgreSQL before it was fixed.

PreparedPlate.copies (migration 0023) is the answer instead: nullable, never defaulted, never backfilled, because a 1 written in for the plates already in the table is an invented number that happens to be the one that makes the common case attach. The unattended path attaches only when the plate's recorded copies equal the line's quantity, and the quantity != 1 refusal is gone. The tripwires are test_a_two_up_plate_is_not_attached_to_a_line_of_one, test_a_one_up_plate_is_not_attached_to_a_line_of_three and test_a_plate_that_does_not_say_how_many_copies_it_holds_is_refused, all in tests/unit/test_intake_plate_selection.py.

A line of three still does not queue itself, and the reason is the fourth review's. The count now agrees; the bed's footprint is recorded nowhere, and the only geometry the planner ever sees is the job's — one part's box. So a three-up bed was being judged against the size of one part, and a machine too small for the plate was eligible for it. plate_admission refuses any plate holding more than one copy; what lifts it is recording the plate's own bed extent, two columns and a console field, exactly the shape copies took. The per-quantity arithmetic copies earned is still pinned, by tests/unit/test_reprice_quantity.py, which is pure pricing and needed no sweep.

What that costs today, and it needs a person. The console's plate upload does not send copies — the field is a query parameter on POST /jobs/{id}/plate/file and a body field on POST /jobs/{id}/plate, and nothing in frontend/ fills either. Until it does, plates recorded through the console carry NULL and the unattended path declines them, which is last week's behaviour rather than a regression. It was not parsed out of the 3MF: plate_file.py says in its own docstring that the sliced <plate> element is implemented from documentation and has never been seen from this farm's slicer, and a miscount there would not fail loudly — it would attach the wrong plate quietly. Asking is the conservative half of that trade, and the frontend field is the follow-up.

Three reviews found three unguarded dimensions one at a time, so the set is now written down in one place. backend/printorian/workers/plate_admission.py is that place: one pure predicate, one refusal code per dimension, and a docstring that says what must match, what is checked elsewhere, what is deliberately absent (finishes cancel on both sides of the difference), and what is still open with the cost of closing each. The cause it names is worth repeating here: plate_key answers "have we sliced this before" and every term in it — geometry, scale, priced material, a profile string, an opaque layout — describes the order. Nothing in the schema describes the bed, and every hole the reviews found was a bed-side property. copies was the first bed-side column ever added.

Four refusals were added there and each was mutation-proved: a plate whose filament count is not the line's distinct colour count (round three's blocking finding — colour is in no key term, and line.material_code is the dearest chosen spec rather than the filament set); a plate holding more than one copy, because the bed's footprint is unrecorded; a line whose part was never measured, because a zero box reads as "fits every machine"; and a plate that is numbers with no file behind it, which would otherwise reach QUEUED and then be re-queued by dispatch for ever without ever returning to PREP. tests/unit/test_intake_bed_admission.py is the file, and deleting any one clause makes exactly its own test queue an order it should not.

A moved engine version now refuses too (_rates_for, ADR-0020's amendment). prepared_cost is line_total — priced by the engine of the day — plus a difference priced by today's, so a changed formula makes that sum a hybrid nobody quoted, recorded as measured. The third review offered "refuse or document"; refusing costs a click.

The part's bounding box was being read at 1× everywhere. OrderLine.mesh holds the unscaled box — _pricing_spec writes analysis.bounding_box verbatim while estimate() scales only volume, mass and time — and both readers of it had forgotten the multiplication. A 40 mm mesh at scale 3 was handed to the planner as 40 mm, whose only geometric test is job.width_mm > printer.width_mm, and to workers/packaging as the carton size. core.geometry.scaled_box is the one multiplication now, and tests/unit/test_scaled_box.py holds both readers to it.

Two cheap ones from the third review, both now held by a test. PlateLibrary.record overwrites copies rather than merging, and the comment saying that is load-bearing was true and untested — the merge passed thirty-nine tests. And POST /jobs/{id}/plate/file?copies=0 raised a bare pydantic error after storage.put: a 500 with no code (ADR-0012) and an orphaned blob. The query parameter carries Query(ge=1) now, which is the bound the model always had.

The path is not reachable from the product at all, and that is the finding to carry forward. OrderingService.place is the only constructor of an OrderLine and it never writes model_asset_id — the field is accepted by POST /orders and dropped — so model_hash is "" and the unattended path declines at its first line on every order the storefront can place. The web checkout sends no mesh either. So the guards on this branch have never been exercised by a real order, the whole feature lives in the test suite, and the two small changes that would switch it on are exactly the changes that would make every open dimension in plate_admission's docstring live at once. That is a decision for a person, and it is why the pull request now says Refs #58 rather than Closes #58.

A payload that will not rebuild must cost one order, not the pass. IntakeSweep.sweep rescues PrintorianError per order and nothing else, and Decimal("no longer a number") raises InvalidOperation, which is not one — so a single unreadable RateSnapshotRecord escaped the whole pass and left every other paid order in the batch jobless. It is caught where it happens now, and the test asserts on the healthy order standing beside the broken one.

The snapshot-id check is what keeps ADR-0020 true. rates_from_dict fills a field a stored row lacks with today's default, so a rebuilt snapshot whose hash no longer matches its row was completed from numbers that were never in force, and is refused. Without it, adding one rate to RateSnapshot would silently re-rate every older order this path touches, and nothing would say so.

PAID → PRICE_REVIEW is a legal transition now, because a cache hit can exceed the band before any engineer has touched the order. The alternative was recording a PREP the order never entered.

intake.py hit the 400-line gate and split into two files. intake.py still answers "which paid orders have no jobs, and what jobs do they need" — #41's question, and the one that runs whether or not the farm has a plate library. intake_routing.py answers the one #58 added: the jobs exist, may the farm start them itself? That is the seam, not the line the counter tripped on, and it is the same cut runner.py took. The second review's tests pushed test_intake_cache_refusals.py over the same gate, and it took the same kind of cut: test_intake_plate_selection.py is "which plate, if any", and what stayed is "the plate is right and the money cannot be worked out honestly".

CachedPlates is an optional collaborator of IntakeSweep, wired in workers/passes.py. Withheld, every order goes to prep exactly as before — so deleting that one line returns the farm to clicking, silently, which is why one test pins that the fallback is the safe one and another pins that the collaborator is actually supplied.

DATABASE-REVIEW.md §1 now says twenty-five migrations, because 0022_plate_model_hash_index and then 0023_prepared_plate_copies moved it and test_the_migration_count_matches_the_versions_directory failed the whole suite until it did. That test is the reason a doc figure moved on the same commit as the schema instead of six weeks later.

Measured, not asserted, and every round was measured. All six backend gates run separately on the final tree, each exit=0; the whole suite 1 363 passed / 8 skipped, exit=0, in 1052.37s (0:17:32) — pytest's own summary line, which reached the redirect this time. Every claim above was mutation-proved, each mutation applied, run and reverted.

Re-measured on this tree: prepared_cost=Decimal(0) fails five of the seven cache-hit tests and prepared_cost=line.line_total fails those five and the journal one; a fresh RateSnapshot() in place of the pinned one fails the ADR-0020 test alone. Measured earlier and not re-run: dropping the snapshot-id check, the PRICE_REVIEW branch, the "never picks between two plates" rule and the rebuild guard each failed exactly the test named for it, and forcing the routing back to PREP failed six.

This round's own six: dropping the copies guard fails three selection tests; defaulting copies to one fails the plate-that-does-not-say test; dropping status == VALID fails the retired-plate test; replacing the plate_key comparison with list(rows) fails the wrong-material test; removing cached from passes.py fails the wiring test; and setting the tier's margin override equal to the snapshot margin fails two of the three tier tests. Both migrations were upgraded, alembic checked, downgraded and re-upgraded against the dev database; alembic current said 0022_plate_model_hash_index beforehand this round.

The reprice also had to be told where it may not write the number. attach_plate put quoted_cost and prepared_cost into the job's journal as well as onto the EstimateVariance row, and a JobEvent's details rides out on JobView.events — which GET /jobs/{job_id} serves under VIEW_PRODUCTION alone, the permission an operator holds. GET /jobs/variances gates the identical pair on VIEW_FINANCIALS, so the journal was a second, ungated copy: CLAUDE.md §1's money split, defeated by the other door. It read "0" for as long as the console's plate upload was the only caller, because those two costs are query parameters the console does not send — so the leak existed and was empty, and this branch is what fills it. The pair is out of details now; overrun_ratio stays, because a ratio is not money and it is what the floor reads an ON_HOLD against. test_the_job_journal_does_not_carry_money_to_the_floor reads the job as an operator and test_the_sweeps_journal_entry_carries_no_money guards the write; putting the two costs back fails both, which was run.

The wiring is covered now, and it was the one hole between "the code exists" and "the farm uses it". workers/passes.py supplies CachedPlates to the sweep, and deleting that argument returned the farm to clicking with every test still green — the two cache-hit files build the sweep themselves, and the one test that goes near it asserts the fallback is safe, which is the opposite claim. tests/unit/test_intake_pass_wiring.py drives IntakePass itself against a stand-in runtime (the real one opens three Redis connections), and removing cached from passes.py now fails it. It is still the only worker pass in this tree with a wiring test.

The masthead no longer tells a signed-in customer they are signed out, and the journal's «—» is now proved at the screen rather than at the component (follow-up to #88, whose second review round landed after it had merged). AppShell destructured only actor from useSession, so for the whole /auth/me round trip the storefront masthead drew «Войти» at someone who was already signed in — and a visitor who believed it and started typing lost their input, because the answer arriving turns actor non-null and AuthDialog stands itself down the moment there is a session. The right-hand group is empty again until there is an answer, which is what it was before #88 gave it an opener. apps/console/src/App.tsx and the Session type's own docstring had each written the rule down already; the shell was the one place that had not read it.

The headline ADR-0007 fix had no screen-level test, and that gap was measured, not argued. #88 stopped JournalPage printing 0 for a section the server had not counted — and its counted memo reverted to the pre-#88 index?.counts form left the entire suite green. FilterChips.test.tsx proves the component honours count: null; nothing proved the page hands it one. apps/web/src/JournalPage.test.tsx now pins both halves — «—» while /journal is still in flight, 0 once the server has answered with none — because the defect is the two facts collapsing into each other, not either one alone.

The catch one branch above it invents the same number, and is deliberately left alone. JournalPage.tsx's .catch(() => setIndex({ rows: [], counts: [], total: 0, … })) renders a backend outage as «Все 0» and «0 ВЫПУСКОВ». It predates #88 and is a decision about what a failed load should say, not what a pending one should; pinning it from a branch about the pending state would pin the wrong behaviour. Written down here rather than fixed quietly or filed — whether it becomes an issue is a person's call.

Three mutations applied, run and reverted. Dropping the ready guard put «Войти» back into the not-yet-asked masthead and the new shell test failed on the button it found. Restoring index?.counts at the journal's memo rendered «Себестоимость0» — the defect verbatim — and the pending-index test failed. Making that same memo answer null for a section the server counted at zero failed the other two tests, which is the evidence the page keeps the two facts apart rather than merely preferring one of them.

Tabs has one tabbed detail view behind it in the kit, not three, and the #37 entry below is corrected to say so. It claimed, in the present tense, that the strip is what the purchase order and the shipment "are drawn with in the kit"; grep -c data-tabs design/*.html gives purchasing.html:0 and logistics.html:0. That was a claim about a file written without reading the file, inside the entry for the pull request whose whole thesis was that a claim about a file had been carried forward without reading it.

The third irreversible operation exists, and it shares its delete with the planner (#31). POST /settings/clear-wait-list empties the wait list, audited per row into each job's own journal. Every removal of a wait_list_entries row now goes through contexts/production/wait_list.py: the planner's per-job replace calls discard, the owner's «Очистить» calls clear_wait_list, and the arrangement is the one drop-telemetry already has with the maintenance worker — one function, so «сделать сейчас» and the scheduled path cannot come to mean different things.

The kit's hint describes a transition the state machine refuses, and it was not implemented. design/settings.html says clearing returns waiting orders to «Подготовка». production.policies.TRANSITIONS gives READY only ASSIGNED and CANCELLED, and the note beside ON_HOLD says why nothing goes back to PENDING — the plate exists, and re-slicing it would not be the fix. So the operation removes the record of the wait and leaves the job where it was, the hint on the button says that instead, and test_clearing_the_wait_list_does_not_move_the_job is what fails if somebody later implements the kit literally. Which of the two is wrong is a question for a person; the code does not guess.

What is irreversible here is the reasons, not the queue. A still-blocked job is written back onto the list by the next planning pass seconds later. Why it was stuck, what was blocking it and when it was predicted to start are held nowhere else, so clear_wait_list copies each row into the job journal before dropping it — an audit reading only "the list was cleared" would answer none of the questions the list was answering. by travels in JobEvent.details because that table has no actor column, unlike OrderEvent; a migration on the busiest history table for one caller was the alternative and was not taken.

Three mutations were applied, run and reverted. Deleting the journal write left «cleared: 1» and a green endpoint — the audit test failed. Reporting the rows without deleting them left the body reading {"cleared": 1} with the row still in the table, which is precisely the 200-proves-nothing shape CLAUDE.md §2 warns about, and only the read-back assertion noticed. Reopening the blank-farm- name hole in ConfirmAction failed the wait-list confirm test as well as the reset-rates one, which is the evidence that the third operation went through the shared gate rather than growing its own.

The three design-kit conventions that were never ported now exist once each, and the row that said so had been wrong about one of them (#37). FilterChips is the counter-chip row, and there had been three of them — the console's table tags, the account's four order groups, the journal's sections — each with its own copy of the markup and its own answer to whether pressing the chip already in force clears it. Two said yes and one said no, which is the same control behaving differently depending on where you met it. The rule is settled in the component now, and the count is number | null: the journal's row had been printing «—» for the total it had not received and 0 for every section beside it, in the same line of pixels.

Tabs is built with no caller, deliberately. The kit draws the strip on exactly one real screen — design/fleet.html's printer popup, «Сейчас · Параметры · Обслуживание · Слоты AMS» — plus design/index.html's own component gallery. design/purchasing.html and design/logistics.html carry no hv-tabs and no data-tabs at all: the purchase order and the shipment are screens the strip is for when those are built, which is how docs/DESIGN-KIT.md words it and how this line should have. The argument for porting it before they exist is that otherwise each of them invents its own — the failure ROADMAP names under "Management tables are not a phase". It shares shell/tablist.ts with the existing TabRail so a rail and a strip cannot drift into two controls: one stop in the page's tab order for the whole list, arrow keys on the axis it is drawn on, and selection following focus. Fourteen settings sections used to be fourteen Tab presses.

AuthDialog got its opener from the masthead, which had none. AppShell's right-hand group rendered only for a signed-in actor, so a signed-out visitor's only way in was to leave for a screen that happened to render an AuthPanel — and reaching one from the catalogue costs the catalogue, which is the exact cost design/js/auth.js was written to avoid. It is the same AuthPanel in the kit's popup chrome, not a second sign-in form, and it stands itself down once there is a session: the control it was opened from is gone by then.

That opener put two copies of one form in one document, and a review caught it. The three screens «Войти» is most likely to be pressed on — the checkout, the cabinet, the account — each already render an inline AuthPanel for exactly the signed-out state the masthead offers it in, so the popup mounted a second panel over the first. AuthPanel wrote its field ids as literals, from when only one of it could exist, and <label for> resolves to the first match in tree order: the popup's «Электронная почта» drove the input on the page underneath, which the overlay covers and aria-modal declares inert. Focus landed outside the dialog, where Modal's Tab trap cannot reach it — that trap only intervenes on the first and last focusable inside the dialog — so Tab then walked the page behind the popup, and autofill and screen readers read the same wrong pairing. The ids come from useId() now. The other hardcoded htmlFor ids in the tree (co-city, cfg-material, j-title) are left alone deliberately: each belongs to a form only one of which can be on screen, and this one stopped being that the day the shell grew a way in.

DESIGN-KIT §3 said "CSS section 22 not ported" and section 22 had been ported. packages/ui/src/harvester/tabs.css is it, near enough verbatim, and TabRail and TabView had been built, exported and in use on two screens. The row had been carried forward from a plan rather than read off the file — the mistake that document's own opening warns about, made in that document. What was genuinely missing was the horizontal strip and the keyboard behaviour. data-bind is now written down as deliberately not ported with the reason, so the next reader does not build it out of completeness.

The kit's attributes are not all worth keeping. data-tab-panel survives because the ported CSS selects on it; data-tabs and data-tab-target were how the static kit's JavaScript found a button's panel, and React state is that wiring. Emitting them anyway would have been a hook with no handler.

Measured on this branch, not asserted. All four frontend gates run separately: typecheck exit=0, lint exit=0, test exit=0 with 276 passed across 28 files (249 before this branch), build exit=0. Each new behaviour was mutation-proved — the em dash, the clearing rule, the arrow keys, the dialog standing down, the masthead's way in and the two panels not colliding were each broken deliberately, the test watched to fail, and the change restored. The bundles were then read rather than grepped: hv-tabs__btn appears zero times in either apps/*/dist/assets/*.js, which is what "no caller yet" means, and hv-tags appears exactly once in each, which is what "one chip row" means.

The delete rules are held to a test, and one way this suite can lie is now written down (#47). backend/tests/test_referential_integrity.py is the inventory — all forty-eight foreign keys grouped by rule, read back out of pg_constraint rather than off the models — and backend/tests/unit/test_delete_rules.py exercises one representative of each rule against real rows.

SET session_replication_role = replica is the finding worth carrying forward. A session that runs it leaves every constraint sitting in pg_constraint and enforces none of them. Applied to the db_session fixture as a mutation, the catalogue file passed every assertion and all six behaviour tests failed. That is why there are two files rather than one, and it is the shape to expect from any test that reads a catalogue and concludes something is being enforced: present and enforced are different facts. Measured, not reasoned about — the mutation was applied, run and reverted, along with three others.

Every delete in the behaviour file is issued as SQL rather than through session.delete. Order.lines and Order.events carry cascade="all, delete-orphan", so the ORM would do the deleting itself, in Python, and every assertion would pass against a database holding no constraints at all — precisely the state these tests exist to detect. Do not "simplify" them onto the ORM.

The issue's premise had already expired, and its last clause had not. #47 was filed as "66 tests build against a fabricated parent id, so foreign keys are off in the fast suite". ADR-0021 moved the suite onto real PostgreSQL, conftest.clean_database emits every key through create_all, and tests/factories.py already gives those tests real parents — 29 calls across 18 files. Measured before anything was written: 48 foreign keys in printorian_test, and a PrintJob inserted against an invented order_id refused with IntegrityError. What was not true is that a wrong cascade would fail anything.

docs/DATABASE-REVIEW.md §3 said "twenty-eight foreign keys" and named "the two references to model_assets". There are forty-eight — 26 CASCADE, 15 SET NULL, 7 RESTRICT — and three RESTRICT references to model_assets, plus a fourth that is SET NULL on purpose (prepared_plates: a plate can be re-sliced, a job cannot). §3 is corrected and now points at the test as the enumeration instead of restating a list, and §10 no longer carries #47 as outstanding work. The count had been describing the schema of the initial commit through four further contexts.

The full backend suite was run locally for this branch — not only in CI, and unlike the session the As-of line above describes: 1333 passed, 7 skipped in 1483.44s, exit=0, against the compose PostgreSQL on 5433. The document-only follow-up that corrected §3 re-ran the six backend gates and the two new test files rather than the whole suite again. The farm can now be asked what it thinks of itself (#30). The settings screen grew the kit's fourteenth section, «Диагностика», and it is the one section where nothing is a setting: /health/ready, /health/workers and the driver roster, drawn as .hv-health rows with the backend's own ok / degraded / failed distinction kept intact. The signals have been real for a while — a beat is recorded at the end of a pass, so a wedged loop is distinguishable from a running one — and until now their only consumer was a person with curl. It is not a substitute for Stage 5 monitoring and should not be argued as one: a dashboard somebody has to open is not an alert.

api.get could not be used, and that is the whole shape of the file. Both endpoints answer 503 with a full body when something is wrong — readiness when a check has failed, workers whenever a loop is not beating — and ApiClient throws on any non-2xx, funnelling the body through readErrorBody, which keeps only {code}-shaped payloads and discards the rest. Going through it would have blanked the panel in precisely the state it exists to explain. DiagnosticsPanel therefore probes with a bare fetch and reads the body whatever the status code was. There is a test whose only job is to notice.

A fourth state exists, and it is the point. unknown is not a backend verdict: it is what the panel says when it could not measure — the probe did not answer, the roster names a printer whose reading has lapsed, or the value is one this build has never heard of. The mapping is a whitelist, so a verdict added on the server tomorrow renders grey and unnamed rather than green and wrong. A !== 'failed' would have been the flattering error CLAUDE.md §1 is about, and there is a mutation test for exactly that.

degraded says a different word, not only a different colour. paused (amber) against error (red) is the visual half; the pill's text is the half that survives a reader who cannot separate the two. The distinction is load-bearing — wal_archiving degraded means every request is being served and the backup guarantee behind it has stopped holding.

Every denominator is what answered. «1 из 2 проверок» is counted from the checks the probe returned, because event_relay is reported only where a relay is configured and a fixed total would have left a deployment without one permanently reading one check short. The same rule is why an empty driver roster gets its own sentence rather than a blank list: core.driver_health is explicit that empty means nothing was published, and a blank panel there would have said "this farm has no printers". And the numerator over it is withheld when nothing answered. A row whose verdict is unknown was not a reading, so it counts on neither side of the fraction: Heartbeat.report() returns all seven loops with state="unknown" when the store cannot be read, and a tile keyed on the length of that list drew «0 из 7 циклов» — seven loops reported stopped, on the evidence that nobody looked. It now reads an em dash over «НЕ ИЗМЕРЕНО», and a partly-measured group carries its shortfall («ИЗ 2 НАБЛЮДАЕМЫХ · 1 НЕ ИЗМЕРЕНО») so that all-fine, partly-known and measured-nothing stay three different things on the tile.

Two of the kit's four stat tiles were dropped rather than filled. Nothing in the system measures uptime or the event-queue depth, and a tile reading 0 events queued on a farm whose relay is down is an invented number with a nicer font. «Версии» and «Журнал» are absent for the same reason — no endpoint serves either.

The tab is inserted by the console, not served. SECTION_ORDER carries fourteen sections where the kit's rail draws fifteen, because a read-only page has nothing for a settings catalogue to describe — that is still right, and it left the rail one entry short. The rail's own length is now what the «Разделы» count reports, and the section number in each heading is read from the rail, so «Обслуживание системы» is section 15 as the kit has it rather than 14. The tab is in the rail as soon as that load has settled, whatever it settled as: GET /settings/sections reads the database, so gating it on the catalogue hid «Диагностика» in exactly the outage it explains, and a failed catalogue now leaves the diagnostics tab standing alone rather than an empty rail under an error banner. DESIGN-KIT §4 is empty for the first time, and the materials popup is why (#38). GET /materials/{code} was the last endpoint the API served that nothing called. The issue allowed either answer — build the popup or delete the route — and the popup was built: apps/console/src/MaterialDetail.tsx reads the spec by code when a row is opened, so the window now shows density, tensile strength, heat-deflection temperature and the flexible/outdoor flags. None of those five is a column of the materials table, which is why the old popup — rendered from the row it was opened from — could say where a spool is and never what the plastic is.

The purchase price is behind VIEW_FINANCIALS, and the route is not. GET /materials/{code} carries purchase_price_per_1000m and has no permission dependency of its own, because the storefront configurator needs the catalogue. The console declines to draw the farm's buying price for anyone without the money permission (root CLAUDE.md §1), which is a decision about a screen and not an access control — anyone who can call the route still gets the field. The measured fact behind that sentence, because it is worse than "the console is being careful": GET /materials and GET /materials/{code} both return MaterialSpecView with purchase_price_per_1000m populated, neither carries a permission dependency, and nothing above them requires a session — so the farm's buying price is served to an anonymous caller. Whether the route should withhold it is a backend decision and it needs an issue, which is a person's to file: open work belongs in the tracker and not in this document (docs/WORKFLOW.md), so what is recorded here is the state, not the task. It was raised in the review of #85 and is waiting on that issue.

An empty §4 broke the gate that watches §4, and the fix is worth knowing before the next entry is closed. test_section_4_still_parses_into_the_entries_it_carries asserted len(parsed) == len(bullets) and parsed — the trailing term was there so that a broken DOC_ENTRY regex could not make the two parametrized gates collect zero cases and report green. But it also required §4 to carry a bullet for ever, and §4 is meant to reach zero; emptying it failed the gate rather than the section. The parser is now proven against a SAMPLE_BULLET constant instead, and the spelled-count assertion flips to "an empty section must not still spell a count". Both directions were mutated and both fail. The two parametrized gates now collect nothing and pytest reports that as 6 passed, 2 skipped; the module docstring says so in as many words, because an unexplained skip in the file whose whole subject is gates that stop running without anyone noticing is the last thing that file should leave to inference.

What measures that the issue is closed is MaterialsPage.test.tsx: it opens a row on the table a person opens a material from and watches the request for /materials/{code} go out. The docs gate is the weaker half of that pair and the difference is worth knowing — deleting the path literal from MaterialDetail.tsx does make test_every_unconsumed_endpoint_is_named_in_the_doc_or_exempted fail naming GET /materials/{code} and nothing else, and that was run, but it is a scan of the source text: a detail window no screen mounted would keep it green. Reachability is a question about the bundle (frontend/CLAUDE.md), and the built console bundle does carry the detail read.

The rates an order was priced at can now be looked at (#40). GET /orders/{order_id}/rate-snapshot serves the pinned bundle, and the order desk gained a «Тарифы заказа» panel. ADR-0020's guarantee has always held — a rate edit changes the next quote and nothing already sold — and nothing could show it: an owner changes seventeen pricing rates, a customer asks why a repeat order costs more than last month's, and the system held both snapshots and could display neither.

The payload is served as stored, and deliberately not rebuilt. pricing.rates_from_dict skips fields absent from a stored row and RateSnapshot then supplies today's defaults for them — so a snapshot written before a rate existed would come back carrying a number that was never in force, indistinguishable from a measured one. The row goes out verbatim, schema_version included, so its vintage is legible.

The id is the answer, not the table. It is a content hash, so two orders showing the same id were priced from identical rates and the difference between them is in the configuration. The panel shows it abbreviated for exactly that comparison.

An order that pinned nothing gets its own code. error.ordering.rates_not_recorded, distinct from not_found: the order exists and its rates were never recorded. The panel renders that sentence and does not even make the request — a table of zeros would be a claim about rates nobody was charged.

The read lives in ordering/snapshots.py, not on OrderingService, which is at the 400-line gate. It wants none of what the service carries — no clock, no bus, no transaction — so the split costs nothing.

The variance queue ADR-0013 feeds is no longer invisible (#39). GET /jobs/variances serves what slicing found against what was quoted, and the order desk gained a «Пересмотр цены» panel that reads it. The detection has always worked — every plate attach writes an EstimateVariance and one beyond tolerance holds the job — and nothing served the rows, so the mechanism that stops a mis-estimated plate printing at a losing price was half-built.

The route carries VIEW_FINANCIALS on top of the router's VIEW_PRODUCTION. A variance is a measurement and this one carries money; CLAUDE.md §1 keeps the two apart precisely so a response about seconds does not quietly start carrying rubles. The engineer who records the plate may not read what it cost. The route is refused whole rather than answered with the money blanked — a null means "not measured" (ADR-0007), and using it for "not permitted" would make the two indistinguishable.

exceeded_only is opt-in, and that default is load-bearing. The in-band rows are the farm absorbing small differences and are the dataset ROADMAP Phase 6 calibrates the estimator against. A read that dropped them would look like a filter and take that dataset with it.

The route is declared above GET /jobs/{job_id}. FastAPI matches in declaration order, so the same route written below resolves as job_id="variances" and fails as a 422 about a UUID nobody asked for, with no warning. There is a test whose only job is to notice.

The desk had no price_review chip at all. It was in none of the three filters — not awaiting_payment, not in_production, not shipped — so the one status that needs a person was reachable only by reading every row.

The farm can now be asked which printers it is actually connected to (#21). /health/workers grew a drivers key: one entry per printer the worker was asked to drive, with its state, the error code behind an unavailable, and when that state began. The worker publishes it (core.driver_health) down the same Redis-with-an-expiry channel the heartbeat uses, because the connection pool lives in the worker and the API holds no connection state of its own.

The original filing's premise had already been corrected, and the gap survived it. ARCHITECTURE §10 says readiness must not report on drivers, and that is right — the API cannot see a connection, so a check there would invent one. But "which process owns the fact" is not an argument about whether the fact should be observable, and a driver unreachable for six hours is still a printer the farm believes it can dispatch to.

Two keys with two windows, and the difference is the design. The readings expire with the loop that writes them; the roster — the printers the worker last said it was driving — is written afterwards and lives four times as long. Without that gap a silent worker takes the roster with it and the report goes quietly empty, which reads as "this farm has no printers". With it, the readings lapse first and every printer the roster still names reports unknown. That is the ADR-0007 case, and it has its own test.

No driver changes a status code, and both halves of that were in the issue. Not readiness, where one unreachable printer would take the whole API out of rotation. And not /health/workers either: a farm with a machine switched off is normal, and a probe that is permanently red is a probe nobody reads. Only the loops decide the code; an alert about a driver keys on the body.

The roster is what the worker observed, never the printers table. Reading the table for it would report on machines this process never tried to reach — root CLAUDE.md §1's denominator rule, in the one place it would have been easiest to get wrong. The SLA credit has a ledger, so a figure that left the farm can be checked (#75). Every movement of orders.sla_credit appends a row to the new sla_credit_entries, carrying the previous value, the new one, the promise and the three decay terms it was derived from — the sweep's accruals and the freeze at dispatch alike. The column used to be its own only record: each pass overwrote it, SlaCreditAccrued went to a bus whose sinks persist nothing, and no prior value survived. Money leaves through PaymentsService.refund_sla_credit and revenue is reported net of the figure, so that was a gap rather than untidiness.

It is a table of its own, and the issue asked for order_events rows. The deviation is recorded on the issue. OrderView eagerly loads Order.events on every read, table() included — and the credit moves on every sweep: at the default sla_sweep_seconds=300 a standard promise moves 1 728 times before it hits the 30% cap, so a page of twenty late orders would have carried thirty-four thousand event rows in one response. The ledger is written far more often than an order's history and is read by query, so it is deliberately not reachable from Order.

sla_sweep_seconds is now also the ledger's resolution. Worth knowing before it is tuned for some other reason: halving it doubles the rows.

Nothing is backfilled and nothing can be. The previous values were never written down, and a ledger opening with rows reconstructed from today's column would be an invented history (ADR-0007). An order already late when 0021 ran gets its first entry on its next movement.

A promise now carries the terms it was sold under (#74). orders gained decay_percent_per_day, decay_grace_seconds and decay_max_percent, copied out of POLICIES at placement; _credit_for computes from that copy. Before this the order recorded only the policy code, so raising standard from 5%/day to 10%/day did not price the next sale — it doubled the credit owed on every promise already sold, on the next pass of workers/sla.py.

The test is the part worth keeping. It sweeps, edits POLICIES between two sweeps, and sweeps again: without the fix the second sweep moves an existing order's credit from 183.27 ₽ to 366.54 ₽, which is the defect stated as a number. All six gates passed both before and after — this is the D13 case again, where shape was green and behaviour was wrong.

Migration 0020 backfills the three known codes with the values they hold today, and leaves any other code null. That is not an invented number: today's values are what every existing order is already being priced at, so writing them down changes nothing anyone is owed and only stops the next edit reaching backwards. A row with an unrecognised code has no recorded terms and gets none; _terms_for falls back to the live lookup for those, exactly as before.

The two listings that were never paged now say when they need to be (#45). GET /printers and GET /materials still return everything, which DATABASE-REVIEW §9 records as a deliberate gap and argues correctly: both are bounded by the size of the farm, not by history. contexts/fleet/listings.py and contexts/inventory/listings.py count their own listing on every readiness probe, and /health/ready reports printers_listing and materials_listing separately, degraded past 500 rows.

#45 stays open too, for the reason #44 does — docs/WORKFLOW.md §3, a deferred issue closes when its trigger fires and the work is done. Nothing here pages anything. What changed is that the trigger stopped being a sentence in a document, which matters more here than it did for #44: the growth #45 names as the dangerous one is the purchasing screen adding spare parts, packaging and printers to the materials listing. That arrives as a feature, not as traffic, and nobody is looking at row counts on the day a feature ships.

The count deliberately stops at the trigger. capped_count issues count(*) over a LIMIT, so the check costs the same on a farm with a million lots as on one with six — a plain count(*) would be a scan growing at exactly the rate of the problem it watches, at its most expensive on the farm that most needs the answer. The catalogue trick #44 used is not available: these readings have a predicate (active specs, lots with material left) and pg_class counts whole relations. The price is that a reading past the line is a floor, and ListingSize.is_exact says so rather than passing a capped count off as a measurement.

Three counting decisions read as arbitrary and are not. Retired printers are counted, because include_inactive=true returns them and nothing ever deletes a printer row — that is the half that only climbs. Inactive material specs are not, because /materials has no such parameter and cannot be asked for them. And the materials reading counts the live lots nested inside each spec as well as the specs, because the response grows on both axes.

These two clear on their own, unlike assignment_records beside them. They read a set that can shrink; that check marks a threshold crossed once. Both comments say which they are, because the reasoning does not transfer.

One of #45's three triggers is not measurable as the endpoint stands, and the issue is worth amending. It watches lots accumulating "without being retired", citing /materials/lots — but there is no such route, and the lots that ride inside /materials are only the ones with material left in them, because _to_view drops a spent spool. So that half tracks material on hand, not receiving history, and it will not climb the way the issue expects until the route it names exists. contexts/inventory/listings.py says this where the next reader will be standing.

Seven mutations were run and each failed: dropping the wiring, removing the cap, calling a saturated reading exact, filtering the printers count to active rows, dropping the lot half, dropping the active-spec filter, and replacing the reading with a confident zero.

The table ADR-0018 said would be "watched" is now actually watched (#44). contexts/production/growth.py measures assignment_records against the trigger DATABASE-REVIEW §9 states — 10 million rows or 20 GiB — and /health/ready reports it as a check of its own, degraded once either half is past. Two pg_class columns, so a readiness probe pays nothing; count(*) over ten million rows on a path a container runtime calls every few seconds would have made the check the outage.

#44 stays open, and that is the point of it. It is a deferred issue and docs/WORKFLOW.md §3 says one closes only when its trigger fires and the work is done. Nothing here partitions anything — the deferral is still correct for the reasons ADR-0018 gives. What changed is that the trigger is measured rather than remembered, which is the half of "indexed and watched" that was not true.

Two things about it read wrong at first and are deliberate. The row figure is pg_class.reltuples, an estimate that is absent — stored as -1 — until something analyses the table; it is reported as unknown rather than as zero, so the exact byte figure decides alone in that state (root CLAUDE.md §1, and the reason estimated_rows exists as its own function). And this check does not clear on its own: it marks a threshold crossed once, so it stays lit until the table is split. That is the opposite of wal_archiving two screens down, which compares watermarks precisely so a fault that has passed stops showing red — the reasoning there does not transfer, and both comments now say so.

The four gates that would have let this ship broken were each mutated and each failed: dropping the wiring, collapsing "never analysed" to zero, dropping the byte half, and replacing the reading with a confident zero.

Three documents now fail CI when their inventories go stale, and two overstated sections are corrected (#10, #11, #13). DATABASE-REVIEW §1, DESIGN-KIT §1 and DESIGN-KIT §4 are checked against __tablename__ declarations, the console's routes, and the OpenAPI schema plus the frontend's client calls. Each gate was proven to fail — nine mutations, every one caught with a message naming the entry that drifted.

Writing the corrections produced three false claims, which is the finding. An adversarial pass caught them before the commit, and each is worth knowing because each was believable:

  • The SLA credit is not audited. refresh_sla_credit writes no order_events row, SlaCreditAccrued goes to a bus that persists nothing, and the sweep overwrites orders.sla_credit in place. No prior value of the credit exists anywhere. On a money path, worth fixing — not filed yet. (Filed as #75, and fixed below.)
  • The order does not pin the terms it was sold under. Only the policy code is stored; POLICIES holds the rates and _credit_for re-reads them every sweep, so editing standard re-prices every unshipped promise. This is exactly what ADR-0020 exists to prevent, and the paragraph asserting otherwise cited ADR-0020 four lines later. The comment at ordering/policies.py:173 still carries the same wrong claim.
  • /health/ready reports event_relay only where a relay is configured, so "the four health checks" overcounts a deployment without one.

The prose now states both gaps plainly instead of reassuring. The first two are the issues #75 and #74 were filed from, and both are fixed below; the policies.py comment no longer carries the wrong claim.

Every enum column now has a database-level CHECK (#43). Twenty-three columns across eighteen tables were bare VARCHAR in PostgreSQL, guarded only by the Python type and by Pydantic — both of which live inside the API process. Migration 0019_enum_check_constraints puts a constraint on each, telemetry_samples included (a CHECK on a partitioned parent recurses into every partition and is inherited by every future one, so fleet.retention keeps creating months that carry it).

The issue was filed as deferred, and the reason it gave was real but not the obstacle it looked like. SQLAlchemy names a generated enum constraint after the enum type, so order_events.from_status and to_status — both OrderStatus — produce two constraints with the same name and the schema will not build. The recorded escape was a hand-picked name at every call site, which is a rule that decays. Naming the constraint after the column instead removes the collision by construction: a column is unique within its table by definition, so the twenty-fourth enum column is safe without anybody remembering anything. That is what core.db.enum_column does now.

create_constraint=True is still off, and turning it on will break alembic check. Alembic skips CHECK constraints marked _type_bound on the metadata side, so a real constraint in the database reads as one the models dropped and every check reports drift. _CheckedEnum builds an ordinary constraint instead. Migration 0006 hit this exact wall and recorded it; its comment now points forward.

What the gate does not cover. Alembic matches CHECK constraints by name only — measured, not assumed: adding a member to an enum with no migration behind it passes alembic check clean. test_every_enum_column_is_checked_in_the_database compares the permitted value sets against the migrated database and is the only thing that catches it. Adding an enum member is now a migration.

A paid order now becomes print jobs without anybody clicking anything (#41). workers/intake.py is a seventh worker loop, reconciling rather than reactive for the reason workers/postproduction.py argues: it asks "which paid orders have no jobs yet" every thirty seconds, so a tick missed during a restart costs latency and never an order.

The gap was wider than the issue said. #41 recorded that jobs were created by "the jobs API, i.e. a person". They were not created by anything — grep -rn "create_job" printorian/ returns the definition and no caller, and there is no create-job endpoint. What existed was a test helper, in tests/scenarios/test_repeat_order_skips_prep.py, whose docstring reads "what a caller does when an order is paid". This is that helper promoted into the product, which is worth knowing because the scenario test has been green the whole time the product could not do it.

Two things it will not do, both deliberate. A cache hit still goes to prep rather than straight to the queue: attaching a plate writes an EstimateVariance whose prepared_cost is NOT NULL, and nothing prices a plate — a zero there would record "the estimate was perfect" for a variance nobody measured, which is §1 of CLAUDE.md in the flattering direction. Repricing from slicer truth is #58 — and that half is no longer true; the entry at the top of this section is what replaced it. And a line carrying an asset whose digest will not resolve refuses the whole order instead of making the job: a job with an asset but no model_hash slices, prints and ships correctly, and quietly sends every repeat of that configuration back through an engineer for ever, because plate_key can never match it.

Open work has moved into GitHub issues, and this changes where to look first. Forty-seven issues across twelve milestones, with the labels and the process in docs/WORKFLOW.md. Nothing in the code changed; what changed is that §3 of this file is no longer the place a session finds its next task.

The reason is the one in §4 of CLAUDE.md. Four documents each carried a list of outstanding work — §3 here, ROADMAP.md, DESIGN-KIT.md §2 and §4, and DATABASE-REVIEW.md §10 — and building the backlog found them disagreeing with each other and, twice, with the code.

Both status tables named there have now been corrected, each verified against the code rather than against the document that reported it (#8, #9). INFRASTRUCTURE.md §1 was stale in seven rows and is re-derived, dated, and split so that what is built and what is scheduled are different claims; Stage 0 is marked done. DESIGN-KIT.md §1 and §2.1 said the settings screen was unbuilt while SettingsPage.tsx served 102 parameters across fourteen sections — §2.1 now records only what is still owed and links it, because a second description of a finished screen is a second thing to keep in step.

One finding recorded there has since been closed rather than corrected: main now has branch protection — backend, frontend and image required, linear history, no force-push, no deletion (#4). The other was new rather than transcribed: the timestamp-sort flake class §2 estimates at "about a dozen" is fifteen, measured, with the file and line of each in the issue.

The README is now the front door rather than a summary. Same facts, reorganised around two rendered diagrams — the container topology (who talks to whom, and over what) and the order state machine, drawn from contexts/ordering/policies.py rather than described. docs/assets/banner.svg and banner-light.svg are generated from the design kit's own tokens and swap on prefers-color-scheme. Three things it corrected while being rewritten: the context list was missing account, packaging, postproduction and settings; printorian/workers/ was absent from the layout altogether; and docs/RUNBOOK-FIRST-BOOT.md had never been added to the document table. Volatile counts were deliberately left out of it and pointed here instead — a badge reading tests 1227 is the staleness trap in §4 of CLAUDE.md with a nicer font.

docs/DATABASE-REVIEW.md §1 was stale in every figure it carried, and is fixed. It said "22 tables across seven contexts, built by nine Alembic migrations"; the ORM has 42 across twelve, and backend/alembic/versions/ holds twenty. Its table was missing account, journal, packaging, postproduction and settings entirely, plus catalog_models, catalog_model_materials and metric_rollups. The list is now diffed against every __tablename__ under contexts/ and matches exactly. "Single linear head" was the one true part — one root, one head, no branch points. The rest of the document already discussed the newer tables; only the summary had drifted, which is the failure mode §4 of CLAUDE.md warns about: the part everyone reads first is the part nobody re-derives.

The settings screen is built, and the settings take effect. contexts/settings now serves the whole kit's catalogue — about a hundred parameters across fourteen sections (diagnostics is read-only, so it has no fields) — through GET /settings, GET /settings/sections and the existing PUT/DELETE /settings/{key}, gated on a new MANAGE_SETTINGS permission (owner only, replacing MANAGE_PRICING on the router). The console has a SettingsPage (owner-only nav) that renders one control per kind — number/unit, select, switch, string, and a write-only, encrypted secret (finance.yookassa_secret_key is stored under PRINTORIAN_SECRET_KEY and never read back). Editing marks a row dirty, counts into a save bar, and each save is a separate audited «было · стало», shown in «Обслуживание системы».

Three settings now take effect at the read edge, the same shape resolve_rates always had: resolve_promise() (lead times — a changed sla.min_lead_hours moves the next quote) and resolve_scheduling() (planner weights, resolved per scheduler pass). The loop intervals (scheduler_tick_seconds, telemetry_poll_seconds, sla_sweep_seconds) are still read at worker startup, so they take effect on restart — recorded rather than wired, because a per-pass re-read is a worker-loop change with little payoff. Of the kit's table-valued settings, the volume ladder and the customer tiers are built (both stored as JSON and parsed back into DiscountLadder / CustomerTier); the tiers' discount and margin override reach the engine through resolve_tiers(), while the loyalty from_spend thresholds that earn a tier stay in loyalty.py. The rest — maintenance intervals, zones, event matrix, API keys, webhooks — are not built — see §3; the diagnostics panel now is, above. Two of the three irreversible operations are wired: POST /settings/reset-rates drops every pricing.* override (audited per row), and POST /settings/drop-telemetry runs retention now through the shared clamp — retention.drop_telemetry_past_retention, which the maintenance worker also uses, so «drop now» and the scheduled sweep cannot drift apart. The third (clear waitlist) is not built.

A review pass fixed four defects in that screen, each now covered by a test that fails without the fix. The save bar's «Отмена» was markup copied from the kit with no handler — it discards every draft now. ConfirmAction compared the typed farm name against the stored one, so a farm with a blank name matched an empty box and armed the irreversible operations on one click; the confirm is withheld and explains why. Clearing a number box saved 0 rather than being refused, because Number('') is 0 and the guard tested for NaN — an emptied numeric field now blocks the whole save and names itself. And groups.in_group_order keeps a panel's fields contiguous: pricing.material and scheduling.normalization were each split across their section, so the screen drew the same heading twice and gave two React siblings one key. That last one is structural on purpose — the pricing fields come off RateSnapshot's declaration order, so hand-sorting would only hold until the next field was added there.

The farm can change its own pricing rates. contexts/settings is a key/value store with an audit, serving the seventeen scalar rates through GET/PUT/DELETE /settings, gated on MANAGE_PRICING (owner only). Two properties are load-bearing and both are tested:

A key with no row resolves to the code default, so an empty table prices exactly as the farm always did — nothing is seeded, and the migration moves no prices on the day it runs. And an order keeps the rate snapshot it was agreed at (ADR-0020), so raising a margin changes the next quote and nothing already sold.

The catalogue is derived from dataclasses.fields(RateSnapshot) rather than hand-listed, so a rate added later appears in the screen without a second place to remember. The other ~85 kit parameters are still constants on core.config.Settings and are a bigger job than they look: they are read once at process start, so moving them changes when they are read as well as where from.

pricing.py reached the 400-line gate and split — spec assembly moved to _pricing_spec.py, and with it the mesh-analysis cache.

Telemetry is summarised, and retention is on. metric_rollups holds one row per printer per hour. telemetry_retention_days ships at 90 for the first time — it had been 0 since the table existed, because dropping raw samples with nothing summarising them destroys the only copy.

The safety property is a clamp, not an ordering. The drop cutoff is min(now − retention, watermark), where the watermark is the hour rollups have actually reached. A farm whose summarising stalls stops dropping raw samples with it, and one that has never summarised an hour drops nothing at all. If you touch workers/maintenance.py or contexts/fleet/retention.py, this is the invariant to preserve — it is the only irreversible path in the system.

The dashboard's occupancy figures changed source, and some numbers moved. run_hours / capacity_hours / idle_hours and the 7 × 24 load map used to be derived from print_jobs — booked time, not running time. A paused or errored print counted as run time; a job row never closed counted from its start to now for ever; machine time with no job behind it was invisible; idle was a residual against the roster. They are now measured from metric_rollups, and the job-derived versions were deleted rather than left alongside.

Two consequences are visible on purpose: the note reads «ИЗ N ИЗМЕРЕННЫХ» rather than «ВОЗМОЖНЫХ», and an unmeasured window shows an em dash where it used to show 0.0. On the load map, an hour nobody polled is hatched — distinct from both bright and the outlined zero that means "measured, and idle".

GET /fleet/metrics and /fleet/metrics/{printer_id} serve it. Seconds only; money and energy stay behind VIEW_FINANCIALS. Deliberately two routes with different shapes, under their own prefix — /printers/metrics would collide with /printers/{printer_id} by declaration order.

The legacy --pr-* design tokens are gone, along with 119 dead CSS rules. Reachability was decided against the built bundle, not the source. One real bug fell out: .prep__done asked for an undefined token, so its hard-coded fallback always won — a light-palette green on a near-black panel at ~2.2:1.

A farm can be provisioned, and can no longer be served from a developer dump. tools/provision_owner.py creates the first owner — the only account in the system made without an authenticated actor behind it. It reads the password from the terminal rather than an argument (a password in argv is in the shell history and in ps), and refuses outright if an owner already exists: provisioning is first boot, not a password reset, and the two want opposite behaviour.

The guard that matters is contexts/identity/reserved.py. DEVELOPMENT.md publishes two account passwords, one an owner, and restoring a dump into another environment is routine — so the API now refuses to start in production while any account sits in a domain reserved for documentation (RFC 2606 / RFC 6761). Not a warning: a warning about credentials is read after the incident. docs/RUNBOOK-FIRST-BOOT.md is the procedure. scripts/create_owner.py was deleted — it was referenced by nothing and defaulted to the published password.

Backup and the restore drill have now actually been run. Both were correct and had never once been executed. backup.sh produced a verified dump and a base backup; the dump restored into a scratch database at schema head. Two real defects fell out and are fixed:

The drill demanded rows in payment_notifications, so it failed on any farm that had not yet taken a payment — which is every farm in its first week, exactly when the first drills run. It now compares restored counts against the live database, which keeps the failure it was built to catch (a backup pointed at the wrong database, producing a valid empty dump nightly) and drops the false alarm. And backup.sh wrote the dump under its final name while still filling it, so a drill overlapping a slow backup would pick a half-written file; the dump is now renamed into place only after it verifies.

deploy/systemd/ holds the units that run the farm — the stack, a nightly backup, a weekly drill — verified with systemd-analyze. This is the piece of INFRASTRUCTURE Stage 2 that closes a measured risk rather than a theoretical one: pg_archivecleanup runs only inside backup.sh, so with nothing scheduling it, archived WAL grows without bound. The dev stack reached 847 segments / 13.9 GB in four days, and compose.prod.yml already carries a comment recording the earlier version of this failure at 23 GB.

There is a farm, and it survives being mistreated. 192.168.29.148, Ubuntu 26.04 under VMware, root grown to 96 GB and /mnt/backup on a second physical disk — the ADR-0019 separation the compose default violates. Console on :8080; the API is reachable only through its Caddy at /api, and postgres and redis are not published at all.

The storefront runs on :8081, but only when asked for:

docker compose -f deploy/compose.prod.yml --profile storefront up -d

It sits behind a Compose profile because this is not where it belongs — ADR-0016 puts it on the rented edge VPS, with TLS there and WireGuard back, and that is Stage 3. Without it a farm-only deployment cannot exercise ordering, quoting or uploading at all, which is most of what a customer does. web-dist stays the bundle the edge will receive; the new storefront target is the same bundle behind a Caddy using the identical /api prefix, so nothing needs rebuilding to move. deploy/storefront.Caddyfile names every difference from the edge.

Measured on that host, not asserted: a reboot brings back the mount, the stack, the timers and the data unattended; SIGKILL to the API is healthy again in ten seconds; SIGKILL to postgres keeps the data through WAL replay and the API recovers its pool without restarting. Backup and drill both run green through systemd.

Do not trust systemctl is-active printorian.service. Type=oneshot with RemainAfterExit=yes means "ExecStart returned 0 once", not "the farm is up". Observed within the hour: systemd says: active | containers running: 0, and systemctl start will not fix it — only restart re-runs ExecStart. The honest checks are /health/ready and the container count. printorian-ensure.timer reconciles every five minutes and logs loudly when it has to act; it reconciles toward systemd's intent, so a farm deliberately stopped stays stopped.

Nine defects that only a real host could surface. Four of them were in units committed hours earlier: the image copied tools/ but not scripts/; nothing mounted backup.sh into postgres; the api container had no /backup; the api image had no pg_restore. Three more were worse:

A write that was never committed. Database.session() commits after the yield, so return from inside async for session in db.session() leaves the generator suspended and the commit never runs — the interpreter finalizes it with GeneratorExit, a BaseException, which slips past the except Exception that would at least have rolled back loudly. provision_owner.py created the farm's first owner, discarded the insert, printed "Created owner" and exited 0. api/ws.py had the same shape. tests/unit/test_session_lifecycle.py now walks the AST and fails on the pattern anywhere.

The drill could never have run on a farm. Synchronous SQLAlchemy resolved a bare postgresql:// URL to psycopg2 — declared only in the dev group, for one migration test. Exactly the failure INFRASTRUCTURE §6 predicts. Now async.

One full backup disk wedged WAL archiving permanently. archive_command copied to the final name, so a full disk left a 786 KB fragment of a 16 MB segment there; test ! -f then saw a file and the && chain never ran again — and freeing the disk did not help. It now writes %f.tmp and renames.

The farm now says when its backup guarantee stops holding. With the disk full, /health/ready used to answer {"status":"ok"} while archiving failed and pg_wal grew toward filling the data disk; systemctl --failed listed nothing. It now reports wal_archiving: degraded — degraded rather than failed, because serving is unaffected and taking the API out of rotation would turn a broken backup into a broken farm. It compares the two watermarks rather than failed_count, which never resets and would leave a farm red for ever over one bad night in March.

Archived WAL is gzipped, which changes the disk arithmetic. archive_timeout is 1 min, so segments are switched on time rather than fullness — 288 segments a day on an idle farm, nearly all empty, at 16 MB each. Measured: 80 MiB of segments compress to 2.95 MiB (27×), and the near-empty ones go 16 MiB → 16 KiB. That is a 98 GiB backup disk filling in 22 days versus over a year. PITR therefore needs restore_command = gunzip -c /backup/wal/%f.gz > %p; a cp-based one finds nothing and PostgreSQL reports recovery complete rather than failing.

The console was rendering without its fonts. Caddy's CSP said font-src 'self' while Vite inlines the interface font as a data: URI, so every Harvester face was blocked and the console fell back. Invisible in development, where the dev server sends no CSP at all.

A host-readiness check now exists as a runnable script. deploy/readiness-check.sh evaluates a candidate farm server — OS family, systemd, RAM/CPU/disk, the ADR-0019 backup-disk separation, clock and timezone, Docker + the compose plugin, the .env and its required secrets, port bindings, printer reachability, and the systemd units — and prints a PASS/WARN/FAIL tally with the fix for each failure. It exits non-zero on any FAIL, so it can gate the Stage 2 Ansible role instead of deploying onto a host that is missing a disk or a secret. This is the first executable half of the "host configuration is prose" row in INFRASTRUCTURE §1 (provisioning, not checking, is still Ansible).

Purchasing exists, on issue-34-purchase-orders, and nothing about it has been run against a database. contexts/procurement — suppliers, purchase orders over six stages plus cancellation, five purchasable classes, and receiving a material line into a material_lots row carrying its lot number and the price paid — plus api/routers/purchasing.py, migration 0026_procurement, 46 backend tests and the console screen. Two things it changed outside its own context are worth knowing before touching either:

  • material_specs.has_open_order is gone. InventoryService.table, get_by_code and recommend take on_order: frozenset[str] as a required keyword, supplied by procurement.reads.ordered_codes. Required, with no empty default, because a default would turn "nobody asked procurement" into "nothing is on order" — silent and flattering, which is the ADR-0007 collapse this repository keeps repeating. There were eight call sites, not the three the plan predicted: get_by_code is also the pricing path's way in.
  • The migration is 0026_procurement, and it was renumbered to get there. It was written as 0024_procurement off 0023, which was correct while this branch stood alone. #95 then landed 0024_printer_failures and #97 landed 0025_storage_cells_and_movements, so it now revises 0025 and is the single head. The renumbering is the merge commit's, not the original author's.

Since verified, in the main tree. Everything the branch could not run has now been run there: ruff check, ruff format --check, mypy, check_context_isolation.py, check_file_length.py and lint-imports (6 contracts kept), all exit=0; 0026_procurement as the single head, applied, alembic check clean, downgraded and re-applied, all exit=0; the whole backend suite, 1 443 collected, 8 skipped, exit=0, the 46 procurement tests among them; and the three frontend gates — typecheck, lint, vitest (290 tests, 7 of them purchasing) — also exit=0. Three things had to be fixed to get there, and all three were the harness rather than the feature:

  • test_the_purchasing_routes_are_actually_mounted walked app.routes one level deep. Since FastAPI 0.141 include_router leaves one _IncludedRouter there instead of splicing routes in, so it saw /docs and nothing else while the ten purchasing operations were mounted and serving. It reads the generated schema now.
  • test_a_refused_delivery_leaves_nothing_behind expected 400. api/errors.py maps every ValidationError to 422 and the rest of the suite asserts 422.
  • PurchasingPage called refetch() from an effect body, which react-hooks/set-state-in-effect refuses. PackagingPage already awaited its fetch inside a closure; this does the same.

Worth knowing for the next verifier: the run began with a wall of drop-table errors that were not this branch. printorian_test still held material_movements, storage_cells and storage_zones from a previous branch's pass, and drop_all sees only the current branch's metadata, so it could not drop material_lots out from under a foreign key it does not know about. Dropping the database and letting conftest rebuild it is the fix; leaving it behind is the trap.

2. Deliberately unfinished

Not oversights. Changing any of them is a decision, not a cleanup.

Why it is like that
customer_storage_quota_bytes displayed, not enforced Refusing a quote mid-configuration is the wrong UX. Growth is bounded by model_retention_days instead.
Rate limiting and sign-in lockout are in-process Correct for one API process (ADR-0003). Counters reset on restart; a second replica would get its own allowance. docs/DATABASE-REVIEW.md §9.
/metrics serves eleven of INFRASTRUCTURE §5's twelve series The four database-backed collectors and the three backup stamps arrived 2026-10-14 (production.vitals, payments.reconciliation, settings.maintenance_runs — backup.sh, restore_drill.py and printorian-offsite.service write a row there when they succeed). The worker exporter and the money series remain, and so does the whole VictoriaMetrics/Grafana/Alertmanager host stack; /health/workers remains the liveness signal, reading beats each loop records at the end of a pass.
printorian_sla_credit_accrued_rub is held back rather than unbuilt /metrics is unauthenticated, so VIEW_FINANCIALS has no caller to check. The money series waits for the scrape to have an identity — a token in Settings, or mTLS — and that is a decision for a person, not a query somebody has not written. A test forbids any _rub or sla_credit name on the endpoint meanwhile.
Off-site backup sync is committed, with no destination deploy/offsite.sh and printorian-offsite.timer are written and tested against a local restic repository in CI. The destination, its credentials and the password's escrow are a person's (#16); OffsiteCopyStale says so in every digest until then.
assignment_records is not partitioned ADR-0018's deferral still holds — bounded by planning frequency, not by the clock. /health/ready now reports when the trigger fires; #44 stays open until it does.
Storefront body lifts the page ground Predates Harvester; --hv-bg vs --hv-void is six values out of 255 in dark, identical in light. A visual call, not a cleanup. See apps/web/src/app.css.
TypeScript held at 5.x openapi-typescript crashes on TS 7. Reason and three failed workarounds are in .github/dependabot.yml.
Six queries still sort on a timestamp alone Read in one pass and left that way on purpose. See below.
pricing.shipping_flat survives the zone tariff It is the pre-address figure, not a leftover. The checkout prices a courier the moment the customer picks one (RepriceLine), and a zone tariff cannot answer a question with no destination in it. It is also where a postcode no zone claims lands, because zone_for returns None rather than guessing. Owner decision, recorded at pricing/lines.py::logistics_lines.
logistics.free_shipping_threshold still unread Shipping sits inside the base that rush, the volume discount and margin are all taken over, so "free over 15 000 ₽" against an order total is circular — the total already contains the shipping and the margin on it. It needs a defined base (the pre-shipping subtotal), which is its own decision with its own test.
logistics.volumetric_divisor still unread Volumetric weight needs a bounding box, and the box that matters is the parcel's rather than the part's. It belongs with the Shipment record (#36).

The single-column time sort has been triaged, once, across the whole tree (#42). It started with SettingsService.history, which ordered by changed_at DESC and nothing else: every row a test writes shares one timestamp, so the sort tied and CI and a dev machine disagreed about the same two rows. Ordering by id as well settles it correctly rather than merely consistently — core.ids.new_id builds a UUIDv7 from time.time_ns(), the real clock, so ids stay chronological where changed_at is frozen.

The idiom now lives in core/pagination.py, next to the argument about sort keys that was already there, along with the two things that make it a rule rather than a habit. The tie is not a test artifact: Entity.created_at is a server_default of now(), and PostgreSQL's now() is the transaction's start, so every row one pass writes carries the same timestamp in production too. And the rule has an exception — JobEvent and OrderEvent carry an explicit sequence, because UUIDv7 orders only to the millisecond and a job passes three statuses inside one.

Where the second term is worth having, and where it is churn. A sort under a LIMIT decides membership: a tie at the boundary moves rows in and out of the answer, so unchanged data reads differently twice. Fourteen queries were fixed: nine of the measured fifteen, plus five of the same shape that a second term had hidden — the scheduler among them, which sorted by priority and created_at and still tied. A sort that returns a whole set for a screen to render decides only presentation, and a term there is churn; the remaining six were read and left, each saying so at the line. production/prep.py is that same call and unbounded, so it stands as it was.

Fixed Left single-term
production/planning.py (the ready batch), production/reads.py (both), production/queue.py (both), production/throughput.py, packaging/board.py (both), packaging/catalogue.py, packaging/service.py, postproduction/board.py, account/service.py (both), workers/postproduction.py catalog/assets.py, identity/service.py, identity/sessions.py, ordering/history.py (both), payments/service.py

production/queue.py's _first_entered was the one that wanted sequence rather than id, and packaging/board.py's pickup roll-up wanted the rest of its group key — there is no id in a grouped result. tests/unit/test_production_ordering.py covers the planner and the assignment record under FixedClock; six of its eight tests fail on every run against the code as it was, which is the part worth knowing.

The postprocessing catalogue is a setting, and two of its columns are not (#29, first slice). The finish rows now come from postprocess.operations and reach the price through SettingsService.resolve_finishes() at four edges — the two quoting endpoints, the order/reprice pair and the intake sweep. FINISH_CATALOGUE stays as the code default beneath them, which is what «Сбросить» returns to.

Three things about it are decisions rather than unfinished work, and each would otherwise be re-litigated. The code set is closed to the four the storefront offers: apps/web/src/config.ts hardcodes them, so a fifth row would be a finish the farm had priced and no customer could choose — which is why the kit's «Добавить операцию» is not ported and the server answers a fifth code with error.settings.finish_code_unknown. «На см² поверхности» is not ported because surface area does not reach the checkout — the quote context emits volume_cm3 and bounding_box_mm and no surface_area_mm2, CheckoutPage.tsx sends no mesh — so the term would price at the configurator and not on the order, and pricing an unmeasured mesh at 0 cm² is ADR-0007's forbidden move. «Доступна» is not ported because FinishStep.tsx renders a hardcoded list before any quote, so an honest switch needs a public read of the catalogue: a new endpoint and a regenerated client, which is the named follow-up slice.

RateSnapshot deliberately did not gain a finishes field: snapshot_id hashes sorted(self.__slots__), so one new field changes the hash of every snapshot rebuilt from a stored row and CachedPlates._rates_for would refuse every already-paid order at once. ADR-0020's new amendment says what is recoverable instead — the pinned Breakdown, and the applied per-unit rate on Basis.rate.

The store's first slice is on issue-35-store-cells-and-movement-ledger, and no test in it has been run. #35 as filed is the whole warehouse; this branch builds one half of it — a lot has a cell address, and every move of a lot appends a row nothing can overwrite. Three tables (storage_zones, storage_cells, material_movements), one column (material_lots.cell_id), migration 0024, /store/*, and the console's StorePage/CellDetail. mount_lot and unmount_lot now write a movement before they overwrite the five location columns, which is the whole leverage argument of the issue: those columns are the only place the previous position exists. Deliberately out and still owed by #35: turnover, dead stock in money, stocktake, drying state, and the three non-filament purchasable classes. docs/DESIGN-KIT.md §2.4 was rewritten to say exactly that rather than deleted.

What was verified there, and what was not. The branch was built in an isolated worktree with no .venv and no node_modules, alongside eight other agents sharing one printorian_test database and one editable install pointing at the main tree. So pytest, lint-imports, every alembic command and every npm script were not run — a pytest run from that worktree imports the main tree's source and reports about code it did not build. What did run, each separately and each exit=0: ruff check, ruff format --check, mypy --strict, check_context_isolation.py, check_file_length.py. The four doc-drift gates and the metadata-only halves of test_schema_contracts.py and test_referential_integrity.py were additionally run as plain functions with the worktree ahead of the editable install on sys.path, which opens no database — and test_every_foreign_key_is_indexed caught two missing indexes that way. The sixteen new tests are written and unproven; the serial verification pass is where they first run.

They have since been run, in the main tree, and they pass. All six backend gates exit=0, lint-imports included — 6 contracts kept, which is the one gate the worktree could not answer. 0024 goes up, alembic check finds no new operations, downgrade -1 comes back clean and up again. The whole backend suite is 1 406 passed, 8 skipped, exit=0. Two things had to be fixed, both frontend and both the cost of never having compiled the files: StorePage.test.tsx read map.zones[0].cells[0], which noUncheckedIndexedAccess will not let a test assume is populated, and both store screens called load() straight from a useEffect body, which react-hooks/set-state-in-effect rejects — the async wrapper MaterialsPage already uses is the fix. npm run typecheck, lint and test (290 tests, 30 files) are exit=0 after those two commits. Nothing in the backend needed changing, and no test was weakened to make anything green.

Two failures in that pass were not this branch's: a procurement/ directory holding nothing but stale __pycache__, and four procurement tables (suppliers, purchase_orders, purchase_order_lines, purchase_receipts) still standing in printorian_test — both left by an earlier branch's run. test_the_contexts_said_to_own_no_tables_own_none counts context directories, so the empty one read as a context that lost its tables; and drop_all cannot drop material_lots while a foreign key from a table outside Base.metadata points at it. Both were cleaned off the machine, not worked around. It is worth knowing that clean_database has no defence against a leftover table from another branch — the next agent to hit it will see the same misleading wall of setup errors.

3. What is actually next

Open work lives in GitHub issues, grouped by milestone and described in docs/WORKFLOW.md. Take one from a milestone rather than from this section. Where an issue and a document disagree, the issue is right.

4. The first real print — started, and blocked on hardware

printorian.drivers.bambu has still never talked to a printer. Phase 4's exit criterion was demonstrated with the mock driver, and tools/bambu_spike.py proved the protocol in standalone code importing nothing from Printorian. The product's own path between the two is the largest unproven assumption in the system, and the one that could still say the design is wrong.

What exists now so that proving it is one command rather than a project:

  • tests/contract/test_bambu_hardware.py — the same contract the mock driver is held to, run against a real machine. Credentials come from the git-ignored printers.local.toml; without it every test skips, so CI is untouched and nobody needs a printer to work on the rest of the system. Read-only by default — connect, capabilities, telemetry, and that wrong credentials are refused rather than answered plausibly. The half that physically prints is behind a second opt-in, because a suite that can start a print by accident is one nobody runs.
  • docs/RUNBOOK-FIRST-PRINT.md — the procedure, in order, with what each failure means. Step 1 separates "the network or the credentials" from "our code", which are indistinguishable from a distance and have completely different fixes.

This needs you and a printer. Nothing further can be verified without one.

5. Needs a person, not an agent

  • Dismiss the code-scanning alert on backend/tools/bambu_spike.py as "Won't fix". py/bind-socket-all-network-interfaces on discover's sock.bind(("", port)): a UDP socket bound to one address does not receive broadcasts on Linux, and broadcasts are all discovery listens for, so binding narrower breaks the tool rather than securing it. It is a hand-run listener that prints what it hears for --timeout seconds. Dismissing needs the Security tab; nothing an agent here can reach writes to it.
  • farm_stats.on_time_percent measures dispatch and calls it arrival. backend/printorian/api/farm_stats.py:53 documents it as "Share of delivered orders that arrived by the date promised"; the query at :117-118 compares Order.shipped_at <= Order.promised_at, which is when the parcel left. grep -rn 'delivered_at' backend/printorian returns nothing, so arrival is recorded nowhere at all. That is an ADR-0007 overstatement standing in the tree today, independent of the zone work, and it has two possible fixes — correct the docstring now, or add a delivered_at column with the shipment record later. Which one is right is a product decision, and it wants its own type:bug issue rather than being folded into somebody else's diff. Editing the tracker is not an agent's to do.
  • A cancelled job keeps its wait-list row, and that is a second defect on a different path — it needs an issue. Measured, not reasoned about: a probe run against the fixed tree wait-listed a job, cancelled it, and queue_position still answered job_status=cancelled with reason='waitlist.awaiting_capacity', position=1 and a predicted start. ProductionService.cancel does not touch wait_list_entries, and a cancelled job is never claimed by another planning pass, so unlike the defect §1 fixes this row is stale permanently and keeps inflating other customers' positions. It was left out deliberately: the fix asked for was scoped to _refresh_wait_list, and folding an unrelated behaviour change into it is what WORKFLOW §3 means by one issue closing on one demonstrated criterion. The shape of the fix is one call to wait_list.discard(db, job_ids=[job.id]) in cancel, plus the test that fails without it. Editing the tracker is not an agent's to do.
  • Dev account passwords have drifted from the docs. DEVELOPMENT.md lists floor@printorian.example / shop-floor-pass-1; the stored hash does not match. boss@printorian.example was reset to the documented owner-pass-12345 and works. Also: floor@ is engineer in the database, operator in the docs — a role is an authorization decision, so it was left alone.
  • Stage 2 is now half done by hand, and that is the argument for Ansible. A farm host exists and works (§1), but every step of getting there was manual and is recorded nowhere executable. The exit criterion is "a wiped machine reaches a running production farm from ansible-playbook plus one SOPS key", and the cheapest time to write that role is now, against a host whose correct end state is known and reproducible. Ansible cannot run on a Windows control node, so it needs WSL or a container.
  • Stage 3 still needs hardware nobody has. "The storefront serves over HTTPS on the real domain" needs a VPS, DNS and an object-storage bucket. Until then there is no customer-facing site anywhere — only the console, on the LAN.
  • Off-site backup is still the largest single gap. Every copy of the farm's data is on one machine. §1's compression buys time on the local disk; it does nothing about fire, theft or that VM being deleted.
  • The storefront ground colour (§2) — keep the lift or take Harvester's void.
  • ruff format --check was failing on main before this run, on a migration committed as raw alembic output. Fixed in passing; worth knowing the gate can drift without anyone noticing, because a red CI on main is easy to live with.
  • #47 needs amending before it closes, and the drift record needs deciding. Its "Done when" opens with "the 66 tests build real parents" and "foreign keys are enforced for the whole fast suite", both of which ADR-0021 and tests/factories.py had already made true; only the third clause was the work (§1). WORKFLOW §3 says a "Done when" that turned out to be the wrong criterion is amended in the issue before closing, so the record says what was delivered — and WORKFLOW §5 says the stale document gets its own drift issue rather than a silent close. The correction to DATABASE-REVIEW §3 and §10 landed with the same pull request, so what is left is a filing decision: amend #47, and decide whether a drift issue closed by its own merge is still worth opening for the record. Editing the tracker is not an agent's to do.

6. If you are picking up mid-flight

Two things this repository will not tell you and that cost an afternoon each:

  1. Check git status first. Agent work has been interrupted mid-write more than once, leaving a tree that compiles, passes lint, and has no tests for the part that matters. All six gates passed on a change whose only irreversible path was untested.
  2. Do not trust an agent's report of its own verification. Reproduce it. Two separate reports of "all gates green" were produced by runs where the gate had not been executed at all.
  3. The repository moved. origin is now git@github.com:iritur/printorian.git; the former home, dimmus/printorian, is still reachable as the remote dimmus and still holds the old Dependabot branches. Nothing was deleted there — if a clone or a CI job on some machine still fetches dimmus, it will keep working and will quietly fall behind, which is the failure mode to watch for. Push over SSH: the HTTPS credential helper has nothing cached for GitHub, and core.sshCommand points the key at C:/gitssh/ because a Cyrillic home directory defeats Git's bundled ssh.