From aa01cf6d279835168c0de0bdd3bf2b6ba3246521 Mon Sep 17 00:00:00 2001 From: fjarmula Date: Fri, 30 Oct 2026 08:37:53 +0100 Subject: [PATCH 1/4] docs: audit application architecture and simulation mathematics Document implemented modes, configuration, routing and timing equations, ITS lifecycles, signal schedules, and model limitations with source references. Remove the redundant Live demo link from the documentation header and update its assertions. Verify both quality suites and the production docs page. --- README.md | 3 + docs/architecture/system-logic.md | 920 ++++++++++++++++++ .../src/components/docs/DocsWorkspace.tsx | 5 +- .../components/docs/docs-workspace.test.tsx | 6 +- 4 files changed, 927 insertions(+), 7 deletions(-) create mode 100644 docs/architecture/system-logic.md diff --git a/README.md b/README.md index 09c5932..9d0633e 100644 --- a/README.md +++ b/README.md @@ -119,6 +119,9 @@ Public HTTPS hosting on a free Oracle VM: [deployment guide](deploy/README.md). ## Documentation +- [Implemented system logic and mathematical audit](docs/architecture/system-logic.md): modes, + configuration, travel-time formulas, signal state machines and implementation limitations. + - [GreenWave_ARCHITECTURE.md](GreenWave_ARCHITECTURE.md): system design and API. - [docs/adr/](docs/adr/README.md): architecture decisions and their status. - [backend/README.md](backend/README.md): ETL, simulation settings, simulated ITS feedback. diff --git a/docs/architecture/system-logic.md b/docs/architecture/system-logic.md new file mode 100644 index 0000000..f2dc6e3 --- /dev/null +++ b/docs/architecture/system-logic.md @@ -0,0 +1,920 @@ +# Implemented application logic and mathematical audit + +Audit date: 2026-10-30. Scope: the application at `origin/main` commit +`4eaaff1764d78e1453af944f026a68e6f1be05ef`, the base of `docs/app-logic-audit`. This is a source-derived description, not a proposed design or +calibration report. All signals, priority decisions, availability and travel predictions +are **simulated**. There is no physical signal actuation or live ITS connection. + +## 1. Architecture and authority + +Backend Pydantic models in [schemas](../../backend/src/greenwave/schemas/) define the +wire contract (`schema_version: "1.0"`, `is_simulated: true` on simulation responses/events). +[OpenAPI](../../contracts/openapi.json) and +[TypeScript API types](../../frontend/src/types/api.generated.ts) are generated from them. +Source links below identify the implementation behind each rule. Existing plans and the +architecture overview describe intent and history; discrepancies are listed in section 10. + +```mermaid +flowchart LR + Raw[Immutable raw inputs and manifest] --> ETL[Offline spatial ETL] + ETL --> Files[Graph and Parquet artifacts plus reports and hashes] + Files --> Load[Startup validation and indexes] + Load --> Rank[Incident lookup and resource ranking] + Rank --> Plan[Directed route and route-local signal model] + Plan --> Engine[One-second motion engine] + Engine --> Controller[Per-run simulated ITS controller] + Controller --> Engine + Engine --> Session[Exclusive session or comparison operation] + Session --> SSE[SSE event streams] + SSE --> Client[Frontend shared runtime and views] + Mock[Independent synthetic mock adapter] --> Client +``` + +### Ownership and boundaries + +| Layer | Responsibility and source | +| ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Offline ETL | [etl](../../backend/src/greenwave/etl/): project coordinates, weld roads, build directed graph, attach attributes and stop lines, group intersections, build neighbour/places/resources/quality artifacts. Never runs inside the tick loop. | +| Startup | [main.py](../../backend/src/greenwave/main.py), [loader.py](../../backend/src/greenwave/dataset/loader.py): load once, validate manifest and cross-stage hashes, counts, references, positions, resources and quality summary; freeze graph and build indexes. Missing, stale or malformed data aborts startup. No automatic mock fallback. | +| Routing | [planner.py](../../backend/src/greenwave/routing/planner.py), [network_index.py](../../backend/src/greenwave/routing/network_index.py): nearest eligible graph-node snapping, directed fastest ambulance route and stable parallel-edge selection. | +| Dispatch | [station_ranking.py](../../backend/src/greenwave/routing/station_ranking.py), [team_ranking.py](../../backend/src/greenwave/routing/team_ranking.py): choose candidates before starting a simulation. Resource eligibility is scenario state, not live dispatch. | +| Simulation | [engine.py](../../backend/src/greenwave/simulation/engine.py), [motion.py](../../backend/src/greenwave/simulation/motion.py): motion, requests, feedback application, fallback and telemetry projection. | +| ITS | [controller.py](../../backend/src/greenwave/its/controller.py): sole runtime phase programme and request lifecycle. The optional legacy gateway is a diagnostic sink only and is not installed by the app. | +| Transport | [session.py](../../backend/src/greenwave/simulation/session.py), [api/simulation.py](../../backend/src/greenwave/api/simulation.py): exclusive operation, clock, cancellation, bounded queues and SSE. No WebSockets or durable event log. | +| UI | [simulation provider](../../frontend/src/components/simulation-provider.tsx), [controller](../../frontend/src/lib/simulation-controller.ts), [adapters](../../frontend/src/lib/simulation-adapter.ts): shared in-memory scenario and transport state across route navigation. Maps/HUD render the contract. | + +Artifact hashes detect inconsistent builds, not malicious tampering: `etl_report.json` +itself is not authenticated. The loader does not claim reproducible or trusted builds. + +## 2. Modes, precedence and lifecycle + +### Independent mode axes + +| Axis | Values | Actual selection and effect | +| ----------------- | ------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Transport | `mock`, `backend` | Frontend build configuration, default `mock`. Backend failure does not switch transport. Mock is a separate synthetic implementation. | +| Run mode | `ENABLED`, `DISABLED` | Start request `green_wave_mode`, default `ENABLED`. Both use the same route selection and ambulance open-road speeds. Disabled uses ordinary stop-line crossing, never requests priority or cascades. | +| Junction crossing | `PRIORITY`, `STANDARD_FALLBACK` | Enabled starts with `PRIORITY`; failed request targets still ahead become `STANDARD_FALLBACK` permanently for that run. Disabled reports `null`. This is not a third global run mode. | +| Controller preset | `NOMINAL`, `DELAYED`, `REJECTED`, `NO_FEEDBACK`, `MIXED` | Applies to enabled runs. Assembly forces `NOMINAL` for disabled runs, regardless of request. | +| Cascade | Boolean | Effective only when enabled mode **and** `enable_cascade_mode` are true. Selection is one hop from independently eligible targets. | +| Operation | Single run or comparison pair | One exclusive operation per server process. A comparison creates enabled and disabled members with the same scenario and one shared simulated clock. | +| Presentation | Home, Green Wave, Standard traffic, Comparison, Diagnostics, Driver, Docs | [workspace-routes.ts](../../frontend/src/lib/workspace-routes.ts). Navigating views does not itself rewrite an active run's mode; a different mode requires replacement. | + +Mode hierarchy: choose transport at build time; construct the request from UI settings; +apply run mode (disabled suppresses cascade and controller preset effects); process the +per-request outcome; apply fallback only to failed, unpassed junctions. The frontend +[start builder](../../frontend/src/lib/start-request.ts) also normalizes disabled scenarios +to `NOMINAL`. No automatic route replanning occurs on rejection or timeout. + +### Server operation lifecycle + +```mermaid +stateDiagram-v2 + [*] --> Idle + Idle --> Planning: start or compare/start + Running --> Planning: replacement request + Planning --> Running: planning succeeds; supersede prior operation + Planning --> Idle: plan fails and no prior operation + Planning --> Running: plan fails; existing operation continues + Running --> Recovering: vehicle arrives + Recovering --> Completed: every junction NORMAL + Running --> Cancelled: stop / supersede / loop error + Recovering --> Cancelled: stop / supersede / loop error + Completed --> Idle + Cancelled --> Idle +``` + +This diagram summarizes operation ownership; planning executes in a worker thread while +an old operation can continue. A lock serializes start/stop planning. Active ID collision +returns HTTP 409 **before** replacement. Both comparison plans must succeed before the +old operation is superseded. Ended IDs may be reused and replace their retained entry. + +Each loop immediately steps every unfinished member once, then sleeps the remaining +interval. Both members get the same wall-clock timestamp. Stopping either member stops +the pair; a completed member's existing terminal is preserved. A loop exception cancels +unfinished members with `SERVER_ERROR`. Explicit stop uses `STOPPED`; replacement uses +`SUPERSEDED`. Exactly one terminal is published per run. Failed ITS requests no longer +emit the compatibility cancellation reasons `ITS_REJECTED`, `ITS_TIMEOUT`, or +`ITS_HOLD_EXPIRED`. + +Arrival is fractional simulated time; completion waits for signal recovery. KPI elapsed +time freezes at arrival. Further recovery ticks show speed zero and status `ARRIVED`. +A disconnect unsubscribes a client, not the run. Shutdown cancels active operations. + +### Tick order and clocks + +A [step](../../backend/src/greenwave/simulation/engine.py) performs, in order: + +1. Move for one simulated second under the **previous** controller report. +2. Build complete observations (TTIs and passed flags) and advance the controller. +3. Apply valid controller feedback, then requester acknowledgement timeouts. +4. Mark failed request targets ahead as fallback. +5. If enabled, select and submit one grouped dispatch for this tick. +6. Emit feedback, optional dispatch, tick, then completion if arrived and all normal. + +A newly submitted request cannot affect the movement or reported phase of that same step. +Fallback applied after movement affects the next motion step. Every step increments tick +and simulated time by **one**, even at accelerated playback. With playback factor $p$, +configured interval $I$ and step processing duration $c$, wall sleep is + +$$\Delta t_{\rm sleep}=\max(0,I/p-c).$$ + +Missed deadlines log a warning; there is no burst of catch-up ticks. Changing $I$ changes +wall pacing, not the simulated second. Expected ITS arrival timestamps separately divide +TTI by $p$; they do not include a nondefault $I$ (see limitations). + +## 3. Configuration reference + +### Sources and override rules + +[SimulationSettings](../../backend/src/greenwave/simulation_settings.py) is instantiated at +startup and frozen. For a field `x`, use environment variable `GREENWAVE_SIM_X` (uppercase). +Explicit constructor arguments override environment values, which override field defaults. +No dotenv file, secrets directory, CLI settings source or hot-reload endpoint is configured +by these classes. A launcher/Compose environment can supply variables, but the app does not +read a `.env` file itself. This follows the default +[Pydantic Settings source ordering](https://github.com/pydantic/pydantic-settings/blob/main/docs/index.md#field-value-priority). +Changing the process environment after startup does not update existing engines. + +Run request parameters are a separate validated layer; they do not override arbitrary +`SimulationSettings` fields. Unknown request fields follow Pydantic's default ignore +behavior; these request models do not enable strict types or `extra="forbid"`. + +| Configuration | Default | Validation / scope | +| ---------------------------------- | ------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------- | +| `GREENWAVE_PROCESSED_DIR` | `backend/data/processed` resolved from package location | `Path`; validated artifacts required at startup | +| `GREENWAVE_RAW_MANIFEST_PATH` | `backend/data/raw/MANIFEST.json` | `Path`; manifest must agree with processed artifacts | +| `GREENWAVE_CORS_ORIGINS` | `http://localhost:3000` | Comma split, trimmed, empty entries removed; no URL validator. Credentials false, GET/POST allowed. Read when app is constructed. | +| `NEXT_PUBLIC_SIMULATION_TRANSPORT` | `mock` | Trimmed `mock` or `backend`; invalid value warns and selects mock | +| `NEXT_PUBLIC_API_BASE_URL` | `http://127.0.0.1:8000` | HTTP(S) URL only; retain origin/path, remove trailing slash, query/hash; invalid value warns and uses default | + +`create_app(dataset=...)` bypasses disk loading for injected datasets; combining it with +path arguments raises `ValueError`. Explicit `processed_dir`/`manifest_path` arguments win +over dataset environment settings. Frontend public values are compiled into the bundle +and [cached](../../frontend/src/lib/config.ts) once per JS runtime. They are not server +simulation tuning variables. Client connection constants are 3 s stale, 15 s lost, +10,000 ms start timeout and 5 failed reconnect attempts; these have no environment override. + +### Every simulation setting + +Bounds below are exactly the declared field bounds, before cross-field validation. +`finite` means explicit `allow_inf_nan=False`; do not infer that constraint for other floats. +Units follow the names (`m`, `s`, `km/h`, `m/s`); factors and counts are dimensionless. + +| Field (`GREENWAVE_SIM_` prefix) | Default | Bounds | +| --------------------------------- | ------- | -------------- | +| `clearing_tti_seconds` | `40` | ge 0 | +| `priority_green_tti_seconds` | `25` | ge 0 | +| `recovery_hold_seconds` | `15` | ge 0 | +| `min_intersection_delay_seconds` | `3` | ge 0 | +| `greenwave_approach_distance_m` | `60` | gt 0, finite | +| `greenwave_min_rolling_speed_kmh` | `15` | gt 0, finite | +| `ambulance_speed_factor` | `1.3` | gt 0 | +| `ambulance_min_speed_kmh` | `30` | ge 0 | +| `ambulance_max_speed_kmh` | `90` | gt 0 | +| `speed_ema_alpha` | `0.25` | gt 0, le 1 | +| `speed_floor_meters_per_second` | `5` | ge 0 | +| `its_ack_delay_seconds` | `1` | ge 1 | +| `its_delayed_ack_seconds` | `5` | ge 1 | +| `its_ack_timeout_seconds` | `8` | ge 2 | +| `its_min_hold_seconds` | `40` | ge 0 | +| `its_hold_buffer_seconds` | `5` | ge 0 | +| `tick_interval_seconds` | `1` | gt 0 | +| `max_snap_distance_meters` | `150` | ge 0 | +| `max_on_foot_meters` | `800` | gt 0, finite | +| `on_foot_detour_factor` | `1.3` | ge 1.0, finite | +| `on_foot_speed_meters_per_second` | `1.4` | gt 0, finite | +| `dispatch_shortlist_size` | `5` | ge 1 | +| `area_preference_margin_seconds` | `60` | ge 0, finite | +| `subscriber_queue_size` | `32` | ge 1 | +| `retained_session_limit` | `4` | ge 1 | +| `normal_single_lane_factor` | `1.15` | ge 1.0 | +| `normal_unpaved_factor` | `1.3` | ge 1.0 | +| `normal_calming_seconds` | `3.0` | ge 0 | +| `ambulance_calming_seconds` | `2.0` | ge 0 | +| `ambulance_bus_lane_factor` | `1.05` | ge 1.0 | +| `ambulance_tram_track_factor` | `1.05` | ge 1.0 | +| `signal_green_seconds` | `30` | gt 0 | +| `signal_yellow_seconds` | `3` | ge 0 | +| `signal_all_red_seconds` | `2` | ge 0 | +| `standard_clearance_factor` | `1.0` | ge 0, finite | +| `standard_crossing_distance_m` | `30` | gt 0, finite | +| `standard_min_rolling_speed_kmh` | `10` | gt 0, finite | +| `standard_max_red_loss_seconds` | `15` | ge 0, finite | + +Cross-field validation additionally requires +`its_ack_delay_seconds <= its_delayed_ack_seconds < its_ack_timeout_seconds`, +`priority_green_tti_seconds <= clearing_tti_seconds`, and +`ambulance_min_speed_kmh <= ambulance_max_speed_kmh`. + +### Request options and frontend defaults + +Canonical sources: [simulation schema](../../backend/src/greenwave/schemas/simulation.py), +[ITS schema](../../backend/src/greenwave/schemas/its.py), +[dispatch schema](../../backend/src/greenwave/schemas/dispatch.py), +[start builder](../../frontend/src/lib/start-request.ts). + +| Field | API default / requirement | UI initial value / semantics | +| ---------------------------- | ----------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | +| `simulation_id` | Required; `^[A-Za-z0-9_-]{1,64}$` pattern | Client chosen; active collision is 409 | +| `origin`, `destination` | Required; lat in [-90,90], lng in [-180,180] | Chosen station and incident, respectively | +| `traffic_density_multiplier` | Required for start, [1,3]; ranking default 1 | 1.5; changes ordinary-car estimate and standard red loss, not open-road ambulance speed | +| `enable_cascade_mode` | Required boolean | true; ignored by disabled mode | +| `playback_speed` | Integer [1,10], default 1 | 1; controls wall pacing only | +| `vehicle_type` | `AMBULANCE` default; also `FIRE_TRUCK`, `POLICE_CAR` | Chooses stations and presentation; all share the ambulance speed model | +| `green_wave_mode` | `ENABLED` default; also `DISABLED` | Mode-specific view/settings; comparison creates one of each | +| `its_scenario` | `NOMINAL` default; five closed enum values | `NOMINAL`; disabled forces nominal | +| `its_outcome_seed` | Integer [0, 4294967295], default 0 | 0; UI truncates finite numbers, clamps to range, non-finite/undefined becomes 0; fixed presets ignore seed | +| Comparison IDs | Required enabled/disabled IDs, must differ | Each streams/stops at its own URL; no global mode field in comparison request | +| Rank `time_mode` | `ENABLED` default | Selects drive estimate used for ranking, including area rule | +| Rank `resource_aware` | false | Opt-in ambulance team eligibility/area policy; false ranks bases by time | +| Rank `scenario_time` | null → server's Warsaw time, minute precision | Aware inputs convert to Europe/Warsaw, naive inputs interpreted as local; not a signal-cycle offset | +| Rank `availability` | Empty dict; at most 200 team-code keys; `free`/`busy` | Missing means assumed free if on shift; free cannot override off shift | +| Geocode `q`, `limit` | Query length 2–100; limit 1–10, default 8 | Local address search, no external geocoder | + +### Controller response presets and deterministic draws + +| Preset | Result for each grouped request | Default simulated delay | +| ------------- | ----------------------------------------------------------------------------- | ----------------------- | +| `NOMINAL` | `ACCEPTED` | 1 s | +| `DELAYED` | `ACCEPTED` | 5 s | +| `REJECTED` | `REJECTED`, reason `CONTROLLER_REJECTED` | 1 s | +| `NO_FEEDBACK` | No controller response; requester marks `TIMED_OUT` / `ACK_TIMEOUT` | 8 s timeout | +| `MIXED` | One of the above four outcomes, deterministic from seed and sorted target IDs | Outcome-specific | + +[MIXED](../../backend/src/greenwave/its/controller.py) is a reproducible hash partition, +not independent random sampling per junction or per tick. A grouped request shares one +outcome. Serialize UTF-8 `":"`; compute FNV-1a using +$h_0=\mathtt{0x811C9DC5}$ and, for each byte $b$, + +$$h\leftarrow((h\oplus b)\,\mathtt{0x01000193})\bmod 2^{32}.$$ + +Finalize using MurmurHash3 `fmix32`: + +$$ +\begin{aligned} +h&\leftarrow h\oplus(h\gg16),\\ +h&\leftarrow h\,\mathtt{0x85EBCA6B}\bmod2^{32},\\ +h&\leftarrow h\oplus(h\gg13),\\ +h&\leftarrow h\,\mathtt{0xC2B2AE35}\bmod2^{32},\\ +h&\leftarrow h\oplus(h\gg16). +\end{aligned} +$$ + +Index $h\gg30$ selects `ACCEPT`, `ACCEPT_DELAYED`, `REJECT`, `NO_RESPONSE` in that order. +The four hash buckets each occupy one quarter of the 32-bit output space; this is not +a guarantee of 25% observed frequency on a finite seed/route set. Time, playback and +simulation ID are not hash inputs; cascade changes grouping and can change the outcome. + +### Offline ETL settings + +[etl/config.py](../../backend/src/greenwave/etl/config.py) holds Python constants, +not request/runtime environment overrides. Changes to derived artifact inputs require +regenerating the affected stages. A few constants also have runtime consumers: +`AREA_LOOKUP_RADIUS_M` controls incident-area lookup and `ADDRESS_MATCH_CLEAN_M` controls +address disagreement presentation. Changing those consumers requires restarting the server; +rebuild any artifacts that also depend on the changed constant. +Its comments mark approved rules, analysis-only probes and uncalibrated placeholders. +The full constant inventory is in [section 11](#11-offline-configuration-inventory). +Important model inputs are: + +| Rule | Implemented default | +| ------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- | +| CRS | Source EPSG:4326; metric calculations EPSG:2178 | +| Ordinary intersection delays | Signalised junction, mid-block signal and pedestrian crossing each 35 s; counted once per unique intersection, not per signal | +| Cascade threshold | 250 m inclusive; loaded from processed neighbours report into routing index | +| Signal grouping / standalone crossing | 40 m single linkage; crossing within 30 m of counted signal is duplicate | +| Junction assignment and merging | ≥3 distinct neighbours; 50 m approach assignment; 30 m junction merge; 15 m pedestrian crossing merge; 65 m merged-group diameter cap | +| Road welding | 1 m, respecting layer/bridge/tunnel separation | +| Tram track matching | Within 6 m along at least 0.5 of edge length | +| Places / address matching | Station dedup 150 m; address dedup 400 m; EMUiA clean agreement ≤100 m and maximum pair match ≤500 m; name-variant 50 m / tight 20 m | +| Dispatch geography | PRM/OSM base match 200 m; nearest EMUiA district lookup 250 m; places snap default 150 m | + +[Road rules](../../backend/src/greenwave/etl/road_rules.py) accept positive integer +`maxspeed` with optional `km/h`; values such as `50 mph`, `PL:urban`, `none`, lists or +zero use the road-class default with an explicit source marker. Defaults: motorway 140, +trunk 70, residential 30, living_street 20, service 30, track 15, pedestrian 10, other supported +classes 50 km/h. Explicit one-way tags win, including `oneway=no`; otherwise roundabout / +circular and motorway / motorway_link imply forward one-way; others default two-way. +Unrecognized direction tags raise an error rather than silently choosing a direction. + +## 4. Routing, spatial math and resource selection + +### Distance and path cost + +Lengths and snapping use projected metres. The snap set is the largest strongly connected +component, so snapped nodes mutually connect in the loaded graph. The graph retains other +components, but they are excluded from endpoint snapping. +Origin beyond the 150 m snap bound raises `ORIGIN_OFF_NETWORK`. Destination outside the +bound attempts on-foot access; an in-bound but unreachable destination does not trigger +that fallback (normally snapped nodes share the largest strongly connected component, +so this unreachable case concerns nonstandard/injected indexes). Same-node direct simulation raises `NO_ROUTE`; dispatch can instead answer +on site without starting a run. + +The [path weight](../../backend/src/greenwave/routing/planner.py) is ambulance **edge** +travel time, including calming but excluding junction penalties, density, controller +outcomes and signal timing. For parallel edges use the smallest edge time; selection ties +use edge ID. Both modes therefore select the same route. Dijkstra-style graph searches +have usual $O((|V|+|E|)\log|V|)$ heap complexity. They run during planning/ranking, outside +the event loop's motion step. + +Each controlled edge ends at a route stop line. Group those lines by unique intersection +ID, preserving its first/last positions and all distinct intermediate lines. The nominal +estimate charges its delay once; Standard motion can make a decision at **every** line. + +### Off-road access + +For projected straight-line distance $r_n$ from node $n$ to incident, detour factor $f=1.3$ +and walking speed $u=1.4$ m/s: + +$$d_{\rm walk}(n)=f r_n,\qquad T_{\rm walk}(n)=fr_n/u.$$ + +Consider eligible nodes with $fr_n\le800$ m and select the reachable node minimizing +$T_{\rm drive,edge}(n)+T_{\rm walk}(n)$, ties by node key. The origin node is excluded +from driven access selection. No candidate within reach gives `DESTINATION_OFF_NETWORK`; +no reachable candidate gives `NO_ROUTE`. The walk is a barrier-free straight-line model +with a scalar detour, not pedestrian routing. Run estimates/KPIs end at vehicle arrival; +`destination_on_foot` reports the walk separately. + +### Ranking and area policy + +Station ranking runs reversed Dijkstra from the incident (or multiple access nodes seeded +with walking time), then fully estimates the best five reachable bases by default. Sort +by mode-specific drive + walk, tie by station ID; return up to three. A base on the +incident node is on site. For off-network incidents, walk directly from the station when +it beats driving to another access point; driving wins equal totals. The top-five cut can +omit a base that would win after junction timing is included. + +Resource-aware ambulance ranking evaluates **all eligible bases** (overriding that cut), +selecting one team per base: in-area first, then team code. Eligibility requires matching +weekday (Monday 1), inclusive `MM-DD` season (including year-wrapping seasons), and +minute-of-day in `[ready_from_min, ready_to_min)`. Off shift wins over any override; on-shift +`busy` is excluded; missing override is eligible but badged `assumed_free`. No eligible +team returns `NO_ELIGIBLE_RESOURCE`, not a fabricated vehicle. Eligible teams with no +reachable base return `NO_STATION_REACHABLE`. + +Let $T_*$ be the fastest candidate's total and $T_A$ the fastest in-area total. If an +in-area candidate exists and + +$$T_A-T_*\le \texttt{area_preference_margin_seconds}=60\text{ s},$$ + +choose it; otherwise choose the fastest. If fastest is already in-area (or no in-area +candidate), reason is `NEAREST`; otherwise `IN_AREA_WITHIN_MARGIN` or +`NEAREST_OUTSIDE_MARGIN`. Put recommendation first, remaining candidates by total. +Unknown incident area gives pure nearest ranking. Team type is display metadata, not +a ranking coefficient. Fire/police and `resource_aware=false` bypass team policy. + +### Address and incident lookup + +[Address search](../../backend/src/greenwave/places/address_index.py) normalizes street +keys, then orders prefix matches before substring matches, exact trailing house number +before number prefixes, Kraków before outside addresses, street and natural house number, +distance to city centre, latitude and longitude. Alternate street names index the same +record; duplicate labels collapse to the best hit. EMUiA coordinates take precedence for +matched addresses; OSM displacement above 100 m is surfaced as disagreement. +[Incident area](../../backend/src/greenwave/places/incident_area.py) uses the nearest +EMUiA-backed district point within 250 m and maps districts 1–3 to Śródmieście, 4–7 to +Krowodrza, 8–13 to Podgórze and 14–18 to Nowa Huta. There is no polygon containment +check in this lookup; a nearby point supplies the district. + +## 5. Travel-time formulas, motion and KPIs + +### Edge models and three different trip times + +Source: [edge_times.py](../../backend/src/greenwave/routing/edge_times.py), +[estimates.py](../../backend/src/greenwave/routing/estimates.py). +Let $L_e$ be edge metres, $V_e$ its ordinary km/h, $n_e$ calming feature count, +$\mu$ traffic density, $D_i$ the stored ordinary delay, and $N$ unique route intersections. +The maximum applicable boost is used, **not** a product: + +$$b_e=\max(1,\ b_{\rm bus}\text{ if bus lane},\ b_{\rm tram}\text{ if tram track}).$$ + +$$V_{a,e}=\min\{\max(f_a V_e b_e,V_{a,\min}),V_{a,\max}\}.$$ + +Defaults are $f_a=1.3$, $V_{a,\min}=30$, $V_{a,\max}=90$ km/h and both boosts 1.05. +Lane factor $\ell_e=1.15$ exactly when `lanes_per_direction == 1`, else 1; +surface factor $s_e=1.3$ exactly when `surface_class == "unpaved"`, else 1. +Unknown attributes are neutral. Then + +$$ \begin{aligned} +t_{a,e}&=L_e/(V_{a,e}/3.6)+n_e c_a, & c_a&=2\text{ s},\\ +t_{n,e}&=L_e\mu\ell_es_e/(V_e/3.6)+n_e c_n, & c_n&=3\text{ s},\\ +\widehat T_{\rm normal}&=\sum_e t_{n,e}+\sum_iD_i,\\ +\widehat T_{\rm greenwave}&=\sum_e t_{a,e}+N D_{\min}, &D_{\min}&=3\text{ s}. +\end{aligned}$$ + +`estimated_normal_time_sec` is an ordinary-car **formula**, not the time of the disabled +ambulance. `estimated_greenwave_time_sec` is nominal and does not simulate acknowledgement, +signal holds, rejection or fallback. `estimated_standard_time_sec` is an actual dry run of +the disabled ambulance's motion from time zero (section 5 below). All three cover the +already chosen route; they are not three independently optimized routes. + +### One-second integrator + +[RouteTrack](../../backend/src/greenwave/simulation/route_track.py) spreads calming +penalties uniformly over an edge: effective speed $u_e=L_e/t_{a,e}$ for positive length; +zero-length edges use boosted speed directly. Each step spends a one-second budget, +splitting at edge boundaries, approach starts, stop lines, crossing ends and destination. +For remaining time $B$ and distance $d$ to the next boundary, move +$\min(d,uB)$, deduct actual travel time, and continue on the next segment. Fractional +arrival is recorded as $t_{\rm old}+1-B_{\rm remaining}$; telemetry speed is distance +actually driven in that second times 3.6, not the instantaneous final-edge speed. +Tolerances are $10^{-9}$ s/m in the integrator. + +### Enabled rolling slowdown and safety hold + +For a junction's first line at $s_i$, approach starts at + +$$a_i=\max(s_{\rm previous\ first\ line},\ s_i-60\text{ m}),$$ + +with previous position zero when absent. At actual slowdown start $x$, let $W=s_i-x$, +$u$ current ambulance m/s, $u_f=15/3.6$ m/s. For $u>u_f$, set + +$$C=\max\left(W,\frac{D_{\min}}{1/u_f-1/u}\right);$$ + +otherwise use $C=W$. Add $C$ to any still-running crossing distance (capped at distance +to destination), and $D_{\min}$ to remaining extra time $E$. Spend it with the shared +cautious-speed formula + +$$u_c=\frac{1}{1/u+E/R},\qquad +E' = E(1-\Delta x/R),\quad R'=R-\Delta x,$$ + +where $R$ is remaining crossing distance. At constant $u$, driving $R$ takes $R/u+E$; +this explains how a delay is spent while rolling. Adjacent slowdowns can merge. With no +room to roll, the code uses a dwell of $D_{\min}$ instead. For a route-ending truncation +or combined slowdown the floor is not mathematically guaranteed (section 10). + +At the priority first line the vehicle holds until all **known supported route vehicle +indications** at that stop-line ownership set were green in the previous report. A known +red/yellow blocks departure even if acceptance has occurred. With no supported route +vehicle phases the check permits departure; it does not fabricate confirmed green. +Later internal lines of the same priority junction do not start another slowdown/hold; +they remain relevant to phase grouping and last-line release. Fallback targets are excluded +from this hold. A hold already waiting there is released +through Standard crossing rules once its owner has fallen back. + +### Standard and fallback crossing + +Disabled mode applies this at every route stop line; enabled mode applies it only to +fallback owners. Sample the ordinary programme at the **fractional** line-arrival time. +All facing route movements green means drive on. Red/yellow/unknown starts a controlled +rolling crossing. With multiple owners, use the longest wait among non-green owners. +If a supported movement has no next-green answer, use its $D_i$. + +For slot length $S=G+Y+A$, cycle $C_y=2S$, route slot $g$, define +$q=(t-gS)\bmod C_y$. The wait is + +$$w(t)=\begin{cases}0&qu_f). +\end{aligned}$$ + +If $u\le u_f$, use $R=L_c$, $E=0$. Unknown movement substitutes $D_i$ for $w$. +Sizing examines covered edges and lowers $u$ to the slowest ordinary limit, lengthening +the crossing until consistent. If a later edge is at/below the floor, end at its start +and cap extra time to fit preceding distance. Motion uses $u_c$ above, with each covered +edge's ordinary limit; open road still uses ambulance speed. There is no stop-and-wait +until green in this model. The ordinary-car lane/surface penalties do not enter it. + +A later line replaces an ongoing Standard crossing; green can clear its remainder. +Fallback also replaces its own earlier priority slowdown remainder, avoiding two penalties +for that owner. A previous priority junction's remaining slowdown is retained/merged. +The crossing extra time is bounded per decision, not per unique junction or complete route. +A destination reached before crossing end discards its unspent remainder. + +### Standard profile, savings and rounding + +[standard_estimate.py](../../backend/src/greenwave/simulation/standard_estimate.py) +dry-runs the **same** `move_one_second` in disabled mode using ordinary controller queries. +It records $(x_k,t_k)$ each second plus the exact final fractional arrival. The finite +iteration bound is the sum of every edge traversed at its ordinary limit plus +`stop_line_count * standard_max_red_loss_seconds`, rounded up plus one step; an +undriveable/non-arriving route raises `RuntimeError`. + +For position $x$ between profile samples, linear interpolation gives + +$$T_s(x)=t_l+\frac{x-x_l}{x_r-x_l}(t_r-t_l).$$ + +The final estimate is exact with respect to this integrator; time at intermediate +positions is interpolated across a one-second sample and can straddle speed changes. +[Live KPIs](../../backend/src/greenwave/simulation/telemetry.py) use + +$$T_{\rm elapsed}=\begin{cases}t_{\rm arrival}&\text{arrived},\\t&\text{otherwise},\end{cases}$$ + +$$\texttt{current_time_saved_sec}=\begin{cases} +0&\text{disabled},\\ +\operatorname{round}(T_s(x))-\operatorname{round}(T_{\rm elapsed})&\text{enabled}. +\end{cases}$$ + +Elapsed KPI is $\operatorname{round}(T_{\rm elapsed})$. The difference is of **separately +rounded** times, not a rounded difference, and is not clamped to zero. Enabled can be +slower. Python `round` uses ties-to-even. Start response estimates are also rounded. +Recovery ticks do not erode savings. Displayed TTI is rounded; request eligibility uses +the unrounded value. + +The [comparison result](../../frontend/src/lib/comparison/race.ts) requires both successful +completion payloads and subtracts their reported arrival times: +$\Delta=T_{\rm disabled}-T_{\rm enabled}$. Its live distance lead is enabled minus disabled +distance, called level when absolute lead is **less than** 10 m. It can show physical +arrival before terminal recovery completes; a tie chooses enabled for its arrival label. + +### Geometry used for display + +Route metric distance is not recomputed from screen coordinates. `RouteTrack.position_at` +uses equirectangular WGS84 polyline segment lengths + +$$\delta_j=111320\sqrt{(\Delta\lambda_j\cos\varphi_0)^2+(\Delta\varphi_j)^2},$$ + +where longitude/latitude differences are in degrees and $\varphi_0$ is converted to radians +for cosine. Map $x/L_{\rm route}$ to the same fraction of total polyline offsets and +linearly interpolate longitude/latitude in that segment. This tolerates metric/display +length differences; it is a city-scale rendering approximation, not the routing metric. + +## 6. Priority selection, cascade and request lifecycle + +### TTI and cascade + +[TTI](../../backend/src/greenwave/simulation/corridor.py) uses first line $s_i$ and distance +travelled $x$, with a moving speed estimate: + +$$\bar v_t=\max\{v_{\rm floor},\alpha\Delta x_t+(1-\alpha)\bar v_{t-1}\},\quad +\mathrm{TTI}_i=\frac{\max(0,s_i-x)}{\bar v_t}.$$ + +Defaults are $\alpha=0.25$, $v_{\rm floor}=5$ m/s; initial EMA is maximum of first-edge +effective speed and that floor. Since the step is one second, $\Delta x_t$ numerically +has units m/s. Passed junctions have TTI `null`. A zero configured floor permits division +by zero in a later stopped state; the schema allows it but supplies no separate guard. + +[Selection](../../backend/src/greenwave/simulation/priority_requests.py) takes every +unrequested, unpassed target with TTI ≤40 s. Add each such source's forward cascade +targets, not the targets' targets. [Route model](../../backend/src/greenwave/simulation/route_model.py) +uses **first-to-first along-route distance ≤ the loaded threshold** (default 250 m). +The offline shortest-drive neighbour table is diagnostic/candidate evidence, not a +runtime membership gate. Sources are marked `is_cascade=false`; added targets that are +not independently eligible are true. At most one grouped request per tick; each target +is requested at most once, including after failure. Separate requests never compete for +a previously used target. + +### Hold and expected arrival + +For each selected target $i$, [release time](../../backend/src/greenwave/simulation/dispatch.py) +is estimated as + +$$R_i=T_{\rm open}(x,s_{i,\rm last})+D_{\min}J_i+E_{\rm remaining},$$ + +where $J_i$ counts unpassed junctions with first line ≤ target first line **or** first line +strictly inside its last line. The in-progress slowdown can be counted both in $J_i$ and +$E_{\rm remaining}$; this conservatively lengthens the hold. It does not predict future +unconfirmed-green waits or Standard fallback loss. + +$$H=\max(\texttt{its_min_hold_seconds},\lceil\max_iR_i\rceil+\texttt{its_hold_buffer_seconds}),$$ + +$$\mathrm{expected\ arrival\ UTC}=\mathrm{now\ UTC}+\min_i\mathrm{TTI}_i/p.$$ + +Default minimum/buffer are 40/5 s. The payload separately validates $H\ge40$ even if the +setting is configured lower. Hold expiry is measured from **submission**, not acceptance. + +### Request transitions + +```mermaid +stateDiagram-v2 + [*] --> REQUESTED: submit once + REQUESTED --> ACCEPTED: preset accepts after delay + REQUESTED --> REJECTED: preset rejects after delay + REQUESTED --> TIMED_OUT: requester timeout + REQUESTED --> RELEASED: all grouped targets passed before decision + ACCEPTED --> RELEASED: all grouped targets passed + ACCEPTED --> EXPIRED: submission time plus hold reached +``` + +The controller first checks all-targets-passed release, then due acknowledgement, then +accepted hold expiry. Acceptance after the hold deadline immediately produces acceptance +and expiry together and never activates an expired target. `NO_RESPONSE` stays pending +until timeout unless all targets pass first. Timeout withdraws it and reserves a controller +sequence number, preventing a later decision/activation. Rejection, timeout and expiry +put only their **unpassed** targets into permanent fallback. Other targets keep requesting +priority; the enabled run can complete with `fallback_intersection_ids` in route order. + +The ledger accepts feedback only for its simulation and known request, with exactly +matching ordered target group, strictly increasing global feedback sequence, legal +transition and nondecreasing observed simulated time. Wrong-run, duplicate, stale and +out-of-order feedback is ignored. Identical duplicate submission is idempotent; +conflicting duplicates or unknown/reused controller targets raise an error. Closing a +controller clears its requests and blocks further activation. + +## 7. Intersection state machine + +The authoritative [controller](../../backend/src/greenwave/its/controller.py) computes +state from observations and accepted requests; it is not a chain of unconditional TTI +threshold transitions. Runtime defaults are `NORMAL`, `is_cascade=false`, unpassed. + +```mermaid +stateDiagram-v2 + [*] --> NORMAL + NORMAL --> CLEARING: accepted request; waiting for eligibility or shown green + NORMAL --> PRIORITY_GREEN: accepted; TTI at most 25; route indications already green + CLEARING --> PRIORITY_GREEN: TTI at most 25 and all route vehicle indications green + PRIORITY_GREEN --> CLEARING: no complete shown-green route confirmation + CLEARING --> NORMAL: request no longer accepted and target unpassed + PRIORITY_GREEN --> NORMAL: request no longer accepted and target unpassed + CLEARING --> RECOVERY: passed after active priority state + PRIORITY_GREEN --> RECOVERY: passed after active priority state + RECOVERY --> NORMAL: recovery age at least 15 s + NORMAL --> NORMAL: passed without active priority +``` + +| State | Exact condition / consequence | +| --- | --- | +| `NORMAL` | No accepted priority for an unpassed target, or passed without previous active state, or recovery completed. A pending dispatch alone stays normal. Ordinary programme applies. | +| `CLEARING` | Accepted, unpassed, TTI >25 s or no TTI; also the reported downgrade when priority targets cannot be confirmed all green. Non-route vehicles and pedestrians target red; route vehicles keep ordinary colour while the programme is in clearing. | +| `PRIORITY_GREEN` | Accepted, unpassed, TTI ≤25 s, and every supported route vehicle indication is present and shown green. Programme targets route vehicles green, others red. No route vehicle phases means reported clearing, never confirmed priority green. | +| `RECOVERY` | A previously active target becomes passed. Records recovery start time and preserves cascade flag. Ordinary cycle resumes immediately; 15 s is a runtime recovery hold, not an additional all-red phase. | + +The controller creates programme targets from tentative runtimes **before** downgrading +unconfirmed `PRIORITY_GREEN` to reported `CLEARING`. This lets clearance advance toward +priority even while the reported state remains clearing. A target can enter priority +directly from normal if acceptance, eligibility and green confirmation coincide. +TTI eligibility is recomputed each tick; there is no latch that requires priority to +remain green after TTI increases. + +Passed requires reaching the **last** line and no longer holding there. An active last +line remains protected through the tick whose movement carries the vehicle across it: +`holding_priority` compares that line with both pre-step and post-step distance. Shared +line waits count for every owning junction. At a destination on that line the arrival +interval remains protected, then recovery can begin next tick. A request passed while +never active needs no recovery. Cancellation closes the controller; it does not stream +15 extra recovery seconds or send a physical reset. + +`is_active_corridor` is true exactly in clearing/priority-green. `is_cascade` is separate +metadata, never a state named `CLEARING_CASCADE`. The frontend consumes these fields; +it does not infer accepted green from an ITS dispatch. + +## 8. Ordinary and priority signal programmes + +Source: [phases.py](../../backend/src/greenwave/simulation/phases.py). +This is a two-slot explanatory abstraction, not geometry-derived lane conflict planning. +A movement group is the sorted controlled-edge identity. All route signal groups are +merged into one through-movement group; pedestrian-only nodes crossing those arms share +its slot. Sort group identities and assign ordinal modulo two. A signal without +controlled-edge identity has no slot/indicator. A vehicle-capable route signal is one +whose controlled edges intersect the route's approach edges. Missing geometry produces +no indicator, rather than a synthetic backend position. + +### Ordinary schedule + +Let green $G=30$ s, yellow $Y=3$ s, all-red $A=2$ s. Slot $S=G+Y+A=35$ s; +cycle $C_y=2S=70$ s. For absolute simulated time $t$: + +$$p=t\bmod C_y,\quad g_{\rm active}=\lfloor p/S\rfloor,\quad r=p-g_{\rm active}S.$$ + +| Within-slot time | Active slot vehicles | Other slot vehicles | Pedestrians crossing other slot's arm | +| --- | --- | --- | --- | +| $0\le r YELLOW: target ceases to be green + YELLOW --> RED: age at least signal_yellow_seconds + RED --> GREEN: target green and all non-green-target other heads already red +``` + +A new head with no prior state initializes directly to its target. A yellow head must +finish yellow even if its target becomes green again. A red head only enters green when +all *other* prior heads not also targeting green are red. Thus the one-second projection +can add an extra tick after yellow turns red before another head enters green. This +check does **not** independently enforce `signal_all_red_seconds` during an arbitrary +priority switch; that configured interval belongs to the ordinary cycle. Even zero +yellow duration still takes a subsequent update to leave a newly entered yellow. +Pedestrians are suppressed to red while any shown vehicle on their arm remains green +or yellow; they have no yellow transition of their own. + +Ordinary Standard/fallback motion samples the unsmoothed programme at fractional arrival, +not the tick-projected head. Enabled priority departure additionally checks the previous +**shown** phases. This distinction explains a map indication lag without changing the +ordinary crossing schedule. At high zoom the map renders vehicle indicators; pedestrian +payload detail remains available in diagnostics. + +## 9. Frontend mock, stream handling and presentation math + +### Synthetic mock differences + +Sources: [mock-route-metrics.ts](../../frontend/src/lib/mock-route-metrics.ts), +[mock config](../../frontend/src/lib/mock-simulation-config.ts), +[mock-session.ts](../../frontend/src/lib/mock-session.ts), +[mock controller](../../frontend/src/lib/mock-its-controller.ts). + +The mock is not an ETL dataset fallback and does not perform road-graph routing or snapping. +It draws a straight origin/destination route. With radian differences and radius +$R_E=6,371,000$ m: + +$$h=\sin^2(\Delta\varphi/2)+\cos\varphi_1\cos\varphi_2\sin^2(\Delta\lambda/2),\quad +L=2R_E\arcsin\sqrt h.$$ + +Scale $q=L/5400$ gives $\widehat T_n=q\,780\,\mu/1.5$ and +$\widehat T_g=q\,380$. Synthetic intersections `INT-9001/9002` occur at fractions +$1480/5400$ and $1632/5400$ of the route, with forward cascade at ≤250 m. Snapped endpoints +are the request coordinates with zero snap distance. These are not Kraków road predictions. + +Mock per-junction slowdown is $D=\min(3,\widehat T_g/(2N))$, preserving positive open-road +time for short synthetic routes; constant ambulance speed is $L/(\widehat T_g-ND)$. +Ordinary limit is at most 50 km/h. Standard red loss uses fixed **35 s** as the wait, +capped at 15 s after multiplying density; backend uses actual seconds until ordinary +green. Mock phases fix route S1 to slot 0 and conflicting S2 to slot 1, rather than deriving +movement groups from a dataset. Mock TTI uses remaining synthetic timeline time, rather +than backend EMA distance/speed. It uses the same hash/outcome order and default response +delays 1/5/8 s. Hold is $\max(40,\lceil\max\mathrm{TTI}\rceil+5)$, rather than the backend's +last-line release calculation. These frontend constants do not read backend environment +settings. JavaScript `Math.round` also differs from Python ties-to-even on half values. + +The mock precomputes a disabled timeline for its Standard estimate/savings. It holds enabled +motion against previously shown route green, then applies controller feedback. Fallback +rebuilds only the undriven timeline from a cursor, retaining already-driven history; +ordinary-colour evaluation accounts for time lost in holds. Held time counts toward trip +time, recovery does not. Completion waits for route progress one and all signals normal. +These are contract-level parallels, not bit-for-bit parity with backend city simulation. + +### Transport and client state + +[SSE framing](../../backend/src/greenwave/api/sse.py) starts with `retry: 2000`, then +`event: `, `id: `, `data: `, blank line. Dispatch, feedback and tick +can share a tick ID. The stream is a snapshot plus live events, **not** replay from +`Last-Event-ID`. Retained terminal sessions yield latest nonterminal and terminal then close. +A bounded subscriber queue (default 32) drops its oldest event on overflow; feedback and +dispatch can be dropped too. Terminal delivery displaces a nonterminal and closes the stream. +Tick request snapshots allow pending/status reconstruction after missing individual events. +Retained-session limit (default four) counts sessions, not operations; active pair members +are preserved even if the configured limit is lower than the active operation size. + +[Client reducer](../../frontend/src/lib/simulation-state.ts) phases are +`SETUP → STARTING → RUNNING → FINISHED/CANCELLED/ERROR`; reset returns to setup. Actions +are scoped to the current simulation ID; stale ticks/feedback are filtered using tick and +feedback sequence. Stop remains running until confirmed, with a separate stop error on +failure. Connection states are separate from simulation/ITS status. There is no automatic +controller-failure retry or automatic transport replacement. + +[Backend adapter](../../frontend/src/lib/transport/backend-simulation-adapter.ts) validates +incoming JSON independently of generated TS types. Browser EventSource retries transient +connections; its permanently closed state is treated as `SIMULATION_NOT_FOUND`. Since +EventSource exposes no HTTP status, CORS/proxy errors can be misclassified this way. A +start timeout triggers best-effort stop, but a stop arriving before server registration +can return 404 and leave the late-started operation running until replacement/stop. + +## 10. Architectural and mathematical findings + +The following are source-derived limitations or documentation discrepancies, not runtime +changes made by this audit. Severity describes impact on this simulation, not real-world +signal safety. No calibrated performance or deployment-safety claim follows from the model. + +| Priority | Finding and implementation evidence | Consequence / follow-up | +| --- | --- | --- | +| High | Nominal GreenWave estimate excludes controller holds and fallback; normal estimate is an ordinary car formula ([estimates](../../backend/src/greenwave/routing/estimates.py), [engine](../../backend/src/greenwave/simulation/engine.py)). | Do not present nominal difference as measured priority savings. Use actual Standard baseline/KPIs or completed pair. Calibrate separately. | +| High | Two-slot modulo grouping is not a lane conflict graph; Standard motion deliberately rolls red/yellow with capped delay ([phases](../../backend/src/greenwave/simulation/phases.py), [motion](../../backend/src/greenwave/simulation/motion.py)). | This is an explanatory emergency-response model, unsuitable as an operational controller or ordinary driver model. | +| Medium | `speed_floor_meters_per_second` allows zero, but TTI divides by the current EMA without a zero guard ([corridor](../../backend/src/greenwave/simulation/corridor.py)). With `speed_ema_alpha=1` and a full held tick, EMA becomes exactly zero; the subsequent TTI calculation divides by zero. | Defaults avoid this; validate positivity or explicitly define zero-speed TTI before supporting such configuration. | +| Medium | `its_min_hold_seconds` permits below 40 and low buffer, but dispatch payload requires ≥40 ([settings](../../backend/src/greenwave/simulation_settings.py), [dispatch](../../backend/src/greenwave/simulation/dispatch.py), [schema](../../backend/src/greenwave/schemas/simulation.py)). | Some individually valid configurations fail at dispatch and cancel the loop with `SERVER_ERROR`; align settings and payload validation in a future behavior change. | +| Medium | Several float fields lack explicit finite checks; no cross-field constraint guarantees a positive effective ambulance speed or floor compatibility ([settings](../../backend/src/greenwave/simulation_settings.py)). | Extreme configuration can invalidate timing assumptions; current validators are the documented bounds, not a proof of model validity. | +| Medium | Enabled slowdown sizing uses current speed; merged windows, downstream edge changes or destination truncation can increase remaining extra-time density ([motion](../../backend/src/greenwave/simulation/motion.py)). | The 15 km/h floor is an intention under the sizing assumptions, not an unconditional invariant. Exact nominal-trip equality also fails with controller holds/fallback. | +| Medium | Unknown route movement cannot confirm priority-green, but absence of phases permits enabled stop-line departure ([engine](../../backend/src/greenwave/simulation/engine.py)). | `CLEARING` plus continued motion can be legitimate under missing data; distinguish it from confirmed green in analysis. | +| Medium | `expected_arrival_utc` uses TTI/playback, while tick pacing also uses configurable interval ([dispatch](../../backend/src/greenwave/simulation/dispatch.py), [session](../../backend/src/greenwave/simulation/session.py)). | UTC ETA is consistent with default interval 1 s only; nondefault pacing is not reflected. It is an extrapolation, not predicted arrival including upcoming delays. | +| Medium | Path search minimizes edge time, not junction/time-dependent trip cost; station shortlist defaults to five ([planner](../../backend/src/greenwave/routing/planner.py), [ranking](../../backend/src/greenwave/routing/station_ranking.py)). | Selected route/base need not minimize full simulated arrival; resource-aware ranking removes the base cut but retains edge-cost route choice. | +| Medium | Per-process exclusive in-memory sessions; lossy SSE queues and no durable replay ([session](../../backend/src/greenwave/simulation/session.py)). | Multiple server workers do not share operation ownership; reconnect gives current state, not a complete event history. | +| Medium | Mock uses synthetic timings/group identities and fixed red wait; settings not shared with server. | Use it for UI/contract demonstration, not backend numerical validation. | +| Low | Prior architecture prose and schema comments describe playback as a 1 Hz wall tick advancing $p$ seconds; some older text describes terminal ITS failure ([overview](../../GreenWave_ARCHITECTURE.md), [schema](../../backend/src/greenwave/schemas/simulation.py)). | Current session emits each simulated second at interval $I/p$; ITS failure is per-junction fallback. This audit and ADR 0015 document actual behavior. | +| Low | The overview says the shortest-drive neighbour table gates cascade; runtime route builder only checks forward along-route distance ([route_model](../../backend/src/greenwave/simulation/route_model.py)). | Candidate mismatches are warnings; they do not suppress cascade. | +| Low | Frontend engineering prose says six documentation tabs; current typed content/test renders five (running guidance is grouped into current content). | Inspect current UI/content rather than treating historical tab counts as contract. | + +Further model boundaries: no turn-restriction model, no dynamic traffic queue or interacting +emergency vehicles, no signal conflict arbitration across operations, no pedestrian barrier +routing, no weather or observed speed calibration, no live team availability. Density does +not slow ambulance open-road movement. Hash outcomes are deterministic scenario choices, +not empirical controller reliability estimates. Signal recovery duration and travel-time +rounding should not be interpreted as measured response-time precision. + +## 11. Offline configuration inventory + +This inventory records every top-level configuration constant in +[etl/config.py](../../backend/src/greenwave/etl/config.py), including analysis/report knobs. +Containers are sorted for reference; their semantic sets/maps are unchanged. The +`SignalHandling` enum is `count_in_delay`, `exclude_and_reject`, `manual_review`. + +| Constant | Value | +| --- | --- | +| `SOURCE_CRS` | 'EPSG:4326' | +| `METRIC_CRS` | 'EPSG:2178' | +| `DRIVABLE_HIGHWAY_VALUES` | ['living_street', 'motorway', 'motorway_link', 'primary', 'primary_link', 'residential', 'road', 'secondary', 'secondary_link', 'service', 'tertiary', 'tertiary_link', 'trunk', 'trunk_link', 'unclassified'] | +| `EXCLUDED_ACCESS_VALUES` | ['no', 'private'] | +| `ACCESS_TRACK_TRACKTYPES` | ['grade1', 'grade2', 'grade3'] | +| `EMERGENCY_ACCESS_VALUES` | ['designated', 'official', 'yes'] | +| `EMERGENCY_EXTRA_HIGHWAY_VALUES` | ['pedestrian', 'track'] | +| `CLUSTER_PROBE_RADII_METERS` | (15.0, 30.0, 50.0) | +| `COVERAGE_TAGS` | ('maxspeed', 'oneway', 'lanes', 'name', 'junction', 'bus:lanes', 'busway', 'lanes:bus') | +| `EXACT_ONLY_TAGS` | ['junction', 'name', 'oneway'] | +| `NON_BLOCKING_SIGNAL_TAGS` | ['blinker', 'tram_priority'] | +| `SAMPLE_LIMIT` | 20 | +| `CLUSTER_MAP_RADII_METERS` | (20.0, 30.0, 40.0, 50.0) | +| `EXCLUDED_SERVICE_SUBTYPES` | ['drive-through', 'driveway', 'parking_aisle'] | +| `ABSENT_TAG` | '' | +| `SIGNAL_CLUSTER_RADIUS_METERS` | 40.0 | +| `SIGNAL_DELAY_SECONDS` | 35.0 | +| `MIDBLOCK_SIGNAL_DELAY_SECONDS` | 35.0 | +| `PEDESTRIAN_CROSSING_DELAY_SECONDS` | 35.0 | +| `SIGNAL_TAG_HANDLING` | {ABSENT_TAG: SignalHandling.COUNT_IN_DELAY, 'signal': SignalHandling.COUNT_IN_DELAY, 'traffic_lights': SignalHandling.COUNT_IN_DELAY, 'blinker': SignalHandling.EXCLUDE_AND_REJECT, 'tram_priority': SignalHandling.EXCLUDE_AND_REJECT, 'controller': SignalHandling.MANUAL_REVIEW} | +| `COUNTED_CROSSING_KINDS` | ['highway=crossing'] | +| `STANDALONE_CROSSING_DISTANCE_METERS` | 30.0 | +| `IMPLIED_ONEWAY_HIGHWAY_VALUES` | ['motorway', 'motorway_link'] | +| `IMPLIED_ONEWAY_JUNCTION_VALUES` | ['circular', 'roundabout'] | +| `CLASS_DEFAULT_SPEED_KMH` | {'motorway': 140, 'motorway_link': 50, 'trunk': 70, 'trunk_link': 50, 'primary': 50, 'primary_link': 50, 'secondary': 50, 'secondary_link': 50, 'tertiary': 50, 'tertiary_link': 50, 'unclassified': 50, 'residential': 30, 'living_street': 20, 'road': 50, 'service': 30, 'track': 15, 'pedestrian': 10} | +| `ROUNDABOUT_SIGNAL_ASSOCIATION_METERS` | 40.0 | +| `STREET_LENGTH_RATIO_RANGE` | (0.8, 1.25) | +| `ROUTE_DETOUR_RATIO_RANGE` | (1.0, 1.6) | +| `ROUTE_SNAP_TOLERANCE_METERS` | 150.0 | +| `SIGNAL_SNAP_TOLERANCE_METERS` | 30.0 | +| `NEAR_MISS_TOLERANCE_METERS` | 1.5 | +| `JUNCTION_MIN_DISTINCT_NEIGHBOURS` | 3 | +| `ASSIGNMENT_LIMIT_METERS` | 50.0 | +| `MERGE_DISTANCE_METERS` | 30.0 | +| `MERGE_MAX_GROUP_DIAMETER_METERS` | 65.0 | +| `CROSSING_MERGE_DISTANCE_METERS` | 15.0 | +| `WELD_TOLERANCE_METERS` | 1.0 | +| `INTERSECTION_ID_PREFIX` | 'INT-' | +| `CASCADE_THRESHOLD_METERS` | 250.0 | +| `CASCADE_ALLOW_U_TURNS` | False | +| `PAVED_SURFACE_VALUES` | ['asphalt', 'cobblestone', 'concrete', 'concrete:lanes', 'concrete:plates', 'metal', 'paved', 'paving_stones', 'sett', 'unhewn_cobblestone', 'wood'] | +| `UNPAVED_SURFACE_VALUES` | ['compacted', 'dirt', 'earth', 'fine_gravel', 'grass', 'grass_paver', 'gravel', 'ground', 'mud', 'pebblestone', 'sand', 'unpaved'] | +| `TRAM_TRACK_MATCH_METERS` | 6.0 | +| `TRAM_TRACK_MIN_OVERLAP_SHARE` | 0.5 | +| `STATION_DEDUP_RADIUS_M` | 150.0 | +| `POLICE_EXCLUDED_NAME_FRAGMENTS` | ('straz miejska', 'strazy miejskiej', 'straz ochrony kolei', 'strazy ochrony kolei', 'inspektorat transportu drogowego', 'komisariat wodny') | +| `AMBULANCE_EXCLUDED_NAMES` | ('reumatologii', 'rehabilitacji') | +| `AMBULANCE_INCLUDED_NAMES` | ('Szpital Uniwersytecki',) | +| `MERGE_SAME_NAME_AT_ANY_DISTANCE` | ('POLICE_CAR',) | +| `ADDRESS_DEDUP_RADIUS_M` | 400.0 | +| `ADDRESS_MATCH_CLEAN_M` | 100.0 | +| `ADDRESS_MATCH_MAX_M` | 500.0 | +| `ADDRESS_NAME_VARIANT_RADIUS_M` | 50.0 | +| `ADDRESS_NAME_VARIANT_TIGHT_M` | 20.0 | +| `KRAKOW_CENTRE_LAT_LNG` | (50.0617, 19.9373) | +| `PLACES_MAX_SNAP_DISTANCE_M` | 150.0 | +| `PRM_BASE_OSM_MATCH_RADIUS_M` | 200.0 | +| `AREA_LOOKUP_RADIUS_M` | 250.0 | + +Road attribute parsing additionally derives directional lanes from directional tags first, +then totals (two-way totals halved, floored and bounded below by one); surface and bus-lane membership are tag +classifications, not learned coefficients. See +[road_attributes.py](../../backend/src/greenwave/etl/road_attributes.py). Tram/calming spatial +attachment is in [edge_enrichment.py](../../backend/src/greenwave/etl/edge_enrichment.py). + +## 12. Verification map and audit method + +The audit traced startup → dataset/indexes → routing/dispatch → assembly → one-second +motion → controller/ledger → telemetry → session/SSE → frontend adapters, then checked +the independent mock. Work plan: inspect sources and tests, write formula/state/config +reference, remove the docs header link test-first, run both quality suites, review the +diff and open a documentation PR. No backend algorithm, schema or generated artifact +was changed. The separate UI change removes only the docs header Live demo link. + +| Behavior | Existing verification source | +| --- | --- | +| Edge factors, boosts, route estimates | [routing tests](../../backend/tests/routing/) (`test_edge_times.py`, `test_estimates.py`, `test_planner.py`) | +| Snapping, access, station/team selection | Same directory (`test_network_index.py`, `test_access.py`, `test_station_ranking.py`, `test_team_ranking.py`, `test_team_eligibility.py`) | +| Rolling motion and exact Standard estimate | [simulation tests](../../backend/tests/simulation/) (`test_motion_modes.py`, `test_standard_estimate.py`, `test_standard_baseline.py`) | +| Phase boundaries, holds, reported states | Same directory (`test_phases.py`, `test_signal_sync.py`, `test_its_feedback.py`) | +| Failure stays per junction | Same directory (`test_priority_fallback.py`) | +| Cascade, hold coverage, KPI rounding | Same directory (`test_route_model.py`, `test_dispatch.py`, `test_telemetry.py`) | +| Cancellation, shared pair clock, queues, reconnect snapshots | Same directory (`test_session.py`, `test_subscriber_queue.py`); [API tests](../../backend/tests/api/) | +| Seed/presets and malformed schemas | [ITS tests](../../backend/tests/its/), [schema tests](../../backend/tests/schemas/) | +| Mock math, reducer, wire validation and comparison | [frontend lib tests](../../frontend/src/lib/) and [transport tests](../../frontend/src/lib/transport/) | +| Docs header removal with badge/GitHub retained | [docs-workspace.test.tsx](../../frontend/src/components/docs/docs-workspace.test.tsx) | + +These tests substantiate implementation behavior; they do not validate the physical +accuracy of the modeling assumptions or eliminate the configuration limitations above. + +Audit verification (2026-10-30): backend `uv run ruff check .`, `ruff format --check .`, +`mypy`, and `pytest` passed (1,553 tests). Frontend `npm run lint`, `typecheck`, +`format:check`, `test`, and `build` passed (1,283 tests across 127 files). The two updated +header assertions failed before removal, then the focused seven-test file passed. +A Playwright CLI check against the production build confirmed the header has only GitHub, +the simulation badge remains visible, and five tabs render. Browser artifacts are local +under `.tmp/playwright/audit/`; they are not documentation or production assets. Vitest +reported its existing Vite native-config compatibility warning; no test failed. +$$ diff --git a/frontend/src/components/docs/DocsWorkspace.tsx b/frontend/src/components/docs/DocsWorkspace.tsx index f70287c..87f8d64 100644 --- a/frontend/src/components/docs/DocsWorkspace.tsx +++ b/frontend/src/components/docs/DocsWorkspace.tsx @@ -6,7 +6,7 @@ import { ThemeToggle } from "@/components/hud/ThemeToggle"; import { ResponsiveNavigation } from "@/components/workspace/ResponsiveNavigation"; import { WorkspaceHeader } from "@/components/workspace/WorkspaceHeader"; import { useIsPhone } from "@/lib/useIsPhone"; -import { DEMO_URL, docsContent } from "@/lib/docs/content"; +import { docsContent } from "@/lib/docs/content"; import { DocsBackdrop } from "./DocsBackdrop"; import { DocsSectionView } from "./DocsSectionView"; import { DocsTabs } from "./DocsTabs"; @@ -46,9 +46,6 @@ export function DocsWorkspace() { - - {t("Live demo")} - { ); }); - it("shows a simulation-mode badge distinct from the demo link", () => { + it("shows a simulation-mode badge without a redundant live-demo header link", () => { const html = english(); expect(html).toMatch(/data-testid="simulation-mode-badge"[\s\S]*?Simulation mode<\/span>/); expect(html).toContain("bg-amber-500"); expect(html).toContain("bg-zinc-900/80"); expect(html).toContain("border-neutral-700/60"); - expect(html).toMatch(/class="docs-chip"[^>]*href="https:\/\/green-wave\.duckdns\.org\/"/); + expect(html).not.toMatch(/class="docs-chip"[^>]*href="https:\/\/green-wave\.duckdns\.org\/"/); }); it("uses an SVG external-link icon and a documentation navigation rail", () => { const html = english(); expect(html).not.toContain("↗"); expect(html).toContain('class="docs-navigation"'); - expect(html).toMatch(/Live demo[\s\S]*?]*>[\s\S]*?GitHub[\s\S]*? Date: Fri, 30 Oct 2026 08:57:43 +0100 Subject: [PATCH 2/4] docs: publish system logic audit in application documentation Add the bilingual System logic tab at /docs#logic with mathematical notation, state diagrams, parameter references and implementation findings. Preserve the repository audit, correct overview claims and verify all frontend checks plus desktop and phone browser navigation. --- README.md | 3 +- docs/architecture/system-logic.md | 16 +- docs/engineering/frontend-dashboard.md | 14 +- frontend/src/app/globals.css | 26 + frontend/src/components/docs/DocsBlocks.tsx | 14 + .../src/components/docs/docs-blocks.test.tsx | 33 + .../components/docs/docs-workspace.test.tsx | 5 +- frontend/src/lib/docs/content.test.ts | 5 +- frontend/src/lib/docs/content.ts | 12 +- frontend/src/lib/docs/logic-content.ts | 696 ++++++++++++++++++ frontend/src/lib/docs/logic-settings.ts | 124 ++++ frontend/src/lib/docs/tabs.test.ts | 4 + frontend/src/lib/docs/tabs.ts | 9 +- 13 files changed, 945 insertions(+), 16 deletions(-) create mode 100644 frontend/src/lib/docs/logic-content.ts create mode 100644 frontend/src/lib/docs/logic-settings.ts diff --git a/README.md b/README.md index 9d0633e..2e7b314 100644 --- a/README.md +++ b/README.md @@ -130,7 +130,8 @@ Public HTTPS hosting on a free Oracle VM: [deployment guide](deploy/README.md). its workspace controls. - [CONTRIBUTING.md](CONTRIBUTING.md): checks, branches, commits and contract changes. - The in-app **Documentation** page (`/docs`): the Open Data App contest write-up in Polish and - English (project, running it, technologies, data, architecture, future development). + English (project, technologies, data, architecture, system logic, future development). + The **System logic** tab at `/docs#logic` contains the formulas, parameter reference and state machines. ## Data sources and attribution diff --git a/docs/architecture/system-logic.md b/docs/architecture/system-logic.md index f2dc6e3..cb1b526 100644 --- a/docs/architecture/system-logic.md +++ b/docs/architecture/system-logic.md @@ -619,7 +619,7 @@ stateDiagram-v2 NORMAL --> CLEARING: accepted request; waiting for eligibility or shown green NORMAL --> PRIORITY_GREEN: accepted; TTI at most 25; route indications already green CLEARING --> PRIORITY_GREEN: TTI at most 25 and all route vehicle indications green - PRIORITY_GREEN --> CLEARING: no complete shown-green route confirmation + PRIORITY_GREEN --> CLEARING: TTI above priority threshold or no shown-green confirmation CLEARING --> NORMAL: request no longer accepted and target unpassed PRIORITY_GREEN --> NORMAL: request no longer accepted and target unpassed CLEARING --> RECOVERY: passed after active priority state @@ -801,7 +801,7 @@ signal safety. No calibrated performance or deployment-safety claim follows from | Medium | Mock uses synthetic timings/group identities and fixed red wait; settings not shared with server. | Use it for UI/contract demonstration, not backend numerical validation. | | Low | Prior architecture prose and schema comments describe playback as a 1 Hz wall tick advancing $p$ seconds; some older text describes terminal ITS failure ([overview](../../GreenWave_ARCHITECTURE.md), [schema](../../backend/src/greenwave/schemas/simulation.py)). | Current session emits each simulated second at interval $I/p$; ITS failure is per-junction fallback. This audit and ADR 0015 document actual behavior. | | Low | The overview says the shortest-drive neighbour table gates cascade; runtime route builder only checks forward along-route distance ([route_model](../../backend/src/greenwave/simulation/route_model.py)). | Candidate mismatches are warnings; they do not suppress cascade. | -| Low | Frontend engineering prose says six documentation tabs; current typed content/test renders five (running guidance is grouped into current content). | Inspect current UI/content rather than treating historical tab counts as contract. | +| Low | At the audit baseline, frontend engineering prose said six documentation tabs while typed content rendered five. This follow-up adds System logic as the sixth tab and aligns the engineering reference. | The tab-count discrepancy is resolved by the in-app audit follow-up. | Further model boundaries: no turn-restriction model, no dynamic traffic queue or interacting emergency vehicles, no signal conflict arbitration across operations, no pedestrian barrier @@ -891,7 +891,8 @@ motion → controller/ledger → telemetry → session/SSE → frontend adapters the independent mock. Work plan: inspect sources and tests, write formula/state/config reference, remove the docs header link test-first, run both quality suites, review the diff and open a documentation PR. No backend algorithm, schema or generated artifact -was changed. The separate UI change removes only the docs header Live demo link. +was changed. The UI exposes the audit in a bilingual System logic tab at `/docs#logic`, with readable +formula blocks, text state diagrams and parameter tables, and removes the docs header Live demo link. | Behavior | Existing verification source | | --- | --- | @@ -918,3 +919,12 @@ the simulation badge remains visible, and five tabs render. Browser artifacts ar under `.tmp/playwright/audit/`; they are not documentation or production assets. Vitest reported its existing Vite native-config compatibility warning; no test failed. $$ + +Follow-up: the audit is also available directly on the in-app Documentation page at +`/docs#logic` (System logic / Logika systemu). Both languages share the parameter values +and equations, with translated explanations, diagram annotations and table headings. + +In-app follow-up verification (2026-10-30): frontend lint, typecheck, formatting, +all 1,286 tests and the production build passed. Playwright CLI checked `/docs#logic` +in PL and EN at 1440, 390 and 320 px: sixteen formula blocks, no document overflow, +keyboard tab navigation and browser-back selection all passed. diff --git a/docs/engineering/frontend-dashboard.md b/docs/engineering/frontend-dashboard.md index 0b22751..9368d11 100644 --- a/docs/engineering/frontend-dashboard.md +++ b/docs/engineering/frontend-dashboard.md @@ -61,10 +61,10 @@ camera actions stop an old gesture before applying the new view so rapid toggles ## Documentation page -`/docs` holds the contest documentation (Open Data App rules §5.2) as six tabs: About, Running it, -Technologies, Data, Architecture, Future development. The copy lives in -`src/lib/docs/content.ts` as typed blocks per language and does not go through the `polish.ts` -dictionary. PL and EN must stay structurally identical, every command must appear in `README.md`, +`/docs` holds the contest documentation (Open Data App rules §5.2) as six tabs: About, Technologies, +Data, Architecture, System logic, Future development. The copy lives in +`src/lib/docs/content.ts` and `logic-content.ts` as typed blocks per language and does not +go through the `polish.ts` dictionary. PL and EN must stay structurally identical, every command must appear in `README.md`, and English sentences must not copy the repository docs (`content.test.ts`, `content-facts.test.ts`). The active tab is the URL hash (`/docs#data`), with unknown hashes opening About, and the tabs follow the WAI-ARIA tabs keyboard model. @@ -75,3 +75,9 @@ full-width tables and diagrams; a section marked `numbered` numbers its headings table marked `cards` renders one card per row. Behind it sits the home corridor in road ink (no signal colours). The tab track sticks under the header and turns glass only while stuck; one thumb slides to the clicked tab and the panel fades in, while keyboard switches stay instant. + +The System logic tab (`/docs#logic`) publishes the implementation audit in both languages. +Its formula and state blocks render readable notation in keyboard-scrollable figures; they +are not shell commands and have no command-copy UI. `logic-settings.ts` stores the audited +parameter reference values, not runtime configuration. Keep it aligned with the audited +backend settings and ETL constants when updating that reference. diff --git a/frontend/src/app/globals.css b/frontend/src/app/globals.css index 6a27903..3e15bef 100644 --- a/frontend/src/app/globals.css +++ b/frontend/src/app/globals.css @@ -3156,6 +3156,32 @@ a.docs-chip:focus-visible, font-weight: 500; color: var(--muted-foreground); } +.docs-notation { + min-width: 0; + max-width: 100%; + border: 1px solid var(--border); + border-radius: var(--radius-card); + background: var(--card); + overflow: hidden; +} +.docs-notation figcaption { + padding: 0.625rem 0.875rem; + font-size: 0.8125rem; + font-weight: 600; + background: var(--muted); +} +.docs-notation pre { + max-width: 100%; + overflow-x: auto; + padding: 0.875rem; + font-family: var(--font-mono); + font-size: 0.875rem; + line-height: 1.75; +} +.docs-notation pre:focus-visible { + outline: 2px solid var(--ring); + outline-offset: -2px; +} .docs-group .docs-code { background: var(--tile); } diff --git a/frontend/src/components/docs/DocsBlocks.tsx b/frontend/src/components/docs/DocsBlocks.tsx index c2afcf1..1f67ede 100644 --- a/frontend/src/components/docs/DocsBlocks.tsx +++ b/frontend/src/components/docs/DocsBlocks.tsx @@ -73,6 +73,20 @@ export function Block({ block }: { block: DocsBlock }) { ); + case "formula": + case "state": + return ( +
+
{block.label}
+
+            {block.expression}
+          
+ + ); case "code": return ; case "links": diff --git a/frontend/src/components/docs/docs-blocks.test.tsx b/frontend/src/components/docs/docs-blocks.test.tsx index a926528..c68a43c 100644 --- a/frontend/src/components/docs/docs-blocks.test.tsx +++ b/frontend/src/components/docs/docs-blocks.test.tsx @@ -143,3 +143,36 @@ it("offers labelled source details for narrow screens", () => { expect(html).toContain('class="docs-table-mobile"'); expect(html).toContain("
Publisher
Community
"); }); + +it("renders readable mathematical notation with its label, without a command-copy control", () => { + const html = renderToStaticMarkup( + , + ); + expect(html).toContain("
Time to intersection
"); + expect(html).toContain('role="math"'); + expect(html).toContain("TTIᵢ = max(0, sᵢ − x) / v̄"); + expect(html).not.toContain(" { + for (const language of ["pl", "en"] as const) { + const logic = docsContent[language].find((section) => section.id === "logic"); + expect(logic).toBeDefined(); + const html = renderToStaticMarkup(); + for (const implementedTerm of [ + "STANDARD_FALLBACK", + "PRIORITY_GREEN", + "its_ack_timeout_seconds", + "min_intersection_delay_seconds", + "estimated_standard_time_sec", + "MIXED", + ]) + expect(html).toContain(implementedTerm); + expect(html.match(/role="math"/g)?.length).toBeGreaterThan(5); + expect(html).toContain("<= 25"); + } +}); diff --git a/frontend/src/components/docs/docs-workspace.test.tsx b/frontend/src/components/docs/docs-workspace.test.tsx index 9d0b00a..c2e35ac 100644 --- a/frontend/src/components/docs/docs-workspace.test.tsx +++ b/frontend/src/components/docs/docs-workspace.test.tsx @@ -14,10 +14,11 @@ const english = () => ); describe("DocsWorkspace", () => { - it("names a tablist with five tabs", () => { + it("names a tablist including the system logic reference", () => { const html = english(); expect(html).toMatch(/role="tablist"[^>]*aria-label="Documentation sections"/); - expect(html.match(/role="tab"/g)).toHaveLength(5); + expect(html.match(/role="tab"/g)).toHaveLength(6); + expect(html).toMatch(/id="docs-tab-logic"[^>]*>System logic<\/button>/); }); it("selects About first with roving focus", () => { diff --git a/frontend/src/lib/docs/content.test.ts b/frontend/src/lib/docs/content.test.ts index ff1d898..563f437 100644 --- a/frontend/src/lib/docs/content.test.ts +++ b/frontend/src/lib/docs/content.test.ts @@ -16,6 +16,9 @@ function strings(block: DocsBlock): string[] { return block.items; case "table": return [...block.columns, ...block.rows.flat()]; + case "formula": + case "state": + return [block.label, block.expression]; case "code": return [block.label, block.code]; case "links": @@ -26,7 +29,7 @@ function strings(block: DocsBlock): string[] { } describe("docs content", () => { - it("lists the five sections in order in both languages", () => { + it("lists the documentation sections in order in both languages", () => { for (const language of languages) expect(docsContent[language].map((section) => section.id)).toEqual([...DOCS_SECTION_IDS]); }); diff --git a/frontend/src/lib/docs/content.ts b/frontend/src/lib/docs/content.ts index a85c800..025a960 100644 --- a/frontend/src/lib/docs/content.ts +++ b/frontend/src/lib/docs/content.ts @@ -1,3 +1,4 @@ +import { logicSections } from "./logic-content"; import type { Language } from "@/lib/localization"; import type { DocsSectionId } from "./tabs"; @@ -11,6 +12,7 @@ export type DocsBlock = /** `cards`: one card per row, first column as its label (rows that read as items, not data). */ | { kind: "table"; columns: string[]; rows: string[][]; cards?: true } | { kind: "code"; label: string; code: string } + | { kind: "formula" | "state"; label: string; expression: string } | { kind: "links"; items: { label: string; href: string }[] } | { kind: "diagram"; @@ -265,7 +267,7 @@ export const docsContent: Record = { { kind: "heading", text: "Ruch standardowy" }, { kind: "paragraph", - text: "W wariancie bez priorytetu pojazd porusza się po tej samej trasie, a sygnalizacja działa według zwykłego programu. Przy czerwonym świetle model zakłada ostrożny przejazd i dolicza opóźnienie zależne od czasu do zmiany światła, nie większe niż 15 s na skrzyżowanie. Wynik porównania dotyczy tych założeń modelu.", + text: "W wariancie bez priorytetu pojazd porusza się po tej samej trasie, a sygnalizacja działa według zwykłego programu. Przy czerwonym świetle model zakłada ostrożny przejazd i dolicza opóźnienie zależne od czasu do zmiany światła, nie większe niż 15 s na decyzję przy linii zatrzymania. Wynik porównania dotyczy tych założeń modelu.", }, { kind: "note", @@ -273,6 +275,7 @@ export const docsContent: Record = { }, ], }, + logicSections.pl, { id: "roadmap", label: "Rozwój", @@ -516,12 +519,12 @@ export const docsContent: Record = { { kind: "heading", text: "Choosing the unit and the route" }, { kind: "paragraph", - text: "Once the incident is placed, the server estimates the driving time from every suitable base and picks the fastest. The emergency vehicle's speed follows the limit on each road. A bus lane or tram track lets it go faster, and each speed bump costs a few seconds.", + text: "Once the incident is placed, the server ranks suitable bases by estimated travel time; resource-aware ambulance selection can prefer a team within the incident’s operating area. The emergency vehicle's speed follows the limit on each road. A bus lane or tram track lets it go faster, and each speed bump costs a few seconds.", }, { kind: "heading", text: "The green corridor" }, { kind: "paragraph", - text: "Every simulated second, the engine computes the time to intersection (TTI) for each signal ahead: remaining distance divided by smoothed speed. As the vehicle approaches, it sends a priority request to the simulated ITS controller. Signals within 250 m of each other along the route are handled together, so a queue at the next junction cannot block the run.", + text: "Every simulated second, the engine computes the time to intersection (TTI) for each signal ahead: remaining distance divided by smoothed speed. As the vehicle approaches, it sends a priority request to the simulated ITS controller. Signals within 250 m of each other along the route are handled together, as a one-hop cascade from independently eligible targets.", }, { kind: "paragraph", @@ -530,7 +533,7 @@ export const docsContent: Record = { { kind: "heading", text: "Standard traffic" }, { kind: "paragraph", - text: "Without priority, the vehicle takes the same route while the signals run their ordinary programme. At a red light it crosses with care and loses time that depends on how long it would have waited for green, at most 15 s per junction. The difference between the two runs is what the green corridor saves.", + text: "Without priority, the vehicle takes the same route while the signals run their ordinary programme. At a red light it crosses with care and loses time that depends on how long it would have waited for green, at most 15 s per stop-line decision. The difference between the two runs is what the green corridor saves.", }, { kind: "note", @@ -538,6 +541,7 @@ export const docsContent: Record = { }, ], }, + logicSections.en, { id: "roadmap", label: "Future development", diff --git a/frontend/src/lib/docs/logic-content.ts b/frontend/src/lib/docs/logic-content.ts new file mode 100644 index 0000000..60607a9 --- /dev/null +++ b/frontend/src/lib/docs/logic-content.ts @@ -0,0 +1,696 @@ +import type { Language } from "@/lib/localization"; +import type { DocsBlock, DocsSection } from "./content"; +import { etlSettingRows, simulationSettingRows } from "./logic-settings"; + +/** Human-facing audit. Equations and identifiers are shared; every explanation is localized. */ +function logicSection(language: Language): DocsSection { + const t = (pl: string, en: string) => (language === "pl" ? pl : en); + const p = (pl: string, en: string): DocsBlock => ({ kind: "paragraph", text: t(pl, en) }); + const h = (pl: string, en: string): DocsBlock => ({ kind: "heading", text: t(pl, en) }); + const f = (pl: string, en: string, expression: string): DocsBlock => ({ + kind: "formula", + label: t(pl, en), + expression, + }); + const state = ( + pl: string, + en: string, + expression: string, + polishExpression: string, + ): DocsBlock => ({ + kind: "state", + label: t(pl, en), + expression: language === "pl" ? polishExpression : expression, + }); + const table = (pl: string[], en: string[], rows: string[][]): DocsBlock => ({ + kind: "table", + columns: language === "pl" ? pl : en, + rows, + }); + + return { + id: "logic", + label: t("Logika systemu", "System logic"), + title: t("Logika, wzory i stany symulacji", "Simulation logic, equations and states"), + blocks: [ + p( + "Ten opis odtwarza działanie kodu sprawdzonego 30.10.2026, a nie docelowy projekt. Zawiera tryby, kolejność ustawień, wszystkie parametry symulacji, wzory czasu przejazdu i dokładne reguły sygnalizacji. Nazwy pól odpowiadają API i kodowi, a wyjaśnienia są dostępne po polsku i angielsku.", + "This reference describes the code audited on 30 October 2026 rather than a future design. It covers mode selection, configuration precedence, every simulation parameter, journey-time equations and the signal rules. Field names match the API and source; explanations are available in Polish and English.", + ), + { + kind: "note", + text: t( + "Wszystkie światła, odpowiedzi ITS i statusy dostępności są symulowane. To model do analizy, bez połączenia z rzeczywistymi sterownikami i bez potwierdzenia dokładności fizycznej. Parametry opóźnień i prędkości wymagają kalibracji.", + "Every light, ITS answer and availability status here is simulated. This analytical model has no connection to physical controllers and has not been validated for physical accuracy. Delay and speed assumptions need calibration.", + ), + }, + h("Architektura i odpowiedzialność", "Architecture and ownership"), + state( + "Przepływ danych i sterowania", + "Data and control flow", + "OSM / MSIP / PRM → ETL → graph + tables + hashes\n→ startup validation → routing / dispatch\n→ motion engine ↔ simulated ITS\n→ session → SSE → dashboard\n\nmock adapter → dashboard (synthetic, separate)", + "OSM / MSIP / PRM → ETL → graf + tabele + hashe\n→ walidacja startowa → trasa / wybór jednostki\n→ silnik ruchu ↔ symulowany ITS\n→ sesja → SSE → panel\n\nadapter mock → panel (osobny model syntetyczny)", + ), + p( + "ETL działa poza symulacją: buduje skierowany graf w EPSG:2178 (metry), wloty, skrzyżowania, adresy i zasoby. Serwer wczytuje je raz; brak pliku, niezgodny manifest, hash, liczność lub odwołanie przerywa start. Graf jest zamrażany. Raporty hashy wykrywają pomieszane wersje artefaktów, ale same nie są podpisane kryptograficznie.", + "Offline ETL builds a directed road graph in EPSG:2178 metres plus approaches, intersections, addresses and resources. Startup loads them once and rejects missing files or inconsistent manifest hashes, artifact hashes, counts and references. The graph is frozen. Hash reports detect mixed artifact versions; the reports themselves are not cryptographically authenticated.", + ), + p( + "Pydantic definiuje kontrakt; OpenAPI i typy TypeScript są generowane. Planowanie trasy i estymacje wykonują się poza pętlą zdarzeń. Silnik odpowiada za ruch i żądania, sterownik za odpowiedzi i program świateł, a SessionManager za jedną aktywną operację i strumienie. Brak WebSocketów, trwałego dziennika zdarzeń i wywołań rzeczywistego ITS.", + "Pydantic defines the contract and generates OpenAPI and TypeScript types. Route planning and estimates run off the event loop. The engine owns movement and requests, the controller owns answers and signal programmes, and SessionManager owns the exclusive operation and streams. There are no WebSockets, durable event log or live ITS calls.", + ), + h("Tryby i ich hierarchia", "Modes and their hierarchy"), + table( + ["Oś", "Wybór i zachowanie"], + ["Axis", "Selection and behavior"], + [ + [ + "mock / backend", + t( + "Transport wybierany przy budowaniu frontendu; domyślnie mock. Błąd backendu nie przełącza na mock.", + "Build-time transport, default mock. A backend error does not switch to mock.", + ), + ], + [ + "ENABLED", + t( + "Domyślny tryb przejazdu. Żądania priorytetu, spowolnienie na dojeździe i oczekiwanie na pokazane zielone.", + "Default run mode. Priority requests, approach slowdown and a hold for previously shown green.", + ), + ], + [ + "DISABLED", + t( + "Ta sama trasa i prędkości na otwartej drodze; zwykłe reguły przekraczania linii. Bez żądań i kaskady; scenariusz ITS wymuszony na NOMINAL.", + "Same route and open-road speeds; ordinary stop-line crossings. No requests or cascade; ITS preset forced to NOMINAL.", + ), + ], + [ + "STANDARD_FALLBACK", + t( + "Strategia tylko nieprzejechanych celów odrzuconego, przeterminowanego lub niepotwierdzonego żądania. Tryb całego przejazdu pozostaje ENABLED.", + "Only unpassed targets of rejected, expired or timed-out requests switch crossing strategy. The overall run remains ENABLED.", + ), + ], + [ + "enable_cascade_mode", + t( + "Działa tylko w ENABLED. Dodaje cele w jednym kroku od niezależnie kwalifikujących się skrzyżowań.", + "Effective only in ENABLED. Adds one-hop targets from independently eligible intersections.", + ), + ], + [ + "comparison", + t( + "Jedna operacja zawiera ENABLED i DISABLED na wspólnym zegarze. Każdy ma osobny silnik i sterownik.", + "One operation contains ENABLED and DISABLED on a shared clock, each with its own engine and controller.", + ), + ], + [ + "Home / Driver / Diagnostics", + t( + "Widoki współdzielą scenariusz i stan w pamięci. Sama nawigacja nie zmienia trybu aktywnego przejazdu.", + "Views share in-memory scenario and run state. Navigation alone does not change an active run’s mode.", + ), + ], + ], + ), + p( + "Kolejność decyzji: transport → ustawienia żądania → tryb przejazdu (DISABLED wyłącza priorytet) → wynik żądania ITS → fallback poszczególnych celów. Odmowa nie zmienia trasy i nie ponawia żądania. Pole crossing_strategy ma wartość PRIORITY lub STANDARD_FALLBACK w ENABLED oraz null w DISABLED.", + "Decision order is transport → request settings → run mode (DISABLED suppresses priority) → ITS request outcome → target-local fallback. Rejection neither replans the route nor retries the request. crossing_strategy is PRIORITY or STANDARD_FALLBACK in ENABLED, and null in DISABLED.", + ), + h("Ustawienia: źródła i nadpisywanie", "Configuration sources and overrides"), + p( + "SimulationSettings powstaje przy starcie serwera i jest niezmienne. Argument konstruktora ma pierwszeństwo przed zmienną środowiskową GREENWAVE_SIM_, a ta przed wartością domyślną. Klasy aplikacji nie konfigurują odczytu pliku .env, katalogu sekretów ani przeładowania w czasie działania. Launcher może przekazać zmienne do procesu. Żądanie API nie nadpisuje dowolnych parametrów silnika.", + "SimulationSettings is created at server startup and frozen. Constructor arguments take precedence over GREENWAVE_SIM_ environment variables, then field defaults. The app classes configure no dotenv reader, secrets directory or runtime reload. A launcher may supply process variables. API requests cannot override arbitrary engine parameters.", + ), + table( + ["Zmienna / opcja", "Domyślnie", "Reguła"], + ["Variable / option", "Default", "Rule"], + [ + [ + "GREENWAVE_PROCESSED_DIR", + "backend/data/processed", + t( + "Ścieżka względem pakietu; artefakty muszą przejść walidację.", + "Package-relative path; artifacts must pass startup validation.", + ), + ], + [ + "GREENWAVE_RAW_MANIFEST_PATH", + "backend/data/raw/MANIFEST.json", + t( + "Manifest musi zgadzać się z przetworzonym zbiorem.", + "Manifest must match the processed dataset.", + ), + ], + [ + "GREENWAVE_CORS_ORIGINS", + "http://localhost:3000", + t( + "Lista po przecinku, usunięte spacje/puste wpisy; brak walidatora URL. GET/POST, bez credentials.", + "Comma-separated, trimmed, empty entries removed; no URL validator. GET/POST, no credentials.", + ), + ], + [ + "NEXT_PUBLIC_SIMULATION_TRANSPORT", + "mock", + t( + "Tylko mock/backend; błędna wartość daje ostrzeżenie i mock.", + "Only mock/backend; invalid values warn and select mock.", + ), + ], + [ + "NEXT_PUBLIC_API_BASE_URL", + "http://127.0.0.1:8000", + t( + "Tylko HTTP(S); pozostaje origin i prefiks ścieżki, bez query/hash/końcowego /. Błąd przywraca domyślny adres.", + "HTTP(S) only; keep origin/path prefix, strip query/hash/trailing slash. Invalid input uses the default.", + ), + ], + [ + "stale / lost / start timeout / reconnects", + "3 s / 15 s / 10000 ms / 5", + t( + "Stałe klienta, bez zmiennych środowiskowych.", + "Client constants with no environment override.", + ), + ], + ], + ), + p( + "Jawne ścieżki create_app wygrywają ze środowiskiem. Wstrzyknięty dataset pomija odczyt dysku, ale nie można go łączyć z argumentami ścieżek. NEXT_PUBLIC_* jest utrwalane podczas budowania i buforowane raz na środowisko JS. Zmiana środowiska serwera nie zmienia gotowego frontendu. Walidacja żądań nie jest strict, a dodatkowe pola są domyślnie ignorowane.", + "Explicit create_app paths override dataset environment paths. Injecting a dataset bypasses disk loading but cannot be combined with path arguments. NEXT_PUBLIC_* values are compiled into the frontend and cached once per JS runtime. Changing server environment does not update an existing bundle. Request validation is not strict and extra fields are ignored by default.", + ), + h("Parametry żądania i wartości interfejsu", "Request parameters and UI defaults"), + table( + ["Pole", "Domyślnie / zakres"], + ["Field", "Default / range"], + [ + [ + "simulation_id", + t( + "Wymagane; 1–64 znaki A–Z, a–z, 0–9, _ lub -. Aktywny duplikat: HTTP 409.", + "Required; 1–64 characters A–Z, a–z, 0–9, _ or -. Active collision: HTTP 409.", + ), + ], + [ + "origin / destination", + t( + "Wymagane; lat [−90,90], lng [−180,180]. W UI: baza → zdarzenie.", + "Required; lat [−90,90], lng [−180,180]. UI sends base → incident.", + ), + ], + [ + "traffic_density_multiplier", + t( + "Start: wymagane [1,3]; ranking: domyślnie 1; UI: 1.5.", + "Start: required [1,3]; ranking default 1; UI default 1.5.", + ), + ], + [ + "enable_cascade_mode / playback_speed", + t( + "Kaskada wymagana, UI true. Prędkość odtwarzania: liczba całkowita [1,10], domyślnie 1.", + "Cascade required, UI true. Playback: integer [1,10], default 1.", + ), + ], + [ + "vehicle_type / green_wave_mode", + "AMBULANCE | FIRE_TRUCK | POLICE_CAR; ENABLED | DISABLED", + ], + ["its_scenario / its_outcome_seed", "NOMINAL; 0 ≤ seed ≤ 4294967295"], + [ + "time_mode / resource_aware", + t( + "Ranking: ENABLED / false; świadomy zasobów tylko dla AMBULANCE.", + "Ranking: ENABLED / false; resource-aware policy applies only to AMBULANCE.", + ), + ], + [ + "scenario_time / availability", + t( + "Domyślnie czas Warszawy do minuty i pusty słownik; do 200 kodów zespołów z free/busy. Czas ze strefą przeliczany na Europe/Warsaw.", + "Default Warsaw time to the minute and empty map; up to 200 team codes with free/busy. Zoned inputs convert to Europe/Warsaw.", + ), + ], + [ + "geocode q / limit", + t( + "q: 2–100 znaków; limit: [1,10], domyślnie 8.", + "q: 2–100 characters; limit: [1,10], default 8.", + ), + ], + ], + ), + p( + "Domyślny pojazd API to AMBULANCE, tryb ENABLED. Wszystkie typy korzystają z tego samego modelu prędkości; typ zmienia bazy i prezentację. UI obcina ziarno do liczby całkowitej i zakresu uint32; brak lub wartość niefinitywna daje 0. Porównanie wymaga dwóch różnych identyfikatorów, bez pola globalnego trybu.", + "The API defaults to AMBULANCE and ENABLED. All vehicle types share the same speed model; type changes candidate bases and presentation. The UI truncates/clamps seeds into uint32, with absent/non-finite values becoming zero. Comparison requires two distinct IDs and has no overall run-mode field.", + ), + h("Pełny katalog parametrów silnika", "Complete engine parameter reference"), + p( + "Dla każdej nazwy użyj prefiksu GREENWAVE_SIM_ i wielkich liter. Jednostki znajdują się w nazwach: sekundy, metry, km/h lub m/s; czynniki i liczności są bezwymiarowe. finite oznacza jawny zakaz NaN i nieskończoności. Nie należy dopisywać takiej gwarancji pozostałym polom.", + "Prefix each uppercase field name with GREENWAVE_SIM_. Names specify seconds, metres, km/h or m/s; factors and counts are dimensionless. finite means NaN/infinity are explicitly forbidden. Do not infer that guarantee for other fields.", + ), + table( + ["Parametr", "Domyślnie", "Ograniczenia"], + ["Parameter", "Default", "Bounds"], + simulationSettingRows, + ), + f( + "Walidacja powiązanych parametrów", + "Cross-field validation", + "ack_delay <= delayed_ack < ack_timeout\npriority_green_tti <= clearing_tti\nambulance_min_speed <= ambulance_max_speed", + ), + h("Wybór trasy, dojazd pieszy i zasoby", "Routing, on-foot access and resources"), + p( + "Punkty końcowe są dopasowywane do najbliższych węzłów największej silnie spójnej składowej grafu. Limit dopasowania wynosi 150 m. Trasa minimalizuje sumę czasów krawędzi pojazdu uprzywilejowanego, włącznie z progami, ale bez kar skrzyżowań, gęstości i odpowiedzi ITS. Spośród równoległych krawędzi wygrywa najkrótszy czas, potem identyfikator. Oba tryby wybierają tę samą trasę.", + "Endpoints snap to the nearest nodes in the graph’s largest strongly connected component, within 150 m. Routing minimizes emergency-vehicle edge time including calming, but excludes junction penalties, density and ITS outcomes. Parallel edges are chosen by minimum time, then ID. Both modes select the same route.", + ), + f( + "Dojście od węzła do zdarzenia", + "Walk from access node to incident", + "d_walk = 1.3 r\nT_walk = d_walk / 1.4\nd_walk <= 800 m\naccess = arg minₙ (T_drive,edge(n) + T_walk(n))", + ), + p( + "r jest odległością prostą w metrach. Początek poza siecią jest błędem; tylko cel poza limitem snap uruchamia dojście piesze. Wybór dojazdu wyklucza węzeł początku, remisy rozstrzyga klucz węzła. Brak węzła w zasięgu daje DESTINATION_OFF_NETWORK, a brak osiągalnego dojazdu NO_ROUTE. Marsz omija model barier i jest raportowany osobno; KPI kończy się na dojeździe pojazdu.", + "r is projected straight-line metres. An off-network origin is an error; only a destination beyond the snap limit triggers walking access. Driven access excludes the origin node and breaks ties by node key. No node within walking reach gives DESTINATION_OFF_NETWORK; no reachable access gives NO_ROUTE. Walking ignores barriers and is reported separately; vehicle KPIs stop at vehicle arrival.", + ), + p( + "Ranking baz używa odwróconej Dijkstry i domyślnie dokładniej ocenia pięć najlepszych baz, zwracając do trzech. Liczy czas wybranego trybu plus marsz. Baza na węźle zdarzenia może obsłużyć je na miejscu bez uruchamiania trasy; poza siecią marsz z bazy musi być szybszy niż przejazd, bo remis wygrywa jazda. Limit pięciu może pominąć bazę lepszą po uwzględnieniu sygnalizacji.", + "Base ranking uses reversed Dijkstra, fully estimates the best five by default and returns up to three. It orders by the selected mode’s drive time plus walking. A base at the incident node can answer on site without a simulated route; off network, walking from the base must beat driving because driving wins ties. The five-base cut may omit a base that wins after signal timing is included.", + ), + p( + "Ranking zasobów karetek ocenia wszystkie uprawnione bazy. Zespół musi być w sezonie i dniu tygodnia oraz w przedziale minut [od, do). OFF_SHIFT ma pierwszeństwo przed free; busy wyklucza zespół na dyżurze; brak nadpisania oznacza assumed_free. W bazie wybierany jest najpierw zespół z rejonu, potem według kodu. Typ zespołu nie jest współczynnikiem czasu.", + "Resource-aware ambulance ranking evaluates every eligible base. A team must match season, weekday and the [from, to) minute window. OFF_SHIFT overrides free; busy excludes an on-shift team; no override means assumed_free. Within a base, in-area teams come first, then team code. Team type is not a time coefficient.", + ), + f( + "Preferencja zespołu z rejonu", + "In-area team preference", + "T_area − T_fastest <= 60 s → choose in-area\notherwise → choose fastest", + ), + p( + "Rekomendacja jest pierwsza, reszta według czasu i identyfikatora bazy. Brak zespołów daje NO_ELIGIBLE_RESOURCE; istniejące zespoły bez osiągalnej bazy: NO_STATION_REACHABLE. Nieznany rejon oznacza wybór najbliższego czasowo. Rejon wynika z najbliższego adresu EMUiA w promieniu 250 m, a nie z testu zawierania punktu w wielokącie.", + "The recommendation is first; remaining candidates sort by time then base ID. No eligible teams gives NO_ELIGIBLE_RESOURCE; eligible teams without a reachable base give NO_STATION_REACHABLE. Unknown area means nearest-by-time selection. Area comes from the nearest EMUiA address within 250 m, rather than polygon containment.", + ), + h("Trzy różne czasy przejazdu", "Three different journey times"), + p( + "Lₑ: metry krawędzi; Vₑ: zwykła prędkość w km/h; nₑ: liczba elementów uspokojenia ruchu; μ: gęstość [1,3]; Dᵢ: zapisane opóźnienie skrzyżowania; N: liczba unikalnych skrzyżowań. Buspas i torowisko dają największą z premii, nigdy ich iloczyn.", + "Lₑ is edge metres, Vₑ ordinary km/h, nₑ calming-feature count, μ density in [1,3], Dᵢ stored junction delay and N unique junction count. Bus and tram advantages use the largest applicable boost, never their product.", + ), + f( + "Prędkość i czas krawędzi", + "Edge speed and time", + "bₑ = max(1, bus ? 1.05 : 1, tram ? 1.05 : 1)\nVₐ,ₑ = min(max(1.3 Vₑ bₑ, 30), 90) km/h\ntₐ,ₑ = Lₑ / (Vₐ,ₑ / 3.6) + 2 nₑ\ntₙ,ₑ = Lₑ μ ℓₑ sₑ / (Vₑ / 3.6) + 3 nₑ", + ), + p( + "ℓₑ = 1.15 tylko dla jednego pasa w danym kierunku; inaczej 1. sₑ = 1.3 tylko dla rozpoznanej nawierzchni nieutwardzonej; inaczej 1. Nieznane cechy są neutralne. Powyższe liczby to wartości domyślne z katalogu parametrów.", + "ℓₑ is 1.15 for exactly one lane per direction, otherwise 1. sₑ is 1.3 for a recognized unpaved surface, otherwise 1. Unknown attributes are neutral. Numbers in these equations are the defaults from the parameter reference.", + ), + f( + "Estymacje nominalne", + "Nominal estimates", + "T̂_normal = ∑ₑ tₙ,ₑ + ∑ᵢ Dᵢ\nT̂_greenwave = ∑ₑ tₐ,ₑ + N D_min\nD_min = 3 s; Dᵢ = 35 s by default", + ), + table( + ["Pole", "Znaczenie"], + ["Field", "Meaning"], + [ + [ + "estimated_normal_time_sec", + t( + "Wzór dla zwykłego samochodu; nie jest czasem karetki w DISABLED. Kara raz na unikalne skrzyżowanie.", + "Ordinary-car formula, not the DISABLED ambulance time. One delay per unique intersection.", + ), + ], + [ + "estimated_greenwave_time_sec", + t( + "Nominalny model bez nieprzewidzianego oczekiwania na potwierdzenie, odmów i fallbacku.", + "Nominal model without unconfirmed-green holds, rejection or fallback.", + ), + ], + [ + "estimated_standard_time_sec", + t( + "Próbny przebieg tego samego integratora ruchu w DISABLED od t = 0, z ułamkowym czasem przyjazdu.", + "Dry run of the same movement integrator in DISABLED from t = 0, including fractional arrival.", + ), + ], + ], + ), + h( + "Ruch, okna priorytetu i przekraczanie linii", + "Movement, priority windows and stop-line crossings", + ), + p( + "Na otwartej drodze prędkość efektywna to uₑ = Lₑ / tₐ,ₑ; koszt progów rozkłada się po krawędzi. Jedna iteracja ma budżet 1 s i dzieli go na końcach krawędzi, początku spowolnienia, liniach i celu. Ruch niesie pozostały czas na kolejną krawędź. Przyjazd zapisuje się z dokładnością do ułamka sekundy, a prędkość telemetryczna to faktyczne metry tej sekundy × 3.6.", + "Open-road effective speed is uₑ = Lₑ / tₐ,ₑ, spreading calming cost across the edge. One iteration has a one-second budget split at edge ends, slowdown starts, stop lines and destination. Remaining time carries onto the next edge. Arrival retains subsecond precision; telemetry speed is metres actually moved that second × 3.6.", + ), + f( + "Ruch przez kolejny odcinek", + "Advance to the next boundary", + "Δx = min(distance_to_boundary, u B)\nB′ = B − Δx / u\nt_arrival = t_old + 1 − B_remaining", + ), + f( + "Spowolnienie GreenWave", + "GreenWave rolling slowdown", + "aᵢ = max(previous_first_line, sᵢ − 60 m)\nW = sᵢ − x; u_f = 15 / 3.6 m/s\nC = max(W, D_min / (1/u_f − 1/u)) if u > u_f\nC = W otherwise\nR ← min(R + C, distance_to_destination)\nE ← E + D_min", + ), + p( + "Spowolnienie zaczyna się najwyżej 60 m przed pierwszą linią, ale nie przed pierwszą linią poprzedniego skrzyżowania. R i E to pozostały dystans i dodatkowy czas; nakładające się okna mogą się łączyć. Brak miejsca daje postój D_min. Kolejne wewnętrzne linie priorytetowego skrzyżowania nie tworzą następnego spowolnienia. Dojazd do pierwszej linii wymaga następnie pokazanego zielonego z poprzedniego raportu; samo ACCEPTED nie wystarcza.", + "Slowdown starts at most 60 m before the first line, but never before the previous junction’s first line. R and E are remaining distance and extra time; overlapping windows may merge. No room means a D_min dwell. Later internal priority lines do not add another slowdown. Departure from the first line then requires green shown in the previous report; ACCEPTED alone does not suffice.", + ), + f( + "Rozłożenie dodatkowego czasu bez zatrzymania", + "Spread extra time while rolling", + "u_c = 1 / (1/u + E/R)\nE′ = E (1 − Δx/R)\nR′ = R − Δx\nconstant u: crossing_time = R/u + E", + ), + p( + "W DISABLED oraz na skrzyżowaniach fallback decyzja zapada przy każdej linii, w dokładnym czasie jej osiągnięcia. Zielone wszystkich właścicieli pozwala jechać dalej. Czerwone, żółte lub nieznane rozpoczyna ostrożny przejazd. u jest wtedy minimum efektywnej prędkości i zwykłego limitu drogi. Dla kilku właścicieli stosowany jest najdłuższy czas do zielonego; brak wiedzy zastępuje go Dᵢ.", + "DISABLED and fallback decide at every stop line at its exact arrival time. Green for every owner drives on; red, yellow or unknown starts a cautious crossing. Here u is the minimum of effective ambulance speed and ordinary road limit. Multiple owners use the longest wait for green; an unknown movement substitutes Dᵢ.", + ), + f( + "Przejazd standardowy przy czerwonym / żółtym", + "Standard red/yellow crossing", + "u_f = 10 / 3.6 m/s\nE = min(standard_clearance_factor × μ × wait, 15 s)\nR = max(30 m, E / (1/u_f − 1/u)) if u > u_f\nR = 30 m; E = 0 if u <= u_f", + ), + p( + "Długość jest sprawdzana względem najwolniejszych krawędzi, które obejmuje. Późniejsza krawędź o prędkości poniżej progu kończy okno na swoim początku i ogranicza koszt. Następna linia zastępuje aktywny standardowy przejazd; zielone może usunąć resztę kosztu. Fallback zastępuje własne spowolnienie, ale zachowuje resztę poprzedniego priorytetowego skrzyżowania. Cel ucina niewydany koszt. Limit 15 s dotyczy decyzji na linii, nie całego skrzyżowania o wielu liniach.", + "Length is sized against the slowest covered edges. A later edge at/below the floor ends the window at its start and caps the extra cost. The next line replaces an active Standard crossing; green can clear its remainder. Fallback replaces its own slowdown but preserves an earlier priority junction’s remainder. Arrival truncates unspent cost. The 15-second cap is per stop-line decision, not per multi-line junction.", + ), + h("TTI, kaskada i długość żądania", "TTI, cascade and request hold"), + f( + "Wygładzona prędkość i czas do skrzyżowania", + "Smoothed speed and time to intersection", + "v̄ₜ = max(5 m/s, 0.25 Δxₜ + 0.75 v̄ₜ₋₁)\nv̄₀ = max(first_edge_effective_speed, speed_floor)\nTTIᵢ = max(0, first_lineᵢ − x) / v̄ₜ", + ), + p( + "Ponieważ krok wynosi 1 s, Δx ma numerycznie wartość m/s. Przejechany cel ma TTI null. Dla nieżądanych i nieprzejechanych celów TTI ≤40 s kwalifikuje do żądania. Kaskada dodaje tylko cele w przód oddalone pierwsza-linia → pierwsza-linia o ≤250 m według wczytanego progu. Nie rozwija się rekurencyjnie. Tabela sąsiadów ETL służy do diagnostyki; nie blokuje dopasowania w modelu trasy.", + "Because a step is one second, Δx numerically equals m/s. Passed targets report null TTI. Unrequested, unpassed targets become eligible at TTI ≤40 s. Cascade adds only forward first-line-to-first-line targets within the loaded threshold, default 250 m, without recursive expansion. ETL neighbour candidates are diagnostic evidence rather than a runtime membership gate.", + ), + f( + "Czas zwolnienia i utrzymania priorytetu", + "Release and hold duration", + "Rᵢ = T_open(x, last_lineᵢ) + D_min Jᵢ + E_remaining\nH = max(its_min_hold_seconds, ceil(maxᵢ Rᵢ) + hold_buffer)\nexpected_arrival_utc = now_utc + minᵢ TTIᵢ / playback_speed", + ), + p( + "Jᵢ liczy nieprzejechane skrzyżowania do pierwszej linii celu lub z pierwszą linią wewnątrz jego ostatniej linii. Trwające spowolnienie bywa policzone konserwatywnie dwa razy. Domyślnie minimum H to 40 s, bufor 5 s. Kontrakt zawsze wymaga H ≥40 s. Zegar wygaśnięcia biegnie od wysłania, nie od akceptacji. Nie przewiduje przyszłych postojów ani fallbacku. Jeden pakiet na krok, cel żądany najwyżej raz.", + "Jᵢ counts unpassed junctions up to the target’s first line or whose first line lies inside its last line. An ongoing slowdown can be conservatively counted twice. H defaults to at least 40 seconds with a five-second buffer; the payload always requires H ≥40. Expiry runs from submission, not acceptance. Release estimates do not predict future holds or fallback. One grouped dispatch per step; each target is requested at most once.", + ), + h("Odpowiedzi ITS i deterministyczne wyniki", "ITS presets and deterministic outcomes"), + table( + ["Scenariusz", "Wynik", "Czas od wysłania"], + ["Preset", "Outcome", "Time from submission"], + [ + ["NOMINAL", "ACCEPTED", "1 s"], + ["DELAYED", "ACCEPTED", "5 s"], + ["REJECTED", "REJECTED / CONTROLLER_REJECTED", "1 s"], + ["NO_FEEDBACK", "TIMED_OUT / ACK_TIMEOUT", "8 s"], + [ + "MIXED", + t( + "Jeden z czterech powyższych wyników, wspólny dla grupy.", + "One of the four outcomes above, shared by the target group.", + ), + t("Zależny od wyniku", "Outcome-specific"), + ], + ], + ), + f( + "Podział hashujący MIXED", + "MIXED hash partition", + "bytes = UTF-8(seed + ':' + sorted_IDs.join(','))\nh = 0x811C9DC5\nfor b: h = ((h XOR b) × 0x01000193) mod 2³²\nh = h XOR (h >> 16)\nh = (h × 0x85EBCA6B) mod 2³²\nh = h XOR (h >> 13)\nh = (h × 0xC2B2AE35) mod 2³²\nh = h XOR (h >> 16)\nindex = h >> 30\n0: ACCEPT; 1: ACCEPT_DELAYED; 2: REJECT; 3: NO_RESPONSE", + ), + p( + "To FNV-1a z finalizatorem MurmurHash3 fmix32, a nie nowe losowanie w każdym kroku. Ziarno i uporządkowane identyfikatory celów wystarczają do odtworzenia. Czas i identyfikator przejazdu nie wpływają na hash; grupowanie kaskady może zmienić wynik. Każdy koszyk ma ¼ przestrzeni wyników, co nie gwarantuje 25% obserwacji w skończonej próbce. Stałe scenariusze ignorują ziarno.", + "This is FNV-1a finalized with MurmurHash3 fmix32, not a fresh random draw every tick. Seed and sorted target IDs determine replay. Time and simulation ID are excluded; cascade grouping can change the outcome. Each bucket occupies one quarter of the output space, without guaranteeing 25% frequency in a finite sample. Fixed presets ignore the seed.", + ), + state( + "Cykl życia żądania", + "Request lifecycle", + "REQUESTED → ACCEPTED → RELEASED\n ↘ REJECTED\n ↘ TIMED_OUT\n ↘ RELEASED (all targets passed)\nACCEPTED → EXPIRED (submission + hold)\n\nREJECTED / TIMED_OUT / EXPIRED\n→ unpassed targets: STANDARD_FALLBACK", + "REQUESTED → ACCEPTED → RELEASED\n ↘ REJECTED\n ↘ TIMED_OUT\n ↘ RELEASED (przejechano wszystkie cele)\nACCEPTED → EXPIRED (wysłanie + czas hold)\n\nREJECTED / TIMED_OUT / EXPIRED\n→ nieprzejechane cele: STANDARD_FALLBACK", + ), + p( + "Najpierw sprawdzane jest przejechanie wszystkich celów, następnie termin odpowiedzi, a potem wygaśnięcie zaakceptowanego żądania. Spóźniona akceptacja po końcu hold daje od razu ACCEPTED i EXPIRED bez aktywacji. Timeout wycofuje żądanie i rezerwuje numer sekwencji. Ledger ignoruje złą symulację, nieznane żądanie, niezgodną kolejność celów, stary numer, cofnięty czas lub niedozwolone przejście. Identyczne ponowne wysłanie jest idempotentne, sprzeczne jest błędem.", + "All-targets-passed release is checked first, then due acknowledgement, then accepted hold expiry. Acceptance after the hold deadline immediately produces ACCEPTED and EXPIRED without activating targets. Timeout withdraws the request and reserves a sequence number. The ledger ignores wrong simulations, unknown requests, mismatched ordered targets, stale sequence numbers, backward time and illegal transitions. Identical duplicate submission is idempotent; conflicting duplicates are errors.", + ), + h("Maszyna stanów skrzyżowania", "Intersection state machine"), + state( + "Przejścia potwierdzonego stanu", + "Reported state transitions", + "NORMAL → CLEARING: accepted, not yet shown green\nNORMAL / CLEARING → PRIORITY_GREEN:\n accepted + TTI <= 25 + all route vehicle heads shown GREEN\nPRIORITY_GREEN → CLEARING: TTI > 25 or no complete green confirmation\nCLEARING / PRIORITY_GREEN → NORMAL: acceptance ends before passage\nCLEARING / PRIORITY_GREEN → RECOVERY: passed after priority\nRECOVERY → NORMAL: recovery age >= 15 s\nNORMAL → NORMAL: passed without active priority", + "NORMAL → CLEARING: przyjęto, brak pokazanego zielonego\nNORMAL / CLEARING → PRIORITY_GREEN:\n przyjęto + TTI <= 25 + wszystkie światła trasy GREEN\nPRIORITY_GREEN → CLEARING: TTI > 25 lub brak pełnego potwierdzenia\nCLEARING / PRIORITY_GREEN → NORMAL: koniec akceptacji przed przejazdem\nCLEARING / PRIORITY_GREEN → RECOVERY: przejazd po priorytecie\nRECOVERY → NORMAL: odzyskiwanie >= 15 s\nNORMAL → NORMAL: przejazd bez aktywnego priorytetu", + ), + table( + ["Stan", "Reguła"], + ["State", "Rule"], + [ + [ + "NORMAL", + t( + "Brak zaakceptowanego priorytetu lub zakończona regeneracja. Samo REQUESTED nie zmienia świateł.", + "No accepted priority or recovery complete. REQUESTED alone changes no lights.", + ), + ], + [ + "CLEARING", + t( + "Akceptacja bez kwalifikacji lub potwierdzonego zielonego. Konfliktowe pojazdy i piesi mają cel czerwony, trasa zachowuje zwykły program.", + "Accepted without eligibility or confirmed green. Conflicting vehicles and pedestrians target red; route vehicles retain the ordinary programme.", + ), + ], + [ + "PRIORITY_GREEN", + t( + "Akceptacja, TTI ≤25 s i wszystkie obsługiwane światła pojazdu na trasie pokazują zielone. Brak takich świateł nie potwierdza priorytetu.", + "Accepted, TTI ≤25 s and all supported route vehicle heads shown green. Missing route heads cannot confirm priority.", + ), + ], + [ + "RECOVERY", + t( + "Przejechano ostatnią linię po aktywnym priorytecie. Zwykły cykl wraca od razu; 15 s to stan odzyskiwania, a nie dodatkowa faza all-red.", + "Last line passed after active priority. Ordinary cycle resumes immediately; 15 seconds is runtime recovery, not an extra all-red phase.", + ), + ], + ], + ), + p( + "Sterownik najpierw tworzy cele świateł, a dopiero potem obniża niepotwierdzone PRIORITY_GREEN do raportowanego CLEARING. Może też wejść z NORMAL od razu w PRIORITY_GREEN. TTI jest oceniane ponownie, bez zatrzaskiwania progu. is_active_corridor oznacza dokładnie CLEARING lub PRIORITY_GREEN; is_cascade jest osobną flagą, nie stanem.", + "The controller creates light targets before downgrading unconfirmed PRIORITY_GREEN to reported CLEARING, and can enter PRIORITY_GREEN directly from NORMAL. TTI eligibility is re-evaluated rather than latched. is_active_corridor means exactly CLEARING or PRIORITY_GREEN; is_cascade is separate metadata, not a state.", + ), + p( + "Ostatnia linia pozostaje chroniona przez krok, który przenosi przez nią pojazd, oraz podczas postoju na wspólnej linii. Przyjazd na linię końcową utrzymuje ochronę dla przedziału przyjazdu, a odzyskiwanie zaczyna się później. Nieaktywowany lub nieudany priorytet nie wymaga RECOVERY. Anulowanie zamyka sterownik bez dodatkowego strumienia 15 s. Gdy brak znanych świateł na trasie, kontrola wyjazdu dopuszcza ruch mimo braku potwierdzonego zielonego.", + "The last line remains protected through the movement interval carrying the vehicle across it and while waiting at a shared line. A destination on that line retains protection for the arrival interval before recovery begins. Priority never activated or already failed requires no RECOVERY. Cancellation closes the controller without another 15-second stream. With no known route vehicle heads, the departure check permits motion without confirming green.", + ), + h( + "Program zwykły, priorytet i czasy przejść świateł", + "Ordinary programme, priority and clearance timers", + ), + p( + "Grupą ruchu jest uporządkowana tożsamość kontrolowanych krawędzi. Grupy trasy są łączone w jedną, potem posortowane grupy dostają numer modulo 2. Nie jest to graf konfliktów pasów. Sygnalizator bez znanej grupy nie ma wskaźnika. Węzły sygnalizacji obsługują pojazdy i pieszych, a przejścia piesze tylko pieszych. Dla wielu świateł trasy wybierany jest najbardziej restrykcyjny kolor: RED, YELLOW, GREEN.", + "Movement identity comes from sorted controlled edges. Route groups merge into one; sorted groups then receive slots modulo two. This is not a lane-conflict graph. Signals without a known group have no indicator. Traffic-signal nodes support vehicles and pedestrians; crossing nodes pedestrians only. Multiple route lights use the most restrictive programme color: RED, YELLOW, GREEN.", + ), + f( + "Zwykły cykl dwóch grup", + "Ordinary two-group cycle", + "G = 30 s; Y = 3 s; A = 2 s\nS = G + Y + A = 35 s; cycle = 2 S = 70 s\np = t mod cycle; active = floor(p / S)\nr = p − active S\nroute_wait = 0 if ((t − route_slot S) mod cycle) < G\notherwise: cycle − ((t − route_slot S) mod cycle)", + ), + table( + ["Część slotu", "Aktywne pojazdy", "Inne pojazdy", "Piesi innej grupy"], + ["Slot interval", "Active vehicles", "Other vehicles", "Other-group pedestrians"], + [ + [ + "0 ≤ r < 30 s", + "GREEN", + "RED", + t( + "GREEN, jeśli pokazane pojazdy tej grupy są czerwone", + "GREEN if shown vehicles on their arm are red", + ), + ], + ["30 ≤ r < 33 s", "YELLOW", "RED", "RED"], + ["33 ≤ r < 35 s", "RED", "RED", "RED"], + ], + ), + p( + "Piesi aktywnej grupy mają czerwone. NORMAL i RECOVERY korzystają z absolutnego czasu cyklu bez resetu. W CLEARING konfliktowe pojazdy i wszyscy piesi dostają cel czerwony; trasa pozostaje w zwykłym cyklu. PRIORITY_GREEN kieruje trasę na zielone, resztę na czerwone. Zmiana nie przeskakuje pokazanego żółtego.", + "Pedestrians on the active arm stay red. NORMAL and RECOVERY follow absolute cycle time without reset. CLEARING targets conflicting vehicles and every pedestrian red while route vehicles keep cycling. PRIORITY_GREEN targets route vehicles green and everything else red. Switching does not skip displayed yellow.", + ), + state( + "Pokazane światła pojazdów", + "Shown vehicle heads", + "GREEN → YELLOW: target is no longer green\nYELLOW → RED: yellow age >= signal_yellow_seconds\nRED → GREEN: target green AND every other head\n not also targeting green was already RED", + "GREEN → YELLOW: docelowy kolor nie jest zielony\nYELLOW → RED: czas żółtego >= signal_yellow_seconds\nRED → GREEN: cel zielony ORAZ każde inne światło\n bez zielonego celu było już RED", + ), + p( + "Nowe światło bez historii przyjmuje cel od razu. Żółte musi się skończyć nawet po powrocie zielonego celu; warunek używa poprzednich świateł, więc możliwy jest dodatkowy krok. Nie ma osobnego wymuszenia 2 s all-red przy dowolnym przełączeniu priorytetu — 2 s należą do zwykłego cyklu. Piesi nie mają żółtego i są blokowani przez zielone/żółte pojazdy na swoim ramieniu. Standard i fallback próbkują program w chwili dotarcia; priorytet sprawdza dodatkowo poprzednio pokazane światła.", + "New heads initialize directly to target. Yellow must finish even if a green target returns; the check uses previous heads and can add another tick. An arbitrary priority switch has no independent two-second all-red hold: those two seconds belong to the ordinary cycle. Pedestrians have no yellow and are blocked by green/yellow vehicles on their arm. Standard and fallback sample the programme at arrival; priority additionally checks previously shown heads.", + ), + h("Oszczędność czasu i zaokrąglenia", "Time savings and rounding"), + f( + "Interpolowany przebieg Standard", + "Interpolated Standard baseline", + "Tₛ(x) = tₗ + ((x − xₗ)/(xᵣ − xₗ)) (tᵣ − tₗ)\nelapsed = arrived ? t_arrival : simulated_time\nsaved_ENABLED = round(Tₛ(x)) − round(elapsed)\nsaved_DISABLED = 0\ncomparison_delta = disabled_arrival − enabled_arrival", + ), + p( + "Próbny przejazd zapisuje pozycję co sekundę i dokładny końcowy przyjazd. Tₛ interpoluje czas na tej samej pozycji, także gdy próbka przecina zmianę prędkości. KPI odejmuje osobno zaokrąglone czasy, nie zaokrągla różnicy, i dopuszcza wynik ujemny. Python używa zaokrąglenia połówek do parzystej. Odzyskiwanie świateł nie zwiększa elapsed. Porównanie czeka na dwa pomyślne zakończenia; pozycje w wyścigu są równe przy różnicy mniejszej niż 10 m.", + "The dry run samples positions each second and retains exact final arrival. Tₛ interpolates time at the same position, including samples spanning speed changes. KPIs subtract separately rounded times rather than rounding a difference, and permit negative savings. Python uses ties-to-even. Recovery does not increase elapsed. Comparison requires both successful completion events; the live race calls gaps under 10 metres level.", + ), + f( + "Pozycja na mapie", + "Position along the display polyline", + "δⱼ = 111320 √((Δlongitudeⱼ cos φ₀)² + Δlatitudeⱼ²)\npolyline_offset = clamp(x / route_length, 0, 1) × ∑ⱼ δⱼ\nposition = linear interpolation within that segment", + ), + p( + "Różnice współrzędnych są w stopniach, a φ₀ jest szerokością pierwszego punktu przeliczoną na radiany do cosinusa. To przybliżenie do rysowania; odległości trasy i snap pochodzą z EPSG:2178.", + "Coordinate differences are degrees, with first-point latitude φ₀ converted to radians for cosine. This approximation places the marker; routing distances and snapping use EPSG:2178.", + ), + h("Cykl operacji, zegar i SSE", "Operation lifecycle, clock and SSE"), + state( + "Przebieg jednej sekundy", + "One simulated second", + "move under previous report\n→ controller observations and feedback\n→ requester timeouts → mark fallback\n→ select / submit request (ENABLED only)\n→ feedback events → optional dispatch → tick\n→ completion after arrival and every junction NORMAL", + "ruch według poprzedniego raportu\n→ obserwacje i odpowiedzi sterownika\n→ timeout żądania → oznaczenie fallback\n→ wybór / wysłanie żądania (tylko ENABLED)\n→ odpowiedzi → opcjonalny pakiet → tick\n→ koniec po przyjeździe i wszystkich skrzyżowaniach NORMAL", + ), + p( + "Żądanie wysłane w danym kroku nie zmienia ruchu ani raportu tego kroku. Fallback działa od następnego ruchu. Każdy krok dodaje dokładnie 1 s i tick. Odtwarzanie p przy interwale I śpi max(0, I/p − czas_obliczeń); przekroczenie terminu jest logowane, bez serii nadrabiającej. ETA UTC dzieli przez p, ale nie uwzględnia niestandardowego I.", + "A request submitted in a step cannot change that step’s movement or report. Fallback affects the next movement. Every step advances exactly one second and tick. Playback p with interval I sleeps max(0, I/p − processing_time); overruns are logged without catch-up bursts. UTC ETA divides by p but does not account for a nondefault I.", + ), + state( + "Cykl przejazdu", + "Run lifecycle", + "plan → INITIALIZED → running → ARRIVED\n→ signal recovery → SIMULATION_COMPLETED\nrunning / recovery → SIMULATION_CANCELLED:\n STOPPED | SUPERSEDED | SERVER_ERROR\n\nUI: SETUP → STARTING → RUNNING\n→ FINISHED | CANCELLED | ERROR", + "plan → INITIALIZED → przejazd → ARRIVED\n→ odzyskiwanie świateł → SIMULATION_COMPLETED\nprzejazd / odzyskiwanie → SIMULATION_CANCELLED:\n STOPPED | SUPERSEDED | SERVER_ERROR\n\nUI: SETUP → STARTING → RUNNING\n→ FINISHED | CANCELLED | ERROR", + ), + p( + "Nowa operacja zastępuje poprzednią dopiero po udanym planowaniu; oba plany porównania muszą się udać. Stop jednego członka zatrzymuje parę. Awaria pętli kończy niezakończonych członków SERVER_ERROR, a jeden terminal na przejazd jest gwarantowany. Przyjazd i koniec operacji nie są tym samym. Historyczne ITS_REJECTED, ITS_TIMEOUT i ITS_HOLD_EXPIRED pozostają poprawnymi kodami kontraktu, ale silnik już ich nie emituje.", + "Replacement supersedes the previous operation only after planning succeeds; both comparison plans must succeed. Stopping either member stops the pair. Loop failure ends unfinished members with SERVER_ERROR; publication permits only one terminal per run. Arrival and operation completion differ. Legacy ITS_REJECTED, ITS_TIMEOUT and ITS_HOLD_EXPIRED remain contract-valid but are no longer emitted by the engine.", + ), + p( + "SSE zaczyna się retry: 2000; ramki mają event, id=tick i JSON data. Wiele zdarzeń może mieć ten sam tick. Reconnect dostaje ostatni stan i zdarzenia bieżące, nie odtwarza Last-Event-ID. Kolejka klienta ma domyślnie 32 zdarzenia i usuwa najstarsze, także feedback. Terminal wypiera zwykłe zdarzenie. Limit pamięci czterech sesji dotyczy sesji, nie operacji; aktywna para pozostaje. Rozłączenie nie zatrzymuje symulacji, a stan jest lokalny dla procesu serwera.", + "SSE begins with retry: 2000; frames contain event, id=tick and JSON data. Several events can share a tick. Reconnect gets the latest snapshot and live events, not Last-Event-ID replay. A subscriber queue holds 32 events by default and drops the oldest, including feedback; terminal delivery displaces a nonterminal. Retention of four counts sessions rather than operations; an active pair is preserved. Disconnect does not stop simulation, and state is server-process-local.", + ), + h("Mock a backend", "Mock versus backend"), + f( + "Syntetyczny dystans i czasy mock", + "Synthetic mock distance and estimates", + "R_E = 6371000 m\nh = sin²(Δφ/2) + cos φ₁ cos φ₂ sin²(Δλ/2)\nL = 2 R_E asin(√h); q = L / 5400\nT̂_normal = q × 780 × μ / 1.5\nT̂_greenwave = q × 380\nD = min(3, T̂_greenwave / (2 N))\nu_mock = L / (T̂_greenwave − N D)", + ), + p( + "Mock rysuje prostą zamiast trasy drogowej, bez snap. INT-9001 i INT-9002 leżą na ułamkach 1480/5400 i 1632/5400 długości. Zwykły limit wynosi 50 km/h, a czerwone używa stałego oczekiwania 35 s zamiast rzeczywistego czasu do zielonego. TTI jest czasem pozostałym na osi syntetycznej, nie EMA. Grupy S1/S2 są stałe; hold = max(40, ceil(max TTI)+5). Parametry backendu nie nadpisują stałych mock.", + "Mock draws a straight line rather than a road route, with no snapping. INT-9001 and INT-9002 sit at fractions 1480/5400 and 1632/5400 of its length. Ordinary limit is 50 km/h; red uses a fixed 35-second wait instead of actual next-green time. TTI is remaining synthetic timeline time, not EMA. S1/S2 groups are fixed; hold = max(40, ceil(max TTI)+5). Backend settings do not override mock constants.", + ), + p( + "Mock korzysta z tego samego hasha i domyślnych czasów 1/5/8 s. Po fallback przebudowuje tylko niezakończoną część osi czasu, zachowując przeszłość. JavaScript Math.round różni się od Python round przy połówkach. To zgodność demonstracyjna kontraktu, nie identyczność wyników numerycznych ani fallback serwera po błędzie.", + "Mock shares the hash and default 1/5/8-second response timing. Fallback rebuilds only the undriven timeline, preserving its past. JavaScript Math.round differs from Python round at half values. This is a contract-level demonstration, not numerical parity or automatic server-error fallback.", + ), + h("Wnioski audytu i granice modelu", "Audit findings and model limits"), + table( + ["Obszar", "Ograniczenie implementacji"], + ["Area", "Implementation limitation"], + [ + [ + t("Estymacje", "Estimates"), + t( + "Nominalny GreenWave nie uwzględnia postojów sterownika i fallbacku. Rzeczywistą oszczędność daje Standard na tej samej pozycji lub dwa zakończone przejazdy.", + "Nominal GreenWave excludes controller holds and fallback. Measured simulation savings use Standard at the same position or two completed runs.", + ), + ], + [ + t("Dzielenie przez zero", "Division by zero"), + t( + "speed_floor_meters_per_second=0 i speed_ema_alpha=1 są dozwolone. Pełna sekunda postoju zeruje EMA, po czym TTI dzieli przez zero.", + "speed_floor_meters_per_second=0 and speed_ema_alpha=1 are permitted. A full held second makes EMA zero and the next TTI divides by zero.", + ), + ], + [ + t("Walidacja hold", "Hold validation"), + t( + "Ustawienie minimum hold poniżej 40 s i mały bufor mogą zbudować pakiet sprzeczny z kontraktem H ≥40, kończąc pętlę SERVER_ERROR.", + "A hold minimum below 40 seconds plus a small buffer can produce a payload violating H ≥40, ending the loop with SERVER_ERROR.", + ), + ], + [ + t("Dolna prędkość", "Rolling floor"), + t( + "Łączenie okien, zmiany krawędzi i ucięcie celu mogą obniżyć prędkość poniżej zamierzonego progu. Część floatów nie ma jawnego zakazu nieskończoności.", + "Merged windows, edge changes and destination truncation can defeat the intended rolling floor. Several floats have no explicit infinity rejection.", + ), + ], + [ + t("Sygnały", "Signals"), + t( + "Dwie grupy modulo 2 nie modelują pełnych konfliktów. Brak sygnałów nie potwierdza zielonego, ale pozwala na opuszczenie linii. Standard celowo przejeżdża czerwone ostrożnie.", + "Two modulo slots do not model full conflicts. Missing heads cannot confirm green but permit line departure. Standard deliberately rolls red with caution.", + ), + ], + [ + t("Optymalizacja", "Optimization"), + t( + "Najkrótsza suma krawędzi nie musi być najkrótszym czasem całej symulacji. Zwykły ranking ma limit pięciu baz; świadomy zasobów ocenia wszystkie uprawnione.", + "Minimum edge cost need not minimize simulated trip time. Ordinary ranking cuts at five bases; resource-aware ranking evaluates all eligible bases.", + ), + ], + [ + t("Zegar i połączenie", "Clock and connection"), + t( + "ETA UTC pomija niestandardowy interwał. EventSource nie udostępnia HTTP status: CORS/proxy może wyglądać jak brak sesji. Stop po timeout startu jest best-effort.", + "UTC ETA omits nondefault interval. EventSource hides HTTP status, so CORS/proxy failures can look like missing sessions. Cleanup after start timeout is best-effort.", + ), + ], + [ + t("Pamięć i odtwarzanie", "State and replay"), + t( + "Wyłączność jest na proces serwera, kolejki są stratne, brak trwałego replay. Więcej workerów nie współdzieli jednej operacji.", + "Exclusivity is per server process, queues are lossy and there is no durable replay. Multiple workers do not share one operation.", + ), + ], + ], + ), + p( + "Brak modelu zakazów skrętu, dynamicznych kolejek, wielu oddziałujących pojazdów uprzywilejowanych, barier pieszych i rzeczywistej dostępności. μ nie spowalnia otwartej drogi karetki. Wyniki hashy nie są empiryczną niezawodnością ITS. Historyczne opisy 1 Hz czasu rzeczywistego i kończenia przejazdu po odmowie są zastąpione przez krok 1 s symulacji i fallback per skrzyżowanie.", + "There is no model of turn restrictions, dynamic queues, interacting emergency vehicles, walking barriers or live availability. μ does not slow open-road ambulance movement. Hash outcomes are not empirical ITS reliability. Historical descriptions of 1 Hz wall-clock ticks and cancellation on rejection are superseded by one-second simulated steps and per-junction fallback.", + ), + h("Konfiguracja przygotowania danych", "Offline data-preparation configuration"), + p( + "Poniżej znajdują się wszystkie stałe etl/config.py, łącznie z progami raportów. To stałe Pythona, bez nadpisywania przez żądania. Zmiana danych pochodnych wymaga ponowienia odpowiednich etapów ETL. AREA_LOOKUP_RADIUS_M i ADDRESS_MATCH_CLEAN_M są także używane podczas działania serwera. Oznaczenia count_in_delay, exclude_and_reject i manual_review dotyczą traktowania sygnalizatorów.", + "Every etl/config.py constant is listed below, including report-only thresholds. These are Python constants with no request override. Changing derived inputs requires rebuilding the affected ETL stages. AREA_LOOKUP_RADIUS_M and ADDRESS_MATCH_CLEAN_M also have runtime server consumers. count_in_delay, exclude_and_reject and manual_review describe signal handling.", + ), + table(["Stała", "Wartość"], ["Constant", "Value"], etlSettingRows), + p( + "Dodatnie całkowite maxspeed z opcjonalnym km/h wygrywa z prędkością klasy; np. mph, listy lub PL:urban trafiają do domyślnej z oznaczeniem źródła. Jawny oneway wygrywa, nawet no na rondzie; bez niego rondo/circular i motorway/link są jednokierunkowe. Wartości nieznane są zgłaszane. Cechy kierunkowe pasów wygrywają z sumą; sumy dwukierunkowe dzielone są na pół z minimum jednego pasa.", + "Positive integer maxspeed with optional km/h wins over class speed; mph, lists and PL:urban use a source-marked default. Explicit oneway wins, even no on a roundabout; without it, roundabout/circular and motorway/link imply one-way. Unknown directions are reported. Directional lane tags override totals; two-way totals are halved with a minimum of one lane.", + ), + h("Źródła i zakres sprawdzenia", "Sources and verification scope"), + p( + "Opis sprawdzono z routing/edge_times, simulation/motion, controller, phases, priority_requests, session i telemetry, a następnie z niezależnym mock frontendu. Testy badają zgodność kodu i kontraktu, nie fizyczną poprawność parametrów. Wersja repozytoryjna zawiera odnośniki do konkretnych modułów i testów; treść matematyczna i katalog parametrów są dostępne powyżej bez opuszczania tej strony.", + "The audit traced routing/edge_times, simulation/motion, controller, phases, priority_requests, session and telemetry, then checked the independent frontend mock. Tests verify implementation and contract behavior, not physical parameter accuracy. The repository reference links individual modules and tests; the equations and parameter catalog are available above without leaving this page.", + ), + { + kind: "links", + items: [ + { + label: t("Audyt ze źródłami i testami", "Audit with source and test references"), + href: "https://github.com/fjarmula/GreenWave/blob/main/docs/architecture/system-logic.md", + }, + { + label: t("Parametry silnika w kodzie", "Engine settings source"), + href: "https://github.com/fjarmula/GreenWave/blob/main/backend/src/greenwave/simulation_settings.py", + }, + { + label: t("Kanoniczne schematy API", "Canonical API schemas"), + href: "https://github.com/fjarmula/GreenWave/tree/main/backend/src/greenwave/schemas", + }, + ], + }, + ], + }; +} + +export const logicSections: Record = { + pl: logicSection("pl"), + en: logicSection("en"), +}; diff --git a/frontend/src/lib/docs/logic-settings.ts b/frontend/src/lib/docs/logic-settings.ts new file mode 100644 index 0000000..97ae6eb --- /dev/null +++ b/frontend/src/lib/docs/logic-settings.ts @@ -0,0 +1,124 @@ +/** Audited defaults from simulation_settings.py and etl/config.py, 2026-10-30. + * Reference data only; never read by the simulation runtime. */ +export const simulationSettingRows: string[][] = [ + ["clearing_tti_seconds", "40", "≥ 0"], + ["priority_green_tti_seconds", "25", "≥ 0"], + ["recovery_hold_seconds", "15", "≥ 0"], + ["min_intersection_delay_seconds", "3", "≥ 0"], + ["greenwave_approach_distance_m", "60", "> 0; finite"], + ["greenwave_min_rolling_speed_kmh", "15", "> 0; finite"], + ["ambulance_speed_factor", "1.3", "> 0"], + ["ambulance_min_speed_kmh", "30", "≥ 0"], + ["ambulance_max_speed_kmh", "90", "> 0"], + ["speed_ema_alpha", "0.25", "> 0; ≤ 1"], + ["speed_floor_meters_per_second", "5", "≥ 0"], + ["its_ack_delay_seconds", "1", "≥ 1"], + ["its_delayed_ack_seconds", "5", "≥ 1"], + ["its_ack_timeout_seconds", "8", "≥ 2"], + ["its_min_hold_seconds", "40", "≥ 0"], + ["its_hold_buffer_seconds", "5", "≥ 0"], + ["tick_interval_seconds", "1", "> 0"], + ["max_snap_distance_meters", "150", "≥ 0"], + ["max_on_foot_meters", "800", "> 0; finite"], + ["on_foot_detour_factor", "1.3", "≥ 1.0; finite"], + ["on_foot_speed_meters_per_second", "1.4", "> 0; finite"], + ["dispatch_shortlist_size", "5", "≥ 1"], + ["area_preference_margin_seconds", "60", "≥ 0; finite"], + ["subscriber_queue_size", "32", "≥ 1"], + ["retained_session_limit", "4", "≥ 1"], + ["normal_single_lane_factor", "1.15", "≥ 1.0"], + ["normal_unpaved_factor", "1.3", "≥ 1.0"], + ["normal_calming_seconds", "3.0", "≥ 0"], + ["ambulance_calming_seconds", "2.0", "≥ 0"], + ["ambulance_bus_lane_factor", "1.05", "≥ 1.0"], + ["ambulance_tram_track_factor", "1.05", "≥ 1.0"], + ["signal_green_seconds", "30", "> 0"], + ["signal_yellow_seconds", "3", "≥ 0"], + ["signal_all_red_seconds", "2", "≥ 0"], + ["standard_clearance_factor", "1.0", "≥ 0; finite"], + ["standard_crossing_distance_m", "30", "> 0; finite"], + ["standard_min_rolling_speed_kmh", "10", "> 0; finite"], + ["standard_max_red_loss_seconds", "15", "≥ 0; finite"], +]; + +export const etlSettingRows: string[][] = [ + ["SOURCE_CRS", '"EPSG:4326"'], + ["METRIC_CRS", '"EPSG:2178"'], + [ + "DRIVABLE_HIGHWAY_VALUES", + '["living_street", "motorway", "motorway_link", "primary", "primary_link", "residential", "road", "secondary", "secondary_link", "service", "tertiary", "tertiary_link", "trunk", "trunk_link", "unclassified"]', + ], + ["EXCLUDED_ACCESS_VALUES", '["no", "private"]'], + ["ACCESS_TRACK_TRACKTYPES", '["grade1", "grade2", "grade3"]'], + ["EMERGENCY_ACCESS_VALUES", '["designated", "official", "yes"]'], + ["EMERGENCY_EXTRA_HIGHWAY_VALUES", '["pedestrian", "track"]'], + ["CLUSTER_PROBE_RADII_METERS", "[15.0, 30.0, 50.0]"], + [ + "COVERAGE_TAGS", + '["maxspeed", "oneway", "lanes", "name", "junction", "bus:lanes", "busway", "lanes:bus"]', + ], + ["EXACT_ONLY_TAGS", '["junction", "name", "oneway"]'], + ["NON_BLOCKING_SIGNAL_TAGS", '["blinker", "tram_priority"]'], + ["SAMPLE_LIMIT", "20"], + ["CLUSTER_MAP_RADII_METERS", "[20.0, 30.0, 40.0, 50.0]"], + ["EXCLUDED_SERVICE_SUBTYPES", '["drive-through", "driveway", "parking_aisle"]'], + ["ABSENT_TAG", '""'], + ["SIGNAL_CLUSTER_RADIUS_METERS", "40.0"], + ["SIGNAL_DELAY_SECONDS", "35.0"], + ["MIDBLOCK_SIGNAL_DELAY_SECONDS", "35.0"], + ["PEDESTRIAN_CROSSING_DELAY_SECONDS", "35.0"], + [ + "SIGNAL_TAG_HANDLING", + "{ABSENT_TAG: SignalHandling.COUNT_IN_DELAY, 'signal': SignalHandling.COUNT_IN_DELAY, 'traffic_lights': SignalHandling.COUNT_IN_DELAY, 'blinker': SignalHandling.EXCLUDE_AND_REJECT, 'tram_priority': SignalHandling.EXCLUDE_AND_REJECT, 'controller': SignalHandling.MANUAL_REVIEW}", + ], + ["COUNTED_CROSSING_KINDS", '["highway=crossing"]'], + ["STANDALONE_CROSSING_DISTANCE_METERS", "30.0"], + ["IMPLIED_ONEWAY_HIGHWAY_VALUES", '["motorway", "motorway_link"]'], + ["IMPLIED_ONEWAY_JUNCTION_VALUES", '["circular", "roundabout"]'], + [ + "CLASS_DEFAULT_SPEED_KMH", + '{"motorway": 140, "motorway_link": 50, "trunk": 70, "trunk_link": 50, "primary": 50, "primary_link": 50, "secondary": 50, "secondary_link": 50, "tertiary": 50, "tertiary_link": 50, "unclassified": 50, "residential": 30, "living_street": 20, "road": 50, "service": 30, "track": 15, "pedestrian": 10}', + ], + ["ROUNDABOUT_SIGNAL_ASSOCIATION_METERS", "40.0"], + ["STREET_LENGTH_RATIO_RANGE", "[0.8, 1.25]"], + ["ROUTE_DETOUR_RATIO_RANGE", "[1.0, 1.6]"], + ["ROUTE_SNAP_TOLERANCE_METERS", "150.0"], + ["SIGNAL_SNAP_TOLERANCE_METERS", "30.0"], + ["NEAR_MISS_TOLERANCE_METERS", "1.5"], + ["JUNCTION_MIN_DISTINCT_NEIGHBOURS", "3"], + ["ASSIGNMENT_LIMIT_METERS", "50.0"], + ["MERGE_DISTANCE_METERS", "30.0"], + ["MERGE_MAX_GROUP_DIAMETER_METERS", "65.0"], + ["CROSSING_MERGE_DISTANCE_METERS", "15.0"], + ["WELD_TOLERANCE_METERS", "1.0"], + ["INTERSECTION_ID_PREFIX", '"INT-"'], + ["CASCADE_THRESHOLD_METERS", "250.0"], + ["CASCADE_ALLOW_U_TURNS", "false"], + [ + "PAVED_SURFACE_VALUES", + '["asphalt", "cobblestone", "concrete", "concrete:lanes", "concrete:plates", "metal", "paved", "paving_stones", "sett", "unhewn_cobblestone", "wood"]', + ], + [ + "UNPAVED_SURFACE_VALUES", + '["compacted", "dirt", "earth", "fine_gravel", "grass", "grass_paver", "gravel", "ground", "mud", "pebblestone", "sand", "unpaved"]', + ], + ["TRAM_TRACK_MATCH_METERS", "6.0"], + ["TRAM_TRACK_MIN_OVERLAP_SHARE", "0.5"], + ["STATION_DEDUP_RADIUS_M", "150.0"], + [ + "POLICE_EXCLUDED_NAME_FRAGMENTS", + '["straz miejska", "strazy miejskiej", "straz ochrony kolei", "strazy ochrony kolei", "inspektorat transportu drogowego", "komisariat wodny"]', + ], + ["AMBULANCE_EXCLUDED_NAMES", '["reumatologii", "rehabilitacji"]'], + ["AMBULANCE_INCLUDED_NAMES", '["Szpital Uniwersytecki"]'], + ["MERGE_SAME_NAME_AT_ANY_DISTANCE", '["POLICE_CAR"]'], + ["ADDRESS_DEDUP_RADIUS_M", "400.0"], + ["ADDRESS_MATCH_CLEAN_M", "100.0"], + ["ADDRESS_MATCH_MAX_M", "500.0"], + ["ADDRESS_NAME_VARIANT_RADIUS_M", "50.0"], + ["ADDRESS_NAME_VARIANT_TIGHT_M", "20.0"], + ["KRAKOW_CENTRE_LAT_LNG", "[50.0617, 19.9373]"], + ["PLACES_MAX_SNAP_DISTANCE_M", "150.0"], + ["PRM_BASE_OSM_MATCH_RADIUS_M", "200.0"], + ["AREA_LOOKUP_RADIUS_M", "250.0"], +]; diff --git a/frontend/src/lib/docs/tabs.test.ts b/frontend/src/lib/docs/tabs.test.ts index b212f65..c5ffd62 100644 --- a/frontend/src/lib/docs/tabs.test.ts +++ b/frontend/src/lib/docs/tabs.test.ts @@ -27,3 +27,7 @@ it("uses Up/Down for the vertical documentation rail", () => { expect(nextTabIndex("ArrowRight", 0, 5, "vertical")).toBeNull(); expect(sectionFromHash("#run")).toBe("about"); }); + +it("opens the system logic reference directly from its URL hash", () => { + expect(sectionFromHash("#logic")).toBe("logic"); +}); diff --git a/frontend/src/lib/docs/tabs.ts b/frontend/src/lib/docs/tabs.ts index b924da6..e7eecbf 100644 --- a/frontend/src/lib/docs/tabs.ts +++ b/frontend/src/lib/docs/tabs.ts @@ -1,4 +1,11 @@ -export const DOCS_SECTION_IDS = ["about", "tech", "data", "architecture", "roadmap"] as const; +export const DOCS_SECTION_IDS = [ + "about", + "tech", + "data", + "architecture", + "logic", + "roadmap", +] as const; export type DocsSectionId = (typeof DOCS_SECTION_IDS)[number]; /** The active docs tab lives in the URL hash; anything unrecognised opens the first tab. */ From 09abeb39b103203a2c758b76b65a24824ce3f8a6 Mon Sep 17 00:00:00 2001 From: Piotr Lorek Date: Fri, 30 Oct 2026 09:19:36 +0100 Subject: [PATCH 3/4] docs: restructure docs page with flows, typeset formulas and author footer --- README.md | 4 +- docs/architecture/system-logic.md | 6 + docs/engineering/frontend-dashboard.md | 18 +- frontend/src/app/docs/page.tsx | 12 +- frontend/src/app/globals.css | 176 +++++++++- frontend/src/app/page-titles.test.ts | 1 + frontend/src/components/docs/DocsBlocks.tsx | 13 +- frontend/src/components/docs/DocsFooter.tsx | 32 ++ .../src/components/docs/DocsWorkspace.tsx | 16 +- frontend/src/components/docs/FlowDiagram.tsx | 51 +++ frontend/src/components/docs/MathNotation.tsx | 79 +++++ .../src/components/docs/docs-blocks.test.tsx | 74 +++- .../components/docs/docs-workspace.test.tsx | 13 +- frontend/src/lib/docs/content.test.ts | 33 +- frontend/src/lib/docs/content.ts | 216 +++++++++++- .../{logic-content.ts => details-content.ts} | 321 ++++++------------ ...{logic-settings.ts => details-settings.ts} | 0 frontend/src/lib/docs/layout.ts | 7 +- frontend/src/lib/docs/tabs.test.ts | 5 +- frontend/src/lib/docs/tabs.ts | 6 +- 20 files changed, 803 insertions(+), 280 deletions(-) create mode 100644 frontend/src/components/docs/DocsFooter.tsx create mode 100644 frontend/src/components/docs/FlowDiagram.tsx create mode 100644 frontend/src/components/docs/MathNotation.tsx rename frontend/src/lib/docs/{logic-content.ts => details-content.ts} (59%) rename frontend/src/lib/docs/{logic-settings.ts => details-settings.ts} (100%) diff --git a/README.md b/README.md index 2e7b314..6238db7 100644 --- a/README.md +++ b/README.md @@ -130,8 +130,8 @@ Public HTTPS hosting on a free Oracle VM: [deployment guide](deploy/README.md). its workspace controls. - [CONTRIBUTING.md](CONTRIBUTING.md): checks, branches, commits and contract changes. - The in-app **Documentation** page (`/docs`): the Open Data App contest write-up in Polish and - English (project, technologies, data, architecture, system logic, future development). - The **System logic** tab at `/docs#logic` contains the formulas, parameter reference and state machines. + English (project, technologies, data, architecture, details, future development). + The **Details** tab at `/docs#details` contains the core formulas, parameter reference and state machines. ## Data sources and attribution diff --git a/docs/architecture/system-logic.md b/docs/architecture/system-logic.md index cb1b526..34eff9f 100644 --- a/docs/architecture/system-logic.md +++ b/docs/architecture/system-logic.md @@ -928,3 +928,9 @@ In-app follow-up verification (2026-10-30): frontend lint, typecheck, formatting all 1,286 tests and the production build passed. Playwright CLI checked `/docs#logic` in PL and EN at 1440, 390 and 320 px: sixteen formula blocks, no document overflow, keyboard tab navigation and browser-back selection all passed. + +Later follow-up: the in-app tab is now **Details** / **Szczegóły** at `/docs#details` +(`#logic` still opens it). System-level ownership, modes, the per-second step and the run +lifecycle moved to the Architecture tab. The page keeps five core formulas typeset in a serif +math face, and draws lifecycles as box-and-arrow flows. This document remains the complete +audit, including every equation. diff --git a/docs/engineering/frontend-dashboard.md b/docs/engineering/frontend-dashboard.md index 9368d11..34bef7f 100644 --- a/docs/engineering/frontend-dashboard.md +++ b/docs/engineering/frontend-dashboard.md @@ -62,8 +62,8 @@ camera actions stop an old gesture before applying the new view so rapid toggles ## Documentation page `/docs` holds the contest documentation (Open Data App rules §5.2) as six tabs: About, Technologies, -Data, Architecture, System logic, Future development. The copy lives in -`src/lib/docs/content.ts` and `logic-content.ts` as typed blocks per language and does not +Data, Architecture, Details, Future development. The copy lives in +`src/lib/docs/content.ts` and `details-content.ts` as typed blocks per language and does not go through the `polish.ts` dictionary. PL and EN must stay structurally identical, every command must appear in `README.md`, and English sentences must not copy the repository docs (`content.test.ts`, `content-facts.test.ts`). The active tab is the URL hash (`/docs#data`), with unknown hashes @@ -76,8 +76,12 @@ table marked `cards` renders one card per row. Behind it sits the home corridor signal colours). The tab track sticks under the header and turns glass only while stuck; one thumb slides to the clicked tab and the panel fades in, while keyboard switches stay instant. -The System logic tab (`/docs#logic`) publishes the implementation audit in both languages. -Its formula and state blocks render readable notation in keyboard-scrollable figures; they -are not shell commands and have no command-copy UI. `logic-settings.ts` stores the audited -parameter reference values, not runtime configuration. Keep it aligned with the audited -backend settings and ETL constants when updating that reference. +Architecture covers ownership, modes, the per-second step and the run lifecycle. The Details tab +(`/docs#details`; the former `#logic` hash still opens it) holds the implementation reference in +both languages: configuration, parameters, movement and signal rules, and model limits. Keep it to +the few core formulas. Formula blocks use compact notation (`x_i`, `t_{a,e}`, `x^2`) typeset by +`MathNotation` in the route-scoped STIX Two Text face. Lifecycles and pipelines are `flow` blocks +(steps, dashed branches, an optional cycle), never preformatted text. `details-settings.ts` stores +the audited parameter reference values, not runtime configuration. Keep it aligned with the audited +backend settings and ETL constants when updating that reference. A footer on every tab credits the +authors with their GitHub profiles. diff --git a/frontend/src/app/docs/page.tsx b/frontend/src/app/docs/page.tsx index 3987304..d64f6d9 100644 --- a/frontend/src/app/docs/page.tsx +++ b/frontend/src/app/docs/page.tsx @@ -1,8 +1,18 @@ +import { STIX_Two_Text } from "next/font/google"; import { pageMetadata } from "@/lib/localized-metadata"; import { DocsWorkspace } from "@/components/docs/DocsWorkspace"; + +/** Formula typeface, loaded only for the documentation route. */ +const mathFont = STIX_Two_Text({ + variable: "--font-math", + subsets: ["latin", "greek"], + style: ["normal", "italic"], + preload: false, +}); + export async function generateMetadata() { return pageMetadata("Documentation"); } export default function Page() { - return ; + return ; } diff --git a/frontend/src/app/globals.css b/frontend/src/app/globals.css index 3e15bef..7e04a4b 100644 --- a/frontend/src/app/globals.css +++ b/frontend/src/app/globals.css @@ -3170,18 +3170,137 @@ a.docs-chip:focus-visible, font-weight: 600; background: var(--muted); } -.docs-notation pre { +/* Formulas read as mathematics: a text serif, italic variables and real scripts. */ +.docs-math { + display: grid; + gap: 0.375rem; max-width: 100%; overflow-x: auto; - padding: 0.875rem; - font-family: var(--font-mono); - font-size: 0.875rem; - line-height: 1.75; + padding: 0.875rem 1rem; + font-family: var(--font-math), "STIX Two Text", "Cambria Math", Cambria, "Times New Roman", serif; + font-size: 1.0625rem; + line-height: 1.6; + font-variant-numeric: lining-nums; } -.docs-notation pre:focus-visible { +.docs-math-line { + white-space: nowrap; +} +.docs-math var { + font-style: italic; +} +.docs-math sub, +.docs-math sup { + font-size: 0.7em; + line-height: 0; +} +.docs-math:focus-visible { outline: 2px solid var(--ring); outline-offset: -2px; } + +/* Flows share the architecture diagram's boxes: solid steps, dashed side outcomes. */ +.docs-flow { + container-type: inline-size; + display: grid; + gap: 0.75rem; + max-width: 54rem; +} +.docs-flow figcaption { + font-size: 0.8125rem; + font-weight: 600; +} +.docs-flow-steps { + display: flex; + flex-direction: column; + gap: 0.25rem; + list-style: none; +} +.docs-flow-step { + display: flex; + flex-direction: column; + min-width: 0; +} +.docs-flow-arrow { + align-self: center; + flex: none; + width: 1rem; + height: 1rem; + margin-bottom: 0.25rem; + color: var(--muted-foreground); + transform: rotate(90deg); +} +.docs-flow-column { + flex: 1; + min-width: 0; +} +.docs-flow-node { + display: grid; + gap: 0.125rem; + padding: 0.625rem 0.75rem; + border: 1px solid color-mix(in oklch, var(--muted-foreground) 50%, transparent); + border-radius: 10px; + background: var(--card); + font-size: 0.8125rem; + line-height: 1.35; +} +.docs-flow-node strong { + font-weight: 600; + overflow-wrap: anywhere; +} +.docs-flow-node span { + font-size: 0.75rem; + color: var(--muted-foreground); +} +.docs-flow-node-branch { + border-style: dashed; + background: transparent; +} +.docs-flow-branches { + display: grid; + gap: 0.375rem; + margin-top: 0.375rem; + list-style: none; +} +.docs-flow-branches li { + display: flex; + align-items: flex-start; + gap: 0.25rem; +} +.docs-flow-branches .docs-flow-node { + flex: 1; + min-width: 0; +} +.docs-flow-branch-arrow { + flex: none; + width: 0.875rem; + height: 0.875rem; + margin-top: 0.625rem; + color: var(--muted-foreground); +} +.docs-flow-cycle { + display: flex; + align-items: center; + gap: 0.5rem; + font-size: 0.8125rem; + color: var(--muted-foreground); +} +@container (min-width: 40rem) { + .docs-flow-steps { + flex-direction: row; + align-items: flex-start; + } + .docs-flow-step { + flex: 1 1 0; + flex-direction: row; + align-items: flex-start; + gap: 0.25rem; + } + .docs-flow-arrow { + align-self: flex-start; + margin: 1.25rem 0 0; + transform: none; + } +} .docs-group .docs-code { background: var(--tile); } @@ -3422,6 +3541,51 @@ a.docs-chip:focus-visible, grid-row: auto; } } +/* Credits close every tab: authors' GitHub profiles, the repository and the simulation notice. */ +.docs-footer { + display: flex; + flex-wrap: wrap; + gap: 1.25rem 3rem; + margin-top: 4rem; + padding-top: 1.5rem; + border-top: 1px solid var(--border); + font-size: 0.875rem; +} +.docs-footer h2 { + font-size: 0.75rem; + font-weight: 600; + letter-spacing: 0.02em; + color: var(--muted-foreground); +} +.docs-footer ul { + display: flex; + flex-wrap: wrap; + gap: 0 1.5rem; + list-style: none; +} +.docs-footer a { + display: inline-flex; + align-items: center; + gap: 0.4375rem; + min-height: 44px; + text-decoration: underline; + text-underline-offset: 4px; + text-decoration-color: color-mix(in srgb, var(--beacon) 35%, transparent); +} +.docs-footer a:focus-visible { + outline: 2px solid var(--ring); + outline-offset: 3px; +} +.docs-footer-handle { + font-family: var(--font-mono); + font-size: 0.75rem; + color: var(--muted-foreground); +} +.docs-footer-notice { + flex-basis: 100%; + font-size: 0.8125rem; + color: var(--muted-foreground); +} .docs-panel:focus-visible { outline: 2px solid var(--ring); outline-offset: 6px; diff --git a/frontend/src/app/page-titles.test.ts b/frontend/src/app/page-titles.test.ts index 62e7f39..ddf460c 100644 --- a/frontend/src/app/page-titles.test.ts +++ b/frontend/src/app/page-titles.test.ts @@ -10,6 +10,7 @@ import { generateMetadata as standard } from "./simulation/standard/page"; vi.mock("next/font/google", () => ({ Geist: () => ({ variable: "" }), Geist_Mono: () => ({ variable: "" }), + STIX_Two_Text: () => ({ variable: "" }), })); it("names each workspace in the browser title", async () => { diff --git a/frontend/src/components/docs/DocsBlocks.tsx b/frontend/src/components/docs/DocsBlocks.tsx index 1f67ede..7dd19fb 100644 --- a/frontend/src/components/docs/DocsBlocks.tsx +++ b/frontend/src/components/docs/DocsBlocks.tsx @@ -2,6 +2,8 @@ import { Info } from "lucide-react"; import type { DocsBlock } from "@/lib/docs/content"; import { ArchitectureDiagram } from "./ArchitectureDiagram"; import { CodeBlock } from "./CodeBlock"; +import { FlowDiagram } from "./FlowDiagram"; +import { MathNotation } from "./MathNotation"; export function Block({ block }: { block: DocsBlock }) { switch (block.kind) { @@ -74,19 +76,14 @@ export function Block({ block }: { block: DocsBlock }) { ); case "formula": - case "state": return (
{block.label}
-
-            {block.expression}
-          
+
); + case "flow": + return ; case "code": return ; case "links": diff --git a/frontend/src/components/docs/DocsFooter.tsx b/frontend/src/components/docs/DocsFooter.tsx new file mode 100644 index 0000000..ecc3d16 --- /dev/null +++ b/frontend/src/components/docs/DocsFooter.tsx @@ -0,0 +1,32 @@ +import { ArrowUpRight } from "lucide-react"; +import type { Language } from "@/lib/localization"; +import { DOCS_AUTHORS, DOCS_REPOSITORY, docsFooter } from "@/lib/docs/content"; + +/** Credits shared by every docs tab: authors' GitHub profiles and the repository. */ +export function DocsFooter({ language }: { language: Language }) { + const copy = docsFooter[language]; + return ( +
+ ); +} diff --git a/frontend/src/components/docs/DocsWorkspace.tsx b/frontend/src/components/docs/DocsWorkspace.tsx index 87f8d64..034dba1 100644 --- a/frontend/src/components/docs/DocsWorkspace.tsx +++ b/frontend/src/components/docs/DocsWorkspace.tsx @@ -6,13 +6,15 @@ import { ThemeToggle } from "@/components/hud/ThemeToggle"; import { ResponsiveNavigation } from "@/components/workspace/ResponsiveNavigation"; import { WorkspaceHeader } from "@/components/workspace/WorkspaceHeader"; import { useIsPhone } from "@/lib/useIsPhone"; -import { docsContent } from "@/lib/docs/content"; +import { DOCS_REPOSITORY, docsContent } from "@/lib/docs/content"; import { DocsBackdrop } from "./DocsBackdrop"; +import { DocsFooter } from "./DocsFooter"; import { DocsSectionView } from "./DocsSectionView"; import { DocsTabs } from "./DocsTabs"; import { useDocsSection } from "./useDocsSection"; -export function DocsWorkspace() { +/** `className` carries the route-scoped math font variable. */ +export function DocsWorkspace({ className }: { className?: string }) { const { t, language } = useTranslation(); const phone = useIsPhone(); const [active, select] = useDocsSection(); @@ -31,7 +33,7 @@ export function DocsWorkspace() { const sections = docsContent[language]; const section = sections.find((item) => item.id === active) ?? sections[0]; return ( -
+
}> @@ -46,12 +48,7 @@ export function DocsWorkspace() { - + GitHub @@ -77,6 +74,7 @@ export function DocsWorkspace() { +
); } diff --git a/frontend/src/components/docs/FlowDiagram.tsx b/frontend/src/components/docs/FlowDiagram.tsx new file mode 100644 index 0000000..9f1c5bc --- /dev/null +++ b/frontend/src/components/docs/FlowDiagram.tsx @@ -0,0 +1,51 @@ +import { ArrowRight, CornerDownRight, RotateCcw } from "lucide-react"; +import type { FlowStep } from "@/lib/docs/content"; + +/** Steps read left to right (top to bottom when narrow); branches hang under the step they leave. */ +export function FlowDiagram({ + label, + steps, + cycle, +}: { + label: string; + steps: FlowStep[]; + cycle?: string; +}) { + return ( +
+
{label}
+
    + {steps.map((step, index) => ( +
  1. + {index > 0 && } +
    +
    + {step.label} + {step.detail && {step.detail}} +
    + {step.branches && ( +
      + {step.branches.map((branch) => ( +
    • + +
      + {branch.label} + {branch.detail && {branch.detail}} +
      +
    • + ))} +
    + )} +
    +
  2. + ))} +
+ {cycle && ( +

+ + {cycle} +

+ )} +
+ ); +} diff --git a/frontend/src/components/docs/MathNotation.tsx b/frontend/src/components/docs/MathNotation.tsx new file mode 100644 index 0000000..e1df9d4 --- /dev/null +++ b/frontend/src/components/docs/MathNotation.tsx @@ -0,0 +1,79 @@ +import type { ReactNode } from "react"; + +type MathNode = + string | { kind: "var"; text: string } | { kind: "sub" | "sup"; children: MathNode[] }; + +const WORD = /[A-Za-z]{2,}/y; +const LETTER = /\p{L}\p{M}*/uy; +const NUMBER = /\d+(?:\.\d+)?/y; +const UPRIGHT_GREEK = /^[Α-Ω]/; + +function push(nodes: MathNode[], node: MathNode) { + const last = nodes.at(-1); + if (typeof node === "string" && typeof last === "string") nodes[nodes.length - 1] = last + node; + else nodes.push(node); +} + +/** One operand: a function name or label word, a single variable letter, a number or a symbol. */ +function atom(source: string, index: number): [MathNode, number] { + for (const pattern of [WORD, LETTER, NUMBER]) { + pattern.lastIndex = index; + const match = pattern.exec(source); + if (!match) continue; + const text = match[0]; + // TeX convention: single Latin and lowercase Greek letters are italic variables. + const node = + pattern === LETTER && !UPRIGHT_GREEK.test(text) ? { kind: "var" as const, text } : text; + return [node, pattern.lastIndex]; + } + return [source[index], index + 1]; +} + +function parse(source: string, index = 0, group = false): [MathNode[], number] { + const nodes: MathNode[] = []; + while (index < source.length) { + const char = source[index]; + if (group && char === "}") return [nodes, index + 1]; + if (char === "_" || char === "^") { + let children: MathNode[]; + if (source[index + 1] === "{") [children, index] = parse(source, index + 2, true); + else { + const [node, next] = atom(source, index + 1); + [children, index] = [[node], next]; + } + nodes.push({ kind: char === "_" ? "sub" : "sup", children }); + continue; + } + const [node, next] = atom(source, index); + push(nodes, node); + index = next; + } + return [nodes, index]; +} + +function render(nodes: MathNode[]): ReactNode[] { + return nodes.map((node, index) => { + if (typeof node === "string") return node; + if (node.kind === "var") return {node.text}; + const Tag = node.kind; + return {render(node.children)}; + }); +} + +/** Typeset lines of compact notation (`x_i`, `t_{a,e}`, `x^2`) as italic variables with scripts. */ +export function MathNotation({ expression }: { expression: string }) { + return ( +
+ {expression.split("\n").map((line, index) => ( + + {render(parse(line)[0])} + + ))} +
+ ); +} diff --git a/frontend/src/components/docs/docs-blocks.test.tsx b/frontend/src/components/docs/docs-blocks.test.tsx index c68a43c..c6cc8ec 100644 --- a/frontend/src/components/docs/docs-blocks.test.tsx +++ b/frontend/src/components/docs/docs-blocks.test.tsx @@ -144,26 +144,58 @@ it("offers labelled source details for narrow screens", () => { expect(html).toContain("
Publisher
Community
"); }); -it("renders readable mathematical notation with its label, without a command-copy control", () => { +it("typesets formulas with italic variables and real subscripts, without a copy control", () => { const html = renderToStaticMarkup( , ); expect(html).toContain("
Time to intersection
"); expect(html).toContain('role="math"'); - expect(html).toContain("TTIᵢ = max(0, sᵢ − x) / v̄"); + expect(html).toContain("TTIi"); + expect(html).toContain("max(0, si − x)"); + expect(html).toContain("v̄t−1"); + expect(html).not.toContain("_"); expect(html).not.toContain(" { - for (const language of ["pl", "en"] as const) { - const logic = docsContent[language].find((section) => section.id === "logic"); - expect(logic).toBeDefined(); - const html = renderToStaticMarkup(); - for (const implementedTerm of [ +it("draws a flow as ordered steps with branches and an optional cycle", () => { + const html = renderToStaticMarkup( + , + ); + expect(html).toContain("
Lifecycle
"); + expect(html.match(/
  • { + const details = (language: "pl" | "en") => + docsContent[language].find((section) => section.id === "details")!; + + it.each(["pl", "en"] as const)("renders substantive %s content", (language) => { + const html = renderToStaticMarkup(); + for (const term of [ "STANDARD_FALLBACK", "PRIORITY_GREEN", "its_ack_timeout_seconds", @@ -171,8 +203,24 @@ it("renders the in-app system logic reference as substantive content in both lan "estimated_standard_time_sec", "MIXED", ]) - expect(html).toContain(implementedTerm); - expect(html.match(/role="math"/g)?.length).toBeGreaterThan(5); - expect(html).toContain("<= 25"); - } + expect(html).toContain(term); + }); + + it.each(["pl", "en"] as const)("keeps at most five core formulas in %s", (language) => { + const formulas = details(language).blocks.filter((block) => block.kind === "formula"); + expect(formulas.length).toBeGreaterThanOrEqual(4); + expect(formulas.length).toBeLessThanOrEqual(5); + }); + + it.each(["pl", "en"] as const)("draws its lifecycles as flows, not text, in %s", (language) => { + const kinds = details(language).blocks.map((block) => block.kind); + expect(kinds).not.toContain("state"); + expect(kinds.filter((kind) => kind === "flow").length).toBeGreaterThanOrEqual(3); + }); + + it("starts without the audit preamble", () => { + expect(details("en").blocks[0].kind).not.toBe("paragraph"); + expect(JSON.stringify(details("en"))).not.toContain("This reference describes"); + expect(JSON.stringify(details("pl"))).not.toContain("Ten opis odtwarza"); + }); }); diff --git a/frontend/src/components/docs/docs-workspace.test.tsx b/frontend/src/components/docs/docs-workspace.test.tsx index c2e35ac..6265bc3 100644 --- a/frontend/src/components/docs/docs-workspace.test.tsx +++ b/frontend/src/components/docs/docs-workspace.test.tsx @@ -14,11 +14,20 @@ const english = () => ); describe("DocsWorkspace", () => { - it("names a tablist including the system logic reference", () => { + it("names a tablist including the details reference", () => { const html = english(); expect(html).toMatch(/role="tablist"[^>]*aria-label="Documentation sections"/); expect(html.match(/role="tab"/g)).toHaveLength(6); - expect(html).toMatch(/id="docs-tab-logic"[^>]*>System logic<\/button>/); + expect(html).toMatch(/id="docs-tab-details"[^>]*>Details<\/button>/); + expect(html).not.toContain("System logic"); + }); + + it("credits both authors in a footer linking their GitHub profiles", () => { + const footer = english().match(/