TiGa-RCE commited on
Commit
a948328
·
verified ·
1 Parent(s): 9f8666e

Release driver-first 60 Hz interface with suggested replay line

Browse files

Qualified exact combined build: four-vehicle native CPU/GPU frozen parity and short training, controls/sensors replay, strict downloads and paired deletion, read-only bucket restore. Geometry suggestion remains distinct from measured telemetry. Existing account scopes, visibility, ZeroGPU hardware, native binaries, Godot, Swift and retained parent are preserved. Rollback source: 9f8666e822f312b197fd8607165b6a2a7c00e7f3

FRONTEND_SOURCE.json CHANGED
@@ -5,23 +5,24 @@
5
  "source": "Runner r14 single-engine browser UI; selected .track tile renderer added from simulator atlas",
6
  "source_sha256": "65d1e5f2c4e19b4951b828e82510005ab99a5270cf3dcb9f4eaa0fa1af8c40f8"
7
  },
8
- "client_sha256": "db89eadb60209fb58e061cd41247a7c2c40e77183a5fd3040cdb8e04a20d1521",
9
  "identity_note": "The historical source fields describe the base frontend; local packaged file hashes describe this candidate's derived frontend.",
10
- "local_customization_id": "ai-training-story-driving-around-20261023",
11
- "output_sha256": "1563f362b39eb62941585b370aded739d408ee917e71ec3de2966930c7d22dd7",
12
  "packaged_frontend_files": {
13
  "agent-manifest.json": "7187c85327d588cb3b81f5ddf60bae099567a656bcceac8147ecb2227e07f561",
14
  "agent-tools.js": "af4af7d4dab229f5988daf49f630e08879025b37b561a5c93669a6667ab8fdf4",
15
  "agents.html": "c2c6889e50056c68c921559ccf95267a541622471e2ccec55099d70989ee8110",
16
- "assets/track-atlas.json": "d97c8900e3e5fb17734b5bd61d1f4f4b196d9be30af9848e2e273ae7e4079ae4",
17
- "client.js": "db89eadb60209fb58e061cd41247a7c2c40e77183a5fd3040cdb8e04a20d1521",
18
- "help.html": "370eafcaf6141c90393761631ff26a4d0c2abd0c14a6a753f78e7dd9329e24e5",
19
  "hf-auth.js": "3f3938bbc0935e4e9230c094029ef46e03beea74be199887c50e053e03dafcfe",
20
- "index.html": "1563f362b39eb62941585b370aded739d408ee917e71ec3de2966930c7d22dd7",
21
  "track-library.js": "351ec4c026b49420ce963f4310cb000d9e987fd28e6dac5ecd0176509340f6e6",
22
- "track-map.js": "c5f56f1083f4c9487f8d3d663c939c736bdc478217e2b60142f820f3263adb44"
23
  },
24
- "packaged_frontend_sha256": "fbf489cd3f38afd927db6b7b0e9ff5a7b62e7360f1e6eae38a99120dd4ebb51b",
25
  "packaged_frontend_sha256_format": "SHA-256 of UTF-8 JSON for packaged_frontend_files, sorted keys, compact separators, no trailing newline",
26
- "status": "AI Training Story: Driving Around name; direct driving-network training wording; experiment controls and contracts preserved"
 
27
  }
 
5
  "source": "Runner r14 single-engine browser UI; selected .track tile renderer added from simulator atlas",
6
  "source_sha256": "65d1e5f2c4e19b4951b828e82510005ab99a5270cf3dcb9f4eaa0fa1af8c40f8"
7
  },
8
+ "client_sha256": "9de0e2faafd9a023391f0c237ab31e395654076072f2fe19327a83c62941e7f0",
9
  "identity_note": "The historical source fields describe the base frontend; local packaged file hashes describe this candidate's derived frontend.",
10
+ "local_customization_id": "driving-around-driver-first-60hz-reference-line-20261023",
11
+ "output_sha256": "c68124925b9f11b2ddba9ba10184853b0bb1e00dc941f8d7ce480336c8e7c29e",
12
  "packaged_frontend_files": {
13
  "agent-manifest.json": "7187c85327d588cb3b81f5ddf60bae099567a656bcceac8147ecb2227e07f561",
14
  "agent-tools.js": "af4af7d4dab229f5988daf49f630e08879025b37b561a5c93669a6667ab8fdf4",
15
  "agents.html": "c2c6889e50056c68c921559ccf95267a541622471e2ccec55099d70989ee8110",
16
+ "assets/track-atlas.json": "d6168fa2bbcf3e387bae2c61aa4912ad4b556038d2c34adeb4a11716139918ea",
17
+ "client.js": "9de0e2faafd9a023391f0c237ab31e395654076072f2fe19327a83c62941e7f0",
18
+ "help.html": "3d97401dfec365b62b5bb14be4a829bf43fbfaf15a2c0878c9945e0725910790",
19
  "hf-auth.js": "3f3938bbc0935e4e9230c094029ef46e03beea74be199887c50e053e03dafcfe",
20
+ "index.html": "c68124925b9f11b2ddba9ba10184853b0bb1e00dc941f8d7ce480336c8e7c29e",
21
  "track-library.js": "351ec4c026b49420ce963f4310cb000d9e987fd28e6dac5ecd0176509340f6e6",
22
+ "track-map.js": "c0deb286a6b52b2a0cca625bc112bbbcf8b7e2b66b2a438d012cd98f23d5780f"
23
  },
24
+ "packaged_frontend_sha256": "1d67e21edfcac6993d65b80bc88dd7855ef9df9221a25416c625e9649d2ac852",
25
  "packaged_frontend_sha256_format": "SHA-256 of UTF-8 JSON for packaged_frontend_files, sorted keys, compact separators, no trailing newline",
26
+ "parent_local_customization_id": "ai-training-story-driving-around-20261023",
27
+ "status": "Driver-first loading, new runs fixed at 60 Hz and geometric suggested-line replay overlay. Build qualification and deployment status are recorded separately."
28
  }
README.md CHANGED
@@ -22,13 +22,13 @@ Train a driver. Replay its decisions. Compare the evidence under matching condit
22
 
23
  Driving Around lets you experiment with small driving controllers in a packaged simulator. You can make a controller in the browser or load a compatible `.evolution` file, then ask the simulator to evaluate it or train a group of candidates. You do not need the original game installed to try the 28 built-in replica tracks and browser editor.
24
 
25
- The app is a separate, bounded experiment. It does not control the original game, reproduce its full campaign, or grant official stars or progression. Its track map previews tiles and terrain; it is not a live driving view. The built-in tracks are reconstructed replicas, and a successful simulation run is not proof of original-game physics parity.
26
 
27
  ## A first run
28
 
29
- 1. Click **Choose a track** and select one of the built-in replicas. You can instead upload a `.track` file. The map is a layout and terrain preview.
30
- 2. Click **Create starter network** to make a small controller in this page, or choose a `.evolution` file/use the **Network editor**. Choose a vehicle for a new starter network; imported controllers keep their own vehicle type. The starter is held in the browser and does not begin training.
31
- 3. Click **Review first-run settings**. The starter recipe is 32 candidates × 20 generations × 900 ticks per generation (15 simulated seconds per car per generation), mutation 0.3, decay 0, and a distance-only reward of +100. Collision and idle elimination are off; selection uses one parent and keeps one elite candidate. These are a starting point, not a promise of a fast or clean lap. Use **Apply first-run settings to this form** only if you want to reset the current form; saved recipes remain unchanged.
32
  4. CPU runs without an HF account. Under **Action**, choose **Train a population** or **Frozen evaluation · one policy, unchanged weights**, then click the run button to begin. Training evolves a group of candidate controllers; a generation is one round of simulation and selection. Reward settings tell the trainer which measured outcomes to favor.
33
  5. Click **Download result** to receive the result and reveal its winner, measurements, and supported challenge checks. Connected bucket autosave handles delivery instead. A challenge check replays the named network with fixed weights; it predicts conditions for the replica track and does not award stars in the original game.
34
  6. Download a controller or portable bundle to keep it locally. You can also connect an existing private Hugging Face bucket for optional saves. Read the storage note below before authorizing bucket access.
@@ -56,3 +56,16 @@ A training result can include the final-generation fitness winner, the fastest c
56
  The app can check supported track conditions after a run by replaying the named controller with fixed weights. This may add time to the run. The result is a bounded prediction for the reconstructed track. It does not award or accumulate original-game stars; opponent races and unsupported conditions remain unchecked.
57
 
58
  The simulator is based on [driving_sim_rs](https://github.com/Zorro909/driving_sim_rs), upstream revision `b90b8af06ffc4ea4e4fd703becd1107a48b8e5e0`; the release receipt records the packaged build and local changes. The package includes the upstream [MIT license](LICENSE). Upstream pull requests 19 and 21 are not included. Feedback: [open an editable issue draft](https://github.com/seeker-cyber-maker/driving_sim_rs/issues/new). It is not submitted automatically. Review the draft and remove private names or data before posting. Never attach tokens, job keys, private networks, proprietary tracks, or unrelated logs.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
 
23
  Driving Around lets you experiment with small driving controllers in a packaged simulator. You can make a controller in the browser or load a compatible `.evolution` file, then ask the simulator to evaluate it or train a group of candidates. You do not need the original game installed to try the 28 built-in replica tracks and browser editor.
24
 
25
+ The app is a separate, bounded experiment. It does not control the original game, reproduce its full campaign, or grant official stars or progression. Its track map shows static walls and a calculated suggested line; saved native recordings animate the measured car motion. It does not stream a running training population. The built-in tracks are reconstructed replicas, and a successful simulation run is not proof of original-game physics parity.
26
 
27
  ## A first run
28
 
29
+ 1. Under **Choose your driver**, use **From this device** to load a compatible `.evolution` file, or **Saved in bucket** to restore an existing private-bucket bundle. Check the selected driver name. If you need a fresh network, expand **Create a new driver instead**; creating one does not start a run.
30
+ 2. Under **Choose a track**, select one of the built-in replicas or expand **Use a custom .track file**. Use **Calculate suggested line** to compare a geometric reference with a recorded drive.
31
+ 3. Click **Review training settings & recipes**. The starter recipe is 32 candidates × 20 generations × 900 ticks per generation (15 simulated seconds per car per generation), mutation 0.3, decay 0, and a distance-only reward of +100. Collision and idle elimination are off; selection uses one parent and keeps one elite candidate. These are a starting point, not a promise of a fast or clean lap. Use **Apply first-run settings to this form** only if you want to reset the current form; saved recipes remain unchanged.
32
  4. CPU runs without an HF account. Under **Action**, choose **Train a population** or **Frozen evaluation · one policy, unchanged weights**, then click the run button to begin. Training evolves a group of candidate controllers; a generation is one round of simulation and selection. Reward settings tell the trainer which measured outcomes to favor.
33
  5. Click **Download result** to receive the result and reveal its winner, measurements, and supported challenge checks. Connected bucket autosave handles delivery instead. A challenge check replays the named network with fixed weights; it predicts conditions for the replica track and does not award stars in the original game.
34
  6. Download a controller or portable bundle to keep it locally. You can also connect an existing private Hugging Face bucket for optional saves. Read the storage note below before authorizing bucket access.
 
56
  The app can check supported track conditions after a run by replaying the named controller with fixed weights. This may add time to the run. The result is a bounded prediction for the reconstructed track. It does not award or accumulate original-game stars; opponent races and unsupported conditions remain unchecked.
57
 
58
  The simulator is based on [driving_sim_rs](https://github.com/Zorro909/driving_sim_rs), upstream revision `b90b8af06ffc4ea4e4fd703becd1107a48b8e5e0`; the release receipt records the packaged build and local changes. The package includes the upstream [MIT license](LICENSE). Upstream pull requests 19 and 21 are not included. Feedback: [open an editable issue draft](https://github.com/seeker-cyber-maker/driving_sim_rs/issues/new). It is not submitted automatically. Review the draft and remove private names or data before posting. Never attach tokens, job keys, private networks, proprietary tracks, or unrelated logs.
59
+
60
+
61
+ ## Driver-first / 60 Hz
62
+
63
+ Load an existing `.evolution` driver or saved bucket bundle first. Creating a new driver is secondary. The Run button follows the driver, track, action and compute settings. New training and frozen evaluations require **60 Hz physics and 60 Hz controller decisions** (`batch_count=1`) on CPU and GPU.
64
+
65
+ Historical 30/15 Hz recipes and receipts remain readable and retain their recorded timing. They cannot start a new run. Use **Make a 60 Hz copy** in Training & recipes to create a new recipe in an empty slot; the original recipe and batches stay unchanged. Restoring an older bundle loads its driver but does not apply its non-60 Hz recipe. Replay sampling and playback speed are unchanged.
66
+
67
+ Build-specific bucket, CPU/GPU and deployment qualification is recorded in the release acceptance receipt. The interface does not automatically promote a trained policy. See `UI_CADENCE_CHANGE.json`.
68
+
69
+ ## Suggested line
70
+
71
+ The preview adds native static wall polygons, a browser-calculated geometric suggestion, and distance from the measured replay position to that line. See `REPLAY_BLACKBOX.md` for its bounded search, static-clearance checks and vehicle-dynamics limitations. This is not an optimal-lap solver or a policy promotion.
RELEASE_MANIFEST.json CHANGED
@@ -7,14 +7,15 @@
7
  "CUDA_REFERENCE.md": "f7453c3254d244f8b0de41fde5851cb025159f5cea4a4d1a5d8208a955550c6c",
8
  "DATA_POLICY.md": "fc5978528abe1c21c14882417ac8a706e04a0831bbd3fdb3de8c64442c1a7b3d",
9
  "FEEDBACK.md": "f95b8f6afbf4a360976c0edca5d52f5b3a0b668c9a944d4947b840a7c53a122a",
10
- "FRONTEND_SOURCE.json": "3b8f536991132cb7536c98de0a76a446f47c641a42d9b2ef13f9cfa6ee4bdc98",
11
  "GODOT_LICENSE": "fb2b3bb82c60f1e76841ba2122eb902f8e39c151476fe21ce10c9a05d1045304",
12
  "IMPORTER_BUILD_RECEIPT.json": "4ba5c533cc617105478e4d85c83f456a7dfa68b1388049624619871ba9e42e9d",
13
  "LICENSE": "53d5851b6440feeae36f72a5f57fcab37858c48b7084765ece4b0c54b9a28ed8",
14
- "README.md": "21615d678ae4e28c09ce658c0aa16a959ccb5627ab01a5cfc23b4ca1adab3c57",
15
- "REPLAY_BLACKBOX.md": "08cbb1fca44e54ac127d049fbad4d34f7e2048c3609f362277bd86dfe524931f",
16
  "STORAGE_BOUNDARY.md": "1d0cab6c82723f1879d7b437bab6b0d21248436bce161f3fbfe6c0e83b9e87a1",
17
  "TRACK_LIBRARY.md": "be64c91633ef6696233df537afeef4c5175b2d55daac9336758d9eb3d24763c9",
 
18
  "UPSTREAM.json": "78472cb79a40839face9ccf81f5b87f3f20a5f1d663101287070222f54ee4608",
19
  "WINNERS_AND_EVALUATION.md": "f281cf496763c59c50a79161cfff1a46d3529edfcfaaa14962c9a3f2d4f9446f",
20
  "agent-manifest.json": "7187c85327d588cb3b81f5ddf60bae099567a656bcceac8147ecb2227e07f561",
@@ -26,7 +27,7 @@
26
  "assets/formula_template.json": "80f745df82bb7be45af52785fd582460bcddc63c5a4e1d8375d85b3122db4c6b",
27
  "assets/rally_template.json": "7350a3fe28d9b4da7a0965ae6ea7ca3472fb7885303e342310d63a0dce80851c",
28
  "assets/snowmobile_template.json": "8232f4d54829445c44de9292e12557bfe66b3d43e0363e07d2ae0b4118721c08",
29
- "assets/track-atlas.json": "d97c8900e3e5fb17734b5bd61d1f4f4b196d9be30af9848e2e273ae7e4079ae4",
30
  "assets/truck_template.json": "a83bffea4d5e818c135ab3aba68a47aa288d6ad0e7b8bd9c95ed0dea9e9df2f7",
31
  "bin/altd-sim": "225de9c2b7dd0d9cb11c2578f50fff8a34f4cf6223580035ab0fa64e700beac8",
32
  "bin/extract_saved_track": "3a7733c45b4301a786fcbfe92660a1c484749272da5f608d62f34878bd4ff31a",
@@ -63,13 +64,13 @@
63
  "builtin_tracks/tracks/Replica R08 Demolition Derby.track": "6f11a9ffbcb477c9d19964566b1b612d2a94675605246e93e21f27bbbdb357ef",
64
  "builtin_tracks/tracks/Replica R09 Eau Noir.track": "3ec0a78478cca1a4f0d2d98ac81f40783928adf271b70f0c32d295a6da2cdaa9",
65
  "builtin_tracks/tracks/Replica The Champions Trial.track": "a3bfb76422affc774b44c739b0636d08acb901fa7615b9adcb52c069f79834e1",
66
- "client.js": "db89eadb60209fb58e061cd41247a7c2c40e77183a5fd3040cdb8e04a20d1521",
67
  "delivery.py": "6bdba2e87c3e19a41440cb16103695af27105f8bafbae38948bbb1b936ed0c1b",
68
  "gpu_tickets.py": "20928fcf1ca24648809ad8712c929377bdcc8b5e6b4387bfff3503ec5711928b",
69
- "help.html": "370eafcaf6141c90393761631ff26a4d0c2abd0c14a6a753f78e7dd9329e24e5",
70
  "hf-auth.js": "3f3938bbc0935e4e9230c094029ef46e03beea74be199887c50e053e03dafcfe",
71
  "hf_identity.py": "913fb1e089af21f376e8359a20cbc838d5bcd7971def6989a4382d53c1127b37",
72
- "index.html": "1563f362b39eb62941585b370aded739d408ee917e71ec3de2966930c7d22dd7",
73
  "native/analysis.patch": "42f79de67cb0734cffb2a7582f5479cab42ab82675884b8b42b9f158d46a98e8",
74
  "native/blackbox-build-receipt.json": "de3eea6c45a5ae4897287a97b0e2822fdae552a0655250bf940cef20d9b60d96",
75
  "native/blackbox-source.tar.gz": "56b43430c68b95bf7ac0d8312975c366c920f99b1653d790fb15b59453728e28",
@@ -91,15 +92,15 @@
91
  "star_check.py": "5c17080957b81ffccf0de8314635b471562e55c92c97a1207d9034a99279b2c3",
92
  "steam_leaderboard.py": "d76397c39cae58f636ddf9a9be1a46ae3d77fefd6b7269feac73d34d97165481",
93
  "track-library.js": "351ec4c026b49420ce963f4310cb000d9e987fd28e6dac5ecd0176509340f6e6",
94
- "track-map.js": "c5f56f1083f4c9487f8d3d663c939c736bdc478217e2b60142f820f3263adb44",
95
- "training_config.py": "6eb7282bbee3b3a6273bddc29c949d9904067414c26e501d815012f033173a1c",
96
  "vendor/gradio-client/LICENSE": "c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4",
97
  "vendor/gradio-client/dist/index.min.js": "fdd776db8633354f118fe2908c980592283968737e6b91dc3aa86d648da5c3fd",
98
  "vendor/gradio-client/package.json": "96c5b9e6d3587fb7bd8e5bb28775ece222de1043045afc4e6389c88db137ad0e",
99
  "vendor/hf-oauth/LICENSE": "d6e7b19451c1b3d1d66353bb4b1274138953b3bfd9ae60c56e77b1f548796982",
100
  "vendor/hf-oauth/index.js": "53282844000a171011e547f6472a3846bb4cecb5071adafea079fcac3a2aee7e",
101
  "vendor/hf-oauth/package.json": "fafd4d8891023a1961546a7d3bc25cd24f64923a2ebfc449fe6d516a2949bda8",
102
- "worker.py": "d18053363baf8147425808e9fd939f44f00af23781662d353196ade974144974"
103
  },
104
  "interface": "single-engine-manual-replay-native-blackbox-v2",
105
  "physics_revision": "20261017-v1.3-candidate",
 
7
  "CUDA_REFERENCE.md": "f7453c3254d244f8b0de41fde5851cb025159f5cea4a4d1a5d8208a955550c6c",
8
  "DATA_POLICY.md": "fc5978528abe1c21c14882417ac8a706e04a0831bbd3fdb3de8c64442c1a7b3d",
9
  "FEEDBACK.md": "f95b8f6afbf4a360976c0edca5d52f5b3a0b668c9a944d4947b840a7c53a122a",
10
+ "FRONTEND_SOURCE.json": "994bff70a53406c87f6fdb27b1a41357700ae4d0e2787ff037be3616780d2dac",
11
  "GODOT_LICENSE": "fb2b3bb82c60f1e76841ba2122eb902f8e39c151476fe21ce10c9a05d1045304",
12
  "IMPORTER_BUILD_RECEIPT.json": "4ba5c533cc617105478e4d85c83f456a7dfa68b1388049624619871ba9e42e9d",
13
  "LICENSE": "53d5851b6440feeae36f72a5f57fcab37858c48b7084765ece4b0c54b9a28ed8",
14
+ "README.md": "eebf3d86c6d4e3c7fff93d20682cd54db80d2d22ad68158265e8ff9767d2b6c5",
15
+ "REPLAY_BLACKBOX.md": "a8b0af35eab6cce73a57500e54dc3ffc99498072500c51dd54022900759793aa",
16
  "STORAGE_BOUNDARY.md": "1d0cab6c82723f1879d7b437bab6b0d21248436bce161f3fbfe6c0e83b9e87a1",
17
  "TRACK_LIBRARY.md": "be64c91633ef6696233df537afeef4c5175b2d55daac9336758d9eb3d24763c9",
18
+ "UI_CADENCE_CHANGE.json": "d7923a03e59bc24ffbf412a49474012fa00c0cdc5f92f4dfb1f72de23d289a4e",
19
  "UPSTREAM.json": "78472cb79a40839face9ccf81f5b87f3f20a5f1d663101287070222f54ee4608",
20
  "WINNERS_AND_EVALUATION.md": "f281cf496763c59c50a79161cfff1a46d3529edfcfaaa14962c9a3f2d4f9446f",
21
  "agent-manifest.json": "7187c85327d588cb3b81f5ddf60bae099567a656bcceac8147ecb2227e07f561",
 
27
  "assets/formula_template.json": "80f745df82bb7be45af52785fd582460bcddc63c5a4e1d8375d85b3122db4c6b",
28
  "assets/rally_template.json": "7350a3fe28d9b4da7a0965ae6ea7ca3472fb7885303e342310d63a0dce80851c",
29
  "assets/snowmobile_template.json": "8232f4d54829445c44de9292e12557bfe66b3d43e0363e07d2ae0b4118721c08",
30
+ "assets/track-atlas.json": "d6168fa2bbcf3e387bae2c61aa4912ad4b556038d2c34adeb4a11716139918ea",
31
  "assets/truck_template.json": "a83bffea4d5e818c135ab3aba68a47aa288d6ad0e7b8bd9c95ed0dea9e9df2f7",
32
  "bin/altd-sim": "225de9c2b7dd0d9cb11c2578f50fff8a34f4cf6223580035ab0fa64e700beac8",
33
  "bin/extract_saved_track": "3a7733c45b4301a786fcbfe92660a1c484749272da5f608d62f34878bd4ff31a",
 
64
  "builtin_tracks/tracks/Replica R08 Demolition Derby.track": "6f11a9ffbcb477c9d19964566b1b612d2a94675605246e93e21f27bbbdb357ef",
65
  "builtin_tracks/tracks/Replica R09 Eau Noir.track": "3ec0a78478cca1a4f0d2d98ac81f40783928adf271b70f0c32d295a6da2cdaa9",
66
  "builtin_tracks/tracks/Replica The Champions Trial.track": "a3bfb76422affc774b44c739b0636d08acb901fa7615b9adcb52c069f79834e1",
67
+ "client.js": "9de0e2faafd9a023391f0c237ab31e395654076072f2fe19327a83c62941e7f0",
68
  "delivery.py": "6bdba2e87c3e19a41440cb16103695af27105f8bafbae38948bbb1b936ed0c1b",
69
  "gpu_tickets.py": "20928fcf1ca24648809ad8712c929377bdcc8b5e6b4387bfff3503ec5711928b",
70
+ "help.html": "3d97401dfec365b62b5bb14be4a829bf43fbfaf15a2c0878c9945e0725910790",
71
  "hf-auth.js": "3f3938bbc0935e4e9230c094029ef46e03beea74be199887c50e053e03dafcfe",
72
  "hf_identity.py": "913fb1e089af21f376e8359a20cbc838d5bcd7971def6989a4382d53c1127b37",
73
+ "index.html": "c68124925b9f11b2ddba9ba10184853b0bb1e00dc941f8d7ce480336c8e7c29e",
74
  "native/analysis.patch": "42f79de67cb0734cffb2a7582f5479cab42ab82675884b8b42b9f158d46a98e8",
75
  "native/blackbox-build-receipt.json": "de3eea6c45a5ae4897287a97b0e2822fdae552a0655250bf940cef20d9b60d96",
76
  "native/blackbox-source.tar.gz": "56b43430c68b95bf7ac0d8312975c366c920f99b1653d790fb15b59453728e28",
 
92
  "star_check.py": "5c17080957b81ffccf0de8314635b471562e55c92c97a1207d9034a99279b2c3",
93
  "steam_leaderboard.py": "d76397c39cae58f636ddf9a9be1a46ae3d77fefd6b7269feac73d34d97165481",
94
  "track-library.js": "351ec4c026b49420ce963f4310cb000d9e987fd28e6dac5ecd0176509340f6e6",
95
+ "track-map.js": "c0deb286a6b52b2a0cca625bc112bbbcf8b7e2b66b2a438d012cd98f23d5780f",
96
+ "training_config.py": "512b9387727eb2cffa39206ac8edbcdf0830e876b16268003f98bd0b146494de",
97
  "vendor/gradio-client/LICENSE": "c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4",
98
  "vendor/gradio-client/dist/index.min.js": "fdd776db8633354f118fe2908c980592283968737e6b91dc3aa86d648da5c3fd",
99
  "vendor/gradio-client/package.json": "96c5b9e6d3587fb7bd8e5bb28775ece222de1043045afc4e6389c88db137ad0e",
100
  "vendor/hf-oauth/LICENSE": "d6e7b19451c1b3d1d66353bb4b1274138953b3bfd9ae60c56e77b1f548796982",
101
  "vendor/hf-oauth/index.js": "53282844000a171011e547f6472a3846bb4cecb5071adafea079fcac3a2aee7e",
102
  "vendor/hf-oauth/package.json": "fafd4d8891023a1961546a7d3bc25cd24f64923a2ebfc449fe6d516a2949bda8",
103
+ "worker.py": "17350cafc4e785f45ce5be5bc272d4cc1d967bc3babd299d94d7238dc48b84ae"
104
  },
105
  "interface": "single-engine-manual-replay-native-blackbox-v2",
106
  "physics_revision": "20261017-v1.3-candidate",
REPLAY_BLACKBOX.md CHANGED
@@ -11,3 +11,11 @@ Contact and active-state events mark sampled intervals. A contact increase in (t
11
  Version 2 JSON contains explicit capture provenance and phases, the ordered sensor descriptors/output slots, each frame's raw/applied commands, and its cached decision tick/input vector. The browser rejects mismatched selected track/policy hashes, missing samples, nonfinite values, invalid sensor layouts, normalization mismatches, future or backward decision clocks and decreasing contact counters. Legacy version 1 recordings remain viewable with controls/sensors explicitly unavailable. Open recording and Download recording support repeatable inspection without starting another simulation. Imported recordings are data, not authenticated provenance claims.
12
 
13
  The native extension does not change CUDA kernels, GPU ABI, physics or evolutionary policy rules. An actual Linux CPU comparison checks old versus new physical samples exactly. Native cache tests check pre-physics inputs and last decision/reset semantics. GPU execution of the new candidate is a separate quota-checked release gate; CPU replay cannot establish general CPU/GPU or original-game parity.
 
 
 
 
 
 
 
 
 
11
  Version 2 JSON contains explicit capture provenance and phases, the ordered sensor descriptors/output slots, each frame's raw/applied commands, and its cached decision tick/input vector. The browser rejects mismatched selected track/policy hashes, missing samples, nonfinite values, invalid sensor layouts, normalization mismatches, future or backward decision clocks and decreasing contact counters. Legacy version 1 recordings remain viewable with controls/sensors explicitly unavailable. Open recording and Download recording support repeatable inspection without starting another simulation. Imported recordings are data, not authenticated provenance claims.
12
 
13
  The native extension does not change CUDA kernels, GPU ABI, physics or evolutionary policy rules. An actual Linux CPU comparison checks old versus new physical samples exactly. Native cache tests check pre-physics inputs and last decision/reset semantics. GPU execution of the new candidate is a separate quota-checked release gate; CPU replay cannot establish general CPU/GPU or original-game parity.
14
+
15
+ ## Suggested line overlay
16
+
17
+ The track preview can calculate a suggested line in the browser. It follows the closed route from the saved starting connection, samples the centerline at equal intervals, finds a feasible seed around obstacles when needed, then uses bounded normal offsets to reduce a discrete geometric bending cost. Every accepted line segment remains inside saved track tiles and at least 32 game units from static wall polygons from the simulator atlas. Offsets are bounded to 192 game units; calculation is capped at 2,048 points and eight sweeps. An infeasible centerline or broken route reports unavailable rather than drawing an unchecked line.
18
+
19
+ Dashed yellow is the suggestion, orange is the saved centerline, and green is the recorded trajectory. Dark shapes show static wall polygons. The nearest-line distance uses the selected measured car sample, including when pose interpolation is enabled. It is not a reward or a driving-quality score. Changing tracks clears the suggestion and recording. Changing policy clears the recording but can retain this geometry-only suggestion.
20
+
21
+ This is a local geometric heuristic, not a guaranteed minimum-curvature or minimum-time path. It does not model vehicle dimensions, steering, grip, surface traction, braking, boost, opponents or dynamic collisions. Static wall clearance does not establish that a vehicle can follow it. It never changes policy inputs, rewards, training or physics. The overlay needs no GPU or simulator call.
UI_CADENCE_CHANGE.json ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "base_github_commit": "9384cb4dd596c101fb8bfd0c4d764452b78717f8",
3
+ "changes": [
4
+ "index.html",
5
+ "client.js",
6
+ "training_config.py",
7
+ "worker.py",
8
+ "FRONTEND_SOURCE.json"
9
+ ],
10
+ "execution": {
11
+ "batch_count": 1,
12
+ "control_hz": 60,
13
+ "physics_hz": 60
14
+ },
15
+ "legacy_policy": "Historical recipe/bundle/report schemas remain readable. New runs reject non-60 Hz. Conversion makes a separate recipe copy and never rewrites batches or measurements.",
16
+ "native_artifacts": "unchanged; no native source or binary rebuild",
17
+ "reference_overlay": {
18
+ "max_offset_game_units": 192,
19
+ "max_points": 2048,
20
+ "method": "bounded normal-offset geometric smoothing with feasible seed search",
21
+ "static_wall_margin_game_units": 32,
22
+ "status": "Geometric suggestion only; not a minimum-time or vehicle-feasibility solver"
23
+ },
24
+ "schema": "ald.ui-cadence-change/v1",
25
+ "status": "qualification_in_release_acceptance_receipt",
26
+ "supplied_patch_sha256": "33cec17dc3b03b720292c2fece10696d5bd04a67739f25eba925eb25059e9bea",
27
+ "validation": "Cadence validation and source-preserving layout changes; see the separate exact-build acceptance receipt for executed gates."
28
+ }
assets/track-atlas.json CHANGED
The diff for this file is too large to render. See raw diff
 
client.js CHANGED
@@ -139,6 +139,8 @@ function buttons() {
139
  syncRunModeUI(settingsUnavailable);
140
  renderResultSummary();
141
  renderRecordingIdentity();
 
 
142
  }
143
  // Presentation only: these summaries reuse the verified run/replay state and existing controls.
144
  function selectedReplayDriverLabel(){
 
139
  syncRunModeUI(settingsUnavailable);
140
  renderResultSummary();
141
  renderRecordingIdentity();
142
+ window.DriverFirst?.update(networkSource()?.name||null);
143
+ if($('driver_inspect'))$('driver_inspect').disabled=unavailable||!networkSource();
144
  }
145
  // Presentation only: these summaries reuse the verified run/replay state and existing controls.
146
  function selectedReplayDriverLabel(){
help.html CHANGED
@@ -25,14 +25,14 @@
25
  <h2>What you are optimizing</h2>
26
  <p>The task is to drive a vehicle around a track. Your controller maps its configured sensor observations—such as raycast distances and velocity—to controls such as steering, acceleration, and braking. The network file includes the vehicle type, sensors, and output order; changing those changes the policy’s interface.</p>
27
  <p>Training uses evolutionary search: simulate a population, score candidates, select parents, then generate variations through mutation and optional crossover. The <strong>mutation rate controls the scale of parameter perturbations</strong>; it is not an SGD learning rate. Reward settings determine the selection objective without changing the physics. Game reference: <a href="https://ai-learns-to-drive.fandom.com/wiki/Training_Process" target="_blank" rel="noopener">Training Process</a>.</p>
28
- <p class="callout">This lab is headless. The map previews the track and terrain; it does not animate the cars. Inspect behavior through reported measurements and fresh evaluations. Built-in tracks are reconstructed replicas, usable without installing the original game. The lab does not award official stars or change game progress.</p>
29
  </section>
30
 
31
  <section class="section" id="first-run">
32
  <h2>Run one small baseline</h2>
33
  <ol class="steps">
34
- <li>On <strong>Run &amp; results</strong>, choose <strong>Replica A01 Beginner</strong>. Set <strong>Starter car</strong> to <strong>Formula</strong>, then click <strong>Create starter network</strong>. This creates the small <strong>6-input → 4-hidden-unit → 5-output</strong> controller in the page; training has not started.</li>
35
- <li>Open <strong>Training &amp; recipes</strong>. Keep the current starter settings below. If you have edited the form, use <strong>Apply first-run settings to this form</strong> to restore them. You do not need to save a recipe first.</li>
36
  <li>Return to <strong>Run &amp; results</strong>. Choose <strong>CPU — no GPU allowance</strong> to run without signing in, and <strong>Action → Train a population</strong>, then click <strong>Run training</strong>.</li>
37
  <li>When it finishes, click <strong>Download result</strong>. Read the laps, lap time, and contacts as explained below, and retain the downloaded <code>.evolution</code> as your checkpoint. To keep a different winner, use <strong>Download weights</strong> in that winner’s row.</li>
38
  </ol>
@@ -114,6 +114,7 @@
114
  <p class="small">These checks are bounded predictions for replica conditions, not original-game awards or Steam leaderboard results.</p>
115
  </section>
116
 
 
117
  <section class="section" id="freeze">
118
  <h2>Selective freezing</h2>
119
  <p>On <strong>Training &amp; recipes</strong>, open <strong>Selective freezing</strong> to keep selected parameters at their values in the starting network. Freezing an input holds its outgoing weights; freezing a hidden layer holds its incoming weights and biases; freezing an output holds its incoming weights and bias. The available choices and names come from the selected network. Freeze selections are part of saved recipes and can be edited later. Frozen evaluation runs the selected policy unchanged.</p>
 
25
  <h2>What you are optimizing</h2>
26
  <p>The task is to drive a vehicle around a track. Your controller maps its configured sensor observations—such as raycast distances and velocity—to controls such as steering, acceleration, and braking. The network file includes the vehicle type, sensors, and output order; changing those changes the policy’s interface.</p>
27
  <p>Training uses evolutionary search: simulate a population, score candidates, select parents, then generate variations through mutation and optional crossover. The <strong>mutation rate controls the scale of parameter perturbations</strong>; it is not an SGD learning rate. Reward settings determine the selection objective without changing the physics. Game reference: <a href="https://ai-learns-to-drive.fandom.com/wiki/Training_Process" target="_blank" rel="noopener">Training Process</a>.</p>
28
+ <p class="callout">Training runs headlessly. The map shows static walls and a suggested line; opening a native recording lets you play the measured car motion and inspect its black box. It does not stream the training population. Built-in tracks are reconstructed replicas, usable without installing the original game. The lab does not award official stars or change game progress.</p>
29
  </section>
30
 
31
  <section class="section" id="first-run">
32
  <h2>Run one small baseline</h2>
33
  <ol class="steps">
34
+ <li>On <strong>Run &amp; results</strong>, load an existing driver from <strong>From this device</strong> or <strong>Saved in bucket</strong>. For this fresh baseline, expand <strong>Create a new driver instead</strong>, set <strong>Starter car</strong> to <strong>Formula</strong>, then click <strong>Create starter network</strong>. Choose <strong>Replica A01 Beginner</strong>. This creates the small <strong>6-input → 4-hidden-unit → 5-output</strong> controller in the page; training has not started.</li>
35
+ <li>Open <strong>Training &amp; recipes</strong>. Keep the current starter settings below. If you have edited the form, use <strong>Apply first-run settings to this form</strong> to restore them. You do not need to save a recipe first. New experiments always use 60 Hz decisions and physics. Historical 30/15 Hz recipes remain readable; use <strong>Make a 60 Hz copy</strong> to create a separate recipe before running one.</li>
36
  <li>Return to <strong>Run &amp; results</strong>. Choose <strong>CPU — no GPU allowance</strong> to run without signing in, and <strong>Action → Train a population</strong>, then click <strong>Run training</strong>.</li>
37
  <li>When it finishes, click <strong>Download result</strong>. Read the laps, lap time, and contacts as explained below, and retain the downloaded <code>.evolution</code> as your checkpoint. To keep a different winner, use <strong>Download weights</strong> in that winner’s row.</li>
38
  </ol>
 
114
  <p class="small">These checks are bounded predictions for replica conditions, not original-game awards or Steam leaderboard results.</p>
115
  </section>
116
 
117
+ <section class="section" id="suggested-line"><h2>Compare the recorded drive with a suggested line</h2><p>On Run &amp; results, use <strong>Calculate suggested line</strong>. Dashed yellow shows a geometry-based suggestion; orange is the track centerline and green is the recorded car path. Dark shapes show static walls. Record or open a drive, then play, scrub or step through its measured car positions and black box.</p><p>The suggestion smooths the route while keeping a 32 game-unit static wall margin. It does not model vehicle size, grip, braking or boost, so it is not a fastest-lap prediction or a guarantee that the car can follow it. Distance to the suggestion is a geometric measurement, not a driving score. Broken or infeasible routes report unavailable. This calculation runs in your browser and does not train or simulate a car.</p></section>
118
  <section class="section" id="freeze">
119
  <h2>Selective freezing</h2>
120
  <p>On <strong>Training &amp; recipes</strong>, open <strong>Selective freezing</strong> to keep selected parameters at their values in the starting network. Freezing an input holds its outgoing weights; freezing a hidden layer holds its incoming weights and biases; freezing an output holds its incoming weights and bias. The available choices and names come from the selected network. Freeze selections are part of saved recipes and can be edited later. Frozen evaluation runs the selected policy unchanged.</p>
index.html CHANGED
@@ -21,6 +21,137 @@
21
  <p id="appConfirmMessage"></p>
22
  <div class="actions"><button id="appConfirmCancel" type="button">Cancel</button><button id="appConfirmAccept" type="button">Continue</button></div>
23
  </dialog>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
  <script>
25
  (() => {
26
  const dialog=document.getElementById('appConfirm'),title=document.getElementById('appConfirmTitle');
@@ -44,34 +175,110 @@
44
  </script>
45
  <style>/* A small pixel-workshop accent; all workspace controls retain their layout. */
46
  .lab-header{border-top:4px solid #f1c66d;padding-top:12px}.lab-header .eyebrow{color:#f1c66d;letter-spacing:.14em}.lab-header h1{font-family:ui-monospace,SFMono-Regular,Consolas,monospace;letter-spacing:-.04em;text-shadow:2px 2px #284539}.brand-copy{min-width:0;max-width:100%}.brand-question{font-size:14px;line-height:1.5;color:#d4e6d9;margin:9px 0 0;max-width:65ch}.lab-header .header-actions{align-self:center}.lab-header .help-link{border-radius:4px;box-shadow:3px 3px #284539}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47
  </style>
48
  <header class="lab-header"><div class="brand-copy"><div class="eyebrow">AI TRAINING STORY</div><h1>Driving Around</h1><p class="intro">Train a driver. Replay its decisions.</p><p class="brand-question">Can you train a neural network to drive better than an agent?</p></div><div class="header-actions"><button id="quick_start_toggle" type="button" aria-controls="firstRunGuide" aria-expanded="false">Quick start</button><a class="help-link" href="/help#start-here" target="_blank" rel="noopener">Help &amp; tutorial ↗</a></div></header>
49
  <div class="lab-utilities"><details class="about"><summary>About &amp; feedback</summary><p><strong>AI Training Story: Driving Around</strong> is a standalone controller workshop inspired by <em>AI Learns To Drive</em>. Train a population, evaluate an unchanged driver, and inspect its measured replay. You or an agent can operate the experiment tools; the opening question is a challenge to investigate through matched comparisons.</p><p>Simulator by <a href="https://github.com/Zorro909/driving_sim_rs">Zorro909</a>; interface and hosting by <a href="https://github.com/seeker-cyber-maker/driving_sim_rs">TiGa</a>. Inspired by the <a href="https://store.steampowered.com/app/3312030/AI_Learns_To_Drive/">game by ActivationFunction</a>. Built-in tracks are reconstructed replicas. For supported conditions, the lab checks the run’s final fitness policy (or frozen input) with a bounded fresh replay. It predicts conditions only and does not award or accumulate original-game stars; opponent races and other unsupported conditions remain unchecked.</p><p>Uploaded files are used for the requested run. Results are held briefly in application memory and deleted after verified download or expiry. Browser recipes contain settings only. <a href="/policy" target="_blank" rel="noopener">Read the data policy</a>.</p><p>The map follows the selected track’s native centerline. Record a short CPU drive to watch an unchanged policy using real vehicle positions. A new recording can differ from an earlier training run. Native control commands and consumed sensor inputs appear in the black box. Ray-hit positions and neural activations are not recorded.</p><p><a id="feedbackLink" href="https://github.com/seeker-cyber-maker/driving_sim_rs/issues/new" target="_blank" rel="noopener">Report a problem</a> · Opens an editable draft for you to review.</p><p id="buildLabel" class="hint">Build: connecting…</p></details>
50
- <details id="agent-interface" class="agent-utility"><summary>Agent tools</summary><p>Use the same local controls as the lab: read the current state, open a section, create a starter, or inspect the active driver. These tools do not submit jobs or save data. <a href="/agents" target="_blank" rel="noopener">Agent interface guide</a> · <a href="/agent-manifest.json" target="_blank" rel="noopener">Action manifest (JSON)</a></p><p id="agent_tools_status" role="status" aria-live="polite">Checking browser tool support…</p><p>The state below is also available to ordinary browser automation. Each listed action identifies a stable control in this page.</p><pre id="agent_state" aria-label="Current Driving Around state (JSON)"></pre></details></div><details id="firstRunGuide" class="quick-start"><summary id="firstRunTitle">New here? Start a first run <span class="hint">Track → driver → settings → run</span></summary><ol class="quick-steps"><li><strong>Choose a track</strong><p>Built-in replica or your own track.</p><button id="first_run_track" type="button">Choose a track</button></li><li><strong>Create a driver</strong><p>Create a starter or upload a driver.</p><button type="button" data-open-tab="drive" data-focus="starter_create">Set up a network</button></li><li><strong>Review the settings</strong><p>Short first-run defaults are ready. Adjust them or save a recipe.</p><button id="first_run_settings" type="button">Review first-run settings</button></li><li><strong>Run and inspect</strong><p>Train, download and replay. A first run may not finish a lap.</p><button type="button" data-open-tab="drive" data-focus="run">Go to run controls</button></li></ol><div class="quick-footer"><a href="/help#start-here" target="_blank" rel="noopener">Read the full step-by-step tutorial ↗</a><button id="quick_start_close" type="button">Close quick start</button></div></details>
51
- <nav class="tabs" role="tablist" aria-label="Driving Around sections"><button type="button" id="tab-drive" role="tab" data-tab="drive" aria-controls="drive" aria-selected="true" tabindex="0">Run &amp; results</button><button type="button" id="tab-training" role="tab" data-tab="training" aria-controls="training" aria-selected="false" tabindex="-1">Training &amp; recipes</button><button type="button" id="tab-batch" role="tab" data-tab="batch" aria-controls="batch" aria-selected="false" tabindex="-1">Batches</button><button type="button" id="tab-editor" role="tab" data-tab="editor" aria-controls="editor" aria-selected="false" tabindex="-1">Network editor</button></nav><div id="drive" class="pane" role="tabpanel" aria-labelledby="tab-drive"><section id="resultSummary" class="card result-summary" hidden aria-labelledby="result_summary_title"><div class="section-heading"><h2 id="result_summary_title" tabindex="-1">Latest run</h2><span id="result_backend" class="pill"></span></div><h3 id="runState" role="status" aria-live="polite">READY — no run started</h3><p id="result_outcome" class="settings-summary"></p><p id="result_driver" class="settings-summary"></p><p id="result_server" class="settings-summary" role="status"></p><div class="result-actions"><button id="download" class="primary" disabled hidden>Download driver</button><button id="saveLocal" class="primary" disabled>Download received driver</button><button id="result_replay" type="button" disabled>Replay selected driver</button><button id="player_report_download" disabled>Download player report (.txt)</button></div><details class="result-exports"><summary>More downloads &amp; server controls</summary><div class="result-actions"><button id="analysis_download" type="button" disabled>Download full analysis archive</button><button id="run_export" disabled>Export run receipt</button><button id="history_csv_download" disabled>Download generation history (.csv)</button><button id="erase" disabled>Delete server-side job data now</button><button id="forgetLocal" disabled>Discard browser result</button></div><p class="privacy-note">The received driver and analysis stay in this page until discarded, replaced, or closed. Save downloads to keep them. Reports describe server-reported measurements; reward weights are configured values, not measured contributions.</p></details><details><summary>Run details</summary><pre id="runSummary" style="white-space:pre-wrap;line-height:1.7" aria-live="polite"></pre></details></section><div class="grid"><section class="card"><h2>Simulation</h2><div class="toolbar" aria-label="Create a starter network"><label for="starter_vehicle">Starter car</label><select id="starter_vehicle"><option value="0" selected>Formula</option><option value="1">Rally</option><option value="2">Snowmobile</option><option value="3">Truck</option></select><button id="starter_create" type="button">Create starter network</button></div><p id="starter_network_status" class="hint" role="status">Creates a small network in this page only. It does not start a run or change saved recipes.</p><label for="run_mode">Action</label><select id="run_mode"><option value="train" selected>Train a population</option><option value="evaluate">Frozen evaluation · one policy, unchanged weights</option></select><p id="run_mode_help" class="hint">Training uses the selected recipe. Frozen evaluation runs the selected policy in a fresh car without changing its weights.</p><button id="run" disabled>Run training</button><p id="starCheckNotice" class="hint">After each run, supported star challenges are checked with unchanged weights. Results are predictions, not game awards. <a href="/help#concepts" target="_blank" rel="noopener">How checks work</a>.</p><p id="setup_next_step" class="hint">Choose or create a driver, then review Training &amp; recipes and start a run.</p><p>Supports Formula, Rally, Snowmobile and Truck networks. Control outputs follow the original vehicle editor rules. Network shape and supported sensors are bounded by the original game contract.</p>
52
- <p id="computeBlock"><label for="backend">Compute</label><select id="backend" disabled><option value="cpu">CPU — no GPU allowance</option><option id="gpuOption" value="gpu" disabled>GPU — uses GPU allowance</option></select></p><p id="backendNote" class="hint">Checking available backends…</p>
53
- <div id="connectionRecovery" hidden><button id="retry" type="button">Reconnect to app</button><p class="hint">Checks server availability. Does not restart training, sign you in, or reset GPU allowance.</p></div>
54
- <div id="gpuAccount" aria-label="Optional GPU account"><p><button id="hfSignIn" type="button" disabled>Sign in with HF for account GPU allowance</button><span id="hfAccount" hidden></span> <button id="hfSignOut" type="button" disabled hidden>Disconnect account</button></p><p id="hfIdentity" role="status" class="hint">CPU needs no sign-in. Checking optional GPU account connection…</p>
55
- <details><summary>Account help &amp; troubleshooting</summary><p>CPU works without an account. HF sign-in identifies GPU requests; it does not guarantee available allowance. Sign in before choosing files: sign-in reloads this page and clears selected files and unsaved edits. Saved recipes remain.</p><p>Your account token stays in page memory. Refreshing or closing this page disconnects the app. Disconnecting here does not sign you out of the HF website or delete job data.</p><button id="hfVerify" type="button" disabled hidden>Check account connection — no GPU used</button><p class="hint">Checks which account the GPU submission service sees. Runs automatically before GPU training; it does not check your remaining allowance.</p></details></div>
56
- <p><label for="trackPresetDrive">Track selection</label><select id="trackPresetDrive" data-track-library disabled><option value="">Upload a custom track</option></select></p>
57
- <p data-track-status role="status" class="hint">Loading built-in replica tracks…</p>
58
-
59
-
60
- <p><label>Track (.track) <input id="track" type="file" accept=".track"></label></p>
61
- <p><label>Vehicle network (.evolution) <input id="network" type="file" accept=".evolution"></label></p>
62
- <p id="networkChoice" role="status">Choose an uploaded file or use a network from the browser editor.</p><p class="privacy-note">Uploads are processed for this run. By default, the server copy is deleted after the browser verifies the download.</p><details><summary>Optional repeat download</summary><label class="keep-result"><input id="keepServer" type="checkbox"> Keep this result on the server for up to five minutes so I can download it again</label><p class="privacy-note">This is optional and resets after each run. When bucket auto-save is on, verified receipt must delete the server copy first, so repeat download is disabled. All results expire after five minutes. <a href="/policy" target="_blank" rel="noopener">Data policy</a></p>
63
- </details></section><section class="card"><h2>Visual replay &amp; car black box</h2><p id="mapStatus" class="map-status" role="status">Loading selected track…</p><button type="button" id="replay_focus" aria-pressed="false">Expand replay workspace</button><div class="replay-bar" id="replayControls" tabindex="-1" aria-label="Recorded drive controls">
64
  <div class="replay-row"><button type="button" id="replay_record" disabled>Record selected policy</button><label for="replay_duration" style="margin:0">Length</label><select id="replay_duration"><option value="300" selected>5 seconds</option><option value="900">15 seconds</option></select><button type="button" id="replay_download" disabled>Download recording</button><label for="replay_import">Open recording<input type="file" id="replay_import" accept=".json,application/json" disabled></label></div>
65
  <p id="replay_policy" class="hint">Choose or create a network to record a drive.</p>
66
  <p class="hint">Fresh CPU drive, including for GPU-trained drivers · unchanged weights · 60 Hz decisions. Playback uses measured samples in your browser.</p>
67
  <p id="replay_loaded" class="recording-identity" role="status" aria-live="polite" hidden></p>
68
  <details><summary>What does this recording show?</summary><p>A single fresh CPU drive records native state, raw and normalized control commands, and the exact cached sensor inputs every 0.1 seconds. Physics and policy decisions run at 60 Hz. Playback starts paused and shows measured poses by default; optional pose smoothing only interpolates between adjacent measured samples. It does not simulate the car. Black-box values always remain at an actual recorded sample. Ray-hit positions, skid marks and hidden-layer activations are not recorded. This is a selected-policy CPU replay, including for GPU-trained policies; it is not a recording of the original training population.</p><p>The recording remains in this page until replaced, cleared by a changed selection, or the page is closed. Use Download recording to keep its measured samples.</p></details>
69
- </div><div class="replay-workbench" id="replay_workspace"><div class="replay-viewer"><div class="map"><canvas id="trackMap" width="1000" height="500" role="img" aria-label="Selected track tile layout and terrain"></canvas></div><div class="replay-bar replay-playback"><div class="replay-row" id="replay_transport" role="group" aria-label="Playback controls" tabindex="-1"><button type="button" id="replay_play" disabled>Play</button><button type="button" id="replay_reset" disabled>Restart</button><button type="button" id="replay_prev" disabled>Previous sample</button><button type="button" id="replay_next" disabled>Next sample</button><input type="range" id="replay_scrub" min="1" max="300" value="1" disabled aria-label="Replay tick scrubber"><span id="replay_time_label" class="replay-time">No recording</span></div>
70
  <details class="replay-options"><summary>Camera, speed &amp; recorded events</summary><div class="replay-row" style="margin-top:8px"><label for="replay_camera" style="margin:0">Camera</label><select id="replay_camera" aria-label="Replay camera mode" disabled><option value="full" selected>Full circuit</option><option value="follow">Follow car</option></select><label for="replay_speed" style="margin:0">Speed</label><select id="replay_speed" aria-label="Replay playback speed" disabled><option value="0.25">0.25×</option><option value="0.5">0.5×</option><option value="1" selected>1×</option><option value="2">2×</option></select></div>
71
  <div class="replay-layers"><label><input type="checkbox" id="replay_layer_outline" checked disabled> Car outline</label><label><input type="checkbox" id="replay_layer_line" checked disabled> Recorded path</label><label><input type="checkbox" id="replay_layer_hud" checked disabled> Recorded telemetry</label></div>
72
  <div class="replay-row"><label><input type="checkbox" id="replay_interpolate" disabled> Smooth pose between measured samples</label><label for="replay_event">Contact / active-state interval</label><select id="replay_event" aria-label="Recorded event interval" disabled><option value="">No recording</option></select></div>
73
 
74
  </details><p id="replay_readout" style="font-size:16px;font-variant-numeric:tabular-nums" aria-live="off"></p>
 
75
  <p id="replay_status" role="status">No replay recorded. The map shows the selected track and its saved starting point.</p></div></div><section id="replay_blackbox" tabindex="-1" hidden aria-label="Recorded car black box"><div class="section-heading"><h3>Car black box</h3><a href="#replay_transport">Back to playback</a></div><p id="blackbox_phase" class="hint"></p>
76
  <p class="hint">All values below belong to the selected native sample. Sensor inputs were consumed before physics at the decision tick; vehicle state is captured after physics. Samples are 0.1 seconds apart. Contact events identify intervals, not exact impact ticks; the counter does not count unique crashes.</p>
77
  <details><summary>Recorded vehicle state</summary><div class="table-scroll"><table><thead><tr><th>Vehicle state</th><th>Recorded value</th></tr></thead><tbody id="blackbox_state"></tbody></table></div></details>
@@ -96,14 +303,14 @@
96
  <section id="starCheckPanel" class="card" hidden aria-labelledby="starCheckTitle"><h2 id="starCheckTitle">Star challenge check</h2><p id="starCheckStatus" role="status" aria-live="polite"></p><div id="starCheckDetails" hidden><p id="starCheckPolicy" class="hint"></p><p id="starCheckBasis" class="hint"></p><p id="starCheckConditions" class="hint"></p><div class="table-scroll"><table><thead><tr><th>Challenge</th><th>Result</th><th>Reason</th><th>Completion time</th></tr></thead><tbody id="starCheckRows"></tbody></table></div><p class="hint">This is an independent check of the named run policy. It does not grant or accumulate original-game stars; replica challenges may differ from the original game.</p></div></section>
97
  <label class="keep-result"><input id="leaderboard_opt_in" type="checkbox"> After a completed lap, check its position against the public Steam leaderboard</label><p class="privacy-note">Optional, read-only check for supported built-in tracks. It sends the track ID and best lap to this app server; Steam receives only a public leaderboard read. No score is submitted. The result is an estimate, not an official rank.</p><p id="leaderboard_status" role="status" aria-live="polite"></p>
98
 
99
- <details id="portableBundle"><summary>Portable bucket bundle</summary><p>Build, export, or restore one validated bundle. Bucket storage is optional. When connected, automatic save is on by default; turn it off here to keep saves manual. Disconnected runs never call bucket storage.</p><label><input id="bundle_track" type="checkbox"> Include the selected track</label><label><input id="bundle_recipe" type="checkbox"> Include the recipe in the selected slot, if saved</label><label><input id="bundle_receipt" type="checkbox"> Include a sanitized receipt for the selected completed result</label><div class="toolbar"><button id="bundle_export" type="button">Export portable bundle</button><label for="bundle_import">Restore portable bundle (.json)<input id="bundle_import" type="file" accept=".json,application/json"></label><button id="bundle_receipt_download" type="button" disabled>Download staged receipt</button></div><p id="bundle_status" role="status" aria-live="polite">No bucket action has been requested.</p>
100
- <details id="bucketStorage"><summary>Connect to an existing private bucket</summary><p>Bucket storage is optional. Authorizing storage also identifies your account for GPU requests; ordinary GPU sign-in remains available with the basic identity permission. Then enter your existing private bucket ID. Connected runs automatically save by default; uncheck this option to keep run saves manual. No personal token is requested or stored.</p><p id="bucket_scope_notice" class="privacy-note">HF describes the requested <code>write-repos</code> permission as read/write access to your personal repositories. That grant is broader than one selected bucket and is not a bucket-only permission; the app limits its own operations to the bucket you enter. The minimum current scope for bucket read/write has not been confirmed by HF.</p><button id="bucket_authorize" type="button" hidden disabled>Authorize bucket access with HF</button><p id="bucket_auth_unavailable" class="hint" hidden>HF bucket authorization is unavailable for this app. Local bundle export remains available.</p><p id="bucket_auth_status" role="status" aria-live="polite">Checking optional HF bucket authorization…</p><div id="bucketConnectForm" hidden><label for="bucket_id">Private bucket ID</label><input id="bucket_id" type="text" autocomplete="off" placeholder="username/bucket-name" disabled><button id="bucket_connect" type="button" disabled>Connect bucket</button></div><div id="bucketConnected" hidden><p id="bucket_account"></p><label class="keep-result"><input id="bucket_autosave" type="checkbox" checked> Automatically save every verified completed network and run log to this bucket</label><p class="hint">For each completed run, the browser fetches and verifies the network, then confirms server deletion before sending the network and sanitized log to your bucket. If deletion is not confirmed, no save occurs. If bucket saving is not confirmed, the verified local candidate stays available to download or retry; the remote save may have completed. Each batch step saves before the next starts, and a failed save stops the batch.</p><button id="bucket_disconnect" type="button">Disconnect bucket and clear HF authorization</button><div class="toolbar"><button id="bucket_save" type="button" disabled>Save selected bundle</button><button id="bucket_refresh" type="button" disabled>Refresh saved bundles</button></div><label for="bucket_items">Saved bundles from this app</label><select id="bucket_items" size="4" disabled><option value="">Refresh to list saved bundles</option></select><button id="bucket_restore" type="button" disabled>Restore selected bundle</button><hr><h3 id="bucketRecipeTitle" tabindex="-1">Recipe library (settings only)</h3><p class="hint">Save and import the validated recipes and batch definitions from this browser. This 32 KB library contains settings only; networks, tracks, run results and access tokens are never included. Import asks before replacing the local recipe library and never starts a run.</p><div class="toolbar"><button id="bucket_recipe_save" type="button" disabled>Save recipe library</button><button id="bucket_recipe_refresh" type="button" disabled>Refresh saved recipe libraries</button></div><label for="bucket_recipe_items">Saved recipe libraries</label><select id="bucket_recipe_items" size="4" disabled><option value="">Refresh to list saved recipe libraries</option></select><button id="bucket_recipe_import" type="button" disabled>Import selected recipe library</button><p id="bucket_recipe_status" role="status" aria-live="polite">No recipe library bucket action requested.</p></div><p id="bucket_status" role="status" aria-live="polite">Not connected. Bucket storage is optional.</p></details></details>
101
  <p id="deadline"></p><p id="status" role="status">Ready. Inputs remain on this device until you run the test.</p>
102
  <details><summary>Effective training settings</summary><pre id="effectiveSettings"></pre></details><details><summary>Generation results</summary><pre id="generationHistory"></pre></details><details><summary>About star challenge checks</summary><p>After a run, supported conditions are checked against its named policy with a bounded fresh replay. Results appear in the Star challenge check panel when available. These are predictions for the reconstructed replica track, not original-game awards; opponent races and unsupported conditions are left unchecked.</p></details></section></div>
103
  </div><section id="training" class="pane" role="tabpanel" aria-labelledby="tab-training" hidden><div class="card">
104
  <div class="section-heading"><h2 id="trainingTitle" tabindex="-1">Training &amp; recipes</h2><a href="/help#recipes" target="_blank" rel="noopener">How recipes work ↗</a></div><p class="section-intro">A recipe saves training settings and rewards. Apply one to this form, or adjust the settings below and save your own. Choose your track and starting network in Run &amp; results.</p>
105
  <div id="libraries" class="recipe-panel"><div class="row"><label for="recipe_slot">Recipe slot<select id="recipe_slot"><option value="A">A · Empty</option><option value="B">B · Empty</option><option value="C">C · Empty</option><option value="D">D · Empty</option><option value="E">E · Empty</option><option value="F">F · Empty</option><option value="G">G · Empty</option><option value="H">H · Empty</option><option value="I">I · Empty</option><option value="J">J · Empty</option></select></label><label for="recipe_name">Recipe name<input id="recipe_name" type="text" maxlength="80" value="First practice" placeholder="e.g. First laps"></label></div>
106
- <p id="recipe_state" class="form-state" role="status" aria-live="polite">Working settings · not saved yet</p><p id="recipe_summary" class="settings-summary"></p><div class="recipe-actions"><button id="recipe_load" type="button" disabled>Apply recipe</button><button id="recipe_save" type="button">Save settings to A</button><button type="button" data-open-tab="batch" data-focus="batch_add_recipe">Build a batch</button></div><p id="recipe_feedback" role="status" aria-live="polite"></p>
107
  <details><summary>Import, export &amp; manage recipes</summary><p class="muted-note">Recipes and batches are saved in this browser. Export a backup to move them to another browser or site. Clearing site data removes this library.</p><div class="manage-actions"><button id="recipe_export" type="button">Export recipe library</button><label for="recipe_import">Import recipe library (.json)<input id="recipe_import" type="file" accept=".json"></label><button id="recipe_bucket_nav" type="button">Bucket import / export</button></div><button id="recipe_clear" class="destructive-action" type="button">Clear saved recipes and batches on this device</button><p class="muted-note">The recipe library contains settings only. Saving a recipe does not start a run or upload tracks, networks, or results.</p></details>
108
  <details><summary>Advanced recipe JSON</summary><textarea id="recipe_draft" rows="12" aria-label="Recipe settings JSON"></textarea><button id="recipe_apply_draft" type="button">Apply JSON to form</button></details></div>
109
  <div class="section-heading"><h3>Settings for the next run</h3><button id="starter_settings_reset" type="button">Apply first-run settings to this form</button></div><p id="starter_settings_status" class="muted-note" role="status" aria-live="polite">Adjusting this form does not change a saved recipe until you save it.</p><div class="subtab-bar" id="trainingSubtabs" role="toolbar" aria-label="Filter training parameter sections"><button type="button" data-train-filter="all" aria-pressed="true">All sections</button><button type="button" data-train-filter="reward_settings" aria-pressed="false">Rewards (14 metrics)</button><button type="button" data-train-filter="native_settings" aria-pressed="false">Evolution &amp; mutation</button><button type="button" data-train-filter="run_settings" aria-pressed="false">Timing &amp; elimination</button><button type="button" data-train-filter="freeze_settings" aria-pressed="false">Selective freezing</button></div><div class="training-track"><label for="trackPresetTraining">Training track · shared with Run &amp; results</label><select id="trackPresetTraining" data-track-library disabled><option value="">Upload a custom track</option></select><p data-track-status role="status" class="hint">Loading built-in replica tracks…</p></div>
@@ -128,7 +335,7 @@
128
  <label for="reward_preset">Reward preset</label><select id="reward_preset" disabled><option value="custom">Custom</option><option value="distance" selected>First laps · distance only (+100 total score)</option><option value="center">Example mix · center, clearance, collisions</option><option value="clean">Clean driving · distance + collision penalty</option><option value="lap">Lap refinement · best lap only</option></select>
129
  <div id="rewards"></div><button id="add" disabled>+ Add reward</button><small>Weights −100…+100; absolute shares normalize to 100%. Fourteen distinct metrics maximum. The current vehicle runner accepts these metrics; choose them for the behavior you want to train.</small>
130
  </details></div>
131
- <details id="run_settings"><summary>Run settings · timing and elimination</summary><div class="row"><div><label for="control_hz">Decisions per second</label><select id="control_hz" disabled><option selected>60</option><option>30</option><option>15</option></select></div><div><label for="workers">Parallel simulations</label><select id="workers" disabled><option>1</option><option selected>1</option><option>2</option><option>3</option><option>4</option></select></div></div><small>Physics runs at 60 Hz. CPU jobs can use 1–4 worker threads.</small><div id="seed_group"><label for="seed">Random seed</label><input id="seed" type="number" min="0" max="2147483647" value="42105" disabled></div><label><input id="collision" type="checkbox" disabled> Eliminate on wall contact</label><label><input id="idle" type="checkbox" disabled> Eliminate when stuck</label><label for="clean_min_laps">Minimum forward laps for a clean-lap winner</label><input id="clean_min_laps" type="number" min="1" max="100" value="2"><small>Winner classification only. Zero physical contacts are required. This does not change your reward recipe.</small></details></div></div></section>
132
  <section id="batch" class="pane" role="tabpanel" aria-labelledby="tab-batch" hidden><div class="card"><div class="section-heading"><h2>Training batches</h2><a href="/help#batches" target="_blank" rel="noopener">How batches work ↗</a></div><p class="section-intro">Arrange saved recipes into a sequence of up to 20 training steps. Use the same recipe more than once to keep training with those settings.</p><div class="batch-layout"><div>
133
  <div class="row"><label for="batch_slot">Batch slot<select id="batch_slot" disabled><option value="A">A · Empty</option><option value="B">B · Empty</option><option value="C">C · Empty</option><option value="D">D · Empty</option><option value="E">E · Empty</option><option value="F">F · Empty</option><option value="G">G · Empty</option><option value="H">H · Empty</option><option value="I">I · Empty</option><option value="J">J · Empty</option></select></label><label for="batch_name">Batch name<input id="batch_name" type="text" maxlength="80" value="My training batch" disabled></label></div><p id="batch_draft_state" class="form-state" role="status" aria-live="polite">New batch · not saved yet</p><div class="batch-actions"><button id="batch_save" type="button" disabled>Save batch</button><button id="batch_load" type="button" disabled>Load saved batch</button></div>
134
  <label class="batch-mode"><input id="carry" type="checkbox" checked disabled> Use each step’s result to train the next step</label><p id="batch_carry_help" class="muted-note">Step 1 uses your selected network. Later steps continue from the previous step’s result.</p>
@@ -198,7 +405,8 @@
198
  save(book){const clean=validate(book),text=JSON.stringify(clean);if(new TextEncoder().encode(text).byteLength>32768)throw Error('Recipe library exceeds 32 KB');storage.setItem(KEY,text);return clean;},
199
  clear(){storage.removeItem(KEY);},
200
  };}
201
- const api={KEY,defaults,metrics,settings,validate,parse,createStore};
 
202
  if(typeof module!=='undefined'&&module.exports)module.exports=api;else root.RecipeLibrary=api;
203
  })(typeof window!=='undefined'?window:globalThis);
204
  </script><script>/* Frozen settings-only plans; execution and stop checks are injected. */
@@ -209,6 +417,7 @@
209
  if(!batch)throw Error('Save or load a batch first');
210
  if(batch.runs.length>20)throw Error('Execution limit: 20 runs per batch');
211
  const runs=batch.runs.map(slot=>JSON.parse(JSON.stringify(library.recipes.find(r=>r.slot===slot))));
 
212
  const work=runs.reduce((n,r)=>n+r.settings.population*r.settings.generations*r.settings.ticks,0);
213
  if(runs.some(r=>r.settings.population*r.settings.generations*r.settings.ticks>workLimit||r.settings.population*r.settings.generations>32768))throw Error('A batch step exceeds this backend’s vehicle-tick or analysis-row limit; split that recipe into shorter runs');
214
  return {slot:batch.slot,name:batch.name,carry:batch.carry,runs,work};
@@ -218,6 +427,7 @@
218
  for(let i=0;i<plan.runs.length;i++){
219
  if(stopped())return {state:'stopped',candidate,history};
220
  const recipe=plan.runs[i],source=plan.carry&&candidate!==null?candidate:original;
 
221
  const result=await process(source,recipe.settings,i);
222
  if(!result||!result.candidate)throw Error('No validated batch candidate');
223
  candidate=result.candidate;
@@ -371,7 +581,7 @@
371
  }
372
  function currentSettings(){
373
  const data={};for(const name of fields)data[name]=booleans.includes(name)?q(name).checked:strings.includes(name)?q(name).value:Number(q(name).value);
374
- data.ticks=Number(q('training_ticks').value);data.rewards=rewards();data.freeze={layers:[...selectedFreeze.layers],inputs:[...selectedFreeze.inputs],outputs:[...selectedFreeze.outputs]};return api.settings(data);
375
  }
376
  function updateWorkBudget(){
377
  const p=Number(q('population').value),g=Number(q('generations').value),t=Number(q('training_ticks').value),box=q('work_budget');
@@ -390,7 +600,7 @@
390
  return data;
391
  }
392
  function applySettings(value){
393
- const data=api.settings(value);
394
  for(const name of fields){if(booleans.includes(name))q(name).checked=data[name];else q(name).value=data[name];}
395
  q('training_ticks').value=data.ticks;q('rewards').replaceChildren();data.rewards.forEach(rewardRow);
396
  for(const kind of ['layers','inputs','outputs'])selectedFreeze[kind]=[...data.freeze[kind]];renderFreeze();
@@ -409,7 +619,14 @@
409
  };
410
  window.stagePortableRecipe=recipe=>{
411
  if(!recipe||! /^[A-J]$/.test(recipe.slot)||typeof recipe.name!=='string'||!recipe.name.trim()||recipe.name.length>80)throw Error('Invalid selected recipe');
412
- const settings=api.settings(recipe.settings);q('recipe_slot').value=recipe.slot;q('recipe_name').value=recipe.name.trim();
 
 
 
 
 
 
 
413
  applySettings(settings);q('preset').value='custom';q('reward_preset').value='custom';stagedPortableRecipe=true;
414
  message('Imported recipe staged in the training form. Save it explicitly to add it to this browser’s recipe library. No run started.');
415
  };
@@ -469,6 +686,7 @@
469
  const maximum=q('backend')?.value==='gpu'?8000000:4000000;
470
  for(let i=0;i<draft.runs.length;i++){
471
  const recipe=book.recipes.find(item=>item.slot===draft.runs[i]),settings=recipe.settings,work=settings.population*settings.generations*settings.ticks,rows=settings.population*settings.generations;
 
472
  if(work>maximum||rows>32768)return {ready:false,message:'Step '+(i+1)+' · '+recipe.slot+' · '+recipe.name+' exceeds this compute limit ('+work.toLocaleString()+' vehicle-ticks; '+rows.toLocaleString()+' analysis rows). Shorten that recipe in Training & recipes.'};
473
  }
474
  return {ready:true,message:'Saved batch matches the steps shown. Ready to run '+draft.runs.length+' '+(draft.runs.length===1?'step':'steps')+'.'};
 
21
  <p id="appConfirmMessage"></p>
22
  <div class="actions"><button id="appConfirmCancel" type="button">Cancel</button><button id="appConfirmAccept" type="button">Continue</button></div>
23
  </dialog>
24
+ <script id="driver-first-controller">
25
+ /* Presentation only. The existing client remains responsible for all loading,
26
+ authentication, jobs, and files. No tokens are read or stored here. */
27
+ (function(root){
28
+ 'use strict';
29
+ const RATE=60;
30
+ const message='New training and evaluation runs require 60 Hz decisions and 60 Hz physics. Historical results keep their original timing.';
31
+ function assertTiming(settings){
32
+ if(!settings||settings.control_hz!==RATE)throw Error(message);
33
+ return settings;
34
+ }
35
+ function convertLibrary(book,slot){
36
+ const recipe=book?.recipes?.find(r=>r.slot===slot);
37
+ if(!recipe)throw Error('Choose a saved recipe first.');
38
+ if(recipe.settings.control_hz===RATE)throw Error('This recipe already uses 60 Hz.');
39
+ if(![30,15].includes(recipe.settings.control_hz))throw Error('Unsupported historical timing.');
40
+ const used=new Set(book.recipes.map(r=>r.slot));
41
+ const free='ABCDEFGHIJ'.split('').find(k=>!used.has(k));
42
+ if(!free)throw Error('No empty recipe slot. Export a backup and free one slot before making a 60 Hz copy.');
43
+ const clone=JSON.parse(JSON.stringify(book));
44
+ const newRecipe={slot:free,name:(recipe.name.slice(0,64)+' (60 Hz copy)').slice(0,80),settings:JSON.parse(JSON.stringify(recipe.settings))};
45
+ newRecipe.settings.control_hz=RATE;
46
+ clone.recipes.push(newRecipe);
47
+ return {book:clone,recipe:newRecipe};
48
+ }
49
+ const api={RATE,message,assertTiming,convertLibrary};
50
+ if(typeof module!=='undefined'&&module.exports){module.exports=api;return;}
51
+ root.DriverFirst=Object.assign(root.DriverFirst||{},api);
52
+ const byId=id=>document.getElementById(id);
53
+ let sourceTouched=false,lastConnected=false,scheduled=false;
54
+ function visibleAncestors(node){
55
+ for(let p=node?.parentElement;p;p=p.parentElement)if(p.tagName==='DETAILS')p.open=true;
56
+ }
57
+ function chooseSource(kind,{focus=false,explicit=false}={}){
58
+ if(explicit)sourceTouched=true;
59
+ for(const source of ['device','bucket']){
60
+ const chosen=source===kind,button=byId('driver_source_'+source),panel=byId('driver_'+source+'_panel');
61
+ if(button){button.setAttribute('aria-selected',String(chosen));button.tabIndex=chosen?0:-1;}
62
+ if(panel)panel.hidden=!chosen;
63
+ }
64
+ if(kind==='bucket'&&byId('bucketStorage'))byId('bucketStorage').open=true;
65
+ if(focus)byId('driver_source_'+kind)?.focus();
66
+ }
67
+ function refresh(){
68
+ scheduled=false;
69
+ const connected=!!byId('bucketConnected')&&!byId('bucketConnected').hidden;
70
+ if(connected&&!lastConnected&&!sourceTouched)chooseSource('bucket');
71
+ lastConnected=connected;
72
+ const bucketButton=byId('driver_source_bucket');
73
+ if(bucketButton)bucketButton.textContent=connected?'Saved in bucket · connected':'Saved in bucket';
74
+ const recipeSummary=byId('recipe_summary')?.textContent;
75
+ if(byId('run_recipe_summary'))byId('run_recipe_summary').textContent=recipeSummary||'Use the current training settings, or choose a saved recipe.';
76
+ // This value is displayed only from the existing client's own selected state.
77
+ const selected=root.DriverFirst.selectedName;
78
+ if(byId('driver_current_name'))byId('driver_current_name').textContent=selected||'No driver selected';
79
+ const button=byId('recipe_convert_60');
80
+ if(button&&root.RecipeLibrary){
81
+ try{
82
+ const book=root.RecipeLibrary.createStore(root.localStorage).load();
83
+ const recipe=book.recipes.find(r=>r.slot===byId('recipe_slot')?.value);
84
+ button.hidden=!recipe||recipe.settings.control_hz===RATE;
85
+ button.disabled=!!byId('recipe_slot')?.disabled;
86
+ if(recipe&&recipe.settings.control_hz!==RATE)button.textContent='Make a 60 Hz copy of '+recipe.slot+' ('+recipe.settings.control_hz+' Hz)';
87
+ }catch{button.hidden=true;}
88
+ }
89
+ }
90
+ function schedule(){if(!scheduled){scheduled=true;queueMicrotask(refresh);}}
91
+ root.DriverFirst.update=name=>{root.DriverFirst.selectedName=name||null;schedule();};
92
+ function mount(){
93
+ if(!byId('driver_device_panel'))return;
94
+ const sourceButtons=['device','bucket'].map(k=>byId('driver_source_'+k));
95
+ sourceButtons.forEach((button,i)=>{
96
+ button.addEventListener('click',()=>chooseSource(i?'bucket':'device',{explicit:true}));
97
+ button.addEventListener('keydown',event=>{
98
+ if(!['ArrowLeft','ArrowRight','Home','End'].includes(event.key))return;
99
+ event.preventDefault();const next=event.key==='Home'?0:event.key==='End'?1:1-i;
100
+ chooseSource(next?'bucket':'device',{explicit:true,focus:true});
101
+ });
102
+ });
103
+ byId('network')?.addEventListener('change',()=>{chooseSource('device',{explicit:true});schedule();});
104
+ byId('run_edit_settings')?.addEventListener('click',()=>{
105
+ byId('tab-training')?.click();byId('trainingTitle')?.focus();
106
+ });
107
+ byId('driver_inspect')?.addEventListener('click',()=>{
108
+ byId('tab-editor')?.click();const b=byId('editor_import');if(b&&!b.disabled)b.click();byId('editor_status')?.focus();
109
+ });
110
+ byId('driver_advanced_create')?.addEventListener('click',()=>{byId('tab-editor')?.click();byId('editor_preset')?.focus();});
111
+ byId('first_run_driver')?.addEventListener('click',()=>{
112
+ byId('tab-drive')?.click();byId('driver_current_name')?.scrollIntoView({block:'center'});
113
+ const button=sourceButtons.find(b=>b.getAttribute('aria-selected')==='true');button?.focus();
114
+ });
115
+ byId('backend')?.addEventListener('change',()=>{if(byId('gpuAccountHelp'))byId('gpuAccountHelp').open=byId('backend').value==='gpu';});
116
+ // Existing navigation may open the old details location. Follow the same
117
+ // action to the moved bucket panel without invoking a network/storage call.
118
+ byId('recipe_bucket_nav')?.addEventListener('click',()=>{
119
+ chooseSource('bucket',{explicit:true});visibleAncestors(byId('bucketRecipeTitle'));
120
+ });
121
+ root.addEventListener('ald:legacy-recipe',event=>{
122
+ const node=byId('legacy_timing_notice');
123
+ if(node)node.textContent='Driver restored. Its saved recipe used '+event.detail.control_hz+' Hz and was not applied. The next run remains at 60 Hz. The original receipt is unchanged; make a 60 Hz recipe copy for a new experiment.';
124
+ });
125
+ const convert=byId('recipe_convert_60');
126
+ if(convert)convert.addEventListener('click',async()=>{
127
+ const feedback=byId('recipe_feedback');
128
+ try{
129
+ if(byId('recipe_slot').disabled)throw Error('Finish the current operation before changing recipes.');
130
+ const store=root.RecipeLibrary.createStore(root.localStorage),before=store.load(),slot=byId('recipe_slot').value;
131
+ const candidate=convertLibrary(before,slot);
132
+ if(!(await root.appConfirm('Create '+candidate.recipe.slot+' · '+candidate.recipe.name+'? The original recipe and its batches remain unchanged. This is a new 60 Hz experiment, not a replay of the earlier timing.',{heading:'Make a 60 Hz recipe copy',confirmLabel:'Create separate copy'})))return;
133
+ if(byId('recipe_slot').disabled||JSON.stringify(store.load())!==JSON.stringify(before))throw Error('The library or operation state changed. No copy was saved; review and try again.');
134
+ store.save(root.RecipeLibrary.validate(candidate.book));
135
+ byId('recipe_slot').value=candidate.recipe.slot;
136
+ byId('recipe_slot').dispatchEvent(new Event('change',{bubbles:true}));
137
+ byId('recipe_load').click();
138
+ if(feedback)feedback.textContent='Created and applied '+candidate.recipe.slot+' · '+candidate.recipe.name+'. Original recipe, batches and historical results are unchanged. No run started.';
139
+ }catch(error){if(feedback)feedback.textContent='Not completed: '+error.message;}
140
+ schedule();
141
+ });
142
+ const observer=new MutationObserver(schedule);
143
+ for(const id of ['bucketConnected','recipe_summary','recipe_slot','networkChoice']){
144
+ const node=byId(id);if(node)observer.observe(node,{attributes:true,childList:true,subtree:true,characterData:true});
145
+ }
146
+ document.addEventListener('change',schedule);
147
+ root.addEventListener('ald:batch-draft-change',schedule);
148
+ root.addEventListener('storage',schedule);
149
+ chooseSource('device');refresh();
150
+ }
151
+ if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',mount,{once:true});else mount();
152
+ })(typeof window!=='undefined'?window:globalThis);
153
+
154
+ </script>
155
  <script>
156
  (() => {
157
  const dialog=document.getElementById('appConfirm'),title=document.getElementById('appConfirmTitle');
 
175
  </script>
176
  <style>/* A small pixel-workshop accent; all workspace controls retain their layout. */
177
  .lab-header{border-top:4px solid #f1c66d;padding-top:12px}.lab-header .eyebrow{color:#f1c66d;letter-spacing:.14em}.lab-header h1{font-family:ui-monospace,SFMono-Regular,Consolas,monospace;letter-spacing:-.04em;text-shadow:2px 2px #284539}.brand-copy{min-width:0;max-width:100%}.brand-question{font-size:14px;line-height:1.5;color:#d4e6d9;margin:9px 0 0;max-width:65ch}.lab-header .header-actions{align-self:center}.lab-header .help-link{border-radius:4px;box-shadow:3px 3px #284539}
178
+ </style>
179
+ <style id="driver-first-style">
180
+ /* Driver-first workspace. Existing controls and backend handlers are retained. */
181
+ .driver-setup { min-width:0; }
182
+ .driver-setup > h2 { margin-bottom:4px; }
183
+ .driver-setup .setup-intro { margin:0 0 20px;color:#b9cddd;line-height:1.55; }
184
+ .driver-setup .setup-step { margin:0;padding:20px 0;border:0;border-top:1px solid #30475d;min-width:0; }
185
+ .driver-setup .step-title { display:flex;align-items:center;gap:10px;margin:0 0 14px;font-size:18px;letter-spacing:-.015em; }
186
+ .driver-setup .step-marker { display:grid;place-items:center;width:27px;height:27px;flex:none;border:1px solid #426453;border-radius:8px;color:#9aeac9;background:#17392f;font-size:13px;font-variant-numeric:tabular-nums; }
187
+ .driver-setup .driver-sources { display:grid;grid-template-columns:1fr 1fr;gap:8px;margin:0 0 12px; }
188
+ .driver-setup .driver-sources button { padding:12px 8px;min-height:46px;line-height:1.4;border-radius:8px; }
189
+ .driver-setup .driver-sources [aria-selected=true] { color:#dcfff0;border-color:#77dcb1;background:#213e38;box-shadow:inset 0 -2px #77dcb1; }
190
+ .driver-setup .source-panel { padding:14px;border:1px solid #36516a;border-radius:10px;background:#0d1a29; }
191
+ .driver-setup .source-panel > p:first-child { margin-top:0; }
192
+ .driver-setup .source-panel label { margin-top:0;line-height:1.6; }
193
+ .driver-setup .source-panel input[type=file] { width:100%;font-size:14px;padding:14px 10px;margin-top:8px;min-height:52px;border-style:dashed;background:#111f2e; }
194
+ .driver-setup .source-panel input::file-selector-button { font:inherit;font-weight:650;padding:8px 11px;margin-right:10px;border:1px solid #4c687e;border-radius:5px;color:#e9f3fa;background:#203448;cursor:pointer; }
195
+ .driver-setup .selected-driver { margin:12px 0;padding:13px 14px;background:#142c2a;border:1px solid #355e52;border-radius:9px;overflow-wrap:anywhere; }
196
+ .driver-setup .selected-driver .mini-label { color:#b5d2c6;font-size:12px;letter-spacing:.09em;text-transform:uppercase;font-weight:700; }
197
+ .driver-setup #driver_current_name { margin:5px 0;font-weight:700;font-size:15px;line-height:1.45;color:#f2fff8; }
198
+ .driver-setup #networkChoice { font-size:13px;line-height:1.5;color:#bed4cb;margin:4px 0 0; }
199
+ .driver-setup details { margin-top:12px;padding-top:10px; }
200
+ .driver-setup details > summary { min-height:44px;display:flex;align-items:center;cursor:pointer; }
201
+ .driver-setup #createDriver { border-top:0;padding:0;margin:10px 0 0; }
202
+ .driver-setup #createDriver > summary { font-size:14px;color:#c2d5e5; }
203
+ .driver-setup #createDriver > summary::before { content:'+';font-size:18px;margin-right:9px;color:#a6c5b5; }
204
+ .driver-setup #createDriver[open] > summary::before { content:'−'; }
205
+ .driver-setup #createDriver .toolbar { margin:0;padding:10px 0 14px;gap:10px; }
206
+ .driver-setup #createDriver .toolbar select { width:auto;flex:1;min-width:135px; }
207
+ .driver-setup #starter_network_status { font-size:13px;margin-top:0; }
208
+ .driver-setup #bucketStorage { border:0;margin:0;padding:0; }
209
+ .driver-setup #bucketStorage > summary { display:none; }
210
+ .driver-setup #bucketStorage #bucketConnected > .bucket-picker { padding-top:0; }
211
+ .driver-setup #bucket_items { width:100%;min-height:112px;font-size:14px;line-height:1.5; }
212
+ .driver-setup #bucket_items option { padding:8px; }
213
+ .driver-setup .bucket-load-actions { display:flex;gap:10px;align-items:center;flex-wrap:wrap;margin-top:12px; }
214
+ .driver-setup #bucket_restore { flex:1;font-weight:700;border-color:#62dfb1; }
215
+ .driver-setup #bucket_account { font-size:13px;overflow-wrap:anywhere;color:#9de2bf; }
216
+ .driver-setup #bucket_status { font-size:13px;line-height:1.55; }
217
+ .driver-setup .bucket-settings { font-size:14px; }
218
+ .driver-setup #bucketConnectForm { margin:12px 0; }
219
+ .driver-setup #bucket_connect { margin-top:10px; }
220
+ .driver-setup .settings-link { margin:10px 0 0;min-height:44px;width:100%;text-align:left;color:#d8f6e8;background:#112d28;border-color:#345c50; }
221
+ .driver-setup .run-facts { display:flex;gap:10px;flex-wrap:wrap;font-size:13px;color:#c8dfd3;padding:11px 0;margin:0; }
222
+ .driver-setup .run-facts span { border:1px solid #38564d;border-radius:6px;padding:5px 8px;background:#142c27; }
223
+ .driver-setup #run_recipe_summary { font-size:14px;line-height:1.6;color:#b9cddd;margin:9px 0; }
224
+ .driver-setup #computeBlock { margin:12px 0 0; }
225
+ .driver-setup #gpuAccount { margin-top:12px; }
226
+ .driver-setup #gpuAccountHelp { margin:8px 0 0; }
227
+ .driver-setup .run-footer { border-top:1px solid #35564c;padding-top:14px;margin-top:8px; }
228
+ .driver-setup #run { margin-top:6px;min-height:54px;border-radius:9px;letter-spacing:.01em;font-size:16px; }
229
+ .driver-setup #setup_next_step { font-size:13px;line-height:1.6;margin:10px 0 2px; }
230
+ .driver-setup #status { font-size:14px;overflow-wrap:anywhere; }
231
+ .fixed-rate { display:block;border:1px solid #3c6555;background:#143229;color:#b9f4d8;padding:12px 14px;border-radius:8px;font-size:14px;line-height:1.5; }
232
+ .timing-warning { border:1px solid #96763d;background:#302719;color:#ffe2a8;border-radius:9px;padding:12px 14px;font-size:14px;line-height:1.6;margin:12px 0; }
233
+ .timing-warning:empty { display:none; }
234
+ #recipe_convert_60 { border-color:#bd9958;color:#ffe2a8;min-height:44px;margin-top:10px; }
235
+ .driver-setup .source-panel[hidden], .driver-setup [hidden] { display:none!important; }
236
+ .driver-setup #trackPresetDrive { margin:0; }
237
+ .driver-setup p[data-track-status] { margin:8px 0 0; }
238
+ .driver-setup #network { cursor:pointer; }
239
+ .driver-setup #driver_device_panel > p { font-size:14px;line-height:1.5;color:#bdcddd; }
240
+ .driver-setup button:focus-visible,.driver-setup input:focus-visible,.driver-setup select:focus-visible,.driver-setup summary:focus-visible { outline:3px solid #ffd073;outline-offset:3px; }
241
+ /* Loading a driver, then running it, stays in normal document and keyboard order. */
242
+ @media(min-width:1050px) { #drive > .grid { grid-template-columns:minmax(360px,.82fr) minmax(0,1.35fr); } }
243
+ @media(max-width:600px) {
244
+ .driver-setup .setup-step { padding:17px 0; }
245
+ .driver-setup .source-panel { padding:12px; }
246
+ .driver-setup .driver-sources button { font-size:14px; }
247
+ .driver-setup #createDriver .toolbar { display:block; }
248
+ .driver-setup #createDriver .toolbar button { margin-top:10px;width:100%; }
249
+ .driver-setup #createDriver .toolbar select { width:100%; }
250
+ .driver-setup .bucket-load-actions > button { width:100%; }
251
+ }
252
+
253
  </style>
254
  <header class="lab-header"><div class="brand-copy"><div class="eyebrow">AI TRAINING STORY</div><h1>Driving Around</h1><p class="intro">Train a driver. Replay its decisions.</p><p class="brand-question">Can you train a neural network to drive better than an agent?</p></div><div class="header-actions"><button id="quick_start_toggle" type="button" aria-controls="firstRunGuide" aria-expanded="false">Quick start</button><a class="help-link" href="/help#start-here" target="_blank" rel="noopener">Help &amp; tutorial ↗</a></div></header>
255
  <div class="lab-utilities"><details class="about"><summary>About &amp; feedback</summary><p><strong>AI Training Story: Driving Around</strong> is a standalone controller workshop inspired by <em>AI Learns To Drive</em>. Train a population, evaluate an unchanged driver, and inspect its measured replay. You or an agent can operate the experiment tools; the opening question is a challenge to investigate through matched comparisons.</p><p>Simulator by <a href="https://github.com/Zorro909/driving_sim_rs">Zorro909</a>; interface and hosting by <a href="https://github.com/seeker-cyber-maker/driving_sim_rs">TiGa</a>. Inspired by the <a href="https://store.steampowered.com/app/3312030/AI_Learns_To_Drive/">game by ActivationFunction</a>. Built-in tracks are reconstructed replicas. For supported conditions, the lab checks the run’s final fitness policy (or frozen input) with a bounded fresh replay. It predicts conditions only and does not award or accumulate original-game stars; opponent races and other unsupported conditions remain unchecked.</p><p>Uploaded files are used for the requested run. Results are held briefly in application memory and deleted after verified download or expiry. Browser recipes contain settings only. <a href="/policy" target="_blank" rel="noopener">Read the data policy</a>.</p><p>The map follows the selected track’s native centerline. Record a short CPU drive to watch an unchanged policy using real vehicle positions. A new recording can differ from an earlier training run. Native control commands and consumed sensor inputs appear in the black box. Ray-hit positions and neural activations are not recorded.</p><p><a id="feedbackLink" href="https://github.com/seeker-cyber-maker/driving_sim_rs/issues/new" target="_blank" rel="noopener">Report a problem</a> · Opens an editable draft for you to review.</p><p id="buildLabel" class="hint">Build: connecting…</p></details>
256
+ <details id="agent-interface" class="agent-utility"><summary>Agent tools</summary><p>Use the same local controls as the lab: read the current state, open a section, create a starter, or inspect the active driver. These tools do not submit jobs or save data. <a href="/agents" target="_blank" rel="noopener">Agent interface guide</a> · <a href="/agent-manifest.json" target="_blank" rel="noopener">Action manifest (JSON)</a></p><p id="agent_tools_status" role="status" aria-live="polite">Checking browser tool support…</p><p>The state below is also available to ordinary browser automation. Each listed action identifies a stable control in this page.</p><pre id="agent_state" aria-label="Current Driving Around state (JSON)"></pre></details></div><details id="firstRunGuide" class="quick-start"><summary id="firstRunTitle">New here? Start a first run <span class="hint">Driver → track → settings → run</span></summary><ol class="quick-steps"><li><strong>Load your driver</strong><p>Choose a file or a saved bucket bundle. New drivers are optional.</p><button id="first_run_driver" type="button">Choose a driver</button></li><li><strong>Choose a track</strong><p>Built-in replica or your own track.</p><button id="first_run_track" type="button">Choose a track</button></li><li><strong>Review the settings</strong><p>Short first-run defaults are ready. Adjust them or save a recipe.</p><button id="first_run_settings" type="button">Review first-run settings</button></li><li><strong>Run and inspect</strong><p>Train, download and replay. A first run may not finish a lap.</p><button type="button" data-open-tab="drive" data-focus="run">Go to run controls</button></li></ol><div class="quick-footer"><a href="/help#start-here" target="_blank" rel="noopener">Read the full step-by-step tutorial ↗</a><button id="quick_start_close" type="button">Close quick start</button></div></details>
257
+ <nav class="tabs" role="tablist" aria-label="Driving Around sections"><button type="button" id="tab-drive" role="tab" data-tab="drive" aria-controls="drive" aria-selected="true" tabindex="0">Run &amp; results</button><button type="button" id="tab-training" role="tab" data-tab="training" aria-controls="training" aria-selected="false" tabindex="-1">Training &amp; recipes</button><button type="button" id="tab-batch" role="tab" data-tab="batch" aria-controls="batch" aria-selected="false" tabindex="-1">Batches</button><button type="button" id="tab-editor" role="tab" data-tab="editor" aria-controls="editor" aria-selected="false" tabindex="-1">Network editor</button></nav><div id="drive" class="pane" role="tabpanel" aria-labelledby="tab-drive"><section id="resultSummary" class="card result-summary" hidden aria-labelledby="result_summary_title"><div class="section-heading"><h2 id="result_summary_title" tabindex="-1">Latest run</h2><span id="result_backend" class="pill"></span></div><h3 id="runState" role="status" aria-live="polite">READY — no run started</h3><p id="result_outcome" class="settings-summary"></p><p id="result_driver" class="settings-summary"></p><p id="result_server" class="settings-summary" role="status"></p><div class="result-actions"><button id="download" class="primary" disabled hidden>Download driver</button><button id="saveLocal" class="primary" disabled>Download received driver</button><button id="result_replay" type="button" disabled>Replay selected driver</button><button id="player_report_download" disabled>Download player report (.txt)</button></div><details class="result-exports"><summary>More downloads &amp; server controls</summary><div class="result-actions"><button id="analysis_download" type="button" disabled>Download full analysis archive</button><button id="run_export" disabled>Export run receipt</button><button id="history_csv_download" disabled>Download generation history (.csv)</button><button id="erase" disabled>Delete server-side job data now</button><button id="forgetLocal" disabled>Discard browser result</button></div><p class="privacy-note">The received driver and analysis stay in this page until discarded, replaced, or closed. Save downloads to keep them. Reports describe server-reported measurements; reward weights are configured values, not measured contributions.</p></details><details><summary>Run details</summary><pre id="runSummary" style="white-space:pre-wrap;line-height:1.7" aria-live="polite"></pre></details></section><div class="grid"><section class="card driver-setup" id="driverSetup" aria-labelledby="driver_setup_title">
258
+ <h2 id="driver_setup_title">Set up your next run</h2><p class="setup-intro">Continue with a saved driver. Create a new one only when you need one.</p>
259
+ <section class="setup-step" aria-labelledby="choose_driver_title"><h3 id="choose_driver_title" class="step-title"><span class="step-marker" aria-hidden="true">1</span> Choose your driver</h3>
260
+ <div class="driver-sources" role="tablist" aria-label="Load a driver"><button id="driver_source_device" type="button" role="tab" aria-selected="true" aria-controls="driver_device_panel" tabindex="0">From this device</button><button id="driver_source_bucket" type="button" role="tab" aria-selected="false" aria-controls="driver_bucket_panel" tabindex="-1">Saved in bucket</button></div>
261
+ <div id="driver_device_panel" class="source-panel" role="tabpanel" aria-labelledby="driver_source_device"><p><label>Vehicle network (.evolution) <input id="network" type="file" accept=".evolution"></label></p><p>Your existing .evolution driver keeps its vehicle, inputs and weights.</p><details><summary>Restore a local experiment bundle</summary><label for="bundle_import">Restore portable bundle (.json)<input id="bundle_import" type="file" accept=".json,application/json"></label></details></div>
262
+ <div id="driver_bucket_panel" class="source-panel" role="tabpanel" aria-labelledby="driver_source_bucket" hidden><details id="bucketStorage"><summary>Connect to an existing private bucket</summary><details class="bucket-settings"><summary>Connection permissions</summary><p>Bucket storage is optional. Authorizing storage also identifies your account for GPU requests; ordinary GPU sign-in remains available with the basic identity permission. Then enter your existing private bucket ID. Connected runs automatically save by default; uncheck this option to keep run saves manual. No personal token is requested or stored.</p><p id="bucket_scope_notice" class="privacy-note">HF describes the requested <code>write-repos</code> permission as read/write access to your personal repositories. That grant is broader than one selected bucket and is not a bucket-only permission; the app limits its own operations to the bucket you enter. The minimum current scope for bucket read/write has not been confirmed by HF.</p></details><button id="bucket_authorize" type="button" hidden disabled>Authorize bucket access with HF</button><p id="bucket_auth_unavailable" class="hint" hidden>HF bucket authorization is unavailable for this app. Local bundle export remains available.</p><p id="bucket_auth_status" role="status" aria-live="polite">Checking optional HF bucket authorization…</p><div id="bucketConnectForm" hidden><label for="bucket_id">Private bucket ID</label><input id="bucket_id" type="text" autocomplete="off" placeholder="username/bucket-name" disabled><button id="bucket_connect" type="button" disabled>Connect bucket</button></div><div id="bucketConnected" hidden><div class="bucket-picker"><p id="bucket_account"></p><label for="bucket_items">Saved bundles from this app</label><select id="bucket_items" size="4" disabled><option value="">Refresh to list saved bundles</option></select><div class="bucket-load-actions"><button id="bucket_restore" type="button" disabled>Load selected driver &amp; bundle</button><button id="bucket_refresh" type="button" disabled>Refresh saved bundles</button></div></div><details class="bucket-settings" id="bucketManagement"><summary>Auto-save, backups &amp; recipe storage</summary><label class="keep-result"><input id="bucket_autosave" type="checkbox" checked> Automatically save every verified completed network and run log to this bucket</label><p class="hint">For each completed run, the browser fetches and verifies the network, then confirms server deletion before sending the network and sanitized log to your bucket. If deletion is not confirmed, no save occurs. If bucket saving is not confirmed, the verified local candidate stays available to download or retry; the remote save may have completed. Each batch step saves before the next starts, and a failed save stops the batch.</p><button id="bucket_disconnect" type="button">Disconnect bucket and clear HF authorization</button><div class="toolbar"><button id="bucket_save" type="button" disabled>Save selected bundle</button></div><hr><h3 id="bucketRecipeTitle" tabindex="-1">Recipe library (settings only)</h3><p class="hint">Save and import the validated recipes and batch definitions from this browser. This 32 KB library contains settings only; networks, tracks, run results and access tokens are never included. Import asks before replacing the local recipe library and never starts a run.</p><div class="toolbar"><button id="bucket_recipe_save" type="button" disabled>Save recipe library</button><button id="bucket_recipe_refresh" type="button" disabled>Refresh saved recipe libraries</button></div><label for="bucket_recipe_items">Saved recipe libraries</label><select id="bucket_recipe_items" size="4" disabled><option value="">Refresh to list saved recipe libraries</option></select><button id="bucket_recipe_import" type="button" disabled>Import selected recipe library</button><p id="bucket_recipe_status" role="status" aria-live="polite">No recipe library bucket action requested.</p></details></div><p id="bucket_status" role="status" aria-live="polite">Not connected. Bucket storage is optional.</p></details></div>
263
+ <div class="selected-driver"><span class="mini-label">Selected for the next run</span><p id="driver_current_name" tabindex="-1">No driver selected</p><p id="networkChoice" role="status">Choose an uploaded file or use a network from the browser editor.</p><button type="button" id="driver_inspect" disabled>Inspect selected driver</button></div><p id="legacy_timing_notice" class="timing-warning" role="status"></p>
264
+ <details id="createDriver"><summary>Create a new driver instead</summary><div class="toolbar" aria-label="Create a starter network"><label for="starter_vehicle">Starter car</label><select id="starter_vehicle"><option value="0" selected>Formula</option><option value="1">Rally</option><option value="2">Snowmobile</option><option value="3">Truck</option></select><button id="starter_create" type="button">Create starter network</button></div><p id="starter_network_status" class="hint" role="status">Creates a small network in this page only. It does not start a run or change saved recipes.</p><button id="driver_advanced_create" type="button">Open the network editor</button></details></section>
265
+ <section class="setup-step" aria-labelledby="choose_track_title"><h3 id="choose_track_title" class="step-title"><span class="step-marker" aria-hidden="true">2</span> Choose a track</h3><p><label for="trackPresetDrive">Track selection</label><select id="trackPresetDrive" data-track-library disabled><option value="">Upload a custom track</option></select></p><p data-track-status role="status" class="hint">Loading built-in replica tracks…</p><details><summary>Use a custom .track file</summary><p><label>Track (.track) <input id="track" type="file" accept=".track"></label></p></details></section>
266
+ <section class="setup-step" aria-labelledby="choose_run_title"><h3 id="choose_run_title" class="step-title"><span class="step-marker" aria-hidden="true">3</span> Configure this run</h3><label for="run_mode">Action</label><select id="run_mode"><option value="train" selected>Train a population</option><option value="evaluate">Frozen evaluation · one policy, unchanged weights</option></select><p id="run_mode_help" class="hint">Training uses the selected recipe. Frozen evaluation runs the selected policy in a fresh car without changing its weights.</p><p id="run_recipe_summary">Use the current training settings, or choose a saved recipe.</p><button type="button" class="settings-link" id="run_edit_settings">Review training settings &amp; recipes →</button><div class="run-facts" aria-label="Fixed execution timing"><span>Physics: 60 Hz</span><span>Decisions: 60 Hz</span><span>1 decision per tick</span></div><p id="computeBlock"><label for="backend">Compute</label><select id="backend" disabled><option value="cpu">CPU — no GPU allowance</option><option id="gpuOption" value="gpu" disabled>GPU — uses GPU allowance</option></select></p><p id="backendNote" class="hint">Checking available backends…</p><div id="connectionRecovery" hidden><button id="retry" type="button">Reconnect to app</button><p class="hint">Checks server availability. Does not restart training, sign you in, or reset GPU allowance.</p></div><details id="gpuAccountHelp"><summary>GPU sign-in &amp; allowance</summary><div id="gpuAccount" aria-label="Optional GPU account"><p><button id="hfSignIn" type="button" disabled>Sign in with HF for account GPU allowance</button><span id="hfAccount" hidden></span> <button id="hfSignOut" type="button" disabled hidden>Disconnect account</button></p><p id="hfIdentity" role="status" class="hint">CPU needs no sign-in. Checking optional GPU account connection…</p>
267
+ <details><summary>Account help &amp; troubleshooting</summary><p>CPU works without an account. HF sign-in identifies GPU requests; it does not guarantee available allowance. Sign in before choosing files: sign-in reloads this page and clears selected files and unsaved edits. Saved recipes remain.</p><p>Your account token stays in page memory. Refreshing or closing this page disconnects the app. Disconnecting here does not sign you out of the HF website or delete job data.</p><button id="hfVerify" type="button" disabled hidden>Check account connection — no GPU used</button><p class="hint">Checks which account the GPU submission service sees. Runs automatically before GPU training; it does not check your remaining allowance.</p></details></div></details></section>
268
+ <div class="run-footer"><button id="run" disabled>Run training</button><p id="setup_next_step" class="hint">Choose or create a driver, then review Training &amp; recipes and start a run.</p><details><summary>Run information &amp; download options</summary><p id="starCheckNotice" class="hint">After each run, supported star challenges are checked with unchanged weights. Results are predictions, not game awards. <a href="/help#concepts" target="_blank" rel="noopener">How checks work</a>.</p><p>Supports Formula, Rally, Snowmobile and Truck networks. Control outputs follow the original vehicle editor rules. Network shape and supported sensors are bounded by the original game contract.</p><p class="privacy-note">Uploads are processed for this run. By default, the server copy is deleted after the browser verifies the download.</p><details><summary>Optional repeat download</summary><label class="keep-result"><input id="keepServer" type="checkbox"> Keep this result on the server for up to five minutes so I can download it again</label><p class="privacy-note">This is optional and resets after each run. When bucket auto-save is on, verified receipt must delete the server copy first, so repeat download is disabled. All results expire after five minutes. <a href="/policy" target="_blank" rel="noopener">Data policy</a></p>
269
+ </details></details></div></section><section class="card"><h2>Visual replay &amp; car black box</h2><p id="mapStatus" class="map-status" role="status">Loading selected track…</p><button type="button" id="replay_focus" aria-pressed="false">Expand replay workspace</button><div class="toolbar"><button type="button" id="reference_calculate" disabled>Calculate suggested line</button><label><input type="checkbox" id="reference_show" checked disabled> Show suggested line</label></div><p id="reference_status" class="hint" role="status" aria-live="polite">Calculate a geometry-based suggested line to compare with the recorded drive. It is not a fastest-lap prediction.</p><div class="replay-bar" id="replayControls" tabindex="-1" aria-label="Recorded drive controls">
270
  <div class="replay-row"><button type="button" id="replay_record" disabled>Record selected policy</button><label for="replay_duration" style="margin:0">Length</label><select id="replay_duration"><option value="300" selected>5 seconds</option><option value="900">15 seconds</option></select><button type="button" id="replay_download" disabled>Download recording</button><label for="replay_import">Open recording<input type="file" id="replay_import" accept=".json,application/json" disabled></label></div>
271
  <p id="replay_policy" class="hint">Choose or create a network to record a drive.</p>
272
  <p class="hint">Fresh CPU drive, including for GPU-trained drivers · unchanged weights · 60 Hz decisions. Playback uses measured samples in your browser.</p>
273
  <p id="replay_loaded" class="recording-identity" role="status" aria-live="polite" hidden></p>
274
  <details><summary>What does this recording show?</summary><p>A single fresh CPU drive records native state, raw and normalized control commands, and the exact cached sensor inputs every 0.1 seconds. Physics and policy decisions run at 60 Hz. Playback starts paused and shows measured poses by default; optional pose smoothing only interpolates between adjacent measured samples. It does not simulate the car. Black-box values always remain at an actual recorded sample. Ray-hit positions, skid marks and hidden-layer activations are not recorded. This is a selected-policy CPU replay, including for GPU-trained policies; it is not a recording of the original training population.</p><p>The recording remains in this page until replaced, cleared by a changed selection, or the page is closed. Use Download recording to keep its measured samples.</p></details>
275
+ </div><div class="replay-workbench" id="replay_workspace"><div class="replay-viewer"><div class="map"><canvas id="trackMap" width="1000" height="500" role="img" aria-label="Selected track, static walls, suggested line and recorded vehicle path"></canvas></div><div class="replay-bar replay-playback"><div class="replay-row" id="replay_transport" role="group" aria-label="Playback controls" tabindex="-1"><button type="button" id="replay_play" disabled>Play</button><button type="button" id="replay_reset" disabled>Restart</button><button type="button" id="replay_prev" disabled>Previous sample</button><button type="button" id="replay_next" disabled>Next sample</button><input type="range" id="replay_scrub" min="1" max="300" value="1" disabled aria-label="Replay tick scrubber"><span id="replay_time_label" class="replay-time">No recording</span></div>
276
  <details class="replay-options"><summary>Camera, speed &amp; recorded events</summary><div class="replay-row" style="margin-top:8px"><label for="replay_camera" style="margin:0">Camera</label><select id="replay_camera" aria-label="Replay camera mode" disabled><option value="full" selected>Full circuit</option><option value="follow">Follow car</option></select><label for="replay_speed" style="margin:0">Speed</label><select id="replay_speed" aria-label="Replay playback speed" disabled><option value="0.25">0.25×</option><option value="0.5">0.5×</option><option value="1" selected>1×</option><option value="2">2×</option></select></div>
277
  <div class="replay-layers"><label><input type="checkbox" id="replay_layer_outline" checked disabled> Car outline</label><label><input type="checkbox" id="replay_layer_line" checked disabled> Recorded path</label><label><input type="checkbox" id="replay_layer_hud" checked disabled> Recorded telemetry</label></div>
278
  <div class="replay-row"><label><input type="checkbox" id="replay_interpolate" disabled> Smooth pose between measured samples</label><label for="replay_event">Contact / active-state interval</label><select id="replay_event" aria-label="Recorded event interval" disabled><option value="">No recording</option></select></div>
279
 
280
  </details><p id="replay_readout" style="font-size:16px;font-variant-numeric:tabular-nums" aria-live="off"></p>
281
+ <p id="reference_deviation" class="hint" aria-live="off"></p>
282
  <p id="replay_status" role="status">No replay recorded. The map shows the selected track and its saved starting point.</p></div></div><section id="replay_blackbox" tabindex="-1" hidden aria-label="Recorded car black box"><div class="section-heading"><h3>Car black box</h3><a href="#replay_transport">Back to playback</a></div><p id="blackbox_phase" class="hint"></p>
283
  <p class="hint">All values below belong to the selected native sample. Sensor inputs were consumed before physics at the decision tick; vehicle state is captured after physics. Samples are 0.1 seconds apart. Contact events identify intervals, not exact impact ticks; the counter does not count unique crashes.</p>
284
  <details><summary>Recorded vehicle state</summary><div class="table-scroll"><table><thead><tr><th>Vehicle state</th><th>Recorded value</th></tr></thead><tbody id="blackbox_state"></tbody></table></div></details>
 
303
  <section id="starCheckPanel" class="card" hidden aria-labelledby="starCheckTitle"><h2 id="starCheckTitle">Star challenge check</h2><p id="starCheckStatus" role="status" aria-live="polite"></p><div id="starCheckDetails" hidden><p id="starCheckPolicy" class="hint"></p><p id="starCheckBasis" class="hint"></p><p id="starCheckConditions" class="hint"></p><div class="table-scroll"><table><thead><tr><th>Challenge</th><th>Result</th><th>Reason</th><th>Completion time</th></tr></thead><tbody id="starCheckRows"></tbody></table></div><p class="hint">This is an independent check of the named run policy. It does not grant or accumulate original-game stars; replica challenges may differ from the original game.</p></div></section>
304
  <label class="keep-result"><input id="leaderboard_opt_in" type="checkbox"> After a completed lap, check its position against the public Steam leaderboard</label><p class="privacy-note">Optional, read-only check for supported built-in tracks. It sends the track ID and best lap to this app server; Steam receives only a public leaderboard read. No score is submitted. The result is an estimate, not an official rank.</p><p id="leaderboard_status" role="status" aria-live="polite"></p>
305
 
306
+ <details id="portableBundle"><summary>Portable bucket bundle</summary><p>Build, export, or restore one validated bundle. Bucket storage is optional. When connected, automatic save is on by default; turn it off here to keep saves manual. Disconnected runs never call bucket storage.</p><label><input id="bundle_track" type="checkbox"> Include the selected track</label><label><input id="bundle_recipe" type="checkbox"> Include the recipe in the selected slot, if saved</label><label><input id="bundle_receipt" type="checkbox"> Include a sanitized receipt for the selected completed result</label><div class="toolbar"><button id="bundle_export" type="button">Export portable bundle</button><button id="bundle_receipt_download" type="button" disabled>Download staged receipt</button></div><p id="bundle_status" role="status" aria-live="polite">No bucket action has been requested.</p>
307
+ </details>
308
  <p id="deadline"></p><p id="status" role="status">Ready. Inputs remain on this device until you run the test.</p>
309
  <details><summary>Effective training settings</summary><pre id="effectiveSettings"></pre></details><details><summary>Generation results</summary><pre id="generationHistory"></pre></details><details><summary>About star challenge checks</summary><p>After a run, supported conditions are checked against its named policy with a bounded fresh replay. Results appear in the Star challenge check panel when available. These are predictions for the reconstructed replica track, not original-game awards; opponent races and unsupported conditions are left unchecked.</p></details></section></div>
310
  </div><section id="training" class="pane" role="tabpanel" aria-labelledby="tab-training" hidden><div class="card">
311
  <div class="section-heading"><h2 id="trainingTitle" tabindex="-1">Training &amp; recipes</h2><a href="/help#recipes" target="_blank" rel="noopener">How recipes work ↗</a></div><p class="section-intro">A recipe saves training settings and rewards. Apply one to this form, or adjust the settings below and save your own. Choose your track and starting network in Run &amp; results.</p>
312
  <div id="libraries" class="recipe-panel"><div class="row"><label for="recipe_slot">Recipe slot<select id="recipe_slot"><option value="A">A · Empty</option><option value="B">B · Empty</option><option value="C">C · Empty</option><option value="D">D · Empty</option><option value="E">E · Empty</option><option value="F">F · Empty</option><option value="G">G · Empty</option><option value="H">H · Empty</option><option value="I">I · Empty</option><option value="J">J · Empty</option></select></label><label for="recipe_name">Recipe name<input id="recipe_name" type="text" maxlength="80" value="First practice" placeholder="e.g. First laps"></label></div>
313
+ <p id="recipe_state" class="form-state" role="status" aria-live="polite">Working settings · not saved yet</p><p id="recipe_summary" class="settings-summary"></p><div class="recipe-actions"><button id="recipe_load" type="button" disabled>Apply recipe</button><button id="recipe_save" type="button">Save settings to A</button><button type="button" data-open-tab="batch" data-focus="batch_add_recipe">Build a batch</button></div><p id="recipe_feedback" role="status" aria-live="polite"></p><button type="button" id="recipe_convert_60" hidden>Make a separate 60 Hz copy</button>
314
  <details><summary>Import, export &amp; manage recipes</summary><p class="muted-note">Recipes and batches are saved in this browser. Export a backup to move them to another browser or site. Clearing site data removes this library.</p><div class="manage-actions"><button id="recipe_export" type="button">Export recipe library</button><label for="recipe_import">Import recipe library (.json)<input id="recipe_import" type="file" accept=".json"></label><button id="recipe_bucket_nav" type="button">Bucket import / export</button></div><button id="recipe_clear" class="destructive-action" type="button">Clear saved recipes and batches on this device</button><p class="muted-note">The recipe library contains settings only. Saving a recipe does not start a run or upload tracks, networks, or results.</p></details>
315
  <details><summary>Advanced recipe JSON</summary><textarea id="recipe_draft" rows="12" aria-label="Recipe settings JSON"></textarea><button id="recipe_apply_draft" type="button">Apply JSON to form</button></details></div>
316
  <div class="section-heading"><h3>Settings for the next run</h3><button id="starter_settings_reset" type="button">Apply first-run settings to this form</button></div><p id="starter_settings_status" class="muted-note" role="status" aria-live="polite">Adjusting this form does not change a saved recipe until you save it.</p><div class="subtab-bar" id="trainingSubtabs" role="toolbar" aria-label="Filter training parameter sections"><button type="button" data-train-filter="all" aria-pressed="true">All sections</button><button type="button" data-train-filter="reward_settings" aria-pressed="false">Rewards (14 metrics)</button><button type="button" data-train-filter="native_settings" aria-pressed="false">Evolution &amp; mutation</button><button type="button" data-train-filter="run_settings" aria-pressed="false">Timing &amp; elimination</button><button type="button" data-train-filter="freeze_settings" aria-pressed="false">Selective freezing</button></div><div class="training-track"><label for="trackPresetTraining">Training track · shared with Run &amp; results</label><select id="trackPresetTraining" data-track-library disabled><option value="">Upload a custom track</option></select><p data-track-status role="status" class="hint">Loading built-in replica tracks…</p></div>
 
335
  <label for="reward_preset">Reward preset</label><select id="reward_preset" disabled><option value="custom">Custom</option><option value="distance" selected>First laps · distance only (+100 total score)</option><option value="center">Example mix · center, clearance, collisions</option><option value="clean">Clean driving · distance + collision penalty</option><option value="lap">Lap refinement · best lap only</option></select>
336
  <div id="rewards"></div><button id="add" disabled>+ Add reward</button><small>Weights −100…+100; absolute shares normalize to 100%. Fourteen distinct metrics maximum. The current vehicle runner accepts these metrics; choose them for the behavior you want to train.</small>
337
  </details></div>
338
+ <details id="run_settings"><summary>Run settings · timing and elimination</summary><div class="row"><div><span class="hint">Fixed simulation timing</span><input id="control_hz" type="hidden" value="60"><output class="fixed-rate" id="fixed_timing">60 Hz physics · 60 Hz decisions<br>One controller update on every physics tick. Fixed for every new run.</output></div><div><label for="workers">Parallel simulations</label><select id="workers" disabled><option>1</option><option selected>1</option><option>2</option><option>3</option><option>4</option></select></div></div><small>Physics runs at 60 Hz. CPU jobs can use 1–4 worker threads.</small><div id="seed_group"><label for="seed">Random seed</label><input id="seed" type="number" min="0" max="2147483647" value="42105" disabled></div><label><input id="collision" type="checkbox" disabled> Eliminate on wall contact</label><label><input id="idle" type="checkbox" disabled> Eliminate when stuck</label><label for="clean_min_laps">Minimum forward laps for a clean-lap winner</label><input id="clean_min_laps" type="number" min="1" max="100" value="2"><small>Winner classification only. Zero physical contacts are required. This does not change your reward recipe.</small></details></div></div></section>
339
  <section id="batch" class="pane" role="tabpanel" aria-labelledby="tab-batch" hidden><div class="card"><div class="section-heading"><h2>Training batches</h2><a href="/help#batches" target="_blank" rel="noopener">How batches work ↗</a></div><p class="section-intro">Arrange saved recipes into a sequence of up to 20 training steps. Use the same recipe more than once to keep training with those settings.</p><div class="batch-layout"><div>
340
  <div class="row"><label for="batch_slot">Batch slot<select id="batch_slot" disabled><option value="A">A · Empty</option><option value="B">B · Empty</option><option value="C">C · Empty</option><option value="D">D · Empty</option><option value="E">E · Empty</option><option value="F">F · Empty</option><option value="G">G · Empty</option><option value="H">H · Empty</option><option value="I">I · Empty</option><option value="J">J · Empty</option></select></label><label for="batch_name">Batch name<input id="batch_name" type="text" maxlength="80" value="My training batch" disabled></label></div><p id="batch_draft_state" class="form-state" role="status" aria-live="polite">New batch · not saved yet</p><div class="batch-actions"><button id="batch_save" type="button" disabled>Save batch</button><button id="batch_load" type="button" disabled>Load saved batch</button></div>
341
  <label class="batch-mode"><input id="carry" type="checkbox" checked disabled> Use each step’s result to train the next step</label><p id="batch_carry_help" class="muted-note">Step 1 uses your selected network. Later steps continue from the previous step’s result.</p>
 
405
  save(book){const clean=validate(book),text=JSON.stringify(clean);if(new TextEncoder().encode(text).byteLength>32768)throw Error('Recipe library exceeds 32 KB');storage.setItem(KEY,text);return clean;},
406
  clear(){storage.removeItem(KEY);},
407
  };}
408
+ function runnableSettings(value){const clean=settings(value);if(clean.control_hz!==60)throw Error('This lab runs new training and evaluations at 60 Hz only. Saved 30/15 Hz recipes are kept for inspection; create a separate 60 Hz copy before running.');return clean;}
409
+ const api={KEY,defaults,metrics,settings,runnableSettings,validate,parse,createStore};
410
  if(typeof module!=='undefined'&&module.exports)module.exports=api;else root.RecipeLibrary=api;
411
  })(typeof window!=='undefined'?window:globalThis);
412
  </script><script>/* Frozen settings-only plans; execution and stop checks are injected. */
 
417
  if(!batch)throw Error('Save or load a batch first');
418
  if(batch.runs.length>20)throw Error('Execution limit: 20 runs per batch');
419
  const runs=batch.runs.map(slot=>JSON.parse(JSON.stringify(library.recipes.find(r=>r.slot===slot))));
420
+ for(const recipe of runs)recipes.runnableSettings(recipe.settings); // Historical timing is not executable.
421
  const work=runs.reduce((n,r)=>n+r.settings.population*r.settings.generations*r.settings.ticks,0);
422
  if(runs.some(r=>r.settings.population*r.settings.generations*r.settings.ticks>workLimit||r.settings.population*r.settings.generations>32768))throw Error('A batch step exceeds this backend’s vehicle-tick or analysis-row limit; split that recipe into shorter runs');
423
  return {slot:batch.slot,name:batch.name,carry:batch.carry,runs,work};
 
427
  for(let i=0;i<plan.runs.length;i++){
428
  if(stopped())return {state:'stopped',candidate,history};
429
  const recipe=plan.runs[i],source=plan.carry&&candidate!==null?candidate:original;
430
+ recipes.runnableSettings(recipe.settings); // Also validate directly supplied plans.
431
  const result=await process(source,recipe.settings,i);
432
  if(!result||!result.candidate)throw Error('No validated batch candidate');
433
  candidate=result.candidate;
 
581
  }
582
  function currentSettings(){
583
  const data={};for(const name of fields)data[name]=booleans.includes(name)?q(name).checked:strings.includes(name)?q(name).value:Number(q(name).value);
584
+ data.ticks=Number(q('training_ticks').value);data.rewards=rewards();data.freeze={layers:[...selectedFreeze.layers],inputs:[...selectedFreeze.inputs],outputs:[...selectedFreeze.outputs]};return api.runnableSettings(data);
585
  }
586
  function updateWorkBudget(){
587
  const p=Number(q('population').value),g=Number(q('generations').value),t=Number(q('training_ticks').value),box=q('work_budget');
 
600
  return data;
601
  }
602
  function applySettings(value){
603
+ const data=api.runnableSettings(value);
604
  for(const name of fields){if(booleans.includes(name))q(name).checked=data[name];else q(name).value=data[name];}
605
  q('training_ticks').value=data.ticks;q('rewards').replaceChildren();data.rewards.forEach(rewardRow);
606
  for(const kind of ['layers','inputs','outputs'])selectedFreeze[kind]=[...data.freeze[kind]];renderFreeze();
 
619
  };
620
  window.stagePortableRecipe=recipe=>{
621
  if(!recipe||! /^[A-J]$/.test(recipe.slot)||typeof recipe.name!=='string'||!recipe.name.trim()||recipe.name.length>80)throw Error('Invalid selected recipe');
622
+ const archived=api.settings(recipe.settings);
623
+ if(archived.control_hz!==60){
624
+ stagedPortableRecipe=false;
625
+ window.dispatchEvent(new CustomEvent('ald:legacy-recipe',{detail:{control_hz:archived.control_hz}}));
626
+ message('Driver restored, but its '+archived.control_hz+' Hz recipe was not applied. The current 60 Hz settings remain selected; the original saved receipt is unchanged.');
627
+ return;
628
+ }
629
+ const settings=api.runnableSettings(recipe.settings);q('recipe_slot').value=recipe.slot;q('recipe_name').value=recipe.name.trim();
630
  applySettings(settings);q('preset').value='custom';q('reward_preset').value='custom';stagedPortableRecipe=true;
631
  message('Imported recipe staged in the training form. Save it explicitly to add it to this browser’s recipe library. No run started.');
632
  };
 
686
  const maximum=q('backend')?.value==='gpu'?8000000:4000000;
687
  for(let i=0;i<draft.runs.length;i++){
688
  const recipe=book.recipes.find(item=>item.slot===draft.runs[i]),settings=recipe.settings,work=settings.population*settings.generations*settings.ticks,rows=settings.population*settings.generations;
689
+ if(settings.control_hz!==60)return {ready:false,message:'Step '+(i+1)+' uses '+settings.control_hz+' Hz. Create a 60 Hz recipe copy and replace this step before running.'};
690
  if(work>maximum||rows>32768)return {ready:false,message:'Step '+(i+1)+' · '+recipe.slot+' · '+recipe.name+' exceeds this compute limit ('+work.toLocaleString()+' vehicle-ticks; '+rows.toLocaleString()+' analysis rows). Shorten that recipe in Training & recipes.'};
691
  }
692
  return {ready:true,message:'Saved batch matches the steps shown. Ready to run '+draft.runs.length+' '+(draft.runs.length===1?'step':'steps')+'.'};
track-map.js CHANGED
@@ -73,7 +73,11 @@
73
  const block=atlas?.blocks?.[`${id?.AtlasId}:${id?.AlternativeId}`];
74
  if(!block||![0,1,2].includes(block.surface))throw Error('Track uses a piece not in the simulator atlas');
75
  if(!Array.isArray(block.connections)||block.connections.length!==2)throw Error('Track piece connections are unavailable');
76
- return {x,y,surface:block.surface,connections:block.connections.map(value=>connection(value))};
 
 
 
 
77
  });
78
  if(new Set(tiles.map(t=>`${t.x},${t.y}`)).size!==tiles.length)throw Error('Duplicate track tile');
79
  const start=vector(saved.StartTileCoords);
@@ -87,6 +91,160 @@
87
  if(maxX-minX>30||maxY-minY>30)throw Error('Track preview is too large');
88
  return {tiles,start,startConnection,bounds:{minX,maxX,minY,maxY}};
89
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90
  function render(canvas,track){
91
  const context=canvas.getContext('2d');
92
  if(!context)throw Error('Canvas preview unavailable');
@@ -102,6 +260,11 @@
102
  context.beginPath();context.roundRect(x+2,y+2,size-4,size-4,Math.max(4,size*.13));context.fill();
103
  context.strokeStyle='#d7e8f2';context.lineWidth=Math.max(1,size*.018);
104
  context.stroke();
 
 
 
 
 
105
  if(Array.isArray(tile.connections)&&tile.connections.length>=2){
106
  const [entry,exit]=tile.connections;
107
  const a=connectionPoint(entry,x,y,size),z=connectionPoint(exit,x,y,size);
@@ -339,6 +502,7 @@
339
  if(!canvas||!status||!legend||!picker)return;
340
  const element=id=>document.getElementById(id);
341
  let version=0,atlasPromise=null,currentTrack=null,currentTrackSha=null,staticLayer=null;
 
342
  let recording=null,hasRunSummary=false,cursor=1,playing=false,animId=null,lastFrameTime=null;
343
  let playSpeed=Math.max(0.25,Math.min(4,Number(element('replay_speed')?.value)||1));
344
  let cameraMode=element('replay_camera')?.value==='follow'?'follow':'full';
@@ -348,6 +512,8 @@
348
  const summaryOnly='No replay recorded. This run contains summary measurements, not vehicle positions or control samples.';
349
  function setText(id,text){const node=element(id);if(node&&node.textContent!==text)node.textContent=text;}
350
  function syncControls(reason){
 
 
351
  const last=recording?.frames[recording.frames.length-1].tick;
352
  const play=element('replay_play');
353
  if(play){play.disabled=!recording||cursor>=last;play.textContent=playing?'Pause':'Play';}
@@ -410,6 +576,11 @@
410
  ctx.translate(canvas.width/2,canvas.height/2);ctx.scale(2,2);ctx.translate(-position[0],-position[1]);
411
  }
412
  if(staticLayer)ctx.drawImage(staticLayer,0,0);else render(canvas,currentTrack);
 
 
 
 
 
413
  if(recording){
414
  if(layers.line){
415
  ctx.beginPath();
@@ -423,6 +594,8 @@
423
  if(state){
424
  const frame=state.frame;blackbox(frame);const speed=Math.hypot(frame.vx,frame.vy)/15*3.6;
425
  const contacts=frame.collision_count===undefined?'unavailable':String(frame.collision_count);
 
 
426
  setText('replay_time_label',`${(cursor/60).toFixed(2)}s / ${(recording.requested_ticks/60).toFixed(2)}s · Tick ${Math.round(cursor)} · Measured tick ${frame.tick}`);
427
  setText('replay_readout',`Recorded sample tick ${frame.tick} (${(frame.tick/60).toFixed(2)}s). Speed ${speed.toFixed(1)} km/h, derived from recorded velocity. Position (${frame.x.toFixed(2)}, ${frame.y.toFixed(2)}). Contacts ${contacts}. ${frame.active?'Active':'Inactive'} at this sample. ${frame.decision?'Native controls and inputs captured at tick '+frame.decision.tick+'.':'No captured decision at this sample.'}`);
428
  if(layers.hud){
@@ -435,6 +608,7 @@
435
  }
436
  function clearRecording(reason){
437
  const hadRecording=recording!==null;stopPlayback();recording=null;cursor=1;blackboxTick=null;eventOptions();
 
438
  if(hadRecording)draw();syncControls(reason);
439
  }
440
  function step(now){
@@ -450,6 +624,35 @@
450
  }
451
  function bind(){
452
  const on=(id,event,callback)=>{const node=element(id);if(node)node.addEventListener(event,callback);};
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
453
  on('replay_play','click',()=>{
454
  if(!recording)return;
455
  if(playing){stopPlayback();syncControls();return;}
@@ -473,7 +676,9 @@
473
  document.addEventListener('visibilitychange',()=>{if(document.hidden){stopPlayback();syncControls();}});
474
  }
475
  async function refresh(){
476
- const current=++version;clearRecording();currentTrackSha=null;currentTrack=null;staticLayer=null;
 
 
477
  const info=picker.info();
478
  const source=info.source==='builtin'?info.display_name:element('track')?.files?.[0]?.name;
479
  if(!source){status.textContent='Select a built-in track or choose a custom .track file.';legend.textContent='';renderEmpty();return;}
@@ -494,7 +699,8 @@
494
  if(off?.getContext?.('2d')){off.width=canvas.width;off.height=canvas.height;render(off,track);staticLayer=off;}
495
  const counts=[0,0,0];track.tiles.forEach(tile=>counts[tile.surface]++);
496
  status.textContent=source+' · '+track.tiles.length+' pieces · green dot marks the saved starting point';
497
- legend.textContent=NAMES.filter((_,i)=>counts[i]).map(name=>name+' '+counts[NAMES.indexOf(name)]).join(' · ')+' · Orange line follows the track centerline. Collision shapes are not shown. Vehicle positions appear only from a recorded replay.';
 
498
  }catch(error){
499
  if(current!==version)return;
500
  currentTrack=null;currentTrackSha=null;staticLayer=null;renderEmpty();
@@ -522,5 +728,5 @@
522
  bind();syncControls();document.addEventListener('track-library-change',refresh);refresh();
523
  return controller;
524
  }
525
- return {mount,model,decode,render,validateRecording,sampleRecording,recordingEvents,adjacentSampleTick};
526
  });
 
73
  const block=atlas?.blocks?.[`${id?.AtlasId}:${id?.AlternativeId}`];
74
  if(!block||![0,1,2].includes(block.surface))throw Error('Track uses a piece not in the simulator atlas');
75
  if(!Array.isArray(block.connections)||block.connections.length!==2)throw Error('Track piece connections are unavailable');
76
+ const polygons=block.polygons;
77
+ if(polygons!==undefined&&(!Array.isArray(polygons)||polygons.length>32||polygons.some(p=>!Array.isArray(p)||p.length<3||p.length>128||p.some(v=>!Array.isArray(v)||v.length!==2||v.some(n=>!Number.isFinite(n)||Math.abs(n)>384)))))
78
+ throw Error('Track wall geometry is invalid');
79
+ return {x,y,surface:block.surface,connections:block.connections.map(value=>connection(value)),
80
+ polygons:polygons?.map(p=>p.map(([px,py])=>[px+x*768+384,py+y*768+384]))};
81
  });
82
  if(new Set(tiles.map(t=>`${t.x},${t.y}`)).size!==tiles.length)throw Error('Duplicate track tile');
83
  const start=vector(saved.StartTileCoords);
 
91
  if(maxX-minX>30||maxY-minY>30)throw Error('Track preview is too large');
92
  return {tiles,start,startConnection,bounds:{minX,maxX,minY,maxY}};
93
  }
94
+ const distance=(a,b)=>Math.hypot(a[0]-b[0],a[1]-b[1]);
95
+ function projectPoint(p,a,b){
96
+ const dx=b[0]-a[0],dy=b[1]-a[1],length=dx*dx+dy*dy;
97
+ const t=length?Math.max(0,Math.min(1,((p[0]-a[0])*dx+(p[1]-a[1])*dy)/length)):0;
98
+ return [a[0]+t*dx,a[1]+t*dy];
99
+ }
100
+ function insidePolygon(point,polygon){
101
+ let inside=false;
102
+ for(let i=0,j=polygon.length-1;i<polygon.length;j=i++){
103
+ const a=polygon[i],b=polygon[j];
104
+ if((a[1]>point[1])!==(b[1]>point[1])&&point[0]<(b[0]-a[0])*(point[1]-a[1])/(b[1]-a[1])+a[0])inside=!inside;
105
+ }
106
+ return inside;
107
+ }
108
+ function segmentDistance(a,b,c,d){
109
+ const cross=(p,q,r)=>(q[0]-p[0])*(r[1]-p[1])-(q[1]-p[1])*(r[0]-p[0]);
110
+ const ac=cross(a,b,c),ad=cross(a,b,d),ca=cross(c,d,a),cb=cross(c,d,b);
111
+ if(ac*ad<0&&ca*cb<0)return 0;
112
+ return Math.min(distance(a,projectPoint(a,c,d)),distance(b,projectPoint(b,c,d)),distance(c,projectPoint(c,a,b)),distance(d,projectPoint(d,a,b)));
113
+ }
114
+ function routePoints(track){
115
+ const byTile=new Map(track.tiles.map(t=>[`${t.x},${t.y}`,t]));
116
+ const equal=(a,b)=>a.side===b.side&&a.index===b.index&&a.type===b.type;
117
+ let tile=byTile.get(track.start.join(',')),incoming=track.startConnection;
118
+ const visited=new Set(),points=[],neighbors=[[0,-1],[0,1],[-1,0],[1,0]];
119
+ while(tile&&!visited.has(`${tile.x},${tile.y}`)){
120
+ visited.add(`${tile.x},${tile.y}`);
121
+ if(!tile.connections.some(c=>equal(c,incoming)))throw Error('The saved route has an incompatible connection');
122
+ const outgoing=tile.connections.find(c=>!equal(c,incoming));
123
+ if(!outgoing)throw Error('The saved route has no exit');
124
+ const a=connectionPoint(incoming,tile.x*768,tile.y*768,768),b=connectionPoint(outgoing,tile.x*768,tile.y*768,768);
125
+ const p=connectionControl(incoming,outgoing,a,b),q=connectionControl(outgoing,incoming,b,a);
126
+ for(let i=0;i<32;i++){
127
+ const t=i/32,s=1-t;
128
+ points.push([s*s*s*a[0]+3*s*s*t*p[0]+3*s*t*t*q[0]+t*t*t*b[0],s*s*s*a[1]+3*s*s*t*p[1]+3*s*t*t*q[1]+t*t*t*b[1]]);
129
+ }
130
+ const step=neighbors[outgoing.side];
131
+ tile=byTile.get(`${tile.x+step[0]},${tile.y+step[1]}`);
132
+ incoming={...outgoing,side:outgoing.side^1};
133
+ }
134
+ if(!tile||tile.x!==track.start[0]||tile.y!==track.start[1]||!equal(incoming,track.startConnection))throw Error('The saved route does not close at its starting connection');
135
+ points.push(points[0]);
136
+ const lengths=[0];
137
+ for(let i=1;i<points.length;i++)lengths.push(lengths[i-1]+distance(points[i-1],points[i]));
138
+ const length=lengths[lengths.length-1];
139
+ if(!Number.isFinite(length)||length<100)throw Error('The saved route has no usable length');
140
+ const count=Math.min(2048,Math.max(32,Math.ceil(length/64))),sampled=[];
141
+ let at=0;
142
+ for(let i=0;i<count;i++){
143
+ const target=length*i/count;
144
+ while(at+1<lengths.length-1&&lengths[at+1]<target)at++;
145
+ const t=(target-lengths[at])/(lengths[at+1]-lengths[at]);
146
+ sampled.push(points[at].map((v,axis)=>v+t*(points[at+1][axis]-v)));
147
+ }
148
+ return {points:sampled,route_tiles:visited.size};
149
+ }
150
+ function referenceLine(track){
151
+ if(track.tiles.some(t=>!Array.isArray(t.polygons)))throw Error('Wall geometry is unavailable for this track');
152
+ const route=routePoints(track),points=route.points.map(p=>[...p]),n=points.length,margin=32;
153
+ const byTile=new Map(track.tiles.map(t=>[`${t.x},${t.y}`,t]));
154
+ const wrap=i=>(i+n)%n;
155
+ function clear(a,b){
156
+ // Split at every tile boundary; each open segment must remain in a saved tile.
157
+ const times=[0,1];
158
+ for(let axis=0;axis<2;axis++)if(a[axis]!==b[axis]){
159
+ for(let k=Math.floor(Math.min(a[axis],b[axis])/768)+1;k*768<Math.max(a[axis],b[axis]);k++)times.push((k*768-a[axis])/(b[axis]-a[axis]));
160
+ }
161
+ times.sort((x,y)=>x-y);
162
+ for(let i=1;i<times.length;i++){
163
+ const t=(times[i-1]+times[i])/2;
164
+ if(!byTile.has(`${Math.floor((a[0]+(b[0]-a[0])*t)/768)},${Math.floor((a[1]+(b[1]-a[1])*t)/768)}`))return false;
165
+ }
166
+ const x0=Math.floor((Math.min(a[0],b[0])-margin)/768),x1=Math.floor((Math.max(a[0],b[0])+margin)/768);
167
+ const y0=Math.floor((Math.min(a[1],b[1])-margin)/768),y1=Math.floor((Math.max(a[1],b[1])+margin)/768);
168
+ for(let x=x0;x<=x1;x++)for(let y=y0;y<=y1;y++)for(const polygon of byTile.get(`${x},${y}`)?.polygons??[]){
169
+ if(insidePolygon(a,polygon)||insidePolygon(b,polygon))return false;
170
+ for(let i=0;i<polygon.length;i++)if(segmentDistance(a,b,polygon[i],polygon[(i+1)%polygon.length])<margin-1e-7)return false;
171
+ }
172
+ return true;
173
+ }
174
+ const normals=points.map((p,i)=>{
175
+ const a=points[wrap(i-1)],b=points[wrap(i+1)],d=distance(a,b);
176
+ return d?[-(b[1]-a[1])/d,(b[0]-a[0])/d]:[0,0];
177
+ });
178
+ const offsets=new Array(n).fill(0);
179
+ if(points.some((p,i)=>!clear(p,points[wrap(i+1)]))){
180
+ // Find a feasible seed around posts and narrow bends before smoothing.
181
+ // The saved start remains fixed; alternate laps are not claimed optimal.
182
+ if(!clear(points[0],points[0]))throw Error('The saved start cannot keep the 32-unit wall margin');
183
+ const choices=route.points.map((p,i)=>{
184
+ if(i===0)return [{point:p,offset:0}];
185
+ const values=[];
186
+ for(let offset=-192;offset<=192;offset+=16){
187
+ const point=p.map((v,axis)=>v+offset*normals[i][axis]);
188
+ if(clear(point,point))values.push({point,offset});
189
+ }
190
+ if(!values.length)throw Error('No suggested line fits the wall margin within the bounded search corridor');
191
+ return values;
192
+ });
193
+ let costs=[0];const parents=[[-1]];
194
+ for(let i=1;i<n;i++){
195
+ const nextCosts=choices[i].map(()=>Infinity),previous=choices[i].map(()=>-1);
196
+ choices[i].forEach((candidate,j)=>choices[i-1].forEach((last,k)=>{
197
+ if(!Number.isFinite(costs[k])||Math.abs(candidate.offset-last.offset)>48)return;
198
+ const cost=costs[k]+(candidate.offset-last.offset)**2+0.01*candidate.offset**2;
199
+ if(cost>=nextCosts[j]||!clear(last.point,candidate.point))return;
200
+ nextCosts[j]=cost;previous[j]=k;
201
+ }));
202
+ costs=nextCosts;parents.push(previous);
203
+ }
204
+ let last=-1,best=Infinity;
205
+ choices[n-1].forEach((candidate,i)=>{
206
+ const cost=costs[i]+candidate.offset**2;
207
+ if(cost<best&&clear(candidate.point,points[0])){last=i;best=cost;}
208
+ });
209
+ if(last<0)throw Error('No closed suggested line found within the bounded search corridor');
210
+ for(let i=n-1;i>0;i--){points[i]=choices[i][last].point;offsets[i]=choices[i][last].offset;last=parents[i][last];}
211
+ }
212
+ function bend(i){
213
+ const a=points[wrap(i-1)],b=points[wrap(i)],c=points[wrap(i+1)];
214
+ return (a[0]-2*b[0]+c[0])**2+(a[1]-2*b[1]+c[1])**2;
215
+ }
216
+ const cost=()=>points.reduce((sum,_,i)=>sum+bend(i),0),before=cost();
217
+ // Bounded coordinate descent on fixed normal offsets. This is a local
218
+ // geometric smoothing objective, not a vehicle model or lap-time solver.
219
+ for(const step of [32,16,8,4])for(let sweep=0;sweep<2;sweep++)for(let i=0;i<n;i++){
220
+ const old=points[i],offset=offsets[i];
221
+ let best=old,bestOffset=offset,bestCost=bend(i-1)+bend(i)+bend(i+1);
222
+ const target=[0,1].map(axis=>(4*(points[wrap(i-1)][axis]+points[wrap(i+1)][axis])-points[wrap(i-2)][axis]-points[wrap(i+2)][axis])/6);
223
+ const optimum=Math.max(-192,Math.min(192,target.reduce((sum,v,axis)=>sum+(v-route.points[i][axis])*normals[i][axis],0)));
224
+ // Keep the start on its saved connection; refine fractional offsets too.
225
+ if(i===0)continue;
226
+ for(const next of [optimum,Math.max(-192,offset-step),Math.min(192,offset+step)]){
227
+ if(Math.abs(next-offset)<1e-9)continue;
228
+ const candidate=route.points[i].map((value,axis)=>value+normals[i][axis]*next);
229
+ if(!clear(points[wrap(i-1)],candidate)||!clear(candidate,points[wrap(i+1)]))continue;
230
+ points[i]=candidate;
231
+ const value=bend(i-1)+bend(i)+bend(i+1);
232
+ if(value<bestCost-1e-9){best=candidate;bestOffset=next;bestCost=value;}
233
+ points[i]=old;
234
+ }
235
+ points[i]=best;offsets[i]=bestOffset;
236
+ }
237
+ return {points,margin,route_tiles:route.route_tiles,smoothness_before:before,smoothness_after:cost(),method:'bounded_normal_offset_smoothing'};
238
+ }
239
+ function referenceDistance(point,line){
240
+ if(!line?.points?.length)return null;
241
+ let best=null;
242
+ line.points.forEach((a,i)=>{
243
+ const projected=projectPoint(point,a,line.points[(i+1)%line.points.length]),d=distance(point,projected);
244
+ if(!best||d<best.distance)best={distance:d,point:projected};
245
+ });
246
+ return best;
247
+ }
248
  function render(canvas,track){
249
  const context=canvas.getContext('2d');
250
  if(!context)throw Error('Canvas preview unavailable');
 
260
  context.beginPath();context.roundRect(x+2,y+2,size-4,size-4,Math.max(4,size*.13));context.fill();
261
  context.strokeStyle='#d7e8f2';context.lineWidth=Math.max(1,size*.018);
262
  context.stroke();
263
+ for(const polygon of tile.polygons??[]){
264
+ context.beginPath();
265
+ polygon.forEach(([px,py],i)=>{const p=[x+(px-tile.x*768)/768*size,y+(py-tile.y*768)/768*size];if(i)context.lineTo(...p);else context.moveTo(...p);});
266
+ context.closePath();context.fillStyle='#253443';context.fill();
267
+ }
268
  if(Array.isArray(tile.connections)&&tile.connections.length>=2){
269
  const [entry,exit]=tile.connections;
270
  const a=connectionPoint(entry,x,y,size),z=connectionPoint(exit,x,y,size);
 
502
  if(!canvas||!status||!legend||!picker)return;
503
  const element=id=>document.getElementById(id);
504
  let version=0,atlasPromise=null,currentTrack=null,currentTrackSha=null,staticLayer=null;
505
+ let reference=null,referenceBusy=false,referenceWorker=null;
506
  let recording=null,hasRunSummary=false,cursor=1,playing=false,animId=null,lastFrameTime=null;
507
  let playSpeed=Math.max(0.25,Math.min(4,Number(element('replay_speed')?.value)||1));
508
  let cameraMode=element('replay_camera')?.value==='follow'?'follow':'full';
 
512
  const summaryOnly='No replay recorded. This run contains summary measurements, not vehicle positions or control samples.';
513
  function setText(id,text){const node=element(id);if(node&&node.textContent!==text)node.textContent=text;}
514
  function syncControls(reason){
515
+ if(element('reference_calculate'))element('reference_calculate').disabled=!currentTrack||referenceBusy;
516
+ if(element('reference_show'))element('reference_show').disabled=!reference;
517
  const last=recording?.frames[recording.frames.length-1].tick;
518
  const play=element('replay_play');
519
  if(play){play.disabled=!recording||cursor>=last;play.textContent=playing?'Pause':'Play';}
 
576
  ctx.translate(canvas.width/2,canvas.height/2);ctx.scale(2,2);ctx.translate(-position[0],-position[1]);
577
  }
578
  if(staticLayer)ctx.drawImage(staticLayer,0,0);else render(canvas,currentTrack);
579
+ if(reference&&element('reference_show')?.checked){
580
+ ctx.beginPath();
581
+ reference.points.forEach((p,i)=>{const xy=worldPoint(view,...p);if(i)ctx.lineTo(...xy);else ctx.moveTo(...xy);});
582
+ ctx.closePath();ctx.strokeStyle='#ffd073';ctx.lineWidth=2.5;ctx.setLineDash([7,5]);ctx.stroke();ctx.setLineDash([]);
583
+ }
584
  if(recording){
585
  if(layers.line){
586
  ctx.beginPath();
 
594
  if(state){
595
  const frame=state.frame;blackbox(frame);const speed=Math.hypot(frame.vx,frame.vy)/15*3.6;
596
  const contacts=frame.collision_count===undefined?'unavailable':String(frame.collision_count);
597
+ const deviation=referenceDistance([frame.x,frame.y],reference);
598
+ setText('reference_deviation',deviation?`Measured position is ${(deviation.distance/15).toFixed(2)} m from the nearest suggested-line segment. Distance alone does not measure driving quality.`:'');
599
  setText('replay_time_label',`${(cursor/60).toFixed(2)}s / ${(recording.requested_ticks/60).toFixed(2)}s · Tick ${Math.round(cursor)} · Measured tick ${frame.tick}`);
600
  setText('replay_readout',`Recorded sample tick ${frame.tick} (${(frame.tick/60).toFixed(2)}s). Speed ${speed.toFixed(1)} km/h, derived from recorded velocity. Position (${frame.x.toFixed(2)}, ${frame.y.toFixed(2)}). Contacts ${contacts}. ${frame.active?'Active':'Inactive'} at this sample. ${frame.decision?'Native controls and inputs captured at tick '+frame.decision.tick+'.':'No captured decision at this sample.'}`);
601
  if(layers.hud){
 
608
  }
609
  function clearRecording(reason){
610
  const hadRecording=recording!==null;stopPlayback();recording=null;cursor=1;blackboxTick=null;eventOptions();
611
+ setText('reference_deviation','');
612
  if(hadRecording)draw();syncControls(reason);
613
  }
614
  function step(now){
 
624
  }
625
  function bind(){
626
  const on=(id,event,callback)=>{const node=element(id);if(node)node.addEventListener(event,callback);};
627
+ on('reference_calculate','click',async()=>{
628
+ if(!currentTrack||referenceBusy)return;
629
+ const track=currentTrack,request=version;referenceBusy=true;syncControls();setText('reference_status','Calculating suggested line…');
630
+ await new Promise(resolve=>typeof root?.setTimeout==='function'?root.setTimeout(resolve,0):resolve());
631
+ if(request!==version)return;
632
+ try{
633
+ if(typeof root?.Worker==='function'&&typeof root?.URL?.createObjectURL==='function'){
634
+ const definitions=[connection,connectionPoint,connectionControl,projectPoint,insidePolygon,segmentDistance,routePoints,referenceLine].map(fn=>fn.toString()).join('\n');
635
+ const source=`const distance=${distance.toString()};\n${definitions}\nonmessage=event=>{try{postMessage({line:referenceLine(event.data)});}catch(error){postMessage({error:error.message});}};`;
636
+ const url=root.URL.createObjectURL(new Blob([source],{type:'application/javascript'}));
637
+ let worker;
638
+ try{
639
+ worker=new root.Worker(url);
640
+ const line=await new Promise((resolve,reject)=>{
641
+ referenceWorker={worker,cancel:()=>reject(Error('Track changed'))};
642
+ worker.onmessage=event=>event.data.error?reject(Error(event.data.error)):resolve(event.data.line);
643
+ worker.onerror=()=>reject(Error('Browser could not calculate the suggested line'));
644
+ worker.postMessage(track);
645
+ });
646
+ if(request!==version)return;
647
+ reference=line;
648
+ }finally{worker?.terminate();root.URL.revokeObjectURL(url);if(referenceWorker?.worker===worker)referenceWorker=null;}
649
+ }else reference=referenceLine(track);
650
+ if(request!==version)return;
651
+ setText('reference_status',`Suggested line ready · ${reference.route_tiles} connected pieces · 32 game-unit static wall margin. Geometry only; grip, braking and boost are not modeled.`);
652
+ }catch(error){if(request===version){reference=null;setText('reference_status','Suggested line unavailable: '+error.message);}}
653
+ finally{if(request===version){referenceBusy=false;draw();syncControls();}}
654
+ });
655
+ on('reference_show','change',draw);
656
  on('replay_play','click',()=>{
657
  if(!recording)return;
658
  if(playing){stopPlayback();syncControls();return;}
 
676
  document.addEventListener('visibilitychange',()=>{if(document.hidden){stopPlayback();syncControls();}});
677
  }
678
  async function refresh(){
679
+ if(referenceWorker){referenceWorker.worker.terminate();referenceWorker.cancel();referenceWorker=null;}
680
+ const current=++version;clearRecording();currentTrackSha=null;currentTrack=null;staticLayer=null;reference=null;referenceBusy=false;
681
+ setText('reference_status','Calculate a geometry-based suggested line to compare with the recorded drive. It is not a fastest-lap prediction.');setText('reference_deviation','');syncControls();
682
  const info=picker.info();
683
  const source=info.source==='builtin'?info.display_name:element('track')?.files?.[0]?.name;
684
  if(!source){status.textContent='Select a built-in track or choose a custom .track file.';legend.textContent='';renderEmpty();return;}
 
699
  if(off?.getContext?.('2d')){off.width=canvas.width;off.height=canvas.height;render(off,track);staticLayer=off;}
700
  const counts=[0,0,0];track.tiles.forEach(tile=>counts[tile.surface]++);
701
  status.textContent=source+' · '+track.tiles.length+' pieces · green dot marks the saved starting point';
702
+ legend.textContent=NAMES.filter((_,i)=>counts[i]).map(name=>name+' '+counts[NAMES.indexOf(name)]).join(' · ')+' · Dark shapes show static walls. Orange: track centerline. Dashed yellow: calculated suggestion. Green: recorded drive. Vehicle positions appear only from a recorded replay.';
703
+ syncControls();
704
  }catch(error){
705
  if(current!==version)return;
706
  currentTrack=null;currentTrackSha=null;staticLayer=null;renderEmpty();
 
728
  bind();syncControls();document.addEventListener('track-library-change',refresh);refresh();
729
  return controller;
730
  }
731
+ return {mount,model,decode,render,referenceLine,referenceDistance,validateRecording,sampleRecording,recordingEvents,adjacentSampleTick};
732
  });
training_config.py CHANGED
@@ -30,6 +30,8 @@ def validate_config(value=None, *, work_limit=4_000_000):
30
  if value is None:return copy.deepcopy(DEFAULTS)
31
  if not isinstance(value,dict) or set(value)-set(DEFAULTS):raise ValueError('Unexpected training settings')
32
  c={**copy.deepcopy(DEFAULTS),**value}
 
 
33
  bounds={'population':(1,1024,True),'generations':(1,2000,True),'ticks':(1,18000,True),
34
  'mutation':(0,4.2,False),'mutation_end':(0,4.2,False),'seed':(0,2147483647,True),
35
  'clean_min_laps':(1,100,True),'parents':(1,1024,True),'elite':(0,1024,True),'decay':(0,1,False),'workers':(1,4,True)}
@@ -37,7 +39,7 @@ def validate_config(value=None, *, work_limit=4_000_000):
37
  v=c[key]
38
  if type(v) not in (int,float) or not math.isfinite(v) or not low<=v<=high or (integer and type(v) is not int):raise ValueError('Invalid '+key)
39
  for key,choices in {'mode':('train','evaluate'),'schedule':('fixed','linear','geometric'),'selection':('best','tournament','roulette'),
40
- 'crossover':('none','single_point','uniform'),'control_hz':(60,30,15)}.items():
41
  if c[key] not in choices or (key=='control_hz' and type(c[key]) is not int):raise ValueError('Invalid '+key)
42
  for key in ('adaptive_mutation','collision','idle'):
43
  if type(c[key]) is not bool:raise ValueError('Invalid '+key)
 
30
  if value is None:return copy.deepcopy(DEFAULTS)
31
  if not isinstance(value,dict) or set(value)-set(DEFAULTS):raise ValueError('Unexpected training settings')
32
  c={**copy.deepcopy(DEFAULTS),**value}
33
+ if type(c['control_hz']) is not int or c['control_hz']!=60:
34
+ raise ValueError('New training and evaluation runs require control_hz=60; historical records are not converted')
35
  bounds={'population':(1,1024,True),'generations':(1,2000,True),'ticks':(1,18000,True),
36
  'mutation':(0,4.2,False),'mutation_end':(0,4.2,False),'seed':(0,2147483647,True),
37
  'clean_min_laps':(1,100,True),'parents':(1,1024,True),'elite':(0,1024,True),'decay':(0,1,False),'workers':(1,4,True)}
 
39
  v=c[key]
40
  if type(v) not in (int,float) or not math.isfinite(v) or not low<=v<=high or (integer and type(v) is not int):raise ValueError('Invalid '+key)
41
  for key,choices in {'mode':('train','evaluate'),'schedule':('fixed','linear','geometric'),'selection':('best','tournament','roulette'),
42
+ 'crossover':('none','single_point','uniform'),'control_hz':(60,)}.items():
43
  if c[key] not in choices or (key=='control_hz' and type(c[key]) is not int):raise ValueError('Invalid '+key)
44
  for key in ('adaptive_mutation','collision','idle'):
45
  if type(c[key]) is not bool:raise ValueError('Invalid '+key)
worker.py CHANGED
@@ -282,7 +282,7 @@ def run_native(track_bytes,network_bytes,*,binary=None,importer=None,scene_templ
282
  '--scene',str(scene),'--spawn-trace',spawn,'--network',network,'--init-network',network,
283
  '--model',model,'--settings',settings,'--shape',','.join(map(str,n['Shape'])),
284
  '--population',str(config['population']),'--generations',str(config['generations']),
285
- '--ticks',str(config['ticks']),'--seed',str(config['seed']),'--batch-count',str(60//config['control_hz']),
286
  '--out-dir',str(out),'--mutation-start',str(config['mutation']),
287
  '--mutation-end',str(config['mutation'] if config['schedule']=='fixed' else config['mutation_end']),
288
  '--schedule','linear' if config['schedule']=='fixed' else config['schedule'],'--save-final-candidate',
 
282
  '--scene',str(scene),'--spawn-trace',spawn,'--network',network,'--init-network',network,
283
  '--model',model,'--settings',settings,'--shape',','.join(map(str,n['Shape'])),
284
  '--population',str(config['population']),'--generations',str(config['generations']),
285
+ '--ticks',str(config['ticks']),'--seed',str(config['seed']),'--batch-count','1',
286
  '--out-dir',str(out),'--mutation-start',str(config['mutation']),
287
  '--mutation-end',str(config['mutation'] if config['schedule']=='fixed' else config['mutation_end']),
288
  '--schedule','linear' if config['schedule']=='fixed' else config['schedule'],'--save-final-candidate',