From 0b33bdc1243ce46a70da50edc19d1a01344a6ea8 Mon Sep 17 00:00:00 2001
From: Nirmith Victor
Date: Sat, 21 Nov 2026 20:05:52 -0500
Subject: [PATCH 1/4] Add fictional driver recruiting, custom builds and lineup
swaps
---
README.md | 1 +
docs/DEMO.md | 2 +-
docs/FOLLOW-UP-PLAN.md | 2 +
docs/TESTING.md | 5 +-
docs/USER-GUIDE.md | 20 +++-
docs/flows.json | 116 ++++++++++++++++++++
docs/guide/05-race-sandbox.md | 2 +
docs/guide/06-maintenance.md | 1 +
docs/guide/08-driver-recruitment.md | 99 ++++++++++++++++++
frontend/e2e/recruitment.spec.ts | 128 +++++++++++++++++++++++
frontend/src/App.tsx | 9 +-
frontend/src/CircuitSandbox.tsx | 4 +
frontend/src/DriverRecruitment.tsx | 124 ++++++++++++++++++++++
frontend/src/lab.css | 9 ++
frontend/src/recruitment.test.ts | 88 ++++++++++++++++
frontend/src/recruitment.ts | 157 ++++++++++++++++++++++++++++
16 files changed, 762 insertions(+), 5 deletions(-)
create mode 100644 docs/guide/08-driver-recruitment.md
create mode 100644 frontend/e2e/recruitment.spec.ts
create mode 100644 frontend/src/DriverRecruitment.tsx
create mode 100644 frontend/src/recruitment.test.ts
create mode 100644 frontend/src/recruitment.ts
diff --git a/README.md b/README.md
index b75773f..df9a3fb 100644
--- a/README.md
+++ b/README.md
@@ -26,6 +26,7 @@ The [handbook](docs/USER-GUIDE.md) documents every current user flow: steps, def
- A circuit race sandbox with editable connected pit lanes, one to six named/coloured drivers, individual pace, scheduled service stops, a simulated running order and browser-saved setups.
- Finite 1–50 lap fictional races with exact finish times/results, plus selected-driver live pit calls, cancellation before entry and repeat visits. See [race sessions](docs/guide/05-race-sandbox.md#sandbox-08).
- Private multiplayer rooms with a C#-owned simulation clock, SignalR snapshots, guest driver claims/readiness, host controls, live pit calls, reconnect, spectator support, guest removal and driver/host handover. Rooms are temporary and use one API instance. See [the multiplayer guide](docs/guide/07-multiplayer.md).
+- Fictional driver recruitment: generated stat-based prospects, a 12,000-credit budget, six-driver roster, custom 210-point builds, two swappable race seats, browser persistence and lineup application to local/new multiplayer races. See [recruiting flows](docs/guide/08-driver-recruitment.md).
- On-demand tool bundles, recovery from tool download failures, indexed replay lookups, a read-only setup doctor, and a one-command local preview.
- Light/dark themes with a header toggle, system preference on first visit, and a browser-saved choice across races.
- Save, revisit, and delete replay moments. Bookmarks are isolated by race and survive API restarts in PostgreSQL.
diff --git a/docs/DEMO.md b/docs/DEMO.md
index 3c200c7..8377dd3 100644
--- a/docs/DEMO.md
+++ b/docs/DEMO.md
@@ -28,7 +28,7 @@ The next session increment also lets you choose **Race distance (laps)**, select
## Engineering evidence
-- [Testing guide](TESTING.md): 66 frontend unit checks, nine Node checks, 49 browser scenarios, real API/database integration and dedicated storage/room concurrency checks.
+- [Testing guide](TESTING.md): 73 frontend unit checks, nine Node checks, 54 browser scenarios, real API/database integration and dedicated storage/room concurrency checks.
- [v1.3 architecture and limitations](V1.3.md): separate recorded/fictional state, independent enrichment, data quality and model assumptions.
- `node scripts/benchmark-replay.mjs`: reproducible lookup-only comparison against v1.2 with correctness assertions.
- GitHub Actions builds and tests the application and container; release branches publish an image. Hosting, accounts and multiplayer are later scope.
diff --git a/docs/FOLLOW-UP-PLAN.md b/docs/FOLLOW-UP-PLAN.md
index 94df30a..a5b6e2a 100644
--- a/docs/FOLLOW-UP-PLAN.md
+++ b/docs/FOLLOW-UP-PLAN.md
@@ -49,6 +49,8 @@ The first v1.4 increment implements finite fictional sessions (1–50 laps), det
The private-room increment adds a server-owned C# simulation, SignalR guest connections, exclusive driver claims/readiness, shared host controls, live calls, spectator support, reconnect and explicit driver/host handover. See [multiplayer flows](guide/07-multiplayer.md). Room storage is in memory, independent of PostgreSQL; public hosting, durable room recovery and multiple-instance coordination remain future scope.
+Fictional recruiting now adds generated prospects/fees, a browser-local budget and six-driver roster, custom stat allocation and two selected/swappable builds. Applying a lineup copies bounded pace/service values into the local sandbox and future room definitions. See [recruitment](guide/08-driver-recruitment.md). Training, wages, seasons, protected server economies and car-part upgrades remain future scope.
+
## Branch and validation workflow
Use a focused feature branch for each milestone, run timing/camera unit tests and browser tests, and review into `develop`. Promote to `master` once the integration branch is ready. Container delivery continues through the existing GitHub Actions workflow.
diff --git a/docs/TESTING.md b/docs/TESTING.md
index 4d0507d..50d92b5 100644
--- a/docs/TESTING.md
+++ b/docs/TESTING.md
@@ -6,7 +6,7 @@ Run `node scripts/check-docs.mjs` from the repository root. CI runs the same che
When changing a flow, update its chapter and `docs/flows.json`, then run `node scripts/update-guide-index.mjs` and the checker. Follow [CONTRIBUTING](../CONTRIBUTING.md). Checks catch structural drift; reviewing the steps against actual behavior remains necessary. Documentation-only changes need this check, without repeating unrelated application suites locally.
-## Playwright: 49 browser scenarios
+## Playwright: 54 browser scenarios
| Area | Coverage |
| --- | --- |
@@ -33,6 +33,7 @@ When changing a flow, update its chapter and `docs/flows.json`, then run `node s
| Circuit race sandbox | Pit entry/service/exit, running order, driver settings, persistent setup/session export, pit validation and undo, keyboard handles, animation, tab isolation and storage/mobile recovery |
| Race sessions and live calls | Exact finite-race results/frozen clock, reset/distance preservation, cancellation without resetting, entry commitment, next-lap targeting and selected-driver/mobile controls |
| Multiplayer | Two independent guest sessions, readiness, synchronized clock/results, live calls, reload/reconnect, driver/host handover, invalid invitations, mobile leave, real-hub concurrent claim conflicts, token/ownership/host checks, forged-time rejection and guest removal |
+| Fictional recruitment | Generated sign/release/scouting fees and persistence, custom point limits, saved seat swaps and applied performance, new multiplayer room copies, mobile/failed-write behavior, stale-tab protection, raw backup and confirmed corrupted-profile recovery |
| Sector map | Completed-reference alignment, saved layout preference, no invented coordinates during gaps, hidden markers before coverage or in estimate mode |
| Tool loading | Studio bundle stays deferred until opened; a failed download returns to a usable replay |
@@ -40,7 +41,7 @@ These scenarios run against the production frontend build in Chromium. Historica
## Other checks
-- 66 Vitest checks cover replay timing and indexed boundary/seek behavior, track interpolation, map/layout preferences, recorded sample lookup and sector alignment, trails, share links, named layouts, geometry/rounding/import validation, deterministic strategy math, held-out pace evaluation, sandbox route/service transitions, setup migration, finish timing/frame invariance, result ordering, cancellation/repeat visits and pit-lane finishes. A committed shared fixture checks browser/server parity for rounded geometry, pit traversal/service/rejoin and finite results.
+- 73 Vitest checks cover replay timing and indexed boundary/seek behavior, track interpolation, map/layout preferences, recorded sample lookup and sector alignment, trails, share links, named layouts, geometry/rounding/import validation, deterministic strategy math, held-out pace evaluation, sandbox route/service transitions, setup migration, finish timing/frame invariance, result ordering, cancellation/repeat visits and pit-lane finishes. Recruiting checks cover seeded stats/identities, custom constraints, budget/fees/refunds, roster limits, seat swapping, applied settings and storage/revision failures. A committed shared fixture checks browser/server parity for rounded geometry, pit traversal/service/rejoin and finite results.
- `Pitwall.RoomChecks` checks authoritative room physics, frame invariance, validation, concurrent seat claims, host/driver authorization, reconnect, handover, guest removal and departure. It also consumes `data/testing/room-model.json`; fixture changes need review, rather than automatic regeneration to make a failure pass.
- Nine Node tests cover catalog filtering, identifiers, location alignment/quality, measured-sector/pit normalization, local environment parsing, bounded ports and connection-string escaping.
- `Pitwall.StoreChecks` verifies enrichment preservation, downgrade protection, concurrent writes, safe bundle seeding and bookmarks against both in-memory storage and PostgreSQL. It creates uniquely named test rows and removes only those rows.
diff --git a/docs/USER-GUIDE.md b/docs/USER-GUIDE.md
index 36491f2..6799f87 100644
--- a/docs/USER-GUIDE.md
+++ b/docs/USER-GUIDE.md
@@ -15,6 +15,7 @@ This is the current handbook for what each flow does, how to use it, what is sav
5. [Configure drivers and pit stops in the race sandbox](guide/05-race-sandbox.md).
6. [Understand storage, maintenance and guide updates](guide/06-maintenance.md).
7. [Host, join and hand over a private multiplayer race](guide/07-multiplayer.md).
+8. [Recruit fictional drivers, create builds and swap your lineup](guide/08-driver-recruitment.md).
Each flow has a stable ID, a **What**, **How**, **Result and storage**, and **Recovery and limits** section. Use these IDs in issues and pull requests instead of relying on a screenshot or an old chat.
@@ -29,6 +30,7 @@ Each flow has a stable ID, a **What**, **How**, **Result and storage**, and **Re
| Can I design my own circuit? | Custom circuit studio → Circuit editor | Fictional geometry, separate from real replays |
| Can I run a custom grid with scheduled stops? | Circuit race sandbox | Fictional pace/route/service animation |
| Can friends control drivers in the same race? | Multiplayer rooms | One server-owned fictional race with guest driver ownership |
+| Can I sign and customize fictional drivers? | Driver recruitment | Browser-local roster/budget with two selected race builds |
```mermaid
flowchart LR
@@ -41,6 +43,8 @@ flowchart LR
Replay --> Editor[Fictional circuit editor]
Editor --> Sandbox[Driver and pit sandbox]
Sandbox --> Room[Private multiplayer room]
+ Editor --> Team[Recruit and build drivers]
+ Team --> Sandbox
```

@@ -60,6 +64,7 @@ Saving to PostgreSQL, saving in your browser and downloading a file are differen
| Combined sandbox session JSON | No session importer yet | Contains geometry/setup/runtime for inspection |
| Share link | Yes, if its server/session is available | Encodes replay settings, not private saves or custom workspaces |
| Multiplayer room | Reconnect while that API process retains it | Guest token in tab session storage; rooms are in server memory even with PostgreSQL |
+| Recruiting team | Yes, same browser origin | Autosaved market, roster, lineup and credits; applying to a grid is separate |
Closing a studio or scenario without saving can lose its draft. Clearing browser data, changing browser/profile, or using another hostname/port can change which browser saves you see. A normal database-backed API restart does not erase server caches/bookmarks.
@@ -81,7 +86,7 @@ Closing a studio or scenario without saving can lose its draft. Clearing browser
-76 documented flows. Each ID links directly to its instructions.
+84 documented flows. Each ID links directly to its instructions.
### Start Pitwall and choose a race
@@ -193,6 +198,19 @@ Closing a studio or scenario without saving can lose its draft. Clearing browser
| [ROOM-06](guide/07-multiplayer.md#room-06) | Hand over a driver without resetting |
| [ROOM-07](guide/07-multiplayer.md#room-07) | Reconnect, leave and remove guests |
| [ROOM-08](guide/07-multiplayer.md#room-08) | Run a two-player trial and prepare outside access |
+
+### Fictional driver recruitment and builds
+
+| Flow | What you can do |
+| --- | --- |
+| [TEAM-01](guide/08-driver-recruitment.md#team-01) | Open and initialize your team |
+| [TEAM-02](guide/08-driver-recruitment.md#team-02) | Scout generated prospects |
+| [TEAM-03](guide/08-driver-recruitment.md#team-03) | Sign and release roster drivers |
+| [TEAM-04](guide/08-driver-recruitment.md#team-04) | Build and sign a custom driver |
+| [TEAM-05](guide/08-driver-recruitment.md#team-05) | Select and swap race seats |
+| [TEAM-06](guide/08-driver-recruitment.md#team-06) | Apply recruited builds and host them in a new room |
+| [TEAM-07](guide/08-driver-recruitment.md#team-07) | Recover from storage failures or another tab's changes |
+| [TEAM-08](guide/08-driver-recruitment.md#team-08) | Export a record or explicitly start fresh |
## How this stays current
diff --git a/docs/flows.json b/docs/flows.json
index c1ec25a..b6286be 100644
--- a/docs/flows.json
+++ b/docs/flows.json
@@ -30,6 +30,10 @@
{
"path": "docs/guide/07-multiplayer.md",
"title": "Private multiplayer races"
+ },
+ {
+ "path": "docs/guide/08-driver-recruitment.md",
+ "title": "Fictional driver recruitment and builds"
}
],
"sharedComponents": [
@@ -902,6 +906,118 @@
"backend/Pitwall.RoomChecks/Program.cs",
"frontend/e2e/multiplayer.spec.ts"
]
+ },
+ {
+ "id": "TEAM-01",
+ "title": "Open and initialize your team",
+ "guide": "docs/guide/08-driver-recruitment.md",
+ "anchor": "team-01",
+ "sources": [
+ "frontend/src/DriverRecruitment.tsx",
+ "frontend/src/recruitment.ts",
+ "frontend/src/recruitment.test.ts",
+ "frontend/src/App.tsx",
+ "frontend/src/CircuitSandbox.tsx",
+ "frontend/e2e/recruitment.spec.ts"
+ ]
+ },
+ {
+ "id": "TEAM-02",
+ "title": "Scout generated prospects",
+ "guide": "docs/guide/08-driver-recruitment.md",
+ "anchor": "team-02",
+ "sources": [
+ "frontend/src/DriverRecruitment.tsx",
+ "frontend/src/recruitment.ts",
+ "frontend/src/recruitment.test.ts",
+ "frontend/src/App.tsx",
+ "frontend/src/CircuitSandbox.tsx",
+ "frontend/e2e/recruitment.spec.ts"
+ ]
+ },
+ {
+ "id": "TEAM-03",
+ "title": "Sign and release roster drivers",
+ "guide": "docs/guide/08-driver-recruitment.md",
+ "anchor": "team-03",
+ "sources": [
+ "frontend/src/DriverRecruitment.tsx",
+ "frontend/src/recruitment.ts",
+ "frontend/src/recruitment.test.ts",
+ "frontend/src/App.tsx",
+ "frontend/src/CircuitSandbox.tsx",
+ "frontend/e2e/recruitment.spec.ts"
+ ]
+ },
+ {
+ "id": "TEAM-04",
+ "title": "Build and sign a custom driver",
+ "guide": "docs/guide/08-driver-recruitment.md",
+ "anchor": "team-04",
+ "sources": [
+ "frontend/src/DriverRecruitment.tsx",
+ "frontend/src/recruitment.ts",
+ "frontend/src/recruitment.test.ts",
+ "frontend/src/App.tsx",
+ "frontend/src/CircuitSandbox.tsx",
+ "frontend/e2e/recruitment.spec.ts"
+ ]
+ },
+ {
+ "id": "TEAM-05",
+ "title": "Select and swap race seats",
+ "guide": "docs/guide/08-driver-recruitment.md",
+ "anchor": "team-05",
+ "sources": [
+ "frontend/src/DriverRecruitment.tsx",
+ "frontend/src/recruitment.ts",
+ "frontend/src/recruitment.test.ts",
+ "frontend/src/App.tsx",
+ "frontend/src/CircuitSandbox.tsx",
+ "frontend/e2e/recruitment.spec.ts"
+ ]
+ },
+ {
+ "id": "TEAM-06",
+ "title": "Apply recruited builds and host them in a new room",
+ "guide": "docs/guide/08-driver-recruitment.md",
+ "anchor": "team-06",
+ "sources": [
+ "frontend/src/DriverRecruitment.tsx",
+ "frontend/src/recruitment.ts",
+ "frontend/src/recruitment.test.ts",
+ "frontend/src/App.tsx",
+ "frontend/src/CircuitSandbox.tsx",
+ "frontend/e2e/recruitment.spec.ts"
+ ]
+ },
+ {
+ "id": "TEAM-07",
+ "title": "Recover from storage failures or another tab's changes",
+ "guide": "docs/guide/08-driver-recruitment.md",
+ "anchor": "team-07",
+ "sources": [
+ "frontend/src/DriverRecruitment.tsx",
+ "frontend/src/recruitment.ts",
+ "frontend/src/recruitment.test.ts",
+ "frontend/src/App.tsx",
+ "frontend/src/CircuitSandbox.tsx",
+ "frontend/e2e/recruitment.spec.ts"
+ ]
+ },
+ {
+ "id": "TEAM-08",
+ "title": "Export a record or explicitly start fresh",
+ "guide": "docs/guide/08-driver-recruitment.md",
+ "anchor": "team-08",
+ "sources": [
+ "frontend/src/DriverRecruitment.tsx",
+ "frontend/src/recruitment.ts",
+ "frontend/src/recruitment.test.ts",
+ "frontend/src/App.tsx",
+ "frontend/src/CircuitSandbox.tsx",
+ "frontend/e2e/recruitment.spec.ts"
+ ]
}
]
}
diff --git a/docs/guide/05-race-sandbox.md b/docs/guide/05-race-sandbox.md
index d734f56..8164f79 100644
--- a/docs/guide/05-race-sandbox.md
+++ b/docs/guide/05-race-sandbox.md
@@ -37,6 +37,8 @@ This is a deterministic geometry/pace/service preview. It does not simulate grip
**Recovery and limits:** Empty/invalid driver settings block running/saving. Numeric inputs accept incomplete typing and apply bounds on blur/Enter. Scheduled stops at/beyond the finish have no effect. Live calls can add visits; there are no compound or car-part controls yet.
+Use **Recruit and manage drivers** for [fictional recruiting and custom stat builds](08-driver-recruitment.md). Applying that lineup replaces the first two grid drivers with derived pace/service settings and restarts this sandbox; it is separate from real players controlling multiplayer seats.
+
## SANDBOX-03 — Attach and edit the pit lane
diff --git a/docs/guide/06-maintenance.md b/docs/guide/06-maintenance.md
index f0ab8a7..a4802ae 100644
--- a/docs/guide/06-maintenance.md
+++ b/docs/guide/06-maintenance.md
@@ -16,6 +16,7 @@
| Replay bookmarks | Database, shared by visitors to that instance | API memory | Not private browser/account data |
| Theme/default map/named map layouts | Browser only | Browser only | Hostname + port + scheme + browser/profile |
| Saved circuits/sandbox setups/strategy scenarios | Browser only | Browser only | Same origin isolation |
+| Recruiting roster/market/lineup/credits | Browser only, autosaved on successful transactions | Browser only | Same origin; separate from server rooms and guest ownership |
| Unsaved drafts, tool selections, simulation clock | Current page/tool session | Current page/tool session | Not automatically restored |
| Multiplayer rooms/shared race clock | API process memory; lost on restart | API process memory; lost on restart | Guest credential in tab session storage, no token in invitation |
| Exported files | Download location you choose | Download location you choose | Not automatically re-imported |
diff --git a/docs/guide/08-driver-recruitment.md b/docs/guide/08-driver-recruitment.md
new file mode 100644
index 0000000..a4ded89
--- /dev/null
+++ b/docs/guide/08-driver-recruitment.md
@@ -0,0 +1,99 @@
+# Fictional driver recruitment and builds
+
+[Guide home](../USER-GUIDE.md) · [Local sandbox](05-race-sandbox.md) · [Multiplayer](07-multiplayer.md)
+
+Recruitment manages fictional driver profiles. It is separate from real players claiming multiplayer seats. Ratings and credits are local game values; no real money, accounts, training, contracts or season rewards are implemented.
+
+
+## TEAM-01 — Open and initialize your team
+
+**What:** Create a browser-local team with a budget, prospect market and roster.
+
+**How:** Open **Driver recruitment** from the replay toolbar, or **Custom circuit studio → Circuit race sandbox → Recruit and manage drivers**. The sandbox pauses when opening its manager. Read your credits and roster count at the top.
+
+**Result and storage:** A fresh team starts with 12,000 credits, six generated prospects, an empty six-driver-capacity roster and two unassigned race seats. The first successful initialization saves that market; reopening does not reroll it. The same team is shared across fictional circuits on this browser origin. An unsaved custom-driver draft is separate from the saved team.
+
+**Recovery and limits:** Storage errors show a warning; unreadable existing data is not silently replaced. **Load latest team** rereads saved state without changing the custom draft or current race. Different browsers/profiles, schemes, hostnames and ports have separate teams. There is no server-synchronized budget or competitive economy verification.
+
+
+## TEAM-02 — Scout generated prospects
+
+**What:** Compare randomly generated fictional names, colours, stats, fees and effective race settings.
+
+**How:** Inspect **Scout market** cards. Each shows overall rating, pace, consistency, pit discipline, derived pace offset/service duration and signing fee. **Scout new market · 250 credits** replaces all unsigned prospects with another six.
+
+**Result and storage:** Each prospect stat is an integer from 45–90. A saved seed/generation gives a stable market between visits; scouting generates the next market and spends 250 credits only after the save succeeds. Signed drivers and lineup stay intact. Overall is the rounded arithmetic mean of the three stats, not a race prediction.
+
+**Recovery and limits:** Scouting disables below 250 credits. Replaced prospects cannot be recovered through undo. Signing removes a prospect from that market; when it is empty, scout another. Random generation belongs to the market, not per-frame race movement or changes to a signed driver's ratings.
+
+
+## TEAM-03 — Sign and release roster drivers
+
+**What:** Spend a limited budget on up to six signed drivers.
+
+**How:** Choose **Sign [name] · [fee] credits**. The prospect moves to **Your roster**. **Release [name] · +[refund]** removes a signed driver and returns the displayed amount. A roster driver outside the two selected seats is a reserve.
+
+**Result and storage:** Signing deducts the fee and saves the roster/market/budget together. The fee is `500 + round((pace² × 0.45 + consistency² × 0.25 + pitDiscipline² × 0.15) / 25) × 25`. Release refunds 40% of that driver's signing fee, rounded down, and clears its selected seats. Release does not return a driver to the market. Existing race copies retain that driver until replaced.
+
+**Recovery and limits:** Insufficient funds or a full roster disable signing. Re-signing a removed market ID is rejected. Signed names must be distinct ignoring case. Releases are immediate and have no undo; the refund is smaller than the signing cost. There are no recurring wages or race income yet.
+
+
+## TEAM-04 — Build and sign a custom driver
+
+**What:** Choose your own stat tradeoffs, name and colour.
+
+**How:** In **Build a custom driver**, set a name (1–24 trimmed characters), colour and integer stats from 10–100. Use at most 210 total stat points; the default is 70 in each stat. Inspect the point total, fee and effective settings, then **Create and sign custom driver**.
+
+| Stat | Current model effect |
+| --- | --- |
+| Pace | 60% of the weighted pace rating |
+| Consistency | 40% of the weighted pace rating; a steady modifier, not random lap variation |
+| Pit discipline | Service seconds = `5 − stat × 0.04` |
+
+**Result and storage:** Pace offset is `(70 − (pace × 0.6 + consistency × 0.4)) × 0.12`, rounded to hundredths of a second/lap; negative is faster. Service is also rounded to hundredths. Custom stat limits give offsets from −3.60 to +7.20 seconds/lap and service from 1.00–4.60 seconds. Successful creation charges the same fee formula as the market and saves the signed profile. Each created driver gets its own identity.
+
+**Recovery and limits:** Over-budget points, insufficient credits and full rosters disable signing; invalid/duplicate names are rejected. You may leave stat points unused for a cheaper build. Ratings of signed drivers are fixed in this version; editing the builder creates another profile. Closing loses the unsaved draft. These stats do not simulate tyre wear, mistakes, traffic or physical vehicle dynamics.
+
+
+## TEAM-05 — Select and swap race seats
+
+**What:** Choose two different signed drivers for the next fictional lineup.
+
+**How:** Set **Race seat 1** and **Race seat 2**. Selecting the driver already occupying the other seat swaps their assignments. With two assigned seats, **Swap race seats** reverses them directly. Choose **Choose signed driver** to clear a seat.
+
+**Result and storage:** Assignments save with the team, preserving profiles, stats and credits. Swapping affects the selected lineup only; it does not alter a running sandbox or an existing multiplayer room. Remaining roster drivers stay in reserve.
+
+**Recovery and limits:** Unsigned drivers cannot occupy seats and one driver cannot occupy both. Releasing a selected profile clears its seat. Assign both seats before applying. This is fictional lineup selection; real-player control handover is documented in [ROOM-06](07-multiplayer.md#room-06).
+
+
+## TEAM-06 — Apply recruited builds and host them in a new room
+
+**What:** Turn your selected profiles into a race grid with their derived performance.
+
+**How:** Open the manager from **Recruit and manage drivers** inside the sandbox. Assign two seats and choose **Apply lineup and restart sandbox**. Inspect grid slots 1–2, then run locally or use **Host this setup with friends** to create a multiplayer copy. Use **Save circuit and race setup** if you also want that grid stored with the circuit.
+
+**Result and storage:** Applying copies names, colours, identities, pace offsets and service times into the first two grid slots. It retains those slots' scheduled pit laps (new slots use no scheduled stop), geometry, distance and other opponents. A one-driver grid grows to two. Duplicate copies of a selected recruited ID in later slots are removed. Applying resets clock, positions, live calls and results through the normal setup-change flow. The manager closes; sandbox undo can restore the previous grid.
+
+**Recovery and limits:** Applying requires both signed seats and no unresolved stale/storage warning. It does not automatically save the circuit setup. Existing multiplayer rooms keep their frozen definitions, ownership and current race; only a newly created room receives the changed lineup. Room validation bounds the copied pace/service settings but does not verify browser-local recruiting credits or ratings. Manual sandbox edits can subsequently override copied values.
+
+
+## TEAM-07 — Recover from storage failures or another tab's changes
+
+**What:** Avoid silently losing purchases or overwriting a newer team.
+
+**How:** Read warnings and use **Load latest team** before retrying a stale transaction. If storage is blocked, restore permission/access and retry. **Back up stored team data** downloads a wrapper containing the raw saved string when a warning is present, if storage can be read.
+
+**Result and storage:** Successful operations save one versioned team JSON record. UI credits/roster change only after storage accepts that record. A saved revision/identity check rejects stale writes. Browsers with Web Locks serialize recruiting transactions across tabs; a storage event also warns open screens about external changes.
+
+**Recovery and limits:** Failed writes leave the displayed previous budget and roster intact. Without Web Locks, revision checks are best effort; use one active recruiting tab. **Load latest team** keeps the unsaved custom draft. Unreadable storage displays a fresh fallback with a warning but cannot overwrite the old record through an ordinary purchase. Backups/exports are inspection files, not automatically restorable through the app.
+
+
+## TEAM-08 — Export a record or explicitly start fresh
+
+**What:** Download the displayed team or reset your local recruiting progress.
+
+**How:** **Export team JSON** downloads the currently displayed team, including seed/market, roster, lineup and credits. **Start fresh team** opens an explanation; **Confirm fresh team** replaces saved recruiting data with a new 12,000-credit team, or **Keep current team** cancels.
+
+**Result and storage:** A confirmed reset replaces this browser origin's recruiting record. Existing circuits, local race grid copies and multiplayer rooms remain separate. Resetting does not save or clear those copies. If you are viewing an unreadable saved record's fallback, back up the raw stored data before resetting; exporting the displayed fallback does not recover the old record.
+
+**Recovery and limits:** There is no team importer or reset undo. A failed reset write retains the old record and reports an error. Other recruiting tabs must load the latest team after a reset. Credits are fictional, so a fresh-team reset is allowed; this is not a protected online economy.
diff --git a/frontend/e2e/recruitment.spec.ts b/frontend/e2e/recruitment.spec.ts
new file mode 100644
index 0000000..29f6e0a
--- /dev/null
+++ b/frontend/e2e/recruitment.spec.ts
@@ -0,0 +1,128 @@
+import {test,expect} from "@playwright/test";
+import {newTeam,signingFee,releaseRefund,teamKey} from "../src/recruitment";
+
+test("recruits generated prospects, preserves the market and budget on reload, scouts and releases", async ({page}) => {
+ const initial={...newTeam(42),revision:1}, prospect=initial.market[0];
+ await page.addInitScript(({key,team})=>{if(!localStorage.getItem(key))localStorage.setItem(key,JSON.stringify(team));},{key:teamKey,team:initial});
+ await page.goto("/?race=monza-2024&t=120");
+ await page.getByRole("button",{name:"Driver recruitment",exact:true}).click();
+ const panel=page.getByRole("dialog",{name:"Driver recruitment",exact:true});
+ await panel.getByRole("article",{name:`Market ${prospect.name}`,exact:true}).getByRole("button",{name:/^Sign /}).click();
+ const remaining=12000-signingFee(prospect.stats);
+ await expect(panel.getByTestId("team-credits")).toHaveText(`${remaining.toLocaleString("en-US")} credits`);
+ await expect(panel.getByTestId("roster-count")).toHaveText("1/6 drivers");
+ await page.reload();
+ await page.getByRole("button",{name:"Driver recruitment",exact:true}).click();
+ await expect(panel.getByRole("article",{name:`Signed ${prospect.name}`,exact:true})).toBeVisible();
+ await expect(panel.getByRole("article",{name:`Market ${prospect.name}`,exact:true})).toHaveCount(0);
+ await expect(panel.getByTestId("team-credits")).toHaveText(`${remaining.toLocaleString("en-US")} credits`);
+ await panel.getByRole("button",{name:/^Release /}).click();
+ await expect(panel.getByTestId("roster-count")).toHaveText("0/6 drivers");
+ const after=remaining+releaseRefund(prospect)-250;
+ await panel.getByRole("button",{name:"Scout new market · 250 credits",exact:true}).click();
+ await expect(panel.getByTestId("team-credits")).toHaveText(`${after.toLocaleString("en-US")} credits`);
+ await expect(panel.getByRole("region",{name:"Driver market",exact:true}).getByRole("article")).toHaveCount(6);
+ const download=page.waitForEvent("download");
+ await panel.getByRole("button",{name:"Export team JSON",exact:true}).click();
+ const stream=await(await download).createReadStream(),chunks=[];
+ for await(const chunk of stream!)chunks.push(chunk);
+ const exported=JSON.parse(Buffer.concat(chunks).toString());
+ expect(exported.credits).toBe(after);expect(exported.roster).toHaveLength(0);
+});
+
+test("custom builds respect points and swapping the lineup changes the sandbox and new room setup", async ({page}) => {
+ await page.goto("/?race=monza-2024&t=120");
+ await page.getByRole("button",{name:"Custom circuit studio",exact:true}).click();
+ await page.getByRole("button",{name:"Circuit race sandbox",exact:true}).click();
+ await page.getByRole("button",{name:"Advance one lap",exact:true}).click();
+ await page.getByRole("button",{name:"Recruit and manage drivers",exact:true}).click();
+ const panel=page.getByRole("dialog",{name:"Driver recruitment",exact:true});
+ const custom=panel.getByRole("region",{name:"Custom driver builder",exact:true});
+ await custom.getByLabel("Custom driver name",{exact:true}).fill("Apex");
+ await custom.getByLabel("Custom pace",{exact:true}).fill("100");
+ await expect(custom.getByRole("button",{name:"Create and sign custom driver",exact:true})).toBeDisabled();
+ await custom.getByLabel("Custom consistency",{exact:true}).fill("60");
+ await custom.getByLabel("Custom pit discipline",{exact:true}).fill("50");
+ await custom.getByRole("button",{name:"Create and sign custom driver",exact:true}).click();
+ await expect(panel.getByTestId("roster-count")).toHaveText("1/6 drivers");
+ await custom.getByLabel("Custom driver name",{exact:true}).fill("Crew");
+ await custom.getByLabel("Custom pace",{exact:true}).fill("50");
+ await custom.getByLabel("Custom consistency",{exact:true}).fill("50");
+ await custom.getByRole("button",{name:"Create and sign custom driver",exact:true}).click();
+ await expect(panel.getByTestId("roster-count")).toHaveText("2/6 drivers");
+ const state=await page.evaluate(key=>JSON.parse(localStorage.getItem(key)!),teamKey);
+ await panel.getByLabel("Race seat 1",{exact:true}).selectOption(state.roster[0].id);
+ await panel.getByLabel("Race seat 2",{exact:true}).selectOption(state.roster[1].id);
+ await panel.getByRole("button",{name:"Swap race seats",exact:true}).click();
+ await panel.getByRole("button",{name:"Apply lineup and restart sandbox",exact:true}).click();
+ const sandbox=page.getByRole("region",{name:"Circuit race sandbox",exact:true});
+ await expect(sandbox.getByLabel("Grid 1 driver name",{exact:true})).toHaveValue("Crew");
+ await expect(sandbox.getByLabel("Grid 2 driver name",{exact:true})).toHaveValue("Apex");
+ await expect(sandbox.getByLabel("Grid 1 pace offset",{exact:true})).toHaveValue("2.4");
+ await expect(sandbox.getByLabel("Grid 2 pace offset",{exact:true})).toHaveValue("-1.68");
+ await expect(sandbox.getByLabel("Grid 2 service seconds",{exact:true})).toHaveValue("3");
+ await expect(sandbox.getByTestId("sandbox-clock")).toHaveText("00:00:00");
+ await expect(sandbox.getByLabel("Grid 3 driver name",{exact:true})).toHaveValue("Driver 3");
+ await sandbox.getByRole("button",{name:"Host this setup with friends",exact:true}).click();
+ const room=page.getByRole("dialog",{name:"Multiplayer rooms",exact:true});
+ await room.getByLabel("Guest name",{exact:true}).fill("Recruiter");
+ await room.getByRole("button",{name:"Create private room",exact:true}).click();
+ await expect(room.getByRole("button",{name:"Claim Crew",exact:true})).toBeVisible();
+ await expect(room.getByRole("button",{name:"Claim Apex",exact:true})).toBeVisible();
+});
+
+test("recruitment is usable on mobile and failed storage writes do not spend credits", async ({page}) => {
+ await page.setViewportSize({width:390,height:844});
+ await page.emulateMedia({colorScheme:"light"});
+ await page.addInitScript(()=>{Storage.prototype.setItem=()=>{throw new Error("Storage denied");};});
+ await page.goto("/?race=monza-2024");
+ await page.getByRole("button",{name:"Driver recruitment",exact:true}).click();
+ const panel=page.getByRole("dialog",{name:"Driver recruitment",exact:true});
+ await expect(panel.getByRole("alert")).toBeVisible();
+ await panel.getByRole("region",{name:"Custom driver builder",exact:true}).getByRole("button",{name:"Create and sign custom driver",exact:true}).click();
+ await expect(panel.getByTestId("team-credits")).toHaveText("12,000 credits");
+ await expect(panel.getByTestId("roster-count")).toHaveText("0/6 drivers");
+ expect(await panel.evaluate(e=>e.scrollWidth<=e.clientWidth)).toBe(true);
+});
+
+test("another tab's purchase cannot be overwritten by a stale team screen", async ({page,context}) => {
+ await page.goto("/?race=monza-2024");
+ await page.getByRole("button",{name:"Driver recruitment",exact:true}).click();
+ const panel=page.getByRole("dialog",{name:"Driver recruitment",exact:true});
+ await expect(panel.getByRole("button",{name:"Create and sign custom driver",exact:true})).toBeEnabled();
+ const other=await context.newPage();
+ try {
+ await other.goto("/?race=monza-2024");
+ await other.getByRole("button",{name:"Driver recruitment",exact:true}).click();
+ await other.getByRole("button",{name:"Create and sign custom driver",exact:true}).click();
+ await expect(panel.getByRole("alert")).toContainText("another tab");
+ await panel.getByRole("button",{name:"Scout new market · 250 credits",exact:true}).click();
+ await expect(panel.getByRole("alert")).toContainText("another tab");
+ await panel.getByRole("button",{name:"Load latest team",exact:true}).click();
+ await expect(panel.getByTestId("roster-count")).toHaveText("1/6 drivers");
+ await expect(panel.getByTestId("team-credits")).toHaveText("7,325 credits");
+ } finally {await other.close();}
+});
+
+test("unreadable team data stays intact until a fresh-team reset is explicitly confirmed", async ({page}) => {
+ const raw="{broken-team-json";
+ await page.addInitScript(({key,raw})=>localStorage.setItem(key,raw),{key:teamKey,raw});
+ await page.goto("/?race=monza-2024");
+ await page.getByRole("button",{name:"Driver recruitment",exact:true}).click();
+ const panel=page.getByRole("dialog",{name:"Driver recruitment",exact:true});
+ await expect(panel.getByRole("alert")).toContainText("could not be read");
+ expect(await page.evaluate(key=>localStorage.getItem(key),teamKey)).toBe(raw);
+ const download=page.waitForEvent("download");
+ await panel.getByRole("button",{name:"Back up stored team data",exact:true}).click();
+ const stream=await(await download).createReadStream(),chunks=[];
+ for await(const chunk of stream!)chunks.push(chunk);
+ expect(JSON.parse(Buffer.concat(chunks).toString()).raw).toBe(raw);
+ await panel.getByRole("button",{name:"Start fresh team",exact:true}).click();
+ await panel.getByRole("button",{name:"Keep current team",exact:true}).click();
+ expect(await page.evaluate(key=>localStorage.getItem(key),teamKey)).toBe(raw);
+ await panel.getByRole("button",{name:"Start fresh team",exact:true}).click();
+ await panel.getByRole("button",{name:"Confirm fresh team",exact:true}).click();
+ await expect(panel.getByRole("alert")).toHaveCount(0);
+ const saved=await page.evaluate(key=>JSON.parse(localStorage.getItem(key)!),teamKey);
+ expect(saved.credits).toBe(12000);expect(saved.roster).toEqual([]);expect(saved.market).toHaveLength(6);
+});
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index 5533191..32b9745 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -48,6 +48,7 @@ const StrategyLab = lazy(() => import("./StrategyLab"));
const RaceAnalysis = lazy(() => import("./RaceAnalysis"));
const PaceBacktest = lazy(() => import("./PaceBacktest"));
const MultiplayerRooms = lazy(() => import("./MultiplayerRooms"));
+const DriverRecruitment = lazy(() => import("./DriverRecruitment"));
import "./lab.css";
import { momentLink, readMoment } from "./replay-link";
import { ensureTiming } from "./import-job";
@@ -91,7 +92,8 @@ function App() {
const [showAnalysis, setShowAnalysis] = useState(false);
const [showBacktest, setShowBacktest] = useState(false);
const [showRooms, setShowRooms] = useState(() => new URLSearchParams(location.search).has("room"));
- const activeTool = showRooms ? "rooms" : showLibrary
+ const [showRecruitment, setShowRecruitment] = useState(false);
+ const activeTool = showRecruitment ? "recruitment" : showRooms ? "rooms" : showLibrary
? "library"
: shareLink
? "share"
@@ -105,6 +107,7 @@ function App() {
? "backtest"
: "none";
const closeTools = () => {
+ setShowRecruitment(false);
setShowRooms(false);
setShowLibrary(false);
setShareLink(null);
@@ -193,6 +196,7 @@ function App() {
showAnalysis ||
showBacktest ||
showRooms ||
+ showRecruitment ||
document.querySelector("dialog[open]")
)
return;
@@ -222,6 +226,7 @@ function App() {
showAnalysis,
showBacktest,
showRooms,
+ showRecruitment,
]);
useEffect(() => {
if (!notice) return;
@@ -419,6 +424,7 @@ function App() {
REPLAY TOOLS
+ {setPlaying(false);setShowRecruitment(true);}}>Driver recruitment
{setPlaying(false);setShowRooms(true);}}>Multiplayer rooms
{
@@ -986,6 +992,7 @@ function App() {
/>
)}
{showRooms && setShowRooms(false)} />}
+ {showRecruitment && setShowRecruitment(false)} />}
{showAnalysis && (
import("./MultiplayerRooms"));
+const DriverRecruitment = lazy(() => import("./DriverRecruitment"));
import {
downloadJson,
parseTrack,
@@ -38,6 +39,7 @@ export default function CircuitSandbox({
}) {
const [setup, setSetup] = useState(() => readSandbox(track));
const [showRoom, setShowRoom] = useState(false);
+ const [showRecruitment, setShowRecruitment] = useState(false);
const [session, setSession] = useState(() => ({
states: initialGrid(setup.drivers), elapsed: 0,
}));
@@ -130,6 +132,8 @@ export default function CircuitSandbox({
{setRunning(false);setShowRoom(true);}}>Host this setup with friends
+ {setRunning(false);setShowRecruitment(true);}}>Recruit and manage drivers
+ {showRecruitment && Loading recruitment…
}> setShowRecruitment(false)} />}
{showRoom && Loading multiplayer…}> setShowRoom(false)} /> }
diff --git a/frontend/src/DriverRecruitment.tsx b/frontend/src/DriverRecruitment.tsx
new file mode 100644
index 0000000..2e7f13d
--- /dev/null
+++ b/frontend/src/DriverRecruitment.tsx
@@ -0,0 +1,124 @@
+import { useEffect, useState } from "react";
+import Dialog from "./Dialog";
+import NumberField from "./NumberField";
+import { downloadJson } from "./custom-track";
+import type { SandboxSetup } from "./sandbox";
+import {
+ applyLineup, assignSeat, createDriver, customPoints, driverEffects, ensureTeam, overall, pointsUsed,
+ readTeam, refreshFee, refreshMarket, releaseDriver, releaseRefund, resetTeam, saveTeam,
+ signDriver, signingFee, teamKey, type DriverStats, type RecruitDriver, type Team,
+} from "./recruitment";
+
+const stats: {key: keyof DriverStats; label: string}[] = [
+ {key:"pace",label:"Pace"}, {key:"consistency",label:"Consistency"}, {key:"pitDiscipline",label:"Pit discipline"},
+];
+function Stats({driver}: {driver: RecruitDriver}) {
+ const effects = driverEffects(driver.stats);
+ return <>
+ {stats.map(s =>
{s.label} {driver.stats[s.key]}
)}
+ Pace offset {effects.paceOffset > 0 ? "+" : ""}{effects.paceOffset.toFixed(2)}s/lap · service {effects.serviceSeconds.toFixed(2)}s
+ >;
+}
+export default function DriverRecruitment({onClose, setup, onApply}: {
+ onClose: () => void; setup?: SandboxSetup; onApply?: (setup: SandboxSetup) => void;
+}) {
+ const [loaded] = useState(readTeam);
+ const [team, setTeam] = useState(loaded.team);
+ const [warning, setWarning] = useState(loaded.warning);
+ const [message, setMessage] = useState("");
+ const [busy, setBusy] = useState(loaded.team.revision === 0 && !loaded.warning);
+ const [confirmReset, setConfirmReset] = useState(false);
+ const [draft, setDraft] = useState(() => ({id:crypto.randomUUID(),name:"My rookie",color:"#64d2b6",origin:"custom",stats:{pace:70,consistency:70,pitDiscipline:70}}));
+ useEffect(() => {
+ let active = true;
+ if (loaded.team.revision === 0 && !loaded.warning) {
+ void ensureTeam(loaded.team).then(saved => { if(active) setTeam(saved); })
+ .catch(e => { if(active) setWarning((e as Error).message); })
+ .finally(() => { if(active) setBusy(false); });
+ }
+ return () => { active = false; };
+ }, [loaded]);
+ useEffect(() => {
+ const changed = (event: StorageEvent) => {
+ if (event.key === teamKey || event.key === null) setWarning("Team data changed in another tab. Load latest team before editing.");
+ };
+ window.addEventListener("storage", changed);
+ return () => window.removeEventListener("storage", changed);
+ }, []);
+ async function transact(change: (team: Team) => Team, success: string) {
+ setBusy(true); setMessage("");
+ try {
+ const saved = await saveTeam(team, change(team));
+ setTeam(saved); setWarning(""); setMessage(success);
+ return true;
+ } catch(e) { setWarning((e as Error).message); return false; }
+ finally { setBusy(false); }
+ }
+ function loadLatest() {
+ const result = readTeam();setTeam(result.team);setWarning(result.warning);setMessage("Latest team loaded. The custom draft and current race are unchanged.");
+ }
+ async function startFresh() {
+ setBusy(true);
+ try {setTeam(await resetTeam());setWarning("");setMessage("Fresh team started with 12,000 credits.");setConfirmReset(false);}
+ catch(e) {setWarning((e as Error).message);}finally{setBusy(false);}
+ }
+ const fee = signingFee(draft.stats), used = pointsUsed(draft.stats);
+ const ready = team.lineup.every(id => id !== null);
+ return
+ FICTIONAL TEAM MANAGER Recruit generated drivers or build your own. Credits and ratings are local game values. Your roster is saved in this browser; it is separate from multiplayer guest ownership.
+
{team.name} {team.credits.toLocaleString("en-US")} credits {team.roster.length}/6 drivers
+ {warning && {warning}
}
+
+ {warning && {
+ try {downloadJson("pitwall-team-stored-backup.json",{raw:localStorage.getItem(teamKey)});}catch(e){setWarning((e as Error).message);}
+ }}>Back up stored team data }
+ Load latest team
+ downloadJson("pitwall-team.json",team)}>Export team JSON
+ setConfirmReset(true)}>Start fresh team
+
+ {confirmReset && This replaces the saved roster, market, lineup and credits with a fresh team. Existing races and saved circuits keep their copied drivers. Export your team first if you want a record.
void startFresh()}>Confirm fresh team setConfirmReset(false)}>Keep current team
}
+ Race lineup
+ {([0,1] as const).map(i => Race seat {i+1}
+ void transact(t => assignSeat(t,i,e.target.value || null), "Lineup saved.")}>
+ Choose signed driver {team.roster.map(d => {d.name} · {overall(d.stats)} OVR )}
+ )}
+ void transact(t => ({...t,lineup:[t.lineup[1],t.lineup[0]]}), "Race seats swapped and saved.")}>Swap race seats
+ {setup && onApply && {
+ try {onApply(applyLineup(team,setup));onClose();}catch(e){setWarning((e as Error).message);}
+ }}>Apply lineup and restart sandbox }
+
+ Assign two different signed drivers. Selecting the other seat's driver swaps them. Applying replaces grid slots 1–2, keeps their scheduled pit laps and other opponents, and restarts the local run. Save the circuit/race setup afterward to retain that grid. Existing multiplayer rooms do not change.
+ {!onApply && To race this lineup, open Custom circuit studio → Circuit race sandbox → Recruit and manage drivers.
}
+
+ Your roster
+ {!team.roster.length && No signed drivers yet. Scout the market or create a custom rookie below.
}
+ {team.roster.map(d =>
+
{d.name} {overall(d.stats)} OVR
+ {d.origin === "custom" ? "CUSTOM BUILD" : "RECRUITED"}{team.lineup.includes(d.id) ? " · RACE LINEUP" : " · RESERVE"}
+ void transact(t => releaseDriver(t,d.id), `${d.name} released. Lineup selection cleared where needed.`)}>Release {d.name} · +{releaseRefund(d).toLocaleString("en-US")}
+ )}
+
+
Scout market void transact(refreshMarket, "New market saved. Signed drivers and lineup retained.")}>Scout new market · {refreshFee} credits
+ Signing is disabled when you cannot afford the fee or your six-driver roster is full. Released drivers leave the roster and are not returned to this market.
+ {team.market.map(d =>
+
{d.name} {overall(d.stats)} OVR
+ = 6 || team.credits < signingFee(d.stats)} onClick={() => void transact(t => signDriver(t,d.id), `${d.name} signed and saved to your roster.`)}>Sign {d.name} · {signingFee(d.stats).toLocaleString("en-US")} credits
+ )}
+ {!team.market.length && All prospects from this market have been signed. Scout another market for 250 credits.
}
+
+
+ {message}
+ Model: pace and consistency form a 60/40 weighted pace rating; offset = (70 − rating) × 0.12 seconds/lap. Pit discipline gives service = 5 − rating × 0.04 seconds. Consistency is a steady pace modifier here, not random lap variation; tyres, traffic and mistakes are not simulated. Signing fees rise with squared stats; releases refund 40%. Export is an inspection record; a team importer is not implemented.
+ ;
+}
diff --git a/frontend/src/lab.css b/frontend/src/lab.css
index 7f341f8..7c3d376 100644
--- a/frontend/src/lab.css
+++ b/frontend/src/lab.css
@@ -144,6 +144,15 @@
.room-status { justify-content: space-between; }
.room-seat { padding: 12px 0; border-bottom: 1px solid var(--line); }
.room-seat > span { flex: 1 1 100%; }
+.recruit-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 16px; margin: 16px 0; }
+.recruit-card { background: var(--panel); border: 1px solid var(--line); border-radius: 16px; padding: 18px; min-width: 0; }
+.recruit-card h4 { margin: 0; padding-left: 10px; border-left: 4px solid; font-size: 15px; overflow-wrap: anywhere; }
+.recruit-card .room-status { margin: 0 0 14px; }
+.recruit-stats { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 12px; margin: 14px 0; }
+.recruit-stats span, .recruit-stats strong { display: block; font-size: 11px; }
+.recruit-stats strong { font-size: 22px; margin: 6px 0; }
+.recruit-stats meter { width: 100%; height: 8px; accent-color: #64d2b6; }
+@media (max-width: 700px) { .recruit-grid { grid-template-columns: minmax(0, 1fr); } }
@media (max-width: 700px) { .room-entry-grid { grid-template-columns: minmax(0, 1fr); } }
.sandbox-stage {
display: grid;
diff --git a/frontend/src/recruitment.test.ts b/frontend/src/recruitment.test.ts
new file mode 100644
index 0000000..a0171e1
--- /dev/null
+++ b/frontend/src/recruitment.test.ts
@@ -0,0 +1,88 @@
+import {afterEach, beforeEach, describe, expect, it, vi} from "vitest";
+import {newTrack} from "./custom-track";
+import {parseSandbox, sandboxDefaults} from "./sandbox";
+import {applyLineup, assignSeat, createDriver, driverEffects, ensureTeam, generateMarket, newTeam, parseTeam, refreshMarket, releaseDriver, releaseRefund, saveTeam, signDriver, signingFee, teamKey, type RecruitDriver} from "./recruitment";
+
+const rookie = (id: string, stats = {pace:70,consistency:70,pitDiscipline:70}): RecruitDriver => ({id,name:id,color:"#64d2b6",origin:"custom",stats});
+describe("fictional recruiting and team economy", () => {
+ let stored: Map;
+ beforeEach(() => {
+ stored = new Map();
+ vi.stubGlobal("navigator",{});
+ vi.stubGlobal("localStorage",{getItem:(key:string)=>stored.get(key)??null,setItem:(key:string,value:string)=>stored.set(key,value)});
+ });
+ afterEach(() => vi.unstubAllGlobals());
+ it("generates reproducible markets with bounded varied stats and unique identities", () => {
+ expect(generateMarket(42,0)).toEqual(generateMarket(42,0));
+ expect(generateMarket(42,1)).not.toEqual(generateMarket(42,0));
+ const ids = new Set(), ratings = new Set();
+ for (let seed=1;seed<=100;seed++) for(const d of generateMarket(seed,0)) {
+ expect(ids.has(d.id)).toBe(false);ids.add(d.id);
+ for(const n of Object.values(d.stats)){expect(n).toBeGreaterThanOrEqual(45);expect(n).toBeLessThanOrEqual(90);ratings.add(n);}
+ }
+ expect(ratings.size).toBeGreaterThan(30);
+ });
+ it("charges exactly once when signing, prevents duplicate signing and prices stronger builds higher", () => {
+ const team=newTeam(42), driver=team.market[0], hired=signDriver(team,driver.id);
+ expect(hired.credits).toBe(12000-signingFee(driver.stats));
+ expect(hired.market.some(d=>d.id===driver.id)).toBe(false);
+ expect(hired.roster).toEqual([driver]);
+ expect(()=>signDriver(hired,driver.id)).toThrow(/available/);
+ expect(()=>signDriver({...team,credits:0},driver.id)).toThrow(/credits/);
+ expect(signingFee({pace:100,consistency:100,pitDiscipline:100})).toBeGreaterThan(signingFee({pace:50,consistency:50,pitDiscipline:50}));
+ expect(team.roster).toHaveLength(0);
+ });
+ it("enforces custom point limits, unique names, valid stats and six roster slots", () => {
+ expect(()=>createDriver(newTeam(1),rookie("Elite",{pace:100,consistency:100,pitDiscipline:100}))).toThrow(/210/);
+ for(const bad of [NaN,9,101,20.5])expect(()=>createDriver(newTeam(1),rookie("Bad",{pace:bad,consistency:10,pitDiscipline:10}))).toThrow();
+ let t=newTeam(1);
+ for(let i=0;i<6;i++)t=createDriver(t,rookie(`Rookie ${i}`,{pace:10,consistency:10,pitDiscipline:10}));
+ expect(()=>createDriver(t,rookie("Overflow"))).toThrow(/full/);
+ const one=createDriver(newTeam(1),rookie("Nova"));
+ expect(()=>createDriver(one,{...rookie("other"),name:"nova"})).toThrow(/name/);
+ });
+ it("swaps occupied seats without duplicating drivers and release clears seats with a partial refund", () => {
+ let t=createDriver(createDriver(newTeam(1),rookie("One")),rookie("Two"));
+ t=assignSeat(assignSeat(t,0,"One"),1,"Two");
+ const swapped=assignSeat(t,0,"Two");
+ expect(swapped.lineup).toEqual(["Two","One"]);
+ expect(swapped.credits).toBe(t.credits);
+ const released=releaseDriver(swapped,"One");
+ expect(released.lineup).toEqual(["Two",null]);
+ expect(released.credits).toBe(t.credits+releaseRefund(t.roster[0]));
+ expect(released.credits).toBeLessThan(12000-signingFee(t.roster[1].stats));
+ expect(()=>assignSeat(released,1,"One")).toThrow(/Sign/);
+ });
+ it("charges scouting while keeping signed drivers/lineup, and retains a valid saved profile", () => {
+ let t=createDriver(newTeam(42),rookie("One"));t=assignSeat(t,0,"One");
+ const next=refreshMarket(t);
+ expect(next.credits).toBe(t.credits-250);expect(next.market).toHaveLength(6);
+ expect(next.market).not.toEqual(t.market);expect(next.roster).toEqual(t.roster);expect(next.lineup).toEqual(t.lineup);
+ expect(parseTeam(JSON.parse(JSON.stringify(next)))).toEqual(next);
+ expect(()=>refreshMarket({...t,credits:249})).toThrow(/credits/);
+ expect(()=>parseTeam({...t,lineup:["One","One"]})).toThrow(/lineup/);
+ expect(()=>parseTeam({...t,credits:-1})).toThrow();
+ expect(()=>parseTeam({...t,market:[t.roster[0]]})).toThrow();
+ });
+ it("applies the two selected builds without mutating opponents, geometry or scheduled stops", () => {
+ let t=createDriver(createDriver(newTeam(1),rookie("Fast",{pace:100,consistency:100,pitDiscipline:10})),rookie("Crew",{pace:10,consistency:90,pitDiscipline:100}));
+ t=assignSeat(assignSeat(t,0,"Fast"),1,"Crew");
+ const setup=sandboxDefaults(newTrack()), next=applyLineup(t,setup);
+ expect(driverEffects(t.roster[0].stats)).toEqual({paceOffset:-3.6,serviceSeconds:4.6});
+ expect(next.drivers[0]).toMatchObject({id:"recruit:Fast",name:"Fast",paceOffset:-3.6,serviceSeconds:4.6,pitLap:1});
+ expect(next.drivers[1]).toMatchObject({name:"Crew",serviceSeconds:1,pitLap:0});
+ expect(next.drivers[2]).toEqual(setup.drivers[2]);expect(next.pitControls).toEqual(setup.pitControls);
+ expect(parseSandbox(next)).toEqual(next);expect(setup.drivers[0].name).toBe("Driver 1");
+ expect(()=>applyLineup(newTeam(42),setup)).toThrow(/two signed/);
+ });
+ it("initializes once even under repeated mounts, detects stale saves and never spends after a storage failure", async () => {
+ const initial=newTeam(42), saved=await ensureTeam(initial);
+ expect(await ensureTeam(newTeam(99))).toEqual(saved);
+ const signed=await saveTeam(saved,signDriver(saved,saved.market[0].id));
+ await expect(saveTeam(saved,refreshMarket(saved))).rejects.toThrow(/another tab/);
+ expect(JSON.parse(stored.get(teamKey)!)).toEqual(signed);
+ vi.stubGlobal("localStorage",{getItem:()=>JSON.stringify(signed),setItem:()=>{throw new Error("Storage denied");}});
+ await expect(saveTeam(signed,refreshMarket(signed))).rejects.toThrow(/denied/);
+ expect(JSON.parse(stored.get(teamKey)!)).toEqual(signed);
+ });
+});
diff --git a/frontend/src/recruitment.ts b/frontend/src/recruitment.ts
new file mode 100644
index 0000000..4bf3ca6
--- /dev/null
+++ b/frontend/src/recruitment.ts
@@ -0,0 +1,157 @@
+import type { SandboxDriver, SandboxSetup } from "./sandbox";
+
+export const teamKey = "pitwall.recruitment.v1";
+export const startingCredits = 12000;
+export const customPoints = 210;
+export const refreshFee = 250;
+export type DriverStats = { pace: number; consistency: number; pitDiscipline: number };
+export type RecruitDriver = {
+ id: string; name: string; color: string; origin: "market" | "custom"; stats: DriverStats;
+};
+export type Team = {
+ version: 1; id: string; revision: number; name: string; credits: number;
+ seed: number; generation: number; roster: RecruitDriver[]; market: RecruitDriver[];
+ lineup: [string | null, string | null];
+};
+const firstNames = ["Nova", "Arden", "Luca", "Mika", "Alex", "Sora", "Remy", "Kai", "Zara", "Eden", "Rio", "Avery"];
+const lastNames = ["Vega", "Marin", "Vale", "Sato", "Reed", "Silva", "Costa", "Quinn", "Mercer", "Blake", "Moreau", "Park"];
+const colors = ["#ff665d", "#6d9fff", "#f2c75e", "#64d2b6", "#bd8bff", "#f095cf"];
+function random(seed: number) {
+ let value = seed >>> 0;
+ return () => {
+ value ^= value << 13; value ^= value >>> 17; value ^= value << 5;
+ return (value >>> 0) / 4294967296;
+ };
+}
+export function generateMarket(seed: number, generation: number): RecruitDriver[] {
+ const next = random(seed);
+ return Array.from({length: 6}, (_, i) => ({
+ id: `market-${generation}-${seed.toString(16)}-${i}`,
+ name: `${firstNames[(Math.floor(next() * firstNames.length) + i) % firstNames.length]} ${lastNames[(generation + i) % lastNames.length]}`,
+ color: colors[i], origin: "market" as const,
+ stats: {pace: 45 + Math.floor(next() * 46), consistency: 45 + Math.floor(next() * 46), pitDiscipline: 45 + Math.floor(next() * 46)},
+ }));
+}
+export function newTeam(seed = crypto.getRandomValues(new Uint32Array(1))[0] || 1): Team {
+ return {version: 1, id: crypto.randomUUID(), revision: 0, name: "Midnight Racing", credits: startingCredits,
+ seed, generation: 0, roster: [], market: generateMarket(seed, 0), lineup: [null, null]};
+}
+export const overall = (s: DriverStats) => Math.round((s.pace + s.consistency + s.pitDiscipline) / 3);
+export const pointsUsed = (s: DriverStats) => s.pace + s.consistency + s.pitDiscipline;
+export const signingFee = (s: DriverStats) => 500 + Math.round((s.pace ** 2 * .45 + s.consistency ** 2 * .25 + s.pitDiscipline ** 2 * .15) / 25) * 25;
+export const releaseRefund = (d: RecruitDriver) => Math.floor(signingFee(d.stats) * .4);
+export function driverEffects(s: DriverStats) {
+ return {paceOffset: Math.round((70 - (s.pace * .6 + s.consistency * .4)) * .12 * 100) / 100,
+ serviceSeconds: Math.round((5 - s.pitDiscipline * .04) * 100) / 100};
+}
+function checkDriver(raw: unknown): RecruitDriver {
+ if (!raw || typeof raw !== "object") throw new Error("Invalid driver.");
+ const d = raw as RecruitDriver;
+ if (typeof d.id !== "string" || !d.id || d.id.length > 64 || typeof d.name !== "string" || !d.name.trim() || d.name.trim().length > 24 || /[\x00-\x1f]/.test(d.name) ||
+ typeof d.color !== "string" || !/^#[0-9a-f]{6}$/i.test(d.color) || !["market", "custom"].includes(d.origin) || !d.stats ||
+ [d.stats.pace, d.stats.consistency, d.stats.pitDiscipline].some(n => !Number.isInteger(n) || n < 10 || n > 100) ||
+ (d.origin === "custom" && pointsUsed(d.stats) > customPoints)) throw new Error("Use a name of 1–24 characters, valid colour and integer stats from 10–100. Custom drivers have 210 points.");
+ return {id: d.id, name: d.name.trim(), color: d.color, origin: d.origin, stats: {...d.stats}};
+}
+export function parseTeam(raw: unknown): Team {
+ if (!raw || typeof raw !== "object") throw new Error("Invalid saved team.");
+ const t = raw as Team;
+ if (t.version !== 1 || typeof t.id !== "string" || !t.id || t.id.length > 64 || !Number.isSafeInteger(t.revision) || t.revision < 0 ||
+ typeof t.name !== "string" || !t.name.trim() || t.name.trim().length > 32 ||
+ !Number.isInteger(t.credits) || t.credits < 0 || t.credits > startingCredits ||
+ !Number.isInteger(t.seed) || t.seed < 1 || t.seed > 4294967295 || !Number.isInteger(t.generation) || t.generation < 0 || t.generation > 1000000 ||
+ !Array.isArray(t.roster) || t.roster.length > 6 || !Array.isArray(t.market) || t.market.length > 6 || !Array.isArray(t.lineup) || t.lineup.length !== 2)
+ throw new Error("Saved team has invalid budget, roster, market or version.");
+ const roster = t.roster.map(checkDriver), market = t.market.map(checkDriver);
+ const ids = [...roster, ...market].map(d => d.id);
+ if (new Set(ids).size !== ids.length || new Set(roster.map(d => d.name.toLowerCase())).size !== roster.length || market.some(d => d.origin !== "market") ||
+ t.lineup.some(id => id !== null && !roster.some(d => d.id === id)) || (t.lineup[0] !== null && t.lineup[0] === t.lineup[1]))
+ throw new Error("Saved team contains duplicate drivers or an invalid lineup.");
+ return {...t, name: t.name.trim(), roster, market, lineup: [...t.lineup]};
+}
+function hire(t: Team, driver: RecruitDriver): Team {
+ if (t.roster.length >= 6) throw new Error("Your roster is full. Release a driver before signing another.");
+ const cost = signingFee(driver.stats);
+ if (t.credits < cost) throw new Error("Not enough credits to sign this driver.");
+ if (t.roster.some(d => d.name.toLowerCase() === driver.name.toLowerCase())) throw new Error("A signed driver already uses this name. Use another name or prospect.");
+ if ([...t.roster, ...t.market].some(d => d.id === driver.id && d !== driver)) throw new Error("This driver ID is already in use.");
+ return {...t, credits: t.credits - cost, roster: [...t.roster, driver], market: t.market.filter(d => d.id !== driver.id)};
+}
+export function signDriver(team: Team, id: string): Team {
+ const d = team.market.find(d => d.id === id);
+ if (!d) throw new Error("This driver is no longer available.");
+ return hire(team, d);
+}
+export function createDriver(team: Team, draft: RecruitDriver): Team {
+ return hire(team, checkDriver({...draft, origin: "custom"}));
+}
+export function releaseDriver(team: Team, id: string): Team {
+ const driver = team.roster.find(d => d.id === id);
+ if (!driver) throw new Error("This driver is not on your roster.");
+ return {...team, credits: team.credits + releaseRefund(driver), roster: team.roster.filter(d => d.id !== id),
+ lineup: team.lineup.map(d => d === id ? null : d) as Team["lineup"]};
+}
+export function assignSeat(team: Team, seat: 0 | 1, id: string | null): Team {
+ if (id !== null && !team.roster.some(d => d.id === id)) throw new Error("Sign the driver before assigning a seat.");
+ const lineup = [...team.lineup] as Team["lineup"];
+ const other = seat === 0 ? 1 : 0;
+ if (id !== null && lineup[other] === id) lineup[other] = lineup[seat];
+ lineup[seat] = id;
+ return {...team, lineup};
+}
+export function refreshMarket(team: Team): Team {
+ if (team.credits < refreshFee) throw new Error("Not enough credits to scout a new market.");
+ const seed = Math.floor(random(team.seed)() * 4294967296) || 1;
+ const generation = team.generation + 1;
+ return {...team, credits: team.credits - refreshFee, seed, generation, market: generateMarket(seed, generation)};
+}
+export function applyLineup(team: Team, setup: SandboxSetup): SandboxSetup {
+ const drivers = team.lineup.map(id => team.roster.find(d => d.id === id));
+ if (drivers.some(d => !d)) throw new Error("Choose two signed drivers before applying your lineup.");
+ const converted = drivers.map((d, i): SandboxDriver => ({id: `recruit:${d!.id}`, name: d!.name, color: d!.color,
+ ...driverEffects(d!.stats), pitLap: setup.drivers[i]?.pitLap ?? 0}));
+ return {...setup, drivers: [...converted, ...setup.drivers.slice(2).filter(d => !converted.some(c => c.id === d.id))]};
+}
+
+export function readTeam(): {team: Team; warning: string} {
+ try {
+ const raw = localStorage.getItem(teamKey);
+ return {team: raw === null ? newTeam() : parseTeam(JSON.parse(raw)), warning: ""};
+ } catch {
+ return {team: newTeam(), warning: "Saved team could not be read. Existing data will not be overwritten. Restore browser storage access or back up the saved data before starting a fresh team."};
+ }
+}
+export async function saveTeam(expected: Team, next: Team): Promise {
+ const write = () => {
+ const raw = localStorage.getItem(teamKey);
+ if (raw !== null) {
+ const current = parseTeam(JSON.parse(raw));
+ if (current.id !== expected.id || current.revision !== expected.revision) throw new Error("Your team changed in another tab. Load latest team before making more changes.");
+ } else if (expected.revision !== 0) throw new Error("Saved team was removed in another tab. Load latest team first.");
+ const saved = parseTeam({...next, revision: expected.revision + 1});
+ localStorage.setItem(teamKey, JSON.stringify(saved));
+ return saved;
+ };
+ return typeof navigator !== "undefined" && navigator.locks
+ ? navigator.locks.request(teamKey, write) : write();
+}
+export async function ensureTeam(candidate: Team): Promise {
+ const write = () => {
+ const raw = localStorage.getItem(teamKey);
+ if (raw !== null) return parseTeam(JSON.parse(raw));
+ const saved = parseTeam({...candidate, revision: 1});
+ localStorage.setItem(teamKey, JSON.stringify(saved));
+ return saved;
+ };
+ return typeof navigator !== "undefined" && navigator.locks
+ ? navigator.locks.request(teamKey, write) : write();
+}
+export async function resetTeam(): Promise {
+ const write = () => {
+ const team = {...newTeam(), revision: 1};
+ localStorage.setItem(teamKey, JSON.stringify(team));
+ return team;
+ };
+ return typeof navigator !== "undefined" && navigator.locks
+ ? navigator.locks.request(teamKey, write) : write();
+}
From e0e5eb3b682a634eb4c5b2ad283bd27dfd3468b5 Mon Sep 17 00:00:00 2001
From: Nirmith Victor
Date: Sat, 21 Nov 2026 20:29:49 -0500
Subject: [PATCH 2/4] Sync signed drivers into sandbox grids and race replay
circuits
---
README.md | 1 +
docs/DEMO.md | 2 +-
docs/FOLLOW-UP-PLAN.md | 2 +
docs/TESTING.md | 5 +-
docs/USER-GUIDE.md | 5 +-
docs/flows.json | 32 ++++++++++++
docs/guide/04-circuit-studio.md | 13 ++++-
docs/guide/05-race-sandbox.md | 2 +
docs/guide/08-driver-recruitment.md | 13 ++++-
frontend/e2e/roster-tracks.spec.ts | 78 +++++++++++++++++++++++++++++
frontend/src/App.tsx | 5 ++
frontend/src/CircuitSandbox.tsx | 28 ++++++++++-
frontend/src/TrackEditor.tsx | 42 ++++++++--------
frontend/src/recruitment.test.ts | 18 ++++++-
frontend/src/recruitment.ts | 34 ++++++++++++-
frontend/src/replay-circuit.test.ts | 25 +++++++++
frontend/src/replay-circuit.ts | 40 +++++++++++++++
frontend/src/sandbox.ts | 15 +++++-
18 files changed, 327 insertions(+), 33 deletions(-)
create mode 100644 frontend/e2e/roster-tracks.spec.ts
create mode 100644 frontend/src/replay-circuit.test.ts
create mode 100644 frontend/src/replay-circuit.ts
diff --git a/README.md b/README.md
index df9a3fb..0f1ba23 100644
--- a/README.md
+++ b/README.md
@@ -27,6 +27,7 @@ The [handbook](docs/USER-GUIDE.md) documents every current user flow: steps, def
- Finite 1–50 lap fictional races with exact finish times/results, plus selected-driver live pit calls, cancellation before entry and repeat visits. See [race sessions](docs/guide/05-race-sandbox.md#sandbox-08).
- Private multiplayer rooms with a C#-owned simulation clock, SignalR snapshots, guest driver claims/readiness, host controls, live pit calls, reconnect, spectator support, guest removal and driver/host handover. Rooms are temporary and use one API instance. See [the multiplayer guide](docs/guide/07-multiplayer.md).
- Fictional driver recruitment: generated stat-based prospects, a 12,000-credit budget, six-driver roster, custom 210-point builds, two swappable race seats, browser persistence and lineup application to local/new multiplayer races. See [recruiting flows](docs/guide/08-driver-recruitment.md).
+- Live signed-roster availability in the sandbox, per-slot build selection and partial-lineup sync. **Race this circuit** starts a separate fictional race on the current replay's approximate outline with your selected signed drivers; generated pit lanes are validated before use.
- On-demand tool bundles, recovery from tool download failures, indexed replay lookups, a read-only setup doctor, and a one-command local preview.
- Light/dark themes with a header toggle, system preference on first visit, and a browser-saved choice across races.
- Save, revisit, and delete replay moments. Bookmarks are isolated by race and survive API restarts in PostgreSQL.
diff --git a/docs/DEMO.md b/docs/DEMO.md
index 8377dd3..053c6b1 100644
--- a/docs/DEMO.md
+++ b/docs/DEMO.md
@@ -28,7 +28,7 @@ The next session increment also lets you choose **Race distance (laps)**, select
## Engineering evidence
-- [Testing guide](TESTING.md): 73 frontend unit checks, nine Node checks, 54 browser scenarios, real API/database integration and dedicated storage/room concurrency checks.
+- [Testing guide](TESTING.md): 78 frontend unit checks, nine Node checks, 57 browser scenarios, real API/database integration and dedicated storage/room concurrency checks.
- [v1.3 architecture and limitations](V1.3.md): separate recorded/fictional state, independent enrichment, data quality and model assumptions.
- `node scripts/benchmark-replay.mjs`: reproducible lookup-only comparison against v1.2 with correctness assertions.
- GitHub Actions builds and tests the application and container; release branches publish an image. Hosting, accounts and multiplayer are later scope.
diff --git a/docs/FOLLOW-UP-PLAN.md b/docs/FOLLOW-UP-PLAN.md
index a5b6e2a..e03a301 100644
--- a/docs/FOLLOW-UP-PLAN.md
+++ b/docs/FOLLOW-UP-PLAN.md
@@ -51,6 +51,8 @@ The private-room increment adds a server-owned C# simulation, SignalR guest conn
Fictional recruiting now adds generated prospects/fees, a browser-local budget and six-driver roster, custom stat allocation and two selected/swappable builds. Applying a lineup copies bounded pace/service values into the local sandbox and future room definitions. See [recruitment](guide/08-driver-recruitment.md). Training, wages, seasons, protected server economies and car-part upgrades remain future scope.
+Roster/venue integration now fills empty team seats on signing, keeps signed choices current in an open sandbox, applies selected profiles to new unsaved grids and supports explicit partial sync/per-slot swaps without silently resetting active runs. **Race this circuit** prepares the open replay's approximate outline as a validated independent race venue, with a generated connected pit route and the selected signed drivers. Historical results remain separate; public hosting and a protected cross-device team economy are still later work.
+
## Branch and validation workflow
Use a focused feature branch for each milestone, run timing/camera unit tests and browser tests, and review into `develop`. Promote to `master` once the integration branch is ready. Container delivery continues through the existing GitHub Actions workflow.
diff --git a/docs/TESTING.md b/docs/TESTING.md
index 50d92b5..271d135 100644
--- a/docs/TESTING.md
+++ b/docs/TESTING.md
@@ -6,7 +6,7 @@ Run `node scripts/check-docs.mjs` from the repository root. CI runs the same che
When changing a flow, update its chapter and `docs/flows.json`, then run `node scripts/update-guide-index.mjs` and the checker. Follow [CONTRIBUTING](../CONTRIBUTING.md). Checks catch structural drift; reviewing the steps against actual behavior remains necessary. Documentation-only changes need this check, without repeating unrelated application suites locally.
-## Playwright: 54 browser scenarios
+## Playwright: 57 browser scenarios
| Area | Coverage |
| --- | --- |
@@ -34,6 +34,7 @@ When changing a flow, update its chapter and `docs/flows.json`, then run `node s
| Race sessions and live calls | Exact finite-race results/frozen clock, reset/distance preservation, cancellation without resetting, entry commitment, next-lap targeting and selected-driver/mobile controls |
| Multiplayer | Two independent guest sessions, readiness, synchronized clock/results, live calls, reload/reconnect, driver/host handover, invalid invitations, mobile leave, real-hub concurrent claim conflicts, token/ownership/host checks, forged-time rejection and guest removal |
| Fictional recruitment | Generated sign/release/scouting fees and persistence, custom point limits, saved seat swaps and applied performance, new multiplayer room copies, mobile/failed-write behavior, stale-tab protection, raw backup and confirmed corrupted-profile recovery |
+| Roster/venue integration | Same-window/cross-tab signed-roster availability without resetting an active run, explicit partial sync and per-slot swaps, saved-grid preservation, replay-outline racing, valid pit geometry, new-room hosting and historical replay isolation |
| Sector map | Completed-reference alignment, saved layout preference, no invented coordinates during gaps, hidden markers before coverage or in estimate mode |
| Tool loading | Studio bundle stays deferred until opened; a failed download returns to a usable replay |
@@ -41,7 +42,7 @@ These scenarios run against the production frontend build in Chromium. Historica
## Other checks
-- 73 Vitest checks cover replay timing and indexed boundary/seek behavior, track interpolation, map/layout preferences, recorded sample lookup and sector alignment, trails, share links, named layouts, geometry/rounding/import validation, deterministic strategy math, held-out pace evaluation, sandbox route/service transitions, setup migration, finish timing/frame invariance, result ordering, cancellation/repeat visits and pit-lane finishes. Recruiting checks cover seeded stats/identities, custom constraints, budget/fees/refunds, roster limits, seat swapping, applied settings and storage/revision failures. A committed shared fixture checks browser/server parity for rounded geometry, pit traversal/service/rejoin and finite results.
+- 78 Vitest checks cover replay timing and indexed boundary/seek behavior, track interpolation, map/layout preferences, recorded sample lookup and sector alignment, trails, share links, named layouts, geometry/rounding/import validation, deterministic strategy math, held-out pace evaluation, sandbox route/service transitions, setup migration, finish timing/frame invariance, result ordering, cancellation/repeat visits and pit-lane finishes. Recruiting checks cover seeded stats/identities, custom constraints, budget/fees/refunds, roster limits, seat swapping, applied settings and storage/revision failures. A committed shared fixture checks browser/server parity for rounded geometry, pit traversal/service/rejoin and finite results.
- `Pitwall.RoomChecks` checks authoritative room physics, frame invariance, validation, concurrent seat claims, host/driver authorization, reconnect, handover, guest removal and departure. It also consumes `data/testing/room-model.json`; fixture changes need review, rather than automatic regeneration to make a failure pass.
- Nine Node tests cover catalog filtering, identifiers, location alignment/quality, measured-sector/pit normalization, local environment parsing, bounded ports and connection-string escaping.
- `Pitwall.StoreChecks` verifies enrichment preservation, downgrade protection, concurrent writes, safe bundle seeding and bookmarks against both in-memory storage and PostgreSQL. It creates uniquely named test rows and removes only those rows.
diff --git a/docs/USER-GUIDE.md b/docs/USER-GUIDE.md
index 6799f87..4bf1650 100644
--- a/docs/USER-GUIDE.md
+++ b/docs/USER-GUIDE.md
@@ -31,6 +31,7 @@ Each flow has a stable ID, a **What**, **How**, **Result and storage**, and **Re
| Can I run a custom grid with scheduled stops? | Circuit race sandbox | Fictional pace/route/service animation |
| Can friends control drivers in the same race? | Multiplayer rooms | One server-owned fictional race with guest driver ownership |
| Can I sign and customize fictional drivers? | Driver recruitment | Browser-local roster/budget with two selected race builds |
+| Can my signed drivers race on an existing track? | Race this circuit | Separate fictional race using the current replay's approximate outline |
```mermaid
flowchart LR
@@ -86,7 +87,7 @@ Closing a studio or scenario without saving can lose its draft. Clearing browser
-84 documented flows. Each ID links directly to its instructions.
+86 documented flows. Each ID links directly to its instructions.
### Start Pitwall and choose a race
@@ -161,6 +162,7 @@ Closing a studio or scenario without saving can lose its draft. Clearing browser
| [STUDIO-07](guide/04-circuit-studio.md#studio-07) | Save and load a circuit |
| [STUDIO-08](guide/04-circuit-studio.md#studio-08) | Delete a saved circuit |
| [STUDIO-09](guide/04-circuit-studio.md#studio-09) | Import or export circuit JSON |
+| [STUDIO-10](guide/04-circuit-studio.md#studio-10) | Race signed drivers on an existing replay circuit |
### Configure and run a fictional race
@@ -211,6 +213,7 @@ Closing a studio or scenario without saving can lose its draft. Clearing browser
| [TEAM-06](guide/08-driver-recruitment.md#team-06) | Apply recruited builds and host them in a new room |
| [TEAM-07](guide/08-driver-recruitment.md#team-07) | Recover from storage failures or another tab's changes |
| [TEAM-08](guide/08-driver-recruitment.md#team-08) | Export a record or explicitly start fresh |
+| [TEAM-09](guide/08-driver-recruitment.md#team-09) | Sync signed drivers directly into a sandbox |
## How this stays current
diff --git a/docs/flows.json b/docs/flows.json
index b6286be..402ebdf 100644
--- a/docs/flows.json
+++ b/docs/flows.json
@@ -1018,6 +1018,38 @@
"frontend/src/CircuitSandbox.tsx",
"frontend/e2e/recruitment.spec.ts"
]
+ },
+ {
+ "id": "STUDIO-10",
+ "title": "Race signed drivers on an existing replay circuit",
+ "guide": "docs/guide/04-circuit-studio.md",
+ "anchor": "studio-10",
+ "sources": [
+ "frontend/src/App.tsx",
+ "frontend/src/TrackEditor.tsx",
+ "frontend/src/CircuitSandbox.tsx",
+ "frontend/src/recruitment.ts",
+ "frontend/src/sandbox.ts",
+ "frontend/src/replay-circuit.ts",
+ "frontend/src/replay-circuit.test.ts",
+ "frontend/e2e/roster-tracks.spec.ts"
+ ]
+ },
+ {
+ "id": "TEAM-09",
+ "title": "Sync signed drivers directly into a sandbox",
+ "guide": "docs/guide/08-driver-recruitment.md",
+ "anchor": "team-09",
+ "sources": [
+ "frontend/src/App.tsx",
+ "frontend/src/TrackEditor.tsx",
+ "frontend/src/CircuitSandbox.tsx",
+ "frontend/src/recruitment.ts",
+ "frontend/src/sandbox.ts",
+ "frontend/src/replay-circuit.ts",
+ "frontend/src/replay-circuit.test.ts",
+ "frontend/e2e/roster-tracks.spec.ts"
+ ]
}
]
}
diff --git a/docs/guide/04-circuit-studio.md b/docs/guide/04-circuit-studio.md
index 37fbb99..00c0ab2 100644
--- a/docs/guide/04-circuit-studio.md
+++ b/docs/guide/04-circuit-studio.md
@@ -11,10 +11,21 @@ The studio holds a draft. Saving/exporting is explicit; closing it is not an aut
**How:** Open **Custom circuit studio**. Edit the starter circuit, choose **New circuit** for a new starter/ID, or **Copy replay outline as draft** when the open race has enough outline points. Enter **Circuit name**.
-**Result and storage:** The default is a ten-point **Midnight circuit**, not a blank canvas. An outline copy is resampled/scaled as a new independent draft named **My outline remix**. Names are 1–48 trimmed characters.
+**Result and storage:** The default is a ten-point **Midnight circuit**, not a blank canvas. An outline copy is fitted with its aspect ratio retained, simplified if necessary to 6–120 separated valid points, and created as an independent draft named **My outline remix**. Copies use zero extra corner rounding to retain the sampled shape; you can change it later. Names are 1–48 trimmed characters.
**Recovery and limits:** Copying an outline does not copy telemetry, drivers or race timing. Validate the new shape before saving. New/copy replaces the working draft; recorded edit history may allow Undo until the studio closes, but explicit saved/exported copies are safer.
+
+## STUDIO-10 — Race signed drivers on an existing replay circuit
+
+**What:** Use an existing race's approximate circuit outline as a venue for a separate fictional race.
+
+**How:** Open/import a race through **Browse races**, then choose **Race this circuit** in the replay toolbar. The studio opens directly in sandbox mode with a new **[Circuit] [Year] · sandbox** draft. From an existing studio, **Race on [Circuit] [Year]** prepares the open replay's outline and replaces the working draft. Save an edited draft before switching.
+
+**Result and storage:** The new draft has its own ID, fitted outline and fictional sector divisions. A new unsaved grid uses available selected signed drivers automatically. The pit lane is generated and validated separately; concave outlines can choose another short connected entry/exit route. Set base pace, distance and pit plans as desired, run locally, or host this setup in a new multiplayer room. Saving the circuit/race setup is explicit.
+
+**Recovery and limits:** This does not reproduce real driver performance, measured sector boundaries, an official pit lane or the original race distance/time. Base pace and race distance use sandbox defaults. Missing outlines disable the shortcut. Outlines outside 6–5,000 finite samples or unable to simplify safely are rejected; a failed toolbar launch reports the failure and shows an editable starter rather than pretending it is the requested venue. Inspect pit validation and edit a lane if no generated route fits. The historical replay remains paused at its previous time with its recorded geometry/results unchanged.
+
## STUDIO-02 — Add, move and remove control points
diff --git a/docs/guide/05-race-sandbox.md b/docs/guide/05-race-sandbox.md
index 8164f79..559f932 100644
--- a/docs/guide/05-race-sandbox.md
+++ b/docs/guide/05-race-sandbox.md
@@ -39,6 +39,8 @@ This is a deterministic geometry/pace/service preview. It does not simulate grip
Use **Recruit and manage drivers** for [fictional recruiting and custom stat builds](08-driver-recruitment.md). Applying that lineup replaces the first two grid drivers with derived pace/service settings and restarts this sandbox; it is separate from real players controlling multiplayer seats.
+The signed roster also appears directly in each grid slot. [TEAM-09](08-driver-recruitment.md#team-09) covers automatic availability, fresh-grid defaults, partial-lineup sync and swapping existing signed builds. [STUDIO-10](04-circuit-studio.md#studio-10) opens a fictional race on the current replay's circuit outline. New default pit lanes try another short connected route if the initial lane crosses a concave circuit; a saved invalid lane still needs explicit editing/recovery.
+
## SANDBOX-03 — Attach and edit the pit lane
diff --git a/docs/guide/08-driver-recruitment.md b/docs/guide/08-driver-recruitment.md
index a4ded89..a9dc1e2 100644
--- a/docs/guide/08-driver-recruitment.md
+++ b/docs/guide/08-driver-recruitment.md
@@ -33,7 +33,7 @@ Recruitment manages fictional driver profiles. It is separate from real players
**How:** Choose **Sign [name] · [fee] credits**. The prospect moves to **Your roster**. **Release [name] · +[refund]** removes a signed driver and returns the displayed amount. A roster driver outside the two selected seats is a reserve.
-**Result and storage:** Signing deducts the fee and saves the roster/market/budget together. The fee is `500 + round((pace² × 0.45 + consistency² × 0.25 + pitDiscipline² × 0.15) / 25) × 25`. Release refunds 40% of that driver's signing fee, rounded down, and clears its selected seats. Release does not return a driver to the market. Existing race copies retain that driver until replaced.
+**Result and storage:** Signing deducts the fee and saves the roster/market/budget together. A signing fills the first empty selected race seat automatically; further signings become reserves when both are occupied. The fee is `500 + round((pace² × 0.45 + consistency² × 0.25 + pitDiscipline² × 0.15) / 25) × 25`. Release refunds 40% of that driver's signing fee, rounded down, and clears its selected seats. Release does not return a driver to the market. Existing race copies retain that driver until replaced.
**Recovery and limits:** Insufficient funds or a full roster disable signing. Re-signing a removed market ID is rejected. Signed names must be distinct ignoring case. Releases are immediate and have no undo; the refund is smaller than the signing cost. There are no recurring wages or race income yet.
@@ -97,3 +97,14 @@ Recruitment manages fictional driver profiles. It is separate from real players
**Result and storage:** A confirmed reset replaces this browser origin's recruiting record. Existing circuits, local race grid copies and multiplayer rooms remain separate. Resetting does not save or clear those copies. If you are viewing an unreadable saved record's fallback, back up the raw stored data before resetting; exporting the displayed fallback does not recover the old record.
**Recovery and limits:** There is no team importer or reset undo. A failed reset write retains the old record and reports an error. Other recruiting tabs must load the latest team after a reset. Credits are fictional, so a fresh-team reset is allowed; this is not a protected online economy.
+
+
+## TEAM-09 — Sync signed drivers directly into a sandbox
+
+**What:** Access the signed roster from the race grid without reopening recruitment or assembling a full two-driver team.
+
+**How:** Inspect **Signed team drivers** in the sandbox. Signings/releases/seat selections update its available roster in the same window or another tab. Use **Sync team lineup and restart** to apply all available selected seats, or choose a profile from **Signed driver** in an individual grid slot. One signed/selected driver is enough for this flow.
+
+**Result and storage:** New unsaved grids automatically use available selected team seats; a stored circuit/race setup retains its own grid until explicitly synced. Signing itself never resets a running race. A grid selection copies the profile's name, colour, derived pace and service duration. Choosing a build already in another slot swaps the builds while keeping each slot's planned pit lap. Sync/selection records ordinary sandbox undo history and restarts its local run; geometry, base pace and distance stay intact. Selecting team seat two can grow a one-driver grid to two.
+
+**Recovery and limits:** Save circuit/race setup separately to persist a copied grid. Unreadable roster storage disables selection/sync while leaving the manual grid usable. Releasing a profile removes it from available choices but does not erase an already copied grid driver. Existing multiplayer rooms keep their frozen driver definitions. Shared browser storage does not synchronize across devices or different origins/profiles.
diff --git a/frontend/e2e/roster-tracks.spec.ts b/frontend/e2e/roster-tracks.spec.ts
new file mode 100644
index 0000000..96a37fe
--- /dev/null
+++ b/frontend/e2e/roster-tracks.spec.ts
@@ -0,0 +1,78 @@
+import {test,expect} from "@playwright/test";
+import {createDriver,newTeam,teamKey} from "../src/recruitment";
+
+test("a signing appears in an open sandbox and can be synced or swapped without reopening the studio",async({page})=>{
+ await page.goto("/?race=monza-2024&t=120");
+ await page.getByRole("button",{name:"Custom circuit studio",exact:true}).click();
+ await page.getByRole("button",{name:"Circuit race sandbox",exact:true}).click();
+ const sandbox=page.getByRole("region",{name:"Circuit race sandbox",exact:true});
+ await sandbox.getByRole("button",{name:"Advance one lap",exact:true}).click();
+ await sandbox.getByRole("button",{name:"Recruit and manage drivers",exact:true}).click();
+ const recruit=page.getByRole("dialog",{name:"Driver recruitment",exact:true});
+ await recruit.getByLabel("Custom driver name",{exact:true}).fill("Synced rookie");
+ await recruit.getByRole("button",{name:"Create and sign custom driver",exact:true}).click();
+ await expect(recruit.getByTestId("roster-count")).toHaveText("1/6 drivers");
+ await recruit.getByRole("button",{name:"Close Driver recruitment",exact:true}).click();
+ await expect(sandbox.getByRole("heading",{name:"Signed team drivers · 1 available",exact:true})).toBeVisible();
+ await expect(sandbox.getByTestId("sandbox-clock")).toHaveText("00:01:30");
+ await sandbox.getByRole("button",{name:"Sync team lineup and restart",exact:true}).click();
+ await expect(sandbox.getByLabel("Grid 1 driver name",{exact:true})).toHaveValue("Synced rookie");
+ await expect(sandbox.getByTestId("sandbox-clock")).toHaveText("00:00:00");
+ await sandbox.getByLabel("Signed driver for grid 2",{exact:true}).selectOption({label:"Synced rookie"});
+ await expect(sandbox.getByLabel("Grid 2 driver name",{exact:true})).toHaveValue("Synced rookie");
+ await expect(sandbox.getByLabel("Grid 1 driver name",{exact:true})).toHaveValue("Driver 2");
+});
+
+test("race this circuit uses the current replay outline and signed lineup, then hosts the copied venue",async({page})=>{
+ const team={...createDriver(createDriver(newTeam(42),{id:"apex",name:"Venue Apex",color:"#64d2b6",origin:"custom",stats:{pace:70,consistency:70,pitDiscipline:70}}),{id:"crew",name:"Venue Crew",color:"#ff665d",origin:"custom",stats:{pace:60,consistency:60,pitDiscipline:60}}),revision:1};
+ await page.addInitScript(({key,team})=>localStorage.setItem(key,JSON.stringify(team)),{key:teamKey,team});
+ await page.goto("/?race=monza-2024&t=120");
+ await page.getByRole("button",{name:"Race this circuit",exact:true}).click();
+ const studio=page.getByRole("dialog",{name:"Custom circuit studio",exact:true});
+ const sandbox=studio.getByRole("region",{name:"Circuit race sandbox",exact:true});
+ await expect(sandbox).toBeVisible();
+ await expect(sandbox.getByLabel("Grid 1 driver name",{exact:true})).toHaveValue("Venue Apex");
+ await expect(sandbox.getByLabel("Grid 2 driver name",{exact:true})).toHaveValue("Venue Crew");
+ await sandbox.getByRole("button",{name:"Advance one lap",exact:true}).click();
+ await expect(sandbox.getByTestId("sandbox-clock")).toHaveText("00:01:30");
+ await studio.getByRole("button",{name:"Circuit editor",exact:true}).click();
+ await expect(studio.getByLabel("Circuit name",{exact:true})).toHaveValue("Monza 2024 · sandbox");
+ await expect(studio.getByRole("alert")).toHaveCount(0);
+ await studio.getByRole("button",{name:"Circuit race sandbox",exact:true}).click();
+ await sandbox.getByRole("button",{name:"Host this setup with friends",exact:true}).click();
+ const room=page.getByRole("dialog",{name:"Multiplayer rooms",exact:true});
+ await room.getByLabel("Guest name",{exact:true}).fill("Venue host");
+ await room.getByRole("button",{name:"Create private room",exact:true}).click();
+ await expect(room.getByRole("status",{exact:true})).toHaveText("Connected");
+ await expect(room.getByRole("button",{name:"Claim Venue Apex",exact:true})).toBeVisible();
+ await room.getByRole("button",{name:"Close Multiplayer rooms",exact:true}).click();
+ await studio.getByRole("button",{name:"Close Custom circuit studio",exact:true}).click();
+ await expect(page.getByTestId("elapsed-time")).toContainText("00:02:00");
+});
+
+test("saved custom grids keep their setup while roster changes arrive from another tab",async({page,context})=>{
+ await page.goto("/?race=monza-2024");
+ await page.getByRole("button",{name:"Custom circuit studio",exact:true}).click();
+ await page.getByLabel("Circuit name",{exact:true}).fill("Retained custom grid");
+ await page.getByRole("button",{name:"Circuit race sandbox",exact:true}).click();
+ const sandbox=page.getByRole("region",{name:"Circuit race sandbox",exact:true});
+ await sandbox.getByLabel("Grid 1 driver name",{exact:true}).fill("Keep my grid");
+ await sandbox.getByRole("button",{name:"Save circuit and race setup",exact:true}).click();
+ await sandbox.getByRole("button",{name:"Advance one lap",exact:true}).click();
+ const other=await context.newPage();
+ try{
+ await other.goto("/?race=monza-2024");
+ await other.getByRole("button",{name:"Driver recruitment",exact:true}).click();
+ await other.getByLabel("Custom driver name",{exact:true}).fill("New signing");
+ await other.getByRole("button",{name:"Create and sign custom driver",exact:true}).click();
+ await expect(sandbox.getByRole("heading",{name:"Signed team drivers · 1 available",exact:true})).toBeVisible();
+ await expect(sandbox.getByLabel("Grid 1 driver name",{exact:true})).toHaveValue("Keep my grid");
+ await expect(sandbox.getByTestId("sandbox-clock")).toHaveText("00:01:30");
+ await page.reload();
+ await page.getByRole("button",{name:"Custom circuit studio",exact:true}).click();
+ await page.getByLabel("Saved circuits",{exact:true}).selectOption({label:"Retained custom grid"});
+ await page.getByRole("button",{name:"Load circuit",exact:true}).click();
+ await page.getByRole("button",{name:"Circuit race sandbox",exact:true}).click();
+ await expect(sandbox.getByLabel("Grid 1 driver name",{exact:true})).toHaveValue("Keep my grid");
+ }finally{await other.close();}
+});
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index 32b9745..ca4a00d 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -88,6 +88,7 @@ function App() {
const [shareLink, setShareLink] = useState(null);
const [positionSource, setPositionSource] = useState("lap");
const [showTrackEditor, setShowTrackEditor] = useState(false);
+ const [raceOnReplay, setRaceOnReplay] = useState(false);
const [showStrategy, setShowStrategy] = useState(false);
const [showAnalysis, setShowAnalysis] = useState(false);
const [showBacktest, setShowBacktest] = useState(false);
@@ -424,6 +425,7 @@ function App() {
REPLAY TOOLS
+
{setPlaying(false);setRaceOnReplay(true);setShowTrackEditor(true);}}>Race this circuit
{setPlaying(false);setShowRecruitment(true);}}>Driver recruitment
{setPlaying(false);setShowRooms(true);}}>Multiplayer rooms
{
setPlaying(false);
+ setRaceOnReplay(false);
setShowTrackEditor(true);
}}
>
@@ -988,6 +991,8 @@ function App() {
{showTrackEditor && (
setShowTrackEditor(false)}
/>
)}
diff --git a/frontend/src/CircuitSandbox.tsx b/frontend/src/CircuitSandbox.tsx
index 155c081..47f6796 100644
--- a/frontend/src/CircuitSandbox.tsx
+++ b/frontend/src/CircuitSandbox.tsx
@@ -10,6 +10,7 @@ import {
type Point,
} from "./custom-track";
import NumberField from "./NumberField";
+import {assignRecruitToGrid, availableLineup, readTeam, teamKey, teamUpdatedEvent} from "./recruitment";
import {
advanceRace,
nextPitEntry,
@@ -37,7 +38,13 @@ export default function CircuitSandbox({
onSaved: () => void;
active: boolean;
}) {
- const [setup, setSetup] = useState(() => readSandbox(track));
+ const [setup, setSetup] = useState(() => {
+ const current=readSandbox(track);
+ try {if(localStorage.getItem(sandboxKey(track.id))!==null)return current;}catch{return current;}
+ const saved=readTeam();
+ return saved.warning?current:availableLineup(saved.team,current);
+ });
+ const [signed, setSigned] = useState(readTeam);
const [showRoom, setShowRoom] = useState(false);
const [showRecruitment, setShowRecruitment] = useState(false);
const [session, setSession] = useState(() => ({
@@ -56,6 +63,12 @@ export default function CircuitSandbox({
const geometry = useMemo(() => sandboxGeometry(track, setup), [track, setup]);
const errors = useMemo(() => validateSandbox(track, setup), [track, setup]),
valid = !errors.length;
+ useEffect(() => {
+ const refresh=()=>setSigned(readTeam());
+ const storage=(e: StorageEvent)=>{if(e.key===teamKey||e.key===null)refresh();};
+ refresh();window.addEventListener(teamUpdatedEvent,refresh);window.addEventListener("storage",storage);window.addEventListener("focus",refresh);
+ return ()=>{window.removeEventListener(teamUpdatedEvent,refresh);window.removeEventListener("storage",storage);window.removeEventListener("focus",refresh);};
+ }, [active]);
useEffect(() => {
if (!active || !running || !valid || complete) return;
let frame = 0,
@@ -135,6 +148,14 @@ export default function CircuitSandbox({
{setRunning(false);setShowRecruitment(true);}}>Recruit and manage drivers
{showRecruitment && Loading recruitment…}> setShowRecruitment(false)} /> }
{showRoom && Loading multiplayer…}> setShowRoom(false)} /> }
+
+ Signed team drivers · {signed.team.roster.length} available
+ Your signed roster updates here automatically. New unsaved grids use your selected team seats. Existing grids and running races change only when you apply a signed build or sync the lineup; doing so restarts this local run.
+ {signed.warning && Could not load the signed roster. Open recruitment to recover it; your current grid stays available.
}
+ id!==null)} onClick={()=>{
+ change(availableLineup(signed.team,setup));setMessage("Selected signed drivers synced to the grid. Local run restarted; save setup to retain this grid.");
+ }}>Sync team lineup and restart
+
Race distance (laps)
@@ -552,6 +573,11 @@ export default function CircuitSandbox({
{setup.drivers.map((d, i) => (
Grid slot {i + 1}
+ Signed driver
+ {
+ if(e.target.value)change(assignRecruitToGrid(signed.team,setup,i,e.target.value));
+ }}>Choose signed build… {signed.team.roster.map(profile=>{profile.name} )}
+
Name
void;
+ replayLabel?: string;
+ startOnReplayCircuit?: boolean;
}) {
- const [draft, setDraft] = useState(newTrack);
- const [workspace, setWorkspace] = useState<"edit" | "race">("edit");
- const [hasSandbox, setHasSandbox] = useState(false);
+ const [initial] = useState(()=>{
+ if(startOnReplayCircuit)try{return {track:circuitFromReplay(outline,`${replayLabel} · sandbox`),racing:true,error:""};}
+ catch(e){return {track:newTrack(),racing:false,error:`Could not prepare ${replayLabel}: ${(e as Error).message} A starter draft is shown for editing.`};}
+ return {track:newTrack(),racing:false,error:""};
+ });
+ const [draft, setDraft] = useState(initial.track);
+ const [workspace, setWorkspace] = useState<"edit" | "race">(initial.racing?"race":"edit");
+ const [hasSandbox, setHasSandbox] = useState(initial.racing);
const [saved, setSaved] = useState(readTracks);
const [savedId, setSavedId] = useState("");
const [selected, setSelected] = useState(0);
@@ -125,6 +135,11 @@ export default function TrackEditor({
keys. Geometry and preview markers belong to this studio; your
historical replay stays separate.
+ {initial.error && {initial.error}
}
+ {
+ try {replace(circuitFromReplay(outline,`${replayLabel} · sandbox`));setHasSandbox(true);setWorkspace("race");}
+ catch(e){setMessage((e as Error).message);}
+ }}>Race on {replayLabel} Uses this replay's approximate circuit outline, with fictional pace, sectors and pit lane. Switching replaces the working draft; save it first.
{
- const step = Math.max(1, Math.ceil(outline.length / 40));
- const points = outline
- .filter((_, i) => i % step === 0)
- .map(
- (p) =>
- [
- Math.round(p[0] * 0.9 + 40),
- Math.round((p[1] * 440) / 520 + 40),
- ] as Point,
- );
- replace({
- ...newTrack(),
- name: "My outline remix",
- points,
- sectorEnds: [
- Math.floor(points.length / 3),
- Math.floor((points.length * 2) / 3),
- ],
- });
+ try {replace(circuitFromReplay(outline,"My outline remix"));}
+ catch(e){setMessage((e as Error).message);}
}}
>
Copy replay outline as draft
diff --git a/frontend/src/recruitment.test.ts b/frontend/src/recruitment.test.ts
index a0171e1..b84ed27 100644
--- a/frontend/src/recruitment.test.ts
+++ b/frontend/src/recruitment.test.ts
@@ -1,7 +1,7 @@
import {afterEach, beforeEach, describe, expect, it, vi} from "vitest";
import {newTrack} from "./custom-track";
import {parseSandbox, sandboxDefaults} from "./sandbox";
-import {applyLineup, assignSeat, createDriver, driverEffects, ensureTeam, generateMarket, newTeam, parseTeam, refreshMarket, releaseDriver, releaseRefund, saveTeam, signDriver, signingFee, teamKey, type RecruitDriver} from "./recruitment";
+import {applyLineup, assignRecruitToGrid, assignSeat, availableLineup, createDriver, driverEffects, ensureTeam, generateMarket, newTeam, parseTeam, refreshMarket, releaseDriver, releaseRefund, saveTeam, signDriver, signingFee, teamKey, type RecruitDriver} from "./recruitment";
const rookie = (id: string, stats = {pace:70,consistency:70,pitDiscipline:70}): RecruitDriver => ({id,name:id,color:"#64d2b6",origin:"custom",stats});
describe("fictional recruiting and team economy", () => {
@@ -85,4 +85,20 @@ describe("fictional recruiting and team economy", () => {
await expect(saveTeam(signed,refreshMarket(signed))).rejects.toThrow(/denied/);
expect(JSON.parse(stored.get(teamKey)!)).toEqual(signed);
});
+ it("fills empty team seats on signing and applies one signed seat without requiring a full team",()=>{
+ const team=createDriver(newTeam(1),rookie("Solo"));
+ expect(team.lineup).toEqual(["Solo",null]);
+ const setup=sandboxDefaults(newTrack()),next=availableLineup(team,setup);
+ expect(next.drivers[0].name).toBe("Solo");expect(next.drivers[1]).toEqual(setup.drivers[1]);
+ const released=releaseDriver(team,"Solo");expect(availableLineup(released,setup)).toEqual(setup);
+ });
+ it("swaps signed builds between grid slots without duplicating IDs or moving planned stops",()=>{
+ const team=createDriver(createDriver(newTeam(1),rookie("One")),rookie("Two"));
+ const setup=applyLineup(team,sandboxDefaults(newTrack()));
+ const next=assignRecruitToGrid(team,setup,1,"One");
+ expect(next.drivers.map(d=>d.id)).toEqual(["recruit:Two","recruit:One",setup.drivers[2].id]);
+ expect(next.drivers.map(d=>d.pitLap)).toEqual(setup.drivers.map(d=>d.pitLap));
+ expect(()=>assignRecruitToGrid(team,setup,9,"One")).toThrow();
+ expect(()=>assignRecruitToGrid(team,setup,0,"not signed")).toThrow();
+ });
});
diff --git a/frontend/src/recruitment.ts b/frontend/src/recruitment.ts
index 4bf3ca6..71973f1 100644
--- a/frontend/src/recruitment.ts
+++ b/frontend/src/recruitment.ts
@@ -1,6 +1,10 @@
-import type { SandboxDriver, SandboxSetup } from "./sandbox";
+import {newSandboxDriver, type SandboxDriver, type SandboxSetup} from "./sandbox";
export const teamKey = "pitwall.recruitment.v1";
+export const teamUpdatedEvent = "pitwall-team-updated";
+function announceTeam() {
+ if (typeof window !== "undefined") window.dispatchEvent(new Event(teamUpdatedEvent));
+}
export const startingCredits = 12000;
export const customPoints = 210;
export const refreshFee = 250;
@@ -75,7 +79,10 @@ function hire(t: Team, driver: RecruitDriver): Team {
if (t.credits < cost) throw new Error("Not enough credits to sign this driver.");
if (t.roster.some(d => d.name.toLowerCase() === driver.name.toLowerCase())) throw new Error("A signed driver already uses this name. Use another name or prospect.");
if ([...t.roster, ...t.market].some(d => d.id === driver.id && d !== driver)) throw new Error("This driver ID is already in use.");
- return {...t, credits: t.credits - cost, roster: [...t.roster, driver], market: t.market.filter(d => d.id !== driver.id)};
+ const lineup = [...t.lineup] as Team["lineup"];
+ const empty = lineup.findIndex(id => id === null);
+ if (empty >= 0) lineup[empty] = driver.id;
+ return {...t, credits: t.credits - cost, roster: [...t.roster, driver], market: t.market.filter(d => d.id !== driver.id), lineup};
}
export function signDriver(team: Team, id: string): Team {
const d = team.market.find(d => d.id === id);
@@ -112,6 +119,26 @@ export function applyLineup(team: Team, setup: SandboxSetup): SandboxSetup {
...driverEffects(d!.stats), pitLap: setup.drivers[i]?.pitLap ?? 0}));
return {...setup, drivers: [...converted, ...setup.drivers.slice(2).filter(d => !converted.some(c => c.id === d.id))]};
}
+export function assignRecruitToGrid(team: Team, setup: SandboxSetup, slot: number, id: string): SandboxSetup {
+ const recruit = team.roster.find(d => d.id === id);
+ if (!recruit || !Number.isInteger(slot) || slot < 0 || slot >= setup.drivers.length) throw new Error("Choose a signed driver and an existing grid slot.");
+ const drivers = setup.drivers.map(d => ({...d}));
+ const profileId = `recruit:${recruit.id}`;
+ const other = drivers.findIndex(d => d.id === profileId);
+ if (other >= 0 && other !== slot) drivers[other] = {...drivers[slot], pitLap: drivers[other].pitLap};
+ drivers[slot] = {id: profileId, name: recruit.name, color: recruit.color, ...driverEffects(recruit.stats), pitLap: drivers[slot].pitLap};
+ return {...setup, drivers};
+}
+export function availableLineup(team: Team, setup: SandboxSetup): SandboxSetup {
+ let next = setup;
+ team.lineup.forEach((id,i) => {
+ if (id !== null && team.roster.some(d => d.id === id)) {
+ if(i>=next.drivers.length)next={...next,drivers:[...next.drivers,newSandboxDriver(i)]};
+ next = assignRecruitToGrid(team,next,i,id);
+ }
+ });
+ return next;
+}
export function readTeam(): {team: Team; warning: string} {
try {
@@ -130,6 +157,7 @@ export async function saveTeam(expected: Team, next: Team): Promise {
} else if (expected.revision !== 0) throw new Error("Saved team was removed in another tab. Load latest team first.");
const saved = parseTeam({...next, revision: expected.revision + 1});
localStorage.setItem(teamKey, JSON.stringify(saved));
+ announceTeam();
return saved;
};
return typeof navigator !== "undefined" && navigator.locks
@@ -141,6 +169,7 @@ export async function ensureTeam(candidate: Team): Promise {
if (raw !== null) return parseTeam(JSON.parse(raw));
const saved = parseTeam({...candidate, revision: 1});
localStorage.setItem(teamKey, JSON.stringify(saved));
+ announceTeam();
return saved;
};
return typeof navigator !== "undefined" && navigator.locks
@@ -150,6 +179,7 @@ export async function resetTeam(): Promise {
const write = () => {
const team = {...newTeam(), revision: 1};
localStorage.setItem(teamKey, JSON.stringify(team));
+ announceTeam();
return team;
};
return typeof navigator !== "undefined" && navigator.locks
diff --git a/frontend/src/replay-circuit.test.ts b/frontend/src/replay-circuit.test.ts
new file mode 100644
index 0000000..e1bd060
--- /dev/null
+++ b/frontend/src/replay-circuit.test.ts
@@ -0,0 +1,25 @@
+import {readFileSync} from "node:fs";
+import {describe,it,expect} from "vitest";
+import {circuitFromReplay} from "./replay-circuit";
+import {validateTrack} from "./custom-track";
+import {sandboxDefaults,validateSandbox} from "./sandbox";
+describe("existing replay circuits as fictional race venues",()=>{
+ for(const filename of ["monza-2024.json","session-11412.json"]){
+ it(`prepares ${filename} without mutating recorded data and finds a valid connected pit lane`,()=>{
+ const replay=JSON.parse(readFileSync(new URL(`../../data/${filename}`,import.meta.url),"utf8"));
+ const before=JSON.stringify(replay.track);
+ const track=circuitFromReplay(replay.track,`${replay.circuit} ${replay.year} · sandbox`);
+ expect(validateTrack(track)).toEqual([]);
+ expect(track.points.length).toBeGreaterThanOrEqual(6);expect(track.points.length).toBeLessThanOrEqual(120);
+ expect(track.name).toContain(replay.circuit);expect(track.id).not.toBe(replay.id);
+ expect(JSON.stringify(replay.track)).toBe(before);
+ const setup=sandboxDefaults(track);
+ expect(validateSandbox(track,setup)).toEqual([]);
+ });
+ }
+ it("rejects unavailable, nonfinite and self-crossing outlines",()=>{
+ expect(()=>circuitFromReplay([],"Missing")).toThrow(/outline/);
+ expect(()=>circuitFromReplay(Array.from({length:6},()=>[NaN,50]),"Invalid")).toThrow(/finite/);
+ expect(()=>circuitFromReplay([[0,0],[100,100],[0,100],[100,0],[120,0],[120,-20]],"Crossed")).toThrow(/valid sandbox/);
+ });
+});
diff --git a/frontend/src/replay-circuit.ts b/frontend/src/replay-circuit.ts
new file mode 100644
index 0000000..6609155
--- /dev/null
+++ b/frontend/src/replay-circuit.ts
@@ -0,0 +1,40 @@
+import {newTrack, validateTrack, type CustomTrack, type Point} from "./custom-track";
+const distance = (a: Point,b: Point) => Math.hypot(a[0]-b[0],a[1]-b[1]);
+function segmentDistance(p: Point,a: Point,b: Point) {
+ const dx=b[0]-a[0],dy=b[1]-a[1],length=dx*dx+dy*dy;
+ const t=length?Math.max(0,Math.min(1,((p[0]-a[0])*dx+(p[1]-a[1])*dy)/length)):0;
+ return Math.hypot(p[0]-a[0]-dx*t,p[1]-a[1]-dy*t);
+}
+function simplify(points: Point[], tolerance: number): Point[] {
+ if(points.length<=2)return points;
+ let farthest=0,index=0;
+ for(let i=1;ifarthest){farthest=d;index=i;}
+ }
+ return farthest>tolerance
+ ? [...simplify(points.slice(0,index+1),tolerance).slice(0,-1),...simplify(points.slice(index),tolerance)]
+ : [points[0],points.at(-1)!];
+}
+export function circuitFromReplay(outline: Point[], label: string): CustomTrack {
+ if(outline.length<6||outline.length>5000||outline.some(p=>!Array.isArray(p)||p.length!==2||p.some(n=>!Number.isFinite(n))))
+ throw new Error("This replay needs a finite circuit outline of 6–5,000 points before it can become a sandbox track.");
+ const xs=outline.map(p=>p[0]),ys=outline.map(p=>p[1]);
+ const minX=Math.min(...xs),minY=Math.min(...ys),width=Math.max(...xs)-minX,height=Math.max(...ys)-minY;
+ if(width<1||height<1)throw new Error("This replay's outline has no usable enclosed circuit.");
+ const scale=Math.min(680/width,400/height);
+ const normalized=outline.map(p=>[Math.round((p[0]-minX)*scale+(800-width*scale)/2),Math.round((p[1]-minY)*scale+(520-height*scale)/2)] as Point);
+ if(distance(normalized[0],normalized.at(-1)!)<1)normalized.pop();
+ let split=1;
+ for(let i=2;idistance(normalized[0],normalized[split]))split=i;
+ const template={...newTrack(),name:label.trim().slice(0,48)||"Replay circuit",cornerRadius:0};
+ for(const tolerance of [0,.5,1,2,3,4,6,8]){
+ const simplified=tolerance===0?normalized:[...simplify(normalized.slice(0,split+1),tolerance).slice(0,-1),...simplify([...normalized.slice(split),normalized[0]],tolerance).slice(0,-1)];
+ const points: Point[]=[];
+ for(const p of simplified)if(!points.length||distance(points.at(-1)!,p)>=8)points.push(p);
+ if(points.length>1&&distance(points.at(-1)!,points[0])<8)points.pop();
+ const track={...template,points,sectorEnds:[Math.floor(points.length/3),Math.floor(points.length*2/3)] as [number,number]};
+ if(points.length>=6 && points.length<=120 && !validateTrack(track).length)return track;
+ }
+ throw new Error("This outline cannot form a valid sandbox circuit without more editing. Copy/edit an outline or choose another replay.");
+}
diff --git a/frontend/src/sandbox.ts b/frontend/src/sandbox.ts
index 8a5bbe1..edf85b3 100644
--- a/frontend/src/sandbox.ts
+++ b/frontend/src/sandbox.ts
@@ -99,7 +99,7 @@ export function sandboxDefaults(track: CustomTrack): SandboxSetup {
Math.max(20, Math.min(500, p[1] + ((mid[1] - center[1]) / length) * 70)),
),
];
- return {
+ const setup: SandboxSetup = {
version: 1,
raceLaps: 10,
baseLapSeconds: 90,
@@ -108,6 +108,19 @@ export function sandboxDefaults(track: CustomTrack): SandboxSetup {
pitControls: [offset(a), offset(b)],
drivers: Array.from({ length: 3 }, (_, i) => newSandboxDriver(i)),
};
+ if(!validateSandbox(track,setup).length)return setup;
+ // Concave replay outlines may need a short lane on a different straight.
+ for(const span of [.08,.12,.16])for(let index=0;index<20;index++){
+ const entry=(19-index)/20,exit=Math.round(((entry+span)%1)*100)/100;
+ const a=pointOnRoute(main,entry),b=pointOnRoute(main,exit);
+ const dx=b[0]-a[0],dy=b[1]-a[1],length=Math.hypot(dx,dy)||1;
+ for(const side of [1,-1])for(const offset of [30,50,70]){
+ const shift=(p: Point): Point=>[Math.round(Math.max(20,Math.min(780,p[0]-dy/length*offset*side))),Math.round(Math.max(20,Math.min(500,p[1]+dx/length*offset*side)))];
+ const candidate={...setup,entry,exit,pitControls:[shift(a),shift(b)]};
+ if(!validateSandbox(track,candidate).length)return candidate;
+ }
+ }
+ return setup; // Leave validation/recovery available when no safe generated lane fits.
}
export function parseSandbox(raw: unknown): SandboxSetup {
if (!raw || typeof raw !== "object")
From 0f6e548d80b34ea7b6ab5fc6a66bdc7a896aba58 Mon Sep 17 00:00:00 2001
From: Nirmith Victor
Date: Sat, 21 Nov 2026 20:34:08 -0500
Subject: [PATCH 3/4] Release Pitwall v1.4.0 and align UI API and guide
versions
---
CONTRIBUTING.md | 2 +-
README.md | 4 ++--
backend/Pitwall.Api/Pitwall.Api.csproj | 2 +-
backend/Pitwall.Api/Program.cs | 2 +-
docs/DEMO.md | 2 +-
docs/USER-GUIDE.md | 2 +-
docs/V1.4.md | 31 ++++++++++++++++++++++++++
docs/flows.json | 2 +-
frontend/package-lock.json | 4 ++--
frontend/package.json | 2 +-
frontend/src/App.tsx | 3 ++-
scripts/check-docs.mjs | 4 ++++
12 files changed, 48 insertions(+), 12 deletions(-)
create mode 100644 docs/V1.4.md
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 49e6791..d7d172c 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -16,7 +16,7 @@ The [user guide](docs/USER-GUIDE.md) is the current behavior contract. Release n
- For a new flow, choose a new stable ID and explicit anchor, write its complete section and add its guide/source entry to `docs/flows.json`. Do not renumber existing IDs for cosmetic reorganization.
- Register new UI view components as flow sources. Classify truly reusable helpers under `sharedComponents` only when they do not represent their own user flow.
- For a removed flow, remove/update its index entry and explain the replacement in release notes. Do not leave a current guide pointing at a retired control.
-- When the product version changes, review the handbook and update `productVersion` / `lastReviewed` in the registry. Review dates reflect actual review, not automatic timestamps.
+- When the product version changes, update the frontend package/root lockfile versions and API project version together, review the handbook, and update `productVersion` / `lastReviewed` in the registry. The header and API status derive their versions from those build metadata fields. Review dates reflect actual review, not automatic timestamps.
- Run `node scripts/update-guide-index.mjs` to regenerate the index/version header, then `node scripts/check-docs.mjs`.
- Update the short demo, README, test guide and release notes only where the change affects them. Do not rewrite historical release behavior as if it always existed.
diff --git a/README.md b/README.md
index 0f1ba23..8df2de1 100644
--- a/README.md
+++ b/README.md
@@ -1,8 +1,8 @@
-# Pitwall v1.3 — Race Replay Lab
+# Pitwall v1.4 — Race Replay Lab
An independent motorsport replay prototype built with React, TypeScript, ASP.NET Core 10, and PostgreSQL 17. Start with recorded races; later, branch into player-controlled strategy simulations.
-[Complete user guide](docs/USER-GUIDE.md) · [Three-minute demo](docs/DEMO.md) · [v1.3 release notes](docs/V1.3.md) · [Testing](docs/TESTING.md) · [Roadmap](docs/FOLLOW-UP-PLAN.md)
+[Complete user guide](docs/USER-GUIDE.md) · [Three-minute demo](docs/DEMO.md) · [v1.4 release notes](docs/V1.4.md) · [Testing](docs/TESTING.md) · [Roadmap](docs/FOLLOW-UP-PLAN.md)
The [handbook](docs/USER-GUIDE.md) documents every current user flow: steps, defaults, saved data, exports, resets and recovery. For future upgrades, follow [CONTRIBUTING](CONTRIBUTING.md) and update the affected flows alongside the implementation. CI checks the registry, links, required sections, UI component coverage and product version.
diff --git a/backend/Pitwall.Api/Pitwall.Api.csproj b/backend/Pitwall.Api/Pitwall.Api.csproj
index d651170..d8cce0e 100644
--- a/backend/Pitwall.Api/Pitwall.Api.csproj
+++ b/backend/Pitwall.Api/Pitwall.Api.csproj
@@ -1,5 +1,5 @@
- net10.0 enable enable true 1.3.0
+ net10.0 enable enable true 1.4.0
diff --git a/backend/Pitwall.Api/Program.cs b/backend/Pitwall.Api/Program.cs
index 38f5c7a..d6c84df 100644
--- a/backend/Pitwall.Api/Program.cs
+++ b/backend/Pitwall.Api/Program.cs
@@ -45,7 +45,7 @@
app.MapGet("/health", async (RaceStore data, CancellationToken ct) =>
await data.ReadyAsync(ct) ? Results.Ok(new { status = "healthy", storage = data.Storage }) : Results.StatusCode(503));
-app.MapGet("/api/status", (RaceStore data) => new { storage = data.Storage, bookmarkScope = "shared-local-development", version = "1.3.0" });
+app.MapGet("/api/status", (RaceStore data) => new { storage = data.Storage, bookmarkScope = "shared-local-development", version = typeof(Program).Assembly.GetName().Version?.ToString(3) ?? "unknown" });
app.MapGet("/api/sessions", async (RaceCatalog catalog, RaceStore store, CancellationToken ct) => {
var cached = await store.CachedIdsAsync(ct);
return Results.Ok(new { catalog.Current.RefreshedAt, catalog.Refreshing, catalog.LastError, sessions = catalog.Current.Sessions.Select(s => new { s.Id, s.SessionKey, s.Title, s.Circuit, s.Country, s.CountryCode, s.Year, s.Date, s.Kind, cached = cached.Contains(s.Id) }) });
diff --git a/docs/DEMO.md b/docs/DEMO.md
index 053c6b1..702d3e8 100644
--- a/docs/DEMO.md
+++ b/docs/DEMO.md
@@ -8,7 +8,7 @@ For all controls, save/reset behavior, limits and recovery paths, use the [compl
From the repository root, run `node scripts/doctor.mjs`. If the frontend/API are built and PostgreSQL is running, use `node scripts/preview.mjs`. Otherwise follow the README's Docker or development setup first. `--snapshot` runs without PostgreSQL, with temporary bookmarks/imports.
-Open [Monza at 30 minutes](http://127.0.0.1:5080/?race=monza-2024&t=1800). The header reports v1.3 and the storage indicator shows the current mode.
+Open [Monza at 30 minutes](http://127.0.0.1:5080/?race=monza-2024&t=1800). The header reports v1.4.0 and the storage indicator shows the current mode.
## Replay and analysis
diff --git a/docs/USER-GUIDE.md b/docs/USER-GUIDE.md
index 4bf1650..7162cb4 100644
--- a/docs/USER-GUIDE.md
+++ b/docs/USER-GUIDE.md
@@ -1,6 +1,6 @@
# Pitwall user guide
-**Product version:** 1.3.0
+**Product version:** 1.4.0
**Last reviewed:** 2026-11-21
diff --git a/docs/V1.4.md b/docs/V1.4.md
new file mode 100644
index 0000000..3588b56
--- /dev/null
+++ b/docs/V1.4.md
@@ -0,0 +1,31 @@
+# v1.4.0 — Playable races, multiplayer and recruited drivers
+
+Release date: 2026-11-21. The [current handbook](USER-GUIDE.md) documents 86 flows across eight chapters. [v1.3 notes](V1.3.md) remain the record of the previous release.
+
+## Race sessions and live decisions
+
+The fictional sandbox runs 1–50 lap sessions with exact simulated finish times, final order and a frozen finishing clock. Select a driver, call a stop before the next eligible entry, cancel before entry, and schedule repeat visits. Setup changes restart the local race; live calls preserve it. A pit lane spanning start/finish uses a mapped crossing, rather than a surveyed timing line.
+
+## Private multiplayer rooms
+
+ASP.NET Core owns the shared simulation clock and validates decisions; SignalR sends snapshots to guests. Rooms support up to six driver seats and twelve guests including spectators, exclusive claims, lobby readiness, host controls, reconnect, driver/host handover and guest removal. Invitation URLs contain the room code; private guest credentials stay in tab session storage. [Multiplayer guide](guide/07-multiplayer.md).
+
+## Recruiting and custom builds
+
+A browser-local team starts with 12,000 fictional credits. Scout generated prospects, sign/release up to six roster drivers, create 210-point custom builds, and select or swap two race seats. Pace/consistency produce a steady synthetic pace offset; pit discipline changes service time. Fees, partial refunds, stat caps, storage failures and stale-tab writes are explicit. [Recruiting guide](guide/08-driver-recruitment.md).
+
+## Synced rosters and existing circuits
+
+Signings fill empty selected team seats and appear in an open sandbox. New unsaved grids use selected signed builds; stored grids and running races wait for explicit sync/selection. Per-slot selection can swap builds while keeping each slot's scheduled pit lap.
+
+**Race this circuit** fits/simplifies the current replay's approximate outline into an independent fictional venue. New pit lanes try validated connected routes; Monza and Interlagos are covered by geometry and browser checks. The historical replay retains its original clock/data. These are approximate venues with fictional sectors, pit geometry, base pace and distance.
+
+## Release validation and versioning
+
+The feature batch passed 78 Vitest checks and 57 Playwright scenarios, plus the authoritative C# room/permission checks and shared browser/server model fixture during room development. The maintained guide has structural/link/version checks in CI. See [TESTING](TESTING.md) for actual coverage and commands.
+
+The header derives its semantic version from the frontend package; `/api/status` derives it from the API assembly. CI's guide checker compares package, lockfile, API project and handbook metadata. The release uses an annotated `v1.4.0` Git tag; publishing a tag is separate from creating a hosted GitHub Release.
+
+## Storage and operating limits
+
+Historical caches/bookmarks use PostgreSQL when configured. Recruiting, custom definitions and local preferences remain browser-origin data. Multiplayer rooms remain in one API process's memory even with PostgreSQL: an API restart/redeployment ends rooms. Guest credentials do not provide account recovery. Public hosting, multi-instance room coordination, durable room resume, protected online economies, tyre physics, wages, seasons and vehicle-part upgrades remain future work.
diff --git a/docs/flows.json b/docs/flows.json
index 402ebdf..0a54a63 100644
--- a/docs/flows.json
+++ b/docs/flows.json
@@ -1,6 +1,6 @@
{
"schemaVersion": 1,
- "productVersion": "1.3.0",
+ "productVersion": "1.4.0",
"lastReviewed": "2026-11-21",
"chapters": [
{
diff --git a/frontend/package-lock.json b/frontend/package-lock.json
index e3bf5d6..0d7b9bd 100644
--- a/frontend/package-lock.json
+++ b/frontend/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "pitwall-web",
- "version": "1.3.0",
+ "version": "1.4.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "pitwall-web",
- "version": "1.3.0",
+ "version": "1.4.0",
"dependencies": {
"@microsoft/signalr": "^10.0.11",
"lucide-react": "^0.468.0",
diff --git a/frontend/package.json b/frontend/package.json
index 003749a..611bd60 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -1,7 +1,7 @@
{
"name": "pitwall-web",
"private": true,
- "version": "1.3.0",
+ "version": "1.4.0",
"type": "module",
"scripts": {
"dev": "vite --configLoader native --host 127.0.0.1",
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index ca4a00d..3335a5a 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -6,6 +6,7 @@ import {
useMemo,
useState,
} from "react";
+import {version as appVersion} from "../package.json";
import {
Activity,
ArrowLeft,
@@ -323,7 +324,7 @@ function App() {
pitwall╱
- RACE REPLAY LAB V1.3
+ RACE REPLAY LAB V{appVersion}
diff --git a/scripts/check-docs.mjs b/scripts/check-docs.mjs
index 4f7efb4..2f72bb1 100644
--- a/scripts/check-docs.mjs
+++ b/scripts/check-docs.mjs
@@ -21,6 +21,10 @@ function anchors(markdown){
return result;
}
const registry=JSON.parse(await text("docs/flows.json")),pkg=JSON.parse(await text("frontend/package.json"));
+const lock=JSON.parse(await text("frontend/package-lock.json"));
+const apiVersion=(await text("backend/Pitwall.Api/Pitwall.Api.csproj")).match(/
([^<]+)<\/Version>/)?.[1];
+if(lock.version!==pkg.version||lock.packages?.[""]?.version!==pkg.version)errors.push("Frontend package and lockfile versions differ.");
+if(apiVersion!==pkg.version)errors.push(`API version ${apiVersion??"missing"} does not match frontend ${pkg.version}.`);
if(registry.schemaVersion!==1)errors.push("Unsupported flow registry schemaVersion.");
if(registry.productVersion!==pkg.version)errors.push(`Guide version ${registry.productVersion} does not match frontend ${pkg.version}. Review the guide and update registry metadata.`);
if(!/^\d{4}-\d{2}-\d{2}$/.test(registry.lastReviewed)||!Number.isFinite(Date.parse(registry.lastReviewed+"T00:00:00Z")))errors.push("Use an actual ISO guide review date.");
From d7d9d57f100b501c1f6d7b589f51b6f7949dafca Mon Sep 17 00:00:00 2001
From: Nirmith Victor
Date: Sat, 21 Nov 2026 20:54:26 -0500
Subject: [PATCH 4/4] Add saved local three-race championships and resumable
rounds
---
README.md | 1 +
docs/DEMO.md | 2 +-
docs/FOLLOW-UP-PLAN.md | 2 +
docs/TESTING.md | 5 +-
docs/USER-GUIDE.md | 18 +++-
docs/flows.json | 108 +++++++++++++++++++
docs/guide/06-maintenance.md | 1 +
docs/guide/09-championship.md | 93 +++++++++++++++++
frontend/e2e/championship.spec.ts | 108 +++++++++++++++++++
frontend/src/App.tsx | 9 +-
frontend/src/LocalChampionship.tsx | 161 +++++++++++++++++++++++++++++
frontend/src/championship.test.ts | 70 +++++++++++++
frontend/src/championship.ts | 126 ++++++++++++++++++++++
13 files changed, 699 insertions(+), 5 deletions(-)
create mode 100644 docs/guide/09-championship.md
create mode 100644 frontend/e2e/championship.spec.ts
create mode 100644 frontend/src/LocalChampionship.tsx
create mode 100644 frontend/src/championship.test.ts
create mode 100644 frontend/src/championship.ts
diff --git a/README.md b/README.md
index 8df2de1..bfb1c80 100644
--- a/README.md
+++ b/README.md
@@ -28,6 +28,7 @@ The [handbook](docs/USER-GUIDE.md) documents every current user flow: steps, def
- Private multiplayer rooms with a C#-owned simulation clock, SignalR snapshots, guest driver claims/readiness, host controls, live pit calls, reconnect, spectator support, guest removal and driver/host handover. Rooms are temporary and use one API instance. See [the multiplayer guide](docs/guide/07-multiplayer.md).
- Fictional driver recruitment: generated stat-based prospects, a 12,000-credit budget, six-driver roster, custom 210-point builds, two swappable race seats, browser persistence and lineup application to local/new multiplayer races. See [recruiting flows](docs/guide/08-driver-recruitment.md).
- Live signed-roster availability in the sandbox, per-slot build selection and partial-lineup sync. **Race this circuit** starts a separate fictional race on the current replay's approximate outline with your selected signed drivers; generated pit lanes are validated before use.
+- A local three-race championship with a frozen signed lineup and four rivals, saved calendar/results, points/countback, team score and resumable in-race checkpoints. Entry is free; recruiting prizes/training and multiplayer championships remain future increments. See [championship flows](docs/guide/09-championship.md).
- On-demand tool bundles, recovery from tool download failures, indexed replay lookups, a read-only setup doctor, and a one-command local preview.
- Light/dark themes with a header toggle, system preference on first visit, and a browser-saved choice across races.
- Save, revisit, and delete replay moments. Bookmarks are isolated by race and survive API restarts in PostgreSQL.
diff --git a/docs/DEMO.md b/docs/DEMO.md
index 702d3e8..43c9bd2 100644
--- a/docs/DEMO.md
+++ b/docs/DEMO.md
@@ -28,7 +28,7 @@ The next session increment also lets you choose **Race distance (laps)**, select
## Engineering evidence
-- [Testing guide](TESTING.md): 78 frontend unit checks, nine Node checks, 57 browser scenarios, real API/database integration and dedicated storage/room concurrency checks.
+- [Testing guide](TESTING.md): 84 frontend unit checks, nine Node checks, 62 browser scenarios, real API/database integration and dedicated storage/room concurrency checks.
- [v1.3 architecture and limitations](V1.3.md): separate recorded/fictional state, independent enrichment, data quality and model assumptions.
- `node scripts/benchmark-replay.mjs`: reproducible lookup-only comparison against v1.2 with correctness assertions.
- GitHub Actions builds and tests the application and container; release branches publish an image. Hosting, accounts and multiplayer are later scope.
diff --git a/docs/FOLLOW-UP-PLAN.md b/docs/FOLLOW-UP-PLAN.md
index e03a301..94da922 100644
--- a/docs/FOLLOW-UP-PLAN.md
+++ b/docs/FOLLOW-UP-PLAN.md
@@ -53,6 +53,8 @@ Fictional recruiting now adds generated prospects/fees, a browser-local budget a
Roster/venue integration now fills empty team seats on signing, keeps signed choices current in an open sandbox, applies selected profiles to new unsaved grids and supports explicit partial sync/per-slot swaps without silently resetting active runs. **Race this circuit** prepares the open replay's approximate outline as a validated independent race venue, with a generated connected pit route and the selected signed drivers. Historical results remain separate; public hosting and a protected cross-device team economy are still later work.
+The next local-career increment implements a three-round championship using saved/custom and cached replay venues, two frozen signed builds plus four rivals, exact classified results, points/countback, team totals and saved race checkpoints. See [championship flows](guide/09-championship.md). Next: integrate carefully bounded prize credits, then capped driver training, then consider multiplayer championships. The current cup does not change recruiting credits.
+
## Branch and validation workflow
Use a focused feature branch for each milestone, run timing/camera unit tests and browser tests, and review into `develop`. Promote to `master` once the integration branch is ready. Container delivery continues through the existing GitHub Actions workflow.
diff --git a/docs/TESTING.md b/docs/TESTING.md
index 271d135..06ce5cd 100644
--- a/docs/TESTING.md
+++ b/docs/TESTING.md
@@ -6,7 +6,7 @@ Run `node scripts/check-docs.mjs` from the repository root. CI runs the same che
When changing a flow, update its chapter and `docs/flows.json`, then run `node scripts/update-guide-index.mjs` and the checker. Follow [CONTRIBUTING](../CONTRIBUTING.md). Checks catch structural drift; reviewing the steps against actual behavior remains necessary. Documentation-only changes need this check, without repeating unrelated application suites locally.
-## Playwright: 57 browser scenarios
+## Playwright: 62 browser scenarios
| Area | Coverage |
| --- | --- |
@@ -35,6 +35,7 @@ When changing a flow, update its chapter and `docs/flows.json`, then run `node s
| Multiplayer | Two independent guest sessions, readiness, synchronized clock/results, live calls, reload/reconnect, driver/host handover, invalid invitations, mobile leave, real-hub concurrent claim conflicts, token/ownership/host checks, forged-time rejection and guest removal |
| Fictional recruitment | Generated sign/release/scouting fees and persistence, custom point limits, saved seat swaps and applied performance, new multiplayer room copies, mobile/failed-write behavior, stale-tab protection, raw backup and confirmed corrupted-profile recovery |
| Roster/venue integration | Same-window/cross-tab signed-roster availability without resetting an active run, explicit partial sync and per-slot swaps, saved-grid preservation, replay-outline racing, valid pit geometry, new-room hosting and historical replay isolation |
+| Local championship | Complete three-venue season/results/standings, between-round reload, frozen recruiting budget, live checkpoint and pit-call restore, animation pause/close persistence, stale-tab locking/reload, mobile failed-write preservation and backed-up corrupted-save recovery |
| Sector map | Completed-reference alignment, saved layout preference, no invented coordinates during gaps, hidden markers before coverage or in estimate mode |
| Tool loading | Studio bundle stays deferred until opened; a failed download returns to a usable replay |
@@ -42,7 +43,7 @@ These scenarios run against the production frontend build in Chromium. Historica
## Other checks
-- 78 Vitest checks cover replay timing and indexed boundary/seek behavior, track interpolation, map/layout preferences, recorded sample lookup and sector alignment, trails, share links, named layouts, geometry/rounding/import validation, deterministic strategy math, held-out pace evaluation, sandbox route/service transitions, setup migration, finish timing/frame invariance, result ordering, cancellation/repeat visits and pit-lane finishes. Recruiting checks cover seeded stats/identities, custom constraints, budget/fees/refunds, roster limits, seat swapping, applied settings and storage/revision failures. A committed shared fixture checks browser/server parity for rounded geometry, pit traversal/service/rejoin and finite results.
+- 84 Vitest checks cover replay timing and indexed boundary/seek behavior, track interpolation, map/layout preferences, recorded sample lookup and sector alignment, trails, share links, named layouts, geometry/rounding/import validation, deterministic strategy math, held-out pace evaluation, sandbox route/service transitions, setup migration, finish timing/frame invariance, result ordering, cancellation/repeat visits and pit-lane finishes. Recruiting checks cover seeded stats/identities, custom constraints, budget/fees/refunds, roster limits, seat swapping, applied settings and storage/revision failures. A committed shared fixture checks browser/server parity for rounded geometry, pit traversal/service/rejoin and finite results.
- `Pitwall.RoomChecks` checks authoritative room physics, frame invariance, validation, concurrent seat claims, host/driver authorization, reconnect, handover, guest removal and departure. It also consumes `data/testing/room-model.json`; fixture changes need review, rather than automatic regeneration to make a failure pass.
- Nine Node tests cover catalog filtering, identifiers, location alignment/quality, measured-sector/pit normalization, local environment parsing, bounded ports and connection-string escaping.
- `Pitwall.StoreChecks` verifies enrichment preservation, downgrade protection, concurrent writes, safe bundle seeding and bookmarks against both in-memory storage and PostgreSQL. It creates uniquely named test rows and removes only those rows.
diff --git a/docs/USER-GUIDE.md b/docs/USER-GUIDE.md
index 7162cb4..766a307 100644
--- a/docs/USER-GUIDE.md
+++ b/docs/USER-GUIDE.md
@@ -16,6 +16,7 @@ This is the current handbook for what each flow does, how to use it, what is sav
6. [Understand storage, maintenance and guide updates](guide/06-maintenance.md).
7. [Host, join and hand over a private multiplayer race](guide/07-multiplayer.md).
8. [Recruit fictional drivers, create builds and swap your lineup](guide/08-driver-recruitment.md).
+9. [Run a saved local three-race championship](guide/09-championship.md).
Each flow has a stable ID, a **What**, **How**, **Result and storage**, and **Recovery and limits** section. Use these IDs in issues and pull requests instead of relying on a screenshot or an old chat.
@@ -32,6 +33,7 @@ Each flow has a stable ID, a **What**, **How**, **Result and storage**, and **Re
| Can friends control drivers in the same race? | Multiplayer rooms | One server-owned fictional race with guest driver ownership |
| Can I sign and customize fictional drivers? | Driver recruitment | Browser-local roster/budget with two selected race builds |
| Can my signed drivers race on an existing track? | Race this circuit | Separate fictional race using the current replay's approximate outline |
+| Can my team compete over several races? | Local championship | Three saved fictional rounds, points/countback and resumable race checkpoints |
```mermaid
flowchart LR
@@ -66,6 +68,7 @@ Saving to PostgreSQL, saving in your browser and downloading a file are differen
| Share link | Yes, if its server/session is available | Encodes replay settings, not private saves or custom workspaces |
| Multiplayer room | Reconnect while that API process retains it | Guest token in tab session storage; rooms are in server memory even with PostgreSQL |
| Recruiting team | Yes, same browser origin | Autosaved market, roster, lineup and credits; applying to a grid is separate |
+| Local championship | Yes, same browser origin | One frozen calendar/lineup, results and latest saved race checkpoint; no importer |
Closing a studio or scenario without saving can lose its draft. Clearing browser data, changing browser/profile, or using another hostname/port can change which browser saves you see. A normal database-backed API restart does not erase server caches/bookmarks.
@@ -87,7 +90,7 @@ Closing a studio or scenario without saving can lose its draft. Clearing browser
-86 documented flows. Each ID links directly to its instructions.
+94 documented flows. Each ID links directly to its instructions.
### Start Pitwall and choose a race
@@ -214,6 +217,19 @@ Closing a studio or scenario without saving can lose its draft. Clearing browser
| [TEAM-07](guide/08-driver-recruitment.md#team-07) | Recover from storage failures or another tab's changes |
| [TEAM-08](guide/08-driver-recruitment.md#team-08) | Export a record or explicitly start fresh |
| [TEAM-09](guide/08-driver-recruitment.md#team-09) | Sync signed drivers directly into a sandbox |
+
+### Local three-race championships
+
+| Flow | What you can do |
+| --- | --- |
+| [CUP-01](guide/09-championship.md#cup-01) | Enter a championship with your signed lineup |
+| [CUP-02](guide/09-championship.md#cup-02) | Choose the three-round calendar |
+| [CUP-03](guide/09-championship.md#cup-03) | Start, run and make team pit decisions |
+| [CUP-04](guide/09-championship.md#cup-04) | Read results and championship standings |
+| [CUP-05](guide/09-championship.md#cup-05) | Save and resume a race or between-round progress |
+| [CUP-06](guide/09-championship.md#cup-06) | Recover from failed saves or another editing tab |
+| [CUP-07](guide/09-championship.md#cup-07) | Export a cup or replace it with a new championship |
+| [CUP-08](guide/09-championship.md#cup-08) | Recover an unreadable saved championship |
## How this stays current
diff --git a/docs/flows.json b/docs/flows.json
index 0a54a63..9fe49ab 100644
--- a/docs/flows.json
+++ b/docs/flows.json
@@ -34,6 +34,10 @@
{
"path": "docs/guide/08-driver-recruitment.md",
"title": "Fictional driver recruitment and builds"
+ },
+ {
+ "path": "docs/guide/09-championship.md",
+ "title": "Local three-race championships"
}
],
"sharedComponents": [
@@ -1050,6 +1054,110 @@
"frontend/src/replay-circuit.test.ts",
"frontend/e2e/roster-tracks.spec.ts"
]
+ },
+ {
+ "id": "CUP-01",
+ "title": "Enter a championship with your signed lineup",
+ "guide": "docs/guide/09-championship.md",
+ "anchor": "cup-01",
+ "sources": [
+ "frontend/src/LocalChampionship.tsx",
+ "frontend/src/championship.ts",
+ "frontend/src/championship.test.ts",
+ "frontend/e2e/championship.spec.ts",
+ "frontend/src/App.tsx"
+ ]
+ },
+ {
+ "id": "CUP-02",
+ "title": "Choose the three-round calendar",
+ "guide": "docs/guide/09-championship.md",
+ "anchor": "cup-02",
+ "sources": [
+ "frontend/src/LocalChampionship.tsx",
+ "frontend/src/championship.ts",
+ "frontend/src/championship.test.ts",
+ "frontend/e2e/championship.spec.ts",
+ "frontend/src/App.tsx"
+ ]
+ },
+ {
+ "id": "CUP-03",
+ "title": "Start, run and make team pit decisions",
+ "guide": "docs/guide/09-championship.md",
+ "anchor": "cup-03",
+ "sources": [
+ "frontend/src/LocalChampionship.tsx",
+ "frontend/src/championship.ts",
+ "frontend/src/championship.test.ts",
+ "frontend/e2e/championship.spec.ts",
+ "frontend/src/App.tsx"
+ ]
+ },
+ {
+ "id": "CUP-04",
+ "title": "Read results and championship standings",
+ "guide": "docs/guide/09-championship.md",
+ "anchor": "cup-04",
+ "sources": [
+ "frontend/src/LocalChampionship.tsx",
+ "frontend/src/championship.ts",
+ "frontend/src/championship.test.ts",
+ "frontend/e2e/championship.spec.ts",
+ "frontend/src/App.tsx"
+ ]
+ },
+ {
+ "id": "CUP-05",
+ "title": "Save and resume a race or between-round progress",
+ "guide": "docs/guide/09-championship.md",
+ "anchor": "cup-05",
+ "sources": [
+ "frontend/src/LocalChampionship.tsx",
+ "frontend/src/championship.ts",
+ "frontend/src/championship.test.ts",
+ "frontend/e2e/championship.spec.ts",
+ "frontend/src/App.tsx"
+ ]
+ },
+ {
+ "id": "CUP-06",
+ "title": "Recover from failed saves or another editing tab",
+ "guide": "docs/guide/09-championship.md",
+ "anchor": "cup-06",
+ "sources": [
+ "frontend/src/LocalChampionship.tsx",
+ "frontend/src/championship.ts",
+ "frontend/src/championship.test.ts",
+ "frontend/e2e/championship.spec.ts",
+ "frontend/src/App.tsx"
+ ]
+ },
+ {
+ "id": "CUP-07",
+ "title": "Export a cup or replace it with a new championship",
+ "guide": "docs/guide/09-championship.md",
+ "anchor": "cup-07",
+ "sources": [
+ "frontend/src/LocalChampionship.tsx",
+ "frontend/src/championship.ts",
+ "frontend/src/championship.test.ts",
+ "frontend/e2e/championship.spec.ts",
+ "frontend/src/App.tsx"
+ ]
+ },
+ {
+ "id": "CUP-08",
+ "title": "Recover an unreadable saved championship",
+ "guide": "docs/guide/09-championship.md",
+ "anchor": "cup-08",
+ "sources": [
+ "frontend/src/LocalChampionship.tsx",
+ "frontend/src/championship.ts",
+ "frontend/src/championship.test.ts",
+ "frontend/e2e/championship.spec.ts",
+ "frontend/src/App.tsx"
+ ]
}
]
}
diff --git a/docs/guide/06-maintenance.md b/docs/guide/06-maintenance.md
index a4802ae..1a7d83d 100644
--- a/docs/guide/06-maintenance.md
+++ b/docs/guide/06-maintenance.md
@@ -17,6 +17,7 @@
| Theme/default map/named map layouts | Browser only | Browser only | Hostname + port + scheme + browser/profile |
| Saved circuits/sandbox setups/strategy scenarios | Browser only | Browser only | Same origin isolation |
| Recruiting roster/market/lineup/credits | Browser only, autosaved on successful transactions | Browser only | Same origin; separate from server rooms and guest ownership |
+| Local championship/results/race checkpoint | Browser only | Browser only | One cup per origin; independent of recruiting credits and server rooms |
| Unsaved drafts, tool selections, simulation clock | Current page/tool session | Current page/tool session | Not automatically restored |
| Multiplayer rooms/shared race clock | API process memory; lost on restart | API process memory; lost on restart | Guest credential in tab session storage, no token in invitation |
| Exported files | Download location you choose | Download location you choose | Not automatically re-imported |
diff --git a/docs/guide/09-championship.md b/docs/guide/09-championship.md
new file mode 100644
index 0000000..fa95501
--- /dev/null
+++ b/docs/guide/09-championship.md
@@ -0,0 +1,93 @@
+# Local three-race championships
+
+[Guide home](../USER-GUIDE.md) · [Recruiting](08-driver-recruitment.md) · [Race sandbox](05-race-sandbox.md)
+
+This cup is a local fictional career loop. It uses the sandbox pace/pit model, keeps a frozen six-driver field and saves one championship per browser origin. Prize credits, driver training, seasons and multiplayer championships are later increments.
+
+
+## CUP-01 — Enter a championship with your signed lineup
+
+**What:** Create a three-round cup with your two selected signed drivers and four rivals.
+
+**How:** Sign/select both race seats in **Driver recruitment**, then open **Local championship** in the replay toolbar. Set **Championship name**, **Laps per round** (1–50) and **Base lap seconds** (30–300). Entry is free. Defaults are **Midnight Cup**, three laps and 60 seconds.
+
+**Result and storage:** Creation freezes driver identities, names, colours, pace, service and scheduled pit assumptions for all three rounds. The four rivals have fixed, differing pace; one has a scheduled visit. Later recruiting purchases, releases, seat changes or resets do not modify an existing cup. The recruiting budget remains separate and unchanged.
+
+**Recovery and limits:** Missing/incomplete signed seats reject entry without creating a save. There are no prize credits, training, entry fees, wages or income in this first increment. It is a local game, not a server-verified competitive economy. Close the panel to manage recruiting, then reopen and create the cup.
+
+
+## CUP-02 — Choose the three-round calendar
+
+**What:** Combine existing replay venues and saved custom circuits.
+
+**How:** Set **Round 1 venue**, **Round 2 venue** and **Round 3 venue** to three different entries, then **Create three-race championship**. Options include the starter circuit, saved custom circuits, the current replay and other cached replay sessions. Import additional replays through **Browse races** before opening the cup panel.
+
+**Result and storage:** Each chosen definition, connected pit route and race setup is validated and stored with the cup. Replay outlines are fitted as independent approximate venues. The same six drivers, lap count and base pace apply throughout. Later edits/deletions of saved custom circuits do not alter the frozen cup copies. Different cached sessions are distinct entries even if their circuit name repeats.
+
+**Recovery and limits:** Duplicate entries disable creation. Missing/unsafe replay outlines, failed cache loads or invalid pit geometry reject creation and preserve the previous save. A failed catalog lookup leaves current/saved options available but may leave too few entries; restore the API or save additional valid custom circuits. Reopen the panel to refresh the available list. No provider import is silently started by choosing a venue.
+
+
+## CUP-03 — Start, run and make team pit decisions
+
+**What:** Race one round with control over your two team drivers.
+
+**How:** Choose **Begin round [n]**, then **Run championship race** / **Pause championship race**. Set **Race speed** to 1×/5×/10×/25× or **Advance championship lap** by one base-lap duration. Choose **Your driver**, then **Box championship this lap** / **Box championship next lap** or **Cancel championship pit call** before entry.
+
+**Result and storage:** The cup uses the same deterministic movement, service and exact finish model as the local sandbox. Only your two frozen drivers accept player calls; rivals retain their planned settings. Calls preserve positions/clock, and pit entry commits the visit. Finished drivers freeze until every car finishes; every car covers the full distance.
+
+**Recovery and limits:** Advancing a base-lap duration does not guarantee every car completes a lap. Pit/service/finished phases lock calls, and no entry remains after the final eligible entry. Setup/geometry cannot be edited mid-cup. Missing physical tyre/traffic/fuel dynamics remain the sandbox's limits; a pit route spanning the finish uses its mapped crossing.
+
+
+## CUP-04 — Read results and championship standings
+
+**What:** Accumulate points and countback across three consecutive rounds.
+
+**How:** Finish the round and read **Round complete**, its classified finish times and awarded points. **Driver standings** and **Team points** update. Use **Begin round [n+1]** after the result saves. After the third result, **Championship complete** replaces further round entry.
+
+**Result and storage:** Places 1–6 earn 25/18/15/12/10/8 points. Your team score sums its two driver scores. Equal points use wins, then second-place counts, thirds and later places, then initial grid order. A round records automatically once, in calendar order, only after all six finish. A saved final result cannot be awarded again by reloading.
+
+**Recovery and limits:** There is no skip, replay-for-more-points or result editing UI. Exact race-time ties retain grid order. Standings are driver standings plus your team total, not a multi-constructor championship. Results do not pay recruiting credits yet.
+
+
+## CUP-05 — Save and resume a race or between-round progress
+
+**What:** Keep completed results, standings and an active race checkpoint between visits.
+
+**How:** Use **Save championship checkpoint**, pause the race or close the panel normally. Autosave also checks for changed progress about every two seconds and saves completed-round results immediately. Wait for a **Saved** message before refreshing. Reopen **Local championship** to load the stored cup; use **Load saved championship** to explicitly replace the in-memory view with the saved record.
+
+**Result and storage:** The versioned JSON record contains the frozen calendar/field, classified results and any current clock, positions, pit decisions, visits and finish states. A restored race always opens paused. Normal panel close waits for an in-flight save and saves the latest progress before closing. The historical replay remains at its prior paused time.
+
+**Recovery and limits:** A hard reload, browser crash or closing the tab can lose the last unsaved seconds; there is no unload-time guarantee. Storage is origin/profile local, including port and hostname isolation. One saved cup exists per origin. Server/database restarts do not erase the browser record, but clearing browser storage can. There is no cross-device/account sync or championship multiplayer yet.
+
+
+## CUP-06 — Recover from failed saves or another editing tab
+
+**What:** Keep the previous checkpoint intact when saving cannot safely complete.
+
+**How:** Read **Save failed** errors. Restore browser storage access and retry **Save championship checkpoint**. If another tab changes the cup, export unsaved progress if needed, then **Load saved championship**; this replaces the current in-memory progress and resumes paused.
+
+**Result and storage:** A failed write pauses the race, preserves the previous stored record and leaves the latest in-memory state available. A revision/identity check rejects stale writes. Browsers supporting Web Locks serialize writes, while storage events lock stale screens. Begin/run/advance/pit controls remain locked until the failure/conflict is resolved. **Close without saving** explicitly exits despite a failed save.
+
+**Recovery and limits:** Use only one active editing tab. Without Web Locks, revision checks are best effort. Loading the stored cup discards unsaved progress in that view; exported JSON is an inspection record, not a supported import path. Never clear all browser data to repair one cup.
+
+
+## CUP-07 — Export a cup or replace it with a new championship
+
+**What:** Keep an inspection record and choose when to replace the saved cup.
+
+**How:** **Export championship JSON** downloads the displayed snapshot, including unsaved progress. **Create another championship → Choose new championship calendar** opens a replacement form. **Replace saved championship** writes the new cup only after its lineup/calendar validates. **Keep this cup** / **Keep current championship** cancels the replacement flow.
+
+**Result and storage:** Replacement changes only the championship key. Recruiting, custom circuit saves, ordinary sandbox setups and multiplayer rooms remain independent. The old cup stays stored until a valid replacement is successfully written. A new cup freezes the then-current selected signed lineup.
+
+**Recovery and limits:** There is no archive list, JSON importer or replacement undo. Export before replacing if you want an inspection copy of the old season. Leaving the replacement form without creating a new cup retains the old cup; unsaved old-race progress still needs a checkpoint before a hard refresh.
+
+
+## CUP-08 — Recover an unreadable saved championship
+
+**What:** Preserve malformed or unsupported saved data until you explicitly discard it.
+
+**How:** When a save cannot be read, use **Back up unreadable championship** first. **Discard unreadable championship → Confirm discard championship** removes that record, then allows creating a fresh cup.
+
+**Result and storage:** The backup wraps the original raw saved string. Reads and failed creation attempts do not overwrite it. Discard checks that the saved string has not changed since it was shown, so a newer save from another tab is not silently removed.
+
+**Recovery and limits:** Discard has no undo/import UI. If storage itself is unavailable, restore access before retrying; a backup cannot be read from blocked storage. The operation removes only the championship record, not signed drivers or custom circuits.
diff --git a/frontend/e2e/championship.spec.ts b/frontend/e2e/championship.spec.ts
new file mode 100644
index 0000000..ce22ebb
--- /dev/null
+++ b/frontend/e2e/championship.spec.ts
@@ -0,0 +1,108 @@
+import {test,expect,type Page} from "@playwright/test";
+import {createDriver,newTeam,teamKey} from "../src/recruitment";
+import {championshipKey} from "../src/championship";
+async function enter(page:Page){
+ const team={...createDriver(createDriver(newTeam(42),{id:"cup-one",name:"Cup One",color:"#64d2b6",origin:"custom",stats:{pace:70,consistency:70,pitDiscipline:70}}),{id:"cup-two",name:"Cup Two",color:"#ff665d",origin:"custom",stats:{pace:60,consistency:60,pitDiscipline:60}}),revision:1};
+ await page.addInitScript(({key,team})=>{if(!localStorage.getItem(key))localStorage.setItem(key,JSON.stringify(team));},{key:teamKey,team});
+ await page.goto("/?race=monza-2024&t=120");
+ await page.getByRole("button",{name:"Local championship",exact:true}).click();
+ return page.getByRole("dialog",{name:"Local championship",exact:true});
+}
+async function create(page:Page,laps=1){
+ const panel=await enter(page);
+ await panel.getByLabel("Championship laps",{exact:true}).fill(String(laps));
+ await panel.getByLabel("Championship base lap seconds",{exact:true}).fill("30");
+ await panel.getByLabel("Round 1 venue",{exact:true}).selectOption("replay:monza-2024");
+ await panel.getByLabel("Round 2 venue",{exact:true}).selectOption("replay:session-11412");
+ await panel.getByLabel("Round 3 venue",{exact:true}).selectOption("starter");
+ await panel.getByRole("button",{name:"Create three-race championship",exact:true}).click();
+ await expect(panel.getByTestId("cup-progress")).toHaveText("0/3 rounds complete");
+ return panel;
+}
+test("completes a three-venue championship, saves standings and resumes between rounds",async({page})=>{
+ const panel=await create(page);
+ const initialBudget=await page.evaluate(key=>JSON.parse(localStorage.getItem(key)!).credits,teamKey);
+ for(let round=1;round<=3;round++){
+ await panel.getByRole("button",{name:`Begin round ${round}`,exact:true}).click();
+ await panel.getByRole("button",{name:"Advance championship lap",exact:true}).click();
+ await panel.getByRole("button",{name:"Advance championship lap",exact:true}).click();
+ await expect(panel.getByTestId("cup-progress")).toHaveText(`${round}/3 rounds complete`);
+ await expect(panel.getByRole("status")).toContainText(`Saved ${round}/3 results`);
+ const state=await page.evaluate(key=>JSON.parse(localStorage.getItem(key)!),championshipKey);
+ expect(state.results).toHaveLength(round);expect(state.session).toBeNull();
+ if(round===1){
+ await page.reload();await page.getByRole("button",{name:"Local championship",exact:true}).click();
+ await expect(panel.getByTestId("cup-progress")).toHaveText("1/3 rounds complete");
+ }
+ }
+ await expect(panel.getByRole("heading",{name:/Championship complete/})).toBeVisible();
+ await expect(panel.getByRole("button",{name:/Begin round/})).toHaveCount(0);
+ const before=await panel.getByRole("region",{name:"Championship standings",exact:true}).innerText();
+ await page.reload();await page.getByRole("button",{name:"Local championship",exact:true}).click();
+ await expect(panel.getByRole("region",{name:"Championship standings",exact:true})).toHaveText(before,{useInnerText:true});
+ expect(await page.evaluate(key=>JSON.parse(localStorage.getItem(key)!).credits,teamKey)).toBe(initialBudget);
+ await panel.getByRole("button",{name:"Close Local championship",exact:true}).click();
+ await expect(page.getByTestId("elapsed-time")).toContainText("00:02:00");
+});
+
+test("another tab's championship change locks stale controls until the saved checkpoint is loaded",async({page,context})=>{
+ const panel=await create(page);
+ const other=await context.newPage();
+ try{
+ await other.goto("/?race=monza-2024");await other.getByRole("button",{name:"Local championship",exact:true}).click();
+ const viewer=other.getByRole("dialog",{name:"Local championship",exact:true});
+ await expect(viewer.getByTestId("cup-progress")).toHaveText("0/3 rounds complete");
+ await panel.getByRole("button",{name:"Begin round 1",exact:true}).click();
+ await expect(viewer.getByRole("alert")).toContainText("another tab");
+ await expect(viewer.getByRole("button",{name:"Begin round 1",exact:true})).toBeDisabled();
+ await viewer.getByRole("button",{name:"Load saved championship",exact:true}).click();
+ await expect(viewer.getByRole("button",{name:"Run championship race",exact:true})).toBeEnabled();
+ await expect(viewer.getByTestId("cup-clock")).toHaveText("00:00:00");
+ }finally{await other.close();}
+});
+test("restores a saved live checkpoint and pit decision paused, and persists animation on close",async({page})=>{
+ const panel=await create(page,4);
+ await panel.getByRole("button",{name:"Begin round 1",exact:true}).click();
+ await panel.getByRole("button",{name:"Advance championship lap",exact:true}).click();
+ await expect(panel.getByTestId("cup-clock")).toHaveText("00:00:30");
+ await panel.getByRole("button",{name:"Box championship this lap",exact:true}).click();
+ await panel.getByRole("button",{name:"Save championship checkpoint",exact:true}).click();
+ await expect(panel.getByRole("status")).toContainText("checkpoint 00:00:30");
+ await page.reload();await page.getByRole("button",{name:"Local championship",exact:true}).click();
+ await expect(panel.getByTestId("cup-clock")).toHaveText("00:00:30");
+ await expect(panel.getByText("Your driver's pit entry is queued on lap 2.",{exact:true})).toBeVisible();
+ await panel.getByRole("button",{name:"Run championship race",exact:true}).click();
+ await expect(panel.getByTestId("cup-clock")).not.toHaveText("00:00:30");
+ await panel.getByRole("button",{name:"Pause championship race",exact:true}).click();
+ const clock=await panel.getByTestId("cup-clock").innerText();
+ await panel.getByRole("button",{name:"Close Local championship",exact:true}).click();
+ await page.getByRole("button",{name:"Local championship",exact:true}).click();
+ await expect(panel.getByTestId("cup-clock")).toHaveText(clock);
+ await expect(panel.getByRole("button",{name:"Run championship race",exact:true})).toBeVisible();
+});
+test("failed checkpoint writes preserve the previous save and the championship fits mobile",async({page})=>{
+ await page.setViewportSize({width:390,height:844});await page.emulateMedia({colorScheme:"light"});
+ const panel=await create(page);
+ const before=await page.evaluate(key=>localStorage.getItem(key),championshipKey);
+ await page.evaluate(()=>{Storage.prototype.setItem=()=>{throw new Error("Storage denied");};});
+ await panel.getByRole("button",{name:"Begin round 1",exact:true}).click();
+ await expect(panel.getByRole("alert")).toContainText("Storage denied");
+ expect(await page.evaluate(key=>localStorage.getItem(key),championshipKey)).toBe(before);
+ await expect(panel.getByRole("button",{name:"Run championship race",exact:true})).toBeDisabled();
+ expect(await panel.evaluate(e=>e.scrollWidth<=e.clientWidth)).toBe(true);
+});
+test("unreadable championship data is preserved until explicitly backed up and discarded",async({page})=>{
+ const raw="{bad-cup-save";
+ await page.addInitScript(({key,raw})=>localStorage.setItem(key,raw),{key:championshipKey,raw});
+ const panel=await enter(page);
+ await expect(panel.getByRole("alert")).toContainText("kept intact");
+ expect(await page.evaluate(key=>localStorage.getItem(key),championshipKey)).toBe(raw);
+ const download=page.waitForEvent("download");
+ await panel.getByRole("button",{name:"Back up unreadable championship",exact:true}).click();
+ const stream=await(await download).createReadStream(),chunks=[];for await(const chunk of stream!)chunks.push(chunk);
+ expect(JSON.parse(Buffer.concat(chunks).toString()).raw).toBe(raw);
+ await panel.getByRole("button",{name:"Discard unreadable championship",exact:true}).click();
+ await panel.getByRole("button",{name:"Confirm discard championship",exact:true}).click();
+ await expect(panel.getByRole("alert")).toHaveCount(0);
+ expect(await page.evaluate(key=>localStorage.getItem(key),championshipKey)).toBeNull();
+});
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index 3335a5a..de9cd3b 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -50,6 +50,7 @@ const RaceAnalysis = lazy(() => import("./RaceAnalysis"));
const PaceBacktest = lazy(() => import("./PaceBacktest"));
const MultiplayerRooms = lazy(() => import("./MultiplayerRooms"));
const DriverRecruitment = lazy(() => import("./DriverRecruitment"));
+const LocalChampionship = lazy(() => import("./LocalChampionship"));
import "./lab.css";
import { momentLink, readMoment } from "./replay-link";
import { ensureTiming } from "./import-job";
@@ -95,7 +96,8 @@ function App() {
const [showBacktest, setShowBacktest] = useState(false);
const [showRooms, setShowRooms] = useState(() => new URLSearchParams(location.search).has("room"));
const [showRecruitment, setShowRecruitment] = useState(false);
- const activeTool = showRecruitment ? "recruitment" : showRooms ? "rooms" : showLibrary
+ const [showChampionship, setShowChampionship] = useState(false);
+ const activeTool = showChampionship ? "championship" : showRecruitment ? "recruitment" : showRooms ? "rooms" : showLibrary
? "library"
: shareLink
? "share"
@@ -109,6 +111,7 @@ function App() {
? "backtest"
: "none";
const closeTools = () => {
+ setShowChampionship(false);
setShowRecruitment(false);
setShowRooms(false);
setShowLibrary(false);
@@ -199,6 +202,7 @@ function App() {
showBacktest ||
showRooms ||
showRecruitment ||
+ showChampionship ||
document.querySelector("dialog[open]")
)
return;
@@ -229,6 +233,7 @@ function App() {
showBacktest,
showRooms,
showRecruitment,
+ showChampionship,
]);
useEffect(() => {
if (!notice) return;
@@ -426,6 +431,7 @@ function App() {
REPLAY TOOLS
+
{setPlaying(false);setShowChampionship(true);}}>Local championship
{setPlaying(false);setRaceOnReplay(true);setShowTrackEditor(true);}}>Race this circuit
{setPlaying(false);setShowRecruitment(true);}}>Driver recruitment
{setPlaying(false);setShowRooms(true);}}>Multiplayer rooms
@@ -999,6 +1005,7 @@ function App() {
)}
{showRooms &&
setShowRooms(false)} />}
{showRecruitment && setShowRecruitment(false)} />}
+ {showChampionship && setShowChampionship(false)} />}
{showAnalysis && (
void}) {
+ const [loaded]=useState(readChampionship);
+ const [recoveryRaw,setRecoveryRaw]=useState(loaded.error?loaded.raw:null);
+ const [champ,setChamp]=useState(loaded.championship);
+ const current=useRef(champ);
+ const saved=useRef(champ?{id:champ.id,revision:champ.revision}:null);
+ const saving=useRef(false),runningRef=useRef(false),unsaved=useRef(false);
+ const saveWaiters=useRef<(()=>void)[]>([]);
+ const [busy,setBusy]=useState(false),[running,setRunning]=useState(false),[dirty,setDirty]=useState(false);
+ const [error,setError]=useState(loaded.error),[writeError,setWriteError]=useState("");
+ const [conflict,setConflict]=useState(false),[message,setMessage]=useState(champ?"Saved championship loaded. Any saved race resumes paused.":"");
+ const [creating,setCreating]=useState(!champ),[confirmReplace,setConfirmReplace]=useState(false),[confirmDiscard,setConfirmDiscard]=useState(false);
+ const [name,setName]=useState("Midnight Cup"),[laps,setLaps]=useState(3),[base,setBase]=useState(60),[speed,setSpeed]=useState(10);
+ const [selected,setSelected]=useState<[string,string,string]>(["", "", ""]);
+ const [catalog,setCatalog]=useState(null),[catalogError,setCatalogError]=useState("");
+ const [starter]=useState(newTrack),[customs]=useState(readTracks);
+ const [controlled,setControlled]=useState(champ?.ownDriverIds[0]??"");
+ const options=useMemo(()=>{
+ const list=[{id:"starter",label:"Midnight circuit",track:starter as CustomTrack|null,raceId:null as string|null},
+ ...customs.map(t=>({id:`custom:${t.id}`,label:t.name,track:t as CustomTrack|null,raceId:null as string|null})),
+ {id:`replay:${race.id}`,label:`${race.circuit} ${race.year}`,track:null as CustomTrack|null,raceId:race.id},
+ ...(catalog?.sessions.filter(s=>s.cached&&s.id!==race.id).map(s=>({id:`replay:${s.id}`,label:`${s.circuit} ${s.year}`,track:null as CustomTrack|null,raceId:s.id}))??[])];
+ return list;
+ },[starter,customs,race,catalog]);
+ useEffect(()=>{
+ const controller=new AbortController();
+ void request("/api/sessions",{signal:controller.signal}).then(setCatalog).catch(e=>{if(!controller.signal.aborted)setCatalogError(e.message);});
+ return ()=>controller.abort();
+ },[]);
+ useEffect(()=>{setSelected(old=>{
+ const next=[...old] as [string,string,string];
+ for(let i=0;i<3;i++)if(!next[i])next[i]=options.find(v=>!next.includes(v.id))?.id??"";
+ return next;
+ });},[options]);
+ const round=champ?.session?.round;
+ const venue=round!==undefined?champ?.venues[round]:null;
+ const geometry=useMemo(()=>venue?sandboxGeometry(venue.track,venue.setup):null,[venue]);
+ function replace(next:Championship|null) {current.current=next;setChamp(next);unsaved.current=true;setDirty(true);}
+ function stop() {runningRef.current=false;setRunning(false);}
+ async function persist():Promise {
+ const snapshot=current.current;
+ if(!snapshot)return true;
+ if(saving.current)return false;
+ saving.current=true;setBusy(true);
+ try {
+ const next=await saveChampionship(saved.current,snapshot);
+ saved.current={id:next.id,revision:next.revision};
+ const unchanged=current.current===snapshot;
+ if(current.current?.id===snapshot.id){current.current={...current.current,revision:next.revision};setChamp(current.current);}
+ unsaved.current=!unchanged;setDirty(!unchanged);setWriteError("");setMessage(`Saved ${next.results.length}/3 results${next.session?` and checkpoint ${formatClock(next.session.elapsed)}`:""}.`);
+ return true;
+ }catch(e){stop();setWriteError((e as Error).message);return false;}
+ finally{saving.current=false;setBusy(false);saveWaiters.current.splice(0).forEach(resolve=>resolve());}
+ }
+ useEffect(()=>{
+ const timer=setInterval(()=>{if(current.current&&unsaved.current&&!conflict&&!creating)void persist();},2000);
+ return ()=>clearInterval(timer);
+ },[conflict,creating]);
+ useEffect(()=>{
+ const external=(e:StorageEvent)=>{if(e.key===championshipKey||e.key===null){stop();setConflict(true);setWriteError("Championship changed in another tab. Export unsaved progress if needed, then load the saved championship.");}};
+ window.addEventListener("storage",external);return ()=>window.removeEventListener("storage",external);
+ },[]);
+ useEffect(()=>{
+ if(!running||!geometry)return;
+ let frame=0,previous=performance.now();
+ const tick=(now:number)=>{
+ if(!runningRef.current||!current.current?.session)return;
+ const seconds=Math.min((now-previous)/1000,.1)*speed;previous=now;
+ const next=advanceChampionship(current.current,seconds,geometry);replace(next);
+ if(!next.session){stop();void persist();return;}
+ frame=requestAnimationFrame(tick);
+ };
+ frame=requestAnimationFrame(tick);return ()=>cancelAnimationFrame(frame);
+ },[running,speed,geometry]);
+ function loadSaved() {
+ stop();const next=readChampionship();current.current=next.championship;setChamp(next.championship);
+ saved.current=next.championship?{id:next.championship.id,revision:next.championship.revision}:null;
+ unsaved.current=false;setRecoveryRaw(next.error?next.raw:null);setError(next.error);setWriteError("");setConflict(false);setDirty(false);setCreating(!next.championship);setControlled(next.championship?.ownDriverIds[0]??"");setMessage("Saved championship loaded; race is paused.");
+ }
+ async function create() {
+ setBusy(true);setError("");
+ try {
+ const team=readTeam();if(team.warning)throw new Error(team.warning);
+ const choices=await Promise.all(selected.map(async id=>{
+ const choice=options.find(v=>v.id===id);if(!choice)throw new Error("Choose all three venues.");
+ const replay=choice.raceId?(choice.raceId===race.id?race:await request(`/api/sessions/${encodeURIComponent(choice.raceId)}`)):null;
+ return {id:choice.id,label:choice.label,track:choice.track??circuitFromReplay(replay!.track,`${choice.label} · cup`)};
+ }));
+ const next=createChampionship(name,team.team,choices,laps,base);
+ const stored=await saveChampionship(saved.current,next);
+ current.current=stored;setChamp(stored);saved.current={id:stored.id,revision:stored.revision};unsaved.current=false;setDirty(false);setWriteError("");setConflict(false);setCreating(false);setConfirmReplace(false);setControlled(stored.ownDriverIds[0]);setMessage("Championship saved. Your signed lineup and calendar are frozen for these three rounds.");
+ }catch(e){setError((e as Error).message);}finally{setBusy(false);}
+ }
+ async function close() {
+ stop();
+ if(saving.current)await new Promise(resolve=>saveWaiters.current.push(resolve));
+ if(!current.current||await persist())onClose();
+ }
+ const control=champ?.session?.states.find(s=>s.id===controlled);
+ const driver=champ?.entrants.find(d=>d.id===controlled);
+ const target=control&&venue?pendingPit(control,driver!,venue.setup):null;
+ const nextEntry=control&&venue?nextPitEntry(control,venue.setup):null;
+ const rows=champ?standings(champ):[];
+ const locked=busy||conflict||!!writeError;
+ const last=champ?.results.at(-1);
+ return void close()}>
+ THREE-ROUND FICTIONAL CUP Race your two signed drivers against four rivals. Earn championship points across three venues. Results and race checkpoints save in this browser; recruiting credits and multiplayer rooms stay separate.
+ {error&&{error}
}{writeError&&Save failed: {writeError}
}
+ Load saved championship
+ {champ&&downloadJson("pitwall-championship.json",champ)}>Export championship JSON }
+ {recoveryRaw!==null&&<>downloadJson("pitwall-championship-backup.json",{raw:recoveryRaw})}>Back up unreadable championship setConfirmDiscard(true)}>Discard unreadable championship >}
+ {writeError&&Close without saving }
+
+ {confirmDiscard&&This deletes only the unreadable championship record. Download its backup first.
{try{await discardUnreadableChampionship(recoveryRaw!);setConfirmDiscard(false);loadSaved();}catch(e){setError((e as Error).message);}}}>Confirm discard championship }
+ {creating?Enter your selected signed lineup Select both race seats in Driver recruitment first. Entry is free; this first cup has points but no prize credits or training. Cached replay venues and saved custom circuits are available; import other replays through Browse races first.
+ Championship name setName(e.target.value)}/>
+ Laps per round
+ Base lap seconds
+ {selected.map((id,i)=>Round {i+1} venuesetSelected(old=>old.map((v,n)=>n===i?e.target.value:v) as [string,string,string])}>Choose venue {options.map(v=>{v.label} )} )}
+
+ {catalogError&&Cached venue list unavailable: {catalogError}. Current/saved circuits can still be selected.
}
+ !id)||new Set(selected).size!==3||!name.trim()} onClick={()=>void create()}>{champ?"Replace saved championship":"Create three-race championship"} {champ&&setCreating(false)}>Keep current championship }
+ {champ&&Creating this replaces the saved championship, including its results and any checkpoint. Export the old championship first if needed.
}
+ :champ&&<>
+
{champ.name} {champ.teamName} {champ.results.length}/3 rounds complete {dirty?"Unsaved progress": "Saved"}
+ {champ.venues.map((v,i)=>{v.label} · {i)}
+ {stop();void persist();}}>Save championship checkpoint
+ {!champ.session&&champ.results.length<3&&{replace(beginRound(champ));void persist();}}>Begin round {champ.results.length+1} }
+ {stop();setConfirmReplace(true);}}>Create another championship
+
+ {confirmReplace&&A new championship replaces this saved cup after you confirm its calendar. Existing recruiting data stays intact.
{setCreating(true);setConfirmReplace(false);}}>Choose new championship calendar setConfirmReplace(false)}>Keep this cup }
+ {champ.session&&venue&&geometry&&
Round {champ.session.round+1} · {venue.label} {formatClock(champ.session.elapsed)}
+ p.join(",")).join(" ")} fill="none" stroke="#f5b257" strokeWidth="3"/>{champ.session.states.map(s=>{const p=previewPoint(s,geometry),d=champ.entrants.find(d=>d.id===s.id)!;return {d.name} ;})}
+
{raceOrder(champ.session.states,venue.setup).map((s,i)=>
{i+1} {champ.entrants.find(d=>d.id===s.id)!.name}{s.phase.toUpperCase()} · {s.stops} stops
)}
+ {if(running){stop();void persist();}else{runningRef.current=true;setRunning(true);}}}>{running?"Pause championship race":"Run championship race"}
+ {stop();replace(advanceChampionship(current.current!,venue.setup.baseLapSeconds,geometry));void persist();}}>Advance championship lap
+ Race speedsetSpeed(Number(e.target.value))}>{[1,5,10,25].map(n=>{n}× )}
+ Your driversetControlled(e.target.value)}>{champ.entrants.filter(d=>champ.ownDriverIds.includes(d.id)).map(d=>{d.name} )}
+ {try{replace(championshipCall(current.current!,controlled,true));}catch(e){setError((e as Error).message);}}}>{control&&nextEntry!==null&&Math.floor(nextEntry)>Math.floor(Math.max(0,control.raceProgress))?"Box championship next lap":"Box championship this lap"}
+ {replace(championshipCall(current.current!,controlled,false));}}>Cancel championship pit call
+
{target!==null?`Your driver's pit entry is queued on lap ${Math.floor(target)+1}.`:control?.phase==="track"?"Your driver stays out until a pit call.":`Your driver is ${control?.phase}.`}
+ }
+ {!champ.session&&last&&{champ.results.length===3?"Championship complete":"Round complete"} · {champ.venues[last.round].label} {last.classification.map((r,i)=>{champ.entrants.find(d=>d.id===r.driverId)!.name} · {r.finishTime.toFixed(3)}s · +{championshipPoints[i]} points )} }
+ Driver standings {rows.map((r,i)=>
{i+1} {r.driver.name}{champ.ownDriverIds.includes(r.driver.id)?" · your team":""}{r.finishes[0]} wins {r.points} pts
)}
Team points: {rows.filter(r=>champ.ownDriverIds.includes(r.driver.id)).reduce((sum,r)=>sum+r.points,0)}
+ Scoring: 25/18/15/12/10/8. Ties use wins, then seconds, thirds and later places, then original grid order. Signed builds and rivals are frozen for this cup; later recruiting changes apply to the next championship.
+ >}
+ {busy?"Saving/loading…":message}
Checkpoints save about every two seconds, on pauses/round finishes and on normal panel close. A hard refresh/crash can lose the last unsaved seconds. Saved races reopen paused. Storage is browser-origin local, and only one active editing tab is supported. Export is an inspection record; no championship importer is implemented.
+ ;
+}
diff --git a/frontend/src/championship.test.ts b/frontend/src/championship.test.ts
new file mode 100644
index 0000000..10551aa
--- /dev/null
+++ b/frontend/src/championship.test.ts
@@ -0,0 +1,70 @@
+import {afterEach,beforeEach,describe,it,expect,vi} from "vitest";
+import {newTrack} from "./custom-track";
+import {createDriver,newTeam} from "./recruitment";
+import {advanceChampionship,beginRound,championshipCall,championshipKey,createChampionship,parseChampionship,recordRound,saveChampionship,standings,type Championship} from "./championship";
+
+const team=()=>createDriver(createDriver(newTeam(1),{id:"one",name:"One",color:"#64d2b6",origin:"custom",stats:{pace:70,consistency:70,pitDiscipline:70}}),{id:"two",name:"Two",color:"#ff665d",origin:"custom",stats:{pace:60,consistency:60,pitDiscipline:60}});
+const venues=()=>Array.from({length:3},(_,i)=>({id:`venue-${i}`,label:`Venue ${i+1}`,track:{...newTrack(),name:`Venue ${i+1}`}}));
+const cup=()=>createChampionship("Test Cup",team(),venues(),1,30);
+const finish=(c:Championship)=>advanceChampionship(beginRound(c),1000);
+describe("local three-round championship",()=>{
+ beforeEach(()=>vi.stubGlobal("navigator",{}));
+ afterEach(()=>vi.unstubAllGlobals());
+ it("freezes a six-driver field from two signed builds and validates entry/calendar",()=>{
+ const entry=team(),c=createChampionship("Test",entry,venues(),2,45);
+ expect(c.entrants).toHaveLength(6);expect(c.ownDriverIds).toEqual(["recruit:one","recruit:two"]);
+ entry.roster[0].name="Changed later";expect(c.entrants[0].name).toBe("One");
+ expect(parseChampionship(JSON.parse(JSON.stringify(c)))).toEqual(c);
+ expect(()=>createChampionship("Bad",newTeam(1),venues(),1,30)).toThrow(/two signed/);
+ const duplicate=venues();duplicate[1].id=duplicate[0].id;
+ expect(()=>createChampionship("Bad",team(),duplicate,1,30)).toThrow(/different/);
+ expect(()=>createChampionship("Bad",team(),venues(),0,30)).toThrow(/1–50/);
+ });
+ it("records each fully finished round once and awards the complete points schedule",()=>{
+ const c=finish(cup());
+ expect(c.results).toHaveLength(1);expect(c.session).toBeNull();
+ expect(standings(c).map(s=>s.points).sort((a,b)=>b-a)).toEqual([25,18,15,12,10,8]);
+ expect(()=>recordRound(c)).toThrow(/fully finished/);
+ expect(()=>recordRound(beginRound(c))).toThrow(/fully finished/);
+ const complete=finish(finish(c));
+ expect(complete.results).toHaveLength(3);expect(standings(complete).reduce((n,s)=>n+s.points,0)).toBe(264);
+ expect(()=>beginRound(complete)).toThrow(/complete/);
+ });
+ it("uses countback then grid order when points are tied",()=>{
+ const c=cup(),ids=c.entrants.map(d=>d.id);
+ const order=(driverIds:string[])=>driverIds.map((driverId,i)=>({driverId,finishTime:30+i}));
+ c.results=[{round:0,classification:order(ids)},{round:1,classification:order([ids[1],ids[0],...ids.slice(2)])}];
+ expect(standings(c).slice(0,2).map(r=>r.driver.id)).toEqual(ids.slice(0,2));
+ expect(standings(c)[0].points).toBe(43);
+ c.results.push({round:2,classification:order([ids[2],ids[1],ids[0],...ids.slice(3)])});
+ expect(standings(c)[0].driver.id).toBe(ids[1]);
+ });
+ it("resumes a serialized checkpoint with identical final times and preserves live decisions",()=>{
+ let c=beginRound(cup());c=championshipCall(c,c.ownDriverIds[0],true);c=advanceChampionship(c,10);
+ const resumed=parseChampionship(JSON.parse(JSON.stringify(c)));
+ expect(resumed.session?.states[0].pitTarget).not.toBeNull();
+ const a=advanceChampionship(c,1000),b=advanceChampionship(resumed,1000);
+ expect(b.results).toEqual(a.results);expect(standings(b)).toEqual(standings(a));
+ expect(()=>championshipCall(c,c.entrants[2].id,true)).toThrow(/team drivers/);
+ });
+ it("rejects malformed checkpoints and duplicate classifications without silently repairing them",()=>{
+ const active=beginRound(cup());
+ expect(()=>parseChampionship({...active,session:{...active.session,elapsed:-1}})).toThrow();
+ expect(()=>parseChampionship({...active,session:{...active.session,states:active.session!.states.map(s=>({...s,raceProgress:100}))}})).toThrow();
+ const complete=finish(cup());
+ const duplicate=structuredClone(complete);duplicate.results[0].classification[1].driverId=duplicate.results[0].classification[0].driverId;
+ expect(()=>parseChampionship(duplicate)).toThrow(/duplicate/);
+ expect(()=>parseChampionship({...complete,results:[...complete.results,...complete.results]})).toThrow();
+ });
+ it("keeps the prior checkpoint on failed writes and rejects stale-tab updates",async()=>{
+ let raw:string|null=null;
+ vi.stubGlobal("localStorage",{getItem:()=>raw,setItem:(_key:string,value:string)=>{raw=value;}});
+ const saved=await saveChampionship(null,cup());
+ const next=await saveChampionship(saved,beginRound(saved));
+ await expect(saveChampionship(saved,saved)).rejects.toThrow(/another tab/);
+ const old=raw;
+ vi.stubGlobal("localStorage",{getItem:()=>raw,setItem:()=>{throw new Error("Storage denied");}});
+ await expect(saveChampionship(next,advanceChampionship(next,1))).rejects.toThrow(/denied/);
+ expect(raw).toBe(old);expect(JSON.parse(raw!)["session"]).not.toBeNull();expect(championshipKey).toContain("championship");
+ });
+});
diff --git a/frontend/src/championship.ts b/frontend/src/championship.ts
new file mode 100644
index 0000000..75a4859
--- /dev/null
+++ b/frontend/src/championship.ts
@@ -0,0 +1,126 @@
+import {parseTrack, type CustomTrack} from "./custom-track";
+import {applyLineup, type Team} from "./recruitment";
+import {advanceRace, initialGrid, newSandboxDriver, nextPitEntry, parseSandbox, raceOrder, sandboxDefaults, sandboxGeometry, validateSandbox, type PreviewState, type SandboxDriver, type SandboxSetup} from "./sandbox";
+
+export const championshipKey = "pitwall.championship.v1";
+export const championshipPoints = [25,18,15,12,10,8];
+export type Venue = {id:string;label:string;track:CustomTrack;setup:SandboxSetup};
+export type Classification = {driverId:string;finishTime:number};
+export type RoundResult = {round:number;classification:Classification[]};
+export type Championship = {
+ version:1;id:string;revision:number;name:string;teamName:string;ownDriverIds:string[];
+ entrants:SandboxDriver[];venues:Venue[];results:RoundResult[];
+ session:{round:number;elapsed:number;states:PreviewState[]}|null;
+};
+export function createChampionship(name:string,team:Team,choices:{id:string;label:string;track:CustomTrack}[],laps:number,baseLapSeconds:number):Championship {
+ if(!name.trim()||name.trim().length>48)throw new Error("Use a championship name of 1–48 characters.");
+ if(choices.length!==3||new Set(choices.map(v=>v.id)).size!==3)throw new Error("Choose three different venues.");
+ if(!Number.isInteger(laps)||laps<1||laps>50||!Number.isFinite(baseLapSeconds)||baseLapSeconds<30||baseLapSeconds>300)throw new Error("Use 1–50 laps and a 30–300 second base pace.");
+ const seedSetup=sandboxDefaults(choices[0].track);
+ seedSetup.drivers=Array.from({length:6},(_,i)=>({...newSandboxDriver(i),name:`Rival ${i-1}`,paceOffset:[0,0,-1.5,.5,2,3.5][i],pitLap:i===2?Math.min(2,laps):0}));
+ const entrants=applyLineup(team,seedSetup).drivers;
+ const venues=choices.map(v=>{
+ const track=parseTrack(v.track);
+ const setup={...sandboxDefaults(track),raceLaps:laps,baseLapSeconds,drivers:entrants.map(d=>({...d}))};
+ const errors=validateSandbox(track,setup);
+ if(errors.length)throw new Error(`${v.label}: ${errors.join(" ")}`);
+ return {...v,track,setup};
+ });
+ return {version:1,id:crypto.randomUUID(),revision:0,name:name.trim(),teamName:team.name,ownDriverIds:entrants.slice(0,2).map(d=>d.id),entrants,venues,results:[],session:null};
+}
+export function beginRound(c:Championship):Championship {
+ if(c.session)throw new Error("Finish the active round before starting another.");
+ if(c.results.length>=3)throw new Error("This championship is complete.");
+ return {...c,session:{round:c.results.length,elapsed:0,states:initialGrid(c.entrants)}};
+}
+export function advanceChampionship(c:Championship,seconds:number,geometry?:ReturnType):Championship {
+ if(!c.session)return c;
+ const venue=c.venues[c.session.round];
+ const session={...advanceRace(c.session,venue.setup,geometry??sandboxGeometry(venue.track,venue.setup),seconds),round:c.session.round};
+ const next={...c,session};
+ return session.states.every(s=>s.phase==="finished")?recordRound(next):next;
+}
+export function recordRound(c:Championship):Championship {
+ if(!c.session||c.session.round!==c.results.length||!c.session.states.every(s=>s.phase==="finished"&&s.finishTime!==null))throw new Error("Only the next fully finished round can be recorded.");
+ const classification=raceOrder(c.session.states,c.venues[c.session.round].setup).map(s=>({driverId:s.id,finishTime:s.finishTime!}));
+ return {...c,results:[...c.results,{round:c.session.round,classification}],session:null};
+}
+export function championshipCall(c:Championship,id:string,box:boolean):Championship {
+ if(!c.session||!c.ownDriverIds.includes(id))throw new Error("Choose one of your active team drivers.");
+ const setup=c.venues[c.session.round].setup;
+ const state=c.session.states.find(s=>s.id===id)!;
+ if(state.phase!=="track")throw new Error("This driver has committed to the pit lane or finished.");
+ const target=box?nextPitEntry(state,setup):null;
+ if(box&&target===null)throw new Error("No pit entry remains before the finish.");
+ return {...c,session:{...c.session,states:c.session.states.map(s=>s.id===id?{...s,pitTarget:target}:s)}};
+}
+export function standings(c:Championship) {
+ const rows=c.entrants.map((d,index)=>({driver:d,points:0,finishes:Array(6).fill(0) as number[],grid:index}));
+ for(const result of c.results)result.classification.forEach((r,i)=>{
+ const row=rows.find(row=>row.driver.id===r.driverId)!;row.points+=championshipPoints[i];row.finishes[i]++;
+ });
+ return rows.sort((a,b)=>b.points-a.points||a.finishes.reduce((tie,n,i)=>tie||b.finishes[i]-n,0)||a.grid-b.grid);
+}
+const number=(n:unknown,min:number,max:number)=>typeof n==="number"&&Number.isFinite(n)&&n>=min&&n<=max;
+function parseSession(raw:NonNullable,c:Championship):NonNullable {
+ if(!raw||!Number.isInteger(raw.round)||raw.round<0||raw.round>2||raw.round!==c.results.length||!number(raw.elapsed,0,1e7)||!Array.isArray(raw.states)||raw.states.length!==6)throw new Error("Invalid saved race checkpoint.");
+ const laps=c.venues[raw.round].setup.raceLaps;
+ const states=raw.states.map((s,i)=>{
+ if(!s||s.id!==c.entrants[i].id||!["track","pit","service","finished"].includes(s.phase)||!number(s.raceProgress,-.04,laps+1e-7)||
+ !number(s.pitProgress,0,1)||!number(s.stopRemaining,0,15)||typeof s.serviced!=="boolean"||typeof s.visited!=="boolean"||typeof s.finishedInPit!=="boolean"||
+ !Number.isInteger(s.stops)||s.stops<0||s.stops>1000||
+ (s.pitTarget!==undefined&&s.pitTarget!==null&&!number(s.pitTarget,0,laps))||
+ (s.finishTime!==null&&!number(s.finishTime,0,raw.elapsed+1e-7))||
+ (s.phase==="finished"&&(s.finishTime===null||Math.abs(s.raceProgress-laps)>1e-7))||
+ (s.phase!=="finished"&&s.finishTime!==null))throw new Error("Saved race checkpoint contains invalid driver state.");
+ return {...s};
+ });
+ if(states.every(s=>s.phase==="finished"))throw new Error("A finished round must be stored as a result.");
+ return {round:raw.round,elapsed:raw.elapsed,states};
+}
+export function parseChampionship(raw:unknown):Championship {
+ if(!raw||typeof raw!=="object")throw new Error("Invalid saved championship.");
+ const r=raw as Championship;
+ if(r.version!==1||typeof r.id!=="string"||!r.id||r.id.length>80||!Number.isSafeInteger(r.revision)||r.revision<0||
+ typeof r.name!=="string"||!r.name.trim()||r.name.length>48||typeof r.teamName!=="string"||r.teamName.length>32||
+ !Array.isArray(r.venues)||r.venues.length!==3||!Array.isArray(r.entrants)||r.entrants.length!==6||
+ !Array.isArray(r.ownDriverIds)||r.ownDriverIds.length!==2||new Set(r.ownDriverIds).size!==2||
+ !r.ownDriverIds.every(id=>r.entrants.some(d=>d.id===id))||!Array.isArray(r.results)||r.results.length>3)throw new Error("Unsupported or invalid championship data.");
+ const venues=r.venues.map(v=>{
+ if(!v||typeof v.id!=="string"||!v.id||v.id.length>100||typeof v.label!=="string"||v.label.length>80)throw new Error("Invalid championship venue.");
+ const track=parseTrack(v.track),setup=parseSandbox(v.setup);
+ if(validateSandbox(track,setup).length||setup.drivers.length!==6||setup.drivers.some((d,i)=>!["id","name","color","paceOffset","pitLap","serviceSeconds"].every(key=>d[key as keyof SandboxDriver]===r.entrants[i]?.[key as keyof SandboxDriver])))throw new Error("Championship venue or frozen lineup is invalid.");
+ return {id:v.id,label:v.label,track,setup};
+ });
+ if(new Set(venues.map(v=>v.id)).size!==3)throw new Error("Championship venues must be distinct.");
+ const results=r.results.map((result,index)=>{
+ if(!result||result.round!==index||!Array.isArray(result.classification)||result.classification.length!==6||
+ new Set(result.classification.map(d=>d.driverId)).size!==6||result.classification.some((d,i)=>!r.entrants.some(e=>e.id===d.driverId)||!number(d.finishTime,0,1e7)||(i>0&&d.finishTime({driverId:d.driverId,finishTime:d.finishTime}))};
+ });
+ const c={...r,venues,results,entrants:venues[0].setup.drivers};
+ return {...c,session:r.session===null?null:parseSession(r.session,c)};
+}
+export function readChampionship():{championship:Championship|null;raw:string|null;error:string} {
+ try {
+ const raw=localStorage.getItem(championshipKey);
+ if(raw===null)return {championship:null,raw:null,error:""};
+ try {if(raw.length>500000)throw new Error("Saved championship is too large.");return {championship:parseChampionship(JSON.parse(raw)),raw,error:""};}
+ catch{return {championship:null,raw,error:"Saved championship could not be read. Its data has been kept intact; back it up before discarding it."};}
+ }catch{return {championship:null,raw:null,error:"Browser storage is unavailable. Restore access before creating or resuming a championship."};}
+}
+export async function saveChampionship(expected:{id:string;revision:number}|null,next:Championship):Promise {
+ const write=()=>{
+ const raw=localStorage.getItem(championshipKey);
+ const current=raw===null?null:parseChampionship(JSON.parse(raw));
+ if(expected===null?current!==null:!current||current.id!==expected.id||current.revision!==expected.revision)throw new Error("Championship changed in another tab. Load saved championship before continuing.");
+ const saved=parseChampionship({...next,revision:(current?.revision??0)+1});
+ localStorage.setItem(championshipKey,JSON.stringify(saved));return saved;
+ };
+ return typeof navigator!=="undefined"&&navigator.locks?navigator.locks.request(championshipKey,write):write();
+}
+export async function discardUnreadableChampionship(expectedRaw:string):Promise {
+ const write=()=>{if(localStorage.getItem(championshipKey)!==expectedRaw)throw new Error("Saved championship changed; load it again before discarding.");localStorage.removeItem(championshipKey);};
+ if(typeof navigator!=="undefined"&&navigator.locks)await navigator.locks.request(championshipKey,write);else write();
+}