- YOUR FIVE-MINUTE WALKTHROUGH
Follow an order from stock to allocation.
This demo reconstructs a warehouse routing workflow with fictional data. Every
From d4a8a65b635ef7033285d26f004f67e008749408 Mon Sep 17 00:00:00 2001
From: grantmaye <80912251+grantmaye@users.noreply.github.com>
Date: Wed, 7 Oct 2026 17:57:44 -0400
Subject: [PATCH 2/4] Format reviewed UI cleanup
---
src/app/globals.css | 5 ++++-
1 file changed, 4 insertions(+), 1 deletion(-)
diff --git a/src/app/globals.css b/src/app/globals.css
index 67fc731..0bad7bd 100644
--- a/src/app/globals.css
+++ b/src/app/globals.css
@@ -1180,4 +1180,7 @@ form .button {
}
}
-.warehouse-region { font-size: 13px; color: var(--muted); }
+.warehouse-region {
+ font-size: 13px;
+ color: var(--muted);
+}
From fb26440146bfc7115d5923545922aee736b56ab8 Mon Sep 17 00:00:00 2001
From: grantmaye <80912251+grantmaye@users.noreply.github.com>
Date: Fri, 9 Oct 2026 01:58:19 -0400
Subject: [PATCH 3/4] Fix numeric audit history ordering and cover exact origin
boundaries
---
src/app/api/graphql/route.ts | 7 ++--
src/lib/request-origin.ts | 14 ++++++++
src/lib/routing.ts | 4 ++-
tests/audit-history.ts | 35 ++++++++++++++++++++
tests/audit.test.ts | 13 ++++++++
tests/e2e/dashboard.spec.ts | 62 ++++++++++++++++++++++++++++++-----
tests/postgres.integration.ts | 12 +++++++
tests/request-origin.test.ts | 50 ++++++++++++++++++++++++++++
8 files changed, 182 insertions(+), 15 deletions(-)
create mode 100644 src/lib/request-origin.ts
create mode 100644 tests/audit-history.ts
create mode 100644 tests/audit.test.ts
create mode 100644 tests/request-origin.test.ts
diff --git a/src/app/api/graphql/route.ts b/src/app/api/graphql/route.ts
index 870049f..b63c01b 100644
--- a/src/app/api/graphql/route.ts
+++ b/src/app/api/graphql/route.ts
@@ -4,6 +4,7 @@ import { NextRequest, NextResponse } from 'next/server';
import { getDatabase } from '@/lib/database';
import { createApi } from '@/lib/graphql';
import { RoutingService } from '@/lib/routing';
+import { hasAllowedOrigin } from '@/lib/request-origin';
export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';
@@ -12,11 +13,7 @@ const started = api.start();
export async function POST(request: NextRequest) {
if (!request.headers.get('content-type')?.startsWith('application/json'))
return NextResponse.json({ error: 'Use application/json.' }, { status: 415 });
- const origin = request.headers.get('origin');
- // NextURL normalizes loopback IPs to localhost. Preserve the browser's Host
- // when comparing origins so legitimate 127.0.0.1 requests remain same-origin.
- const expectedOrigin = `${request.nextUrl.protocol}//${request.headers.get('host')}`;
- if (origin && origin !== expectedOrigin)
+ if (!hasAllowedOrigin(request))
return NextResponse.json({ error: 'Cross-origin requests are not allowed.' }, { status: 403 });
const body = await request.text();
if (body.length > 16000)
diff --git a/src/lib/request-origin.ts b/src/lib/request-origin.ts
new file mode 100644
index 0000000..ccb6868
--- /dev/null
+++ b/src/lib/request-origin.ts
@@ -0,0 +1,14 @@
+import type { NextRequest } from 'next/server';
+
+/** Compare the browser's exact origin, not an allowlist of loopback aliases. */
+export function hasAllowedOrigin(request: Pick): boolean {
+ const origin = request.headers.get('origin');
+ // Non-browser clients such as curl may omit Origin, as before.
+ if (origin === null) return true;
+ const host = request.headers.get('host');
+ if (!host) return false;
+ // NextURL canonicalizes 127.0.0.1 and [::1] to localhost. Use the actual
+ // request Host, including its port, so each spelling works only with itself.
+ // Do not use X-Forwarded-Host to expand trust without a proxy trust policy.
+ return origin === `${request.nextUrl.protocol}//${host}`;
+}
diff --git a/src/lib/routing.ts b/src/lib/routing.ts
index 5d5c0ee..c2a5853 100644
--- a/src/lib/routing.ts
+++ b/src/lib/routing.ts
@@ -185,8 +185,10 @@ export class RoutingService {
)
).map((r) => r.data),
inventory: await inventoryFor(tx, sessionId),
+ // Qualify the numeric column: the output `id` is text for GraphQL and
+ // ORDER BY id would sort that alias lexically (9 before 10 or 100).
events: await tx.query(
- 'SELECT id::text,id::text AS "eventId",order_id AS "orderId",action,detail,created_at::text AS "createdAt" FROM audit_events WHERE session_id=$1 ORDER BY id DESC LIMIT 100',
+ 'SELECT id::text,id::text AS "eventId",order_id AS "orderId",action,detail,created_at::text AS "createdAt" FROM audit_events WHERE session_id=$1 ORDER BY audit_events.id DESC LIMIT 100',
[sessionId],
),
storageMode: this.db.mode,
diff --git a/tests/audit-history.ts b/tests/audit-history.ts
new file mode 100644
index 0000000..238904b
--- /dev/null
+++ b/tests/audit-history.ts
@@ -0,0 +1,35 @@
+import assert from 'node:assert/strict';
+import { randomUUID } from 'node:crypto';
+import type { Database } from '../src/lib/database';
+import { RoutingService } from '../src/lib/routing';
+
+// Shared contract: exercise the actual dashboard SQL on both database adapters.
+export async function assertRecentAuditHistory(db: Database) {
+ const session = randomUUID();
+ const otherSession = randomUUID();
+ const service = new RoutingService(db);
+ try {
+ await service.initialize(session);
+ const inserted = await db.query<{ id: string; detail: string }>(
+ `INSERT INTO audit_events(session_id, action, detail, created_at)
+ SELECT $1, 'HISTORY_TEST', 'Event ' || n, '2026-01-01T00:00:00Z'::timestamptz
+ FROM generate_series(1, 125) AS n
+ RETURNING id::text, detail`,
+ [session],
+ );
+ // A later event from another workspace must not leak into this history.
+ await service.initialize(otherSession);
+ const expected = inserted.sort((a, b) => (BigInt(a.id) > BigInt(b.id) ? -1 : 1)).slice(0, 100);
+ assert.ok(expected.every((event) => BigInt(event.id) > 9n));
+ const actual = (await service.dashboard(session)).events;
+ assert.equal(actual.length, 100);
+ assert.deepEqual(
+ actual.map(({ id, detail }) => ({ id, detail })),
+ expected,
+ 'history must contain the newest 100 numeric IDs in descending order',
+ );
+ assert.ok(actual.every((event) => event.action === 'HISTORY_TEST'));
+ } finally {
+ await db.query('DELETE FROM demo_sessions WHERE id=$1 OR id=$2', [session, otherSession]);
+ }
+}
diff --git a/tests/audit.test.ts b/tests/audit.test.ts
new file mode 100644
index 0000000..4ca912f
--- /dev/null
+++ b/tests/audit.test.ts
@@ -0,0 +1,13 @@
+import { test } from 'node:test';
+import { createDatabase, migrate } from '../src/lib/database';
+import { assertRecentAuditHistory } from './audit-history';
+
+test('audit history returns the newest 100 events across numeric ID boundaries', async () => {
+ const db = await createDatabase();
+ try {
+ await migrate(db);
+ await assertRecentAuditHistory(db);
+ } finally {
+ await db.close();
+ }
+});
diff --git a/tests/e2e/dashboard.spec.ts b/tests/e2e/dashboard.spec.ts
index 5a05978..f23d77b 100644
--- a/tests/e2e/dashboard.spec.ts
+++ b/tests/e2e/dashboard.spec.ts
@@ -53,17 +53,61 @@ test('stock shortage, quote failure, audit trail and last-unit race', async ({ p
await expect(page.getByRole('heading', { name: 'Decision trail' })).toBeVisible();
});
-test('HTTP origin checks allow the current host and reject a foreign origin', async ({
+test('HTTP origin checks allow each local host and reject mismatched origins', async ({
request,
baseURL,
}) => {
const data = { query: '{ products { sku } }' };
- const allowed = await request.post('/api/graphql', { headers: { origin: baseURL! }, data });
- expect(allowed.status()).toBe(200);
- expect((await allowed.json()).data.products).toHaveLength(5);
- const rejected = await request.post('/api/graphql', {
- headers: { origin: 'https://unrelated.example' },
- data,
- });
- expect(rejected.status()).toBe(403);
+ for (const hostname of ['localhost', '127.0.0.1']) {
+ const url = new URL(baseURL!);
+ url.hostname = hostname;
+ const allowed = await request.post(`${url.origin}/api/graphql`, {
+ headers: { origin: url.origin },
+ data,
+ });
+ expect(allowed.status()).toBe(200);
+ expect((await allowed.json()).data.products).toHaveLength(5);
+ }
+ const mismatchedPort = new URL(baseURL!);
+ mismatchedPort.port = String(Number(mismatchedPort.port) + 1);
+ for (const origin of [
+ 'https://unrelated.example',
+ baseURL!.replace('127.0.0.1', 'localhost'),
+ mismatchedPort.origin,
+ baseURL!.replace('http:', 'https:'),
+ 'null',
+ '',
+ ]) {
+ const rejected = await request.post('/api/graphql', {
+ headers: { origin, 'x-forwarded-host': origin.replace(/^https?:\/\//, '') },
+ data,
+ });
+ expect(rejected.status(), origin).toBe(403);
+ expect(await rejected.json()).toEqual({ error: 'Cross-origin requests are not allowed.' });
+ expect(rejected.headers()['set-cookie']).toBeUndefined();
+ }
+});
+
+test('activity renders numeric event order after more than nine events', async ({ page }) => {
+ await page.goto('/');
+ await expect(page.getByText('RNO recommended', { exact: true })).toBeVisible();
+ const ids: string[] = [];
+ for (let index = 0; index < 12; index++) {
+ const response = await page.request.post('/api/graphql', {
+ data: {
+ query: `mutation { createOrder(input: { customer: "History fixture", destinationId: NYC,
+ items: [{ sku: "PH-100", quantity: 1 }] }) { id } }`,
+ },
+ });
+ const result = await response.json();
+ expect(result.errors).toBeUndefined();
+ ids.push(result.data.createOrder.id);
+ }
+ await page.getByRole('button', { name: 'Activity log', exact: true }).click();
+ await page.getByRole('button', { name: 'Refresh', exact: true }).click();
+ const articles = page.locator('.timeline article');
+ await expect(articles).toHaveCount(13);
+ await expect(articles.first().getByRole('button')).toHaveText(ids[11]);
+ await expect(page.locator('.timeline article button')).toHaveText([...ids].reverse());
+ await expect(articles.last()).toContainText('DEMO READY');
});
diff --git a/tests/postgres.integration.ts b/tests/postgres.integration.ts
index 8f30e58..1b8b53f 100644
--- a/tests/postgres.integration.ts
+++ b/tests/postgres.integration.ts
@@ -3,6 +3,18 @@ import assert from 'node:assert/strict';
import { randomUUID } from 'node:crypto';
import { createDatabase, migrate } from '../src/lib/database';
import { RoutingService } from '../src/lib/routing';
+import { assertRecentAuditHistory } from './audit-history';
+
+test('PostgreSQL audit history returns the newest 100 numeric IDs', async () => {
+ assert.ok(process.env.DATABASE_URL, 'Set DATABASE_URL to a disposable PostgreSQL database.');
+ const db = await createDatabase(process.env.DATABASE_URL);
+ try {
+ await migrate(db);
+ await assertRecentAuditHistory(db);
+ } finally {
+ await db.close();
+ }
+});
test('separate PostgreSQL pools compete for one unit', async () => {
assert.ok(process.env.DATABASE_URL, 'Set DATABASE_URL to a disposable PostgreSQL database.');
diff --git a/tests/request-origin.test.ts b/tests/request-origin.test.ts
new file mode 100644
index 0000000..f503d41
--- /dev/null
+++ b/tests/request-origin.test.ts
@@ -0,0 +1,50 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { NextRequest } from 'next/server';
+import { hasAllowedOrigin } from '../src/lib/request-origin';
+
+test('same-origin localhost, IPv4 and IPv6 loopback survive NextURL normalization', () => {
+ for (const host of ['localhost:3000', '127.0.0.1:3000', '[::1]:3000']) {
+ const origin = `http://${host}`;
+ const request = new NextRequest(`${origin}/api/graphql`, { headers: { host, origin } });
+ assert.equal(request.nextUrl.hostname, 'localhost');
+ assert.equal(hasAllowedOrigin(request), true, origin);
+ }
+});
+
+test('origin checks retain exact host, port and scheme boundaries', () => {
+ for (const origin of [
+ 'https://unrelated.example',
+ 'http://localhost:3000',
+ 'http://127.0.0.1:3001',
+ 'https://127.0.0.1:3000',
+ 'http://127.0.0.1.evil.example:3000',
+ 'http://127.0.0.1:3000@evil.example',
+ 'null',
+ '',
+ ]) {
+ const request = new NextRequest('http://127.0.0.1:3000/api/graphql', {
+ headers: { host: '127.0.0.1:3000', origin, 'x-forwarded-host': origin.slice(7) },
+ });
+ assert.equal(hasAllowedOrigin(request), false, origin);
+ }
+});
+
+test('explicit origins require Host; absent Origin remains usable by CLI clients', () => {
+ const url = 'http://localhost:3000/api/graphql';
+ assert.equal(
+ hasAllowedOrigin(new NextRequest(url, { headers: { origin: 'http://localhost:3000' } })),
+ false,
+ );
+ assert.equal(
+ hasAllowedOrigin(new NextRequest(url, { headers: { host: 'localhost:3000' } })),
+ true,
+ );
+});
+
+test('HTTPS same-origin requests remain allowed without a loopback exception', () => {
+ const request = new NextRequest('https://dispatch.example/api/graphql', {
+ headers: { host: 'dispatch.example', origin: 'https://dispatch.example' },
+ });
+ assert.equal(hasAllowedOrigin(request), true);
+});
From 9ee34044b3ae1031886cd995b4c1c47179ef8982 Mon Sep 17 00:00:00 2001
From: grantmaye <80912251+grantmaye@users.noreply.github.com>
Date: Fri, 9 Oct 2026 01:58:19 -0400
Subject: [PATCH 4/4] Teach the full Dispatch build with UI lessons and a
tested order walkthrough
---
README.md | 2 +
docs/technical-manual.md | 381 +++++++++++++++++++++++++++++++++++++-
tests/walkthrough.test.ts | 59 ++++++
3 files changed, 441 insertions(+), 1 deletion(-)
create mode 100644 tests/walkthrough.test.ts
diff --git a/README.md b/README.md
index 2c24801..995d11e 100644
--- a/README.md
+++ b/README.md
@@ -22,6 +22,8 @@ Built with **Next.js, TypeScript, Node.js, Apollo Server, GraphQL, and PostgreSQ
## Learn the project
+Start with the [build-from-zero lesson](docs/technical-manual.md#10-build-it-from-zero-a-teaching-sequence), then [build the React/CSS interface](docs/technical-manual.md#11-build-the-interface-from-layout-to-interaction) and [trace FR-1041 from click to SQL](docs/technical-manual.md#12-follow-fr-1041-from-a-click-to-sql-and-back). The manual includes exercises with executable solutions and explains the demo's limits.
+
- [Technical manual](docs/technical-manual.md): setup, architecture, contracts, failure labs, extension exercises, and interview answers.
- [Product story](docs/product-story.md): the hypothetical workflow, intended value, limitations, and a 60–90 second demo script.
diff --git a/docs/technical-manual.md b/docs/technical-manual.md
index 6c08f05..5593cd2 100644
--- a/docs/technical-manual.md
+++ b/docs/technical-manual.md
@@ -2,6 +2,10 @@
This manual teaches the **Dispatch** demo from first run to maintenance. Read the [product story](product-story.md) for the problem it illustrates and the [interview walkthrough](INTERVIEW-WALKTHROUGH.md) for a shorter presentation. Source links below are the implementation, not claims about a production deployment.
+**Start learning here:** [first lesson and build sequence](#10-build-it-from-zero-a-teaching-sequence), then [build the UI](#11-build-the-interface-from-layout-to-interaction), then [trace FR-1041 end to end](#12-follow-fr-1041-from-a-click-to-sql-and-back), and [practice with solutions](#13-hands-on-exercises-with-solutions). Sections 1–9 remain the reference manual for running, operating, and extending the project.
+
+This is a reconstruction of how to build the **current code**, not a claim about the historical order in which it was written. You can learn the design without assuming it was deployed in production. Use a separate checkout, unused port, and separate data directory for experiments. Do not reset a workspace someone is using for a live walkthrough.
+
## 1. Vocabulary and first principles
An **order** is a customer label, a sample destination, and one or more SKU/quantity lines. A **SKU** identifies a product. **On-hand** means physically counted stock in this model; **reserved** means promised to an allocated order. **Available** is `on_hand - reserved`. Allocation reserves stock; it does not purchase a label or ship goods.
@@ -161,7 +165,7 @@ The audit failure test wraps the transaction adapter and throws at INSERT INTO a
### Diagnose symptoms
-A 503 health response means database readiness failed; inspect the server log and connection/directory configuration first. A cross-origin 403 often means the browser/proxy origin does not match the effective server origin. Preserve the host consistently and check proxy configuration. A stale preview is expected under concurrent changes; route rechecks stock. A duplicate embedded server can lock or corrupt its files: stop duplicate processes and use a fresh data directory. Never delete a live shared database to fix a demo.
+A 503 health response means database readiness failed; inspect the server log and connection/directory configuration first. A cross-origin 403 means the browser origin must be compared with the request protocol and actual Host, including port; see [request-origin.ts](../src/lib/request-origin.ts). Both `localhost` and `127.0.0.1` work when the browser uses the same spelling for the page and its request. They are not interchangeable origins. A stale preview is expected under concurrent changes; route rechecks stock. A duplicate embedded server can lock or corrupt its files: stop duplicate processes and use a fresh data directory. Never delete a live shared database to fix a demo.
## 8. Design choices and extension exercises
@@ -187,3 +191,378 @@ A 503 health response means database readiness failed; inspect the server log an
**What does the test suite prove?** Reproducible domain behavior, rollback, separate-connection contention in PostgreSQL, and browser flows. It does not prove arbitrary production load, real carrier correctness, or authenticated multitenancy.
**What would you change first for production?** Establish real identity/data boundaries and external contracts, then normalized durable reservation ownership and migrations. Preserve the tested atomicity while adding operational limits; do not begin with cosmetic rewrites.
+
+## 10. Build it from zero: a teaching sequence
+
+### First lesson: separate a screen from a decision
+
+Start with a piece of paper. Draw two warehouse boxes and write “45 phones, 28 headsets” in Buffalo and “32 phones, 40 headsets” in Reno. Write FR-1041 beside them: four phones and two headsets to New York. Both boxes can cover the full order. Given quotes of $18.12 and $33.26, choose Buffalo. Cross out **available** 45/28 and replace it with 41/26. Do not change on-hand 45/28: the goods have been promised, not shipped.
+
+Now open three files side by side:
+
+1. [dashboard.tsx](../src/components/dashboard.tsx), the button with `act(() => routeOrder(selected.id), ...)`: what the person does.
+2. [client.ts](../src/lib/client.ts), `routeOrder`: what the browser asks the server to do.
+3. [routing.ts](../src/lib/routing.ts), `RoutingService.route`: what the server must verify before making a promise.
+
+The browser may display an old preview. The server must decide using current inventory. That distinction is the foundation of this project. You do not need to understand every React hook or SQL statement before understanding it.
+
+### Toolchain in plain language
+
+**JavaScript** runs the program. **TypeScript** adds types checked during development; those types disappear at runtime. **Node.js** runs JavaScript on the server. **React** turns state into interface elements. **Next.js** supplies the web server, file-based routes, React build pipeline, and production packaging. **npm** installs packages and runs the commands in package.json.
+
+**GraphQL** is the typed request language between browser and server. **Apollo Server** validates and executes that schema. It is not a separate deployed service here. **Zod** validates actual runtime input in the service, including callers that do not use GraphQL. **PostgreSQL** stores records and provides transactions; **pg** connects to a PostgreSQL server, while **PGlite** runs an embedded PostgreSQL engine. **Lucide React** supplies the icons. **Prettier** formats source. **tsx** lets Node execute the TypeScript tests. **Playwright** drives desktop and mobile browser tests.
+
+Use the checked-in [package.json](../package.json) and [package-lock.json](../package-lock.json), not a list of unpinned “latest” installs. The lockfile specifies resolved versions; `npm ci` reproduces them. Node must satisfy `>=22.13`; CI uses Node 22. A successful Node 24 local run does not replace that CI coverage.
+
+| Command | What it does | When to use it |
+| ----------------------- | ---------------------------------------------------------------------------- | -------------------------------------------------------- |
+| `npm ci` | Installs the lockfile's dependency tree | After cloning or dependency changes |
+| `npm run dev` | Starts Next development mode | Editing and learning |
+| `npm run build` | Compiles the production app and checks types | Before production-mode testing |
+| `npm start` | Serves the existing production build | Stable local walkthrough |
+| `npm run typecheck` | Runs TypeScript without emitting JS | Catch mismatched types |
+| `npm test` | Executes `tests/*.test.ts` with Node + tsx | Domain, API, origin and embedded audit checks |
+| `npm run check` | Typecheck followed by unit/service tests | Normal pre-commit check |
+| `npm run test:postgres` | Runs server-database integration tests | Numeric audit history and separate-pool contention |
+| `npm run test:e2e` | Starts an isolated production server and runs browser tests | UI/HTTP regression checks |
+| `npm run format:check` | Checks formatting without edits | Before committing |
+| `npm run format` | Applies Prettier to the project | Intentional formatting pass; inspect the diff |
+| `npm run db:reset` | Deletes all sessions in the configured database after its confirmation guard | Disposable databases only; not a troubleshooting default |
+
+There is no separate lint script, CSS framework, ORM, or client-side state library in this project.
+
+### Repository map
+
+```text
+src/app/layout.tsx HTML shell, page metadata, global CSS import
+src/app/page.tsx / route: renders Dashboard
+src/app/globals.css design tokens, layout, components, responsive rules
+src/app/api/graphql/route.ts POST transport, cookie, Apollo execution
+src/app/api/health/route.ts database readiness
+src/components/dashboard.tsx all four views, dialogs, state, Metric helper
+src/lib/model.ts types and catalog/destination/warehouse fixtures
+src/lib/shipping.ts ShippingProvider interface and rate simulator
+src/lib/database.ts SQL adapters and schema initialization
+src/lib/seed.ts six initial orders and inventory
+src/lib/routing.ts policy and transactional application service
+src/lib/graphql.ts GraphQL schema, resolvers, limits and errors
+src/lib/client.ts browser fetch and GraphQL operations
+src/lib/request-origin.ts exact request-origin policy
+tests/ service, audit, origin, PostgreSQL and browser tests
+scripts/reset.ts explicit all-session reset utility
+docs/ this manual, API, architecture, operations and walkthrough
+```
+
+[tsconfig.json](../tsconfig.json) enables strict TypeScript and maps `@/*` to `src/*`; this is why `@/lib/model` works. [next.config.ts](../next.config.ts) keeps pg/PGlite as server external packages and removes the X-Powered-By header. [playwright.config.ts](../playwright.config.ts) selects Chromium desktop and mobile profiles and uses `E2E_PORT`. [.github/workflows/ci.yml](../.github/workflows/ci.yml) provisions PostgreSQL 17 and runs formatting, types, tests, build, and browser checks. Build output, data, dependencies and environment files are ignored by [.gitignore](../.gitignore).
+
+### A sequence for rebuilding, with a checkpoint at each step
+
+Use a new learning folder; keep the working reference repository beside it. These are implementation milestones, not commands that automatically generate the complete product.
+
+1. **Create the skeleton.** Copy package.json, package-lock.json, tsconfig.json, next-env.d.ts and next.config.ts from the reference. Run `npm ci`. Add `src/app/layout.tsx`, `page.tsx` and a small globals.css. The layout returns `{children}`; the page can initially render `Dispatch
`. Checkpoint: `npm run dev -- --hostname 127.0.0.1 --port 3002` renders your heading. Stop only your learning process before using the same port for another server.
+2. **Name the domain.** Reconstruct model.ts: warehouse and destination IDs, products with weight, `LineItem`, `Inventory`, `Order`, `Candidate` and `Decision`. A TypeScript union such as `'PENDING' | 'ALLOCATED' | 'REVIEW' | 'CANCELLED'` restricts valid strings at compile time. Checkpoint: explain why an order needs both current `warehouseId` and a historical `decision`.
+3. **Make the price calculator pure.** Add shipping.ts. Its deterministic inputs are warehouse, destination and items. There is no fetch, account, or payment. Checkpoint: four phones plus two headsets produce BUF 1812 cents and RNO 3326 cents. Use the solution in section 13.
+4. **Make selection independent of persistence.** Add the `evaluate` function from routing.ts. Give it an order, inventory array and provider. Check stock before comparing quotes. Checkpoint: shortage gives no selection; a missing eligible quote gives an incomplete comparison; equal prices resolve to BUF. You can test this before creating any HTTP server.
+5. **Add durable data.** Implement the `Sql` and `Database` interfaces and both adapters in database.ts. Create the four tables, then seed.ts. SQL parameters such as `$1` hold values separately from SQL syntax. Checkpoint: a fresh in-memory database contains six orders and ten inventory rows; reserved is zero. Use test setup from routing.test.ts rather than the live demo database.
+6. **Add the transaction boundary.** Implement `locked`, `createOrder`, `route`, `cancel` and override handling. Never implement allocation as three independent API writes. Checkpoint: the rollback and last-unit tests pass; failed overrides leave the original allocation intact. Add the workspace cap and race helper only after ordinary order operations are correct.
+7. **Expose the service.** Add graphql.ts and the GraphQL route. A resolver is the function that implements a GraphQL field. Put policy in the service rather than in resolvers. Add the cookie and origin helper. Checkpoint: a query returns six orders and a mutation updates one; a foreign origin is rejected before any workspace initialization.
+8. **Build the browser adapter.** Add client.ts. Send JSON containing a query and variables using `fetch('/api/graphql')`; check HTTP failure and GraphQL `errors`. Checkpoint: a missing order produces a useful error, even when HTTP status is 200.
+9. **Build the UI in layers.** Follow section 11: static shell, read-only queue, selection and preview, mutation state, dialogs, then inventory/activity/guide views. Checkpoint: a route action reloads real server state and displays the saved decision. Do not pretend to allocate by incrementing local counters.
+10. **Make it usable at smaller widths.** Add responsive rules, keyboard focus, form labels and status messages. Checkpoint: the desktop and mobile browser suites pass without page overflow. A test pass is not a complete accessibility audit.
+11. **Add failure cases before polish.** Exercise missing stock, missing quotes, cancellation during a delayed quote, audit-write failure, and repeated commands. Checkpoint: tests verify unchanged state after rejected operations, not merely an exception message.
+12. **Package the result for review.** Build once, run tests against that build, inspect only intended diffs, and submit a draft PR. Keep demo data and environment files out of Git. CI passing is evidence for the tested commit, not a production certification.
+
+## 11. Build the interface from layout to interaction
+
+### The document and the client boundary
+
+[layout.tsx](../src/app/layout.tsx) is the document frame: English language, metadata, global CSS, and children. [page.tsx](../src/app/page.tsx) renders ``. [dashboard.tsx](../src/components/dashboard.tsx) begins with `'use client'` because it uses state, effects, event handlers and native dialogs. That marks a client component; it does not mean every part of Next.js runs only in the browser.
+
+**JSX** is the HTML-like syntax inside TypeScript. `` calls a React component with **props** (inputs). JSX uses `className` instead of `class`, braces for JavaScript values, and `onClick` for event handlers. A `.tsx` file can contain both TypeScript and JSX. The small `Metric` component is reused four times; most other UI is intentionally in one Dashboard component. This makes the demo easy to inspect but is a maintenance tradeoff, not a recommendation to put every large application in one file.
+
+### Design from big boxes to small details
+
+Draw a fixed left navigation, a top bar, a heading/actions row, four metrics, then a two-column work area. Put the order table on the left and the selected order inspector on the right. Inventory needs warehouse tables; Activity needs a timeline; Guide needs scenario cards. All four views share one shell and dataset. They are state-selected views, not separate URL routes.
+
+The design uses ordinary CSS in [globals.css](../src/app/globals.css):
+
+```css
+:root {
+ --bg: #f7f8fa;
+ --ink: #202a34;
+ --muted: #7b8490;
+ --line: #e7eaee;
+ --orange: #de5a36;
+ --nav: #17212b;
+ --green: #268367;
+ --font: Arial, Helvetica, sans-serif;
+}
+```
+
+These **custom properties** are reusable design values. The light surface separates working content from dark navigation; orange marks the main action, and status badges use text as well as color. This is an explanation of the current visual choices, not a claim of a particular designer's historical process. Arial/Helvetica/system fallbacks require no external font fetch. Lucide components such as `Truck`, `Plus` and `GitBranch` render SVG icons.
+
+`box-sizing: border-box` includes borders/padding in declared widths. `.shell` uses flex layout; `.sidebar` is fixed at 228px on wide screens, and `main` makes room for it. `.content` bounds the workspace. `.metrics` uses `repeat(4, 1fr)` to create equal columns. `.orders-layout` uses `minmax(480px, 1.55fr) minmax(310px, 1fr)` so the queue gets more room than the inspector. `fr` means a fraction of the remaining grid space. Panels provide borders, white surfaces and spacing. Tables retain actual table markup rather than imitating rows with arbitrary divs.
+
+The draft's caption cleanup removes decorative labels such as “FULFILLMENT CONTROL” and “ROUTING INSPECTOR.” It preserves factual warehouse region text as `.warehouse-region`. This reduces repeated headings without removing the order ID, status, warehouse comparison or demo disclosure.
+
+### Responsive behavior is a set of layout decisions
+
+| CSS boundary | What changes |
+| --------------- | ---------------------------------------------------------------------------------------------------------------------- |
+| At least 1500px | Wider queue/inspector proportions and 32px heading |
+| At most 1200px | Sidebar shrinks to 195px; heading stacks; warehouse panels become one column; queue destination column hides |
+| At most 850px | Sidebar becomes an ordinary top block; navigation becomes horizontal; main loses its left margin; guide stacks |
+| At most 650px | Queue and inspector stack; metrics become two columns; queue destination column returns; typography and spacing shrink |
+
+The destination column returns on phones because the queue has its own full-width row above the inspector. That is an explicit choice in the stylesheet, not a framework default. On phones the inspector follows the queue, so you may need to scroll down to see the selected order. Test intermediate widths as well as one phone preset before making broad claims about responsiveness.
+
+### Understand the state before adding a button
+
+**State** is a value React remembers across renders. Updating it schedules another render; directly modifying a local variable does not update the screen. In Dashboard:
+
+| State/ref | Purpose |
+| ------------------------------------- | ---------------------------------------------------------------------- |
+| `data` | Latest server dashboard or null during initial load |
+| `tab` | orders, inventory, activity or guide view |
+| `selectedId` | Which order to inspect; initially FR-1042 |
+| `decision`, `previewing` | Current advisory comparison or stored decision, plus loading state |
+| `busy` | Disable conflicting controls while a mutation and refresh run |
+| `notice` | Success/error text and alert style |
+| `search`, `filter` | Local queue filtering |
+| `overrideWarehouse`, `overrideReason` | Controlled override form inputs |
+| Three `useRef` dialog handles | Access native `