One application for running several manufacturing plants: it records the work that happens on the floor and reports the numbers that work produces.
It replaces two earlier applications — a people directory and a maintenance
system — which become Modules inside it rather than separate deployments.
The vocabulary is defined in CONTEXT.md and the decisions
behind the shape of it in docs/adr/.
Flutter Web frontend, Express API, PostgreSQL. Production ("VIProd") runs the API and frontend on LXC CT102, with PostgreSQL self-hosted on LXC CT100 and sign-in by the Platform's own passwords (ADR-0051). The code also supports a database hosted elsewhere — the home LXC 150 deployment keeps its PostgreSQL with a hosted provider — but identity is local in every deployment: the Platform's own passwords, never a hosted identity provider. The API runs as a container on a self-hosted LXC behind a reverse proxy; the frontend is served from the same hostname, so the browser sees one origin and there is no CORS anywhere in this repository.
lean-platform/
├── frontend/ Flutter web app
├── backend/ Express API
│ ├── src/platform/ shared foundation: database, logging, health
│ └── src/modules/ People, then Maintenance, then the Tier Board
├── dev/ Local-only edge router used by docker compose
├── docs/adr/ Decision records
└── docker-compose.yml
The Flutter version is pinned in two places that must agree: FLUTTER_VERSION
in .github/workflows/ci.yml and the base image in frontend/Dockerfile. If
they drift, CI passes against a toolchain that never builds the image.
frontend/pubspec.lock pins what that toolchain resolves.
docker compose up -d --buildEvery variable has a local default, so that is the whole thing on a clean
checkout. Copy .env.example to .env to override them.
Then open http://localhost:3002. The edge container mirrors production
routing: /api/* goes to the backend, everything else to the Flutter app.
Host ports sit one above maintenance-management's, which sit one above
employee-management's. All three are routinely run side by side.
pgAdmin, for browsing the local Postgres directly, is at http://localhost:5052 — local-development-only, with the local Postgres connection already pre-registered.
docker compose up alone leaves the schema unmigrated, since compose has no
equivalent of the migration step deploy/deploy.sh runs before starting
production. ./scripts/review.sh does the equivalent locally — build, wait for
Postgres, migrate, seed the Demo Plant, wait for the app to answer — so a
reviewer gets one command that ends at a stack that is actually usable, at
http://localhost:3002, rather than a backend erroring against an empty
database. ./scripts/review.sh help lists down, reset, logs, status,
seed and grant-account alongside the default up.
The seed it applies is dev/seed-demo.sql — a versioned, idempotent demo
dataset: a Demo Plant with Org Units, Employees, Assets, a parts catalogue and
stock, meters and PM schedules, work orders and their cost, and the plant's
shifts and production. ./scripts/review.sh seed re-applies it on demand
without rebuilding. An Account only gains a Grant after signing in, so
./scripts/review.sh grant-account <email> <org-unit-code> [--write] gives a
signed-in Account a Grant on a Demo Org Unit — the thing that makes the
Org-Unit-scoped behaviour visible.
The seed inserts no Account, deliberately — an Account is the stack's way in,
not plant data — and signing in creates none (issue #480), so up provisions
one demo administrator itself, then signs in as it to prove the password
verifies, and prints the credential pair it created — admin@demo.local with
the password shown in that block, both overridable in .env. It is
local-development furniture and is never the way into a deployment, where the
first administrator's password is set by hand (dev/set-a-password.mjs,
below).
The Platform has one test seam: HTTP against the running API, with a real database. A test drives the app the way a client does and asserts on what a client can observe. Reaching into a route handler or a service to check that a function was called tests the implementation, not the behaviour — and the things that actually break, a route that was never mounted or a pool that cannot reach Postgres, are invisible from below HTTP.
test/integration/schema.test.js and test/integration/views.test.js are a
named exception: they assert the baseline migration directly against Postgres
rather than over HTTP, because there are no endpoints over most of that schema
yet — they arrive with the People, Maintenance and Tier Board Modules. Once a
Module owns a table, its behaviour belongs in an HTTP-level test instead.
The integration tier needs the baseline migration applied first; the API's own health checks do not touch the schema, but these two files do.
test:integration runs its files with --test-concurrency=1: several files
share the same tables in the same real database (app_users for
accounts.test.js, plant.test.js and approval.test.js, for instance), and at
least one of them needs sole ownership of its table for the length of its own
run — node --test's default is to run separate files in parallel, which
raced two files' own cleanup against each other before this flag was added.
cd backend
# Needs no database: shutdown, and the Module boundary rule.
npm test
# Needs a database with the baseline migration applied.
DATABASE_URL=postgresql://platform:localdev@127.0.0.1:5434/platform npm run migrate
# Drives the API over HTTP, and — for the schema/views exception above —
# queries Postgres directly.
DATABASE_URL=postgresql://platform:localdev@127.0.0.1:5434/platform npm run test:integrationNode's built-in test runner, and no test framework. The backend carries no development dependencies, matching its predecessors.
Push to main and CI builds both images, publishes them to GHCR tagged with the
commit, and a self-hosted runner on the LXC deploys them (on VIProd, CT102). Nothing inbound is
exposed: the runner polls GitHub outbound, so there is no SSH key in this
repository and no port open on the box.
deploy/
├── compose.yml the Platform: backend and frontend, from GHCR
├── caddy.compose.yml the reverse proxy, deployed once and left alone
├── Caddyfile one hostname, /api split from everything else
└── deploy.sh deploys a tag, and puts the old one back if it fails
A failed deploy restores the previous version automatically. The k3s
platform got that from Helm's --atomic; Compose has no equivalent, so
deploy.sh does it by hand: it pulls before touching anything running, starts
the new tag, waits for every container to report healthy, and on failure brings
the previous tag back. The rollback passes --pull never — the previous images
are already on the box, and an unreachable registry is one of the things that
makes a deploy fail in the first place.
This is a replace-then-check, not a blue/green swap: the new containers take over first, so there is a window of up to the health timeout during which the site is down before the old version returns. Removing that window needs two stacks and a proxy switch, which is more machinery than the plant needs today.
Migrations run as their own step, before anything running is touched.
After the pull (if any — see below), deploy.sh runs a one-off container from
the new backend image — npm run migrate against DATABASE_URL — before it
starts a single new container. This is what replaces the k3s platform's
pre-upgrade migration Job. A migration failure dies right there: no
container has been started or stopped, and whatever was serving before this
run is still serving exactly as it was.
This step runs unconditionally, on every invocation, including --no-pull.
That flag means "the images are already on the box", not "this is a
rollback" — a re-deploy of a tag that happens to be local already (after a
runner wipe, an air-gapped push, debugging by hand on the box) still needs its
schema current before it starts. node-pg-migrate up against an
already-current schema is a no-op, so running it on every invocation costs one
extra container start and nothing more.
Because migrations land before the new code does, there is a window — this step plus however long the new containers take to report healthy — during which the old version runs against the new schema. Every migration must therefore be safe for the version it is replacing to run against: add a column and start filling it in one deploy, drop what nothing reads any more only in a later deploy once nothing depends on it. Expand now, contract later — this applies to every migration written after this one, not just the baseline.
A failed deploy rolls the image back, never the schema
(ADR-0007).
There is no node-pg-migrate down anywhere in this script, and there is not
meant to be one: an automatic schema rollback run under deploy-failure pressure
is more dangerous than the forward state it would undo — it can drop a column
or table the previous version's own queries still reference. The
expand/contract rule above is what makes an image-only rollback safe rather
than reckless: because a migration is never a breaking change for the version
it replaces, the previous image can simply keep serving the migrated schema,
which is exactly what rollback asks it to do. Migrations are forward-only; the
only way back from a bad one is a further migration that fixes it forward.
Rollback itself never re-runs the migration step, because it never re-invokes
deploy.sh at all — it is inline code at the bottom of the same run that
restores the previous image directly and returns.
Where production runs. VIProd: API and frontend on LXC CT102, from
deploy/compose.yml; PostgreSQL on LXC CT100. The deploy gets DATABASE_URL
from the repository secret of that name, which release.yml passes to
deploy/deploy.sh as an environment variable; the runner does not read a file
on the box for it. .env.production is the gitignored file
scripts/setup-deployment.sh writes, and deploy.sh's error message points at
it; whether a copy lives at /opt/lean-platform/.env.production on CT102 is
not recorded (/opt/lean-platform/ is known to hold .deployed-tag). Not
recorded in this repository: CT100's PostgreSQL major version, its backups,
and its address.
The deploy also needs MTU_DATABASE_URL, the second connection string (the
KPI Module, ADR-0055). It is a repository secret of the same name, passed by
release.yml alongside DATABASE_URL. It names database mtu on CT100 as
role lean_app, which may SELECT the catalogue and INSERT Targets and reviews
only: no UPDATE and no DELETE, so a compromised application token cannot
rewrite history, and the worst it buys is a bad Target or review row, both
visible in the history views. The secret's own copy on CT100 is
/root/.mtu-kpi/lean_app.env (mode 600). deploy.sh refuses to run without
it and deploy/compose.yml requires it. When it is missing from a running
API, the API still boots and everything else is unaffected: /api/kpi/*
answers 503 with error kpi_catalogue_unavailable, and GET /api/health
reports kpi_catalogue: "unconfigured".
Nightly maintenance runs inside the database, not on the LXC.
sqdcp_maintenance() — defined in the baseline, scheduled by
migrations/1756000000001_schedule-maintenance.js — creates the next three
months of partitions for measurements and audit_log, then refreshes
mv_daily_oee. pg_cron runs it at 03:17 UTC every day, inside the database itself, where
pg_cron is installed (a hosted Postgres may have it; pg_cron on CT100: not
recorded - check it, see below); there is no CronJob or scheduler process on the LXC, because
none of this depends on the API being up. A fixed UTC time is correct here —
neither partition creation nor rollup refresh is Site-specific, unlike shift
and production-day attribution.
If this stops running, nothing looks broken at first. Inserts keep succeeding
into a DEFAULT partition instead of a monthly one, and the tier board keeps
showing whatever mv_daily_oee last held — a wrong number, not a missing one.
The partition gap is the expensive half: once a month's rows have landed in
the default partition, that month can no longer get its own partition
(CREATE TABLE ... PARTITION OF refuses once matching rows already exist
elsewhere), and recovering means moving rows by hand. Check for it with:
SELECT status, return_message, start_time, end_time
FROM cron.job_run_details
WHERE jobid = (SELECT jobid FROM cron.job WHERE jobname = 'sqdcp-maintenance')
ORDER BY start_time DESC
LIMIT 20;A run with status <> 'succeeded', or no run at all for last night, means the
board is stale and partitions may be running out. On CT100 the query only
works if pg_cron is installed there, which is not recorded; if the cron
schema is missing, nothing is scheduling the job and it needs another scheduler.
The migration that schedules this only installs pg_cron where
pg_available_extensions says it exists — a hosted Postgres may have it, CT100 is
not recorded, stock
postgres:17-alpine (CI, local docker compose) does not — and says so with
a RAISE NOTICE where it skips. CI cannot exercise the schedule itself for
that reason, so it calls sqdcp_maintenance() directly instead (see the
"Maintenance smoke test" step), which is what actually catches a
schema-qualification or partition-window regression before it reaches a
database that would have run it nightly for months before anyone noticed.
Row Level Security is enabled on every table, with no policies, and a
dedicated read-only role reads through it.
(ADR-0004). Two
clients reach this database: the API, which connects as postgres —
unaffected by deny-all RLS because it owns every table in this schema and
holds rolbypassrls = true, not because of any "service role" (a hosted
platform's service_role is NOLOGIN; it is a PostgREST-level JWT claim, not a
Postgres login role a DATABASE_URL could ever connect as) — and owns every
write; and Power BI, over powerbi_reader, created by
migrations/1756000000002_deny-all-rls.js, which can SELECT everywhere in
public and nothing more. See
docs/power-bi-connection.md for the
connection string, the username format, and where the password lives (not
here).
The proxy runs as its own Compose project, platform-edge. That is not
cosmetic: the application deploy passes --remove-orphans, which deletes any
container in its project that its compose file does not define — so a shared
project name means the first deploy removes TLS termination.
Images are tagged sha-<commit>, never latest. A floating tag would make a
rollback meaningless, because the tag it rolls back to may since have moved.
The deploy carries no authentication settings. Sign-in is the Platform's
own passwords in PostgreSQL (ADR-0051), so there is no identity provider to
configure and no door to switch: GET /api/auth/mode always answers
local. Nothing about sign-in belongs in a repository variable, and the
deploy log's "Report what is serving" step has only the image tag to report.
The first administrator's password. Nobody can sign in
until an Account has a password, and the route that sets one (#270) needs a
signed-in administrator, so the first one is set by hand, once, by a person
at the deployment's database. On VIProd that is CT100's PostgreSQL, so
DATABASE_URL must be CT100's connection string (the same value as the
repository secret DATABASE_URL), and the script must run from a machine
that can reach CT100:
export DATABASE_URL=postgresql://... # CT100's Postgres on VIProd
read -s -p 'New password: ' PW && printf '%s' "$PW" | node dev/set-a-password.mjs admin@example.com
unset PWThe password is read from stdin only and stored as temporary
(must_change_password); #270's change flow replaces it afterwards, and until
it has, the API refuses every route except GET /api/people/me and the change
itself (403 { code: "MUST_CHANGE_PASSWORD" }, middleware.js). The script
refuses to overwrite an existing password unless run with --force, and
prints only the email and the time.
Two separate steps, in this order, for everyone but an administrator. A non-admin Account signs in only when both are true: (1) it is linked to an active Employee, and (2) it has a password. Linking is not the script's job and setting a password does not link; do the link first (the Approval queue or the Account's Employee dialog, both need a signed-in administrator), then set the password. A password on an unlinked non-admin still answers 401, which is the rule working, not the script failing; the script prints a warning in that case.
An administrator needs only the password (ADR-0045). An Account with role
admin signs in without an Employee link, so the first administrator is just
the command above. It must still be enabled and the password must match. Its
identity is local-account:<id>, assigned at first sign-in.
First-time setup of a deployment is walked through by
scripts/setup-deployment.sh: it creates the hosted PostgreSQL database project
first (ADR-0002),
then DNS, Docker, certificates and the runner. It has no stage for self-hosted
PostgreSQL or the local-password configuration; VIProd's CT100 database setup is
not scripted in this repository. The hosted project is a database host only —
its own auth service is unused, and sign-in is the Platform's local passwords
on every deployment.
A Module is a functional area that records real work and produces the measurements KPIs are calculated from. Modules are code seams, not data seams (ADR-0006): they share one schema and one process, and a Module never reaches into another Module's internals — it calls that Module's service.
npm run lint enforces this rather than leaving it to review. Shared code the
Modules stand on lives in src/platform and is not a Module; the foundation
must not depend on what is built on it.
One Module reaches past the one-database rule on purpose. The KPI catalogue
Module (src/modules/kpi) manages the MTU line's KPIs, their Targets and the
daily Review, which live in a second PostgreSQL database, mtu, shared with
Power BI. The Platform connects to it through its own pool
(src/platform/mtu-db.js, MTU_DATABASE_URL) as a role that can read it and
append to it; with the variable unset, /api/kpi/* answers 503 and the rest of
the API is unaffected
(ADR-0055).
The timed assessment belongs to People (src/modules/people), which already
owns the Org Unit tree it is filed on
(ADR-0068,
issue #588):
- The Question bank (
assessment-questions.js,assessment-question-routes.js): five routes under/api/people/assessment-questionslist a process's bank, raise a Question, paste a block of them at once (all-or-nothing), correct one and retire one. - Assessments and Attempts (
assessments.js,assessment-routes.js): an Assessment is created as a draft, assigned all-or-nothing to a group (one Attempt per Employee), and closed; an Attempt can be cancelled before it starts, and a retake follows a final one. The paper is drawn from the bank and frozen when the Attempt starts, never at creation, and a thin bank is a refusal, not a short paper. - Marking (
assessment-marking.js): the Marker's queue, the marked paper, the mark and the result. A score is shown only once the paper is marked. - The floor sitting (
floor-assessment-routes.js,assessment-sittings.js): an Employee with no Account identifies at the shared floor device and sits their own Attempt under/api/maintenance/floor, holding a per-Attempt sitting token. - Timing, with no cron.
started_atanddeadline_atcome from the database'snow(); no route reads a client's time. The two time-caused transitions,in_progress → submitted(submitted_late) at the deadline andassigned → expiredonce the Site's local date passesdue_on, are applied lazily byassessment-sweep.js. Each is a status-guardedUPDATE … WHERE, scoped to one Attempt, Employee or Assessment and committed before every Attempt read and Answer write, so a refusal cannot undo it and two racing reads finalise once. There is no cron, background worker or timer. The client's countdown is display only.
One door: the Platform's own passwords. POST /api/auth/login takes an email
and a password held in this deployment's PostgreSQL (account_credentials,
ADR-0022, ADR-0045) and answers an opaque session token, stored hashed in
account_sessions; the Flutter app sends that token as a bearer token on every
request. GET /api/auth/mode answers {"password":"local"} as an
unauthenticated constant, for any client that asks the question before it holds
a token. There is no hosted identity provider and no switch
between doors — issue #480 deleted that branch, so production
(ADR-0051)
runs the same one everywhere.
backend/src/modules/people/middleware.js resolves the token to an Account
(app_users.external_subject). The Account always already exists: POST /api/auth/login looks the email up in app_users and needs a row that holds a
credential, and answers 401 with Email or password is not recognised. for
anything else, inserting nothing — there is no sign-up route and no first
sign-in is exempted (issue #480). An Account must exist, with a password,
before anyone can sign in to it; the deployment's first administrator is an
app_users row a person inserts and then sets a password on by hand, exactly
as The first administrator's password above describes.
Every endpoint except an
Account's own status (GET /api/people/me) refuses an inactive Account with a
403 and a status the Flutter app can distinguish from a real failure —
"pending_approval" for an Account nobody has decided about yet,
"rejected" for one an administrator turned away, and "deactivated" for one
that was approved and later deactivated (backend/src/modules/people/ middleware.js's statusFor). Approval itself
— an administrator admitting an Account, setting its role and granting its
Org Units, or rejecting or deactivating one — and role/Org Unit scope
enforcement on every other route are issue #8. See issues #6 and #8 and
CONTEXT.md's Account/Approval entries.
Signing in needs no configuration beyond DATABASE_URL: there is no key to
set, and the integration suite mints real sessions
(backend/test/helpers/session.js) rather than depending on an external
identity service.
This is the walking skeleton, plus sign-in, plus Approval. It proves the path from browser to database and lets a person sign in, wait for Approval, and — once an administrator approves them — act within the Org Units they were granted (issue #8).
- Roboto is bundled; the engine's glyph fallback is not.
frontend/assets/fontsships Roboto with the app, served from its own origin, so a private deployment with no egress still renders every string this interface currently shows. What remains unbundled is the Flutter engine's own fallback base URL,fonts.gstatic.com, used only for glyphs outside the Roboto family — it affects nothing the interface currently renders.