diff --git a/README.md b/README.md index 18c6df8..87e8190 100644 --- a/README.md +++ b/README.md @@ -32,9 +32,20 @@ supported vehicle modules. profile-verified identity and keeps expected/probed/identified counts distinct. Read/clear actions remain gated on verified identity. Step-03 as a whole remains subject to manual orchestrator acceptance. +- Step-04 adds immutable versioned dynamics configurations, a fixed-step + coupled synthetic engine/transmission/longitudinal model, an explicit + `autoforge.simulation.dynamics` provider using protocol v2, configuration + import/export, lifecycle/scenario controls, and source/unit/model-time-aware + telemetry at `/simulation`. Step-04A corrects typed reference-validation + failures, drivetrain/rev-limit consistency, monotonic phase/overall progress, + terminal-failure telemetry/UI behavior, and single-owner cancellable pacing. + The static provider and protocol v1 remain separate. See the historical + Step-04 report and corrective Step-04A report for their distinct evidence; + neither worker report claims orchestrator acceptance. - UI routes: `/` foundation, `/execution-targets` explicit metadata selection, `/vehicle-profiles` explicit profile import/revision selection/inspection/export, - `/diagnostics` synthetic diagnostics, and a visible not-found route. + `/diagnostics` static synthetic diagnostics, `/simulation` dynamics, and a + visible not-found route. - Capability declarations distinguish Supported, Unsupported, Unknown, Inaccessible and Restricted. Missing declarations are explicitly Unknown. Provenance and all profile facts are supplied metadata, not independently @@ -49,16 +60,21 @@ supported vehicle modules. ### In progress -Manual orchestrator review and acceptance of the Step-03B correction report; -the worker's native baseline smoke and Release verification are complete. +Manual orchestrator review and acceptance of Step-03B remain pending. Step-04 +was returned for correction; Step-04A corrective implementation, regression +coverage and native smoke are recorded separately. Manual orchestrator +acceptance of Step-04 remains pending. Step-04B further corrects +side-effect-free Start/Resume rejection during prior-owner cleanup; its worker +evidence is in the [Step-04B corrective report](prompts/Step-04B-Report.md) +and does not imply Step-04 acceptance. ### Planned -Vehicle dynamics/scenarios, telemetry recording/replay, calibration values/ -editing/backups, AI and real hardware operations require later approved -assignments. This Step-03 virtual protocol is explicitly synthetic and does not -provide vehicle compatibility, physical access or authorization. No capability -is implemented merely because it appears in the product vision or roadmap. +Telemetry recording/replay, calibration values/editing/backups, AI and real +hardware operations require later approved assignments. Dynamics estimates are +synthetic, not manufacturer prediction, vehicle compatibility, physical access, +safe tuning advice or authorization. No capability is implemented merely +because it appears in the product vision or roadmap. ## Architecture @@ -70,11 +86,12 @@ modular monolith, and Core remains platform-neutral. There is no backend, browser-hosted WASM shell, Blazor Server host or second application executable. The application slices provide explicit target metadata resolution, -vehicle-profile metadata import/list/select/export, and simulation-only -diagnostic sessions. The Client composes the actual synthetic provider through -the provider-neutral factory contract and a session-lifetime in-memory profile -catalog. Import never auto-selects or replaces an existing profile revision; -metadata resolution never opens a session. +vehicle-profile metadata import/list/select/export, dynamics configuration +catalog/import/export, and simulation-only diagnostic sessions. The Client +composes separate static and dynamics synthetic providers through +provider-neutral factory contracts and a session-lifetime in-memory profile/ +configuration catalog. Import never opens a session; metadata resolution never +opens a session or starts a run. ```mermaid flowchart TD @@ -104,10 +121,12 @@ Core and Application own their behaviors under feature-focused source folders: - `AutoForge.Application/Features/ExecutionTargets/SelectExecutionTarget` - `AutoForge.Application/Features/Vehicles/Profiles` - `AutoForge.Application/Features/Vehicles/Diagnostics` +- `AutoForge.Application/Features/Vehicles/Simulation` - `AutoForge.Diagnostics` (provider-neutral protocol, transport/session contracts) -- `AutoForge.Simulation` (data-driven virtual modules and synthetic transport) +- `AutoForge.Simulation` (data-driven virtual modules, fixed-step engine and transports) - `AutoForge.UI/Features/Vehicles/Profiles` - `AutoForge.UI/Features/Vehicles/Diagnostics` +- `AutoForge.UI/Features/Vehicles/Simulation` No mediator, generic repository layer, database, or empty future feature is required. See the [schema-v1 profile guide](docs/vehicle-profile-schema-v1.md) @@ -132,7 +151,7 @@ AutoForge/ AutoForge.Core/ Platform-neutral domain invariants AutoForge.Application/ In-process application feature slices AutoForge.Diagnostics/ Provider-neutral diagnostic protocol/contracts - AutoForge.Simulation/ Synthetic virtual-module provider/transport + AutoForge.Simulation/ Static modules, dynamics engine and transports tests/ AutoForge.UnitTests/ AutoForge.IntegrationTests/ @@ -176,6 +195,7 @@ acceptance remains the orchestrator's responsibility. - [Documentation index](docs/README.md) - [Architecture and project graph](docs/architecture.md) - [Synthetic diagnostics protocol v1](docs/synthetic-diagnostics-v1.md) +- [Synthetic diagnostics protocol v2](docs/synthetic-diagnostics-v2.md) - [Simulation definitions and state](docs/simulation.md) - [Vehicle-profile schema v1 and usage](docs/vehicle-profile-schema-v1.md) - [Build, tests and native smoke guide](docs/build-and-test.md) @@ -190,8 +210,10 @@ acceptance remains the orchestrator's responsibility. - [Step-03 worker report](prompts/Step-03-Report.md) - [Step-03A corrective worker report](prompts/Step-03A-Report.md) - [Step-03B corrective worker report](prompts/Step-03B-Report.md) +- [Step-04 worker report](prompts/Step-04-Report.md) +- [Step-04A corrective worker report](prompts/Step-04A-Report.md) - [Orchestrator-owned roadmap](prompts/ROADMAP.md) and [orchestration state](prompts/STATE.md) -Handoffs are manual. Step-03 worker completion does not mean orchestrator -acceptance or authorize Step-04. +Handoffs are manual. Worker completion does not mean orchestrator acceptance or +authorize Step-05. diff --git a/docs/README.md b/docs/README.md index cc88d24..82c886e 100644 --- a/docs/README.md +++ b/docs/README.md @@ -1,17 +1,22 @@ # AutoForge documentation The implemented scope includes the accepted Step-01/Step-01A foundation, -accepted Step-02/Step-02A vehicle-profile metadata, and the Step-03 synthetic -diagnostic vertical slice with the Step-03A integrity/verification corrections. -Worker completion/verification is reported separately from manual orchestrator -acceptance; Step-03 is not accepted until that review. +accepted Step-02/Step-02A vehicle-profile metadata, the Step-03 synthetic +diagnostic vertical slice with its integrity corrections, and the Step-04 +synthetic dynamics implementation and Step-04A corrective work. Step-04A +Release regression and native workflow smoke passed; manual orchestrator +acceptance of Step-04 remains pending. - [Architecture](architecture.md): actual nine-project graph, responsibilities, route ownership and provider/reference boundaries. - [Synthetic diagnostics protocol v1](synthetic-diagnostics-v1.md): request and response envelope, outcomes, validation, logical timing and bounded trace. +- [Synthetic diagnostics protocol v2](synthetic-diagnostics-v2.md): explicit + run/configuration-bound dynamic telemetry while retaining strict v1 static + behavior. - [Simulation definitions and state](simulation.md): profile binding, module - inventory, service declarations, per-session DTC state and deterministic faults. + inventory, fixed-step model, configuration identity, scenario and protocol + boundaries. - [ADR-0001: Headless .NET 10 foundation](adr-0001-headless-foundation.md): historical foundation decisions; dual-shell/deferred-host decision superseded. - [ADR-0002: Single native shell and feature slices](adr-0002-single-shell-vsa.md): @@ -33,5 +38,8 @@ historical/worker reports for their own execution evidence: [Step-02](../prompts/Step-02-Report.md), [Step-02A](../prompts/Step-02A-Report.md) and [Step-03 worker report](../prompts/Step-03-Report.md), -[Step-03A corrective worker report](../prompts/Step-03A-Report.md). +[Step-03A corrective worker report](../prompts/Step-03A-Report.md), +[Step-03B corrective worker report](../prompts/Step-03B-Report.md), and +[Step-04 worker report](../prompts/Step-04-Report.md) and +[Step-04A corrective worker report](../prompts/Step-04A-Report.md). Handoffs are manual; acceptance remains the orchestrator's responsibility. diff --git a/docs/architecture.md b/docs/architecture.md index 72b306b..816ad61 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -37,10 +37,10 @@ All nine projects are in [AutoForge.slnx](../src/AutoForge.slnx): | Project | Target and responsibility | Project references | |---|---|---| -| [Core](../src/AutoForge.Core/AutoForge.Core.csproj) | `net10.0`; platform-neutral target and immutable vehicle-profile/module/capability/provenance invariants | None | -| [Diagnostics](../src/AutoForge.Diagnostics/AutoForge.Diagnostics.csproj) | `net10.0`; provider/session/transport contracts, synthetic protocol v1 codec/client, typed operation results and bounded trace | Core | -| [Simulation](../src/AutoForge.Simulation/AutoForge.Simulation.csproj) | `net10.0`; validated data-driven virtual modules, isolated state, provider factory and deterministic in-process transport | Core, Diagnostics | -| [Application](../src/AutoForge.Application/AutoForge.Application.csproj) | `net10.0`; target/profile/diagnostic-session feature slices | Core, Diagnostics | +| [Core](../src/AutoForge.Core/AutoForge.Core.csproj) | `net10.0`; platform-neutral target/profile invariants and immutable dynamics configuration/status contracts | None | +| [Diagnostics](../src/AutoForge.Diagnostics/AutoForge.Diagnostics.csproj) | `net10.0`; provider/session/transport/control contracts, strict synthetic protocol v1/v2 client, typed results and bounded trace | Core | +| [Simulation](../src/AutoForge.Simulation/AutoForge.Simulation.csproj) | `net10.0`; validated static modules, fixed-step engine, isolated state, explicit provider factories and transports | Core, Diagnostics | +| [Application](../src/AutoForge.Application/AutoForge.Application.csproj) | `net10.0`; target/profile/diagnostic-session and dynamics-configuration feature slices | Core, Diagnostics | | [Components](../src/AutoForge.Components/AutoForge.Components.csproj) | `net10.0` RCL; generic `StatusNotice` with accessible tone and safe text rendering | None | | [UI](../src/AutoForge.UI/AutoForge.UI.csproj) | `net10.0` RCL; all application routes, navigation, layout and presentation | Application, Components, Diagnostics | | [Client](../src/AutoForge.Client/AutoForge.Client.csproj) | `net10.0-windows10.0.26100.0`; only MAUI Blazor Hybrid application executable | Application, Simulation, UI | @@ -50,14 +50,19 @@ All nine projects are in [AutoForge.slnx](../src/AutoForge.slnx): Components has no AutoForge project dependency. UI never references Client or Simulation. Application never references Simulation, UI, Components or Client. Core, Diagnostics and Simulation do not reference Application/UI/Client. -Simulation's internal test oracle is available only to the integration-test -assembly; it is not part of the production diagnostics or UI contract. There are +The static provider's DTC oracle is limited to IntegrationTests; the fixed-step +engine test surface is limited to UnitTests. Neither is part of production +Application/Diagnostics/UI contracts. There are no cycles or production-to-test edges. Tests render UI directly and never reference or launch Client. -The Client composes one `SimulatedDiagnosticTransportFactory` with both truck and -orchard definitions. `AddAutoForgeDiagnostics` registers that factory's target -descriptor and operational transport from the same registration data. Target +The Client composes the unchanged static `SimulatedDiagnosticTransportFactory` +and the separate `DynamicsDiagnosticTransportFactory`. The static provider +remains `autoforge.simulation.synthetic` and uses strict protocol v1; the dynamics +provider is `autoforge.simulation.dynamics` and requires an explicit versioned +configuration, run identity, control capability and protocol-v2 frames. +`AddAutoForgeDiagnostics` registers both factory descriptors from the same +factory registrations used for transport resolution. Target metadata resolution remains a separate, metadata-only action. The profile catalog is process-local; importing does not select a revision or open a session. Replay and physical kinds have no operational implementation and are never @@ -73,7 +78,8 @@ assembly, not the native Client assembly. | `/` | `Features/Foundation/Home.razor` | Describes the synthetic diagnostic workflow and distinguishes it from dynamics and physical operations | | `/execution-targets` | `Features/ExecutionTargets/SelectExecutionTarget/ExecutionTargetSelectionPage.razor` | Explicitly resolves registered provider metadata only; does not open a session | | `/vehicle-profiles` | `Features/Vehicles/Profiles/VehicleProfilesPage.razor` | Explicit schema-v1 import, exact revision selection, metadata/provenance inspection and read-only export | -| `/diagnostics` | `Features/Vehicles/Diagnostics/DiagnosticsPage.razor` | Explicit saved profile/revision/provider/kind selection, session lifecycle, separate expected/probed/identified counts, retained partial probe services, identity-gated DTC/static signal operations, clear acknowledgement plus fresh-empty-readback verification, and raw/decoded trace | +| `/diagnostics` | `Features/Vehicles/Diagnostics/DiagnosticsPage.razor` | Explicit saved profile/revision/provider/kind selection, static-v1 session lifecycle, separate expected/probed/identified counts, retained partial probe services, identity-gated DTC/static signal operations, clear acknowledgement plus fresh-empty-readback verification, and raw/decoded trace | +| `/simulation` | `Features/Vehicles/Simulation/SimulationPage.razor` | Explicit profile/config/provider selection, JSON import/export, stopped-by-default dynamics session, lifecycle/step/pacing/scenario controls, and source/unit/quality/model-time/config/run-aware telemetry over diagnostic protocol v2 | | Any unmatched route | `Features/Foundation/NotFoundPage.razor` via UI `Routes.razor` | Explicit not-found page and supported navigation | The generic [StatusNotice](../src/AutoForge.Components/StatusNotice.razor) @@ -90,10 +96,12 @@ advertised services alone never enable identity-dependent read/clear actions. The feature-local target-selection view model adapts explicit input to the existing Application resolver. The same target resolver is populated from the diagnostic factories' descriptors, so `/execution-targets` shows the actual -provider metadata without implying connection. Diagnostic sessions bind the -exact profile revision, vehicle, target and deterministic profile-configuration -identifier. Closing releases per-session state; resetting closes and opens a -new session at the definition's configured initial state. +provider metadata without implying connection. Static sessions bind the exact +profile revision, vehicle and target. Dynamics identity additionally binds the +versioned configuration fingerprint and a separate operational run/session +identifier. Closing releases per-run engine, control and transport state; +reset opens a new session using the exact configuration snapshot held by the +original session, not a newer catalog selection. The Application session use case keeps low-level `clear.dtcs` acknowledgement distinct from verified clear. It performs a fresh read and only marks the @@ -116,26 +124,28 @@ schema-v1 JSON interchange and an in-memory catalog with exact unchanged. `AutoForge.Diagnostics` defines provider-neutral endpoint, transport, session, -protocol-client, logical-clock, operation-result and trace contracts. Its -synthetic protocol v1 encodes each request and decodes each actual response -through the transport interface. `AutoForge.Simulation` supplies the only -operational implementation in this milestone. Module IDs, endpoint addresses, -identities, supported synthetic services, initial DTC state, static signals and -deterministic faults come from validated source-controlled definitions, not -hard-coded application roles or profile capability claims. Details and honest -limitations are in the [protocol guide](synthetic-diagnostics-v1.md) and -[simulation guide](simulation.md). +protocol-client, logical-clock, operation-result, dynamics-control and trace +contracts. Protocol v1 remains the static diagnostics wire path. Protocol v2 is +an explicit dynamic telemetry path with a separate run/configuration-bound +payload; neither path dispatches through the other provider. Simulation owns +the numerical engine and diagnostic transports. Application owns configuration +import/export/catalog and session coordination; UI consumes shared controls and +diagnostic results only. The profile/module IDs, endpoint addresses and +identities are validated against the exact selected profile. See the [v1 +guide](synthetic-diagnostics-v1.md), [v2 guide](synthetic-diagnostics-v2.md) +and [simulation guide](simulation.md). ## Honest limitations and safety boundaries -Implemented diagnostics are synthetic, in-process and Simulation-only. They -prove the encoded request/response path and deterministic module behavior, not -vehicle compatibility, access, authenticity, real capture or permission. -Telemetry is a static synthetic state snapshot, not vehicle dynamics. Virtual -DTC clear mutates only the selected in-memory virtual module/session and has no -physical write path. Acknowledgement alone is not evidence that virtual state -changed. No real vehicle, physical adapter, replay provider, -programming, calibration values, backups, AI, persistence or cloud service is +Implemented diagnostics and dynamics are synthetic, in-process and +Simulation-only. They prove encoded request/response handling and deterministic +model behavior, not vehicle compatibility, access, authenticity, real capture, +manufacturer accuracy or permission. Static v1 signals remain static. Protocol +v2 dynamic telemetry is computed from an explicitly configured simplified +model; it is not real sensor data or validated prediction. Virtual DTC clear +mutates only selected in-memory module/session state and has no physical write +path. No real vehicle, physical adapter, replay provider, programming, +calibration values, backups, AI, durable persistence or cloud service is implemented. A `SUPPORTED` declaration, `VERIFIED` provenance label, physical metadata kind or calibration reference does not implement or authorize an operation. diff --git a/docs/build-and-test.md b/docs/build-and-test.md index 7f5c4cc..1ec4003 100644 --- a/docs/build-and-test.md +++ b/docs/build-and-test.md @@ -102,6 +102,48 @@ used a session-local WebView debug port on the worker-launched Client; partial identity remains covered by real-DI rendered tests because the shipped native configuration has no fault selector for that scenario. +## Step-04 fixed-step dynamics verification + +The Step-04 Release regression ran sequentially against the full solution: + +```powershell +dotnet build .\src\AutoForge.slnx --configuration Release --no-restore +dotnet test .\src\AutoForge.slnx --configuration Release --no-build +``` + +The native Windows-targeted build covered all nine solution projects with zero +warnings/errors. The complete test command passed 115 unit and 75 integration +tests (190 total, zero failed/skipped), preserving the Step-03B 183-test +baseline. The unit numerical gate executes 3,361 deterministic 0.1-second +samples and compares full sampled state across equal runs. The baseline results +were: 10.0 s warm idle at 650.000 rpm; acceleration to 20.1473 m/s in 10.3 s +with four scheduled shifts; all 3,000 cruise samples inside the configured +45-MPH +/- 1-MPH band and fully coupled; braking to 0.0000 m/s in 5.8 s; 10.0 s +return idle; and 0.518387 kg modeled total fuel. These are synthetic model +outputs, not measured vehicle performance or manufacturer predictions. + +The actual Windows Client was launched with WebView2 local DevTools enabled for +the native smoke. `/simulation` required explicit selection of profile +`autoforge.synthetic.test-truck` revision 1, provider +`autoforge.simulation.dynamics`, and a configuration with fingerprint +`sha256:v1:e8991ae139b54959ec53a4fe64b08dc9bfc03feb533496cf741f2c9f3a2342da`. +Export/import preserved that fingerprint. A stopped open session returned 17 +protocol-v2 dynamic telemetry values at step 4 / 0.4 model seconds after explicit +start/pause/step controls. The accelerated full scenario completed at step +3,361 / 336.1 model seconds with 17 telemetry values and four shifts. Invalid +`{}` import visibly reported the missing required `formatVersion`; exact-config +reset opened a new session at step 0 with the same fingerprint, and close +released it. + +The native `/diagnostics` regression separately selected the original +`autoforge.simulation.synthetic` provider, discovered two positive probes out +of three expected endpoints (the transmission remained configured no-response), +and read the original engine DTC plus static 850-rpm and 12.6-V signals through +protocol v1 with trace records. The session was closed. Native route smoke +covered `/execution-targets` (both providers remain metadata), `/vehicle-profiles`, +`/`, and an unmatched not-found route. Numerical fidelity and reproducibility +are established by headless tests, not by visual telemetry. + ## Native synthetic diagnostics smoke Launch the actual Windows Client and visit `/diagnostics`: @@ -156,7 +198,91 @@ unknown-value, capability, provenance and strict JSON rules. Important invariant metadata, not connection, compatibility, a working service or authorization. - Data remains in memory for the process only. JSON import/export does not write files or timestamps implicitly. -- Simulation uses the separate [synthetic protocol](synthetic-diagnostics-v1.md) - and [definition guide](simulation.md). It is not a real vehicle adapter, - dynamics model, telemetry capture, replay provider, calibration/firmware - editor or hardware write path. +- Static synthetic diagnostics use the [protocol v1 guide](synthetic-diagnostics-v1.md) + and [simulation definitions](simulation.md); dynamic output uses the separate + documented protocol-v2 provider. Neither is a real vehicle adapter, telemetry + capture, replay provider, calibration/firmware editor or hardware write path. + +## Step-04A corrective verification + +Step-04A corrects typed import errors for unavailable profile/revision/module or +conflicting calibration references, enforces the supported coupled RPM/redline +envelope, and makes progress, terminal failure and asynchronous runner ownership +explicit. It adds seven unit and five integration cases over the 190-case +Step-04 baseline. The final sequential commands were: + +`dotnet build .\src\AutoForge.slnx --configuration Release --no-restore` + +`dotnet test .\src\AutoForge.slnx --configuration Release --no-build` + +The nine-project Windows Release build succeeded with zero warnings and zero +errors. The full test command passed 122 unit and 80 integration tests (202 +total; zero failed/skipped). The warm baseline remains reproducible at 3,361 +samples / 336.1 virtual seconds; 10.0 s warm idle at 650 rpm, 10.3 s acceleration +to 20.1473 m/s with four shifts, all 3,000 cruise samples in the original +45-MPH +/- 1-MPH band while coupled, braking to 0.0000 m/s in 5.8 s, 10.0 s +return idle, and 0.518387 kg modeled fuel. The added independent constant-torque +force/mass equation and speed-step equation checks use a `1e-10` acceleration +tolerance; independent locked RPM checks use `1e-8` rpm. + +Controlled-pacer unit tests exercised active pause/freeze, resume, stop, reset, +restart, cancellation and disposal without wall-timer polling. Equivalent full +scenario samples were identical at 0.25x and 1000x; only requested pacing delay +changed. Rendered integration tests covered typed/atomic profile, revision and +module import failures; a persistent 0.1-second deadline failure and negative +`DYNAMICS_RUN_FAULTED` response; UI run reentrancy; and stale-run suppression +across reset, close, reopen and delayed open. + +Headless numerical/integration coverage also accepts a finite but extreme +torque/gear vector that overflows modeled power during launch. The engine +rolls back to its last finite state/sample, marks the lifecycle Faulted, and the +real v2 session returns a negative `DYNAMICS_RUN_FAULTED` response rather than +encoding poisoned values. + +The rebuilt Windows Client was launched at +`src/AutoForge.Client/bin/Release/net10.0-windows10.0.26100.0/win-x64/AutoForge.Client.exe` +and operated through its local WebView2 session. Import of unknown profile, +revision and module references showed recoverable error notices without +changing the selected valid configuration. The short-deadline run visibly ended +Faulted at step 101 / 10.1 model seconds; the failure remained visible after a +dynamic diagnostic read and previously good telemetry rows were cleared. A +valid baseline run completed at step 3,361 / 336.1 model seconds. The active +runner was then paused and held at step 1 while waiting, resumed, stopped, +explicitly stepped, reset to a new step-0 session, read 17 `SYNTHETIC_DYNAMIC` +values at step 0, exported/re-imported the configuration, and closed. The +`/diagnostics`, `/vehicle-profiles`, `/execution-targets`, `/`, and unmatched +not-found routes loaded. The launched Client and its local DevTools listener +were closed and verified absent afterward. + +The Step-04 worker report remains historical; the corrective evidence is in the +[Step-04A report](../prompts/Step-04A-Report.md). Manual orchestrator acceptance +of Step-04 remains pending. All model and telemetry values remain synthetic. + +## Step-04B owner-drain corrective verification + +Start and resume now reject before changing lifecycle state when a previous +advancement owner is still cleaning up after pause, stop or reset. The real +simulation page reports that rejection as an error rather than a successful +start/resume. Controlled barrier tests reproduced the prior defect: while the +cancelled owner was held in cleanup, Pause-to-Resume changed `Paused` to +`Running`, Stop-to-Start changed `Stopped` to `Running`, and Reset-to-Start +changed `Stopped` at step 0 to `Running`. After the guard, all three complete +status snapshots and sample counts remain unchanged on rejection; releasing +cleanup then permits exactly one retry and one new fixed step. + +The final sequential Release build covered all nine solution projects and +succeeded with zero warnings and zero errors. The full solution test command +passed 126 unit and 81 integration tests (207 total; zero failed/skipped), +preserving all 202 Step-04A cases. Focused owner-drain regressions passed 4 +unit and 2 integration tests. See the [Step-04B corrective report](../prompts/Step-04B-Report.md) +for exact commands and detailed contract evidence. + +The actual native Windows Client smoke exercised start, active pause/resume, +stop/restart, reset, protocol-v2 telemetry read and close. It confirmed stable +paused/stopped steps, a reset session at step 0, `SYNTHETIC_DYNAMIC` telemetry, +and release of the closed session. This manual UI smoke does not claim to force +the cleanup interleaving; that exact race is established by the controlled +headless tests. The Client and its task-local WebView2 debug listener/profile +were stopped and cleaned up. Step-04 remains pending manual orchestrator +acceptance; the prior numerical thresholds and synthetic-only scope are +unchanged. diff --git a/docs/simulation.md b/docs/simulation.md index fd6a9e6..74d5edd 100644 --- a/docs/simulation.md +++ b/docs/simulation.md @@ -70,8 +70,170 @@ Replies carry the logical request tick and origin `SYNTHETIC_STATIC`. These are reproducible fixture values, not dynamic model output, current sensor data, a vehicle capture, compatibility evidence or operational advice. Unknown -values remain unknown; there is no generated motion, fuel, road-load or -scenario physics. +values remain unknown. This static provider does not generate motion, fuel, +road-load or scenario physics; those capabilities are isolated in the explicitly +selected dynamics provider below. + +## Fixed-step dynamics configuration + +The separate `DynamicsConfiguration` document is format version 1 and model +version 1; it does not change profile schema v1. It binds an exact profile ID, +revision, vehicle ID, engine/transmission module IDs and calibration references +to explicit model parameters, initial conditions, and five ordered finite +scenario phases. Configuration JSON uses exact camelCase member names, string +scenario enums, and strict required/unknown/duplicate-member validation at every +object level. Missing values are not defaulted. Input ranges include fixed +steps from 0.01 to 0.5 s, mass 100-100,000 kg, wheel radius 0.05-2 m, drag area +0-20 m2, rolling coefficient 0-0.2, ambient density 0.1-2 kg/m3, gravity 1-20 +m/s2, engine speed up to 12,000 rpm, 2-12 strictly descending positive forward +gear ratios, and finite strictly increasing torque-curve points. Scenario speeds +are bounded at 150 m/s and durations at 86,400 s; the cruise phase must be at +least 300 s and return-idle at least 10 s. Initial conditions are copied and +validated against the model and exact profile. + +The `sha256:v1:` configuration identifier is SHA-256 over stable +camelCase JSON serialization of the immutable configuration (the derived +identifier itself is omitted). The catalog is in-memory. Import validates exact +profile/module/calibration references before registration; export followed by +import preserves the identifier. A diagnostic run ID is separate from this +stable configuration fingerprint and is bound into its session identity. +Reset closes the existing session and opens a new one with the exact original +immutable configuration object, regardless of later catalog selections. + +The explicit warmed example uses SI units internally: + +| Input | Value | +|---|---:| +| Fixed virtual step | 0.1 s | +| Vehicle mass | 1,800 kg | +| Wheel radius | 0.34 m | +| Aerodynamic drag area (CdA) | 0.68 m2 | +| Rolling resistance coefficient | 0.012 | +| Air density / gravity | 1.2 kg/m3 / 9.80665 m/s2 | +| Drivetrain efficiency / final drive | 0.9 / 3.6 | +| Maximum brake force | 10,000 N | +| Idle / warm target / maximum engine speed | 650 / 650 / 5,000 rpm | +| Launch slip end speed | 2.5 m/s | +| Idle fuel flow / fuel mass per joule | 0.00045 kg/s / 1.2e-7 kg/J | +| Ambient / initial / equilibrium engine temperature | 20 / 88 / 90 degC | +| Thermal response rate | 0.015 per second | +| Forward gear ratios | 3.5, 2.2, 1.4, 0.9 | +| Upshift / downshift schedules | 4,000 / 1,450 rpm per gear | + +Torque curve points are `(rpm, N*m)`: `(650,240)`, `(1000,300)`, +`(2000,360)`, `(3200,350)`, `(4200,300)`, `(5000,180)`. Torque is linearly +interpolated between points and held at endpoint values outside the curve. +Automatic shifts use the configured schedule and hysteresis; launch coupling +slip is limited to first gear below the configured launch speed. When locked, +reported engine speed follows + +`engineRPM = speed_mps / (2*pi*wheelRadius_m) * 60 * gearRatio * finalDrive`. + +The launch torque-transfer factor is speed-based and is not the reported slip +fraction. Reported slip is the normalized engine/wheel RPM discrepancy, so it +cannot claim zero slip when those speeds differ. Wheel force is +`engineTorque * gearRatio * finalDrive * efficiency / wheelRadius * +couplingFactor`. Rolling and aerodynamic loads are `m*g*Crr` and +`0.5*rho*CdA*v^2`; brake force is configured maximum force times brake ratio. +Longitudinal acceleration is `(wheelForce - roadLoad - brakeForce)/mass`. +Each fixed step updates speed using forward Euler with a zero lower bound; +distance uses trapezoidal integration of the old/new nonnegative speed. Scenario +controllers adjust bounded throttle/brake commands but never assign vehicle +speed. + +An initial running in-gear condition is supported only when engine RPM equals +the wheel/gear-derived RPM within `1e-8` rpm and remains within the engine +limits. The initial-condition contract does not invent an unprovided clutch-slip +input. Scenario targets and initial speed must also fit the top-gear redline +envelope: + +`maximumEngineRPM * (2*pi*wheelRadius) / (60*topGearRatio*finalDrive)`. + +The engine does not independently clamp RPM while keeping an unchanged, +contradictory wheel speed. The phase throttle is instead bounded to the target +speed/redline envelope for each fixed step. Inputs outside the documented +envelope fail validation rather than producing healthy contradictory telemetry. + +Fuel power is `torque * engineAngularVelocity`; fuel rate is idle flow plus +nonnegative power times the configured mass-per-joule coefficient. Fuel and +distance integrate from the fixed step. Engine-off RPM/fuel are zero. The +thermal approximation is a first-order response toward the greater of ambient +and configured equilibrium temperature, with a bounded additional target +increase from modeled power; it is not coolant-flow or component simulation. +All model state is checked for finiteness/domain violations and a failed run is +explicitly marked `Faulted`. An arithmetic/domain failure rolls state and +samples back to the last valid fixed-step snapshot before publishing the +terminal reason. + +Configuration import converts unavailable profile/revision, missing module and +calibration-conflict references to the typed configuration-validation error +contract. Validation precedes catalog registration; a rejected import preserves +the selected configuration and any active run binding. + +The ordered baseline scenario has 10 s warm idle, acceleration to 20.1168 m/s +(45 MPH) with a 60 s maximum, a full 300 s target-speed hold, braking to 0.1 m/s +with a 60 s maximum, and at least 10 s stationary return-idle. Headless stepping +uses virtual steps only. `RunScenarioAsync` has an optional real-time pacer; +0.25x-1000x changes delay scheduling only, not the numerical step. Start, +pause, resume, stop, reset, and explicit stopped/paused stepping are serialized. +Diagnostic reads never advance model state. The numerical test independently +checks the 650 +/- 5 rpm idle gate, 45 MPH <=60 s with shift activity, all 3,000 +cruise samples with >=95% inside +/-0.44704 m/s, coupled cruise RPM relation, +braking/return-idle limits, finite/nonnegative monotonic fuel, and exact +same-input sampled-state reproducibility. Exact run outputs are recorded in +the Step-04 worker report. + +Overall scenario progress is cumulative elapsed scenario time divided by total +configured phase duration; completed phase duration is retained across phase +transitions. Current-phase progress is elapsed time divided by that phase's +configured duration and is displayed separately. Both are bounded to `[0,1]`; +reset starts both at zero and successful completion sets both to one. A missed +phase target by its deadline ends in `Faulted` with the phase and reason +preserved. Faulted dynamic signal reads return protocol-v2 negative response +`DYNAMICS_RUN_FAULTED`, not a positive `Good` snapshot. The UI preserves the +failure notice and clears previously good telemetry rows so they are not +mistaken for a current healthy sample. + +Each running controller owns one cancellable advancement task. Start/resume +performs the first fixed step and then waits on the configured pacer; pacing +changes delay only. Pause, stop, reset and dispose cancel and await that owner +before returning, so a pending delay cannot advance a stale session. The +simulation project exposes a narrow `IDynamicsPacer` seam for deterministic +controlled-scheduler tests; it is not a general clock framework. UI operations +also guard session/run generations after awaits. A stale open/reset/run result +is discarded and disposed rather than published into a later session. + +Start and resume validate that no prior advancement owner remains active or is +settling before changing lifecycle state. If pause, stop or reset has cancelled +an owner but its cleanup has not completed, a concurrent start/resume is +rejected immediately with an explicit error and leaves lifecycle, model time, +step, progress, configuration and ownership unchanged. The caller can retry +after the cancelling operation completes. The command gate is not held while +waiting for runner cleanup, so the owner can finish its cleanup path. + +## Static versus dynamic diagnostic providers + +The existing `autoforge.simulation.synthetic` provider remains the static +protocol-v1 baseline, including its fixed 850 rpm engine signal, original fault +behavior and original tests. Dynamics is a separate +`autoforge.simulation.dynamics` factory requiring `OpenDynamicsAsync` and an +exact selected configuration; the static-open path cannot acquire dynamics +controls. It exposes only the configured engine and transmission endpoint map. +The engine and transmission telemetry are both snapshots from the same +thread-safe engine state. While paused/stopped, reads across modules preserve +the step/time; while the runner is active, each response advertises its actual +sample step/time rather than pretending multiple requests are simultaneous. +Each dynamic signal carries source module, unit, quality, `SYNTHETIC_DYNAMIC` +origin and model/config/run metadata. Diagnostic capture ticks remain separate +from the model clock. See [protocol v2](synthetic-diagnostics-v2.md) for wire +fields and strict validation. + +The `/simulation` route requires explicit profile revision, dynamics provider +and configuration selection. User-triggered example creation/import does not +open or start a run. Controls and JSON interchange coordinate through +Application; the telemetry table calls the actual protocol client, not the +engine API. Values are synthetic behavior, not firmware, calibration, safe +tuning guidance, validated manufacturer prediction or physical vehicle data. ## Reproducible faults and lifecycle diff --git a/docs/synthetic-diagnostics-v1.md b/docs/synthetic-diagnostics-v1.md index 0473f1f..cff4b91 100644 --- a/docs/synthetic-diagnostics-v1.md +++ b/docs/synthetic-diagnostics-v1.md @@ -8,6 +8,12 @@ simulation transport. The frames are UTF-8 JSON. They are not CAN, ISO-TP, UDS, OBD-II, a manufacturer protocol, or a claim of vehicle compatibility. No physical transport or vehicle operation is implemented. +V1 is intentionally static. Its `SYNTHETIC_STATIC` signals retain request-start +logical-tick semantics and are not the Step-04 dynamics path. The separate +[`SYNTHETIC_DYNAMIC` protocol-v2 extension](synthetic-diagnostics-v2.md) binds +computed telemetry to an exact dynamics configuration and run; the static v1 +provider and strict v1 parsing behavior are unchanged. + The actual capability path is: 1. `SyntheticDiagnosticProtocolClient` builds and encodes a request. diff --git a/docs/synthetic-diagnostics-v2.md b/docs/synthetic-diagnostics-v2.md new file mode 100644 index 0000000..ffbe8f8 --- /dev/null +++ b/docs/synthetic-diagnostics-v2.md @@ -0,0 +1,90 @@ +# Synthetic diagnostics protocol v2: dynamics telemetry + +## Compatibility boundary + +Protocol v2 is an explicit UTF-8 JSON extension for the separate +`autoforge.simulation.dynamics` provider. It does not reinterpret or weaken +[protocol v1](synthetic-diagnostics-v1.md): `autoforge.simulation.synthetic` +continues to require v1 static semantics, including origin +`SYNTHETIC_STATIC` and the request-start logical tick. A static session cannot +acquire dynamics controls, and a dynamics session must be opened with a +validated immutable format-v1/model-v1 `DynamicsConfiguration`. This protocol +is synthetic in-process JSON, not CAN/ISO-TP/UDS/OBD-II or a manufacturer +protocol. + +The request envelope has the same required top-level fields as v1, but its +`version` is exactly `2` and its `configurationIdentifier` binds the selected +profile revision and stable dynamics fingerprint. `sessionIdentifier` and the +separate dynamics run identifier provide operational isolation. The request's +`logicalTimeTicks` is the diagnostic capture/request clock; it is not model +time. + +## Dynamic `read.signals` payload + +All v2 response envelopes retain the strict v1 envelope/correlation fields, +with `version: 2`. The `read.signals` data object has exactly these required +fields: + +| Field | Meaning | +|---|---| +| `moduleIdentifier` | Exact requested engine or transmission module | +| `configurationIdentifier` | Stable `sha256:v1:` configuration fingerprint | +| `runIdentifier` | Operational dynamics-run ID bound to this session | +| `modelStepIndex` | Nonnegative integer fixed-step count | +| `modelTimeSeconds` | Virtual model time, equal to step index times configured step seconds | +| `origin` | Exactly `SYNTHETIC_DYNAMIC` | +| `captureLogicalTimeTicks` | Diagnostic logical start tick, exactly matching the request | +| `signals` | Exact source module signal list, with identifier, JSON value, unit and quality | + +Signal identifiers and units are validated exactly. Engine signals are +`engine.running` (boolean), `engine.speed` (rpm), `vehicle.speed` (m/s), +`engine.throttle` (ratio), `engine.load` (ratio), `engine.torque` (N*m), +`engine.fuel-rate` (kg/s), `engine.fuel-consumed` (kg), +`engine.temperature` (degC), `vehicle.distance` (m), +`vehicle.acceleration` (m/s^2), and `driver.brake` (ratio). Transmission +signals are `transmission.gear` (gear), `transmission.shift-count` (count), +`transmission.coupling-slip` (ratio), `vehicle.speed` (m/s), and +`engine.speed` (rpm). Numeric dynamic values must be finite JSON numbers; +identifiers, source module, units, quality, origin and model/run/configuration +identity are retained in the typed snapshot. + +The receiver rejects duplicate/unknown/missing fields, unsupported versions, +invalid correlation/envelope identity, wrong module, unexpected dynamic signal +or unit, non-finite numeric telemetry, wrong capture tick, invalid model step/ +time, and configuration/run mismatch as `ProtocolError` with no partial value. +The configured step size is used to validate +`modelTimeSeconds = modelStepIndex * stepSeconds`. Positive replies preserve +the transport's elapsed diagnostic ticks in bounded trace timing; those ticks +remain independent from model step/time. + +Every request samples the engine once under its state lock and serializes that +snapshot. A paused or explicitly stepped run therefore returns the same +step/time from engine and transmission reads until a control step occurs. While +the asynchronous scenario pacer is running, separate requests can capture +different steps; each response reports its actual step/time and does not imply +simultaneous capture. Reads themselves never advance the engine. + +A faulted run never serializes a positive dynamic snapshot: `read.signals` +returns a correlated v2 negative response with failure code +`DYNAMICS_RUN_FAULTED` and the retained lifecycle reason. It does not replace a +failed computation with zero-valued or empty `Good` signals. The UI preserves +that terminal failure and clears any previously displayed rows so older +successful values cannot be mistaken for current post-fault telemetry. + +Probe, identity, DTC and clear service names retain their v1 service-level +shapes inside a v2 envelope. Dynamics module services are still checked against +their explicit endpoint advertisement; provider selection never falls back to +the static provider. Static protocol clients and static provider response +versions remain v1. The actual strict client and provider implementation is in +`AutoForge.Diagnostics` and `AutoForge.Simulation`; Application/UI telemetry +still traverses encoded diagnostic frames rather than a model-state oracle. + +## Limitations + +The origin means generated by this AutoForge synthetic model only. Quality +`Good` means the deterministic synthetic computation completed, not sensor +quality or real vehicle truth. The model omits detailed engine combustion, +torque-converter dynamics, tire/road conditions, gearshift transient mechanics, +thermal circuits, emissions, manufacturer calibration and uncertainty +quantification. Protocol v2 is not evidence of compatibility, prediction +accuracy, safe tuning or physical authorization. diff --git a/prompts/ROADMAP.md b/prompts/ROADMAP.md index 3789418..418bf80 100644 --- a/prompts/ROADMAP.md +++ b/prompts/ROADMAP.md @@ -3,12 +3,12 @@ ## Status and authority - Initialized: 2026-10-28. -- Current phase: corrected synthetic diagnostics accepted; deterministic dynamics next. -- Active assignment: [Step-04](Step-04.md), ready for manual worker execution. -- Last accepted milestone: Step-03 with Step-03A/Step-03B, accepted 2026-10-28. -- Last accepted correction: Step-03B; all Step-03 findings closed. +- Current phase: corrected deterministic dynamics accepted; first bounded live dashboard next. +- Active assignment: [Step-05](Step-05.md), ready for manual worker execution. +- Last accepted milestone: Step-04 with Step-04A/Step-04B, accepted 2026-10-28. +- Last accepted correction: Step-04B; all Step-04 findings closed. - Outstanding corrections: none. -- Step-04 status: READY FOR WORKER; no dynamics implementation or report yet. +- Step-05 status: READY FOR WORKER; no dashboard implementation/report yet. - Current state and handoff: [STATE.md](STATE.md). - Authority: the master charter, repository/handoff amendment, and the owner's 2026-10-28 architectural realignment. The latest decision cancels the dual-shell @@ -71,6 +71,60 @@ and `Step-01A-Report.md`, then `Step-01B.md`. Accept all necessary corrections before assigning the next major step. Do not use the superseded numeric-dot prompt/report naming convention. +## Assignment sizing and handoff policy - revised 2026-10-28 + +The owner requested an orchestration-level reassessment to reduce repeated +corrective handoffs. Longer prose and larger passing test counts have not been +enough. The changes below are prospective; they do not add acceptance criteria +retroactively to completed assignments. + +### Evidence and causes + +- Step-01A was an owner-directed architecture change, not a preventable + implementation defect. Keep that separate from quality failures. +- Steps 02-04 combined many new contracts: parsing, state/capability semantics, + protocol validation, physics, async ownership and UI integration. The default + paths could pass while invalid/partial/reentrant paths remained untested. +- Assignments described broad responsibilities but did not always supply decisive + input/outcome and transition matrices before coding. Review was discovering + those contracts too late. +- Orchestrator review also surfaced some parent-milestone cases in successive + passes. Future review must consolidate the whole assigned contract, not rely + on passing counts or accept only an attractive demonstration. + +### Changes effective for the next handoff + +1. Use [WORKER-QUALITY-GATE.md](WORKER-QUALITY-GATE.md) for all new assignments, + beginning with Step-04B. It supplements the bounded assignment and existing + manual/protected-file rules; it does not authorize agents or automation. +2. One observable user outcome and one primary new behavioral contract per + assignment. Do not combine several new formats/state machines/engines merely + because they belong to the same milestone. Integration remains end-to-end. +3. Before implementation, supply a compact contract matrix: normal, rejected, + boundary/partial, lifecycle/interleaving and UI/result outcomes where relevant. + Name exact invariants and test vectors; omit irrelevant rows with a reason. +4. The worker tests those cases, then performs its own source-path self-review + after the first green run. It fixes findings inside the active assignment + before declaring COMPLETE. Test totals are evidence of execution, not coverage. +5. Reviewer and worker use the same frozen criteria. Do not turn optional + improvements or new feature preferences into corrective requirements. + Genuine defects, regressions, safety problems and unmet existing criteria + still block acceptance, with one consolidated narrowly scoped correction. +6. Preserve manual handoff and truthful BLOCKED/INCOMPLETE reporting. No prompt + can guarantee zero defects; the goal is fewer preventable handoffs, not weaker + review or concealed failures. + +Unassigned future rows remain milestone envelopes, not a requirement to implement +their entire scope in one worker turn. If an envelope is too large, split and +update the future major-step numbering/dependencies before handoff; letters +remain reserved for actual corrections. Do not renumber completed history. + +The next dashboard milestone is narrowed to the first real configurable live +dashboard: numeric and bar displays, explicit binding/range/unit/error states +and one acquisition owner. Charts, drag/drop, complex layouts and advanced +analytics remain in the later visualization milestone. Calibration/runbook and +hardware envelopes must likewise be risk-sliced before assignment. + ## Architecture baseline ### Existing accepted foundation, preserved @@ -163,12 +217,15 @@ clear-verification findings, and Step-03B separates successful probe evidence fr identity availability. The corrected Step-03 milestone is accepted. Worker verification now covers 111 unit and 72 integration cases (183 total). -Step-04 extends the existing Simulation implementation with coupled dynamics and +Step-04 has extended the existing Simulation implementation with coupled dynamics and a fixed-step virtual clock. Shared platform-neutral configuration/control contracts belong in Core or an appropriate existing shared-contract location; Application still does not depend on Simulation implementation. No additional project is assigned. Static synthetic diagnostics remain available, separate from an -explicitly selected dynamics provider/run configuration. +explicitly selected dynamics provider/run configuration. The dynamics code is +accepted with Step-04A/Step-04B: reference handling, drivetrain invariants, +terminal/progress outcomes and controlled owner-drain rejection have been reviewed. +Worker verification now covers 126 unit and 81 integration cases (207 total). Planned dependency flow: @@ -247,9 +304,11 @@ UI unrestricted programming authority. ## Milestones and acceptance gates -Step-01, Step-01A, corrected Step-02 and corrected Step-03 are accepted. Original -and corrective reports remain historical evidence. Step-04 is the only active -assignment. Dynamics and later capabilities remain unimplemented. +Step-01, Step-01A, corrected Step-02 and corrected Step-03 remain accepted. +Corrected Step-04 is accepted with original and corrective evidence preserved. +Step-05 is the only active assignment and uses the revised bounded-scope/ +contract-matrix/worker-self-review policy. Dashboard and later capabilities +remain unimplemented. Dependencies indicate acceptance prerequisites, not permission for automatic handoff. Later assignments refine these scopes using actual implementation evidence; they must not silently discard required capabilities. @@ -263,8 +322,10 @@ evidence; they must not silently discard required capabilities. | 03 | Virtual modules and diagnostic communication | 02 and 02A accepted | ACCEPTED 2026-10-28 AFTER 03A/03B | Real synthetic wire/provider/session/virtual-state path, truthful phase discovery and verified clear; complete corrected evidence inspected | | 03A | Synthetic wire validation and verified-clear correction | 03 review findings | ACCEPTED FOR R-01/R-02/R-03 2026-10-28 | Strict wire and semantic reply validation, matching trace and Application verified clear inspected; 111 unit/64 integration passes plus native baseline reported | | 03B | Partial discovery and identification correction | 03A review finding R-04 | ACCEPTED 2026-10-28 | Independent probe/identity outcomes, retained partial services, accurate counts and fail-closed actions inspected; 183-case/native evidence reported | -| 04 | Deterministic vehicle dynamics | 03, 03A and 03B accepted | READY FOR WORKER | Explicit immutable model/run configuration, fixed-step lifecycle/scenario engine, coupled SI dynamics and diagnostic dynamic telemetry; reproducibility and numeric scenario gates | -| 05 | Live dashboard in the established Client/UI/Components architecture | 04; accepted 01A foundation | PLANNED | Feature pages select a profile, control simulation and display independently collected live telemetry through reusable Components; no new application host | +| 04 | Deterministic vehicle dynamics | 03, 03A and 03B accepted | ACCEPTED 2026-10-28 AFTER 04A/04B | Coupled numeric scenario gates, strict config/run/v2 binding, typed failures and deterministic lifecycle ownership inspected | +| 04A | Dynamics input, drivetrain and lifecycle integrity correction | 04 review findings | ACCEPTED 2026-10-28 AFTER 04B | Reference/kinematic/progress/failure/ownership corrections and independent/controlled evidence inspected | +| 04B | Side-effect-free lifecycle rejection during owner drain | Existing 04A R-03/AC-04 | ACCEPTED 2026-10-28 | Frozen five-case overlap/retry contract satisfied; 126 unit/81 integration passes, clean Release/native evidence and worker self-review supplied | +| 05 | First configurable live dashboard | 04 and corrections accepted; 01A foundation | READY FOR WORKER | Numeric/bar gauges, validated in-memory bindings/ranges/units, explicit data states and one session-owned acquisition feed; no new schema/host/charts/drag-drop | | 06 | Telemetry recording and replay | 05 | PLANNED | Persist raw messages and decoded signals with metadata; playback/seek/speed controls feed the same gauges without silently reconstructing missing data | | 07 | Calibration management and simulated programming | 06 | PLANNED | Versioned definitions/diffs, verified baseline and backup, approved simulated write, readback/unrelated-data checks, audit and supported restore; no physical writes | | 08 | Local AI, knowledge, and validated runbooks | 07 | PLANNED | Replaceable local inference, applicable knowledge retrieval, structured logical runbook, independent validation/approval and simulation-only execution | @@ -325,12 +386,22 @@ evidence; they must not silently discard required capabilities. driven physics. Preserve static v1 diagnostics and use an explicit versioned/ negotiated dynamic telemetry extension with separate model and diagnostic time. Report mathematical assumptions and repeatability tolerances. -- **05:** extend the already established UI feature pages with reusable data-bound - gauges, settings, profile/module selection, connection state and diagnostics. - Client remains thin; application slices coordinate in-process capabilities. - Use ordinary packaged RCL/feature composition, not unsupported arbitrary assembly - loading. Missing MAUI workloads are blockers, not permission to substitute a - WebAssembly/web host. Native adapters do not require a separate backend. +- **04A correction:** reject invalid references through normal typed/UI failures, + enforce initial and runtime drivetrain consistency rather than independent RPM + clamping/false locked flags, and make progress/terminal failures/async ownership + truthful. Add independent force/boundary checks and controlled pacing/lifecycle + tests; preserve the existing warm/45-MPH/full-hold/stop numerical gates. +- **04B correction:** only the existing pending-owner overlap gap: validate + Start/Resume eligibility before any lifecycle mutation while pause/stop/reset + is still draining its old task. No physics, wire, schema or UI feature expansion. +- **05:** first bounded dashboard slice: reusable numeric/bar components bound to + actual diagnostic signals, validated display configuration, explicit units and + unavailable/stale/error states, with one source/session-aware acquisition owner. + Supply a contract matrix for invalid ranges, missing signals and session + replacement before coding. No charts, drag/drop or new clock/protocol/backend. + Larger dashboard composition remains Step-11 scope. Client stays thin and no + alternate host is introduced. Dashboard configuration is in-memory only for + this slice; persistence/schema work is not bundled into the feed state machine. - **06:** versioned recording format, module/source/units/time/quality metadata, raw plus decoded retention, interrupted/corrupt session handling, replay play/pause/stop/restart/seek/navigation/speed. Acquisition must not depend on @@ -556,19 +627,80 @@ history, not repeated redesign without evidence. - Source counts, graph and existing restore/Release/native artifacts corroborate that evidence; the orchestrator did not run builds/tests or launch the app. - Prepared [Step-04](Step-04.md); no Step-03C is required. +- Reviewed completed Step-04 configuration/model/controller/provider, v2 integration, + UI, tests, documentation and worker report. Worker evidence records a clean + nine-project Release build, 115 unit + 75 integration passes (190 total, + zero failed/skipped), numerical baseline metrics and rebuilt native smoke. +- The warmed default reports 3,361 reproducible samples, 10 s idle, 10.3 s + acceleration, all 3,000 cruise samples inside the required band, 5.8 s braking + and 10 s return idle. These are worker results, not orchestrator test execution. +- Source counts, graph and existing outputs corroborate the reported run. + Acceptance was withheld at that review for the input/kinematic/lifecycle findings; prepared + [Step-04A](Step-04A.md) without changing implementation or original evidence. +- Reviewed Step-04A's reference/coupling/progress/failure/controller/UI corrections, + independent equations and controlled scheduler tests. Worker reports 122 unit + + 80 integration passes (202 total, zero failed/skipped), clean full Release build, + unchanged numerical gates and native invalid-reference/fault/baseline smoke. +- R-01/R-02 and the progress/failure/reentrancy fixes satisfy their inspected + scope. One existing R-03 overlap remains: Start/Resume mutates the engine before + StartRunnerLocked rejects an old task that has not drained. +- Prepared a single-issue [Step-04B](Step-04B.md). Also reassessed assignment sizing, + frozen contract matrices and worker self-review; added the prospective shared + quality gate rather than adding new criteria to Step-04A. +- Reviewed and accepted Step-04B against C-01 through C-05: Start/Resume/scenario + start all check owner eligibility before lifecycle mutation, rejected commands + preserve full status/sample state, cleanup can finish and one retry starts once. +- Worker reports actual three-transition pre-fix state failures, corrected + controlled unit/real UI-service tests, explicit self-review, complete Release + build zero warnings/errors and 126 unit + 81 integration passes (207 total, + zero failed/skipped). Native baseline is distinct from controlled race proof. +- Source counts, graph and existing outputs corroborate that evidence; the + orchestrator ran no application builds/tests/native commands. +- Accepted corrected Step-04 with Step-04A/04B and prepared bounded + [Step-05](Step-05.md) using the shared quality gate and frozen data/feed matrix. ### Remaining -- Worker execution of Step-04, then manual review of numeric dynamics, lifecycle, - configuration, wire integration and native evidence. Complete Step-04A corrections - if needed before Step-05. -- Profile/module metadata, synthetic virtual-module communication and static - diagnostics are accepted; dynamics and later capabilities - remain planned. Preserve the complete sequence and safety gates. +- Worker execution of Step-05, then one consolidated review against its frozen + contract matrix and shared quality gate. Complete Step-05A only for genuine + unmet requirements/regressions before Step-06; do not expand criteria in review. +- Profile/module metadata, synthetic virtual-module communication and deterministic + dynamics/v2 are accepted. Dashboard and later capabilities remain planned. + Preserve the complete sequence/safety gates. ### Known blockers and uncertainties -No blocking Step-03 correction deficiency remains. R-04 below is historical and +No blocking Step-04 deficiency remains. The owner-drain finding below is +historical and closed by accepted Step-04B: + +- StartOrResumeAsync changes engine lifecycle to Running before checking whether + the old advancement task has finished. During pending pause/stop/reset cleanup, + StartRunnerLocked can throw "already active" after that mutation. The old + cancelled task then exits, leaving a rejected command's Running state without + an owner. Existing tests await transition completion before starting/resuming, + so they do not cover the interleaving. + +This was within Step-04A's existing concurrent lifecycle/no-stale-owner criterion, +not a retrospective quality-gate requirement. Step-04B supplied the controlled +pre-fix reproduction and validated owner eligibility before mutation. + +The original Step-04 findings below are retained as history; R-01/R-02 and the +other R-03 corrections have been inspected as fixed: + +- Step-04 R-01: missing profile/module references can escape configuration import + as catalog/lookup exceptions that the simulation import UI does not handle. +- Step-04 R-02: accepted initial RPM/speed/gear inputs can contradict a locked + drivetrain. Runtime RPM is independently capped while reporting zero slip; + supported launch settings can also report zero slip despite uncoupled RPM. +- Step-04 R-03: cumulative progress is cleared at phase boundaries; faulted + scenarios and subsequent reads can publish success status; pending scenario + cancellation ownership and late async results need guards and controlled proof. + +Step-04A supplied before/after, independent force/ratio, controlled pacing and +UI/native evidence. The orchestrator did not run application code or reproduce +these vectors. The new shared exit gate applies only to future work. + +No Step-03 correction deficiency has reopened. R-04 below is historical and closed by Step-03B, alongside Step-03A's R-01/R-02/R-03: - A module can return a valid positive probe but not support `read.identity`, or @@ -627,9 +759,9 @@ Non-blocking deviations are retained explicitly: - Step-02 resolved the working README CRLF issue: inspection found 149 LF and zero CRLF lines. A command-local CR-at-EOL-aware diff check passes. No global Git setting was changed; the existing LF-to-CRLF notice remains non-blocking. -- Corrected discovery/identity contracts are documented. Step-04 must align - acceptance lifecycle text while preserving the original 161-case and corrective - 175-/183-case reports as distinct historical evidence. +- The pending-transition rejection policy is now documented. Step-05 must align + remaining acceptance-pending lifecycle text while preserving the original and + corrective numerical/native reports, including the 207-case Step-04B run. No major environment installation, update, repair or rollback is automatically authorized. Physical definitions/access and programming approval remain future gates. diff --git a/prompts/STATE.md b/prompts/STATE.md index 7aff2e4..0a48e5f 100644 --- a/prompts/STATE.md +++ b/prompts/STATE.md @@ -5,19 +5,21 @@ | Field | Value | |---|---| | Updated | 2026-10-28 | -| Phase | Corrected Step-03 accepted; deterministic vehicle dynamics next | -| Active step | Step-04 - Deterministic vehicle dynamics and scenario execution | -| Assignment | [Step-04.md](Step-04.md) | +| Phase | Corrected dynamics accepted; first bounded live dashboard next | +| Active step | Step-05 - Configurable numeric/bar live dashboard | +| Assignment | [Step-05.md](Step-05.md) | | Assignment status | READY FOR WORKER / AWAITING MANUAL HANDOFF | -| Expected worker report | `prompts/Step-04-Report.md` - not yet created | -| Last accepted correction | Step-03B - accepted 2026-10-28 | -| Last accepted major milestone | Step-03 with Step-03A/Step-03B - accepted 2026-10-28 | +| Expected worker report | `prompts/Step-05-Report.md` - not yet created | +| Last accepted correction | Step-04B - accepted 2026-10-28 | +| Last accepted major milestone | Step-04 with Step-04A/Step-04B - accepted 2026-10-28 | | Outstanding corrections | None | | Step-02 status | ACCEPTED after Step-02A | | Step-03 status | ACCEPTED after Step-03A/Step-03B | -| Step-04 status | READY FOR WORKER | -| Worker execution | Step-03B manually completed; Step-04 not invoked | -| Immediate next action | User manually directs the worker to execute Step-04 only | +| Step-04 status | ACCEPTED after Step-04A/Step-04B | +| Step-04A review | All original corrective criteria closed with Step-04B | +| Step-05 status | READY FOR WORKER | +| Worker execution | Step-04B manually completed; Step-05 not invoked | +| Immediate next action | User manually directs the worker to execute Step-05 and shared quality gate only | | Next orchestrator action | After manual return, inspect the assignment, report, implementation, tests, Git changes, documentation and recorded command evidence | ## Repository baseline at initialization @@ -430,8 +432,200 @@ native/workload command was executed by the orchestrator. Step-04 is prepared against the actual accepted interfaces. It assigns a separate explicit dynamics provider/configuration, fixed-step clock/model/scenario controls, configuration-preserving reset and versioned dynamic telemetry through diagnostics. -There is no dynamics implementation yet, no extra executable/project assigned, -and no physical integration or calibration programming. +The dynamics implementation now exists under review, still without any extra +executable/project, physical integration or calibration programming. + +## Historical Step-04 review and corrective decision + +Initial decision: **REQUIRES CORRECTION**, 2026-10-28. The original findings +below describe pre-Step-04A code. At the follow-up, most were fixed but an +overlap criterion still required Step-04B. The closing review below now accepts +the corrected milestone. + +Inspected the [assignment](Step-04.md), [worker report](Step-04-Report.md), +configuration/initial/model validation and fingerprinting, complete physics/ +scenario/control implementation, dynamic provider and v2 binding, Application +configuration/session paths, UI controls/status, all new unit/integration tests +and related model/protocol/build documentation. + +| Criterion | Review result | Evidence / remaining work | +|---|---|---| +| AC-01 | Present; reference correction required | Immutable config/shape/fingerprint and profile binding exist; missing profile/module references can escape the import UI's handled exception contract | +| AC-02 | NOT SATISFIED | Progress resets at phase boundaries and async owner/active-pacer behavior lacks controlled proof; tests use wall delays/polling | +| AC-03 | Present on inspected evidence | Separate static/dynamics factories and exact original-config reset/session isolation implemented; no fallback or extra project | +| AC-04 | NOT SATISFIED | Initial and runtime locked-RPM/speed/gear consistency is not guaranteed across accepted inputs; independent force tests are absent | +| AC-05 | Baseline passed per worker | Default 650-rpm/45-MPH/full 300-s hold/stop/repeatability gates are meaningfully asserted; broader boundary inputs are not covered | +| AC-06 | Present; fault policy correction required | Actual strict v2 snapshots and static v1 compatibility exist; faulted/invalid model state must not become healthy success or an unhandled serialization failure | +| AC-07 | Corrective lifecycle/status required | Real controls/table/DI exist; faulted-run success notices, overwritten cancellation ownership and stale async publication require correction | +| AC-08 | Existing suite passed per worker; insufficient coverage | 115 unit + 75 integration passed, zero failed/skipped; complete Release/native and numerical baseline evidence supplied; review vectors not covered | +| AC-09 | Corrective alignment required | Equations/contracts/native guide present; operating envelope, fault/progress/clock ownership and corrected verification need documentation | +| AC-10 | Report/preservation inspected | Required report, nine-project scope and prior history preserved; no Step-05 | + +### Step-04 R-01 - Unhandled configuration reference errors + +[DynamicsConfigurationService.cs](../src/AutoForge.Application/Features/Vehicles/Simulation/DynamicsConfigurationService.cs), +line 68, selects the referenced profile inside Import but catches only JSON and +argument exceptions. Missing profile/revision throws VehicleProfileCatalogException. +[DynamicsConfiguration.cs](../src/AutoForge.Core/Simulation/DynamicsConfiguration.cs), +line 340, uses GetModule and can throw KeyNotFoundException for a missing module. +[SimulationPageViewModel.cs](../src/AutoForge.UI/Features/Vehicles/Simulation/SimulationPageViewModel.cs), +line 106, handles only DynamicsConfigurationException for import. Those valid +JSON/invalid-reference inputs can therefore escape the ordinary visible-error +path instead of leaving a usable page with actionable input feedback. + +### Step-04 R-02 - Unsupported or contradictory drivetrain states + +Configuration checks RPM range/gear count but not redundant initial kinematics. +For example a running first-gear state at 10 m/s and 650 rpm is accepted under +the default ratios even though reset publishes zero slip and the wheel equation +requires a different RPM. Reading before any step exposes the contradiction. + +[DynamicsEngine.cs](../src/AutoForge.Simulation/DynamicsEngine.cs), line 385, +independently caps coupled RPM with Math.Min while leaving speed/gear and zero +slip unchanged. Allowed high-speed/shift configurations can violate the promised +locked equation. At line 368, a slipping condition caused by below-idle wheel RPM +can also produce zero reported slip when speed exceeds a low configured launch +threshold. Validation or truthful modeled limits/slip/failure must replace those +healthy contradictory states, without gaming the default cruise gate. + +### Step-04 R-03 - Progress, terminal failures and async ownership + +[DynamicsEngine.cs](../src/AutoForge.Simulation/DynamicsEngine.cs), line 486, +clears cumulative completed time immediately after adding the finished phase, +so scenario progress drops at phase transitions. + +[SimulationPageViewModel.cs](../src/AutoForge.UI/Features/Vehicles/Simulation/SimulationPageViewModel.cs), +line 204, reports every returned scenario status via SetSuccess, including +Faulted; RefreshTelemetryAsync can overwrite the failure with another success. +The run method also replaces its pending cancellation slot before rejecting a +second runner, leaving the first runner no longer reachable through Cancel. +Post-await status/data publication lacks the earlier diagnostic UI's current- +session guard, so old work can update presentation during reset/close/reopen. + +Finite/domain failures mutate engine fields before checking them. The producer +can then read that failed snapshot and serialize positive Good telemetry; +non-finite fields can instead escape as a serialization exception. A clear +failed-run/last-valid-snapshot or typed negative policy is required. + +The active pacer uses direct Task.Delay; the lifecycle test uses fixed wall delays +and polling, and repeatability tests bypass the pacer. Add a controlled scheduler/ +time seam and actual active-run pause/resume/stop/reset/restart/close and pacing +tests, plus independent force/kinematic boundary evidence. + +All findings are source/contract review, not orchestrator-executed failures. +Worker baseline evidence remains historical: complete nine-project/native Release +build zero warnings/errors; 115 unit + 75 integration passed; 3,361 equal samples, +10 s warm idle, 10.3 s acceleration, 3,000/3,000 cruise samples in band/coupled, +5.8 s braking and 10 s return idle, plus actual native workflow. These useful +default results do not prove the missing boundary/failure/lifecycle cases. +Source case counts, graph and existing artifacts corroborate the report. + +## Historical Step-04A review and focused follow-up + +Decision at that review: most scope was satisfied, but existing R-03/AC-04 +required Step-04B. The follow-up below has now closed that condition. + +Reviewed [Step-04A](Step-04A.md), its [report](Step-04A-Report.md), typed +reference handling, initial/runtime coupling/limit guards and rollback, phase/ +overall progress, terminal v2 failures, UI generations/cancellation ownership, +actual controller/pacer code, independent numerical and controlled tests and docs. + +| Criterion | Review result | Evidence / remaining work | +|---|---|---| +| AC-01 | Satisfied on inspected/reported evidence | Missing profile/revision/module/calibration inputs are typed and atomic; rendered/native recoverable input errors reported | +| AC-02 | Satisfied on inspected/reported evidence | Initial coupled relation, redline validation/runtime guard, actual RPM-discrepancy slip and rollback; independent force/RPM boundary tests | +| AC-03 | Satisfied on inspected/reported evidence | Cumulative/phase progress corrected, fault snapshots rollback, negative DYNAMICS_RUN_FAULTED, persistent error and no healthy poisoned telemetry | +| AC-04 | NOT YET SATISFIED | Sequential controlled lifecycle and UI owner tests improved, but Start/Resume can mutate before rejecting an undrained advancement task | +| AC-05 | Existing regressions/numerical gates retained | Reported unchanged 3,361-sample baseline and all 190 cases within 202 passes; static/profile/wire/clear/discovery/source graph preserved | +| AC-06 | Reported execution inspected | Before-fix reference/coupling/progress failures, corrected focused runs, clean complete Release build, 122 unit + 80 integration passes and native smoke supplied | +| AC-07 | Satisfied on inspected evidence | Directly related model/config/lifecycle/v2/README/testing documentation updated | +| AC-08 | Preservation/scope inspected | Only scoped correction/source/tests/docs/report; no new project/package/workload action, orchestration/history edit or later step | + +### Remaining existing criterion: reject before lifecycle mutation + +[DynamicsEngine.cs](../src/AutoForge.Simulation/DynamicsEngine.cs), +StartOrResumeAsync around line 772 calls engine.Start/Resume before +StartRunnerLocked checks its still-active task. StopRunnerAsync changes state, +cancels the owner, releases the gate and then awaits its completion. + +If Resume/Start arrives while that cleanup is pending, the engine can become +Running and only then throw "already active". The cancelled old owner exits and +the rejected command can leave Running without an owner. A rejected operation +must wait under a documented policy or leave state unchanged; it cannot mutate +first. Existing controlled tests await Pause/Stop/Reset before the next start/ +resume, so the pending-transition overlap is absent. + +This is a source/contract finding within the original Step-04A overlap/lifecycle +criterion, not a new requirement introduced by the owner's process-improvement +request. The orchestrator did not execute it; Step-04B requires a controlled +pre-fix reproduction and is limited to this issue. + +Worker-reported Step-04A results remain historical: full nine-project/native +Release build zero warnings/errors; 122 unit + 80 integration passed (202 total, +zero failed/skipped); unchanged default numerical gates, independent force +equations, controlled pacing comparison and native input/fault/baseline smoke. +Source counts, graph and existing artifacts corroborate that evidence; the +orchestrator ran no application builds/tests/native/workload commands. + +## Step-04B acceptance and corrected Step-04 + +Decision: **ACCEPTED**, 2026-10-28. C-01 through C-05 and the remaining +Step-04A criterion are satisfied; corrected Step-04/04A/04B are accepted. +No Step-04C is required. + +Reviewed [Step-04B](Step-04B.md), its [report](Step-04B-Report.md), the shared +owner precondition before all start mutations, complete controlled status/ +sample assertions for pending pause/stop/reset, cleanup/retry/invalid/disposed +cases, real SimulationPage service/UI rejection and documentation/self-review. + +| Criterion | Decision | Evidence | +|---|---|---| +| AC-01 | ACCEPTED | All frozen cases covered; EnsureNoActiveAdvancementOwner precedes engine.Start/Resume/scenario state changes, with defensive check retained at owner installation | +| AC-02 | ACCEPTED | Old task drains without holding its cleanup gate; rejection preserves full status/sample count; one retry advances once; real UI error never reports resumed success | +| AC-03 | ACCEPTED ON WORKER EXECUTION EVIDENCE | Reported complete Release build zero warnings/errors; 126 unit + 81 integration passes (207 total, zero failed/skipped), original numerical gates and native lifecycle/reset/telemetry smoke | +| AC-04 | ACCEPTED | C-01..C-05 matrix, actual pre-fix observations, source-path self-review and matching lifecycle/README/testing policy | +| AC-05 | ACCEPTED | Single-issue guard/tests/docs/report change, no new project/package/interface/physics/protocol; historical assignments/reports and orchestration files preserved | + +Worker source-path self-review explicitly walks precondition order, producer/ +consumer callers, failure cleanup and barrier-finally behavior. The exact race +is controlled unit/real-DI/UI evidence, not claimed human-timed native proof. + +Static source case counts, nine-project acyclic references, restored assets, +Release assemblies and native output corroborate the report. The orchestrator +did not execute application builds/tests/native/workload commands. + +Step-05 is prepared under the revised prospective policy: one user outcome, +one acquisition-owner contract, numeric/bar rendering and validated in-memory +configuration. No new persistence/wire format, clock/model, project or host. +The frozen matrix states missing/uncertain/stale/range and source-lifetime +outcomes before coding; future enhancements stay out of acceptance. + +## Prospective orchestration/process improvement + +The owner requested fewer corrective handoffs through better planning/prompts. +The [revised roadmap policy](ROADMAP.md) and +[WORKER-QUALITY-GATE.md](WORKER-QUALITY-GATE.md) now require: + +- Smaller capability-complete assignments instead of several new subsystems/ + state machines/formats in one handoff. +- A compact agreed input/outcome/transition matrix before implementation. +- Worker source-path self-review after the first green run, fixing issues inside + the active assignment before COMPLETE. +- Evidence mapped to exact cases/invariants, not test-count proxies. +- One consolidated review against frozen criteria; new preferences are planned, + not retroactively called defects. + +The rules apply to new work beginning with Step-04B, not retroactively to +Step-04A. No automated agents/handoffs or weaker quality bar is introduced. +Step-01A was owner-driven architecture change, not an implementation-quality +failure. Earlier technical cycles exposed contract/coverage and overlarge-scope +gaps; orchestration shares responsibility for those gaps. + +The next dashboard envelope is narrowed prospectively to numeric/bar gauges, +validated bindings/ranges/units and missing/stale states with one acquisition +owner. Advanced charts/layout/editing stay later. Future broad calibration/AI/ +hardware envelopes must be split before assignment if needed; history is not +renumbered and corrective letters are not used for planned features. ## Prerequisites, limitations, and known issues @@ -454,29 +648,28 @@ and no physical integration or calibration programming. - Step-02 worker reports no workload-changing command was invoked; prior incident remains historical and does not authorize future installation/update/rollback. - Profile Step-02 R-01/R-02 remain closed and accepted; do not regress those fixes. -- Step-03 R-01/R-02/R-03/R-04 are closed; no blocking Step-04 prerequisite is - currently identified. Preserve all correction invariants. -- Step-04 must align remaining acceptance-pending lifecycle text without altering - original 161-case or corrective 175-/183-case reports. -- Profile metadata/UI and synthetic virtual-module diagnostics/static signals - are accepted. Full dynamics, replay, calibration +- Step-03 R-01/R-02/R-03/R-04 remain closed; preserve all correction invariants. +- Step-04 reference/coupling/progress/failure/UI/owner fixes are accepted with + Step-04B. No blocking Step-05 prerequisite is identified. Preserve the 190-/ + 202-/207-case reports and original numerical/native evidence distinctly. +- Profile metadata/UI, synthetic diagnostics and deterministic dynamics/v2 are + accepted. Dashboard, replay, calibration values, persistence, AI and physical hardware operations remain unimplemented. - No application build or test has been executed by the orchestrator. ## Review and progression gate -On manual return, evaluate Step-04 criteria using the original +On manual return, evaluate Step-05 against its frozen contract and shared quality gate using the original assignment, worker report, actual code/tests, dependency graph, Git changes, README/docs, and recorded build/test evidence. Do not accept solely on a success claim; do not claim independent runtime verification. -- Inspect coupled physics/numeric thresholds, fixed clock/lifecycle/pacing, - run/configuration identity and reset, strict static/dynamic wire integration, - independent oracle and real application/UI/native evidence. -- If accepted: record evidence, update roadmap/state, create Step-05 and stop for - manual handoff. Do not execute it. -- If deficient: create `Step-04A.md` with measurable corrections and matching - report requirements, update state and stop. Do not advance to Step-05. +- Inspect pure gauge projections/states, validated definitions, one session-owned + feed, independent visibility/acquisition, source replacement and real UI/native + evidence. Do not add deferred persistence/charts/conversion requirements. +- If accepted: update roadmap/state, create Step-06 and stop for manual handoff. +- If deficient: issue narrowly scoped Step-05A only for a material unmet contract/ + regression, then stop. Planned new features are not corrections. - If blocked: retain the active step, document the prerequisite and required worker evidence; do not advance or mark unexecuted checks as successful. - Never create the next major assignment while acceptance or corrections are open. @@ -511,11 +704,21 @@ claim; do not claim independent runtime verification. | 2026-10-28 | Step-03B returned and ACCEPTED | R-04 closed; phase/count/guard/trace source and reported 183-case/native evidence inspected | | 2026-10-28 | Corrected Step-03 ACCEPTED | All R-01/R-02/R-03/R-04 closed; normal and partial diagnostics, wire integrity and verified clear retained | | 2026-10-28 | Step-04 prepared | Fixed-step coupled dynamics, explicit configuration/control and dynamic diagnostic telemetry; manual worker handoff pending | +| 2026-10-28 | Step-04 returned for review | Model/config/controller/provider/UI and reported 190-case/numerical/native evidence inspected | +| 2026-10-28 | Step-04 requires correction | Missing-reference handling, drivetrain boundary states and failed/progress/async lifecycle gaps; baseline drive cycle itself reports all numeric gates met | +| 2026-10-28 | Step-04A prepared | Narrow correctness and controlled-proof correction; Step-05 blocked and not assigned | +| 2026-10-28 | Step-04A returned for review | Reference/coupling/progress/failure/UI fixes and reported 202-case/native evidence inspected; pending owner-drain transition remains | +| 2026-10-28 | Owner requested orchestration reassessment | Prospective scope sizing, frozen contract/evidence matrices and worker self-review gate introduced; no retrospective criteria | +| 2026-10-28 | Step-04B prepared | Single existing reject-before-mutate overlap; no physics/protocol/new feature scope; Step-05 remains blocked | +| 2026-10-28 | Step-04B returned and ACCEPTED | Frozen C-01..C-05 satisfied; guard ordering, before/after status/state tests, real UI, self-review and reported 207-case/native evidence inspected | +| 2026-10-28 | Corrected Step-04 ACCEPTED | Original and 04A/04B criteria closed; source and numerical history preserved; no 04C | +| 2026-10-28 | Step-05 prepared | Bounded numeric/bar dashboard with one acquisition owner, in-memory validated bindings and frozen data/lifecycle matrix; manual handoff pending | ## Manual handoff instruction -Provide [Step-04.md](Step-04.md) to the separate worker and request execution -of that assignment only. The worker must produce `prompts/Step-04-Report.md` -and stop for review. Do not begin Step-05. +Provide [Step-05.md](Step-05.md) and the shared +[worker gate](WORKER-QUALITY-GATE.md) to the separate worker and request execution +of that assignment only. The worker must produce `prompts/Step-05-Report.md` +and stop for review. Do not begin Step-06. Return manually to the orchestrator for review. Reports, including final chat reports, must follow the single plain triple-backtick copy-window requirement. diff --git a/prompts/Step-04-Report.md b/prompts/Step-04-Report.md new file mode 100644 index 0000000..eb809a7 --- /dev/null +++ b/prompts/Step-04-Report.md @@ -0,0 +1,145 @@ +``` +# Step-04 - Deterministic vehicle dynamics and scenario execution + +Status: COMPLETE (worker implementation and verification; pending manual orchestrator acceptance) + +## Summary + +Implemented the explicit, deterministic synthetic dynamics workflow without changing the nine-project .NET 10 modular-monolith shape or adding an executable, backend, service, or project. The existing static diagnostics provider and strict protocol v1 remain available; the dynamics provider is separately selected and uses protocol v2. Configuration selection, run/session identity, lifecycle control, numerical output, and diagnostic telemetry are covered by unit, integration, rendered-route, and native Client checks. + +The complete Release build and test suites passed, and the required Windows native smoke completed. No Step-05 work was started. Manual orchestrator acceptance remains pending. + +## Implementation and boundaries + +- Added immutable format-version-1/model-version-1 `DynamicsConfiguration`, validated model inputs, copied scenario/gear/curve collections, and an exact profile/revision/module/calibration binding. The stable configuration fingerprint is `sha256:v1:` plus lowercase SHA-256 over stable camelCase JSON with the derived fingerprint omitted. Operational run and diagnostic-session IDs are separate. +- Added the Application configuration catalog/import/export service. Import checks exact required, duplicate, and unknown JSON members and validates compatibility with the selected profile before registration. Export/import preserves the configuration fingerprint. Invalid JSON is reported visibly; it does not become a successful fallback. +- Added the separate `autoforge.simulation.dynamics` provider, run-control capability, coupled fixed-step engine, scenario runner, and encoded dynamic diagnostic transport. Static `autoforge.simulation.synthetic` continues to provide fixed protocol-v1 data and cannot acquire dynamics control through the static-open path. +- Added protocol v2 validation and run/configuration/model-time binding while retaining strict v1 static semantics. Paused and stepped module reads identify the same model step; dynamic signals carry source, unit, quality, `SYNTHETIC_DYNAMIC`, step/time, configuration fingerprint, and run identity. Diagnostic capture ticks remain separate from virtual model time. +- Added `/simulation` for explicit profile/revision/provider/configuration selection, import/export, open/start/pause/resume/stop/reset/step, scenario execution, pacing, visible errors, and a telemetry table populated through actual diagnostic frames. Loading an example does not open or start a run. +- Reset reopens the original immutable configuration, independent of later catalog selection. Closing/resetting waits for active work and releases the prior run. A disposal/cancellation race found during the final full-suite run was corrected so an in-flight scenario exits cleanly when its controller is disposed; post-disposal control calls still fail explicitly. +- Corrected the rendered model-version and phase-progress expressions and added integration assertions for their output. Updated the home status notice to describe the now-available synthetic dynamics workflow. + +Production dependency boundaries remain: + +- Diagnostics -> Core. +- Simulation -> Core and Diagnostics. +- Application -> Core and Diagnostics; it does not reference Simulation implementation. +- UI -> Application, Components, and Diagnostics. +- Client -> Application, UI, and Simulation; it composes both providers. +- Core and Components have no AutoForge project dependencies. + +The two test projects remain under `src/tests`. No project, shell, backend, or external runtime dependency was added. + +## Model, clock, and scenario + +The engine uses SI units and a fixed 0.1-second virtual step (validated supported interval: 0.01-0.5 seconds). Virtual time is derived from integer step count. Pacing from 0.25x through 1000x changes scheduling only. The warmed example uses: + +- 1,800 kg mass; 0.34 m wheel radius; CdA 0.68 m2; rolling coefficient 0.012; air density 1.2 kg/m3; gravity 9.80665 m/s2. +- 0.9 drivetrain efficiency; 3.6 final drive; maximum braking force 10,000 N. +- 650 rpm idle/warm target; 5,000 rpm maximum; 2.5 m/s first-gear launch-slip end speed. +- Forward ratios 3.5, 2.2, 1.4, 0.9; 4,000 rpm upshift and 1,450 rpm downshift schedules. +- Torque curve (rpm, N*m): (650,240), (1000,300), (2000,360), (3200,350), (4200,300), (5000,180). +- Idle fuel flow 0.00045 kg/s; fuel mass per joule 1.2e-7 kg/J; ambient/initial/equilibrium temperature 20/88/90 degC; thermal response rate 0.015 per second. + +Torque is interpolated linearly between curve points. Wheel force is engine torque times gear ratio, final drive, efficiency, and coupling factor divided by wheel radius. Rolling and aerodynamic loads are `m*g*Crr` and `0.5*rho*CdA*v^2`; braking is bounded by configured maximum force; longitudinal acceleration is net force divided by mass. Speed uses fixed-step forward Euler with a zero lower bound; distance uses trapezoidal integration. Fuel derives from engine power and configured fuel parameters. Temperature uses a documented first-order approximation. When coupled, engine RPM is derived from vehicle speed, wheel radius, gear ratio, and final drive; the explicit launch-slip model avoids claiming locked idle-speed coupling. + +The ordered baseline is 10 seconds warm idle, acceleration to 20.1168 m/s (45 MPH) with a 60-second limit, the full 300-second cruise hold, braking to at most 0.1 m/s within 60 seconds, and at least 10 seconds stationary return-idle. Scenario controllers bound throttle/brake commands and never assign vehicle speed directly. Non-finite/domain failures fault the run explicitly. Fuel remains finite/nonnegative and cumulative consumption is monotonic. + +This is a simplified deterministic behavioral model, not firmware emulation, manufacturer prediction, real fuel-economy evidence, emissions analysis, calibration advice, a safe tune recommendation, compatibility evidence, or physical vehicle access. + +## Numerical and test evidence + +Exact full Release commands: + +- `dotnet build .\src\AutoForge.slnx --configuration Release --no-restore` +- `dotnet test .\src\AutoForge.slnx --configuration Release --no-build` + +The Release build succeeded with zero warnings and zero errors. It compiled all nine projects: AutoForge.Core, AutoForge.Components, AutoForge.Diagnostics, AutoForge.Simulation, AutoForge.Application, AutoForge.UnitTests, AutoForge.UI, AutoForge.IntegrationTests, and the Windows-targeted AutoForge.Client. Portable projects/tests target `net10.0`; Client targets `net10.0-windows10.0.26100.0`/`win-x64`. + +The complete test command passed 115 unit tests and 75 integration tests (190 total; zero failed and zero skipped), preserving the Step-03B 183-test baseline. The final focused lifecycle-disposal regression passed, the changed rendered home-route regression passed, and the detailed numerical baseline test passed. + +The numerical test ran two equal immutable configurations and compared every sampled state (`SequenceEqual`), including lifecycle/scenario outcomes. Actual test output: + +- 3,361 samples at 0.1 seconds; the full run completed in 336.1 virtual seconds. +- Warm idle: 100 samples / 10.0 seconds; final engine speed 650.000 rpm, within the 650 +/- 5 rpm gate. +- Acceleration: target 20.1168 m/s reached at 10.3 seconds and 20.1473 m/s; four scheduled shifts. The test also rejects a per-step speed jump of 0.5 m/s or more. +- Cruise: all 3,000 required samples retained; 3,000/3,000 (100.000%) within +/-0.44704 m/s (45-MPH +/-1-MPH band); all 3,000 were in the defined coupled regime. Coupled RPM was independently checked against the gear/wheel-radius equation to 1e-8 rpm. +- Braking: 58 samples / 5.8 seconds; final speed 0.0000 m/s, bounded nonnegative and within the 0.1 m/s limit. +- Return-idle: 100 samples / 10.0 seconds, all stationary. +- Final modeled fuel: 0.518387 kg; every sampled rate/value was finite, rates nonnegative, and cumulative fuel monotonic. + +Relevant regression coverage includes configuration required/unknown/duplicate/version/range/profile validation, fingerprint and interchange behavior, immutability, numerical equations, phase thresholds, coupling and shifts, protocol-v1 preservation and v2 binding/time/origin validation, paused multi-module snapshots, read-without-advance, separate sessions/configurations, reset identity, lifecycle transitions, cancellation/disposal, and rendered real-provider UI workflows. + +## Native Windows Client evidence + +Environment: .NET SDK 10.0.402; .NET runtime 10.0.13; Windows SDK target 10.0.26100.0; MAUI Windows workload manifest 10.0.110; WebView2 Runtime 155.0.4283.62. The actual rebuilt Client executable was launched from `src\AutoForge.Client\bin\Release\net10.0-windows10.0.26100.0\win-x64\AutoForge.Client.exe` with a task-local WebView debug port for inspection. It was stopped after verification; PID 33312 exited and port 9335 was no longer listening. + +Native `/simulation` observations on the rebuilt binary: + +- Initial page had no selected profile/configuration and no open session. User-triggered profile loading added the synthetic truck but left the profile selection blank. +- Explicit profile/revision/provider/configuration selection used `autoforge.synthetic.test-truck` revision 1, `autoforge.simulation.dynamics`, and fingerprint `sha256:v1:e8991ae139b54959ec53a4fe64b08dc9bfc03feb533496cf741f2c9f3a2342da`. +- The rendered model identity showed `autoforge.synthetic.longitudinal v1`; stopped progress showed `WarmIdle (0.0%)`, and after four explicit steps it showed 0.4 seconds / step 4 and `WarmIdle (0.1%)`. +- Start/pause/step then read 17 protocol-v2 telemetry rows across the engine and transmission at the same paused step/time. All rows showed `SYNTHETIC_DYNAMIC`, units, quality, configuration fingerprint, and run ID. +- At 1000x pacing the native full scenario completed at step 3361 / 336.1 seconds with 17 telemetry values, four shifts, 0 m/s, and 650 rpm. This native display smoke supplements, but does not replace, the headless numerical proof. +- Native configuration export produced 2,789 JSON characters. An invalid `{}` import visibly reported the missing required `formatVersion`. Reset then opened a new run/session on the exact same fingerprint at step 0 with `WarmIdle (0.0%)`. Export/import fingerprint preservation was also exercised during the earlier native smoke in this task. +- The native session was closed. + +Native `/diagnostics` regression on the rebuilt binary selected the unchanged `autoforge.simulation.synthetic` provider. Discovery showed three expected endpoints, two positive probes/verified identities, and the configured transmission no-response. The engine returned its synthetic DTC `SYN-P0123` and static 850-rpm / 12.6-V values with `SYNTHETIC_STATIC`; the bounded trace retained seven correlated v1 records. The static session was closed. + +The existing `/execution-targets`, `/vehicle-profiles`, `/`, and unmatched not-found route were visited on the rebuilt Client. Both providers remained visible as metadata; selection did not open a session. The updated home notice accurately describes the available synthetic dynamics scope. + +## Files created + +- `docs/synthetic-diagnostics-v2.md` +- `src/AutoForge.Application/Features/Vehicles/Simulation/DynamicsConfigurationService.cs` +- `src/AutoForge.Core/Simulation/DynamicsConfiguration.cs` +- `src/AutoForge.Core/Simulation/DynamicsRunStatus.cs` +- `src/AutoForge.Simulation/AssemblyInfo.cs` +- `src/AutoForge.Simulation/DynamicsDiagnosticProvider.cs` +- `src/AutoForge.Simulation/DynamicsEngine.cs` +- `src/AutoForge.UI/Features/Vehicles/Simulation/SimulationPage.razor` +- `src/AutoForge.UI/Features/Vehicles/Simulation/SimulationPageViewModel.cs` +- `src/tests/AutoForge.IntegrationTests/DynamicsWorkflowTests.cs` +- `src/tests/AutoForge.UnitTests/DynamicsEngineTests.cs` +- `prompts/Step-04-Report.md` + +## Files modified + +- `README.md` +- `docs/README.md` +- `docs/architecture.md` +- `docs/build-and-test.md` +- `docs/simulation.md` +- `docs/synthetic-diagnostics-v1.md` +- `src/AutoForge.Application/Features/Vehicles/Diagnostics/DiagnosticSessionService.cs` +- `src/AutoForge.Client/MauiProgram.cs` +- `src/AutoForge.Diagnostics/ProviderContracts.cs` +- `src/AutoForge.Diagnostics/SyntheticDiagnosticProtocolClient.cs` +- `src/AutoForge.Diagnostics/SyntheticProtocolV1.cs` +- `src/AutoForge.UI/Features/Foundation/AddAutoForgeUi.cs` +- `src/AutoForge.UI/Features/Foundation/Home.razor` +- `src/AutoForge.UI/Layout/MainLayout.razor` +- `src/AutoForge.UI/_Imports.razor` +- `src/tests/AutoForge.IntegrationTests/UiCompositionTests.cs` + +## Acceptance criteria + +| ID | Status | Evidence | +|---|---|---| +| AC-01 | PASSED | Immutable exact profile/config/model/scenario inputs, strict interchange validation, stable fingerprint, compatibility checks, and configuration tests/docs. | +| AC-02 | PASSED | Integer fixed-step time, lifecycle/step/pacing controls, controlled cancellation/disposal regressions, and no diagnostic-read advancement. | +| AC-03 | PASSED | Separate static-v1 and dynamics-v2 provider/control paths; actual session/config identity, isolation, exact reset, and wrong-path regressions. | +| AC-04 | PASSED | Coupled force/RPM/gear/road-load/fuel/thermal model, independent coupled-RPM equation check, bounded/nonnegative finite evolution, and shift/idle/brake tests. | +| AC-05 | PASSED | All 3,361 samples reproduced exactly; 10.0 s idle, 10.3 s acceleration, full 3,000-sample cruise at 100% in tolerance/coupled, 5.8 s stop, and 10.0 s return-idle. | +| AC-06 | PASSED | Actual encoded v2 requests/responses, run/config/time/source/unit/origin validation, paused shared-step reads, static-v1 regression, and malformed-binding tests. | +| AC-07 | PASSED | Real Application/UI controls and telemetry, corrected rendered model/progress, explicit user selection, real-provider integration tests, and rebuilt native interaction. | +| AC-08 | PASSED | Nine-project Release build, 115 unit + 75 integration tests, numerical evidence, rebuilt Windows Client smoke, static regression and preserved routes. | +| AC-09 | PASSED | README, documentation index, architecture, build/test guide, simulation and protocol-v1/v2 documentation updated with behavior and limitations. | +| AC-10 | PASSED | Only the Step-04 report was created under `prompts`; protected assignments/state/roadmap/historical reports remained unchanged; no stage/commit/push/Step-05/agent/handoff action. Git whitespace check passed and native helper/listener was stopped. | + +## Documentation, limitations, and handoff + +Updated README/index, architecture, build/test evidence, simulation equations/configuration/limitations, and protocol v1/v2 separation. The static diagnostics provider and protocol v1 remain separate from dynamic output. All imported metadata and outputs remain synthetic and process/session-local. No actual vehicle, manufacturer model, physical write, replay, calibration editor, AI, persistence, or hardware adapter is included. + +No unresolved implementation or verification failure remains. Manual orchestrator acceptance is pending and is not claimed. Protected files were absent from the changed-path list; `git diff --check` passed. No files were staged, committed, or pushed, and no Step-05 or automated handoff was started. +``` diff --git a/prompts/Step-04A-Report.md b/prompts/Step-04A-Report.md new file mode 100644 index 0000000..c1f4eab --- /dev/null +++ b/prompts/Step-04A-Report.md @@ -0,0 +1,126 @@ +``` +# Step-04A - Dynamics input, drivetrain and lifecycle integrity + +Status: COMPLETE (worker implementation and verification; manual orchestrator acceptance remains pending) + +Step-04 was returned for correction and remains NOT ACCEPTED until the orchestrator reviews it. This report records only the Step-04A corrective work. No Step-05 work was started. + +## Summary + +Corrected the dynamics configuration reference contract, drivetrain coupling/rev-limit behavior, scenario progress and failure presentation, and asynchronous lifecycle ownership. Added independent numerical, controlled-scheduler, rendered UI, and diagnostic-protocol tests. The original Step-04 scenario thresholds and all 190 existing tests were retained. No project, package, host, backend, or physical-vehicle capability was added. + +## Root causes and corrections + +### R-01 - Typed and atomic configuration-reference validation + +The configuration importer allowed unavailable profile/revision and module references to escape through catalog/dictionary exceptions rather than the normal typed configuration-validation contract. `DynamicsConfigurationService.Import` now translates those reference and calibration-conflict failures into `DynamicsConfigurationException` before registration. A rejected import does not alter the catalog. `SimulationPageViewModel.ImportConfiguration` presents that typed error and preserves the selected valid configuration and existing active session/run binding. + +Tests cover unknown profile, unknown revision, missing engine/transmission modules, and conflicting calibration references. Rendered integration and native Client checks confirmed visible errors without partial registration or selection/session mutation. + +### R-02 - Coupled RPM, launch slip and rev-limit envelope + +The old runtime independently capped engine RPM while leaving vehicle speed unchanged, permitting a healthy-looking locked state that violated the wheel/gear equation. Launch torque transfer could also differ from the reported slip, yielding mismatched engine/wheel RPM with reported zero slip. + +Running initial in-gear states now require a locked wheel/gear RPM relation within `1e-8` rpm; unsupported initial states and scenario targets outside the top-gear redline envelope are rejected. Upshift thresholds must be within the engine speed limit. The runtime no longer independently clamps healthy locked RPM: scenario throttle is bounded against the target-speed/redline envelope. Launch torque-transfer factor is separate from the reported slip metric, which reflects actual engine/wheel RPM discrepancy. A finite but extreme accepted configuration that overflows model power rolls back to its last valid sample and faults explicitly. + +Independent checks cover initial and runtime RPM equations, a high-torque/high-speed variant, a low launch-slip threshold, and a constant-torque force/mass/acceleration calculation. The force-balance and speed-step acceleration comparisons use `1e-10` tolerance. + +### R-03 - Truthful progress, terminal failures and lifecycle ownership + +Overall progress now retains completed phase duration; current-phase progress is exposed separately and rendered separately. Both are bounded to `[0,1]`, reset to zero, and reach one on successful completion. A missed phase deadline remains Faulted with its reason intact. + +Faulted dynamic `read.signals` requests return correlated protocol-v2 negative response `DYNAMICS_RUN_FAULTED`; no zero/empty healthy fallback is serialized. Arithmetic/domain failures roll back state and sample output to the last valid fixed-step snapshot before faulting. UI fault handling clears previously displayed good telemetry rows, preserves the failure notice through refresh, and does not present failure as scenario success. + +The run controller owns one cancellable advancement task. Start/resume advances the first fixed step and then waits on the configured pacer. Pause, stop, reset, and disposal cancel and await that owner. A narrow `IDynamicsPacer` seam permits deterministic scheduling tests. UI run reentrancy retains the first cancellation owner; session/run generations invalidate stale results from reset/close/reopen and a close during a pending open disposes the stale session. + +## Files touched for Step-04A + +- `README.md` +- `docs/README.md` +- `docs/build-and-test.md` +- `docs/simulation.md` +- `docs/synthetic-diagnostics-v2.md` +- `src/AutoForge.Core/Simulation/DynamicsConfiguration.cs` +- `src/AutoForge.Core/Simulation/DynamicsRunStatus.cs` +- `src/AutoForge.Application/Features/Vehicles/Simulation/DynamicsConfigurationService.cs` +- `src/AutoForge.Simulation/DynamicsEngine.cs` +- `src/AutoForge.Simulation/DynamicsDiagnosticProvider.cs` +- `src/AutoForge.UI/Features/Vehicles/Simulation/SimulationPage.razor` +- `src/AutoForge.UI/Features/Vehicles/Simulation/SimulationPageViewModel.cs` +- `src/tests/AutoForge.UnitTests/DynamicsEngineTests.cs` +- `src/tests/AutoForge.IntegrationTests/DynamicsWorkflowTests.cs` +- `prompts/Step-04A-Report.md` (created) + +## Before/after regression evidence + +Focused pre-fix reproductions were run before the corresponding corrections. They exposed: + +- `ConfigurationImport_ReferencesFailThroughTypedValidationWithoutRegistration`: an unknown profile escaped as `VehicleProfileCatalogException` rather than the expected `DynamicsConfigurationException`. +- `DynamicsConfiguration_RejectsInconsistentInitialCouplingAndOverRevStates`: 10 m/s, first gear and 650 rpm was accepted despite inconsistent coupling. +- `DynamicsRuntime_DoesNotReportFalseLockedOrZeroSlipState`: an accepted high-torque/high-speed variant could report locked RPM inconsistent with wheel speed, and a low launch-slip threshold could produce RPM discrepancy with zero reported slip. +- `ScenarioProgress_IsMonotonicAcrossPhasesAndDeadlineFailureIsTerminal`: overall progress moved backward at four phase boundaries; the 0.1-second acceleration deadline did not satisfy the required terminal-failure assertion. + +The UI owner-slot defect was traced to assigning a second run's cancellation source before the controller rejected duplicate advancement, allowing the rejected request's cleanup to clear the active owner's slot. The corrected owner/reentrancy behavior is covered by controlled post-fix integration tests. + +Corrected focused selections passed: + +- Unit selection covering typed import, initial/runtime coupling, progress/deadline, independent force, baseline reproducibility, controlled lifecycle/pacing and non-finite rollback: 8 passed before the final non-finite case was added; final focused follow-up of non-finite rollback, constant-torque force and baseline: 3 passed. +- Integration selection covering typed/atomic UI import, deadline and non-finite failures through v2 diagnostics, overlapping run/cancel, pending open/close, reset/close stale-result suppression, and the original rendered workflow: 6 passed in the final selection. + +The full final Release regression retained the 190 Step-04 cases and added 7 unit and 5 integration cases: 122 unit tests and 80 integration tests passed (202 total, zero failed/skipped). + +## Numerical and lifecycle evidence + +The original warm-baseline thresholds and trajectory remained unchanged and reproducible across equal configurations: + +- 3,361 samples / 336.1 virtual seconds. +- Warm idle: 100 samples / 10.0 seconds, final 650.000 rpm. +- Acceleration: 20.1473 m/s reached in 10.3 seconds with four shifts. +- Cruise: all 3,000 samples retained and in the original 45-MPH +/- 1-MPH band while coupled. +- Braking: 0.0000 m/s in 5.8 seconds; return-idle: 10.0 seconds stationary. +- Total modeled fuel: 0.518387 kg; sampled quantities finite and cumulative fuel monotonic. +- Independent locked RPM equation tolerance: `1e-8` rpm. Constant 300 N*m torque force-balance and speed-step equation tolerance: `1e-10` m/s2. + +Controlled-pacer tests compared equivalent full virtual sample sequences at 0.25x and 1000x; only delay requests changed. Tests actively paused and proved no step change while a delay was pending, resumed, stopped, reset, restarted, canceled and disposed. UI integration covered duplicate run/cancel, stale reset/close work, delayed open followed by close, and exact original configuration rebinding. A finite but extreme torque/ratio vector produced a Faulted lifecycle with the last valid state/sample retained and a negative v2 diagnostic response. + +## Full Release verification + +Commands were run sequentially after the final code/test edits: + +- `dotnet build .\src\AutoForge.slnx --configuration Release --no-restore` — succeeded, 0 warnings, 0 errors; all nine solution projects built, including the native Windows Client. The MAUI XAML source-generation notice was informational. +- `dotnet test .\src\AutoForge.slnx --configuration Release --no-build` — succeeded: `AutoForge.UnitTests` 122 passed / 0 failed / 0 skipped; `AutoForge.IntegrationTests` 80 passed / 0 failed / 0 skipped; total 202. + +No dependency restore or workload change was needed. + +## Native Client observations + +The rebuilt Windows Client was launched from `src/AutoForge.Client/bin/Release/net10.0-windows10.0.26100.0/win-x64/AutoForge.Client.exe`; its `AutoForge` window responded and its WebView2 page was exercised over a worker-local debugging endpoint. The actual native `/simulation` route: + +- Loaded and explicitly selected profile `autoforge.synthetic.test-truck` revision 1, provider `autoforge.simulation.dynamics`, and the warm-baseline configuration `sha256:v1:e8991ae139b54959ec53a4fe64b08dc9bfc03feb533496cf741f2c9f3a2342da`. +- Rejected unknown profile, revision and module JSON references with visible recoverable errors while preserving the original selected configuration. +- Ran a 0.1-second acceleration deadline variant (`sha256:v1:5f0d61a046321131bc5f0c464b8e28082717cc81668c06c1d8c5127e542c422d`). It remained visibly Faulted at step 101 / 10.1 virtual seconds after diagnostic refresh; the failure notice remained and prior telemetry rows were cleared. +- Completed the valid accelerated baseline at step 3,361 / 336.1 virtual seconds. The active runner was separately paused at step 1 and held there while waiting, resumed, stopped, explicitly stepped, and reset into a new step-0 session. +- Read 17 protocol-v2 `SYNTHETIC_DYNAMIC` values at step 0, exported and re-imported the valid configuration, confirmed its active session binding stayed exact, and closed the session. +- Loaded `/diagnostics`, `/vehicle-profiles`, `/execution-targets`, `/`, and an unmatched not-found route. The static route check was a route/render smoke; the prior Step-04 report retains its earlier static diagnostics operational evidence. + +The worker-launched Client, its child WebView process and local DevTools listener were closed; follow-up process/listener checks found none. Native observations are distinct from the numerical and controlled-scheduler proof above. + +## Acceptance criteria + +| ID | Status | Evidence | +|---|---|---| +| AC-01 | PASSED | Typed direct/service validation, atomic catalog behavior, rendered/native errors for profile/revision/module references, and preservation of selected configuration and active run binding. | +| AC-02 | PASSED | Initial and runtime coupling checks, redline rejection/enforcement, independent wheel/RPM and constant-torque force equations, accepted boundary variant, and v2 fault/signal reads. | +| AC-03 | PASSED | Monotonic overall and phase progress, deadline and non-finite terminal faults, rollback/negative telemetry policy, persistent UI error, and explicit cancel/stop/close outcomes. | +| AC-04 | PASSED | Controlled real-pacer tests and UI integration for active freeze/resume/stop/reset/restart/dispose/cancel, overlapping calls, delayed open, and stale-result suppression. | +| AC-05 | PASSED | Original full numerical gates and 190-case regression preserved; final 122-unit/80-integration suite passed; native legacy route smoke and unchanged project graph. | +| AC-06 | PASSED | Actual pre-fix typed-reference, coupling/slip and progress/deadline findings recorded above; corrected focused/full build/test outcomes and required native paths recorded. | +| AC-07 | PASSED | README, documentation index, build/test guide, model/configuration/lifecycle guide, and protocol-v2 fault contract updated. | +| AC-08 | PASSED | Only the required Step-04A report was created under `prompts`; protected assignments, ROADMAP, STATE and prior reports were not edited; no project/dependency/workload or out-of-scope change, stage, commit, push or Step-05 work. | + +## Documentation, limitations and preservation + +Updated README and directly related configuration/model, protocol-v2, build/test and lifecycle documentation. The model remains synthetic and is not validated real-world prediction, manufacturer calibration, safe tuning advice, vehicle compatibility, physical access or authorization. No ADR was needed because the nine-project architecture and dependency directions were unchanged. + +The original Step-04 report remains historical and unmodified. `prompts/Step-04A.md`, `prompts/ROADMAP.md`, and `prompts/STATE.md` were preserved. No agent, handoff automation, Git staging, commit, push, reset or unrelated cleanup was used. Full regression/build passed and the worker stops here; Step-04 acceptance remains the orchestrator's responsibility. +``` diff --git a/prompts/Step-04A.md b/prompts/Step-04A.md new file mode 100644 index 0000000..8212282 --- /dev/null +++ b/prompts/Step-04A.md @@ -0,0 +1,344 @@ +# Step-04A - Dynamics input, drivetrain and lifecycle integrity + +## STEP IDENTIFIER + +Step-04A, corrective assignment for Step-04. Step-04 is NOT ACCEPTED. +This is the sole active assignment. Step-05 is blocked and not assigned. +R-01/R-02/R-03 below are Step-04 findings; prior diagnostic findings remain closed. + +## STEP TITLE + +Make invalid references, drivetrain limits and run lifecycle/failure presentation +reliable, with independent numerical and controlled scheduling evidence. + +## OBJECTIVE + +Correct three coupled integrity gaps without discarding the useful default +numerical model or redesigning the product. Preserve exact run/config bindings, +static diagnostics, strict v1/v2 wire handling and all accepted profile/diagnostic +corrections. Keep the nine-project single-Client/two-RCL modular monolith. + +You are the WORKER. Execute only this correction, write +`prompts/Step-04A-Report.md`, and STOP for manual orchestrator review. + +## ARCHITECTURAL CONTEXT + +Read [STATE.md](STATE.md), [ROADMAP.md](ROADMAP.md), +[Step-04](Step-04.md), its [report](Step-04-Report.md), current +[simulation documentation](../docs/simulation.md) and +[protocol v2](../docs/synthetic-diagnostics-v2.md). + +Core/shared contracts own input invariants; Simulation owns physics/clock; +Application owns configuration/session features; UI adapts their typed outcomes. +Telemetry still crosses actual diagnostic frames, not a UI oracle shortcut. +No new project, host, backend, package or physical capability is assigned. + +Keep application/tests under `src`, tests under `src/tests`, technical docs under +`docs` and all handoffs under `prompts`. Do not modify orchestration files or +historical reports. Handoffs remain manual. + +## CURRENT IMPLEMENTATION STATE + +Step-04 introduced immutable DynamicsConfiguration, fingerprinted JSON catalog, +coupled engine/transmission/longitudinal model, fixed steps, scenario/controller, +separate dynamics provider/protocol v2 and `/simulation` controls/table. +Static `autoforge.simulation.synthetic` and its v1 behavior remain separate. + +Worker baseline evidence reports 115 unit + 75 integration passes (190 total, +zero failed/skipped), clean complete nine-project/native Release build and native +smoke. Its warmed example meets the original idle/acceleration/300-second hold/ +stop gates and reproduces 3,361 sampled states. Preserve those meaningful tests +and thresholds; they do not cover the findings below. + +The orchestrator inspected source/contracts/tests and reported evidence without +executing application code. Reproduce the actual failures before fixing them. +Inspect Git/instructions and preserve pre-existing dirty implementation/history. +No workload/system installation/update/repair/rollback or new dependency is +authorized. Use the existing supported SDK/runner and ordinary package restore +only when actually necessary. + +## REQUIRED IMPLEMENTATION + +### R-01 - Keep invalid configuration references in the normal error contract + +Locations: + +- [DynamicsConfigurationService.cs](../src/AutoForge.Application/Features/Vehicles/Simulation/DynamicsConfigurationService.cs), + Import around line 68. +- [DynamicsConfiguration.cs](../src/AutoForge.Core/Simulation/DynamicsConfiguration.cs), + ValidateAgainst around line 340. +- [SimulationPageViewModel.cs](../src/AutoForge.UI/Features/Vehicles/Simulation/SimulationPageViewModel.cs), + ImportConfiguration around line 106. + +A complete JSON document referencing an absent profile/revision throws +VehicleProfileCatalogException outside the handled configuration exception path. +An absent engine/transmission module can throw KeyNotFoundException instead. +The import UI catches only DynamicsConfigurationException, so those input errors +can escape the visible/recoverable validation workflow. + +Normalize or explicitly handle these known reference failures at the appropriate +Core/Application/UI boundary, following existing typed-error patterns: + +- Missing profile/revision, missing engine/transmission module and conflicting + calibration/reference inputs produce actionable errors identifying the bad + reference. Do not expose a generic unhandled-error banner for ordinary input. +- Failed import cannot register a config, mutate an active run, change its exact + binding or discard the current valid selection/configuration. +- Preserve malformed/duplicate/unknown/member/numeric validation and valid imports. +- Do not add a blanket catch or repair references by choosing another profile, + module, revision, provider or example. + +Use real service and rendered-page tests. Preserve the existing correctly typed +static-provider/dynamics-control rejection; do not change unrelated provider +semantics or infer model behavior from unverified vehicle metadata. + +### R-02 - Validate and preserve actual drivetrain consistency + +Locations: +[DynamicsConfiguration.cs](../src/AutoForge.Core/Simulation/DynamicsConfiguration.cs), +initial-condition/model checks, and +[DynamicsEngine.cs](../src/AutoForge.Simulation/DynamicsEngine.cs), +ResetState, slip reporting and coupled RPM calculation around lines 368/385. + +Current code accepts redundant initial speed/gear/RPM without enforcing their +declared coupling relation. Reset publishes zero slip. Example: the default +model with engine running, 10 m/s, first gear and 650 rpm passes validation, +but a zero-slip snapshot requires a different RPM by the documented wheel ratio. +Reading before any step can expose that contradiction. + +Runtime code independently caps coupled RPM with Math.Min while leaving +speed/gear/zero slip unchanged. Allowed high-speed/shift configurations can +therefore violate the same equation. A low allowed launch-slip threshold can +also yield reported zero slip while below-idle wheel RPM still uses an uncoupled +engine RPM. + +Required behavior: + +- Define valid independent initial inputs and supported coupling states; reject + inconsistent redundant inputs or derive them by an explicit documented rule. + Do not silently repair them during a diagnostic read or first tick. +- Across supported initial/runtime states, reported locked/zero-slip behavior + must satisfy `rpm = speed/(2*pi*radius)*60*gearRatio*finalDrive` within the + documented numerical tolerance. +- Handle rev/shift/engagement limits physically within the declared simplified + model or fail explicitly outside its operating envelope. Do not independently + clamp RPM while claiming a locked drivetrain at the unchanged speed. +- Validate necessary cross-parameter ranges or model actual slip consistently. + Do not report zero/locked slip when a different RPM is being imposed. +- Do not game the checks by always marking the drivetrain slipping, teleporting + vehicle speed, filtering bad samples or weakening the baseline cruise gate. +- Preserve valid neutral/engine-off/idle/launch/shift behavior, immutable inputs, + source/config bindings and the original full numerical scenario thresholds. + +Reproduce the initial vector above and a reachable high-RPM/low-launch-threshold +case using accepted inputs. If a configuration is genuinely unsupported, reject +it clearly and document the support range rather than return healthy +contradictory telemetry. + +Add independent force/mass/acceleration evidence as well as ratio tests. A +constant known torque case can avoid relying on the production interpolation +routine for expected values. Test boundary/variant inputs, not only the default +45-MPH cruise subset. + +### R-03 - Truthful progress/failures and owned async lifecycle + +Locations: +[DynamicsEngine.cs](../src/AutoForge.Simulation/DynamicsEngine.cs), +phase progress at line 486 and DynamicsRunControl; +[SimulationPageViewModel.cs](../src/AutoForge.UI/Features/Vehicles/Simulation/SimulationPageViewModel.cs), +RunScenarioAsync around line 204 and async controls/telemetry publication; +[DynamicsDiagnosticProvider.cs](../src/AutoForge.Simulation/DynamicsDiagnosticProvider.cs), +failed-state telemetry handling. + +#### Progress + +Cumulative completed scenario time is immediately reset to zero at each phase +transition. Fix progress so its documented overall/phase meaning is accurate +and monotonic across transitions, within [0,1], with completion/reset semantics +explicit. Reset cumulative counters on reset, not after every completed phase. +Distinguish overall scenario percentage from current-phase progress in the UI; +do not label one as the other. + +#### Terminal model/scenario failures + +The UI currently calls SetSuccess for a returned Faulted scenario, then a +telemetry read can overwrite the failure with another success notice. +For a simple pre-fix vector, keep the baseline target but set acceleration's +allowed duration to 0.1 seconds. It cannot reach 45 MPH and must remain a visible +failed scenario, never an overall success-shaped result. + +- Preserve the terminal failure/reason through automatic telemetry refresh and + control completion; valid remaining/last-known data is not scenario success. +- A non-finite/out-of-domain model failure must not emit positive Good poisoned + telemetry or escape as an unhandled JSON serialization exception. Define a + typed negative or explicitly failed/stale last-valid-snapshot policy. +- Do not substitute zeros/empty success or erase failure to make the frame encode. + Keep model time/snapshot/failure state internally consistent. +- Closing/cancelling is not a successful completed scenario; label it accurately. + +#### Async ownership, cancellation and reset + +A second RunScenarioAsync call replaces the UI cancellation slot before the +controller rejects it. Its finally block clears the slot, so Cancel can lose +the still-running first operation. Guard reentrancy without losing that owner. +Post-await updates also need current-session/run guards; old work must not +publish status/telemetry into a reset/reopened/closed session. + +Exercise and enforce one coherent advancement owner. Active pause/stop/reset/ +resume/restart/close must not revive an old paced runner or let a pending delay +retain stale ownership. Reset/stop behavior must not depend on an uncontrolled +wall timer finishing before it can settle. Keep Start/Resume and actual +advancement semantics explicit and truthful rather than treating a state-only +assertion as proof that an active clock was paused. + +Introduce the smallest injectable scheduling/time seam needed to test the actual +pacer and lifecycle deterministically. Use verified existing .NET facilities or +a local focused interface in an existing project. Do not create a clock framework +or use wall delays/poll-until-step loops as correctness evidence. + +## FILES OR PROJECTS EXPECTED TO CHANGE + +- Correct existing Core/Application input-reference/coupling validation. +- Correct Simulation's drivetrain/progress/fault/lifecycle paths as necessary. +- Adapt the existing simulation UI for typed errors, persistent failed outcomes, + reentrancy and current-session/run result publication. +- Extend actual unit/integration/rendered tests with independent numerical and + controlled scheduler cases; minimal test-only helpers are permitted. +- Update README, model/protocol/build documentation and a focused ADR if needed. +- Create only `prompts/Step-04A-Report.md` under `prompts`. + +No new project/host/backend/package or unrelated refactor is expected. Do not +modify assignments, ROADMAP, STATE, prior reports or protected Copilot instructions, +or create override instructions. No staging, commit, push, Git initialization/ +reset or unrelated worktree cleanup. + +## INTERFACE AND DEPENDENCY REQUIREMENTS + +Keep the nine-project graph, one Client/two RCLs, Simulation implementation +outside Application/UI, private test oracle and actual v2 diagnostic telemetry. +Preserve strict v1 static behavior, exact dynamics configuration/reset/session +binding, partial probe/identity states, verified DTC clear and all profile fixes. + +Use strongly typed inputs/results, immutable configurations and bounded explicit +lifecycle ownership. Do not broaden parser/default/target behavior to hide errors, +or introduce physical/calibration/AI capability. + +## TESTING REQUIREMENTS + +### Actual pre-fix reproductions + +Add focused tests for the findings and run them against the current code before +fixing it. Record actual failing assertions/commands, then corrected runs: + +- Complete JSON with unknown profile/revision and missing module references: + actionable handled import UI failure, no partial config or active-run mutation. +- Initial coupled-state mismatch and runtime cap/false-slip vector: no healthy + contradictory state. Assert the independently computed wheel/RPM relation. +- Progress across phase boundaries and short acceleration deadline: progress + cannot jump backwards and Faulted must remain visibly failed. +- Double run/cancel and reset/close/reopen during pending work: active ownership + and current-session presentation remain correct. + +If a suggested vector differs in practice, investigate and record real evidence, +not an invented failure or a weakened assertion. + +### Numerical and controlled lifecycle matrix + +- Valid/invalid direct construction plus JSON/open paths, preserving atomicity. +- Locked/neutral/slipping/limit states before the first tick and across phases, + shifts and parameter boundaries; finite state or explicit supported-domain failure. +- Independent force/mass/acceleration and RPM equations using known inputs; + expected answers must not call the same production functions under test. +- Original idle, <=60 s acceleration, full 300 s cruise >=95% in band, stop/ + return-idle and repeatability gates unchanged. Record new actual metrics if + a justified model correction changes the baseline trajectory. +- Use a controlled scheduler to run the real pacer at more than one pacing factor + and compare equivalent virtual-step state sequences. Reads/renders never tick + physics. Pause an actually active runner; advance scheduled time and prove freeze. +- Active stop/reset/resume/restart/dispose/cancel, overlapping UI requests and + delayed old-run replies: no extra stale tick, revived worker, lost cancellation, + deadlock or old-run success in the new session. +- Faulted finite/out-of-domain runs produce explicit lifecycle/diagnostic/UI + outcomes and no healthy serialization fallback or unhandled bad-number encode. + +Replace the existing fixed-delay/polling lifecycle correctness checks with +deterministic synchronization/clock control. Do not rely on arbitrary elapsed- +time thresholds or change machine date/time/time zone. + +### Full regression and native evidence + +Preserve the 190 current cases (115 unit, 75 integration), mapping intentional +contract/presentation changes and adding substantive coverage. Preserve all +accepted static/profile/wire/verification/partial-discovery invariants. + +Run focused tests, then sequential full Release verification: + +- `dotnet build .\src\AutoForge.slnx --configuration Release --no-restore` +- `dotnet test .\src\AutoForge.slnx --configuration Release --no-build` + +The full build includes the real Windows Client/all nine projects. Record exact +commands/exit outcomes, warnings and per-project discovered/passed/failed/skipped +counts. Restore packages only when needed; no workload-changing action. + +Launch the actual native Client: import invalid-reference JSON and verify a +recoverable visible error, run a finite deadline-failure scenario and verify its +persistent failure, then run the valid baseline with active pause/resume/step/ +pacing/stop/reset, protocol-v2 telemetry, export/import and close. Recheck old +static diagnostics/profile/target/not-found routes. Clearly distinguish native +observations from headless numerical/controlled-scheduler proof. + +## DOCUMENTATION REQUIREMENTS + +Update README and directly related model/config/protocol/lifecycle/testing docs: + +- Reference failure contract and preservation of valid selection/active run. +- Supported initial/coupling/rev-limit envelope, equations and no independent + healthy RPM cap or false locked/slip label. +- Progress definition, terminal-failure telemetry/UI policy, advancement ownership, + async cancellation/reset/current-run guards and scheduling test seam. +- Actual before/after/full-suite/numerical/native evidence and pending Step-04A/ + parent Step-04 acceptance. Preserve the original 190-case report/metrics. + +Keep LF Markdown and historical reports intact. All dynamics remain synthetic +and unvalidated for real-world prediction/tuning/physical programming. + +## ACCEPTANCE CRITERIA + +| ID | Criterion | Required evidence | +|---|---|---| +| AC-01 | Missing/conflicting profile/revision/module references are actionable typed/UI validation failures with atomic import and intact active binding | Direct/service/rendered negative and valid cases | +| AC-02 | Initial and runtime supported coupling/limit states are physically consistent or explicitly rejected/faulted, never healthy independent RPM caps/false lock | Boundary matrix, independent wheel/force equations and real v2 reads | +| AC-03 | Overall/phase progress and terminal failure/telemetry/UI outcomes are truthful; failed/closed/cancelled runs cannot become success notices | Phase-transition/deadline/domain-fault and real UI/diagnostic assertions | +| AC-04 | Actual paced lifecycle has one owner, retained cancellation and current-run publication, without stale tick/revival/deadlock across reset/close | Controlled scheduler and active-run/reentrant UI/session tests, no wall sleeps | +| AC-05 | Original numerical gates, repeatability, 190 baseline cases, static diagnostics/profile/wire/clear/discovery and project boundaries retained | Full scenario metrics/sample totals and per-project regression/reference evidence | +| AC-06 | Actual pre-fix failures, corrected focused/full build/test and required native paths recorded honestly | Exact commands, outcomes, counts and native versus headless proof | +| AC-07 | README/model/config/protocol/test documentation matches corrected support envelope and lifecycle | Changed document list and contract/limitations summary | +| AC-08 | Protected/history/manual workflow preserved, no unrelated capability/dependency/workload action; report complete and worker stops | Preservation/Git review and `prompts/Step-04A-Report.md` | + +Map every criterion to PASSED, FAILED, NOT EXECUTED or BLOCKED with evidence. +COMPLETE requires all required correction, numerical, regression and native checks. +Do not begin Step-05; acceptance belongs to the orchestrator. + +## OUT-OF-SCOPE WORK + +Dashboard/gauge framework, telemetry recording/replay/comparison, physical adapters/ +vehicles, real manufacturer definitions, firmware/calibration/programming/backups, +AI/research/persistence/cloud, extra hosts/projects/packages, broad architecture +replacement and unrelated cleanup. Physical safety/prohibited operations remain. + +## REPORTING REQUIREMENTS + +Create `prompts/Step-04A-Report.md` entirely inside exactly one plain triple-backtick +code fence, without language tag or outside content. Use no nested fences. +Use the same copy-window format for the final chat report. + +Include step/title and COMPLETE/INCOMPLETE/BLOCKED status; R-01/R-02/R-03 root +causes/fixes; files created/modified; any interface/lifecycle changes; unit/ +integration tests and actual before/after evidence; independent numeric metrics/ +tolerances/sample totals; exact build/test commands/results with per-project +counts; controlled pacing and native observations; AC-01 through AC-08 mapping; +documentation/README changes; limitations/issues; deviations/recommendations; +and protected/scope/Git preservation review. + +Save the report and STOP. Do not modify assignments/roadmap/state, create or begin +Step-05, invoke agents, automate handoff, stage, commit or push. diff --git a/prompts/Step-04B-Report.md b/prompts/Step-04B-Report.md new file mode 100644 index 0000000..1e6eb74 --- /dev/null +++ b/prompts/Step-04B-Report.md @@ -0,0 +1,153 @@ +``` +# Step-04B - Reject lifecycle starts before mutating an undrained run + +Status: COMPLETE (worker implementation and verification; manual orchestrator acceptance of Step-04 remains pending) + +## Summary + +Start and resume now reject before mutating engine lifecycle state when a prior +advancement owner is still active or settling. `RunScenarioAsync` follows the +same validate-before-mutate ordering, and `StartRunnerLocked` retains its +defensive one-owner check. The policy is immediate, side-effect-free rejection; +callers retry after the cancelling operation has completed. No wait is performed +while holding the gate needed by old-owner cleanup. + +The original 202 Step-04A tests and numerical gates are preserved. Five new +focused cases bring the final total to 126 unit and 81 integration tests +(207 total). No project, package, public interface, physics, protocol, schema +or physical capability was added or changed. + +## Files changed for Step-04B + +- `src/AutoForge.Simulation/DynamicsEngine.cs` +- `src/tests/AutoForge.UnitTests/DynamicsEngineTests.cs` +- `src/tests/AutoForge.IntegrationTests/DynamicsWorkflowTests.cs` +- `docs/simulation.md` +- `docs/build-and-test.md` +- `README.md` +- `prompts/Step-04B-Report.md` (created) + +Architecture/interface changes: none. The existing private lifecycle helper is +shared by Start/Resume; the equivalent scenario start path validates the owner +before changing Stopped/Paused state. Existing run status, controls, services, +protocol and UI contracts are unchanged except that the failed overlapping +command no longer leaves a mutated Running state. + +## Before/after regression evidence + +The controlled pre-fix reproduction held the old pacer in cancellation cleanup. +The three transitions threw the expected owner-rejection exception only after +changing state: + +- Pause -> Resume: expected `Paused`, observed `Running` at step 1 / 0.1 s. +- Stop -> Start: expected `Stopped`, observed `Running` at step 1 / 0.1 s. +- Reset -> Start: expected `Stopped` at step 0 / 0.0 s, observed `Running` at + step 0 / 0.0 s. + +These were behavioral state assertions, not a compilation failure. The +independent duplicate-start/invalid-resume case passed before the fix. + +After the fix, the unit regression asserts the complete status record and engine +sample count before and after each rejected call, verifies cleanup remains +blocked until released, awaits old-owner completion, then retries once. It +asserts exactly one new step/sample and that pause cancels the new owner at that +step. The real IntegrationTests DI/session/UI path also rejects `RunScenario` +and Resume during the pending pause cleanup, preserves the status snapshot, and +renders an error tone rather than reporting resumed/started success. + +## Contract matrix + +| ID | Outcome | Evidence | +|---|---|---| +| C-01 | PASSED | After prior cleanup settles, Resume from Paused and Start from Stopped create the new owner; tests observe a distinct delay and exactly one new step/sample. | +| C-02 | PASSED | Controlled Pause -> Resume rejection preserves the complete status and sample count. Real SimulationPageViewModel integration also rejects Resume and the equivalent RunScenario path with a visible error while cleanup is blocked. | +| C-03 | PASSED | Controlled Stop -> Start and Reset -> Start rejection preserve complete status and sample count; reset remains at step/time zero and stop remains stopped. | +| C-04 | PASSED | Releasing the cleanup barrier allows the original transition to finish; one retry advances once, old delay/task does not revive, and a subsequent pause freezes the new owner. | +| C-05 | PASSED | Duplicate Start, Resume while Stopped, and Start/Resume after disposal remain explicit failures with intact status/ownership. Existing cancellation, disposal, reset, close and UI-run regressions also pass. | + +Focused checks: + +- Unit command: `dotnet test .\src\tests\AutoForge.UnitTests\AutoForge.UnitTests.csproj --configuration Release --no-restore --filter "FullyQualifiedName~StartOrResumeDuringOwnerDrainRejectsWithoutChangingStatus|FullyQualifiedName~DuplicateStartAndInvalidResumeDoNotChangeLifecycleOrOwner"` — exit 0; 4 passed, 0 failed/skipped. +- Integration command: `dotnet test .\src\tests\AutoForge.IntegrationTests\AutoForge.IntegrationTests.csproj --configuration Release --no-restore --filter "FullyQualifiedName~ResumeRejectedDuringOwnerDrainIsVisibleThroughRealSimulationPage|FullyQualifiedName~ScenarioOwnerCannotBeReplacedAndResetOrCloseSuppressesOldRunPublication"` — exit 0; 2 passed, 0 failed/skipped. + +## Full verification and numerical preservation + +Commands were run sequentially after the final code changes: + +- `dotnet build .\src\AutoForge.slnx --configuration Release --no-restore` — exit 0; all nine solution projects built; 0 warnings, 0 errors. +- `dotnet test .\src\AutoForge.slnx --configuration Release --no-build` — exit 0; `AutoForge.UnitTests`: 126 passed; `AutoForge.IntegrationTests`: 81 passed; 207 total, 0 failed, 0 skipped. + +All 202 Step-04A baseline cases are included in those final counts, plus the +five owner-drain cases. The full unit suite continues to verify the original +deterministic baseline: 3,361 samples / 336.1 virtual seconds; 650 rpm warm +idle; acceleration to 20.1473 m/s in 10.3 s with four shifts; all 3,000 cruise +samples within the original 45-MPH +/- 1-MPH band while coupled; braking to +0.0000 m/s in 5.8 s; 10.0 s return idle; and 0.518387 kg modeled fuel. +No numerical thresholds or model behavior were changed. + +## Native Client smoke + +The actual Windows Client was launched from +`src\AutoForge.Client\bin\Release\net10.0-windows10.0.26100.0\win-x64\AutoForge.Client.exe` +with task-local WebView2 DevTools port 9347 and an isolated temporary profile. +The native `/simulation` UI explicitly loaded profile +`autoforge.synthetic.test-truck` revision 1, selected +`autoforge.simulation.dynamics`, created the warm-baseline configuration +`sha256:v1:e8991ae139b54959ec53a4fe64b08dc9bfc03feb533496cf741f2c9f3a2342da`, +and opened a stopped session. + +The observed UI sequence was: + +- Start, Pause: `Paused`, 0.7 s / step 7. +- Resume, Stop: `Stopped`, 0.8 s / step 8. +- Restart, Stop: `Stopped`, 0.9 s / step 9. +- Reset: new session `Stopped`, 0.0 s / step 0; protocol-v2 telemetry read + included `SYNTHETIC_DYNAMIC` values at step 0. +- Close: UI reported the session and its engine/pending work were released. + +This manual native click-path verifies normal lifecycle/time/telemetry behavior; +it does not claim to force the cleanup race. The exact cancellation-drain +interleaving is established by the controlled unit and real service/UI +integration barriers. The task-launched Client (PID 22924), WebView2 helpers, +port 9347 listener and isolated temporary profile were stopped/removed and +verified absent. + +## Acceptance criteria + +| ID | Result | Evidence | +|---|---|---| +| AC-01 | PASSED | C-01 through C-05 are mapped above to controlled pre-fix/post-fix snapshots, owner cleanup/retry, and invalid/closed transition assertions. | +| AC-02 | PASSED | Cleanup remains awaitable without holding its gate; controlled retry/cancel/dispose and real UI/service rejection pass. No duplicate owner, stale task revival or false resumed/started success was observed. | +| AC-03 | PASSED | Nine-project Release build: exit 0, 0 warnings/errors. Full suites: 126 unit + 81 integration passed. Original numerical gates pass. Native Client lifecycle/reset/telemetry/close smoke completed; forced interleaving is correctly distinguished as headless controlled evidence. | +| AC-04 | PASSED | This report contains the contract/evidence matrix and source-path self-review. `docs/simulation.md`, `docs/build-and-test.md` and `README.md` document the policy, evidence and pending acceptance status. | +| AC-05 | PASSED | Scope stayed within the listed Step-04B code/tests/docs/report. Protected assignment, ROADMAP, STATE and historical reports were not edited by this work. Existing dirty/untracked Step-04 history was retained; no staging, commit, push, agent or Step-05 work occurred. `git diff --check` exited 0; Git emitted its configured LF-to-CRLF working-copy notice for README. | + +## Worker source-path self-review + +- Start and Resume enter `StartOrResumeAsync`: `EnsureOpen` and + `EnsureNoActiveAdvancementOwner` precede `DynamicsEngine.Start/Resume`. +- `RunScenarioAsync` performs the same owner check before changing Stopped or + Paused lifecycle state. A currently running or draining owner is rejected + before a second task can be installed. +- `StartRunnerLocked` retains its owner check as a defensive invariant. +- Pause/Stop/Reset mutate their intended lifecycle state, cancel the runner, + release the gate, and only then await cleanup. The old runner can acquire the + gate in its `finally` block and clear its ownership slot. Start/Resume do not + wait while holding that gate. +- `EnsureOpen` remains ahead of owner validation; invalid, duplicate, closed + and disposed requests remain explicit errors. UI lifecycle and scenario + wrappers surface rejected commands as error notices; real integration tests + assert rejection does not change run state. +- Test barriers release in `finally`; controlled tests assert status, sample, + cleanup, retry and cancellation behavior without sleeps/polling. +- Full Release tests preserve the earlier numerical, protocol and lifecycle + regressions. Native evidence verifies the normal Client path only. + +## Limitations and handoff + +The forced cleanup interleaving is not a human-timed native UI scenario; it is +covered by deterministic controlled pacers in unit and real DI/session/UI +integration tests. Numerical outputs remain synthetic. No other deviation or +unresolved implementation issue remains for this assignment. Step-04 acceptance +remains the orchestrator's responsibility. No Step-05 work was started. +``` diff --git a/prompts/Step-04B.md b/prompts/Step-04B.md new file mode 100644 index 0000000..19dda5d --- /dev/null +++ b/prompts/Step-04B.md @@ -0,0 +1,171 @@ +# Step-04B - Reject lifecycle starts before mutating an undrained run + +## STEP IDENTIFIER + +Step-04B, focused follow-up to existing Step-04A R-03 / AC-04. +Step-04 remains NOT ACCEPTED. This is the sole active assignment; Step-05 is blocked. + +## STEP TITLE + +Make Start/Resume during pending owner cleanup side-effect-free. + +## OBJECTIVE + +Fix one existing lifecycle ordering defect. Do not redo the corrected physics, +reference, progress, failure, protocol or UI-generation work. Preserve all 202 +current cases and the original numerical thresholds. + +Execute only this assignment, write `prompts/Step-04B-Report.md`, and STOP. + +## ARCHITECTURAL CONTEXT + +Read [STATE.md](STATE.md), [Step-04A](Step-04A.md), its +[report](Step-04A-Report.md) and the prospective +[WORKER-QUALITY-GATE.md](WORKER-QUALITY-GATE.md). + +Keep the nine-project .NET 10 modular monolith, sole native Client/two RCLs, +Simulation-owned implementation and normal Application/UI ports. No new project, +package, host, backend or physical capability. + +The new shared gate applies to this new work, not retroactively to Step-04A. +The defect below is already within that assignment's overlap/one-owner criterion. + +## CURRENT IMPLEMENTATION STATE + +Step-04A corrected R-01 reference errors, R-02 coupling/limits, progress/fault +handling and most R-03 ownership/UI issues. The worker reports 122 unit + 80 +integration passes (202 total, zero failed/skipped), a zero-warning/error complete +Release build, unchanged numerical baseline and native smoke. + +One ordering issue remains in +[DynamicsEngine.cs](../src/AutoForge.Simulation/DynamicsEngine.cs): + +- StartOrResumeAsync (around line 772) mutates engine lifecycle first. +- StartRunnerLocked (around line 936) then rejects a still-active task. +- Pause/Stop/Reset cancel and await that task after releasing the command gate. + +A Start/Resume arriving while the prior task is still draining can therefore +throw after setting Running. The cancelled old task then exits, leaving a +rejected operation's Running state without an owner. + +This is source-review evidence; the orchestrator did not execute a reproduction. +Reinspect Git/instructions and preserve pre-existing dirty implementation/history. + +## REQUIRED IMPLEMENTATION + +Use the smallest clear ordering/transition guard that validates owner eligibility +before any engine lifecycle mutation. During prior-owner drain, this assignment's +default policy is explicit side-effect-free rejection; a correctly serialized +wait policy is acceptable only if documented/tested and does not deadlock cleanup. + +Do not hold a gate across an await if the old runner needs it to finish. +Do not paper over the issue with a catch that leaves mutated state, remove the +one-owner check, force a second runner or introduce sleeps. + +### Frozen contract matrix + +| ID | Precondition/action | Required outcome | +|---|---|---| +| C-01 | Stopped/Paused, old owner fully settled, valid Start/Resume | Running with exactly one new owner and unchanged configuration | +| C-02 | Pause has cancelled an owner but its cleanup is pending; Resume arrives | Rejection before mutation (or documented serialization); no orphan Running state | +| C-03 | Stop or Reset has cancelled an owner but cleanup is pending; Start arrives | Same side-effect-free policy; time/step/progress/configuration remain unchanged by a rejected action | +| C-04 | Old cleanup completes, then caller retries normally | Valid start/resume works once; no revived old task, extra tick or lost cancellation | +| C-05 | Closed/disposed or invalid lifecycle/duplicate start | Existing explicit rejection and intact state/ownership; previous regressions preserved | + +Audit both Start and Resume through the shared helper and any equivalent +start path touched by the fix. All relevant entry points must follow the same +ordering rule. Do not expand this into a controller redesign. + +## FILES OR PROJECTS EXPECTED TO CHANGE + +- Existing DynamicsRunControl guard/ordering in Simulation. +- Existing unit/real integration tests and narrowly needed test-only pacer helper. +- Directly related lifecycle/build/README text only if changed or status needs it. +- Only `prompts/Step-04B-Report.md` under `prompts`. + +No physics equations/parameters, config/wire schema, provider, feature UI, dependency +or project changes are assigned. Do not modify assignments, ROADMAP, STATE, +previous reports or protected instructions. No stage/commit/push or destructive Git. + +## INTERFACE AND DEPENDENCY REQUIREMENTS + +Keep existing public control semantics except the corrected failed-transition +side effect. Preserve exact run/config/session binding, source/oracle boundaries, +single advancement owner, cancellation, progress/failure handling and static/ +dynamic diagnostics. No broad catches, fallback states or unauthorized workload +install/update/restore/repair/rollback. + +## TESTING REQUIREMENTS + +1. Add a controlled pacer with a barrier that acknowledges cancellation but holds + task cleanup until explicitly released. This is a test-only cancellation-drain + interleaving, not a production delay. Release barriers in finally even if an + assertion fails, so a failed pre-fix test cannot strand the runner. +2. Reproduce C-02/C-03 against the current code. Record the actual rejection plus + invalid state change, then apply the fix and show the prior state unchanged. +3. Assert the complete relevant status snapshot and owner/tick behavior, not just + exception type. After cleanup, prove C-01/C-04 and no old task revival. +4. Exercise Pause->Resume, Stop->Start and Reset->Start overlaps; preserve C-05. + No Thread.Sleep, Task.Delay polling or probabilistic race/stress assertions. +5. Use actual control/engine behavior and the existing real service/UI path where + affected. Do not mock away the controller under test. A rejected UI action + must not be presented as a successful resumed/started run. + +Follow the shared worker self-review gate: specifically walk validate-before- +mutate and pending-cleanup paths after the first green run. Fix any finding inside +this assignment before handoff. + +Run focused regressions, then sequentially: + +- `dotnet build .\src\AutoForge.slnx --configuration Release --no-restore` +- `dotnet test .\src\AutoForge.slnx --configuration Release --no-build` + +Preserve all 202 baseline cases (122 unit, 80 integration), numerical gates and +nine-project/native build. Record exact commands/exit results/warnings/counts. +No new dependency or restore is expected absent a real missing-dependency failure. + +Native baseline smoke: open the real Client, start an actual run, pause/resume, +stop/restart, reset/close and confirm normal state/time/telemetry. The forced +cleanup interleaving is controlled-test evidence; do not claim a human-timed +click sequence proves it or add a runtime fault console just for native coverage. +Stop only task-owned smoke helpers; report limitations honestly. + +## DOCUMENTATION REQUIREMENTS + +Document the exact pending-transition reject/wait policy and side-effect-free +failed command behavior in the existing lifecycle guide, plus current worker/ +pending-acceptance status and new evidence in README/build guidance as appropriate. +Preserve previous numerical metrics/reports and LF Markdown. No new planning file. + +## ACCEPTANCE CRITERIA + +| ID | Criterion | Evidence | +|---|---|---| +| AC-01 | C-01 through C-05 hold for both Start/Resume and relevant pending-drain transitions; rejection cannot mutate lifecycle or orphan ownership | Controlled pre-fix/post-fix status/owner/tick assertions | +| AC-02 | Cleanup/retry/cancel/close remain correct without deadlock, duplicate owner, stale work or UI false success | Real control/service coverage and unchanged baseline invariants | +| AC-03 | All 202 cases, original numerical gates, complete Release/native build and required smoke pass | Exact commands, warnings, per-project counts and native/test distinction | +| AC-04 | Contract/evidence matrix and worker source-path self-review are complete; docs match the policy | Report matrix, self-review summary and changed-document list | +| AC-05 | Scope/protected/history/manual workflow preserved; report saved and worker stops | Git/preservation review and `prompts/Step-04B-Report.md` | + +Use PASSED, FAILED, NOT EXECUTED or BLOCKED with actual evidence. COMPLETE +requires all assigned checks. Do not add new acceptance conditions or features. + +## OUT-OF-SCOPE WORK + +Physics/configuration/protocol redesign, new model features, dashboards, telemetry +recording, hardware, tuning/programming, AI/persistence, new projects/packages and +unrelated cleanup. All existing safety/prohibited-operation restrictions remain. + +## REPORTING REQUIREMENTS + +Create `prompts/Step-04B-Report.md` entirely inside exactly one plain triple-backtick +code fence, without language tag or outside content. Use no nested fences. +Include identifier/title/status, implemented fix, files created/modified, +architectural/interface changes (or none), unit/integration coverage and actual +before/after results, C-01 through C-05 and AC-01 through AC-05 evidence, +build/test commands with exit outcomes/warnings/per-project counts, native +distinction, worker self-review, docs/README changes, limitations/outstanding +issues/deviations/recommendations and preservation review. + +Save the report and STOP. Do not change assignments/roadmap/state, create or begin +Step-05, invoke agents, automate handoff, stage, commit or push. diff --git a/prompts/Step-05.md b/prompts/Step-05.md new file mode 100644 index 0000000..411bca5 --- /dev/null +++ b/prompts/Step-05.md @@ -0,0 +1,251 @@ +# Step-05 - First configurable numeric/bar live dashboard + +## STEP IDENTIFIER + +Step-05. Corrected Step-04/04A/04B were accepted on 2026-10-28. +This is the sole active implementation assignment. + +## STEP TITLE + +Display configurable numeric and bar gauges from one session-owned diagnostic +acquisition feed, with explicit missing/stale/uncertain/range states. + +## OBJECTIVE + +One user outcome: configure and observe a small live dashboard on an existing +explicitly opened static or dynamics diagnostic session. +One primary new behavioral contract: a shared session-bound acquisition owner, +independent of gauge visibility. Gauge configuration is validated in-memory data, +not a new persisted format or another application subsystem. + +Read [WORKER-QUALITY-GATE.md](WORKER-QUALITY-GATE.md), apply the frozen matrix +below before coding, self-review after the first green run, write +`prompts/Step-05-Report.md`, and STOP for manual review. + +## ARCHITECTURAL CONTEXT + +Read [STATE.md](STATE.md), [architecture](../docs/architecture.md), +[protocol v1](../docs/synthetic-diagnostics-v1.md) and +[v2](../docs/synthetic-diagnostics-v2.md). + +Keep all nine projects and one native MAUI Client. Components owns generic pure +UI controls and has no AutoForge project reference. Application owns feed/ +configuration use cases using Diagnostics ports. UI owns composition/editor/ +interaction. Client is DI/lifecycle only. No new host, project, package or +Application/UI dependency on Simulation implementation. + +All source/tests remain under `src`, tests under `src/tests`. Root project +directories remain `docs`, `src`, `prompts`. Manual handoff/protected/history +rules in the shared gate remain mandatory. + +## CURRENT IMPLEMENTATION STATE + +Accepted features already provide: + +- Exact profile/configuration/provider/session selection; static v1 and dynamics + v2 providers; validated identity/service discovery and actual encoded reads. +- DiagnosticSignal/SignalSnapshot values, units, quality, synthetic origin, + request time and v2 model/config/run context. +- Existing `/diagnostics` and `/simulation` workflows with owned ActiveSession, + explicit close/reset, actual telemetry reads and current-generation guards. +- StatusNotice and headless HtmlRenderer/real-DI integration tests. + +Worker-reported baseline: clean complete nine-project Release build; 126 unit + +81 integration passes (207 total, zero failed/skipped), numerical gates and +native baseline smoke. No chart/dashboard acquisition service exists yet. +The orchestrator did not rerun those checks. + +Reuse [DiagnosticSession](../src/AutoForge.Application/Features/Vehicles/Diagnostics/DiagnosticSessionService.cs) +and current host feature view models. Do not duplicate profile/provider opening, +physics, protocol/version or virtual-clock behavior. Inspect actual code/Git +before editing and preserve existing dirty work and historical reports. + +## REQUIRED IMPLEMENTATION + +### Frozen contract matrix + +These are the acceptance outcomes, not examples to replace with weaker proxies. + +| ID | Input/precondition | Required result | +|---|---|---| +| C-01 | Good finite 850 rpm; display 0..1000, decimals 0 | Numeric displays 850 with rpm; bar projects 85%; actual source/context retained. Legitimate numeric zero displays zero, not missing. | +| C-02 | Finite value below/above display range, e.g. -10 or 1100 | Preserve actual numeric value; clamp bar geometry only to 0/100%, with explicit low/high indication. No fabricated in-range reading. | +| C-03 | Null/missing/non-numeric value or Unknown quality; finite Uncertain quality | Unknown/unavailable shows `--` and reason, not zero/current bar. Uncertain finite data may display only with an explicit warning state, never Good. | +| C-04 | Invalid definition/range/precision/binding/unit/count | Typed visible rejection before mutation; previous valid definitions/source/feed stay intact. Include finite-span overflow as well as NaN/infinity/min>=max. | +| C-05 | Repeated Start on same running feed; Start while Stop drains; retry after Stop | First is idempotent with one owner; draining Start rejects before mutation; Stop cancels/awaits cleanup; retry starts one owner. | +| C-06 | Source close/reset/replacement or late reply from old generation | Old owner/resources stop; old values do not appear in the new context. Pending new data is explicit; no global active-source fallback or stale publication. | +| C-07 | Gauges hidden/removed/re-rendered/disposed while source monitoring remains open | Acquisition continues independently. Widget disposal only removes its subscription; explicit monitoring stop/source close/owning scope disposal ends acquisition. | +| C-08 | Last good value followed by read failure; no previous value; later recovery/stop | Retain a value only as clearly last-known Stale with failure/source time. With no valid prior value show Error/`--`. Recovery restores correct state. Stopped data is not labeled live. | +| C-09 | Multiple gauges bind signals on the same module; controlled polling; paused dynamics | One read.signals per eligible module per dashboard poll, not per gauge/render. Polling does not advance physics; v1 static and v2 dynamic source/time semantics are preserved. | +| C-10 | Real host UI configure/edit/hide/stop/reset/close and current error cases | Same actual Application feed/validated definitions/pure components are used. No mock live data, oracle read, shell restructuring or hidden owner. | + +### A. Small validated in-memory dashboard + +Support zero to eight gauges using numeric or horizontal-bar type, a stable +unique gauge ID, label, explicit module/signal binding, exact reported unit, +finite minimum/maximum with finite positive span, and integer decimal precision +0..3. Copy definitions; reject duplicate IDs/undefined kinds/invalid fields. +Use documented identifier comparison rules consistent with signal/module IDs. + +Bindings are selected explicitly from actually read, identity-verified session +signal metadata, not role names or guessed RPM aliases. Reject unknown module/ +signal or requested-unit mismatch during configuration. Runtime loss/change of a +previously valid signal becomes an explicit data state, not a silent rebind. +No unit conversion is assigned; display the exact source unit. + +Editing/rejecting/removing a gauge cannot mutate model inputs, run state, source +selection or other valid definitions. Empty dashboards are valid and do not stop +an explicitly running acquisition owner. + +### B. One real session-owned acquisition feed + +Add a focused Application feature under Telemetry/LiveDashboard or equally clear +ownership. Bind to the existing explicit DiagnosticSession and immutable context: +session/target/profile plus available config/run identity. No global current +vehicle/provider registry or competing open workflow. + +Use one owned loop per bound dashboard/session. Repeated acquisition of that same +owner must share it or reject duplicate ownership before mutation; repeated Start +on the owner is idempotent as C-05 states. Do not create a poll loop per component. + +On explicit monitoring Start, obtain verified service/endpoint/signal availability +through actual discovery/read ports, then publish an initial snapshot. Subsequent +cycles wait 250 ms after the preceding completed cycle; no overlapping polls. +Use a small injectable scheduler/time seam for deterministic tests, not the +physics pacer or a new clock project. This interval is not a real-time guarantee +and is not a new user-configurable rate in this slice. + +Group reads by eligible module. Acquire independently of current widget count/ +visibility and publish immutable latest snapshots only; no unbounded history, +recording, interpolation or replay. Preserve per-response source/quality/request +time and model step/time; do not claim simultaneous capture for running modules. + +Freshness here is cycle-based, not a new wall-age SLA: initial/pending reads, +last completed data, failed-cycle Stale/Error and Stopped are explicit. Show +source/sample context and refresh state. No silent zeros or invented timestamps. + +Tie ownership to source/feature lifetime, not the Razor widget. Coordinate actual +close/reset/disposal so the worker and any pending read are cancelled/drained; +source lifetime integration may be added narrowly if needed. Prevent old +generations from publishing after stop/restart/rebind. Do not wait under a gate +needed by cleanup. Monitoring never starts/stops/steps physics. + +### C. Pure reusable controls and real UI + +Add generic numeric/bar renderers in Components. They consume presentation data, +not DiagnosticSession, Simulation, native drivers or acquisition services. +Use accessible labels/value/state descriptions and safe text rendering. +Handle invalid public presentation parameters explicitly, never healthy NaN/ +infinite width or an unhandled user-input rendering failure. + +Compose a reusable dashboard panel/editor in UI within the existing `/diagnostics` +and `/simulation` session workflows. The host/session owns the feed; mounting/ +hiding widgets does not own it. Provide explicit Start/Stop monitoring, add/edit/ +remove gauge controls and a simple fixed layout. Preserve existing controls/routes. + +Label synthetic/static/dynamic origin and selected source clearly. Missing, +uncertain, stale/error, out-of-range and stopped states must be visually/textually +distinct. Last-known values may remain only with their stale/stopped label and +source time; they are not current measurements or real vehicle evidence. + +## FILES OR PROJECTS EXPECTED TO CHANGE + +- Application dashboard definitions/validation/feed use cases and minimal session- + lifetime integration necessary for owner cleanup. +- Components numeric/bar renderers and UI dashboard composition/host wiring. +- Client DI only if needed; existing unit/integration tests and related docs. +- Only `prompts/Step-05-Report.md` under `prompts`. + +No persisted dashboard format, new project/dependency, provider/protocol/model/ +clock redesign, extra host or physics change is assigned. Do not edit assignments, +ROADMAP, STATE, shared gate or historical reports. No protected-instruction edit, +staging/commit/push, destructive Git or unrelated worktree cleanup. + +## INTERFACE AND DEPENDENCY REQUIREMENTS + +Keep the nine-project graph, Components independence, Application/Diagnostics +boundary and private simulation oracle. Preserve wire/profile schemas, exact +source/config binding, verified clear, partial identities and clock ownership. +Only identity-verified endpoints that implement read.signals are polled; unknown/ +restricted/unavailable metadata does not fabricate support. + +Use typed visible errors and validate-before-mutate. No broad catches, fake data, +target fallback, direct engine access, real hardware or workload/system action. +Keep the shared quality gate's frozen-criteria and self-review requirements. + +## TESTING REQUIREMENTS + +Implement C-01..C-10 as relevant component, validation, feed, actual DI and rendered +tests before handoff. In particular: + +- Assert exact 850/85%/unit/precision and true-zero rendering, out-of-range geometry + versus actual value, unknown/uncertain/stale/error/stopped state and safe text. +- Prove invalid definitions (including non-finite span) are rejected atomically. +- Drive the real feed with controlled ticks/barriers through duplicate start, + pending stop/restart, close/reset/new source and delayed old response. +- Count actual wire reads for shared bindings and hidden/zero widgets. Preserve + model step/time while the dynamics source is paused. No sleeps/polling or + arbitrary elapsed-time thresholds as correctness proof. +- Exercise both actual static v1 and dynamics v2 sessions; inject data loss/ + negative responses below the feature boundary, not a mock dashboard service. +- Render the real panel/editor against actual Application DI and ensure component + disposal does not stop source acquisition while explicit close does. + +Preserve the 207-case baseline (126 unit, 81 integration); map intentional UI +assertion changes without deleting safety/error checks. Run focused tests, then +sequential full Release build/test using the existing commands/runner: + +- `dotnet build .\src\AutoForge.slnx --configuration Release --no-restore` +- `dotnet test .\src\AutoForge.slnx --configuration Release --no-build` + +No new dependency/restore is expected absent a real missing-dependency failure. +The complete build includes the real Windows Client/all nine projects. + +Native smoke: open an actual static session and configure numeric/bar views of +its signal; verify live/stop/hide/range behavior. Repeat with a real dynamics +session, pause/step/read to observe correct value/time and prove monitoring alone +does not step it; test invalid range/binding, stop/reset/close and old routes. +Distinguish native observations from controlled fault/lifecycle proof. + +## DOCUMENTATION REQUIREMENTS + +Update README/index/architecture/build guide and concise dashboard usage/contracts: +input limits/binding/unit policy, state semantics, cycle-based freshness, one +owner/visibility/lifetime rules, v1/v2 sample context and actual evidence. +Mark Step-04/04A/04B accepted, Step-05 worker status pending review, and retain +historical reports. No dashboard persistence, charts or conversions are claimed. + +## ACCEPTANCE CRITERIA + +| ID | Criterion | Evidence | +|---|---|---| +| AC-01 | C-01..C-04 exact rendering/projection/state and atomic definition rules | Component/validation matrix and actual UI failures | +| AC-02 | C-05..C-08 one-owner, cleanup/generation/visibility and state rules hold | Controlled feed/service/rendered lifecycle tests | +| AC-03 | C-09 actual static/dynamic wire acquisition is grouped and independent of renders/physics | Per-module frame counts, true source/time and paused-step assertions | +| AC-04 | C-10 real host workflow uses pure Components and actual Application feed without scope expansion | Reference/source review and rendered/native evidence | +| AC-05 | Existing 207 cases/invariants, full nine-project Release/native build and required smoke pass | Exact commands, warnings, per-project counts and coverage distinction | +| AC-06 | Contract/evidence matrix, self-review, docs/README and limitations match implementation | Report mapping and documentation summary | +| AC-07 | Protected/history/manual workflow preserved; complete report saved and worker stops | Preservation/Git review and `prompts/Step-05-Report.md` | + +Use PASSED, FAILED, NOT EXECUTED or BLOCKED precisely. COMPLETE requires assigned +checks; optional future preferences are not acceptance requirements. + +## OUT-OF-SCOPE WORK + +Dashboard JSON/storage/persistence, charts/time series, analog/SVG clusters, +drag/drop/layout designers, new unit conversion/rate/freshness policies, recording/ +replay/comparison, model/protocol/physics changes, hardware/calibration/AI, +new projects/packages/hosts/platforms and unrelated cleanup. + +## REPORTING REQUIREMENTS + +Create `prompts/Step-05-Report.md` entirely inside exactly one plain triple-backtick +code fence, without language tag or outside content. Use no nested fences. +Include identifier/title/status, implemented functions, files created/modified, +architecture/interfaces, unit/integration and C-01..C-10/AC-01..AC-07 evidence, +exact build/test results with warnings/exits/per-project counts, native versus +controlled observations, worker self-review, docs/README, limitations/outstanding +issues/deviations/recommendations and preservation review. + +Save and STOP. No orchestration/shared-gate edit, Step-06, agents, automatic +handoff, stage, commit or push. diff --git a/prompts/WORKER-QUALITY-GATE.md b/prompts/WORKER-QUALITY-GATE.md new file mode 100644 index 0000000..7bccba9 --- /dev/null +++ b/prompts/WORKER-QUALITY-GATE.md @@ -0,0 +1,82 @@ +# Worker quality gate - prospective manual handoffs + +Effective 2026-10-28 for new assignments beginning with Step-04B. +This supplements the active assignment and existing protected-file/manual +workflow rules. It does not impose new criteria on completed work, authorize +agents/automation, or replace repository instructions. + +## 1. Before coding: make the contract executable + +Read the assignment, current implementation and its acceptance cases. Establish +a compact matrix for the changed behavior, not an inventory of every project: + +| Case | Input/precondition | Expected result and unchanged state | Test/evidence | +|---|---|---|---| +| Normal | Valid explicit selection/input | Exact successful output | Named behavior test | +| Rejected | Invalid/missing/unknown input | Typed visible failure, no partial mutation/fallback | Negative test | +| Boundary/partial | Relevant limit, unknown or incomplete result | Defined explicit outcome, not invented data | Boundary test | +| Lifecycle | Only if affected: cancellation/reentry/overlap/close | One owner, valid transitions, no stale publication | Controlled interleaving test | +| Integration | Real producer/consumer and UI where affected | Same validated contract end-to-end | Real integration/native evidence | + +Apply only relevant rows and explain any N/A briefly. The assignment supplies +the decisive vectors; add tightly coupled edge cases found during implementation. +For bug fixes, execute a real pre-fix regression and record the actual failure. +Do not invent results or use compilation failure as a behavioral reproduction. + +If the intended contract is genuinely ambiguous or requires a material design +change, report the exact choice/blocker; do not silently guess a success default. +Do not broaden scope to speculative future features. + +## 2. Implement and verify the actual boundary + +- Validate syntax, semantic references, cross-field invariants and eligibility + before committing state or publishing success. +- Rejected actions leave the prior valid state/ownership intact. An acknowledgement + is not verification; a partial/unknown result is not complete success. +- Keep exact identity/version/unit/time/source semantics. No role-based fallback, + hidden defaults, false zero data, swallowed failure or broad exception mask. +- When state/lifetime changes, test competing requests while work is pending, + not only sequential commands after each await completes. +- Use controlled schedulers/barriers for timing. No arbitrary sleeps/polling as + correctness proof. Always release test barriers/resources in finally cleanup. +- Exercise the real implementation under test. Faults may be injected below the + feature boundary; do not mock away the feature or bypass transport/validation. +- Preserve existing behavior and named regressions; explain intentional contract/ + presentation changes. Test counts alone do not prove obligations were covered. + +Run focused checks, then the assignment's required complete build/regressions +sequentially. Package/system changes remain subject to existing authorization. + +## 3. After the first green run: self-review before handoff + +Do one source-path review of the changed flow: + +1. List affected public entry points and actual producers/consumers. +2. Walk normal, rejected, partial and relevant overlap/cleanup paths against the + matrix. Inspect validation order, not just error messages. +3. Check every success/verified/healthy UI or trace commitment occurs only after + required validation, and no old operation can publish into a newer context. +4. Check failure/cancel/close cleanup, state rollback and resource ownership. +5. Check every required matrix row has a meaningful assertion and executed result. +6. Check actual dependencies/Git scope, docs/README, protected files and no secrets. + +Fix issues found in this pass inside the current assignment and rerun affected +checks. Do not declare COMPLETE after only the first plausible green result or +hand known defects to the orchestrator as recommendations. + +This is the worker's own review; do not invoke another agent or automate handoff. +It is a short risk-based check, not a new document/report file or broad unrelated +audit. + +## 4. COMPLETE means the exit contract passed + +In the required step report, include the compact contract/evidence matrix, exact +commands/outcomes, per-project counts, relevant numerical thresholds, self-review +summary and honest native versus headless coverage. + +Use PASSED, FAILED, NOT EXECUTED or BLOCKED precisely. COMPLETE requires all +assigned acceptance checks; use INCOMPLETE/BLOCKED for unresolved requirements. +Keep historical reports unchanged and report necessary deviations explicitly. + +After saving the single fenced report, STOP. No future step, orchestration edit, +automatic agent communication, staging/commit/push or unauthorized system change. diff --git a/src/AutoForge.Application/Features/Vehicles/Diagnostics/DiagnosticSessionService.cs b/src/AutoForge.Application/Features/Vehicles/Diagnostics/DiagnosticSessionService.cs index 0965a7b..c18d4b3 100644 --- a/src/AutoForge.Application/Features/Vehicles/Diagnostics/DiagnosticSessionService.cs +++ b/src/AutoForge.Application/Features/Vehicles/Diagnostics/DiagnosticSessionService.cs @@ -1,6 +1,7 @@ using AutoForge.Application.ExecutionTargets; using AutoForge.Application.Features.Vehicles.Profiles; using AutoForge.Core.ExecutionTargets; +using AutoForge.Core.Simulation; using AutoForge.Core.Vehicles; using AutoForge.Diagnostics; using Microsoft.Extensions.DependencyInjection; @@ -13,7 +14,8 @@ public enum DiagnosticSessionFailure UnsupportedTargetKind, DefinitionNotFound, InvalidDefinition, - SessionConflict + SessionConflict, + DynamicsCapabilityUnavailable } public sealed class DiagnosticSessionException( @@ -53,6 +55,13 @@ public interface IDiagnosticSessionService string providerIdentifier, ExecutionTargetKind targetKind, CancellationToken cancellationToken = default); + Task OpenDynamicsAsync( + string profileIdentifier, + int profileRevision, + string providerIdentifier, + ExecutionTargetKind targetKind, + DynamicsConfiguration configuration, + CancellationToken cancellationToken = default); Task ResetAsync(DiagnosticSession session, CancellationToken cancellationToken = default); } @@ -61,12 +70,16 @@ public sealed class DiagnosticSession( DiagnosticSessionIdentity identity, IDiagnosticProtocolClient protocol, IDiagnosticTransport transport, - CancellationTokenSource lifetime) : IAsyncDisposable + CancellationTokenSource lifetime, + DynamicsConfiguration? dynamicsConfiguration = null, + IDynamicsControl? dynamicsControl = null) : IAsyncDisposable { private int _closed; public VehicleProfile Profile { get; } = profile; public DiagnosticSessionIdentity Identity { get; } = identity; + public DynamicsConfiguration? DynamicsConfiguration { get; } = dynamicsConfiguration; + public IDynamicsControl? DynamicsControl { get; } = dynamicsControl; public IReadOnlyList ExpectedEndpoints => protocol.ExpectedEndpoints; public DiagnosticTraceSnapshot Trace => protocol.Trace; public bool IsClosed => Volatile.Read(ref _closed) != 0; @@ -136,6 +149,11 @@ public sealed class DiagnosticSession( if (Interlocked.Exchange(ref _closed, 1) == 0) { lifetime.Cancel(); + if (DynamicsControl is not null) + { + await DynamicsControl.DisposeAsync().ConfigureAwait(false); + } + await transport.DisposeAsync().ConfigureAwait(false); lifetime.Dispose(); } @@ -165,6 +183,7 @@ public sealed class DiagnosticSessionService : IDiagnosticSessionService private readonly IReadOnlyList _factories; private readonly Func _logicalClockFactory; private long _sessionSequence; + private long _runSequence; public DiagnosticSessionService( IVehicleProfileService profiles, @@ -207,6 +226,13 @@ public sealed class DiagnosticSessionService : IDiagnosticSessionService $"No diagnostic transport is registered for provider '{target.ProviderIdentifier}'."); } + if (factory is IDynamicsDiagnosticTransportFactory) + { + throw new DiagnosticSessionException( + DiagnosticSessionFailure.DynamicsCapabilityUnavailable, + $"Provider '{target.ProviderIdentifier}' requires an explicit dynamics configuration; use the dynamics session workflow instead of opening a static session."); + } + var sequence = Interlocked.Increment(ref _sessionSequence); var identity = new DiagnosticSessionIdentity( $"diagnostic-session-{sequence:D6}", @@ -251,12 +277,84 @@ public sealed class DiagnosticSessionService : IDiagnosticSessionService return Task.FromResult(new DiagnosticSession(profile, identity, protocol, transport, lifetime)); } + public Task OpenDynamicsAsync( + string profileIdentifier, + int profileRevision, + string providerIdentifier, + ExecutionTargetKind targetKind, + DynamicsConfiguration configuration, + CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + ArgumentNullException.ThrowIfNull(configuration); + var profile = _profiles.Select(profileIdentifier, profileRevision); + configuration.ValidateAgainst(profile); + var target = _targets.Resolve(new ExecutionTargetDescriptor(providerIdentifier, targetKind)); + if (target.Kind != ExecutionTargetKind.Simulation) + { + throw new DiagnosticSessionException( + DiagnosticSessionFailure.UnsupportedTargetKind, + $"{target.Kind} operational sessions are unavailable; no provider substitution is performed."); + } + + var factory = _factories.FirstOrDefault(item => + StringComparer.OrdinalIgnoreCase.Equals(item.Descriptor.Target.ProviderIdentifier, target.ProviderIdentifier)); + if (factory is not IDynamicsDiagnosticTransportFactory dynamicsFactory) + { + throw new DiagnosticSessionException( + DiagnosticSessionFailure.DynamicsCapabilityUnavailable, + $"Provider '{target.ProviderIdentifier}' does not offer dynamics control; no static or other-target fallback is performed."); + } + + var sessionSequence = Interlocked.Increment(ref _sessionSequence); + var runSequence = Interlocked.Increment(ref _runSequence); + var identity = new DiagnosticSessionIdentity( + $"diagnostic-session-{sessionSequence:D6}", + profile.ProfileIdentifier, + profile.Revision, + profile.Vehicle.VehicleIdentifier, + target, + configuration.ConfigurationIdentifier, + $"dynamics-run-{runSequence:D6}"); + var binding = dynamicsFactory.OpenDynamicsTransport(profile, identity, configuration); + var transport = binding.Transport ?? throw new InvalidOperationException("Dynamics provider returned a null transport."); + var control = binding.Control ?? throw new InvalidOperationException("Dynamics provider returned a null control capability."); + var protocol = new SyntheticDiagnosticProtocolClient( + profile, + identity, + transport, + _logicalClockFactory() + ?? throw new InvalidOperationException("The logical clock factory returned null."), + protocolVersion: 2, + dynamicsConfiguration: configuration); + return Task.FromResult(new DiagnosticSession( + profile, + identity, + protocol, + transport, + new CancellationTokenSource(), + configuration, + control)); + } + public async Task ResetAsync( DiagnosticSession session, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(session); var identity = session.Identity; + if (session.DynamicsConfiguration is { } configuration) + { + await session.DisposeAsync().ConfigureAwait(false); + return await OpenDynamicsAsync( + identity.ProfileIdentifier, + identity.ProfileRevision, + identity.Target.ProviderIdentifier, + identity.Target.Kind, + configuration, + cancellationToken).ConfigureAwait(false); + } + await session.DisposeAsync().ConfigureAwait(false); return await OpenAsync( identity.ProfileIdentifier, diff --git a/src/AutoForge.Application/Features/Vehicles/Simulation/DynamicsConfigurationService.cs b/src/AutoForge.Application/Features/Vehicles/Simulation/DynamicsConfigurationService.cs new file mode 100644 index 0000000..a7d3886 --- /dev/null +++ b/src/AutoForge.Application/Features/Vehicles/Simulation/DynamicsConfigurationService.cs @@ -0,0 +1,292 @@ +using System.Collections.ObjectModel; +using System.Text.Json; +using System.Text.Json.Serialization; +using AutoForge.Application.Features.Vehicles.Profiles; +using AutoForge.Core.Simulation; +using AutoForge.Core.Vehicles; +using Microsoft.Extensions.DependencyInjection; + +namespace AutoForge.Application.Features.Vehicles.Simulation; + +public sealed record DynamicsConfigurationReference( + string ConfigurationIdentifier, + string ProfileIdentifier, + int ProfileRevision, + string ModelIdentifier); + +public sealed class DynamicsConfigurationException(string message, Exception? innerException = null) + : Exception(message, innerException); + +public interface IDynamicsConfigurationService +{ + DynamicsConfiguration CreateExample(string profileIdentifier, int profileRevision); + DynamicsConfiguration Import(string json); + IReadOnlyList List(); + DynamicsConfiguration Select(string configurationIdentifier); + string Export(string configurationIdentifier); +} + +public sealed class DynamicsConfigurationService : IDynamicsConfigurationService +{ + private static readonly JsonSerializerOptions JsonOptions = new() + { + PropertyNamingPolicy = JsonNamingPolicy.CamelCase, + UnmappedMemberHandling = JsonUnmappedMemberHandling.Disallow, + WriteIndented = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + private readonly object _gate = new(); + private readonly IVehicleProfileService _profiles; + private readonly Dictionary _configurations = + new(StringComparer.Ordinal); + + public DynamicsConfigurationService(IVehicleProfileService profiles) => + _profiles = profiles ?? throw new ArgumentNullException(nameof(profiles)); + + public DynamicsConfiguration CreateExample(string profileIdentifier, int profileRevision) + { + var profile = _profiles.Select(profileIdentifier, profileRevision); + var configuration = DynamicsConfiguration.CreateWarmBaseline(profile); + Register(configuration); + return configuration; + } + + public DynamicsConfiguration Import(string json) + { + ArgumentNullException.ThrowIfNull(json); + try + { + using var document = JsonDocument.Parse(json); + if (document.RootElement.ValueKind != JsonValueKind.Object || !HasUniqueProperties(document.RootElement)) + { + throw new JsonException("Dynamics configuration must be a JSON object with no duplicate properties."); + } + + ValidateDocumentShape(document.RootElement); + var configuration = JsonSerializer.Deserialize(json, JsonOptions) + ?? throw new JsonException("Dynamics configuration cannot be null."); + VehicleProfile profile; + try + { + profile = _profiles.Select(configuration.ProfileIdentifier, configuration.ProfileRevision); + } + catch (VehicleProfileCatalogException exception) + { + throw new DynamicsConfigurationException( + $"Dynamics profile reference '{configuration.ProfileIdentifier}' revision {configuration.ProfileRevision} is not available: {exception.Message}", + exception); + } + + try + { + configuration.ValidateAgainst(profile); + } + catch (ArgumentException exception) + { + throw new DynamicsConfigurationException(exception.Message, exception); + } + + Register(configuration); + return configuration; + } + catch (JsonException exception) + { + throw new DynamicsConfigurationException($"Dynamics configuration JSON is invalid: {exception.Message}", exception); + } + catch (ArgumentException exception) + { + throw new DynamicsConfigurationException($"Dynamics configuration is invalid: {exception.Message}", exception); + } + catch (KeyNotFoundException exception) + { + throw new DynamicsConfigurationException( + $"Dynamics configuration references a module that is not present in the selected profile: {exception.Message}", + exception); + } + } + + public IReadOnlyList List() + { + lock (_gate) + { + return Array.AsReadOnly(_configurations.Values + .OrderBy(configuration => configuration.ProfileIdentifier, StringComparer.OrdinalIgnoreCase) + .ThenBy(configuration => configuration.ProfileRevision) + .ThenBy(configuration => configuration.ConfigurationIdentifier, StringComparer.Ordinal) + .Select(configuration => new DynamicsConfigurationReference( + configuration.ConfigurationIdentifier, + configuration.ProfileIdentifier, + configuration.ProfileRevision, + configuration.ModelIdentifier)) + .ToArray()); + } + } + + public DynamicsConfiguration Select(string configurationIdentifier) + { + ArgumentException.ThrowIfNullOrWhiteSpace(configurationIdentifier); + lock (_gate) + { + return _configurations.TryGetValue(configurationIdentifier, out var configuration) + ? configuration + : throw new DynamicsConfigurationException( + $"Dynamics configuration '{configurationIdentifier}' has not been explicitly imported or created."); + } + } + + public string Export(string configurationIdentifier) => + JsonSerializer.Serialize(Select(configurationIdentifier), JsonOptions); + + private void Register(DynamicsConfiguration configuration) + { + lock (_gate) + { + if (_configurations.TryGetValue(configuration.ConfigurationIdentifier, out var existing)) + { + if (!StringComparer.Ordinal.Equals(ExportCanonical(existing), ExportCanonical(configuration))) + { + throw new DynamicsConfigurationException("A configuration fingerprint collision was detected."); + } + + return; + } + + _configurations.Add(configuration.ConfigurationIdentifier, configuration); + } + } + + private static string ExportCanonical(DynamicsConfiguration configuration) => + JsonSerializer.Serialize(configuration, JsonOptions); + + private static bool HasUniqueProperties(JsonElement element) + { + if (element.ValueKind == JsonValueKind.Object) + { + var names = new HashSet(StringComparer.Ordinal); + foreach (var property in element.EnumerateObject()) + { + if (!names.Add(property.Name) || !HasUniqueProperties(property.Value)) + { + return false; + } + } + } + else if (element.ValueKind == JsonValueKind.Array) + { + return element.EnumerateArray().All(HasUniqueProperties); + } + + return true; + } + + private static void ValidateDocumentShape(JsonElement root) + { + EnsureProperties( + root, + "formatVersion", + "profileIdentifier", + "profileRevision", + "vehicleIdentifier", + "engineModuleIdentifier", + "engineCalibrationReference", + "transmissionModuleIdentifier", + "transmissionCalibrationReference", + "modelIdentifier", + "modelVersion", + "model", + "initialConditions", + "scenario"); + var model = root.GetProperty("model"); + EnsureProperties( + model, + "stepSeconds", + "vehicleMassKilograms", + "wheelRadiusMeters", + "dragAreaSquareMeters", + "rollingResistanceCoefficient", + "airDensityKilogramsPerCubicMeter", + "gravityMetersPerSecondSquared", + "drivetrainEfficiency", + "maximumBrakeForceNewtons", + "idleSpeedRpm", + "maximumEngineSpeedRpm", + "warmIdleTargetRpm", + "launchSlipEndSpeedMetersPerSecond", + "idleFuelRateKilogramsPerSecond", + "fuelKilogramsPerJoule", + "ambientTemperatureCelsius", + "initialEngineTemperatureCelsius", + "equilibriumEngineTemperatureCelsius", + "thermalResponsePerSecond", + "engineTorqueCurve", + "forwardGearRatios", + "upshiftSpeedsRpm", + "downshiftSpeedsRpm", + "finalDriveRatio"); + foreach (var point in RequireArray(model.GetProperty("engineTorqueCurve"), "engineTorqueCurve").EnumerateArray()) + { + EnsureProperties(point, "engineSpeedRpm", "torqueNewtonMeters"); + } + + EnsureProperties( + root.GetProperty("initialConditions"), + "engineRunning", + "vehicleSpeedMetersPerSecond", + "gear", + "engineSpeedRpm", + "engineTemperatureCelsius", + "fuelConsumedKilograms", + "distanceMeters"); + foreach (var phase in RequireArray(root.GetProperty("scenario"), "scenario").EnumerateArray()) + { + EnsureProperties(phase, "kind", "targetSpeedMetersPerSecond", "durationSeconds"); + } + } + + private static void EnsureProperties(JsonElement element, params string[] expectedProperties) + { + if (element.ValueKind != JsonValueKind.Object) + { + throw new JsonException("Dynamics configuration objects must be JSON objects."); + } + + var expected = new HashSet(expectedProperties, StringComparer.Ordinal); + foreach (var property in element.EnumerateObject()) + { + if (!expected.Remove(property.Name)) + { + throw new JsonException($"Dynamics configuration contains an unknown property '{property.Name}'."); + } + } + + if (expected.Count != 0) + { + throw new JsonException($"Dynamics configuration is missing required property '{expected.First()}'."); + } + } + + private static JsonElement RequireArray(JsonElement element, string propertyName) + { + if (element.ValueKind != JsonValueKind.Array) + { + throw new JsonException($"Dynamics configuration property '{propertyName}' must be an array."); + } + + return element; + } +} + +public static class DynamicsConfigurationServiceCollectionExtensions +{ + public static IServiceCollection AddAutoForgeDynamicsConfigurations(this IServiceCollection services) + { + ArgumentNullException.ThrowIfNull(services); + if (!services.Any(service => service.ServiceType == typeof(IDynamicsConfigurationService))) + { + services.AddSingleton(); + } + + return services; + } +} diff --git a/src/AutoForge.Client/MauiProgram.cs b/src/AutoForge.Client/MauiProgram.cs index 2747777..6fe5e7a 100644 --- a/src/AutoForge.Client/MauiProgram.cs +++ b/src/AutoForge.Client/MauiProgram.cs @@ -1,6 +1,7 @@ using Microsoft.Extensions.Logging; using AutoForge.Diagnostics; using AutoForge.Application.Features.Vehicles.Profiles; +using AutoForge.Application.Features.Vehicles.Simulation; using AutoForge.Application.Features.Vehicles.Diagnostics; using AutoForge.Simulation; using AutoForge.UI; @@ -18,7 +19,11 @@ public static class MauiProgram builder.Services.AddAutoForgeVehicleProfiles(); builder.Services.AddAutoForgeDiagnostics( - [new SimulatedDiagnosticTransportFactory(SyntheticDiagnosticExamples.CreateDefinitions())]); + [ + new SimulatedDiagnosticTransportFactory(SyntheticDiagnosticExamples.CreateDefinitions()), + new DynamicsDiagnosticTransportFactory(SyntheticDiagnosticExamples.CreateDefinitions()) + ]); + builder.Services.AddAutoForgeDynamicsConfigurations(); builder.Services.AddAutoForgeUi(); builder.Services.AddMauiBlazorWebView(); diff --git a/src/AutoForge.Core/Simulation/DynamicsConfiguration.cs b/src/AutoForge.Core/Simulation/DynamicsConfiguration.cs new file mode 100644 index 0000000..f283172 --- /dev/null +++ b/src/AutoForge.Core/Simulation/DynamicsConfiguration.cs @@ -0,0 +1,495 @@ +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; +using System.Text.Json.Serialization; +using AutoForge.Core.Vehicles; + +namespace AutoForge.Core.Simulation; + +public enum DynamicsScenarioPhaseKind +{ + WarmIdle, + Accelerate, + Cruise, + Brake, + ReturnIdle +} + +public sealed record EngineTorquePoint(double EngineSpeedRpm, double TorqueNewtonMeters); + +public sealed class DynamicsModelParameters +{ + public DynamicsModelParameters( + double stepSeconds, + double vehicleMassKilograms, + double wheelRadiusMeters, + double dragAreaSquareMeters, + double rollingResistanceCoefficient, + double airDensityKilogramsPerCubicMeter, + double gravityMetersPerSecondSquared, + double drivetrainEfficiency, + double maximumBrakeForceNewtons, + double idleSpeedRpm, + double maximumEngineSpeedRpm, + double warmIdleTargetRpm, + double launchSlipEndSpeedMetersPerSecond, + double idleFuelRateKilogramsPerSecond, + double fuelKilogramsPerJoule, + double ambientTemperatureCelsius, + double initialEngineTemperatureCelsius, + double equilibriumEngineTemperatureCelsius, + double thermalResponsePerSecond, + IReadOnlyList engineTorqueCurve, + IReadOnlyList forwardGearRatios, + IReadOnlyList upshiftSpeedsRpm, + IReadOnlyList downshiftSpeedsRpm, + double finalDriveRatio) + { + StepSeconds = RequireRange(stepSeconds, 0.01, 0.5, nameof(stepSeconds)); + VehicleMassKilograms = RequireRange(vehicleMassKilograms, 100, 100_000, nameof(vehicleMassKilograms)); + WheelRadiusMeters = RequireRange(wheelRadiusMeters, 0.05, 2, nameof(wheelRadiusMeters)); + DragAreaSquareMeters = RequireRange(dragAreaSquareMeters, 0, 20, nameof(dragAreaSquareMeters)); + RollingResistanceCoefficient = RequireRange(rollingResistanceCoefficient, 0, 0.2, nameof(rollingResistanceCoefficient)); + AirDensityKilogramsPerCubicMeter = RequireRange(airDensityKilogramsPerCubicMeter, 0.1, 2, nameof(airDensityKilogramsPerCubicMeter)); + GravityMetersPerSecondSquared = RequireRange(gravityMetersPerSecondSquared, 1, 20, nameof(gravityMetersPerSecondSquared)); + DrivetrainEfficiency = RequireRange(drivetrainEfficiency, 0.1, 1, nameof(drivetrainEfficiency)); + MaximumBrakeForceNewtons = RequireRange(maximumBrakeForceNewtons, 1, 1_000_000, nameof(maximumBrakeForceNewtons)); + IdleSpeedRpm = RequireRange(idleSpeedRpm, 400, 2_000, nameof(idleSpeedRpm)); + MaximumEngineSpeedRpm = RequireRange(maximumEngineSpeedRpm, 1_500, 12_000, nameof(maximumEngineSpeedRpm)); + WarmIdleTargetRpm = RequireRange(warmIdleTargetRpm, IdleSpeedRpm, MaximumEngineSpeedRpm, nameof(warmIdleTargetRpm)); + LaunchSlipEndSpeedMetersPerSecond = RequireRange(launchSlipEndSpeedMetersPerSecond, 0.1, 15, nameof(launchSlipEndSpeedMetersPerSecond)); + IdleFuelRateKilogramsPerSecond = RequireRange(idleFuelRateKilogramsPerSecond, 0, 0.01, nameof(idleFuelRateKilogramsPerSecond)); + FuelKilogramsPerJoule = RequireRange(fuelKilogramsPerJoule, 0, 0.001, nameof(fuelKilogramsPerJoule)); + AmbientTemperatureCelsius = RequireRange(ambientTemperatureCelsius, -80, 80, nameof(ambientTemperatureCelsius)); + InitialEngineTemperatureCelsius = RequireRange(initialEngineTemperatureCelsius, -80, 250, nameof(initialEngineTemperatureCelsius)); + EquilibriumEngineTemperatureCelsius = RequireRange(equilibriumEngineTemperatureCelsius, -20, 250, nameof(equilibriumEngineTemperatureCelsius)); + ThermalResponsePerSecond = RequireRange(thermalResponsePerSecond, 0, 1, nameof(thermalResponsePerSecond)); + FinalDriveRatio = RequireRange(finalDriveRatio, 0.1, 20, nameof(finalDriveRatio)); + + EngineTorqueCurve = CopyCurve(engineTorqueCurve, MaximumEngineSpeedRpm); + ForwardGearRatios = CopyDescendingRatios(forwardGearRatios, nameof(forwardGearRatios)); + UpshiftSpeedsRpm = CopyShiftThresholds(upshiftSpeedsRpm, ForwardGearRatios.Count, nameof(upshiftSpeedsRpm)); + DownshiftSpeedsRpm = CopyShiftThresholds(downshiftSpeedsRpm, ForwardGearRatios.Count, nameof(downshiftSpeedsRpm)); + for (var index = 0; index < UpshiftSpeedsRpm.Count; index++) + { + if (DownshiftSpeedsRpm[index] >= UpshiftSpeedsRpm[index] || + UpshiftSpeedsRpm[index] > MaximumEngineSpeedRpm) + { + throw new ArgumentException( + "Each downshift speed must be below its upshift speed, and all upshift thresholds must be within the engine speed limit.", + nameof(downshiftSpeedsRpm)); + } + } + + if (WarmIdleTargetRpm < IdleSpeedRpm) + { + throw new ArgumentException("Warm-idle speed cannot be below engine idle speed.", nameof(warmIdleTargetRpm)); + } + } + + public double StepSeconds { get; } + public double VehicleMassKilograms { get; } + public double WheelRadiusMeters { get; } + public double DragAreaSquareMeters { get; } + public double RollingResistanceCoefficient { get; } + public double AirDensityKilogramsPerCubicMeter { get; } + public double GravityMetersPerSecondSquared { get; } + public double DrivetrainEfficiency { get; } + public double MaximumBrakeForceNewtons { get; } + public double IdleSpeedRpm { get; } + public double MaximumEngineSpeedRpm { get; } + public double WarmIdleTargetRpm { get; } + public double LaunchSlipEndSpeedMetersPerSecond { get; } + public double IdleFuelRateKilogramsPerSecond { get; } + public double FuelKilogramsPerJoule { get; } + public double AmbientTemperatureCelsius { get; } + public double InitialEngineTemperatureCelsius { get; } + public double EquilibriumEngineTemperatureCelsius { get; } + public double ThermalResponsePerSecond { get; } + public IReadOnlyList EngineTorqueCurve { get; } + public IReadOnlyList ForwardGearRatios { get; } + public IReadOnlyList UpshiftSpeedsRpm { get; } + public IReadOnlyList DownshiftSpeedsRpm { get; } + public double FinalDriveRatio { get; } + + private static double RequireRange(double value, double minimum, double maximum, string name) + { + if (!double.IsFinite(value) || value < minimum || value > maximum) + { + throw new ArgumentOutOfRangeException(name, value, $"Value must be finite and between {minimum} and {maximum}."); + } + + return value; + } + + private static IReadOnlyList CopyCurve(IReadOnlyList values, double maximumRpm) + { + ArgumentNullException.ThrowIfNull(values); + var points = values.ToArray(); + if (points.Length < 2 || + points.Any(point => point is null || + !double.IsFinite(point.EngineSpeedRpm) || + !double.IsFinite(point.TorqueNewtonMeters) || + point.EngineSpeedRpm < 0 || + point.EngineSpeedRpm > maximumRpm || + point.TorqueNewtonMeters <= 0) || + points.Zip(points.Skip(1), (left, right) => left.EngineSpeedRpm < right.EngineSpeedRpm).Any(ordered => !ordered)) + { + throw new ArgumentException("Torque curve points must be finite, positive, in range, unique and strictly increasing.", nameof(values)); + } + + return Array.AsReadOnly(points); + } + + private static IReadOnlyList CopyDescendingRatios(IReadOnlyList values, string name) + { + ArgumentNullException.ThrowIfNull(values); + var ratios = values.ToArray(); + if (ratios.Length is < 2 or > 12 || + ratios.Any(ratio => !double.IsFinite(ratio) || ratio <= 0 || ratio > 20) || + ratios.Zip(ratios.Skip(1), (left, right) => left > right).Any(descending => !descending)) + { + throw new ArgumentException("Forward gear ratios must be finite, positive and strictly descending.", name); + } + + return Array.AsReadOnly(ratios); + } + + private static IReadOnlyList CopyShiftThresholds(IReadOnlyList values, int gearCount, string name) + { + ArgumentNullException.ThrowIfNull(values); + var thresholds = values.ToArray(); + if (thresholds.Length != gearCount || + thresholds.Any(value => !double.IsFinite(value) || value <= 0 || value > 20_000)) + { + throw new ArgumentException("Each forward gear must have one finite positive shift threshold.", name); + } + + return Array.AsReadOnly(thresholds); + } +} + +public sealed class DynamicsInitialConditions +{ + public DynamicsInitialConditions( + bool engineRunning, + double vehicleSpeedMetersPerSecond, + int gear, + double engineSpeedRpm, + double engineTemperatureCelsius, + double fuelConsumedKilograms, + double distanceMeters) + { + if (!double.IsFinite(vehicleSpeedMetersPerSecond) || vehicleSpeedMetersPerSecond is < 0 or > 150 || + !double.IsFinite(engineSpeedRpm) || engineSpeedRpm < 0 || + !double.IsFinite(engineTemperatureCelsius) || engineTemperatureCelsius is < -80 or > 250 || + !double.IsFinite(fuelConsumedKilograms) || fuelConsumedKilograms < 0 || + !double.IsFinite(distanceMeters) || distanceMeters < 0 || + gear is < 0 or > 12) + { + throw new ArgumentException("Initial dynamics conditions must be finite and within their physical domains."); + } + + if (!engineRunning && (engineSpeedRpm != 0 || gear != 0) || + vehicleSpeedMetersPerSecond == 0 && gear > 0) + { + throw new ArgumentException("Engine-off conditions require zero rpm and neutral; a stationary vehicle cannot start in gear."); + } + + EngineRunning = engineRunning; + VehicleSpeedMetersPerSecond = vehicleSpeedMetersPerSecond; + Gear = gear; + EngineSpeedRpm = engineSpeedRpm; + EngineTemperatureCelsius = engineTemperatureCelsius; + FuelConsumedKilograms = fuelConsumedKilograms; + DistanceMeters = distanceMeters; + } + + public bool EngineRunning { get; } + public double VehicleSpeedMetersPerSecond { get; } + public int Gear { get; } + public double EngineSpeedRpm { get; } + public double EngineTemperatureCelsius { get; } + public double FuelConsumedKilograms { get; } + public double DistanceMeters { get; } +} + +public sealed class DynamicsScenarioPhase +{ + public DynamicsScenarioPhase(DynamicsScenarioPhaseKind kind, double targetSpeedMetersPerSecond, double durationSeconds) + { + if (!Enum.IsDefined(kind) || + !double.IsFinite(targetSpeedMetersPerSecond) || + targetSpeedMetersPerSecond < 0 || + !double.IsFinite(durationSeconds) || + durationSeconds <= 0 || + durationSeconds > 86_400) + { + throw new ArgumentException("Scenario phase kind, target speed and duration must be valid and finite."); + } + + Kind = kind; + TargetSpeedMetersPerSecond = targetSpeedMetersPerSecond; + DurationSeconds = durationSeconds; + } + + public DynamicsScenarioPhaseKind Kind { get; } + public double TargetSpeedMetersPerSecond { get; } + public double DurationSeconds { get; } +} + +public sealed class DynamicsConfiguration +{ + private static readonly JsonSerializerOptions FingerprintOptions = new() + { + PropertyNamingPolicy = JsonNamingPolicy.CamelCase + }; + + public DynamicsConfiguration( + int formatVersion, + string profileIdentifier, + int profileRevision, + string vehicleIdentifier, + string engineModuleIdentifier, + string? engineCalibrationReference, + string transmissionModuleIdentifier, + string? transmissionCalibrationReference, + string modelIdentifier, + int modelVersion, + DynamicsModelParameters model, + DynamicsInitialConditions initialConditions, + IReadOnlyList scenario) + { + if (formatVersion != 1 || modelVersion != 1) + { + throw new ArgumentOutOfRangeException(nameof(formatVersion), "Only configuration format 1 and model version 1 are supported."); + } + + ProfileIdentifier = RequireText(profileIdentifier, nameof(profileIdentifier)); + if (profileRevision <= 0) + { + throw new ArgumentOutOfRangeException(nameof(profileRevision)); + } + + VehicleIdentifier = RequireText(vehicleIdentifier, nameof(vehicleIdentifier)); + EngineModuleIdentifier = RequireText(engineModuleIdentifier, nameof(engineModuleIdentifier)); + EngineCalibrationReference = OptionalText(engineCalibrationReference, nameof(engineCalibrationReference)); + TransmissionModuleIdentifier = RequireText(transmissionModuleIdentifier, nameof(transmissionModuleIdentifier)); + TransmissionCalibrationReference = OptionalText(transmissionCalibrationReference, nameof(transmissionCalibrationReference)); + if (StringComparer.OrdinalIgnoreCase.Equals(EngineModuleIdentifier, TransmissionModuleIdentifier)) + { + throw new ArgumentException("Engine and transmission module references must be distinct."); + } + + ModelIdentifier = RequireText(modelIdentifier, nameof(modelIdentifier)); + ModelVersion = modelVersion; + Model = model ?? throw new ArgumentNullException(nameof(model)); + InitialConditions = initialConditions ?? throw new ArgumentNullException(nameof(initialConditions)); + if (InitialConditions.EngineSpeedRpm > Model.MaximumEngineSpeedRpm || + InitialConditions.EngineRunning && InitialConditions.EngineSpeedRpm < Model.IdleSpeedRpm || + InitialConditions.EngineTemperatureCelsius != Model.InitialEngineTemperatureCelsius || + InitialConditions.Gear > Model.ForwardGearRatios.Count) + { + throw new ArgumentException("Initial engine speed, gear, and temperature must be compatible with the selected model."); + } + + if (InitialConditions.EngineRunning && InitialConditions.Gear > 0) + { + var expectedRpm = CoupledEngineSpeed( + InitialConditions.VehicleSpeedMetersPerSecond, + InitialConditions.Gear, + Model); + if (Math.Abs(InitialConditions.EngineSpeedRpm - expectedRpm) > 1e-8 || + expectedRpm < Model.IdleSpeedRpm) + { + throw new ArgumentException( + "An initial in-gear condition must be locked to the configured wheel/gear ratio; launch slip is not an independent initial input."); + } + } + ArgumentNullException.ThrowIfNull(scenario); + var phases = scenario.ToArray(); + if (phases.Length != 5 || + phases.Any(phase => phase is null) || + !phases.Select(phase => phase.Kind).SequenceEqual( + [ + DynamicsScenarioPhaseKind.WarmIdle, + DynamicsScenarioPhaseKind.Accelerate, + DynamicsScenarioPhaseKind.Cruise, + DynamicsScenarioPhaseKind.Brake, + DynamicsScenarioPhaseKind.ReturnIdle + ]) || + phases[0].TargetSpeedMetersPerSecond != 0 || + phases[1].TargetSpeedMetersPerSecond is <= 0 or > 150 || + phases[2].TargetSpeedMetersPerSecond != phases[1].TargetSpeedMetersPerSecond || + phases[3].TargetSpeedMetersPerSecond != 0 || + phases[4].TargetSpeedMetersPerSecond != 0 || + phases[2].DurationSeconds < 300 || + phases[4].DurationSeconds < 10) + { + throw new ArgumentException("Scenario must define warm idle, acceleration, cruise, braking and return-idle phases in order.", nameof(scenario)); + } + + var maximumCoupledSpeed = Model.MaximumEngineSpeedRpm * + (2 * Math.PI * Model.WheelRadiusMeters) / 60 / + (Model.ForwardGearRatios[^1] * Model.FinalDriveRatio); + if (phases[1].TargetSpeedMetersPerSecond > maximumCoupledSpeed || + InitialConditions.VehicleSpeedMetersPerSecond > maximumCoupledSpeed) + { + throw new ArgumentException( + $"Scenario target or initial speed exceeds the configured top-gear redline envelope of {maximumCoupledSpeed:F4} m/s."); + } + + FormatVersion = formatVersion; + ProfileRevision = profileRevision; + Scenario = Array.AsReadOnly(phases); + ConfigurationIdentifier = CreateFingerprint(); + } + + public int FormatVersion { get; } + public string ProfileIdentifier { get; } + public int ProfileRevision { get; } + public string VehicleIdentifier { get; } + public string EngineModuleIdentifier { get; } + public string? EngineCalibrationReference { get; } + public string TransmissionModuleIdentifier { get; } + public string? TransmissionCalibrationReference { get; } + public string ModelIdentifier { get; } + public int ModelVersion { get; } + public DynamicsModelParameters Model { get; } + public DynamicsInitialConditions InitialConditions { get; } + public IReadOnlyList Scenario { get; } + [JsonIgnore] public string ConfigurationIdentifier { get; } + + private static double CoupledEngineSpeed(double speedMetersPerSecond, int gear, DynamicsModelParameters model) => + speedMetersPerSecond / (2 * Math.PI * model.WheelRadiusMeters) * 60 * + model.ForwardGearRatios[gear - 1] * model.FinalDriveRatio; + + public void ValidateAgainst(VehicleProfile profile) + { + ArgumentNullException.ThrowIfNull(profile); + if (!Same(ProfileIdentifier, profile.ProfileIdentifier) || + ProfileRevision != profile.Revision || + !Same(VehicleIdentifier, profile.Vehicle.VehicleIdentifier)) + { + throw new ArgumentException("Dynamics configuration does not bind to the exact selected profile identity and revision.", nameof(profile)); + } + + var engine = profile.Modules.FirstOrDefault(module => + StringComparer.OrdinalIgnoreCase.Equals(module.InstanceIdentifier, EngineModuleIdentifier)) + ?? throw new ArgumentException( + $"Engine module reference '{EngineModuleIdentifier}' does not exist in profile '{profile.ProfileIdentifier}' revision {profile.Revision}.", + nameof(profile)); + var transmission = profile.Modules.FirstOrDefault(module => + StringComparer.OrdinalIgnoreCase.Equals(module.InstanceIdentifier, TransmissionModuleIdentifier)) + ?? throw new ArgumentException( + $"Transmission module reference '{TransmissionModuleIdentifier}' does not exist in profile '{profile.ProfileIdentifier}' revision {profile.Revision}.", + nameof(profile)); + if (!SameOptional(EngineCalibrationReference, engine.CalibrationIdentifier) || + !SameOptional(TransmissionCalibrationReference, transmission.CalibrationIdentifier)) + { + throw new ArgumentException( + $"Dynamics calibration reference conflicts with profile '{profile.ProfileIdentifier}' revision {profile.Revision} for engine module '{EngineModuleIdentifier}' or transmission module '{TransmissionModuleIdentifier}'.", + nameof(profile)); + } + + if (InitialConditions.Gear > Model.ForwardGearRatios.Count || + InitialConditions.EngineSpeedRpm > Model.MaximumEngineSpeedRpm) + { + throw new ArgumentException("Initial dynamics conditions are incompatible with the model's gear or speed range.", nameof(profile)); + } + } + + public static DynamicsConfiguration CreateWarmBaseline(VehicleProfile profile) + { + ArgumentNullException.ThrowIfNull(profile); + var engine = profile.Modules.FirstOrDefault(module => + module.Role.Contains("engine", StringComparison.OrdinalIgnoreCase)); + var transmission = profile.Modules.FirstOrDefault(module => + module.Role.Contains("transmission", StringComparison.OrdinalIgnoreCase)); + if (engine is null || transmission is null) + { + throw new ArgumentException("The synthetic dynamics example requires explicit engine and transmission modules.", nameof(profile)); + } + + var model = new DynamicsModelParameters( + stepSeconds: 0.1, + vehicleMassKilograms: 1_800, + wheelRadiusMeters: 0.34, + dragAreaSquareMeters: 0.68, + rollingResistanceCoefficient: 0.012, + airDensityKilogramsPerCubicMeter: 1.2, + gravityMetersPerSecondSquared: 9.80665, + drivetrainEfficiency: 0.9, + maximumBrakeForceNewtons: 10_000, + idleSpeedRpm: 650, + maximumEngineSpeedRpm: 5_000, + warmIdleTargetRpm: 650, + launchSlipEndSpeedMetersPerSecond: 2.5, + idleFuelRateKilogramsPerSecond: 0.00045, + fuelKilogramsPerJoule: 0.00000012, + ambientTemperatureCelsius: 20, + initialEngineTemperatureCelsius: 88, + equilibriumEngineTemperatureCelsius: 90, + thermalResponsePerSecond: 0.015, + engineTorqueCurve: + [ + new(650, 240), + new(1_000, 300), + new(2_000, 360), + new(3_200, 350), + new(4_200, 300), + new(5_000, 180) + ], + forwardGearRatios: [3.5, 2.2, 1.4, 0.9], + upshiftSpeedsRpm: [4_000, 4_000, 4_000, 4_000], + downshiftSpeedsRpm: [1_450, 1_450, 1_450, 1_450], + finalDriveRatio: 3.6); + return new DynamicsConfiguration( + 1, + profile.ProfileIdentifier, + profile.Revision, + profile.Vehicle.VehicleIdentifier, + engine.InstanceIdentifier, + engine.CalibrationIdentifier, + transmission.InstanceIdentifier, + transmission.CalibrationIdentifier, + "autoforge.synthetic.longitudinal", + 1, + model, + new DynamicsInitialConditions(false, 0, 0, 0, 88, 0, 0), + [ + new(DynamicsScenarioPhaseKind.WarmIdle, 0, 10), + new(DynamicsScenarioPhaseKind.Accelerate, 20.1168, 60), + new(DynamicsScenarioPhaseKind.Cruise, 20.1168, 300), + new(DynamicsScenarioPhaseKind.Brake, 0, 60), + new(DynamicsScenarioPhaseKind.ReturnIdle, 0, 10) + ]); + } + + private string CreateFingerprint() + { + var json = JsonSerializer.SerializeToUtf8Bytes(this, FingerprintOptions); + var hash = SHA256.HashData(json); + return $"sha256:v1:{Convert.ToHexString(hash).ToLowerInvariant()}"; + } + + private static string RequireText(string value, string name) + { + ArgumentException.ThrowIfNullOrWhiteSpace(value, name); + if (!StringComparer.Ordinal.Equals(value, value.Trim())) + { + throw new ArgumentException("Configuration identifiers must not contain surrounding whitespace.", name); + } + + return value; + } + + private static string? OptionalText(string? value, string name) => + value is null ? null : RequireText(value, name); + + private static bool Same(string left, string right) => + StringComparer.OrdinalIgnoreCase.Equals(left, right); + + private static bool SameOptional(string? left, string? right) => + left is null ? right is null : right is not null && Same(left, right); +} diff --git a/src/AutoForge.Core/Simulation/DynamicsRunStatus.cs b/src/AutoForge.Core/Simulation/DynamicsRunStatus.cs new file mode 100644 index 0000000..40007af --- /dev/null +++ b/src/AutoForge.Core/Simulation/DynamicsRunStatus.cs @@ -0,0 +1,24 @@ +namespace AutoForge.Core.Simulation; + +public enum DynamicsLifecycleState +{ + Stopped, + Running, + Paused, + Completed, + Faulted, + Closed +} + +public sealed record DynamicsRunStatus( + string RunIdentifier, + string ConfigurationIdentifier, + long StepIndex, + double VirtualTimeSeconds, + DynamicsLifecycleState State, + int ScenarioPhaseIndex, + string? ScenarioPhase, + double ScenarioPhaseElapsedSeconds, + double ScenarioProgress, + double ScenarioPhaseProgress, + string? Failure); diff --git a/src/AutoForge.Diagnostics/ProviderContracts.cs b/src/AutoForge.Diagnostics/ProviderContracts.cs index 266ca8e..08271bc 100644 --- a/src/AutoForge.Diagnostics/ProviderContracts.cs +++ b/src/AutoForge.Diagnostics/ProviderContracts.cs @@ -2,6 +2,7 @@ using System.Collections.ObjectModel; using System.Text.Json; using System.Text.RegularExpressions; using AutoForge.Core.ExecutionTargets; +using AutoForge.Core.Simulation; using AutoForge.Core.Vehicles; namespace AutoForge.Diagnostics; @@ -26,7 +27,9 @@ public sealed class DiagnosticSessionIdentity string profileIdentifier, int profileRevision, string vehicleIdentifier, - ExecutionTargetDescriptor target) + ExecutionTargetDescriptor target, + string? dynamicsConfigurationIdentifier = null, + string? dynamicsRunIdentifier = null) { SessionIdentifier = Require(sessionIdentifier, nameof(sessionIdentifier)); ProfileIdentifier = Require(profileIdentifier, nameof(profileIdentifier)); @@ -36,9 +39,22 @@ public sealed class DiagnosticSessionIdentity } ProfileRevision = profileRevision; - ConfigurationIdentifier = $"profile:{ProfileIdentifier}@revision:{ProfileRevision}"; VehicleIdentifier = Require(vehicleIdentifier, nameof(vehicleIdentifier)); Target = target ?? throw new ArgumentNullException(nameof(target)); + if ((dynamicsConfigurationIdentifier is null) != (dynamicsRunIdentifier is null)) + { + throw new ArgumentException("Dynamics configuration and run identities must either both be present or both be absent."); + } + + DynamicsConfigurationIdentifier = dynamicsConfigurationIdentifier is null + ? null + : Require(dynamicsConfigurationIdentifier, nameof(dynamicsConfigurationIdentifier)); + DynamicsRunIdentifier = dynamicsRunIdentifier is null + ? null + : Require(dynamicsRunIdentifier, nameof(dynamicsRunIdentifier)); + ConfigurationIdentifier = DynamicsConfigurationIdentifier is null + ? $"profile:{ProfileIdentifier}@revision:{ProfileRevision}" + : $"profile:{ProfileIdentifier}@revision:{ProfileRevision};dynamics:{DynamicsConfigurationIdentifier}"; } public string SessionIdentifier { get; } @@ -47,6 +63,8 @@ public sealed class DiagnosticSessionIdentity public string ConfigurationIdentifier { get; } public string VehicleIdentifier { get; } public ExecutionTargetDescriptor Target { get; } + public string? DynamicsConfigurationIdentifier { get; } + public string? DynamicsRunIdentifier { get; } private static string Require(string value, string parameterName) { @@ -96,6 +114,30 @@ public interface IDiagnosticTransportFactory IDiagnosticTransport OpenTransport(VehicleProfile profile, DiagnosticSessionIdentity identity); } +public interface IDynamicsControl : IAsyncDisposable +{ + DynamicsRunStatus Status { get; } + double PacingFactor { get; } + Task StartAsync(CancellationToken cancellationToken = default); + Task PauseAsync(CancellationToken cancellationToken = default); + Task ResumeAsync(CancellationToken cancellationToken = default); + Task StopAsync(CancellationToken cancellationToken = default); + Task ResetAsync(CancellationToken cancellationToken = default); + Task StepAsync(int stepCount = 1, CancellationToken cancellationToken = default); + Task SetPacingFactorAsync(double factor, CancellationToken cancellationToken = default); + Task RunScenarioAsync(CancellationToken cancellationToken = default); +} + +public sealed record DynamicsSessionBinding(IDiagnosticTransport Transport, IDynamicsControl Control); + +public interface IDynamicsDiagnosticTransportFactory : IDiagnosticTransportFactory +{ + DynamicsSessionBinding OpenDynamicsTransport( + VehicleProfile profile, + DiagnosticSessionIdentity identity, + DynamicsConfiguration configuration); +} + public enum DiagnosticProviderFailure { ConfigurationNotFound, @@ -358,18 +400,36 @@ public sealed record DiagnosticSignal( string Unit, SignalQuality Quality, long LogicalTimeTicks, - string Origin); + string Origin, + long? ModelStepIndex = null, + double? ModelTimeSeconds = null, + string? ModelConfigurationIdentifier = null, + string? ModelRunIdentifier = null); public sealed class SignalSnapshot { - public SignalSnapshot(string moduleIdentifier, IEnumerable signals) + public SignalSnapshot( + string moduleIdentifier, + IEnumerable signals, + long? modelStepIndex = null, + double? modelTimeSeconds = null, + string? modelConfigurationIdentifier = null, + string? modelRunIdentifier = null) { ModuleIdentifier = moduleIdentifier; Signals = Array.AsReadOnly(signals.ToArray()); + ModelStepIndex = modelStepIndex; + ModelTimeSeconds = modelTimeSeconds; + ModelConfigurationIdentifier = modelConfigurationIdentifier; + ModelRunIdentifier = modelRunIdentifier; } public string ModuleIdentifier { get; } public IReadOnlyList Signals { get; } + public long? ModelStepIndex { get; } + public double? ModelTimeSeconds { get; } + public string? ModelConfigurationIdentifier { get; } + public string? ModelRunIdentifier { get; } } public sealed class DiagnosticTraceEntry diff --git a/src/AutoForge.Diagnostics/SyntheticDiagnosticProtocolClient.cs b/src/AutoForge.Diagnostics/SyntheticDiagnosticProtocolClient.cs index 6319185..9b63da9 100644 --- a/src/AutoForge.Diagnostics/SyntheticDiagnosticProtocolClient.cs +++ b/src/AutoForge.Diagnostics/SyntheticDiagnosticProtocolClient.cs @@ -1,4 +1,5 @@ using System.Text.Json; +using AutoForge.Core.Simulation; using AutoForge.Core.Vehicles; namespace AutoForge.Diagnostics; @@ -6,10 +7,31 @@ namespace AutoForge.Diagnostics; public sealed class SyntheticDiagnosticProtocolClient : IDiagnosticProtocolClient { private const long DefaultTimeoutTicks = 5; + private static readonly IReadOnlyDictionary DynamicSignalShape = + new Dictionary(StringComparer.Ordinal) + { + ["engine.running"] = ("boolean", JsonValueKind.True), + ["engine.speed"] = ("rpm", JsonValueKind.Number), + ["vehicle.speed"] = ("m/s", JsonValueKind.Number), + ["engine.throttle"] = ("ratio", JsonValueKind.Number), + ["engine.load"] = ("ratio", JsonValueKind.Number), + ["engine.torque"] = ("N*m", JsonValueKind.Number), + ["engine.fuel-rate"] = ("kg/s", JsonValueKind.Number), + ["engine.fuel-consumed"] = ("kg", JsonValueKind.Number), + ["engine.temperature"] = ("degC", JsonValueKind.Number), + ["vehicle.distance"] = ("m", JsonValueKind.Number), + ["vehicle.acceleration"] = ("m/s^2", JsonValueKind.Number), + ["driver.brake"] = ("ratio", JsonValueKind.Number), + ["transmission.gear"] = ("gear", JsonValueKind.Number), + ["transmission.shift-count"] = ("count", JsonValueKind.Number), + ["transmission.coupling-slip"] = ("ratio", JsonValueKind.Number) + }; private readonly VehicleProfile _profile; private readonly IDiagnosticTransport _transport; private readonly IDiagnosticLogicalClock _clock; private readonly DiagnosticTraceBuffer _trace; + private readonly int _protocolVersion; + private readonly DynamicsConfiguration? _dynamicsConfiguration; private readonly SemaphoreSlim _exchangeGate = new(1, 1); private long _correlationSequence; @@ -18,12 +40,37 @@ public sealed class SyntheticDiagnosticProtocolClient : IDiagnosticProtocolClien DiagnosticSessionIdentity session, IDiagnosticTransport transport, IDiagnosticLogicalClock clock, - int traceCapacity = 200) + int traceCapacity = 200, + int protocolVersion = 1, + DynamicsConfiguration? dynamicsConfiguration = null) { _profile = profile ?? throw new ArgumentNullException(nameof(profile)); Session = session ?? throw new ArgumentNullException(nameof(session)); _transport = transport ?? throw new ArgumentNullException(nameof(transport)); _clock = clock ?? throw new ArgumentNullException(nameof(clock)); + if (protocolVersion is not (1 or 2)) + { + throw new ArgumentOutOfRangeException(nameof(protocolVersion)); + } + + if (protocolVersion == 2 && + (dynamicsConfiguration is null || + session.DynamicsConfigurationIdentifier is null || + session.DynamicsRunIdentifier is null || + !StringComparer.Ordinal.Equals( + dynamicsConfiguration.ConfigurationIdentifier, + session.DynamicsConfigurationIdentifier))) + { + throw new ArgumentException("Dynamic protocol v2 requires the exact bound dynamics configuration and run identity."); + } + + if (protocolVersion == 1 && dynamicsConfiguration is not null) + { + throw new ArgumentException("Static protocol v1 cannot be bound to a dynamics configuration.", nameof(dynamicsConfiguration)); + } + + _protocolVersion = protocolVersion; + _dynamicsConfiguration = dynamicsConfiguration; _trace = new DiagnosticTraceBuffer(traceCapacity); ExpectedEndpoints = Array.AsReadOnly(transport.ExpectedEndpoints.ToArray()); } @@ -184,26 +231,68 @@ public sealed class SyntheticDiagnosticProtocolClient : IDiagnosticProtocolClien DiagnosticServices.ReadSignals, (data, request) => { - EnsureProperties(data, "moduleIdentifier", "logicalTimeTicks", "origin", "signals"); + EnsureProperties( + data, + _protocolVersion == 1 + ? ["moduleIdentifier", "logicalTimeTicks", "origin", "signals"] + : [ + "moduleIdentifier", + "configurationIdentifier", + "runIdentifier", + "modelStepIndex", + "modelTimeSeconds", + "origin", + "captureLogicalTimeTicks", + "signals" + ]); var moduleIdentifier = RequiredString(data, "moduleIdentifier"); ValidateModuleIdentifier(endpoint, moduleIdentifier); - var logicalTime = RequiredInt64(data, "logicalTimeTicks"); - if (logicalTime != request.LogicalTimeTicks) - { - throw new DiagnosticProtocolException( - "INVALID_RESPONSE", - "Static signal snapshot time must equal the request logical start tick."); - } - var origin = RequiredString(data, "origin"); - if (!StringComparer.Ordinal.Equals(origin, "SYNTHETIC_STATIC")) + long? modelStepIndex = null; + double? modelTimeSeconds = null; + string? modelConfigurationIdentifier = null; + string? modelRunIdentifier = null; + var logicalTime = request.LogicalTimeTicks; + if (_protocolVersion == 1) { - throw new DiagnosticProtocolException("INVALID_RESPONSE", "Signal origin must be SYNTHETIC_STATIC."); + if (RequiredInt64(data, "logicalTimeTicks") != request.LogicalTimeTicks || + !StringComparer.Ordinal.Equals(origin, "SYNTHETIC_STATIC")) + { + throw new DiagnosticProtocolException( + "INVALID_RESPONSE", + "Static signal origin and snapshot time must match protocol v1 semantics."); + } + } + else + { + modelConfigurationIdentifier = RequiredString(data, "configurationIdentifier"); + modelRunIdentifier = RequiredString(data, "runIdentifier"); + modelStepIndex = RequiredInt64(data, "modelStepIndex"); + modelTimeSeconds = RequiredFiniteDouble(data, "modelTimeSeconds"); + if (RequiredInt64(data, "captureLogicalTimeTicks") != request.LogicalTimeTicks) + { + throw new DiagnosticProtocolException( + "INVALID_RESPONSE", + "Dynamic diagnostic capture ticks must match the request start ticks."); + } + + var expectedTime = modelStepIndex.Value * _dynamicsConfiguration!.Model.StepSeconds; + if (modelStepIndex.Value < 0 || + Math.Abs(modelTimeSeconds.Value - expectedTime) > 1e-9 || + !StringComparer.Ordinal.Equals(modelConfigurationIdentifier, Session.DynamicsConfigurationIdentifier) || + !StringComparer.Ordinal.Equals(modelRunIdentifier, Session.DynamicsRunIdentifier) || + !StringComparer.Ordinal.Equals(origin, "SYNTHETIC_DYNAMIC")) + { + throw new DiagnosticProtocolException( + "INVALID_RESPONSE", + "Dynamic snapshot model time, origin, run or configuration binding is invalid."); + } } var signals = RequiredArray(data, "signals").EnumerateArray().Select(item => { EnsureProperties(item, "signalIdentifier", "value", "unit", "quality"); + var signalIdentifier = RequiredString(item, "signalIdentifier"); var qualityText = RequiredString(item, "quality"); if (!Enum.TryParse(qualityText, ignoreCase: false, out var quality) || !Enum.IsDefined(quality)) @@ -212,14 +301,24 @@ public sealed class SyntheticDiagnosticProtocolClient : IDiagnosticProtocolClien } var value = Required(item, "value"); + var unit = RequiredString(item, "unit"); + if (_protocolVersion == 2) + { + ValidateDynamicSignal(signalIdentifier, value, unit, moduleIdentifier); + } + return new DiagnosticSignal( - RequiredString(item, "signalIdentifier"), + signalIdentifier, moduleIdentifier, value.Clone(), - RequiredString(item, "unit"), + unit, quality, logicalTime, - origin); + origin, + modelStepIndex, + modelTimeSeconds, + modelConfigurationIdentifier, + modelRunIdentifier); }).ToArray(); if (signals.Select(signal => signal.SignalIdentifier) .Distinct(StringComparer.OrdinalIgnoreCase).Count() != signals.Length) @@ -229,7 +328,28 @@ public sealed class SyntheticDiagnosticProtocolClient : IDiagnosticProtocolClien "Signal identifiers must be unique within a module snapshot."); } - return new SignalSnapshot(moduleIdentifier, signals); + if (_protocolVersion == 2) + { + var expectedCount = StringComparer.OrdinalIgnoreCase.Equals( + moduleIdentifier, + _dynamicsConfiguration!.EngineModuleIdentifier) + ? 12 + : 5; + if (signals.Length != expectedCount) + { + throw new DiagnosticProtocolException( + "INVALID_RESPONSE", + $"Dynamic module snapshot must contain exactly {expectedCount} configured signals."); + } + } + + return new SignalSnapshot( + moduleIdentifier, + signals, + modelStepIndex, + modelTimeSeconds, + modelConfigurationIdentifier, + modelRunIdentifier); }, cancellationToken); @@ -291,7 +411,10 @@ public sealed class SyntheticDiagnosticProtocolClient : IDiagnosticProtocolClien endpoint.Address, service, startTicks, - DefaultTimeoutTicks); + DefaultTimeoutTicks) + { + Version = _protocolVersion + }; var requestPayload = SyntheticProtocolV1.EncodeRequest(request); TransportReply transportReply; @@ -344,7 +467,7 @@ public sealed class SyntheticDiagnosticProtocolClient : IDiagnosticProtocolClien } catch (JsonException) { - const string error = "Response is not valid synthetic protocol v1 JSON."; + var error = $"Response is not valid synthetic protocol v{_protocolVersion} JSON."; AddTrace(endpoint, correlation, service, startTicks, _clock.Ticks, requestPayload, responsePayload, DiagnosticOutcome.ProtocolError, null, error); return DiagnosticOperationResult.Failure(DiagnosticOutcome.ProtocolError, "MALFORMED_RESPONSE", error); } @@ -376,9 +499,11 @@ public sealed class SyntheticDiagnosticProtocolClient : IDiagnosticProtocolClien "errorCode", "error", "data"); - if (RequiredInt32(root, "version") != 1) + if (RequiredInt32(root, "version") != _protocolVersion) { - throw new DiagnosticProtocolException("UNSUPPORTED_VERSION", "Response protocol version is unsupported."); + throw new DiagnosticProtocolException( + "UNSUPPORTED_VERSION", + $"Response protocol version {_protocolVersion} was expected."); } if (!Same(RequiredString(root, "sessionIdentifier"), Session.SessionIdentifier) || @@ -617,6 +742,68 @@ public sealed class SyntheticDiagnosticProtocolClient : IDiagnosticProtocolClien return result; } + private static double RequiredFiniteDouble(JsonElement element, string property) + { + var value = Required(element, property); + if (value.ValueKind != JsonValueKind.Number || + !value.TryGetDouble(out var result) || + !double.IsFinite(result)) + { + throw new DiagnosticProtocolException("MALFORMED_RESPONSE", $"Response property '{property}' must be a finite number."); + } + + return result; + } + + private void ValidateDynamicSignal( + string signalIdentifier, + JsonElement value, + string unit, + string moduleIdentifier) + { + if (!DynamicSignalShape.TryGetValue(signalIdentifier, out var shape) || + !StringComparer.Ordinal.Equals(unit, shape.Unit)) + { + throw new DiagnosticProtocolException( + "INVALID_RESPONSE", + $"Dynamic signal '{signalIdentifier}' is unknown or has an invalid unit."); + } + + var engineSignal = signalIdentifier is + "engine.running" or "engine.speed" or "engine.throttle" or "engine.load" or "engine.torque" or + "engine.fuel-rate" or "engine.fuel-consumed" or "engine.temperature" or "vehicle.speed" or + "vehicle.distance" or "vehicle.acceleration" or "driver.brake"; + var expectedModule = engineSignal + ? _dynamicsConfiguration!.EngineModuleIdentifier + : _dynamicsConfiguration!.TransmissionModuleIdentifier; + var sharedPowertrainSignal = signalIdentifier is "engine.speed" or "vehicle.speed"; + if (!StringComparer.OrdinalIgnoreCase.Equals(moduleIdentifier, expectedModule) && + !(sharedPowertrainSignal && + StringComparer.OrdinalIgnoreCase.Equals(moduleIdentifier, _dynamicsConfiguration!.TransmissionModuleIdentifier))) + { + throw new DiagnosticProtocolException( + "INVALID_RESPONSE", + $"Dynamic signal '{signalIdentifier}' came from the wrong module."); + } + + if (shape.Kind == JsonValueKind.True) + { + if (value.ValueKind is not (JsonValueKind.True or JsonValueKind.False)) + { + throw new DiagnosticProtocolException("INVALID_RESPONSE", $"Dynamic signal '{signalIdentifier}' must be boolean."); + } + + return; + } + + if (value.ValueKind != JsonValueKind.Number || + !value.TryGetDouble(out var number) || + !double.IsFinite(number)) + { + throw new DiagnosticProtocolException("INVALID_RESPONSE", $"Dynamic signal '{signalIdentifier}' must be a finite JSON number."); + } + } + private static bool Same(string left, string right) => StringComparer.OrdinalIgnoreCase.Equals(left, right); diff --git a/src/AutoForge.Diagnostics/SyntheticProtocolV1.cs b/src/AutoForge.Diagnostics/SyntheticProtocolV1.cs index c73d5b5..6064368 100644 --- a/src/AutoForge.Diagnostics/SyntheticProtocolV1.cs +++ b/src/AutoForge.Diagnostics/SyntheticProtocolV1.cs @@ -179,6 +179,52 @@ public static class SyntheticProtocolV1 JsonOptions); } +public static class SyntheticProtocolV2 +{ + private static readonly JsonSerializerOptions JsonOptions = new() + { + PropertyNamingPolicy = JsonNamingPolicy.CamelCase, + UnmappedMemberHandling = JsonUnmappedMemberHandling.Disallow + }; + + public static byte[] EncodePositiveResponse(SyntheticDiagnosticRequest request, object data) => + JsonSerializer.SerializeToUtf8Bytes( + new + { + version = 2, + sessionIdentifier = request.SessionIdentifier, + configurationIdentifier = request.ConfigurationIdentifier, + correlationIdentifier = request.CorrelationIdentifier, + targetAddress = request.TargetAddress, + service = request.Service, + success = true, + errorCode = (string?)null, + error = (string?)null, + data + }, + JsonOptions); + + public static byte[] EncodeNegativeResponse( + SyntheticDiagnosticRequest request, + string code, + string message) => + JsonSerializer.SerializeToUtf8Bytes( + new + { + version = 2, + sessionIdentifier = request.SessionIdentifier, + configurationIdentifier = request.ConfigurationIdentifier, + correlationIdentifier = request.CorrelationIdentifier, + targetAddress = request.TargetAddress, + service = request.Service, + success = false, + errorCode = code, + error = message, + data = (object?)null + }, + JsonOptions); +} + public sealed class DiagnosticProtocolException(string failureCode, string message) : Exception(message) { public string FailureCode { get; } = failureCode; diff --git a/src/AutoForge.Simulation/AssemblyInfo.cs b/src/AutoForge.Simulation/AssemblyInfo.cs new file mode 100644 index 0000000..6de025a --- /dev/null +++ b/src/AutoForge.Simulation/AssemblyInfo.cs @@ -0,0 +1,3 @@ +using System.Runtime.CompilerServices; + +[assembly: InternalsVisibleTo("AutoForge.UnitTests")] diff --git a/src/AutoForge.Simulation/DynamicsDiagnosticProvider.cs b/src/AutoForge.Simulation/DynamicsDiagnosticProvider.cs new file mode 100644 index 0000000..6cf7893 --- /dev/null +++ b/src/AutoForge.Simulation/DynamicsDiagnosticProvider.cs @@ -0,0 +1,302 @@ +using System.Collections.Concurrent; +using System.Text.Json; +using AutoForge.Core.ExecutionTargets; +using AutoForge.Core.Simulation; +using AutoForge.Core.Vehicles; +using AutoForge.Diagnostics; + +namespace AutoForge.Simulation; + +public sealed class DynamicsDiagnosticTransportFactory : IDynamicsDiagnosticTransportFactory +{ + public const string ProviderIdentifier = "autoforge.simulation.dynamics"; + + private readonly Dictionary<(string ProfileIdentifier, int Revision), SimulationDefinition> _definitions; + private readonly IDynamicsPacer _pacer; + private readonly ConcurrentDictionary _active = + new(StringComparer.Ordinal); + + public DynamicsDiagnosticTransportFactory(IEnumerable definitions, IDynamicsPacer? pacer = null) + { + ArgumentNullException.ThrowIfNull(definitions); + _pacer = pacer ?? new TaskDelayDynamicsPacer(); + _definitions = definitions.ToDictionary( + definition => (definition.ProfileIdentifier.ToUpperInvariant(), definition.ProfileRevision)); + Descriptor = new DiagnosticProviderDescriptor( + new ExecutionTargetDescriptor(ProviderIdentifier, ExecutionTargetKind.Simulation), + "Synthetic fixed-step dynamics provider"); + } + + public DiagnosticProviderDescriptor Descriptor { get; } + + public IDiagnosticTransport OpenTransport(VehicleProfile profile, DiagnosticSessionIdentity identity) => + throw new InvalidOperationException("Dynamics provider sessions must be explicitly opened with a dynamics configuration."); + + public DynamicsSessionBinding OpenDynamicsTransport( + VehicleProfile profile, + DiagnosticSessionIdentity identity, + DynamicsConfiguration configuration) + { + ArgumentNullException.ThrowIfNull(profile); + ArgumentNullException.ThrowIfNull(identity); + ArgumentNullException.ThrowIfNull(configuration); + if (identity.Target.Kind != ExecutionTargetKind.Simulation || + !StringComparer.OrdinalIgnoreCase.Equals(identity.Target.ProviderIdentifier, ProviderIdentifier) || + !StringComparer.OrdinalIgnoreCase.Equals(identity.ProfileIdentifier, profile.ProfileIdentifier) || + identity.ProfileRevision != profile.Revision || + !StringComparer.OrdinalIgnoreCase.Equals(identity.VehicleIdentifier, profile.Vehicle.VehicleIdentifier) || + !StringComparer.Ordinal.Equals(identity.DynamicsConfigurationIdentifier, configuration.ConfigurationIdentifier) || + identity.DynamicsRunIdentifier is null) + { + throw new ArgumentException("Dynamics session identity does not bind to the exact selected profile, provider and configuration.", nameof(identity)); + } + + configuration.ValidateAgainst(profile); + if (!_definitions.TryGetValue((profile.ProfileIdentifier.ToUpperInvariant(), profile.Revision), out var definition)) + { + throw new DiagnosticProviderException( + DiagnosticProviderFailure.ConfigurationNotFound, + $"No dynamics endpoint mapping exists for profile '{profile.ProfileIdentifier}' revision {profile.Revision}."); + } + + definition.ValidateAgainst(profile); + var engineModule = definition.Modules.FirstOrDefault(module => + StringComparer.OrdinalIgnoreCase.Equals(module.ModuleIdentifier, configuration.EngineModuleIdentifier)); + var transmissionModule = definition.Modules.FirstOrDefault(module => + StringComparer.OrdinalIgnoreCase.Equals(module.ModuleIdentifier, configuration.TransmissionModuleIdentifier)); + if (engineModule is null || transmissionModule is null) + { + throw new ArgumentException("The selected configuration modules must have explicit diagnostic endpoint mappings.", nameof(configuration)); + } + + var engine = new DynamicsEngine(configuration, identity.DynamicsRunIdentifier); + var control = new DynamicsRunControl(engine, _pacer); + var transport = new DynamicsDiagnosticTransport( + profile, + identity, + configuration, + engine, + definition.Modules + .Where(module => StringComparer.OrdinalIgnoreCase.Equals(module.ModuleIdentifier, engineModule.ModuleIdentifier) || + StringComparer.OrdinalIgnoreCase.Equals(module.ModuleIdentifier, transmissionModule.ModuleIdentifier)) + .ToArray(), + closed => _active.TryRemove(closed, out _)); + if (!_active.TryAdd(identity.SessionIdentifier, transport)) + { + _ = control.DisposeAsync(); + throw new DiagnosticProviderException( + DiagnosticProviderFailure.SessionConflict, + $"Dynamics session '{identity.SessionIdentifier}' is already active."); + } + + return new DynamicsSessionBinding(transport, control); + } +} + +internal sealed class DynamicsDiagnosticTransport : IDiagnosticTransport +{ + private readonly VehicleProfile _profile; + private readonly DiagnosticSessionIdentity _identity; + private readonly DynamicsConfiguration _configuration; + private readonly DynamicsEngine _engine; + private readonly IReadOnlyDictionary _modules; + private readonly Action _onClosed; + private int _closed; + + public DynamicsDiagnosticTransport( + VehicleProfile profile, + DiagnosticSessionIdentity identity, + DynamicsConfiguration configuration, + DynamicsEngine engine, + IReadOnlyList modules, + Action onClosed) + { + _profile = profile; + _identity = identity; + _configuration = configuration; + _engine = engine; + _modules = modules.ToDictionary(module => module.Address, StringComparer.OrdinalIgnoreCase); + _onClosed = onClosed; + ExpectedEndpoints = Array.AsReadOnly(modules + .Select(module => new DiagnosticEndpoint(module.ModuleIdentifier, module.Address)) + .ToArray()); + } + + public IReadOnlyList ExpectedEndpoints { get; } + + public ValueTask SendAsync(ReadOnlyMemory payload, CancellationToken cancellationToken) + { + cancellationToken.ThrowIfCancellationRequested(); + if (Volatile.Read(ref _closed) != 0) + { + return ValueTask.FromResult(new TransportReply( + TransportOutcome.Cancelled, + ReadOnlyMemory.Empty, + 0, + "Dynamics diagnostic transport is closed.")); + } + + if (!SyntheticProtocolV1.TryDecodeRequest(payload, out var request) || request is null) + { + return ValueTask.FromResult(new TransportReply( + TransportOutcome.NoResponse, + ReadOnlyMemory.Empty, + 0, + "Request frame was malformed.")); + } + + if (request.Version != 2) + { + return Reply(request, false, "UNSUPPORTED_VERSION", "Dynamics protocol version 2 is required."); + } + + if (!StringComparer.Ordinal.Equals(request.SessionIdentifier, _identity.SessionIdentifier) || + !StringComparer.Ordinal.Equals(request.ConfigurationIdentifier, _identity.ConfigurationIdentifier) || + request.ProfileRevision != _identity.ProfileRevision || + !StringComparer.Ordinal.Equals(request.ProfileIdentifier, _identity.ProfileIdentifier)) + { + return Reply(request, false, "SESSION_MISMATCH", "Request session/profile identity is not bound to this dynamics transport."); + } + + if (!_modules.TryGetValue(request.TargetAddress, out var module)) + { + return Reply(request, false, "UNKNOWN_ADDRESS", "No dynamics endpoint is mapped to this address."); + } + + if (!module.ImplementedServices.Contains(request.Service, StringComparer.Ordinal)) + { + return Reply(request, false, "UNSUPPORTED_SERVICE", $"Service '{request.Service}' is not implemented by this virtual endpoint."); + } + + cancellationToken.ThrowIfCancellationRequested(); + object data; + try + { + data = request.Service switch + { + DiagnosticServices.Probe => new + { + moduleIdentifier = module.ModuleIdentifier, + implementedServices = module.ImplementedServices + }, + DiagnosticServices.ReadIdentity => IdentityData(module), + DiagnosticServices.ReadTroubleCodes => new { moduleIdentifier = module.ModuleIdentifier, codes = Array.Empty() }, + DiagnosticServices.ClearTroubleCodes => new { moduleIdentifier = module.ModuleIdentifier, clearedCount = 0 }, + DiagnosticServices.ReadSignals => ReadDynamicSignals(module, request), + _ => throw new DiagnosticProtocolException("UNSUPPORTED_SERVICE", $"Service '{request.Service}' is not defined by dynamics protocol v2.") + }; + } + catch (DiagnosticProtocolException exception) + { + return Reply(request, false, exception.FailureCode, exception.Message); + } + + return ValueTask.FromResult(new TransportReply( + TransportOutcome.Response, + SyntheticProtocolV2.EncodePositiveResponse(request, data), + 1)); + } + + public ValueTask DisposeAsync() + { + if (Interlocked.Exchange(ref _closed, 1) == 0) + { + _onClosed(_identity.SessionIdentifier); + } + + return ValueTask.CompletedTask; + } + + private object IdentityData(VirtualModuleDefinition module) + { + var identity = module.Identity; + var profileModule = _profile.GetModule(module.ModuleIdentifier); + if (!StringComparer.OrdinalIgnoreCase.Equals(identity.Role, profileModule.Role) || + !StringComparer.OrdinalIgnoreCase.Equals(identity.Name, profileModule.Name) || + !StringComparer.OrdinalIgnoreCase.Equals(identity.CalibrationIdentifier, profileModule.CalibrationIdentifier)) + { + throw new DiagnosticProtocolException("INVALID_MAPPING", "Dynamics endpoint identity does not match the selected profile."); + } + + return new + { + moduleIdentifier = module.ModuleIdentifier, + role = identity.Role, + name = identity.Name, + hardwareIdentifier = identity.HardwareIdentifier, + softwareIdentifier = identity.SoftwareIdentifier, + firmwareIdentifier = identity.FirmwareIdentifier, + calibrationIdentifier = identity.CalibrationIdentifier + }; + } + + private object ReadDynamicSignals(VirtualModuleDefinition module, SyntheticDiagnosticRequest request) + { + lock (_engine.SyncRoot) + { + var status = _engine.Status; + if (status.State == DynamicsLifecycleState.Faulted) + { + throw new DiagnosticProtocolException( + "DYNAMICS_RUN_FAULTED", + status.Failure ?? "Dynamics run failed; telemetry is unavailable."); + } + + var state = _engine.ReadTelemetry(module.ModuleIdentifier); + var signals = StringComparer.OrdinalIgnoreCase.Equals(module.ModuleIdentifier, _configuration.EngineModuleIdentifier) + ? EngineSignals(state) + : TransmissionSignals(state); + return new + { + moduleIdentifier = module.ModuleIdentifier, + configurationIdentifier = _configuration.ConfigurationIdentifier, + runIdentifier = _identity.DynamicsRunIdentifier, + modelStepIndex = state.StepIndex, + modelTimeSeconds = state.ModelTimeSeconds, + origin = "SYNTHETIC_DYNAMIC", + captureLogicalTimeTicks = request.LogicalTimeTicks, + signals + }; + } + } + + private static object[] EngineSignals(DynamicsTelemetryState state) => + [ + Signal("engine.running", state.EngineRunning, "boolean"), + Signal("engine.speed", state.EngineSpeedRpm, "rpm"), + Signal("vehicle.speed", state.VehicleSpeedMetersPerSecond, "m/s"), + Signal("engine.throttle", state.Throttle, "ratio"), + Signal("engine.load", state.EngineLoad, "ratio"), + Signal("engine.torque", state.EngineTorqueNewtonMeters, "N*m"), + Signal("engine.fuel-rate", state.FuelRateKilogramsPerSecond, "kg/s"), + Signal("engine.fuel-consumed", state.FuelConsumedKilograms, "kg"), + Signal("engine.temperature", state.EngineTemperatureCelsius, "degC"), + Signal("vehicle.distance", state.DistanceMeters, "m"), + Signal("vehicle.acceleration", state.AccelerationMetersPerSecondSquared, "m/s^2"), + Signal("driver.brake", state.Brake, "ratio") + ]; + + private static object[] TransmissionSignals(DynamicsTelemetryState state) => + [ + Signal("transmission.gear", state.Gear, "gear"), + Signal("transmission.shift-count", state.ShiftCount, "count"), + Signal("transmission.coupling-slip", state.CouplingSlipFraction, "ratio"), + Signal("vehicle.speed", state.VehicleSpeedMetersPerSecond, "m/s"), + Signal("engine.speed", state.EngineSpeedRpm, "rpm") + ]; + + private static object Signal(string identifier, object value, string unit) => + new { signalIdentifier = identifier, value, unit, quality = "Good" }; + + private static ValueTask Reply( + SyntheticDiagnosticRequest request, + bool success, + string code, + string message) => + ValueTask.FromResult(new TransportReply( + TransportOutcome.Response, + success + ? SyntheticProtocolV2.EncodePositiveResponse(request, new { }) + : SyntheticProtocolV2.EncodeNegativeResponse(request, code, message), + 1)); +} diff --git a/src/AutoForge.Simulation/DynamicsEngine.cs b/src/AutoForge.Simulation/DynamicsEngine.cs new file mode 100644 index 0000000..8d81c5c --- /dev/null +++ b/src/AutoForge.Simulation/DynamicsEngine.cs @@ -0,0 +1,1093 @@ +using AutoForge.Core.Simulation; +using AutoForge.Diagnostics; + +namespace AutoForge.Simulation; + +internal sealed record DynamicsTelemetryState( + long StepIndex, + double ModelTimeSeconds, + bool EngineRunning, + double EngineSpeedRpm, + double VehicleSpeedMetersPerSecond, + int Gear, + double Throttle, + double Brake, + double EngineLoad, + double EngineTorqueNewtonMeters, + double FuelRateKilogramsPerSecond, + double FuelConsumedKilograms, + double EngineTemperatureCelsius, + double DistanceMeters, + double AccelerationMetersPerSecondSquared, + double CouplingSlipFraction, + int ShiftCount, + DynamicsScenarioPhaseKind Phase); + +internal sealed class DynamicsEngine +{ + internal object SyncRoot { get; } = new(); + private readonly DynamicsConfiguration _configuration; + private readonly List _samples = []; + private long _stepIndex; + private int _phaseIndex; + private long _phaseStepCount; + private double _phaseElapsedSeconds; + private double _completedScenarioSeconds; + private double _speed; + private int _gear; + private bool _engineRunning; + private double _engineSpeedRpm; + private double _engineTemperature; + private double _fuelConsumed; + private double _distance; + private double _throttle; + private double _brake; + private double _engineLoad; + private double _engineTorque; + private double _fuelRate; + private double _acceleration; + private double _couplingSlip; + private double _cruiseIntegral; + private int _shiftCount; + private DynamicsLifecycleState _lifecycle = DynamicsLifecycleState.Stopped; + private string? _failure; + + private sealed record MutableState( + long StepIndex, + int PhaseIndex, + long PhaseStepCount, + double PhaseElapsedSeconds, + double CompletedScenarioSeconds, + double Speed, + int Gear, + bool EngineRunning, + double EngineSpeedRpm, + double EngineTemperature, + double FuelConsumed, + double Distance, + double Throttle, + double Brake, + double EngineLoad, + double EngineTorque, + double FuelRate, + double Acceleration, + double CouplingSlip, + double CruiseIntegral, + int ShiftCount, + DynamicsLifecycleState Lifecycle, + string? Failure, + int SampleCount); + + public DynamicsEngine(DynamicsConfiguration configuration, string runIdentifier) + { + _configuration = configuration ?? throw new ArgumentNullException(nameof(configuration)); + ArgumentException.ThrowIfNullOrWhiteSpace(runIdentifier); + RunIdentifier = runIdentifier; + ResetState(); + } + + public string RunIdentifier { get; } + public DynamicsConfiguration Configuration => _configuration; + public DynamicsLifecycleState Lifecycle => _lifecycle; + public int SampleCount => _samples.Count; + public int CruiseSampleCount => _samples.Count(sample => sample.Phase == DynamicsScenarioPhaseKind.Cruise); + + public DynamicsRunStatus Status + { + get + { + lock (SyncRoot) + { + var phase = _phaseIndex < _configuration.Scenario.Count + ? _configuration.Scenario[_phaseIndex] + : null; + var totalDuration = _configuration.Scenario.Sum(item => item.DurationSeconds); + var completedDuration = _completedScenarioSeconds + _phaseElapsedSeconds; + var phaseProgress = phase is null + ? 1 + : Math.Clamp(_phaseElapsedSeconds / phase.DurationSeconds, 0, 1); + return new DynamicsRunStatus( + RunIdentifier, + _configuration.ConfigurationIdentifier, + _stepIndex, + _stepIndex * _configuration.Model.StepSeconds, + _lifecycle, + _phaseIndex, + phase?.Kind.ToString(), + _phaseElapsedSeconds, + _lifecycle == DynamicsLifecycleState.Completed || totalDuration == 0 + ? 1 + : Math.Clamp(completedDuration / totalDuration, 0, 1), + phaseProgress, + _failure); + } + } + } + + public DynamicsTelemetryState ReadTelemetry(string moduleIdentifier) + { + lock (SyncRoot) + { + if (!StringComparer.OrdinalIgnoreCase.Equals(moduleIdentifier, _configuration.EngineModuleIdentifier) && + !StringComparer.OrdinalIgnoreCase.Equals(moduleIdentifier, _configuration.TransmissionModuleIdentifier)) + { + throw new KeyNotFoundException($"Dynamics module '{moduleIdentifier}' is not part of this run."); + } + + return CurrentState(); + } + } + + public void Start() + { + RequireLifecycle(DynamicsLifecycleState.Stopped); + _lifecycle = DynamicsLifecycleState.Running; + } + + public void Pause() + { + RequireLifecycle(DynamicsLifecycleState.Running); + _lifecycle = DynamicsLifecycleState.Paused; + } + + public void Resume() + { + RequireLifecycle(DynamicsLifecycleState.Paused); + _lifecycle = DynamicsLifecycleState.Running; + } + + public void Stop() + { + if (_lifecycle is DynamicsLifecycleState.Closed or DynamicsLifecycleState.Faulted or DynamicsLifecycleState.Completed) + { + throw new InvalidOperationException($"A {_lifecycle} dynamics run cannot be stopped."); + } + + _lifecycle = DynamicsLifecycleState.Stopped; + } + + public void Reset() + { + if (_lifecycle == DynamicsLifecycleState.Closed) + { + throw new InvalidOperationException("A closed dynamics run cannot be reset."); + } + + ResetState(); + } + + public void Close() + { + if (_lifecycle != DynamicsLifecycleState.Closed) + { + _lifecycle = DynamicsLifecycleState.Closed; + } + } + + public DynamicsRunStatus AdvanceOne() + { + if (_lifecycle is DynamicsLifecycleState.Closed or DynamicsLifecycleState.Faulted or DynamicsLifecycleState.Completed) + { + throw new InvalidOperationException($"A {_lifecycle} dynamics run cannot advance."); + } + + if (_phaseIndex >= _configuration.Scenario.Count) + { + _lifecycle = DynamicsLifecycleState.Completed; + return Status; + } + + var previous = CaptureMutableState(); + try + { + var model = _configuration.Model; + var step = model.StepSeconds; + var phase = _configuration.Scenario[_phaseIndex]; + UpdateGearAndEngineState(phase); + UpdateDriverInputs(phase); + UpdateEngineAndForces(step, phase); + if (!AllFiniteAndInDomain()) + { + throw new ArithmeticException("Dynamics left its finite supported domain."); + } + + _stepIndex++; + _phaseStepCount++; + _phaseElapsedSeconds = _phaseStepCount * step; + _samples.Add(CurrentState()); + AdvanceScenarioIfReady(phase); + } + catch (ArithmeticException exception) + { + RestoreMutableState(previous); + Fault($"Dynamics calculation failed explicitly: {exception.Message}"); + } + + return Status; + } + + internal DynamicsTelemetryState CurrentState() => new( + _stepIndex, + _stepIndex * _configuration.Model.StepSeconds, + _engineRunning, + _engineSpeedRpm, + _speed, + _gear, + _throttle, + _brake, + _engineLoad, + _engineTorque, + _fuelRate, + _fuelConsumed, + _engineTemperature, + _distance, + _acceleration, + _couplingSlip, + _shiftCount, + _configuration.Scenario[Math.Min(_phaseIndex, _configuration.Scenario.Count - 1)].Kind); + + internal IReadOnlyList Samples => Array.AsReadOnly(_samples.ToArray()); + + private void UpdateGearAndEngineState(DynamicsScenarioPhase phase) + { + var model = _configuration.Model; + if (phase.Kind == DynamicsScenarioPhaseKind.WarmIdle) + { + _engineRunning = true; + _gear = 0; + } + else if (phase.Kind is DynamicsScenarioPhaseKind.Accelerate or DynamicsScenarioPhaseKind.Cruise) + { + _engineRunning = true; + if (_gear == 0) + { + _gear = 1; + } + + var lockedRpm = CoupledEngineSpeed(_gear); + var inSlip = lockedRpm < model.IdleSpeedRpm || + _speed < model.LaunchSlipEndSpeedMetersPerSecond && _gear == 1; + if (!inSlip) + { + while (_gear < model.ForwardGearRatios.Count) + { + var gearIndex = _gear - 1; + if (lockedRpm < model.UpshiftSpeedsRpm[gearIndex] && + lockedRpm <= model.MaximumEngineSpeedRpm) + { + break; + } + + _gear++; + _shiftCount++; + _cruiseIntegral = 0; + lockedRpm = CoupledEngineSpeed(_gear); + } + + if (lockedRpm > model.MaximumEngineSpeedRpm) + { + throw new ArithmeticException( + $"Locked drivetrain speed {lockedRpm:F1} rpm exceeds the configured {model.MaximumEngineSpeedRpm:F1} rpm limit in top gear."); + } + + var activeGearIndex = _gear - 1; + if (lockedRpm <= model.DownshiftSpeedsRpm[activeGearIndex] && _gear > 1) + { + _gear--; + _shiftCount++; + _cruiseIntegral = 0; + } + } + } + else if (phase.Kind is DynamicsScenarioPhaseKind.Brake or DynamicsScenarioPhaseKind.ReturnIdle) + { + _engineRunning = true; + if (_speed <= 0.1) + { + _gear = 0; + } + else if (_gear > 1) + { + var gearIndex = _gear - 1; + if (CoupledEngineSpeed(_gear) <= model.DownshiftSpeedsRpm[gearIndex]) + { + _gear--; + _shiftCount++; + } + } + } + } + + private void UpdateDriverInputs(DynamicsScenarioPhase phase) + { + var model = _configuration.Model; + var roadLoad = RoadLoadForce(_speed); + _brake = 0; + switch (phase.Kind) + { + case DynamicsScenarioPhaseKind.WarmIdle: + _throttle = 0; + break; + case DynamicsScenarioPhaseKind.Accelerate: + { + if (_speed >= phase.TargetSpeedMetersPerSecond) + { + _throttle = 0; + break; + } + + var requestedForce = model.VehicleMassKilograms * 2.0 + roadLoad; + _throttle = ThrottleForForce(requestedForce); + break; + } + case DynamicsScenarioPhaseKind.Cruise: + { + var error = phase.TargetSpeedMetersPerSecond - _speed; + _cruiseIntegral = Math.Clamp(_cruiseIntegral + error * model.StepSeconds, -5, 5); + var requestedForce = roadLoad + 1_600 * error + 35 * _cruiseIntegral; + _throttle = ThrottleForForce(Math.Max(0, requestedForce)); + break; + } + case DynamicsScenarioPhaseKind.Brake: + _throttle = 0; + _brake = Math.Clamp( + (model.VehicleMassKilograms * 3.2 + roadLoad) / model.MaximumBrakeForceNewtons, + 0, + 1); + break; + case DynamicsScenarioPhaseKind.ReturnIdle: + _throttle = 0; + if (_speed > 0.005) + { + _brake = Math.Clamp( + (model.VehicleMassKilograms * 2 + roadLoad) / model.MaximumBrakeForceNewtons, + 0, + 1); + } + break; + default: + throw new ArgumentOutOfRangeException(nameof(phase)); + } + + if (phase.Kind is DynamicsScenarioPhaseKind.Accelerate or DynamicsScenarioPhaseKind.Cruise) + { + var maximumSpeed = Math.Min( + phase.TargetSpeedMetersPerSecond, + MaximumCoupledSpeedMetersPerSecond()); + var allowableAcceleration = (maximumSpeed - _speed) / model.StepSeconds; + var allowableForce = roadLoad + model.VehicleMassKilograms * Math.Max(0, allowableAcceleration); + _throttle = Math.Min(_throttle, ThrottleForForce(allowableForce)); + } + } + + private void UpdateEngineAndForces(double step, DynamicsScenarioPhase phase) + { + var model = _configuration.Model; + var previousSpeed = _speed; + var lockedRpm = _gear > 0 ? CoupledEngineSpeed(_gear) : 0; + var slipping = _engineRunning && + _gear == 1 && + (_speed < model.LaunchSlipEndSpeedMetersPerSecond || lockedRpm < model.IdleSpeedRpm); + if (!_engineRunning) + { + _engineSpeedRpm = 0; + } + else if (_gear == 0) + { + _engineSpeedRpm += (model.WarmIdleTargetRpm - _engineSpeedRpm) * Math.Min(1, step * 4); + } + else if (slipping) + { + _engineSpeedRpm = Math.Min( + model.MaximumEngineSpeedRpm, + model.IdleSpeedRpm + Math.Min(2_000, _throttle * 2_000)); + } + else + { + _engineSpeedRpm = lockedRpm; + } + + _engineTorque = _engineRunning + ? TorqueAtSpeed(_engineSpeedRpm) * _throttle + : 0; + var maximumTorque = TorqueAtSpeed(Math.Max(model.IdleSpeedRpm, _engineSpeedRpm)); + _engineLoad = maximumTorque <= 0 ? 0 : Math.Clamp(_engineTorque / maximumTorque, 0, 1); + var engineAngularVelocity = _engineSpeedRpm * (Math.PI * 2) / 60; + var enginePower = Math.Max(0, _engineTorque * engineAngularVelocity); + _fuelRate = _engineRunning + ? model.IdleFuelRateKilogramsPerSecond + enginePower * model.FuelKilogramsPerJoule + : 0; + + var couplingFactor = slipping + ? Math.Clamp(_speed / model.LaunchSlipEndSpeedMetersPerSecond, 0.2, 1) + : 1; + _couplingSlip = slipping ? 1 - couplingFactor : 0; + var gearRatio = _gear > 0 ? model.ForwardGearRatios[_gear - 1] : 0; + var tractionForce = _engineRunning && _gear > 0 + ? _engineTorque * gearRatio * model.FinalDriveRatio * model.DrivetrainEfficiency / + model.WheelRadiusMeters * couplingFactor + : 0; + var roadLoad = RoadLoadForce(_speed); + var brakeForce = _brake * model.MaximumBrakeForceNewtons; + _acceleration = (tractionForce - roadLoad - brakeForce) / model.VehicleMassKilograms; + _speed = Math.Max(0, _speed + _acceleration * step); + if (_speed == 0 && _acceleration < 0) + { + _acceleration = (0 - previousSpeed) / step; + } + + if (_engineRunning && _gear > 0 && !slipping) + { + _engineSpeedRpm = CoupledEngineSpeed(_gear); + _engineTorque = TorqueAtSpeed(_engineSpeedRpm) * _throttle; + maximumTorque = TorqueAtSpeed(Math.Max(model.IdleSpeedRpm, _engineSpeedRpm)); + _engineLoad = maximumTorque <= 0 ? 0 : Math.Clamp(_engineTorque / maximumTorque, 0, 1); + engineAngularVelocity = _engineSpeedRpm * (Math.PI * 2) / 60; + enginePower = Math.Max(0, _engineTorque * engineAngularVelocity); + _fuelRate = model.IdleFuelRateKilogramsPerSecond + enginePower * model.FuelKilogramsPerJoule; + } + + if (_engineRunning && _gear > 0) + { + _couplingSlip = CouplingSlipFraction(_engineSpeedRpm, CoupledEngineSpeed(_gear)); + } + else + { + _couplingSlip = 0; + } + + _distance += (previousSpeed + _speed) * 0.5 * step; + _fuelConsumed += _fuelRate * step; + var thermalTarget = Math.Max(model.AmbientTemperatureCelsius, model.EquilibriumEngineTemperatureCelsius) + + Math.Min(15, enginePower / 100_000 * 4); + _engineTemperature += (thermalTarget - _engineTemperature) * model.ThermalResponsePerSecond * step; + + if (phase.Kind == DynamicsScenarioPhaseKind.ReturnIdle && _speed <= 0.005) + { + _speed = 0; + _acceleration = 0; + _gear = 0; + _couplingSlip = 0; + } + } + + private double ThrottleForForce(double forceNewtons) + { + if (!_engineRunning || _gear <= 0 || forceNewtons <= 0) + { + return 0; + } + + var model = _configuration.Model; + var torque = TorqueAtSpeed(Math.Max(_engineSpeedRpm, model.IdleSpeedRpm)); + var coupling = _speed < model.LaunchSlipEndSpeedMetersPerSecond && _gear == 1 + ? Math.Clamp(_speed / model.LaunchSlipEndSpeedMetersPerSecond, 0.2, 1) + : 1; + var forceAtFullThrottle = torque * model.ForwardGearRatios[_gear - 1] * + model.FinalDriveRatio * model.DrivetrainEfficiency / + model.WheelRadiusMeters * coupling; + return forceAtFullThrottle <= 0 + ? 0 + : Math.Clamp(forceNewtons / forceAtFullThrottle, 0, 1); + } + + private double TorqueAtSpeed(double rpm) + { + var curve = _configuration.Model.EngineTorqueCurve; + if (rpm <= curve[0].EngineSpeedRpm) + { + return curve[0].TorqueNewtonMeters; + } + + for (var index = 1; index < curve.Count; index++) + { + if (rpm <= curve[index].EngineSpeedRpm) + { + var lower = curve[index - 1]; + var upper = curve[index]; + var fraction = (rpm - lower.EngineSpeedRpm) / + (upper.EngineSpeedRpm - lower.EngineSpeedRpm); + return lower.TorqueNewtonMeters + + (upper.TorqueNewtonMeters - lower.TorqueNewtonMeters) * fraction; + } + } + + return curve[^1].TorqueNewtonMeters; + } + + private double CoupledEngineSpeed(int gear) + { + var model = _configuration.Model; + return _speed / (Math.PI * 2 * model.WheelRadiusMeters) * 60 * + model.ForwardGearRatios[gear - 1] * model.FinalDriveRatio; + } + + private static double CouplingSlipFraction(double engineSpeedRpm, double wheelSpeedRpm) + { + var maximumSpeed = Math.Max(engineSpeedRpm, wheelSpeedRpm); + return maximumSpeed == 0 ? 0 : Math.Abs(engineSpeedRpm - wheelSpeedRpm) / maximumSpeed; + } + + private double MaximumCoupledSpeedMetersPerSecond() + { + var model = _configuration.Model; + return model.MaximumEngineSpeedRpm * (2 * Math.PI * model.WheelRadiusMeters) / 60 / + (model.ForwardGearRatios[^1] * model.FinalDriveRatio); + } + + private double RoadLoadForce(double speed) => + _configuration.Model.VehicleMassKilograms * + _configuration.Model.GravityMetersPerSecondSquared * + _configuration.Model.RollingResistanceCoefficient + + 0.5 * _configuration.Model.AirDensityKilogramsPerCubicMeter * + _configuration.Model.DragAreaSquareMeters * speed * speed; + + private void AdvanceScenarioIfReady(DynamicsScenarioPhase phase) + { + var model = _configuration.Model; + var succeeded = phase.Kind switch + { + DynamicsScenarioPhaseKind.WarmIdle => _phaseElapsedSeconds >= phase.DurationSeconds, + DynamicsScenarioPhaseKind.Accelerate => _speed >= phase.TargetSpeedMetersPerSecond, + DynamicsScenarioPhaseKind.Cruise => _phaseElapsedSeconds >= phase.DurationSeconds, + DynamicsScenarioPhaseKind.Brake => _speed <= 0.1, + DynamicsScenarioPhaseKind.ReturnIdle => + _phaseElapsedSeconds >= phase.DurationSeconds && _speed <= 0.1, + _ => false + }; + + if (succeeded) + { + _completedScenarioSeconds += _phaseElapsedSeconds; + _phaseIndex++; + _phaseStepCount = 0; + _phaseElapsedSeconds = 0; + _cruiseIntegral = 0; + if (_phaseIndex >= _configuration.Scenario.Count) + { + _lifecycle = DynamicsLifecycleState.Completed; + } + + return; + } + + if (_phaseElapsedSeconds >= phase.DurationSeconds && + phase.Kind is DynamicsScenarioPhaseKind.Accelerate or DynamicsScenarioPhaseKind.Brake or DynamicsScenarioPhaseKind.ReturnIdle) + { + Fault($"Scenario phase '{phase.Kind}' did not meet its target within {phase.DurationSeconds} virtual seconds."); + } + } + + private bool AllFiniteAndInDomain() + { + var values = new[] + { + _speed, _engineSpeedRpm, _throttle, _brake, _engineLoad, _engineTorque, + _fuelRate, _fuelConsumed, _engineTemperature, _distance, _acceleration + }; + return values.All(double.IsFinite) && + _speed >= 0 && + _engineSpeedRpm >= 0 && + _throttle is >= 0 and <= 1 && + _brake is >= 0 and <= 1 && + _engineLoad is >= 0 and <= 1 && + _engineTorque >= 0 && + _fuelRate >= 0 && + _fuelConsumed >= 0 && + _distance >= 0 && + _couplingSlip is >= 0 and <= 1 && + _engineSpeedRpm <= _configuration.Model.MaximumEngineSpeedRpm && + _gear >= 0 && + _gear <= _configuration.Model.ForwardGearRatios.Count; + } + + private void Fault(string message) + { + _failure = message; + _lifecycle = DynamicsLifecycleState.Faulted; + } + + private void RequireLifecycle(DynamicsLifecycleState expected) + { + if (_lifecycle != expected) + { + throw new InvalidOperationException($"Dynamics lifecycle transition requires {expected}; current state is {_lifecycle}."); + } + } + + private void ResetState() + { + var initial = _configuration.InitialConditions; + _stepIndex = 0; + _phaseIndex = 0; + _phaseStepCount = 0; + _phaseElapsedSeconds = 0; + _completedScenarioSeconds = 0; + _speed = initial.VehicleSpeedMetersPerSecond; + _gear = initial.Gear; + _engineRunning = initial.EngineRunning; + _engineSpeedRpm = initial.EngineSpeedRpm; + _engineTemperature = initial.EngineTemperatureCelsius; + _fuelConsumed = initial.FuelConsumedKilograms; + _distance = initial.DistanceMeters; + _throttle = 0; + _brake = 0; + _engineLoad = 0; + _engineTorque = 0; + _fuelRate = 0; + _acceleration = 0; + _couplingSlip = 0; + _cruiseIntegral = 0; + _shiftCount = 0; + _failure = null; + _samples.Clear(); + _lifecycle = DynamicsLifecycleState.Stopped; + } + + private MutableState CaptureMutableState() => + new( + _stepIndex, + _phaseIndex, + _phaseStepCount, + _phaseElapsedSeconds, + _completedScenarioSeconds, + _speed, + _gear, + _engineRunning, + _engineSpeedRpm, + _engineTemperature, + _fuelConsumed, + _distance, + _throttle, + _brake, + _engineLoad, + _engineTorque, + _fuelRate, + _acceleration, + _couplingSlip, + _cruiseIntegral, + _shiftCount, + _lifecycle, + _failure, + _samples.Count); + + private void RestoreMutableState(MutableState state) + { + _stepIndex = state.StepIndex; + _phaseIndex = state.PhaseIndex; + _phaseStepCount = state.PhaseStepCount; + _phaseElapsedSeconds = state.PhaseElapsedSeconds; + _completedScenarioSeconds = state.CompletedScenarioSeconds; + _speed = state.Speed; + _gear = state.Gear; + _engineRunning = state.EngineRunning; + _engineSpeedRpm = state.EngineSpeedRpm; + _engineTemperature = state.EngineTemperature; + _fuelConsumed = state.FuelConsumed; + _distance = state.Distance; + _throttle = state.Throttle; + _brake = state.Brake; + _engineLoad = state.EngineLoad; + _engineTorque = state.EngineTorque; + _fuelRate = state.FuelRate; + _acceleration = state.Acceleration; + _couplingSlip = state.CouplingSlip; + _cruiseIntegral = state.CruiseIntegral; + _shiftCount = state.ShiftCount; + _lifecycle = state.Lifecycle; + _failure = state.Failure; + if (_samples.Count > state.SampleCount) + { + _samples.RemoveRange(state.SampleCount, _samples.Count - state.SampleCount); + } + } + +} + +public interface IDynamicsPacer +{ + Task DelayAsync(TimeSpan delay, CancellationToken cancellationToken); +} + +internal sealed class TaskDelayDynamicsPacer : IDynamicsPacer +{ + public async Task DelayAsync(TimeSpan delay, CancellationToken cancellationToken) + { + cancellationToken.ThrowIfCancellationRequested(); + if (delay < TimeSpan.FromMilliseconds(1)) + { + await Task.Yield(); + cancellationToken.ThrowIfCancellationRequested(); + return; + } + + await Task.Delay(delay, cancellationToken).ConfigureAwait(false); + } +} + +internal sealed class DynamicsRunControl : IDynamicsControl +{ + private readonly DynamicsEngine _engine; + private readonly IDynamicsPacer _pacer; + private readonly SemaphoreSlim _gate = new(1, 1); + private readonly CancellationTokenSource _lifetime = new(); + private double _pacingFactor = 1; + private CancellationTokenSource? _runnerCancellation; + private Task? _runnerTask; + private bool _disposed; + + public DynamicsRunControl(DynamicsEngine engine, IDynamicsPacer? pacer = null) + { + _engine = engine ?? throw new ArgumentNullException(nameof(engine)); + _pacer = pacer ?? new TaskDelayDynamicsPacer(); + } + + public DynamicsRunStatus Status + { + get + { + lock (_engine.SyncRoot) + { + return _engine.Status; + } + } + } + public double PacingFactor => Volatile.Read(ref _pacingFactor); + + public Task StartAsync(CancellationToken cancellationToken = default) => + StartOrResumeAsync(resume: false, cancellationToken); + + public Task PauseAsync(CancellationToken cancellationToken = default) => + StopRunnerAsync(pause: true, reset: false, cancellationToken); + + public Task ResumeAsync(CancellationToken cancellationToken = default) => + StartOrResumeAsync(resume: true, cancellationToken); + + public Task StopAsync(CancellationToken cancellationToken = default) => + StopRunnerAsync(pause: false, reset: false, cancellationToken); + + public Task ResetAsync(CancellationToken cancellationToken = default) => + StopRunnerAsync(pause: false, reset: true, cancellationToken); + + private async Task StartOrResumeAsync(bool resume, CancellationToken cancellationToken) + { + await _gate.WaitAsync(cancellationToken).ConfigureAwait(false); + try + { + EnsureOpen(); + EnsureNoActiveAdvancementOwner(); + lock (_engine.SyncRoot) + { + if (resume) + { + _engine.Resume(); + } + else + { + _engine.Start(); + } + } + + _ = StartRunnerLocked(CancellationToken.None); + return Status; + } + finally + { + _gate.Release(); + } + } + + private async Task StopRunnerAsync( + bool pause, + bool reset, + CancellationToken cancellationToken) + { + Task? runner; + await _gate.WaitAsync(cancellationToken).ConfigureAwait(false); + try + { + EnsureOpen(); + lock (_engine.SyncRoot) + { + if (reset) + { + _engine.Reset(); + } + else if (pause) + { + _engine.Pause(); + } + else + { + _engine.Stop(); + } + } + + runner = CancelRunnerLocked(); + } + finally + { + _gate.Release(); + } + + if (runner is not null) + { + await runner.ConfigureAwait(false); + } + + return Status; + } + + public async Task StepAsync(int stepCount = 1, CancellationToken cancellationToken = default) + { + if (stepCount is < 1 or > 100_000) + { + throw new ArgumentOutOfRangeException(nameof(stepCount), "Explicit step count must be between 1 and 100000."); + } + + await _gate.WaitAsync(cancellationToken).ConfigureAwait(false); + try + { + EnsureOpen(); + if (_engine.Lifecycle is not (DynamicsLifecycleState.Stopped or DynamicsLifecycleState.Paused)) + { + throw new InvalidOperationException("Explicit stepping is allowed only while stopped or paused."); + } + + for (var step = 0; step < stepCount; step++) + { + cancellationToken.ThrowIfCancellationRequested(); + lock (_engine.SyncRoot) + { + if (_engine.Lifecycle is DynamicsLifecycleState.Completed or DynamicsLifecycleState.Faulted) + { + break; + } + + _engine.AdvanceOne(); + } + } + + return Status; + } + finally + { + _gate.Release(); + } + } + + public async Task SetPacingFactorAsync(double factor, CancellationToken cancellationToken = default) + { + if (!double.IsFinite(factor) || factor is < 0.25 or > 1_000) + { + throw new ArgumentOutOfRangeException(nameof(factor), "Pacing factor must be finite and between 0.25 and 1000."); + } + + await _gate.WaitAsync(cancellationToken).ConfigureAwait(false); + try + { + EnsureOpen(); + Volatile.Write(ref _pacingFactor, factor); + return Status; + } + finally + { + _gate.Release(); + } + } + + public async Task RunScenarioAsync(CancellationToken cancellationToken = default) + { + Task runner; + await _gate.WaitAsync(cancellationToken).ConfigureAwait(false); + try + { + EnsureOpen(); + EnsureNoActiveAdvancementOwner(); + + lock (_engine.SyncRoot) + { + if (_engine.Lifecycle == DynamicsLifecycleState.Stopped) + { + _engine.Start(); + } + else if (_engine.Lifecycle == DynamicsLifecycleState.Paused) + { + _engine.Resume(); + } + else if (_engine.Lifecycle != DynamicsLifecycleState.Running) + { + throw new InvalidOperationException($"A scenario cannot run from lifecycle state {_engine.Lifecycle}."); + } + } + + runner = StartRunnerLocked(cancellationToken); + } + finally + { + _gate.Release(); + } + + return await runner.ConfigureAwait(false); + } + + private Task StartRunnerLocked(CancellationToken callerToken) + { + EnsureNoActiveAdvancementOwner(); + + var source = CancellationTokenSource.CreateLinkedTokenSource(_lifetime.Token, callerToken); + _runnerCancellation = source; + _runnerTask = RunLoopAsync(source, callerToken); + return _runnerTask; + } + + private void EnsureNoActiveAdvancementOwner() + { + if (_runnerTask is { IsCompleted: false }) + { + throw new InvalidOperationException( + "A dynamics advancement owner is still active or settling; retry after its cleanup completes."); + } + } + + private async Task RunLoopAsync( + CancellationTokenSource source, + CancellationToken callerToken) + { + var linkedToken = source.Token; + try + { + while (true) + { + linkedToken.ThrowIfCancellationRequested(); + TimeSpan pacingDelay; + await _gate.WaitAsync(linkedToken).ConfigureAwait(false); + try + { + lock (_engine.SyncRoot) + { + if (_engine.Lifecycle == DynamicsLifecycleState.Running) + { + _engine.AdvanceOne(); + if (_engine.Lifecycle != DynamicsLifecycleState.Running) + { + return Status; + } + } + else + { + return Status; + } + } + + pacingDelay = TimeSpan.FromSeconds( + _engine.Configuration.Model.StepSeconds / PacingFactor); + } + finally + { + _gate.Release(); + } + + await _pacer.DelayAsync(pacingDelay, linkedToken).ConfigureAwait(false); + await Task.Yield(); + } + } + catch (OperationCanceledException) when (_lifetime.IsCancellationRequested) + { + return Status; + } + catch (OperationCanceledException) when (callerToken.IsCancellationRequested) + { + await PauseIfRunningAsync().ConfigureAwait(false); + throw; + } + catch (OperationCanceledException) + { + return Status; + } + finally + { + await _gate.WaitAsync().ConfigureAwait(false); + try + { + if (ReferenceEquals(_runnerCancellation, source)) + { + _runnerCancellation = null; + _runnerTask = null; + source.Dispose(); + } + } + finally + { + _gate.Release(); + } + } + } + + public async ValueTask DisposeAsync() + { + Task? runner; + await _gate.WaitAsync().ConfigureAwait(false); + try + { + if (_disposed) + { + return; + } + + _disposed = true; + _lifetime.Cancel(); + lock (_engine.SyncRoot) + { + _engine.Close(); + } + runner = CancelRunnerLocked(); + } + finally + { + _gate.Release(); + } + + if (runner is not null) + { + await runner.ConfigureAwait(false); + } + + _lifetime.Dispose(); + } + + private async Task PauseIfRunningAsync() + { + await _gate.WaitAsync().ConfigureAwait(false); + try + { + lock (_engine.SyncRoot) + { + if (_engine.Lifecycle == DynamicsLifecycleState.Running) + { + _engine.Pause(); + } + } + } + finally + { + _gate.Release(); + } + } + + private Task? CancelRunnerLocked() + { + var runner = _runnerTask; + _runnerCancellation?.Cancel(); + return runner; + } + + private void EnsureOpen() + { + if (_disposed) + { + throw new ObjectDisposedException(nameof(DynamicsRunControl)); + } + } + +} diff --git a/src/AutoForge.UI/Features/Foundation/AddAutoForgeUi.cs b/src/AutoForge.UI/Features/Foundation/AddAutoForgeUi.cs index 485836d..58ccced 100644 --- a/src/AutoForge.UI/Features/Foundation/AddAutoForgeUi.cs +++ b/src/AutoForge.UI/Features/Foundation/AddAutoForgeUi.cs @@ -1,6 +1,8 @@ using AutoForge.UI.Features.ExecutionTargets.SelectExecutionTarget; using AutoForge.UI.Features.Vehicles.Diagnostics; using AutoForge.UI.Features.Vehicles.Profiles; +using AutoForge.UI.Features.Vehicles.Simulation; +using AutoForge.Application.Features.Vehicles.Simulation; using Microsoft.Extensions.DependencyInjection; namespace AutoForge.UI; @@ -11,9 +13,11 @@ public static class ServiceCollectionExtensions { ArgumentNullException.ThrowIfNull(services); + services.AddAutoForgeDynamicsConfigurations(); services.AddScoped(); services.AddScoped(); services.AddScoped(); + services.AddScoped(); return services; } } diff --git a/src/AutoForge.UI/Features/Foundation/Home.razor b/src/AutoForge.UI/Features/Foundation/Home.razor index 33d24d9..9022c3d 100644 --- a/src/AutoForge.UI/Features/Foundation/Home.razor +++ b/src/AutoForge.UI/Features/Foundation/Home.razor @@ -8,10 +8,11 @@ It does not connect to a real vehicle and requires no driver, backend or cloud service.

+ Message="Available: explicit target metadata, static synthetic diagnostics, and a fixed-step synthetic dynamics workflow. Dynamics are not manufacturer-validated; physical hardware operations are not implemented." />

Review execution-target selection

Open synthetic diagnostics + Open vehicle simulation

diff --git a/src/AutoForge.UI/Features/Vehicles/Simulation/SimulationPage.razor b/src/AutoForge.UI/Features/Vehicles/Simulation/SimulationPage.razor new file mode 100644 index 0000000..b9ec874 --- /dev/null +++ b/src/AutoForge.UI/Features/Vehicles/Simulation/SimulationPage.razor @@ -0,0 +1,177 @@ +@page "/simulation" +@inject SimulationPageViewModel Simulation + +Vehicle simulation - AutoForge + +

Deterministic synthetic vehicle simulation

+

+ This fixed-step synthetic model is not validated real-world prediction, vehicle + compatibility evidence, calibration advice, or a physical connection. +

+ + +
+

Explicit profile and configuration selection

+ + + + + + + + + + + @if (Simulation.SelectedConfiguration is { } selectedConfiguration) + { +

+ Model @selectedConfiguration.ModelIdentifier v@(selectedConfiguration.ModelVersion); + fingerprint @selectedConfiguration.ConfigurationIdentifier. +

+
    + @foreach (var phase in selectedConfiguration.Scenario) + { +
  1. + @phase.Kind — target @phase.TargetSpeedMetersPerSecond.ToString("F4", System.Globalization.CultureInfo.InvariantCulture) m/s; + phase limit/hold @phase.DurationSeconds.ToString("F1", System.Globalization.CultureInfo.InvariantCulture) s +
  2. + } +
+ } + + +

Configuration JSON interchange

+ + + + + + +
+ +@if (Simulation.ActiveSession is { } session && session.DynamicsControl is { } control) +{ +
+

Run lifecycle and fixed-step controls

+

+ Configuration @session.Identity.DynamicsConfigurationIdentifier; + run @session.Identity.DynamicsRunIdentifier; + session @session.Identity.SessionIdentifier. +

+ @if (Simulation.RunStatus is { } status) + { +
+
Lifecycle
+
@status.State
+
Model time
+
@status.VirtualTimeSeconds.ToString("F1", System.Globalization.CultureInfo.InvariantCulture) s; step @status.StepIndex
+
Scenario phase
+
@(status.ScenarioPhase ?? "Complete") (@((status.ScenarioPhaseProgress * 100).ToString("F1", System.Globalization.CultureInfo.InvariantCulture))%)
+
Overall scenario progress
+
@((status.ScenarioProgress * 100).ToString("F1", System.Globalization.CultureInfo.InvariantCulture))%
+ @if (status.Failure is not null) + { +
Failure
+
@status.Failure
+ } +
+ } + + + + + + + + + + + + + + + +

Current pacing: @control.PacingFactor.ToString("F2", System.Globalization.CultureInfo.InvariantCulture)x.

+
+ +
+

Diagnostic-frame telemetry

+

Every value below was read through the selected session's encoded protocol v2 diagnostic path.

+ @if (Simulation.Telemetry.Count == 0) + { +

No telemetry has been read yet.

+ } + else + { + + + + + + + + + + + + + + + @foreach (var row in Simulation.Telemetry) + { + + + + + + + + + + + } + +
Source moduleSignalValueUnitQualityOriginModel step/timeConfiguration/run
@row.ModuleIdentifier@row.SignalIdentifier@row.Value@row.Unit@row.Quality@row.Origin@row.StepIndex / @row.ModelTimeSeconds.ToString("F1", System.Globalization.CultureInfo.InvariantCulture) s@row.ConfigurationIdentifier / @row.RunIdentifier
+ } +
+} + +

The model is deliberately synthetic and does not provide manufacturer-validated performance, safe tuning guidance, or physical operations.

diff --git a/src/AutoForge.UI/Features/Vehicles/Simulation/SimulationPageViewModel.cs b/src/AutoForge.UI/Features/Vehicles/Simulation/SimulationPageViewModel.cs new file mode 100644 index 0000000..1f4136c --- /dev/null +++ b/src/AutoForge.UI/Features/Vehicles/Simulation/SimulationPageViewModel.cs @@ -0,0 +1,510 @@ +using System.Globalization; +using AutoForge.Application.ExecutionTargets; +using AutoForge.Application.Features.Vehicles.Diagnostics; +using AutoForge.Application.Features.Vehicles.Profiles; +using AutoForge.Application.Features.Vehicles.Simulation; +using AutoForge.Components; +using AutoForge.Core.ExecutionTargets; +using AutoForge.Core.Simulation; +using AutoForge.Core.Vehicles; +using AutoForge.Diagnostics; + +namespace AutoForge.UI.Features.Vehicles.Simulation; + +public sealed record DynamicsTelemetryRow( + string ModuleIdentifier, + string SignalIdentifier, + string Value, + string Unit, + SignalQuality Quality, + string Origin, + long StepIndex, + double ModelTimeSeconds, + string ConfigurationIdentifier, + string RunIdentifier); + +public sealed class SimulationPageViewModel( + IVehicleProfileService profiles, + IDynamicsConfigurationService configurations, + IDiagnosticSessionService sessions) +{ + private readonly object _scenarioGate = new(); + private CancellationTokenSource? _scenarioCancellation; + private long _sessionGeneration; + + public IReadOnlyList AvailableProfiles { get; private set; } = profiles.List(); + public IReadOnlyList AvailableConfigurations => configurations.List(); + public DynamicsConfiguration? SelectedConfiguration => + SelectedConfigurationIdentifier is { } identifier && + AvailableConfigurations.Any(item => StringComparer.Ordinal.Equals(item.ConfigurationIdentifier, identifier)) + ? configurations.Select(identifier) + : null; + public IReadOnlyList DynamicsProviders => sessions.Providers + .Where(provider => StringComparer.OrdinalIgnoreCase.Equals( + provider.Target.ProviderIdentifier, + "autoforge.simulation.dynamics")) + .ToArray(); + public string? SelectedProfileIdentifier { get; set; } + public int? SelectedProfileRevision { get; set; } + public string? SelectedProviderIdentifier { get; set; } + public string? SelectedConfigurationIdentifier { get; set; } + public string ConfigurationJson { get; set; } = string.Empty; + public string ExportedConfigurationJson { get; private set; } = string.Empty; + public string? ErrorMessage { get; private set; } + public string StatusMessage { get; private set; } = "Load/select an exact profile and configuration. No session is open."; + public StatusNoticeTone StatusTone { get; private set; } = StatusNoticeTone.Information; + public DiagnosticSession? ActiveSession { get; private set; } + public DynamicsRunStatus? RunStatus => ActiveSession?.DynamicsControl?.Status; + public IReadOnlyList VerifiedEndpoints { get; private set; } = []; + public IReadOnlyList Telemetry { get; private set; } = []; + public double PacingFactorInput { get; set; } = 1; + public int StepCountInput { get; set; } = 1; + + public void LoadSyntheticProfile() + { + try + { + var profile = profiles.Import(ReadSyntheticProfile()); + AvailableProfiles = profiles.List(); + SetSuccess($"Loaded synthetic profile '{profile.ProfileIdentifier}' revision {profile.Revision}. Select it explicitly; no session was opened."); + } + catch (VehicleProfileInterchangeException exception) + { + SetError(exception.Message); + } + catch (VehicleProfileCatalogException exception) + { + SetError(exception.Message); + } + } + + public void CreateWarmExample() + { + try + { + if (SelectedProfileIdentifier is null || SelectedProfileRevision is null) + { + throw new InvalidOperationException("Select an exact saved profile revision before creating the example configuration."); + } + + var configuration = configurations.CreateExample(SelectedProfileIdentifier, SelectedProfileRevision.Value); + SelectedConfigurationIdentifier = configuration.ConfigurationIdentifier; + SetSuccess($"Created and selected configuration {configuration.ConfigurationIdentifier}. A session was not opened or started."); + } + catch (Exception exception) when (exception is InvalidOperationException or VehicleProfileCatalogException or ArgumentException) + { + SetError(exception.Message); + } + } + + public void ImportConfiguration() + { + try + { + var configuration = configurations.Import(ConfigurationJson); + SelectedConfigurationIdentifier = configuration.ConfigurationIdentifier; + SetSuccess($"Imported configuration {configuration.ConfigurationIdentifier}; its profile/revision binding was validated."); + } + catch (DynamicsConfigurationException exception) + { + SetError(exception.Message); + } + } + + public void ExportConfiguration() + { + try + { + if (SelectedConfigurationIdentifier is null) + { + throw new DynamicsConfigurationException("Select a configuration before exporting."); + } + + ExportedConfigurationJson = configurations.Export(SelectedConfigurationIdentifier); + SetSuccess($"Exported exact configuration {SelectedConfigurationIdentifier}."); + } + catch (DynamicsConfigurationException exception) + { + SetError(exception.Message); + } + } + + public async Task OpenSessionAsync() + { + if (ActiveSession is not null) + { + SetError("Close the current run before opening another dynamics session."); + return; + } + + if (SelectedProfileIdentifier is null || + SelectedProfileRevision is null || + SelectedProviderIdentifier is null || + SelectedConfigurationIdentifier is null) + { + SetError("Select an exact saved profile revision, dynamics provider and configuration before opening."); + return; + } + + var generation = Interlocked.Increment(ref _sessionGeneration); + try + { + var configuration = configurations.Select(SelectedConfigurationIdentifier); + if (!StringComparer.OrdinalIgnoreCase.Equals(configuration.ProfileIdentifier, SelectedProfileIdentifier) || + configuration.ProfileRevision != SelectedProfileRevision.Value) + { + throw new DynamicsConfigurationException("The selected configuration does not bind to the selected exact profile revision."); + } + + var session = await sessions.OpenDynamicsAsync( + SelectedProfileIdentifier, + SelectedProfileRevision.Value, + SelectedProviderIdentifier, + ExecutionTargetKind.Simulation, + configuration); + if (generation != Volatile.Read(ref _sessionGeneration) || ActiveSession is not null) + { + await session.DisposeAsync(); + return; + } + + ActiveSession = session; + var discovery = await session.DiscoverAsync(); + if (!IsCurrent(session, generation)) + { + return; + } + + VerifiedEndpoints = discovery.Endpoints + .Where(entry => entry.ProbeSucceeded && entry.Identity is not null) + .Select(entry => entry.Endpoint) + .ToArray(); + Telemetry = []; + SetSuccess( + $"Opened dynamics session {session.Identity.SessionIdentifier} with configuration {configuration.ConfigurationIdentifier}. The run remains stopped until explicitly started."); + } + catch (Exception exception) when (exception is DiagnosticSessionException or DiagnosticProviderException or DynamicsConfigurationException or TargetSelectionException or VehicleProfileCatalogException or ArgumentException or InvalidOperationException) + { + if (generation == Volatile.Read(ref _sessionGeneration)) + { + SetError(exception.Message); + } + } + } + + public Task StartAsync() => ApplyControlAsync(control => control.StartAsync(), "Started"); + public Task PauseAsync() => ApplyControlAsync(control => control.PauseAsync(), "Paused"); + public Task ResumeAsync() => ApplyControlAsync(control => control.ResumeAsync(), "Resumed"); + public Task StopAsync() => ApplyControlAsync(control => control.StopAsync(), "Stopped"); + public Task ResetAsync() => ResetSessionAsync(); + public Task StepAsync() => ApplyControlAsync( + control => control.StepAsync(StepCountInput), + $"Advanced {StepCountInput} configured step(s)"); + public Task SetPacingAsync() => ApplyControlAsync( + control => control.SetPacingFactorAsync(PacingFactorInput), + $"Set pacing to {PacingFactorInput.ToString(CultureInfo.InvariantCulture)}x"); + + public async Task RunScenarioAsync() + { + var session = ActiveSession; + if (session is null || session.DynamicsControl is not { } control) + { + SetError("Open an explicit dynamics session before running its scenario."); + return; + } + + var generation = Volatile.Read(ref _sessionGeneration); + CancellationTokenSource cancellation; + lock (_scenarioGate) + { + if (_scenarioCancellation is not null) + { + SetError("A scenario runner already owns this session; cancel or wait for it before starting another."); + return; + } + + cancellation = new CancellationTokenSource(); + _scenarioCancellation = cancellation; + } + + try + { + var status = await control.RunScenarioAsync(cancellation.Token); + if (!IsCurrent(session, generation)) + { + return; + } + + switch (status.State) + { + case DynamicsLifecycleState.Completed: + SetSuccess($"Scenario completed at {status.VirtualTimeSeconds:F1} virtual seconds."); + break; + case DynamicsLifecycleState.Faulted: + Telemetry = []; + SetError(status.Failure ?? "Scenario failed without a failure reason."); + return; + case DynamicsLifecycleState.Paused: + SetInformation($"Scenario paused at {status.VirtualTimeSeconds:F1} virtual seconds; it has not completed."); + break; + case DynamicsLifecycleState.Stopped: + SetInformation($"Scenario stopped at {status.VirtualTimeSeconds:F1} virtual seconds; it has not completed."); + break; + default: + SetError($"Scenario ended in unexpected state {status.State}."); + return; + } + + await RefreshTelemetryAsync(session, generation, preserveStatus: true); + } + catch (OperationCanceledException) + { + if (IsCurrent(session, generation)) + { + SetInformation("Scenario runner was cancelled; it is not complete and retains its exact virtual state."); + } + } + catch (InvalidOperationException exception) + { + if (IsCurrent(session, generation)) + { + SetError(exception.Message); + } + } + finally + { + lock (_scenarioGate) + { + if (ReferenceEquals(_scenarioCancellation, cancellation)) + { + _scenarioCancellation = null; + } + } + + cancellation.Dispose(); + } + } + + public void CancelScenario() + { + lock (_scenarioGate) + { + _scenarioCancellation?.Cancel(); + } + } + + public Task RefreshTelemetryAsync() + { + var session = ActiveSession; + return session is null + ? ReportMissingSessionAsync() + : RefreshTelemetryAsync(session, Volatile.Read(ref _sessionGeneration), preserveStatus: false); + } + + private async Task RefreshTelemetryAsync( + DiagnosticSession session, + long generation, + bool preserveStatus) + { + var rows = new List(); + foreach (var endpoint in VerifiedEndpoints) + { + var response = await session.ReadSignalsAsync(endpoint); + if (!IsCurrent(session, generation)) + { + return; + } + + if (!response.IsSuccess) + { + if (session.DynamicsControl?.Status is { State: DynamicsLifecycleState.Faulted, Failure: { } failure }) + { + SetError(failure); + return; + } + + SetError($"{endpoint.ModuleIdentifier} signal read failed ({response.Outcome}): {response.Error}"); + return; + } + + var snapshot = response.Value!; + if (snapshot.ModelStepIndex is not { } step || + snapshot.ModelTimeSeconds is not { } modelTime || + snapshot.ModelConfigurationIdentifier is not { } configurationIdentifier || + snapshot.ModelRunIdentifier is not { } runIdentifier) + { + SetError("The dynamics diagnostic response omitted model step/time/configuration/run identity."); + return; + } + + rows.AddRange(snapshot.Signals.Select(signal => new DynamicsTelemetryRow( + signal.ModuleIdentifier, + signal.SignalIdentifier, + signal.Value.ToString(), + signal.Unit, + signal.Quality, + signal.Origin, + step, + modelTime, + configurationIdentifier, + runIdentifier))); + } + + if (!IsCurrent(session, generation)) + { + return; + } + + Telemetry = rows; + if (!preserveStatus) + { + SetSuccess($"Read {rows.Count} telemetry signal(s) through protocol v2 diagnostic frames; the read did not advance model time."); + } + } + + public async Task ResetSessionAsync() + { + if (ActiveSession is not { } session) + { + SetError("There is no dynamics session to reset."); + return; + } + + var generation = Interlocked.Increment(ref _sessionGeneration); + CancelScenario(); + try + { + ActiveSession = null; + VerifiedEndpoints = []; + Telemetry = []; + var reset = await sessions.ResetAsync(session); + if (generation != Volatile.Read(ref _sessionGeneration)) + { + await reset.DisposeAsync(); + return; + } + + ActiveSession = reset; + var discovery = await reset.DiscoverAsync(); + if (!IsCurrent(reset, generation)) + { + return; + } + + VerifiedEndpoints = discovery.Endpoints + .Where(entry => entry.ProbeSucceeded && entry.Identity is not null) + .Select(entry => entry.Endpoint) + .ToArray(); + SetSuccess($"Reset the exact original configuration in new session {reset.Identity.SessionIdentifier}; no later catalog selection was substituted."); + } + catch (Exception exception) when (exception is DiagnosticSessionException or DiagnosticProviderException or InvalidOperationException) + { + if (generation == Volatile.Read(ref _sessionGeneration)) + { + SetError(exception.Message); + } + } + } + + public async Task CloseSessionAsync() + { + var generation = Interlocked.Increment(ref _sessionGeneration); + CancelScenario(); + var session = ActiveSession; + if (session is null) + { + SetError("No dynamics session is open."); + return; + } + + ActiveSession = null; + VerifiedEndpoints = []; + Telemetry = []; + await session.DisposeAsync(); + if (generation == Volatile.Read(ref _sessionGeneration) && ActiveSession is null) + { + SetInformation($"Closed dynamics session {session.Identity.SessionIdentifier}; its engine and pending work were released."); + } + } + + private async Task ApplyControlAsync( + Func> operation, + string description) + { + var session = ActiveSession; + if (session is null || session.DynamicsControl is not { } control) + { + SetError("Open an explicit dynamics session before changing run state."); + return; + } + + var generation = Volatile.Read(ref _sessionGeneration); + try + { + var status = await operation(control); + if (!IsCurrent(session, generation)) + { + return; + } + + if (status.State == DynamicsLifecycleState.Faulted) + { + SetError(status.Failure ?? "Dynamics run failed without a failure reason."); + return; + } + + SetSuccess($"{description}: {status.State}, step {status.StepIndex}, model time {status.VirtualTimeSeconds:F1} s."); + await RefreshTelemetryAsync(session, generation, preserveStatus: true); + } + catch (Exception exception) when (exception is InvalidOperationException or ArgumentOutOfRangeException or ObjectDisposedException) + { + if (IsCurrent(session, generation)) + { + SetError(exception.Message); + } + } + } + + private void SetSuccess(string message) + { + ErrorMessage = null; + StatusTone = StatusNoticeTone.Success; + StatusMessage = message; + } + + private void SetError(string message) + { + ErrorMessage = message; + StatusTone = StatusNoticeTone.Error; + StatusMessage = message; + } + + private void SetInformation(string message) + { + ErrorMessage = null; + StatusTone = StatusNoticeTone.Information; + StatusMessage = message; + } + + private bool IsCurrent(DiagnosticSession session, long generation) => + generation == Volatile.Read(ref _sessionGeneration) && + ReferenceEquals(ActiveSession, session) && + StringComparer.Ordinal.Equals( + ActiveSession?.Identity.DynamicsRunIdentifier, + session.Identity.DynamicsRunIdentifier); + + private Task ReportMissingSessionAsync() + { + SetError("Open a dynamics session before reading telemetry."); + return Task.CompletedTask; + } + + private static string ReadSyntheticProfile() + { + using var stream = typeof(SimulationPageViewModel).Assembly.GetManifestResourceStream( + "AutoForge.UI.SyntheticExamples.synthetic-truck-baseline.json") + ?? throw new InvalidOperationException("The source-controlled synthetic profile example is unavailable."); + using var reader = new StreamReader(stream); + return reader.ReadToEnd(); + } +} diff --git a/src/AutoForge.UI/Layout/MainLayout.razor b/src/AutoForge.UI/Layout/MainLayout.razor index 43d2346..5fc2f52 100644 --- a/src/AutoForge.UI/Layout/MainLayout.razor +++ b/src/AutoForge.UI/Layout/MainLayout.razor @@ -8,6 +8,7 @@ Target selection Vehicle profiles Synthetic diagnostics + Vehicle simulation diff --git a/src/AutoForge.UI/_Imports.razor b/src/AutoForge.UI/_Imports.razor index 9b3f679..acda386 100644 --- a/src/AutoForge.UI/_Imports.razor +++ b/src/AutoForge.UI/_Imports.razor @@ -8,3 +8,4 @@ @using AutoForge.UI.Features.ExecutionTargets.SelectExecutionTarget @using AutoForge.UI.Features.Vehicles.Diagnostics @using AutoForge.UI.Features.Vehicles.Profiles +@using AutoForge.UI.Features.Vehicles.Simulation diff --git a/src/tests/AutoForge.IntegrationTests/DynamicsWorkflowTests.cs b/src/tests/AutoForge.IntegrationTests/DynamicsWorkflowTests.cs new file mode 100644 index 0000000..0fb2f11 --- /dev/null +++ b/src/tests/AutoForge.IntegrationTests/DynamicsWorkflowTests.cs @@ -0,0 +1,620 @@ +using System.Text.Json.Nodes; +using System.Threading.Channels; +using AutoForge.Application.ExecutionTargets; +using AutoForge.Components; +using AutoForge.Application.Features.Vehicles.Diagnostics; +using AutoForge.Application.Features.Vehicles.Profiles; +using AutoForge.Application.Features.Vehicles.Simulation; +using AutoForge.Core.ExecutionTargets; +using AutoForge.Core.Simulation; +using AutoForge.Diagnostics; +using AutoForge.Simulation; +using AutoForge.UI; +using AutoForge.UI.Features.Vehicles.Simulation; +using Microsoft.AspNetCore.Components; +using Microsoft.AspNetCore.Components.Routing; +using Microsoft.AspNetCore.Components.Web; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; + +namespace AutoForge.IntegrationTests; + +public sealed class DynamicsWorkflowTests +{ + [Fact] + public async Task RealApplicationAndRenderedRoute_RunAndReadDynamicTelemetryWithoutOracle() + { + using var provider = CreateProvider(); + var profiles = provider.GetRequiredService(); + profiles.Import(ReadFixture("synthetic-truck-baseline.json")); + var configurations = provider.GetRequiredService(); + var original = configurations.CreateExample("autoforge.synthetic.test-truck", 1); + var page = provider.GetRequiredService(); + Assert.Null(page.ActiveSession); + page.SelectedProfileIdentifier = original.ProfileIdentifier; + page.SelectedProfileRevision = original.ProfileRevision; + page.SelectedProviderIdentifier = DynamicsDiagnosticTransportFactory.ProviderIdentifier; + page.SelectedConfigurationIdentifier = original.ConfigurationIdentifier; + + await page.OpenSessionAsync(); + var session = Assert.IsType(page.ActiveSession); + Assert.Equal(DynamicsLifecycleState.Stopped, session.DynamicsControl!.Status.State); + Assert.Equal(2, page.VerifiedEndpoints.Count); + + await page.StartAsync(); + await page.PauseAsync(); + page.StepCountInput = 4; + await page.StepAsync(); + await page.RefreshTelemetryAsync(); + + Assert.Equal(5, session.DynamicsControl.Status.StepIndex); + Assert.NotEmpty(page.Telemetry); + Assert.All(page.Telemetry, row => + { + Assert.Equal(5, row.StepIndex); + Assert.Equal("SYNTHETIC_DYNAMIC", row.Origin); + Assert.Equal(original.ConfigurationIdentifier, row.ConfigurationIdentifier); + Assert.Equal(session.Identity.DynamicsRunIdentifier, row.RunIdentifier); + }); + Assert.Single(page.Telemetry.Select(row => (row.StepIndex, row.ModelTimeSeconds)).Distinct()); + + page.PacingFactorInput = 1_000; + await page.SetPacingAsync(); + await page.RunScenarioAsync(); + Assert.Equal(DynamicsLifecycleState.Completed, session.DynamicsControl.Status.State); + Assert.Equal(1, session.DynamicsControl.Status.ScenarioProgress); + + var changed = JsonNode.Parse(configurations.Export(original.ConfigurationIdentifier))!.AsObject(); + changed["model"]!["vehicleMassKilograms"] = 1_900; + var newer = configurations.Import(changed.ToJsonString()); + page.SelectedConfigurationIdentifier = newer.ConfigurationIdentifier; + await page.ResetAsync(); + + var reset = Assert.IsType(page.ActiveSession); + Assert.Equal(original.ConfigurationIdentifier, reset.DynamicsConfiguration!.ConfigurationIdentifier); + Assert.NotEqual(session.Identity.SessionIdentifier, reset.Identity.SessionIdentifier); + Assert.Equal(0, reset.DynamicsControl!.Status.StepIndex); + await page.RefreshTelemetryAsync(); + + var html = await RenderRoutesAsync(provider); + Assert.Contains("Deterministic synthetic vehicle simulation", html); + Assert.Contains("dynamics-telemetry", html); + Assert.Contains("SYNTHETIC_DYNAMIC", html); + Assert.Contains("dynamics-run-status", html); + Assert.Contains("WarmIdle (0.0%)", html); + Assert.Contains("Model autoforge.synthetic.longitudinal v1;", html); + + await page.CloseSessionAsync(); + Assert.Null(page.ActiveSession); + Assert.True(reset.IsClosed); + } + + [Fact] + public async Task StaticProviderCannotOpenDynamicsControls() + { + using var provider = CreateProvider(); + provider.GetRequiredService().Import(ReadFixture("synthetic-truck-baseline.json")); + var configurations = provider.GetRequiredService(); + var configuration = configurations.CreateExample("autoforge.synthetic.test-truck", 1); + var sessions = provider.GetRequiredService(); + + await Assert.ThrowsAsync(() => sessions.OpenDynamicsAsync( + configuration.ProfileIdentifier, + configuration.ProfileRevision, + SimulatedDiagnosticTransportFactory.ProviderIdentifier, + ExecutionTargetKind.Simulation, + configuration)); + } + + [Fact] + public async Task DifferentDynamicsConfigurationsRemainIsolatedAcrossSessionsAndReset() + { + using var provider = CreateProvider(); + provider.GetRequiredService().Import(ReadFixture("synthetic-truck-baseline.json")); + var configurations = provider.GetRequiredService(); + var firstConfiguration = configurations.CreateExample("autoforge.synthetic.test-truck", 1); + var changed = JsonNode.Parse(configurations.Export(firstConfiguration.ConfigurationIdentifier))!.AsObject(); + changed["model"]!["vehicleMassKilograms"] = 2_100; + var secondConfiguration = configurations.Import(changed.ToJsonString()); + var sessions = provider.GetRequiredService(); + + await using var first = await sessions.OpenDynamicsAsync( + firstConfiguration.ProfileIdentifier, + firstConfiguration.ProfileRevision, + DynamicsDiagnosticTransportFactory.ProviderIdentifier, + ExecutionTargetKind.Simulation, + firstConfiguration); + await using var second = await sessions.OpenDynamicsAsync( + secondConfiguration.ProfileIdentifier, + secondConfiguration.ProfileRevision, + DynamicsDiagnosticTransportFactory.ProviderIdentifier, + ExecutionTargetKind.Simulation, + secondConfiguration); + await first.DynamicsControl!.StepAsync(2); + + Assert.Equal(2, first.DynamicsControl.Status.StepIndex); + Assert.Equal(0, second.DynamicsControl!.Status.StepIndex); + Assert.NotEqual(first.Identity.DynamicsRunIdentifier, second.Identity.DynamicsRunIdentifier); + + await using var reset = await sessions.ResetAsync(first); + Assert.Equal(firstConfiguration.ConfigurationIdentifier, reset.DynamicsConfiguration!.ConfigurationIdentifier); + Assert.NotEqual(first.Identity.SessionIdentifier, reset.Identity.SessionIdentifier); + Assert.Equal(0, reset.DynamicsControl!.Status.StepIndex); + Assert.Equal(0, second.DynamicsControl.Status.StepIndex); + + } + + [Fact] + public async Task InvalidReferenceImportIsVisibleAtomicAndLeavesActiveBindingUnchanged() + { + using var provider = CreateProvider(); + provider.GetRequiredService().Import(ReadFixture("synthetic-truck-baseline.json")); + var configurations = provider.GetRequiredService(); + var original = configurations.CreateExample("autoforge.synthetic.test-truck", 1); + var page = provider.GetRequiredService(); + page.SelectedProfileIdentifier = original.ProfileIdentifier; + page.SelectedProfileRevision = original.ProfileRevision; + page.SelectedProviderIdentifier = DynamicsDiagnosticTransportFactory.ProviderIdentifier; + page.SelectedConfigurationIdentifier = original.ConfigurationIdentifier; + await page.OpenSessionAsync(); + var active = Assert.IsType(page.ActiveSession); + var invalid = JsonNode.Parse(configurations.Export(original.ConfigurationIdentifier))!.AsObject(); + invalid["profileIdentifier"] = "autoforge.synthetic.missing"; + page.ConfigurationJson = invalid.ToJsonString(); + + page.ImportConfiguration(); + + Assert.Equal(original.ConfigurationIdentifier, page.SelectedConfigurationIdentifier); + Assert.Same(active, page.ActiveSession); + Assert.Equal(original.ConfigurationIdentifier, active.Identity.DynamicsConfigurationIdentifier); + Assert.Contains("profile reference", page.ErrorMessage, StringComparison.OrdinalIgnoreCase); + Assert.Single(configurations.List()); + var html = await RenderRoutesAsync(provider); + Assert.Contains("profile reference", html, StringComparison.OrdinalIgnoreCase); + Assert.Contains("status-notice--error", html); + + var invalidRevision = JsonNode.Parse(configurations.Export(original.ConfigurationIdentifier))!.AsObject(); + invalidRevision["profileRevision"] = 99; + page.ConfigurationJson = invalidRevision.ToJsonString(); + page.ImportConfiguration(); + Assert.Contains("profile reference", page.ErrorMessage, StringComparison.OrdinalIgnoreCase); + Assert.Same(active, page.ActiveSession); + Assert.Single(configurations.List()); + + var invalidModule = JsonNode.Parse(configurations.Export(original.ConfigurationIdentifier))!.AsObject(); + invalidModule["engineModuleIdentifier"] = "module.engine.missing"; + page.ConfigurationJson = invalidModule.ToJsonString(); + page.ImportConfiguration(); + Assert.Contains("module", page.ErrorMessage, StringComparison.OrdinalIgnoreCase); + Assert.Same(active, page.ActiveSession); + Assert.Equal(original.ConfigurationIdentifier, page.SelectedConfigurationIdentifier); + Assert.Equal(original.ConfigurationIdentifier, active.Identity.DynamicsConfigurationIdentifier); + Assert.Single(configurations.List()); + + await page.CloseSessionAsync(); + } + + [Fact] + public async Task DeadlineFailureRemainsVisibleAndDynamicDiagnosticsReturnNegativeOutcome() + { + using var provider = CreateProvider(new ImmediateDynamicsPacer()); + provider.GetRequiredService().Import(ReadFixture("synthetic-truck-baseline.json")); + var configurations = provider.GetRequiredService(); + var baseline = configurations.CreateExample("autoforge.synthetic.test-truck", 1); + var invalidDeadline = JsonNode.Parse(configurations.Export(baseline.ConfigurationIdentifier))!.AsObject(); + invalidDeadline["scenario"]![1]!["durationSeconds"] = 0.1; + var configuration = configurations.Import(invalidDeadline.ToJsonString()); + var page = provider.GetRequiredService(); + page.SelectedProfileIdentifier = configuration.ProfileIdentifier; + page.SelectedProfileRevision = configuration.ProfileRevision; + page.SelectedProviderIdentifier = DynamicsDiagnosticTransportFactory.ProviderIdentifier; + page.SelectedConfigurationIdentifier = configuration.ConfigurationIdentifier; + await page.OpenSessionAsync(); + var session = Assert.IsType(page.ActiveSession); + await page.SetPacingAsync(); + Assert.NotEmpty(page.Telemetry); + + await page.RunScenarioAsync(); + + Assert.Equal(DynamicsLifecycleState.Faulted, session.DynamicsControl!.Status.State); + Assert.Contains("did not meet its target", page.ErrorMessage); + Assert.Equal(StatusNoticeTone.Error, page.StatusTone); + Assert.Empty(page.Telemetry); + var engineEndpoint = Assert.Single(page.VerifiedEndpoints, + endpoint => endpoint.ModuleIdentifier == configuration.EngineModuleIdentifier); + var response = await session.ReadSignalsAsync(engineEndpoint); + Assert.Equal(DiagnosticOutcome.NegativeResponse, response.Outcome); + Assert.Equal("DYNAMICS_RUN_FAULTED", response.FailureCode); + Assert.Contains("did not meet its target", response.Error); + + var html = await RenderRoutesAsync(provider); + Assert.Contains("status-notice--error", html); + Assert.Contains("did not meet its target", html); + Assert.DoesNotContain("status-notice--success", html); + await page.CloseSessionAsync(); + } + + [Fact] + public async Task NonFiniteModelFailureRollsBackAndCannotEmitPositiveDynamicSignals() + { + using var provider = CreateProvider(new ImmediateDynamicsPacer()); + provider.GetRequiredService().Import(ReadFixture("synthetic-truck-baseline.json")); + var configurations = provider.GetRequiredService(); + var baseline = configurations.CreateExample("autoforge.synthetic.test-truck", 1); + var nonFiniteModel = JsonNode.Parse(configurations.Export(baseline.ConfigurationIdentifier))!.AsObject(); + nonFiniteModel["scenario"]![0]!["durationSeconds"] = 0.1; + nonFiniteModel["model"]!["forwardGearRatios"] = new JsonArray(1e-304, 9e-305, 8e-305, 7e-305); + nonFiniteModel["model"]!["finalDriveRatio"] = 0.1; + foreach (var point in nonFiniteModel["model"]!["engineTorqueCurve"]!.AsArray()) + { + point!["torqueNewtonMeters"] = 1e308; + } + + var configuration = configurations.Import(nonFiniteModel.ToJsonString()); + var page = provider.GetRequiredService(); + page.SelectedProfileIdentifier = configuration.ProfileIdentifier; + page.SelectedProfileRevision = configuration.ProfileRevision; + page.SelectedProviderIdentifier = DynamicsDiagnosticTransportFactory.ProviderIdentifier; + page.SelectedConfigurationIdentifier = configuration.ConfigurationIdentifier; + await page.OpenSessionAsync(); + var session = Assert.IsType(page.ActiveSession); + await page.SetPacingAsync(); + Assert.NotEmpty(page.Telemetry); + + await page.RunScenarioAsync(); + + Assert.Equal(DynamicsLifecycleState.Faulted, session.DynamicsControl!.Status.State); + Assert.Equal(1, session.DynamicsControl.Status.StepIndex); + Assert.Contains("finite supported domain", page.ErrorMessage); + Assert.Empty(page.Telemetry); + var engineEndpoint = Assert.Single(page.VerifiedEndpoints, + endpoint => endpoint.ModuleIdentifier == configuration.EngineModuleIdentifier); + var response = await session.ReadSignalsAsync(engineEndpoint); + Assert.Equal(DiagnosticOutcome.NegativeResponse, response.Outcome); + Assert.Equal("DYNAMICS_RUN_FAULTED", response.FailureCode); + Assert.Contains("finite supported domain", response.Error); + + var html = await RenderRoutesAsync(provider); + Assert.Contains("status-notice--error", html); + Assert.Contains("finite supported domain", html); + await page.CloseSessionAsync(); + } + + [Fact] + public async Task ScenarioOwnerCannotBeReplacedAndResetOrCloseSuppressesOldRunPublication() + { + var pacer = new BlockingDynamicsPacer(); + using var provider = CreateProvider(pacer); + provider.GetRequiredService().Import(ReadFixture("synthetic-truck-baseline.json")); + var configurations = provider.GetRequiredService(); + var configuration = configurations.CreateExample("autoforge.synthetic.test-truck", 1); + var page = provider.GetRequiredService(); + page.SelectedProfileIdentifier = configuration.ProfileIdentifier; + page.SelectedProfileRevision = configuration.ProfileRevision; + page.SelectedProviderIdentifier = DynamicsDiagnosticTransportFactory.ProviderIdentifier; + page.SelectedConfigurationIdentifier = configuration.ConfigurationIdentifier; + await page.OpenSessionAsync(); + var initial = Assert.IsType(page.ActiveSession); + + var firstRun = page.RunScenarioAsync(); + var pendingDelay = await pacer.NextDelayAsync(); + Assert.Equal(1, initial.DynamicsControl!.Status.StepIndex); + var replacedRun = page.RunScenarioAsync(); + Assert.Contains("already owns", page.ErrorMessage); + page.CancelScenario(); + await firstRun; + Assert.Equal(DynamicsLifecycleState.Paused, initial.DynamicsControl.Status.State); + Assert.Contains("cancelled", page.StatusMessage, StringComparison.OrdinalIgnoreCase); + Assert.True(pendingDelay.IsCancelled); + await replacedRun; + + var resetRun = page.RunScenarioAsync(); + _ = await pacer.NextDelayAsync(); + await page.ResetAsync(); + await resetRun; + var reset = Assert.IsType(page.ActiveSession); + Assert.NotSame(initial, reset); + Assert.Equal(0, reset.DynamicsControl!.Status.StepIndex); + Assert.Contains("Reset the exact original configuration", page.StatusMessage); + + var closeRun = page.RunScenarioAsync(); + _ = await pacer.NextDelayAsync(); + await page.CloseSessionAsync(); + await closeRun; + Assert.Null(page.ActiveSession); + Assert.Contains("Closed dynamics session", page.StatusMessage); + } + + [Fact] + public async Task ResumeRejectedDuringOwnerDrainIsVisibleThroughRealSimulationPage() + { + var pacer = new CancellationDrainDynamicsPacer(); + using var provider = CreateProvider(pacer); + provider.GetRequiredService().Import(ReadFixture("synthetic-truck-baseline.json")); + var configuration = provider.GetRequiredService() + .CreateExample("autoforge.synthetic.test-truck", 1); + var page = provider.GetRequiredService(); + page.SelectedProfileIdentifier = configuration.ProfileIdentifier; + page.SelectedProfileRevision = configuration.ProfileRevision; + page.SelectedProviderIdentifier = DynamicsDiagnosticTransportFactory.ProviderIdentifier; + page.SelectedConfigurationIdentifier = configuration.ConfigurationIdentifier; + Task? pause = null; + + try + { + await page.OpenSessionAsync(); + var session = Assert.IsType(page.ActiveSession); + await page.StartAsync(); + var oldDelay = await pacer.NextDelayAsync(); + + pause = page.PauseAsync(); + await oldDelay.CancellationObserved.Task; + await oldDelay.CleanupBlocked.Task; + Assert.False(pause.IsCompleted); + + var pausedStatus = session.DynamicsControl!.Status; + await page.RunScenarioAsync(); + Assert.Equal(pausedStatus, session.DynamicsControl.Status); + Assert.Contains("owner", page.ErrorMessage, StringComparison.OrdinalIgnoreCase); + Assert.Equal(StatusNoticeTone.Error, page.StatusTone); + Assert.False(pause.IsCompleted); + + await page.ResumeAsync(); + + Assert.Equal(pausedStatus, session.DynamicsControl.Status); + Assert.Contains("owner", page.ErrorMessage, StringComparison.OrdinalIgnoreCase); + Assert.Equal(StatusNoticeTone.Error, page.StatusTone); + Assert.DoesNotContain("Resumed", page.StatusMessage, StringComparison.OrdinalIgnoreCase); + Assert.False(pause.IsCompleted); + + oldDelay.ReleaseCleanup(); + await pause; + pause = null; + Assert.Equal(DynamicsLifecycleState.Paused, session.DynamicsControl.Status.State); + } + finally + { + pacer.ReleaseAllCleanup(); + if (pause is not null) + { + await pause; + } + + if (page.ActiveSession is not null) + { + await page.CloseSessionAsync(); + } + } + } + + [Fact] + public async Task CloseDuringPendingOpenInvalidatesAndDisposesTheStaleSession() + { + var openGate = new BlockingDynamicsOpen(); + using var provider = CreateProvider(openGate: openGate); + provider.GetRequiredService().Import(ReadFixture("synthetic-truck-baseline.json")); + var configuration = provider.GetRequiredService() + .CreateExample("autoforge.synthetic.test-truck", 1); + var page = provider.GetRequiredService(); + page.SelectedProfileIdentifier = configuration.ProfileIdentifier; + page.SelectedProfileRevision = configuration.ProfileRevision; + page.SelectedProviderIdentifier = DynamicsDiagnosticTransportFactory.ProviderIdentifier; + page.SelectedConfigurationIdentifier = configuration.ConfigurationIdentifier; + + var opening = page.OpenSessionAsync(); + await openGate.Entered.Task; + await page.CloseSessionAsync(); + Assert.Contains("No dynamics session is open", page.StatusMessage); + openGate.Release.TrySetResult(); + await opening; + + Assert.Null(page.ActiveSession); + Assert.True(openGate.OpenedSession!.IsClosed); + Assert.Contains("No dynamics session is open", page.StatusMessage); + } + + private static ServiceProvider CreateProvider( + IDynamicsPacer? pacer = null, + BlockingDynamicsOpen? openGate = null) + { + var services = new ServiceCollection(); + services.AddLogging(); + services.AddAutoForgeVehicleProfiles(); + var definitions = SyntheticDiagnosticExamples.CreateDefinitions(); + services.AddAutoForgeDiagnostics( + [ + new SimulatedDiagnosticTransportFactory(definitions), + new DynamicsDiagnosticTransportFactory(definitions, pacer) + ]); + if (openGate is not null) + { + services.AddSingleton(serviceProvider => + new BlockingOpenSessionService( + new DiagnosticSessionService( + serviceProvider.GetRequiredService(), + serviceProvider.GetRequiredService(), + serviceProvider.GetServices(), + () => new DiagnosticLogicalClock()), + openGate)); + services.AddSingleton(serviceProvider => + serviceProvider.GetRequiredService()); + } + + services.AddAutoForgeDynamicsConfigurations(); + services.AddAutoForgeUi(); + services.AddSingleton(new TestNavigationManager("http://localhost/simulation")); + services.AddSingleton(); + services.AddSingleton(); + return services.BuildServiceProvider(new ServiceProviderOptions { ValidateOnBuild = true }); + } + + private sealed record PendingDelay(TimeSpan Delay, TaskCompletionSource Completion) + { + public bool IsCancelled => Completion.Task.IsCanceled; + } + + private sealed class BlockingDynamicsPacer : IDynamicsPacer + { + private readonly Channel _requests = Channel.CreateUnbounded(); + + public async Task DelayAsync(TimeSpan delay, CancellationToken cancellationToken) + { + var completion = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + using var registration = cancellationToken.Register( + () => completion.TrySetCanceled(cancellationToken)); + await _requests.Writer.WriteAsync(new PendingDelay(delay, completion), cancellationToken); + await completion.Task; + } + + public ValueTask NextDelayAsync() => _requests.Reader.ReadAsync(); + } + + private sealed record DrainDelay(TimeSpan Delay) + { + private readonly TaskCompletionSource _releaseCleanup = + new(TaskCreationOptions.RunContinuationsAsynchronously); + + public TaskCompletionSource CancellationObserved { get; } = + new(TaskCreationOptions.RunContinuationsAsynchronously); + public TaskCompletionSource CleanupBlocked { get; } = + new(TaskCreationOptions.RunContinuationsAsynchronously); + public void ReleaseCleanup() => _releaseCleanup.TrySetResult(); + public Task CleanupReleased => _releaseCleanup.Task; + } + + private sealed class CancellationDrainDynamicsPacer : IDynamicsPacer + { + private readonly Channel _requests = Channel.CreateUnbounded(); + private readonly object _gate = new(); + private readonly List _delays = []; + + public async Task DelayAsync(TimeSpan delay, CancellationToken cancellationToken) + { + var pending = new DrainDelay(delay); + lock (_gate) + { + _delays.Add(pending); + } + + await _requests.Writer.WriteAsync(pending, cancellationToken); + try + { + await Task.Delay(Timeout.InfiniteTimeSpan, cancellationToken); + } + catch (OperationCanceledException) + { + pending.CancellationObserved.TrySetResult(); + pending.CleanupBlocked.TrySetResult(); + await pending.CleanupReleased.ConfigureAwait(false); + throw; + } + } + + public ValueTask NextDelayAsync() => _requests.Reader.ReadAsync(); + + public void ReleaseAllCleanup() + { + lock (_gate) + { + foreach (var delay in _delays) + { + delay.ReleaseCleanup(); + } + } + } + } + + private sealed class ImmediateDynamicsPacer : IDynamicsPacer + { + public Task DelayAsync(TimeSpan delay, CancellationToken cancellationToken) + { + cancellationToken.ThrowIfCancellationRequested(); + return Task.CompletedTask; + } + } + + private sealed class BlockingDynamicsOpen + { + public TaskCompletionSource Entered { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + public TaskCompletionSource Release { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + public DiagnosticSession? OpenedSession { get; set; } + } + + private sealed class BlockingOpenSessionService( + IDiagnosticSessionService inner, + BlockingDynamicsOpen openGate) : IDiagnosticSessionService + { + public IReadOnlyList Providers => inner.Providers; + + public Task OpenAsync( + string profileIdentifier, + int profileRevision, + string providerIdentifier, + ExecutionTargetKind targetKind, + CancellationToken cancellationToken = default) => + inner.OpenAsync(profileIdentifier, profileRevision, providerIdentifier, targetKind, cancellationToken); + + public async Task OpenDynamicsAsync( + string profileIdentifier, + int profileRevision, + string providerIdentifier, + ExecutionTargetKind targetKind, + DynamicsConfiguration configuration, + CancellationToken cancellationToken = default) + { + openGate.Entered.TrySetResult(); + await openGate.Release.Task.WaitAsync(cancellationToken); + var session = await inner.OpenDynamicsAsync( + profileIdentifier, + profileRevision, + providerIdentifier, + targetKind, + configuration, + cancellationToken); + openGate.OpenedSession = session; + return session; + } + + public Task ResetAsync( + DiagnosticSession session, + CancellationToken cancellationToken = default) => + inner.ResetAsync(session, cancellationToken); + } + + private static async Task RenderRoutesAsync(IServiceProvider services) + { + await using var renderer = new HtmlRenderer( + services, + services.GetRequiredService()); + + return await renderer.Dispatcher.InvokeAsync(async () => + { + var component = await renderer.RenderComponentAsync(); + return component.ToHtmlString(); + }); + } + + private static string ReadFixture(string name) => + File.ReadAllText(Path.Combine(AppContext.BaseDirectory, "Fixtures", name)); + + private sealed class TestNavigationManager : NavigationManager + { + public TestNavigationManager(string uri) => Initialize("http://localhost/", uri); + + protected override void NavigateToCore(string uri, bool forceLoad) + { + Uri = ToAbsoluteUri(uri).ToString(); + NotifyLocationChanged(forceLoad); + } + } + + private sealed class TestNavigationInterception : INavigationInterception + { + public Task EnableNavigationInterceptionAsync() => Task.CompletedTask; + } + + private sealed class TestScrollToLocationHash : IScrollToLocationHash + { + public Task RefreshScrollPositionForHash(string locationAbsolute) => Task.CompletedTask; + } +} diff --git a/src/tests/AutoForge.IntegrationTests/UiCompositionTests.cs b/src/tests/AutoForge.IntegrationTests/UiCompositionTests.cs index 21527e3..31e0f4b 100644 --- a/src/tests/AutoForge.IntegrationTests/UiCompositionTests.cs +++ b/src/tests/AutoForge.IntegrationTests/UiCompositionTests.cs @@ -24,7 +24,9 @@ public sealed class UiCompositionTests Assert.Contains("

AutoForge foundation

", html); Assert.Contains("Review execution-target selection", html); Assert.Contains("status-notice--information", html); - Assert.Contains("synthetic diagnostic sessions with static module data", html); + Assert.Contains("static synthetic diagnostics", html); + Assert.Contains("fixed-step synthetic dynamics workflow", html); + Assert.Contains("not manufacturer-validated", html); Assert.Contains("Target selection is metadata only", html); } diff --git a/src/tests/AutoForge.UnitTests/DynamicsEngineTests.cs b/src/tests/AutoForge.UnitTests/DynamicsEngineTests.cs new file mode 100644 index 0000000..9c1058c --- /dev/null +++ b/src/tests/AutoForge.UnitTests/DynamicsEngineTests.cs @@ -0,0 +1,844 @@ +using System.Text.Json; +using System.Text.Json.Nodes; +using System.Threading.Channels; +using AutoForge.Application.Features.Vehicles.Profiles; +using AutoForge.Application.Features.Vehicles.Simulation; +using AutoForge.Core.ExecutionTargets; +using AutoForge.Core.Simulation; +using AutoForge.Core.Vehicles; +using AutoForge.Diagnostics; +using AutoForge.Simulation; +using Xunit.Abstractions; + +namespace AutoForge.UnitTests; + +public sealed class DynamicsEngineTests +{ + private readonly ITestOutputHelper _output; + + public DynamicsEngineTests(ITestOutputHelper output) => _output = output; + + [Fact] + public void WarmBaseline_MeetsConfiguredScenarioThresholdsAndIsReproducible() + { + var configuration = CreateConfiguration(); + var first = Run(configuration); + var second = Run(configuration); + + Assert.Equal(DynamicsLifecycleState.Completed, first.Status.State); + Assert.Null(first.Status.Failure); + Assert.Equal(1, first.Status.ScenarioProgress); + Assert.Equal(first.Samples.Count, second.Samples.Count); + Assert.Equal(first.Samples, second.Samples); + + var model = configuration.Model; + var idle = first.Samples.Where(sample => sample.Phase == DynamicsScenarioPhaseKind.WarmIdle).ToArray(); + Assert.Equal(100, idle.Length); + Assert.InRange(Math.Abs(idle[^1].EngineSpeedRpm - model.WarmIdleTargetRpm), 0, 5); + + var acceleration = first.Samples.Where(sample => sample.Phase == DynamicsScenarioPhaseKind.Accelerate).ToArray(); + var target = configuration.Scenario.Single(phase => phase.Kind == DynamicsScenarioPhaseKind.Accelerate) + .TargetSpeedMetersPerSecond; + var achieved = Assert.Single(acceleration, sample => sample.VehicleSpeedMetersPerSecond >= target); + Assert.True(achieved.ModelTimeSeconds - idle[^1].ModelTimeSeconds <= 60); + Assert.True(achieved.ShiftCount >= 1); + Assert.True(first.Samples.Zip(first.Samples.Skip(1), (left, right) => + right.VehicleSpeedMetersPerSecond - left.VehicleSpeedMetersPerSecond).Max() < 0.5); + + var cruise = first.Samples.Where(sample => sample.Phase == DynamicsScenarioPhaseKind.Cruise).ToArray(); + Assert.Equal(3_000, cruise.Length); + var cruiseWithinToleranceCount = cruise.Count(sample => + Math.Abs(sample.VehicleSpeedMetersPerSecond - target) <= 0.44704); + Assert.True(cruiseWithinToleranceCount / (double)cruise.Length >= 0.95); + Assert.Contains(cruise, sample => sample.CouplingSlipFraction == 0 && sample.Gear > 0); + foreach (var sample in cruise.Where(sample => sample.CouplingSlipFraction == 0 && sample.Gear > 0)) + { + var expectedRpm = sample.VehicleSpeedMetersPerSecond / + (Math.PI * 2 * model.WheelRadiusMeters) * 60 * + model.ForwardGearRatios[sample.Gear - 1] * model.FinalDriveRatio; + Assert.InRange(Math.Abs(sample.EngineSpeedRpm - expectedRpm), 0, 1e-8); + } + + var braking = first.Samples.Where(sample => sample.Phase == DynamicsScenarioPhaseKind.Brake).ToArray(); + Assert.NotEmpty(braking); + Assert.True(braking.Length * model.StepSeconds <= 60); + Assert.InRange(braking[^1].VehicleSpeedMetersPerSecond, 0, 0.1); + var returnIdle = first.Samples.Where(sample => sample.Phase == DynamicsScenarioPhaseKind.ReturnIdle).ToArray(); + Assert.True(returnIdle.Length >= 100); + Assert.All(returnIdle, sample => Assert.Equal(0, sample.VehicleSpeedMetersPerSecond)); + Assert.All(first.Samples, sample => + { + Assert.True(double.IsFinite(sample.EngineSpeedRpm)); + Assert.True(double.IsFinite(sample.VehicleSpeedMetersPerSecond)); + Assert.True(double.IsFinite(sample.FuelRateKilogramsPerSecond)); + Assert.True(double.IsFinite(sample.FuelConsumedKilograms)); + Assert.True(double.IsFinite(sample.EngineTemperatureCelsius)); + Assert.True(sample.FuelRateKilogramsPerSecond >= 0); + }); + Assert.True(first.Samples.Zip(first.Samples.Skip(1), (left, right) => + right.FuelConsumedKilograms >= left.FuelConsumedKilograms).All(monotonic => monotonic)); + _output.WriteLine( + "samples={0}; warmIdle={1:F1}s/{2:F3}rpm; acceleration={3:F1}s/{4:F4}m/s; shifts={5}; " + + "cruise={6} samples, withinTolerance={7} ({8:P3}), coupled={9}; brake={10:F1}s/{11:F4}m/s; " + + "returnIdle={12:F1}s; totalFuel={13:F6}kg; reproducible={14}", + first.Samples.Count, + idle.Length * model.StepSeconds, + idle[^1].EngineSpeedRpm, + acceleration.Length * model.StepSeconds, + achieved.VehicleSpeedMetersPerSecond, + first.Samples[^1].ShiftCount, + cruise.Length, + cruiseWithinToleranceCount, + cruiseWithinToleranceCount / (double)cruise.Length, + cruise.Count(sample => sample.CouplingSlipFraction == 0 && sample.Gear > 0), + braking.Length * model.StepSeconds, + braking[^1].VehicleSpeedMetersPerSecond, + returnIdle.Length * model.StepSeconds, + first.Samples[^1].FuelConsumedKilograms, + first.Samples.SequenceEqual(second.Samples)); + } + + [Fact] + public void ConfigurationImportExport_IsStrictImmutableAndHasStableFingerprint() + { + var profile = CreateProfile(); + var profiles = new VehicleProfileService(new VehicleProfileJsonCodec(), new InMemoryVehicleProfileCatalog()); + profiles.Import(new VehicleProfileJsonCodec().Export(profile)); + var service = new DynamicsConfigurationService(profiles); + var original = service.CreateExample(profile.ProfileIdentifier, profile.Revision); + var exported = service.Export(original.ConfigurationIdentifier); + var imported = service.Import(exported); + + Assert.Equal(original.ConfigurationIdentifier, imported.ConfigurationIdentifier); + Assert.Equal(original.Model.ForwardGearRatios, imported.Model.ForwardGearRatios); + Assert.Equal( + original.Scenario.Select(phase => (phase.Kind, phase.TargetSpeedMetersPerSecond, phase.DurationSeconds)), + imported.Scenario.Select(phase => (phase.Kind, phase.TargetSpeedMetersPerSecond, phase.DurationSeconds))); + Assert.Throws(() => service.Import("{\"unknown\":1}")); + Assert.Throws(() => + service.Import("{\"formatVersion\":1,\"formatVersion\":1}")); + + var gearRatios = new[] { 3.5, 2.2, 1.4, 0.9 }; + var copiedModel = CopyModelWithGearRatios(original.Model, gearRatios); + gearRatios[0] = 18; + Assert.Equal(3.5, copiedModel.ForwardGearRatios[0]); + } + + [Fact] + public void ConfigurationImport_ReferencesFailThroughTypedValidationWithoutRegistration() + { + var profile = CreateProfile(); + var profiles = new VehicleProfileService(new VehicleProfileJsonCodec(), new InMemoryVehicleProfileCatalog()); + profiles.Import(new VehicleProfileJsonCodec().Export(profile)); + var service = new DynamicsConfigurationService(profiles); + var valid = service.CreateExample(profile.ProfileIdentifier, profile.Revision); + var validJson = JsonNode.Parse(service.Export(valid.ConfigurationIdentifier))!.AsObject(); + var unknownProfile = JsonNode.Parse(validJson.ToJsonString())!.AsObject(); + unknownProfile["profileIdentifier"] = "autoforge.synthetic.missing"; + var unknownRevision = JsonNode.Parse(validJson.ToJsonString())!.AsObject(); + unknownRevision["profileRevision"] = 99; + var unknownModule = JsonNode.Parse(validJson.ToJsonString())!.AsObject(); + unknownModule["engineModuleIdentifier"] = "module.engine.missing"; + var conflictingCalibration = JsonNode.Parse(validJson.ToJsonString())!.AsObject(); + conflictingCalibration["engineCalibrationReference"] = "calibration.synthetic.conflict"; + + Assert.Throws(() => service.Import(unknownProfile.ToJsonString())); + Assert.Throws(() => service.Import(unknownRevision.ToJsonString())); + Assert.Throws(() => service.Import(unknownModule.ToJsonString())); + Assert.Throws(() => service.Import(conflictingCalibration.ToJsonString())); + var missingTransmission = JsonNode.Parse(validJson.ToJsonString())!.AsObject(); + missingTransmission["transmissionModuleIdentifier"] = "module.transmission.missing"; + Assert.Throws(() => service.Import(missingTransmission.ToJsonString())); + Assert.Single(service.List()); + Assert.Equal(valid.ConfigurationIdentifier, service.Select(valid.ConfigurationIdentifier).ConfigurationIdentifier); + } + + [Fact] + public void DynamicsConfiguration_RejectsInconsistentInitialCouplingAndOverRevStates() + { + var profile = CreateProfile(); + var profiles = new VehicleProfileService(new VehicleProfileJsonCodec(), new InMemoryVehicleProfileCatalog()); + profiles.Import(new VehicleProfileJsonCodec().Export(profile)); + var service = new DynamicsConfigurationService(profiles); + var baseline = service.CreateExample(profile.ProfileIdentifier, profile.Revision); + var mismatched = JsonNode.Parse(service.Export(baseline.ConfigurationIdentifier))!.AsObject(); + mismatched["initialConditions"]!["engineRunning"] = true; + mismatched["initialConditions"]!["vehicleSpeedMetersPerSecond"] = 10; + mismatched["initialConditions"]!["gear"] = 1; + mismatched["initialConditions"]!["engineSpeedRpm"] = 650; + + Assert.Throws(() => service.Import(mismatched.ToJsonString())); + var coupledInitial = JsonNode.Parse(service.Export(baseline.ConfigurationIdentifier))!.AsObject(); + coupledInitial["initialConditions"]!["engineRunning"] = true; + coupledInitial["initialConditions"]!["vehicleSpeedMetersPerSecond"] = 10; + coupledInitial["initialConditions"]!["gear"] = 1; + coupledInitial["initialConditions"]!["engineSpeedRpm"] = + 10 / (Math.PI * 2 * baseline.Model.WheelRadiusMeters) * 60 * + baseline.Model.ForwardGearRatios[0] * baseline.Model.FinalDriveRatio; + var acceptedInitial = service.Import(coupledInitial.ToJsonString()); + var initialEngine = new DynamicsEngine(acceptedInitial, "consistent-initial-run"); + Assert.Equal(acceptedInitial.InitialConditions.EngineSpeedRpm, initialEngine.CurrentState().EngineSpeedRpm); + } + + [Fact] + public void DynamicsRuntime_DoesNotReportFalseLockedOrZeroSlipState() + { + var profile = CreateProfile(); + var profiles = new VehicleProfileService(new VehicleProfileJsonCodec(), new InMemoryVehicleProfileCatalog()); + profiles.Import(new VehicleProfileJsonCodec().Export(profile)); + var configurations = new DynamicsConfigurationService(profiles); + var couplingBaseline = configurations.CreateExample(profile.ProfileIdentifier, profile.Revision); + var highSpeed = JsonNode.Parse(configurations.Export(couplingBaseline.ConfigurationIdentifier))!.AsObject(); + highSpeed["model"]!["vehicleMassKilograms"] = 100; + highSpeed["model"]!["dragAreaSquareMeters"] = 0; + highSpeed["model"]!["rollingResistanceCoefficient"] = 0; + foreach (var point in highSpeed["model"]!["engineTorqueCurve"]!.AsArray()) + { + point!["torqueNewtonMeters"] = 1_000; + } + highSpeed["scenario"]![1]!["targetSpeedMetersPerSecond"] = 60; + highSpeed["scenario"]![2]!["targetSpeedMetersPerSecond"] = 60; + Assert.Throws(() => configurations.Import(highSpeed.ToJsonString())); + + highSpeed["model"]!["maximumEngineSpeedRpm"] = 12_000; + highSpeed["model"]!["warmIdleTargetRpm"] = 650; + highSpeed["model"]!["upshiftSpeedsRpm"] = new JsonArray(11_000, 11_000, 11_000, 11_000); + highSpeed["scenario"]![1]!["targetSpeedMetersPerSecond"] = 100; + highSpeed["scenario"]![2]!["targetSpeedMetersPerSecond"] = 100; + var highSpeedConfiguration = configurations.Import(highSpeed.ToJsonString()); + var highSpeedEngine = new DynamicsEngine(highSpeedConfiguration, "over-rev-run"); + for (var index = 0; index < 10_000 && + highSpeedEngine.Lifecycle is not (DynamicsLifecycleState.Completed or DynamicsLifecycleState.Faulted); + index++) + { + highSpeedEngine.AdvanceOne(); + } + + Assert.Equal(DynamicsLifecycleState.Completed, highSpeedEngine.Status.State); + var highRpmSamples = highSpeedEngine.Samples.Where(sample => sample.Gear > 0 && + sample.CouplingSlipFraction == 0).ToArray(); + Assert.Contains(highRpmSamples, sample => sample.EngineSpeedRpm > 9_000); + Assert.All(highRpmSamples, sample => + { + var expectedRpm = sample.VehicleSpeedMetersPerSecond / + (Math.PI * 2 * highSpeedConfiguration.Model.WheelRadiusMeters) * 60 * + highSpeedConfiguration.Model.ForwardGearRatios[sample.Gear - 1] * + highSpeedConfiguration.Model.FinalDriveRatio; + Assert.InRange(Math.Abs(sample.EngineSpeedRpm - expectedRpm), 0, 1e-8); + }); + + var lowSlip = JsonNode.Parse(configurations.Export(couplingBaseline.ConfigurationIdentifier))!.AsObject(); + lowSlip["model"]!["launchSlipEndSpeedMetersPerSecond"] = 0.1; + lowSlip["scenario"]![0]!["durationSeconds"] = 0.1; + var lowSlipConfiguration = configurations.Import(lowSlip.ToJsonString()); + var lowSlipEngine = new DynamicsEngine(lowSlipConfiguration, "low-slip-run"); + for (var index = 0; index < 5; index++) + { + lowSlipEngine.AdvanceOne(); + } + + var lowSlipMismatches = lowSlipEngine.Samples.Where(sample => sample.Gear > 0 && + Math.Abs(sample.EngineSpeedRpm - + sample.VehicleSpeedMetersPerSecond / (Math.PI * 2 * lowSlipConfiguration.Model.WheelRadiusMeters) * + 60 * lowSlipConfiguration.Model.ForwardGearRatios[sample.Gear - 1] * + lowSlipConfiguration.Model.FinalDriveRatio) > 1e-8).ToArray(); + Assert.NotEmpty(lowSlipMismatches); + Assert.All(lowSlipMismatches, + sample => Assert.True(sample.CouplingSlipFraction > 0)); + } + + [Fact] + public void ScenarioProgress_IsMonotonicAcrossPhasesAndDeadlineFailureIsTerminal() + { + var configuration = CreateConfiguration(); + var engine = new DynamicsEngine(configuration, "progress-run"); + var progress = new List(); + for (var index = 0; index < 10_000 && + engine.Lifecycle is not (DynamicsLifecycleState.Completed or DynamicsLifecycleState.Faulted); + index++) + { + engine.AdvanceOne(); + progress.Add(engine.Status.ScenarioProgress); + } + + Assert.Equal(DynamicsLifecycleState.Completed, engine.Lifecycle); + Assert.All(progress.Zip(progress.Skip(1), (left, right) => right >= left), Assert.True); + + var profile = CreateProfile(); + var profiles = new VehicleProfileService(new VehicleProfileJsonCodec(), new InMemoryVehicleProfileCatalog()); + profiles.Import(new VehicleProfileJsonCodec().Export(profile)); + var configurations = new DynamicsConfigurationService(profiles); + var baseline = configurations.CreateExample(profile.ProfileIdentifier, profile.Revision); + var shortDeadline = JsonNode.Parse(configurations.Export(baseline.ConfigurationIdentifier))!.AsObject(); + shortDeadline["scenario"]![1]!["durationSeconds"] = 0.1; + var failing = configurations.Import(shortDeadline.ToJsonString()); + var failedEngine = new DynamicsEngine(failing, "deadline-run"); + for (var index = 0; index < 120 && failedEngine.Lifecycle != DynamicsLifecycleState.Faulted; index++) + { + failedEngine.AdvanceOne(); + } + + Assert.Equal(DynamicsLifecycleState.Faulted, failedEngine.Status.State); + Assert.False(string.IsNullOrWhiteSpace(failedEngine.Status.Failure)); + Assert.InRange(failedEngine.Status.ScenarioProgress, 0, 1); + } + + [Fact] + public void LaunchSample_MatchesIndependentConstantTorqueForceAndMassEquation() + { + var profile = CreateProfile(); + var profiles = new VehicleProfileService(new VehicleProfileJsonCodec(), new InMemoryVehicleProfileCatalog()); + profiles.Import(new VehicleProfileJsonCodec().Export(profile)); + var configurations = new DynamicsConfigurationService(profiles); + var baseline = configurations.CreateExample(profile.ProfileIdentifier, profile.Revision); + var json = JsonNode.Parse(configurations.Export(baseline.ConfigurationIdentifier))!.AsObject(); + json["scenario"]![0]!["durationSeconds"] = 0.1; + foreach (var point in json["model"]!["engineTorqueCurve"]!.AsArray()) + { + point!["torqueNewtonMeters"] = 300; + } + + var configuration = configurations.Import(json.ToJsonString()); + var engine = new DynamicsEngine(configuration, "force-check-run"); + engine.AdvanceOne(); + engine.AdvanceOne(); + var samples = engine.Samples; + var previous = samples[^2]; + var current = samples[^1]; + var model = configuration.Model; + var couplingFactor = Math.Clamp( + previous.VehicleSpeedMetersPerSecond / model.LaunchSlipEndSpeedMetersPerSecond, + 0.2, + 1); + var wheelForce = 300 * current.Throttle * model.ForwardGearRatios[current.Gear - 1] * + model.FinalDriveRatio * model.DrivetrainEfficiency / + model.WheelRadiusMeters * couplingFactor; + var rollingForce = model.VehicleMassKilograms * model.GravityMetersPerSecondSquared * + model.RollingResistanceCoefficient; + var aerodynamicForce = 0.5 * model.AirDensityKilogramsPerCubicMeter * + model.DragAreaSquareMeters * + previous.VehicleSpeedMetersPerSecond * + previous.VehicleSpeedMetersPerSecond; + var expectedAcceleration = + (wheelForce - rollingForce - aerodynamicForce - + current.Brake * model.MaximumBrakeForceNewtons) / model.VehicleMassKilograms; + + Assert.Equal(300 * current.Throttle, current.EngineTorqueNewtonMeters, 10); + Assert.InRange(Math.Abs(current.AccelerationMetersPerSecondSquared - expectedAcceleration), 0, 1e-10); + Assert.InRange(Math.Abs( + (current.VehicleSpeedMetersPerSecond - previous.VehicleSpeedMetersPerSecond) / model.StepSeconds - + expectedAcceleration), 0, 1e-10); + } + + [Fact] + public void NonFiniteModelEvolutionRollsBackToLastValidSnapshotAndFaults() + { + var profile = CreateProfile(); + var profiles = new VehicleProfileService(new VehicleProfileJsonCodec(), new InMemoryVehicleProfileCatalog()); + profiles.Import(new VehicleProfileJsonCodec().Export(profile)); + var configurations = new DynamicsConfigurationService(profiles); + var baseline = configurations.CreateExample(profile.ProfileIdentifier, profile.Revision); + var json = JsonNode.Parse(configurations.Export(baseline.ConfigurationIdentifier))!.AsObject(); + json["scenario"]![0]!["durationSeconds"] = 0.1; + json["model"]!["forwardGearRatios"] = new JsonArray(1e-304, 9e-305, 8e-305, 7e-305); + json["model"]!["finalDriveRatio"] = 0.1; + foreach (var point in json["model"]!["engineTorqueCurve"]!.AsArray()) + { + point!["torqueNewtonMeters"] = 1e308; + } + + var configuration = configurations.Import(json.ToJsonString()); + var engine = new DynamicsEngine(configuration, "non-finite-run"); + engine.AdvanceOne(); + var lastValid = engine.CurrentState(); + var sampleCount = engine.SampleCount; + + engine.AdvanceOne(); + + Assert.Equal(DynamicsLifecycleState.Faulted, engine.Status.State); + Assert.Contains("finite supported domain", engine.Status.Failure); + Assert.Equal(lastValid, engine.CurrentState()); + Assert.Equal(sampleCount, engine.SampleCount); + Assert.All(engine.Samples, sample => + { + Assert.True(double.IsFinite(sample.EngineSpeedRpm)); + Assert.True(double.IsFinite(sample.FuelRateKilogramsPerSecond)); + Assert.True(double.IsFinite(sample.FuelConsumedKilograms)); + Assert.True(double.IsFinite(sample.EngineTemperatureCelsius)); + }); + } + + [Fact] + public async Task DynamicProtocolReadsBoundTelemetryWithoutAdvancingModelTime() + { + var profile = CreateProfile(); + var configuration = DynamicsConfiguration.CreateWarmBaseline(profile); + var definition = CreateDefinition(profile); + var factory = new DynamicsDiagnosticTransportFactory([definition]); + var identity = new DiagnosticSessionIdentity( + "dynamics-test-session", + profile.ProfileIdentifier, + profile.Revision, + profile.Vehicle.VehicleIdentifier, + factory.Descriptor.Target, + configuration.ConfigurationIdentifier, + "dynamics-test-run"); + var binding = factory.OpenDynamicsTransport(profile, identity, configuration); + await using var control = binding.Control; + await using var transport = binding.Transport; + var protocol = new SyntheticDiagnosticProtocolClient( + profile, + identity, + transport, + new DiagnosticLogicalClock(), + protocolVersion: 2, + dynamicsConfiguration: configuration); + var engineEndpoint = Assert.Single(protocol.ExpectedEndpoints, endpoint => + endpoint.ModuleIdentifier == configuration.EngineModuleIdentifier); + + var before = control.Status; + var response = await protocol.ReadSignalsAsync(engineEndpoint); + var after = control.Status; + + Assert.True(response.IsSuccess, response.Error); + Assert.Equal(before.StepIndex, after.StepIndex); + Assert.Equal(before.VirtualTimeSeconds, after.VirtualTimeSeconds); + Assert.Equal(before.ConfigurationIdentifier, response.Value!.ModelConfigurationIdentifier); + Assert.Equal(before.RunIdentifier, response.Value.ModelRunIdentifier); + Assert.Equal(before.StepIndex, response.Value.ModelStepIndex); + Assert.All(response.Value.Signals, signal => + { + Assert.Equal("SYNTHETIC_DYNAMIC", signal.Origin); + Assert.Equal(before.StepIndex, signal.ModelStepIndex); + Assert.Equal(before.VirtualTimeSeconds, signal.ModelTimeSeconds); + }); + + var tampered = new SyntheticDiagnosticProtocolClient( + profile, + identity, + new RewritingTransport(transport, root => + root["data"]!["configurationIdentifier"] = "sha256:v1:wrong"), + new DiagnosticLogicalClock(), + protocolVersion: 2, + dynamicsConfiguration: configuration); + var invalid = await tampered.ReadSignalsAsync(engineEndpoint); + Assert.Equal(DiagnosticOutcome.ProtocolError, invalid.Outcome); + Assert.Equal("INVALID_RESPONSE", invalid.FailureCode); + Assert.Equal(before.StepIndex, control.Status.StepIndex); + } + + [Fact] + public async Task LifecycleControlsFreezeStepExactlyAndDisposeWithoutStaleTicks() + { + var engine = new DynamicsEngine(CreateConfiguration(), "lifecycle-run"); + var pacer = new ControlledDynamicsPacer(); + await using var control = new DynamicsRunControl(engine, pacer); + var stepped = await control.StepAsync(3); + Assert.Equal(DynamicsLifecycleState.Stopped, stepped.State); + Assert.Equal(3, stepped.StepIndex); + + await control.StartAsync(); + var firstDelay = await pacer.NextDelayAsync(); + Assert.Equal(4, control.Status.StepIndex); + Assert.Equal(DynamicsLifecycleState.Running, control.Status.State); + Assert.Equal(TimeSpan.FromSeconds(0.1), firstDelay.Delay); + var paused = await control.PauseAsync(); + Assert.Equal(DynamicsLifecycleState.Paused, paused.State); + Assert.Equal(4, paused.StepIndex); + Assert.Equal(paused, control.Status); + + var pausedStep = await control.StepAsync(2); + Assert.Equal(6, pausedStep.StepIndex); + Assert.Equal(DynamicsLifecycleState.Paused, pausedStep.State); + await control.ResumeAsync(); + var resumedDelay = await pacer.NextDelayAsync(); + Assert.Equal(7, control.Status.StepIndex); + Assert.Equal(DynamicsLifecycleState.Running, control.Status.State); + var reset = await control.ResetAsync(); + Assert.Equal(0, reset.StepIndex); + Assert.Equal(DynamicsLifecycleState.Stopped, reset.State); + Assert.Equal(reset, control.Status); + Assert.True(resumedDelay.IsCancelled); + + await control.StartAsync(); + var stopDelay = await pacer.NextDelayAsync(); + var activeStep = control.Status.StepIndex; + var stopped = await control.StopAsync(); + Assert.Equal(DynamicsLifecycleState.Stopped, stopped.State); + Assert.Equal(activeStep, stopped.StepIndex); + Assert.True(stopDelay.IsCancelled); + + await control.StartAsync(); + var disposeDelay = await pacer.NextDelayAsync(); + Assert.Equal(activeStep + 1, control.Status.StepIndex); + await control.DisposeAsync(); + var closed = control.Status; + Assert.Equal(DynamicsLifecycleState.Closed, closed.State); + Assert.True(disposeDelay.IsCancelled); + Assert.Equal(closed, control.Status); + await Assert.ThrowsAsync(() => control.StepAsync()); + } + + [Theory] + [InlineData("pause-resume")] + [InlineData("stop-start")] + [InlineData("reset-start")] + public async Task StartOrResumeDuringOwnerDrainRejectsWithoutChangingStatus(string transition) + { + var pacer = new CancellationDrainPacer(); + var engine = new DynamicsEngine(CreateConfiguration(), $"drain-{transition}"); + var control = new DynamicsRunControl(engine, pacer); + Task? drainingTransition = null; + try + { + await control.StartAsync(); + var oldDelay = await pacer.NextDelayAsync(); + Assert.Equal(1, control.Status.StepIndex); + + drainingTransition = transition switch + { + "pause-resume" => control.PauseAsync(), + "stop-start" => control.StopAsync(), + "reset-start" => control.ResetAsync(), + _ => throw new ArgumentOutOfRangeException(nameof(transition)) + }; + await oldDelay.CancellationObserved.Task; + await oldDelay.CleanupBlocked.Task; + Assert.False(drainingTransition.IsCompleted); + + var beforeRejectedCall = control.Status; + var sampleCountBeforeRejectedCall = engine.SampleCount; + var rejectedStart = transition == "pause-resume" + ? control.ResumeAsync() + : control.StartAsync(); + var rejection = await Assert.ThrowsAsync(() => rejectedStart); + + Assert.Contains("owner", rejection.Message, StringComparison.OrdinalIgnoreCase); + Assert.Equal(beforeRejectedCall, control.Status); + Assert.Equal(sampleCountBeforeRejectedCall, engine.SampleCount); + Assert.False(drainingTransition.IsCompleted); + Assert.False(oldDelay.CleanupReleased.IsCompleted); + + oldDelay.ReleaseCleanup(); + var settledStatus = await drainingTransition; + var expectedSettledState = transition == "pause-resume" + ? DynamicsLifecycleState.Paused + : DynamicsLifecycleState.Stopped; + Assert.Equal(expectedSettledState, settledStatus.State); + Assert.Equal(expectedSettledState, control.Status.State); + Assert.Equal(beforeRejectedCall.StepIndex, settledStatus.StepIndex); + Assert.True(oldDelay.CleanupReleased.IsCompleted); + var settledSampleCount = engine.SampleCount; + + var retryStatus = transition == "pause-resume" + ? await control.ResumeAsync() + : await control.StartAsync(); + Assert.Equal(DynamicsLifecycleState.Running, retryStatus.State); + Assert.Equal(settledStatus.StepIndex, retryStatus.StepIndex); + var newDelay = await pacer.NextDelayAsync(); + Assert.NotSame(oldDelay, newDelay); + var activeStatus = control.Status; + Assert.Equal(settledStatus.StepIndex + 1, activeStatus.StepIndex); + Assert.Equal(settledSampleCount + 1, engine.SampleCount); + + var finalPause = control.PauseAsync(); + await newDelay.CancellationObserved.Task; + await newDelay.CleanupBlocked.Task; + newDelay.ReleaseCleanup(); + var finalStatus = await finalPause; + Assert.Equal(DynamicsLifecycleState.Paused, finalStatus.State); + Assert.Equal(activeStatus.StepIndex, finalStatus.StepIndex); + } + finally + { + pacer.ReleaseAllCleanup(); + await control.DisposeAsync(); + if (drainingTransition is not null) + { + await drainingTransition; + } + } + } + + [Fact] + public async Task DuplicateStartAndInvalidResumeDoNotChangeLifecycleOrOwner() + { + var pacer = new ControlledDynamicsPacer(); + var engine = new DynamicsEngine(CreateConfiguration(), "duplicate-start-run"); + await using var control = new DynamicsRunControl(engine, pacer); + + await control.StartAsync(); + var pendingDelay = await pacer.NextDelayAsync(); + var duplicateStart = control.Status; + await Assert.ThrowsAsync(() => control.StartAsync()); + Assert.Equal(duplicateStart, control.Status); + Assert.False(pendingDelay.IsCancelled); + + var paused = await control.PauseAsync(); + Assert.Equal(DynamicsLifecycleState.Paused, paused.State); + Assert.True(pendingDelay.IsCancelled); + + var stoppedEngine = new DynamicsEngine(CreateConfiguration(), "invalid-resume-run"); + await using var stoppedControl = new DynamicsRunControl(stoppedEngine, new ImmediateDynamicsPacer()); + var stoppedBeforeResume = stoppedControl.Status; + await Assert.ThrowsAsync(() => stoppedControl.ResumeAsync()); + Assert.Equal(stoppedBeforeResume, stoppedControl.Status); + + await stoppedControl.DisposeAsync(); + var closedStatus = stoppedControl.Status; + await Assert.ThrowsAsync(() => stoppedControl.StartAsync()); + await Assert.ThrowsAsync(() => stoppedControl.ResumeAsync()); + Assert.Equal(closedStatus, stoppedControl.Status); + } + + [Fact] + public async Task PacedRuns_KeepOneOwnerAndProduceIdenticalSamplesAtDifferentFactors() + { + var cancellationPacer = new ControlledDynamicsPacer(); + var cancellationControl = new DynamicsRunControl( + new DynamicsEngine(CreateConfiguration(), "cancel-run"), + cancellationPacer); + using var cancellation = new CancellationTokenSource(); + var firstRun = cancellationControl.RunScenarioAsync(cancellation.Token); + var pending = await cancellationPacer.NextDelayAsync(); + Assert.Equal(1, cancellationControl.Status.StepIndex); + await Assert.ThrowsAsync(() => cancellationControl.RunScenarioAsync()); + cancellation.Cancel(); + await Assert.ThrowsAnyAsync(() => firstRun); + Assert.Equal(DynamicsLifecycleState.Paused, cancellationControl.Status.State); + Assert.True(pending.IsCancelled); + await cancellationControl.DisposeAsync(); + + var slow = await RunWithImmediatePacerAsync(0.25, "slow-pacing-run"); + var fast = await RunWithImmediatePacerAsync(1_000, "fast-pacing-run"); + Assert.Equal(DynamicsLifecycleState.Completed, slow.Status.State); + Assert.Equal(slow.Samples, fast.Samples); + Assert.Equal(TimeSpan.FromSeconds(0.4), slow.RequestedDelays[0]); + Assert.Equal(TimeSpan.FromSeconds(0.0001), fast.RequestedDelays[0]); + } + + private static async Task<(DynamicsRunStatus Status, IReadOnlyList Samples, IReadOnlyList RequestedDelays)> + RunWithImmediatePacerAsync(double pacingFactor, string runIdentifier) + { + var pacer = new ImmediateDynamicsPacer(); + var engine = new DynamicsEngine(CreateConfiguration(), runIdentifier); + await using var control = new DynamicsRunControl(engine, pacer); + await control.SetPacingFactorAsync(pacingFactor); + var status = await control.RunScenarioAsync(); + return (status, engine.Samples, pacer.RequestedDelays); + } + + private sealed record PendingDynamicsDelay(TimeSpan Delay, TaskCompletionSource Completion) + { + public bool IsCancelled => Completion.Task.IsCanceled; + } + + private sealed class ControlledDynamicsPacer : IDynamicsPacer + { + private readonly Channel _requests = Channel.CreateUnbounded(); + + public async Task DelayAsync(TimeSpan delay, CancellationToken cancellationToken) + { + var completion = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + using var registration = cancellationToken.Register( + () => completion.TrySetCanceled(cancellationToken)); + await _requests.Writer.WriteAsync(new PendingDynamicsDelay(delay, completion), cancellationToken); + await completion.Task; + } + + public ValueTask NextDelayAsync() => _requests.Reader.ReadAsync(); + } + + private sealed class DrainDelay(TimeSpan delay) + { + private readonly TaskCompletionSource _releaseCleanup = + new(TaskCreationOptions.RunContinuationsAsynchronously); + + public TimeSpan Delay { get; } = delay; + public TaskCompletionSource CancellationObserved { get; } = + new(TaskCreationOptions.RunContinuationsAsynchronously); + public TaskCompletionSource CleanupBlocked { get; } = + new(TaskCreationOptions.RunContinuationsAsynchronously); + public Task CleanupReleased => _releaseCleanup.Task; + public void ReleaseCleanup() => _releaseCleanup.TrySetResult(); + } + + private sealed class CancellationDrainPacer : IDynamicsPacer + { + private readonly Channel _requests = Channel.CreateUnbounded(); + private readonly object _gate = new(); + private readonly List _delays = []; + + public async Task DelayAsync(TimeSpan delay, CancellationToken cancellationToken) + { + var pending = new DrainDelay(delay); + lock (_gate) + { + _delays.Add(pending); + } + + await _requests.Writer.WriteAsync(pending, cancellationToken); + try + { + await Task.Delay(Timeout.InfiniteTimeSpan, cancellationToken); + } + catch (OperationCanceledException) + { + pending.CancellationObserved.TrySetResult(); + pending.CleanupBlocked.TrySetResult(); + await pending.CleanupReleased.ConfigureAwait(false); + throw; + } + } + + public ValueTask NextDelayAsync() => _requests.Reader.ReadAsync(); + + public void ReleaseAllCleanup() + { + lock (_gate) + { + foreach (var delay in _delays) + { + delay.ReleaseCleanup(); + } + } + } + } + + private sealed class ImmediateDynamicsPacer : IDynamicsPacer + { + private readonly List _requestedDelays = []; + public IReadOnlyList RequestedDelays => _requestedDelays.AsReadOnly(); + + public Task DelayAsync(TimeSpan delay, CancellationToken cancellationToken) + { + cancellationToken.ThrowIfCancellationRequested(); + _requestedDelays.Add(delay); + return Task.CompletedTask; + } + } + + private static (DynamicsRunStatus Status, IReadOnlyList Samples) Run( + DynamicsConfiguration configuration) + { + var engine = new DynamicsEngine(configuration, "numeric-run"); + for (var index = 0; index < 10_000 && + engine.Lifecycle is not (DynamicsLifecycleState.Completed or DynamicsLifecycleState.Faulted); + index++) + { + engine.AdvanceOne(); + } + + Assert.Equal(DynamicsLifecycleState.Completed, engine.Lifecycle); + return (engine.Status, engine.Samples); + } + + private static DynamicsConfiguration CreateConfiguration() => + DynamicsConfiguration.CreateWarmBaseline(CreateProfile()); + + private static VehicleProfile CreateProfile() => + new( + "autoforge.synthetic.test-truck", + 1, + new VehicleIdentity("vehicle.synthetic.test-truck", "AutoForge", "Synthetic Truck"), + [ + new ModuleInstance( + "module.engine.primary", + "powertrain.engine-controller", + "Synthetic Engine Controller", + "hardware.synthetic.engine-a", + "software.synthetic.engine-1", + calibrationIdentifier: "calibration.synthetic.engine-base"), + new ModuleInstance( + "module.transmission.primary", + "powertrain.transmission-controller", + "Synthetic Transmission Controller") + ], + []); + + private static SimulationDefinition CreateDefinition(VehicleProfile profile) + { + var services = new[] + { + DiagnosticServices.Probe, + DiagnosticServices.ReadIdentity, + DiagnosticServices.ReadTroubleCodes, + DiagnosticServices.ClearTroubleCodes, + DiagnosticServices.ReadSignals + }; + var engine = profile.GetModule("module.engine.primary"); + var transmission = profile.GetModule("module.transmission.primary"); + return new SimulationDefinition( + profile.ProfileIdentifier, + profile.Revision, + [ + new VirtualModuleDefinition( + engine.InstanceIdentifier, + "10", + VirtualIdentityDefinition.FromModule(engine), + services), + new VirtualModuleDefinition( + transmission.InstanceIdentifier, + "20", + VirtualIdentityDefinition.FromModule(transmission), + services) + ]); + } + + private static DynamicsModelParameters CopyModelWithGearRatios( + DynamicsModelParameters model, + IReadOnlyList ratios) => + new( + model.StepSeconds, + model.VehicleMassKilograms, + model.WheelRadiusMeters, + model.DragAreaSquareMeters, + model.RollingResistanceCoefficient, + model.AirDensityKilogramsPerCubicMeter, + model.GravityMetersPerSecondSquared, + model.DrivetrainEfficiency, + model.MaximumBrakeForceNewtons, + model.IdleSpeedRpm, + model.MaximumEngineSpeedRpm, + model.WarmIdleTargetRpm, + model.LaunchSlipEndSpeedMetersPerSecond, + model.IdleFuelRateKilogramsPerSecond, + model.FuelKilogramsPerJoule, + model.AmbientTemperatureCelsius, + model.InitialEngineTemperatureCelsius, + model.EquilibriumEngineTemperatureCelsius, + model.ThermalResponsePerSecond, + model.EngineTorqueCurve, + ratios, + model.UpshiftSpeedsRpm, + model.DownshiftSpeedsRpm, + model.FinalDriveRatio); + + private sealed class RewritingTransport( + IDiagnosticTransport inner, + Action rewrite) : IDiagnosticTransport + { + public IReadOnlyList ExpectedEndpoints => inner.ExpectedEndpoints; + + public async ValueTask SendAsync( + ReadOnlyMemory request, + CancellationToken cancellationToken) + { + var reply = await inner.SendAsync(request, cancellationToken); + if (reply.Outcome != TransportOutcome.Response) + { + return reply; + } + + var root = JsonNode.Parse(reply.Payload.ToArray())!.AsObject(); + rewrite(root); + return new TransportReply( + TransportOutcome.Response, + JsonSerializer.SerializeToUtf8Bytes(root), + reply.ElapsedTicks, + reply.Detail); + } + + public ValueTask DisposeAsync() => ValueTask.CompletedTask; + } +}