After Step 4
This commit is contained in:
parent
fe43fcf97b
commit
1efbe7b3c9
56
README.md
56
README.md
|
|
@ -32,9 +32,20 @@ supported vehicle modules.
|
||||||
profile-verified identity and keeps expected/probed/identified counts distinct.
|
profile-verified identity and keeps expected/probed/identified counts distinct.
|
||||||
Read/clear actions remain gated on verified identity. Step-03 as a whole remains
|
Read/clear actions remain gated on verified identity. Step-03 as a whole remains
|
||||||
subject to manual orchestrator acceptance.
|
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,
|
- UI routes: `/` foundation, `/execution-targets` explicit metadata selection,
|
||||||
`/vehicle-profiles` explicit profile import/revision selection/inspection/export,
|
`/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,
|
- Capability declarations distinguish Supported, Unsupported, Unknown,
|
||||||
Inaccessible and Restricted. Missing declarations are explicitly Unknown.
|
Inaccessible and Restricted. Missing declarations are explicitly Unknown.
|
||||||
Provenance and all profile facts are supplied metadata, not independently
|
Provenance and all profile facts are supplied metadata, not independently
|
||||||
|
|
@ -49,16 +60,21 @@ supported vehicle modules.
|
||||||
|
|
||||||
### In progress
|
### In progress
|
||||||
|
|
||||||
Manual orchestrator review and acceptance of the Step-03B correction report;
|
Manual orchestrator review and acceptance of Step-03B remain pending. Step-04
|
||||||
the worker's native baseline smoke and Release verification are complete.
|
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
|
### Planned
|
||||||
|
|
||||||
Vehicle dynamics/scenarios, telemetry recording/replay, calibration values/
|
Telemetry recording/replay, calibration values/editing/backups, AI and real
|
||||||
editing/backups, AI and real hardware operations require later approved
|
hardware operations require later approved assignments. Dynamics estimates are
|
||||||
assignments. This Step-03 virtual protocol is explicitly synthetic and does not
|
synthetic, not manufacturer prediction, vehicle compatibility, physical access,
|
||||||
provide vehicle compatibility, physical access or authorization. No capability
|
safe tuning advice or authorization. No capability is implemented merely
|
||||||
is implemented merely because it appears in the product vision or roadmap.
|
because it appears in the product vision or roadmap.
|
||||||
|
|
||||||
## Architecture
|
## 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.
|
browser-hosted WASM shell, Blazor Server host or second application executable.
|
||||||
|
|
||||||
The application slices provide explicit target metadata resolution,
|
The application slices provide explicit target metadata resolution,
|
||||||
vehicle-profile metadata import/list/select/export, and simulation-only
|
vehicle-profile metadata import/list/select/export, dynamics configuration
|
||||||
diagnostic sessions. The Client composes the actual synthetic provider through
|
catalog/import/export, and simulation-only diagnostic sessions. The Client
|
||||||
the provider-neutral factory contract and a session-lifetime in-memory profile
|
composes separate static and dynamics synthetic providers through
|
||||||
catalog. Import never auto-selects or replaces an existing profile revision;
|
provider-neutral factory contracts and a session-lifetime in-memory profile/
|
||||||
metadata resolution never opens a session.
|
configuration catalog. Import never opens a session; metadata resolution never
|
||||||
|
opens a session or starts a run.
|
||||||
|
|
||||||
```mermaid
|
```mermaid
|
||||||
flowchart TD
|
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/ExecutionTargets/SelectExecutionTarget`
|
||||||
- `AutoForge.Application/Features/Vehicles/Profiles`
|
- `AutoForge.Application/Features/Vehicles/Profiles`
|
||||||
- `AutoForge.Application/Features/Vehicles/Diagnostics`
|
- `AutoForge.Application/Features/Vehicles/Diagnostics`
|
||||||
|
- `AutoForge.Application/Features/Vehicles/Simulation`
|
||||||
- `AutoForge.Diagnostics` (provider-neutral protocol, transport/session contracts)
|
- `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/Profiles`
|
||||||
- `AutoForge.UI/Features/Vehicles/Diagnostics`
|
- `AutoForge.UI/Features/Vehicles/Diagnostics`
|
||||||
|
- `AutoForge.UI/Features/Vehicles/Simulation`
|
||||||
|
|
||||||
No mediator, generic repository layer, database, or empty future feature is
|
No mediator, generic repository layer, database, or empty future feature is
|
||||||
required. See the [schema-v1 profile guide](docs/vehicle-profile-schema-v1.md)
|
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.Core/ Platform-neutral domain invariants
|
||||||
AutoForge.Application/ In-process application feature slices
|
AutoForge.Application/ In-process application feature slices
|
||||||
AutoForge.Diagnostics/ Provider-neutral diagnostic protocol/contracts
|
AutoForge.Diagnostics/ Provider-neutral diagnostic protocol/contracts
|
||||||
AutoForge.Simulation/ Synthetic virtual-module provider/transport
|
AutoForge.Simulation/ Static modules, dynamics engine and transports
|
||||||
tests/
|
tests/
|
||||||
AutoForge.UnitTests/
|
AutoForge.UnitTests/
|
||||||
AutoForge.IntegrationTests/
|
AutoForge.IntegrationTests/
|
||||||
|
|
@ -176,6 +195,7 @@ acceptance remains the orchestrator's responsibility.
|
||||||
- [Documentation index](docs/README.md)
|
- [Documentation index](docs/README.md)
|
||||||
- [Architecture and project graph](docs/architecture.md)
|
- [Architecture and project graph](docs/architecture.md)
|
||||||
- [Synthetic diagnostics protocol v1](docs/synthetic-diagnostics-v1.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)
|
- [Simulation definitions and state](docs/simulation.md)
|
||||||
- [Vehicle-profile schema v1 and usage](docs/vehicle-profile-schema-v1.md)
|
- [Vehicle-profile schema v1 and usage](docs/vehicle-profile-schema-v1.md)
|
||||||
- [Build, tests and native smoke guide](docs/build-and-test.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-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)
|
- [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
|
- [Orchestrator-owned roadmap](prompts/ROADMAP.md) and
|
||||||
[orchestration state](prompts/STATE.md)
|
[orchestration state](prompts/STATE.md)
|
||||||
|
|
||||||
Handoffs are manual. Step-03 worker completion does not mean orchestrator
|
Handoffs are manual. Worker completion does not mean orchestrator acceptance or
|
||||||
acceptance or authorize Step-04.
|
authorize Step-05.
|
||||||
|
|
|
||||||
|
|
@ -1,17 +1,22 @@
|
||||||
# AutoForge documentation
|
# AutoForge documentation
|
||||||
|
|
||||||
The implemented scope includes the accepted Step-01/Step-01A foundation,
|
The implemented scope includes the accepted Step-01/Step-01A foundation,
|
||||||
accepted Step-02/Step-02A vehicle-profile metadata, and the Step-03 synthetic
|
accepted Step-02/Step-02A vehicle-profile metadata, the Step-03 synthetic
|
||||||
diagnostic vertical slice with the Step-03A integrity/verification corrections.
|
diagnostic vertical slice with its integrity corrections, and the Step-04
|
||||||
Worker completion/verification is reported separately from manual orchestrator
|
synthetic dynamics implementation and Step-04A corrective work. Step-04A
|
||||||
acceptance; Step-03 is not accepted until that review.
|
Release regression and native workflow smoke passed; manual orchestrator
|
||||||
|
acceptance of Step-04 remains pending.
|
||||||
|
|
||||||
- [Architecture](architecture.md): actual nine-project graph, responsibilities,
|
- [Architecture](architecture.md): actual nine-project graph, responsibilities,
|
||||||
route ownership and provider/reference boundaries.
|
route ownership and provider/reference boundaries.
|
||||||
- [Synthetic diagnostics protocol v1](synthetic-diagnostics-v1.md): request and
|
- [Synthetic diagnostics protocol v1](synthetic-diagnostics-v1.md): request and
|
||||||
response envelope, outcomes, validation, logical timing and bounded trace.
|
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
|
- [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):
|
- [ADR-0001: Headless .NET 10 foundation](adr-0001-headless-foundation.md):
|
||||||
historical foundation decisions; dual-shell/deferred-host decision superseded.
|
historical foundation decisions; dual-shell/deferred-host decision superseded.
|
||||||
- [ADR-0002: Single native shell and feature slices](adr-0002-single-shell-vsa.md):
|
- [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-02](../prompts/Step-02-Report.md),
|
||||||
[Step-02A](../prompts/Step-02A-Report.md) and
|
[Step-02A](../prompts/Step-02A-Report.md) and
|
||||||
[Step-03 worker report](../prompts/Step-03-Report.md),
|
[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.
|
Handoffs are manual; acceptance remains the orchestrator's responsibility.
|
||||||
|
|
|
||||||
|
|
@ -37,10 +37,10 @@ All nine projects are in [AutoForge.slnx](../src/AutoForge.slnx):
|
||||||
|
|
||||||
| Project | Target and responsibility | Project references |
|
| 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 |
|
| [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 contracts, synthetic protocol v1 codec/client, typed operation results and bounded trace | Core |
|
| [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 data-driven virtual modules, isolated state, provider factory and deterministic in-process transport | Core, Diagnostics |
|
| [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 feature slices | 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 |
|
| [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 |
|
| [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 |
|
| [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
|
Components has no AutoForge project dependency. UI never references Client or
|
||||||
Simulation. Application never references Simulation, UI, Components or Client.
|
Simulation. Application never references Simulation, UI, Components or Client.
|
||||||
Core, Diagnostics and Simulation do not reference Application/UI/Client.
|
Core, Diagnostics and Simulation do not reference Application/UI/Client.
|
||||||
Simulation's internal test oracle is available only to the integration-test
|
The static provider's DTC oracle is limited to IntegrationTests; the fixed-step
|
||||||
assembly; it is not part of the production diagnostics or UI contract. There are
|
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
|
no cycles or production-to-test edges. Tests render UI directly and never
|
||||||
reference or launch Client.
|
reference or launch Client.
|
||||||
|
|
||||||
The Client composes one `SimulatedDiagnosticTransportFactory` with both truck and
|
The Client composes the unchanged static `SimulatedDiagnosticTransportFactory`
|
||||||
orchard definitions. `AddAutoForgeDiagnostics` registers that factory's target
|
and the separate `DynamicsDiagnosticTransportFactory`. The static provider
|
||||||
descriptor and operational transport from the same registration data. Target
|
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
|
metadata resolution remains a separate, metadata-only action. The profile
|
||||||
catalog is process-local; importing does not select a revision or open a session.
|
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
|
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 |
|
| `/` | `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 |
|
| `/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 |
|
| `/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 |
|
| 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)
|
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
|
The feature-local target-selection view model adapts explicit input to the
|
||||||
existing Application resolver. The same target resolver is populated from the
|
existing Application resolver. The same target resolver is populated from the
|
||||||
diagnostic factories' descriptors, so `/execution-targets` shows the actual
|
diagnostic factories' descriptors, so `/execution-targets` shows the actual
|
||||||
provider metadata without implying connection. Diagnostic sessions bind the
|
provider metadata without implying connection. Static sessions bind the exact
|
||||||
exact profile revision, vehicle, target and deterministic profile-configuration
|
profile revision, vehicle and target. Dynamics identity additionally binds the
|
||||||
identifier. Closing releases per-session state; resetting closes and opens a
|
versioned configuration fingerprint and a separate operational run/session
|
||||||
new session at the definition's configured initial state.
|
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
|
The Application session use case keeps low-level `clear.dtcs` acknowledgement
|
||||||
distinct from verified clear. It performs a fresh read and only marks the
|
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.
|
unchanged.
|
||||||
|
|
||||||
`AutoForge.Diagnostics` defines provider-neutral endpoint, transport, session,
|
`AutoForge.Diagnostics` defines provider-neutral endpoint, transport, session,
|
||||||
protocol-client, logical-clock, operation-result and trace contracts. Its
|
protocol-client, logical-clock, operation-result, dynamics-control and trace
|
||||||
synthetic protocol v1 encodes each request and decodes each actual response
|
contracts. Protocol v1 remains the static diagnostics wire path. Protocol v2 is
|
||||||
through the transport interface. `AutoForge.Simulation` supplies the only
|
an explicit dynamic telemetry path with a separate run/configuration-bound
|
||||||
operational implementation in this milestone. Module IDs, endpoint addresses,
|
payload; neither path dispatches through the other provider. Simulation owns
|
||||||
identities, supported synthetic services, initial DTC state, static signals and
|
the numerical engine and diagnostic transports. Application owns configuration
|
||||||
deterministic faults come from validated source-controlled definitions, not
|
import/export/catalog and session coordination; UI consumes shared controls and
|
||||||
hard-coded application roles or profile capability claims. Details and honest
|
diagnostic results only. The profile/module IDs, endpoint addresses and
|
||||||
limitations are in the [protocol guide](synthetic-diagnostics-v1.md) and
|
identities are validated against the exact selected profile. See the [v1
|
||||||
[simulation guide](simulation.md).
|
guide](synthetic-diagnostics-v1.md), [v2 guide](synthetic-diagnostics-v2.md)
|
||||||
|
and [simulation guide](simulation.md).
|
||||||
|
|
||||||
## Honest limitations and safety boundaries
|
## Honest limitations and safety boundaries
|
||||||
|
|
||||||
Implemented diagnostics are synthetic, in-process and Simulation-only. They
|
Implemented diagnostics and dynamics are synthetic, in-process and
|
||||||
prove the encoded request/response path and deterministic module behavior, not
|
Simulation-only. They prove encoded request/response handling and deterministic
|
||||||
vehicle compatibility, access, authenticity, real capture or permission.
|
model behavior, not vehicle compatibility, access, authenticity, real capture,
|
||||||
Telemetry is a static synthetic state snapshot, not vehicle dynamics. Virtual
|
manufacturer accuracy or permission. Static v1 signals remain static. Protocol
|
||||||
DTC clear mutates only the selected in-memory virtual module/session and has no
|
v2 dynamic telemetry is computed from an explicitly configured simplified
|
||||||
physical write path. Acknowledgement alone is not evidence that virtual state
|
model; it is not real sensor data or validated prediction. Virtual DTC clear
|
||||||
changed. No real vehicle, physical adapter, replay provider,
|
mutates only selected in-memory module/session state and has no physical write
|
||||||
programming, calibration values, backups, AI, persistence or cloud service is
|
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
|
implemented. A `SUPPORTED` declaration, `VERIFIED` provenance label, physical
|
||||||
metadata kind or calibration reference does not implement or authorize an
|
metadata kind or calibration reference does not implement or authorize an
|
||||||
operation.
|
operation.
|
||||||
|
|
|
||||||
|
|
@ -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
|
identity remains covered by real-DI rendered tests because the shipped native
|
||||||
configuration has no fault selector for that scenario.
|
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
|
## Native synthetic diagnostics smoke
|
||||||
|
|
||||||
Launch the actual Windows Client and visit `/diagnostics`:
|
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.
|
metadata, not connection, compatibility, a working service or authorization.
|
||||||
- Data remains in memory for the process only. JSON import/export does not write
|
- Data remains in memory for the process only. JSON import/export does not write
|
||||||
files or timestamps implicitly.
|
files or timestamps implicitly.
|
||||||
- Simulation uses the separate [synthetic protocol](synthetic-diagnostics-v1.md)
|
- Static synthetic diagnostics use the [protocol v1 guide](synthetic-diagnostics-v1.md)
|
||||||
and [definition guide](simulation.md). It is not a real vehicle adapter,
|
and [simulation definitions](simulation.md); dynamic output uses the separate
|
||||||
dynamics model, telemetry capture, replay provider, calibration/firmware
|
documented protocol-v2 provider. Neither is a real vehicle adapter, telemetry
|
||||||
editor or hardware write path.
|
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.
|
||||||
|
|
|
||||||
|
|
@ -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
|
These are reproducible fixture values, not dynamic model output, current sensor
|
||||||
data, a vehicle capture, compatibility evidence or operational advice. Unknown
|
data, a vehicle capture, compatibility evidence or operational advice. Unknown
|
||||||
values remain unknown; there is no generated motion, fuel, road-load or
|
values remain unknown. This static provider does not generate motion, fuel,
|
||||||
scenario physics.
|
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:<lowercase hex>` 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
|
## Reproducible faults and lifecycle
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -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
|
OBD-II, a manufacturer protocol, or a claim of vehicle compatibility. No
|
||||||
physical transport or vehicle operation is implemented.
|
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:
|
The actual capability path is:
|
||||||
|
|
||||||
1. `SyntheticDiagnosticProtocolClient` builds and encodes a request.
|
1. `SyntheticDiagnosticProtocolClient` builds and encodes a request.
|
||||||
|
|
|
||||||
|
|
@ -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:<hex>` 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.
|
||||||
|
|
@ -3,12 +3,12 @@
|
||||||
## Status and authority
|
## Status and authority
|
||||||
|
|
||||||
- Initialized: 2026-10-28.
|
- Initialized: 2026-10-28.
|
||||||
- Current phase: corrected synthetic diagnostics accepted; deterministic dynamics next.
|
- Current phase: corrected deterministic dynamics accepted; first bounded live dashboard next.
|
||||||
- Active assignment: [Step-04](Step-04.md), ready for manual worker execution.
|
- Active assignment: [Step-05](Step-05.md), ready for manual worker execution.
|
||||||
- Last accepted milestone: Step-03 with Step-03A/Step-03B, accepted 2026-10-28.
|
- Last accepted milestone: Step-04 with Step-04A/Step-04B, accepted 2026-10-28.
|
||||||
- Last accepted correction: Step-03B; all Step-03 findings closed.
|
- Last accepted correction: Step-04B; all Step-04 findings closed.
|
||||||
- Outstanding corrections: none.
|
- 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).
|
- Current state and handoff: [STATE.md](STATE.md).
|
||||||
- Authority: the master charter, repository/handoff amendment, and the owner's
|
- Authority: the master charter, repository/handoff amendment, and the owner's
|
||||||
2026-10-28 architectural realignment. The latest decision cancels the dual-shell
|
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
|
before assigning the next major step. Do not use the superseded numeric-dot
|
||||||
prompt/report naming convention.
|
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
|
## Architecture baseline
|
||||||
|
|
||||||
### Existing accepted foundation, preserved
|
### 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
|
identity availability. The corrected Step-03 milestone is accepted. Worker
|
||||||
verification now covers 111 unit and 72 integration cases (183 total).
|
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
|
a fixed-step virtual clock. Shared platform-neutral configuration/control contracts
|
||||||
belong in Core or an appropriate existing shared-contract location; Application
|
belong in Core or an appropriate existing shared-contract location; Application
|
||||||
still does not depend on Simulation implementation. No additional project is
|
still does not depend on Simulation implementation. No additional project is
|
||||||
assigned. Static synthetic diagnostics remain available, separate from an
|
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:
|
Planned dependency flow:
|
||||||
|
|
||||||
|
|
@ -247,9 +304,11 @@ UI unrestricted programming authority.
|
||||||
|
|
||||||
## Milestones and acceptance gates
|
## Milestones and acceptance gates
|
||||||
|
|
||||||
Step-01, Step-01A, corrected Step-02 and corrected Step-03 are accepted. Original
|
Step-01, Step-01A, corrected Step-02 and corrected Step-03 remain accepted.
|
||||||
and corrective reports remain historical evidence. Step-04 is the only active
|
Corrected Step-04 is accepted with original and corrective evidence preserved.
|
||||||
assignment. Dynamics and later capabilities remain unimplemented.
|
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
|
Dependencies indicate acceptance prerequisites, not permission for automatic
|
||||||
handoff. Later assignments refine these scopes using actual implementation
|
handoff. Later assignments refine these scopes using actual implementation
|
||||||
evidence; they must not silently discard required capabilities.
|
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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
||||||
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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/
|
driven physics. Preserve static v1 diagnostics and use an explicit versioned/
|
||||||
negotiated dynamic telemetry extension with separate model and diagnostic time.
|
negotiated dynamic telemetry extension with separate model and diagnostic time.
|
||||||
Report mathematical assumptions and repeatability tolerances.
|
Report mathematical assumptions and repeatability tolerances.
|
||||||
- **05:** extend the already established UI feature pages with reusable data-bound
|
- **04A correction:** reject invalid references through normal typed/UI failures,
|
||||||
gauges, settings, profile/module selection, connection state and diagnostics.
|
enforce initial and runtime drivetrain consistency rather than independent RPM
|
||||||
Client remains thin; application slices coordinate in-process capabilities.
|
clamping/false locked flags, and make progress/terminal failures/async ownership
|
||||||
Use ordinary packaged RCL/feature composition, not unsupported arbitrary assembly
|
truthful. Add independent force/boundary checks and controlled pacing/lifecycle
|
||||||
loading. Missing MAUI workloads are blockers, not permission to substitute a
|
tests; preserve the existing warm/45-MPH/full-hold/stop numerical gates.
|
||||||
WebAssembly/web host. Native adapters do not require a separate backend.
|
- **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,
|
- **06:** versioned recording format, module/source/units/time/quality metadata,
|
||||||
raw plus decoded retention, interrupted/corrupt session handling, replay
|
raw plus decoded retention, interrupted/corrupt session handling, replay
|
||||||
play/pause/stop/restart/seek/navigation/speed. Acquisition must not depend on
|
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
|
- Source counts, graph and existing restore/Release/native artifacts corroborate
|
||||||
that evidence; the orchestrator did not run builds/tests or launch the app.
|
that evidence; the orchestrator did not run builds/tests or launch the app.
|
||||||
- Prepared [Step-04](Step-04.md); no Step-03C is required.
|
- 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
|
### Remaining
|
||||||
|
|
||||||
- Worker execution of Step-04, then manual review of numeric dynamics, lifecycle,
|
- Worker execution of Step-05, then one consolidated review against its frozen
|
||||||
configuration, wire integration and native evidence. Complete Step-04A corrections
|
contract matrix and shared quality gate. Complete Step-05A only for genuine
|
||||||
if needed before Step-05.
|
unmet requirements/regressions before Step-06; do not expand criteria in review.
|
||||||
- Profile/module metadata, synthetic virtual-module communication and static
|
- Profile/module metadata, synthetic virtual-module communication and deterministic
|
||||||
diagnostics are accepted; dynamics and later capabilities
|
dynamics/v2 are accepted. Dashboard and later capabilities remain planned.
|
||||||
remain planned. Preserve the complete sequence and safety gates.
|
Preserve the complete sequence/safety gates.
|
||||||
|
|
||||||
### Known blockers and uncertainties
|
### 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:
|
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
|
- 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
|
- 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
|
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.
|
Git setting was changed; the existing LF-to-CRLF notice remains non-blocking.
|
||||||
- Corrected discovery/identity contracts are documented. Step-04 must align
|
- The pending-transition rejection policy is now documented. Step-05 must align
|
||||||
acceptance lifecycle text while preserving the original 161-case and corrective
|
remaining acceptance-pending lifecycle text while preserving the original and
|
||||||
175-/183-case reports as distinct historical evidence.
|
corrective numerical/native reports, including the 207-case Step-04B run.
|
||||||
|
|
||||||
No major environment installation, update, repair or rollback is automatically
|
No major environment installation, update, repair or rollback is automatically
|
||||||
authorized. Physical definitions/access and programming approval remain future gates.
|
authorized. Physical definitions/access and programming approval remain future gates.
|
||||||
|
|
|
||||||
259
prompts/STATE.md
259
prompts/STATE.md
|
|
@ -5,19 +5,21 @@
|
||||||
| Field | Value |
|
| Field | Value |
|
||||||
|---|---|
|
|---|---|
|
||||||
| Updated | 2026-10-28 |
|
| Updated | 2026-10-28 |
|
||||||
| Phase | Corrected Step-03 accepted; deterministic vehicle dynamics next |
|
| Phase | Corrected dynamics accepted; first bounded live dashboard next |
|
||||||
| Active step | Step-04 - Deterministic vehicle dynamics and scenario execution |
|
| Active step | Step-05 - Configurable numeric/bar live dashboard |
|
||||||
| Assignment | [Step-04.md](Step-04.md) |
|
| Assignment | [Step-05.md](Step-05.md) |
|
||||||
| Assignment status | READY FOR WORKER / AWAITING MANUAL HANDOFF |
|
| Assignment status | READY FOR WORKER / AWAITING MANUAL HANDOFF |
|
||||||
| Expected worker report | `prompts/Step-04-Report.md` - not yet created |
|
| Expected worker report | `prompts/Step-05-Report.md` - not yet created |
|
||||||
| Last accepted correction | Step-03B - accepted 2026-10-28 |
|
| Last accepted correction | Step-04B - accepted 2026-10-28 |
|
||||||
| Last accepted major milestone | Step-03 with Step-03A/Step-03B - accepted 2026-10-28 |
|
| Last accepted major milestone | Step-04 with Step-04A/Step-04B - accepted 2026-10-28 |
|
||||||
| Outstanding corrections | None |
|
| Outstanding corrections | None |
|
||||||
| Step-02 status | ACCEPTED after Step-02A |
|
| Step-02 status | ACCEPTED after Step-02A |
|
||||||
| Step-03 status | ACCEPTED after Step-03A/Step-03B |
|
| Step-03 status | ACCEPTED after Step-03A/Step-03B |
|
||||||
| Step-04 status | READY FOR WORKER |
|
| Step-04 status | ACCEPTED after Step-04A/Step-04B |
|
||||||
| Worker execution | Step-03B manually completed; Step-04 not invoked |
|
| Step-04A review | All original corrective criteria closed with Step-04B |
|
||||||
| Immediate next action | User manually directs the worker to execute Step-04 only |
|
| 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 |
|
| Next orchestrator action | After manual return, inspect the assignment, report, implementation, tests, Git changes, documentation and recorded command evidence |
|
||||||
|
|
||||||
## Repository baseline at initialization
|
## 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
|
Step-04 is prepared against the actual accepted interfaces. It assigns a separate
|
||||||
explicit dynamics provider/configuration, fixed-step clock/model/scenario controls,
|
explicit dynamics provider/configuration, fixed-step clock/model/scenario controls,
|
||||||
configuration-preserving reset and versioned dynamic telemetry through diagnostics.
|
configuration-preserving reset and versioned dynamic telemetry through diagnostics.
|
||||||
There is no dynamics implementation yet, no extra executable/project assigned,
|
The dynamics implementation now exists under review, still without any extra
|
||||||
and no physical integration or calibration programming.
|
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
|
## 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
|
- Step-02 worker reports no workload-changing command was invoked; prior incident
|
||||||
remains historical and does not authorize future installation/update/rollback.
|
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.
|
- 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
|
- Step-03 R-01/R-02/R-03/R-04 remain closed; preserve all correction invariants.
|
||||||
currently identified. Preserve all correction invariants.
|
- Step-04 reference/coupling/progress/failure/UI/owner fixes are accepted with
|
||||||
- Step-04 must align remaining acceptance-pending lifecycle text without altering
|
Step-04B. No blocking Step-05 prerequisite is identified. Preserve the 190-/
|
||||||
original 161-case or corrective 175-/183-case reports.
|
202-/207-case reports and original numerical/native evidence distinctly.
|
||||||
- Profile metadata/UI and synthetic virtual-module diagnostics/static signals
|
- Profile metadata/UI, synthetic diagnostics and deterministic dynamics/v2 are
|
||||||
are accepted. Full dynamics, replay, calibration
|
accepted. Dashboard, replay, calibration
|
||||||
values, persistence, AI and physical hardware operations remain unimplemented.
|
values, persistence, AI and physical hardware operations remain unimplemented.
|
||||||
- No application build or test has been executed by the orchestrator.
|
- No application build or test has been executed by the orchestrator.
|
||||||
|
|
||||||
## Review and progression gate
|
## 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,
|
assignment, worker report, actual code/tests, dependency graph, Git changes,
|
||||||
README/docs, and recorded build/test evidence. Do not accept solely on a success
|
README/docs, and recorded build/test evidence. Do not accept solely on a success
|
||||||
claim; do not claim independent runtime verification.
|
claim; do not claim independent runtime verification.
|
||||||
|
|
||||||
- Inspect coupled physics/numeric thresholds, fixed clock/lifecycle/pacing,
|
- Inspect pure gauge projections/states, validated definitions, one session-owned
|
||||||
run/configuration identity and reset, strict static/dynamic wire integration,
|
feed, independent visibility/acquisition, source replacement and real UI/native
|
||||||
independent oracle and real application/UI/native evidence.
|
evidence. Do not add deferred persistence/charts/conversion requirements.
|
||||||
- If accepted: record evidence, update roadmap/state, create Step-05 and stop for
|
- If accepted: update roadmap/state, create Step-06 and stop for manual handoff.
|
||||||
manual handoff. Do not execute it.
|
- If deficient: issue narrowly scoped Step-05A only for a material unmet contract/
|
||||||
- If deficient: create `Step-04A.md` with measurable corrections and matching
|
regression, then stop. Planned new features are not corrections.
|
||||||
report requirements, update state and stop. Do not advance to Step-05.
|
|
||||||
- If blocked: retain the active step, document the prerequisite and required
|
- If blocked: retain the active step, document the prerequisite and required
|
||||||
worker evidence; do not advance or mark unexecuted checks as successful.
|
worker evidence; do not advance or mark unexecuted checks as successful.
|
||||||
- Never create the next major assignment while acceptance or corrections are open.
|
- 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 | 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 | 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 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
|
## Manual handoff instruction
|
||||||
|
|
||||||
Provide [Step-04.md](Step-04.md) to the separate worker and request execution
|
Provide [Step-05.md](Step-05.md) and the shared
|
||||||
of that assignment only. The worker must produce `prompts/Step-04-Report.md`
|
[worker gate](WORKER-QUALITY-GATE.md) to the separate worker and request execution
|
||||||
and stop for review. Do not begin Step-05.
|
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
|
Return manually to the orchestrator for review. Reports, including final chat
|
||||||
reports, must follow the single plain triple-backtick copy-window requirement.
|
reports, must follow the single plain triple-backtick copy-window requirement.
|
||||||
|
|
|
||||||
|
|
@ -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.
|
||||||
|
```
|
||||||
|
|
@ -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.
|
||||||
|
```
|
||||||
|
|
@ -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.
|
||||||
|
|
@ -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.
|
||||||
|
```
|
||||||
|
|
@ -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.
|
||||||
|
|
@ -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.
|
||||||
|
|
@ -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.
|
||||||
|
|
@ -1,6 +1,7 @@
|
||||||
using AutoForge.Application.ExecutionTargets;
|
using AutoForge.Application.ExecutionTargets;
|
||||||
using AutoForge.Application.Features.Vehicles.Profiles;
|
using AutoForge.Application.Features.Vehicles.Profiles;
|
||||||
using AutoForge.Core.ExecutionTargets;
|
using AutoForge.Core.ExecutionTargets;
|
||||||
|
using AutoForge.Core.Simulation;
|
||||||
using AutoForge.Core.Vehicles;
|
using AutoForge.Core.Vehicles;
|
||||||
using AutoForge.Diagnostics;
|
using AutoForge.Diagnostics;
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
|
@ -13,7 +14,8 @@ public enum DiagnosticSessionFailure
|
||||||
UnsupportedTargetKind,
|
UnsupportedTargetKind,
|
||||||
DefinitionNotFound,
|
DefinitionNotFound,
|
||||||
InvalidDefinition,
|
InvalidDefinition,
|
||||||
SessionConflict
|
SessionConflict,
|
||||||
|
DynamicsCapabilityUnavailable
|
||||||
}
|
}
|
||||||
|
|
||||||
public sealed class DiagnosticSessionException(
|
public sealed class DiagnosticSessionException(
|
||||||
|
|
@ -53,6 +55,13 @@ public interface IDiagnosticSessionService
|
||||||
string providerIdentifier,
|
string providerIdentifier,
|
||||||
ExecutionTargetKind targetKind,
|
ExecutionTargetKind targetKind,
|
||||||
CancellationToken cancellationToken = default);
|
CancellationToken cancellationToken = default);
|
||||||
|
Task<DiagnosticSession> OpenDynamicsAsync(
|
||||||
|
string profileIdentifier,
|
||||||
|
int profileRevision,
|
||||||
|
string providerIdentifier,
|
||||||
|
ExecutionTargetKind targetKind,
|
||||||
|
DynamicsConfiguration configuration,
|
||||||
|
CancellationToken cancellationToken = default);
|
||||||
Task<DiagnosticSession> ResetAsync(DiagnosticSession session, CancellationToken cancellationToken = default);
|
Task<DiagnosticSession> ResetAsync(DiagnosticSession session, CancellationToken cancellationToken = default);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -61,12 +70,16 @@ public sealed class DiagnosticSession(
|
||||||
DiagnosticSessionIdentity identity,
|
DiagnosticSessionIdentity identity,
|
||||||
IDiagnosticProtocolClient protocol,
|
IDiagnosticProtocolClient protocol,
|
||||||
IDiagnosticTransport transport,
|
IDiagnosticTransport transport,
|
||||||
CancellationTokenSource lifetime) : IAsyncDisposable
|
CancellationTokenSource lifetime,
|
||||||
|
DynamicsConfiguration? dynamicsConfiguration = null,
|
||||||
|
IDynamicsControl? dynamicsControl = null) : IAsyncDisposable
|
||||||
{
|
{
|
||||||
private int _closed;
|
private int _closed;
|
||||||
|
|
||||||
public VehicleProfile Profile { get; } = profile;
|
public VehicleProfile Profile { get; } = profile;
|
||||||
public DiagnosticSessionIdentity Identity { get; } = identity;
|
public DiagnosticSessionIdentity Identity { get; } = identity;
|
||||||
|
public DynamicsConfiguration? DynamicsConfiguration { get; } = dynamicsConfiguration;
|
||||||
|
public IDynamicsControl? DynamicsControl { get; } = dynamicsControl;
|
||||||
public IReadOnlyList<DiagnosticEndpoint> ExpectedEndpoints => protocol.ExpectedEndpoints;
|
public IReadOnlyList<DiagnosticEndpoint> ExpectedEndpoints => protocol.ExpectedEndpoints;
|
||||||
public DiagnosticTraceSnapshot Trace => protocol.Trace;
|
public DiagnosticTraceSnapshot Trace => protocol.Trace;
|
||||||
public bool IsClosed => Volatile.Read(ref _closed) != 0;
|
public bool IsClosed => Volatile.Read(ref _closed) != 0;
|
||||||
|
|
@ -136,6 +149,11 @@ public sealed class DiagnosticSession(
|
||||||
if (Interlocked.Exchange(ref _closed, 1) == 0)
|
if (Interlocked.Exchange(ref _closed, 1) == 0)
|
||||||
{
|
{
|
||||||
lifetime.Cancel();
|
lifetime.Cancel();
|
||||||
|
if (DynamicsControl is not null)
|
||||||
|
{
|
||||||
|
await DynamicsControl.DisposeAsync().ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
await transport.DisposeAsync().ConfigureAwait(false);
|
await transport.DisposeAsync().ConfigureAwait(false);
|
||||||
lifetime.Dispose();
|
lifetime.Dispose();
|
||||||
}
|
}
|
||||||
|
|
@ -165,6 +183,7 @@ public sealed class DiagnosticSessionService : IDiagnosticSessionService
|
||||||
private readonly IReadOnlyList<IDiagnosticTransportFactory> _factories;
|
private readonly IReadOnlyList<IDiagnosticTransportFactory> _factories;
|
||||||
private readonly Func<IDiagnosticLogicalClock> _logicalClockFactory;
|
private readonly Func<IDiagnosticLogicalClock> _logicalClockFactory;
|
||||||
private long _sessionSequence;
|
private long _sessionSequence;
|
||||||
|
private long _runSequence;
|
||||||
|
|
||||||
public DiagnosticSessionService(
|
public DiagnosticSessionService(
|
||||||
IVehicleProfileService profiles,
|
IVehicleProfileService profiles,
|
||||||
|
|
@ -207,6 +226,13 @@ public sealed class DiagnosticSessionService : IDiagnosticSessionService
|
||||||
$"No diagnostic transport is registered for provider '{target.ProviderIdentifier}'.");
|
$"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 sequence = Interlocked.Increment(ref _sessionSequence);
|
||||||
var identity = new DiagnosticSessionIdentity(
|
var identity = new DiagnosticSessionIdentity(
|
||||||
$"diagnostic-session-{sequence:D6}",
|
$"diagnostic-session-{sequence:D6}",
|
||||||
|
|
@ -251,12 +277,84 @@ public sealed class DiagnosticSessionService : IDiagnosticSessionService
|
||||||
return Task.FromResult(new DiagnosticSession(profile, identity, protocol, transport, lifetime));
|
return Task.FromResult(new DiagnosticSession(profile, identity, protocol, transport, lifetime));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public Task<DiagnosticSession> 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<DiagnosticSession> ResetAsync(
|
public async Task<DiagnosticSession> ResetAsync(
|
||||||
DiagnosticSession session,
|
DiagnosticSession session,
|
||||||
CancellationToken cancellationToken = default)
|
CancellationToken cancellationToken = default)
|
||||||
{
|
{
|
||||||
ArgumentNullException.ThrowIfNull(session);
|
ArgumentNullException.ThrowIfNull(session);
|
||||||
var identity = session.Identity;
|
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);
|
await session.DisposeAsync().ConfigureAwait(false);
|
||||||
return await OpenAsync(
|
return await OpenAsync(
|
||||||
identity.ProfileIdentifier,
|
identity.ProfileIdentifier,
|
||||||
|
|
|
||||||
|
|
@ -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<DynamicsConfigurationReference> 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<string, DynamicsConfiguration> _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<DynamicsConfiguration>(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<DynamicsConfigurationReference> 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<string>(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<string>(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<IDynamicsConfigurationService, DynamicsConfigurationService>();
|
||||||
|
}
|
||||||
|
|
||||||
|
return services;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -1,6 +1,7 @@
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
using AutoForge.Diagnostics;
|
using AutoForge.Diagnostics;
|
||||||
using AutoForge.Application.Features.Vehicles.Profiles;
|
using AutoForge.Application.Features.Vehicles.Profiles;
|
||||||
|
using AutoForge.Application.Features.Vehicles.Simulation;
|
||||||
using AutoForge.Application.Features.Vehicles.Diagnostics;
|
using AutoForge.Application.Features.Vehicles.Diagnostics;
|
||||||
using AutoForge.Simulation;
|
using AutoForge.Simulation;
|
||||||
using AutoForge.UI;
|
using AutoForge.UI;
|
||||||
|
|
@ -18,7 +19,11 @@ public static class MauiProgram
|
||||||
|
|
||||||
builder.Services.AddAutoForgeVehicleProfiles();
|
builder.Services.AddAutoForgeVehicleProfiles();
|
||||||
builder.Services.AddAutoForgeDiagnostics(
|
builder.Services.AddAutoForgeDiagnostics(
|
||||||
[new SimulatedDiagnosticTransportFactory(SyntheticDiagnosticExamples.CreateDefinitions())]);
|
[
|
||||||
|
new SimulatedDiagnosticTransportFactory(SyntheticDiagnosticExamples.CreateDefinitions()),
|
||||||
|
new DynamicsDiagnosticTransportFactory(SyntheticDiagnosticExamples.CreateDefinitions())
|
||||||
|
]);
|
||||||
|
builder.Services.AddAutoForgeDynamicsConfigurations();
|
||||||
builder.Services.AddAutoForgeUi();
|
builder.Services.AddAutoForgeUi();
|
||||||
builder.Services.AddMauiBlazorWebView();
|
builder.Services.AddMauiBlazorWebView();
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -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<EngineTorquePoint> engineTorqueCurve,
|
||||||
|
IReadOnlyList<double> forwardGearRatios,
|
||||||
|
IReadOnlyList<double> upshiftSpeedsRpm,
|
||||||
|
IReadOnlyList<double> 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<EngineTorquePoint> EngineTorqueCurve { get; }
|
||||||
|
public IReadOnlyList<double> ForwardGearRatios { get; }
|
||||||
|
public IReadOnlyList<double> UpshiftSpeedsRpm { get; }
|
||||||
|
public IReadOnlyList<double> 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<EngineTorquePoint> CopyCurve(IReadOnlyList<EngineTorquePoint> 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<double> CopyDescendingRatios(IReadOnlyList<double> 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<double> CopyShiftThresholds(IReadOnlyList<double> 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<DynamicsScenarioPhase> 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<DynamicsScenarioPhase> 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);
|
||||||
|
}
|
||||||
|
|
@ -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);
|
||||||
|
|
@ -2,6 +2,7 @@ using System.Collections.ObjectModel;
|
||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
using System.Text.RegularExpressions;
|
using System.Text.RegularExpressions;
|
||||||
using AutoForge.Core.ExecutionTargets;
|
using AutoForge.Core.ExecutionTargets;
|
||||||
|
using AutoForge.Core.Simulation;
|
||||||
using AutoForge.Core.Vehicles;
|
using AutoForge.Core.Vehicles;
|
||||||
|
|
||||||
namespace AutoForge.Diagnostics;
|
namespace AutoForge.Diagnostics;
|
||||||
|
|
@ -26,7 +27,9 @@ public sealed class DiagnosticSessionIdentity
|
||||||
string profileIdentifier,
|
string profileIdentifier,
|
||||||
int profileRevision,
|
int profileRevision,
|
||||||
string vehicleIdentifier,
|
string vehicleIdentifier,
|
||||||
ExecutionTargetDescriptor target)
|
ExecutionTargetDescriptor target,
|
||||||
|
string? dynamicsConfigurationIdentifier = null,
|
||||||
|
string? dynamicsRunIdentifier = null)
|
||||||
{
|
{
|
||||||
SessionIdentifier = Require(sessionIdentifier, nameof(sessionIdentifier));
|
SessionIdentifier = Require(sessionIdentifier, nameof(sessionIdentifier));
|
||||||
ProfileIdentifier = Require(profileIdentifier, nameof(profileIdentifier));
|
ProfileIdentifier = Require(profileIdentifier, nameof(profileIdentifier));
|
||||||
|
|
@ -36,9 +39,22 @@ public sealed class DiagnosticSessionIdentity
|
||||||
}
|
}
|
||||||
|
|
||||||
ProfileRevision = profileRevision;
|
ProfileRevision = profileRevision;
|
||||||
ConfigurationIdentifier = $"profile:{ProfileIdentifier}@revision:{ProfileRevision}";
|
|
||||||
VehicleIdentifier = Require(vehicleIdentifier, nameof(vehicleIdentifier));
|
VehicleIdentifier = Require(vehicleIdentifier, nameof(vehicleIdentifier));
|
||||||
Target = target ?? throw new ArgumentNullException(nameof(target));
|
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; }
|
public string SessionIdentifier { get; }
|
||||||
|
|
@ -47,6 +63,8 @@ public sealed class DiagnosticSessionIdentity
|
||||||
public string ConfigurationIdentifier { get; }
|
public string ConfigurationIdentifier { get; }
|
||||||
public string VehicleIdentifier { get; }
|
public string VehicleIdentifier { get; }
|
||||||
public ExecutionTargetDescriptor Target { get; }
|
public ExecutionTargetDescriptor Target { get; }
|
||||||
|
public string? DynamicsConfigurationIdentifier { get; }
|
||||||
|
public string? DynamicsRunIdentifier { get; }
|
||||||
|
|
||||||
private static string Require(string value, string parameterName)
|
private static string Require(string value, string parameterName)
|
||||||
{
|
{
|
||||||
|
|
@ -96,6 +114,30 @@ public interface IDiagnosticTransportFactory
|
||||||
IDiagnosticTransport OpenTransport(VehicleProfile profile, DiagnosticSessionIdentity identity);
|
IDiagnosticTransport OpenTransport(VehicleProfile profile, DiagnosticSessionIdentity identity);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public interface IDynamicsControl : IAsyncDisposable
|
||||||
|
{
|
||||||
|
DynamicsRunStatus Status { get; }
|
||||||
|
double PacingFactor { get; }
|
||||||
|
Task<DynamicsRunStatus> StartAsync(CancellationToken cancellationToken = default);
|
||||||
|
Task<DynamicsRunStatus> PauseAsync(CancellationToken cancellationToken = default);
|
||||||
|
Task<DynamicsRunStatus> ResumeAsync(CancellationToken cancellationToken = default);
|
||||||
|
Task<DynamicsRunStatus> StopAsync(CancellationToken cancellationToken = default);
|
||||||
|
Task<DynamicsRunStatus> ResetAsync(CancellationToken cancellationToken = default);
|
||||||
|
Task<DynamicsRunStatus> StepAsync(int stepCount = 1, CancellationToken cancellationToken = default);
|
||||||
|
Task<DynamicsRunStatus> SetPacingFactorAsync(double factor, CancellationToken cancellationToken = default);
|
||||||
|
Task<DynamicsRunStatus> 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
|
public enum DiagnosticProviderFailure
|
||||||
{
|
{
|
||||||
ConfigurationNotFound,
|
ConfigurationNotFound,
|
||||||
|
|
@ -358,18 +400,36 @@ public sealed record DiagnosticSignal(
|
||||||
string Unit,
|
string Unit,
|
||||||
SignalQuality Quality,
|
SignalQuality Quality,
|
||||||
long LogicalTimeTicks,
|
long LogicalTimeTicks,
|
||||||
string Origin);
|
string Origin,
|
||||||
|
long? ModelStepIndex = null,
|
||||||
|
double? ModelTimeSeconds = null,
|
||||||
|
string? ModelConfigurationIdentifier = null,
|
||||||
|
string? ModelRunIdentifier = null);
|
||||||
|
|
||||||
public sealed class SignalSnapshot
|
public sealed class SignalSnapshot
|
||||||
{
|
{
|
||||||
public SignalSnapshot(string moduleIdentifier, IEnumerable<DiagnosticSignal> signals)
|
public SignalSnapshot(
|
||||||
|
string moduleIdentifier,
|
||||||
|
IEnumerable<DiagnosticSignal> signals,
|
||||||
|
long? modelStepIndex = null,
|
||||||
|
double? modelTimeSeconds = null,
|
||||||
|
string? modelConfigurationIdentifier = null,
|
||||||
|
string? modelRunIdentifier = null)
|
||||||
{
|
{
|
||||||
ModuleIdentifier = moduleIdentifier;
|
ModuleIdentifier = moduleIdentifier;
|
||||||
Signals = Array.AsReadOnly(signals.ToArray());
|
Signals = Array.AsReadOnly(signals.ToArray());
|
||||||
|
ModelStepIndex = modelStepIndex;
|
||||||
|
ModelTimeSeconds = modelTimeSeconds;
|
||||||
|
ModelConfigurationIdentifier = modelConfigurationIdentifier;
|
||||||
|
ModelRunIdentifier = modelRunIdentifier;
|
||||||
}
|
}
|
||||||
|
|
||||||
public string ModuleIdentifier { get; }
|
public string ModuleIdentifier { get; }
|
||||||
public IReadOnlyList<DiagnosticSignal> Signals { get; }
|
public IReadOnlyList<DiagnosticSignal> Signals { get; }
|
||||||
|
public long? ModelStepIndex { get; }
|
||||||
|
public double? ModelTimeSeconds { get; }
|
||||||
|
public string? ModelConfigurationIdentifier { get; }
|
||||||
|
public string? ModelRunIdentifier { get; }
|
||||||
}
|
}
|
||||||
|
|
||||||
public sealed class DiagnosticTraceEntry
|
public sealed class DiagnosticTraceEntry
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,5 @@
|
||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
|
using AutoForge.Core.Simulation;
|
||||||
using AutoForge.Core.Vehicles;
|
using AutoForge.Core.Vehicles;
|
||||||
|
|
||||||
namespace AutoForge.Diagnostics;
|
namespace AutoForge.Diagnostics;
|
||||||
|
|
@ -6,10 +7,31 @@ namespace AutoForge.Diagnostics;
|
||||||
public sealed class SyntheticDiagnosticProtocolClient : IDiagnosticProtocolClient
|
public sealed class SyntheticDiagnosticProtocolClient : IDiagnosticProtocolClient
|
||||||
{
|
{
|
||||||
private const long DefaultTimeoutTicks = 5;
|
private const long DefaultTimeoutTicks = 5;
|
||||||
|
private static readonly IReadOnlyDictionary<string, (string Unit, JsonValueKind Kind)> DynamicSignalShape =
|
||||||
|
new Dictionary<string, (string Unit, JsonValueKind Kind)>(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 VehicleProfile _profile;
|
||||||
private readonly IDiagnosticTransport _transport;
|
private readonly IDiagnosticTransport _transport;
|
||||||
private readonly IDiagnosticLogicalClock _clock;
|
private readonly IDiagnosticLogicalClock _clock;
|
||||||
private readonly DiagnosticTraceBuffer _trace;
|
private readonly DiagnosticTraceBuffer _trace;
|
||||||
|
private readonly int _protocolVersion;
|
||||||
|
private readonly DynamicsConfiguration? _dynamicsConfiguration;
|
||||||
private readonly SemaphoreSlim _exchangeGate = new(1, 1);
|
private readonly SemaphoreSlim _exchangeGate = new(1, 1);
|
||||||
private long _correlationSequence;
|
private long _correlationSequence;
|
||||||
|
|
||||||
|
|
@ -18,12 +40,37 @@ public sealed class SyntheticDiagnosticProtocolClient : IDiagnosticProtocolClien
|
||||||
DiagnosticSessionIdentity session,
|
DiagnosticSessionIdentity session,
|
||||||
IDiagnosticTransport transport,
|
IDiagnosticTransport transport,
|
||||||
IDiagnosticLogicalClock clock,
|
IDiagnosticLogicalClock clock,
|
||||||
int traceCapacity = 200)
|
int traceCapacity = 200,
|
||||||
|
int protocolVersion = 1,
|
||||||
|
DynamicsConfiguration? dynamicsConfiguration = null)
|
||||||
{
|
{
|
||||||
_profile = profile ?? throw new ArgumentNullException(nameof(profile));
|
_profile = profile ?? throw new ArgumentNullException(nameof(profile));
|
||||||
Session = session ?? throw new ArgumentNullException(nameof(session));
|
Session = session ?? throw new ArgumentNullException(nameof(session));
|
||||||
_transport = transport ?? throw new ArgumentNullException(nameof(transport));
|
_transport = transport ?? throw new ArgumentNullException(nameof(transport));
|
||||||
_clock = clock ?? throw new ArgumentNullException(nameof(clock));
|
_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);
|
_trace = new DiagnosticTraceBuffer(traceCapacity);
|
||||||
ExpectedEndpoints = Array.AsReadOnly(transport.ExpectedEndpoints.ToArray());
|
ExpectedEndpoints = Array.AsReadOnly(transport.ExpectedEndpoints.ToArray());
|
||||||
}
|
}
|
||||||
|
|
@ -184,26 +231,68 @@ public sealed class SyntheticDiagnosticProtocolClient : IDiagnosticProtocolClien
|
||||||
DiagnosticServices.ReadSignals,
|
DiagnosticServices.ReadSignals,
|
||||||
(data, request) =>
|
(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");
|
var moduleIdentifier = RequiredString(data, "moduleIdentifier");
|
||||||
ValidateModuleIdentifier(endpoint, moduleIdentifier);
|
ValidateModuleIdentifier(endpoint, moduleIdentifier);
|
||||||
var logicalTime = RequiredInt64(data, "logicalTimeTicks");
|
var origin = RequiredString(data, "origin");
|
||||||
if (logicalTime != request.LogicalTimeTicks)
|
long? modelStepIndex = null;
|
||||||
|
double? modelTimeSeconds = null;
|
||||||
|
string? modelConfigurationIdentifier = null;
|
||||||
|
string? modelRunIdentifier = null;
|
||||||
|
var logicalTime = request.LogicalTimeTicks;
|
||||||
|
if (_protocolVersion == 1)
|
||||||
|
{
|
||||||
|
if (RequiredInt64(data, "logicalTimeTicks") != request.LogicalTimeTicks ||
|
||||||
|
!StringComparer.Ordinal.Equals(origin, "SYNTHETIC_STATIC"))
|
||||||
{
|
{
|
||||||
throw new DiagnosticProtocolException(
|
throw new DiagnosticProtocolException(
|
||||||
"INVALID_RESPONSE",
|
"INVALID_RESPONSE",
|
||||||
"Static signal snapshot time must equal the request logical start tick.");
|
"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 origin = RequiredString(data, "origin");
|
var expectedTime = modelStepIndex.Value * _dynamicsConfiguration!.Model.StepSeconds;
|
||||||
if (!StringComparer.Ordinal.Equals(origin, "SYNTHETIC_STATIC"))
|
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", "Signal origin must be SYNTHETIC_STATIC.");
|
throw new DiagnosticProtocolException(
|
||||||
|
"INVALID_RESPONSE",
|
||||||
|
"Dynamic snapshot model time, origin, run or configuration binding is invalid.");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
var signals = RequiredArray(data, "signals").EnumerateArray().Select(item =>
|
var signals = RequiredArray(data, "signals").EnumerateArray().Select(item =>
|
||||||
{
|
{
|
||||||
EnsureProperties(item, "signalIdentifier", "value", "unit", "quality");
|
EnsureProperties(item, "signalIdentifier", "value", "unit", "quality");
|
||||||
|
var signalIdentifier = RequiredString(item, "signalIdentifier");
|
||||||
var qualityText = RequiredString(item, "quality");
|
var qualityText = RequiredString(item, "quality");
|
||||||
if (!Enum.TryParse<SignalQuality>(qualityText, ignoreCase: false, out var quality) ||
|
if (!Enum.TryParse<SignalQuality>(qualityText, ignoreCase: false, out var quality) ||
|
||||||
!Enum.IsDefined(quality))
|
!Enum.IsDefined(quality))
|
||||||
|
|
@ -212,14 +301,24 @@ public sealed class SyntheticDiagnosticProtocolClient : IDiagnosticProtocolClien
|
||||||
}
|
}
|
||||||
|
|
||||||
var value = Required(item, "value");
|
var value = Required(item, "value");
|
||||||
|
var unit = RequiredString(item, "unit");
|
||||||
|
if (_protocolVersion == 2)
|
||||||
|
{
|
||||||
|
ValidateDynamicSignal(signalIdentifier, value, unit, moduleIdentifier);
|
||||||
|
}
|
||||||
|
|
||||||
return new DiagnosticSignal(
|
return new DiagnosticSignal(
|
||||||
RequiredString(item, "signalIdentifier"),
|
signalIdentifier,
|
||||||
moduleIdentifier,
|
moduleIdentifier,
|
||||||
value.Clone(),
|
value.Clone(),
|
||||||
RequiredString(item, "unit"),
|
unit,
|
||||||
quality,
|
quality,
|
||||||
logicalTime,
|
logicalTime,
|
||||||
origin);
|
origin,
|
||||||
|
modelStepIndex,
|
||||||
|
modelTimeSeconds,
|
||||||
|
modelConfigurationIdentifier,
|
||||||
|
modelRunIdentifier);
|
||||||
}).ToArray();
|
}).ToArray();
|
||||||
if (signals.Select(signal => signal.SignalIdentifier)
|
if (signals.Select(signal => signal.SignalIdentifier)
|
||||||
.Distinct(StringComparer.OrdinalIgnoreCase).Count() != signals.Length)
|
.Distinct(StringComparer.OrdinalIgnoreCase).Count() != signals.Length)
|
||||||
|
|
@ -229,7 +328,28 @@ public sealed class SyntheticDiagnosticProtocolClient : IDiagnosticProtocolClien
|
||||||
"Signal identifiers must be unique within a module snapshot.");
|
"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);
|
cancellationToken);
|
||||||
|
|
||||||
|
|
@ -291,7 +411,10 @@ public sealed class SyntheticDiagnosticProtocolClient : IDiagnosticProtocolClien
|
||||||
endpoint.Address,
|
endpoint.Address,
|
||||||
service,
|
service,
|
||||||
startTicks,
|
startTicks,
|
||||||
DefaultTimeoutTicks);
|
DefaultTimeoutTicks)
|
||||||
|
{
|
||||||
|
Version = _protocolVersion
|
||||||
|
};
|
||||||
var requestPayload = SyntheticProtocolV1.EncodeRequest(request);
|
var requestPayload = SyntheticProtocolV1.EncodeRequest(request);
|
||||||
TransportReply transportReply;
|
TransportReply transportReply;
|
||||||
|
|
||||||
|
|
@ -344,7 +467,7 @@ public sealed class SyntheticDiagnosticProtocolClient : IDiagnosticProtocolClien
|
||||||
}
|
}
|
||||||
catch (JsonException)
|
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);
|
AddTrace(endpoint, correlation, service, startTicks, _clock.Ticks, requestPayload, responsePayload, DiagnosticOutcome.ProtocolError, null, error);
|
||||||
return DiagnosticOperationResult<T>.Failure(DiagnosticOutcome.ProtocolError, "MALFORMED_RESPONSE", error);
|
return DiagnosticOperationResult<T>.Failure(DiagnosticOutcome.ProtocolError, "MALFORMED_RESPONSE", error);
|
||||||
}
|
}
|
||||||
|
|
@ -376,9 +499,11 @@ public sealed class SyntheticDiagnosticProtocolClient : IDiagnosticProtocolClien
|
||||||
"errorCode",
|
"errorCode",
|
||||||
"error",
|
"error",
|
||||||
"data");
|
"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) ||
|
if (!Same(RequiredString(root, "sessionIdentifier"), Session.SessionIdentifier) ||
|
||||||
|
|
@ -617,6 +742,68 @@ public sealed class SyntheticDiagnosticProtocolClient : IDiagnosticProtocolClien
|
||||||
return result;
|
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) =>
|
private static bool Same(string left, string right) =>
|
||||||
StringComparer.OrdinalIgnoreCase.Equals(left, right);
|
StringComparer.OrdinalIgnoreCase.Equals(left, right);
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -179,6 +179,52 @@ public static class SyntheticProtocolV1
|
||||||
JsonOptions);
|
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 sealed class DiagnosticProtocolException(string failureCode, string message) : Exception(message)
|
||||||
{
|
{
|
||||||
public string FailureCode { get; } = failureCode;
|
public string FailureCode { get; } = failureCode;
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,3 @@
|
||||||
|
using System.Runtime.CompilerServices;
|
||||||
|
|
||||||
|
[assembly: InternalsVisibleTo("AutoForge.UnitTests")]
|
||||||
|
|
@ -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<string, DynamicsDiagnosticTransport> _active =
|
||||||
|
new(StringComparer.Ordinal);
|
||||||
|
|
||||||
|
public DynamicsDiagnosticTransportFactory(IEnumerable<SimulationDefinition> 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<string, VirtualModuleDefinition> _modules;
|
||||||
|
private readonly Action<string> _onClosed;
|
||||||
|
private int _closed;
|
||||||
|
|
||||||
|
public DynamicsDiagnosticTransport(
|
||||||
|
VehicleProfile profile,
|
||||||
|
DiagnosticSessionIdentity identity,
|
||||||
|
DynamicsConfiguration configuration,
|
||||||
|
DynamicsEngine engine,
|
||||||
|
IReadOnlyList<VirtualModuleDefinition> modules,
|
||||||
|
Action<string> 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<DiagnosticEndpoint> ExpectedEndpoints { get; }
|
||||||
|
|
||||||
|
public ValueTask<TransportReply> SendAsync(ReadOnlyMemory<byte> payload, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
cancellationToken.ThrowIfCancellationRequested();
|
||||||
|
if (Volatile.Read(ref _closed) != 0)
|
||||||
|
{
|
||||||
|
return ValueTask.FromResult(new TransportReply(
|
||||||
|
TransportOutcome.Cancelled,
|
||||||
|
ReadOnlyMemory<byte>.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<byte>.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<object>() },
|
||||||
|
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<TransportReply> 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));
|
||||||
|
}
|
||||||
File diff suppressed because it is too large
Load Diff
|
|
@ -1,6 +1,8 @@
|
||||||
using AutoForge.UI.Features.ExecutionTargets.SelectExecutionTarget;
|
using AutoForge.UI.Features.ExecutionTargets.SelectExecutionTarget;
|
||||||
using AutoForge.UI.Features.Vehicles.Diagnostics;
|
using AutoForge.UI.Features.Vehicles.Diagnostics;
|
||||||
using AutoForge.UI.Features.Vehicles.Profiles;
|
using AutoForge.UI.Features.Vehicles.Profiles;
|
||||||
|
using AutoForge.UI.Features.Vehicles.Simulation;
|
||||||
|
using AutoForge.Application.Features.Vehicles.Simulation;
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
|
||||||
namespace AutoForge.UI;
|
namespace AutoForge.UI;
|
||||||
|
|
@ -11,9 +13,11 @@ public static class ServiceCollectionExtensions
|
||||||
{
|
{
|
||||||
ArgumentNullException.ThrowIfNull(services);
|
ArgumentNullException.ThrowIfNull(services);
|
||||||
|
|
||||||
|
services.AddAutoForgeDynamicsConfigurations();
|
||||||
services.AddScoped<ExecutionTargetSelectionViewModel>();
|
services.AddScoped<ExecutionTargetSelectionViewModel>();
|
||||||
services.AddScoped<DiagnosticPageViewModel>();
|
services.AddScoped<DiagnosticPageViewModel>();
|
||||||
services.AddScoped<VehicleProfilePageViewModel>();
|
services.AddScoped<VehicleProfilePageViewModel>();
|
||||||
|
services.AddScoped<SimulationPageViewModel>();
|
||||||
return services;
|
return services;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -8,10 +8,11 @@
|
||||||
It does not connect to a real vehicle and requires no driver, backend or cloud service.
|
It does not connect to a real vehicle and requires no driver, backend or cloud service.
|
||||||
</p>
|
</p>
|
||||||
<StatusNotice Tone="StatusNoticeTone.Information"
|
<StatusNotice Tone="StatusNoticeTone.Information"
|
||||||
Message="Available: explicit target metadata selection and synthetic diagnostic sessions with static module data. Vehicle dynamics and physical hardware operations are not implemented." />
|
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." />
|
||||||
<p>
|
<p>
|
||||||
<a href="/execution-targets">Review execution-target selection</a>
|
<a href="/execution-targets">Review execution-target selection</a>
|
||||||
</p>
|
</p>
|
||||||
<p>
|
<p>
|
||||||
<a href="/diagnostics">Open synthetic diagnostics</a>
|
<a href="/diagnostics">Open synthetic diagnostics</a>
|
||||||
|
<a href="/simulation">Open vehicle simulation</a>
|
||||||
</p>
|
</p>
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,177 @@
|
||||||
|
@page "/simulation"
|
||||||
|
@inject SimulationPageViewModel Simulation
|
||||||
|
|
||||||
|
<PageTitle>Vehicle simulation - AutoForge</PageTitle>
|
||||||
|
|
||||||
|
<h1>Deterministic synthetic vehicle simulation</h1>
|
||||||
|
<p>
|
||||||
|
This fixed-step synthetic model is not validated real-world prediction, vehicle
|
||||||
|
compatibility evidence, calibration advice, or a physical connection.
|
||||||
|
</p>
|
||||||
|
<StatusNotice Tone="@Simulation.StatusTone" Message="@Simulation.StatusMessage" />
|
||||||
|
|
||||||
|
<section aria-labelledby="simulation-configuration-heading">
|
||||||
|
<h2 id="simulation-configuration-heading">Explicit profile and configuration selection</h2>
|
||||||
|
<button id="load-dynamics-profile" type="button" @onclick="Simulation.LoadSyntheticProfile">
|
||||||
|
Load synthetic profile
|
||||||
|
</button>
|
||||||
|
<label for="simulation-profile">Profile</label>
|
||||||
|
<select id="simulation-profile" @bind="Simulation.SelectedProfileIdentifier">
|
||||||
|
<option value="">Choose profile</option>
|
||||||
|
@foreach (var profile in Simulation.AvailableProfiles)
|
||||||
|
{
|
||||||
|
<option value="@profile.ProfileIdentifier">@profile.ProfileIdentifier</option>
|
||||||
|
}
|
||||||
|
</select>
|
||||||
|
<label for="simulation-revision">Exact profile revision</label>
|
||||||
|
<select id="simulation-revision" @bind="Simulation.SelectedProfileRevision">
|
||||||
|
<option value="">Choose revision</option>
|
||||||
|
@foreach (var profile in Simulation.AvailableProfiles.Where(item =>
|
||||||
|
StringComparer.OrdinalIgnoreCase.Equals(item.ProfileIdentifier, Simulation.SelectedProfileIdentifier)))
|
||||||
|
{
|
||||||
|
<option value="@profile.Revision">@profile.Revision</option>
|
||||||
|
}
|
||||||
|
</select>
|
||||||
|
<button id="create-dynamics-example" type="button" @onclick="Simulation.CreateWarmExample">
|
||||||
|
Create warm-baseline configuration
|
||||||
|
</button>
|
||||||
|
<label for="simulation-provider">Dynamics provider</label>
|
||||||
|
<select id="simulation-provider" @bind="Simulation.SelectedProviderIdentifier">
|
||||||
|
<option value="">Choose dynamics provider</option>
|
||||||
|
@foreach (var provider in Simulation.DynamicsProviders)
|
||||||
|
{
|
||||||
|
<option value="@provider.Target.ProviderIdentifier">@provider.DisplayName</option>
|
||||||
|
}
|
||||||
|
</select>
|
||||||
|
<label for="simulation-configuration">Configuration</label>
|
||||||
|
<select id="simulation-configuration" @bind="Simulation.SelectedConfigurationIdentifier">
|
||||||
|
<option value="">Choose imported/created configuration</option>
|
||||||
|
@foreach (var configuration in Simulation.AvailableConfigurations)
|
||||||
|
{
|
||||||
|
<option value="@configuration.ConfigurationIdentifier">
|
||||||
|
@configuration.ProfileIdentifier revision @configuration.ProfileRevision — @configuration.ConfigurationIdentifier
|
||||||
|
</option>
|
||||||
|
}
|
||||||
|
</select>
|
||||||
|
@if (Simulation.SelectedConfiguration is { } selectedConfiguration)
|
||||||
|
{
|
||||||
|
<p id="selected-scenario-identity">
|
||||||
|
Model @selectedConfiguration.ModelIdentifier v@(selectedConfiguration.ModelVersion);
|
||||||
|
fingerprint @selectedConfiguration.ConfigurationIdentifier.
|
||||||
|
</p>
|
||||||
|
<ol id="selected-scenario-phases">
|
||||||
|
@foreach (var phase in selectedConfiguration.Scenario)
|
||||||
|
{
|
||||||
|
<li data-phase="@phase.Kind">
|
||||||
|
@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
|
||||||
|
</li>
|
||||||
|
}
|
||||||
|
</ol>
|
||||||
|
}
|
||||||
|
<button id="open-dynamics-session" type="button" disabled="@(Simulation.ActiveSession is not null)"
|
||||||
|
@onclick="Simulation.OpenSessionAsync">
|
||||||
|
Open dynamics session
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<h3>Configuration JSON interchange</h3>
|
||||||
|
<label for="dynamics-import-json">Paste a versioned dynamics configuration JSON document</label>
|
||||||
|
<textarea id="dynamics-import-json" @bind="Simulation.ConfigurationJson" rows="8"></textarea>
|
||||||
|
<button id="import-dynamics-configuration" type="button" @onclick="Simulation.ImportConfiguration">
|
||||||
|
Import configuration
|
||||||
|
</button>
|
||||||
|
<button id="export-dynamics-configuration" type="button" @onclick="Simulation.ExportConfiguration">
|
||||||
|
Export selected configuration
|
||||||
|
</button>
|
||||||
|
<label for="dynamics-export-json">Exported configuration</label>
|
||||||
|
<textarea id="dynamics-export-json" readonly rows="8">@Simulation.ExportedConfigurationJson</textarea>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
@if (Simulation.ActiveSession is { } session && session.DynamicsControl is { } control)
|
||||||
|
{
|
||||||
|
<section aria-labelledby="simulation-controls-heading">
|
||||||
|
<h2 id="simulation-controls-heading">Run lifecycle and fixed-step controls</h2>
|
||||||
|
<p id="dynamics-session-identity">
|
||||||
|
Configuration @session.Identity.DynamicsConfigurationIdentifier;
|
||||||
|
run @session.Identity.DynamicsRunIdentifier;
|
||||||
|
session @session.Identity.SessionIdentifier.
|
||||||
|
</p>
|
||||||
|
@if (Simulation.RunStatus is { } status)
|
||||||
|
{
|
||||||
|
<dl id="dynamics-run-status">
|
||||||
|
<dt>Lifecycle</dt>
|
||||||
|
<dd>@status.State</dd>
|
||||||
|
<dt>Model time</dt>
|
||||||
|
<dd>@status.VirtualTimeSeconds.ToString("F1", System.Globalization.CultureInfo.InvariantCulture) s; step @status.StepIndex</dd>
|
||||||
|
<dt>Scenario phase</dt>
|
||||||
|
<dd>@(status.ScenarioPhase ?? "Complete") (@((status.ScenarioPhaseProgress * 100).ToString("F1", System.Globalization.CultureInfo.InvariantCulture))%)</dd>
|
||||||
|
<dt>Overall scenario progress</dt>
|
||||||
|
<dd>@((status.ScenarioProgress * 100).ToString("F1", System.Globalization.CultureInfo.InvariantCulture))%</dd>
|
||||||
|
@if (status.Failure is not null)
|
||||||
|
{
|
||||||
|
<dt>Failure</dt>
|
||||||
|
<dd>@status.Failure</dd>
|
||||||
|
}
|
||||||
|
</dl>
|
||||||
|
}
|
||||||
|
<button id="dynamics-start" type="button" @onclick="Simulation.StartAsync">Start</button>
|
||||||
|
<button id="dynamics-pause" type="button" @onclick="Simulation.PauseAsync">Pause</button>
|
||||||
|
<button id="dynamics-resume" type="button" @onclick="Simulation.ResumeAsync">Resume</button>
|
||||||
|
<button id="dynamics-stop" type="button" @onclick="Simulation.StopAsync">Stop</button>
|
||||||
|
<label for="dynamics-step-count">Explicit fixed steps</label>
|
||||||
|
<input id="dynamics-step-count" type="number" min="1" max="100000" @bind="Simulation.StepCountInput" />
|
||||||
|
<button id="dynamics-step" type="button" @onclick="Simulation.StepAsync">Step</button>
|
||||||
|
<label for="dynamics-pacing">Playback pacing (0.25x–1000x)</label>
|
||||||
|
<input id="dynamics-pacing" type="number" min="0.25" max="1000" step="0.25" @bind="Simulation.PacingFactorInput" />
|
||||||
|
<button id="dynamics-set-pacing" type="button" @onclick="Simulation.SetPacingAsync">Set pacing</button>
|
||||||
|
<button id="dynamics-run-scenario" type="button" @onclick="Simulation.RunScenarioAsync">Run finite scenario</button>
|
||||||
|
<button id="dynamics-cancel-scenario" type="button" @onclick="Simulation.CancelScenario">Cancel runner</button>
|
||||||
|
<button id="dynamics-reset" type="button" @onclick="Simulation.ResetAsync">Reset exact configuration</button>
|
||||||
|
<button id="dynamics-refresh" type="button" @onclick="Simulation.RefreshTelemetryAsync">Read diagnostic telemetry</button>
|
||||||
|
<button id="dynamics-close" type="button" @onclick="Simulation.CloseSessionAsync">Close dynamics session</button>
|
||||||
|
<p>Current pacing: @control.PacingFactor.ToString("F2", System.Globalization.CultureInfo.InvariantCulture)x.</p>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section aria-labelledby="dynamics-telemetry-heading">
|
||||||
|
<h2 id="dynamics-telemetry-heading">Diagnostic-frame telemetry</h2>
|
||||||
|
<p>Every value below was read through the selected session's encoded protocol v2 diagnostic path.</p>
|
||||||
|
@if (Simulation.Telemetry.Count == 0)
|
||||||
|
{
|
||||||
|
<p>No telemetry has been read yet.</p>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<table id="dynamics-telemetry">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>Source module</th>
|
||||||
|
<th>Signal</th>
|
||||||
|
<th>Value</th>
|
||||||
|
<th>Unit</th>
|
||||||
|
<th>Quality</th>
|
||||||
|
<th>Origin</th>
|
||||||
|
<th>Model step/time</th>
|
||||||
|
<th>Configuration/run</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
@foreach (var row in Simulation.Telemetry)
|
||||||
|
{
|
||||||
|
<tr data-module="@row.ModuleIdentifier" data-signal="@row.SignalIdentifier">
|
||||||
|
<td>@row.ModuleIdentifier</td>
|
||||||
|
<td>@row.SignalIdentifier</td>
|
||||||
|
<td>@row.Value</td>
|
||||||
|
<td>@row.Unit</td>
|
||||||
|
<td>@row.Quality</td>
|
||||||
|
<td>@row.Origin</td>
|
||||||
|
<td>@row.StepIndex / @row.ModelTimeSeconds.ToString("F1", System.Globalization.CultureInfo.InvariantCulture) s</td>
|
||||||
|
<td>@row.ConfigurationIdentifier / @row.RunIdentifier</td>
|
||||||
|
</tr>
|
||||||
|
}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
}
|
||||||
|
</section>
|
||||||
|
}
|
||||||
|
|
||||||
|
<p id="dynamics-fidelity-limit">The model is deliberately synthetic and does not provide manufacturer-validated performance, safe tuning guidance, or physical operations.</p>
|
||||||
|
|
@ -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<VehicleProfileReference> AvailableProfiles { get; private set; } = profiles.List();
|
||||||
|
public IReadOnlyList<DynamicsConfigurationReference> AvailableConfigurations => configurations.List();
|
||||||
|
public DynamicsConfiguration? SelectedConfiguration =>
|
||||||
|
SelectedConfigurationIdentifier is { } identifier &&
|
||||||
|
AvailableConfigurations.Any(item => StringComparer.Ordinal.Equals(item.ConfigurationIdentifier, identifier))
|
||||||
|
? configurations.Select(identifier)
|
||||||
|
: null;
|
||||||
|
public IReadOnlyList<DiagnosticProviderDescriptor> 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<DiagnosticEndpoint> VerifiedEndpoints { get; private set; } = [];
|
||||||
|
public IReadOnlyList<DynamicsTelemetryRow> 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<DynamicsTelemetryRow>();
|
||||||
|
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<IDynamicsControl, Task<DynamicsRunStatus>> 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();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -8,6 +8,7 @@
|
||||||
<NavLink href="/execution-targets">Target selection</NavLink>
|
<NavLink href="/execution-targets">Target selection</NavLink>
|
||||||
<NavLink href="/vehicle-profiles">Vehicle profiles</NavLink>
|
<NavLink href="/vehicle-profiles">Vehicle profiles</NavLink>
|
||||||
<NavLink href="/diagnostics">Synthetic diagnostics</NavLink>
|
<NavLink href="/diagnostics">Synthetic diagnostics</NavLink>
|
||||||
|
<NavLink href="/simulation">Vehicle simulation</NavLink>
|
||||||
</nav>
|
</nav>
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -8,3 +8,4 @@
|
||||||
@using AutoForge.UI.Features.ExecutionTargets.SelectExecutionTarget
|
@using AutoForge.UI.Features.ExecutionTargets.SelectExecutionTarget
|
||||||
@using AutoForge.UI.Features.Vehicles.Diagnostics
|
@using AutoForge.UI.Features.Vehicles.Diagnostics
|
||||||
@using AutoForge.UI.Features.Vehicles.Profiles
|
@using AutoForge.UI.Features.Vehicles.Profiles
|
||||||
|
@using AutoForge.UI.Features.Vehicles.Simulation
|
||||||
|
|
|
||||||
|
|
@ -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<IVehicleProfileService>();
|
||||||
|
profiles.Import(ReadFixture("synthetic-truck-baseline.json"));
|
||||||
|
var configurations = provider.GetRequiredService<IDynamicsConfigurationService>();
|
||||||
|
var original = configurations.CreateExample("autoforge.synthetic.test-truck", 1);
|
||||||
|
var page = provider.GetRequiredService<SimulationPageViewModel>();
|
||||||
|
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<DiagnosticSession>(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<DiagnosticSession>(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<IVehicleProfileService>().Import(ReadFixture("synthetic-truck-baseline.json"));
|
||||||
|
var configurations = provider.GetRequiredService<IDynamicsConfigurationService>();
|
||||||
|
var configuration = configurations.CreateExample("autoforge.synthetic.test-truck", 1);
|
||||||
|
var sessions = provider.GetRequiredService<IDiagnosticSessionService>();
|
||||||
|
|
||||||
|
await Assert.ThrowsAsync<DiagnosticSessionException>(() => sessions.OpenDynamicsAsync(
|
||||||
|
configuration.ProfileIdentifier,
|
||||||
|
configuration.ProfileRevision,
|
||||||
|
SimulatedDiagnosticTransportFactory.ProviderIdentifier,
|
||||||
|
ExecutionTargetKind.Simulation,
|
||||||
|
configuration));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task DifferentDynamicsConfigurationsRemainIsolatedAcrossSessionsAndReset()
|
||||||
|
{
|
||||||
|
using var provider = CreateProvider();
|
||||||
|
provider.GetRequiredService<IVehicleProfileService>().Import(ReadFixture("synthetic-truck-baseline.json"));
|
||||||
|
var configurations = provider.GetRequiredService<IDynamicsConfigurationService>();
|
||||||
|
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<IDiagnosticSessionService>();
|
||||||
|
|
||||||
|
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<IVehicleProfileService>().Import(ReadFixture("synthetic-truck-baseline.json"));
|
||||||
|
var configurations = provider.GetRequiredService<IDynamicsConfigurationService>();
|
||||||
|
var original = configurations.CreateExample("autoforge.synthetic.test-truck", 1);
|
||||||
|
var page = provider.GetRequiredService<SimulationPageViewModel>();
|
||||||
|
page.SelectedProfileIdentifier = original.ProfileIdentifier;
|
||||||
|
page.SelectedProfileRevision = original.ProfileRevision;
|
||||||
|
page.SelectedProviderIdentifier = DynamicsDiagnosticTransportFactory.ProviderIdentifier;
|
||||||
|
page.SelectedConfigurationIdentifier = original.ConfigurationIdentifier;
|
||||||
|
await page.OpenSessionAsync();
|
||||||
|
var active = Assert.IsType<DiagnosticSession>(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<IVehicleProfileService>().Import(ReadFixture("synthetic-truck-baseline.json"));
|
||||||
|
var configurations = provider.GetRequiredService<IDynamicsConfigurationService>();
|
||||||
|
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<SimulationPageViewModel>();
|
||||||
|
page.SelectedProfileIdentifier = configuration.ProfileIdentifier;
|
||||||
|
page.SelectedProfileRevision = configuration.ProfileRevision;
|
||||||
|
page.SelectedProviderIdentifier = DynamicsDiagnosticTransportFactory.ProviderIdentifier;
|
||||||
|
page.SelectedConfigurationIdentifier = configuration.ConfigurationIdentifier;
|
||||||
|
await page.OpenSessionAsync();
|
||||||
|
var session = Assert.IsType<DiagnosticSession>(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<IVehicleProfileService>().Import(ReadFixture("synthetic-truck-baseline.json"));
|
||||||
|
var configurations = provider.GetRequiredService<IDynamicsConfigurationService>();
|
||||||
|
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<SimulationPageViewModel>();
|
||||||
|
page.SelectedProfileIdentifier = configuration.ProfileIdentifier;
|
||||||
|
page.SelectedProfileRevision = configuration.ProfileRevision;
|
||||||
|
page.SelectedProviderIdentifier = DynamicsDiagnosticTransportFactory.ProviderIdentifier;
|
||||||
|
page.SelectedConfigurationIdentifier = configuration.ConfigurationIdentifier;
|
||||||
|
await page.OpenSessionAsync();
|
||||||
|
var session = Assert.IsType<DiagnosticSession>(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<IVehicleProfileService>().Import(ReadFixture("synthetic-truck-baseline.json"));
|
||||||
|
var configurations = provider.GetRequiredService<IDynamicsConfigurationService>();
|
||||||
|
var configuration = configurations.CreateExample("autoforge.synthetic.test-truck", 1);
|
||||||
|
var page = provider.GetRequiredService<SimulationPageViewModel>();
|
||||||
|
page.SelectedProfileIdentifier = configuration.ProfileIdentifier;
|
||||||
|
page.SelectedProfileRevision = configuration.ProfileRevision;
|
||||||
|
page.SelectedProviderIdentifier = DynamicsDiagnosticTransportFactory.ProviderIdentifier;
|
||||||
|
page.SelectedConfigurationIdentifier = configuration.ConfigurationIdentifier;
|
||||||
|
await page.OpenSessionAsync();
|
||||||
|
var initial = Assert.IsType<DiagnosticSession>(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<DiagnosticSession>(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<IVehicleProfileService>().Import(ReadFixture("synthetic-truck-baseline.json"));
|
||||||
|
var configuration = provider.GetRequiredService<IDynamicsConfigurationService>()
|
||||||
|
.CreateExample("autoforge.synthetic.test-truck", 1);
|
||||||
|
var page = provider.GetRequiredService<SimulationPageViewModel>();
|
||||||
|
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<DiagnosticSession>(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<IVehicleProfileService>().Import(ReadFixture("synthetic-truck-baseline.json"));
|
||||||
|
var configuration = provider.GetRequiredService<IDynamicsConfigurationService>()
|
||||||
|
.CreateExample("autoforge.synthetic.test-truck", 1);
|
||||||
|
var page = provider.GetRequiredService<SimulationPageViewModel>();
|
||||||
|
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<BlockingOpenSessionService>(serviceProvider =>
|
||||||
|
new BlockingOpenSessionService(
|
||||||
|
new DiagnosticSessionService(
|
||||||
|
serviceProvider.GetRequiredService<IVehicleProfileService>(),
|
||||||
|
serviceProvider.GetRequiredService<IExecutionTargetResolver>(),
|
||||||
|
serviceProvider.GetServices<IDiagnosticTransportFactory>(),
|
||||||
|
() => new DiagnosticLogicalClock()),
|
||||||
|
openGate));
|
||||||
|
services.AddSingleton<IDiagnosticSessionService>(serviceProvider =>
|
||||||
|
serviceProvider.GetRequiredService<BlockingOpenSessionService>());
|
||||||
|
}
|
||||||
|
|
||||||
|
services.AddAutoForgeDynamicsConfigurations();
|
||||||
|
services.AddAutoForgeUi();
|
||||||
|
services.AddSingleton<NavigationManager>(new TestNavigationManager("http://localhost/simulation"));
|
||||||
|
services.AddSingleton<INavigationInterception, TestNavigationInterception>();
|
||||||
|
services.AddSingleton<IScrollToLocationHash, TestScrollToLocationHash>();
|
||||||
|
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<PendingDelay> _requests = Channel.CreateUnbounded<PendingDelay>();
|
||||||
|
|
||||||
|
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<PendingDelay> 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<DrainDelay> _requests = Channel.CreateUnbounded<DrainDelay>();
|
||||||
|
private readonly object _gate = new();
|
||||||
|
private readonly List<DrainDelay> _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<DrainDelay> 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<DiagnosticProviderDescriptor> Providers => inner.Providers;
|
||||||
|
|
||||||
|
public Task<DiagnosticSession> OpenAsync(
|
||||||
|
string profileIdentifier,
|
||||||
|
int profileRevision,
|
||||||
|
string providerIdentifier,
|
||||||
|
ExecutionTargetKind targetKind,
|
||||||
|
CancellationToken cancellationToken = default) =>
|
||||||
|
inner.OpenAsync(profileIdentifier, profileRevision, providerIdentifier, targetKind, cancellationToken);
|
||||||
|
|
||||||
|
public async Task<DiagnosticSession> 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<DiagnosticSession> ResetAsync(
|
||||||
|
DiagnosticSession session,
|
||||||
|
CancellationToken cancellationToken = default) =>
|
||||||
|
inner.ResetAsync(session, cancellationToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static async Task<string> RenderRoutesAsync(IServiceProvider services)
|
||||||
|
{
|
||||||
|
await using var renderer = new HtmlRenderer(
|
||||||
|
services,
|
||||||
|
services.GetRequiredService<ILoggerFactory>());
|
||||||
|
|
||||||
|
return await renderer.Dispatcher.InvokeAsync(async () =>
|
||||||
|
{
|
||||||
|
var component = await renderer.RenderComponentAsync<Routes>();
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -24,7 +24,9 @@ public sealed class UiCompositionTests
|
||||||
Assert.Contains("<h1>AutoForge foundation</h1>", html);
|
Assert.Contains("<h1>AutoForge foundation</h1>", html);
|
||||||
Assert.Contains("Review execution-target selection", html);
|
Assert.Contains("Review execution-target selection", html);
|
||||||
Assert.Contains("status-notice--information", 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);
|
Assert.Contains("Target selection is metadata only", html);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -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<DynamicsConfigurationException>(() => service.Import("{\"unknown\":1}"));
|
||||||
|
Assert.Throws<DynamicsConfigurationException>(() =>
|
||||||
|
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<DynamicsConfigurationException>(() => service.Import(unknownProfile.ToJsonString()));
|
||||||
|
Assert.Throws<DynamicsConfigurationException>(() => service.Import(unknownRevision.ToJsonString()));
|
||||||
|
Assert.Throws<DynamicsConfigurationException>(() => service.Import(unknownModule.ToJsonString()));
|
||||||
|
Assert.Throws<DynamicsConfigurationException>(() => service.Import(conflictingCalibration.ToJsonString()));
|
||||||
|
var missingTransmission = JsonNode.Parse(validJson.ToJsonString())!.AsObject();
|
||||||
|
missingTransmission["transmissionModuleIdentifier"] = "module.transmission.missing";
|
||||||
|
Assert.Throws<DynamicsConfigurationException>(() => 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<DynamicsConfigurationException>(() => 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<DynamicsConfigurationException>(() => 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<double>();
|
||||||
|
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<ObjectDisposedException>(() => 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<DynamicsRunStatus>? 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<InvalidOperationException>(() => 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<InvalidOperationException>(() => 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<InvalidOperationException>(() => stoppedControl.ResumeAsync());
|
||||||
|
Assert.Equal(stoppedBeforeResume, stoppedControl.Status);
|
||||||
|
|
||||||
|
await stoppedControl.DisposeAsync();
|
||||||
|
var closedStatus = stoppedControl.Status;
|
||||||
|
await Assert.ThrowsAsync<ObjectDisposedException>(() => stoppedControl.StartAsync());
|
||||||
|
await Assert.ThrowsAsync<ObjectDisposedException>(() => 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<InvalidOperationException>(() => cancellationControl.RunScenarioAsync());
|
||||||
|
cancellation.Cancel();
|
||||||
|
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => 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<DynamicsTelemetryState> Samples, IReadOnlyList<TimeSpan> 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<PendingDynamicsDelay> _requests = Channel.CreateUnbounded<PendingDynamicsDelay>();
|
||||||
|
|
||||||
|
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<PendingDynamicsDelay> 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<DrainDelay> _requests = Channel.CreateUnbounded<DrainDelay>();
|
||||||
|
private readonly object _gate = new();
|
||||||
|
private readonly List<DrainDelay> _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<DrainDelay> NextDelayAsync() => _requests.Reader.ReadAsync();
|
||||||
|
|
||||||
|
public void ReleaseAllCleanup()
|
||||||
|
{
|
||||||
|
lock (_gate)
|
||||||
|
{
|
||||||
|
foreach (var delay in _delays)
|
||||||
|
{
|
||||||
|
delay.ReleaseCleanup();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private sealed class ImmediateDynamicsPacer : IDynamicsPacer
|
||||||
|
{
|
||||||
|
private readonly List<TimeSpan> _requestedDelays = [];
|
||||||
|
public IReadOnlyList<TimeSpan> RequestedDelays => _requestedDelays.AsReadOnly();
|
||||||
|
|
||||||
|
public Task DelayAsync(TimeSpan delay, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
cancellationToken.ThrowIfCancellationRequested();
|
||||||
|
_requestedDelays.Add(delay);
|
||||||
|
return Task.CompletedTask;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static (DynamicsRunStatus Status, IReadOnlyList<DynamicsTelemetryState> 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<double> 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<JsonObject> rewrite) : IDiagnosticTransport
|
||||||
|
{
|
||||||
|
public IReadOnlyList<DiagnosticEndpoint> ExpectedEndpoints => inner.ExpectedEndpoints;
|
||||||
|
|
||||||
|
public async ValueTask<TransportReply> SendAsync(
|
||||||
|
ReadOnlyMemory<byte> 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;
|
||||||
|
}
|
||||||
|
}
|
||||||
Loading…
Reference in New Issue