Coding Standards & Engineering Conventions — Empire Teas CRM
Status: confirmed as-is by the team, 2026-08-19 (drafted 2026-08-18, Tharinda; §§7–9 tooling/logging/documentation added 2026-08-19; confirmed ahead of mobilisation week; §7.7 secret-scanning layer revised 2026-08-20 — gitleaks in the fast lane, not the paid GitHub add-on; 2026-08-20 — §0.1 added as a second prime directive, never show a user something that isn’t true, with its four failure shapes worked out: §3.1 build-time-baked data, §3.2 the six loading/empty/error states and their copy rules, §3.3 the server owns every number that matters, §2 one authoritative predicate per visibility or temporal rule, §5 fixtures structurally unreachable, enforced at three levels (§7.2 ArchUnit, §7.3 dependency-cruiser, §7.6 artifact grep), §6.10 the guarantee demonstrated before the first feature WI; §2 Identity & uniqueness — derived state is never authoritative: DB-allocated ids, sequence/counter-row allocators for reference numbers, constraint-backed uniqueness with violations translated,
COUNT/MAX-derived identifiers banned; §5.1 added 2026-08-20 — the team is mixed macOS/Windows, so line endings, path handling, and shell portability are repo-decided, not machine-decided; §2.1–2.2 added 2026-08-20 — Lombok annotation policy (sanctioned set, rejected set,lombok.configenforcing the rejections) and Apache Commons Lang3 for boundary null-safety) — binding for every WI. Copied into each app repo’s CLAUDE.md (condensed) at Foundation slice 1 (repo CLAUDE.md creation) so implementer agents load it automatically. Condensation discipline (2026-08-29): the repo copy carries each rule as its imperative plus a§pointer only — rationale never duplicates out of this document; a rule change updates both in the same change, and this document wins on disagreement. Revised 2026-11-13, second change (lead decision): §6.8 —forge-et-be’sSlow lanecap rises from 60 to 90 minutes. It now runs only when someone asks CI for the suite, and the suite took 47 minutes on 2026-11-11, growing 5–6 minutes a week (forge-et-be#420). Revised 2026-11-13 (lead decision,.forge/design/harness/test-run-cost.mdN-5): §7.1 — theSlow laneno longer runs on a Dependabot PR; a delivery-team member’s local record on its final head setsTest record, as on any other PR. Dependabot PRs’ Slow lanes took about 560 runner minutes in the 30 days to 2026-11-12. Revised 2026-11-12, second change (measured, no cap changed): §6.8 — two test JVMs (build.gradle’set.testForks) do not fitforge-et-be’sSlow lanerunner, 2 processors and 7.9 GB, so CI keeps one; and a dependency bump inbuild.gradleno longer makes Spotless check every file; a change to what Spotless does, or tobuild.gradlebeyond versions and comments, still does (scripts/spotless-scope.py). Both forge-et-be#411. Revised 2026-11-12 (lead decision): §6.8 —forge-et-fe’sSlow lanecap rises from 30 to 45 minutes;forge-et-pwa’s stays at 30. Its suite takes 24–26 minutes, and a Dependabot run on forge-et-fe#500 was cancelled at 30 (forge-et-fe#511). Revised 2026-11-11 (lead decision): §6.8 —forge-et-be’sFast lanecap rises from 15 to 25 minutes; the frontends’ stay at 15. A change to the build files makes Spotless check every Groovy file, and forge-et-be#407 (Gradle 9.9, Spotless 8.11) was cancelled at 15m4s with every check passed (forge-et-be#408). Revised 2026-11-03 (lead decision,.forge/design/harness/test-run-cost.mdN-5): §7.1 — a suite runs in one place: theSlow laneno longer runs on a push torelease/*, whose PR’s local record now runs every test; the scheduled run is weekly and keeps only theFast lane, to refreshmain’s caches; an on-demand run onmaintakes-f tests=falsefor theFast lanealone (on any other branch the suite still runs, so the input cannot clear a failedSlow laneon a Dependabot PR). Revised 2026-10-27 (lead decision at F38-i’s spec,architecture.mdRev 81): §7.1 — the “Release tag” row: production, like UAT, gets the smoke run by hand after the deploys; no browser tier runs insidedeploy-prod. Revised 2026-10-27 (lead decision,.forge/design/harness/test-run-cost.mdN-3): §7.1 — theSlow laneno longer runs on the nightly schedule; the scheduled run keeps only theFast laneand Trivy (AD #38), and the nightly full run of all three app repos runs on the lead’s Mac. §9’s “nightly full E2E run” row now names CI. Revised 2026-10-26 (harness review, corrections to match what is built and decided): §5 — theet.aiexample now shows the five features and two price rowsforge-et-be’sapplication.ymlholds, where it showed one feature and one price; §7.1 — the “Release tag” row follows AD-O-11 as revised byarchitecture.mdRev 72 (a smoke run by hand on UAT; the full browser suite insidedeploy-prodonly). Revised 2026-10-22 (lead decision): §6.8 —forge-et-be’sSlow lanecap rises from 30 to 60 minutes; the frontends’ stay at 30. Every nightly run onmainfrom 2026-10-16 hit the 30-minute cap and was cancelled (forge-et-be#299). Revised 2026-10-20 (F38-d spec Rev 3, AD #38 restated): §6.8 —forge-et-be’s devdeployjob’s 30-minute exception is withdrawn with the stability wait; §7 tooling table — the Trivy row says the dev deploy runs no scan. Revised 2026-10-12, second change (lead decisions): §7.1 — the frontends run their tests in aSlow lanejob of their own, as the backend does, and the local record becomes a requiredTest recordcommit status in all three app repos, set once per PR after the last push instead of being checked by a Fast-lane step before every push; §6.8 — everySlow laneis capped at 30 minutes (the backend’s was 20; its nightly run hit that cap on 2026-10-10) and everyFast laneat 15. Why and how:git-conventions.md § The test suites run locally, and the PR records them.Revised 2026-10-28 (AD #40, F38-i spec Rev 1): §5 — a setting that is not secret, production’s seeded-administrator email and the Entra tenant ID, client ID and certificate included, is a plain task-definition value; only a secret comes through a
secretsreference. Revised 2026-10-12 (GitHub Actions minutes, lead decision): §7.1 — the frontends’ unit and component tests leave PR CI as the backend’s suite did: developers run them locally and record them on the PR (pnpm test:record), the fast lane’sTest recordstep checks the record, and CI runs them nightly onmain, onrelease/*, on Dependabot PRs and on demand; §6.8 — the frontends’ Fast-lane cap rises to 30 minutes for those runs. Why and how:git-conventions.md § The test suites run locally, and the PR records them. Revised 2026-10-05 (second project audit, lead decisions): §3 — API types are hand-written per feature’s wire module (no generated client exists); §6.8 — the Fast lanes’ 15-minute cap is recorded; §7.5 — the frontends’ dead-code error comes fromtsc, not Biome; §8.5 —Updatedis allowed for a record’s general edit. Revised 2026-09-24 (AD #34, AD #35, AD #36): §2 Persistence gains two rules —created_at/modified_at(andcreated_by/modified_bywhere a person acts) on every table, with the audit event written in the same transaction; and per-environment seed values as Flyway placeholders, production’s from Secrets Manager. §2’s role-scoping corollary names the oneauth.accessvisibility rule for lists and per-record checks. §3 locks TanStack Query as the server-state layer from F5-c WI-1.2 and adds the/mere-read rule. §3.4’s example drops the(role, resource, level)tables. The condensed copies in the app repos’CLAUDE.mdowe the same changes (the condensation discipline above). Revised 2026-10-02 (F5-l Reflect, L-115): §2 Persistence gains the drop-one-release-later rule for columns and tables from the first deploy to dev (F38) — a release is a tag; every migration works with the previous release’s code; a rename or type change takes four releases (add and write both; backfill and move the readers; stop writing the old one; drop it). Until dev runs, a drop in the same release is stated in the PR body. The condensed copy inforge-et-be/CLAUDE.mdandforge-et-be/docs/migrations.mdcarry it too. Revised 2026-09-30 (F5-k WI-2.2, AD #34): §3 — the/mere-read rule states what is built (403 by status alone, window focus and document visibility, one request in flight, 401 to the expiry path, any other failure changes nothing), and a new rule wraps every section route inRoutePermissionGuardon its navigation key.forge-et-fe/CLAUDE.mdcarries the condensed copy. Revised 2026-09-29 (F40): §7.1 — the ladder gains “Before a PR is marked ready” forforge-et-feandforge-et-pwa(pnpm e2e:gate, recorded as theBrowser gate:line in the PR description), beside the backend’s local row, and the fast lane’s full run in the two frontends ends with the description check (node scripts/browser-gate.mjs ci-check). The gate’s rules live intest-strategy.md § Browsers & Viewports. Revised 2026-09-28 (GitHub Actions minutes, lead decision): §7.1 — the backend test suite leaves PR CI: developers run it locally and record it on the PR, and CI runs it nightly onmain, onrelease/*, on Dependabot PRs and on demand; the frontends run every check in one Fast-lane job. The wall-clock caps in §6.8 are unchanged. Why and how:git-conventions.md § The backend test suite runs locally. Revised 2026-09-27 (second harness review — corrections, no rule reversed): §1 drops the removedcatalogpackage; §5.1 adopts* text=auto eol=lfand states the Python encoding-pin rule the CI already enforces; §6.8 records the backend Slow lane’s lead-approved 20-minute cap; §7.2 moves doclint to the slow lane, where it runs; the Trivy row states AD #27’s flip trigger; coverage scopes includesrc/ui. Revised 2026-09-26 (F39 WI-2.1, AD #36): §2 Persistence states the standalone security-event exception to the same-transaction rule and adds the raw-write rule (@Modifying/@RawWrite,modified_atset by the statement, the caller records the event) with its two guards; §7.2’s ArchUnit row names the audit write guards.forge-et-be/CLAUDE.mdcarries the condensed copy. Scope: all three app repos (forge-et-be,forge-et-fe,forge-et-pwa). The capture app inherits the TypeScript/React, testing, logging-discipline, and design-token sections; the Spring/Gradle sections apply to the backend only. Complements — never repeats —architecture.md(design),.forge/test-strategy.md(testing),.claude/rules/git-conventions.md(git).
0. The prime directive
Simple, boring, and deletable beats clever. This is a 15-user internal system with a fixed build window and a small team — every abstraction must pay rent now, not in a hypothetical future.
- Rule of two: don’t extract an abstraction until the second real usage exists. (AD #29/#31 retired the former exception — the ten core/domain extension points are no longer pre-paid; a workflow primitive is built and sized by its first consuming feature.)
- YAGNI applies to infrastructure too: no caching layer, no Redis, no GraphQL, no micro-frontends, no event sourcing. The architecture already made these calls; don’t re-litigate them inside a feature branch.
- Prefer deleting code to configuring it. A feature flag, option, or parameter nobody asked for is a liability with a config surface.
- If a reviewer needs the commit message to understand the code, rewrite the code.
0.1 The second prime directive: never show a user something that isn’t true
A CRM’s whole value is that the number on the screen is the number. The moment a screen can show a plausible falsehood, every screen becomes untrustworthy — and unlike a crash, nobody reports it, because nothing looks broken. A rep quotes the fabricated price and finds out at invoicing.
This outranks convenience, first-paint speed, and looking polished. It has four failure shapes, and all four are ordinary things a competent developer does for good reasons:
| Shape | The good intention behind it | Rule |
|---|---|---|
| Fabricated fallback — a hardcoded dataset served when a fetch fails or returns empty | “the page shouldn’t look broken in a demo” | Never. An honest error beats invented data, always. §5 |
| Stale-as-live — a snapshot rendered as though it were current | “faster first paint” | Data is fetched at runtime, never baked. §3.1 |
| Empty/error conflation — “No results” when the truth is “we couldn’t reach the server” | “one code path is simpler” | Three distinct states, three distinct messages. §3.2 |
| Client-computed authority — the UI calculating a number the server owns | “avoid a round-trip” | The server computes, the client displays. §3.3 |
If you cannot show the truth, show that you cannot show the truth. That is a complete, correct, shippable answer, and it is always available.
1. Feature-first placement (both repos — the structure the guards enforce)
AD #31 (2026-09-09, FS-14) collapsed the former backend module split and the former three-package frontend UI split into one Gradle module and one frontend package. The boundary rules and banned-vocabulary rule are gone; a small set of hygiene guards replaces them.
- Backend: one Gradle module, feature-first packages
com.empireteas.<capability>—platform,pricing, then one package per feature as it lands (ls src/main/java/com/empireteaslists them; thecatalogpackage was removed with the product entity at FS-15 — PRD Rev 27). Nocore/tea/appsegments. The layersweb/service/repositorylive inside each package and depend inward only (web → service → repository, ArchUnitLayeringSpec). Feature packages must be free of dependency cycles, andplatformreaches no feature (FeatureSlicesSpec). - Frontend: one package
src/{app, features, ui, lib}.src/uiandsrc/libare leaves (no import intosrc/featuresorsrc/app); a feature imports onlysrc/ui,src/liband its own subtree — never a sibling feature; onlysrc/main.tsxandsrc/appreachsrc/app(dependency-cruiser folder rules — §7.3). Generic surfaces (lists, filters, search, detail shells, import/export) compose registered fields via theFieldRendererregistry — never by naming them. - Placement test for every new class/component: put it in the package/folder of the capability it serves; cross-cutting infrastructure goes in
platform(backend) orsrc/ui/src/lib(frontend). A shared abstraction waits for a second real consumer (rule of two — §0) rather than being pre-built for a hypothetical one. - Never weaken a structural guard to make a deadline: a suppressed layering, feature-cycle,
@NullMarkedor schema-qualifier rule is an architecture change → ASK FIRST. - A source file holds at most 800 code lines, in every app repo (
.forge/design/harness/file-size-check.mdD-1, D-2): a code line is a line that still holds something other than whitespace once comments are removed; blank lines,//and/* */comments and Javadoc do not count, text inside a string, template literal or text block does. Source files are.javaundersrc/main/javainforge-et-be, and non-test.ts/.tsxundersrc(not.d.ts) in the frontends. Before a change takes a file past the limit, split the code by job into new classes or modules in the same feature package or folder — never into a general-purpose helper class, and never intoPartOne/PartTwo. There are no exceptions. A unit test in each app repo enforces it (FileSizeSpecinforge-et-be,src/app/fileSize.test.tsin the frontends) and lists the files still over the limit, each with its planned split; the list only empties: a listed file may not grow, and its count comes down in the PR that shrinks it. Progress:.forge/design/harness/file-size-progress.md. Why: each large file grew one reviewed PR at a time, and no single diff showed it had gone too far.
2. Backend (Java 21 / Spring Boot)
Layering. Controller → Service → Repository, dependencies point inward only. Controllers are thin: bind → validate → delegate → map to DTO. Business rules live in services; repositories contain queries, not logic. No entity leaves the service layer — API DTOs are explicit records with hand-written mappers — small static factories or dedicated *Mapper classes that read like ordinary code. MapStruct is rejected for this project (decided at §0’s prime directive: annotation-processor magic, generated sources, and IDE quirks bought us nothing a fifteen-line explicit mapper doesn’t do better for a team of three — a mapper you can read, grep, and step through beats one you have to decode). The cost is honest boilerplate; the discipline that replaces unmappedTargetPolicy=ERROR is the review question “does this mapper copy every field the DTO declares?” plus the T1 test every non-trivial mapper gets.
Exceptions.
- Throw specific unchecked domain exceptions (
QuoteNotReadyException,PriceWindowClosedException) extending a small shared hierarchy; translate to the API error envelope in one@RestControllerAdvice— never per-controller try/catch. - Never swallow: no empty catch, no
catch (Exception e) { log.warn(...) }that continues as if nothing happened. Catch only where you can act (retry, fallback, translate); otherwise let it propagate. - Don’t use exceptions for expected control flow (“no rows found” on an optional lookup returns
Optional, not a throw). - A domain exception’s message is caller-facing and never contains PII (a buyer’s name, an email address): identifiers go in fields. The API error handler logs refusal messages at WARN, so PII in a message reaches the production log (§8.6).
- Every thrown-to-user error is actionable and safe (no stack traces, SQL, or internal IDs in API responses); the correlation ID links the user-visible error to the full server log.
- Queue consumers: failures throw so SQS redelivers → DLQ; a consumer that catches-and-logs converts at-least-once delivery into silent data loss.
Null-safety.
Optional<T>for genuinely-absent returns on service/repository boundaries; neverOptionalfields or parameters.- Why
Optionaland not a nullable return +!= null? The problem is not the check — it’s knowing the check is needed. A method returningTthat can benullrelies on every caller remembering that fact; the compiler says nothing when one forgets, and the NPE surfaces two layers away at runtime.Optional<T>puts absence in the signature, so the caller cannot get the value without deciding what absence means (orElse,orElseThrow,map). Plain== null/!= nullchecks remain the right tool inside method bodies, on@Nullable-annotated values, and in hot loops —Optionalis a boundary contract, not a blanket replacement for null checks (which is why fields and parameters never use it).
- Why
- JSpecify
@NullMarkedper package (nullable is the exception, annotated) — the nullness checker is Error Prone + NullAway, wired into the build at slice 4 (§7.2). Java package annotations do not cascade to subpackages, so per package means every package gets its ownpackage-info.java; an ArchUnit rule (§7.2) fails the build on any production package missing it, so a new package cannot silently opt out. (Chosen over NullAway’sAnnotatedPackagesbuild flag: source-level JSpecify keeps the semantics visible to the IDE — §7.1’s earliest-point principle — and matches where the ecosystem landed, Spring Framework 7 itself included.) - Validate at the edge: Bean Validation (
@NotNull,@Valid) on DTOs; inside the domain, absence is a modelling decision, not a null check per call site.- A date from a request is range-checked before it reaches SQL.
@DateTimeFormat(iso = DATE)accepts signed years of five or more digits (+9999999-01-01), which PostgreSQL’sdaterefuses, so an unchecked value answers 500 instead of 400. Refuse a year outside 1…9999 as400 VALIDATION_FAILEDwith anOUT_OF_RANGEentry on the parameter, and give the endpoint’s integration spec a row with such a year, sent as a URI variable (?asOf={asOf}) — a literal+in a query string arrives as a space and hides the case. (Lesson L-087;BuyingStandardPriceControlleris the worked example.)
- A date from a request is range-checked before it reaches SQL.
- Never return
nullcollections — empty collections always.
Persistence. Flyway migrations are append-only, one location, plain sequential integer versions (V1, V2, … — FS-14 collapsed the former per-module version bands into one line); every FK indexed; no bidirectional JPA relationships unless genuinely needed; fetch lazily and shape queries per use case (no N+1 — the backend-reviewer checks); effective-dated tables follow the slice-2 temporal conventions (never UPDATE a price row — AD #14).
- Every table carries
created_atandmodified_at, andcreated_by/modified_bywhere a person makes the change (AD #36) — a new table gets them in the migration that creates it; F39 checks the tables already onmainand adds any that are missing. Every write also records itsaudit_eventthrough the one audit service, inside the same transaction as the change (AD #36, F39) — never a separate transaction, never after commit, and never a feature’s own audit table. The one exception: sign-in success, sign-in refusal, sign-out and the end of a deactivated user’s session (auth.session_ended, BUG-094) commit in a transaction of their own (the audit service’s standalone security-event calls), because no data change accompanies them and a refusal throws, which would roll an in-transaction row back (F39 FR-8). - A raw SQL write lives in a repository method marked
@Modifyingor@RawWrite(com.empireteas.platform.persistence.RawWrite) — never aJdbcClient/JdbcTemplate/NamedParameterJdbcTemplateupdate or a bulkexecuteUpdateanywhere else. A rawUPDATEsetsmodified_atitself, andmodified_bywhen a person acts, because JPA auditing never sees it; a rawINSERTmay rely on the column defaults. The class that calls the method — the service that owns the transaction — records the audit event. Enforced (F39 FR-12):AuditWriteGuardSpec(§7.2) fails an unmarked raw write and a caller of a marked method that does not depend on the audit service; the runtime commit check (UnauditedWriteCheck) fails, inlocalandtest, any transaction that wrote an entity through Hibernate and recorded no event other thanjob.message_claimed, and logs one ERROR line in every other profile. A test fixture that must write through Hibernate uses the test suite’sAuditedFixture, or seeds over JDBC. - Per-environment seed values are Flyway placeholders, never literals in a migration. A migration that seeds environment-specific data (the F5-k IT Admin user’s email is the first) reads a placeholder: the
localandtestprofiles supply a test value, cloud profiles supply it from the task definition, and production’s value comes from Secrets Manager through a task-definitionsecretsreference (§5). Flyway refuses a migration whose placeholder has no value, so a missing value fails startup loudly rather than seeding nothing. Never a real person’s email outside production — the non-production value is a test mailbox (crm01@empire.lk). A migration’s placeholder name is a configuration key (CLAUDE.md § ASK FIRST). - Once anything is deployed, a column or table is dropped one release after the code stops reading it. From the first deploy to dev (F38) onwards, release N stops reading and writing the column or table (the field is removed from the JPA entity, since Hibernate selects and inserts every mapped column; a
NOT NULLcolumn without a default loses itsNOT NULLfirst), and release N+1’s migration drops it: in a rolling ECS deploy the previous release’s tasks keep running against the database the new release has just migrated, and they fail on anything it dropped until they are replaced (.forge/lessons.mdL-115). A release is a tagged release (vX.Y.Z, AD #24): dev deploys every merge, but UAT and production deploy tags, so the drop ships in a later tag than the code that stopped reading it. Every migration also works with the previous release’s code: a new column is nullable or has a default, and a constraint the old code could violate is added in a later release. A rename or a type change takes four releases — add the new column or table and write both; backfill the existing rows and move the readers, still writing both; stop writing the old one (remove it from the entity); then drop it. Until dev runs, a drop in the same release as the code change is acceptable, but the PR body states it, so the reviewer sees a decision rather than an oversight. The backend’s working copy of this rule isforge-et-be/docs/migrations.md § Dropping or renaming a column or table.
Transactions. @Transactional on the service method that forms the unit of work — not on controllers, not on repositories; mail/AI/S3 calls stay outside transactions (queue a job instead of holding a connection over I/O).
Identity & uniqueness — the database allocates; the application never counts.
- Surrogate primary keys are DB-allocated (identity column or a DB-generated UUID — FS-2’s base-entity conventions fix the concrete default). Application code never chooses, computes, or predicts a primary key.
- Human-facing reference numbers (quote numbers, sample-round numbers, handoff document numbers) come from a dedicated allocator: a Postgres sequence per series, or a counter row updated atomically inside the issuing transaction. Gaps in a series are normal and accepted — a deleted draft leaves a hole, and that is fine; wanting a gapless-looking series is a report-formatting concern, never an allocation constraint. Chasing gaplessness is exactly what tempts people into the banned pattern below.
- Never derive an identifier from current table state.
COUNT(*) + 1,MAX(id) + 1, row position, “how many exist so far” — all banned, in any form. Two independent ways it breaks: deletion shrinks the count so the next allocation collides with a surviving row, and concurrency breaks it with no deletion at all — two transactions read the same count and allocate the same id. The failure is an insert error on a good day and a silently mis-linked record on a bad one. - This is one instance of a general rule: derived state is never authoritative. Any invariant — identity, uniqueness, “one active row per key”, a running balance — is owned by exactly one enforcing mechanism in the database (identity/sequence, unique or exclusion constraint, the AD #14 effective-dating conventions), never re-derived in application code from whatever the tables currently contain. If the application recomputes it, the recomputation will disagree with the truth under concurrency or after a delete.
- Uniqueness is a constraint, not a lookup. Check-then-insert is a race that loses under concurrent writers; the pre-check may still run for a friendlier error message, but the unique constraint is the enforcement. Treat the violation as an expected domain outcome: catch the specific integrity violation at the service boundary and translate it into the domain error (§ Exceptions) — the user sees “a contact with this email already exists”, never a raw SQL error.
Reuse. Before writing a helper, grep for it. Shared logic promotes to core only via §1’s placement test + rule of two. Utility classes are a smell — prefer methods on the type that owns the data.
One authoritative predicate per visibility or temporal rule. What counts as current, active, published, expired or stale is defined once, server-side, and every caller receives the already-filtered set. Never re-implement the rule client-side as a safety net: two copies drift, and the drift surfaces as one screen disagreeing with another over the same data — a list and the summary above it, filtered differently. This bites hardest where the predicate has a boundary worth arguing about, and this domain is full of those: an effective-dated price is as-of a date, not the newest row (AD #14); a stale deal needs a stated clock (StaleClock, F18/F24); a sample round’s open state is a lifecycle value, not a date comparison. Write the boundary into the spec’s acceptance criteria — >= or >, and which timestamp — because that ambiguity is precisely where the defect lives, and two tickets describing the same rule differently is the smell that it was never settled. Corollary: role-scoped filtering is server-side, always (the (role, permission_key) grants, the reporting line and per-record shares — AD #30, AD #34, AD #35, AD #37) — a client-side filter over an over-broad response is not a display bug, it is a data-exposure bug. Record visibility is the canonical case of this rule: one visibility rule (the reporting tree, the entity’s all key and shares — AD #37), exposed through auth.access, serves both the list queries and the per-record checks (AD #35, built by F5-f). A repository never writes its own owner_id filter — a list that re-implements the rule is how F1-a’s account list came to treat team as own while the per-record check walked the tree. Children (contacts, notes, tasks, attachments, timeline, record-linked email) are filtered through their parent’s reach.
Every request that reaches a handler has passed a permission check — fail closed. Spring Security’s anyRequest().authenticated() lets every signed-in user through, so the permission check (PermissionChecker, naming the key it needs — AD #26) is what stops a request, and a service method that forgets it is open to everyone. PermissionCheckGuard (auth.config) holds this: every PermissionChecker call marks the request (PermissionCheckMarker), and a request that reached an application handler and answered below 400 with no mark is replaced by a 500 naming the handler in the local and test profiles, so the endpoint’s own test fails, and logs one ERROR line in every other profile — the same shape as the audit trail’s UnauditedWriteCheck (AD #36). A refusal of 400 or more is not judged, since request validation can refuse a body before the service runs. A handler that needs no permission (the caller’s own /me, reference vocabularies, sign-in, an OAuth landing, a callback authenticated another way) carries @NoPermissionRequired("<reason>") (platform.access), on the method — on a controller only when the whole class is one exempt thing (a profile-scoped stub, a callback, the error controller), since a class-level entry also exempts every handler added later; adding one is a reviewed change.
No constructor or member exists only for a test. A bean has one constructor, the one Spring calls, and a test builds it through that constructor. What a test replaces is a collaborator the bean takes — a RestClient (bound to MockRestServiceServer in the spec), an SqsAsyncClient, a Supplier of a client — or a configuration value bound from et.* (a timeout). A configuration record has its one canonical constructor; a spec passes null for the components it does not use. No second constructor, no @VisibleForTesting member, no package-private setter. Why: a test-only constructor makes production take a path the tests never run, and a second constructor forces @Autowired onto the real one (project audit E-11.2, which removed them from ContributedTokenRefreshGrant, GraphMailboxProvider, QueueProvisioner and two EtProperties records).
Comments & documentation (both repos).
- A comment states what the code cannot say: a constraint, an invariant, a why (“SQS redelivers — this consumer must be idempotent”), a domain fact. Never what the next line does, and never history or authorship — git carries provenance (
CLAUDE.md § NEVER DO). - A pointer to a spec or plan item names its document —
F38-c FR-1,FS-11 plan Decision 13,AD #36— never a bareFR-D2,AC-4orDecision 6: every spec has its ownFR-D2and every plan its ownDecision 6, so a bare one resolves only for the person who wrote it. A decision in a decomposed feature’s plan names its work item too —F5-c WI-2.2 plan Decision 9, notF5-c Decision 9— because each work-item plan numbers its decisions from 1 (lead’s decision, 2026-10-05). The work item there is part of the document’s name; it is not history. Delivery history stays out of code: no wave or work-item (WI-x.y) narrative of who built what, and no “added in”, “was”, “previously”, “for now until the next wave” — that is git’s and the plan’s. A comment that is true only while a piece of work is in flight carries a tracker id (theTODOrule below). A diff that changes behaviour updates every comment, Javadoc and doc sentence that described the old behaviour, and a removed or renamed name (key, class, profile, workflow step) is grepped for across the repo in the same change. - Javadoc only where a contract needs stating beyond the signature: a package’s published surface (service interfaces, shared configuration types, any seam another package calls through) — units, invariants, nullability nuance, threading. No boilerplate javadoc on controllers, DTOs, or accessors; a javadoc that rephrases the signature is deleted in review. Feature code prefers expressive names + tests over javadoc. The full contract for Javadoc blocks and Spock-spec documentation is §9.
- No commented-out code — delete it; git remembers.
TODOonly with a pointer (an OQ, bug, or tracker id); anonymous TODOs don’t pass review.- Frontend: props are documented by their TypeScript types; JSDoc only on exported hooks/utilities with non-obvious contracts.
2.1 Lombok — the annotations we use, and the ones the build rejects
A small team on a fixed build window should not spend review budget reading generated
accessors. Lombok is adopted for that, and §8.1 already depends on it for @Slf4j. The list below
is short on purpose: every annotation here removes boilerplate a reader would skip anyway, and
every annotation in the rejected list changes behaviour rather than removing typing.
Records first. Java 21 records already do immutable value types, and §2 requires API DTOs be records. Lombok’s job is the two things a record cannot be: a JPA entity and a Spring bean. If a record fits, use a record.
Generated by default; hand-written only where behaviour is customized (made operative
2026-08-29 — the FS-2 substrate shipped hand-written default accessors and assignment-only
constructors against this section, and the divergence went unrecorded). If a member’s body would
match what a sanctioned annotation generates, the annotation is the required form — a hand-written
default-behaviour member is a review finding, not a style choice. The sweep covers every
boilerplate kind: getters, setters, constructors of all arities (no-args, required-args,
all-args), and builders — including the non-obvious forms, e.g. the private X() {}
noninstantiability idiom is @NoArgsConstructor(access = PRIVATE) and a JPA entity’s protected
ctor is @NoArgsConstructor(access = PROTECTED): an access-level tweak is an annotation
attribute, not a reason to hand-write. Hand-write exactly where the default is wrong:
BaseEntity’s proxy-safe equals/hashCode, a constructor that validates or defaults its
inputs, a getter that computes. Beware the access-widening trap when deleting an explicit ctor:
an implicit constructor takes the class’s access, so removing a protected one from a public
class silently publishes it — use the annotation with the access attribute instead.
Javadoc follows the code, never the reverse: when an accessor is generated, its contract prose
(nullability, units, invariants) lives on the field; a member is never hand-written to give a
comment somewhere to live, and no build nudge may steer this — which is why §7.2’s doclint runs
all,-missing (generated members are not in the source the javadoc tool reads, so a missing
check can only nag about code nobody wrote).
Sanctioned:
| Annotation | Where | Note |
|---|---|---|
@Slf4j |
any class that logs | The logging standard (§8.1) — never also a manual LoggerFactory field |
@RequiredArgsConstructor |
Spring beans | This is the DI pattern: private final collaborators, constructor injection, no @Autowired field injection anywhere |
@Getter |
entities, and beans that genuinely expose state | Prefer field-level over class-level so a field that should not be readable is not |
@Setter |
JPA entities only, field-level | Class-level @Setter on an entity makes every column mutable including the ones that must not be; put it on the fields that are genuinely mutable |
@NoArgsConstructor(access = PROTECTED) |
JPA entities; access = PRIVATE on a noninstantiable marker/holder class |
Hibernate requires a no-arg constructor; PROTECTED keeps it out of application code so nobody constructs a half-built entity. The PRIVATE form replaces the hand-written private X() {} noninstantiability idiom — same generate-don’t-hand-write rule |
@AllArgsConstructor |
test fixture builders, and value holders that are not records | Not on Spring beans — @RequiredArgsConstructor over final fields is the DI form |
@Builder |
where a constructor’s parameter list has stopped being readable | Pair with @AllArgsConstructor(access = PRIVATE) so the builder is the only way in |
Rejected, and enforced by lombok.config rather than remembered:
@Data— bundles@Setter+@EqualsAndHashCode+@ToStringinto one annotation, which on a JPA entity is three distinct hazards at once: mutability nobody asked for,equals/hashCodeover mutable fields, and atoStringthat dumps every column. Ask for the pieces you actually want.@EqualsAndHashCodeon a JPA entity — primary keys are DB-allocated (§2 Identity), so the id is null before the save and populated after. Generatedequals/hashCodeover it means an entity’s identity changes mid-transaction, and anything already in aHashSetis lost.@ToString— a generatedtoStringis precisely the “raw object dump” §8.1 bans, and it goes live the moment someone interpolates the object into a log line, re-introducing every §8.6 deny-listed field at once. Where atoStringis genuinely wanted, hand-write it and return ids. Three lines, greppable, and — the reason it beats the annotation — it cannot silently start dumping a new field when someone adds one to the entity. Revised 2026-08-21 (FS-1). This bullet previously sanctioned@ToString(onlyExplicitlyIncluded = true)atflagUsage = WARNING. Measuring the gate showed that form could not work:flagUsageflags the annotation regardless of its attributes, and §7.2’sjavac -Werrorescalates the resulting warning intoerror: warnings found and -Werror specified, so the sanctioned form failed the build exactly as the bare one did.WARNINGdescribed an outcome that could not happen. It also failed open — the annotation only stays safe while every field is remembered as@ToString.Include, so forgetting one leaks rather than breaks. Records too: the language generates a record’stoString()from every component, so a record or class that holds a secret (password, private key, token) or PII overridestoString()to omit it — configuration records included (EtProperties).- Lombok’s
@Value— two independent reasons. Records already cover immutable value types, and the name collides with the Spring@Valuethis project bans (§5, “typed config only”), so allowing it would defeat thegrep -rn "@Value"check that proves no string-plucking config exists. @SneakyThrows— launders a checked exception past the compiler leaving no trace at the call site. §2’s no-swallow rule and “catch only where you can act” both depend on the exception being visible in the signature.- Lombok’s
@NonNull— the project’s nullness vocabulary is JSpecify@NullMarkedplus Error Prone/NullAway (§7.2). Two nullness systems in one codebase means two sets of semantics and two failure modes; Lombok’s generates a runtime NPE, which is not what a static checker gives you. - The entire
lombok.experimentalpackage (added 2026-08-29) —@UtilityClass,@SuperBuilder,@Accessors,@FieldDefaults,@Delegate,@ExtensionMethodand whatever joins them later, rejected as a group by one config switch rather than annotation-by-annotation. Experimental features carry no stability promise — their semantics can change or they can be dropped between Lombok releases, the wrong bet for a codebase riding a moving Boot BOM (AD #25). Only stable core annotations are used; if a stable one cannot express it, hand-write it.
lombok.config is committed at each backend repo root and is what makes the list above a build
outcome instead of a review topic. The committed file is authoritative — the block below is an
illustration that no checker holds in step, so verify a flag against the repo copy before citing
it, and update both in the same change when the policy moves:
config.stopBubbling = true
lombok.addLombokGeneratedAnnotation = true # JaCoCo and NullAway skip generated code (§7.2, wired FS-4)
lombok.data.flagUsage = ERROR
lombok.value.flagUsage = ERROR
lombok.sneakyThrows.flagUsage = ERROR
lombok.nonNull.flagUsage = ERROR
lombok.toString.flagUsage = ERROR # hand-write a toString that returns ids
lombok.experimental.flagUsage = ERROR # the whole experimental package, one switch
addLombokGeneratedAnnotation is the load-bearing line: without it FS-4’s coverage numbers count
generated accessors, and NullAway analyses code no human wrote.
2.2 Apache Commons Lang3 — for null-safety at the boundary, not as a habit
StringUtils is adopted for one reason worth the dependency: s.isBlank() throws on null and
StringUtils.isBlank(s) does not. That matters exactly where a string arrives from outside the
type system.
- Sanctioned:
StringUtils(isBlank/isNotBlank,trimToNull,defaultIfBlank,equalsIgnoreCase,abbreviate) andObjectUtils(defaultIfNull,firstNonNull). Also sanctioned anywhere:StringUtils.split(Error Prone’sStringSplitterrefusesString.split, andStringUtils.splitdrops empty tokens), thesubstringBefore/substringAfter/substringAfterLastfamily andcapitalize, which have no one-call JDK equivalent. - Use it at boundaries, not everywhere. Inside
@NullMarkedcode most values are non-null by contract, sos.isBlank()is both correct and clearer there.StringUtilsis for genuinely nullable inbound values — request parameters, imported CSV cells, Graph payloads, AI-extracted fields. Reaching for it on a value the type system already guarantees is not just noise: it signals “this might be null” to the next reader, which is worse than noise because it is false. - Never as a JDK substitute.
String.join,String.repeat,List.of,Objects.requireNonNullElseandOptionalall post-date lang3’s equivalents and win. AStringUtilscall where a JDK method does the same job is deleted in review. - The dependency stops at lang3. No
commons-collections, nocommons-beanutils(reflection- based, with the CVE history to match), noSerializationUtils, and no Guava — §0’s YAGNI rule covers libraries too. lang3 is a real runtime dependency (unlike Lombok, which iscompileOnly), so it sits in the lockfile and the dependency-scan surface; that is an accepted cost for one small, ubiquitous jar. - It is platform infrastructure, not domain — declared once in the single
build.gradle, exactly like the JSpecify annotations.
2.3 Dependency versions come from the Spring BOM, not from build files
The Spring Boot BOM is imported once in the single build.gradle, so a dependency names
coordinates and inherits the version:
dependencies {
implementation 'org.apache.commons:commons-lang3' // yes
implementation 'org.apache.commons:commons-lang3:3.17.0' // no — the BOM manages this
}
Two reasons, and the second is the one that bites. Boot ships a set of versions tested together, so overriding one member is a compatibility decision taken by whoever happened to be typing. And a pinned module silently stops moving when the Boot line moves — both versions resolve fine, no warning appears, and the drift is found much later by someone debugging why one module behaves differently from the rest of the tree.
- The Boot version is pinned in exactly one place — the
org.springframework.bootplugin declaration inbuild.gradle. Moving the line moves every managed library at once, which is the point of having a BOM at all. - A library the BOM genuinely does not manage carries an explicit version, and that is not a
violation — Spock and ArchUnit are examples. Prefer the library’s own BOM where it ships one
(
spock-bom) so its members stay consistent with each other. - Overriding a managed version is done once, as a
<lib>.versionproperty, with the reason — never as a literal on the dependency, where the next reader cannot tell a deliberate override from a habit. - Enforced, not remembered: a configuration-time check in
build.gradlefails the build when a declared version collides with a managed one, naming both. It carries a short allow-list for coordinates the project deliberately owns, each with its reason at the site. managedVersionsis the whole transitive BOM closure, not Spring’s own list, which is the subtlety worth knowing before adding an allow-list entry:spring-boot-dependenciesimportslog4j-bom, whose parent managesorg.jspecify:jspecifybecause log4j depends on it. Inheriting a version by that route puts a first-class policy choice — the nullness vocabulary everypackage-info.javauses — under an unrelated library’s release decisions, and it breaks the day that library drops the dependency. Check why a version is managed before deciding to inherit it.
2.4 Spring Boot 4 / Framework 7 — reach for the modern API
The backend is pinned to Boot 4.2 / Spring Framework 7 / Jakarta EE 11 deliberately (AD #25). Use what that platform gives you; do not carry a 3.x idiom forward when 4/7 ships a better one, and never reach for a deprecated or marked-for-removal API.
- No deprecated or
forRemovalAPIs.RestTemplate→RestClient(or an@HttpExchangeHTTP-interface client backed by it);WebClientonly where the call is genuinely reactive. Prefer thejakarta.*namespaces, Jackson 3, and the Spring Security 7 APIs.-Xlint:all -Werror(§7.2) already fails a main-code compile ondeprecation/removal; this rule extends the intent to test code and, more usefully, to choosing the modern API up front rather than leaning on the compiler to reject an old one. Check the Spring reference and the deprecation notice before committing to an API — treat any “for removal” / “in maintenance mode” note as hard-avoid. - Boot 4 is modular: add the per-technology module, not a bare library. Each technology ships as
spring-boot-<tech>(and aspring-boot-<tech>-testfor its test slice); the umbrellaspring-boot-autoconfigure/-test-autoconfigureno longer carry them, so a raw integration jar is not enough — you need Boot’s module or starter. Three cases the build has already hit:spring-boot-flyway(without it the app booted but silently never migrated),spring-boot-data-jpa-test(for@DataJpaTest, whose slice types moved toorg.springframework.boot.data.jpa.test.autoconfigure, with@AutoConfigureTestDatabaseunder…jdbc.test.autoconfigureandTestEntityManagerunder…jpa.test.autoconfigure), andspring-boot-micrometer-tracing-brave(FS-5: the Micrometer bindingmicrometer-tracing-bridge-braveon its own auto-configures nothing — noTracer, no MDCtraceId/spanId— the app boots and traces nothing; seelessons.mdL-028). All three fail the same silent way — green boot, absent feature — so prove any Boot-4 integration on a real boot, never from the dependency’s name (L-028). - This is a written-down default, not a new invariant — the FS-1/FS-2 work already chose
RestTestClientover the removedTestRestTemplate, thejcl-over-slf4jbridge for the removedspring-jcl, and thejakarta.*persistence/validation namespaces. §2.4 makes the standing preference explicit so it is a habit, not a rediscovery each time.
2.5 Java 21 — modern syntax where it reads better, never mechanically
Java 21 is the floor, not a ceiling to write Java-8-shaped code against. Where a modern construct makes the code clearer, reach for it; where it does not, leave it alone. Clarity and maintainability decide, not feature count.
- Pattern matching:
if (x instanceof Foo foo)over test-then-cast, and pattern matching forswitch(type patterns, record deconstruction,case null) for genuine multi-way dispatch over a value’s shape. A single-branchifstays anif— a one-arm switch is ceremony, not clarity. - Switch expressions (arrow labels, no fall-through) over statement switches and if/else-if ladders that compute a value — the compiler then proves every case is handled.
- Sealed hierarchies where the subtypes are a closed set the domain defines, which is what makes
a
switchover them exhaustive without adefault. Not for open extension — and never on a JPA entity: Hibernate’s lazy-loading proxies are runtime subclasses a sealed type cannot admit (BaseEntityis deliberately unsealed for exactly this reason). - Records for immutable data carriers — already the DTO rule above — with compact constructors
for validation, as
EtPropertiesdoes. - Text blocks for multi-line SQL/JSON/HTML literals;
varonly where the type is spelled on the right of the=(a constructor call, a cast) — keep the explicit type wherevarwould hide it.
Two standing carve-outs, both found by review and kept on purpose:
- An entity
equalskeeps the exact-classHibernate.getClasscomparison. Converting it to aninstanceofpattern is not a cleanup, it is a bug:instanceofmatches subtypes, so two different entity types sharing an id would compare equal — the classic JPA equality defect the check exists to prevent — and the proxy unwrapping would be lost with it. - Never refactor working code just to modernize it. This section governs code as it is written and touched, not a sweep. A diff whose only content is syntax modernization is churn, not progress.
3. Frontend (TypeScript / React SPA on Vite — AD #21)
strict: true, noany(useunknown+ narrowing); API types are written once per feature in its<name>Api.tsmodule (usersApi.ts,standardsApi.ts; shared reads undersrc/lib, with the parsing helpers insrc/lib/api/wire.ts), which parses each response fromunknowninto the type the screens use; there is no generated client yet (generating one from the backend’s OpenAPI document is a later option), so each type follows the seam contract field for field.- No SSR and no server components — both apps are SPAs. Data-fetching goes through TanStack Query — the query layer, locked 2026-09-24 and installed by F26-b WI-1.3 (one
QueryClientProviderat the app root, the client insrc/app/queryClient.ts); the email hooks (useMailboxConnection,useInboxMessages) read through it too (moved by F5-d, superseding F20-a’s recorded interim choice) — never rawuseEffectfetches; route-level code-splitting (React.lazy) keeps the initial bundle honest, since there is no server render to hide behind. (Until 2026-09-24 this rule said the query layer was “chosen by its first real caller”.) - State: server state via TanStack Query, URL state for filters/views (shareable lists are a P-31 parity feature!), local
useStatefor the rest. No global state library until the rule of two demands one. - Permissions are never trusted from a stale copy. The session’s permission set comes from
GET /api/v1/meand is re-read after any 403 (the HTTP status alone, whatever the body’scode— a CSRF refusal included), when the window gains focus and when the document becomes visible, with one request in flight shared by every trigger; a re-read answering 401 takes the session-expiry path, and any other failure leaves the screen and permissions as they are (AD #34 — the backend re-reads grants every request, so the frontend is the only side that can be behind).design/ui/design-system.md§9 carries the rendering convention. - Every section route is guarded on its navigation key. Wrap each section route in
RoutePermissionGuardon its navigation entry’s id (a sub-route with no entry takes its section’s), so a deep link is gated exactly like the sidebar entry and a user without the key sees the no-access state in place; the landing and not-found routes stay unguarded (design/ui/design-system.md§6, Rev 24). - Components small and single-purpose; extract when JSX nesting or prop count hurts readability, not by line-count dogma.
- Design tokens only — no raw hex/px where a semantic token exists (slice 3’s swappable theme layer is the reuse story for the next client).
- Untrusted content (synced email bodies, AI drafts) renders as text or through the sanctioned sanitizer —
dangerouslySetInnerHTMLis banned outside that one wrapper. - Accessibility is an NFR, not polish: real
<button>/<a>, labelled inputs, keyboard path for every mouse path (Kanban drag included), status never by colour alone.
3.1 Config is baked at build time. Data never is.
Both frontends ship as static bundles on S3 + CloudFront (AD #22). That hosting model has one characteristic failure: something that looks like live data is actually a snapshot frozen at build time, so the screen is wrong until someone redeploys — and a redeploy is the only thing that ever fixes it. It has three faces, and they are usually mistaken for three unrelated bugs: stale content shown indefinitely; fresh content that never appears without a deploy; and stale content that flashes and then vanishes to an empty state as a real fetch resolves behind it.
We are structurally protected against the usual cause and must stay that way:
- There is no build-time data path in this stack, and none may be added. AD #21 puts both apps on
plain Vite with no SSR and no server components — there is no
getStaticProps, no static generation, no build-time database read. Every value a user reads comes from a runtime API call to the backend. Adding any build-time data-fetch step to a frontend build is an architecture change → ASK FIRST. VITE_*variables carry configuration only — an API base URL, a feature flag, a public identifier. Never a list, a catalogue, a price, a taxonomy, or anything a user or admin can change. §5 already forbids secrets in the bundle for a different reason; this forbids data for this one.- No committed data module standing in for an API call. A
grades.json,incoterms.ts, orcertifications.tsimported at build time is the same bug wearing different clothes: the admin edits the value in the CRM and the screen does not move. This project is unusually exposed here — pipeline stages (F24), custom-field definitions (F34), the certification taxonomy, and the Buying Standard catalogue are all admin-editable by design, so each is a live fetch, always. Genuinely immutable constants (ISO country codes, currency minor units) are fine; if a human in Empire Teas can change it, it comes from the API. - Weekly bulk pricing is the case that turns this from cosmetic into commercial. Prices are effective-dated and published on a weekly cadence (AD #14, F26). A rep shown a stale price quotes a stale price. Anything on a pricing or quoting surface reads through the API with no client-side persistence, and an as-of date is displayed alongside any price so a stale value is visible rather than merely wrong.
- The service worker caches the app shell and nothing else. The capture PWA registers one (FS-1). It may cache HTML, JS, CSS, fonts and icons; it must never cache an API response — a service worker serving stale JSON survives redeploys and is the hardest version of this bug to diagnose, because the fix that normally works (deploy again) does nothing. The capture app’s kept-and-retried captures (F36-a) are outbound writes stored on the phone; they are not a read cache.
- Every data region declares loading, empty and error states explicitly, and is never seeded with placeholder content that resembles real data. A region that renders optimistic or leftover content and then empties itself is the flash-then-vanish face of this failure, and it reads to a user as the system losing their data.
Freshness is a test assertion, not an intention. For any surface showing server data, the
verify tier proves the loop: change the value through the API, then assert the UI reflects it
without a rebuild or redeploy. test-strategy.md § Coverage Targets carries this on the
always-test list.
And it cannot be verified on a fresh build. This failure class self-conceals: a build made in the current data state bakes the correct answer, so the bug vanishes on redeploy and looks fixed. Reproducing it means building against one data state and serving that build against another — or building against an unreachable API and grepping the output bundle for what it baked. A “works on my latest deploy” verification proves nothing here.
3.2 Loading, empty and error are three different states
Collapsing any two of them is how a data region ends up lying to a user. Three is the slogan; a real screen has six, and the two pairs that get merged are exactly the two that must not be:
| State | When | What the user sees |
|---|---|---|
| Loading | first fetch, nothing on screen yet | Fixed-height skeleton matching the resolved layout. Not a spinner, not zero-state copy |
| Refreshing | a fetch while data is already displayed | Never blank. A table re-reading for another page, sort, filter or search keeps its header and draws as many skeleton rows as it showed, in place of the rows, so its height holds; a re-read of the same request (after a write in a row, a retry) keeps the data on screen, because a row holds the control that started it. Neither draws a visible line above the data: the region’s polite status line says the update (design-system Rev 83). Outside a table, keep the data with a subtle in-progress affordance |
| Empty — nothing exists | fetch succeeded, [], no filters active |
Name what is empty and offer the creating action: “No quotes yet.” + New quote |
| Empty — nothing matches | fetch succeeded, [], filters or search active |
Say the filters are why, and offer the exit: “No accounts match these filters.” + Clear filters. Merging this into the row above makes users think their data is gone |
| Error — nothing on screen | first fetch failed | Say it failed and that it is not their data: “Couldn’t load quotes. Your data is safe — this is a connection problem.” + Retry. Never zero-state copy |
| Error — stale on screen | a refresh failed, data already displayed | Keep the data, band it as stale with its age: “Showing data from 14:32 — couldn’t refresh.” + Retry |
Copy rules for those messages: name the thing (“quotes”, not “items”); never blame the user for a server failure; always offer the next action (retry, clear filters, create); and on any error make it explicit that nothing was lost, because a suddenly-empty screen is read as data loss. Error text carries the correlation id (§8) in a copyable form — that is what makes a support conversation a five-minute log lookup instead of an interrogation.
[]from a successful fetch is the empty state. A failed fetch is the error state. They are not the same event and they do not render the same way. “No results” where the truth is “we could not reach the server” sends a rep to the wrong conclusion.- A failed refresh keeps what is already on screen. Never blank a populated region because a refetch failed — to a user, content disappearing reads as data loss, and they will not report it as an error because no error was shown.
- A write has three outcomes, not two. It was refused (nothing changed; say why), it succeeded,
or its outcome is unknown: a network failure, a 5xx with no problem body, or a response the client
cannot parse, where the server may well have committed. For the third, say the change could not be
confirmed and offer a re-read of what the write changes; never “Nothing was changed”.
forge-et-febranches onisWriteOutcomeUnknown(src/features/pricing/CorrectPriceDialog.tsxis the pattern). Because the record carries a version, a repeat of a write that did commit is refused, so the action can stay available (L-191). - The data layer propagates; the caller decides the fallback. A service that catches an error and substitutes something robs every caller of a choice only the caller can make.
- When you change a function from swallowing to propagating, audit every
catchdownstream in the same change. Error handlers that were unreachable become reachable the moment the contract changes, and whatever they do — including selecting a fixture — goes live with no diff to hint at it. This is a review question on any change to an error contract. - A region that resolves after first paint reserves its space. Fixed-height skeleton while loading; cards must not shove the page around as they arrive. Layout shift is a defect.
- A region whose content swaps after first paint is wrapped in
aria-live="polite", rendered unconditionally. A live region has to exist before its content changes for the change to be announced — conditionally rendering the wrapper alongside the content silently defeats it. The swap into an empty state gets announced too. A list or table is the exception: its data region is not live, because a live table makes a screen reader read every row on each filter or page change. One visually hiddenrole="status"line, rendered in every state, announces the change in one sentence — the count, “Loading …”, the empty state — and is empty on an error whose panel isrole="alert", which announces itself (BUG-104;forge-et-feUsersScreen,LeadListPane, the inbox’sinbox-status). - An effect that sets state from an async call carries a cancellation guard. React StrictMode double-invokes effects in development, and an unmount before the request resolves otherwise lets a losing run clobber a newer result or set state after unmount. The query layer handles this, which is one more reason §3 routes fetching through it rather than raw effects.
- Give the empty state a
data-testidwhen you build it (§4) — it is a state that needs asserting, and retrofitting the hook comes exactly when you are trying to write the test.
3.3 The server owns every number that matters
The fourth shape in §0.1, and the one with the least obvious blast radius. A UI that computes a server-owned value has created a second implementation of a business rule, and two implementations drift. The drift is invisible until someone compares a screen to an invoice.
- A value the server computes is never recomputed client-side for display. Line-item extensions, quote totals, gross profit and margin, the readiness-checklist state, an as-of price lookup: the API returns the computed value, the UI renders it. Not “the UI recalculates to avoid a round-trip.”
- A gate the server enforces is never decided client-side. The UI may show that Managing Director approval is required because the response says so; it must never compute a margin, compare it against the floor, and reach that conclusion itself. A client that decides can be wrong or simply bypassed, and the failure mode is a sub-floor quote going out unapproved — an authorization hole wearing a display bug’s clothes. Same shape as §2’s role-scoping corollary.
- Formatting is not computation. Rendering a number the server sent — currency symbols, thousands separators, date formats — is the UI’s job. Deriving it is not. Rounding and precision decisions (half-up, decimal places, currency minor units) live server-side, once, so the displayed figure and the stored figure cannot disagree.
- Optimistic updates only for values the client legitimately owns — text it just typed, a local toggle. Never for a server-derived value. Where an optimistic value is shown it is visibly provisional until confirmed, and a failed confirmation rolls it back with a message, rather than leaving something that looks committed.
- Provenance is visible, never implicit. AI-generated content is labelled as AI-generated and unapproved until a human approves it — the PRD’s human-in-the-loop mandate is a display requirement as much as a workflow one. An AI-extracted field rendered identically to a human-entered one is §0.1’s fabricated-data failure with a friendlier origin story.
- Anything served from a cache or known to be stale carries its as-of time (§3.2’s degraded row). A labelled old number is usable; an unlabelled one is a trap.
3.4 Modern TypeScript — the idioms the code is written in
The frontend counterpart of §2.5, and under the same governor: modern syntax where it improves clarity, never as churn, and never a modernization-only diff.
- View/request state is a discriminated union, rendered through an exhaustive
switchwith anever-typeddefault. §3.2’s states are the union’s variants, so adding a state without a render becomes a compile error instead of a review hope. This is the type-level half of a rule §3.2 already makes behaviorally — and note the tooling gap it closes:noFallthroughCasesInSwitch(already on) catches a missingbreak, not a missing case; only theneverdefault catches that. ??/??=for defaults;||only for genuine boolean OR. A0quantity, a0margin, afalseapproval flag are real valuesvalue || fallbacksilently discards — in this domain that bug class prices a quote wrong (§3.3’s server-owned numbers make it worse, not better, because the discarded value was authoritative).satisfiesfor literal-typed lookup objects — token maps, the permission-key tables AD #26 and AD #34 imply (a nav entry or route mapped to theviewkey it needs), feature-flag config: it checks the object against the type while keeping the precise literal inference anascast or a type annotation would widen away.- Modern stdlib opportunistically —
Object.hasOwnoverhasOwnProperty,structuredCloneover a JSON round-trip,.at(-1)for last-element — as a review nudge, not a lint crusade. - React deprecation discipline is convention-enforced, not tooling-enforced. Biome has no
equivalent of
react/no-deprecated, so a regression into class components (beyond the one error-boundary exception), legacyReactDOM.render, ordefaultPropson a function component is stopped in review, with React 19’s types catching some of it incidentally. Named here so nobody assumes the linter has it covered.
(Each frontend’s CLAUDE.md carries a one-line pointer to this section; a change here updates
both in the same change.)
4. Test hooks — data-testid (yes, we need them)
Playwright’s order of preference (mirrors test-strategy.md): getByRole/getByLabel first — they test accessibility for free — then data-testid where semantics can’t uniquely address an element (cards on a Kanban board, rows in a virtualized list, icon-only buttons).
- Convention:
data-testid="<feature>-<element>[-<qualifier>]"—deal-card,quote-checklist-item-incoterm,lead-triage-approve. - Add them when building the component, not when writing the test — retrofitting ids churns every E2E later.
- They are stable API: renaming one is a breaking change to the test suite; never generate them from user data.
- Never assert styling/classnames in E2E; assert roles, text, and testids.
5. Configuration & environments
Three runtime contexts, two of them in AWS (per the accepted proposal; UAT rounds run in a temporary environment or pre-go-live production — there is no third cloud environment unless OQ-49 resolves otherwise):
| Context | Spring profile | Vite mode (build-time) | Where config lives |
|---|---|---|---|
| local — developer machine | local |
.env.local |
application-local.yml + Docker Compose (Postgres, LocalStack for SQS/S3); safe defaults, no real secrets, mail sender + AI provider stubbed, or pointed at the developer’s own AWS credentials (Bedrock) — no personal API keys exist |
| dev — AWS (build environment) | (none — cloud default) | GitHub Actions repository variables baked at build | Backend env vars injected by the ECS task definition; secret values via secrets/valueFrom references into Secrets Manager (never plain env). UAT rounds deploy the release candidate to a temporary environment on the same cloud shape (or pre-go-live production), never to dev |
| prod — AWS | (none — cloud default) | GitHub Actions repository variables (prod set) | Same mechanism, separate account — the only difference between dev and prod is the task definition’s values |
Rules:
- One
application.yml, env-var values, minimal profiles. The singleapplication.ymlholds the shape (every key as${ENV_VAR:default}— safe default or placeholder); all per-environment values live in the ECS task definition (the team’s established pattern), so dev and prod run the identical file and image and there are noapplication-dev.yml/application-prod.ymlvalue files to drift. Profiles exist only where a bean graph changes, not a value:local(stub seams, Docker Compose) andtest(Testcontainers). A key that must be set per-environment fails fast at startup (@ConfigurationProperties+ validation) rather than defaulting silently. - Typed config only:
@ConfigurationProperties(prefix = "et.…")records — no@Valuestring-plucking scattered through code. OneEtPropertiestree documents every knob. application.ymlstays clean. Never restate a framework or library default — a restated default reads as a deliberate decision and buries the keys that actually are ones. Only keys that deviate from a default or are genuinely required appear. Inline${ENV_VAR:default}fallbacks only where a safe universal default exists; a per-environment value gets no inline default, so a missing task-definition entry fails fast at startup instead of silently running on a placeholder. Keys grouped by subsystem with a one-line section comment, custom keys always under the typedet.*tree — the file should read as a table of contents of what this app actually configures.- No secrets in any yml or .env that is committed. Local:
.env.local/application-local.ymlare gitignored with a committed*.exampletwin. Cloud: Secrets Manager only. - Flyway placeholder values follow the same split (§2 Persistence): a non-secret per-environment value is a plain task-definition value — production’s seeded-administrator email included (AD #40, refining AD #34), and the Entra tenant ID, client ID and certificate; only a value that must stay secret (the Entra private key, the Exa key, the database password) comes from Secrets Manager through a
secretsreference. Thelocal/testvalue lives with the profile, never in a cloud-reachable file. - Profile-specific beans over
if (env == prod)conditionals:@Profile("local")stub implementations forMailboxProvider/AIProvider/ErpHandoffServiceseams so a laptop runs the full app with zero cloud dependencies. - Code never reads
et.environmentto change behaviour. The one exception is a startup guard (aBeanFactoryPostProcessorthat refuses a misconfigured shape), which may compare it with exactlytestand only to decide whether to refuse.SqsListenerSwitchis the one place that does, for the two guards that call it,SchedulerConfigGuardandScanResultQueueGuard(BUG-097): they refusespring.cloud.aws.sqs.listener.auto-startup=falseunlesset.environmentistest, because a deployment runs with no profile and the cloud-shape tests cannot activatetestwithout losing the cloud bean graph they exist to test (BUG-070, the lead’s decision of 2026-10-06). The labeltestis reserved for test contexts; a task definition never uses it. Any other read ofet.environment— a branch ondev,uatorprod, or a guard that compares it with anything buttest— is a review Blocker. - A stub or fixture must be structurally unreachable outside
localandtest. The profile-scoped seam stubs above are the sanctioned pattern because the profile makes them unreachable in a cloud context. What is never sanctioned is a fallback dataset a production path can select — a hardcoded list returned when a fetch fails or a response comes back empty. Empty is honest; invented is not, and invented data that reaches a user is worse than a visible error, because nobody reports what looks plausible. In a CRM the blast radius is not cosmetic: a fabricated price, account or lead is a commercial decision made on fiction. The frontends carry the same rule with a sharper edge — a static build that cannot reach the API must bake the empty state, never a fixture, or the fabricated content ships to every user until the next deploy (§3.1). Enforced at three levels, because this is the §0.1 failure with the worst blast radius: structurally — ArchUnit forbids a production class reaching a fixture/test-data package,dependency-cruiserforbids a non-test module importing**/fixtures/**or**/mocks/**transitively (§7.2, §7.3), so the fallback is unreachable rather than merely discouraged; by naming — every string value in a shared fixture or factory module that shipping code could import (afixtures/,mocks/or__fixtures__/folder or a data helper undersrc/test/in the frontends, a test-data package in the backend) carries aFIXTURE_prefix; inline values inside one test file, browser-test data undere2e/, which no build bundles, and tool-input files a script test reads (src/test/scripts/fixtures/— copies of lockfiles and the like) need not (project audit F-12, 2026-10-04); and in the artifact — a CI script greps each built bundle and jar for that prefix (§7.6). The last one is the backstop that survives a refactor quietly re-activating an error path, which is exactly how this failure reaches production. - Tests use the Testcontainers profile (
test) — never thelocalprofile’s Docker Compose state. - The frontends carry no secrets, period. Anything a Vite build embeds (
VITE_*) ships to every browser — so GitHub Actions variables carry only public config (API base URL); GitHub Actions secrets exist only for the deploy pipeline’s own AWS credentials, never for values the bundle reads. Every real secret is server-side, behind the API.
AI models are configuration, not code (and it isn’t over-complicated — it’s one properties block behind the existing AIProvider seam):
et:
ai:
provider: bedrock # AD #19 — Claude via Amazon Bedrock, called from inside the project's account
# in us-east-1; neither pinned model runs in-Region on bedrock-runtime: the us.
# profile may process in us-east-1, us-east-2 or us-west-2, the global. profile in
# any commercial Region (ai-provider-strategy.md §4b). No fallback provider: on
# failure the seam degrades to the manual path. Default bedrock — not restated.
features: # one named record field per feature (AiProperties.Features), never a map
inquiry-extract:
model: "us.anthropic.claude-haiku-4-5-20251001-v1:0" # F12; enabled defaults to true
email-draft:
model: "global.anthropic.claude-sonnet-5-5" # F11-h
lead-triage:
model: "us.anthropic.claude-haiku-4-5-20251001-v1:0" # F11-d
account-briefing:
model: "global.anthropic.claude-sonnet-5-5" # F13
lead-research:
model: "global.anthropic.claude-sonnet-5-5" # F11-c
prices: # every model a feature may use; startup refuses a feature model with no row
- model: "us.anthropic.claude-haiku-4-5-20251001-v1:0"
input-usd-per-million-tokens: 1.10 # Haiku 4.5 list + 10% through the us. profile
output-usd-per-million-tokens: 5.50
- model: "global.anthropic.claude-sonnet-5-5"
input-usd-per-million-tokens: 2.00 # Sonnet 5.5 through the global. profile
output-usd-per-million-tokens: 10.00
# call: deadline 9s, max-transient-retries 2, max-invalid-output-retries 1,
# initial-backoff 200ms, max-backoff 2s — defaults on AiProperties.Call, not restated
# circuit-breaker: failure-threshold 5, window 60s, open-interval 60s — defaults, not restated
# monthly-budget-usd, billing-alert-usd, hard-ceiling-usd: not built — F12 spec Q-1 (proposal A.3.2's
# budget envelope, alert and hard stop); the AI-spend alert is the billing owners'
# AWS Budgets alert (F38 Rev 18, Rev 23)
That is the shape forge-et-be ships (AiProperties, application.yml, docs/ai/README.md): each model and its price are set in application.yml as universal values, the same in every environment, and the call and breaker settings carry their defaults on the record. Model IDs and per-feature toggles are env-overridable so an evaluation can flip a model with no code change and no redeploy beyond config — the env-selected-model pattern proven on a previous Altrium engagement, extended per-feature. The variable is the feature key without its dash: ET_AI_FEATURES_INQUIRYEXTRACT_MODEL and ET_AI_FEATURES_INQUIRYEXTRACT_ENABLED (proved by AiPropertiesBindingSpec; Spring also accepts the dash written as an underscore for a record field, but the no-dash form is the documented one). Setting any ET_AI_PRICES_<n>_* replaces the whole price list. Every read goes through one resolver (AiFeatureSettingsResolver), so the administrator toggle of proposal A.3.2 — not built yet, F12 spec Q-1 — replaces the source without touching a caller.
Logging (both repos). The full standard — mechanics, trace propagation, levels, the business-event contract, message structure, the deny-list — is §8; it is binding from the first feature WI. What belongs to configuration:
- Formats: structured JSON in cloud profiles, pretty in
local. Every line carriestraceId/spanIdfrom Micrometer Tracing (§8.2) — across request threads,@Asynchops, and SQS legs (trace context in message attributes alongside the AD #13 idempotency key). - Every controller and service that can fail has a logger — no
System.out, noprintStackTrace, ever. - Every AI call logs the metadata set
{feature, provider, model, tokens, cost_usd, latency, outcome}— and never the prompt/response bodies in production (§8.6, A.6.3). - Frontend: no
console.login committed code; errors route to the error boundary and the telemetry seam.
Scripts & automation.
- A guard gates on exit codes, never on printed output — a check that prints
FAILbut exits 0 lets the next step run anyway (… || exit 1, then act). - A scripted find-and-replace must assert its anchor matched and verify the result — an unmatched replacement exits 0 and is indistinguishable from success. Prefer edit tooling that fails loudly on a non-match.
5.1 The team is mixed macOS/Windows — nothing may assume one of them
The team works on both Windows and macOS (at least two developers on Windows), so a convention that only works on the author’s machine fails for part of the team, and it fails after the convention has shipped. Every repo carries these:
- Line endings are decided by the repo, never by the developer. Each repo commits a
.gitattributes:* text=auto eol=lf(LF in git and in every working tree, whatever a developer’score.autocrlfsays — the app repos adopted theeol=lfdefault on 2026-09-27), plus expliciteol=lfkept on everything that is executed or byte-compared —*.sh,*.py, git hooks (extension-less, so list them by path),gradlew— andeol=crlfongradlew.bat..editorconfigsetsend_of_line = lfto match. Why it matters twice: a CRLF checkout makes bash refuse a script outright ($'\r': command not found), and it silently breaks any generator whose output is diffed for staleness. Never rely on a developer having setcore.autocrlf. - Python reads pin their encoding. Every
open(),Path.read_text(),subprocess(..., text=True)and friends passesencoding="utf-8"— Windows decodes with cp1252 by default, and the first byte outside it kills the tool. Enforced bycheck-encoding-pins.py(an AST check) in the harness’sRepo hygienejob and the backend’s Fast lane. - Path handling is OS-neutral in code. Java:
Path/Paths.get, never string-concatenated separators. Node:path.join/path.posix— and when a path becomes an identifier (a doc-site slug, a graph node id), normalize\to/so the same input yields the same output on both platforms. - No macOS-only or Linux-only commands in anything a developer runs — build scripts, git hooks, npm scripts, docs. The BSD/GNU split is the usual trap:
sed -itakes an argument on macOS and not on GNU, and\+/\|insedare GNU extensions. Prefer the portable subset, or do the text work in Node/Python (both already required by the toolchain). The same applies to case sensitivity: macOS filesystems are case-insensitive by default and Linux CI is not, so an import of./Buttonthat resolves locally fails the build — file names and import paths must match exactly. - Docker Desktop with the WSL 2 backend is the assumed local container runtime on Windows (Compose Postgres + LocalStack, Testcontainers). Keep bind-mount paths inside the repo and relative, and don’t depend on host networking specifics.
- Verify on both before calling a convention done. Anything shell- or path-shaped that lands in Foundation gets run once on Windows (Git Bash) by a Windows developer — a review pairing that already exists. A convention that has only ever run on one OS is unproven, not portable.
6. Foundation-strength checklist (what “strong foundation” means, concretely)
Beyond the Foundation Backlog slices (architecture.md § Foundation Backlog is the authoritative list), these are the make-later-features-easy invariants to verify before the first feature WI:
- Boundary enforcement red-green proven: a deliberate core→tea import and a banned word each fail the build in CI, once, on purpose. Superseded by AD #31 / FS-14 (2026-09-10): the core→tea build-graph rule and the banned-word
VocabularySpecwere retired with the module split (FS-14 spec Appendix B). The surviving red-green boundary invariants areFeatureSlicesSpec(feature packages free of cycles;platformdepends on no feature),LayeringSpec(web → service → repository) and the hygiene guards, each proven red-green once at FS-10 / FS-14. Kept as written for the record. application.ymlshape + fail-fast validation +.exampletwins committed; a fresh laptop reaches a running app with seeded data in ≤ 30 minutes via the onramp README (slice 8’s acceptance test). Measured 2026-09-16 — 23 min 13 s on a Windows laptop on office wifi, by a developer who did not write the READMEs, downloads inside the clock; five runs, thirteen README defects found and fixed before it passed. Record:.forge/specs/foundation/008-developer-onramp-findings.mdF-001.- Error envelope + correlation ID +
@RestControllerAdvicedemonstrated on the slice-10 reference endpoint. - One scheduled job, one queued job, one DLQ alarm proven end-to-end in dev (slices 7/9) — with an idempotency-key replay test.
- The four provider seams (
AIProvider,MailboxProvider,ErpHandoffService,AuctionPriceProvider— the last a no-op in V1) each have alocal-profile stub so the app runs offline;PriceModelis a domain extension point, always present, not a stubbed provider. (AD #29 / #31 note: “extension point” is pre-collapse vocabulary —PriceModelis a first-class type in thepricingpackage; no extension-registration substrate exists or is planned.) (Manual foundation review, 2026-09-15 — accepted risk R-FND-001 inengagement-gate-runs.md: none of the four seams existed at foundation close; each is built by its first consuming feature — F11/F12, F20, F19, F26 — with alocal/teststub and a fail-closed cloud guard on the FS-11SeamGuardpattern.PriceModelexists.) - Design tokens render one screen in Empire’s theme and a neutral theme (the reuse proof, cheap while there’s one screen).
data-testid+ role-query conventions demonstrated in the first Playwright smoke test against the slice-1 shell.- CI wall-clock < 10 minutes — with recorded exceptions:
forge-et-pwa’sSlow lane, the job that runs the test suite, is capped at 30 minutes,forge-et-fe’s at 45 (lead-approved, 2026-11-12: its suite takes 24–26 minutes, and a Dependabot run on forge-et-fe#500 was cancelled at 30 — forge-et-fe#511), andforge-et-be’s at 90 (lead-approved, 2026-10-12 for 30: the backend’s nightly suite took 13 to 19 minutes and hit its earlier 20-minute cap on 2026-10-10; forge-et-fe’s suite takes about 10 minutes on a runner (2026-10-23: forge-et-fe’s wholeSlow lanejob took 26 minutes on the nightly run of 2026-10-20 and 24 minutes on 2026-10-22, against its 30-minute cap). Lead-approved, 2026-10-22 for the backend’s 60: its build-and-test step took 26 minutes on 2026-10-15 and every nightly run from 2026-10-16 hit 30 and was cancelled — the suite runs one spec at a time, and the mailbox and email-send specs wait on the LocalStack queue and on real timeouts; forge-et-be#299 also trimmed the waits that were not the subject of a test. The first nightly run under the 60-minute cap, on 2026-10-22 (run 39841344696), passed: a 30-minute build-and-test step, 10,162 tests, 0 failed. If the backend’s suite nears 60 again, the next lever is running specs in parallel, which needs the specs that wait for a whole shared queue to be empty to wait on their own messages instead. (2026-11-12: the backend’sSlow lanetook 47 minutes on 2026-11-11.build.gradle’set.testForksnow runs the specs in more than one test JVM, each with its own Postgres and LocalStack, so no spec shares a queue across JVMs; but two JVMs do not fit the Slow lane’s GitHub-hosted runner, 2 processors and 7.9 GB — both tries were stopped for lack of memory, at 3 GB and at 2 GB per JVM (forge-et-be#411) — so CI keeps one. A larger runner, or a higher cap, is the lead’s decision,.forge/owed.md. Since 2026-11-13 theSlow laneruns only on demand, so the cap bounds only a run someone asks for, N-5. Lead-approved, 2026-11-13 for the backend’s 90: that run would reach 60 within weeks at the suite’s growth of 5–6 minutes a week, and only the minutes used are billed — forge-et-be#420.) The reason is in each repo’s.github/workflows/pr-validation.yml), and everyFast laneat 15 minutes, exceptforge-et-be’s at 25, which only bounds a hung step (the backend’s ran in about six minutes as of 2026-10-05, the frontends’ in under two). Lead-approved, 2026-11-11 for the backend’s 25: a change to the build files makes Spotless check every Groovy file instead of the changed ones; the build step took 11 minutes on forge-et-be#362 (2026-11-04) and 13m46s on forge-et-be#407, whose job was cancelled at 15m4s with every check passed (forge-et-be#408). (2026-11-12: a dependency bump no longer makes Spotless check every file. It checks every file when a PR changes what Spotless does, or anything inbuild.gradlebeyond versions, comments and blank lines: a Spotless setting, another Gradle file, the Gradle wrapper, a.gitattributesor the workflow;scripts/spotless-scope.py, forge-et-be#411.) And(withdrawn 2026-10-20 with the stability wait — F38-d spec Rev 3, forge-et-be#286; the job is back to the 10-minute cap). A further raise is a lead decision recorded the same way — slower gates erode the check-after-every-change habit the Boundaries demand. The §7.1 fast/slow lane split is what keeps it there. Every workflow job declaresforge-et-be’sbuild.yamldeployjob at 30 minutes (lead-approved, 2026-10-19, at the F38-d WI-2.1 plan review: the job waits up to 15 minutes for a stable service, as F38-d FR-2 required, after the image build and scan;.forge/plans/F38-d/F38-d-WI-2.1-plan.mdD-12, D-13)timeout-minuteswith this target as the cap — GitHub’s default job timeout is 360 minutes, so one hung step otherwise burns six hours of the monthly Actions quota. - Every §7 tool is wired and proven red-green once, on purpose — a formatting violation, a null-safety violation, a malformed commit message and a boundary breach each fail a build before the first feature WI. (Post-FS-14 the “boundary breach” is a feature-package cycle or a layering violation —
FeatureSlicesSpec/LayeringSpec— not a core→tea import.) A gate nobody has seen fail is a gate nobody knows works. - The §0.1 honest-failure guarantee is demonstrated, not asserted. Before the first feature WI: a fixture reachable from a production path fails the build (ArchUnit +
dependency-cruiser); a fixture string present in a built artifact fails CI; and the first real list screen renders all six §3.2 states — including empty-filtered distinct from empty, and refresh-failed keeping its data with an as-of label. Cheap to prove on one screen now; unprovable across thirty features later. (Manual foundation review, 2026-09-15 — the first two clauses are proven: FS-1 AC-7, FS-3 AC-8/AC-9, FS-14 AC-11; FS-4 AC-16. The list-screen clause is accepted risk R-FND-002 inengagement-gate-runs.md, owed by F32 or the first screen-shipping feature, whose spec must carry the six-state acceptance criterion.) - Identity allocation follows §2 from the first entity. FS-2’s base-entity conventions bake in DB-allocated PKs; the first human-facing number series to ship is allocated by sequence/counter-row with its allocation proven under two concurrent issuers, and its unique constraint’s violation path is translated and tested. No
COUNT/MAX-derived identifier exists anywhere — greppable, and grepped in review.
7. Tooling & enforcement
The principle: a machine decides everything mechanical, so review can spend its whole budget on meaning. Formatting, import order, unused variables, nullness, boundary violations and commit shape are not opinions — they are settled once, in config, and never discussed in a PR again. What a reviewer is for is whether the code is correct, well-placed and worth keeping.
Two constraints shape every choice below. §6.8 caps CI wall-clock at under 10 minutes, so checks run cheapest-first and the expensive ones only after the cheap ones pass. And this is a small team on a fixed build window — every tool has to earn its configuration and its failure modes, which is why the list of what we don’t run (§7.9) is as deliberate as what we do.
7.1 The enforcement ladder
Each check runs at the earliest point it can. A check that only ever fires in CI is a check that wastes a developer’s round-trip.
| Stage | What runs | Blocks |
|---|---|---|
| Editor | .editorconfig (committed in every repo) |
nothing — prevents whitespace churn between editors |
| Pre-commit (husky + lint-staged) | Format + autofix on staged files only; commitlint on the message |
the commit |
| PR CI — fast lane | Format check, lint, typecheck, boundary rules, PR-title lint, secret scan, the record script’s self-test; on a ready PR also the build and dependency scan (and, in the two frontends, last, on a PR into release/* only, the Browser gate: description check, node scripts/browser-gate.mjs ci-check). A draft, or a PR that changes only documentation no test or build step reads, stops after the static checks; a ready documentation-only PR into main or release/* gets the Test record check from a job of its own after this lane |
the PR |
| Local, recorded on the PR — all three app repos | The tests the change needs (every test when it touches shared code, on a PR into release/*, or with --full; .forge/design/harness/test-run-cost.md S-4), once per PR, on its final commit after the last push, recorded as a PR comment naming the commit and as the required Test record commit status on it: ./gradlew build with the selected tests by scripts/local-build-evidence.py in the backend, the selected Vitest tests by pnpm test:record (scripts/local-test-evidence.mjs) in the frontends; a PR whose head has none cannot merge, and review blocks it (git-conventions.md § The test suites run locally, and the PR records them) |
the merge |
Before a PR into release/* is marked ready — forge-et-fe, forge-et-pwa |
pnpm e2e:gate --full, the browser gate’s full profile on a clean commit (test-strategy.md § Browsers & Viewports), recorded as the Browser gate: line in the PR description (F40 FR-13); the push that marks the PR ready goes through pnpm e2e:gate --full --push, and so does the last later push that changes a gate input. A PR into main runs no full gate (a frontend PR runs only the browser tests its change selects, PRD Rev 93): the nightly full run checks every browser spec at every size on main (PRD Rev 81). The rules — what a result covers, the push order, the skip line — are in test-strategy.md § Browsers & Viewports |
the ready PR into release/* (the description check above) |
Nightly on main — the lead’s Mac |
gitleaks over each repo’s history and Trivy over its lockfiles, every night; the backend build with every test; each frontend’s Biome, typecheck, folder boundaries, test-hook coverage, build, bundle budget, work-marker, skipped-test, fixture-leak, stub-sign-in, record-script self-test and Knip (advisory) checks (and the capture app’s live shared-file comparison); the backend’s Fast-lane guard scripts, build record self-test, DDL drift and jar fixture check after the build; both Vitest suites; both browser gates in the full profile (.claude/lib/nightly/run-nightly.py, .forge/design/harness/test-run-cost.md N-3, S-4); a red suite opens a nightly-red issue |
new work — a red night is fixed first |
| CI — the test suite: each app repo’s slow lane | The test suite and coverage report — on demand only; skipped on every PR, a Dependabot PR included (its local record runs the tests, as on any other PR), on a push to release/* (whose PR recorded every test locally) and on the weekly schedule, whose run keeps only the Fast lane (a suite runs in one place: the nightly full run on the lead’s Mac and the local records, .forge/design/harness/test-run-cost.md N-3, N-5) |
nothing — a run someone asked for |
Merge to main |
deploy-dev, then the E2E smoke tier, run by hand by the delivery-team member whose merge or manual dispatch started the deploy, once it finishes, with no CI job (AD-O-11 as revised by architecture.md Rev 68; F38-g) |
new work on main — a failing smoke run is fixed first |
| Release tag | UAT and production: the E2E smoke tier, run by hand against the environment after the deploys, with the release track’s regression cycle as the full check; no browser tier runs inside deploy-uat or deploy-prod (F38 OQ-D; AD-O-11 as revised by architecture.md Rev 72 and Rev 81) |
the release |
The fast lane exists so a missing semicolon fails in ~60 seconds instead of after an eight-minute test run.
The file-size limit (§1) is a unit test, so it runs in the local record of every PR, whatever the change (the backend’s test selection always runs com.empireteas.arch.*; the frontends’ selection always runs a test that reads files), and in the nightly full run: forge-et-be src/test/groovy/com/empireteas/arch/FileSizeSpec.groovy, forge-et-fe and forge-et-pwa src/app/fileSize.test.ts. A failing test means the record records nothing, so the PR cannot merge (.forge/design/harness/file-size-check.md D-3).
Naming inside a workflow file — sentence case throughout (the design system’s Title Case for the CRM’s titles and buttons, §9 of design/ui/design-system.md, does not apply to CI names): the workflow name: (Repo hygiene, PR validation), each job name: (Fast lane, Slow lane), and every step name. Workflow files are kebab-case .yml (repo-hygiene.yml, pr-validation.yml). One caveat that outranks tidiness: a job name is the required-check context in the branch rulesets, and changing that list needs repo admin — so a required job is never renamed, and the ruleset changes in the same change as the workflow (git-conventions.md § Branch Protection). Workflow and step names carry no such contract and can be edited freely. The deploy workflows are the exception (build.yaml, deploy-uat.yaml, deploy-prod.yaml and forge-et-iaac’s dev.yaml/uat.yaml, written first by the DevOps team): their workflow name: is lower case (build) and their steps are named area::action (artifact::upload, identity::aws), the same way round in every repository (the lead, 2026-11-19; F38-d WI-2.1 plan D-14).
7.2 Backend — forge-et-be
| Tool | What it buys | Gate | Wired at |
|---|---|---|---|
Spotless — palantirJavaFormat() + removeUnusedImports() (Java), greclipse() + 4-space (Groovy/Spock) |
Formatting stops being a review topic; unused imports never accumulate. spotlessCheck is part of check |
PR (fast) | Slice 1 |
ArchUnit — web → service → repository layering + feature-package acyclicity (platform/ui reach no feature) + no schema qualifier on an entity + no production class reaches a fixture/test-data package + @NullMarked package-info.java present in every production package + the audit write guards (AuditWriteGuardSpec, F39 FR-12): a raw SQL write only in a @Modifying / @RawWrite repository method, a caller of such a method depends on the audit service, only the audit service stores an audit row, and only SignInAudit looks up a user of any status by email — each rule also proved failing on committed probe classes |
The hygiene guards are only real if a machine enforces them (FS-14 retired the split’s boundary + banned-vocabulary rules; these remain). The fixture rule enforces §5 structurally: §0.1’s fabricated-fallback failure needs a reachable fixture, so making it unreachable kills the failure class rather than policing it. The null-marked presence rule keeps §2’s per-package convention self-enforcing as packages multiply — package annotations don’t cascade, so without the guard every new package is a silent opt-out | Local build record + nightly Slow lane — not run on an ordinary PR (git-conventions.md § The test suites run locally, and the PR records them) |
Slice 1 |
Error Prone + NullAway with JSpecify @NullMarked per package |
Turns §2’s null-safety rules from convention into compile errors — the single highest-value correctness tool available for Java | PR (fast) | Slice 4 |
javac -Xlint:all -Werror on main sources (-processing excluded) |
Compiler warnings are free findings; letting them accumulate makes the useful ones invisible | PR (fast) | Slice 1 |
Javadoc as a lint — -Xdoclint:all,-missing, failOnError = true |
Catches unresolved {@link} and malformed @param/@return on a package’s published surface — a service interface another package calls through is an API. Nothing else sees these. The missing group is off (2026-08-29): boilerplate members are Lombok-generated (§2.1) and invisible to the javadoc tool, so missing could only nag about code nobody wrote — a standing nudge that tempts hand-written boilerplate back in. What a hand-written member must document is §9.1’s review-owned contract |
PR (fast) | Slice 1 |
| JaCoCo | Coverage visibility per §7.4 | report → gate | Slice 4 |
Spock 2 — all tests in src/test/groovy |
Team standard (test-strategy.md). Add a build check that src/test/java contains no test classes, so the convention can’t erode one JUnit file at a time. The tests themselves run in the local build record and the nightly Slow lane |
PR (fast) for the guard | Slice 1 |
dependencyLocking STRICT + committed gradle.lockfile |
Reproducible builds; makes the dependency scan meaningful (you scan what actually resolves) | PR (fast) | Slice 1 |
project-report plugin |
./gradlew htmlDependencyReport / projectReport — answers “where does this jar come from?” when the lockfile or dependency scan flags something; zero config |
— (diagnostic, run on demand) | Slice 1 |
Gradle wrapper validation (gradle/actions/wrapper-validation) |
Verifies the gradlew jar checksum — a compromised wrapper executes arbitrary code in CI with the deploy role attached |
PR (fast) | Slice 4 |
Trivy dependency-vulnerability scan — gate HIGH,CRITICAL ≡ CVSS ≥ 7.0, report-only on every ready PR, release/* push, manual and weekly CI run, and the nightly full run on the lead’s Mac (the dev deploy runs none; ECR scans each dev image on push — AD #38 as restated 2026-11-03); a UAT or production release stops on an open finding without an exception (AD #27, AD #38, which replaced FS-4 spec Rev 3’s planned flip); reads the committed lockfiles directly (--include-dev-deps), governed .trivyignore.yaml (id + purls + statement + tool-enforced expired_at). Was OWASP Dependency-Check until 2026-08-31 — it cannot scan pnpm, so AD #9’s one-uniform-tool intent moved to Trivy (AD #27) |
AD #9 / AD #27 | PR (fast, report-only) | Slice 4 |
The backend compiles on Temurin 21, and Error Prone and NullAway move together (the lead’s decision of 2026-11-19, forge-et-be#487). NullAway 0.12.11 and later run JSpecify mode only on a javac that reads type-use annotations from class files: on JDK 21 that is -XDaddTypeAnnotationsToSymbol=true, which OpenJDK builds support from 21.0.8 and Oracle JDK 21 does not. So build.gradle’s toolchain asks for JvmVendorSpec.ADOPTIUM, compileJava passes the flag, and the foojay resolver plugin in settings.gradle downloads Temurin 21 into ~/.gradle/jdks on a machine that has none; any JDK 21 or later may still run Gradle itself. The README offers a package manager’s Temurin first: Gradle checks no checksum on the resolver’s download, only HTTPS and foojay’s redirect, a risk accepted for developer machines and the nightly Mac (CI installs its JDK with setup-java). An installed Temurin 21 older than 21.0.8 matches the toolchain and then fails NullAway’s check; upgrade it. Never set the toolchain back to “any vendor”: on an Oracle JDK the build stops. Dependabot raises both analyzers in an analyzers group of their own, so they move together (NullAway hooks Error Prone’s internal javac APIs) and hold up no other update; a release whose new checks fail the -Werror build merges only once its branch fixes the code they flag.
Put @Nullable inside a type argument only where an element can really be null, because every reader of such a type must then handle, or cast away, a null that never comes. A JSON null list entry reads as a NullNode, not a Java null, and a map can leave a key out instead of holding null. A single-column JdbcClient read of a column that cannot be NULL uses SingleColumn.LONG or SingleColumn.STRING (platform/persistence): Spring 7 types .query(Long.class) and .query(String.class) as giving @Nullable elements, and the mappers fail the read on a NULL instead.
The flag above also reads type-use annotations inside type arguments from class files, so an incremental compile sees the same types as a clean one. That removed BUG-237’s cause (.forge/lessons.md L-216): on Oracle JDK 21, or Temurin without the flag, an incremental compile saw another file’s List<@Nullable T> as List<T> and failed NullAway while CI’s clean compile passed. A reader in another file no longer needs var for such a value, and scripts/check-incremental-compile.py, which probed for that failure, was retired with forge-et-be#487.
7.3 Frontend — forge-et-fe and forge-et-pwa
Package manager: pnpm for both frontends — pnpm-lock.yaml committed, CI installs with --frozen-lockfile (§7.7). Never npm or yarn; pnpm’s strict node_modules makes undeclared (phantom) imports unresolvable, which the boundary tooling below relies on. The capture POC’s npm-workspaces layout is not carried into forge-et-pwa — it is a single app in its own repo.
| Tool | What it buys | Gate | Wired at |
|---|---|---|---|
| Biome — formatter + linter in one | Replaces ESLint + Prettier: one config, one dependency, order-of-magnitude faster. Baseline rules as errors: noExplicitAny, noNonNullAssertion, noConsole, useImportType, noArrayIndexKey, plus the whole a11y group — accessibility is an NFR (§3), so it is a build failure, not a review note |
PR (fast) | Slice 1 |
dependency-cruiser as a standalone check:boundaries script |
Biome can restrict import paths but does no graph analysis. The src/{app,features,ui,lib} folder rules (ui/lib are leaves, features don’t import each other, only main/app reach app) need transitive analysis, cycle detection and orphan detection — keep the dedicated tool. Carries the fixture-import rule too (no non-test module reaches **/fixtures/**, **/mocks/**, **/__fixtures__/**) — the frontend half of the §5 guard, and transitive, so a fixture pulled in two hops still fails |
PR (fast) | Slice 3 |
tsc --noEmit (over tsconfig.json, then e2e/tsconfig.json) with strict, noUncheckedIndexedAccess, exactOptionalPropertyTypes, noImplicitOverride, noFallthroughCasesInSwitch |
strict alone still lets arr[i] lie about being defined. noUncheckedIndexedAccess is the one people skip and the one that catches real bugs. (FS-14 collapsed the workspace, so the former tsc -b project-references build is now a plain --noEmit typecheck of the one package.) |
PR (fast) | Slice 1 |
Vitest + React Testing Library (+ @testing-library/user-event), v8 coverage |
T1/T2 per test-strategy.md — unit and component tests are non-negotiable on the frontends, not an aspiration |
Local test record on the PR (pnpm test:record); the nightly full run on main; CI only on demand (§7.1) |
Slice 1 |
check-testid-coverage.mjs — a purpose-built node script, shipped with a --self-test mode so the check itself is testable in CI |
§4 mandates data-testid on interactive elements; this makes it mechanical |
PR (fast) | Slice 3 |
| Bundle-size budget per route chunk, failing over threshold | §3 mandates route-level code-splitting; without a budget the mandate silently rots. There is no server render to hide a fat bundle behind | PR (Fast lane, not drafts) | Slice 4 |
| Knip — unused files, exports, dependencies | See §7.5 | advisory | Slice 4 |
| Trivy dependency-vulnerability scan — same gate, same step shape and same governed ignore format as §7.2’s row (added 2026-08-31 with AD #27) | AD #9’s “one tool uniform across Java and Node” is literal now: Trivy parses pnpm-lock.yaml natively, needs no JRE on the frontend runners, and --include-dev-deps is mandatory — a Vite app carries nearly everything as devDependencies and build tooling is supply chain |
PR (Fast lane, not drafts; report-only) | Slice 4 |
husky + lint-staged — biome check --write on staged files |
Formatting is fixed before it reaches CI | pre-commit | Slice 1 |
7.4 Test coverage
test-strategy.md § Coverage Targets sets business logic ≥ 80% and interactive UI ≥ 70%. How those are enforced matters more than the numbers:
- Measure per package, never on the aggregate. A repo-wide number is dominated by scaffolding, config and generated code, so it says nothing about whether the quote-approval rules are tested. JaCoCo
violationRulesscope to business-logic packages; Vitest thresholds scope tosrc/features,src/**/hooksandsrc/ui(the shared components, added at FS-14). - Report through Phase 1, gate from Phase 2. During Foundation and the first phase the denominator is still moving; a threshold set now is either meaningless or obstructive. Publish the report as a CI artifact from slice 4, read it in wave review, and turn on
violationRulesat the Phase 1 → Phase 2 boundary using the measured baseline. - Coverage never substitutes for the always-test list.
test-strategy.mdnames authorization, every state transition, role-scoped data access, validation and pagination as non-negotiable regardless of what the percentage says. 100% coverage of a component with no assertion about role scoping is worth nothing.
7.5 Dead code
- Frontend — Knip, advisory not blocking. It finds unused files, exports and dependencies, which is genuinely valuable across a 30-feature SPA. But the
FieldRendererregistry and route-level dynamic imports produce false positives by design, and a noisy gate teaches people to suppress rather than read. Run it in CI, publish the report, review it at each phase boundary. Promote to a gate only if the false-positive rate proves low. - In-file dead code is a hard error on both sides: in the frontends,
tsc’snoUnusedLocals/noUnusedParametersfailpnpm typecheck(Biome’snoUnusedImports/noUnusedVariablesonly warn, sopnpm checkalone does not fail on it); in the backend, Spotless’sremoveUnusedImportsand-Xlint:all -Werror. - Backend unused classes/methods: no tool. Java has no good free option; dead coupling stays a review responsibility (the former core/domain acceptance test that once surfaced it was retired by FS-14).
- Commented-out code is deleted, always (§2). Git remembers; a commented block is ambiguous forever about whether it is a plan or a corpse.
7.6 Commit, PR and comment conventions
commitlinton the huskycommit-msghook, configured for.claude/rules/git-conventions.md’s format —<type>(<TICKET>): <description>, allowed types, a header of at most 120 characters, no trailing period. A convention nobody can violate needs no policing in review.- PR-title lint in CI, same ruleset. PRs merge as merge commits (squash and rebase are disabled —
git-conventions.md § Pull Requests), and the PR title is carried in the merge commit onmain— it is how the change is named in history and release notes, so an unchecked title puts a malformed name in permanent history. The branch’s own commits are gated by commitlint separately. - Anonymous-
TODOcheck — a short CI script failing on anyTODO/FIXMEwithout a tracked id (F<n>,FS-<n>,BUG-<nnn>,UAT-<nnn>,OQ-<n>). §2 already requires the pointer; this makes it mechanical, and it is perhaps fifteen lines. - Fixture-leak check — a comparably short CI script grepping each built artifact (the Vite bundles, the backend jar) for the
FIXTURE_prefix §5 mandates, failing if any fixture reached a shipped build. Cheap, and it is the only guard that survives a refactor silently re-activating an error path that selects one. Wired with the other §7.6 scripts. - Everything else about comments in §2 — no narration of the next line, no authorship or history, Javadoc only where a contract needs stating — stays a review judgement. It is exactly the kind of thing a tool cannot assess and a reviewer can.
7.7 Supply chain and secrets
- Secret scanning =
gitleaksin the fast lane on all four delivery repos (pinned, checksum-verified binary; full-history scan; wired in the harness repo-hygiene workflow and in each app repo’s bootstrappedFast lanejob). GitHub’s native scanning with push protection was decided against — on this org’s plan it is a paid per-committer add-on. The consequence to understand: gitleaks catches a secret before merge but after push — a caught secret has already reached the remote and must be rotated, not just removed from the branch.CLAUDE.md § NEVER DOforbids committing secrets; the local discipline (never hardcode, use task-definition references / env) is the real first line. - Dependabot, weekly, with updates grouped (one PR per ecosystem, not per package) — ecosystems: Gradle, npm (pnpm lockfiles), and
github-actions, the last so workflow action pins stay on current majors without hand-tracking. Ungrouped Dependabot on four repos generates more PRs than a small team will ever review, and unreviewed update PRs are worse than none. In the two frontends, npm has two groups (F41):tooling(listed first: the packages onscripts/browser-gate/gate-inputs.json’stypesOnlyPackagesandtoolsNotRunByGatelists) andruntime(everything else). A tooling PR then changes nothing the browser gate loads, so it goes green with no gate run, and a runtime PR still needs one. The groups may drift from the lists; the lists decide, so a drifted package only costs a gate run. - Lockfiles committed everywhere —
gradle.lockfile(STRICT) andpnpm-lock.yaml. CI installs with--frozen-lockfile/ locked resolution so a build never silently drifts. - Deploy credentials are an IAM service user’s access key per workload account, held as a GitHub Environment secret — never in git, a log or a person’s hands, and rotated at least every 90 days (in dev, the shared key only if it may have leaked — F38 Rev 18) (
architecture.md § CI/CD Pipelines, Rev 50; F38 FR-19).
7.8 Suppression discipline
This is the rule that decides whether the rest of §7 still means anything in November.
- Every suppression carries a written justification at the suppression site —
@SuppressWarnings,biome-ignore, a dependency-cheque suppression, a skipped test. “Why this is safe here”, not “why this was inconvenient”. - No blanket disables. Never a file-level or rule-level off switch where a line-level one works; never a rule removed from config to make a build pass.
- Dependency-scan suppressions carry an expiry (AD #9) and are re-reviewed when they lapse.
- A skipped or
.onlytest fails the build. A quarantined test that nobody deletes is a permanent silent hole.- One recorded exception (lead, 2026-09-27):
forge-et-fee2e/seam/laptop-signin.seam.spec.tsskips its five tests unlessE2E_BACKEND_ENTRA_LAPTOP=1, because they need a backend running in laptop mode (F5-i-WI-1.3 plan, Decision 3). It is environment-gated, not quarantined: the tests run whenever that precondition holds, and any other value of the variable fails the run. A future CI check for skipped tests must either run the file against a laptop-mode backend (no network needed — the set-up is the plan’s Run A) or list these five skips as expected. - Backend — two recorded exceptions (lead, 2026-10-04, project audit E-9.1), both environment-gated:
AccountVolumeMeasurementIT(the NFR-2 volume measurement; runs withET_VOLUME_MEASUREMENT=1) andRealExportLocalCheckSpec(reads the real Pipedrive exports, which never leave a developer’s machine; runs when the threePIPEDRIVE_*_XLSXvariables are set outside CI).forge-et-bescripts/check-no-skipped-tests.pyfails the Fast lane on any other skip annotation insrc/test; itsALLOWEDtable and this list change together. - Frontends — one recorded exception (lead, 2026-10-04, project audit F-17):
src/test/scripts/browserGateRun.test.ts, byte-identical in both frontends, usesrunIfto run the half that applies to the repo it is in.scripts/check-no-skipped-tests.mjsin each frontend fails the Fast lane on any other.skip,.only,.todo,skipIforrunIfin a Vitest file undersrc/, and Vitest runs withallowOnly: false; browser tests keep the gate’sexpected-skips.json.
- One recorded exception (lead, 2026-09-27):
- JPA entities need no
NullAway.Initsuppression.build.gradlesets NullAway’sExternalInitAnnotations=jakarta.persistence.Entity, which exempts only an@Entityclass’s no-arg constructor (Hibernate fills the fields by reflection); every other constructor must still set its@NonNullfields. Do not add@SuppressWarnings("NullAway.Init")to an entity. Why: the option replaced twenty per-entity suppressions, each with its own justification, and is narrower than a class-level suppression (project audit E-2.4, measured 2026-10-05: the build fails without either and passes with the option alone). - Weakening a boundary rule is an architecture change → ASK FIRST (§1). It is never a local decision under deadline.
7.9 What we deliberately do not run
Recorded so it is not re-proposed, and so the reasoning is inspectable if the trade-off changes:
- Checkstyle, PMD, SpotBugs. Spotless owns formatting and Error Prone owns the correctness classes that actually bite. These three overlap both, need per-project rule tuning, and mostly produce findings reviewers learn to scroll past.
- SonarQube / SonarCloud. Meaningful setup and either a licence or a hosted dependency, largely duplicating the above for a fixed-window internal build.
- A nightly full E2E run in CI. Decided in AD-O-11 — it duplicates the release-tag run without adding a distinct failure class. The browser suite does run nightly off CI, on the lead’s Mac (
.forge/design/harness/test-run-cost.mdN-3). - Mutation testing (PIT / Stryker). Genuinely the best measure of test quality, and genuinely too slow to sit in this project’s CI budget. Worth revisiting if the codebase outlives V1.
- A repo-wide coverage percentage gate. See §7.4 — per-package or nothing.
8. Logging standard (backend)
Every rule here is anchored to one of this project’s own commitments — A.6.3 (AI bodies never in production logs), AD #13 (idempotent queue consumers), the pricing-sensitivity requirement — or to a failure mode already paid for on earlier Altrium engagements. §5’s logging block states the formats; this section is the discipline. Wired at FS-5; binding from the first feature WI.
8.1 Mechanics
- SLF4J via Lombok
@Slf4j— one logger per class, declared by the annotation, never a manualLoggerFactoryfield, never both. - Parameterized placeholders only —
log.info("… [quoteId={}]", id); never concatenation orString.format. Concatenation is also how a wholetoString()slips into a log line. - No level guards (
if (log.isDebugEnabled())) — redundant with parameterized logging. If the argument is genuinely expensive to compute, the better fix is usually not logging that value. - No raw object dumps. Never log an entity, DTO, or request body wholesale —
log.debug("account={}", account)re-introduces every deny-listed field at once. Log named fields. - Never log a trace id by hand —
traceId/spanIdare already on every line (§8.2).
8.2 Trace propagation — Micrometer Tracing
Every log line carries traceId/spanId, stamped into the JSON log pattern from the MDC by Micrometer Tracing (micrometer-tracing-bridge-brave). One user action reads as one trace across every hop:
- Request threads: two runtimeOnly artifacts on Boot 4, and both are load-bearing.
io.micrometer:micrometer-tracing-bridge-braveis the Brave binding; the auto-configuration that wires theTracer, the observation→tracing handler and the MDC correlation lives in Boot’s own moduleorg.springframework.boot:spring-boot-micrometer-tracing-brave—spring-boot-starter-actuatordoes not pull it, and its POM does not pull the binding (the same modular split asspring-boot-flywaybesideflyway-core, §2.4). With both present, request threads are auto-instrumented, the MDC carriestraceId/spanId, and the log pattern prints them. With the binding alone the app boots and traces nothing — no MDC, notraceIdon any envelope — measured on a realbootRunat FS-5 (the same silent boots-but-does-nothing failurespring-boot-flywayhad). No application code writes to the MDC — ever. @Async/ executor hops need one config step: the MDC is per-thread, so context does not follow a thread hop by itself. Every executor the app defines (the@Asyncconfiguration, anyTaskExecutorbean) sets a task decorator that snapshots the submitting thread’s MDC (MDC.getCopyOfContextMap()), installs it on the worker for the task’s duration, and clears it in afinally— the clear is what stops one task’s context leaking into the next task to reuse the pooled thread. Applied in the async configuration, once, never per call site. Pair every such executor with a bounded pool andAbortPolicy— a capped queue that rejects at submission rather than absorbing a backlog or running the task on the submitting (request) thread. An unwrapped executor is a review-blocking defect: its logs are orphans no trace can find.- Queue legs (SQS): a thread-local cannot cross a queue. The producer writes the trace context into SQS message attributes alongside the AD #13 idempotency key; the consumer restores it into the MDC before processing, so the worker’s lines join the trace that enqueued the job. On redelivery the restored trace still identifies the original request.
- Scheduled legs (EventBridge → SQS, AD #12): no originating request exists — the consumer starts a fresh trace and logs the schedule/job name and idempotency key on the first line, so the run is findable by name.
- Client-facing errors return the error code plus the
traceId(§2’s correlation rule — the correlation id is the trace id; there is no second scheme). A user-reported error is greppable in one step without exposing internals.
8.3 Levels — and the fault-vs-outcome rule
| Level | Use for |
|---|---|
| ERROR | A fault: the system did something wrong or could not do its job — dependency down, invariant violated, unhandled exception. Someone should look. Always with the exception as the last argument (that is what prints the stack trace; interpolating e.getMessage() discards it). |
| WARN | Degraded-but-handled: a guard tripped, a retry recovered, a fallback taken (ai.degraded.manual — circuit open, feature fell back to the manual path). |
| INFO | Business events (§8.4). The production default — assume every INFO line is always on. |
| DEBUG | Execution flow, inputs, intermediate state, masked PII. Off in production. |
| TRACE | Reads, ticks, iterations. |
An expected business outcome is never an ERROR. A quote blocked by its readiness gate, a stale price rejected, a failed login, a permission denial — these are the system working correctly and producing a negative answer: WARN at most, usually DEBUG. The test: if this fired a hundred times tonight, would that mean something is broken — or that a hundred users did an ordinary thing? ERROR is the level the SNS alarms watch; every outcome logged as ERROR raises the noise floor, and the noise floor is how a real fault gets ignored. Corollary: a broad catch (Exception) cannot pick the level correctly — it must distinguish expected domain exceptions (WARN/DEBUG) from everything else (ERROR), which is §2’s no-swallow rule approached from the level side.
The PII exception to “exception last”. Where an exception’s message can carry a row or PII (a JDBC or constraint failure on a security or audit path), log the exception class only (exception={} with e.getClass().getName()), and say why in a comment at the site — otherwise a reviewer applying the rule above will restore the leak.
A batch job that fails every unit it tried logs once at ERROR. A scheduled job that works through many units (mailbox connections, queued items) logs each unit’s failure at WARN, since one bad connection is degraded-but-handled. When every unit in a run failed (and at least one was tried), that is an outage, not a bad unit: the run ends with one ERROR line naming the job and the count, so the alarm fires.
8.4 The business-event contract
A business event is a service method that persists or mutates domain state, causes an external side effect (mail, AI call, S3 write, queue publish), or represents a lifecycle transition. Pure computation, helpers, and pass-throughs are not business events.
- Exactly one INFO per business event, owned by the service method that performs the change, logged after it succeeds — never duplicated at both the calling and called service (“how many quotes were approved today?” must be answerable by counting lines).
- A method-entry DEBUG documenting intent and inputs.
- Reads are TRACE, not INFO — entry plus result count, never the results. Nothing changed; nothing to announce.
- Never log an outcome you did not verify. A log line is a factual claim — “Notification Sent” before the send returns makes the log lie, and a log that lies ends investigations in the wrong place.
- Multi-write operations log each leg. Where one operation writes twice (record + queue publish, entity + extension row), each leg after the first gets its own INFO — a gap between two consecutive INFO lines then reads as “leg two never ran.”
8.5 Message structure
[ENTITY] [ACTION] - [IDENTIFIER] [DETAILS] [METADATA]
Quote Approval Initiated - [quoteId={}, approverId={}]
Quote Approved - [quoteId={}, dealId={}] readiness checklist complete
Price Week Published - [standardId={}, weekStart={}] [rowCount={}]
Sample Round Advanced - [sampleId={}, round={}] awaiting buyer feedback
Lead Captured - [leadId={}, source=trade-show] notification queued
- ACTION is the real business action in domain words — never
Processed/Handled.Updatedis allowed only for a general edit of a record’s fields (the entity’sPATCH, as inAccount Updated), including one that also changes the owner, which it reports asreassigned=; an action with its own endpoint gets its own name (Archived,Published). If you cannot name it confidently, re-read the method rather than reaching for a generic verb. - Identifiers are
[field={}], guaranteed non-null, authoritative ids only — no DB-generated ids before the save, no values an async side effect will produce later. Silence beats anulla reader will take for data. - Reasons are prose in DETAILS, never fake metadata —
Price Publish Skipped - [standardId={}] window already closed, not[reason="windowClosed"]. - Service-layer entry language is “Initiated”; “Requested” is ingress language and belongs to the HTTP layer.
8.6 The deny-list — what never appears in a log
Overrides every other rule here. “No sensitive data” is not enforceable; a named list is.
- Never, at any level, in any environment: credentials, session ids, OAuth/Graph tokens and refresh tokens, AWS credentials, presigned URLs, password hashes, API keys, cookie values.
- AI prompt and response bodies: never in production logs — development only. This is a contractual commitment (
proposal § A.6.3, AD-O-6), not hygiene. The sanctioned line per AI call is the §5 metadata set:{feature, provider, model, tokens, cost_usd, latency, outcome}. - PII — buyer contact details, synced email bodies, captured business-card content: never above DEBUG, and masked even there. Log record ids, not payloads.
- Commercial figures — weekly bulk prices, margins, costs, quote amounts: not at INFO. Pricing sensitivity is a client requirement (F26/F7/F14 carry it); an INFO line is permanent operational record. Log the id and the outcome (
Price Week Published,[rowCount={}]), not the numbers. DEBUG may carry amounts in development only.
8.7 Configuration
- Per-environment levels, all five SLF4J levels in play.
local/test: application packages default DEBUG, TRACE freely usable — a laptop can afford it.devandprod: default INFO. Levels live inapplication.ymlunderlogging.leveland are overridden per environment through the task definition (§5): Spring Boot mapsLOGGING_LEVEL_COM_EMPIRETEAS_PRICING=DEBUGontologging.level.com.empireteas.pricing, so when something goes wrong in dev or prod, raising one package to DEBUG is a task-definition config change and a service restart — no rebuild, no redeploy of code, and turned back down the same way. - What makes DEBUG-in-prod safe to even offer is §8.6. The deny-list holds at every level — secrets never, PII masked even at DEBUG — precisely so that turning DEBUG on during an incident does not become the leak. A DEBUG line that would violate §8.6 is wrong at authoring time, not at enablement time.
- No framework package is pinned to DEBUG for all environments —
org.springframework.securityat DEBUG in production dumps authentication internals continuously. - One authoritative place: levels are governed by
application.yml; do not add alogback-spring.xmlthat also sets them. - One JCL provider on the classpath — and on Boot 4 it is not a Spring artifact. Spring Framework 7 removed
spring-jcl, which is what used to supply the Commons Logging API (Boot 3.5.16 lockedspring-jcl:6.2.19; Boot 4.2.x locks no replacement, AD #25 —git -C ../forge-et-be grep -c spring-jcl gradle.lockfilere-checks it). The provider is now an explicitorg.slf4j:jcl-over-slf4jbridge, which routes JCL into the same SLF4J/Logback pipeline everything else uses. It sits ontestRuntimeOnlyinforge-et-be’s onebuild.gradle(spring-testlogs through JCL) and onruntimeOnlythere too — the first realbootRunshowedspring-corelogs through JCL on the main runtime too, ahead of the AWS SDK that was expected to force the move. Omitting it is not a degraded-logging failure — every test task dies at test-discovery time withClassNotFoundException: org.apache.commons.logging.LogFactory, before a spec runs, reading like a test-framework fault. Still exclude the realcommons-loggingjar globally (configurations.configureEach { exclude group: 'commons-logging', module: 'commons-logging' }) — the AWS SDK pulls it transitively viahttpclient, and two providers make logging discovery nondeterministic. This repo is unusually exposed: S3, SQS, SES, EventBridge and Bedrock clients all ride the same SDK.
8.8 Frontend
No console.* in committed code (Biome noConsole, §7.3 — an error, not a warning). Errors route to the error boundary and the telemetry seam. The capture app inherits this section per the scope note at the top of this document.
9. Documentation standard — Javadoc and Spock specs
§2’s comment philosophy governs everywhere; this section is the contract for the two places documentation is structural: the published Java surface and the Groovy specs. Each rule below exists because the opposite has been watched fail — confident doc claims refuted at the call site, spec blocks restating their own method names at scale. The -Xdoclint gate (§7.2) enforces the mechanical half.
9.1 Javadoc — document the contract, not the implementation
Where it is required (unchanged from §2): a package’s published surface — service interfaces, shared configuration types, any seam another package calls through. Feature code prefers expressive names + tests; controllers, DTOs and accessors get no boilerplate blocks. Where a block exists, these rules apply:
- Generated members carry no Javadoc, and none is owed. A Lombok-generated accessor or constructor (§2.1) is not in the source the javadoc tool reads; the contract prose that would have sat on it lives on the field. Never hand-write a member to give a comment somewhere to live — the code comes first, the documentation describes it.
- State what a caller can rely on, including the boring paths — empty input, missing record, a second identical call (idempotency is a contract). State why when the shape is non-obvious, and what was deliberately not done when a reader would otherwise wonder. Never narrate the steps.
- One claim per
<p>, bold topic lead-ins (<p><b>Idempotent by construction.</b> …), name the rejected alternative where one was seriously considered, and every{@link}must resolve (doclint fails the build on it). {@link}uses the short name backed by a normal import — never an inline FQCN. Javadoc resolves links against the file’s imports, an import used only by Javadoc is legitimate (Spotless’sremoveUnusedImportscounts Javadoc references as usage and keeps it), and a fully-qualified path inline is noise that survives refactors wrong. The only excuse for a FQCN in a link is a simple-name clash with an already-imported type.- Tags: public/protected methods — every
@param,@returnif non-void,@throwsfor every exception a caller can hit (unchecked included), naming the error-envelope code the client will actually see (@throws QuoteNotReadyException {@code QUOTE_NOT_READY} — …) so a support symptom greps back to the throw site. Private helpers take prose, no tags. A description is never optional — a block that is only tags is not documentation. - Absolutes are whole-codebase claims. No / every / never / only / nowhere — grep the codebase or drop the quantifier. Prefer a structural fact over a quantified one (“neither creation path audits” beats “most records are unaudited”). If a claim depends on framework behaviour, verify it against the pinned version, not memory.
- Document what the code does. If the code is wrong, document what it does and raise a finding — never document the aspiration, never silently fix while documenting.
9.2 Spock specs — the block says what the test cannot
A feature method is already named in prose (def "quote gate blocks when a checklist item is open"()) and labelled given:/when:/then: — restating any of that in a doc block is the exact defect §2 bans. The bar for every block: does it say something the name, labels, and assertions do not? If not, it must not exist.
- The spec class block is mandatory and carries the weight, in priority order: what is under test and what breaks if it is wrong; what the spec pins (the specific property a refactor could silently drop); the doubling strategy in one clause (“mocked
AIProvider, real Postgres via Testcontainers”); and what the spec cannot prove — the sentence that stops it being read as proving more than it does. - Shared fixture builders and
BaseSpechelpers are always documented (prose, no tags) — the highest-value blocks in the test tree. - Feature methods get a block only where it earns one: a regression with a history (name the
BUG-NNN), why this data when a literal is load-bearing (“the max is deliberately not last — last cannot distinguish ‘take max’ from ‘take latest’”), a mutation that would survive green, what this test deliberately does not prove and which sibling does, a non-obvious assertion strategy (including a deliberate absence of assertion). - No
@param/@return/@throwson feature methods — there is no caller contract. Prose only. where:tables — document the axis, not the rows. The table is the list; prose rows drift. A single load-bearing row takes an inline//on that row.- Prefer an inline
//where the point is local to one line inside a block; a method-level block is for the method as a whole. - Forbidden: “Spock specification for X” as the whole first sentence · a bullet list of the test names (a TOC that rots) · filler intensifiers (“comprehensive”, “all”, “various”) · the boilerplate mocked-dependencies closer · authorship tags (
CLAUDE.md § NEVER DO).
9.3 Gradle and scripts
build.gradle and CI/hook scripts follow §2’s philosophy in ///# form: a comment states the constraint or the why — what breaks if the block is removed, which rule mandates it — never a narration of the next line. The bar for a tool-configuration block (Spotless, the Javadoc gate): explain what this tool catches that nothing else in the build does — that is the sentence that stops the block being deleted as noise.