Spaces:
Running on Zero
Running on Zero
Add optional HF bucket consent, automatic unique saves, history and restore picker
Browse filesFiles changed (13)
- BUCKET_BUNDLE.md+3-3
- DATA_POLICY.md+16-16
- FRONTEND_SOURCE.json+3-3
- README.md+2
- RELEASE_MANIFEST.json+12-12
- STORAGE_BOUNDARY.md+4-3
- bucket_storage.py+200-22
- client.js+245-56
- hf-auth.js+89-26
- hf_identity.py+7-2
- index.html+8-7
- portable_bundle.py+35-4
- server.py+41-4
1 unmodified line23456782 unmodified lines1112131415161 unmodified lineThe browser supports explicit local-file export/import and optional direct save/restore to an existing private bucket. Local export downloads one JSON bundle. Restore validates the complete bundle before staging the network and any optional track or recipe in the current page. A restored receipt is kept in page memory and offered as a separate download. Restore never starts a run or writes browser storage.Bucket storage starts disconnected and never uploads automatically. The user enters a separate fine-grained token and explicitly connects, saves, refreshes, or restores. An expired/denied server response clears the page connection; the UI does not claim to know token expiry before a request. During those actions, the token and selected bundle pass through this app server to the user-owned private bucket; the app does not keep copies after the operation and exposes no bucket deletion, overwrite, creation, or visibility controls. Provider-side logs and retention are outside the app's deletion guarantee. The token is not included in the portable bundle. Existing run-retention controls remain independent. A separate local CLI guide is distributed with the candidate tooling for users who prefer local bucket transfer.## Envelope2 unmodified lines- A network stores its original `.evolution` bytes as base64 with byte length, SHA-256, format `evolution`, and kind `input` or `result`. The page validates decoded network content with its existing game-network validator and keeps the original bytes when staging it.- A track stores original `.track` bytes with length and SHA-256. A built-in track also records its catalog ID and display label; an uploaded track has no extra identifying metadata.- A recipe stores only version, A–J slot, name, and the existing validated training settings. Restore stages it into the form; saving it to the browser recipe library remains a separate user action.- A run receipt is an allowlisted summary only: build ID, backend, output hash, and whitelisted report fields for vehicle, counts, metrics, file hashes, and settings. It excludes history, paths, filenames, usernames, account data, job IDs/keys, and raw errors. Receipts that do not match the bundled network or included track are omitted on export or rejected on import.Caps are 4 MiB for network bytes, 1 MiB for track bytes, 32 KiB for recipe JSON, 128 KiB for receipt JSON, and 8 MiB for the complete bundle. Payload bytes and hashes must match exactly.1 unmodified line23456782 unmodified lines1112131415161 unmodified lineThe browser supports explicit local-file export/import and optional direct save/restore to an existing private bucket. Local export downloads one JSON bundle. Restore validates the complete bundle before staging the network and any optional track or recipe in the current page. A restored receipt is kept in page memory and offered as a separate download. Restore never starts a run or writes browser storage.Bucket storage starts disconnected. After an explicit HF OAuth authorization for `openid profile write-repos`, the user enters an existing private bucket ID and connects. Connected-run autosave is on by default and can be turned off; disconnected or manual-only runs make no bucket storage calls. HF describes `write-repos` as read/write access to personal repositories; the grant is broader than one selected bucket, is not a bucket-only permission, and its mapping to bucket access and minimum required scope still needs live qualification. During storage operations, the page-memory token and selected bundle pass through this app server to the user-owned bucket. The app removes temporary files after an operation and exposes no bucket deletion, overwrite, creation or visibility controls. An observed expired/denied response clears the connection; the UI does not claim advance token-expiry knowledge. Provider-side logs and retention are outside the app's deletion guarantee. The token is not included in the portable bundle. With autosave, the browser verifies output and confirms server deletion before sending the network and sanitized run report to the bucket. A failure preserves the received local candidate; a batch stops before its next run if saving is not confirmed. A separate local CLI guide is distributed with the candidate tooling for users who prefer local bucket transfer.## Envelope2 unmodified lines- A network stores its original `.evolution` bytes as base64 with byte length, SHA-256, format `evolution`, and kind `input` or `result`. The page validates decoded network content with its existing game-network validator and keeps the original bytes when staging it.- A track stores original `.track` bytes with length and SHA-256. A built-in track also records its catalog ID and display label; an uploaded track has no extra identifying metadata.- A recipe stores only version, A–J slot, name, and the existing validated training settings. Restore stages it into the form; saving it to the browser recipe library remains a separate user action.- A run receipt is an allowlisted summary only: build ID, backend, output hash, whitelisted report fields for vehicle, counts, metrics, file hashes, and settings, plus up to 1,000 validated generation-history rows. It excludes paths, filenames, usernames, account data, job IDs/keys, and raw errors. Receipts that do not match the bundled network or included track are omitted on export or rejected on import. A connected auto-save bundles the exact verified run output, its captured input track, and matching run receipt.Caps are 4 MiB for network bytes, 1 MiB for track bytes, 32 KiB for recipe JSON, 512 KiB for receipt JSON, and 8 MiB for the complete bundle. Payload bytes and hashes must match exactly.
2 unmodified lines345678930 unmodified lines404142434445465 unmodified lines525354555657585960616263646566678 unmodified lines7677787980818235 unmodified lines1181191201211221231241252 unmodified linesOperator: TiGa (seeker-cyber-maker). Candidate version: 2026-10-13. This package is not a receipt that a hosted deployment or publication has occurred.Files are processed only for the requested job, not collected for our owntraining, analytics or public examples. Inputs remain in the browser until Run or an explicit bucket save.The interface supports native CPU and, on a ZeroGPU deployment, an explicitlyselected GPU job. CPU requests do not acquire a GPU lease.30 unmodified linesbrowser saved to disk. An interrupted default-mode download is not retryable;Delete now and fixed expiry still work. Visitors can opt in for each single runto keep its result in application memory for repeat downloads until the samefive-minute deadline. The checkbox resets after every run. Batch runs alwaysuse automatic deletion. Delete now removes a stored result immediately, anddownloads never reset expiry. The browser can also save its received resultagain from page memory.5 unmodified linesof physical RAM/disk erasure, prevention of swap, or deletion of response buffers.No claim is made about hosting-provider logs or infrastructure retention.Optional HF sign-in uses the official HF OAuth authorization-code/PKCE flow withonly openid/profile scopes. Access tokens and basic profile details live in browserpage memory, not cookies, localStorage, recipes, or a server session database.Only the one-use PKCE verifier/nonce and start time are temporarily saved intab-local sessionStorage to survive the full-page redirect, with a five-minuteacceptance limit; they are removed on return, error, or a fresh app load. Closingthe tab loses them. HF handles password entry and authorization. The callbackbriefly carries a one-use authorization code and state in its URL; the app clearsthat URL before loading the OAuth helper. HF/proxy infrastructure handling is outside thisapplication's deletion guarantee. The OAuth flow does not request email, billing, repository access or bucket scopes. Optional bucket operations use the separate user-supplied credential described below.A non-GPU queue check forwards the visitor bearer credential to HF's fixeduserinfo endpoint and returns only the username, PRO flag, and authentication8 unmodified linesThe browser retains its received result in page memory so Save received resultagain can retry a local save without another server retrieval. Discard browserresult clears the app's reference; closing or refreshing the page loses it.Optional bucket access is separate from HF sign-in. The user enters a fine-grained token for an existing private bucket; it remains in page memory and is sent with the requested bundle through this app server only for explicit Connect, Save, Refresh or Restore actions. Training and result deletion do not require a bucket connection.The service uses one result-owning process. HF framework and proxy behavior may have retention outside this app, so this isan application-level near-zero-retention design, not a provider-wide ZDR claim.35 unmodified lines## Optional private bucket storageBucket storage starts disconnected and never saves automatically. The user enters an existing private bucket ID and a separate fine-grained HF token, then explicitly selects Connect, Save, Refresh saved bundles or Restore. The token is held in this page's memory, sent in the Authorization header only to the app's fixed bucket routes, and cleared on disconnect, after the app receives an expired/denied response, or on page close. It is not the HF OAuth identity token and is not stored in localStorage, recipes, portable bundles, run receipts, URLs or application logs.For an explicit operation, the selected bundle and the bucket token pass through this app server to the user's private bucket. The storage bridge uses a short-lived worker and temporary cache, removes temporary files on completion or failure, and does not keep application copies after the operation. The saved object remains in the user's bucket under the app-owned prefix until the user manages it through another authorized tool; this app does not expose bucket deletion, overwriting, creation, or visibility changes. A failed save or restore leaves the page's received result and ordinary training controls available.These are application-level handling rules, not a guarantee about HF, network, proxy or hosting-provider logs and retention. They do not establish provider-wide zero data retention or secure physical erasure.2 unmodified lines345678930 unmodified lines404142434445465 unmodified lines52535455565758596061626364656667688 unmodified lines77787980818235 unmodified lines1181191201211221231241252 unmodified linesOperator: TiGa (seeker-cyber-maker). Candidate version: 2026-10-13. This package is not a receipt that a hosted deployment or publication has occurred.Files are processed only for the requested job, not collected for our owntraining, analytics or public examples. Inputs remain in the browser until Run or an explicit bucket action.The interface supports native CPU and, on a ZeroGPU deployment, an explicitlyselected GPU job. CPU requests do not acquire a GPU lease.30 unmodified linesbrowser saved to disk. An interrupted default-mode download is not retryable;Delete now and fixed expiry still work. Visitors can opt in for each single runto keep its result in application memory for repeat downloads until the samefive-minute deadline when bucket autosave is disconnected or off. The checkbox resets after every run. Batch runs alwaysuse automatic deletion. Delete now removes a stored result immediately, anddownloads never reset expiry. The browser can also save its received resultagain from page memory.5 unmodified linesof physical RAM/disk erasure, prevention of swap, or deletion of response buffers.No claim is made about hosting-provider logs or infrastructure retention.Optional HF identity sign-in uses the official OAuth authorization-code/PKCE flowwith openid/profile scopes. It identifies account GPU requests and is independentof CPU access. Access tokens and basic profile details live in browser page memory,not cookies, localStorage, recipes, or a server session database. Only the one-usePKCE verifier/nonce, purpose and start time are temporarily saved in tab-localsessionStorage to survive the full-page redirect, with a five-minute acceptancelimit; they are removed on return, error, or a fresh app load. Closing the tab losesthem. HF handles password entry and authorization. The callback briefly carries aone-use authorization code and state in its URL; the app clears that URL beforeloading the OAuth helper. HF/proxy infrastructure handling is outside thisapplication's deletion guarantee.A non-GPU queue check forwards the visitor bearer credential to HF's fixeduserinfo endpoint and returns only the username, PRO flag, and authentication8 unmodified linesThe browser retains its received result in page memory so Save received resultagain can retry a local save without another server retrieval. Discard browserresult clears the app's reference; closing or refreshing the page loses it.The service uses one result-owning process. HF framework and proxy behavior may have retention outside this app, so this isan application-level near-zero-retention design, not a provider-wide ZDR claim.35 unmodified lines## Optional private bucket storageBucket storage starts disconnected. After an explicit HF OAuth authorization and connection to an existing private bucket, automatic saving is on by default and can be turned off for manual saves. With no connection or autosave turned off, completed runs make no bucket storage calls. With autosave enabled, each completed run is downloaded and hash-verified in the browser, then the application confirms deletion of the server result before it sends the resulting network and sanitized run report to the bucket. Each batch result is saved before the next run starts; a save failure stops the batch. A failed receive has no verified local copy; a deletion-acknowledgment failure skips bucket saving; after confirmed deletion, an unconfirmed bucket save leaves the verified local candidate available for download or manual retry. A remote save might have completed if its response could not be verified.HF describes the requested `write-repos` scope as read/write access to personal repositories. This grant is broader than one selected bucket and has not been confirmed as bucket-only or the minimum required scope. The token and bundle pass through this app server during storage operations; the app keeps the token in page memory only and removes temporary storage files after operations. It does not save tokens in URLs, browser storage, receipts or bundles. Disconnect, observed authorization denial/expiry, and page close clear the app's connection. The app has no bucket create, delete, overwrite or visibility controls; saved objects remain in the user's bucket until managed elsewhere. Provider-side logs and retention are outside app cleanup guarantees, which do not establish provider-wide zero data retention or secure physical erasure.Connecting checks the listed bundles and selects the newest compatible entry among those returned. It restores the entry in this page only when there is no existing network, track, result or editor draft; otherwise it only selects it. The list is bounded, so an incomplete scan may omit a newer bundle. No run starts automatically. Reports contain only fields returned by the engine, including generation history and configured settings; reward weights are not reported as per-reward contributions.
12345678910{"source": "Runner r14 single-engine browser UI; selected .track tile renderer added from simulator atlas","source_sha256": "65d1e5f2c4e19b4951b828e82510005ab99a5270cf3dcb9f4eaa0fa1af8c40f8","output_sha256": "f6834f72d072bbfea28af7f1a686c5439be06c5c0848873ab6723745ea330051","scope": "Frontend only; no engine, private data, track assets, API calls or storage copied","status": "Local v1.1 hosted bucket candidate: explicit private bucket connect/save/list/restore plus local portable bundles; not deployed","track_atlas_sha256": "d97c8900e3e5fb17734b5bd61d1f4f4b196d9be30af9848e2e273ae7e4079ae4","client_sha256": "b47fc63b34fc68a7d3eb43317f574a16ebded99d296d7aea3d2f6f47a86ebc6b","track_map_sha256": "ab5374aa49c7ccec90a787ee8c56cd71beb56b903bf2bbc322783e6f43c009f0"}12345678910{"source": "Runner r14 single-engine browser UI; selected .track tile renderer added from simulator atlas","source_sha256": "65d1e5f2c4e19b4951b828e82510005ab99a5270cf3dcb9f4eaa0fa1af8c40f8","output_sha256": "a145fbb303a85c728a530d98fbea998677c1c62a2589c46af9b8b287e4ce1f48","scope": "Frontend only; no engine, private data, track assets, API calls or storage copied","status": "Reviewed candidate with optional HF bucket OAuth, connected autosave, unique exports, player reports and latest-network picker; hosted qualification recorded separately","track_atlas_sha256": "d97c8900e3e5fb17734b5bd61d1f4f4b196d9be30af9848e2e273ae7e4079ae4","client_sha256": "7e4bea3b9d2ffa79533ff6abed54481a3a6530e8152093f388e229c621bed9ec","track_map_sha256": "ab5374aa49c7ccec90a787ee8c56cd71beb56b903bf2bbc322783e6f43c009f0"}
5 unmodified lines678910115 unmodified linesapp_file: app.pyhf_oauth: truehf_oauth_expiration_minutes: 60---Public GPU app package. Its intended topology is a publicly reachable app at https://tiga-rce-ald-tao-gpu.hf.space/ with the GPU Space source repository restricted; the standalone CPU Space remains private. Deployment status and build-specific qualification are recorded in the release receipt. The native runner accepts Formula (Type 0), Rally (Type 1), Snowmobile (Type 2), and Truck (Type 3) networks and selects a packaged trusted scene template from the network type. Build-specific native vehicle support must be qualified with the matching simulator and importer binaries recorded in the release receipt. CPU runs anonymously. GPU is explicitly selected and subject to available HF allowance; optional HF sign-in uses the official OAuth flow and needs no personal token entry.5 unmodified lines6789101112135 unmodified linesapp_file: app.pyhf_oauth: truehf_oauth_expiration_minutes: 60hf_oauth_scopes:- write-repos---Public GPU app package. Its intended topology is a publicly reachable app at https://tiga-rce-ald-tao-gpu.hf.space/ with the GPU Space source repository restricted; the standalone CPU Space remains private. Deployment status and build-specific qualification are recorded in the release receipt. The native runner accepts Formula (Type 0), Rally (Type 1), Snowmobile (Type 2), and Truck (Type 3) networks and selects a packaged trusted scene template from the network type. Build-specific native vehicle support must be qualified with the matching simulator and importer binaries recorded in the release receipt. CPU runs anonymously. GPU is explicitly selected and subject to available HF allowance; optional HF sign-in uses the official OAuth flow and needs no personal token entry.
3 unmodified lines456789101112131415161718196 unmodified lines2627282930313225 unmodified lines5859606162636465666768697071723 unmodified lines".gitattributes": "c2ad16718fc51c888d32efc88c8f6e23ebe5fcf6f48e2954f896ba9770f24d72","BETA_TESTING.md": "27e2492f9fe87cc04f52de2974b685b44041f7de9fa1155926b66c436f0bc613","BINARY_PROVENANCE.json": "825d98f9ae91d88ee08143b11d1af9dd6f889c37f68dbea24163f718759dda3e","BUCKET_BUNDLE.md": "34dfebb783ca61b5b362ca9b2d936e19c87ea440f87558a8a5cfcb11ce1fdd30","CUDA_REFERENCE.md": "f7453c3254d244f8b0de41fde5851cb025159f5cea4a4d1a5d8208a955550c6c","DATA_POLICY.md": "015ba656568b956f058359d141bd6adb9e8b7fd07bcad50c10c132455c7a4a19","FEEDBACK.md": "f95b8f6afbf4a360976c0edca5d52f5b3a0b668c9a944d4947b840a7c53a122a","FRONTEND_SOURCE.json": "1adfdbd649fb75b9ce80d58134c182b19e4b1877b40130efac0767a80947b6cd","GODOT_LICENSE": "fb2b3bb82c60f1e76841ba2122eb902f8e39c151476fe21ce10c9a05d1045304","IMPORTER_BUILD_RECEIPT.json": "4ba5c533cc617105478e4d85c83f456a7dfa68b1388049624619871ba9e42e9d","LICENSE": "53d5851b6440feeae36f72a5f57fcab37858c48b7084765ece4b0c54b9a28ed8","README.md": "b2e1d4a21c1ffd0d652a6e2448284b358f4e42dbfa8a0af6b1842d55c2f7c954","STORAGE_BOUNDARY.md": "e0df12d422a3e9bcc85468fcb6af202fd65551cba6f84d2c8f70f03e8e8cc55e","TRACK_LIBRARY.md": "66b3656ed84f137d5b6116a0075731cd467818f555cca0969084aff67875319f","UPSTREAM.json": "003235bbdf5e966561797fbe3d8bfc65c7c43d4a887fa54c3e6a96fb7c0c6938","app.py": "162486abd6ac7c9281c8e75c15e33373e0fddba2baf6a799dfd54d333fd575d2",6 unmodified lines"bin/altd-sim": "0135ecc3d435a9d327be7a92e048cfb5c5291a02ef1e0dddd6ead1cc19b31166","bin/extract_saved_track": "3a7733c45b4301a786fcbfe92660a1c484749272da5f608d62f34878bd4ff31a","bin/libaltd_gpu.so": "3b1b88bccc06a21acc33ac4400af016d55a7e3d8727136a0c43b541f3c7887ca","bucket_storage.py": "6dedcdc6391be574805208e36c4f553e1c3e6faf41c68783c4c825e093dc9d94","build_info.py": "93d331c0405cd10076a544f87761bb4a00f6556bbbdab8abc12e070c4661bd78","builtin_tracks.py": "2ecc2b1d00fe15701b0271d71e1e68d2e7e59c596330879494055f9b2a99c242","builtin_tracks/catalog.json": "65006e70a87a5a53e3738166b0895bc4db9f99767dd891d917b68029abb4e80a",25 unmodified lines"builtin_tracks/tracks/Replica R08 Demolition Derby.track": "6f11a9ffbcb477c9d19964566b1b612d2a94675605246e93e21f27bbbdb357ef","builtin_tracks/tracks/Replica R09 Eau Noir.track": "3ec0a78478cca1a4f0d2d98ac81f40783928adf271b70f0c32d295a6da2cdaa9","builtin_tracks/tracks/Replica The Champions Trial.track": "a3bfb76422affc774b44c739b0636d08acb901fa7615b9adcb52c069f79834e1","client.js": "b47fc63b34fc68a7d3eb43317f574a16ebded99d296d7aea3d2f6f47a86ebc6b","delivery.py": "07453999c3831a16e8b1fcc2b4ae5fb28beb7d3952a3fae8de65d16eb6f11e5b","gpu_tickets.py": "b81aadb5ed42cec9212d44da7e7bbb7b413c5bd517383cac0b49ec9b4d659c92","hf-auth.js": "d5cf17b961d1f2efa9d4648d33ba86a148eff0d542c74a121710c4df35c92936","hf_identity.py": "6993d0238ada835606dbdc3275c17a3fe5a5cac5ad2156ab78230acf2d051eba","index.html": "f6834f72d072bbfea28af7f1a686c5439be06c5c0848873ab6723745ea330051","portable_bundle.py": "933915422905883e74081fa073a8024024d3d92662bf653f2174c212fa6cb5da","requirements.txt": "fc7e0703ad2289fd3926a36efbdce8c61f0edc00f7575a87e2b565e46588c5a4","server.py": "209936a7f21c290514b1dda68f3c9121366df907c9f7b9ffb08a17c9941ec29f","steam_leaderboard.py": "d76397c39cae58f636ddf9a9be1a46ae3d77fefd6b7269feac73d34d97165481","track-library.js": "351ec4c026b49420ce963f4310cb000d9e987fd28e6dac5ecd0176509340f6e6","track-map.js": "ab5374aa49c7ccec90a787ee8c56cd71beb56b903bf2bbc322783e6f43c009f0",3 unmodified lines456789101112131415161718196 unmodified lines2627282930313225 unmodified lines5859606162636465666768697071723 unmodified lines".gitattributes": "c2ad16718fc51c888d32efc88c8f6e23ebe5fcf6f48e2954f896ba9770f24d72","BETA_TESTING.md": "27e2492f9fe87cc04f52de2974b685b44041f7de9fa1155926b66c436f0bc613","BINARY_PROVENANCE.json": "825d98f9ae91d88ee08143b11d1af9dd6f889c37f68dbea24163f718759dda3e","BUCKET_BUNDLE.md": "8130b374ffa54dd8539910b58b9f1c8d49eb62098db7aa2c560762da9356e25c","CUDA_REFERENCE.md": "f7453c3254d244f8b0de41fde5851cb025159f5cea4a4d1a5d8208a955550c6c","DATA_POLICY.md": "f6f7057cda3eac7b40122ffe1ead0e0accd496bc0f5bd20fabf83dce83edfc72","FEEDBACK.md": "f95b8f6afbf4a360976c0edca5d52f5b3a0b668c9a944d4947b840a7c53a122a","FRONTEND_SOURCE.json": "67d3348aa3c119c766f259c97d665d93e6a503e7b0ac7eab2f49a66776efd1e3","GODOT_LICENSE": "fb2b3bb82c60f1e76841ba2122eb902f8e39c151476fe21ce10c9a05d1045304","IMPORTER_BUILD_RECEIPT.json": "4ba5c533cc617105478e4d85c83f456a7dfa68b1388049624619871ba9e42e9d","LICENSE": "53d5851b6440feeae36f72a5f57fcab37858c48b7084765ece4b0c54b9a28ed8","README.md": "b7d9e16dc252925f9c0db14b4811afae00de6c6af29439f9a9788791c7cb9a75","STORAGE_BOUNDARY.md": "a35197d79e13f868323bff9ad736fa9ef3233649c2cac44ae40bbc4881939310","TRACK_LIBRARY.md": "66b3656ed84f137d5b6116a0075731cd467818f555cca0969084aff67875319f","UPSTREAM.json": "003235bbdf5e966561797fbe3d8bfc65c7c43d4a887fa54c3e6a96fb7c0c6938","app.py": "162486abd6ac7c9281c8e75c15e33373e0fddba2baf6a799dfd54d333fd575d2",6 unmodified lines"bin/altd-sim": "0135ecc3d435a9d327be7a92e048cfb5c5291a02ef1e0dddd6ead1cc19b31166","bin/extract_saved_track": "3a7733c45b4301a786fcbfe92660a1c484749272da5f608d62f34878bd4ff31a","bin/libaltd_gpu.so": "3b1b88bccc06a21acc33ac4400af016d55a7e3d8727136a0c43b541f3c7887ca","bucket_storage.py": "a0c17fa2ddde99f25b4cfc017557b4d8826f72ebbf3898a2394f072227ececa6","build_info.py": "93d331c0405cd10076a544f87761bb4a00f6556bbbdab8abc12e070c4661bd78","builtin_tracks.py": "2ecc2b1d00fe15701b0271d71e1e68d2e7e59c596330879494055f9b2a99c242","builtin_tracks/catalog.json": "65006e70a87a5a53e3738166b0895bc4db9f99767dd891d917b68029abb4e80a",25 unmodified lines"builtin_tracks/tracks/Replica R08 Demolition Derby.track": "6f11a9ffbcb477c9d19964566b1b612d2a94675605246e93e21f27bbbdb357ef","builtin_tracks/tracks/Replica R09 Eau Noir.track": "3ec0a78478cca1a4f0d2d98ac81f40783928adf271b70f0c32d295a6da2cdaa9","builtin_tracks/tracks/Replica The Champions Trial.track": "a3bfb76422affc774b44c739b0636d08acb901fa7615b9adcb52c069f79834e1","client.js": "7e4bea3b9d2ffa79533ff6abed54481a3a6530e8152093f388e229c621bed9ec","delivery.py": "07453999c3831a16e8b1fcc2b4ae5fb28beb7d3952a3fae8de65d16eb6f11e5b","gpu_tickets.py": "b81aadb5ed42cec9212d44da7e7bbb7b413c5bd517383cac0b49ec9b4d659c92","hf-auth.js": "866b36d1d5332311a15ab5cc75a5e941c208bd5d2ab3bdb100590dd9a97e7817","hf_identity.py": "913fb1e089af21f376e8359a20cbc838d5bcd7971def6989a4382d53c1127b37","index.html": "a145fbb303a85c728a530d98fbea998677c1c62a2589c46af9b8b287e4ce1f48","portable_bundle.py": "dec236bf875a431b650e04715e2677344203ec2f1eedc63493caee97f338d50f","requirements.txt": "fc7e0703ad2289fd3926a36efbdce8c61f0edc00f7575a87e2b565e46588c5a4","server.py": "06e2a27e110f655cfc9bf4aabdc74a88b735ad366aab36e0b5907aa780feb024","steam_leaderboard.py": "d76397c39cae58f636ddf9a9be1a46ae3d77fefd6b7269feac73d34d97165481","track-library.js": "351ec4c026b49420ce963f4310cb000d9e987fd28e6dac5ecd0176509340f6e6","track-map.js": "ab5374aa49c7ccec90a787ee8c56cd71beb56b903bf2bbc322783e6f43c009f0",
12 unmodified lines131415161718192021222 unmodified lines2526272829303112 unmodified lines| GPU pending inputs | Opaque single-use ticket plus memory store | Dispatch, confirmed quota-rejection discard, fixed 120-second expiry, or shutdown || Single-run output | Memory result store and random job key | Default receipt ACK; opt-in repeat download until fixed five-minute expiry; manual delete or shutdown || Batch intermediates | Same job contract, always automatic | Verified size/hash and deletion ACK before advancement || Received candidate / receipt | Browser page memory | Explicit discard, replacement, page reload/close; explicit export to disk || Optional HF identity / token | Browser page memory, separate from job/recipe storage | Sign out, expiry, or page reload/close; no app auth cookie or server session database || One-use HF PKCE verifier/nonce | Tab-local sessionStorage for the sign-in redirect only | Five-minute acceptance limit; removed on return/error/fresh app load or tab close; never stores access tokens or files || User private bucket | Separate optional connection with explicit Save, Refresh and Restore | Only user-selected bundles are sent through the app server; the object remains in the user bucket until managed elsewhere; this app exposes no delete/overwrite/create/visibility operation |`recipes.cjs` has no host/network dependency. Its `createStore(storage)` receivesonly getItem/setItem/removeItem capabilities. A future bucket adapter must keep2 unmodified linesartifact storage implicitly. Server cleanup must never clear the recipe library;clearing recipes must never delete a server job, bucket, or downloaded file.The app has no persistent HF identity or bucket credential storage, telemetry, or automatic recipe/bundle upload. Bucket operations are explicit and application-level cleanup does not make provider-wide retention claims. Browser-local storage is site-specific and may beblocked by browser privacy settings. A local runner and an HF iframe do notautomatically share their library; explicit JSON export/import is the bridge.12 unmodified lines13141516171819202122232 unmodified lines2627282930313212 unmodified lines| GPU pending inputs | Opaque single-use ticket plus memory store | Dispatch, confirmed quota-rejection discard, fixed 120-second expiry, or shutdown || Single-run output | Memory result store and random job key | Default receipt ACK; opt-in repeat download until fixed five-minute expiry; manual delete or shutdown || Batch intermediates | Same job contract, always automatic | Verified size/hash and deletion ACK before advancement || Received candidate / receipt | Browser page memory | Explicit discard, replacement, page reload/close; download to disk or optional connected-bucket autosave || Optional HF identity / token | Browser page memory, separate from job/recipe storage | Sign out, expiry, or page reload/close; no app auth cookie or server session database || Optional HF bucket OAuth grant | Separate explicit `openid profile write-repos` authorization; shared in memory with identity when granted together | Disconnect, observed expiry/denial, or page reload/close; no token in URL, localStorage, recipes or bundles || One-use HF PKCE verifier/nonce | Tab-local sessionStorage for the sign-in redirect only | Five-minute acceptance limit; removed on return/error/fresh app load or tab close; never stores access tokens or files || User private bucket | Separate optional connection; autosave is on by default after connection and can be disabled; explicit Save, Refresh and Restore remain available | Verified run output is sent through the app server only after result deletion is confirmed; a failed save keeps the local candidate; bucket objects remain until managed elsewhere |`recipes.cjs` has no host/network dependency. Its `createStore(storage)` receivesonly getItem/setItem/removeItem capabilities. A future bucket adapter must keep2 unmodified linesartifact storage implicitly. Server cleanup must never clear the recipe library;clearing recipes must never delete a server job, bucket, or downloaded file.The app has no persistent HF identity or bucket credential storage, telemetry, or automatic recipe upload. Optional bucket authorization requests `write-repos`, which HF describes as read/write access to personal repositories; that scope is broader than one selected bucket, and a bucket-only minimum permission has not been confirmed. Explicit bucket operations and connected autosave send the selected bundle and page-memory OAuth token through this app server. Application-level cleanup does not make provider-wide retention claims. Browser-local storage is site-specific and may beblocked by browser privacy settings. A local runner and an HF iframe do notautomatically share their library; explicit JSON export/import is the bridge.
1 unmodified line234567893 unmodified lines13141516171819202122232425262710 unmodified lines38394041424344139 unmodified lines1841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212221 unmodified line2242252262272282292302312322332341 unmodified linefrom __future__ import annotationsimport base64from datetime import datetime, timezoneimport hashlibimport jsonimport osfrom pathlib import Path3 unmodified linesimport tempfileimport uuidfrom portable_bundle import BundleError, MAX_BUNDLE, load_bundleHF_ENDPOINT = "https://huggingface.co"MAX_REQUEST = 2 * MAX_BUNDLE + 64 * 1024MAX_CHILD_INPUT = 4 * ((MAX_BUNDLE + 2) // 3) + 64 * 1024MAX_CHILD_OUTPUT = 128 * 1024CHILD_TIMEOUT_SECONDS = 55MAX_LIST_SCAN = 50APP_KEY = re.compile(r"^ald-exports/([0-9a-f]{32}|[0-9a-f]{64})/bundle\.json$")BUCKET_ID = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}/[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$")10 unmodified linesdef valid_bundle_key(value: object) -> bool:return isinstance(value, str) and bool(APP_KEY.fullmatch(value))def _child_environment(cache_root: Path) -> dict[str, str]:139 unmodified linesreturn {"status": "connected", "bucket_id": bucket_id, "username": username, "private": True}if operation == "list":items = []truncated = Falsefor index, item in enumerate(api.list_bucket_tree(bucket_id, prefix="ald-exports", recursive=True, token=token)):if index >= MAX_LIST_SCAN:truncated = Truebreakkey = getattr(item, "path", None)size = getattr(item, "size", None)match = APP_KEY.fullmatch(key) if isinstance(key, str) else Noneif match and type(size) is int and 0 <= size <= MAX_BUNDLE:uploaded = getattr(item, "uploaded_at", None) or getattr(item, "mtime", None)if isinstance(uploaded, datetime):if uploaded.tzinfo is None:uploaded = uploaded.replace(tzinfo=timezone.utc)date_label = uploaded.astimezone(timezone.utc).strftime("%Y-%m-%d %H:%M UTC")else:date_label = "Saved bundle"items.append({"key": key, "bytes": size, "label": f"{date_label} · {match.group(1)[:8]}"})return {"items": items, "truncated": truncated}if operation == "save":encoded = request.get("bundle_base64")if not isinstance(encoded, str) or len(encoded) > 4 * ((MAX_BUNDLE + 2) // 3):raise BucketStorageError("invalid_request")try:bundle = base64.b64decode(encoded, validate=True)load_bundle(bundle)except Exception:raise BucketStorageError("invalid_bundle") from Nonedigest = hashlib.sha256(bundle).hexdigest()prefix = f"ald-exports/{uuid.uuid4().hex}"key = f"{prefix}/bundle.json"source = temp / "upload"source.mkdir(mode=0o700)(source / "bundle.json").write_bytes(bundle)try:api.sync_bucket(str(source), f"hf://buckets/{bucket_id}/{prefix}",1 unmodified line)except Exception:raise BucketStorageError("storage_unavailable") from Nonereadback = temp / "readback.json"size, _ = _download_descriptor(api, token, bucket_id, key, readback)if size != len(bundle) or hashlib.sha256(readback.read_bytes()).hexdigest() != digest:raise BucketStorageError("storage_unavailable")return {"status": "saved_verified", "bucket_id": bucket_id, "key": key, "bytes": size, "sha256": digest}key = request.get("key")if not valid_bundle_key(key):raise BucketStorageError("invalid_request")1 unmodified line2345678910113 unmodified lines151617181920212223242526272829303132333435363738394010 unmodified lines51525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211139 unmodified lines3513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893901 unmodified line3923933943953963973983994004014024034044054064074084094104114121 unmodified linefrom __future__ import annotationsimport base64import csvfrom datetime import datetime, timezoneimport hashlibimport ioimport jsonimport osfrom pathlib import Path3 unmodified linesimport tempfileimport uuidfrom portable_bundle import BundleError, MAX_BUNDLE, MAX_NETWORK, load_bundlefrom worker import network_inputHF_ENDPOINT = "https://huggingface.co"MAX_REQUEST = 2 * MAX_BUNDLE + 64 * 1024MAX_CHILD_INPUT = 4 * ((MAX_BUNDLE + 2) // 3) + 64 * 1024MAX_CHILD_OUTPUT = 128 * 1024CHILD_TIMEOUT_SECONDS = 55MAX_LIST_SCAN = 10_000MAX_LIST_RESULTS = 50LEGACY_APP_KEY = re.compile(r"^ald-exports/([0-9a-f]{32}|[0-9a-f]{64})/bundle\.json$")AUTOSAVE_APP_KEY = re.compile(r"^ald-exports/(?P<timestamp>[0-9]{8}T[0-9]{6}Z)-"r"(?P<track>[a-z0-9][a-z0-9-]{0,63})-"r"(?P<vehicle>formula|rally|snowmobile|truck)-"r"g(?P<generations>0|[1-9][0-9]{0,3})-"r"lap(?P<lap>none|[0-9]{1,16}ms)-(?P<uuid>[0-9a-f]{32})/bundle\.json$")VEHICLE_NAMES = ("Formula", "Rally", "Snowmobile", "Truck")MAX_SIDECAR_TOTAL = 1024 * 1024BUCKET_ID = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}/[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$")10 unmodified linesdef valid_bundle_key(value: object) -> bool:return isinstance(value, str) and bool(LEGACY_APP_KEY.fullmatch(value) or AUTOSAVE_APP_KEY.fullmatch(value))def _autosave_prefix(bundle: dict, files: dict[str, bytes], now: datetime | None = None) -> tuple[str, str, str]:artifacts = bundle["artifacts"]receipt = artifacts.get("run_receipt")track = artifacts.get("selected_track")track_id = _track_path_slug(track)if receipt is not None:report = receipt["report"]vehicle_type = report["vehicle_type"]generations = report["generations_completed"]lap = report["best_lap_seconds"]else:try:vehicle_type = network_input(files["selected_network.evolution"])["Type"]except Exception:raise BucketStorageError("invalid_bundle") from Nonegenerations = 0lap = Nonevehicle = VEHICLE_NAMES[vehicle_type]timestamp = (now or datetime.now(timezone.utc)).astimezone(timezone.utc).strftime("%Y%m%dT%H%M%SZ")lap_part = "none" if lap is None else f"{int(round(lap * 1000))}ms"segment = f"{timestamp}-{track_id}-{vehicle.lower()}-g{generations}-lap{lap_part}-{uuid.uuid4().hex}"return f"ald-exports/{segment}", track_id, timestampdef _readable_track(track_id: str, track: dict | None) -> str:if isinstance(track, dict) and track.get("source") == "builtin":return _track_path_slug(track)if track_id == "custom":return "custom-track"return "custom-track"def _track_path_slug(track: dict | None) -> str:if isinstance(track, dict) and track.get("source") == "builtin":display_name = track.get("display_name")if isinstance(display_name, str):slug = re.sub(r"[^A-Za-z0-9]+", "-", display_name).strip("-").lower()[:64].strip("-")if slug and re.fullmatch(r"[a-z0-9][a-z0-9-]{0,63}", slug):return slugtrack_id = track.get("track_id")if isinstance(track_id, str):fragment = re.sub(r"[^A-Za-z0-9]+", "-", track_id).strip("-").lower()[:48].strip("-")if fragment:return "track-" + fragmentreturn "custom"def _render_history_csv(report: dict) -> bytes:stream = io.StringIO(newline="")writer = csv.writer(stream, lineterminator="\n")fields = ("generation", "mutation", "best_score", "mean_score", "best_lap_seconds", "lapped_cars", "simulated_ticks")writer.writerow(fields)for row in report.get("history", []):writer.writerow(["" if row[field] is None else row[field] for field in fields])return stream.getvalue().encode("utf-8")def _render_report(bundle: dict) -> bytes:artifacts = bundle["artifacts"]receipt = artifacts["run_receipt"]report = receipt["report"]track = artifacts.get("selected_track")track_label = track.get("display_name", "Built-in track") if isinstance(track, dict) and track.get("source") == "builtin" else "Custom or uploaded track"lap = report["best_lap_seconds"]lap_label = "No completed lap" if lap is None else f"{lap:.3f} s"lines = ["# ALD training run","",f"- Track: {track_label}",f"- Vehicle: {report['vehicle_name']}",f"- Backend: {receipt['backend']} ({report['execution_backend']})",f"- Build: {receipt['build_id']}",f"- Generations: {report['generations_completed']} completed of {report['generations_requested']} requested",f"- Population: {report['population']}",f"- Final-generation best score: {report['best_score']}",f"- Final-generation mean score: {report['mean_score']}",f"- Best completed lap observed during this run: {lap_label}","- The best completed lap may belong to a different car than the exported candidate.",f"- Lapped cars in the final generation: {report['lapped_cars']}",f"- Simulated ticks: {report['simulated_ticks']} of {report['requested_ticks']} requested per car",f"- Elapsed seconds: {report['elapsed_seconds']:.3f}",f"- Exported network SHA-256: {receipt['output_sha256']}","","## Validated run settings","",]for key in sorted(report["settings"]):lines.append(f"- {key}: `{json.dumps(report['settings'][key], ensure_ascii=True, allow_nan=False, separators=(',', ':'))}`")return ("\n".join(lines) + "\n").encode("utf-8")def _save_files(bundle_bytes: bytes, bundle: dict, files: dict[str, bytes], *, now: datetime | None = None) -> tuple[str, dict[str, bytes]]:prefix, track, timestamp = _autosave_prefix(bundle, files, now)artifacts = bundle["artifacts"]receipt = artifacts.get("run_receipt")if receipt is not None:report = receipt["report"]vehicle = report["vehicle_name"].lower()else:vehicle = VEHICLE_NAMES[network_input(files["selected_network.evolution"])["Type"]].lower()uploads = {"bundle.json": bundle_bytes}network_suffix = prefix.rsplit("-", 1)[-1][:8]uploads[f"{_readable_track(track, artifacts.get('selected_track'))}-{vehicle}-{timestamp}-{network_suffix}.evolution"] = files["selected_network.evolution"]if receipt is not None:uploads["report.md"] = _render_report(bundle)uploads["generation-history.csv"] = _render_history_csv(receipt["report"])if sum(map(len, uploads.values())) > MAX_BUNDLE + MAX_NETWORK + MAX_SIDECAR_TOTAL:raise BucketStorageError("invalid_bundle")return prefix, uploadsdef _list_metadata(key: str, uploaded: datetime | None) -> tuple[str, str | None]:match = AUTOSAVE_APP_KEY.fullmatch(key)if match:try:path_when = datetime.strptime(match.group("timestamp"), "%Y%m%dT%H%M%SZ").replace(tzinfo=timezone.utc)except ValueError:path_when = Nonewhen = _valid_utc_datetime(uploaded) or path_whenif when is None:created_at = Nonedate_label = "Saved bundle"else:# Fixed fractional precision keeps lexicographic ordering chronological# when multiple uploads occur within the same generated-key second.created_at = when.isoformat(timespec="microseconds").replace("+00:00", "Z")date_label = when.strftime("%Y-%m-%d %H:%M UTC")lap = match.group("lap")lap_label = "no completed lap" if lap == "none" else f"best run lap {int(lap[:-2])} ms"track = "Custom track" if match.group("track") == "custom" else match.group("track").replace("-", " ").title()label = f"{date_label} · {track} · {match.group('vehicle').title()} · {match.group('generations')} generations · {lap_label}"return label[:192], created_atdate_label = "Saved bundle"created_at = Noneuploaded = _valid_utc_datetime(uploaded)if uploaded is not None:date_label = uploaded.strftime("%Y-%m-%d %H:%M UTC")created_at = uploaded.isoformat(timespec="microseconds").replace("+00:00", "Z")legacy = LEGACY_APP_KEY.fullmatch(key)label = f"{date_label} · imported portable network {legacy.group(1)[:8] if legacy else ''}".strip()return label[:192], created_atdef _valid_utc_datetime(value: object) -> datetime | None:if not isinstance(value, datetime):return Nonetry:if value.tzinfo is None:value = value.replace(tzinfo=timezone.utc)return value.astimezone(timezone.utc)except (OverflowError, ValueError):return Nonedef _child_environment(cache_root: Path) -> dict[str, str]:139 unmodified linesreturn {"status": "connected", "bucket_id": bucket_id, "username": username, "private": True}if operation == "list":items = []scan_incomplete = Falsefor index, item in enumerate(api.list_bucket_tree(bucket_id, prefix="ald-exports", recursive=True, token=token)):if index >= MAX_LIST_SCAN:scan_incomplete = Truebreakkey = getattr(item, "path", None)size = getattr(item, "size", None)match = (LEGACY_APP_KEY.fullmatch(key) or AUTOSAVE_APP_KEY.fullmatch(key)) if isinstance(key, str) else Noneif match and type(size) is int and 0 <= size <= MAX_BUNDLE:uploaded = getattr(item, "uploaded_at", None) or getattr(item, "mtime", None)label, created_at = _list_metadata(key, uploaded)items.append({"key": key, "bytes": size, "label": label, "created_at": created_at})# The primary ordering is newest first; unknown legacy timestamps remain at the end.items.sort(key=lambda item: item["created_at"] or "", reverse=True)truncated = len(items) > MAX_LIST_RESULTSif len(items) > MAX_LIST_RESULTS:items = items[:MAX_LIST_RESULTS]return {"items": items, "truncated": truncated, "scan_incomplete": scan_incomplete}if operation == "save":encoded = request.get("bundle_base64")if not isinstance(encoded, str) or len(encoded) > 4 * ((MAX_BUNDLE + 2) // 3):raise BucketStorageError("invalid_request")try:bundle = base64.b64decode(encoded, validate=True)bundle_obj, bundle_files = load_bundle(bundle)except Exception:raise BucketStorageError("invalid_bundle") from Nonedigest = hashlib.sha256(bundle).hexdigest()prefix, uploads = _save_files(bundle, bundle_obj, bundle_files)key = f"{prefix}/bundle.json"source = temp / "upload"source.mkdir(mode=0o700)for filename, content in uploads.items():(source / filename).write_bytes(content)try:api.sync_bucket(str(source), f"hf://buckets/{bucket_id}/{prefix}",1 unmodified line)except Exception:raise BucketStorageError("storage_unavailable") from Noneverified_files = {}for index, (filename, expected) in enumerate(uploads.items()):remote_path = f"{prefix}/{filename}"readback = temp / f"readback-{index}.bin"size, _ = _download_descriptor(api, token, bucket_id, remote_path, readback)content = readback.read_bytes()expected_sha = hashlib.sha256(expected).hexdigest()if size != len(expected) or hashlib.sha256(content).hexdigest() != expected_sha:raise BucketStorageError("storage_unavailable")verified_files[filename] = {"bytes": size, "sha256": expected_sha}if verified_files.get("bundle.json", {}).get("sha256") != digest:raise BucketStorageError("storage_unavailable")(temp / "readback.json").write_bytes(bundle)return {"status": "saved_verified", "bucket_id": bucket_id, "key": key, "bytes": len(bundle), "sha256": digest,"verified_files": verified_files}key = request.get("key")if not valid_bundle_key(key):raise BucketStorageError("invalid_request")
11 unmodified lines1213141516173 unmodified lines21222324252620 unmodified lines474849505152531 unmodified line5556575859606162636465666768697071727374752 unmodified lines78798081828384858687881 unmodified line90919293949596976 unmodified lines10410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116254 unmodified lines21721821922022122268 unmodified lines29129229329429529616 unmodified lines3133143153163173183192 unmodified lines3223233243253263273283293303313323333341 unmodified line3363373383393403412 unmodified lines3443453463473483493503513524 unmodified lines35735835936036136230 unmodified lines3933943953963973983994004014024034044054065 unmodified lines4124134144154164174184194204214224237 unmodified lines43143243343443543643743843944044151 unmodified lines49349449549649749849950050150250350450550611 unmodified lines51851952052152252352452552652752852953053153253353453553 unmodified lines5895905915925935942 unmodified lines59759859960060160260360411 unmodified lines6166176186196206216226238 unmodified lines63263363463563663711 unmodified lineslet batchStopRequested = false;let batchReceipt = null;let runReceipt = null;let appBuild = null;let leaderboardRequest = null;let leaderboardGeneration = 0;3 unmodified lineslet bucketId = null;let bucketUsername = null;let bucketItems = [];let bucketOperation = false;let bucketOperationId = 0;let bucketEpoch = 0;20 unmodified lines$('backend').disabled = unavailable || !capabilitiesReady;$('download').disabled = busy || !job;$('erase').disabled = busy || !job;$('keepServer').disabled = busy || !!job;$('saveLocal').disabled = busy || !localResult;$('forgetLocal').disabled = busy || !localResult;$('track').disabled=unavailable;1 unmodified lineif($('batch_start'))$('batch_start').disabled=unavailable || !capabilitiesReady || ($('backend').value==='gpu'&&!gpuAvailable);if($('batch_stop'))$('batch_stop').disabled=!batchActive || batchStopRequested;if($('run_export'))$('run_export').disabled=busy || !runReceipt;if($('batch_export'))$('batch_export').disabled=busy || !batchReceipt;if($('bundle_export'))$('bundle_export').disabled=unavailable;if($('bundle_import'))$('bundle_import').disabled=unavailable;if($('bucket_connect'))$('bucket_connect').disabled=unavailable||!!bucketToken;if($('bucket_id'))$('bucket_id').disabled=unavailable||!!bucketToken;if($('bucket_token'))$('bucket_token').disabled=unavailable||!!bucketToken;if($('bucket_disconnect'))$('bucket_disconnect').disabled=unavailable||!bucketToken;if($('bucket_save'))$('bucket_save').disabled=unavailable||!bucketToken||(!networkSource()&&!localResult);if($('bucket_refresh'))$('bucket_refresh').disabled=unavailable||!bucketToken;if($('bucket_restore'))$('bucket_restore').disabled=unavailable||!bucketToken||!$('bucket_items')?.value;if($('bucket_items'))$('bucket_items').disabled=unavailable||!bucketToken;}function renderBucketConnection(){const connected=!!bucketToken&&!!bucketId;$('bucketConnectForm')?.toggleAttribute('hidden',connected);$('bucketConnected')?.toggleAttribute('hidden',!connected);if($('bucket_account'))$('bucket_account').textContent=connected?'Connected as '+bucketUsername+' · '+bucketId:'';const select=$('bucket_items');2 unmodified linesif(!bucketItems.length){const option=document.createElement('option');option.value='';option.textContent='Refresh to list saved bundles';options.push(option);}for(const item of bucketItems){const option=document.createElement('option');option.value=item.key;option.textContent=item.label+' · '+item.bytes+' bytes';options.push(option);}select.replaceChildren(...options);if(options.length)select.value='';}buttons();}const bucketKeyValid=key=>typeof key==='string'&&/^ald-exports\/(?:[0-9a-f]{32}|[0-9a-f]{64})\/bundle\.json$/.test(key);function bucketSnapshot(){return {token:bucketToken,id:bucketId,epoch:bucketEpoch};}function bucketSnapshotCurrent(snapshot){return !!snapshot?.token&&snapshot.epoch===bucketEpoch&&snapshot.token===bucketToken&&snapshot.id===bucketId;}function clearBucketConnection(snapshot=null){1 unmodified linebucketEpoch++;bucketOperationId++;bucketOperation=false;bundleRestoreId++;bundleRestoring=false;bucketToken=null;bucketId=null;bucketUsername=null;bucketItems=[];if($('bucket_token'))$('bucket_token').value='';if($('bucket_id'))$('bucket_id').value='';if($('bucket_status'))$('bucket_status').textContent='Bucket connection cleared. Reconnect to continue.';renderBucketConnection();6 unmodified lines: bucketSnapshotCurrent(snapshot);const response=await fetch('/api/bucket/'+endpoint,{method:'POST',cache:'no-store',credentials:'omit',headers:{'Content-Type':'application/json','Authorization':'Bearer '+snapshot.token},body:JSON.stringify(body)});if(!current())throw Error('Bucket connection changed; the old response was ignored');if(response.status===401||response.status===403){if(endpoint!=='connect')clearBucketConnection(snapshot);throw Error('Bucket access expired or was denied. Reconnect to continue.');}if(!response.ok)throw Error('Bucket action failed. Check the bucket settings and try again.');return response;}function beginBucketOperation(){bucketOperation=true;const id=++bucketOperationId;buttons();return id;}function endBucketOperation(id){if(id!==bucketOperationId)return;bucketOperation=false;buttons();}if($('bucket_connect'))$('bucket_connect').onclick=async()=>{const id=$('bucket_id').value.trim(),token=$('bucket_token').value.trim();if(!id||!token){$('bucket_status').textContent='Enter the existing private bucket ID and its fine-grained token.';return;}const epoch=++bucketEpoch,snapshot={token,id,epoch},operationId=beginBucketOperation();$('bucket_status').textContent='Checking private bucket access…';try{const response=await bucketRequest('connect',{bucket_id:id},snapshot),result=await response.json();if(epoch!==bucketEpoch||bucketToken!==null||bucketId!==null)return;if(result?.status!=='connected'||result.bucket_id!==id||result.private!==true||typeof result.username!=='string'||!result.username.trim()||result.username.length>200)throw Error('Private bucket access could not be verified.');bucketToken=token;bucketId=id;bucketUsername=result.username;bucketItems=[];$('bucket_token').value='';$('bucket_status').textContent='Connected. Refresh saved bundles or choose Save; nothing is uploaded automatically.';renderBucketConnection();}catch(error){if(epoch===bucketEpoch){bucketToken=null;bucketId=null;bucketUsername=null;bucketItems=[];$('bucket_token').value='';$('bucket_status').textContent=error.message||'Bucket connection failed.';renderBucketConnection();}}finally{if(epoch===bucketEpoch)endBucketOperation(operationId);}};if($('bucket_disconnect'))$('bucket_disconnect').onclick=()=>{if(bucketOperation)return;clearBucketConnection();$('bucket_status').textContent='Disconnected. The bucket token was cleared from this page.';};if($('bucket_refresh'))$('bucket_refresh').onclick=async()=>{if(!bucketToken)return;const snapshot=bucketSnapshot(),operationId=beginBucketOperation();$('bucket_status').textContent='Refreshing this app’s saved bundle list…';try{const response=await bucketRequest('list',{bucket_id:snapshot.id},snapshot),result=await response.json();if(!bucketSnapshotCurrent(snapshot))return;if(!Array.isArray(result?.items)||result.items.length>50||typeof result.truncated!=='boolean')throw Error('The saved bundle list was not valid.');const checked=result.items.map(item=>{if(!bucketKeyValid(item?.key)||!Number.isSafeInteger(item.bytes)||item.bytes<1||item.bytes>window.PortableBundle.LIMITS.bundle||typeof item.label!=='string'||!item.label.trim()||item.label.length>120)throw Error('The saved bundle list was not valid.');return {key:item.key,bytes:item.bytes,label:item.label};});bucketItems=checked;renderBucketConnection();$('bucket_status').textContent=checked.length?checked.length+' saved bundle'+(checked.length===1?'':'s')+' available.'+(result.truncated?' Listing limited; additional bundles may not be shown.':''):'No bundles saved by this app were found.';}catch(error){if(bucketSnapshotCurrent(snapshot))$('bucket_status').textContent=error.message||'Could not refresh saved bundles.';}finally{endBucketOperation(operationId);}};if($('bucket_items'))$('bucket_items').addEventListener('change',buttons);if($('bucket_save'))$('bucket_save').onclick=async()=>{if(!bucketToken)return;const snapshot=bucketSnapshot(),operationId=beginBucketOperation();$('bucket_status').textContent='Building and verifying the selected bundle…';try{const {text}=await buildPortableBundle();if(!bucketSnapshotCurrent(snapshot))throw Error('Bucket connection changed; no save was attempted.');const bytes=new TextEncoder().encode(text),sha256=await window.PortableBundle.sha(bytes);if(bytes.byteLength>window.PortableBundle.LIMITS.bundle)throw Error('Portable bundle exceeds 8 MiB');const response=await bucketRequest('save',{bucket_id:snapshot.id,bundle:text},snapshot),result=await response.json();if(!bucketSnapshotCurrent(snapshot))return;if(result?.status!=='saved_verified'||result.bucket_id!==snapshot.id||!bucketKeyValid(result.key)||result.bytes!==bytes.byteLength||result.sha256!==sha256)throw Error('The app could not verify the saved bundle. Refresh the list before trying again; the remote save may have completed.');$('bucket_status').textContent='Bundle saved and read back successfully. Refresh the list to see it. Your current result remains available for download.';}catch(error){if(bucketSnapshotCurrent(snapshot))$('bucket_status').textContent=error.message||'Bundle save failed. Your current result remains available for download.';}finally{endBucketOperation(operationId);}};54 unmodified lines$('network').onchange=()=>{stagedNetwork=null;if($('networkChoice'))$('networkChoice').textContent='Uploaded file selected.';buttons();};window.TrainingClient={isBusy:()=>busy||!!job||bundleRestoring,useNetwork(file){if(busy||job)throw Error('Finish or delete the current result before changing the network');stagedNetwork=file;$('network').value='';68 unmodified lineswindow.addEventListener('hf-auth-change',()=>{const previous=gradioClient;gradioClient=null;if(previous)Promise.resolve(previous.close()).catch(()=>{});});window.TrainingClient.verifyIdentity=async()=>{if(busy||job)throw Error('Finish the current result before checking identity');16 unmodified linesconst metric=n=>typeof n==='number'?n.toFixed(3):'Not reported';if($('effectiveSettings'))$('effectiveSettings').textContent=JSON.stringify(r?.settings??{},null,2);if($('generationHistory'))$('generationHistory').textContent=(r?.history??[]).map(h=>'Generation '+h.generation+' · mutation '+metric(h.mutation)+' · best '+metric(h.best_score)+' · mean '+metric(h.mean_score)+' · lap '+(h.best_lap_seconds??'none')).join('\n');}$('run').onclick = async () => {cancelSteamLeaderboard();2 unmodified lines$('runState').textContent='RUNNING — waiting for server confirmation';$('runState').style.color='#ffd073';runReceipt=null;showDetails(null);const tick=()=>{$('runSummary').textContent='Backend: '+$('backend').value.toUpperCase()+'\nElapsed: '+((performance.now()-started)/1000).toFixed(1)+' s\nCompletion is not yet confirmed.';};tick(); const progress=setInterval(tick,250);busy=true; buttons(); say(window.getTrainingSettings?'Processing the training run…':'Processing the bounded test…');try {const trackInfo=trackLibrary?.info();const body={track:await encoded(await trackSource()),network:await encoded(networkSource()),automatic:!$('keepServer').checked,backend:$('backend').value};if(window.getTrainingSettings)body.settings=window.getTrainingSettings();job=await submit(body);localResult=null;clearInterval(progress);1 unmodified line$('runState').style.color='#62dfb1';const r=job.report;runReceipt={version:1,state:'completed',build:r?.build??appBuild,backend:job.backend,output_sha256:job.sha256,report:r};const metric=n=>typeof n==='number'?n.toFixed(3):'Not reported';$('runSummary').textContent=r?['Build: '+(r.build?.build_id??'Not reported'),2 unmodified lines'Track: '+(trackInfo?.source==='builtin'?trackInfo.display_name:'Custom upload'),'Generations: '+r.generations_completed+' / '+r.generations_requested+' · Population: '+r.population,'Server processing: '+metric(r.elapsed_seconds)+' s','Best score: '+metric(r.best_score)+' · Mean score: '+metric(r.mean_score),'Best lap: '+(r.best_lap_seconds==null?'No completed lap':metric(r.best_lap_seconds)+' s'),'Cars completing a lap: '+(r.lapped_cars??'Not reported'),'Actual frames (including stats cutoff): '+(r.simulated_ticks??'Not reported')+' · Configured time limit: '+r.requested_ticks+' ticks','Candidate validated: '+(r.candidate_validated?'Yes':'No'),'A completed test does not establish improved driving.'4 unmodified lines$('track').value=''; $('network').value='';stagedNetwork=null;if($('networkChoice'))$('networkChoice').textContent='Network input released after the run.';say('Result ready ('+job.backend.toUpperCase()+'). Inputs and intermediate worker files have been removed.');} catch (error) {clearInterval(progress);$('runState').textContent='ERROR — no successful result confirmed';30 unmodified lines$('batch_stop').onclick=()=>{batchStopRequested=true;buttons();$('batch_status').textContent='Stop requested — the current run will finish; no next run will start.';};$('batch_start').onclick=async()=>{if(busy||job||!capabilitiesReady)return;let plan;const history=[];const started=Date.now();try{if(busy||job||!capabilitiesReady)throw Error('Finish the current job and connect first');plan=window.getBatchPlan();busy=true;buttons(); // Freeze both selectors before an asynchronous track fetch.const track=await encoded(await trackSource()),original=networkSource();await encoded(original); // Reject missing/oversize inputs before dispatch.const backend=$('backend').value;busy=true;batchActive=true;batchStopRequested=false;batchReceipt=null;buttons();localResult=null;$('batch_history').replaceChildren();5 unmodified lines$('batch_status').textContent='RUNNING · '+plan.name+' · step '+(i+1)+' / '+plan.runs.length+' · '+plan.runs[i].slot;const inputHash=await sha(await source.arrayBuffer());job=await submit({track,network:await encoded(source),settings,backend,automatic:true});const {bytes,receipt}=await receive(job);localResult=new Blob([bytes]);showDetails(job.report);const ack=await acknowledge(job,receipt);if(!ack.deleted)throw Error('Intermediate deletion was not confirmed; batch stopped');const summary={backend,input_network_sha256:inputHash,output_sha256:job.sha256,server_result_deleted:true,report:job.report};job=null;return {candidate:localResult,receipt:summary};},{stopped:()=>batchStopRequested,onStep:step=>{history.push(step);const line=document.createElement('p');7 unmodified lines$('runSummary').textContent='Backend: '+backend.toUpperCase()+'\nCompleted steps: '+history.length+'\nUse Save received result again for the last candidate. A completed batch does not establish improved driving.';say('Batch results are in browser memory only; no server result remains for completed steps.');}catch(error){batchReceipt={version:1,build:appBuild,state:'error',plan:plan??null,history,error:error.message,elapsed_seconds:(Date.now()-started)/1000};$('batch_status').textContent='ERROR · '+history.length+' confirmed steps. '+displayError(error);$('runState').textContent='BATCH ERROR — '+history.length+' completed steps';$('runState').style.color='#ffb5a2';$('runSummary').textContent='Confirmed completed steps: '+history.length+'\n'+(job?'A server result remains accessible; use Delete now or await expiry.':'No current server result was received.')+'\n'+displayError(error);say(displayError(error)+(job?' Use Delete server-side job data now or await expiry.':''));}finally{if(batchActive){51 unmodified linesif($('run_export'))$('run_export').onclick=()=>{if(!runReceipt)return;const url=URL.createObjectURL(new Blob([JSON.stringify(runReceipt,null,2)],{type:'application/json'}));const a=document.createElement('a');a.href=url;a.download='ald-run-receipt.json';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);};const bundleMessage=text=>{if($('bundle_status'))$('bundle_status').textContent=text;};const bundleExact=(value,keys)=>{if(!value||typeof value!=='object'||Array.isArray(value)||Object.keys(value).sort().join()!==[...keys].sort().join())throw Error('Unexpected receipt fields');};const bundleFinite=value=>typeof value==='number'&&Number.isFinite(value);function cleanRunReceipt(source){if(!source||!source.report)return null;const report=source.report,buildId=source.build_id??source.build?.build_id??report.build?.build_id;11 unmodified linesbundleExact(report.inputs,['track_sha256','network_sha256']);if(!/^[a-f0-9]{64}$/.test(report.inputs.track_sha256)||!/^[a-f0-9]{64}$/.test(report.inputs.network_sha256))return null;bundleExact(report.settings,Object.keys(window.RecipeLibrary.defaults));const settings=window.RecipeLibrary.settings(report.settings);return {version:1,kind:'run',state:'completed',build_id:buildId,backend:source.backend,output_sha256:source.output_sha256,report:{vehicle_type:report.vehicle_type,vehicle_name:report.vehicle_name,generations_completed:report.generations_completed,generations_requested:report.generations_requested,population:report.population,elapsed_seconds:report.elapsed_seconds,best_score:report.best_score,mean_score:report.mean_score,best_lap_seconds:report.best_lap_seconds,lapped_cars:report.lapped_cars,simulated_ticks:report.simulated_ticks,requested_ticks:report.requested_ticks,candidate_validated:true,execution_backend:report.execution_backend,inputs:{track_sha256:report.inputs.track_sha256,network_sha256:report.inputs.network_sha256},settings}};}catch{return null;}}function validatePortableReceipt(receipt,network,track){bundleExact(receipt,['version','kind','state','build_id','backend','output_sha256','report']);const report=receipt.report,reportKeys=['vehicle_type','vehicle_name','generations_completed','generations_requested','population','elapsed_seconds','best_score','mean_score','best_lap_seconds','lapped_cars','simulated_ticks','requested_ticks','candidate_validated','execution_backend','inputs','settings'];bundleExact(report,reportKeys);const clean=cleanRunReceipt(receipt);if(receipt.version!==1||receipt.kind!=='run'||receipt.state!=='completed'||!clean)throw Error('Run receipt failed its allowlist or value checks');53 unmodified linesconst text=await api.pack(artifacts);return {text,note};}async function exportPortableBundle(){const {text,note}=await buildPortableBundle(),url=URL.createObjectURL(new Blob([text],{type:'application/json'}));const a=document.createElement('a');a.href=url;a.download='ald-portable-bundle.json';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);2 unmodified linesif($('bundle_export'))$('bundle_export').onclick=async()=>{try{await exportPortableBundle();}catch(error){bundleMessage('Bundle not exported: '+error.message);}};async function restorePortableText(text,{lockHeld=false,isCurrent=null}={}){if((bundleRestoring&&!lockHeld)||busy||job)throw Error('Finish the active run before restoring a bundle');if(new TextEncoder().encode(text).byteLength>window.PortableBundle.LIMITS.bundle)throw Error('Portable bundle exceeds 8 MiB');const parsed=await window.PortableBundle.parse(text);await validateNetworkBytes(parsed.network.bytes);11 unmodified linesif(typeof DataTransfer!=='function')throw Error('This browser cannot stage an uploaded track; no bundle data was applied');trackTransfer=new DataTransfer();trackTransfer.items.add(parsed.track.file);}const networkFile=new File([parsed.network.bytes],'portable-network.evolution',{type:'application/octet-stream'});// Recheck immediately before applying; a run or connection change during validation must not partially restore state.if(busy||job)throw Error('A run started while the bundle was being validated; no bundle data was applied');if(isCurrent&&!isCurrent())throw Error('Bucket connection changed while the bundle was being validated; no bundle data was applied');if(parsed.track){8 unmodified linesportableReceipt=parsed.receipt||null;$('bundle_receipt_download').disabled=!portableReceipt;bundleMessage('Bundle restored in this page only. Network and optional track/recipe are staged; no run started and no browser storage or server was changed.'+(portableReceipt?' Sanitized receipt is available for separate download.':''));}if($('bundle_import'))$('bundle_import').onchange=async()=>{const input=$('bundle_import'),file=input.files?.[0];if(!file)return;let restoreId=null;11 unmodified lines121314151617183 unmodified lines2223242526272820 unmodified lines49505152535455561 unmodified line5859606162636465666768697071727374757677787980818283842 unmodified lines878889909192939495969798991 unmodified line1011021031041051061076 unmodified lines11411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722854 unmodified lines28328428528628728828968 unmodified lines35835936036136236336436516 unmodified lines3823833843853863873882 unmodified lines3913923933943953963973983994004014024034044054064074084091 unmodified line4114124134144154164172 unmodified lines4204214224234244254264274284 unmodified lines43343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346430 unmodified lines4954964974984995005015025035045055065075085 unmodified lines5145155165175185195205215225235245255265275285295305315325335345355367 unmodified lines54454554654754854955055155255355455555655755851 unmodified lines61061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965011 unmodified lines66266366466566666766866967067167267367467567667767867968068153 unmodified lines7357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747752 unmodified lines77877978078178278378411 unmodified lines7967977987998008018028038048058 unmodified lines81481581681781881982082182282382482582611 unmodified lineslet batchStopRequested = false;let batchReceipt = null;let runReceipt = null;let runResultContext = null;let appBuild = null;let leaderboardRequest = null;let leaderboardGeneration = 0;3 unmodified lineslet bucketId = null;let bucketUsername = null;let bucketItems = [];let bucketSelectedKey = null;let bucketOperation = false;let bucketOperationId = 0;let bucketEpoch = 0;20 unmodified lines$('backend').disabled = unavailable || !capabilitiesReady;$('download').disabled = busy || !job;$('erase').disabled = busy || !job;const autosaving=!!bucketToken&&!!$('bucket_autosave')?.checked;$('keepServer').disabled = busy || !!job || autosaving;$('saveLocal').disabled = busy || !localResult;$('forgetLocal').disabled = busy || !localResult;$('track').disabled=unavailable;1 unmodified lineif($('batch_start'))$('batch_start').disabled=unavailable || !capabilitiesReady || ($('backend').value==='gpu'&&!gpuAvailable);if($('batch_stop'))$('batch_stop').disabled=!batchActive || batchStopRequested;if($('run_export'))$('run_export').disabled=busy || !runReceipt;const report=cleanRunReceipt(runReceipt)||cleanRunReceipt(portableReceipt);if($('player_report_download'))$('player_report_download').disabled=busy||!report;if($('history_csv_download'))$('history_csv_download').disabled=busy||!report?.report?.history?.length;if($('batch_export'))$('batch_export').disabled=busy || !batchReceipt;if($('bundle_export'))$('bundle_export').disabled=unavailable;if($('bundle_import'))$('bundle_import').disabled=unavailable;const storageToken=window.HFAuth?.getStorageToken?.()??null;if($('bucket_connect'))$('bucket_connect').disabled=unavailable||!storageToken||!!bucketToken;if($('bucket_id'))$('bucket_id').disabled=unavailable||!storageToken||!!bucketToken;if($('bucket_disconnect'))$('bucket_disconnect').disabled=unavailable||!bucketToken;if($('bucket_save'))$('bucket_save').disabled=unavailable||!bucketToken||(!networkSource()&&!localResult);if($('bucket_refresh'))$('bucket_refresh').disabled=unavailable||!bucketToken;if($('bucket_restore'))$('bucket_restore').disabled=unavailable||!bucketToken||!$('bucket_items')?.value;if($('bucket_items'))$('bucket_items').disabled=unavailable||!bucketToken;if($('bucket_autosave'))$('bucket_autosave').disabled=unavailable||!bucketToken;}function renderBucketConnection(){const connected=!!bucketToken&&!!bucketId;const authorized=!!window.HFAuth?.getStorageToken?.();if(connected&&$('bucket_autosave')?.checked&&$('keepServer')?.checked){$('keepServer').checked=false;$('bucket_status').textContent='Automatic bucket saving requires deletion after a verified download; the repeat-download option was turned off.';}$('bucketConnectForm')?.toggleAttribute('hidden',connected||!authorized);$('bucketConnected')?.toggleAttribute('hidden',!connected);if($('bucket_account'))$('bucket_account').textContent=connected?'Connected as '+bucketUsername+' · '+bucketId:'';const select=$('bucket_items');2 unmodified linesif(!bucketItems.length){const option=document.createElement('option');option.value='';option.textContent='Refresh to list saved bundles';options.push(option);}for(const item of bucketItems){const option=document.createElement('option');option.value=item.key;option.textContent=item.label+' · '+item.bytes+' bytes';options.push(option);}select.replaceChildren(...options);if(options.length)select.value=bucketSelectedKey&&bucketItems.some(item=>item.key===bucketSelectedKey)?bucketSelectedKey:'';}buttons();}const bucketKeyValid=key=>typeof key==='string'&&(/^ald-exports\/(?:[0-9a-f]{32}|[0-9a-f]{64})\/bundle\.json$/.test(key)||/^ald-exports\/\d{8}T\d{6}Z-[a-z0-9-]{1,64}-(?:formula|rally|snowmobile|truck)-g\d{1,4}-lap(?:\d{1,16}ms|none)-[0-9a-f]{32}\/bundle\.json$/.test(key));function bucketSnapshot(){return {token:bucketToken,id:bucketId,epoch:bucketEpoch};}function bucketSnapshotCurrent(snapshot){return !!snapshot?.token&&snapshot.epoch===bucketEpoch&&snapshot.token===bucketToken&&snapshot.id===bucketId;}function clearBucketConnection(snapshot=null){1 unmodified linebucketEpoch++;bucketOperationId++;bucketOperation=false;bundleRestoreId++;bundleRestoring=false;bucketToken=null;bucketId=null;bucketUsername=null;bucketItems=[];bucketSelectedKey=null;if($('bucket_id'))$('bucket_id').value='';if($('bucket_status'))$('bucket_status').textContent='Bucket connection cleared. Reconnect to continue.';renderBucketConnection();6 unmodified lines: bucketSnapshotCurrent(snapshot);const response=await fetch('/api/bucket/'+endpoint,{method:'POST',cache:'no-store',credentials:'omit',headers:{'Content-Type':'application/json','Authorization':'Bearer '+snapshot.token},body:JSON.stringify(body)});if(!current())throw Error('Bucket connection changed; the old response was ignored');if(response.status===401||response.status===403){if(endpoint!=='connect')clearBucketConnection(snapshot);window.HFAuth?.clearStorageAuthorization?.();throw Error('Bucket access expired or was denied. Authorize access again to reconnect.');}if(!response.ok)throw Error('Bucket action failed. Check the bucket settings and try again.');return response;}function beginBucketOperation(){bucketOperation=true;const id=++bucketOperationId;buttons();return id;}function endBucketOperation(id){if(id!==bucketOperationId)return;bucketOperation=false;buttons();}async function saveBucketBundleText(text,snapshot){if(!bucketSnapshotCurrent(snapshot))throw Error('Bucket connection changed; no save was attempted.');const bytes=new TextEncoder().encode(text);if(bytes.byteLength>window.PortableBundle.LIMITS.bundle)throw Error('Portable bundle exceeds 8 MiB');const sha256=await window.PortableBundle.sha(bytes);const response=await bucketRequest('save',{bucket_id:snapshot.id,bundle:text},snapshot),result=await response.json();if(!bucketSnapshotCurrent(snapshot))throw Error('Bucket connection changed; the old save response was ignored.');if(result?.status!=='saved_verified'||result.bucket_id!==snapshot.id||!bucketKeyValid(result.key)||result.bytes!==bytes.byteLength||result.sha256!==sha256)throw Error('The app could not verify the saved bundle. Refresh the list before trying again; the remote save may have completed.');return result;}if($('bucket_connect'))$('bucket_connect').onclick=async()=>{const id=$('bucket_id').value.trim(),token=window.HFAuth?.getStorageToken?.(),authUser=window.HFAuth?.getStorageUsername?.();if(!token){$('bucket_status').textContent='Authorize bucket access with HF before connecting.';return;}if(!id){$('bucket_status').textContent='Enter the ID of your existing private bucket.';return;}const epoch=++bucketEpoch,snapshot={token,id,epoch},operationId=beginBucketOperation();$('bucket_status').textContent='Checking private bucket access…';try{const response=await bucketRequest('connect',{bucket_id:id},snapshot),result=await response.json();if(epoch!==bucketEpoch||bucketToken!==null||bucketId!==null)return;if(result?.status!=='connected'||result.bucket_id!==id||result.private!==true||typeof result.username!=='string'||!result.username.trim()||result.username.length>200||result.username!==authUser)throw Error('Private bucket access could not be verified for the authorized HF account.');bucketToken=token;bucketId=id;bucketUsername=result.username;bucketItems=[];bucketSelectedKey=null;$('bucket_status').textContent='Connected. Checking saved bundles…';renderBucketConnection();try{await refreshBucketItems(snapshot,{autoRestore:true});}catch{$('bucket_status').textContent='Connected. Saved bundles could not be checked; refresh the list to retry.';}}catch(error){if(epoch===bucketEpoch){bucketToken=null;bucketId=null;bucketUsername=null;bucketItems=[];$('bucket_status').textContent=error.message||'Bucket connection failed.';renderBucketConnection();}}finally{if(epoch===bucketEpoch)endBucketOperation(operationId);}};if($('bucket_disconnect'))$('bucket_disconnect').onclick=()=>{if(bucketOperation)return;clearBucketConnection();window.HFAuth?.clearStorageAuthorization?.();$('bucket_status').textContent='Disconnected. HF bucket authorization was cleared from this page.';};function itemTime(item){if(typeof item.created_at==='string'){const created=item.created_at.match(/^(\d{4})-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d)(?:\.(\d{1,6}))?Z$/);if(created){const parts=created.slice(1,7).map(Number),time=Date.UTC(parts[0],parts[1]-1,parts[2],parts[3],parts[4],parts[5]),date=new Date(time);if(date.getUTCFullYear()===parts[0]&&date.getUTCMonth()===parts[1]-1&&date.getUTCDate()===parts[2]&&date.getUTCHours()===parts[3]&&date.getUTCMinutes()===parts[4]&&date.getUTCSeconds()===parts[5])return time+Number((created[7]||'').padEnd(6,'0')||0)/1000;}}const m=item.key.match(/^ald-exports\/(\d{4})(\d\d)(\d\d)T(\d\d)(\d\d)(\d\d)Z-/);if(!m)return null;const parts=m.slice(1).map(Number),time=Date.UTC(parts[0],parts[1]-1,parts[2],parts[3],parts[4],parts[5]),date=new Date(time);return date.getUTCFullYear()===parts[0]&&date.getUTCMonth()===parts[1]-1&&date.getUTCDate()===parts[2]&&date.getUTCHours()===parts[3]&&date.getUTCMinutes()===parts[4]&&date.getUTCSeconds()===parts[5]?time:null;}async function workspaceIsEmpty(){const trackInfo=trackLibrary?.info?.();return !busy&&!job&&!networkSource()&&!localResult&&!$('track').files.length&&trackInfo?.source!=='builtin'&&!window.hasUnsavedNetworkDraft?.();}async function refreshBucketItems(snapshot,{selectKey=null,autoRestore=false}={}){const response=await bucketRequest('list',{bucket_id:snapshot.id},snapshot),result=await response.json();if(!bucketSnapshotCurrent(snapshot))return;if(!Array.isArray(result?.items)||result.items.length>50||typeof result.truncated!=='boolean'||(result.scan_incomplete!==undefined&&typeof result.scan_incomplete!=='boolean'))throw Error('The saved bundle list was not valid.');const checked=result.items.map(item=>{if(!bucketKeyValid(item?.key)||!Number.isSafeInteger(item.bytes)||item.bytes<1||item.bytes>window.PortableBundle.LIMITS.bundle||typeof item.label!=='string'||!item.label.trim()||item.label.length>160||!(item.created_at===undefined||item.created_at===null||(typeof item.created_at==='string'&&itemTime(item)!==null)))throw Error('The saved bundle list was not valid.');return {key:item.key,bytes:item.bytes,label:item.label,created_at:item.created_at??null};}).sort((a,b)=>(itemTime(b)??-1)-(itemTime(a)??-1));bucketItems=checked;bucketSelectedKey=selectKey&&checked.some(item=>item.key===selectKey)?selectKey:null;renderBucketConnection();if(!checked.length){$('bucket_status').textContent='No bundles saved by this app were found.'+(result.scan_incomplete?' The bounded scan was incomplete; additional bundles may exist.':'');return;}if(autoRestore){const empty=await workspaceIsEmpty();for(const item of checked){if(!bucketSnapshotCurrent(snapshot))return;try{const saved=await bucketRequest('restore',{bucket_id:snapshot.id,key:item.key},snapshot),text=await saved.text();if(!bucketSnapshotCurrent(snapshot))return;const prepared=await preparePortableText(text);if(!bucketSnapshotCurrent(snapshot))return;bucketSelectedKey=item.key;renderBucketConnection();if(empty&&await workspaceIsEmpty()){await applyPreparedPortable(prepared,{isCurrent:()=>bucketSnapshotCurrent(snapshot)});$('bucket_status').textContent='Selected and restored the newest compatible bundle among the listed entries in this page. No run started.';}else $('bucket_status').textContent='Selected the newest compatible bundle among the listed entries. Existing network, track, result or editor state was left untouched; choose Restore when ready.';if(result.scan_incomplete)$('bucket_status').textContent+=' The bounded scan was incomplete, so a newer bundle may exist.';else if(result.truncated)$('bucket_status').textContent+=' Only the 50 newest listed bundles are shown; an older compatible bundle may not be listed.';return;}catch(error){if(!bucketSnapshotCurrent(snapshot))return;}}bucketSelectedKey=null;renderBucketConnection();$('bucket_status').textContent='No compatible saved bundle was found in the listed entries.'+(result.scan_incomplete?' The bounded scan was incomplete, so additional bundles may exist.':result.truncated?' Only the 50 newest listed bundles were checked.':'');return;}const listingNote=result.scan_incomplete?' Bounded scan incomplete; a newer bundle may exist.':result.truncated?' Listing shows up to 50 bundles; additional, older bundles may not be shown.':'';if(selectKey&&bucketSelectedKey) $('bucket_status').textContent='Saved bundle verified and selected in the refreshed list.'+listingNote;else $('bucket_status').textContent=checked.length+' saved bundle'+(checked.length===1?'':'s')+' available.'+listingNote;}if($('bucket_refresh'))$('bucket_refresh').onclick=async()=>{if(!bucketToken)return;const snapshot=bucketSnapshot(),operationId=beginBucketOperation();$('bucket_status').textContent='Refreshing this app’s saved bundle list…';try{await refreshBucketItems(snapshot,{autoRestore:true});}catch(error){if(bucketSnapshotCurrent(snapshot))$('bucket_status').textContent=error.message||'Could not refresh saved bundles.';}finally{endBucketOperation(operationId);}};if($('bucket_items'))$('bucket_items').addEventListener('change',()=>{bucketSelectedKey=$('bucket_items').value||null;buttons();});if($('bucket_autosave'))$('bucket_autosave').addEventListener('change',()=>{if($('bucket_autosave').checked&&$('keepServer').checked){$('keepServer').checked=false;$('bucket_status').textContent='Automatic bucket saving requires deletion after a verified download; the repeat-download option was turned off.';}buttons();});if($('bucket_save'))$('bucket_save').onclick=async()=>{if(!bucketToken)return;const snapshot=bucketSnapshot(),operationId=beginBucketOperation();$('bucket_status').textContent='Building and verifying the selected bundle…';try{const useLatestResult=!!(localResult&&runReceipt&&runResultContext&&!networkSource()&&!$('track').files.length&&(()=>{const current=trackLibrary?.info?.()??{source:'upload'},prior=runResultContext.trackInfo??{source:'upload'};return current.source===prior.source&&(current.source!=='builtin'||current.id===prior.id);})());const {text}=useLatestResult?await buildRunResultBundle(localResult,runReceipt,runResultContext):await buildPortableBundle();const result=await saveBucketBundleText(text,snapshot);$('bucket_status').textContent='Bundle saved and read back successfully. Your current result remains available for download.';await refreshBucketItems(snapshot,{selectKey:result.key,preflight:false});}catch(error){if(bucketSnapshotCurrent(snapshot))$('bucket_status').textContent=error.message||'Bundle save failed. Your current result remains available for download.';}finally{endBucketOperation(operationId);}};54 unmodified lines$('network').onchange=()=>{stagedNetwork=null;if($('networkChoice'))$('networkChoice').textContent='Uploaded file selected.';buttons();};window.TrainingClient={isBusy:()=>busy||!!job||bundleRestoring,hasUnsavedState:()=>!!(networkSource()||localResult||$('track').files.length||trackLibrary?.info?.()?.source==='builtin'||$('editor_file')?.files.length||window.hasUnsavedNetworkDraft?.()),useNetwork(file){if(busy||job)throw Error('Finish or delete the current result before changing the network');stagedNetwork=file;$('network').value='';68 unmodified lineswindow.addEventListener('hf-auth-change',()=>{const previous=gradioClient;gradioClient=null;if(previous)Promise.resolve(previous.close()).catch(()=>{});if(bucketToken||bucketId)clearBucketConnection();renderBucketConnection();});window.TrainingClient.verifyIdentity=async()=>{if(busy||job)throw Error('Finish the current result before checking identity');16 unmodified linesconst metric=n=>typeof n==='number'?n.toFixed(3):'Not reported';if($('effectiveSettings'))$('effectiveSettings').textContent=JSON.stringify(r?.settings??{},null,2);if($('generationHistory'))$('generationHistory').textContent=(r?.history??[]).map(h=>'Generation '+h.generation+' · mutation '+metric(h.mutation)+' · best '+metric(h.best_score)+' · mean '+metric(h.mean_score)+' · lap '+(h.best_lap_seconds??'none')+' · cars lapped '+(h.lapped_cars??'not reported')+' · ticks '+metric(h.simulated_ticks)).join('\n');}$('run').onclick = async () => {cancelSteamLeaderboard();2 unmodified lines$('runState').textContent='RUNNING — waiting for server confirmation';$('runState').style.color='#ffd073';runReceipt=null;runResultContext=null;showDetails(null);const tick=()=>{$('runSummary').textContent='Backend: '+$('backend').value.toUpperCase()+'\nElapsed: '+((performance.now()-started)/1000).toFixed(1)+' s\nCompletion is not yet confirmed.';};tick(); const progress=setInterval(tick,250);busy=true; buttons(); say(window.getTrainingSettings?'Processing the training run…':'Processing the bounded test…');try {const trackInfo=trackLibrary?.info()??{source:'upload'};const trackFile=await trackSource(),networkFile=networkSource();const trackBytes=new Uint8Array(await trackFile.arrayBuffer()),networkBytes=new Uint8Array(await networkFile.arrayBuffer());const autosaveSnapshot=bucketToken&&$('bucket_autosave')?.checked?bucketSnapshot():null;if(autosaveSnapshot)$('keepServer').checked=false;const context={trackInfo,trackBytes,inputNetworkSha256:await sha(networkBytes),autosaveSnapshot};const body={track:await encoded(trackFile),network:await encoded(networkFile),automatic:autosaveSnapshot?true:!$('keepServer').checked,backend:$('backend').value};if(window.getTrainingSettings)body.settings=window.getTrainingSettings();job=await submit(body);localResult=null;clearInterval(progress);1 unmodified line$('runState').style.color='#62dfb1';const r=job.report;runReceipt={version:1,state:'completed',build:r?.build??appBuild,backend:job.backend,output_sha256:job.sha256,report:r};runResultContext=context;const metric=n=>typeof n==='number'?n.toFixed(3):'Not reported';$('runSummary').textContent=r?['Build: '+(r.build?.build_id??'Not reported'),2 unmodified lines'Track: '+(trackInfo?.source==='builtin'?trackInfo.display_name:'Custom upload'),'Generations: '+r.generations_completed+' / '+r.generations_requested+' · Population: '+r.population,'Server processing: '+metric(r.elapsed_seconds)+' s','Final-generation population scores — best: '+metric(r.best_score)+' · mean: '+metric(r.mean_score),'Best completed lap observed during this run (may be another car): '+(r.best_lap_seconds==null?'No completed lap':metric(r.best_lap_seconds)+' s'),'Cars completing a lap in the final generation: '+(r.lapped_cars??'Not reported'),'Actual frames (including stats cutoff): '+(r.simulated_ticks??'Not reported')+' · Configured time limit: '+r.requested_ticks+' ticks','Candidate validated: '+(r.candidate_validated?'Yes':'No'),'A completed test does not establish improved driving.'4 unmodified lines$('track').value=''; $('network').value='';stagedNetwork=null;if($('networkChoice'))$('networkChoice').textContent='Network input released after the run.';say('Result ready ('+job.backend.toUpperCase()+'). Inputs and intermediate worker files have been removed.');if(autosaveSnapshot){try{const outcome=await receiveAndAutosave(job,autosaveSnapshot,context);$('runState').textContent='COMPLETE — verified candidate saved to bucket';say('Result was hash-verified, the server copy was deleted, and the run bundle was read back from your bucket. A local browser copy remains available to download.');$('runSummary').textContent+='\nBucket save: verified read-back succeeded.';try{await refreshBucketItems(autosaveSnapshot,{selectKey:outcome.saved.key,preflight:false});}catch{$('bucket_status').textContent='Network and run log were saved and verified. The saved-bundle list could not refresh; use Refresh saved bundles.';}}catch(error){if(!context.localVerified){$('runSummary').textContent+='\nAutomatic receive failed: '+error.message+' No verified local copy is available. The server result may remain available until deletion or expiry; retry download or delete it.';$('bucket_status').textContent='Run completed, but the result was not verified in this browser. No bucket save was attempted.';$('runState').textContent='COMPLETE — result not received or verified';$('runState').style.color='#ffd073';say('The run completed, but no verified local copy was received. The server result may remain available until deletion or expiry.');}else if(!context.serverDeleted){$('runSummary').textContent+='\nThe candidate was verified locally, but deletion of the server copy was not confirmed. No bucket save was attempted. The local network remains available to download; the server result may remain available until deletion or expiry.';$('bucket_status').textContent='Verified network remains in this page; server deletion was not confirmed and bucket save was skipped.';say('A verified local network is available. Server deletion still needs attention.');}else{const saveDisposition=context.bucketSaveStarted?'Bucket save was not confirmed; the remote save may have completed.':'No bucket save was attempted.';$('runSummary').textContent+='\n'+saveDisposition+' '+error.message+' The verified candidate remains available in this page; use Download received result or Save selected bundle to retry.';$('bucket_status').textContent='Server copy deleted. '+saveDisposition+' '+error.message+' The received network remains available in this page.';say('Run completed. A verified candidate remains in this page; bucket save needs attention.');}}}} catch (error) {clearInterval(progress);$('runState').textContent='ERROR — no successful result confirmed';30 unmodified lines$('batch_stop').onclick=()=>{batchStopRequested=true;buttons();$('batch_status').textContent='Stop requested — the current run will finish; no next run will start.';};$('batch_start').onclick=async()=>{if(busy||job||!capabilitiesReady)return;let plan,failedCandidateStep=null;const history=[];const started=Date.now();try{if(busy||job||!capabilitiesReady)throw Error('Finish the current job and connect first');plan=window.getBatchPlan();busy=true;buttons(); // Freeze both selectors before an asynchronous track fetch.const trackFile=await trackSource(),trackBytes=new Uint8Array(await trackFile.arrayBuffer()),track=await encoded(trackFile),trackInfo=trackLibrary?.info()??{source:'upload'},original=networkSource();await encoded(original); // Reject missing/oversize inputs before dispatch.const backend=$('backend').value,autosaveSnapshot=bucketToken&&$('bucket_autosave')?.checked?bucketSnapshot():null;busy=true;batchActive=true;batchStopRequested=false;batchReceipt=null;buttons();localResult=null;$('batch_history').replaceChildren();5 unmodified lines$('batch_status').textContent='RUNNING · '+plan.name+' · step '+(i+1)+' / '+plan.runs.length+' · '+plan.runs[i].slot;const inputHash=await sha(await source.arrayBuffer());job=await submit({track,network:await encoded(source),settings,backend,automatic:true});const stepJob=job,{bytes,receipt}=await receive(job);localResult=new Blob([bytes]);showDetails(job.report);const report=stepJob.report,stepRunReceipt={version:1,state:'completed',build:report?.build??appBuild,backend,output_sha256:stepJob.sha256,report};const stepContext={trackInfo,trackBytes,inputNetworkSha256:inputHash,autosaveSnapshot};runReceipt=stepRunReceipt;runResultContext=stepContext;runReceipt.delivery={received_and_hash_verified:true,server_copy_deleted:false};const ack=await acknowledge(job,receipt);if(!ack.deleted)throw Error('Intermediate deletion was not confirmed; batch stopped');runReceipt.delivery.server_copy_deleted=true;const summary={backend,input_network_sha256:inputHash,output_sha256:stepJob.sha256,server_result_deleted:true,report};job=null;if(autosaveSnapshot){failedCandidateStep={step:i+1,slot:plan.runs[i].slot,name:plan.runs[i].name,...summary,autosave:'pending'};const outcome=await saveVerifiedRunToBucket(autosaveSnapshot,stepContext);failedCandidateStep.autosave='verified';failedCandidateStep.bucket_key=outcome.saved.key;try{await refreshBucketItems(autosaveSnapshot,{selectKey:outcome.saved.key,preflight:false});}catch{$('bucket_status').textContent='Run network and log saved and verified; saved-bundle list could not refresh.';}failedCandidateStep=null;}return {candidate:localResult,receipt:summary};},{stopped:()=>batchStopRequested,onStep:step=>{history.push(step);const line=document.createElement('p');7 unmodified lines$('runSummary').textContent='Backend: '+backend.toUpperCase()+'\nCompleted steps: '+history.length+'\nUse Save received result again for the last candidate. A completed batch does not establish improved driving.';say('Batch results are in browser memory only; no server result remains for completed steps.');}catch(error){if(failedCandidateStep&&!history.some(step=>step.step===failedCandidateStep.step)){const failed={...failedCandidateStep,autosave:'failed'};history.push(failed);const line=document.createElement('p');line.textContent='Step '+failed.step+' · '+failed.slot+' · '+failed.name+' · result received and server copy deleted · bucket save not confirmed';$('batch_history').append(line);}batchReceipt={version:1,build:appBuild,state:'error',plan:plan??null,history,error:error.message,elapsed_seconds:(Date.now()-started)/1000};$('batch_status').textContent='ERROR · '+history.length+' confirmed steps. '+displayError(error);$('runState').textContent='BATCH ERROR — '+history.length+' completed steps';$('runState').style.color='#ffb5a2';$('runSummary').textContent='Confirmed completed steps: '+history.length+'\n'+(job?'A server result remains accessible; use Delete now or await expiry.':localResult?'A verified local candidate remains in this page.':'No current server result was received.')+'\n'+displayError(error);say(displayError(error)+(job?' Use Delete server-side job data now or await expiry.':''));}finally{if(batchActive){51 unmodified linesif($('run_export'))$('run_export').onclick=()=>{if(!runReceipt)return;const cleaned=cleanRunReceipt(runReceipt);if(!cleaned)return;const url=URL.createObjectURL(new Blob([JSON.stringify(cleaned,null,2)],{type:'application/json'}));const a=document.createElement('a');a.href=url;a.download='ald-run-receipt.json';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);};function activeCleanReceipt(){return cleanRunReceipt(runReceipt)||cleanRunReceipt(portableReceipt);}function downloadTextFile(text,name,type){const url=URL.createObjectURL(new Blob([text],{type}));const a=document.createElement('a');a.href=url;a.download=name;a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);}function formatPlayerReport(receipt){const r=receipt.report,metric=value=>typeof value==='number'?String(value):'Not reported';const lines=['ALD driving run report','',`Build: ${receipt.build_id}`,`Backend: ${receipt.backend}`,`Vehicle: ${r.vehicle_name} (Type ${r.vehicle_type})`,`Generations: ${r.generations_completed} / ${r.generations_requested}`,`Population: ${r.population}`,`Elapsed seconds: ${metric(r.elapsed_seconds)}`,`Final-generation population best score: ${metric(r.best_score)}`,`Final-generation population mean score: ${metric(r.mean_score)}`,`Best completed lap observed during this run (may be another car): ${r.best_lap_seconds===null?'None':metric(r.best_lap_seconds)+' s'}`,`Cars completing a lap in the final generation: ${r.lapped_cars===null?'Not reported':r.lapped_cars}`,`Simulated ticks: ${r.simulated_ticks}`,`Input network SHA-256: ${r.inputs.network_sha256}`,`Track SHA-256: ${r.inputs.track_sha256}`,`Output network SHA-256: ${receipt.output_sha256}`,'','Configured training settings:',JSON.stringify(r.settings,null,2),'','Reward weights are configured values; per-reward contribution is not reported by the engine.'];if(r.history?.length){lines.push('','Generation history:','Generation | Mutation | Best score | Mean score | Best lap observed in generation | Cars lapped | Simulated ticks');for(const h of r.history)lines.push([h.generation,h.mutation,h.best_score,h.mean_score,h.best_lap_seconds===null?'':h.best_lap_seconds,h.lapped_cars===null?'':h.lapped_cars,h.simulated_ticks].join(' | '));}return lines.join('\n')+'\n';}const csvCell=value=>{const text=value===null?'':String(value);return /[",\r\n]/.test(text)?'"'+text.replaceAll('"','""')+'"':text;};function formatHistoryCsv(receipt){const rows=receipt?.report?.history;if(!Array.isArray(rows)||!rows.length)throw Error('No generation history is available in this receipt');const headers=['generation','mutation','best_score','mean_score','best_lap_seconds_observed_in_generation','lapped_cars','simulated_ticks'];return [headers.map(csvCell).join(','),...rows.map(row=>runHistoryKeys.map(key=>csvCell(row[key])).join(','))].join('\r\n')+'\r\n';}if($('player_report_download'))$('player_report_download').onclick=()=>{const receipt=activeCleanReceipt();if(receipt)downloadTextFile(formatPlayerReport(receipt),'ald-player-report.txt','text/plain;charset=utf-8');};if($('history_csv_download'))$('history_csv_download').onclick=()=>{const receipt=activeCleanReceipt();if(receipt?.report?.history?.length)downloadTextFile(formatHistoryCsv(receipt),'ald-generation-history.csv','text/csv;charset=utf-8');};const bundleMessage=text=>{if($('bundle_status'))$('bundle_status').textContent=text;};const bundleExact=(value,keys)=>{if(!value||typeof value!=='object'||Array.isArray(value)||Object.keys(value).sort().join()!==[...keys].sort().join())throw Error('Unexpected receipt fields');};const bundleFinite=value=>typeof value==='number'&&Number.isFinite(value);const runHistoryKeys=['generation','mutation','best_score','mean_score','best_lap_seconds','lapped_cars','simulated_ticks'];function cleanRunHistory(value){if(value===undefined)return undefined;if(!Array.isArray(value)||value.length>1000)throw Error('Generation history exceeds its 1,000-row limit');return value.map((row,index)=>{bundleExact(row,runHistoryKeys);if(!Number.isInteger(row.generation)||row.generation!==index+1||row.generation>1000||!bundleFinite(row.mutation)||row.mutation<0||row.mutation>4.2||!bundleFinite(row.best_score)||Math.abs(row.best_score)>1e12||!bundleFinite(row.mean_score)||Math.abs(row.mean_score)>1e12||!(row.best_lap_seconds===null||(bundleFinite(row.best_lap_seconds)&&row.best_lap_seconds>0&&row.best_lap_seconds<=1e12))||!(row.lapped_cars===null||(Number.isInteger(row.lapped_cars)&&row.lapped_cars>=0&&row.lapped_cars<=128))||!Number.isInteger(row.simulated_ticks)||row.simulated_ticks<0||row.simulated_ticks>4000000)throw Error('Generation history contains an invalid value');return {generation:row.generation,mutation:row.mutation,best_score:row.best_score,mean_score:row.mean_score,best_lap_seconds:row.best_lap_seconds,lapped_cars:row.lapped_cars,simulated_ticks:row.simulated_ticks};});}function cleanRunReceipt(source){if(!source||!source.report)return null;const report=source.report,buildId=source.build_id??source.build?.build_id??report.build?.build_id;11 unmodified linesbundleExact(report.inputs,['track_sha256','network_sha256']);if(!/^[a-f0-9]{64}$/.test(report.inputs.track_sha256)||!/^[a-f0-9]{64}$/.test(report.inputs.network_sha256))return null;bundleExact(report.settings,Object.keys(window.RecipeLibrary.defaults));const settings=window.RecipeLibrary.settings(report.settings),history=cleanRunHistory(report.history);if(report.population!==settings.population||report.generations_requested!==settings.generations||report.requested_ticks!==settings.ticks||(history&&history.length!==report.generations_completed))return null;return {version:1,kind:'run',state:'completed',build_id:buildId,backend:source.backend,output_sha256:source.output_sha256,report:{vehicle_type:report.vehicle_type,vehicle_name:report.vehicle_name,generations_completed:report.generations_completed,generations_requested:report.generations_requested,population:report.population,elapsed_seconds:report.elapsed_seconds,best_score:report.best_score,mean_score:report.mean_score,best_lap_seconds:report.best_lap_seconds,lapped_cars:report.lapped_cars,simulated_ticks:report.simulated_ticks,requested_ticks:report.requested_ticks,candidate_validated:true,execution_backend:report.execution_backend,inputs:{track_sha256:report.inputs.track_sha256,network_sha256:report.inputs.network_sha256},settings,...(history?{history}:{})}};}catch{return null;}}function validatePortableReceipt(receipt,network,track){bundleExact(receipt,['version','kind','state','build_id','backend','output_sha256','report']);const report=receipt.report,reportKeys=['vehicle_type','vehicle_name','generations_completed','generations_requested','population','elapsed_seconds','best_score','mean_score','best_lap_seconds','lapped_cars','simulated_ticks','requested_ticks','candidate_validated','execution_backend','inputs','settings'];if(Object.hasOwn(report,'history'))reportKeys.push('history');bundleExact(report,reportKeys);const clean=cleanRunReceipt(receipt);if(receipt.version!==1||receipt.kind!=='run'||receipt.state!=='completed'||!clean)throw Error('Run receipt failed its allowlist or value checks');53 unmodified linesconst text=await api.pack(artifacts);return {text,note};}async function buildRunResultBundle(resultBlob,sourceReceipt,context){if(!(resultBlob instanceof Blob)||!sourceReceipt||!context?.trackBytes)throw Error('The completed run data is not available for a verified bundle');const networkBytes=new Uint8Array(await resultBlob.arrayBuffer()),trackBytes=context.trackBytes;await validateNetworkBytes(networkBytes);const api=window.PortableBundle,network=await api.artifact('evolution','result',networkBytes);const track=await api.artifact('track','selected',trackBytes);delete track.kind;const info=context.trackInfo??{source:'upload'};if(info.source==='builtin')Object.assign(track,{source:'builtin',track_id:info.id,display_name:info.display_name});else track.source='upload';await validateBundleTrack({bytes:trackBytes,metadata:track});const receipt=cleanRunReceipt(sourceReceipt);if(!receipt?.report?.history?.length)throw Error('The completed run has no validated generation history to save');if(receipt.output_sha256!==network.sha256||receipt.report.inputs.network_sha256!==context.inputNetworkSha256||receipt.report.inputs.track_sha256!==track.sha256)throw Error('The saved run log does not match the verified network and track bytes');validatePortableReceipt(receipt,network,track);const text=await api.pack({selected_network:network,selected_track:track,run_receipt:receipt});return {text,receipt,network,track};}async function saveVerifiedRunToBucket(snapshot,context){if(!bucketSnapshotCurrent(snapshot))throw Error('Candidate is safe in this page, but the bucket connection changed before saving. Reconnect and save it manually.');const bundle=await buildRunResultBundle(localResult,runReceipt,context);if(!bucketSnapshotCurrent(snapshot))throw Error('Candidate is safe in this page, but the bucket connection changed before saving. Reconnect and save it manually.');context.bucketSaveStarted=true;const saved=await saveBucketBundleText(bundle.text,snapshot);if(!bucketSnapshotCurrent(snapshot))throw Error('Bucket connection changed after the save; the old response was ignored. Candidate remains available in this page.');return {saved,bundle};}async function receiveAndAutosave(currentJob,snapshot,context){const received=await receive(currentJob);localResult=new Blob([received.bytes]);context.localVerified=true;buttons();const acknowledgment=await acknowledge(currentJob,received.receipt);if(acknowledgment.deleted!==true)throw Error('Candidate was verified, but server deletion was not confirmed; the bucket save was skipped. Download or delete the server result manually.');context.serverDeleted=true;if(runReceipt)runReceipt.delivery={received_and_hash_verified:true,server_copy_deleted:true};if(job===currentJob)job=null;buttons();const outcome=await saveVerifiedRunToBucket(snapshot,context);context.bucketSaveConfirmed=true;return outcome;}async function exportPortableBundle(){const {text,note}=await buildPortableBundle(),url=URL.createObjectURL(new Blob([text],{type:'application/json'}));const a=document.createElement('a');a.href=url;a.download='ald-portable-bundle.json';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);2 unmodified linesif($('bundle_export'))$('bundle_export').onclick=async()=>{try{await exportPortableBundle();}catch(error){bundleMessage('Bundle not exported: '+error.message);}};async function preparePortableText(text){if(new TextEncoder().encode(text).byteLength>window.PortableBundle.LIMITS.bundle)throw Error('Portable bundle exceeds 8 MiB');const parsed=await window.PortableBundle.parse(text);await validateNetworkBytes(parsed.network.bytes);11 unmodified linesif(typeof DataTransfer!=='function')throw Error('This browser cannot stage an uploaded track; no bundle data was applied');trackTransfer=new DataTransfer();trackTransfer.items.add(parsed.track.file);}return {parsed,trackTransfer,networkFile:new File([parsed.network.bytes],'portable-network.evolution',{type:'application/octet-stream'})};}async function applyPreparedPortable(prepared,{isCurrent=null}={}){const {parsed,trackTransfer,networkFile}=prepared;if(busy||job)throw Error('A run started while the bundle was being validated; no bundle data was applied');if(isCurrent&&!isCurrent())throw Error('Bucket connection changed while the bundle was being validated; no bundle data was applied');if(parsed.track){8 unmodified linesportableReceipt=parsed.receipt||null;$('bundle_receipt_download').disabled=!portableReceipt;bundleMessage('Bundle restored in this page only. Network and optional track/recipe are staged; no run started and no browser storage or server was changed.'+(portableReceipt?' Sanitized receipt is available for separate download.':''));buttons();}async function restorePortableText(text,{lockHeld=false,isCurrent=null}={}){if((bundleRestoring&&!lockHeld)||busy||job)throw Error('Finish the active run before restoring a bundle');const prepared=await preparePortableText(text);await applyPreparedPortable(prepared,{isCurrent});return prepared;}if($('bundle_import'))$('bundle_import').onchange=async()=>{const input=$('bundle_import'),file=input.files?.[0];if(!file)return;let restoreId=null;
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758593 unmodified lines636465666768697071727374757677787980818283848586878889'use strict';// Official HF PKCE redirect helpers. Only the one-use verifier crosses navigation;// account access tokens and profile details stay in this page's memory.(() => {const node=id=>document.getElementById(id),flowKey='tiga.ald.hf.pkce.v1';let session=null,locked=false,ready=false,config=null,exchanging=false;const message=text=>{node('hfIdentity').textContent=text;};function render(){node('hfSignIn').hidden=!!session;node('hfSignIn').disabled=locked||exchanging||!ready;node('hfAccount').hidden=!session;node('hfAccount').textContent=session?'Connected as '+session.userInfo.preferred_username:'';node('hfSignOut').hidden=!session;node('hfSignOut').disabled=locked||exchanging||!session;node('hfVerify').hidden=!session;node('hfVerify').disabled=locked||exchanging||!session;}function clear(){session=null;window.dispatchEvent(new Event('hf-auth-change'));render();}window.HFAuth={setBusy(value){locked=value;render();},credentials(){if(exchanging)throw Error('Complete HF sign-in before starting GPU');if(session && session.accessTokenExpiresAt.getTime()<=Date.now()){clear();message('HF sign-in expired. Sign in again before an account GPU request.');throw Error('HF sign-in expired; sign in again');}return session?{token:session.accessToken}:{};},verify(identity){if(session && (!identity.authenticated||identity.auth_path!=='queue-bearer'||identity.username!==session.userInfo.preferred_username))throw Error('GPU queue visitor identity did not match your HF sign-in; no GPU request started');if(session)message('Account connection checked. GPU use remains subject to your HF allowance.');}};node('hfSignOut').onclick=()=>{clear();message('Account disconnected from this app. CPU remains available. HF website sign-in is unchanged.');};node('hfVerify').onclick=async()=>{try{await window.TrainingClient.verifyIdentity();}catch{message('Account connection check failed. No GPU request started. Disconnect and sign in again, or use CPU.');}};node('hfSignIn').onclick=async()=>{if(locked||exchanging||!ready)return;if((node('track').files.length||node('network').files.length) &&!(await window.appConfirm('HF sign-in navigates away. Selected files and unsaved editor changes are lost; saved recipes remain. Continue, then reselect files?',{heading:'Continue to HF sign-in',confirmLabel:'Continue to sign in'})))return;exchanging=true;render();try{const state={};const helpers=await import('/hf-oauth.js');const url=await helpers.oauthLoginUrl({clientId:config.client_id,scopes:'openid profile',redirectUrl:location.origin+'/',localStorage:state});sessionStorage.setItem(flowKey,JSON.stringify({...state,started:Date.now()}));message('Opening Hugging Face sign-in. No password or personal token is entered here.');location.href=url;}catch{exchanging=false;render();message('HF sign-in could not start. Tab-local sign-in storage is required; CPU remains available.');}};const returned=location.href,params=new URL(returned).searchParams;const isCallback=params.has('code')||params.has('error');if(isCallback){history.replaceState(null,'','/');exchanging=true;}3 unmodified lineslet flow;try{flow=JSON.parse(sessionStorage.getItem(flowKey));}finally{sessionStorage.removeItem(flowKey);}if(!ready||!flow?.nonce||!flow?.codeVerifier||Date.now()-flow.started>300000||flow.started>Date.now())throw Error();const helpers=await import('/hf-oauth.js');const result=await helpers.oauthHandleRedirect({redirectedUrl:returned,nonce:flow.nonce,codeVerifier:flow.codeVerifier});flow.nonce=null;flow.codeVerifier=null;const scopes=new Set(result.scope.split(/\s+/));if([...scopes].some(scope=>!['openid','profile'].includes(scope)))throw Error();if(!result.accessToken||!result.userInfo.preferred_username||result.accessTokenExpiresAt.getTime()<=Date.now())throw Error();session=result;window.dispatchEvent(new Event('hf-auth-change'));message('Account connected. You can choose GPU; your account is checked automatically before the run.');}else{sessionStorage.removeItem(flowKey);message(ready?'CPU needs no sign-in. For your account GPU allowance, sign in before choosing files.':'HF sign-in is not configured on this deployment. CPU remains anonymous.');}}).catch(()=>{try{sessionStorage.removeItem(flowKey);}catch{}clear();message('HF sign-in unavailable, cancelled, expired, or not verified. No GPU request started; CPU remains anonymous.');}).finally(()=>{exchanging=false;render();});setInterval(()=>{if(session&&session.accessTokenExpiresAt.getTime()<=Date.now()){clear();message('HF sign-in expired. Sign in again to identify account GPU requests. CPU remains available.');}},1000);})();1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041053 unmodified lines109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152'use strict';// Official HF PKCE redirect helpers. Only the one-use verifier crosses navigation;// OAuth access tokens and profile details stay in this page's memory.(() => {const node=id=>document.getElementById(id),flowKey='tiga.ald.hf.pkce.v1';const identityScopes=['openid','profile'],storageScopes=['openid','profile','write-repos'];let session=null,storageSession=null,locked=false,ready=false,config=null,exchanging=false;const message=text=>{node('hfIdentity').textContent=text;};const storageMessage=text=>{node('bucket_auth_status').textContent=text;};const scopeSet=value=>{if(typeof value!=='string'||!value.trim())return null;const items=value.trim().split(/\s+/),set=new Set(items);return set.size===items.length?set:null;};const exactScopes=(value,expected)=>{const scopes=scopeSet(value);return !!scopes&&scopes.size===expected.length&&expected.every(scope=>scopes.has(scope));};const storageEnabled=()=>ready&&config?.storage_enabled===true&&exactScopes(config.storage_scopes,storageScopes);function emitChange(){window.dispatchEvent(new Event('hf-auth-change'));}function render(){const anySession=!!session||!!storageSession;node('hfSignIn').hidden=!!session;node('hfSignIn').disabled=locked||exchanging||!ready;node('hfAccount').hidden=!session;node('hfAccount').textContent=session?'Connected as '+session.userInfo.preferred_username:'';node('hfSignOut').hidden=!anySession;node('hfSignOut').disabled=locked||exchanging||!anySession;node('hfSignOut').textContent=session?'Disconnect account':'Disconnect HF access';node('hfVerify').hidden=!session;node('hfVerify').disabled=locked||exchanging||!session;const authorize=node('bucket_authorize');if(authorize){authorize.hidden=!storageEnabled()||!!storageSession;authorize.disabled=locked||exchanging||!storageEnabled()||!!storageSession;}if(node('bucket_auth_unavailable'))node('bucket_auth_unavailable').hidden=storageEnabled();getStorageToken();if(node('bucket_auth_status'))node('bucket_auth_status').textContent=storageSession?'HF bucket access authorized as '+storageSession.userInfo.preferred_username+'. Choose your private bucket below.':'Not authorized. Bucket storage is optional.';}function clearAll(){session=null;storageSession=null;emitChange();render();}function clearStorage(){if(!storageSession)return;if(session===storageSession)session=null;storageSession=null;emitChange();render();}function getStorageToken(){if(storageSession&&storageSession.accessTokenExpiresAt.getTime()<=Date.now()){if(session===storageSession)session=null;storageSession=null;emitChange();storageMessage('HF authorization expired. Sign in or authorize access again to reconnect.');render();return null;}return storageSession?.accessToken??null;}window.HFAuth={get storageEnabled(){return storageEnabled();},get storageAuthorized(){return !!getStorageToken();},setBusy(value){locked=value;render();},credentials(){if(exchanging)throw Error('Complete HF sign-in before starting GPU');if(session&&session.accessTokenExpiresAt.getTime()<=Date.now()){clearAll();message('HF sign-in expired. Sign in again before an account GPU request.');throw Error('HF sign-in expired; sign in again');}return session?{token:session.accessToken}:{};},getStorageToken,getStorageUsername(){return getStorageToken()?storageSession.userInfo.preferred_username:null;},clearStorageAuthorization:clearStorage,verify(identity){if(session&&(!identity.authenticated||identity.auth_path!=='queue-bearer'||identity.username!==session.userInfo.preferred_username))throw Error('GPU queue visitor identity did not match your HF sign-in; no GPU request started');if(session)message('Account connection checked. GPU use remains subject to your HF allowance.');}};node('hfSignOut').onclick=()=>{clearAll();message('HF access disconnected from this app. CPU remains available. HF website sign-in is unchanged.');storageMessage('HF access disconnected. Authorize bucket access again to use storage.');};node('hfVerify').onclick=async()=>{try{await window.TrainingClient.verifyIdentity();}catch{message('Account connection check failed. No GPU request started. Disconnect and sign in again, or use CPU.');}};async function authorize(purpose){if(locked||exchanging||!ready)return;if(purpose==='storage'&&!storageEnabled())return;if(window.TrainingClient?.hasUnsavedState?.() &&!(await window.appConfirm('HF authorization navigates away. Selected files, a downloaded result and unsaved editor changes are lost; saved recipes remain. Continue, then reselect or recreate them?',{heading:'Continue to HF authorization',confirmLabel:'Continue to HF'})))return;exchanging=true;render();try{const state={},requested=purpose==='storage'?storageScopes:identityScopes;const helpers=await import('/hf-oauth.js');const url=await helpers.oauthLoginUrl({clientId:config.client_id,scopes:requested.join(' '),redirectUrl:location.origin+'/',localStorage:state});sessionStorage.setItem(flowKey,JSON.stringify({...state,started:Date.now(),purpose}));if(purpose==='storage')storageMessage('Opening HF permission request for bucket access. No password or personal token is entered here.');else message('Opening Hugging Face sign-in. No password or personal token is entered here.');location.href=url;}catch{exchanging=false;render();const text='HF authorization could not start. Tab-local sign-in storage is required; local export and CPU remain available.';if(purpose==='storage')storageMessage(text);else message(text);}}node('hfSignIn').onclick=()=>authorize('identity');node('bucket_authorize').onclick=()=>authorize('storage');const returned=location.href,params=new URL(returned).searchParams;const isCallback=params.has('code')||params.has('error');if(isCallback){history.replaceState(null,'','/');exchanging=true;}3 unmodified lineslet flow;try{flow=JSON.parse(sessionStorage.getItem(flowKey));}finally{sessionStorage.removeItem(flowKey);}if(!ready||!flow?.nonce||!flow?.codeVerifier||!Number.isFinite(flow.started)||Date.now()-flow.started>300000||flow.started>Date.now()||!['identity','storage'].includes(flow.purpose))throw Error();if(flow.purpose==='storage'&&!storageEnabled())throw Error();const helpers=await import('/hf-oauth.js');const result=await helpers.oauthHandleRedirect({redirectedUrl:returned,nonce:flow.nonce,codeVerifier:flow.codeVerifier});flow.nonce=null;flow.codeVerifier=null;const allowed=flow.purpose==='storage'?storageScopes:identityScopes;if(!exactScopes(result.scope,allowed))throw Error();if(!result.accessToken||!result.userInfo?.preferred_username||!Number.isFinite(result.accessTokenExpiresAt?.getTime())||result.accessTokenExpiresAt.getTime()<=Date.now())throw Error();if(flow.purpose==='storage'){// The optional storage grant includes the ordinary identity scopes. Reuse// this one page-memory grant for both purposes so the user signs in once.session=result;storageSession=result;emitChange();storageMessage('HF bucket access authorized as '+result.userInfo.preferred_username+'. Choose your existing private bucket below.');}else{session=result;storageSession=null;emitChange();message('Account connected. You can choose GPU; your account is checked automatically before the run.');}}else{sessionStorage.removeItem(flowKey);message(ready?'CPU needs no sign-in. For your account GPU allowance, sign in before choosing files.':'HF sign-in is not configured on this deployment. CPU remains anonymous.');storageMessage(storageEnabled()?'Not authorized. Bucket storage is optional.':'HF storage authorization is unavailable on this deployment. Local bundle export remains available.');}}).catch(()=>{try{sessionStorage.removeItem(flowKey);}catch{}clearAll();message('HF sign-in unavailable, cancelled, expired, or not verified. No GPU request started; CPU remains anonymous.');storageMessage('HF authorization unavailable, cancelled, expired, or not verified. Bucket storage remains disconnected; local export is available.');}).finally(()=>{exchanging=false;render();});setInterval(()=>{let changed=false;if(session&&session.accessTokenExpiresAt.getTime()<=Date.now()){session=null;message('HF sign-in expired. Sign in again to identify account GPU requests. CPU remains available.');changed=true;}if(storageSession&&storageSession.accessTokenExpiresAt.getTime()<=Date.now()){storageSession=null;storageMessage('HF bucket authorization expired. Authorize access again to reconnect.');changed=true;}if(changed){emitChange();render();}},1000);render();})();
5 unmodified lines6789101112135 unmodified linesdef oauth_config():client_id = os.environ.get('OAUTH_CLIENT_ID', '')return {'enabled': bool(client_id), 'client_id': client_id,'scopes': 'openid profile'}def visitor_identity(headers):5 unmodified lines67891011121314151617185 unmodified linesdef oauth_config():client_id = os.environ.get('OAUTH_CLIENT_ID', '')configured_scopes = set(os.environ.get('OAUTH_SCOPES', '').split())storage_enabled = bool(client_id and 'write-repos' in configured_scopes)config = {'enabled': bool(client_id), 'client_id': client_id,'scopes': 'openid profile', 'storage_enabled': storage_enabled}if storage_enabled:config['storage_scopes'] = 'openid profile write-repos'return configdef visitor_identity(headers):
38 unmodified lines394041424344454647484950515253414 unmodified lines46846947047147247347443 unmodified lines51851952052152252352415 unmodified lines54054154254354454538 unmodified lines<p><label>Track (.track) <input id="track" type="file" accept=".track"></label></p><p><label>Vehicle network (.evolution) <input id="network" type="file" accept=".evolution"></label></p><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. All results expire after five minutes. <a href="/policy" target="_blank" rel="noopener">Data policy</a></p></details></section><section class="card"><h2>Selected track & terrain</h2><p id="mapStatus" class="map-status" role="status">Loading selected track…</p><div class="map"><canvas id="trackMap" width="1000" height="500" role="img" aria-label="Selected track tile layout and terrain"></canvas></div><div class="map-legend"><span><i class="terrain asphalt"></i> Asphalt</span><span><i class="terrain dirt"></i> Dirt</span><span><i class="terrain ice"></i> Ice</span><span><i class="terrain start"></i> Start</span></div><p id="mapLegend" class="hint"></p><h2>Run & results</h2><button id="download" disabled>Download result</button> <button id="erase" disabled>Delete server-side job data now</button><p><button id="saveLocal" disabled>Save received result again (browser only)</button> <button id="forgetLocal" disabled>Discard browser result</button></p><p>The browser keeps the received result in memory until discarded, replaced by a new run, or this page is closed. It is not saved to browser storage.</p><h3 id="runState" role="status" aria-live="polite">READY — no run started</h3><pre id="runSummary" style="white-space:pre-wrap;line-height:1.7" aria-live="polite"></pre><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><p><button id="run_export" disabled>Export run receipt</button></p><p class="hint">Receipts include build identity, settings, metrics and file hashes. Review them before sharing; they contain no network weights or job access keys.</p><details id="portableBundle"><summary>Portable bucket bundle</summary><p>Build, export, or restore one validated bundle. Saving to an existing private bucket is optional and happens only when you explicitly connect, save, or restore. No automatic uploads occur.</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><details id="bucketStorage"><summary>Connect to an existing private bucket</summary><p>Use a fine-grained Hugging Face token that can access your private bucket. The token is sent to this app only for explicit bucket actions, stays in page memory, and is cleared when you disconnect, the app receives an expired or denied response, or this page closes. The app cannot create buckets or change visibility. Normal runs do not require a bucket connection.</p><div id="bucketConnectForm"><label for="bucket_id">Private bucket ID</label><input id="bucket_id" type="text" autocomplete="off" placeholder="username/bucket-name"><label for="bucket_token">Fine-grained bucket token</label><input id="bucket_token" type="password" autocomplete="new-password" spellcheck="false"><button id="bucket_connect" type="button">Connect bucket</button></div><div id="bucketConnected" hidden><p id="bucket_account"></p><button id="bucket_disconnect" type="button">Disconnect bucket</button><div class="toolbar"><button id="bucket_save" type="button" disabled>Save selected bundle</button><button id="bucket_refresh" type="button">Refresh saved bundles</button></div><label for="bucket_items">Saved bundles from this app</label><select id="bucket_items" size="4"><option value="">Refresh to list saved bundles</option></select><button id="bucket_restore" type="button" disabled>Restore selected bundle</button></div><p id="bucket_status" role="status" aria-live="polite">Not connected. Bucket storage is optional.</p></details></details><p id="deadline"></p><p id="status" role="status">Ready. Inputs remain on this device until you run the test.</p><details><summary>Effective training settings</summary><pre id="effectiveSettings"></pre></details><details><summary>Generation results</summary><pre id="generationHistory"></pre></details><details><summary>Star challenges — not evaluated</summary><p>The current runner has star-challenge reporting. Its evaluator and required statistics have not been ported to HF; no star result is inferred from a completed test.</p></details></section></div></div><section id="training" class="pane" hidden><div class="card"><h2>Training settings</h2><p class="hint">Choose the track on Drive & view. Choose the training settings and reward mix here, then start the run on Drive & view. Recipes and batch sequences are saved in this browser.</p><p><label for="trackPresetTraining">Training track</label><select id="trackPresetTraining" 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><div id="training_controls"><label for="training_ticks">Simulated ticks per generation</label><input id="training_ticks" type="number" min="1" max="18000" value="60"><small>60 ticks = one simulated second. Current preview limit: population × generations × ticks ≤ 4,000,000; execution timeout 25 seconds.</small>414 unmodified linesif(typeof module==='object'&&module.exports)module.exports=factory();else root.PortableBundle=factory();})(typeof window==='undefined'?globalThis:window,function(){const SCHEMA='ald.portable-bundle',LIMITS={network:4*1024*1024,track:1024*1024,recipe:32768,receipt:131072,bundle:8*1024*1024};const exact=(value,keys)=>{if(!value||typeof value!=='object'||Array.isArray(value)||Object.keys(value).sort().join()!==[...keys].sort().join())throw Error('Unexpected portable bundle fields');};43 unmodified linesif(Object.hasOwn(a,'run_receipt')){const r=a.run_receipt;exact(r,['version','kind','state','build_id','backend','output_sha256','report']);if(r.version!==1||r.kind!=='run'||r.state!=='completed'||typeof r.build_id!=='string'||r.build_id.length>128||!['cpu','gpu'].includes(r.backend)||! /^[a-f0-9]{64}$/.test(r.output_sha256)||!r.report||typeof r.report!=='object'||Array.isArray(r.report))throw Error('Invalid sanitized run receipt');const text=JSON.stringify(r);if(utf8(text).byteLength>LIMITS.receipt)throw Error('Run receipt exceeds 128 KiB bundle limit');receipt=r;}return {bundle,network:{...networkMeta,bytes:networkBytes},track,recipe,receipt};15 unmodified linesconst q=id=>document.getElementById(id),api=window.NetworkEditor;const status=text=>q('editor_status').textContent=text;let source=null,exportURL=null;for(const id of ['editor_name','editor_vehicle','editor_preset','editor_shape','editor_seed','editor_xavier','editor_bias','editor_create','editor_import','editor_outputs',...Array.from({length:5},(_,i)=>'editor_output_'+i)])q(id).disabled=false;const outputIds=[0,1,2,3,4],outputName=id=>'editor_output_'+id;function setOutputs(ids){for(const id of outputIds)q(outputName(id)).checked=ids.includes(id);}38 unmodified lines394041424344454647484950515253414 unmodified lines46846947047147247347443 unmodified lines51851952052152252352415 unmodified lines54054154254354454554638 unmodified lines<p><label>Track (.track) <input id="track" type="file" accept=".track"></label></p><p><label>Vehicle network (.evolution) <input id="network" type="file" accept=".evolution"></label></p><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></details></section><section class="card"><h2>Selected track & terrain</h2><p id="mapStatus" class="map-status" role="status">Loading selected track…</p><div class="map"><canvas id="trackMap" width="1000" height="500" role="img" aria-label="Selected track tile layout and terrain"></canvas></div><div class="map-legend"><span><i class="terrain asphalt"></i> Asphalt</span><span><i class="terrain dirt"></i> Dirt</span><span><i class="terrain ice"></i> Ice</span><span><i class="terrain start"></i> Start</span></div><p id="mapLegend" class="hint"></p><h2>Run & results</h2><button id="download" disabled>Download result</button> <button id="erase" disabled>Delete server-side job data now</button><p><button id="saveLocal" disabled>Download received result (browser only)</button> <button id="forgetLocal" disabled>Discard browser result</button></p><p>The browser keeps the received result in memory until discarded, replaced by a new run, or this page is closed. It is not saved to browser storage.</p><h3 id="runState" role="status" aria-live="polite">READY — no run started</h3><pre id="runSummary" style="white-space:pre-wrap;line-height:1.7" aria-live="polite"></pre><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><p><button id="run_export" disabled>Export run receipt</button> <button id="player_report_download" disabled>Download player report (.txt)</button> <button id="history_csv_download" disabled>Download generation history (.csv)</button></p><p class="hint">Reports use only server-reported run and generation fields. The engine does not report per-reward contribution, so reward weights are shown as configured values only.</p><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><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></div><p id="bucket_status" role="status" aria-live="polite">Not connected. Bucket storage is optional.</p></details></details><p id="deadline"></p><p id="status" role="status">Ready. Inputs remain on this device until you run the test.</p><details><summary>Effective training settings</summary><pre id="effectiveSettings"></pre></details><details><summary>Generation results</summary><pre id="generationHistory"></pre></details><details><summary>Star challenges — not evaluated</summary><p>The current runner has star-challenge reporting. Its evaluator and required statistics have not been ported to HF; no star result is inferred from a completed test.</p></details></section></div></div><section id="training" class="pane" hidden><div class="card"><h2>Training settings</h2><p class="hint">Choose the track on Drive & view. Choose the training settings and reward mix here, then start the run on Drive & view. Recipes and batch sequences are saved in this browser.</p><p><label for="trackPresetTraining">Training track</label><select id="trackPresetTraining" 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><div id="training_controls"><label for="training_ticks">Simulated ticks per generation</label><input id="training_ticks" type="number" min="1" max="18000" value="60"><small>60 ticks = one simulated second. Current preview limit: population × generations × ticks ≤ 4,000,000; execution timeout 25 seconds.</small>414 unmodified linesif(typeof module==='object'&&module.exports)module.exports=factory();else root.PortableBundle=factory();})(typeof window==='undefined'?globalThis:window,function(){const SCHEMA='ald.portable-bundle',LIMITS={network:4*1024*1024,track:1024*1024,recipe:32768,receipt:524288,bundle:8*1024*1024};const exact=(value,keys)=>{if(!value||typeof value!=='object'||Array.isArray(value)||Object.keys(value).sort().join()!==[...keys].sort().join())throw Error('Unexpected portable bundle fields');};43 unmodified linesif(Object.hasOwn(a,'run_receipt')){const r=a.run_receipt;exact(r,['version','kind','state','build_id','backend','output_sha256','report']);if(r.version!==1||r.kind!=='run'||r.state!=='completed'||typeof r.build_id!=='string'||r.build_id.length>128||!['cpu','gpu'].includes(r.backend)||! /^[a-f0-9]{64}$/.test(r.output_sha256)||!r.report||typeof r.report!=='object'||Array.isArray(r.report))throw Error('Invalid sanitized run receipt');const text=JSON.stringify(r);if(utf8(text).byteLength>LIMITS.receipt)throw Error('Run receipt exceeds 512 KiB bundle limit');receipt=r;}return {bundle,network:{...networkMeta,bytes:networkBytes},track,recipe,receipt};15 unmodified linesconst q=id=>document.getElementById(id),api=window.NetworkEditor;const status=text=>q('editor_status').textContent=text;let source=null,exportURL=null;window.hasUnsavedNetworkDraft=()=>!!source||q('editor_name').value!=='Fresh network'||q('editor_vehicle').value!=='0'||q('editor_shape').value!=='6,4'||q('editor_seed').value!=='42105'||!q('editor_xavier').checked||q('editor_bias').checked;for(const id of ['editor_name','editor_vehicle','editor_preset','editor_shape','editor_seed','editor_xavier','editor_bias','editor_create','editor_import','editor_outputs',...Array.from({length:5},(_,i)=>'editor_output_'+i)])q(id).disabled=false;const outputIds=[0,1,2,3,4],outputName=id=>'editor_output_'+id;function setOutputs(ids){for(const id of outputIds)q(outputName(id)).checked=ids.includes(id);}
11 unmodified lines1213141516171817 unmodified lines363738394041117 unmodified lines15916016116216316416518 unmodified lines184185186187188189190150 unmodified lines34134234334434534634711 unmodified linesMAX_NETWORK = 4 * 1024 * 1024MAX_TRACK = 1 * 1024 * 1024MAX_RECIPE = 32 * 1024MAX_RECEIPT = 128 * 1024MAX_BUNDLE = 8 * 1024 * 1024MAX_EXPANDED_JSON = 4 * 1024 * 1024HEX64 = re.compile(r"^[0-9a-f]{64}$")17 unmodified lines"elapsed_seconds", "best_score", "mean_score", "best_lap_seconds", "lapped_cars","simulated_ticks", "requested_ticks", "candidate_validated", "execution_backend", "inputs", "settings",}INPUT_HASH_KEYS = {"track_sha256", "network_sha256"}117 unmodified linesraise BundleError("run receipt build id is invalid")if not isinstance(receipt["output_sha256"], str) or not HEX64.fullmatch(receipt["output_sha256"]):raise BundleError("run receipt output hash is invalid")report = _strict_keys(receipt["report"], REPORT_KEYS, REPORT_KEYS, "run receipt report")if not _is_int(report["vehicle_type"], 0, 3) or report["vehicle_name"] != ("Formula", "Rally", "Snowmobile", "Truck")[report["vehicle_type"]]:raise BundleError("run receipt vehicle is invalid")for key in ("generations_completed", "generations_requested", "population", "simulated_ticks", "requested_ticks"):18 unmodified lineshashes = _strict_keys(report["inputs"], INPUT_HASH_KEYS, INPUT_HASH_KEYS, "run receipt inputs")if any(not isinstance(hashes[k], str) or not HEX64.fullmatch(hashes[k]) for k in INPUT_HASH_KEYS):raise BundleError("run receipt input hash is invalid")validate_settings(report["settings"])return receipt150 unmodified linesraise BundleError("run receipt backend does not match its execution backend")receipt_bytes = _json_bytes(receipt)if len(receipt_bytes) > MAX_RECEIPT:raise BundleError("run receipt exceeds 128 KiB")files["run_receipt.json"] = receipt_bytesreturn bundle, files11 unmodified lines1213141516171817 unmodified lines36373839404142434445117 unmodified lines16316416516616716816918 unmodified lines188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221150 unmodified lines37237337437537637737811 unmodified linesMAX_NETWORK = 4 * 1024 * 1024MAX_TRACK = 1 * 1024 * 1024MAX_RECIPE = 32 * 1024MAX_RECEIPT = 512 * 1024MAX_BUNDLE = 8 * 1024 * 1024MAX_EXPANDED_JSON = 4 * 1024 * 1024HEX64 = re.compile(r"^[0-9a-f]{64}$")17 unmodified lines"elapsed_seconds", "best_score", "mean_score", "best_lap_seconds", "lapped_cars","simulated_ticks", "requested_ticks", "candidate_validated", "execution_backend", "inputs", "settings",}HISTORY_ROW_KEYS = {"generation", "mutation", "best_score", "mean_score","best_lap_seconds", "lapped_cars", "simulated_ticks",}INPUT_HASH_KEYS = {"track_sha256", "network_sha256"}117 unmodified linesraise BundleError("run receipt build id is invalid")if not isinstance(receipt["output_sha256"], str) or not HEX64.fullmatch(receipt["output_sha256"]):raise BundleError("run receipt output hash is invalid")report = _strict_keys(receipt["report"], REPORT_KEYS | {"history"}, REPORT_KEYS, "run receipt report")if not _is_int(report["vehicle_type"], 0, 3) or report["vehicle_name"] != ("Formula", "Rally", "Snowmobile", "Truck")[report["vehicle_type"]]:raise BundleError("run receipt vehicle is invalid")for key in ("generations_completed", "generations_requested", "population", "simulated_ticks", "requested_ticks"):18 unmodified lineshashes = _strict_keys(report["inputs"], INPUT_HASH_KEYS, INPUT_HASH_KEYS, "run receipt inputs")if any(not isinstance(hashes[k], str) or not HEX64.fullmatch(hashes[k]) for k in INPUT_HASH_KEYS):raise BundleError("run receipt input hash is invalid")settings = validate_settings(report["settings"])if (report["population"] != settings["population"]or report["generations_requested"] != settings["generations"]or report["requested_ticks"] != settings["ticks"]):raise BundleError("run receipt summary does not match its validated settings")if "history" in report:history = report["history"]if not isinstance(history, list) or len(history) > 1000:raise BundleError("run receipt history must contain at most 1000 rows")if len(history) != report["generations_completed"]:raise BundleError("run receipt history length does not match completed generations")for index, row in enumerate(history, 1):row = _strict_keys(row, HISTORY_ROW_KEYS, HISTORY_ROW_KEYS, "run receipt history row")if not _is_int(row["generation"], 1, 1000) or row["generation"] != index:raise BundleError("run receipt history generations must be ordered from one")if not _is_number(row["mutation"], 0, 4.2):raise BundleError("run receipt history mutation is invalid")for key in ("best_score", "mean_score"):if not _is_number(row[key], -1e12, 1e12):raise BundleError("run receipt history score is invalid")if row["best_lap_seconds"] is not None and not _is_number(row["best_lap_seconds"], 0, 1e12):raise BundleError("run receipt history lap is invalid")if row["best_lap_seconds"] == 0:raise BundleError("run receipt history lap must be positive")if row["lapped_cars"] is not None and not _is_int(row["lapped_cars"], 0, 128):raise BundleError("run receipt history lapped-car count is invalid")if not _is_int(row["simulated_ticks"], 0, 4_000_000):raise BundleError("run receipt history tick count is invalid")return receipt150 unmodified linesraise BundleError("run receipt backend does not match its execution backend")receipt_bytes = _json_bytes(receipt)if len(receipt_bytes) > MAX_RECEIPT:raise BundleError("run receipt exceeds 512 KiB")files["run_receipt.json"] = receipt_bytesreturn bundle, files
12345676 unmodified lines14151617181920212259 unmodified lines828384858687888990919293944 unmodified lines9910010110210310411 unmodified lines116117118119120121122"""Shared CPU routes and delivery API for hosted ALD training."""import base64import jsonfrom pathlib import Pathimport threadingfrom fastapi import HTTPException, Requestfrom fastapi.responses import FileResponse, Response, HTMLResponse, JSONResponse6 unmodified linesfrom builtin_tracks import TrackLibraryfrom steam_leaderboard import compare_public_best_lap, milliseconds, SteamUnavailablefrom bucket_storage import BucketStorageError, MAX_REQUEST as BUCKET_MAX_REQUEST, run_bucket_operation, valid_bucket_id, valid_bundle_keyfrom portable_bundle import BundleError, load_bundle, MAX_BUNDLEROOT=Path(__file__).resolve().parentdef create_app(worker=run_reported,store=None,gpu_worker=None,track_library=None):app=create_api(store)59 unmodified linesraise HTTPException(429,'Storage operation busy')try:body=await bucket_body(request,token,limit=limit,fields=fields)if operation=='save':bundle=body.get('bundle')if not isinstance(bundle,str) or len(bundle.encode('utf-8'))>MAX_BUNDLE:raise HTTPException(400,'Invalid portable bundle')try: load_bundle(bundle.encode('utf-8'))except BundleError: raise HTTPException(400,'Invalid portable bundle') from Nonecall_args={'bundle_base64':base64.b64encode(bundle.encode('utf-8')).decode('ascii')}elif operation=='restore':if not valid_bundle_key(body.get('key')):raise HTTPException(400,'Invalid storage request')4 unmodified linesresult=await run_in_threadpool(run_bucket_operation,operation,token,body['bucket_id'],**call_args)except BucketStorageError as exc:raise bucket_http_error(exc) from Nonereturn resultfinally:bucket_admission.release()11 unmodified lines@app.post('/api/bucket/save')async def bucket_save(request:Request):result=await bucket_operation(request,'save',fields={'bucket_id','bundle'},limit=BUCKET_MAX_REQUEST)return JSONResponse({key:result[key] for key in ('status','bucket_id','key','bytes','sha256')},headers={'Cache-Control':'no-store'})@app.post('/api/bucket/restore')async def bucket_restore(request:Request):1234567896 unmodified lines1617181920212223242559 unmodified lines8586878889909192939495969798991001014 unmodified lines10610710810911011111211311411511 unmodified lines127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159"""Shared CPU routes and delivery API for hosted ALD training."""import base64import hashlibimport jsonfrom pathlib import Pathimport reimport threadingfrom fastapi import HTTPException, Requestfrom fastapi.responses import FileResponse, Response, HTMLResponse, JSONResponse6 unmodified linesfrom builtin_tracks import TrackLibraryfrom steam_leaderboard import compare_public_best_lap, milliseconds, SteamUnavailablefrom bucket_storage import BucketStorageError, MAX_REQUEST as BUCKET_MAX_REQUEST, run_bucket_operation, valid_bucket_id, valid_bundle_keyfrom portable_bundle import BundleError, load_bundle, MAX_BUNDLE, MAX_NETWORKROOT=Path(__file__).resolve().parentEVOLUTION_SIDECAR=re.compile(r'^[a-z0-9][a-z0-9-]{0,63}-(formula|rally|snowmobile|truck)-[0-9]{8}T[0-9]{6}Z-[0-9a-f]{8}\.evolution$')def create_app(worker=run_reported,store=None,gpu_worker=None,track_library=None):app=create_api(store)59 unmodified linesraise HTTPException(429,'Storage operation busy')try:body=await bucket_body(request,token,limit=limit,fields=fields)bundle_raw=Nonebundle_obj=Nonebundle_files=Noneif operation=='save':bundle=body.get('bundle')if not isinstance(bundle,str) or len(bundle.encode('utf-8'))>MAX_BUNDLE:raise HTTPException(400,'Invalid portable bundle')try: bundle_obj,bundle_files=load_bundle(bundle.encode('utf-8'))except BundleError: raise HTTPException(400,'Invalid portable bundle') from Nonebundle_raw=bundle.encode('utf-8')call_args={'bundle_base64':base64.b64encode(bundle_raw).decode('ascii')}elif operation=='restore':if not valid_bundle_key(body.get('key')):raise HTTPException(400,'Invalid storage request')4 unmodified linesresult=await run_in_threadpool(run_bucket_operation,operation,token,body['bucket_id'],**call_args)except BucketStorageError as exc:raise bucket_http_error(exc) from Noneif operation=='save':result['_validated_bundle_bytes']=bundle_rawresult['_validated_bundle_files']=bundle_filesresult['_validated_bundle_has_receipt']='run_receipt' in bundle_obj['artifacts']return resultfinally:bucket_admission.release()11 unmodified lines@app.post('/api/bucket/save')async def bucket_save(request:Request):result=await bucket_operation(request,'save',fields={'bucket_id','bundle'},limit=BUCKET_MAX_REQUEST)raw=result.pop('_validated_bundle_bytes',None)bundle_files=result.pop('_validated_bundle_files',None)has_receipt=result.pop('_validated_bundle_has_receipt',False)verified=result.get('verified_files')required={'bundle.json'}if has_receipt:required|={'report.md','generation-history.csv'}evolution=[name for name in verified if isinstance(name,str) and EVOLUTION_SIDECAR.fullmatch(name)] if isinstance(verified,dict) else []if len(evolution)!=1 or not isinstance(verified,dict) or set(verified)!=(required|{evolution[0]}):raise HTTPException(502,'Storage operation failed')if not isinstance(raw,bytes) or not isinstance(bundle_files,dict):raise HTTPException(502,'Storage operation failed')network=bundle_files['selected_network.evolution']safe_verified={}total=0for name,proof in verified.items():if (not isinstance(proof,dict) or set(proof)!={'bytes','sha256'}or type(proof['bytes']) is not int or not 0<=proof['bytes']<=MAX_BUNDLEor not isinstance(proof['sha256'],str) or not re.fullmatch(r'[0-9a-f]{64}',proof['sha256'])):raise HTTPException(502,'Storage operation failed')total+=proof['bytes']safe_verified[name]={'bytes':proof['bytes'],'sha256':proof['sha256']}if (total>MAX_BUNDLE+MAX_NETWORK+1024*1024or safe_verified['bundle.json']!={'bytes':len(raw),'sha256':hashlib.sha256(raw).hexdigest()}or safe_verified[evolution[0]]!={'bytes':len(network),'sha256':hashlib.sha256(network).hexdigest()}):raise HTTPException(502,'Storage operation failed')return JSONResponse({key:result[key] for key in ('status','bucket_id','key','bytes','sha256')}|{'verified_files':safe_verified},headers={'Cache-Control':'no-store'})@app.post('/api/bucket/restore')async def bucket_restore(request:Request):
BUCKET_BUNDLE.md+3-3
DATA_POLICY.md+16-16
FRONTEND_SOURCE.json+3-3
README.md+2
RELEASE_MANIFEST.json+12-12
STORAGE_BOUNDARY.md+4-3
bucket_storage.py+200-22
client.js+245-56
hf-auth.js+89-26
hf_identity.py+7-2
index.html+8-7
portable_bundle.py+35-4
server.py+41-4