After 3
This commit is contained in:
parent
9de82e53d5
commit
fe43fcf97b
80
README.md
80
README.md
|
|
@ -20,11 +20,21 @@ supported vehicle modules.
|
|||
- Step-02 validated vehicle/profile/module metadata, strict schema-v1 JSON
|
||||
interchange, an in-memory revision catalog, and a synthetic profile UI.
|
||||
Step-02A corrected strict timestamp parsing and optional evidence applicability.
|
||||
Both worker implementation/verification runs are complete; manual orchestrator
|
||||
acceptance of Step-02 remains pending.
|
||||
Step-02 and Step-02A were accepted by the orchestrator on 2026-10-28.
|
||||
- Step-03 adds a provider-neutral diagnostic protocol/session path and a
|
||||
data-driven synthetic virtual-module provider. The native UI explicitly loads
|
||||
and selects a saved profile revision/provider, opens a separate simulation
|
||||
session, probes endpoints, reads module identity/DTC/static signal snapshots,
|
||||
clears only supported virtual DTC state after fresh empty readback verification,
|
||||
and exposes a bounded raw/decoded trace. Step-03A corrects strict wire presence/
|
||||
ambiguity checks, complete reply validation and truthful trace outcomes.
|
||||
Step-03B preserves successful probe/service evidence separately from optional
|
||||
profile-verified identity and keeps expected/probed/identified counts distinct.
|
||||
Read/clear actions remain gated on verified identity. Step-03 as a whole remains
|
||||
subject to manual orchestrator acceptance.
|
||||
- UI routes: `/` foundation, `/execution-targets` explicit metadata selection,
|
||||
`/vehicle-profiles` explicit profile import/revision selection/inspection/export,
|
||||
and a visible not-found route.
|
||||
`/diagnostics` synthetic diagnostics, and a visible not-found route.
|
||||
- Capability declarations distinguish Supported, Unsupported, Unknown,
|
||||
Inaccessible and Restricted. Missing declarations are explicitly Unknown.
|
||||
Provenance and all profile facts are supplied metadata, not independently
|
||||
|
|
@ -39,15 +49,16 @@ supported vehicle modules.
|
|||
|
||||
### In progress
|
||||
|
||||
Manual orchestrator review and acceptance of Step-02 after the Step-02A correction.
|
||||
Manual orchestrator review and acceptance of the Step-03B correction report;
|
||||
the worker's native baseline smoke and Release verification are complete.
|
||||
|
||||
### Planned
|
||||
|
||||
Vehicle/module discovery, deterministic simulation, diagnostics, telemetry and
|
||||
replay, calibration values/editing/backups, AI and real hardware operations
|
||||
require later approved assignments. No capability is implemented merely because
|
||||
it appears in the product vision or roadmap. Initial future hardware integration
|
||||
remains read-only; any programming requires separate authorization and evidence.
|
||||
Vehicle dynamics/scenarios, telemetry recording/replay, calibration values/
|
||||
editing/backups, AI and real hardware operations require later approved
|
||||
assignments. This Step-03 virtual protocol is explicitly synthetic and does not
|
||||
provide vehicle compatibility, physical access or authorization. No capability
|
||||
is implemented merely because it appears in the product vision or roadmap.
|
||||
|
||||
## Architecture
|
||||
|
||||
|
|
@ -58,31 +69,45 @@ vehicle-independent reusable controls. Application features run in-process in a
|
|||
modular monolith, and Core remains platform-neutral. There is no backend,
|
||||
browser-hosted WASM shell, Blazor Server host or second application executable.
|
||||
|
||||
The application slices currently provide explicit target metadata resolution
|
||||
and vehicle-profile metadata import/list/select/export. The Client composes an
|
||||
empty target-provider registration and a session-lifetime in-memory profile
|
||||
catalog. Import never auto-selects, replaces an existing profile revision, or
|
||||
changes target selection.
|
||||
The application slices provide explicit target metadata resolution,
|
||||
vehicle-profile metadata import/list/select/export, and simulation-only
|
||||
diagnostic sessions. The Client composes the actual synthetic provider through
|
||||
the provider-neutral factory contract and a session-lifetime in-memory profile
|
||||
catalog. Import never auto-selects or replaces an existing profile revision;
|
||||
metadata resolution never opens a session.
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
Client[MAUI Blazor Hybrid Client] --> UI[UI RCL]
|
||||
Client --> Simulation[Simulation provider]
|
||||
UI --> Components[Reusable Components RCL]
|
||||
UI --> App[Application feature slices]
|
||||
Client --> App
|
||||
App --> Diagnostics[Provider-neutral Diagnostics contracts and protocol]
|
||||
App --> Core[Platform-neutral Core models]
|
||||
Diagnostics --> Core
|
||||
Simulation --> Diagnostics
|
||||
Simulation --> Core
|
||||
UnitTests[Headless unit tests] --> Core
|
||||
UnitTests --> App
|
||||
UnitTests --> Diagnostics
|
||||
UnitTests --> Simulation
|
||||
IntegrationTests[Headless integration and rendered UI tests] --> UI
|
||||
IntegrationTests --> App
|
||||
IntegrationTests --> Core
|
||||
IntegrationTests --> Diagnostics
|
||||
IntegrationTests --> Simulation
|
||||
```
|
||||
|
||||
Core and Application own their behaviors under feature-focused source folders:
|
||||
|
||||
- `AutoForge.Application/Features/ExecutionTargets/SelectExecutionTarget`
|
||||
- `AutoForge.Application/Features/Vehicles/Profiles`
|
||||
- `AutoForge.Application/Features/Vehicles/Diagnostics`
|
||||
- `AutoForge.Diagnostics` (provider-neutral protocol, transport/session contracts)
|
||||
- `AutoForge.Simulation` (data-driven virtual modules and synthetic transport)
|
||||
- `AutoForge.UI/Features/Vehicles/Profiles`
|
||||
- `AutoForge.UI/Features/Vehicles/Diagnostics`
|
||||
|
||||
No mediator, generic repository layer, database, or empty future feature is
|
||||
required. See the [schema-v1 profile guide](docs/vehicle-profile-schema-v1.md)
|
||||
|
|
@ -106,6 +131,8 @@ AutoForge/
|
|||
AutoForge.Components/ Generic reusable UI components
|
||||
AutoForge.Core/ Platform-neutral domain invariants
|
||||
AutoForge.Application/ In-process application feature slices
|
||||
AutoForge.Diagnostics/ Provider-neutral diagnostic protocol/contracts
|
||||
AutoForge.Simulation/ Synthetic virtual-module provider/transport
|
||||
tests/
|
||||
AutoForge.UnitTests/
|
||||
AutoForge.IntegrationTests/
|
||||
|
|
@ -125,8 +152,8 @@ From the repository root in PowerShell:
|
|||
|
||||
```powershell
|
||||
dotnet restore .\src\AutoForge.slnx
|
||||
dotnet build .\src\AutoForge.slnx --configuration Release
|
||||
dotnet test .\src\AutoForge.slnx --configuration Release
|
||||
dotnet build .\src\AutoForge.slnx --configuration Release --no-restore
|
||||
dotnet test .\src\AutoForge.slnx --configuration Release --no-build
|
||||
dotnet run --project .\src\AutoForge.Client\AutoForge.Client.csproj --configuration Release --framework net10.0-windows10.0.26100.0
|
||||
```
|
||||
|
||||
|
|
@ -135,25 +162,36 @@ warnings/errors, 103 unit and 37 integration tests passed (140 total, zero
|
|||
failed/skipped), and native Client checks for strict timestamp failures, partial
|
||||
evidence import/export and conflicting-identity atomicity. The original Step-02
|
||||
report records its historical 59 unit/34 integration cases; those runs did not
|
||||
include the Step-02A corrections. Exact commands and evidence are in the
|
||||
[Step-02A report](prompts/Step-02A-Report.md). Manual orchestrator acceptance
|
||||
remains pending.
|
||||
include the Step-02A corrections. Step-03 extends those suites and records its
|
||||
actual full-build/test and native-smoke evidence in the
|
||||
[Step-03 worker report](prompts/Step-03-Report.md). Step-03A's stricter
|
||||
request/reply validation, trace consistency and clear-verification behavior,
|
||||
tests, final 111-unit/64-integration Release results, and worker evidence are
|
||||
recorded in the
|
||||
[Step-03A corrective report](prompts/Step-03A-Report.md). Manual Step-03
|
||||
acceptance remains the orchestrator's responsibility.
|
||||
|
||||
## Documentation and handoff
|
||||
|
||||
- [Documentation index](docs/README.md)
|
||||
- [Architecture and project graph](docs/architecture.md)
|
||||
- [Synthetic diagnostics protocol v1](docs/synthetic-diagnostics-v1.md)
|
||||
- [Simulation definitions and state](docs/simulation.md)
|
||||
- [Vehicle-profile schema v1 and usage](docs/vehicle-profile-schema-v1.md)
|
||||
- [Build, tests and native smoke guide](docs/build-and-test.md)
|
||||
- [ADR-0001: historical .NET foundation](docs/adr-0001-headless-foundation.md)
|
||||
- [ADR-0002: one native shell and feature slices](docs/adr-0002-single-shell-vsa.md)
|
||||
- [ADR-0003: strict profile interchange v1](docs/adr-0003-profile-interchange-v1.md)
|
||||
- [ADR-0004: synthetic diagnostics boundaries](docs/adr-0004-synthetic-diagnostics.md)
|
||||
- [Step-01 historical report](prompts/Step-01-Report.md)
|
||||
- [Accepted Step-01A report](prompts/Step-01A-Report.md)
|
||||
- [Step-02 worker report](prompts/Step-02-Report.md)
|
||||
- [Step-02A corrective worker report](prompts/Step-02A-Report.md)
|
||||
- [Step-03 worker report](prompts/Step-03-Report.md)
|
||||
- [Step-03A corrective worker report](prompts/Step-03A-Report.md)
|
||||
- [Step-03B corrective worker report](prompts/Step-03B-Report.md)
|
||||
- [Orchestrator-owned roadmap](prompts/ROADMAP.md) and
|
||||
[orchestration state](prompts/STATE.md)
|
||||
|
||||
Handoffs are manual. Step-02/Step-02A worker completion does not mean
|
||||
orchestrator acceptance or authorize Step-03.
|
||||
Handoffs are manual. Step-03 worker completion does not mean orchestrator
|
||||
acceptance or authorize Step-04.
|
||||
|
|
|
|||
|
|
@ -1,27 +1,37 @@
|
|||
# AutoForge documentation
|
||||
|
||||
The implemented scope is the accepted Step-01/Step-01A foundation plus
|
||||
Step-02's validated synthetic vehicle-profile metadata slice. Step-02 worker
|
||||
and Step-02A corrective verification are complete; manual orchestrator
|
||||
acceptance of Step-02 remains pending.
|
||||
The implemented scope includes the accepted Step-01/Step-01A foundation,
|
||||
accepted Step-02/Step-02A vehicle-profile metadata, and the Step-03 synthetic
|
||||
diagnostic vertical slice with the Step-03A integrity/verification corrections.
|
||||
Worker completion/verification is reported separately from manual orchestrator
|
||||
acceptance; Step-03 is not accepted until that review.
|
||||
|
||||
- [Architecture](architecture.md): actual seven-project graph, Client/UI/RCL
|
||||
ownership, feature-slice organization, target selection and profile catalog.
|
||||
- [Architecture](architecture.md): actual nine-project graph, responsibilities,
|
||||
route ownership and provider/reference boundaries.
|
||||
- [Synthetic diagnostics protocol v1](synthetic-diagnostics-v1.md): request and
|
||||
response envelope, outcomes, validation, logical timing and bounded trace.
|
||||
- [Simulation definitions and state](simulation.md): profile binding, module
|
||||
inventory, service declarations, per-session DTC state and deterministic faults.
|
||||
- [ADR-0001: Headless .NET 10 foundation](adr-0001-headless-foundation.md):
|
||||
historical foundation decisions, with dual-shell/deferred-host superseded.
|
||||
historical foundation decisions; dual-shell/deferred-host decision superseded.
|
||||
- [ADR-0002: Single native shell and feature slices](adr-0002-single-shell-vsa.md):
|
||||
one Client, two RCLs and the modular-monolith composition.
|
||||
one Client, two RCLs and modular-monolith composition.
|
||||
- [ADR-0003: Strict profile interchange v1](adr-0003-profile-interchange-v1.md):
|
||||
immutable profile revisions, strict versioned JSON and in-memory catalog.
|
||||
- [ADR-0004: Synthetic diagnostics boundaries](adr-0004-synthetic-diagnostics.md):
|
||||
provider-neutral ports and explicit non-authentic protocol decision.
|
||||
- [Vehicle-profile schema v1](vehicle-profile-schema-v1.md): identity/revision,
|
||||
explicit unknowns, capability/provenance contracts, JSON policy and usage.
|
||||
- [Build and test](build-and-test.md): SDK/MAUI/Windows/WebView2 prerequisites,
|
||||
exact commands, rendered/native verification, evidence and limitations.
|
||||
full solution/test commands and separate native-smoke workflow.
|
||||
|
||||
See the [root README](../README.md) for product vision and implementation status,
|
||||
the [roadmap](../prompts/ROADMAP.md) for future milestones, the
|
||||
[Step-01 historical report](../prompts/Step-01-Report.md), the
|
||||
[accepted Step-01A report](../prompts/Step-01A-Report.md) and
|
||||
[Step-02 worker report](../prompts/Step-02-Report.md) and
|
||||
[Step-02A corrective report](../prompts/Step-02A-Report.md) for execution evidence.
|
||||
Manual acceptance remains the orchestrator's responsibility.
|
||||
See the [root README](../README.md) for product vision and implementation
|
||||
status, the [roadmap](../prompts/ROADMAP.md) for future milestones, and the
|
||||
historical/worker reports for their own execution evidence:
|
||||
[Step-01](../prompts/Step-01-Report.md),
|
||||
[accepted Step-01A](../prompts/Step-01A-Report.md),
|
||||
[Step-02](../prompts/Step-02-Report.md),
|
||||
[Step-02A](../prompts/Step-02A-Report.md) and
|
||||
[Step-03 worker report](../prompts/Step-03-Report.md),
|
||||
[Step-03A corrective worker report](../prompts/Step-03A-Report.md).
|
||||
Handoffs are manual; acceptance remains the orchestrator's responsibility.
|
||||
|
|
|
|||
|
|
@ -0,0 +1,89 @@
|
|||
# ADR-0004: Provider-neutral synthetic diagnostics boundary
|
||||
|
||||
- Status: Step-03A corrective implementation and verification complete; manual
|
||||
orchestrator acceptance of Step-03 remains pending.
|
||||
- Date: 2026-10-29.
|
||||
|
||||
## Context
|
||||
|
||||
The accepted profile slice provides explicit immutable metadata and capability
|
||||
claims, not actual module services, communication or vehicle access. Step-03
|
||||
requires proving that diagnostics requests traverse a transport, that failures
|
||||
remain truthful, and that deterministic virtual state can be inspected without
|
||||
claiming a real automotive standard or adding a physical adapter.
|
||||
|
||||
## Decision
|
||||
|
||||
Add exactly two portable capability libraries:
|
||||
|
||||
- `AutoForge.Diagnostics` owns provider-neutral transport/session/operation
|
||||
contracts, typed results, a synthetic protocol-v1 codec/client and bounded
|
||||
trace.
|
||||
- `AutoForge.Simulation` owns data-driven virtual module definitions, isolated
|
||||
per-session state, and an in-process transport implementing the diagnostics
|
||||
factory/transport ports.
|
||||
|
||||
Application coordinates exact profile/revision/provider/kind selection and
|
||||
session lifecycle using Diagnostics interfaces only. The native Client composes
|
||||
the Simulation provider from a single factory/descriptor registration source.
|
||||
UI owns `/diagnostics`, requires explicit import/selection/open, and consumes
|
||||
Application/Diagnostics APIs. Metadata resolution remains separate from session
|
||||
opening. Simulation is never a fallback for replay or physical kinds.
|
||||
|
||||
Synthetic protocol v1 uses UTF-8 JSON with explicit version/session/profile/
|
||||
configuration/correlation/address/service/logical-time/deadline fields and
|
||||
positive or negative replies. Actual frames cross the transport port. Malformed,
|
||||
mismatched, unsupported, no-response, timeout and cancellation results remain
|
||||
typed failures. Static synthetic signals and virtual DTCs are data, not dynamics,
|
||||
vehicle capture or physical writes. A session owns deterministic state and a
|
||||
bounded 200-entry trace; reset closes/reopens exact selected configuration.
|
||||
Only integration tests can access the internal state oracle.
|
||||
|
||||
The Step-03A correction requires every request/envelope/service property with
|
||||
exact camelCase spelling, rejects unknown and duplicate properties before
|
||||
dispatch or interpretation, and validates all service payload semantics before
|
||||
returning a positive value or trace outcome. A complete unsupported protocol
|
||||
version remains an explicit version failure. Malformed requests do not dispatch
|
||||
or mutate state. Probe identity/service claims and trace outcomes are validated
|
||||
in the protocol exchange path.
|
||||
|
||||
An acknowledged virtual DTC clear is not a verified state change. Application
|
||||
coordinates the clear and a fresh DTC read; only a valid empty readback is
|
||||
verified success. Nonempty data is retained as observed with verification
|
||||
failure, while failed/uncertain readback is not reported as success. The
|
||||
operation remains Simulation-only and performs no physical write.
|
||||
|
||||
## Consequences
|
||||
|
||||
- The application has a real, testable diagnostics path without a hardware
|
||||
driver, backend, generic plugin framework or extra executable.
|
||||
- Services are declared in simulation data and discovered by real protocol
|
||||
probes; profile capability claims do not grant them.
|
||||
- Discovery keeps expected endpoints, validated positive probes and identities
|
||||
verified against the selected profile as distinct facts. Probe services
|
||||
survive later identity failures; profile metadata never fills runtime
|
||||
identity, and read/clear actions remain identity-gated.
|
||||
- Each wire phase keeps its own immutable raw/decoded trace outcome, including
|
||||
cancellation or failure after a positive probe.
|
||||
- Invalid frames cannot select state-changing services through missing defaults
|
||||
or duplicate fields, and semantic response errors cannot appear as successful
|
||||
values or contradictory positive trace records.
|
||||
- The new protocol is intentionally non-authentic and cannot be used as evidence
|
||||
of standards compatibility. There is still no physical or replay provider,
|
||||
vehicle dynamics, telemetry capture/replay, programming or calibration write.
|
||||
- Future providers may implement the provider-neutral Diagnostics ports only
|
||||
through a separately approved assignment and operation-specific safeguards.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
- Treat profile capability claims as implemented services: rejected because
|
||||
metadata is not executable behavior or authorization.
|
||||
- Read virtual state directly from Application/UI: rejected because it would
|
||||
bypass request/transport/response validation and conceal communication faults.
|
||||
- Reuse Simulation for physical/replay selections: rejected because it creates
|
||||
false connection semantics and unsafe fallback behavior.
|
||||
- Adopt a real automotive standard: rejected because this milestone has no
|
||||
validated hardware/standard transport, and calling synthetic frames authentic
|
||||
would be misleading.
|
||||
- Add a general protocol/plugin/clock assembly or full dynamics engine:
|
||||
rejected as unnecessary to this bounded vertical slice.
|
||||
|
|
@ -11,42 +11,57 @@ There is no web/server host, WASM host or backend process.
|
|||
flowchart TD
|
||||
Client[AutoForge.Client: MAUI startup, BlazorWebView and DI] --> UI[AutoForge.UI: routes and feature presentation]
|
||||
UI --> Components[AutoForge.Components: reusable generic UI]
|
||||
UI --> Application[AutoForge.Application: cohesive feature slices]
|
||||
Client --> Application
|
||||
Application --> Core[AutoForge.Core: platform-neutral contracts]
|
||||
UI --> App[AutoForge.Application: cohesive feature slices]
|
||||
Client --> App
|
||||
App --> Diagnostics[AutoForge.Diagnostics: provider-neutral protocol and contracts]
|
||||
App --> Core[AutoForge.Core: platform-neutral models]
|
||||
Diagnostics --> Core
|
||||
Client --> Simulation[AutoForge.Simulation: synthetic provider and transport]
|
||||
Simulation --> Diagnostics
|
||||
Simulation --> Core
|
||||
UnitTests[AutoForge.UnitTests] --> Components
|
||||
UnitTests --> Core
|
||||
UnitTests --> App
|
||||
UnitTests --> Diagnostics
|
||||
UnitTests --> Simulation
|
||||
IntegrationTests[AutoForge.IntegrationTests] --> UI
|
||||
IntegrationTests --> Application
|
||||
IntegrationTests --> App
|
||||
IntegrationTests --> Core
|
||||
IntegrationTests --> Diagnostics
|
||||
IntegrationTests --> Simulation
|
||||
```
|
||||
|
||||
## Projects and dependency boundaries
|
||||
|
||||
All seven projects are in [AutoForge.slnx](../src/AutoForge.slnx):
|
||||
All nine projects are in [AutoForge.slnx](../src/AutoForge.slnx):
|
||||
|
||||
| Project | Target and responsibility | Project references |
|
||||
|---|---|---|
|
||||
| [Core](../src/AutoForge.Core/AutoForge.Core.csproj) | `net10.0`; platform-neutral target and immutable vehicle-profile/module/capability/provenance invariants | None |
|
||||
| [Application](../src/AutoForge.Application/AutoForge.Application.csproj) | `net10.0`; target-selection and vehicle-profile import/catalog/select/export feature slices | Core |
|
||||
| [Diagnostics](../src/AutoForge.Diagnostics/AutoForge.Diagnostics.csproj) | `net10.0`; provider/session/transport contracts, synthetic protocol v1 codec/client, typed operation results and bounded trace | Core |
|
||||
| [Simulation](../src/AutoForge.Simulation/AutoForge.Simulation.csproj) | `net10.0`; validated data-driven virtual modules, isolated state, provider factory and deterministic in-process transport | Core, Diagnostics |
|
||||
| [Application](../src/AutoForge.Application/AutoForge.Application.csproj) | `net10.0`; target/profile/diagnostic-session feature slices | Core, Diagnostics |
|
||||
| [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 |
|
||||
| [Client](../src/AutoForge.Client/AutoForge.Client.csproj) | `net10.0-windows10.0.26100.0`; only MAUI Blazor Hybrid application executable | Application, UI |
|
||||
| [UnitTests](../src/tests/AutoForge.UnitTests/AutoForge.UnitTests.csproj) | `net10.0`; descriptor/resolver, rendered component, profile-domain and strict JSON tests | Application, Components, Core |
|
||||
| [IntegrationTests](../src/tests/AutoForge.IntegrationTests/AutoForge.IntegrationTests.csproj) | `net10.0`; real DI, synthetic profile fixture, rendered RCL and actual project-graph tests | Application, Components, Core, UI |
|
||||
| [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 |
|
||||
| [UnitTests](../src/tests/AutoForge.UnitTests/AutoForge.UnitTests.csproj) | `net10.0`; Core/Application/contracts, protocol and reusable component tests | Application, Components, Core, Diagnostics, Simulation |
|
||||
| [IntegrationTests](../src/tests/AutoForge.IntegrationTests/AutoForge.IntegrationTests.csproj) | `net10.0`; real DI, fixtures, provider transport/session and rendered UI/project-graph tests | Application, Components, Core, Diagnostics, Simulation, UI |
|
||||
|
||||
Components has no AutoForge project dependency. UI never references Client.
|
||||
Core and Application never reference UI/Components/Client or tests. There are no
|
||||
cycles or production-to-test edges. Tests render UI directly and never reference
|
||||
or launch Client.
|
||||
Components has no AutoForge project dependency. UI never references Client or
|
||||
Simulation. Application never references Simulation, UI, Components or Client.
|
||||
Core, Diagnostics and Simulation do not reference Application/UI/Client.
|
||||
Simulation's internal test oracle is available only to the integration-test
|
||||
assembly; it is not part of the production diagnostics or UI contract. There are
|
||||
no cycles or production-to-test edges. Tests render UI directly and never
|
||||
reference or launch Client.
|
||||
|
||||
The Client contains only MAUI lifecycle/startup, its Windows platform entry
|
||||
point, the `BlazorWebView`, host HTML/CSS and in-process composition. It registers
|
||||
an empty target metadata set deliberately, so the real selection use case reports
|
||||
not-registered until an explicit future composition supplies real metadata.
|
||||
Vehicle profiles use a distinct per-process in-memory catalog; importing one does
|
||||
not register or alter an execution target. No fake connected/available provider
|
||||
is added.
|
||||
The Client composes one `SimulatedDiagnosticTransportFactory` with both truck and
|
||||
orchard definitions. `AddAutoForgeDiagnostics` registers that factory's target
|
||||
descriptor and operational transport from the same registration data. Target
|
||||
metadata resolution remains a separate, metadata-only action. The profile
|
||||
catalog is process-local; importing does not select a revision or open a session.
|
||||
Replay and physical kinds have no operational implementation and are never
|
||||
substituted with Simulation.
|
||||
|
||||
## UI ownership and real routes
|
||||
|
||||
|
|
@ -55,76 +70,79 @@ assembly, not the native Client assembly.
|
|||
|
||||
| Route | UI owner | Implemented behavior |
|
||||
|---|---|---|
|
||||
| `/` | `Features/Foundation/Home.razor` | Describes the current foundation and accurately distinguishes implemented from absent features |
|
||||
| `/execution-targets` | `Features/ExecutionTargets/SelectExecutionTarget/ExecutionTargetSelectionPage.razor` | Requires explicit provider identifier and target kind, calls the real injected application resolver and displays success/errors |
|
||||
| `/vehicle-profiles` | `Features/Vehicles/Profiles/VehicleProfilesPage.razor` | Explicitly imports schema-v1 JSON, lists profile revisions, requires exact selection, renders metadata/provenance/unknowns and exposes read-only JSON export |
|
||||
| Any unmatched route | `Features/Foundation/NotFoundPage.razor` via UI `Routes.razor` | Presents an explicit not-found page and supported navigation |
|
||||
| `/` | `Features/Foundation/Home.razor` | Describes the synthetic diagnostic workflow and distinguishes it from dynamics and physical operations |
|
||||
| `/execution-targets` | `Features/ExecutionTargets/SelectExecutionTarget/ExecutionTargetSelectionPage.razor` | Explicitly resolves registered provider metadata only; does not open a session |
|
||||
| `/vehicle-profiles` | `Features/Vehicles/Profiles/VehicleProfilesPage.razor` | Explicit schema-v1 import, exact revision selection, metadata/provenance inspection and read-only export |
|
||||
| `/diagnostics` | `Features/Vehicles/Diagnostics/DiagnosticsPage.razor` | Explicit saved profile/revision/provider/kind selection, session lifecycle, separate expected/probed/identified counts, retained partial probe services, identity-gated DTC/static signal operations, clear acknowledgement plus fresh-empty-readback verification, and raw/decoded trace |
|
||||
| Any unmatched route | `Features/Foundation/NotFoundPage.razor` via UI `Routes.razor` | Explicit not-found page and supported navigation |
|
||||
|
||||
`Layout/MainLayout.razor` supplies main navigation, shared layout and a permanent
|
||||
metadata-only limitation statement. The generic
|
||||
[StatusNotice](../src/AutoForge.Components/StatusNotice.razor) is shared by the
|
||||
home, target-selection, profile and not-found pages; isolated CSS bundles from both RCLs
|
||||
are imported through the Client scoped-style bundle.
|
||||
The generic [StatusNotice](../src/AutoForge.Components/StatusNotice.razor)
|
||||
provides accessible status/error feedback. The diagnostics page loads its
|
||||
source-controlled synthetic profile example only after the user clicks its
|
||||
import action; it does not select the new profile. Every operational action
|
||||
requires an explicitly opened Simulation session. The page labels values as
|
||||
static synthetic snapshots and exposes transport outcomes instead of treating
|
||||
timeouts/no-responses as empty data.
|
||||
Discovery preserves a validated positive probe independently from optional
|
||||
profile-verified identity. Partial rows state the identity phase and reason;
|
||||
advertised services alone never enable identity-dependent read/clear actions.
|
||||
|
||||
The target-selection page's feature-local `ExecutionTargetSelectionViewModel`
|
||||
adapts explicit input to the existing Application resolver. It contains only
|
||||
presentation state/input validation and expected error display; it does not
|
||||
reimplement provider resolution. It receives the actual `IExecutionTargetResolver`
|
||||
through DI. The same `AddAutoForgeTargetSelection` registration used in the
|
||||
headless integration tests is composed by Client.
|
||||
The feature-local target-selection view model adapts explicit input to the
|
||||
existing Application resolver. The same target resolver is populated from the
|
||||
diagnostic factories' descriptors, so `/execution-targets` shows the actual
|
||||
provider metadata without implying connection. Diagnostic sessions bind the
|
||||
exact profile revision, vehicle, target and deterministic profile-configuration
|
||||
identifier. Closing releases per-session state; resetting closes and opens a
|
||||
new session at the definition's configured initial state.
|
||||
|
||||
## Application feature organization
|
||||
The Application session use case keeps low-level `clear.dtcs` acknowledgement
|
||||
distinct from verified clear. It performs a fresh read and only marks the
|
||||
operation verified when the valid returned DTC list is empty. Failed or
|
||||
nonempty readback remains a visible failure/uncertainty; valid remaining codes
|
||||
are retained in the UI.
|
||||
|
||||
The accepted target-selection use case is grouped under
|
||||
`Application/Features/ExecutionTargets/SelectExecutionTarget/`; its original
|
||||
public namespace and API remain unchanged. Core still owns
|
||||
`Simulation`, `RecordedReplay`, `PhysicalHardware` and immutable target descriptor
|
||||
invariants. Application snapshots registrations, rejects duplicate IDs using
|
||||
ordinal case-insensitive comparison, resolves only exact requested metadata and
|
||||
returns the registered descriptor. Existing typed failures and no-fallback
|
||||
behavior remain unchanged.
|
||||
## Application and capability boundaries
|
||||
|
||||
The vehicle profile slice is organized under
|
||||
`Application/Features/Vehicles/Profiles/`. Core owns immutable profile identity
|
||||
and revision, vehicle facts, arbitrary module roles, operation declarations,
|
||||
capability states and provenance context. Application owns strict schema-v1
|
||||
JSON interchange plus an in-memory catalog with explicit exact
|
||||
`(profileIdentifier, revision)` selection. An import validates fully before it
|
||||
registers; duplicate identities do not replace data. The Client catalog is
|
||||
process-local and is not persistent.
|
||||
The accepted target-selection use case remains grouped under
|
||||
`Application/Features/ExecutionTargets/SelectExecutionTarget/`. It snapshots
|
||||
registrations, rejects duplicate IDs using ordinal case-insensitive comparison,
|
||||
resolves only exact requested metadata and preserves typed no-fallback failures.
|
||||
|
||||
The profile UI invokes the real import/list/select/export service through DI and
|
||||
never auto-selects an imported/latest profile. Unknown optional facts remain
|
||||
explicit `null`. Capability states and provenance are declarations only. Detailed
|
||||
field, identifier, applicability and unknown-property rules are in the
|
||||
[schema-v1 guide](vehicle-profile-schema-v1.md) and
|
||||
[ADR-0003](adr-0003-profile-interchange-v1.md).
|
||||
The vehicle profile slice remains under `Application/Features/Vehicles/Profiles/`.
|
||||
Core owns immutable profile identity/revision, vehicle facts, arbitrary module
|
||||
roles, capability states and provenance context. Application owns strict
|
||||
schema-v1 JSON interchange and an in-memory catalog with exact
|
||||
`(profileIdentifier, revision)` selection. Existing schema-v1 profile JSON is
|
||||
unchanged.
|
||||
|
||||
New use cases should be cohesive and independently testable slices. Each slice
|
||||
owns its request/coordination and relevant application contract without forcing
|
||||
unrelated projects to depend on Application. Domain engines/protocols remain
|
||||
platform-neutral and can be extracted only when a real boundary warrants it.
|
||||
Do not add mediator boilerplate, generic manager/repository layers or empty
|
||||
future slices to demonstrate architecture.
|
||||
`AutoForge.Diagnostics` defines provider-neutral endpoint, transport, session,
|
||||
protocol-client, logical-clock, operation-result and trace contracts. Its
|
||||
synthetic protocol v1 encodes each request and decodes each actual response
|
||||
through the transport interface. `AutoForge.Simulation` supplies the only
|
||||
operational implementation in this milestone. Module IDs, endpoint addresses,
|
||||
identities, supported synthetic services, initial DTC state, static signals and
|
||||
deterministic faults come from validated source-controlled definitions, not
|
||||
hard-coded application roles or profile capability claims. Details and honest
|
||||
limitations are in the [protocol guide](synthetic-diagnostics-v1.md) and
|
||||
[simulation guide](simulation.md).
|
||||
|
||||
## Honest limitations and safety boundaries
|
||||
|
||||
Current work implements application-shell/navigation behavior, accessible status
|
||||
presentation, explicit execution-target metadata selection and **synthetic,
|
||||
in-memory vehicle/module profile metadata interchange and selection**. The
|
||||
profiles are not vehicle discovery or compatibility data. The product still does
|
||||
not implement connection/discovery, simulation, diagnostics, telemetry, replay,
|
||||
backups, calibration values/editing, persistent storage, AI, cloud services,
|
||||
operation execution or hardware integration. A `SUPPORTED` declaration, a
|
||||
`VERIFIED` provenance label, physical-kind metadata or a calibration reference
|
||||
does not implement or authorize an operation.
|
||||
Implemented diagnostics are synthetic, in-process and Simulation-only. They
|
||||
prove the encoded request/response path and deterministic module behavior, not
|
||||
vehicle compatibility, access, authenticity, real capture or permission.
|
||||
Telemetry is a static synthetic state snapshot, not vehicle dynamics. Virtual
|
||||
DTC clear mutates only the selected in-memory virtual module/session and has no
|
||||
physical write path. Acknowledgement alone is not evidence that virtual state
|
||||
changed. No real vehicle, physical adapter, replay provider,
|
||||
programming, calibration values, backups, AI, persistence or cloud service is
|
||||
implemented. A `SUPPORTED` declaration, `VERIFIED` provenance label, physical
|
||||
metadata kind or calibration reference does not implement or authorize an
|
||||
operation.
|
||||
|
||||
Future simulation remains deterministic and AI-independent with an isolated
|
||||
verification oracle. Future initial hardware integration is read-only. Physical
|
||||
programming requires separate operation-specific authorization and evidence.
|
||||
These are architectural requirements, not current app behavior.
|
||||
|
||||
The original [ADR-0001](adr-0001-headless-foundation.md) preserves valid foundation
|
||||
decisions but marks its dual-shell/deferred-host decision superseded.
|
||||
[ADR-0002](adr-0002-single-shell-vsa.md) is the current host and feature-slice
|
||||
decision.
|
||||
The original [ADR-0001](adr-0001-headless-foundation.md) preserves valid
|
||||
foundation decisions but marks its dual-shell/deferred-host decision
|
||||
superseded. [ADR-0002](adr-0002-single-shell-vsa.md) is the current host and
|
||||
feature-slice decision. [ADR-0004](adr-0004-synthetic-diagnostics.md) records
|
||||
the Step-03 provider/protocol boundary. Worker completion remains distinct from
|
||||
manual orchestrator acceptance.
|
||||
|
|
|
|||
|
|
@ -6,15 +6,16 @@
|
|||
- Windows SDK target 10.0.26100.0 and MAUI Windows workload manifest 10.0.110.
|
||||
- Microsoft Edge WebView2 Runtime to launch the native Blazor Hybrid Client.
|
||||
|
||||
Step-02/Step-02A verification used .NET runtime 10.0.13, workload version
|
||||
10.0.403 as listed by the installed SDK, and WebView2 Runtime 155.0.4283.62. The Client
|
||||
targets `net10.0-windows10.0.26100.0` and `win-x64`. Core, Application, UI,
|
||||
Components and both test projects target portable `net10.0`; unit/integration
|
||||
tests do not require MAUI or WebView2.
|
||||
The previously verified environment reported runtime 10.0.13, MAUI workload
|
||||
version 10.0.403 as listed by the installed SDK, and WebView2 Runtime
|
||||
155.0.4283.62. The Client targets `net10.0-windows10.0.26100.0` and `win-x64`.
|
||||
All other projects target portable `net10.0`; tests do not require MAUI or
|
||||
WebView2.
|
||||
|
||||
## Restore, build and launch
|
||||
## Restore, build, test and launch
|
||||
|
||||
From the repository root in PowerShell:
|
||||
From the repository root in PowerShell, run the full build and both suites
|
||||
sequentially:
|
||||
|
||||
```powershell
|
||||
dotnet restore .\src\AutoForge.slnx
|
||||
|
|
@ -23,21 +24,19 @@ dotnet test .\src\AutoForge.slnx --configuration Release --no-build
|
|||
dotnet run --project .\src\AutoForge.Client\AutoForge.Client.csproj --configuration Release --framework net10.0-windows10.0.26100.0
|
||||
```
|
||||
|
||||
For an explicit Windows runtime pack restore or a direct native build:
|
||||
The build includes the actual native Client and all nine solution projects.
|
||||
For an explicit Windows runtime pack restore or direct native build:
|
||||
|
||||
```powershell
|
||||
dotnet restore .\src\AutoForge.Client\AutoForge.Client.csproj --runtime win-x64
|
||||
dotnet build .\src\AutoForge.Client\AutoForge.Client.csproj --configuration Release --framework net10.0-windows10.0.26100.0 --no-restore
|
||||
```
|
||||
|
||||
The Client is a native MAUI window containing the actual `AutoForge.UI` routes in
|
||||
a BlazorWebView. Profiles are imported explicitly into an in-memory catalog for
|
||||
the current Client process. No automotive driver, actual vehicle, database,
|
||||
backend, model or cloud account is required.
|
||||
Do not pass Windows TFM overrides to the portable test projects. The Client
|
||||
contains the real UI RCL in a native MAUI BlazorWebView. No automotive driver,
|
||||
actual vehicle, database, backend, model or cloud account is required.
|
||||
|
||||
## Automated verification
|
||||
|
||||
Run focused suites while developing:
|
||||
## Focused tests
|
||||
|
||||
```powershell
|
||||
dotnet test .\src\tests\AutoForge.UnitTests\AutoForge.UnitTests.csproj --configuration Release
|
||||
|
|
@ -45,55 +44,103 @@ dotnet test .\src\tests\AutoForge.IntegrationTests\AutoForge.IntegrationTests.cs
|
|||
```
|
||||
|
||||
The unit suite covers existing Core/Application behavior, rendered generic
|
||||
components, profile invariants and strict codec behavior. The integration suite
|
||||
loads source-controlled synthetic fixtures through the real DI service/catalog,
|
||||
selects exact revisions, verifies semantic JSON round-trip and atomic failure,
|
||||
retains target-selection behavior, and renders the real profile UI. The
|
||||
project-graph test continues to enforce the seven-project reference boundaries.
|
||||
Fixtures are copied from `src/tests/AutoForge.IntegrationTests/Fixtures` and are
|
||||
never treated as real vehicle definitions.
|
||||
components, profile invariants and strict codec behavior, plus protocol v1
|
||||
round-trip/snapshot contracts and bounded trace behavior. The integration suite
|
||||
loads source-controlled profile fixtures through real DI, opens actual
|
||||
simulation sessions, sends/decodes requests through the transport, verifies
|
||||
identity/DTC/static signals, virtual clear/readback/reset and independent
|
||||
session state, exercises deterministic malformed/no-response/timeout/cancelled
|
||||
faults, renders the diagnostic route against the actual provider, and checks
|
||||
the nine-project reference graph. Fixtures are never treated as real vehicle
|
||||
definitions. The internal state oracle is exposed only to the integration-test
|
||||
assembly.
|
||||
|
||||
Step-02 worker verification covered 59 unit and 34 integration cases (93 total).
|
||||
Those historical runs did not include the two defects later assigned to Step-02A.
|
||||
Step-02A added focused pre-fix reproductions, then verified the corrected
|
||||
timestamp and applicability paths along with the full regression suites: 103
|
||||
unit and 37 integration tests passed (140 total, zero failed/skipped). The
|
||||
seven-project Release build completed with zero warnings/errors. See the
|
||||
[Step-02 report](../prompts/Step-02-Report.md) for the original evidence and the
|
||||
[Step-02A report](../prompts/Step-02A-Report.md) for exact corrective commands
|
||||
and separate native observations. Manual orchestrator acceptance remains pending.
|
||||
The accepted Step-02A baseline was 103 unit plus 37 integration tests (140
|
||||
total). The Step-03 worker report records the full, expanded counts, warnings,
|
||||
commands and native observations; do not infer acceptance from these earlier
|
||||
runs. Historical Step-02 had 59 unit and 34 integration cases; it predates the
|
||||
Step-02A corrections. See the [Step-02 report](../prompts/Step-02-Report.md) and
|
||||
[Step-02A report](../prompts/Step-02A-Report.md) for historical evidence.
|
||||
|
||||
## Native profile smoke procedure
|
||||
Step-03 worker verification ran the nine-project Release build with zero
|
||||
warnings/errors, then passed 108 unit and 53 integration cases (161 total,
|
||||
zero failed/skipped). Its native smoke used the actual Windows Client and
|
||||
verified explicit synthetic selection, module probes/identity, DTC and static
|
||||
signals, raw request/reply trace, virtual clear/readback/reset, close, target
|
||||
metadata, profile, home and not-found routes. Exact observations and limitations
|
||||
are recorded in the [Step-03 worker report](../prompts/Step-03-Report.md);
|
||||
the run did not cover the subsequently identified integrity findings and Step-03
|
||||
was not accepted.
|
||||
|
||||
Run the actual Windows Client and open `/vehicle-profiles`:
|
||||
Step-03A added actual failing-before/passing-after regressions for missing and
|
||||
duplicate request fields, semantic response validation/trace consistency, and
|
||||
clear acknowledgement versus verified readback. The final sequential Release
|
||||
verification passed 111 unit tests and 64 integration tests (175 total, zero
|
||||
failed/skipped), preserving the original 161 cases plus 14 additional test
|
||||
cases. Exact commands and outcome details are in the
|
||||
[Step-03A corrective report](../prompts/Step-03A-Report.md). Manual
|
||||
orchestrator acceptance remains pending.
|
||||
|
||||
1. Paste `synthetic-truck-baseline.json` from the integration-test `Fixtures`
|
||||
folder and import it. Confirm the revision appears but is not auto-selected.
|
||||
2. Select revision 1. Inspect module identities, the five declared capability
|
||||
states, `null`/unknown values, SYNTHETIC provenance and limitations. Export
|
||||
the selected revision and verify schema version/identity remain intact.
|
||||
3. Paste/import `synthetic-truck-variant.json`; select revision 2 explicitly and
|
||||
verify its calibration identity differs while revision 1 remains unchanged.
|
||||
4. Attempt duplicate import and malformed JSON; observe an error, unchanged
|
||||
catalog and unchanged selected profile.
|
||||
5. Verify the alternate vehicle/custom role fixture can be imported and selected.
|
||||
6. Confirm `/`, `/execution-targets` and an unmatched route still work, and that
|
||||
profile import/selection did not create or alter execution-target providers.
|
||||
7. Verify a complete timestamp with `Z` or a signed offset imports and round-trips;
|
||||
a time-only timestamp shows its exact evidence JSON path and is not registered.
|
||||
8. Verify module-scoped evidence with null hardware/software/firmware/calibration
|
||||
constraints stays null after export even when the module identities are known.
|
||||
A supplied conflicting identity must show an error without replacing the
|
||||
catalog entry or selected profile.
|
||||
Step-03B reproduced the probe-only identity-loss defect before the fix through
|
||||
the real Simulation transport: the regression expected a positive probe but
|
||||
observed a negative discovery outcome. After the correction, the focused
|
||||
protocol/UI integration selection passed 35 cases. The complete nine-project
|
||||
Release build passed with zero warnings and errors, and the complete suite
|
||||
passed 111 unit plus 72 integration tests (183 total, zero failed/skipped),
|
||||
preserving all 175 Step-03A cases. Exact commands and AC mapping are recorded in
|
||||
the [Step-03B corrective report](../prompts/Step-03B-Report.md).
|
||||
|
||||
Native route/interaction evidence is distinct from headless rendered tests.
|
||||
Worker evidence records the launch method and actual observed outcomes in the
|
||||
Step-02 and Step-02A reports.
|
||||
The native Windows Client was launched and the operational baseline was
|
||||
exercised in its own WebView: explicit example import/profile/revision/provider/
|
||||
Simulation selection, session open, discovery with expected/probe/identity
|
||||
counts, configured transmission no-response, engine DTC/static-signal reads,
|
||||
verified clear with fresh empty readback, raw/decoded trace, reset with initial
|
||||
DTC restoration, close, and `/execution-targets`, `/vehicle-profiles`, `/`,
|
||||
and not-found routes. Exact observations and limitations are in the
|
||||
[Step-03B corrective report](../prompts/Step-03B-Report.md). Native interaction
|
||||
used a session-local WebView debug port on the worker-launched Client; partial
|
||||
identity remains covered by real-DI rendered tests because the shipped native
|
||||
configuration has no fault selector for that scenario.
|
||||
|
||||
## Schema and safety boundaries
|
||||
## Native synthetic diagnostics smoke
|
||||
|
||||
See the [schema-v1 guide](vehicle-profile-schema-v1.md) for all field, identity,
|
||||
unknown-value, capability, provenance and strict JSON rules. In brief:
|
||||
Launch the actual Windows Client and visit `/diagnostics`:
|
||||
|
||||
1. Confirm the page starts without selecting/importing a profile or opening a
|
||||
session. Click **Load synthetic truck example**; verify the profile appears
|
||||
as an available revision but remains unselected.
|
||||
2. Explicitly select `autoforge.synthetic.test-truck`, revision `1`, provider
|
||||
`autoforge.simulation.synthetic`, and kind `Simulation`. Click **Open
|
||||
simulation session** and confirm the visible session/profile/provider/
|
||||
configuration identity. The session opens in process only.
|
||||
3. Click **Probe virtual modules**. Engine/body respond; the configured
|
||||
transmission endpoint visibly reports no response and is not reported as an
|
||||
actual responder. Inspect the identity and declared implemented services.
|
||||
4. Read the engine's DTCs and static signals. Values are synthetic static
|
||||
snapshots with source, unit, quality and logical tick. Expand the bounded
|
||||
trace to inspect actual request/response JSON and correlation values.
|
||||
5. Clear the supported engine virtual DTCs, confirm the fresh readback is empty,
|
||||
and confirm the UI explicitly states that no physical write occurred. Other
|
||||
module/session state is isolated.
|
||||
6. Exercise a visible deterministic failure (for example the configured
|
||||
transmission no-response), then reset to the initial synthetic state and
|
||||
close the session. Closing releases that session's trace and virtual state.
|
||||
7. Separately visit `/execution-targets`, `/vehicle-profiles`, `/`, and an
|
||||
unmatched route. Confirm metadata selection remains separate from an
|
||||
operational session and the not-found/navigation behavior remains.
|
||||
|
||||
The Step-03A report records actual native baseline smoke separately from
|
||||
headless rendered fault tests. The native Client revalidated explicit
|
||||
profile/provider selection, successful clear with fresh empty readback,
|
||||
trace/raw frames, visible no-response, reset/initial-state restoration, close
|
||||
and existing routes. A deliberately false clear acknowledgement was injected
|
||||
only in the rendered integration composition; the production Client has no UI
|
||||
fault selector, so this is not native fault-injection evidence.
|
||||
|
||||
## Profile-schema and safety boundaries
|
||||
|
||||
See the [schema-v1 guide](vehicle-profile-schema-v1.md) for field, identity,
|
||||
unknown-value, capability, provenance and strict JSON rules. Important invariants:
|
||||
|
||||
- Every v1 field is required; unknown optional facts are explicit JSON `null`.
|
||||
Unknown fields and duplicate/case-ambiguous properties are rejected.
|
||||
|
|
@ -105,9 +152,11 @@ unknown-value, capability, provenance and strict JSON rules. In brief:
|
|||
- A null optional module identity in evidence is an absent constraint. Any
|
||||
supplied identity must match a known module value; an unknown target or
|
||||
mismatch is rejected without identity inference.
|
||||
- Imported profiles and capability/provenance statements are immutable metadata,
|
||||
not connection, compatibility, a working service or authorization.
|
||||
- Imported profiles and capability/provenance statements are immutable
|
||||
metadata, not connection, compatibility, a working service or authorization.
|
||||
- Data remains in memory for the process only. JSON import/export does not write
|
||||
files or timestamps implicitly.
|
||||
- There is no simulation engine, diagnostic transport, calibration data editor,
|
||||
firmware image, operation executor, AI, persistent store or hardware adapter.
|
||||
- Simulation uses the separate [synthetic protocol](synthetic-diagnostics-v1.md)
|
||||
and [definition guide](simulation.md). It is not a real vehicle adapter,
|
||||
dynamics model, telemetry capture, replay provider, calibration/firmware
|
||||
editor or hardware write path.
|
||||
|
|
|
|||
|
|
@ -0,0 +1,96 @@
|
|||
# Synthetic simulation definitions and state
|
||||
|
||||
## Definition boundary
|
||||
|
||||
Vehicle-profile JSON remains the strict schema-v1 metadata contract. Endpoint
|
||||
addresses, implemented services, initial DTC state, static signals, response
|
||||
latency and deterministic faults live in a separate source-controlled
|
||||
`SimulationDefinition`, not in profile JSON.
|
||||
|
||||
The `SyntheticDiagnosticExamples` catalog contains two inventories:
|
||||
|
||||
- `autoforge.synthetic.test-truck` revision 1: a synthetic engine controller,
|
||||
transmission controller and cabin/body controller.
|
||||
- `autoforge.synthetic.orchard-cart` revision 1: an alternate inventory with a
|
||||
custom experimental sensor-bridge role.
|
||||
|
||||
IDs, names, identities and declared configuration are intentionally synthetic.
|
||||
The truck has no-response configured for the transmission probe to demonstrate
|
||||
that expected inventory is not the same as actual discovery. The body module
|
||||
returns an explicit unsupported negative response to virtual DTC clear. The
|
||||
engine has one initial virtual DTC and supports virtual clear.
|
||||
|
||||
`SimulationDefinition.ValidateAgainst` requires the exact profile identifier
|
||||
and revision, one unique mapping for every profile module and matching role,
|
||||
name and supplied hardware/software/firmware/calibration identity. Endpoint
|
||||
addresses and module IDs are unique. Service identifiers must be known protocol
|
||||
v1 synthetic services; signal IDs, units, JSON values, DTC values and fault
|
||||
entries are validated. Profile capability/provenance declarations do not
|
||||
enable or prove a virtual service.
|
||||
|
||||
Definitions may advertise `probe` without `read.identity`. Discovery then
|
||||
retains the validated probe and its advertised services, marks identity as not
|
||||
attempted with an explicit reason, and does not synthesize identity from the
|
||||
matching profile entry. Expected endpoints, positive probes and identities
|
||||
verified against the selected profile are counted separately. Advertised
|
||||
read/clear services do not enable UI actions until runtime identity is verified.
|
||||
|
||||
## Session state
|
||||
|
||||
Opening a new Simulation session creates independent DTC state for each virtual
|
||||
module from its configured initial values. A successful `clear.dtcs` response
|
||||
acknowledges the request but is not itself proof of a state change. The
|
||||
Application clear-and-verify use case issues a fresh `read.dtcs` request and
|
||||
reports success only for a valid empty readback. A nonempty readback remains
|
||||
visible and fails verification; timeout, cancellation, closed session,
|
||||
no-response or malformed/negative readback is explicit uncertainty, never
|
||||
verified success. An already-empty module can still verify successfully even
|
||||
when the acknowledgement count is zero. These semantics concern virtual
|
||||
in-memory state only; no physical write occurs.
|
||||
|
||||
An accepted clear changes only that module in that session. Opening a second
|
||||
session starts with the definition's original initial values.
|
||||
Reset explicitly closes the old session and opens a new one against the same
|
||||
exact profile revision/provider/configuration, thereby restoring initial state
|
||||
and starting a new trace. Closing releases the old transport and its trace/state.
|
||||
No profile metadata or another session is mutated.
|
||||
|
||||
Normal Application/UI consumers see state only through encoded diagnostic
|
||||
requests and typed responses. An internal simulation oracle is granted only to
|
||||
the IntegrationTests assembly so tests can independently assert clear/reset/
|
||||
isolation behavior; it is not a public provider or application service.
|
||||
|
||||
## Static signals
|
||||
|
||||
Signals are configured JSON values with a source module, identifier, unit and
|
||||
quality. In this example, engine speed is the fixed synthetic value 850 rpm,
|
||||
engine supply voltage is fixed at 12.6 V, transmission state is the string
|
||||
`parked-static`, and the body module reports a static synthetic door count.
|
||||
Replies carry the logical request tick and origin `SYNTHETIC_STATIC`.
|
||||
|
||||
These are reproducible fixture values, not dynamic model output, current sensor
|
||||
data, a vehicle capture, compatibility evidence or operational advice. Unknown
|
||||
values remain unknown; there is no generated motion, fuel, road-load or
|
||||
scenario physics.
|
||||
|
||||
## Reproducible faults and lifecycle
|
||||
|
||||
`VirtualModuleDefinition` accepts a validated fault map keyed by a defined
|
||||
synthetic service, plus non-negative logical response latency. Fault modes are:
|
||||
|
||||
- `NoResponse`: no response payload arrives.
|
||||
- Latency above the protocol deadline: explicit `Timeout`, no response payload.
|
||||
- `MalformedResponse`: response bytes are retained but protocol decoding fails.
|
||||
- `WrongCorrelation`: response does not match request correlation.
|
||||
- `WrongIdentity`: identity reply names an unexpected module.
|
||||
- `HoldUntilCancelled`: pending transport work completes only on request
|
||||
cancellation or session close.
|
||||
|
||||
Fault maps are data, not random scheduling. The default truck definition
|
||||
reproducibly demonstrates a missing transmission probe response; tests construct
|
||||
other explicit vectors and assert their exact outcomes and trace records.
|
||||
|
||||
There is no physical/replay provider in this implementation. The Simulation
|
||||
provider will reject unknown or incompatible profile revisions and target
|
||||
selection does not automatically open an operational session. No simulation
|
||||
state is persisted beyond the current process/session.
|
||||
|
|
@ -0,0 +1,168 @@
|
|||
# Synthetic diagnostics protocol v1
|
||||
|
||||
## Purpose and limitations
|
||||
|
||||
Protocol v1 is a small, explicit JSON request/reply contract used only between
|
||||
the provider-neutral diagnostic protocol client and the in-process synthetic
|
||||
simulation transport. The frames are UTF-8 JSON. They are not CAN, ISO-TP, UDS,
|
||||
OBD-II, a manufacturer protocol, or a claim of vehicle compatibility. No
|
||||
physical transport or vehicle operation is implemented.
|
||||
|
||||
The actual capability path is:
|
||||
|
||||
1. `SyntheticDiagnosticProtocolClient` builds and encodes a request.
|
||||
2. The encoded bytes cross `IDiagnosticTransport.SendAsync`.
|
||||
3. The simulation transport decodes the request, checks its bound session and
|
||||
profile/configuration, selects a configured virtual endpoint by address and
|
||||
service, and creates a response or explicit transport outcome.
|
||||
4. The protocol client validates the response envelope/correlation and decodes
|
||||
service data into typed results. Identity is compared with the exact selected
|
||||
profile snapshot.
|
||||
5. The exchange is added to that session's bounded trace with copied payloads
|
||||
and logical timing.
|
||||
|
||||
The application and UI never read the simulation module objects directly.
|
||||
|
||||
## Request
|
||||
|
||||
The request contains protocol version, session/profile/configuration identity,
|
||||
correlation identifier, target address, service identifier, logical start tick
|
||||
and logical timeout:
|
||||
|
||||
```json
|
||||
{
|
||||
"version": 1,
|
||||
"sessionIdentifier": "diagnostic-session-000001",
|
||||
"profileIdentifier": "autoforge.synthetic.test-truck",
|
||||
"profileRevision": 1,
|
||||
"configurationIdentifier": "profile:autoforge.synthetic.test-truck@revision:1",
|
||||
"correlationIdentifier": "diagnostic-session-000001-000001",
|
||||
"targetAddress": "10",
|
||||
"service": "probe",
|
||||
"logicalTimeTicks": 0,
|
||||
"timeoutTicks": 5
|
||||
}
|
||||
```
|
||||
|
||||
All ten top-level fields shown are required on the wire. Protocol fields use
|
||||
exact camelCase spelling; names are case-sensitive. The decoder rejects a
|
||||
missing field rather than filling it from a C# initializer or primitive
|
||||
default. An explicitly supplied `logicalTimeTicks: 0` is valid. Unknown fields,
|
||||
case variants and duplicate properties are rejected recursively before session
|
||||
binding, endpoint selection or service dispatch. A malformed request receives
|
||||
the transport's explicit no-response outcome; it does not dispatch a service,
|
||||
and no response correlation is fabricated from ambiguous input. A complete
|
||||
request with explicit version `2` remains distinguishable and receives the
|
||||
typed `UNSUPPORTED_VERSION` negative response.
|
||||
|
||||
The address is a one-to-four digit hexadecimal text value. Module IDs are
|
||||
separate diagnostic context and are never inferred from an address alone. The
|
||||
current service identifiers are `probe`, `read.identity`, `read.dtcs`,
|
||||
`clear.dtcs` and `read.signals`. These are AutoForge's synthetic service names,
|
||||
not standardized vehicle commands.
|
||||
|
||||
## Reply and failures
|
||||
|
||||
Every received reply includes version, session/configuration, correlation,
|
||||
target address, service, a success flag, optional error code/message and data.
|
||||
A positive example:
|
||||
|
||||
```json
|
||||
{
|
||||
"version": 1,
|
||||
"sessionIdentifier": "diagnostic-session-000001",
|
||||
"configurationIdentifier": "profile:autoforge.synthetic.test-truck@revision:1",
|
||||
"correlationIdentifier": "diagnostic-session-000001-000001",
|
||||
"targetAddress": "10",
|
||||
"service": "probe",
|
||||
"success": true,
|
||||
"errorCode": null,
|
||||
"error": null,
|
||||
"data": {
|
||||
"moduleIdentifier": "module.engine.primary",
|
||||
"implementedServices": ["probe", "read.identity", "read.dtcs", "clear.dtcs", "read.signals"]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
A negative service reply uses `success: false`, a typed error code/message and
|
||||
`data: null`; an unsupported operation is never represented as a successful
|
||||
empty collection. Wrong version, session/configuration, correlation, address or
|
||||
service is rejected. Malformed JSON or required fields produce
|
||||
`ProtocolError`. A valid DTC reply with an empty `codes` array is distinct from
|
||||
all failures.
|
||||
|
||||
Discovery records the validated probe and identity exchange as separate
|
||||
results. A positive probe retains its validated module ID and immutable
|
||||
advertised service list even if identity is later unavailable, negative,
|
||||
malformed, mismatched, timed out or cancelled. If `read.identity` was not
|
||||
advertised, the client does not send that unsupported request and records an
|
||||
explicit not-attempted reason. A failed probe has no advertised services and
|
||||
identity remains not attempted. The result exposes expected endpoint count,
|
||||
validated positive probe count and profile-verified identity count separately.
|
||||
Profile metadata never fills an absent runtime identity or grants permission.
|
||||
The UI shows partial probe evidence, but identity-dependent read/clear actions
|
||||
remain disabled until identity is validated against the selected profile.
|
||||
|
||||
The receiver requires every envelope field shown, exact camelCase spelling,
|
||||
unique properties at every object level and no unknown fields. Positive replies
|
||||
must carry an object `data` and null `errorCode`/`error`; negative replies must
|
||||
carry nonblank `errorCode`/`error` and null `data`. Each interpreted service
|
||||
object has its own exact required-field set. Identifiers/text must be nonblank
|
||||
and trimmed; DTC codes, advertised services and signal identifiers are unique.
|
||||
Probe replies must name the requested module and advertise only known, unique
|
||||
v1 service tokens, including `probe`. Identity is compared with the selected
|
||||
profile snapshot. Static-signal source/module and quality are validated; the
|
||||
snapshot logical tick must equal the request start tick. Any invalid or
|
||||
ambiguous response produces `ProtocolError` with no partial result value.
|
||||
Signal `value` remains an explicit arbitrary JSON value, including `null` for
|
||||
unknown; protocol envelope/service objects themselves reject unknown members.
|
||||
|
||||
No-response, timeout and cancellation are transport outcomes, not fabricated
|
||||
JSON replies. Their trace record has the immutable request bytes and no response
|
||||
payload. A configured no-response endpoint is not counted as a validated probe;
|
||||
an earlier successful probe remains positive in its own trace record even when
|
||||
the subsequent identity exchange fails.
|
||||
|
||||
An accepted `clear.dtcs` positive response is only an acknowledgement. The
|
||||
Application clear-and-verify use case performs a fresh `read.dtcs` request and
|
||||
reports verified success only when that valid response contains an empty code
|
||||
set. A nonempty readback is retained as observed data and reported as a
|
||||
verification failure; any failed/uncertain readback is not a verified clear.
|
||||
This result describes in-memory Simulation state only; it is not a physical
|
||||
write.
|
||||
|
||||
## Logical timing and concurrency
|
||||
|
||||
The logical clock is injected per diagnostic session. Successful transport
|
||||
delivery advances it by deterministic configured response ticks; no
|
||||
wall-clock-based fault choice or random delay is used. A request includes a
|
||||
logical timeout of five ticks. A virtual latency greater than the deadline
|
||||
returns Timeout without a response. The protocol client serializes exchanges
|
||||
per session so correlation sequence, logical time and retained trace order stay
|
||||
consistent.
|
||||
|
||||
`HoldUntilCancelled` is a deterministic blocking fault released only by
|
||||
cancellation or session close. No `Thread.Sleep` is used. The logical clock is
|
||||
for diagnostics only; it is not the Step-04 dynamics/scenario clock.
|
||||
|
||||
## Trace
|
||||
|
||||
Each session keeps at most 200 in-memory records. Every record contains session
|
||||
identity (including exact target/profile/revision/configuration), module/address,
|
||||
correlation, service, start/end logical ticks, copied request bytes, optional
|
||||
copied response bytes, typed outcome, decoded summary and explicit error text.
|
||||
The oldest entry is dropped at capacity and `DroppedRecordCount` increases.
|
||||
The response is validated completely before positive result and trace commitment;
|
||||
semantic probe failures therefore have one `ProtocolError` record with the
|
||||
actual raw reply instead of a positive record followed by a contradictory
|
||||
discovery result.
|
||||
The trace is session-local, not persistent logging, telemetry recording or
|
||||
replay. Closing the session releases the trace with its transport state.
|
||||
Cancellation after a successful probe retains that phase's probe/service facts
|
||||
and records cancellation only for the pending identity exchange; closing the
|
||||
session suppresses stale UI updates and releases the active session results.
|
||||
|
||||
The UI renders decoded summaries and lets the user inspect raw UTF-8 request and
|
||||
response JSON. It labels synthetic operation results and never describes them
|
||||
as live vehicle capture.
|
||||
|
|
@ -3,11 +3,12 @@
|
|||
## Status and authority
|
||||
|
||||
- Initialized: 2026-10-28.
|
||||
- Current phase: corrected profile milestone accepted; simulated diagnostic communication next.
|
||||
- Active assignment: [Step-03](Step-03.md), ready for manual worker execution.
|
||||
- Last accepted milestone: Step-02 with Step-02A, accepted 2026-10-28.
|
||||
- Current phase: corrected synthetic diagnostics accepted; deterministic dynamics next.
|
||||
- Active assignment: [Step-04](Step-04.md), ready for manual worker execution.
|
||||
- Last accepted milestone: Step-03 with Step-03A/Step-03B, accepted 2026-10-28.
|
||||
- Last accepted correction: Step-03B; all Step-03 findings closed.
|
||||
- Outstanding corrections: none.
|
||||
- Step-03 status: READY FOR WORKER; no implementation or report yet.
|
||||
- Step-04 status: READY FOR WORKER; no dynamics implementation or report yet.
|
||||
- Current state and handoff: [STATE.md](STATE.md).
|
||||
- Authority: the master charter, repository/handoff amendment, and the owner's
|
||||
2026-10-28 architectural realignment. The latest decision cancels the dual-shell
|
||||
|
|
@ -79,9 +80,9 @@ Step-01 established four projects, all preserved by Step-01A. Their current refe
|
|||
| Project | Responsibility | Allowed project references |
|
||||
|---|---|---|
|
||||
| `src/AutoForge.Core` | Platform-neutral foundational value types, invariants, and shared contracts | None |
|
||||
| `src/AutoForge.Application` | Use-case coordination and application-facing services; initially explicit execution-target selection | Core |
|
||||
| `src/tests/AutoForge.UnitTests` | Domain/application behavior and rendered generic component tests | Core, Application, Components |
|
||||
| `src/tests/AutoForge.IntegrationTests` | Real application/RCL composition and project-graph tests, without hardware/cloud | Core, Application, Components, UI |
|
||||
| `src/AutoForge.Application` | Use-case coordination and application-facing services; target/profile features and pending-review diagnostic sessions | Core, Diagnostics |
|
||||
| `src/tests/AutoForge.UnitTests` | Domain/application behavior, generic component, protocol and trace tests | Core, Application, Components, Diagnostics, Simulation |
|
||||
| `src/tests/AutoForge.IntegrationTests` | Real application/RCL/diagnostic composition and project-graph tests, without hardware/cloud | Core, Application, Components, UI, Diagnostics, Simulation |
|
||||
|
||||
The original foundation was headless. Accepted Step-01A added Client/UI/Components
|
||||
without discarding these projects or their 54 cases. The solution now has seven
|
||||
|
|
@ -102,8 +103,8 @@ Accepted Step-01A established:
|
|||
|
||||
| Project | Responsibility | Allowed project references |
|
||||
|---|---|---|
|
||||
| `src/AutoForge.Client` | Thin native MAUI startup, lifecycle, configuration, BlazorWebView hosting and DI/platform composition | UI, Application and justified platform adapters; no test projects |
|
||||
| `src/AutoForge.UI` | Complete application routes, pages, navigation, layouts, feature presentation and interaction workflows | Components, Application/contracts and justified domain contracts; never Client |
|
||||
| `src/AutoForge.Client` | Thin native MAUI startup, lifecycle, configuration, BlazorWebView hosting and DI/platform composition | UI, Application, Simulation composition and justified platform adapters; no test projects |
|
||||
| `src/AutoForge.UI` | Complete application routes, pages, navigation, layouts, feature presentation and interaction workflows | Components, Application/Diagnostics contracts and justified domain contracts; never Client/Simulation |
|
||||
| `src/AutoForge.Components` | Generic reusable status controls, inputs, gauges/charts/layout building blocks as actually needed | Framework UI dependencies; no UI, Client, hardware or application feature implementation |
|
||||
|
||||
Primary UI direction: **Client -> UI -> Components**. The shell contains only
|
||||
|
|
@ -151,14 +152,23 @@ These are logical responsibilities, not an instruction to create all assemblies
|
|||
now. Keep related responsibilities together until an actual dependency or
|
||||
platform boundary justifies extraction. Avoid premature microservices.
|
||||
|
||||
For Step-03, two concrete boundaries are now justified by actual implementation:
|
||||
Step-03 has added two actual capability boundaries:
|
||||
`AutoForge.Diagnostics` owns diagnostic/provider/transport contracts, a clearly
|
||||
synthetic protocol and decoding; `AutoForge.Simulation` implements virtual modules
|
||||
and simulated transport against those contracts. Application coordinates
|
||||
Diagnostics, not Simulation internals. Client composes Simulation in-process.
|
||||
Simulation depends on Core/Diagnostics, never Application/UI/Client or an LLM.
|
||||
These are assigned additions, not existing projects; the current solution still
|
||||
contains seven projects until the worker implements the step.
|
||||
The current solution now has nine projects. Step-03A closed the frame/reply/trace/
|
||||
clear-verification findings, and Step-03B separates successful probe evidence from
|
||||
identity availability. The corrected Step-03 milestone is accepted. Worker
|
||||
verification now covers 111 unit and 72 integration cases (183 total).
|
||||
|
||||
Step-04 extends the existing Simulation implementation with coupled dynamics and
|
||||
a fixed-step virtual clock. Shared platform-neutral configuration/control contracts
|
||||
belong in Core or an appropriate existing shared-contract location; Application
|
||||
still does not depend on Simulation implementation. No additional project is
|
||||
assigned. Static synthetic diagnostics remain available, separate from an
|
||||
explicitly selected dynamics provider/run configuration.
|
||||
|
||||
Planned dependency flow:
|
||||
|
||||
|
|
@ -237,10 +247,9 @@ UI unrestricted programming authority.
|
|||
|
||||
## Milestones and acceptance gates
|
||||
|
||||
Step-01, Step-01A and corrected Step-02/Step-02A are accepted. The original 93-case
|
||||
Step-02 run is retained as historical evidence; the correction adds actual
|
||||
before/after regressions and a 140-case passing run. Step-03 is the only active
|
||||
assignment. Step-03 and later capabilities remain unimplemented.
|
||||
Step-01, Step-01A, corrected Step-02 and corrected Step-03 are accepted. Original
|
||||
and corrective reports remain historical evidence. Step-04 is the only active
|
||||
assignment. Dynamics and later capabilities remain unimplemented.
|
||||
Dependencies indicate acceptance prerequisites, not permission for automatic
|
||||
handoff. Later assignments refine these scopes using actual implementation
|
||||
evidence; they must not silently discard required capabilities.
|
||||
|
|
@ -251,8 +260,10 @@ evidence; they must not silently discard required capabilities.
|
|||
| 01A | Single-shell and vertical-slice architectural correction | 01 accepted; owner realignment | ACCEPTED 2026-10-28 | Seven-project Client -> UI -> Components foundation; preserved Core/Application; 65 passing cases and successful solution/native build/startup reported; corrected ADR/docs inspected |
|
||||
| 02 | Vehicle profiles and module model | 01A accepted; assignment regenerated | ACCEPTED 2026-10-28 AFTER 02A | Immutable versioned profile metadata, strict interchange, provenance/capabilities, exact selection and real UI; correction evidence inspected |
|
||||
| 02A | Profile timestamp and optional evidence validation correction | 02 review findings | ACCEPTED 2026-10-28 | Explicit-offset parser and optional-constraint semantics inspected; actual pre-fix failures and 103 unit/37 integration passes plus native checks reported |
|
||||
| 03 | Virtual modules and diagnostic communication | 02 and 02A accepted | READY FOR WORKER | Explicit simulated session, wire-path module discovery/identity, synthetic DTC/read-clear and static telemetry, trace and deterministic negative/timeout/cancellation evidence |
|
||||
| 04 | Deterministic vehicle dynamics | 03 | PLANNED | Coupled engine/transmission/road-load model, virtual clock and lifecycle controls; identical scenarios/inputs reproduce outputs under a documented numerical contract |
|
||||
| 03 | Virtual modules and diagnostic communication | 02 and 02A accepted | ACCEPTED 2026-10-28 AFTER 03A/03B | Real synthetic wire/provider/session/virtual-state path, truthful phase discovery and verified clear; complete corrected evidence inspected |
|
||||
| 03A | Synthetic wire validation and verified-clear correction | 03 review findings | ACCEPTED FOR R-01/R-02/R-03 2026-10-28 | Strict wire and semantic reply validation, matching trace and Application verified clear inspected; 111 unit/64 integration passes plus native baseline reported |
|
||||
| 03B | Partial discovery and identification correction | 03A review finding R-04 | ACCEPTED 2026-10-28 | Independent probe/identity outcomes, retained partial services, accurate counts and fail-closed actions inspected; 183-case/native evidence reported |
|
||||
| 04 | Deterministic vehicle dynamics | 03, 03A and 03B accepted | READY FOR WORKER | Explicit immutable model/run configuration, fixed-step lifecycle/scenario engine, coupled SI dynamics and diagnostic dynamic telemetry; reproducibility and numeric scenario gates |
|
||||
| 05 | Live dashboard in the established Client/UI/Components architecture | 04; accepted 01A foundation | PLANNED | Feature pages select a profile, control simulation and display independently collected live telemetry through reusable Components; no new application host |
|
||||
| 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 |
|
||||
|
|
@ -296,11 +307,24 @@ evidence; they must not silently discard required capabilities.
|
|||
separate validated simulation endpoint/service definitions from profile metadata.
|
||||
A real Simulation provider is registered explicitly; update former empty-provider
|
||||
UI wording. No physical adapter or vehicle dynamics is implemented in this step.
|
||||
- **03A correction:** reject incomplete/ambiguous frames before service dispatch,
|
||||
validate decoded replies before positive results/trace, and distinguish a clear
|
||||
acknowledgement from verified empty readback. Preserve actual virtual sessions,
|
||||
state isolation, static signals, controlled faults and previous regressions.
|
||||
Do not introduce dynamics, physical adapters or an arbitrary raw-frame UI.
|
||||
- **03B correction:** preserve a validated positive probe and its advertised
|
||||
services when identity is unsupported, fails or is cancelled. Distinguish probe
|
||||
responders from identified modules; do not fabricate identity or relax existing
|
||||
identity-dependent action gates. Keep each wire exchange's truthful trace.
|
||||
- **04:** start/stop/pause/resume/reset/step, configurable pacing independent of
|
||||
simulation results, save/load configuration, seeded scenarios, engine idle,
|
||||
throttle/load/torque/fuel, transmission/shift scheduling, mass/drivetrain/road
|
||||
load, temperatures, and a stationary-to-45-MPH-to-stop scenario with a five-minute
|
||||
hold. Report mathematical assumptions and repeatability tolerances.
|
||||
hold. Bind model version/initial conditions/environment/scenario to explicit
|
||||
run identity, with versioned configuration import/export and no diagnostic-read
|
||||
driven physics. Preserve static v1 diagnostics and use an explicit versioned/
|
||||
negotiated dynamic telemetry extension with separate model and diagnostic time.
|
||||
Report mathematical assumptions and repeatability tolerances.
|
||||
- **05:** extend the already established UI feature pages with reusable data-bound
|
||||
gauges, settings, profile/module selection, connection state and diagnostics.
|
||||
Client remains thin; application slices coordinate in-process capabilities.
|
||||
|
|
@ -440,6 +464,16 @@ not proven real-world economy improvements.
|
|||
libraries, composed by the existing Client. Diagnostic application features use
|
||||
provider-neutral ports; virtual state/oracles do not leak into Application/UI.
|
||||
Initial telemetry is explicitly static synthetic module state, not vehicle physics.
|
||||
- D-015: Step-04 keeps the nine-project architecture. Simulation owns physics and
|
||||
clock implementation; Core/shared contracts expose only needed run inputs and
|
||||
controls. UI/Application read vehicle telemetry through diagnostics, not the oracle.
|
||||
- D-016: dynamics uses an explicitly selected provider/configuration, separate from
|
||||
the existing static provider. Run identity binds the exact configuration/model;
|
||||
reset preserves that binding. Dynamic wire/origin/time changes are versioned
|
||||
explicitly rather than weakening static protocol v1 or relabeling physics as static.
|
||||
- D-017: fixed virtual steps determine physics; wall pacing, UI refresh and diagnostic
|
||||
request counts cannot change results at a given model time. Full acquisition/
|
||||
recording/dashboard work remains assigned to later milestones.
|
||||
|
||||
The worker records the relevant accepted decisions as technical ADRs when creating
|
||||
or changing the implementation. Future changes require a reason and roadmap/state
|
||||
|
|
@ -492,19 +526,80 @@ history, not repeated redesign without evidence.
|
|||
counts, seven-project graph and existing outputs corroborate the report.
|
||||
The orchestrator did not run builds/tests or launch the native app.
|
||||
- Prepared [Step-03](Step-03.md) for manual handoff; no Step-02B is required.
|
||||
- Reviewed the completed Step-03 protocol/transport, definitions/session state,
|
||||
application/UI, oracle/tests, dependency graph, docs and report. Worker evidence
|
||||
records 108 unit + 53 integration passes (161 total, zero failed/skipped),
|
||||
clean complete nine-project/native Release build and actual native workflow.
|
||||
- Static source counts, project graph, restore/Release/native outputs corroborate
|
||||
the reported normal-flow checks, not independent runtime execution.
|
||||
- Found three uncovered correctness gaps and prepared [Step-03A](Step-03A.md).
|
||||
At that review Step-03 was not accepted and Step-04 was withheld; the original
|
||||
report remains preserved.
|
||||
- Reviewed Step-03A source/tests/docs and actual reported pre-fix failures:
|
||||
R-01/R-02/R-03 are closed. Required/unique fields, semantic validation before
|
||||
positive trace, and the Application clear-and-verify rule now satisfy that scope.
|
||||
- Worker reports sequential nine-project Release build with zero warnings/errors,
|
||||
111 unit + 64 integration passes (175 total, zero failed/skipped) and native
|
||||
normal-flow smoke. Injected failed-clear evidence is correctly identified as
|
||||
real DI/rendered integration, not native evidence.
|
||||
- Static source counts, graph and existing outputs corroborate the report.
|
||||
Review also found R-04: positive probe evidence was lost when the subsequent
|
||||
identity read was unavailable. Prepared [Step-03B](Step-03B.md); Step-04 was
|
||||
withheld pending that correction.
|
||||
- Reviewed and accepted Step-03B and corrected Step-03: independent probe/identity
|
||||
outcomes, retained services, accurate expected/probed/identified counts, partial
|
||||
failures/cancellation, fail-closed actions and raw exchange truthfulness.
|
||||
- Worker reports actual pre-fix failure, corrected real-DI/rendered matrix,
|
||||
complete nine-project Release build with zero warnings/errors, 111 unit +
|
||||
72 integration passes (183 total, zero failed/skipped) and native baseline smoke.
|
||||
Partial-identity fault coverage is explicitly rendered real-DI, not native.
|
||||
- Source counts, graph and existing restore/Release/native artifacts corroborate
|
||||
that evidence; the orchestrator did not run builds/tests or launch the app.
|
||||
- Prepared [Step-04](Step-04.md); no Step-03C is required.
|
||||
|
||||
### Remaining
|
||||
|
||||
- Worker execution of Step-03, then manual review and any Step-03A corrections
|
||||
before Step-04. Full vehicle dynamics and live dashboard milestones remain later.
|
||||
- Profile/module metadata is accepted. Virtual-module communication and later
|
||||
product capabilities remain planned. Preserve the complete sequence and safety
|
||||
gates rather than restarting or reducing scope.
|
||||
- Worker execution of Step-04, then manual review of numeric dynamics, lifecycle,
|
||||
configuration, wire integration and native evidence. Complete Step-04A corrections
|
||||
if needed before Step-05.
|
||||
- Profile/module metadata, synthetic virtual-module communication and static
|
||||
diagnostics are accepted; dynamics and later capabilities
|
||||
remain planned. Preserve the complete sequence and safety gates.
|
||||
|
||||
### Known blockers and uncertainties
|
||||
|
||||
No blocking profile-correction deficiency remains. The original Step-02 findings
|
||||
below are historical and resolved by accepted Step-02A:
|
||||
No blocking Step-03 correction deficiency remains. R-04 below is historical and
|
||||
closed by Step-03B, alongside Step-03A's R-01/R-02/R-03:
|
||||
|
||||
- A module can return a valid positive probe but not support `read.identity`, or
|
||||
its identity request can fail. The discovery client replaces the successful
|
||||
probe with the identity result and discards its advertised services.
|
||||
DiscoveryResult.Responders then counts only non-null identities, and UI calls
|
||||
that count "actual ... endpoint(s) responded". A reachable endpoint is therefore
|
||||
reported as not responding. The corrected result now preserves both phase
|
||||
outcomes, retained probe services, explicit unavailable identity and separate
|
||||
counts without relaxing identity-dependent action guards.
|
||||
|
||||
The worker supplied an actual pre-fix reproduction and corrected coverage for the
|
||||
valid probe-only and identity-failure cases. The orchestrator did not run them.
|
||||
|
||||
The original Step-03 R-01/R-02/R-03 findings below are historical and closed:
|
||||
|
||||
- R-01: missing request version is silently defaulted to 1, missing logical tick
|
||||
can become zero, and duplicate dispatch properties are not rejected before
|
||||
deserialization. An invalid/ambiguous frame can reach virtual service dispatch.
|
||||
- R-02: positive service payloads are not fully validated (for example negative
|
||||
signal ticks or blank identifiers/units), and a mismatched probe module is
|
||||
detected only after its trace has already recorded PositiveResponse.
|
||||
- R-03: the UI treats any successful DTC readback as proof of clearing, including
|
||||
readback that still contains codes. A positive acknowledgement is not verified
|
||||
state change.
|
||||
|
||||
Step-03A supplied actual pre-fix reproductions, corrected wire/service/UI
|
||||
regressions, documented contracts and native baseline smoke. The orchestrator did
|
||||
not execute those cases.
|
||||
|
||||
The original Step-02 findings below are historical and resolved by Step-02A:
|
||||
|
||||
- R-01 originally used permissive DateTimeOffset parsing. The replacement requires
|
||||
complete date/time/seconds and explicit Z/numeric offset, validates its calendar
|
||||
|
|
@ -532,9 +627,9 @@ Non-blocking deviations are retained explicitly:
|
|||
- Step-02 resolved the working README CRLF issue: inspection found 149 LF and
|
||||
zero CRLF lines. A command-local CR-at-EOL-aware diff check passes. No global
|
||||
Git setting was changed; the existing LF-to-CRLF notice remains non-blocking.
|
||||
- Current README/schema/ADR text must be aligned with the corrective status and
|
||||
acceptance lifecycle by Step-03's worker while preserving the original 93-case
|
||||
and corrective 140-case reports. The corrected contracts are already documented.
|
||||
- Corrected discovery/identity contracts are documented. Step-04 must align
|
||||
acceptance lifecycle text while preserving the original 161-case and corrective
|
||||
175-/183-case reports as distinct historical evidence.
|
||||
|
||||
No major environment installation, update, repair or rollback is automatically
|
||||
authorized. Physical definitions/access and programming approval remain future gates.
|
||||
|
|
|
|||
229
prompts/STATE.md
229
prompts/STATE.md
|
|
@ -5,17 +5,19 @@
|
|||
| Field | Value |
|
||||
|---|---|
|
||||
| Updated | 2026-10-28 |
|
||||
| Phase | Corrected profile milestone accepted; simulated diagnostics next |
|
||||
| Active step | Step-03 - Virtual modules and simulated diagnostic communication |
|
||||
| Assignment | [Step-03.md](Step-03.md) |
|
||||
| Phase | Corrected Step-03 accepted; deterministic vehicle dynamics next |
|
||||
| Active step | Step-04 - Deterministic vehicle dynamics and scenario execution |
|
||||
| Assignment | [Step-04.md](Step-04.md) |
|
||||
| Assignment status | READY FOR WORKER / AWAITING MANUAL HANDOFF |
|
||||
| Expected worker report | `prompts/Step-03-Report.md` - not yet created |
|
||||
| Last accepted step | Step-02 with Step-02A - accepted 2026-10-28 |
|
||||
| Expected worker report | `prompts/Step-04-Report.md` - not yet created |
|
||||
| Last accepted correction | Step-03B - accepted 2026-10-28 |
|
||||
| Last accepted major milestone | Step-03 with Step-03A/Step-03B - accepted 2026-10-28 |
|
||||
| Outstanding corrections | None |
|
||||
| Step-02 status | ACCEPTED after Step-02A |
|
||||
| Step-03 status | READY FOR WORKER |
|
||||
| Worker execution | Step-02A manually completed; Step-03 not invoked |
|
||||
| Immediate next action | User manually directs the worker to execute Step-03 only |
|
||||
| Step-03 status | ACCEPTED after Step-03A/Step-03B |
|
||||
| Step-04 status | READY FOR WORKER |
|
||||
| Worker execution | Step-03B manually completed; Step-04 not invoked |
|
||||
| Immediate next action | User manually directs the worker to execute Step-04 only |
|
||||
| Next orchestrator action | After manual return, inspect the assignment, report, implementation, tests, Git changes, documentation and recorded command evidence |
|
||||
|
||||
## Repository baseline at initialization
|
||||
|
|
@ -265,8 +267,171 @@ The original Step-02 and Step-02A assignments/reports remain historical evidence
|
|||
|
||||
Step-03 is prepared against the actual accepted profile/Application/UI baseline.
|
||||
It assigns Diagnostics and Simulation as two real new library boundaries, with
|
||||
provider-neutral Application features and Client composition. They do not exist
|
||||
yet; full dynamics/physical adapters remain outside that assignment.
|
||||
provider-neutral Application features and Client composition. They now exist
|
||||
and the corrected Step-03 milestone is accepted; dynamics/physical adapters remain
|
||||
unimplemented until their separate assignments.
|
||||
|
||||
## Historical Step-03 review and corrective decision
|
||||
|
||||
Initial decision: **REQUIRES CORRECTION**, 2026-10-28. R-01/R-02/R-03 below
|
||||
describe the pre-Step-03A code and are now closed. Step-03 still requires the
|
||||
additional R-04 correction recorded after the Step-03A review below.
|
||||
|
||||
Inspected the [assignment](Step-03.md), [worker report](Step-03-Report.md),
|
||||
Diagnostics contracts/codec/client, Simulation definitions/provider/state and
|
||||
internal oracle, application session service, UI view model/page, new protocol/
|
||||
session/rendered tests, project references, README and protocol/simulation/ADR/
|
||||
build documentation.
|
||||
|
||||
| Criterion | Review result | Evidence / remaining work |
|
||||
|---|---|---|
|
||||
| AC-01 | Preserved on inspected evidence | Nine-project graph, sole Client, no reverse references/cycles and IntegrationTests-only internal oracle |
|
||||
| AC-02 | Present on inspected evidence | Explicit exact profile/provider/kind/session selection and reset/close with no fallback |
|
||||
| AC-03 | Present; validation correction required | Real frames traverse transport, but omitted/duplicate request fields and semantically invalid positive replies are not adequately rejected |
|
||||
| AC-04 | Normal flow works per inspected/reported evidence | State isolation, read/clear/reset and static signals present; R-03 must detect clear acknowledgement without empty readback |
|
||||
| AC-05 | NOT SATISFIED | R-01/R-02 expose malformed/ambiguous frames and invalid typed data outside existing fault tests |
|
||||
| AC-06 | NOT SATISFIED | Probe identity mismatch becomes a discovery ProtocolError after its exchange was already traced PositiveResponse |
|
||||
| AC-07 | Corrective verification required | UI/session/provider composition is real, but nonempty successful readback is labeled cleared/verified |
|
||||
| AC-08 | Existing suite passed per worker; insufficient coverage | 108 unit + 53 integration passed, zero failed/skipped; complete Release/native build and native smoke reported; new vectors not covered |
|
||||
| AC-09 | Corrective alignment required | Documentation exists; wire presence/ambiguity, semantic validation and verified-clear contracts/lifecycle must be aligned |
|
||||
| AC-10 | Report/preservation inspected | Required report and scoped changes present; original assignment/report preserved; no Step-04 |
|
||||
|
||||
### Step-03 R-01 - Required and unambiguous frames
|
||||
|
||||
[SyntheticProtocolV1.cs](../src/AutoForge.Diagnostics/SyntheticProtocolV1.cs),
|
||||
lines 45 and 82, defaults Version to 1 and deserializes without requiring its
|
||||
presence or rejecting duplicate JSON properties. Omitting version leaves a valid
|
||||
v1 object; omitting logicalTimeTicks can leave zero. Repeated service/version/
|
||||
correlation fields can be resolved by last-value deserialization rather than
|
||||
rejected. With otherwise valid session binding, the transport can dispatch a
|
||||
virtual clear from a malformed/ambiguous request.
|
||||
|
||||
### Step-03 R-02 - Service semantics and truthful trace
|
||||
|
||||
[SyntheticDiagnosticProtocolClient.cs](../src/AutoForge.Diagnostics/SyntheticDiagnosticProtocolClient.cs),
|
||||
line 143, reads signal ticks and strings into unvalidated result records.
|
||||
For example a negative logicalTimeTicks or blank signal ID/unit can still become
|
||||
PositiveResponse. DTC strings likewise lack semantic validation.
|
||||
|
||||
The probe module-identity check at line 55 occurs outside the exchange decoder.
|
||||
A mismatched probe is recorded positive at line 289 before discovery converts it
|
||||
to ProtocolError. Returned outcome and raw exchange trace therefore disagree.
|
||||
Validate the complete interpreted payload before positive result/trace commitment.
|
||||
|
||||
### Step-03 R-03 - Acknowledgement versus verified clear
|
||||
|
||||
[DiagnosticPageViewModel.cs](../src/AutoForge.UI/Features/Vehicles/Diagnostics/DiagnosticPageViewModel.cs),
|
||||
line 261, tests only readback.IsSuccess and then says the state was cleared.
|
||||
A successful response containing remaining DTCs still takes this success path.
|
||||
The logical use case must fail verification when readback is nonempty or
|
||||
failed/unknown/cancelled, while preserving the actual observed data and no
|
||||
physical-operation claim.
|
||||
|
||||
These are static source/contract findings, not parent-executed reproductions.
|
||||
The worker subsequently supplied actual reproductions and corrected evidence.
|
||||
|
||||
Reported Step-03 evidence remains historical: complete nine-project/native Release
|
||||
build zero warnings/errors; 108 unit + 53 integration passed, zero failed/skipped;
|
||||
native explicit open/probe/read/clear/reset/close/trace and old routes observed.
|
||||
Static case counts, graph, restore assets and Release/native outputs corroborate
|
||||
the report. No build/test/native/workload command was executed by the orchestrator.
|
||||
|
||||
## Historical Step-03A scoped acceptance and additional discovery finding
|
||||
|
||||
Decision: Step-03A's **R-01/R-02/R-03 corrections ACCEPTED**, 2026-10-28.
|
||||
At that review the parent Step-03 milestone was **NOT ACCEPTED**: R-04 required
|
||||
Step-03B. The three successful corrections remain closed; R-04 is now also
|
||||
closed by the subsequent acceptance review below.
|
||||
|
||||
Reviewed [Step-03A](Step-03A.md), its [report](Step-03A-Report.md), strict wire
|
||||
presence/uniqueness logic, complete reply/trace validation, Application verified
|
||||
clear/result and UI adaptation, unit/state-oracle/real-DI/rendered fault tests,
|
||||
test-only rewriting transport and directly related docs.
|
||||
|
||||
| Criterion | Scoped decision | Evidence |
|
||||
|---|---|---|
|
||||
| AC-01 | ACCEPTED | All ten request fields required, explicit zero retained, duplicate/unknown fields rejected; malformed clear vectors leave independent state unchanged |
|
||||
| AC-02 | ACCEPTED | Exact reply/service shapes, semantic identifiers/timing/uniqueness and positive/error/data consistency validated before positive result; malformed vectors return no value |
|
||||
| AC-03 | ACCEPTED | Wrong probe module is now checked within the exchange decoder; one matching ProtocolError trace retains actual request/reply rather than false positive |
|
||||
| AC-04 | ACCEPTED | Application clear-and-verify separates acknowledgement/readback, rejects nonempty/failed/unknown readback, preserves remaining codes and renders failure |
|
||||
| AC-05 | ACCEPTED WITHIN CORRECTIVE SCOPE | Original 161-case baseline retained, nine-project graph/state/target/profile/clock boundaries unchanged; R-04 is an additional pre-existing discovery case |
|
||||
| AC-06 | ACCEPTED ON WORKER EXECUTION EVIDENCE | Reported actual 2-unit/5-integration pre-fix failures; corrected focused runs; full Release build 0 warnings/errors; 111 unit + 64 integration passes, zero failed/skipped; native baseline observed |
|
||||
| AC-07 | ACCEPTED | README/protocol/simulation/ADR/test docs reflect corrected wire/verification and historical versus corrective results |
|
||||
| AC-08 | ACCEPTED | No new project/package/workload action or future step; original assignments/reports and orchestration files preserved by worker |
|
||||
|
||||
Worker-reported final coverage: 175 passed (111 unit, 64 integration), zero
|
||||
failed/skipped. Native evidence covers genuine verified clear/empty readback,
|
||||
probe/read/trace/reset/close and old routes. The false-ack/nonempty-readback fault
|
||||
is explicitly real DI/rendered integration evidence, not native coverage; the
|
||||
production Client has no runtime fault control and none was added just for proof.
|
||||
|
||||
Static source case counts, nine-project acyclic graph and existing restore/
|
||||
Release/native artifacts corroborate the report, not independent runtime
|
||||
execution. The orchestrator did not run builds/tests or launch the app.
|
||||
|
||||
### R-04 - Successful probe evidence discarded when identity is unavailable
|
||||
|
||||
[SyntheticDiagnosticProtocolClient.cs](../src/AutoForge.Diagnostics/SyntheticDiagnosticProtocolClient.cs),
|
||||
line 72, always follows a valid probe with an identity read, then constructs the
|
||||
entry solely from identity outcome and drops the validated service list when
|
||||
identity fails. [ProviderContracts.cs](../src/AutoForge.Diagnostics/ProviderContracts.cs),
|
||||
line 257, defines Responders as non-null identities.
|
||||
[DiagnosticPageViewModel.cs](../src/AutoForge.UI/Features/Vehicles/Diagnostics/DiagnosticPageViewModel.cs),
|
||||
line 132, labels this identity count as actual endpoints that responded.
|
||||
|
||||
A valid module definition implementing `probe` but not `read.identity` is allowed.
|
||||
It returns a positive validated probe and an unsupported identity reply, yet it
|
||||
is omitted from the responder count. Likewise, a successful probe is lost if
|
||||
the subsequent identity reply is malformed, timed out or cancelled. Reachability,
|
||||
advertised services and identity verification are different facts.
|
||||
|
||||
Step-03B was required to preserve both phase outcomes, keep valid probe/service evidence,
|
||||
label probe responders versus identified modules honestly, and keep unavailable
|
||||
identity explicit without fabricating profile-derived identity or relaxing
|
||||
existing identity-dependent action guards. The source finding was not executed
|
||||
by the orchestrator; the worker subsequently supplied the pre-fix reproduction
|
||||
reviewed below.
|
||||
|
||||
## Step-03B acceptance and corrected Step-03
|
||||
|
||||
Decision: **ACCEPTED**, 2026-10-28. Step-03B closes R-04; corrected Step-03 is
|
||||
accepted with Step-03A/Step-03B. No Step-03C is required.
|
||||
|
||||
Reviewed [Step-03B](Step-03B.md), its [report](Step-03B-Report.md),
|
||||
phase-specific discovery/probe/identity models and aggregation, UI summary/rows/
|
||||
guards, actual Simulation/DI/rendered regression tests, trace assertions and
|
||||
directly related protocol/simulation/ADR/README/testing documentation.
|
||||
|
||||
| Criterion | Decision | Evidence |
|
||||
|---|---|---|
|
||||
| AC-01 | ACCEPTED | Valid positive probe and immutable services retained independently of optional identity result; unsupported/unavailable identity stays null with explicit phase reason |
|
||||
| AC-02 | ACCEPTED | Expected/probed/identified counts distinct; partial UI preserves services and unknown identity; controls disabled and direct view-model guards emit no operation |
|
||||
| AC-03 | ACCEPTED | Negative/malformed/mismatched/timed-out/cancelled identity preserves positive probe and its own trace; failed probe does not invent identity/services; close clears active presentation |
|
||||
| AC-04 | ACCEPTED | Normal synthetic workflow, R-01/R-02/R-03, profile/target/state/oracle boundaries and nine-project graph retained; 175 prior cases included in 183 |
|
||||
| AC-05 | ACCEPTED ON WORKER EXECUTION EVIDENCE | Reported actual pre-fix phase-conflation failure; focused 35 passes; complete Release build zero warnings/errors; 111 unit + 72 integration passes, zero failed/skipped; native baseline observed |
|
||||
| AC-06 | ACCEPTED | README/protocol/simulation/architecture/ADR/testing docs describe phase/count/action policy and native versus rendered evidence |
|
||||
| AC-07 | ACCEPTED | Only scoped source/tests/docs/report work; previous assignments/reports and orchestration files preserved; no new project/package/workload action or future step |
|
||||
|
||||
Chosen policy: a validated probe without advertised read.identity does not issue
|
||||
an unsupported identity request. Its probe/services remain available as claims;
|
||||
identity is explicitly not attempted and never populated from profile metadata.
|
||||
Identity-dependent actions stay fail-closed.
|
||||
|
||||
Worker-reported coverage: 183 passed (111 unit, 72 integration), zero failed/skipped.
|
||||
Native baseline covers explicit load/open, 3 expected/2 successful probes/2
|
||||
identified modules, no-response, read/static signals/raw trace, verified clear,
|
||||
reset/close and old routes. Partial-identity faults/action guards/cancellation are
|
||||
real-DI/rendered test coverage, not claimed native fault coverage.
|
||||
|
||||
Static source counts, nine-project acyclic references and existing restore/
|
||||
Release/native artifacts corroborate the report. No application build/test/
|
||||
native/workload command was executed by the orchestrator.
|
||||
|
||||
Step-04 is prepared against the actual accepted interfaces. It assigns a separate
|
||||
explicit dynamics provider/configuration, fixed-step clock/model/scenario controls,
|
||||
configuration-preserving reset and versioned dynamic telemetry through diagnostics.
|
||||
There is no dynamics implementation yet, no extra executable/project assigned,
|
||||
and no physical integration or calibration programming.
|
||||
|
||||
## Prerequisites, limitations, and known issues
|
||||
|
||||
|
|
@ -288,29 +453,30 @@ yet; full dynamics/physical adapters remain outside that assignment.
|
|||
the CR-at-EOL-aware diff check passes with no global settings changed.
|
||||
- Step-02 worker reports no workload-changing command was invoked; prior incident
|
||||
remains historical and does not authorize future installation/update/rollback.
|
||||
- Corrected schema/ADR contracts are implemented and documented. Step-03 must
|
||||
align remaining acceptance-pending lifecycle text with this decision while
|
||||
preserving previous reports.
|
||||
- R-01 and R-02 are closed; no blocking Step-03 prerequisite is currently identified.
|
||||
- Profile metadata/UI are accepted. Simulation, replay,
|
||||
diagnostics, telemetry, calibration values, persistence, AI and hardware
|
||||
operations remain unimplemented.
|
||||
- Profile Step-02 R-01/R-02 remain closed and accepted; do not regress those fixes.
|
||||
- Step-03 R-01/R-02/R-03/R-04 are closed; no blocking Step-04 prerequisite is
|
||||
currently identified. Preserve all correction invariants.
|
||||
- Step-04 must align remaining acceptance-pending lifecycle text without altering
|
||||
original 161-case or corrective 175-/183-case reports.
|
||||
- Profile metadata/UI and synthetic virtual-module diagnostics/static signals
|
||||
are accepted. Full dynamics, replay, calibration
|
||||
values, persistence, AI and physical hardware operations remain unimplemented.
|
||||
- No application build or test has been executed by the orchestrator.
|
||||
|
||||
## Review and progression gate
|
||||
|
||||
On manual return, evaluate Step-03 criteria using the original
|
||||
On manual return, evaluate Step-04 criteria using the original
|
||||
assignment, worker report, actual code/tests, dependency graph, Git changes,
|
||||
README/docs, and recorded build/test evidence. Do not accept solely on a success
|
||||
claim; do not claim independent runtime verification.
|
||||
|
||||
- Inspect provider/session boundaries, actual wire request/response path,
|
||||
module discovery/identity/DTC/telemetry, isolated virtual state, deterministic
|
||||
faults/trace and application/UI/native evidence.
|
||||
- If accepted: record evidence, update roadmap/state, create Step-04 and stop for
|
||||
- Inspect coupled physics/numeric thresholds, fixed clock/lifecycle/pacing,
|
||||
run/configuration identity and reset, strict static/dynamic wire integration,
|
||||
independent oracle and real application/UI/native evidence.
|
||||
- If accepted: record evidence, update roadmap/state, create Step-05 and stop for
|
||||
manual handoff. Do not execute it.
|
||||
- If deficient: create `Step-03A.md` with measurable corrections and matching
|
||||
report requirements, update state and stop. Do not advance to Step-04.
|
||||
- If deficient: create `Step-04A.md` with measurable corrections and matching
|
||||
report requirements, update state and stop. Do not advance to Step-05.
|
||||
- If blocked: retain the active step, document the prerequisite and required
|
||||
worker evidence; do not advance or mark unexecuted checks as successful.
|
||||
- Never create the next major assignment while acceptance or corrections are open.
|
||||
|
|
@ -336,11 +502,20 @@ claim; do not claim independent runtime verification.
|
|||
| 2026-10-28 | Step-02A returned and ACCEPTED | Parser/constraint fixes and direct/DI/UI/native evidence reviewed; 103 unit + 37 integration passes and clean Release build reported |
|
||||
| 2026-10-28 | Corrected Step-02 ACCEPTED | R-01/R-02 closed; prior 93-case and corrective 140-case reports preserved; no Step-02B |
|
||||
| 2026-10-28 | Step-03 prepared | Explicit simulated sessions, virtual modules, synthetic protocol/read-clear/telemetry/trace and deterministic faults; manual handoff pending |
|
||||
| 2026-10-28 | Step-03 returned for review | Nine-project protocol/provider/session/UI path and reported 161-case/native verification inspected |
|
||||
| 2026-10-28 | Step-03 requires correction | Missing/ambiguous wire fields, semantic positive replies/false-positive probe trace, and clear acknowledgement treated as verification |
|
||||
| 2026-10-28 | Step-03A prepared | Narrow correction with pre-fix regressions, state/trace/UI verification and documentation; Step-04 blocked |
|
||||
| 2026-10-28 | Step-03A returned; scoped corrections ACCEPTED | R-01/R-02/R-03 fixed; actual pre-fix failures, clean Release build, 175-case passing run and native baseline inspected |
|
||||
| 2026-10-28 | Additional Step-03 finding R-04 | Valid positive probe is discarded from responder count/service evidence when identity is unavailable; not covered by current tests |
|
||||
| 2026-10-28 | Step-03B prepared | Preserve phase-specific probe/identity facts and truthful counts without relaxing identity-dependent action gates; Step-04 remains blocked |
|
||||
| 2026-10-28 | Step-03B returned and ACCEPTED | R-04 closed; phase/count/guard/trace source and reported 183-case/native evidence inspected |
|
||||
| 2026-10-28 | Corrected Step-03 ACCEPTED | All R-01/R-02/R-03/R-04 closed; normal and partial diagnostics, wire integrity and verified clear retained |
|
||||
| 2026-10-28 | Step-04 prepared | Fixed-step coupled dynamics, explicit configuration/control and dynamic diagnostic telemetry; manual worker handoff pending |
|
||||
|
||||
## Manual handoff instruction
|
||||
|
||||
Provide [Step-03.md](Step-03.md) to the separate worker and request execution
|
||||
of that assignment only. The worker must produce `prompts/Step-03-Report.md`
|
||||
and stop for review. Do not begin Step-04.
|
||||
Provide [Step-04.md](Step-04.md) to the separate worker and request execution
|
||||
of that assignment only. The worker must produce `prompts/Step-04-Report.md`
|
||||
and stop for review. Do not begin Step-05.
|
||||
Return manually to the orchestrator for review. Reports, including final chat
|
||||
reports, must follow the single plain triple-backtick copy-window requirement.
|
||||
|
|
|
|||
|
|
@ -0,0 +1,251 @@
|
|||
```
|
||||
# Step-03 Worker Report
|
||||
|
||||
## Status
|
||||
|
||||
**COMPLETE** for the Step-03 worker implementation, full Release verification
|
||||
and native Windows Client smoke. Manual orchestrator review/acceptance remains
|
||||
pending. Step-04 was not started.
|
||||
|
||||
## Objective and scope
|
||||
|
||||
Delivered the synthetic diagnostics vertical slice in the existing native
|
||||
Client: explicit profile/revision/provider/session selection; a provider-neutral
|
||||
diagnostic contract and encoded request/response path; validated, data-driven
|
||||
virtual modules; typed deterministic outcomes; session-isolated virtual DTC
|
||||
state; static synthetic signals; bounded inspectable trace; rendered UI; tests
|
||||
and documentation.
|
||||
|
||||
This implementation does not connect to a real vehicle. Protocol v1 is
|
||||
AutoForge-specific JSON, not CAN, ISO-TP, UDS, OBD or a manufacturer protocol.
|
||||
Static signals are fixture state, not vehicle capture, dynamics or prediction.
|
||||
Virtual DTC clearing is in-memory simulation behavior only. There is no physical
|
||||
adapter, replay provider, calibration/firmware/programming path, AI, backend,
|
||||
persistence or additional executable.
|
||||
|
||||
## Projects and reference graph
|
||||
|
||||
Added exactly two `net10.0` class libraries; the solution contains nine projects
|
||||
and retains one production executable and two test projects:
|
||||
|
||||
| Project | Direct project references |
|
||||
|---|---|
|
||||
| AutoForge.Core | None |
|
||||
| AutoForge.Diagnostics | Core |
|
||||
| AutoForge.Simulation | Core, Diagnostics |
|
||||
| AutoForge.Application | Core, Diagnostics |
|
||||
| AutoForge.Components | None |
|
||||
| AutoForge.UI | Application, Components, Diagnostics |
|
||||
| AutoForge.Client | Application, Simulation, UI |
|
||||
| AutoForge.UnitTests | Application, Components, Core, Diagnostics, Simulation |
|
||||
| AutoForge.IntegrationTests | Application, Components, Core, Diagnostics, Simulation, UI |
|
||||
|
||||
The project-graph integration test checks all nine projects, the exact direct
|
||||
references, one `AutoForge.Client` executable and the existing framework
|
||||
targets. Application/UI do not reference Simulation; Core, Diagnostics and
|
||||
Simulation do not reference Application/UI/Client. Components remains
|
||||
independent. There are no cycles or production-to-test edges.
|
||||
|
||||
`AutoForge.Diagnostics` owns provider/session/transport contracts, typed
|
||||
operation and provider failures, immutable diagnostic results, logical-clock
|
||||
and protocol-client interfaces, synthetic protocol-v1 codec/client and bounded
|
||||
trace. `AutoForge.Simulation` owns the provider factory, validated data-driven
|
||||
definitions, in-process transport, isolated state and deterministic faults.
|
||||
Application owns explicit session open/reset/close coordination using
|
||||
diagnostic interfaces and the existing profile/target services. Client
|
||||
composes a single `SimulatedDiagnosticTransportFactory` with both source
|
||||
definitions; its descriptor and operational factory are registered from the
|
||||
same factory instance.
|
||||
|
||||
The state oracle is internal and available only to `AutoForge.IntegrationTests`
|
||||
through `InternalsVisibleTo`. It is not exposed as an Application/UI service.
|
||||
|
||||
## Provider, session and protocol behavior
|
||||
|
||||
- Provider identifier/kind: `autoforge.simulation.synthetic` / `Simulation`.
|
||||
The provider resolves exact profile/revision and configuration; unknown
|
||||
profile, provider, target kind, definition or invalid mapping returns an
|
||||
explicit typed error. No first/latest/default/demo fallback exists.
|
||||
- Target metadata resolution remains a separate metadata-only action. Opening
|
||||
a session requires explicit profile ID, exact revision, provider ID and kind.
|
||||
Replay and physical operational sessions are unavailable and are never
|
||||
substituted with Simulation.
|
||||
- Session identity binds a deterministic session ID, exact profile/revision,
|
||||
vehicle ID, target descriptor and profile-configuration identifier. Each
|
||||
session owns its transport, logical clock, trace and virtual DTC state.
|
||||
Closing releases the session. Reset closes it and opens a new exact selection
|
||||
with configured initial state.
|
||||
- Protocol v1 requests are UTF-8 JSON with version, session/profile/revision/
|
||||
configuration, correlation, target address, service, logical start tick and
|
||||
timeout tick. The actual encoded bytes traverse `IDiagnosticTransport`;
|
||||
actual reply bytes are envelope-validated and decoded into typed identity,
|
||||
DTC-clear/read and static-signal results.
|
||||
- Received replies validate protocol version, session/configuration, address,
|
||||
service and correlation. Identity is compared to the exact selected profile
|
||||
snapshot. Unsupported service/version, unknown address, malformed payload,
|
||||
identity/correlation mismatch, no response, timeout and cancellation cannot
|
||||
produce success-shaped empty data.
|
||||
- The default definition contains synthetic engine (`0x10`), transmission
|
||||
(`0x20`) and cabin/body (`0x30`) modules. Engine supports virtual DTC clear
|
||||
and starts with `SYN-P0123`; transmission probe deterministically does not
|
||||
respond and its existing DTC state is not cleared by engine operations;
|
||||
body clear is an unsupported negative response. The alternate orchard-cart
|
||||
inventory exercises an open custom module role.
|
||||
- Static configured signals include fixed synthetic engine speed (850 rpm),
|
||||
voltage (12.6 V), transmission state and body door count. Signal results
|
||||
retain module/source, identifier, JSON value, unit, quality, logical time
|
||||
and `SYNTHETIC_STATIC` origin. These are not dynamics or live capture.
|
||||
- Logical time is injectable per session and advances by deterministic
|
||||
transport ticks. Latency above the five-tick deadline returns Timeout with no
|
||||
response. Fault definitions cover no response, malformed reply, wrong
|
||||
correlation, wrong identity, timeout latency and hold-until-cancelled. No
|
||||
`Thread.Sleep`, randomness or wall-clock fault selection is used.
|
||||
- Protocol exchanges are serialized per session. Trace retains at most 200
|
||||
ordered records, each with context, logical timing, raw copied request and
|
||||
optional copied response, decoded summary and explicit outcome. Oldest
|
||||
records are dropped at capacity and the count is exposed. No response payload
|
||||
is stored or fabricated for no-response/timeout/cancelled outcomes.
|
||||
|
||||
## UI and coupled status surfaces
|
||||
|
||||
Added `/diagnostics` in the UI RCL and navigation. The page has a user-triggered
|
||||
synthetic profile import (no automatic import or selection), exact profile and
|
||||
revision controls, explicit provider/kind controls, separate open/close/reset,
|
||||
probe/read/virtual-clear actions gated by actually probed service declarations,
|
||||
visible typed errors, module identities, DTCs, static signals, raw request/reply
|
||||
inspection and trace-loss indication. Pending cancellation and session close
|
||||
discard stale session results.
|
||||
|
||||
Client now registers the real Simulation provider. Target-selection metadata
|
||||
presentation therefore shows the registered synthetic descriptor while still
|
||||
stating that metadata selection does not open a session. Home text no longer
|
||||
claims diagnostics are absent. Profile import/export and exact revision
|
||||
semantics are unchanged.
|
||||
|
||||
The changed UI assertions intentionally reflect the new real provider: the
|
||||
home-page assertion now describes the implemented synthetic workflow, and the
|
||||
kind-mismatch page test no longer asserts that *all* `data-provider` markup is
|
||||
absent because registered metadata is now correctly listed. It instead confirms
|
||||
that no resolved `data-kind` result is rendered; it still asserts the mismatch,
|
||||
no-fallback error and null selected descriptor. Empty-registry resolver,
|
||||
unknown-provider, safety and no-fallback tests remain. No acceptance case was
|
||||
deleted or skipped.
|
||||
|
||||
## Tests and verification
|
||||
|
||||
The accepted Step-02A regression baseline was 103 unit and 37 integration
|
||||
tests (140 total). Step-03 retains those suites and adds protocol/trace and
|
||||
transport/session/fault/UI coverage. Final full-suite results:
|
||||
|
||||
| Test project | Discovered | Passed | Failed | Skipped |
|
||||
|---|---:|---:|---:|---:|
|
||||
| AutoForge.UnitTests | 108 | 108 | 0 | 0 |
|
||||
| AutoForge.IntegrationTests | 53 | 53 | 0 | 0 |
|
||||
| Total | 161 | 161 | 0 | 0 |
|
||||
|
||||
Coverage includes request encode/decode and payload snapshots; bounded trace
|
||||
order/loss and immutable raw bytes; exact/missing/duplicate/mismatched
|
||||
simulation mappings and invalid services/signals; actual transport discovery,
|
||||
identity, DTC, static signals and wire errors; virtual clear/readback plus the
|
||||
independent oracle; other-module/session isolation and reset; unknown
|
||||
profile/provider/definition/kind and no-fallback; unsupported version/service
|
||||
and unknown address; no-response, timeout, malformed response, wrong
|
||||
correlation/identity, cancellation/session close; injected logical-clock
|
||||
determinism; rendered real-provider positive, timeout and cancelled states;
|
||||
target/profile/home/not-found UI; and exact nine-project graph.
|
||||
|
||||
Commands were run sequentially:
|
||||
|
||||
- `dotnet restore .\src\AutoForge.slnx` — exit 0.
|
||||
- `dotnet build .\src\AutoForge.slnx --configuration Release --no-restore` —
|
||||
exit 0; all nine projects, including Client
|
||||
`net10.0-windows10.0.26100.0` / `win-x64`; 0 warnings, 0 errors.
|
||||
- `dotnet test .\src\AutoForge.slnx --configuration Release --no-build` —
|
||||
exit 0; 108 unit + 53 integration passed, 0 failed/skipped.
|
||||
|
||||
The verified environment was Windows x64, .NET SDK 10.0.402, runtime 10.0.13,
|
||||
Windows SDK target 10.0.26100.0, MAUI Windows workload manifest 10.0.110 and
|
||||
WebView2 Runtime 155.0.4283.62. No workload install/restore/update/repair or
|
||||
package addition was needed.
|
||||
|
||||
## Native Client smoke
|
||||
|
||||
Launched the actual Windows MAUI executable using:
|
||||
|
||||
`dotnet run --project .\src\AutoForge.Client\AutoForge.Client.csproj --configuration Release --framework net10.0-windows10.0.26100.0 --no-build`
|
||||
|
||||
For local-only inspection of the actual WebView, the process used
|
||||
`WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS=--remote-debugging-port=9222`; no source,
|
||||
launch setting or persistent environment configuration was changed. The
|
||||
WebView2 DevTools endpoint was restricted to loopback and the native process
|
||||
was stopped after the smoke.
|
||||
|
||||
Observed workflow:
|
||||
|
||||
1. `/diagnostics` initially showed only the profile placeholder and no session.
|
||||
The synthetic truck was imported only after clicking the explicit load
|
||||
action; the exact profile/revision/provider/kind were then selected.
|
||||
2. Opening displayed Simulation provider, session ID, profile/revision and
|
||||
configuration ID. Probe found three expected endpoints and two actual
|
||||
responders: engine/body were positive; transmission at `0x20` showed
|
||||
`NoResponse` with “Configured endpoint did not respond.”
|
||||
3. Engine identity, initial `SYN-P0123`, static signal identifiers/origin and
|
||||
trace were rendered. The trace showed ordered logical ticks/correlations and
|
||||
its expandable raw request and raw positive response JSON.
|
||||
4. Virtual clear showed fresh readback with zero DTCs and explicitly stated
|
||||
“No physical write was performed.” Reset created a different session ID;
|
||||
rediscovery/read returned the configured initial `SYN-P0123`. Close removed
|
||||
the active session view.
|
||||
5. `/execution-targets` listed and explicitly resolved
|
||||
`autoforge.simulation.synthetic (Simulation)` with “No connection or
|
||||
operation was performed” and no open session. `/vehicle-profiles` showed
|
||||
the explicitly imported revision without auto-selecting it. `/` and an
|
||||
unmatched route displayed the home and not-found pages with navigation.
|
||||
|
||||
Headless rendered tests additionally verified deterministic timeout and
|
||||
cancelled trace/error presentation. The native smoke was performed against the
|
||||
actual MAUI Client, not a browser host, mock provider or test-only host.
|
||||
|
||||
## Documentation and files
|
||||
|
||||
Added the Diagnostics and Simulation projects plus provider-neutral contracts,
|
||||
synthetic protocol/client, simulation definitions/transport, application
|
||||
session service, UI view model/page and unit/integration coverage. Updated
|
||||
solution and project references, Client composition, route/navigation, home and
|
||||
target metadata presentation, and project graph assertions.
|
||||
|
||||
Documentation updated: `README.md`, `docs/README.md`,
|
||||
`docs/architecture.md`, `docs/build-and-test.md`. New documents:
|
||||
`docs/synthetic-diagnostics-v1.md`, `docs/simulation.md` and
|
||||
`docs/adr-0004-synthetic-diagnostics.md`.
|
||||
|
||||
The synthetic wire contract, module/profile binding, service-vs-claim
|
||||
distinction, state/reset/oracle boundary, deterministic faults/logical time,
|
||||
trace capacity/loss, native workflow and non-authentic limitations are
|
||||
documented. Historical reports and strict profile schema documentation remain
|
||||
unchanged.
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
| ID | Status | Evidence |
|
||||
|---|---|---|
|
||||
| AC-01 | PASSED | Nine-project graph test, exact references and one executable; Simulation oracle internal to IntegrationTests only. |
|
||||
| AC-02 | PASSED | Exact profile/revision/provider/kind and session lifecycle integration tests; missing/unknown/mismatched selection failures; native explicit-selection flow; no physical/replay fallback. |
|
||||
| AC-03 | PASSED | Real encoded requests cross the simulation transport; decoded responders/identity and raw frame/trace assertions; transmission is not falsely reported as a responder. |
|
||||
| AC-04 | PASSED | DTC read/virtual clear/fresh readback, static signals, independent oracle, unrelated module and session isolation, reset-to-initial-state assertions. |
|
||||
| AC-05 | PASSED | Deterministic unsupported, unknown address/version, no-response, timeout, malformed, correlation/identity mismatch, cancel and close vectors assert typed outcomes and no false empty success. |
|
||||
| AC-06 | PASSED | Serialized logical trace, raw payload snapshot tests, exact outcomes, capacity/order/drop accounting and native expandable request/reply trace. |
|
||||
| AC-07 | PASSED | Real application DI and Simulation composition; rendered positive, unsupported/no-response, timeout and cancelled/error UI; explicit provider metadata remains separate from open session. |
|
||||
| AC-08 | PASSED | Full nine-project Release build (0 warnings/errors), 108 unit + 53 integration passed and actual native Client workflow/routes completed. |
|
||||
| AC-09 | PASSED | README/index, architecture, build guide, protocol/simulation guides and focused ADR updated to implemented scope. |
|
||||
| AC-10 | PASSED | Only Step-03 implementation/docs/tests and `prompts/Step-03-Report.md` changed; assignments, roadmap/state, prior reports and protected instructions preserved; no stage/commit/push/agent/handoff automation. |
|
||||
|
||||
## Limitations and handoff
|
||||
|
||||
Worker implementation, Release verification and native smoke are complete.
|
||||
Manual orchestrator review/acceptance remains pending. The protocol is
|
||||
synthetic-only, the current signal set is static, all data/state is
|
||||
process/session-local, and no physical/replay/hardware operation is available.
|
||||
Proceed only to manual review; do not begin Step-04 without an authorized
|
||||
assignment.
|
||||
```
|
||||
|
|
@ -0,0 +1,265 @@
|
|||
```
|
||||
# Step-03A Worker Report
|
||||
|
||||
## Status
|
||||
|
||||
**COMPLETE** for the assigned Step-03A corrective implementation, regression
|
||||
testing, complete Release build/test verification and native baseline smoke.
|
||||
Step-03 remains **NOT ACCEPTED** pending manual orchestrator review. Step-04
|
||||
was not started.
|
||||
|
||||
## Scope and implementation
|
||||
|
||||
Corrected the three Step-03 integrity findings without changing the nine-project
|
||||
architecture, introducing a package/project/host, or enabling physical or replay
|
||||
operations.
|
||||
|
||||
### R-01 — Incomplete and ambiguous requests
|
||||
|
||||
**Root cause:** `SyntheticDiagnosticRequest.Version` had an initializer of `1`;
|
||||
`TryDecodeRequest` relied on object deserialization alone, so missing version or
|
||||
logical tick could be supplied by defaults. Duplicate JSON object names were
|
||||
left to last-value deserialization.
|
||||
|
||||
**Fix:** The v1 decoder now requires all ten exact camelCase wire properties,
|
||||
checks object-property uniqueness recursively before deserialization, and still
|
||||
uses `JsonUnmappedMemberHandling.Disallow`. Missing, unknown, case-variant,
|
||||
duplicate, invalid-time or invalid-timeout requests are malformed. The
|
||||
simulation transport returns its explicit no-response outcome before session
|
||||
binding/address/service dispatch, so no trustworthy response correlation is
|
||||
fabricated and no virtual service runs. Explicit zero logical time remains valid.
|
||||
A structurally complete version-2 request still receives the pre-existing
|
||||
`UNSUPPORTED_VERSION` negative response.
|
||||
|
||||
Unit tests remove each of the ten required request fields, test invalid timing,
|
||||
explicit zero, unknown/case-variant properties and a real duplicate service
|
||||
property. The real Simulation transport test sends five malformed clear frames:
|
||||
missing version, missing logical time, duplicate conflicting service,
|
||||
duplicate conflicting correlation and duplicate conflicting version. The
|
||||
IntegrationTests-only oracle confirms `SYN-P0123` remains unchanged after each
|
||||
rejected frame. Duplicate test inputs are parsed and counted as containing two
|
||||
actual properties before dispatch; the test does not reconstruct them through a
|
||||
dictionary that would erase duplicates.
|
||||
|
||||
### R-02 — Complete reply validation and truthful trace
|
||||
|
||||
**Root cause:** Interpreted service payloads had incomplete semantic checks, and
|
||||
discovery compared a decoded probe module only after `ExchangeAsync` had already
|
||||
recorded a `PositiveResponse`.
|
||||
|
||||
**Fix:** The protocol client now rejects duplicate object properties before
|
||||
interpretation; requires exact known envelope/service fields; checks response
|
||||
success/error/data consistency; and validates nonblank trimmed identifiers/text,
|
||||
module/profile identity, unique DTC/service/signal identifiers, service and
|
||||
quality tokens, and static signal source/timing. Signal snapshot ticks must equal
|
||||
the request logical start tick. Valid empty DTC collections and explicit JSON
|
||||
`null` signal values remain valid.
|
||||
|
||||
Probe identity and advertised-service validation now run in the same decoder
|
||||
path as other services. An invalid probe produces one `ProtocolError` result and
|
||||
one `ProtocolError` trace entry with the actual immutable raw request/reply;
|
||||
there is no positive trace followed by a contradictory discovery result.
|
||||
Invalid/inconsistent responses return no partial value. No-response, timeout,
|
||||
cancel and malformed transport behavior remains unchanged.
|
||||
|
||||
Actual DI/transport integration tests mutate actual encoded Simulation replies
|
||||
to cover negative signal tick; blank signal identifier/unit; wrong module
|
||||
source; invalid quality; duplicate signal identifier property; duplicate signal
|
||||
IDs; blank DTC code/description; unknown/duplicate advertised services; wrong
|
||||
probe module; duplicate response correlation; missing/unknown response fields;
|
||||
positive response with error text; and negative response with data. Each asserts
|
||||
a typed failure, null result value and matching trace outcome/raw response.
|
||||
Existing unsupported-version/address/service, valid empty/nonempty DTC,
|
||||
identity, timeout/no-response/cancellation and trace tests remain in the full
|
||||
suite.
|
||||
|
||||
### R-03 — Clear acknowledgement versus verified state
|
||||
|
||||
**Root cause:** UI treated any successful post-clear DTC read as proof the
|
||||
virtual clear succeeded, including a nonempty readback.
|
||||
|
||||
**Fix:** Added `DiagnosticSession.ClearTroubleCodesAndVerifyAsync` and the
|
||||
Application result `DiagnosticClearVerificationResult`. The use case preserves
|
||||
the low-level acknowledgement separately, then performs a fresh read. It marks
|
||||
the operation verified only if that read succeeds with an empty DTC set.
|
||||
Nonempty readback is retained as observed data with verification failure;
|
||||
negative/protocol/no-response/timeout/cancelled or closed-session readback is
|
||||
explicitly uncertain/failed and never verified. A zero acknowledgement count
|
||||
does not prevent verification when the fresh read is valid and empty.
|
||||
|
||||
The UI now calls the Application use case rather than duplicating verification
|
||||
logic. It renders acknowledgement and verification as separate outcomes,
|
||||
preserves valid remaining codes, reports failure/uncertainty, never emits the
|
||||
old “was cleared and re-read” success for a nonempty readback, and explicitly
|
||||
states that no physical write occurred.
|
||||
|
||||
A deterministic test transport decorator sits below the real protocol client
|
||||
and Application session: it returns a positive clear acknowledgement without
|
||||
dispatching clear to the actual Simulation transport. The actual subsequent
|
||||
readback and independent oracle show `SYN-P0123` remains. Rendered UI asserts
|
||||
error tone, visible remaining code, verification failure, no false success and
|
||||
unchanged oracle state. Additional Application integration tests cover genuine
|
||||
clear/empty verification, a second already-empty clear with acknowledgement
|
||||
count zero, no-response, timeout, malformed protocol response, request
|
||||
cancellation and session close.
|
||||
|
||||
## Architecture and interfaces
|
||||
|
||||
The nine-project graph and production dependencies are unchanged. No assembly,
|
||||
executable, package, workload action, external provider or public state oracle
|
||||
was added. The new Application result and session method depend only on the
|
||||
existing Diagnostics protocol/session contracts. Normal Application/UI paths
|
||||
still cannot access Simulation internals; the virtual DTC oracle remains
|
||||
IntegrationTests-only. Existing exact profile/revision/provider/kind selection,
|
||||
metadata-only target resolution, state isolation, reset/close lifecycle,
|
||||
logical-clock/trace behavior and synthetic-only restrictions remain.
|
||||
|
||||
The test-only `RewritingDiagnosticTransportFactory` wraps the real simulation
|
||||
factory only in IntegrationTests. It is not registered by Client and is not a
|
||||
runtime fault selector.
|
||||
|
||||
## Before/after regression evidence
|
||||
|
||||
Before production fixes, the focused unit command below failed both new tests:
|
||||
missing `version`/`logicalTimeTicks` was accepted, and the actual duplicate
|
||||
`service` property was accepted.
|
||||
|
||||
`dotnet test .\src\tests\AutoForge.UnitTests\AutoForge.UnitTests.csproj --configuration Release --filter "FullyQualifiedName~SyntheticProtocolV1_RequiresExplicitWireVersionAndLogicalTime|FullyQualifiedName~SyntheticProtocolV1_RejectsDuplicateDispatchAndBindingProperties"`
|
||||
|
||||
Result: **2 failed, 0 passed**. The assertions expected decoder rejection and
|
||||
observed `Actual: True`.
|
||||
|
||||
Before production fixes, the five real integration/rendered regression tests
|
||||
failed as expected:
|
||||
|
||||
`dotnet test .\src\tests\AutoForge.IntegrationTests\AutoForge.IntegrationTests.csproj --configuration Release --filter "FullyQualifiedName~SimulationTransport_RejectsIncompleteAndAmbiguousClearFramesWithoutMutation|FullyQualifiedName~ProbeIdentityMismatch_IsProtocolErrorInTheSingleMatchingTraceEntry|FullyQualifiedName~RealProtocol_RejectsInvalidSignalAndDtcDataWithoutSuccessValues|FullyQualifiedName~ResponseEnvelope_RejectsDuplicateBindingFieldAndContradictoryPositiveError|FullyQualifiedName~DiagnosticRoute_ClearAcknowledgementWithRemainingCodesIsNotReportedVerified"`
|
||||
|
||||
Result: **5 failed, 0 passed**. The real transport accepted the missing-field
|
||||
clear as positive; malformed signal/DTC and inconsistent replies were returned
|
||||
as `PositiveResponse`; wrong probe identity was discovered as an error while its
|
||||
trace remained `PositiveResponse`; and the UI reported `Information` for a
|
||||
nonempty readback rather than verification failure.
|
||||
|
||||
After fixes, focused decoder tests passed **3/3** and focused real integration/
|
||||
rendered correction tests passed **12/12** (the latter includes the existing
|
||||
normal native-provider rendered workflow).
|
||||
|
||||
## Full verification
|
||||
|
||||
The final complete commands were run sequentially after source/test changes:
|
||||
|
||||
- `dotnet build .\src\AutoForge.slnx --configuration Release --no-restore`
|
||||
— exit 0; all nine projects built, including the actual Windows Client target
|
||||
`net10.0-windows10.0.26100.0` / `win-x64`; **0 warnings, 0 errors**.
|
||||
- `dotnet test .\src\AutoForge.slnx --configuration Release --no-build`
|
||||
— exit 0; all tests passed, with no failures or skips.
|
||||
|
||||
| Test project | Discovered | Passed | Failed | Skipped |
|
||||
|---|---:|---:|---:|---:|
|
||||
| AutoForge.UnitTests | 111 | 111 | 0 | 0 |
|
||||
| AutoForge.IntegrationTests | 64 | 64 | 0 | 0 |
|
||||
| Total | 175 | 175 | 0 | 0 |
|
||||
|
||||
This retains the historical Step-03 baseline of 108 unit + 53 integration
|
||||
(161 total) and adds 14 test cases. The original Step-03 run did not cover the
|
||||
Step-03A vectors and is not represented as having done so. No dependency
|
||||
manifest changed; no explicit restore command or workload operation was
|
||||
required. Test-runner restore checks reported all projects up-to-date.
|
||||
|
||||
## Native Client versus rendered fault verification
|
||||
|
||||
Launched the actual Windows Client executable:
|
||||
|
||||
`.\src\AutoForge.Client\bin\Release\net10.0-windows10.0.26100.0\win-x64\AutoForge.Client.exe`
|
||||
|
||||
For local smoke inspection only, the child process received
|
||||
`WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS=--remote-debugging-port=9222`; the
|
||||
WebView2 DevTools endpoint was accessed via loopback at `127.0.0.1`. No source,
|
||||
launch configuration or persistent environment setting was changed. The
|
||||
native Client process was stopped after the smoke.
|
||||
|
||||
Native observations:
|
||||
|
||||
- Explicitly loaded the synthetic truck example, explicitly selected exact
|
||||
profile revision/provider/kind and opened Simulation session
|
||||
`diagnostic-session-000001`.
|
||||
- Probed three expected modules: engine and body responded; transmission
|
||||
`0x20` visibly returned `NoResponse` and was not counted as a responder.
|
||||
- Read engine identity, `SYN-P0123`, static engine speed 850 rpm, voltage 12.6 V,
|
||||
quality/unit/origin/source and logical time.
|
||||
- Inspected actual raw JSON request and response bytes in the native trace,
|
||||
including matching correlation and decoded positive probe entry.
|
||||
- Virtual clear showed one acknowledged item followed by a fresh read with zero
|
||||
DTCs and the status “Fresh readback verified an empty virtual DTC state… No
|
||||
physical write was performed.”
|
||||
- Reset created session `diagnostic-session-000002`; probing and reading restored
|
||||
the configured initial `SYN-P0123`. The configured transmission no-response
|
||||
remained visible. Closed the session and verified the active-session view was
|
||||
removed.
|
||||
- Rechecked `/execution-targets` provider metadata without a session,
|
||||
`/vehicle-profiles` imported revision, `/`, and an unmatched not-found route.
|
||||
|
||||
The false-ack/nonempty-readback fault is **rendered IntegrationTests evidence**,
|
||||
not native Client evidence. Production Client has no supported runtime
|
||||
fault-injection control; adding one merely to create native evidence would
|
||||
change the product surface and was not authorized. The native run verifies the
|
||||
normal baseline clear; the rendered test verifies the failure case.
|
||||
|
||||
## Documentation and files
|
||||
|
||||
Modified:
|
||||
|
||||
- `src/AutoForge.Diagnostics/SyntheticProtocolV1.cs`
|
||||
- `src/AutoForge.Diagnostics/SyntheticDiagnosticProtocolClient.cs`
|
||||
- `src/AutoForge.Application/Features/Vehicles/Diagnostics/DiagnosticSessionService.cs`
|
||||
- `src/AutoForge.UI/Features/Vehicles/Diagnostics/DiagnosticPageViewModel.cs`
|
||||
- `src/tests/AutoForge.UnitTests/SyntheticDiagnosticsContractTests.cs`
|
||||
- `src/tests/AutoForge.IntegrationTests/DiagnosticSessionCompositionTests.cs`
|
||||
- `src/tests/AutoForge.IntegrationTests/DiagnosticUiCompositionTests.cs`
|
||||
- `README.md`
|
||||
- `docs/README.md`
|
||||
- `docs/architecture.md`
|
||||
- `docs/build-and-test.md`
|
||||
- `docs/synthetic-diagnostics-v1.md`
|
||||
- `docs/simulation.md`
|
||||
- `docs/adr-0004-synthetic-diagnostics.md`
|
||||
|
||||
Created:
|
||||
|
||||
- `src/tests/AutoForge.IntegrationTests/RewritingDiagnosticTransportFactory.cs`
|
||||
- `prompts/Step-03A-Report.md`
|
||||
|
||||
Documentation now states exact wire naming/presence/unknown/duplicate policy,
|
||||
no-dispatch semantics, full response validation, trace/result consistency,
|
||||
acknowledgement versus verified empty readback, test counts and evidence
|
||||
distinctions. Synthetic/non-vehicle, static-signal, no-physical-write,
|
||||
no-programming and no-replay limits remain explicit.
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
| ID | Status | Evidence |
|
||||
|---|---|---|
|
||||
| AC-01 | PASSED | All ten fields, unknown/case variant and duplicate rules tested; five conflicting/missing clear frames sent through the real bound Simulation transport; independent oracle confirms no state mutation. |
|
||||
| AC-02 | PASSED | Exact envelope/service payload policy, timing, identifiers, DTC metadata, signal semantics, probe metadata and success/error/data consistency tested; invalid replies return typed ProtocolError with no value. |
|
||||
| AC-03 | PASSED | Wrong probe module and invalid service claims produce discovery failures matching one actual-raw-reply ProtocolError trace entry; no positive/partial probe result. |
|
||||
| AC-04 | PASSED | Application clear-and-verify tested for genuine empty result, zero acknowledgement count, false acknowledgement/nonempty readback, no-response, timeout, malformed response, cancellation and closed session; rendered UI retains remaining code and displays failure; oracle confirms unchanged state. |
|
||||
| AC-05 | PASSED | Original 161-case Step-03 baseline remains within the final 175-case suite; session/state/target/profile/clock/trace/project-graph regressions pass; nine-project architecture and internal oracle boundary unchanged. |
|
||||
| AC-06 | PASSED | Actual pre-fix failures recorded; focused corrected regressions pass; complete nine-project Release build has 0 warnings/errors; 111 unit + 64 integration pass; actual native Client baseline smoke performed and distinguished from rendered injected fault. |
|
||||
| AC-07 | PASSED | README, documentation index, architecture, build guide, protocol guide, simulation guide and ADR-0004 document the corrected contract and evidence. |
|
||||
| AC-08 | PASSED | Scope and protected orchestration/history files preserved; no Step-04, agents, handoff automation, staging, commit or push; required report written; stop for manual review. |
|
||||
|
||||
## Preservation, limitations and handoff
|
||||
|
||||
No assignment, roadmap, orchestration state, prior report, protected Copilot
|
||||
instructions, dependency manifest or solution/project graph was modified by
|
||||
Step-03A. At task start, `prompts/ROADMAP.md` and `prompts/STATE.md` were already
|
||||
modified in the shared worktree; they were read as authority and left untouched.
|
||||
Pre-existing Step-03 implementation changes were preserved and integrated.
|
||||
No stage, commit, push or automated handoff was performed.
|
||||
|
||||
The protocol remains synthetic UTF-8 JSON, Simulation-only and in-process.
|
||||
Signals are static fixtures; no vehicle, physical transport, replay, telemetry
|
||||
capture, dynamics, calibration/firmware/programming, persistence or backend is
|
||||
available. Worker implementation and verification are complete; manual
|
||||
orchestrator acceptance remains pending. Stop here; do not begin Step-04.
|
||||
```
|
||||
|
|
@ -0,0 +1,342 @@
|
|||
# Step-03A - Synthetic wire integrity and verified virtual DTC clear
|
||||
|
||||
## STEP IDENTIFIER
|
||||
|
||||
Step-03A, corrective assignment for Step-03. Step-03 is NOT ACCEPTED.
|
||||
This is the sole active assignment. Step-04 is blocked and not assigned.
|
||||
R-01/R-02/R-03 below are Step-03 findings, not the closed Step-02 findings.
|
||||
|
||||
## STEP TITLE
|
||||
|
||||
Reject incomplete/ambiguous frames, validate replies before success/trace, and
|
||||
distinguish a virtual-clear acknowledgement from verified state change.
|
||||
|
||||
## OBJECTIVE
|
||||
|
||||
Correct three coupled integrity/verification defects in the existing synthetic
|
||||
diagnostics path, add actual failing-before/passing-after regressions and preserve
|
||||
the normal workflow and architecture. Do not start dynamics or redesign providers.
|
||||
|
||||
You are the WORKER. Execute only this correction, write
|
||||
`prompts/Step-03A-Report.md`, and STOP for manual orchestrator review.
|
||||
|
||||
## ARCHITECTURAL CONTEXT
|
||||
|
||||
Read [STATE.md](STATE.md), [ROADMAP.md](ROADMAP.md), original
|
||||
[Step-03](Step-03.md), its [report](Step-03-Report.md), the
|
||||
[protocol guide](../docs/synthetic-diagnostics-v1.md),
|
||||
[simulation guide](../docs/simulation.md) and
|
||||
[ADR-0004](../docs/adr-0004-synthetic-diagnostics.md).
|
||||
|
||||
Keep the nine-project .NET 10 modular monolith, Client -> UI -> Components,
|
||||
Application -> Core/Diagnostics and Simulation -> Core/Diagnostics. Client is
|
||||
the sole executable and composes the actual Simulation provider. Normal
|
||||
Application/UI paths cannot access the internal state oracle.
|
||||
|
||||
Only `docs`, `src`, `prompts` are top-level project directories; application/test
|
||||
projects stay under `src`, tests under `src/tests`. Handoffs remain manual.
|
||||
Do not invoke agents, automate communication or modify orchestration files.
|
||||
|
||||
## CURRENT IMPLEMENTATION STATE
|
||||
|
||||
Step-03 added actual provider/session/transport interfaces, a UTF-8 JSON synthetic
|
||||
protocol, virtual module definitions/state, typed outcomes, static signals,
|
||||
logical fault timing, bounded trace and the existing UI's `/diagnostics` route.
|
||||
|
||||
The provider is `autoforge.simulation.synthetic`, kind Simulation. Explicit
|
||||
profile/revision/provider/kind opening is separate from target metadata resolution.
|
||||
The engine virtual module supports DTC clear; its default state contains
|
||||
`SYN-P0123`. Other modules/session state and profile metadata must remain isolated.
|
||||
The internal IntegrationTests-only oracle supports independent state assertions.
|
||||
|
||||
Worker evidence reports complete nine-project/native Release build with zero
|
||||
warnings/errors, 108 unit + 53 integration cases passed (161 total, zero failed/
|
||||
skipped), plus actual native workflow/trace smoke. These covered normal paths and
|
||||
configured faults, not the vectors identified below.
|
||||
|
||||
Findings are from source/contract inspection. The orchestrator did not run
|
||||
application code/tests. Reproduce them yourself before changing behavior and
|
||||
report exact evidence; do not label static counterexamples as executed tests.
|
||||
|
||||
Inspect Git/instructions and preserve pre-existing dirty implementation, previous
|
||||
assignments/reports and accepted profile timestamp/evidence fixes. Use existing
|
||||
SDK/package/runner conventions. No new package, project, workload action,
|
||||
environment installation/repair/rollback or physical operation is authorized.
|
||||
|
||||
## REQUIRED IMPLEMENTATION
|
||||
|
||||
### R-01 - Reject incomplete and ambiguous requests before dispatch
|
||||
|
||||
Location:
|
||||
[SyntheticProtocolV1.cs](../src/AutoForge.Diagnostics/SyntheticProtocolV1.cs),
|
||||
Version at line 45 and TryDecodeRequest at line 82; dispatch occurs in
|
||||
[SimulationProvider.cs](../src/AutoForge.Simulation/SimulationProvider.cs).
|
||||
|
||||
Current deserialization leaves Version at its initializer value 1 if omitted.
|
||||
Omitted logicalTimeTicks can become zero, and duplicate JSON properties are not
|
||||
rejected before dispatch. With otherwise valid session/address/service fields,
|
||||
these frames can reach a state-changing virtual service.
|
||||
|
||||
Required behavior:
|
||||
|
||||
- Require the explicit wire fields documented for protocol v1. Omitted version
|
||||
or logical time is malformed, not an instruction to supply a default.
|
||||
An explicitly supplied zero logical tick remains valid.
|
||||
- Reject duplicate/ambiguous dispatch or binding fields rather than letting
|
||||
last-value deserialization select version, service, session, correlation,
|
||||
address, timing or profile/configuration.
|
||||
- Preserve request unknown-member rejection and document the field-name/
|
||||
unknown-field policy. Define consistent presence/ambiguity checks for received
|
||||
response envelopes and interpreted service objects as well.
|
||||
- Malformed requests must not dispatch any service or mutate virtual state.
|
||||
Use the existing explicit malformed/no-response or negative policy consistently;
|
||||
do not fabricate trustworthy correlation from an ambiguous frame.
|
||||
- Preserve explicit unsupported-version, unknown-address, service/session mismatch
|
||||
behavior. A structurally complete version-2 request still receives the existing
|
||||
unsupported-version failure; it must not be executed or silently treated as v1.
|
||||
|
||||
Keep programmatic request construction convenient if useful, but a C# initializer
|
||||
is not permission to infer a missing wire field. Do not introduce a new schema/
|
||||
protocol version merely to fix invalid input accepted by the stated v1 contract.
|
||||
|
||||
Minimum counterexamples for worker reproduction:
|
||||
|
||||
1. Encode an otherwise valid clear.dtcs request for a bound session and remove
|
||||
version. Current code defaults it to 1 and can clear virtual state.
|
||||
2. Remove logicalTimeTicks from an otherwise valid request.
|
||||
3. Use duplicate service properties with conflicting read/clear values, or
|
||||
duplicate version/correlation fields. Invalid/ambiguous bytes must not decide
|
||||
an operation by last-value parsing.
|
||||
|
||||
Use the real simulation transport and independent oracle to prove that rejected
|
||||
requests leave DTC state unchanged.
|
||||
|
||||
### R-02 - Complete response validation before positive results or trace
|
||||
|
||||
Location:
|
||||
[SyntheticDiagnosticProtocolClient.cs](../src/AutoForge.Diagnostics/SyntheticDiagnosticProtocolClient.cs),
|
||||
probe decoding/check around lines 35-65, static signal decoding at line 143,
|
||||
and positive trace/result commitment around line 289.
|
||||
|
||||
There are two related gaps:
|
||||
|
||||
- Well-formed JSON service payloads can contain semantically invalid data and
|
||||
still become successful results. For example negative signal logicalTimeTicks
|
||||
or blank signal identifier/unit are copied into record results. DTC text and
|
||||
advertised service lists also need appropriate semantic checks.
|
||||
- A probe naming the wrong module is marked ProtocolError by DiscoverAsync only
|
||||
after ExchangeAsync has traced it PositiveResponse. Trace and returned result
|
||||
disagree for the same received bytes.
|
||||
|
||||
Required behavior:
|
||||
|
||||
- Validate the envelope and complete interpreted service payload before returning
|
||||
or recording success. Duplicate/ambiguous response properties cannot select a
|
||||
different meaning through last-property lookup.
|
||||
- Enforce required nonblank identifiers/text, uniqueness where required by v1,
|
||||
valid service/quality tokens, source/module identity and valid logical timing.
|
||||
Static reply time must follow the documented request-time semantics; negative/
|
||||
inconsistent ticks cannot become a valid snapshot. Preserve explicit unknown
|
||||
values and legitimate empty DTC collections.
|
||||
- Validate success/error/data consistency against the documented positive and
|
||||
negative v1 contract. Contradictory or invalid positive data is ProtocolError,
|
||||
not successful empty or partially populated data.
|
||||
- Perform probe identity and service-list validation inside the same validated
|
||||
exchange path as other decoders. Exactly one truthful exchange trace must show
|
||||
the failure, retain the actual raw request/reply, and agree with the returned
|
||||
outcome. Do not leave a positive record then append a contradictory error.
|
||||
- Preserve actual timeout/no-response/cancelled behavior and no fabricated replies.
|
||||
Surface expected validation failures as typed, actionable protocol failures;
|
||||
do not add a blanket catch that hides unrelated implementation bugs.
|
||||
|
||||
Use small shared validation helpers only where useful. Do not duplicate alternative
|
||||
parsers/identity checks in UI or weaken existing profile validation.
|
||||
|
||||
Minimum counterexamples: a valid-envelope read.signals reply with a negative tick
|
||||
or blank ID/unit; a valid-envelope probe naming another module; duplicate response
|
||||
binding/service fields. Assert no success result/value and no positive trace for
|
||||
those exchanges. Also cover malformed DTC/service metadata and valid empty data.
|
||||
|
||||
### R-03 - Separate acknowledgement from verified clear
|
||||
|
||||
Location:
|
||||
[DiagnosticPageViewModel.cs](../src/AutoForge.UI/Features/Vehicles/Diagnostics/DiagnosticPageViewModel.cs),
|
||||
line 261. It tests only readback.IsSuccess and announces cleared state even when
|
||||
that successful readback still contains DTCs.
|
||||
|
||||
Required behavior:
|
||||
|
||||
- A positive clear response is an acknowledgement, not proof of state change.
|
||||
The logical clear-and-verify use case succeeds only when a fresh valid readback
|
||||
confirms the expected empty virtual DTC set.
|
||||
- Enforce verification in the existing Application/use-case boundary, with UI
|
||||
adapting its result. Keep low-level protocol acknowledgement distinct from the
|
||||
verified operation; use the smallest cohesive change, not a generic workflow engine.
|
||||
- Nonempty readback, failed/malformed/negative readback, timeout, cancellation or
|
||||
closed session must not produce a verified/cleared success message.
|
||||
- Report explicit verification failure/uncertainty. If a valid readback returned
|
||||
remaining codes, retain them as observed data with the failure visible; do not
|
||||
replace them with a success-shaped empty collection or misleading stale success.
|
||||
- Acknowledgement count alone must not determine verification. Already-empty
|
||||
valid modules may clear/read back empty successfully.
|
||||
- Preserve Simulation-only restriction, exact module/session binding, isolated
|
||||
state, unsupported-service outcomes, metadata-only profile semantics and the
|
||||
explicit statement that no physical write occurs.
|
||||
|
||||
Reproduce a positive clear acknowledgement that does not change virtual state,
|
||||
followed by a successful nonempty readback. Use a deterministic faulty transport/
|
||||
module below the real protocol/application boundary and the independent oracle.
|
||||
The real UI must show verification failure, not "was cleared and re-read".
|
||||
|
||||
## FILES OR PROJECTS EXPECTED TO CHANGE
|
||||
|
||||
- Correct existing Diagnostics request/reply validation and trace commitment.
|
||||
- Add the narrow Application clear-and-verify behavior/result as needed; adapt the
|
||||
existing UI view model/page without duplicating business verification logic.
|
||||
- Extend existing unit/integration/rendered tests and minimal deterministic fault
|
||||
helpers/definitions where needed. No new assembly, host, backend or package.
|
||||
- Update protocol/simulation/ADR/build guidance, documentation index as needed,
|
||||
and root README for actual corrective status/contracts/results.
|
||||
- Create only `prompts/Step-03A-Report.md` under `prompts`.
|
||||
|
||||
Do not modify assignments, ROADMAP, STATE, previous reports or protected Copilot
|
||||
instructions. Do not create override instruction files, initialize/reset Git,
|
||||
stage, commit, push or discard unrelated changes.
|
||||
|
||||
## INTERFACE AND DEPENDENCY REQUIREMENTS
|
||||
|
||||
Preserve the nine-project boundaries, actual wire path, explicit provider/profile/
|
||||
revision/session selection and lack of fallback. Keep normal Application/UI
|
||||
consumers outside Simulation internals; the test oracle remains internal to
|
||||
IntegrationTests.
|
||||
|
||||
Keep raw immutable payloads, bounded trace/loss, logical reproducibility, state
|
||||
isolation and accepted profile/schema behavior. Preserve valid v1 exchanges and
|
||||
error distinctions; document any necessary public contract change precisely.
|
||||
No clock redesign, physical adapter, dynamics engine or arbitrary packet console.
|
||||
|
||||
## TESTING REQUIREMENTS
|
||||
|
||||
### Before/after reproduction
|
||||
|
||||
Add focused regressions and execute them against the current code before the
|
||||
fixes. Record actual failing assertions/results, then correct the implementation
|
||||
and rerun. If a proposed vector behaves differently, investigate and report the
|
||||
actual evidence rather than inventing a failure.
|
||||
|
||||
### Unit and protocol regressions
|
||||
|
||||
- Valid v1 round trips still preserve all fields, including explicitly zero ticks.
|
||||
- Each required field missing/invalid is rejected as specified; exact duplicate/
|
||||
ambiguous properties cannot select dispatch or response meaning.
|
||||
- Missing version/tick and conflicting duplicate service/version/correlation
|
||||
requests do not cause virtual DTC mutation.
|
||||
- Valid unsupported-version/address/service cases retain their intended failures.
|
||||
- Semantically invalid signal time/identifier/unit/source/quality, malformed DTC
|
||||
text and probe metadata, inconsistent positive/error/data and duplicate reply
|
||||
fields yield typed protocol failures, not positive or partial data.
|
||||
- Wrong probe module yields matching discovery and trace failure; retain actual
|
||||
raw reply, exactly one exchange record and no positive record for that exchange.
|
||||
- Valid identity, DTC empty/nonempty, static signals, negative responses and
|
||||
bounded trace/outcome/cancellation behavior remain unchanged.
|
||||
|
||||
### Real Application/UI integration
|
||||
|
||||
Use the actual protocol client, application/session use cases and rendered UI.
|
||||
Faults may be injected by a small transport/factory decorator around the actual
|
||||
Simulation transport or a focused supported fault definition. Do not mock the
|
||||
feature/component under test, bypass the encoded path or add a fake app host.
|
||||
|
||||
Verify:
|
||||
|
||||
1. Invalid/ambiguous clear frames leave independent oracle state unchanged.
|
||||
2. Invalid positive/probe replies return failure and trace that same failure.
|
||||
3. Clear acknowledgement with no state change produces nonempty readback and
|
||||
explicit verification failure; codes remain visible and unrelated state is intact.
|
||||
4. Genuine clear plus empty readback is verified; readback failure/timeout/cancel/
|
||||
protocol error is never verified. Acknowledgement and verification are distinct.
|
||||
5. Session/target/profile isolation, reset, close, old routes and all accepted
|
||||
timestamp/optional-evidence behavior remain.
|
||||
|
||||
Use robust JSON mutation helpers and assertions that prove the intended field was
|
||||
changed/removed. Duplicate-field tests must really contain duplicate properties,
|
||||
not lose the duplication while reconstructing a JSON object in the test helper.
|
||||
|
||||
### Full regression and native verification
|
||||
|
||||
Preserve the current 161-case baseline (108 unit, 53 integration), add substantive
|
||||
coverage for all findings, and run sequential complete Release verification:
|
||||
|
||||
- `dotnet build .\src\AutoForge.slnx --configuration Release --no-restore`
|
||||
- `dotnet test .\src\AutoForge.slnx --configuration Release --no-build`
|
||||
|
||||
Restore packages only when needed; no workload-changing command is authorized.
|
||||
The complete build must include the actual Windows Client and all nine projects.
|
||||
Record exact commands/exit outcomes, warnings and per-project discovered/passed/
|
||||
failed/skipped counts; no required skip or headless subset reported as full success.
|
||||
|
||||
Launch the actual native Client and recheck explicit import/open/probe/read,
|
||||
successful virtual clear/verified empty readback, trace, an existing visible
|
||||
failure, reset/close and old routes. New malformed-wire and failed-verification
|
||||
vectors must be covered through real automated DI/rendered UI tests. If the
|
||||
existing safe fault composition permits a native failed-verification case,
|
||||
exercise it too; otherwise explicitly distinguish that rendered fault evidence
|
||||
from native baseline smoke. Do not add a raw-frame UI/test executable merely
|
||||
to manufacture native coverage. Report missing prerequisites honestly.
|
||||
|
||||
## DOCUMENTATION REQUIREMENTS
|
||||
|
||||
Update README and directly related protocol/simulation/ADR/testing guidance:
|
||||
|
||||
- Required request/reply presence, field-name/unknown-field policy, duplicate/
|
||||
ambiguity rejection and no-dispatch/no-state-change for malformed requests.
|
||||
- Semantic reply validation, failure/value rules and trace/result consistency.
|
||||
- Clear acknowledgement versus verified empty readback, failure/uncertainty
|
||||
presentation and Simulation-only limits.
|
||||
- Actual before/after/full-suite/native versus rendered evidence and Step-03A
|
||||
worker status versus pending orchestrator acceptance.
|
||||
|
||||
Preserve historical reports and LF Markdown conventions. Do not claim the
|
||||
original 161-case run covered these new vectors. Keep the synthetic/non-vehicle,
|
||||
static-signal, no-physical-programming limitations clear.
|
||||
|
||||
## ACCEPTANCE CRITERIA
|
||||
|
||||
| ID | Criterion | Required evidence |
|
||||
|---|---|---|
|
||||
| AC-01 | Explicit required/unambiguous v1 request fields enforced before dispatch; invalid frames never mutate virtual state | Missing/default/duplicate vectors through real transport and independent oracle |
|
||||
| AC-02 | Reply envelope/service semantics validate fully before success, with typed failure and no positive/partial values for malformed data | Valid/invalid response matrix and exact outcome/value assertions |
|
||||
| AC-03 | Probe identity and other semantic failures produce one truthful exchange trace matching returned outcome and retaining raw bytes | Correlation-specific trace assertions and real discovery integration |
|
||||
| AC-04 | Logical verified clear distinguishes acknowledgement from empty fresh readback; failed/nonempty/unknown readback cannot be reported verified | Application/real UI fault tests, oracle state and valid positive cases |
|
||||
| AC-05 | All prior state/session/target/profile/clock/trace/architecture invariants and 161 baseline cases retained | Regression mapping, actual graph/source review and per-project results |
|
||||
| AC-06 | Actual pre-fix failures, corrected focused/full nine-project build/test and native baseline smoke recorded honestly | Exact commands, outcomes, counts, native/rendered coverage distinction |
|
||||
| AC-07 | README/protocol/simulation/ADR/test docs accurately describe contract, verification and corrective lifecycle | Changed document list and policy/results summary |
|
||||
| AC-08 | Scope/protected/orchestration/history/manual handoff preserved; complete report written and worker stops | Preservation/Git review and `prompts/Step-03A-Report.md` |
|
||||
|
||||
Map every criterion to PASSED, FAILED, NOT EXECUTED or BLOCKED with evidence.
|
||||
COMPLETE requires all required correction/regression/native checks.
|
||||
Do not begin Step-04; acceptance belongs to the orchestrator.
|
||||
|
||||
## OUT-OF-SCOPE WORK
|
||||
|
||||
Vehicle dynamics/scenarios, real hardware/protocol/driver integration, telemetry
|
||||
recording/replay, calibration/firmware/programming/backups, AI/research, persistence,
|
||||
new hosts/projects/packages, clock/scheduling redesign, unrestricted raw-frame UI
|
||||
and unrelated cleanup. Physical safety/prohibited-operation restrictions remain.
|
||||
|
||||
## REPORTING REQUIREMENTS
|
||||
|
||||
Create `prompts/Step-03A-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; implemented functions;
|
||||
files created/modified; R-01/R-02/R-03 root causes/fixes; architectural/interface
|
||||
changes; unit/integration tests and actual before/after evidence; exact build/test
|
||||
commands/results and per-project counts; native versus rendered fault observations;
|
||||
AC-01 through AC-08 mapping; documentation and README updates; limitations/issues;
|
||||
deviations/recommendations; and protected/scope/Git preservation review.
|
||||
|
||||
No unexecuted case may be called passed. Save the report and STOP. Do not modify
|
||||
assignments/roadmap/state, create or begin Step-04, invoke agents, automate handoff,
|
||||
stage, commit or push.
|
||||
|
|
@ -0,0 +1,187 @@
|
|||
```
|
||||
# Step-03B - Preserve probe evidence when identification is unavailable
|
||||
|
||||
## Status
|
||||
|
||||
COMPLETE — implementation, documentation, regression coverage, Release build,
|
||||
complete test suite and required native baseline smoke are verified. Step-03
|
||||
remains pending manual orchestrator acceptance; Step-04 was not started.
|
||||
|
||||
## Root cause and correction
|
||||
|
||||
`DiscoverAsync` represented the combined discovery result using the later
|
||||
identity result. Consequently, a successful validated probe was lost whenever
|
||||
identity was unavailable or failed, and the responder count described verified
|
||||
identities rather than endpoints that had actually passed probe validation.
|
||||
|
||||
Discovery now keeps the validated `DiagnosticProbeResult` and its immutable
|
||||
advertised services separate from the optional `DiagnosticOperationResult`
|
||||
for identity. `DiscoveryEntry` exposes independent probe and identity outcomes,
|
||||
errors, identity status, and a reason when identity was not attempted.
|
||||
`DiscoveryResult` exposes expected-endpoint, validated-probe and identified-
|
||||
module collections/counts independently.
|
||||
|
||||
Chosen policy: when a positive probe does not advertise `read.identity`, do not
|
||||
send an unsupported identity request. Preserve the positive probe and services,
|
||||
leave identity null/unverified, and report an explicit not-attempted reason.
|
||||
Failed probes have no services and identity remains not attempted. No identity
|
||||
or permission is inferred from profile metadata. Read and clear remain gated on
|
||||
profile-verified runtime identity.
|
||||
|
||||
The UI reports the three distinct counts, renders phase-specific outcomes and
|
||||
reasons, shows retained probe service claims for partial rows, and disables
|
||||
identity-dependent actions until identity is verified. View-model action guards
|
||||
remain in place independently of the disabled controls. Each trace record
|
||||
continues to reflect only its actual exchange.
|
||||
|
||||
## Files changed for Step-03B
|
||||
|
||||
- `src/AutoForge.Diagnostics/ProviderContracts.cs`
|
||||
- `src/AutoForge.Diagnostics/SyntheticDiagnosticProtocolClient.cs`
|
||||
- `src/AutoForge.UI/Features/Vehicles/Diagnostics/DiagnosticPageViewModel.cs`
|
||||
- `src/AutoForge.UI/Features/Vehicles/Diagnostics/DiagnosticsPage.razor`
|
||||
- `src/tests/AutoForge.IntegrationTests/DiagnosticSessionCompositionTests.cs`
|
||||
- `src/tests/AutoForge.IntegrationTests/DiagnosticUiCompositionTests.cs`
|
||||
- `README.md`
|
||||
- `docs/synthetic-diagnostics-v1.md`
|
||||
- `docs/simulation.md`
|
||||
- `docs/architecture.md`
|
||||
- `docs/adr-0004-synthetic-diagnostics.md`
|
||||
- `docs/build-and-test.md`
|
||||
- `prompts/Step-03B-Report.md` (this report)
|
||||
|
||||
No assignment, roadmap or state file was edited in this step.
|
||||
|
||||
## Reproduction and tests
|
||||
|
||||
Before the fix, the new probe-only regression was executed through the real
|
||||
Simulation transport and DI composition. It failed as expected: the test
|
||||
observed `NegativeResponse` for discovery where the validated probe phase
|
||||
expected `PositiveResponse`. This reproduced the phase conflation at runtime,
|
||||
not by static inspection.
|
||||
|
||||
After correction, the focused real protocol/UI integration selection passed:
|
||||
35 passed, 0 failed, 0 skipped. The real-path matrix covers:
|
||||
|
||||
- Probe-only module: positive probe and service list retained, identity not
|
||||
attempted, no identity request emitted, and expected/probed/identified counts
|
||||
asserted.
|
||||
- Negative, malformed, mismatched and timed-out identity exchanges after a
|
||||
positive probe: null identity, retained exact service list, separate phase
|
||||
outcomes and exactly one truthful trace record per exchange, with distinct
|
||||
correlation identifiers.
|
||||
- Cancellation while identity is pending: positive probe remains positive,
|
||||
identity is cancelled, and partial counts/services remain accurate.
|
||||
- Failed probe vectors: no invented services or identity, explicit
|
||||
not-attempted identity state, and counts exclude the failed probe.
|
||||
- Normal identified and configured no-response modules, plus existing
|
||||
clear/readback/reset/session-isolation and trace behavior.
|
||||
- Rendered real `/diagnostics` partial state: distinct counts, reason/status,
|
||||
retained services, no profile-derived identity, and disabled read/clear
|
||||
buttons. Directly invoking the view-model actions also emits no new exchange
|
||||
and fails closed.
|
||||
- Rendered UI cancellation after a positive probe, followed by session close;
|
||||
no stale discovery row remains after close.
|
||||
|
||||
An intermediate focused run exposed an incorrect new test expectation: because
|
||||
discovery is sequential, cancellation during the first endpoint's identity
|
||||
exchange leaves only that endpoint's probe completed. The expected partial
|
||||
counts were corrected to one validated probe and zero identities; the focused
|
||||
suite then passed.
|
||||
|
||||
## Full Release verification
|
||||
|
||||
Exact build command:
|
||||
|
||||
`dotnet build .\src\AutoForge.slnx --configuration Release --no-restore`
|
||||
|
||||
Result: exit code 0; all nine solution projects built; 0 warnings and 0 errors.
|
||||
The MAUI XAML source-generation informational message was emitted; it was not a
|
||||
warning or error.
|
||||
|
||||
Exact test command:
|
||||
|
||||
`dotnet test .\src\AutoForge.slnx --configuration Release --no-build`
|
||||
|
||||
Result: exit code 0; `AutoForge.UnitTests`: 111 passed, 0 failed, 0 skipped;
|
||||
`AutoForge.IntegrationTests`: 72 passed, 0 failed, 0 skipped; 183 total.
|
||||
This retains the 175 Step-03A cases (111 unit and 64 integration) and adds
|
||||
eight integration cases for Step-03B.
|
||||
|
||||
## Native and rendered evidence
|
||||
|
||||
The actual Windows Client was launched with:
|
||||
|
||||
`src\AutoForge.Client\bin\Release\net10.0-windows10.0.26100.0\win-x64\AutoForge.Client.exe`
|
||||
|
||||
The Client was launched as a native Windows process. To interact only with its
|
||||
own WebView while leaving the shared desktop undisturbed, it was relaunched with
|
||||
the process-local `WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS=--remote-debugging-port=9333`;
|
||||
the local WebView target was `https://0.0.0.1/`. The transient debug listener
|
||||
and Client processes were stopped after the smoke. No project configuration or
|
||||
dependency was changed for this test.
|
||||
|
||||
Observed native baseline sequence:
|
||||
|
||||
1. `/diagnostics` initially showed no imported/selected profile or active
|
||||
session. Clicked **Load synthetic truck example** and verified the profile
|
||||
became available without auto-selection or session opening.
|
||||
2. Explicitly selected `autoforge.synthetic.test-truck`, revision `1`,
|
||||
`autoforge.simulation.synthetic`, and `Simulation`; opened session
|
||||
`diagnostic-session-000001`. The UI stated that no physical connection was
|
||||
attempted.
|
||||
3. Probed modules. The summary showed 3 expected endpoints, 2 validated
|
||||
positive probes, and 2 profile-verified identities. Engine and cabin/body
|
||||
had positive probe and identity results. The transmission probe visibly
|
||||
returned `NoResponse` with `Configured endpoint did not respond.` The raw
|
||||
trace contained the distinct positive probe/identity records and the
|
||||
transmission no-response record.
|
||||
4. Read engine DTCs and static signals. The UI showed `SYN-P0123`,
|
||||
`synthetic.engine.speed`, and `850`; the trace grew from five discovery
|
||||
records to seven and included positive `read.dtcs` and `read.signals`
|
||||
exchanges.
|
||||
5. Cleared engine virtual DTC state. The UI stated “Fresh readback verified
|
||||
that no DTCs remain” and “No physical write was performed.” The trace grew
|
||||
to nine records and showed positive `clear.dtcs` followed by a fresh
|
||||
positive `read.dtcs` with zero DTCs.
|
||||
6. Reset opened `diagnostic-session-000002` and cleared prior discovery
|
||||
presentation. A new probe/read restored and displayed `SYN-P0123`.
|
||||
Closing removed active-session and discovery rows and showed the expected
|
||||
isolated-state/trace release status.
|
||||
7. Existing native routes rendered expected headings: `/execution-targets`
|
||||
(“Select execution-target metadata”), `/vehicle-profiles` (“Vehicle profile
|
||||
metadata”), `/` (“AutoForge foundation”), and `/not-a-route` (“Page not
|
||||
found”).
|
||||
|
||||
The Step-03B partial-identity scenario, disabled actions and cancellation/
|
||||
close behavior are covered by the actual DI transport composition and rendered
|
||||
Blazor route tests; they are not claimed as native Client coverage. The prior
|
||||
Step-03A native evidence remains historical and is not substituted for this
|
||||
Step-03B native requirement.
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
| Criterion | Status | Evidence |
|
||||
|---|---|---|
|
||||
| AC-01 | PASSED | Real probe-only and identity-failure transport tests assert separate phase results, retained service values and null/unverified identity. |
|
||||
| AC-02 | PASSED | Result counts and rendered partial row/reason/service/action-gate assertions; direct view-model action guards emit no exchange. |
|
||||
| AC-03 | PASSED | Probe failure, no-response, identity timeout/malformed/mismatch/cancellation, correlation-specific trace, session lifecycle and rendered close/cancellation coverage. |
|
||||
| AC-04 | PASSED | Nine-project Release build and all 183 tests pass; prior 175 cases remain. Existing Step-03A verified-clear and wire-validation coverage remains green. |
|
||||
| AC-05 | PASSED | Actual pre-fix runtime failure, focused and complete verification, and the native Windows operational baseline smoke are recorded above. The partial-identity fault is covered by rendered real-DI tests, not claimed as native coverage. |
|
||||
| AC-06 | PASSED | README, protocol, Simulation, architecture, ADR-0004 and build/test documentation describe phase/count/action semantics and evidence. |
|
||||
| AC-07 | PASSED | This report is saved; only scoped code/tests/docs/report work was performed. No Step-04, assignment/roadmap/state edits, staging, commit or push. |
|
||||
|
||||
## Preservation, scope and remaining work
|
||||
|
||||
The existing dirty worktree includes broader Step-03/Step-03A implementation
|
||||
and documentation, as well as pre-existing edits to `prompts/ROADMAP.md` and
|
||||
`prompts/STATE.md`. Those two orchestration files were preserved and not edited.
|
||||
No new project, package, dependency, workload, host, provider, protocol version
|
||||
or unrelated feature was added. R-01/R-02/R-03 behavior and tests remain intact.
|
||||
`git diff --check` reported no whitespace errors; Git emitted only its existing
|
||||
LF-to-CRLF working-copy advisory for `README.md`.
|
||||
|
||||
All Step-03B worker checks are complete. Stop for manual orchestrator review;
|
||||
do not begin Step-04. No files outside the Step-03B scope were staged or
|
||||
committed; no push or handoff automation was performed.
|
||||
```
|
||||
|
|
@ -0,0 +1,298 @@
|
|||
# Step-03B - Preserve probe evidence when identification is unavailable
|
||||
|
||||
## STEP IDENTIFIER
|
||||
|
||||
Step-03B, corrective assignment for the remaining Step-03 finding R-04.
|
||||
Step-03A's R-01/R-02/R-03 fixes are accepted within their scope. Step-03 as a
|
||||
whole is NOT ACCEPTED. This is the sole active assignment; Step-04 is blocked.
|
||||
|
||||
## STEP TITLE
|
||||
|
||||
Represent successful probing and successful identification as separate facts,
|
||||
retaining valid partial discovery evidence and truthful UI counts.
|
||||
|
||||
## OBJECTIVE
|
||||
|
||||
Correct discovery's loss of a validated positive probe when the later identity
|
||||
operation is unavailable or fails. Preserve actual services/phase outcomes,
|
||||
explicit uncertainty, existing action guards, transport traces and all accepted
|
||||
wire/verification fixes. Do not redesign the protocol or begin dynamics.
|
||||
|
||||
You are the WORKER. Execute only this correction, write
|
||||
`prompts/Step-03B-Report.md`, and STOP for manual orchestrator review.
|
||||
|
||||
## ARCHITECTURAL CONTEXT
|
||||
|
||||
Read [STATE.md](STATE.md), [ROADMAP.md](ROADMAP.md), [Step-03](Step-03.md),
|
||||
its [report](Step-03-Report.md), [Step-03A](Step-03A.md) and its
|
||||
[report](Step-03A-Report.md), plus current protocol/simulation/architecture docs.
|
||||
|
||||
Keep the nine-project .NET 10 modular monolith, sole native Client and two RCLs.
|
||||
Diagnostics owns protocol/session/result contracts; Simulation owns virtual
|
||||
definitions/state; Application coordinates ports; UI presents application facts.
|
||||
No new project, package, host, backend, provider or mediator.
|
||||
|
||||
All source/projects/tests remain under `src`, tests under `src/tests`. Root
|
||||
project directories remain `docs`, `src`, `prompts`. Handoffs are manual.
|
||||
|
||||
## CURRENT IMPLEMENTATION STATE
|
||||
|
||||
The synthetic provider, explicit session lifecycle, real encoded wire path,
|
||||
static signals, virtual DTC state/oracle, bounded trace and `/diagnostics` UI
|
||||
exist. Step-03A corrected:
|
||||
|
||||
- Required/unambiguous requests and no dispatch for malformed clear frames.
|
||||
- Complete semantic reply validation before positive result/trace.
|
||||
- Application clear-and-verify, distinct acknowledgement and empty fresh readback.
|
||||
|
||||
Preserve these fixes and their actual regression coverage. Worker evidence records
|
||||
a clean complete nine-project/native Release build and 175 passed cases:
|
||||
111 unit + 64 integration, zero failed/skipped. Native baseline smoke passed;
|
||||
test-only injected failed-clear evidence was correctly reported as rendered
|
||||
real-DI integration, not native Client coverage.
|
||||
|
||||
The orchestrator found R-04 by inspecting source, allowed definitions and the
|
||||
discovery contract; it did not execute a reproduction or run builds/tests.
|
||||
Reinspect Git/instructions and preserve pre-existing dirty implementation and
|
||||
historical assignments/reports.
|
||||
|
||||
## REQUIRED IMPLEMENTATION
|
||||
|
||||
### R-04 - Do not discard successful probe evidence on identity failure
|
||||
|
||||
Relevant locations:
|
||||
|
||||
- [SyntheticDiagnosticProtocolClient.cs](../src/AutoForge.Diagnostics/SyntheticDiagnosticProtocolClient.cs),
|
||||
DiscoverAsync around line 72: after a positive probe, it builds the entry from
|
||||
the later identity result and discards advertised services if identity fails.
|
||||
- [ProviderContracts.cs](../src/AutoForge.Diagnostics/ProviderContracts.cs),
|
||||
DiscoveryResult around line 257: Responders counts non-null identities only.
|
||||
- [DiagnosticPageViewModel.cs](../src/AutoForge.UI/Features/Vehicles/Diagnostics/DiagnosticPageViewModel.cs),
|
||||
around line 132: that identity count is labeled actual endpoints that responded.
|
||||
|
||||
Concrete valid counterexample: configure a module to implement `probe` but not
|
||||
`read.identity`. This is allowed by VirtualModuleDefinition and protocol v1.
|
||||
The endpoint returns a validated positive probe. Its identity is unavailable,
|
||||
but current discovery loses its successful probe/service evidence and counts
|
||||
it as though it never responded.
|
||||
|
||||
The same information loss occurs when probing succeeds and identification then
|
||||
returns a negative response, malformed/mismatched identity, timeout or cancellation.
|
||||
This is not the fixed Step-03A case of an invalid probe: the probe itself is valid.
|
||||
|
||||
### 1. Preserve phase-specific results
|
||||
|
||||
Use the smallest clear result/model change that represents:
|
||||
|
||||
- Expected endpoint/profile context.
|
||||
- Probe outcome and its actionable error, if any.
|
||||
- Whether a validated positive probe was received, with its immutable advertised
|
||||
services retained independently of identity success.
|
||||
- Identity outcome or explicit not-attempted/unavailable state, its error and
|
||||
identity only when actually validated.
|
||||
|
||||
Do not encode not-attempted as default PositiveResponse, parse human error strings
|
||||
to infer the phase, or reconstruct business results from the trace.
|
||||
Define counts/collections so successful probes and successfully identified
|
||||
modules are distinguishable. Rename ambiguous members/update consumers where
|
||||
appropriate; no speculative compatibility adapter is required.
|
||||
|
||||
On probe success plus identity failure:
|
||||
|
||||
- Keep the successful probe and advertised services.
|
||||
- Keep identity null/unverified; preserve its actual failure/unavailable reason.
|
||||
- Do not substitute role/name/hardware/software/calibration from profile metadata
|
||||
and call that a retrieved identity.
|
||||
- Do not relabel the valid positive probe as failed because another exchange
|
||||
failed. Keep each actual wire exchange's own truthful trace/outcome.
|
||||
|
||||
On no-response/timeout/malformed/mismatched probe:
|
||||
|
||||
- Do not count it as a validated positive probe or an identified module.
|
||||
- Do not invent advertised services or perform/claim a successful identity read.
|
||||
- Preserve precise outcomes and explicit not-attempted identity state.
|
||||
|
||||
If identity is not advertised, the client may avoid an unsupported identity
|
||||
request or retain the existing explicit request/failure behavior. Document and
|
||||
test the chosen policy. Either way, its valid probe/service evidence remains.
|
||||
Do not require every virtual module to implement identity or reject valid
|
||||
probe-only definitions merely to hide the defect.
|
||||
|
||||
### 2. Make UI summaries and partial states truthful
|
||||
|
||||
Update the real UI/view model to distinguish expected endpoints, successful
|
||||
validated probes and identified modules. Labels must say what is counted;
|
||||
do not use an identity count as the number of endpoints that responded.
|
||||
|
||||
Show partial rows and advertised services with explicit identity-unavailable/
|
||||
unverified status and the phase-specific reason. A successful probe is not a
|
||||
complete identity verification or operational authorization.
|
||||
|
||||
Preserve existing identity-dependent read/clear action gates. In particular,
|
||||
retaining advertised clear support must not enable virtual clear when identity
|
||||
validation failed. Do not broaden low-level service authorization or physical
|
||||
access as part of this display/result correction.
|
||||
|
||||
Cancellation after a successful probe must retain already validated partial
|
||||
facts without claiming successful identification. Closing/resetting a session
|
||||
must still discard stale active-session presentation and preserve isolation.
|
||||
Normal fully identified examples and existing no-response behavior remain correct.
|
||||
|
||||
### 3. Keep the actual communication and safety boundaries
|
||||
|
||||
Derive facts from actual validated probe/identity exchanges, not profile inventory,
|
||||
role assumptions or test-only shortcuts. Preserve strict v1 request/reply
|
||||
validation, no fallback, immutable raw trace, logical timing, isolated state,
|
||||
Application verified-clear and the internal test-oracle boundary.
|
||||
|
||||
No wire-format/schema version change, simulation clock redesign, extra service,
|
||||
physics, raw-frame console or new host is required.
|
||||
|
||||
## FILES OR PROJECTS EXPECTED TO CHANGE
|
||||
|
||||
- Diagnostics discovery result/aggregation and directly related consumers.
|
||||
- Existing diagnostic UI view model/page for phase-specific rows/counts/messages.
|
||||
- Existing unit/real-DI/rendered integration tests and narrowly needed data/fault
|
||||
helpers. Keep original synthetic examples where practical.
|
||||
- README, discovery/protocol/simulation/ADR/testing docs as directly affected.
|
||||
- Create only `prompts/Step-03B-Report.md` under `prompts`.
|
||||
|
||||
Do not change assignments, ROADMAP, STATE, previous reports or protected Copilot
|
||||
instructions, or create override instructions. Do not stage, commit, push,
|
||||
initialize/reset Git or discard unrelated work.
|
||||
|
||||
## INTERFACE AND DEPENDENCY REQUIREMENTS
|
||||
|
||||
Retain the nine-project graph and one Client executable. Keep phase/model/business
|
||||
aggregation in Diagnostics/Application and UI presentation in the RCL. No UI or
|
||||
Application access to Simulation runtime state/oracle. No new dependencies or
|
||||
workload install/restore/update/repair/rollback are authorized; ordinary package
|
||||
restore is distinct and only needed after a real missing-dependency failure.
|
||||
|
||||
Unknown/unavailable identity is never fabricated verification or permission.
|
||||
All Simulation-only, metadata/connection, no-physical-programming and accepted
|
||||
profile timestamp/evidence safeguards remain unchanged.
|
||||
|
||||
## TESTING REQUIREMENTS
|
||||
|
||||
### Actual pre-fix reproduction
|
||||
|
||||
Add a real-definition/transport regression for a valid positive probe with
|
||||
unsupported identity and execute it against the current code. Record the actual
|
||||
failure before implementing the correction, then record passing corrected runs.
|
||||
Do not describe static analysis as a runtime reproduction.
|
||||
|
||||
### Required behavioral matrix
|
||||
|
||||
Use actual protocol/Simulation/Application paths, not a mocked discovery service:
|
||||
|
||||
1. Valid probe-only module: positive probe retained, no verified identity, explicit
|
||||
unsupported/unavailable identity, advertised probe services retained; correct
|
||||
probe-versus-identified counts.
|
||||
2. Valid probe advertising other services but unavailable identity: retain claims
|
||||
as probe evidence while existing identity-dependent actions remain blocked.
|
||||
3. Valid probe followed by negative identity, malformed/mismatched identity and
|
||||
timeout: preserve probe and services, report actual identity failure, no fake
|
||||
identity and no false no-response classification.
|
||||
4. Cancellation or session close after a successful probe while identity is
|
||||
pending: preserve correct low-level phase facts; UI remains partial/cancelled
|
||||
or closed, never stale identified success.
|
||||
5. Failed/no-response/timeout/invalid probe: zero validated positive probe count,
|
||||
no fabricated identity/services, clear identity-not-attempted status.
|
||||
6. Normal fully responding/identified modules: both metrics correct, existing
|
||||
discovery/read/verified-clear/reset/trace behavior unchanged.
|
||||
|
||||
A small deterministic response decorator may reuse the existing
|
||||
RewritingDiagnosticTransportFactory for identity-specific faults. Do not alter
|
||||
every service's latency just to simulate an identity timeout if that would time
|
||||
out the preceding probe too. Do not add random delays or Thread.Sleep tests.
|
||||
|
||||
Assert actual raw traces per exchange: valid probe stays PositiveResponse;
|
||||
identity failure retains its own negative/protocol/timeout/cancelled outcome;
|
||||
no duplicate or rewritten probe trace. Assert exact identity-null and retained
|
||||
service-list values, not just endpoint counts.
|
||||
|
||||
### Real UI integration
|
||||
|
||||
Render the actual `/diagnostics` route with real DI after the partial discovery.
|
||||
Assert truthful distinct counts/labels, phase-specific reason, visible unverified
|
||||
identity and retained advertised services. Ensure no profile-derived identity or
|
||||
identity-dependent clear/read button is enabled on that partial row.
|
||||
|
||||
Keep original profile/target/home/not-found routes and R-01/R-02/R-03 correction
|
||||
assertions. Map any necessary discovery API/label assertion changes explicitly;
|
||||
do not delete safety or failure checks to make the suite green.
|
||||
|
||||
### Full build/regression and native evidence
|
||||
|
||||
Preserve the accepted corrective baseline of 175 cases (111 unit/64 integration)
|
||||
and add the missing cases. Run focused checks, then sequential complete Release
|
||||
verification with the actual Windows Client:
|
||||
|
||||
- `dotnet build .\src\AutoForge.slnx --configuration Release --no-restore`
|
||||
- `dotnet test .\src\AutoForge.slnx --configuration Release --no-build`
|
||||
|
||||
Record exact commands/exit outcomes, warnings and per-project discovered/passed/
|
||||
failed/skipped counts. No filtered headless build reported as complete.
|
||||
|
||||
Run native baseline smoke for explicit import/open/probe, truthful summary,
|
||||
read/verified clear, trace, an existing visible failure, reset/close and old routes.
|
||||
If the existing safe composition permits a native partial-identity scenario,
|
||||
exercise it. Otherwise distinguish its real-DI/rendered test evidence from native
|
||||
baseline smoke, as Step-03A did. Do not add a fault console/test executable merely
|
||||
to manufacture native coverage. Report missing prerequisites honestly.
|
||||
|
||||
## DOCUMENTATION REQUIREMENTS
|
||||
|
||||
Update README and directly related protocol/simulation/ADR/testing docs for:
|
||||
|
||||
- Probe success versus identity verification and not-attempted/unavailable states.
|
||||
- Count/collection semantics and retained partial advertised services.
|
||||
- Identity-dependent action policy, no metadata-derived identity/authority, trace
|
||||
phase consistency and cancellation/close behavior.
|
||||
- Actual before/after/full-suite results, native versus rendered evidence and
|
||||
pending parent Step-03 acceptance.
|
||||
|
||||
Preserve historical reports and LF Markdown conventions. Do not rewrite the
|
||||
175-case report as if it covered R-04. Static signals remain synthetic fixtures,
|
||||
not dynamics, capture, compatibility or physical access.
|
||||
|
||||
## ACCEPTANCE CRITERIA
|
||||
|
||||
| ID | Criterion | Required evidence |
|
||||
|---|---|---|
|
||||
| AC-01 | Successful probe/service evidence survives unavailable/failed identity with explicit independent phase states and no fabricated identity | Probe-only and advertised-identity-failure real transport/DI assertions |
|
||||
| AC-02 | Expected/probed/identified counts and UI rows accurately describe partial discovery, with identity-dependent actions still fail-closed | Actual result values, rendered labels/reasons/service lists and action assertions |
|
||||
| AC-03 | Invalid/no-response probes and post-probe timeout/cancel/close preserve truthful outcomes/trace without stale success | Deterministic phase matrix and correlation-specific raw trace/lifecycle checks |
|
||||
| AC-04 | Normal workflow, R-01/R-02/R-03 fixes, profiles/targets/state/oracle/project graph and all 175 prior cases retained | Regression mapping, actual nine-project build and per-project suite evidence |
|
||||
| AC-05 | Actual pre-fix failure, corrected focused/full verification and native baseline evidence are recorded honestly | Exact commands, outcomes, counts and native/rendered coverage distinction |
|
||||
| AC-06 | README/protocol/simulation/ADR/test docs match phase/count/action semantics and corrective lifecycle | Changed document list and contract summary |
|
||||
| AC-07 | No unrelated feature/package/workload/orchestration/history change; complete report saved and worker stops | Preservation/Git/scope evidence and `prompts/Step-03B-Report.md` |
|
||||
|
||||
Map every criterion to PASSED, FAILED, NOT EXECUTED or BLOCKED with evidence.
|
||||
COMPLETE requires all required correction/regression/native checks.
|
||||
Do not begin Step-04; parent milestone acceptance belongs to the orchestrator.
|
||||
|
||||
## OUT-OF-SCOPE WORK
|
||||
|
||||
New diagnostic protocols/services or physical adapters, relaxed authorization,
|
||||
vehicle dynamics/scenarios, telemetry recording/replay, calibration/programming,
|
||||
AI/research/persistence, new projects/hosts/packages, clock redesign, broad model
|
||||
refactors, fault consoles and unrelated cleanup. Physical safety/prohibited-
|
||||
operation restrictions remain in force.
|
||||
|
||||
## REPORTING REQUIREMENTS
|
||||
|
||||
Create `prompts/Step-03B-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-04 root cause/fix;
|
||||
files created/modified; result/API/phase/count changes; unit/integration/UI tests
|
||||
and actual pre-fix/post-fix evidence; exact build/test commands/results with
|
||||
per-project counts; native/rendered observations; AC-01 through AC-07 mapping;
|
||||
documentation and 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-04, invoke agents, automate handoff, stage, commit or push.
|
||||
|
|
@ -0,0 +1,433 @@
|
|||
# Step-04 - Deterministic vehicle dynamics and scenario execution
|
||||
|
||||
## STEP IDENTIFIER
|
||||
|
||||
Step-04. Corrected Step-03 and its Step-03A/Step-03B corrections were accepted
|
||||
on 2026-10-28. This is the sole active implementation assignment.
|
||||
|
||||
## STEP TITLE
|
||||
|
||||
Run an explicitly configured synthetic vehicle through coupled engine,
|
||||
transmission and longitudinal dynamics using a fixed virtual clock, with actual
|
||||
dynamic telemetry exposed through the diagnostic path.
|
||||
|
||||
## OBJECTIVE
|
||||
|
||||
Deliver a deterministic, headless-testable dynamics engine and a working
|
||||
native-application slice: explicitly load/select configuration, open a dynamics
|
||||
session, start/pause/resume/stop/reset/step, execute a scenario, inspect diagnostic
|
||||
telemetry and import/export the configuration for reproduction.
|
||||
|
||||
Preserve the accepted static synthetic provider and all diagnostics/profile
|
||||
corrections. This is simplified synthetic physics, not a validated real-world
|
||||
prediction, module calibration/programming, AI or physical vehicle integration.
|
||||
|
||||
You are the WORKER. Execute only this assignment, verify it, write
|
||||
`prompts/Step-04-Report.md`, and STOP for manual orchestrator review.
|
||||
|
||||
## ARCHITECTURAL CONTEXT
|
||||
|
||||
Read [ROADMAP.md](ROADMAP.md), [STATE.md](STATE.md), accepted
|
||||
[Step-03](Step-03.md), [Step-03A](Step-03A.md), [Step-03B](Step-03B.md) and their
|
||||
reports, [architecture](../docs/architecture.md),
|
||||
[simulation](../docs/simulation.md), [protocol v1](../docs/synthetic-diagnostics-v1.md)
|
||||
and [profile schema v1](../docs/vehicle-profile-schema-v1.md).
|
||||
|
||||
Keep the nine-project .NET 10 modular monolith and sole MAUI Blazor Hybrid Client.
|
||||
Simulation owns physics/clock implementation, not Application/UI. Put only needed
|
||||
platform-neutral run/configuration/control contracts in Core or an appropriate
|
||||
existing shared-contract location. Application coordinates those ports and
|
||||
Diagnostics; it must not reference Simulation implementation. Client composes it.
|
||||
UI calls application features; it does not read the simulation oracle.
|
||||
|
||||
No new assembly, executable, backend, mediator, container or cloud dependency is
|
||||
needed. Root project directories remain `docs`, `src`, `prompts`; all projects/
|
||||
tests stay under `src`, tests under `src/tests`. Handoffs remain manual.
|
||||
|
||||
## CURRENT IMPLEMENTATION STATE
|
||||
|
||||
The solution has Core, Application, Diagnostics, Simulation, Components, UI,
|
||||
Client, UnitTests and IntegrationTests. Actual production references:
|
||||
|
||||
- Diagnostics -> Core; Simulation -> Core/Diagnostics.
|
||||
- Application -> Core/Diagnostics; UI -> Application/Components/Diagnostics.
|
||||
- Client -> Application/UI/Simulation; Components and Core have no AutoForge
|
||||
project dependency. One executable, no cycles.
|
||||
|
||||
Accepted features include immutable schema-v1 profiles/provenance/capabilities,
|
||||
explicit target metadata and exact profile/revision selection, real Simulation
|
||||
sessions, strict synthetic protocol v1, module probing/identity/DTC/virtual-clear,
|
||||
static signals, logical diagnostic timing/faults and bounded raw trace.
|
||||
|
||||
The provider `autoforge.simulation.synthetic` is static: configured engine speed
|
||||
is 850 rpm, not dynamics. Preserve it and its wire behavior. Discovery now retains
|
||||
positive probe/service evidence independently of identity success; actions remain
|
||||
identity-gated. Application verified clear requires fresh empty readback.
|
||||
|
||||
Important existing surfaces:
|
||||
|
||||
- [DiagnosticSessionService.cs](../src/AutoForge.Application/Features/Vehicles/Diagnostics/DiagnosticSessionService.cs)
|
||||
opens/resets exact profile/provider sessions. Reset currently preserves those
|
||||
fields; it will also need to preserve the new dynamics configuration binding.
|
||||
- [ProviderContracts.cs](../src/AutoForge.Diagnostics/ProviderContracts.cs) derives
|
||||
ConfigurationIdentifier from profile/revision and exposes diagnostic/control
|
||||
boundaries; profile identity alone is insufficient to identify a dynamics setup.
|
||||
- [SyntheticDiagnosticProtocolClient.cs](../src/AutoForge.Diagnostics/SyntheticDiagnosticProtocolClient.cs)
|
||||
strictly accepts v1 static signal origin and request-time semantics.
|
||||
- [SimulationProvider.cs](../src/AutoForge.Simulation/SimulationProvider.cs) owns
|
||||
per-session virtual state; the runtime state oracle is internal to tests.
|
||||
|
||||
Worker evidence records a complete nine-project Release build with zero warnings/
|
||||
errors, 111 unit + 72 integration passes (183 total, zero failed/skipped), and
|
||||
native baseline smoke. These are previous worker results, not orchestrator reruns.
|
||||
|
||||
Existing verified worker platform: SDK 10.0.402, runtime 10.0.13, Windows Client
|
||||
TFM `net10.0-windows10.0.26100.0`/win-x64, MAUI Windows manifest 10.0.110,
|
||||
WebView2 155.0.4283.62. Inspect prerequisites read-only if needed. No workload/
|
||||
system install, update, restore, repair or rollback is authorized.
|
||||
|
||||
Recheck Git/instructions and preserve pre-existing dirty implementation and all
|
||||
historical assignments/reports.
|
||||
|
||||
## REQUIRED IMPLEMENTATION
|
||||
|
||||
### 1. Explicit immutable run/model/scenario configuration
|
||||
|
||||
Introduce a small versioned configuration document separate from profile schema v1:
|
||||
|
||||
- Exact profile identifier/revision and relevant module/calibration reference
|
||||
metadata; model/version and configuration identity.
|
||||
- Required synthetic model parameters, explicit units and provenance/limitations.
|
||||
- Initial conditions, environment/road-load settings, fixed virtual step and
|
||||
driving scenario. No hidden defaults for missing physical inputs.
|
||||
- Enough information to reproduce an entire run without AI, network, wall-clock
|
||||
state or previously active UI choices.
|
||||
|
||||
Keep shared contracts/invariants platform-neutral; implement engine/clock in
|
||||
Simulation and import/list/select/export use cases in appropriate Application
|
||||
feature slices. An in-memory configuration catalog plus explicit JSON import/
|
||||
export is sufficient; no user-file storage/database is required.
|
||||
|
||||
Reject unsupported format/model versions, missing/duplicate/unknown fields,
|
||||
non-finite numbers, invalid units/ranges, zero/negative mass/radius/ratios,
|
||||
unordered/duplicate curve points and incompatible profile/module references.
|
||||
Document supported numeric/step ranges. Do not silently clamp invalid inputs or
|
||||
fill them with a preset. Named synthetic examples may explicitly supply defaults.
|
||||
Snapshot collections/configuration; caller edits/imports cannot mutate a live run.
|
||||
|
||||
Run identity must bind exact profile/configuration/model/initial/environment/
|
||||
scenario inputs, not merely profile key or process GetHashCode. Use a documented
|
||||
stable versioned identity/fingerprint where needed. Keep operational run/session
|
||||
IDs distinct from the stable reproducibility identity.
|
||||
|
||||
Save/export and reload/import must preserve semantic inputs. Unknown real-world
|
||||
facts remain unknown: synthetic model parameters do not promote profile metadata
|
||||
to verified manufacturer data. Idle/shift model settings here are simulation
|
||||
inputs, not edited module calibration, firmware or approved tunes.
|
||||
|
||||
### 2. Separate dynamics from existing static diagnostics
|
||||
|
||||
Add a real explicitly selected dynamics provider, for example
|
||||
`autoforge.simulation.dynamics`, kind Simulation. Preserve the existing static
|
||||
provider/fixtures without silently converting their responses into physics.
|
||||
|
||||
Bind a control capability and diagnostic transport to the same run/session.
|
||||
Application uses shared interfaces, never concrete engine fields or a competing
|
||||
global active-run registry. Choose the simplest coherent capability/factory
|
||||
extension; no generic plugin framework or new ports assembly.
|
||||
|
||||
- Exact configuration selection is mandatory for a dynamics session. Missing/
|
||||
incompatible config, wrong provider/kind or unsupported control capability
|
||||
fails explicitly; no static/dynamic/profile fallback.
|
||||
- Update open/reset/session identity/transport/composition/UI surfaces together.
|
||||
Reset must reopen/reset the exact selected configuration and initial state,
|
||||
not whatever config was imported or selected later.
|
||||
- Closing/resetting releases the old engine/pacer/pending operations and cannot
|
||||
change another session or leave a stale active controller.
|
||||
- Static/replay/physical selections cannot acquire dynamics controls accidentally.
|
||||
Replay and physical operation remain unavailable.
|
||||
- A user-triggered example load may prepare profile/config/scenario data but
|
||||
must not auto-select/open/start a run when a page opens.
|
||||
|
||||
### 3. Fixed-step virtual clock and lifecycle
|
||||
|
||||
Implement one authority for model time and state advancement. Recommended default
|
||||
step: 0.1 virtual seconds; document and validate the actual supported interval.
|
||||
Compute model time from integer step/tick count, not accumulated wall-clock deltas.
|
||||
|
||||
Support start, pause, resume, stop, reset, single/multiple explicit steps and
|
||||
configurable playback/pacing speed. Define valid state transitions and failures:
|
||||
|
||||
- Pause/stop freeze virtual time and all physics. Stop is not engine ignition-off;
|
||||
reset explicitly restores configured initial conditions and counters.
|
||||
- Stepping advances exact configured virtual steps in allowed non-running states;
|
||||
it does not silently start a background loop.
|
||||
- Pacing changes only scheduling, never the numerical step, physics or scenario
|
||||
inputs. Same virtual steps/inputs produce the same state at every pacing factor.
|
||||
- Diagnostic reads, UI renders, trace capacity and wall-clock jitter cannot advance
|
||||
or alter vehicle state. Keep diagnostic delivery ticks separate from model time.
|
||||
- Serialize step/control/lifecycle changes; pause/stop/close must complete without
|
||||
a later stale tick or disposed-resource operation. Cancellation is explicit.
|
||||
|
||||
A real-time pacer may schedule fixed steps for native interaction. Headless
|
||||
scenario execution must run virtual minutes without sleeping for real minutes.
|
||||
No Thread.Sleep, random sensor generation or LLM-in-the-loop calculations.
|
||||
Introduce no randomness unless genuinely required; no unused seed placeholder.
|
||||
|
||||
### 4. Coupled simplified longitudinal vehicle model
|
||||
|
||||
Provide data-driven synthetic parameters for:
|
||||
|
||||
- Engine running/idle control, throttle, RPM, torque/load and fuel use.
|
||||
- Forward transmission gears/ratios/final drive, automatic shift schedule and
|
||||
hysteresis; explicit neutral/engagement/slip assumptions.
|
||||
- Vehicle mass, wheel radius, longitudinal forces, acceleration/deceleration,
|
||||
braking, rolling/aerodynamic road load and distance.
|
||||
- Ambient/initial temperatures and a documented simple coolant/thermal model.
|
||||
|
||||
Use SI internally and explicit presentation conversions. Dynamic signals derive
|
||||
from one coupled state; do not generate independent RPM/speed/gear readings.
|
||||
When fully coupled, outside declared shift/slip intervals:
|
||||
|
||||
`engineRPM = speed_mps / (2 * pi * wheelRadius_m) * 60 * gearRatio * finalDrive`
|
||||
|
||||
Low-speed idle/launch behavior needs an explicit coupling/slip assumption; do
|
||||
not claim locked coupling while independently clamping RPM to idle. Gear/torque
|
||||
changes must affect wheel force/speed, and shifts must not hunt under steady
|
||||
cruise. Automatic shifting is a model input schedule, not a calibration write.
|
||||
|
||||
Advance speed from configured tractive/braking/road forces and mass. Do not set
|
||||
actual speed directly to a scenario target or teleport between states. Fuel/
|
||||
load/power/temperature calculations must follow the model state and assumptions.
|
||||
Fuel rate/total must stay finite/nonnegative; cumulative consumption is monotonic.
|
||||
Engine-off fuel/RPM and stopped/neutral behavior are explicitly modeled.
|
||||
|
||||
Validate impossible initial combinations or derive redundant values from a
|
||||
documented independent state; do not silently repair conflicting inputs.
|
||||
Detect non-finite/out-of-domain evolution as an explicit failed run, not zero
|
||||
telemetry/success fallback. Keep original input snapshots unchanged.
|
||||
|
||||
This is a simplified behavioral model, not firmware emulation, manufacturer
|
||||
accuracy, emissions analysis, a safe tune recommendation or real fuel-economy proof.
|
||||
|
||||
### 5. Deterministic scenario and measurable synthetic demonstration
|
||||
|
||||
Support a versioned machine-readable finite scenario with explicit start/engine,
|
||||
idle, acceleration/target-speed hold, braking/stop and return-idle phases.
|
||||
Controllers produce bounded throttle/brake/gear inputs using virtual time;
|
||||
they never directly assign vehicle speed. Define failure/time-limit behavior.
|
||||
|
||||
Provide a complete documented warmed synthetic baseline using a 650 rpm warm
|
||||
idle target. Under its declared parameters, test:
|
||||
|
||||
1. Stationary warm idle stabilizes within 650 +/- 5 rpm after 10 virtual seconds.
|
||||
2. Normal/moderate acceleration reaches 45 MPH (20.1168 m/s) within 60 virtual
|
||||
seconds without a speed jump, with genuine scheduled shifting.
|
||||
3. Hold 45 MPH for the full 300 virtual seconds; at least 95% of hold samples are
|
||||
within +/- 1 MPH (0.44704 m/s). Do not shorten or omit failed samples. The
|
||||
warmed cruise must actually enter its defined coupled regime.
|
||||
4. Brake to speed <= 0.1 m/s within 60 virtual seconds, without negative-speed
|
||||
overshoot, and return to stationary idle for at least 10 virtual seconds.
|
||||
5. Same immutable inputs/step sequence reproduce all sampled model results and
|
||||
lifecycle/scenario outcomes under a documented numerical comparison contract.
|
||||
|
||||
Publish the actual chosen model parameters/curves and achievable assumptions.
|
||||
Do not tune test assertions to broad "nonzero" proxies or game the goal by
|
||||
teleporting, always labeling the drivetrain slipping, or filtering bad samples.
|
||||
Manual inputs and scenario control must have a documented single-owner policy.
|
||||
|
||||
### 6. Dynamic telemetry through actual diagnostic communications
|
||||
|
||||
The engine updates virtual module state internally; normal Application/UI
|
||||
telemetry still comes through actual encoded diagnostic requests/responses.
|
||||
Expose RPM, speed, gear, throttle/brake/load/torque, fuel rate/total, temperature,
|
||||
distance/acceleration and model time as appropriate to the modeled modules.
|
||||
Preserve source module, units, quality, model/configuration identity and origin.
|
||||
|
||||
Existing protocol v1 is explicitly static and strict. Do not relabel dynamic
|
||||
readings SYNTHETIC_STATIC, silently accept new unknown fields or conflate its
|
||||
request ticks with model time. Introduce the smallest explicit versioned/
|
||||
negotiated dynamic protocol extension, preserving old v1 behavior and its
|
||||
unsupported-version tests. Document exact new fields/origins/time units.
|
||||
|
||||
Dynamic replies must bind to the actual selected run/configuration and a
|
||||
consistent model-step snapshot. Preserve diagnostic correlation and distinguish
|
||||
capture/request time from model time. Paused/stepped reads across modules must
|
||||
refer to the same unchanged model step. Running asynchronous samples must expose
|
||||
their actual model time rather than claim simultaneous sampling.
|
||||
|
||||
Keep service/payload validation, partial probe/identity states, verified clear,
|
||||
no-response/error/cancellation and bounded trace/loss semantics. Reading signals
|
||||
must not itself tick physics. No UI/AI ground-truth shortcut: internal test
|
||||
oracle access may be deliberately limited to approved test assemblies only.
|
||||
|
||||
### 7. Application/UI integration
|
||||
|
||||
Add cohesive Application configuration/run/scenario/control features and a minimal
|
||||
simulation page/workflow in the existing UI:
|
||||
|
||||
- Explicit profile/config/provider selection and separate open/start actions.
|
||||
- Config JSON import/export, lifecycle/scenario selection and controls, current
|
||||
virtual time/phase/progress, explicit stop/cancel and pacing selection.
|
||||
- A simple source/unit/model-time-aware numeric telemetry table refreshed through
|
||||
diagnostics; no full gauge/dashboard framework (Step-05).
|
||||
- Visible configuration/lifecycle/model/protocol failures, including unsupported
|
||||
static-target controls, with no stale active-run success after close/reset.
|
||||
|
||||
Reuse shared components and existing navigation/DI. Client changes are composition
|
||||
and platform lifecycle only. Preserve old static diagnostics/profile/target routes.
|
||||
Do not auto-open a run, require AI, create a backend or add a new executable.
|
||||
|
||||
## FILES OR PROJECTS EXPECTED TO CHANGE
|
||||
|
||||
- Needed Core/shared run/config/control contracts and validation.
|
||||
- Simulation model/clock/scenario/controller implementation and explicit dynamics
|
||||
factory/definitions, without UI/Application dependency.
|
||||
- Diagnostics/session/configuration/protocol integration required for dynamic
|
||||
snapshots and exact binding, keeping static compatibility.
|
||||
- Application configuration/run/control slices and UI feature presentation.
|
||||
- Client composition, existing unit/integration tests and related documentation.
|
||||
- Create only `prompts/Step-04-Report.md` under `prompts`.
|
||||
|
||||
No new project is assigned. Do not modify assignments, ROADMAP, STATE, previous
|
||||
reports or protected Copilot instructions, or create override instructions.
|
||||
Do not stage, commit, push, initialize/reset Git or discard unrelated dirty work.
|
||||
|
||||
## INTERFACE AND DEPENDENCY REQUIREMENTS
|
||||
|
||||
Keep the nine-project inward/reference boundaries, one Client/two RCLs and static/
|
||||
dynamic selection explicit. Runtime sensors are diagnostic data; control/status
|
||||
ports are not public unrestricted engine/module ground truth. Keep test-oracle
|
||||
access internal and document any necessary test-only access change.
|
||||
|
||||
Use proper types/units, immutable configuration and explicit failures. Do not
|
||||
introduce generic managers/repositories, mediator boilerplate, arbitrary scripting,
|
||||
magic physical defaults, broad catches or invalid-input success fallbacks.
|
||||
Physical writes, arbitrary hardware frames and calibration/tune editing remain absent.
|
||||
|
||||
## TESTING REQUIREMENTS
|
||||
|
||||
### Unit and independent numerical verification
|
||||
|
||||
Test actual model/clock/controller/configuration behavior, not just DI:
|
||||
|
||||
- Required/finite/range/unit/curve/identity validation and semantic configuration
|
||||
round-trip; caller mutation and incompatible versions cannot alter a run.
|
||||
- Fixed-step lifecycle, pause/stop/reset/step, pacing-independent results, invalid
|
||||
transitions, cancellation/disposal and no background tick after close.
|
||||
- Independent wheel/RPM/gear-ratio calculations for coupled states, force/mass/
|
||||
acceleration checks, braking/drag and meaningful shift/hysteresis behavior.
|
||||
- Idle/engine-off/neutral/launch/shift assumptions, finite load/fuel/temperature,
|
||||
monotonic fuel/distance and the complete numeric scenario thresholds above.
|
||||
- Repeat equivalent runs and compare full sampled results, not only final speed.
|
||||
No wall-clock sleeps or arbitrary elapsed-time/performance success thresholds.
|
||||
|
||||
Do not validate an algorithm by calling the same implementation to compute its
|
||||
expected answer. Use analytical/reference equations and known fixtures; an
|
||||
internal oracle may inspect actual state independently of the diagnostic decoder.
|
||||
|
||||
### Real Application/diagnostic/UI integration
|
||||
|
||||
1. Import/select exact profile and run config, explicitly open a dynamics session,
|
||||
start/pause/step/run scenario and read computed values through actual frames.
|
||||
2. Pause, read repeatedly/across modules and prove no physics/model-time change;
|
||||
verify ratios and shared snapshot identity/time independently.
|
||||
3. Import/select another config while a run exists; prove original is immutable
|
||||
and reset preserves the original exact configuration, not latest selection.
|
||||
4. Different sessions remain isolated; close/reset/cancel releases resources and
|
||||
suppresses stale tick/telemetry/lifecycle results. Use controlled scheduling.
|
||||
5. Wrong/missing profile/config/provider, static controls, malformed/version/
|
||||
origin/time/binding replies and unsupported targets fail explicitly.
|
||||
6. Preserve static v1 diagnostics and R-01/R-02/R-03/R-04, including partial
|
||||
identity/action guards, verified clear, raw trace and strict profile schema.
|
||||
7. Render the actual UI with real ports; inspect meaningful control/state/
|
||||
telemetry/error results. No feature-under-test mock or direct UI engine oracle.
|
||||
|
||||
### Full build and native evidence
|
||||
|
||||
Preserve the 183-case baseline (111 unit/72 integration), mapping any intentional
|
||||
interface/presentation assertion changes. Add substantive new tests; no required
|
||||
skips, removed safety assertions or fake green placeholders.
|
||||
|
||||
Run focused tests during implementation, then sequential complete Release
|
||||
verification using the existing runner/SDK:
|
||||
|
||||
- `dotnet build .\src\AutoForge.slnx --configuration Release --no-restore`
|
||||
- `dotnet test .\src\AutoForge.slnx --configuration Release --no-build`
|
||||
|
||||
Restore packages only when needed. The full build includes the actual native
|
||||
Windows Client and all nine projects, not a filtered headless substitute.
|
||||
Record exact commands/targets/versions/results, warnings and per-project counts.
|
||||
|
||||
Launch the actual native Client: explicitly load/select a dynamics example,
|
||||
open/start, observe diagnostic dynamic telemetry/model time, pause/step/resume,
|
||||
change pacing, run the scenario (accelerated pacing is allowed), stop/reset and
|
||||
export/reload configuration. Verify reset identity, visible invalid/unsupported
|
||||
case, clean close and old static/profile/target/not-found routes. Distinguish
|
||||
native observations from headless numerical proof; do not claim a visual gauge
|
||||
proves mathematical consistency or repeatability.
|
||||
|
||||
Stop only task-owned helper processes and clean exact temporary smoke assets.
|
||||
Report missing prerequisites honestly; no workload install or host substitution.
|
||||
|
||||
## DOCUMENTATION REQUIREMENTS
|
||||
|
||||
Update README/index/architecture/build guide and add only useful actual docs/ADRs:
|
||||
|
||||
- Model equations, units, parameters/curves, numerical integration, coupling/
|
||||
slip/shift/fuel/thermal assumptions and unsupported fidelity.
|
||||
- Fixed clock/lifecycle/scenario/pacing and concurrency/cancellation semantics.
|
||||
- Versioned configuration identity/format, exact reset binding and reproduction.
|
||||
- Static versus dynamic provider/protocol/origin/model-time compatibility.
|
||||
- Actual Application/UI workflow, source/quality/telemetry/oracle boundaries,
|
||||
tests, numeric thresholds/results and native limitations.
|
||||
|
||||
Align Step-03/03A/03B acceptance and Step-04 worker status accurately. Preserve
|
||||
historical reports. Simulation estimates are not proven real-world fuel savings,
|
||||
safe calibrations, manufacturer compatibility or programming authorization.
|
||||
|
||||
## ACCEPTANCE CRITERIA
|
||||
|
||||
| ID | Criterion | Required evidence |
|
||||
|---|---|---|
|
||||
| AC-01 | Immutable explicit versioned run/config/scenario inputs bind exact profile/model/initial/environment data, with strict validation and import/export | Invalid/round-trip/mutation tests and documented stable identity/format |
|
||||
| AC-02 | Fixed virtual clock, lifecycle/step/pacing and cancellation/disposal are deterministic and independent of reads/UI/wall jitter | Controlled scheduling tests, exact tick/step assertions and no stale work |
|
||||
| AC-03 | Static provider remains intact; explicit dynamics provider/control capability and reset preserve exact configuration/session isolation | Actual factory/session/feature tests, two configurations/sessions and wrong-target failures |
|
||||
| AC-04 | Coupled engine/transmission/longitudinal/load/fuel/thermal behavior is finite and physically consistent within declared assumptions | Independent equations/oracle checks, shift/idle/brake cases and full state comparisons |
|
||||
| AC-05 | Warm idle, <=60s acceleration to 45 MPH, full 300s hold accuracy, stop/return-idle and reproducibility meet numeric gates above | Exact metrics/sample counts/tolerances from automated tests, not visual proxies |
|
||||
| AC-06 | Dynamic telemetry crosses actual versioned diagnostic path with truthful origin/model time/config binding; static v1 and error/partial/clear guards preserved | Wire compatibility/bad-payload tests, paused multi-module snapshot checks and no read-driven physics |
|
||||
| AC-07 | Real Application/UI provide configuration/lifecycle/scenario/pacing/diagnostic table without oracle shortcut or shell restructuring | Source/reference review, rendered tests and native interaction evidence |
|
||||
| AC-08 | Complete nine-project Release/native build, both suites/baseline regressions and required native workflow succeed | Exact commands, warnings, per-project counts, numerical results and native observations |
|
||||
| AC-09 | README/docs/ADRs accurately describe implementation, equations/contracts/reproduction and limitations | Changed document list and implemented/planned/fidelity summary |
|
||||
| AC-10 | Protected/history/manual workflow preserved; complete report saved and worker stops | Preservation/Git/scope review and `prompts/Step-04-Report.md` |
|
||||
|
||||
Map every criterion to PASSED, FAILED, NOT EXECUTED or BLOCKED with evidence.
|
||||
COMPLETE requires all required numeric, regression and native checks.
|
||||
Do not begin Step-05; acceptance belongs to the orchestrator.
|
||||
|
||||
## OUT-OF-SCOPE WORK
|
||||
|
||||
Full configurable gauges/dashboard framework, telemetry recording/replay/
|
||||
comparison, real manufacturer definitions, firmware emulation, calibration/
|
||||
programming/backups, AI/research/knowledge, physical adapters/vehicles, databases,
|
||||
cloud/containers, additional platforms/hosts/projects and unrelated refactoring.
|
||||
No emissions defeat, anti-theft bypass, mileage falsification or safety disabling.
|
||||
|
||||
## REPORTING REQUIREMENTS
|
||||
|
||||
Create `prompts/Step-04-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; implemented functions;
|
||||
files created/modified; actual contracts/reference graph and provider/config/run
|
||||
identity; equations/parameters/units/clock/scenario assumptions; unit/integration
|
||||
coverage and independent numerical evidence; exact build/test commands/results
|
||||
with per-project counts; all scenario metrics/tolerances/sample totals; native
|
||||
versus headless observations; AC-01 through AC-10 mapping; documentation/README
|
||||
updates; limitations/issues; deviations/recommendations; and protected/scope/Git
|
||||
preservation review.
|
||||
|
||||
No failed/unexecuted case may be called passed. Save the report and STOP.
|
||||
Do not modify assignments/roadmap/state, create or begin Step-05, invoke agents,
|
||||
automate handoff, stage, commit or push.
|
||||
|
|
@ -2,6 +2,7 @@
|
|||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\AutoForge.Core\AutoForge.Core.csproj" />
|
||||
<ProjectReference Include="..\AutoForge.Diagnostics\AutoForge.Diagnostics.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<PropertyGroup>
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
using System.Collections.ObjectModel;
|
||||
using AutoForge.Core.ExecutionTargets;
|
||||
|
||||
namespace AutoForge.Application.ExecutionTargets;
|
||||
|
|
@ -6,6 +7,7 @@ public sealed class ExecutionTargetResolver : IExecutionTargetResolver
|
|||
{
|
||||
private readonly Dictionary<string, ExecutionTargetDescriptor> registrations =
|
||||
new(StringComparer.OrdinalIgnoreCase);
|
||||
private readonly IReadOnlyList<ExecutionTargetDescriptor> _registeredDescriptors;
|
||||
|
||||
public ExecutionTargetResolver(IEnumerable<ExecutionTargetDescriptor> registrations)
|
||||
{
|
||||
|
|
@ -26,8 +28,12 @@ public sealed class ExecutionTargetResolver : IExecutionTargetResolver
|
|||
"Use unique identifiers under ordinal case-insensitive comparison, even across target kinds.");
|
||||
}
|
||||
}
|
||||
|
||||
_registeredDescriptors = new ReadOnlyCollection<ExecutionTargetDescriptor>(this.registrations.Values.ToArray());
|
||||
}
|
||||
|
||||
public IReadOnlyList<ExecutionTargetDescriptor> RegisteredDescriptors => _registeredDescriptors;
|
||||
|
||||
public ExecutionTargetDescriptor Resolve(ExecutionTargetDescriptor selection)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(selection);
|
||||
|
|
|
|||
|
|
@ -5,5 +5,6 @@ namespace AutoForge.Application.ExecutionTargets;
|
|||
/// <summary>Resolves an explicit provider identifier and kind without substituting another target.</summary>
|
||||
public interface IExecutionTargetResolver
|
||||
{
|
||||
IReadOnlyList<ExecutionTargetDescriptor> RegisteredDescriptors { get; }
|
||||
ExecutionTargetDescriptor Resolve(ExecutionTargetDescriptor selection);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,305 @@
|
|||
using AutoForge.Application.ExecutionTargets;
|
||||
using AutoForge.Application.Features.Vehicles.Profiles;
|
||||
using AutoForge.Core.ExecutionTargets;
|
||||
using AutoForge.Core.Vehicles;
|
||||
using AutoForge.Diagnostics;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace AutoForge.Application.Features.Vehicles.Diagnostics;
|
||||
|
||||
public enum DiagnosticSessionFailure
|
||||
{
|
||||
ProviderNotRegistered,
|
||||
UnsupportedTargetKind,
|
||||
DefinitionNotFound,
|
||||
InvalidDefinition,
|
||||
SessionConflict
|
||||
}
|
||||
|
||||
public sealed class DiagnosticSessionException(
|
||||
DiagnosticSessionFailure failure,
|
||||
string message,
|
||||
Exception? innerException = null) : Exception(message, innerException)
|
||||
{
|
||||
public DiagnosticSessionFailure Failure { get; } = failure;
|
||||
}
|
||||
|
||||
public sealed class DiagnosticClearVerificationResult
|
||||
{
|
||||
internal DiagnosticClearVerificationResult(
|
||||
DiagnosticOperationResult<TroubleCodeClearResult> acknowledgement,
|
||||
DiagnosticOperationResult<TroubleCodeReadResult>? readback,
|
||||
bool isVerified,
|
||||
string? verificationError)
|
||||
{
|
||||
Acknowledgement = acknowledgement;
|
||||
Readback = readback;
|
||||
IsVerified = isVerified;
|
||||
VerificationError = verificationError;
|
||||
}
|
||||
|
||||
public DiagnosticOperationResult<TroubleCodeClearResult> Acknowledgement { get; }
|
||||
public DiagnosticOperationResult<TroubleCodeReadResult>? Readback { get; }
|
||||
public bool IsVerified { get; }
|
||||
public string? VerificationError { get; }
|
||||
}
|
||||
|
||||
public interface IDiagnosticSessionService
|
||||
{
|
||||
IReadOnlyList<DiagnosticProviderDescriptor> Providers { get; }
|
||||
Task<DiagnosticSession> OpenAsync(
|
||||
string profileIdentifier,
|
||||
int profileRevision,
|
||||
string providerIdentifier,
|
||||
ExecutionTargetKind targetKind,
|
||||
CancellationToken cancellationToken = default);
|
||||
Task<DiagnosticSession> ResetAsync(DiagnosticSession session, CancellationToken cancellationToken = default);
|
||||
}
|
||||
|
||||
public sealed class DiagnosticSession(
|
||||
VehicleProfile profile,
|
||||
DiagnosticSessionIdentity identity,
|
||||
IDiagnosticProtocolClient protocol,
|
||||
IDiagnosticTransport transport,
|
||||
CancellationTokenSource lifetime) : IAsyncDisposable
|
||||
{
|
||||
private int _closed;
|
||||
|
||||
public VehicleProfile Profile { get; } = profile;
|
||||
public DiagnosticSessionIdentity Identity { get; } = identity;
|
||||
public IReadOnlyList<DiagnosticEndpoint> ExpectedEndpoints => protocol.ExpectedEndpoints;
|
||||
public DiagnosticTraceSnapshot Trace => protocol.Trace;
|
||||
public bool IsClosed => Volatile.Read(ref _closed) != 0;
|
||||
|
||||
public Task<DiscoveryResult> DiscoverAsync(CancellationToken cancellationToken = default) =>
|
||||
InvokeAsync(protocol.DiscoverAsync, cancellationToken);
|
||||
|
||||
public Task<DiagnosticOperationResult<ModuleIdentityResult>> ReadIdentityAsync(
|
||||
DiagnosticEndpoint endpoint,
|
||||
CancellationToken cancellationToken = default) =>
|
||||
InvokeAsync(token => protocol.ReadIdentityAsync(endpoint, token), cancellationToken);
|
||||
|
||||
public Task<DiagnosticOperationResult<TroubleCodeReadResult>> ReadTroubleCodesAsync(
|
||||
DiagnosticEndpoint endpoint,
|
||||
CancellationToken cancellationToken = default) =>
|
||||
InvokeAsync(token => protocol.ReadTroubleCodesAsync(endpoint, token), cancellationToken);
|
||||
|
||||
public Task<DiagnosticOperationResult<TroubleCodeClearResult>> ClearTroubleCodesAsync(
|
||||
DiagnosticEndpoint endpoint,
|
||||
CancellationToken cancellationToken = default) =>
|
||||
InvokeAsync(token => protocol.ClearTroubleCodesAsync(endpoint, token), cancellationToken);
|
||||
|
||||
public Task<DiagnosticClearVerificationResult> ClearTroubleCodesAndVerifyAsync(
|
||||
DiagnosticEndpoint endpoint,
|
||||
CancellationToken cancellationToken = default) =>
|
||||
InvokeAsync(async token =>
|
||||
{
|
||||
var acknowledgement = await protocol.ClearTroubleCodesAsync(endpoint, token).ConfigureAwait(false);
|
||||
if (!acknowledgement.IsSuccess)
|
||||
{
|
||||
return new DiagnosticClearVerificationResult(
|
||||
acknowledgement,
|
||||
null,
|
||||
false,
|
||||
$"Virtual clear was not acknowledged ({acknowledgement.Outcome}): {acknowledgement.Error}");
|
||||
}
|
||||
|
||||
var readback = await protocol.ReadTroubleCodesAsync(endpoint, token).ConfigureAwait(false);
|
||||
if (!readback.IsSuccess)
|
||||
{
|
||||
return new DiagnosticClearVerificationResult(
|
||||
acknowledgement,
|
||||
readback,
|
||||
false,
|
||||
$"Virtual clear was acknowledged, but fresh readback could not verify the state ({readback.Outcome}): {readback.Error}");
|
||||
}
|
||||
|
||||
if (readback.Value!.Codes.Count != 0)
|
||||
{
|
||||
return new DiagnosticClearVerificationResult(
|
||||
acknowledgement,
|
||||
readback,
|
||||
false,
|
||||
$"Virtual clear was acknowledged, but fresh readback still contains {readback.Value.Codes.Count} DTC(s).");
|
||||
}
|
||||
|
||||
return new DiagnosticClearVerificationResult(acknowledgement, readback, true, null);
|
||||
}, cancellationToken);
|
||||
|
||||
public Task<DiagnosticOperationResult<SignalSnapshot>> ReadSignalsAsync(
|
||||
DiagnosticEndpoint endpoint,
|
||||
CancellationToken cancellationToken = default) =>
|
||||
InvokeAsync(token => protocol.ReadSignalsAsync(endpoint, token), cancellationToken);
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _closed, 1) == 0)
|
||||
{
|
||||
lifetime.Cancel();
|
||||
await transport.DisposeAsync().ConfigureAwait(false);
|
||||
lifetime.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<T> InvokeAsync<T>(Func<CancellationToken, Task<T>> operation, CancellationToken cancellationToken)
|
||||
{
|
||||
if (IsClosed)
|
||||
{
|
||||
return await operation(new CancellationToken(canceled: true)).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (!cancellationToken.CanBeCanceled)
|
||||
{
|
||||
return await operation(lifetime.Token).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
using var linked = CancellationTokenSource.CreateLinkedTokenSource(lifetime.Token, cancellationToken);
|
||||
return await operation(linked.Token).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class DiagnosticSessionService : IDiagnosticSessionService
|
||||
{
|
||||
private readonly IVehicleProfileService _profiles;
|
||||
private readonly IExecutionTargetResolver _targets;
|
||||
private readonly IReadOnlyList<IDiagnosticTransportFactory> _factories;
|
||||
private readonly Func<IDiagnosticLogicalClock> _logicalClockFactory;
|
||||
private long _sessionSequence;
|
||||
|
||||
public DiagnosticSessionService(
|
||||
IVehicleProfileService profiles,
|
||||
IExecutionTargetResolver targets,
|
||||
IEnumerable<IDiagnosticTransportFactory> factories,
|
||||
Func<IDiagnosticLogicalClock> logicalClockFactory)
|
||||
{
|
||||
_profiles = profiles;
|
||||
_targets = targets;
|
||||
_factories = Array.AsReadOnly(factories.ToArray());
|
||||
_logicalClockFactory = logicalClockFactory ?? throw new ArgumentNullException(nameof(logicalClockFactory));
|
||||
Providers = Array.AsReadOnly(_factories.Select(factory => factory.Descriptor).ToArray());
|
||||
}
|
||||
|
||||
public IReadOnlyList<DiagnosticProviderDescriptor> Providers { get; }
|
||||
|
||||
public Task<DiagnosticSession> OpenAsync(
|
||||
string profileIdentifier,
|
||||
int profileRevision,
|
||||
string providerIdentifier,
|
||||
ExecutionTargetKind targetKind,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
var profile = _profiles.Select(profileIdentifier, profileRevision);
|
||||
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 null)
|
||||
{
|
||||
throw new DiagnosticSessionException(
|
||||
DiagnosticSessionFailure.ProviderNotRegistered,
|
||||
$"No diagnostic transport is registered for provider '{target.ProviderIdentifier}'.");
|
||||
}
|
||||
|
||||
var sequence = Interlocked.Increment(ref _sessionSequence);
|
||||
var identity = new DiagnosticSessionIdentity(
|
||||
$"diagnostic-session-{sequence:D6}",
|
||||
profile.ProfileIdentifier,
|
||||
profile.Revision,
|
||||
profile.Vehicle.VehicleIdentifier,
|
||||
target);
|
||||
var logicalClock = _logicalClockFactory()
|
||||
?? throw new InvalidOperationException("The logical clock factory returned null.");
|
||||
|
||||
IDiagnosticTransport transport;
|
||||
try
|
||||
{
|
||||
transport = factory.OpenTransport(profile, identity);
|
||||
}
|
||||
catch (DiagnosticProviderException exception)
|
||||
{
|
||||
throw new DiagnosticSessionException(
|
||||
exception.Failure switch
|
||||
{
|
||||
DiagnosticProviderFailure.ConfigurationNotFound => DiagnosticSessionFailure.DefinitionNotFound,
|
||||
DiagnosticProviderFailure.SessionConflict => DiagnosticSessionFailure.SessionConflict,
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(exception), "The provider returned an undefined failure.")
|
||||
},
|
||||
exception.Message,
|
||||
exception);
|
||||
}
|
||||
catch (ArgumentException exception)
|
||||
{
|
||||
throw new DiagnosticSessionException(
|
||||
DiagnosticSessionFailure.InvalidDefinition,
|
||||
exception.Message,
|
||||
exception);
|
||||
}
|
||||
|
||||
var lifetime = new CancellationTokenSource();
|
||||
var protocol = new SyntheticDiagnosticProtocolClient(
|
||||
profile,
|
||||
identity,
|
||||
transport,
|
||||
logicalClock);
|
||||
return Task.FromResult(new DiagnosticSession(profile, identity, protocol, transport, lifetime));
|
||||
}
|
||||
|
||||
public async Task<DiagnosticSession> ResetAsync(
|
||||
DiagnosticSession session,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(session);
|
||||
var identity = session.Identity;
|
||||
await session.DisposeAsync().ConfigureAwait(false);
|
||||
return await OpenAsync(
|
||||
identity.ProfileIdentifier,
|
||||
identity.ProfileRevision,
|
||||
identity.Target.ProviderIdentifier,
|
||||
identity.Target.Kind,
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
public static class DiagnosticSessionServiceCollectionExtensions
|
||||
{
|
||||
public static IServiceCollection AddAutoForgeDiagnostics(
|
||||
this IServiceCollection services,
|
||||
IEnumerable<IDiagnosticTransportFactory> factories,
|
||||
Func<IDiagnosticLogicalClock>? logicalClockFactory = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(services);
|
||||
ArgumentNullException.ThrowIfNull(factories);
|
||||
if (services.Any(service => service.ServiceType == typeof(IDiagnosticSessionService)))
|
||||
{
|
||||
throw new InvalidOperationException("Diagnostic session services are already registered.");
|
||||
}
|
||||
|
||||
var providerFactories = factories.ToArray();
|
||||
if (providerFactories.Any(factory => factory is null))
|
||||
{
|
||||
throw new ArgumentException("Diagnostic provider factories cannot contain null values.", nameof(factories));
|
||||
}
|
||||
|
||||
services.AddAutoForgeTargetSelection(providerFactories.Select(factory => factory.Descriptor.Target));
|
||||
foreach (var factory in providerFactories)
|
||||
{
|
||||
services.AddSingleton(typeof(IDiagnosticTransportFactory), factory);
|
||||
services.AddSingleton(factory.GetType(), factory);
|
||||
}
|
||||
|
||||
services.AddSingleton<IDiagnosticSessionService>(provider =>
|
||||
new DiagnosticSessionService(
|
||||
provider.GetRequiredService<IVehicleProfileService>(),
|
||||
provider.GetRequiredService<IExecutionTargetResolver>(),
|
||||
provider.GetServices<IDiagnosticTransportFactory>(),
|
||||
logicalClockFactory ?? (() => new DiagnosticLogicalClock())));
|
||||
return services;
|
||||
}
|
||||
}
|
||||
|
|
@ -62,6 +62,7 @@
|
|||
<ItemGroup>
|
||||
<ProjectReference Include="..\AutoForge.UI\AutoForge.UI.csproj" />
|
||||
<ProjectReference Include="..\AutoForge.Application\AutoForge.Application.csproj" />
|
||||
<ProjectReference Include="..\AutoForge.Simulation\AutoForge.Simulation.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
|
|
|||
|
|
@ -1,6 +1,8 @@
|
|||
using Microsoft.Extensions.Logging;
|
||||
using AutoForge.Application.ExecutionTargets;
|
||||
using AutoForge.Diagnostics;
|
||||
using AutoForge.Application.Features.Vehicles.Profiles;
|
||||
using AutoForge.Application.Features.Vehicles.Diagnostics;
|
||||
using AutoForge.Simulation;
|
||||
using AutoForge.UI;
|
||||
|
||||
namespace AutoForge.Client;
|
||||
|
|
@ -14,8 +16,9 @@ public static class MauiProgram
|
|||
.UseMauiApp<App>()
|
||||
.ConfigureFonts(fonts => fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular"));
|
||||
|
||||
builder.Services.AddAutoForgeTargetSelection([]);
|
||||
builder.Services.AddAutoForgeVehicleProfiles();
|
||||
builder.Services.AddAutoForgeDiagnostics(
|
||||
[new SimulatedDiagnosticTransportFactory(SyntheticDiagnosticExamples.CreateDefinitions())]);
|
||||
builder.Services.AddAutoForgeUi();
|
||||
builder.Services.AddMauiBlazorWebView();
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,13 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\AutoForge.Core\AutoForge.Core.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
</Project>
|
||||
|
|
@ -0,0 +1,521 @@
|
|||
using System.Collections.ObjectModel;
|
||||
using System.Text.Json;
|
||||
using System.Text.RegularExpressions;
|
||||
using AutoForge.Core.ExecutionTargets;
|
||||
using AutoForge.Core.Vehicles;
|
||||
|
||||
namespace AutoForge.Diagnostics;
|
||||
|
||||
public sealed class DiagnosticProviderDescriptor
|
||||
{
|
||||
public DiagnosticProviderDescriptor(ExecutionTargetDescriptor target, string displayName)
|
||||
{
|
||||
Target = target ?? throw new ArgumentNullException(nameof(target));
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(displayName);
|
||||
DisplayName = displayName;
|
||||
}
|
||||
|
||||
public ExecutionTargetDescriptor Target { get; }
|
||||
public string DisplayName { get; }
|
||||
}
|
||||
|
||||
public sealed class DiagnosticSessionIdentity
|
||||
{
|
||||
public DiagnosticSessionIdentity(
|
||||
string sessionIdentifier,
|
||||
string profileIdentifier,
|
||||
int profileRevision,
|
||||
string vehicleIdentifier,
|
||||
ExecutionTargetDescriptor target)
|
||||
{
|
||||
SessionIdentifier = Require(sessionIdentifier, nameof(sessionIdentifier));
|
||||
ProfileIdentifier = Require(profileIdentifier, nameof(profileIdentifier));
|
||||
if (profileRevision <= 0)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(profileRevision));
|
||||
}
|
||||
|
||||
ProfileRevision = profileRevision;
|
||||
ConfigurationIdentifier = $"profile:{ProfileIdentifier}@revision:{ProfileRevision}";
|
||||
VehicleIdentifier = Require(vehicleIdentifier, nameof(vehicleIdentifier));
|
||||
Target = target ?? throw new ArgumentNullException(nameof(target));
|
||||
}
|
||||
|
||||
public string SessionIdentifier { get; }
|
||||
public string ProfileIdentifier { get; }
|
||||
public int ProfileRevision { get; }
|
||||
public string ConfigurationIdentifier { get; }
|
||||
public string VehicleIdentifier { get; }
|
||||
public ExecutionTargetDescriptor Target { get; }
|
||||
|
||||
private static string Require(string value, string parameterName)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(value, parameterName);
|
||||
if (!StringComparer.Ordinal.Equals(value, value.Trim()))
|
||||
{
|
||||
throw new ArgumentException("Values must not contain surrounding whitespace.", parameterName);
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class DiagnosticEndpoint
|
||||
{
|
||||
private static readonly Regex AddressPattern = new(@"\A[0-9A-Fa-f]{1,4}\z", RegexOptions.CultureInvariant | RegexOptions.Compiled);
|
||||
|
||||
public DiagnosticEndpoint(string moduleIdentifier, string address)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(moduleIdentifier);
|
||||
if (!StringComparer.Ordinal.Equals(moduleIdentifier, moduleIdentifier.Trim()))
|
||||
{
|
||||
throw new ArgumentException("Module identifiers must not contain surrounding whitespace.", nameof(moduleIdentifier));
|
||||
}
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(address);
|
||||
if (!StringComparer.Ordinal.Equals(address, address.Trim()))
|
||||
{
|
||||
throw new ArgumentException("Endpoint addresses must not contain surrounding whitespace.", nameof(address));
|
||||
}
|
||||
|
||||
if (!AddressPattern.IsMatch(address))
|
||||
{
|
||||
throw new ArgumentException("Synthetic protocol addresses must be one to four hexadecimal digits.", nameof(address));
|
||||
}
|
||||
|
||||
ModuleIdentifier = moduleIdentifier;
|
||||
Address = address;
|
||||
}
|
||||
|
||||
public string ModuleIdentifier { get; }
|
||||
public string Address { get; }
|
||||
}
|
||||
|
||||
public interface IDiagnosticTransportFactory
|
||||
{
|
||||
DiagnosticProviderDescriptor Descriptor { get; }
|
||||
IDiagnosticTransport OpenTransport(VehicleProfile profile, DiagnosticSessionIdentity identity);
|
||||
}
|
||||
|
||||
public enum DiagnosticProviderFailure
|
||||
{
|
||||
ConfigurationNotFound,
|
||||
SessionConflict
|
||||
}
|
||||
|
||||
public sealed class DiagnosticProviderException(
|
||||
DiagnosticProviderFailure failure,
|
||||
string message,
|
||||
Exception? innerException = null) : Exception(message, innerException)
|
||||
{
|
||||
public DiagnosticProviderFailure Failure { get; } = failure;
|
||||
}
|
||||
|
||||
public interface IDiagnosticTransport : IAsyncDisposable
|
||||
{
|
||||
IReadOnlyList<DiagnosticEndpoint> ExpectedEndpoints { get; }
|
||||
ValueTask<TransportReply> SendAsync(ReadOnlyMemory<byte> request, CancellationToken cancellationToken);
|
||||
}
|
||||
|
||||
public enum TransportOutcome
|
||||
{
|
||||
Response,
|
||||
NoResponse,
|
||||
Timeout,
|
||||
Cancelled
|
||||
}
|
||||
|
||||
public sealed class TransportReply
|
||||
{
|
||||
private readonly byte[]? _payload;
|
||||
|
||||
public TransportReply(TransportOutcome outcome, ReadOnlyMemory<byte> payload, long elapsedTicks, string? detail = null)
|
||||
{
|
||||
if (!Enum.IsDefined(outcome))
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(outcome));
|
||||
}
|
||||
|
||||
if (elapsedTicks < 0)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(elapsedTicks));
|
||||
}
|
||||
|
||||
if (outcome == TransportOutcome.Response && payload.IsEmpty)
|
||||
{
|
||||
throw new ArgumentException("A response outcome must contain a payload.", nameof(payload));
|
||||
}
|
||||
|
||||
if (outcome != TransportOutcome.Response && !payload.IsEmpty)
|
||||
{
|
||||
throw new ArgumentException("A non-response outcome cannot contain a response payload.", nameof(payload));
|
||||
}
|
||||
|
||||
Outcome = outcome;
|
||||
_payload = payload.IsEmpty ? null : payload.ToArray();
|
||||
ElapsedTicks = elapsedTicks;
|
||||
Detail = detail;
|
||||
}
|
||||
|
||||
public TransportOutcome Outcome { get; }
|
||||
public ReadOnlyMemory<byte> Payload => _payload ?? ReadOnlyMemory<byte>.Empty;
|
||||
public long ElapsedTicks { get; }
|
||||
public string? Detail { get; }
|
||||
}
|
||||
|
||||
public enum DiagnosticOutcome
|
||||
{
|
||||
PositiveResponse,
|
||||
NegativeResponse,
|
||||
NoResponse,
|
||||
Timeout,
|
||||
Cancelled,
|
||||
ProtocolError
|
||||
}
|
||||
|
||||
public sealed class DiagnosticOperationResult<T>
|
||||
{
|
||||
private DiagnosticOperationResult(
|
||||
DiagnosticOutcome outcome,
|
||||
T? value,
|
||||
string? failureCode,
|
||||
string? error)
|
||||
{
|
||||
Outcome = outcome;
|
||||
Value = value;
|
||||
FailureCode = failureCode;
|
||||
Error = error;
|
||||
}
|
||||
|
||||
public DiagnosticOutcome Outcome { get; }
|
||||
public T? Value { get; }
|
||||
public string? FailureCode { get; }
|
||||
public string? Error { get; }
|
||||
public bool IsSuccess => Outcome == DiagnosticOutcome.PositiveResponse;
|
||||
|
||||
public static DiagnosticOperationResult<T> Success(T value) =>
|
||||
new(DiagnosticOutcome.PositiveResponse, value ?? throw new ArgumentNullException(nameof(value)), null, null);
|
||||
|
||||
public static DiagnosticOperationResult<T> Failure(DiagnosticOutcome outcome, string code, string message)
|
||||
{
|
||||
if (outcome == DiagnosticOutcome.PositiveResponse)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(outcome));
|
||||
}
|
||||
|
||||
return new DiagnosticOperationResult<T>(outcome, default, code, message);
|
||||
}
|
||||
}
|
||||
|
||||
public sealed record ModuleIdentityResult(
|
||||
string ModuleIdentifier,
|
||||
string Address,
|
||||
string Role,
|
||||
string Name,
|
||||
string? HardwareIdentifier,
|
||||
string? SoftwareIdentifier,
|
||||
string? FirmwareIdentifier,
|
||||
string? CalibrationIdentifier);
|
||||
|
||||
public sealed class DiagnosticProbeResult
|
||||
{
|
||||
public DiagnosticProbeResult(string moduleIdentifier, IEnumerable<string> implementedServices)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(moduleIdentifier);
|
||||
ArgumentNullException.ThrowIfNull(implementedServices);
|
||||
ModuleIdentifier = moduleIdentifier;
|
||||
ImplementedServices = Array.AsReadOnly(implementedServices.ToArray());
|
||||
}
|
||||
|
||||
public string ModuleIdentifier { get; }
|
||||
public IReadOnlyList<string> ImplementedServices { get; }
|
||||
}
|
||||
|
||||
public enum DiagnosticIdentityStatus
|
||||
{
|
||||
NotAttempted,
|
||||
Verified,
|
||||
Unavailable
|
||||
}
|
||||
|
||||
public sealed class DiscoveryEntry
|
||||
{
|
||||
public DiscoveryEntry(
|
||||
DiagnosticEndpoint endpoint,
|
||||
DiagnosticOperationResult<DiagnosticProbeResult> probe,
|
||||
DiagnosticOperationResult<ModuleIdentityResult>? identityResult,
|
||||
string? identityNotAttemptedReason = null)
|
||||
{
|
||||
Endpoint = endpoint ?? throw new ArgumentNullException(nameof(endpoint));
|
||||
Probe = probe ?? throw new ArgumentNullException(nameof(probe));
|
||||
if (probe.IsSuccess != (probe.Value is not null))
|
||||
{
|
||||
throw new ArgumentException("Probe result value must match its success outcome.", nameof(probe));
|
||||
}
|
||||
|
||||
if (!probe.IsSuccess && identityResult is not null)
|
||||
{
|
||||
throw new ArgumentException("Identity cannot be attempted when the probe did not succeed.", nameof(identityResult));
|
||||
}
|
||||
|
||||
if (identityResult is not null && !probe.Value!.ImplementedServices.Contains(
|
||||
DiagnosticServices.ReadIdentity,
|
||||
StringComparer.Ordinal))
|
||||
{
|
||||
throw new ArgumentException("Identity cannot be attempted when the probe did not advertise the service.", nameof(identityResult));
|
||||
}
|
||||
|
||||
if (identityResult is not null &&
|
||||
identityResult.IsSuccess != (identityResult.Value is not null))
|
||||
{
|
||||
throw new ArgumentException("Identity result value must match its success outcome.", nameof(identityResult));
|
||||
}
|
||||
|
||||
if (identityResult is null)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(identityNotAttemptedReason);
|
||||
}
|
||||
|
||||
if (identityResult is not null && identityNotAttemptedReason is not null)
|
||||
{
|
||||
throw new ArgumentException("An identity attempt cannot also have a not-attempted reason.", nameof(identityNotAttemptedReason));
|
||||
}
|
||||
|
||||
if (!Enum.IsDefined(probe.Outcome) ||
|
||||
identityResult is not null && !Enum.IsDefined(identityResult.Outcome))
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(probe), "Discovery phases must use defined diagnostic outcomes.");
|
||||
}
|
||||
|
||||
Probe = probe;
|
||||
IdentityResult = identityResult;
|
||||
IdentityNotAttemptedReason = identityNotAttemptedReason;
|
||||
}
|
||||
|
||||
public DiagnosticEndpoint Endpoint { get; }
|
||||
public DiagnosticOperationResult<DiagnosticProbeResult> Probe { get; }
|
||||
public DiagnosticOutcome ProbeOutcome => Probe.Outcome;
|
||||
public string? ProbeError => Probe.Error;
|
||||
public bool ProbeSucceeded => Probe.IsSuccess;
|
||||
public IReadOnlyList<string> ImplementedServices => Probe.Value?.ImplementedServices ?? Array.Empty<string>();
|
||||
public DiagnosticOperationResult<ModuleIdentityResult>? IdentityResult { get; }
|
||||
public ModuleIdentityResult? Identity => IdentityResult?.Value;
|
||||
public DiagnosticIdentityStatus IdentityStatus => IdentityResult switch
|
||||
{
|
||||
null => DiagnosticIdentityStatus.NotAttempted,
|
||||
{ IsSuccess: true } => DiagnosticIdentityStatus.Verified,
|
||||
_ => DiagnosticIdentityStatus.Unavailable
|
||||
};
|
||||
public DiagnosticOutcome? IdentityOutcome => IdentityResult?.Outcome;
|
||||
public string? IdentityError => IdentityResult?.Error ?? IdentityNotAttemptedReason;
|
||||
public string? IdentityNotAttemptedReason { get; }
|
||||
}
|
||||
|
||||
public sealed class DiscoveryResult
|
||||
{
|
||||
public DiscoveryResult(IEnumerable<DiscoveryEntry> endpoints)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(endpoints);
|
||||
Endpoints = Array.AsReadOnly(endpoints.ToArray());
|
||||
}
|
||||
|
||||
public IReadOnlyList<DiscoveryEntry> Endpoints { get; }
|
||||
public IReadOnlyList<DiscoveryEntry> ValidatedProbes =>
|
||||
Array.AsReadOnly(Endpoints.Where(endpoint => endpoint.ProbeSucceeded).ToArray());
|
||||
public IReadOnlyList<ModuleIdentityResult> IdentifiedModules =>
|
||||
Array.AsReadOnly(Endpoints.Where(endpoint => endpoint.Identity is not null).Select(endpoint => endpoint.Identity!).ToArray());
|
||||
public int ExpectedEndpointCount => Endpoints.Count;
|
||||
public int ValidatedProbeCount => ValidatedProbes.Count;
|
||||
public int IdentifiedModuleCount => IdentifiedModules.Count;
|
||||
}
|
||||
|
||||
public sealed record DiagnosticTroubleCode(string Code, string Description, string SourceModuleIdentifier);
|
||||
|
||||
public sealed class TroubleCodeReadResult
|
||||
{
|
||||
public TroubleCodeReadResult(string moduleIdentifier, IEnumerable<DiagnosticTroubleCode> codes)
|
||||
{
|
||||
ModuleIdentifier = moduleIdentifier;
|
||||
Codes = Array.AsReadOnly(codes.ToArray());
|
||||
}
|
||||
|
||||
public string ModuleIdentifier { get; }
|
||||
public IReadOnlyList<DiagnosticTroubleCode> Codes { get; }
|
||||
}
|
||||
|
||||
public sealed record TroubleCodeClearResult(string ModuleIdentifier, int ClearedCount);
|
||||
|
||||
public enum SignalQuality
|
||||
{
|
||||
Good,
|
||||
Uncertain,
|
||||
Unknown
|
||||
}
|
||||
|
||||
public sealed record DiagnosticSignal(
|
||||
string SignalIdentifier,
|
||||
string ModuleIdentifier,
|
||||
JsonElement Value,
|
||||
string Unit,
|
||||
SignalQuality Quality,
|
||||
long LogicalTimeTicks,
|
||||
string Origin);
|
||||
|
||||
public sealed class SignalSnapshot
|
||||
{
|
||||
public SignalSnapshot(string moduleIdentifier, IEnumerable<DiagnosticSignal> signals)
|
||||
{
|
||||
ModuleIdentifier = moduleIdentifier;
|
||||
Signals = Array.AsReadOnly(signals.ToArray());
|
||||
}
|
||||
|
||||
public string ModuleIdentifier { get; }
|
||||
public IReadOnlyList<DiagnosticSignal> Signals { get; }
|
||||
}
|
||||
|
||||
public sealed class DiagnosticTraceEntry
|
||||
{
|
||||
private readonly byte[] _requestPayload;
|
||||
private readonly byte[]? _responsePayload;
|
||||
|
||||
public DiagnosticTraceEntry(
|
||||
DiagnosticSessionIdentity session,
|
||||
string moduleIdentifier,
|
||||
string address,
|
||||
string correlationIdentifier,
|
||||
string service,
|
||||
long startLogicalTicks,
|
||||
long endLogicalTicks,
|
||||
ReadOnlyMemory<byte> requestPayload,
|
||||
ReadOnlyMemory<byte> responsePayload,
|
||||
DiagnosticOutcome outcome,
|
||||
string? decodedSummary,
|
||||
string? error)
|
||||
{
|
||||
Session = session;
|
||||
ModuleIdentifier = moduleIdentifier;
|
||||
Address = address;
|
||||
CorrelationIdentifier = correlationIdentifier;
|
||||
Service = service;
|
||||
StartLogicalTicks = startLogicalTicks;
|
||||
EndLogicalTicks = endLogicalTicks;
|
||||
_requestPayload = requestPayload.ToArray();
|
||||
_responsePayload = responsePayload.IsEmpty ? null : responsePayload.ToArray();
|
||||
Outcome = outcome;
|
||||
DecodedSummary = decodedSummary;
|
||||
Error = error;
|
||||
}
|
||||
|
||||
public DiagnosticSessionIdentity Session { get; }
|
||||
public string ModuleIdentifier { get; }
|
||||
public string Address { get; }
|
||||
public string CorrelationIdentifier { get; }
|
||||
public string Service { get; }
|
||||
public long StartLogicalTicks { get; }
|
||||
public long EndLogicalTicks { get; }
|
||||
public ReadOnlyMemory<byte> RequestPayload => _requestPayload.ToArray();
|
||||
public ReadOnlyMemory<byte>? ResponsePayload =>
|
||||
_responsePayload is null
|
||||
? (ReadOnlyMemory<byte>?)null
|
||||
: new ReadOnlyMemory<byte>(_responsePayload.ToArray());
|
||||
public DiagnosticOutcome Outcome { get; }
|
||||
public string? DecodedSummary { get; }
|
||||
public string? Error { get; }
|
||||
}
|
||||
|
||||
public sealed class DiagnosticTraceSnapshot
|
||||
{
|
||||
public DiagnosticTraceSnapshot(IEnumerable<DiagnosticTraceEntry> entries, long droppedRecordCount)
|
||||
{
|
||||
Entries = new ReadOnlyCollection<DiagnosticTraceEntry>(entries.ToArray());
|
||||
DroppedRecordCount = droppedRecordCount;
|
||||
}
|
||||
|
||||
public IReadOnlyList<DiagnosticTraceEntry> Entries { get; }
|
||||
public long DroppedRecordCount { get; }
|
||||
}
|
||||
|
||||
public sealed class DiagnosticTraceBuffer
|
||||
{
|
||||
private readonly object _gate = new();
|
||||
private readonly Queue<DiagnosticTraceEntry> _entries = new();
|
||||
|
||||
public DiagnosticTraceBuffer(int capacity)
|
||||
{
|
||||
if (capacity <= 0)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(capacity));
|
||||
}
|
||||
|
||||
Capacity = capacity;
|
||||
}
|
||||
|
||||
public int Capacity { get; }
|
||||
public long DroppedRecordCount { get; private set; }
|
||||
|
||||
public void Add(DiagnosticTraceEntry entry)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(entry);
|
||||
lock (_gate)
|
||||
{
|
||||
if (_entries.Count == Capacity)
|
||||
{
|
||||
_entries.Dequeue();
|
||||
DroppedRecordCount++;
|
||||
}
|
||||
|
||||
_entries.Enqueue(entry);
|
||||
}
|
||||
}
|
||||
|
||||
public DiagnosticTraceSnapshot Snapshot()
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
return new DiagnosticTraceSnapshot(_entries, DroppedRecordCount);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public interface IDiagnosticLogicalClock
|
||||
{
|
||||
long Ticks { get; }
|
||||
void AdvanceBy(long ticks);
|
||||
}
|
||||
|
||||
public sealed class DiagnosticLogicalClock : IDiagnosticLogicalClock
|
||||
{
|
||||
private long _ticks;
|
||||
|
||||
public long Ticks => Interlocked.Read(ref _ticks);
|
||||
|
||||
public void AdvanceBy(long ticks)
|
||||
{
|
||||
if (ticks < 0)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(ticks));
|
||||
}
|
||||
|
||||
Interlocked.Add(ref _ticks, ticks);
|
||||
}
|
||||
}
|
||||
|
||||
public static class DiagnosticServices
|
||||
{
|
||||
public const string Probe = "probe";
|
||||
public const string ReadIdentity = "read.identity";
|
||||
public const string ReadTroubleCodes = "read.dtcs";
|
||||
public const string ClearTroubleCodes = "clear.dtcs";
|
||||
public const string ReadSignals = "read.signals";
|
||||
}
|
||||
|
||||
public interface IDiagnosticProtocolClient
|
||||
{
|
||||
DiagnosticSessionIdentity Session { get; }
|
||||
IReadOnlyList<DiagnosticEndpoint> ExpectedEndpoints { get; }
|
||||
DiagnosticTraceSnapshot Trace { get; }
|
||||
Task<DiscoveryResult> DiscoverAsync(CancellationToken cancellationToken = default);
|
||||
Task<DiagnosticOperationResult<ModuleIdentityResult>> ReadIdentityAsync(DiagnosticEndpoint endpoint, CancellationToken cancellationToken = default);
|
||||
Task<DiagnosticOperationResult<TroubleCodeReadResult>> ReadTroubleCodesAsync(DiagnosticEndpoint endpoint, CancellationToken cancellationToken = default);
|
||||
Task<DiagnosticOperationResult<TroubleCodeClearResult>> ClearTroubleCodesAsync(DiagnosticEndpoint endpoint, CancellationToken cancellationToken = default);
|
||||
Task<DiagnosticOperationResult<SignalSnapshot>> ReadSignalsAsync(DiagnosticEndpoint endpoint, CancellationToken cancellationToken = default);
|
||||
}
|
||||
|
|
@ -0,0 +1,626 @@
|
|||
using System.Text.Json;
|
||||
using AutoForge.Core.Vehicles;
|
||||
|
||||
namespace AutoForge.Diagnostics;
|
||||
|
||||
public sealed class SyntheticDiagnosticProtocolClient : IDiagnosticProtocolClient
|
||||
{
|
||||
private const long DefaultTimeoutTicks = 5;
|
||||
private readonly VehicleProfile _profile;
|
||||
private readonly IDiagnosticTransport _transport;
|
||||
private readonly IDiagnosticLogicalClock _clock;
|
||||
private readonly DiagnosticTraceBuffer _trace;
|
||||
private readonly SemaphoreSlim _exchangeGate = new(1, 1);
|
||||
private long _correlationSequence;
|
||||
|
||||
public SyntheticDiagnosticProtocolClient(
|
||||
VehicleProfile profile,
|
||||
DiagnosticSessionIdentity session,
|
||||
IDiagnosticTransport transport,
|
||||
IDiagnosticLogicalClock clock,
|
||||
int traceCapacity = 200)
|
||||
{
|
||||
_profile = profile ?? throw new ArgumentNullException(nameof(profile));
|
||||
Session = session ?? throw new ArgumentNullException(nameof(session));
|
||||
_transport = transport ?? throw new ArgumentNullException(nameof(transport));
|
||||
_clock = clock ?? throw new ArgumentNullException(nameof(clock));
|
||||
_trace = new DiagnosticTraceBuffer(traceCapacity);
|
||||
ExpectedEndpoints = Array.AsReadOnly(transport.ExpectedEndpoints.ToArray());
|
||||
}
|
||||
|
||||
public DiagnosticSessionIdentity Session { get; }
|
||||
public IReadOnlyList<DiagnosticEndpoint> ExpectedEndpoints { get; }
|
||||
public DiagnosticTraceSnapshot Trace => _trace.Snapshot();
|
||||
|
||||
public async Task<DiscoveryResult> DiscoverAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
var results = new List<DiscoveryEntry>(ExpectedEndpoints.Count);
|
||||
foreach (var endpoint in ExpectedEndpoints)
|
||||
{
|
||||
var probe = await ExchangeAsync(
|
||||
endpoint,
|
||||
DiagnosticServices.Probe,
|
||||
(data, _) =>
|
||||
{
|
||||
EnsureProperties(data, "moduleIdentifier", "implementedServices");
|
||||
var moduleIdentifier = RequiredString(data, "moduleIdentifier");
|
||||
ValidateModuleIdentifier(endpoint, moduleIdentifier);
|
||||
var services = RequiredArray(data, "implementedServices")
|
||||
.EnumerateArray()
|
||||
.Select(item => item.ValueKind == JsonValueKind.String
|
||||
? ValidateService(RequiredStringValue(item, "Implemented service"))
|
||||
: throw new DiagnosticProtocolException("MALFORMED_RESPONSE", "Implemented services must be strings."))
|
||||
.ToArray();
|
||||
if (services.Length == 0 ||
|
||||
services.Distinct(StringComparer.Ordinal).Count() != services.Length ||
|
||||
!services.Contains(DiagnosticServices.Probe, StringComparer.Ordinal))
|
||||
{
|
||||
throw new DiagnosticProtocolException(
|
||||
"INVALID_RESPONSE",
|
||||
"Probe services must be unique and include the probe service.");
|
||||
}
|
||||
|
||||
return new DiagnosticProbeResult(moduleIdentifier, services);
|
||||
},
|
||||
cancellationToken);
|
||||
if (!probe.IsSuccess)
|
||||
{
|
||||
results.Add(new DiscoveryEntry(
|
||||
endpoint,
|
||||
probe,
|
||||
null,
|
||||
$"Identity read was not attempted because probe failed ({probe.Outcome})."));
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!probe.Value!.ImplementedServices.Contains(DiagnosticServices.ReadIdentity, StringComparer.Ordinal))
|
||||
{
|
||||
results.Add(new DiscoveryEntry(
|
||||
endpoint,
|
||||
probe,
|
||||
null,
|
||||
$"Identity read was not attempted because '{DiagnosticServices.ReadIdentity}' was not advertised by the validated probe."));
|
||||
continue;
|
||||
}
|
||||
|
||||
var identity = await ReadIdentityAsync(endpoint, cancellationToken);
|
||||
results.Add(new DiscoveryEntry(
|
||||
endpoint,
|
||||
probe,
|
||||
identity));
|
||||
}
|
||||
|
||||
return new DiscoveryResult(results);
|
||||
}
|
||||
|
||||
public Task<DiagnosticOperationResult<ModuleIdentityResult>> ReadIdentityAsync(
|
||||
DiagnosticEndpoint endpoint,
|
||||
CancellationToken cancellationToken = default) =>
|
||||
ExchangeAsync(
|
||||
endpoint,
|
||||
DiagnosticServices.ReadIdentity,
|
||||
(data, _) =>
|
||||
{
|
||||
EnsureProperties(
|
||||
data,
|
||||
"moduleIdentifier",
|
||||
"role",
|
||||
"name",
|
||||
"hardwareIdentifier",
|
||||
"softwareIdentifier",
|
||||
"firmwareIdentifier",
|
||||
"calibrationIdentifier");
|
||||
var identity = new ModuleIdentityResult(
|
||||
RequiredString(data, "moduleIdentifier"),
|
||||
endpoint.Address,
|
||||
RequiredString(data, "role"),
|
||||
RequiredString(data, "name"),
|
||||
NullableString(data, "hardwareIdentifier"),
|
||||
NullableString(data, "softwareIdentifier"),
|
||||
NullableString(data, "firmwareIdentifier"),
|
||||
NullableString(data, "calibrationIdentifier"));
|
||||
ValidateIdentity(endpoint, identity);
|
||||
return identity;
|
||||
},
|
||||
cancellationToken);
|
||||
|
||||
public Task<DiagnosticOperationResult<TroubleCodeReadResult>> ReadTroubleCodesAsync(
|
||||
DiagnosticEndpoint endpoint,
|
||||
CancellationToken cancellationToken = default) =>
|
||||
ExchangeAsync(
|
||||
endpoint,
|
||||
DiagnosticServices.ReadTroubleCodes,
|
||||
(data, _) =>
|
||||
{
|
||||
EnsureProperties(data, "moduleIdentifier", "codes");
|
||||
var moduleIdentifier = RequiredString(data, "moduleIdentifier");
|
||||
ValidateModuleIdentifier(endpoint, moduleIdentifier);
|
||||
var codes = RequiredArray(data, "codes")
|
||||
.EnumerateArray()
|
||||
.Select(item =>
|
||||
{
|
||||
EnsureProperties(item, "code", "description");
|
||||
return new DiagnosticTroubleCode(
|
||||
RequiredString(item, "code"),
|
||||
RequiredString(item, "description"),
|
||||
moduleIdentifier);
|
||||
})
|
||||
.ToArray();
|
||||
if (codes.Select(code => code.Code).Distinct(StringComparer.OrdinalIgnoreCase).Count() != codes.Length)
|
||||
{
|
||||
throw new DiagnosticProtocolException("INVALID_RESPONSE", "DTC codes must be unique within a module response.");
|
||||
}
|
||||
|
||||
return new TroubleCodeReadResult(moduleIdentifier, codes);
|
||||
},
|
||||
cancellationToken);
|
||||
|
||||
public Task<DiagnosticOperationResult<TroubleCodeClearResult>> ClearTroubleCodesAsync(
|
||||
DiagnosticEndpoint endpoint,
|
||||
CancellationToken cancellationToken = default) =>
|
||||
ExchangeAsync(
|
||||
endpoint,
|
||||
DiagnosticServices.ClearTroubleCodes,
|
||||
(data, _) =>
|
||||
{
|
||||
EnsureProperties(data, "moduleIdentifier", "clearedCount");
|
||||
var moduleIdentifier = RequiredString(data, "moduleIdentifier");
|
||||
ValidateModuleIdentifier(endpoint, moduleIdentifier);
|
||||
var count = RequiredInt32(data, "clearedCount");
|
||||
if (count < 0)
|
||||
{
|
||||
throw new DiagnosticProtocolException("INVALID_RESPONSE", "Cleared count cannot be negative.");
|
||||
}
|
||||
|
||||
return new TroubleCodeClearResult(moduleIdentifier, count);
|
||||
},
|
||||
cancellationToken);
|
||||
|
||||
public Task<DiagnosticOperationResult<SignalSnapshot>> ReadSignalsAsync(
|
||||
DiagnosticEndpoint endpoint,
|
||||
CancellationToken cancellationToken = default) =>
|
||||
ExchangeAsync(
|
||||
endpoint,
|
||||
DiagnosticServices.ReadSignals,
|
||||
(data, request) =>
|
||||
{
|
||||
EnsureProperties(data, "moduleIdentifier", "logicalTimeTicks", "origin", "signals");
|
||||
var moduleIdentifier = RequiredString(data, "moduleIdentifier");
|
||||
ValidateModuleIdentifier(endpoint, moduleIdentifier);
|
||||
var logicalTime = RequiredInt64(data, "logicalTimeTicks");
|
||||
if (logicalTime != request.LogicalTimeTicks)
|
||||
{
|
||||
throw new DiagnosticProtocolException(
|
||||
"INVALID_RESPONSE",
|
||||
"Static signal snapshot time must equal the request logical start tick.");
|
||||
}
|
||||
|
||||
var origin = RequiredString(data, "origin");
|
||||
if (!StringComparer.Ordinal.Equals(origin, "SYNTHETIC_STATIC"))
|
||||
{
|
||||
throw new DiagnosticProtocolException("INVALID_RESPONSE", "Signal origin must be SYNTHETIC_STATIC.");
|
||||
}
|
||||
|
||||
var signals = RequiredArray(data, "signals").EnumerateArray().Select(item =>
|
||||
{
|
||||
EnsureProperties(item, "signalIdentifier", "value", "unit", "quality");
|
||||
var qualityText = RequiredString(item, "quality");
|
||||
if (!Enum.TryParse<SignalQuality>(qualityText, ignoreCase: false, out var quality) ||
|
||||
!Enum.IsDefined(quality))
|
||||
{
|
||||
throw new DiagnosticProtocolException("INVALID_RESPONSE", $"Signal quality '{qualityText}' is invalid.");
|
||||
}
|
||||
|
||||
var value = Required(item, "value");
|
||||
return new DiagnosticSignal(
|
||||
RequiredString(item, "signalIdentifier"),
|
||||
moduleIdentifier,
|
||||
value.Clone(),
|
||||
RequiredString(item, "unit"),
|
||||
quality,
|
||||
logicalTime,
|
||||
origin);
|
||||
}).ToArray();
|
||||
if (signals.Select(signal => signal.SignalIdentifier)
|
||||
.Distinct(StringComparer.OrdinalIgnoreCase).Count() != signals.Length)
|
||||
{
|
||||
throw new DiagnosticProtocolException(
|
||||
"INVALID_RESPONSE",
|
||||
"Signal identifiers must be unique within a module snapshot.");
|
||||
}
|
||||
|
||||
return new SignalSnapshot(moduleIdentifier, signals);
|
||||
},
|
||||
cancellationToken);
|
||||
|
||||
private async Task<DiagnosticOperationResult<T>> ExchangeAsync<T>(
|
||||
DiagnosticEndpoint endpoint,
|
||||
string service,
|
||||
Func<JsonElement, SyntheticDiagnosticRequest, T> decode,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(endpoint);
|
||||
ArgumentNullException.ThrowIfNull(decode);
|
||||
if (!ExpectedEndpoints.Any(candidate =>
|
||||
Same(candidate.ModuleIdentifier, endpoint.ModuleIdentifier) &&
|
||||
Same(candidate.Address, endpoint.Address)))
|
||||
{
|
||||
return DiagnosticOperationResult<T>.Failure(
|
||||
DiagnosticOutcome.ProtocolError,
|
||||
"UNEXPECTED_ENDPOINT",
|
||||
"The requested endpoint is not part of this session.");
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
await _exchangeGate.WaitAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
return DiagnosticOperationResult<T>.Failure(
|
||||
DiagnosticOutcome.Cancelled,
|
||||
"CANCELLED",
|
||||
"Operation was cancelled while waiting for the session transport.");
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
return await ExchangeSerializedAsync(endpoint, service, decode, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_exchangeGate.Release();
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<DiagnosticOperationResult<T>> ExchangeSerializedAsync<T>(
|
||||
DiagnosticEndpoint endpoint,
|
||||
string service,
|
||||
Func<JsonElement, SyntheticDiagnosticRequest, T> decode,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var sequence = Interlocked.Increment(ref _correlationSequence);
|
||||
var correlation = $"{Session.SessionIdentifier}-{sequence:D6}";
|
||||
var startTicks = _clock.Ticks;
|
||||
var request = new SyntheticDiagnosticRequest(
|
||||
Session.SessionIdentifier,
|
||||
Session.ProfileIdentifier,
|
||||
Session.ProfileRevision,
|
||||
Session.ConfigurationIdentifier,
|
||||
correlation,
|
||||
endpoint.Address,
|
||||
service,
|
||||
startTicks,
|
||||
DefaultTimeoutTicks);
|
||||
var requestPayload = SyntheticProtocolV1.EncodeRequest(request);
|
||||
TransportReply transportReply;
|
||||
|
||||
try
|
||||
{
|
||||
transportReply = await _transport.SendAsync(requestPayload, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
var endTicks = _clock.Ticks;
|
||||
AddTrace(endpoint, correlation, service, startTicks, endTicks, requestPayload, ReadOnlyMemory<byte>.Empty, DiagnosticOutcome.Cancelled, null, "Operation was cancelled.");
|
||||
return DiagnosticOperationResult<T>.Failure(DiagnosticOutcome.Cancelled, "CANCELLED", "Operation was cancelled.");
|
||||
}
|
||||
|
||||
_clock.AdvanceBy(transportReply.ElapsedTicks);
|
||||
var responsePayload = transportReply.Payload;
|
||||
if (transportReply.Outcome != TransportOutcome.Response)
|
||||
{
|
||||
var outcome = transportReply.Outcome switch
|
||||
{
|
||||
TransportOutcome.NoResponse => DiagnosticOutcome.NoResponse,
|
||||
TransportOutcome.Timeout => DiagnosticOutcome.Timeout,
|
||||
TransportOutcome.Cancelled => DiagnosticOutcome.Cancelled,
|
||||
_ => DiagnosticOutcome.ProtocolError
|
||||
};
|
||||
var code = transportReply.Outcome.ToString().ToUpperInvariant();
|
||||
var error = transportReply.Detail ?? $"Transport completed with {outcome}.";
|
||||
AddTrace(endpoint, correlation, service, startTicks, _clock.Ticks, requestPayload, ReadOnlyMemory<byte>.Empty, outcome, null, error);
|
||||
return DiagnosticOperationResult<T>.Failure(outcome, code, error);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
using var document = JsonDocument.Parse(responsePayload);
|
||||
var root = document.RootElement;
|
||||
ValidateResponseEnvelope(root, request);
|
||||
var success = RequiredBoolean(root, "success");
|
||||
if (!success)
|
||||
{
|
||||
var errorCode = RequiredString(root, "errorCode");
|
||||
var message = RequiredString(root, "error");
|
||||
AddTrace(endpoint, correlation, service, startTicks, _clock.Ticks, requestPayload, responsePayload, DiagnosticOutcome.NegativeResponse, errorCode, message);
|
||||
return DiagnosticOperationResult<T>.Failure(DiagnosticOutcome.NegativeResponse, errorCode, message);
|
||||
}
|
||||
|
||||
var data = Required(root, "data");
|
||||
var value = decode(data, request);
|
||||
AddTrace(endpoint, correlation, service, startTicks, _clock.Ticks, requestPayload, responsePayload, DiagnosticOutcome.PositiveResponse, Summarize(value), null);
|
||||
return DiagnosticOperationResult<T>.Success(value);
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
const string error = "Response is not valid synthetic protocol v1 JSON.";
|
||||
AddTrace(endpoint, correlation, service, startTicks, _clock.Ticks, requestPayload, responsePayload, DiagnosticOutcome.ProtocolError, null, error);
|
||||
return DiagnosticOperationResult<T>.Failure(DiagnosticOutcome.ProtocolError, "MALFORMED_RESPONSE", error);
|
||||
}
|
||||
catch (DiagnosticProtocolException exception)
|
||||
{
|
||||
AddTrace(endpoint, correlation, service, startTicks, _clock.Ticks, requestPayload, responsePayload, DiagnosticOutcome.ProtocolError, null, exception.Message);
|
||||
return DiagnosticOperationResult<T>.Failure(DiagnosticOutcome.ProtocolError, exception.FailureCode, exception.Message);
|
||||
}
|
||||
}
|
||||
|
||||
private void ValidateResponseEnvelope(JsonElement root, SyntheticDiagnosticRequest request)
|
||||
{
|
||||
if (root.ValueKind != JsonValueKind.Object || !SyntheticProtocolV1.HasUniqueProperties(root))
|
||||
{
|
||||
throw new DiagnosticProtocolException(
|
||||
"MALFORMED_RESPONSE",
|
||||
"Response objects must be valid JSON objects without duplicate properties.");
|
||||
}
|
||||
|
||||
EnsureProperties(
|
||||
root,
|
||||
"version",
|
||||
"sessionIdentifier",
|
||||
"configurationIdentifier",
|
||||
"correlationIdentifier",
|
||||
"targetAddress",
|
||||
"service",
|
||||
"success",
|
||||
"errorCode",
|
||||
"error",
|
||||
"data");
|
||||
if (RequiredInt32(root, "version") != 1)
|
||||
{
|
||||
throw new DiagnosticProtocolException("UNSUPPORTED_VERSION", "Response protocol version is unsupported.");
|
||||
}
|
||||
|
||||
if (!Same(RequiredString(root, "sessionIdentifier"), Session.SessionIdentifier) ||
|
||||
!Same(RequiredString(root, "configurationIdentifier"), Session.ConfigurationIdentifier) ||
|
||||
!Same(RequiredString(root, "correlationIdentifier"), request.CorrelationIdentifier) ||
|
||||
!Same(RequiredString(root, "targetAddress"), request.TargetAddress) ||
|
||||
!Same(RequiredString(root, "service"), request.Service))
|
||||
{
|
||||
throw new DiagnosticProtocolException(
|
||||
"CORRELATION_MISMATCH",
|
||||
"Response session, correlation, address or service did not match the request.");
|
||||
}
|
||||
|
||||
if (RequiredBoolean(root, "success"))
|
||||
{
|
||||
if (Required(root, "errorCode").ValueKind != JsonValueKind.Null ||
|
||||
Required(root, "error").ValueKind != JsonValueKind.Null ||
|
||||
Required(root, "data").ValueKind != JsonValueKind.Object)
|
||||
{
|
||||
throw new DiagnosticProtocolException(
|
||||
"INVALID_RESPONSE",
|
||||
"Positive responses require null error fields and an object data payload.");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
_ = RequiredString(root, "errorCode");
|
||||
_ = RequiredString(root, "error");
|
||||
if (Required(root, "data").ValueKind != JsonValueKind.Null)
|
||||
{
|
||||
throw new DiagnosticProtocolException(
|
||||
"INVALID_RESPONSE",
|
||||
"Negative responses require a typed error and null data.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void ValidateIdentity(DiagnosticEndpoint endpoint, ModuleIdentityResult identity)
|
||||
{
|
||||
ValidateModuleIdentifier(endpoint, identity.ModuleIdentifier);
|
||||
var expected = _profile.GetModule(endpoint.ModuleIdentifier);
|
||||
if (!Same(expected.Role, identity.Role) ||
|
||||
!Same(expected.Name, identity.Name) ||
|
||||
!SameOptional(expected.HardwareIdentifier, identity.HardwareIdentifier) ||
|
||||
!SameOptional(expected.SoftwareIdentifier, identity.SoftwareIdentifier) ||
|
||||
!SameOptional(expected.FirmwareIdentifier, identity.FirmwareIdentifier) ||
|
||||
!SameOptional(expected.CalibrationIdentifier, identity.CalibrationIdentifier))
|
||||
{
|
||||
throw new DiagnosticProtocolException(
|
||||
"IDENTITY_MISMATCH",
|
||||
$"Response identity for module '{endpoint.ModuleIdentifier}' does not match the selected profile snapshot.");
|
||||
}
|
||||
}
|
||||
|
||||
private static void ValidateModuleIdentifier(DiagnosticEndpoint endpoint, string moduleIdentifier)
|
||||
{
|
||||
if (!Same(endpoint.ModuleIdentifier, moduleIdentifier))
|
||||
{
|
||||
throw new DiagnosticProtocolException(
|
||||
"IDENTITY_MISMATCH",
|
||||
$"Response module '{moduleIdentifier}' does not match expected module '{endpoint.ModuleIdentifier}'.");
|
||||
}
|
||||
}
|
||||
|
||||
private void AddTrace(
|
||||
DiagnosticEndpoint endpoint,
|
||||
string correlation,
|
||||
string service,
|
||||
long startTicks,
|
||||
long endTicks,
|
||||
ReadOnlyMemory<byte> request,
|
||||
ReadOnlyMemory<byte> response,
|
||||
DiagnosticOutcome outcome,
|
||||
string? summary,
|
||||
string? error) =>
|
||||
_trace.Add(new DiagnosticTraceEntry(
|
||||
Session,
|
||||
endpoint.ModuleIdentifier,
|
||||
endpoint.Address,
|
||||
correlation,
|
||||
service,
|
||||
startTicks,
|
||||
endTicks,
|
||||
request,
|
||||
response,
|
||||
outcome,
|
||||
summary,
|
||||
error));
|
||||
|
||||
private static string Summarize<T>(T value) => value switch
|
||||
{
|
||||
string text => text,
|
||||
DiagnosticProbeResult probe => $"Probe responded with {probe.ImplementedServices.Count} service(s)",
|
||||
TroubleCodeReadResult dtcs => $"{dtcs.Codes.Count} DTC(s)",
|
||||
TroubleCodeClearResult cleared => $"{cleared.ClearedCount} virtual DTC(s) cleared",
|
||||
SignalSnapshot signals => $"{signals.Signals.Count} static signal(s)",
|
||||
ModuleIdentityResult identity => $"Identity for {identity.ModuleIdentifier}",
|
||||
_ => typeof(T).Name
|
||||
};
|
||||
|
||||
private static JsonElement Required(JsonElement element, string property)
|
||||
{
|
||||
if (element.ValueKind != JsonValueKind.Object ||
|
||||
!element.TryGetProperty(property, out var value))
|
||||
{
|
||||
throw new DiagnosticProtocolException("MALFORMED_RESPONSE", $"Required response property '{property}' is missing.");
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
private static void EnsureProperties(JsonElement element, params string[] requiredProperties)
|
||||
{
|
||||
if (element.ValueKind != JsonValueKind.Object)
|
||||
{
|
||||
throw new DiagnosticProtocolException("MALFORMED_RESPONSE", "Service payloads must be JSON objects.");
|
||||
}
|
||||
|
||||
var allowed = new HashSet<string>(requiredProperties, StringComparer.Ordinal);
|
||||
foreach (var property in element.EnumerateObject())
|
||||
{
|
||||
if (!allowed.Remove(property.Name))
|
||||
{
|
||||
throw new DiagnosticProtocolException(
|
||||
"MALFORMED_RESPONSE",
|
||||
$"Response contains an unknown property '{property.Name}'.");
|
||||
}
|
||||
}
|
||||
|
||||
if (allowed.Count != 0)
|
||||
{
|
||||
throw new DiagnosticProtocolException(
|
||||
"MALFORMED_RESPONSE",
|
||||
$"Response is missing required property '{allowed.First()}'.");
|
||||
}
|
||||
}
|
||||
|
||||
private static string RequiredStringValue(JsonElement value, string description)
|
||||
{
|
||||
if (value.ValueKind != JsonValueKind.String || value.GetString() is not { } text)
|
||||
{
|
||||
throw new DiagnosticProtocolException("MALFORMED_RESPONSE", $"{description} must be a string.");
|
||||
}
|
||||
|
||||
return ValidateText(text, description);
|
||||
}
|
||||
|
||||
private static string RequiredString(JsonElement element, string property)
|
||||
{
|
||||
return RequiredStringValue(Required(element, property), $"Response property '{property}'");
|
||||
}
|
||||
|
||||
private static string ValidateText(string text, string description)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(text) || !StringComparer.Ordinal.Equals(text, text.Trim()))
|
||||
{
|
||||
throw new DiagnosticProtocolException(
|
||||
"INVALID_RESPONSE",
|
||||
$"{description} must be nonblank text without surrounding whitespace.");
|
||||
}
|
||||
|
||||
return text;
|
||||
}
|
||||
|
||||
private static string ValidateService(string service)
|
||||
{
|
||||
if (service is not (DiagnosticServices.Probe or
|
||||
DiagnosticServices.ReadIdentity or
|
||||
DiagnosticServices.ReadTroubleCodes or
|
||||
DiagnosticServices.ClearTroubleCodes or
|
||||
DiagnosticServices.ReadSignals))
|
||||
{
|
||||
throw new DiagnosticProtocolException("INVALID_RESPONSE", $"Service '{service}' is not defined by protocol v1.");
|
||||
}
|
||||
|
||||
return service;
|
||||
}
|
||||
|
||||
private static string? NullableString(JsonElement element, string property)
|
||||
{
|
||||
var value = Required(element, property);
|
||||
if (value.ValueKind == JsonValueKind.Null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
if (value.ValueKind != JsonValueKind.String)
|
||||
{
|
||||
throw new DiagnosticProtocolException("MALFORMED_RESPONSE", $"Response property '{property}' must be a string or null.");
|
||||
}
|
||||
|
||||
return ValidateText(value.GetString()!, $"Response property '{property}'");
|
||||
}
|
||||
|
||||
private static JsonElement RequiredArray(JsonElement element, string property)
|
||||
{
|
||||
var value = Required(element, property);
|
||||
if (value.ValueKind != JsonValueKind.Array)
|
||||
{
|
||||
throw new DiagnosticProtocolException("MALFORMED_RESPONSE", $"Response property '{property}' must be an array.");
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
private static bool RequiredBoolean(JsonElement element, string property)
|
||||
{
|
||||
var value = Required(element, property);
|
||||
if (value.ValueKind is not (JsonValueKind.True or JsonValueKind.False))
|
||||
{
|
||||
throw new DiagnosticProtocolException("MALFORMED_RESPONSE", $"Response property '{property}' must be a boolean.");
|
||||
}
|
||||
|
||||
return value.GetBoolean();
|
||||
}
|
||||
|
||||
private static int RequiredInt32(JsonElement element, string property)
|
||||
{
|
||||
var value = Required(element, property);
|
||||
if (value.ValueKind != JsonValueKind.Number || !value.TryGetInt32(out var result))
|
||||
{
|
||||
throw new DiagnosticProtocolException("MALFORMED_RESPONSE", $"Response property '{property}' must be a 32-bit integer.");
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private static long RequiredInt64(JsonElement element, string property)
|
||||
{
|
||||
var value = Required(element, property);
|
||||
if (value.ValueKind != JsonValueKind.Number || !value.TryGetInt64(out var result))
|
||||
{
|
||||
throw new DiagnosticProtocolException("MALFORMED_RESPONSE", $"Response property '{property}' must be a 64-bit integer.");
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private static bool Same(string left, string right) =>
|
||||
StringComparer.OrdinalIgnoreCase.Equals(left, right);
|
||||
|
||||
private static bool SameOptional(string? expected, string? actual) =>
|
||||
expected is null ? actual is null : actual is not null && Same(expected, actual);
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,185 @@
|
|||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace AutoForge.Diagnostics;
|
||||
|
||||
public sealed class SyntheticDiagnosticRequest
|
||||
{
|
||||
public SyntheticDiagnosticRequest(
|
||||
string sessionIdentifier,
|
||||
string profileIdentifier,
|
||||
int profileRevision,
|
||||
string configurationIdentifier,
|
||||
string correlationIdentifier,
|
||||
string targetAddress,
|
||||
string service,
|
||||
long logicalTimeTicks,
|
||||
long timeoutTicks)
|
||||
{
|
||||
SessionIdentifier = Require(sessionIdentifier, nameof(sessionIdentifier));
|
||||
ProfileIdentifier = Require(profileIdentifier, nameof(profileIdentifier));
|
||||
if (profileRevision <= 0)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(profileRevision));
|
||||
}
|
||||
|
||||
ProfileRevision = profileRevision;
|
||||
ConfigurationIdentifier = Require(configurationIdentifier, nameof(configurationIdentifier));
|
||||
CorrelationIdentifier = Require(correlationIdentifier, nameof(correlationIdentifier));
|
||||
_ = new DiagnosticEndpoint("protocol.target", targetAddress);
|
||||
TargetAddress = targetAddress;
|
||||
Service = Require(service, nameof(service));
|
||||
if (logicalTimeTicks < 0)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(logicalTimeTicks));
|
||||
}
|
||||
if (timeoutTicks <= 0)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(timeoutTicks));
|
||||
}
|
||||
|
||||
LogicalTimeTicks = logicalTimeTicks;
|
||||
TimeoutTicks = timeoutTicks;
|
||||
}
|
||||
|
||||
public int Version { get; init; } = 1;
|
||||
public string SessionIdentifier { get; }
|
||||
public string ProfileIdentifier { get; }
|
||||
public int ProfileRevision { get; }
|
||||
public string ConfigurationIdentifier { get; }
|
||||
public string CorrelationIdentifier { get; }
|
||||
public string TargetAddress { get; }
|
||||
public string Service { get; }
|
||||
public long LogicalTimeTicks { get; }
|
||||
public long TimeoutTicks { get; }
|
||||
|
||||
private static string Require(string value, string parameterName)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(value, parameterName);
|
||||
if (!StringComparer.Ordinal.Equals(value, value.Trim()))
|
||||
{
|
||||
throw new ArgumentException("Protocol text values must not contain surrounding whitespace.", parameterName);
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
public static class SyntheticProtocolV1
|
||||
{
|
||||
private static readonly string[] RequiredRequestProperties =
|
||||
[
|
||||
"version",
|
||||
"sessionIdentifier",
|
||||
"profileIdentifier",
|
||||
"profileRevision",
|
||||
"configurationIdentifier",
|
||||
"correlationIdentifier",
|
||||
"targetAddress",
|
||||
"service",
|
||||
"logicalTimeTicks",
|
||||
"timeoutTicks"
|
||||
];
|
||||
|
||||
private static readonly JsonSerializerOptions JsonOptions = new()
|
||||
{
|
||||
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
|
||||
UnmappedMemberHandling = JsonUnmappedMemberHandling.Disallow
|
||||
};
|
||||
|
||||
public static byte[] EncodeRequest(SyntheticDiagnosticRequest request)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(request);
|
||||
return JsonSerializer.SerializeToUtf8Bytes(request, JsonOptions);
|
||||
}
|
||||
|
||||
public static bool TryDecodeRequest(ReadOnlyMemory<byte> payload, out SyntheticDiagnosticRequest? request)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var document = JsonDocument.Parse(payload);
|
||||
var root = document.RootElement;
|
||||
if (root.ValueKind != JsonValueKind.Object ||
|
||||
!HasUniqueProperties(root) ||
|
||||
RequiredRequestProperties.Any(property => !root.TryGetProperty(property, out _)))
|
||||
{
|
||||
request = null;
|
||||
return false;
|
||||
}
|
||||
|
||||
request = JsonSerializer.Deserialize<SyntheticDiagnosticRequest>(payload.Span, JsonOptions);
|
||||
return request is not null;
|
||||
}
|
||||
catch (Exception exception) when (exception is JsonException or ArgumentException)
|
||||
{
|
||||
request = null;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
internal static bool HasUniqueProperties(JsonElement element)
|
||||
{
|
||||
switch (element.ValueKind)
|
||||
{
|
||||
case 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;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
case JsonValueKind.Array:
|
||||
return element.EnumerateArray().All(HasUniqueProperties);
|
||||
default:
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
public static byte[] EncodePositiveResponse(SyntheticDiagnosticRequest request, object data) =>
|
||||
JsonSerializer.SerializeToUtf8Bytes(
|
||||
new
|
||||
{
|
||||
version = 1,
|
||||
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 = 1,
|
||||
sessionIdentifier = request.SessionIdentifier,
|
||||
configurationIdentifier = request.ConfigurationIdentifier,
|
||||
correlationIdentifier = request.CorrelationIdentifier,
|
||||
targetAddress = request.TargetAddress,
|
||||
service = request.Service,
|
||||
success = false,
|
||||
errorCode = code,
|
||||
error = message,
|
||||
data = (object?)null
|
||||
},
|
||||
JsonOptions);
|
||||
}
|
||||
|
||||
public sealed class DiagnosticProtocolException(string failureCode, string message) : Exception(message)
|
||||
{
|
||||
public string FailureCode { get; } = failureCode;
|
||||
}
|
||||
|
|
@ -0,0 +1,14 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\AutoForge.Core\AutoForge.Core.csproj" />
|
||||
<ProjectReference Include="..\AutoForge.Diagnostics\AutoForge.Diagnostics.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
</Project>
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
using System.Runtime.CompilerServices;
|
||||
|
||||
[assembly: InternalsVisibleTo("AutoForge.IntegrationTests")]
|
||||
|
|
@ -0,0 +1,354 @@
|
|||
using System.Collections.ObjectModel;
|
||||
using System.Text.Json;
|
||||
using AutoForge.Core.Vehicles;
|
||||
using AutoForge.Diagnostics;
|
||||
|
||||
namespace AutoForge.Simulation;
|
||||
|
||||
public enum SimulatedFault
|
||||
{
|
||||
None,
|
||||
NoResponse,
|
||||
MalformedResponse,
|
||||
WrongCorrelation,
|
||||
WrongIdentity,
|
||||
HoldUntilCancelled
|
||||
}
|
||||
|
||||
public sealed class VirtualIdentityDefinition
|
||||
{
|
||||
public VirtualIdentityDefinition(
|
||||
string role,
|
||||
string name,
|
||||
string? hardwareIdentifier,
|
||||
string? softwareIdentifier,
|
||||
string? firmwareIdentifier,
|
||||
string? calibrationIdentifier)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(role);
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(name);
|
||||
if (!StringComparer.Ordinal.Equals(role, role.Trim()) ||
|
||||
!StringComparer.Ordinal.Equals(name, name.Trim()))
|
||||
{
|
||||
throw new ArgumentException("Identity role and name must not contain surrounding whitespace.");
|
||||
}
|
||||
Role = role;
|
||||
Name = name;
|
||||
HardwareIdentifier = ValidateOptional(hardwareIdentifier, nameof(hardwareIdentifier));
|
||||
SoftwareIdentifier = ValidateOptional(softwareIdentifier, nameof(softwareIdentifier));
|
||||
FirmwareIdentifier = ValidateOptional(firmwareIdentifier, nameof(firmwareIdentifier));
|
||||
CalibrationIdentifier = ValidateOptional(calibrationIdentifier, nameof(calibrationIdentifier));
|
||||
}
|
||||
|
||||
public string Role { get; }
|
||||
public string Name { get; }
|
||||
public string? HardwareIdentifier { get; }
|
||||
public string? SoftwareIdentifier { get; }
|
||||
public string? FirmwareIdentifier { get; }
|
||||
public string? CalibrationIdentifier { get; }
|
||||
|
||||
public static VirtualIdentityDefinition FromModule(ModuleInstance module) =>
|
||||
new(
|
||||
module.Role,
|
||||
module.Name,
|
||||
module.HardwareIdentifier,
|
||||
module.SoftwareIdentifier,
|
||||
module.FirmwareIdentifier,
|
||||
module.CalibrationIdentifier);
|
||||
|
||||
private static string? ValidateOptional(string? value, string parameterName)
|
||||
{
|
||||
if (value is not null)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(value, parameterName);
|
||||
if (!StringComparer.Ordinal.Equals(value, value.Trim()))
|
||||
{
|
||||
throw new ArgumentException("Identity values must not contain surrounding whitespace.", parameterName);
|
||||
}
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class VirtualSignalDefinition
|
||||
{
|
||||
public VirtualSignalDefinition(
|
||||
string signalIdentifier,
|
||||
JsonElement value,
|
||||
string unit,
|
||||
SignalQuality quality = SignalQuality.Good)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(signalIdentifier);
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(unit);
|
||||
if (!StringComparer.Ordinal.Equals(signalIdentifier, signalIdentifier.Trim()) ||
|
||||
!StringComparer.Ordinal.Equals(unit, unit.Trim()))
|
||||
{
|
||||
throw new ArgumentException("Signal identifiers and units must not contain surrounding whitespace.");
|
||||
}
|
||||
|
||||
if (value.ValueKind == JsonValueKind.Undefined)
|
||||
{
|
||||
throw new ArgumentException("Signal values must be valid JSON values.", nameof(value));
|
||||
}
|
||||
if (!Enum.IsDefined(quality))
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(quality));
|
||||
}
|
||||
|
||||
SignalIdentifier = signalIdentifier;
|
||||
Value = value.Clone();
|
||||
Unit = unit;
|
||||
Quality = quality;
|
||||
}
|
||||
|
||||
public string SignalIdentifier { get; }
|
||||
public JsonElement Value { get; }
|
||||
public string Unit { get; }
|
||||
public SignalQuality Quality { get; }
|
||||
}
|
||||
|
||||
public sealed record VirtualTroubleCodeDefinition(string Code, string Description);
|
||||
|
||||
public sealed class VirtualModuleDefinition
|
||||
{
|
||||
public VirtualModuleDefinition(
|
||||
string moduleIdentifier,
|
||||
string address,
|
||||
VirtualIdentityDefinition identity,
|
||||
IEnumerable<string> implementedServices,
|
||||
IEnumerable<VirtualTroubleCodeDefinition>? initialTroubleCodes = null,
|
||||
IEnumerable<VirtualSignalDefinition>? signals = null,
|
||||
IReadOnlyDictionary<string, SimulatedFault>? faults = null,
|
||||
long responseLatencyTicks = 1)
|
||||
{
|
||||
_ = new DiagnosticEndpoint(moduleIdentifier, address);
|
||||
Identity = identity ?? throw new ArgumentNullException(nameof(identity));
|
||||
ArgumentNullException.ThrowIfNull(implementedServices);
|
||||
if (responseLatencyTicks < 0)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(responseLatencyTicks));
|
||||
}
|
||||
|
||||
ModuleIdentifier = moduleIdentifier;
|
||||
Address = address;
|
||||
ResponseLatencyTicks = responseLatencyTicks;
|
||||
ImplementedServices = Array.AsReadOnly(implementedServices.ToArray());
|
||||
InitialTroubleCodes = Array.AsReadOnly((initialTroubleCodes ?? []).ToArray());
|
||||
Signals = Array.AsReadOnly((signals ?? []).ToArray());
|
||||
Faults = new ReadOnlyDictionary<string, SimulatedFault>(
|
||||
faults?.ToDictionary(pair => pair.Key, pair => pair.Value, StringComparer.Ordinal) ??
|
||||
new Dictionary<string, SimulatedFault>(StringComparer.Ordinal));
|
||||
|
||||
if (InitialTroubleCodes.Any(code => code is null) || Signals.Any(signal => signal is null))
|
||||
{
|
||||
throw new ArgumentException("Virtual DTC and signal definitions cannot contain null values.");
|
||||
}
|
||||
EnsureUnique(ImplementedServices, "Implemented services must be unique.");
|
||||
if (ImplementedServices.Any(service => string.IsNullOrWhiteSpace(service) ||
|
||||
!StringComparer.Ordinal.Equals(service, service.Trim()) ||
|
||||
!KnownServices.Contains(service)))
|
||||
{
|
||||
throw new ArgumentException("Virtual modules may implement only defined synthetic diagnostic services.", nameof(implementedServices));
|
||||
}
|
||||
EnsureUnique(InitialTroubleCodes.Select(code => code.Code), "DTC codes must be unique within a module.");
|
||||
EnsureUnique(Signals.Select(signal => signal.SignalIdentifier), "Signal identifiers must be unique within a module.");
|
||||
if (InitialTroubleCodes.Any(code =>
|
||||
string.IsNullOrWhiteSpace(code.Code) ||
|
||||
string.IsNullOrWhiteSpace(code.Description) ||
|
||||
!StringComparer.Ordinal.Equals(code.Code, code.Code.Trim())))
|
||||
{
|
||||
throw new ArgumentException("Virtual DTC codes and descriptions must be non-empty, and codes may not have surrounding whitespace.", nameof(initialTroubleCodes));
|
||||
}
|
||||
if (Faults.Any(pair => !KnownServices.Contains(pair.Key) || !Enum.IsDefined(pair.Value)))
|
||||
{
|
||||
throw new ArgumentException("Fault maps must use defined synthetic services and fault values.", nameof(faults));
|
||||
}
|
||||
}
|
||||
|
||||
public string ModuleIdentifier { get; }
|
||||
public string Address { get; }
|
||||
public VirtualIdentityDefinition Identity { get; }
|
||||
public IReadOnlyList<string> ImplementedServices { get; }
|
||||
public IReadOnlyList<VirtualTroubleCodeDefinition> InitialTroubleCodes { get; }
|
||||
public IReadOnlyList<VirtualSignalDefinition> Signals { get; }
|
||||
public IReadOnlyDictionary<string, SimulatedFault> Faults { get; }
|
||||
public long ResponseLatencyTicks { get; }
|
||||
private static readonly HashSet<string> KnownServices =
|
||||
[
|
||||
DiagnosticServices.Probe,
|
||||
DiagnosticServices.ReadIdentity,
|
||||
DiagnosticServices.ReadTroubleCodes,
|
||||
DiagnosticServices.ClearTroubleCodes,
|
||||
DiagnosticServices.ReadSignals
|
||||
];
|
||||
|
||||
private static void EnsureUnique(IEnumerable<string> values, string message)
|
||||
{
|
||||
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
if (values.Any(value => !seen.Add(value)))
|
||||
{
|
||||
throw new ArgumentException(message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class SimulationDefinition
|
||||
{
|
||||
public SimulationDefinition(
|
||||
string profileIdentifier,
|
||||
int profileRevision,
|
||||
IEnumerable<VirtualModuleDefinition> modules)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(profileIdentifier);
|
||||
if (profileRevision <= 0)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(profileRevision));
|
||||
}
|
||||
|
||||
ArgumentNullException.ThrowIfNull(modules);
|
||||
ProfileIdentifier = profileIdentifier;
|
||||
ProfileRevision = profileRevision;
|
||||
Modules = Array.AsReadOnly(modules.ToArray());
|
||||
if (Modules.Any(module => module is null))
|
||||
{
|
||||
throw new ArgumentException("Simulation definitions cannot contain null modules.", nameof(modules));
|
||||
}
|
||||
EnsureUnique(Modules.Select(module => module.ModuleIdentifier), "Module mappings must be unique.");
|
||||
EnsureUnique(Modules.Select(module => module.Address), "Endpoint addresses must be unique.");
|
||||
}
|
||||
|
||||
public string ProfileIdentifier { get; }
|
||||
public int ProfileRevision { get; }
|
||||
public IReadOnlyList<VirtualModuleDefinition> Modules { get; }
|
||||
|
||||
public void ValidateAgainst(VehicleProfile profile)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(profile);
|
||||
if (!Same(ProfileIdentifier, profile.ProfileIdentifier) || ProfileRevision != profile.Revision)
|
||||
{
|
||||
throw new ArgumentException(
|
||||
$"Simulation definition does not match profile '{profile.ProfileIdentifier}' revision {profile.Revision}.",
|
||||
nameof(profile));
|
||||
}
|
||||
|
||||
if (Modules.Count != profile.Modules.Count)
|
||||
{
|
||||
throw new ArgumentException("Simulation definition must map every profile module exactly once.", nameof(profile));
|
||||
}
|
||||
|
||||
foreach (var virtualModule in Modules)
|
||||
{
|
||||
ModuleInstance module;
|
||||
try
|
||||
{
|
||||
module = profile.GetModule(virtualModule.ModuleIdentifier);
|
||||
}
|
||||
catch (KeyNotFoundException exception)
|
||||
{
|
||||
throw new ArgumentException(
|
||||
$"Simulation mapping references missing profile module '{virtualModule.ModuleIdentifier}'.",
|
||||
nameof(profile),
|
||||
exception);
|
||||
}
|
||||
|
||||
var identity = virtualModule.Identity;
|
||||
if (!Same(module.Role, identity.Role) ||
|
||||
!Same(module.Name, identity.Name) ||
|
||||
!SameOptional(module.HardwareIdentifier, identity.HardwareIdentifier) ||
|
||||
!SameOptional(module.SoftwareIdentifier, identity.SoftwareIdentifier) ||
|
||||
!SameOptional(module.FirmwareIdentifier, identity.FirmwareIdentifier) ||
|
||||
!SameOptional(module.CalibrationIdentifier, identity.CalibrationIdentifier))
|
||||
{
|
||||
throw new ArgumentException(
|
||||
$"Simulation identity for module '{module.InstanceIdentifier}' conflicts with the selected profile.",
|
||||
nameof(profile));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void EnsureUnique(IEnumerable<string> values, string message)
|
||||
{
|
||||
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
if (values.Any(value => !seen.Add(value)))
|
||||
{
|
||||
throw new ArgumentException(message);
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
public static class SyntheticDiagnosticExamples
|
||||
{
|
||||
public static IReadOnlyList<SimulationDefinition> CreateDefinitions()
|
||||
{
|
||||
using var rpm = JsonDocument.Parse("850");
|
||||
using var voltage = JsonDocument.Parse("12.6");
|
||||
using var state = JsonDocument.Parse("\"parked-static\"");
|
||||
var truckDefinition = new SimulationDefinition(
|
||||
"autoforge.synthetic.test-truck",
|
||||
1,
|
||||
[
|
||||
new VirtualModuleDefinition(
|
||||
"module.engine.primary",
|
||||
"10",
|
||||
new("powertrain.engine-controller", "Synthetic Engine Controller", "hardware.synthetic.engine-a",
|
||||
"software.synthetic.engine-1", null, "calibration.synthetic.engine-base"),
|
||||
[AutoForge.Diagnostics.DiagnosticServices.Probe, AutoForge.Diagnostics.DiagnosticServices.ReadIdentity,
|
||||
AutoForge.Diagnostics.DiagnosticServices.ReadTroubleCodes, AutoForge.Diagnostics.DiagnosticServices.ClearTroubleCodes,
|
||||
AutoForge.Diagnostics.DiagnosticServices.ReadSignals],
|
||||
[new("SYN-P0123", "Synthetic manifold pressure signal range notice.")],
|
||||
[new("synthetic.engine.speed", rpm.RootElement, "rpm"),
|
||||
new("synthetic.engine.battery-voltage", voltage.RootElement, "V")]),
|
||||
new VirtualModuleDefinition(
|
||||
"module.transmission.primary",
|
||||
"20",
|
||||
new("powertrain.transmission-controller", "Synthetic Transmission Controller", null, null, null, null),
|
||||
[AutoForge.Diagnostics.DiagnosticServices.Probe, AutoForge.Diagnostics.DiagnosticServices.ReadIdentity,
|
||||
AutoForge.Diagnostics.DiagnosticServices.ReadTroubleCodes, AutoForge.Diagnostics.DiagnosticServices.ReadSignals],
|
||||
[new("SYN-U0100", "Synthetic communication notice.")],
|
||||
[new("synthetic.transmission.state", state.RootElement, "label")],
|
||||
new Dictionary<string, SimulatedFault>(StringComparer.Ordinal)
|
||||
{
|
||||
[AutoForge.Diagnostics.DiagnosticServices.Probe] = SimulatedFault.NoResponse
|
||||
}),
|
||||
new VirtualModuleDefinition(
|
||||
"module.cabin.body",
|
||||
"30",
|
||||
new("body-control", "Synthetic Cabin Controller", "hardware.synthetic.body",
|
||||
"software.synthetic.body-1", null, null),
|
||||
[AutoForge.Diagnostics.DiagnosticServices.Probe, AutoForge.Diagnostics.DiagnosticServices.ReadIdentity,
|
||||
AutoForge.Diagnostics.DiagnosticServices.ReadTroubleCodes, AutoForge.Diagnostics.DiagnosticServices.ReadSignals],
|
||||
[],
|
||||
[new("synthetic.body.door-count", JsonNumber(4), "count")])
|
||||
]);
|
||||
|
||||
var orchardDefinition = new SimulationDefinition(
|
||||
"autoforge.synthetic.orchard-cart",
|
||||
1,
|
||||
[
|
||||
new VirtualModuleDefinition(
|
||||
"module.custom.sensor-bridge",
|
||||
"41",
|
||||
new("custom.experimental-sensor-bridge", "Synthetic Sensor Bridge",
|
||||
null, "software.synthetic.bridge", null, null),
|
||||
[AutoForge.Diagnostics.DiagnosticServices.Probe, AutoForge.Diagnostics.DiagnosticServices.ReadIdentity,
|
||||
AutoForge.Diagnostics.DiagnosticServices.ReadTroubleCodes, AutoForge.Diagnostics.DiagnosticServices.ReadSignals],
|
||||
[],
|
||||
[new("synthetic.orchard.environment", state.RootElement, "label")])
|
||||
]);
|
||||
|
||||
return Array.AsReadOnly([truckDefinition, orchardDefinition]);
|
||||
}
|
||||
|
||||
private static JsonElement JsonNumber(int value)
|
||||
{
|
||||
using var document = JsonDocument.Parse(value.ToString(System.Globalization.CultureInfo.InvariantCulture));
|
||||
return document.RootElement.Clone();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,349 @@
|
|||
using System.Collections.Concurrent;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
using AutoForge.Core.ExecutionTargets;
|
||||
using AutoForge.Core.Vehicles;
|
||||
using AutoForge.Diagnostics;
|
||||
|
||||
namespace AutoForge.Simulation;
|
||||
|
||||
public sealed class SimulatedDiagnosticTransportFactory : IDiagnosticTransportFactory
|
||||
{
|
||||
public const string ProviderIdentifier = "autoforge.simulation.synthetic";
|
||||
private readonly Dictionary<ProfileRevisionKey, SimulationDefinition> _definitions;
|
||||
private readonly ConcurrentDictionary<string, SimulatedDiagnosticTransport> _activeTransports =
|
||||
new(StringComparer.Ordinal);
|
||||
|
||||
public SimulatedDiagnosticTransportFactory(IEnumerable<SimulationDefinition> definitions)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(definitions);
|
||||
var source = definitions.ToArray();
|
||||
_definitions = new Dictionary<ProfileRevisionKey, SimulationDefinition>(ProfileRevisionKeyComparer.Instance);
|
||||
foreach (var definition in source)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(definition);
|
||||
if (!_definitions.TryAdd(new ProfileRevisionKey(definition.ProfileIdentifier, definition.ProfileRevision), definition))
|
||||
{
|
||||
throw new ArgumentException("Simulation definitions contain a duplicate profile revision.", nameof(definitions));
|
||||
}
|
||||
}
|
||||
|
||||
Descriptor = new DiagnosticProviderDescriptor(
|
||||
new ExecutionTargetDescriptor(ProviderIdentifier, ExecutionTargetKind.Simulation),
|
||||
"Synthetic virtual-module provider");
|
||||
}
|
||||
|
||||
public DiagnosticProviderDescriptor Descriptor { get; }
|
||||
|
||||
public IDiagnosticTransport OpenTransport(VehicleProfile profile, DiagnosticSessionIdentity identity)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(profile);
|
||||
ArgumentNullException.ThrowIfNull(identity);
|
||||
if (!Same(profile.ProfileIdentifier, identity.ProfileIdentifier) ||
|
||||
profile.Revision != identity.ProfileRevision ||
|
||||
!Same(profile.Vehicle.VehicleIdentifier, identity.VehicleIdentifier))
|
||||
{
|
||||
throw new ArgumentException("Session identity does not bind to the supplied immutable profile.", nameof(identity));
|
||||
}
|
||||
|
||||
if (identity.Target.Kind != ExecutionTargetKind.Simulation ||
|
||||
!Same(identity.Target.ProviderIdentifier, Descriptor.Target.ProviderIdentifier))
|
||||
{
|
||||
throw new ArgumentException("The synthetic provider accepts only its explicitly registered Simulation target.", nameof(identity));
|
||||
}
|
||||
|
||||
if (!_definitions.TryGetValue(new ProfileRevisionKey(profile.ProfileIdentifier, profile.Revision), out var definition))
|
||||
{
|
||||
throw new DiagnosticProviderException(
|
||||
DiagnosticProviderFailure.ConfigurationNotFound,
|
||||
$"No synthetic simulation definition exists for profile '{profile.ProfileIdentifier}' revision {profile.Revision}.");
|
||||
}
|
||||
|
||||
definition.ValidateAgainst(profile);
|
||||
var transport = new SimulatedDiagnosticTransport(
|
||||
definition,
|
||||
identity,
|
||||
onClosed: closed => _activeTransports.TryRemove(closed.SessionIdentifier, out _));
|
||||
if (!_activeTransports.TryAdd(identity.SessionIdentifier, transport))
|
||||
{
|
||||
throw new DiagnosticProviderException(
|
||||
DiagnosticProviderFailure.SessionConflict,
|
||||
$"Session '{identity.SessionIdentifier}' already has a simulated transport.");
|
||||
}
|
||||
|
||||
return transport;
|
||||
}
|
||||
|
||||
internal IReadOnlyList<string> ReadVirtualDtcStateForTest(string sessionIdentifier, string moduleIdentifier)
|
||||
{
|
||||
if (!_activeTransports.TryGetValue(sessionIdentifier, out var transport))
|
||||
{
|
||||
throw new InvalidOperationException("The test oracle can inspect only an active simulated session.");
|
||||
}
|
||||
|
||||
return transport.ReadDtcStateForTest(moduleIdentifier);
|
||||
}
|
||||
|
||||
internal Task WaitForPendingRequestForTestAsync(string sessionIdentifier)
|
||||
{
|
||||
if (!_activeTransports.TryGetValue(sessionIdentifier, out var transport))
|
||||
{
|
||||
throw new InvalidOperationException("The test oracle can inspect only an active simulated session.");
|
||||
}
|
||||
|
||||
return transport.WaitForPendingRequestForTestAsync();
|
||||
}
|
||||
|
||||
private readonly record struct ProfileRevisionKey(string ProfileIdentifier, int Revision);
|
||||
|
||||
private sealed class ProfileRevisionKeyComparer : IEqualityComparer<ProfileRevisionKey>
|
||||
{
|
||||
public static ProfileRevisionKeyComparer Instance { get; } = new();
|
||||
public bool Equals(ProfileRevisionKey x, ProfileRevisionKey y) =>
|
||||
x.Revision == y.Revision && Same(x.ProfileIdentifier, y.ProfileIdentifier);
|
||||
public int GetHashCode(ProfileRevisionKey value) =>
|
||||
HashCode.Combine(StringComparer.OrdinalIgnoreCase.GetHashCode(value.ProfileIdentifier), value.Revision);
|
||||
}
|
||||
|
||||
private static bool Same(string left, string right) =>
|
||||
StringComparer.OrdinalIgnoreCase.Equals(left, right);
|
||||
|
||||
}
|
||||
|
||||
internal sealed class SimulatedDiagnosticTransport : IDiagnosticTransport
|
||||
{
|
||||
private readonly SimulationDefinition _definition;
|
||||
private readonly DiagnosticSessionIdentity _identity;
|
||||
private readonly CancellationTokenSource _closed = new();
|
||||
private readonly Action<DiagnosticSessionIdentity> _onClosed;
|
||||
private readonly Dictionary<string, VirtualModuleState> _states;
|
||||
private readonly TaskCompletionSource _pendingRequestStarted = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
private int _isClosed;
|
||||
|
||||
public SimulatedDiagnosticTransport(
|
||||
SimulationDefinition definition,
|
||||
DiagnosticSessionIdentity identity,
|
||||
Action<DiagnosticSessionIdentity> onClosed)
|
||||
{
|
||||
_definition = definition;
|
||||
_identity = identity;
|
||||
_onClosed = onClosed;
|
||||
_states = definition.Modules.ToDictionary(
|
||||
module => module.ModuleIdentifier,
|
||||
module => new VirtualModuleState(module),
|
||||
StringComparer.OrdinalIgnoreCase);
|
||||
ExpectedEndpoints = Array.AsReadOnly(definition.Modules
|
||||
.Select(module => new DiagnosticEndpoint(module.ModuleIdentifier, module.Address))
|
||||
.ToArray());
|
||||
}
|
||||
|
||||
public IReadOnlyList<DiagnosticEndpoint> ExpectedEndpoints { get; }
|
||||
|
||||
public async ValueTask<TransportReply> SendAsync(ReadOnlyMemory<byte> requestPayload, CancellationToken cancellationToken)
|
||||
{
|
||||
if (Volatile.Read(ref _isClosed) != 0)
|
||||
{
|
||||
return new TransportReply(TransportOutcome.Cancelled, ReadOnlyMemory<byte>.Empty, 0, "Session transport is closed.");
|
||||
}
|
||||
|
||||
if (!SyntheticProtocolV1.TryDecodeRequest(requestPayload, out var request) || request is null)
|
||||
{
|
||||
return new TransportReply(TransportOutcome.NoResponse, ReadOnlyMemory<byte>.Empty, 0, "Request frame was malformed.");
|
||||
}
|
||||
|
||||
if (request.Version != 1)
|
||||
{
|
||||
return new TransportReply(
|
||||
TransportOutcome.Response,
|
||||
SyntheticProtocolV1.EncodeNegativeResponse(request, "UNSUPPORTED_VERSION", "Synthetic protocol version 1 is required."),
|
||||
0);
|
||||
}
|
||||
|
||||
if (!Same(request.SessionIdentifier, _identity.SessionIdentifier) ||
|
||||
!Same(request.ProfileIdentifier, _identity.ProfileIdentifier) ||
|
||||
!Same(request.ConfigurationIdentifier, _identity.ConfigurationIdentifier) ||
|
||||
request.ProfileRevision != _identity.ProfileRevision)
|
||||
{
|
||||
return new TransportReply(
|
||||
TransportOutcome.Response,
|
||||
SyntheticProtocolV1.EncodeNegativeResponse(request, "SESSION_MISMATCH", "Request session/profile identity is not bound to this transport."),
|
||||
0);
|
||||
}
|
||||
|
||||
var module = _definition.Modules.FirstOrDefault(candidate => Same(candidate.Address, request.TargetAddress));
|
||||
if (module is null)
|
||||
{
|
||||
return new TransportReply(
|
||||
TransportOutcome.Response,
|
||||
SyntheticProtocolV1.EncodeNegativeResponse(request, "UNKNOWN_ADDRESS", "No virtual endpoint is configured at this address."),
|
||||
0);
|
||||
}
|
||||
|
||||
var fault = module.Faults.TryGetValue(request.Service, out var configuredFault)
|
||||
? configuredFault
|
||||
: SimulatedFault.None;
|
||||
if (fault == SimulatedFault.NoResponse)
|
||||
{
|
||||
return new TransportReply(TransportOutcome.NoResponse, ReadOnlyMemory<byte>.Empty, 0, "Configured endpoint did not respond.");
|
||||
}
|
||||
|
||||
if (fault == SimulatedFault.HoldUntilCancelled)
|
||||
{
|
||||
using var linked = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _closed.Token);
|
||||
_pendingRequestStarted.TrySetResult();
|
||||
try
|
||||
{
|
||||
await Task.Delay(Timeout.InfiniteTimeSpan, linked.Token).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
return new TransportReply(TransportOutcome.Cancelled, ReadOnlyMemory<byte>.Empty, 0, "Pending virtual request was cancelled or its session closed.");
|
||||
}
|
||||
}
|
||||
|
||||
if (Volatile.Read(ref _isClosed) != 0 || cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
return new TransportReply(TransportOutcome.Cancelled, ReadOnlyMemory<byte>.Empty, 0, "Session transport is closed or request cancelled.");
|
||||
}
|
||||
|
||||
if (module.ResponseLatencyTicks > request.TimeoutTicks)
|
||||
{
|
||||
return new TransportReply(
|
||||
TransportOutcome.Timeout,
|
||||
ReadOnlyMemory<byte>.Empty,
|
||||
request.TimeoutTicks,
|
||||
$"Virtual response latency {module.ResponseLatencyTicks} exceeded deadline {request.TimeoutTicks}.");
|
||||
}
|
||||
|
||||
if (fault == SimulatedFault.MalformedResponse)
|
||||
{
|
||||
return new TransportReply(TransportOutcome.Response, "{malformed"u8.ToArray(), module.ResponseLatencyTicks);
|
||||
}
|
||||
|
||||
var response = CreateResponse(request, module);
|
||||
if (fault == SimulatedFault.WrongCorrelation)
|
||||
{
|
||||
var corrupted = JsonNode.Parse(response)!.AsObject();
|
||||
corrupted["correlationIdentifier"] = "unexpected-correlation";
|
||||
response = JsonSerializer.SerializeToUtf8Bytes(corrupted);
|
||||
}
|
||||
else if (fault == SimulatedFault.WrongIdentity && request.Service == DiagnosticServices.ReadIdentity)
|
||||
{
|
||||
var corrupted = JsonNode.Parse(response)!.AsObject();
|
||||
corrupted["data"]!["moduleIdentifier"] = "module.unexpected";
|
||||
response = JsonSerializer.SerializeToUtf8Bytes(corrupted);
|
||||
}
|
||||
|
||||
return new TransportReply(TransportOutcome.Response, response, module.ResponseLatencyTicks);
|
||||
}
|
||||
|
||||
internal IReadOnlyList<string> ReadDtcStateForTest(string moduleIdentifier)
|
||||
{
|
||||
if (!_states.TryGetValue(moduleIdentifier, out var state))
|
||||
{
|
||||
throw new KeyNotFoundException($"Virtual module '{moduleIdentifier}' is not configured.");
|
||||
}
|
||||
|
||||
lock (state.Gate)
|
||||
{
|
||||
return Array.AsReadOnly(state.TroubleCodes.Select(code => code.Code).ToArray());
|
||||
}
|
||||
}
|
||||
|
||||
internal Task WaitForPendingRequestForTestAsync() => _pendingRequestStarted.Task;
|
||||
|
||||
public ValueTask DisposeAsync()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _isClosed, 1) == 0)
|
||||
{
|
||||
_closed.Cancel();
|
||||
_onClosed(_identity);
|
||||
_closed.Dispose();
|
||||
}
|
||||
|
||||
return ValueTask.CompletedTask;
|
||||
}
|
||||
|
||||
private byte[] CreateResponse(SyntheticDiagnosticRequest request, VirtualModuleDefinition module)
|
||||
{
|
||||
if (!module.ImplementedServices.Contains(request.Service, StringComparer.Ordinal))
|
||||
{
|
||||
return SyntheticProtocolV1.EncodeNegativeResponse(
|
||||
request,
|
||||
"UNSUPPORTED_SERVICE",
|
||||
$"Service '{request.Service}' is not implemented by this virtual endpoint.");
|
||||
}
|
||||
|
||||
var state = _states[module.ModuleIdentifier];
|
||||
object data = request.Service switch
|
||||
{
|
||||
DiagnosticServices.Probe => new
|
||||
{
|
||||
moduleIdentifier = module.ModuleIdentifier,
|
||||
implementedServices = module.ImplementedServices
|
||||
},
|
||||
DiagnosticServices.ReadIdentity => new
|
||||
{
|
||||
moduleIdentifier = module.ModuleIdentifier,
|
||||
role = module.Identity.Role,
|
||||
name = module.Identity.Name,
|
||||
hardwareIdentifier = module.Identity.HardwareIdentifier,
|
||||
softwareIdentifier = module.Identity.SoftwareIdentifier,
|
||||
firmwareIdentifier = module.Identity.FirmwareIdentifier,
|
||||
calibrationIdentifier = module.Identity.CalibrationIdentifier
|
||||
},
|
||||
DiagnosticServices.ReadTroubleCodes => ReadDtcData(module, state),
|
||||
DiagnosticServices.ClearTroubleCodes => ClearDtcData(module, state),
|
||||
DiagnosticServices.ReadSignals => new
|
||||
{
|
||||
moduleIdentifier = module.ModuleIdentifier,
|
||||
logicalTimeTicks = request.LogicalTimeTicks,
|
||||
origin = "SYNTHETIC_STATIC",
|
||||
signals = module.Signals.Select(signal => new
|
||||
{
|
||||
signalIdentifier = signal.SignalIdentifier,
|
||||
value = signal.Value,
|
||||
unit = signal.Unit,
|
||||
quality = signal.Quality.ToString()
|
||||
}).ToArray()
|
||||
},
|
||||
_ => null!
|
||||
};
|
||||
|
||||
return data is null
|
||||
? SyntheticProtocolV1.EncodeNegativeResponse(request, "UNSUPPORTED_SERVICE", $"Service '{request.Service}' is not implemented.")
|
||||
: SyntheticProtocolV1.EncodePositiveResponse(request, data);
|
||||
}
|
||||
|
||||
private static object ReadDtcData(VirtualModuleDefinition module, VirtualModuleState state)
|
||||
{
|
||||
lock (state.Gate)
|
||||
{
|
||||
return new
|
||||
{
|
||||
moduleIdentifier = module.ModuleIdentifier,
|
||||
codes = state.TroubleCodes.Select(code => new { code = code.Code, description = code.Description }).ToArray()
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
private static object ClearDtcData(VirtualModuleDefinition module, VirtualModuleState state)
|
||||
{
|
||||
lock (state.Gate)
|
||||
{
|
||||
var count = state.TroubleCodes.Count;
|
||||
state.TroubleCodes.Clear();
|
||||
return new { moduleIdentifier = module.ModuleIdentifier, clearedCount = count };
|
||||
}
|
||||
}
|
||||
|
||||
private static bool Same(string left, string right) =>
|
||||
StringComparer.OrdinalIgnoreCase.Equals(left, right);
|
||||
|
||||
private sealed class VirtualModuleState(VirtualModuleDefinition definition)
|
||||
{
|
||||
public object Gate { get; } = new();
|
||||
public List<VirtualTroubleCodeDefinition> TroubleCodes { get; } = definition.InitialTroubleCodes.ToList();
|
||||
}
|
||||
}
|
||||
|
|
@ -14,6 +14,12 @@
|
|||
<ItemGroup>
|
||||
<ProjectReference Include="..\AutoForge.Components\AutoForge.Components.csproj" />
|
||||
<ProjectReference Include="..\AutoForge.Application\AutoForge.Application.csproj" />
|
||||
<ProjectReference Include="..\AutoForge.Diagnostics\AutoForge.Diagnostics.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<EmbeddedResource Include="..\tests\AutoForge.IntegrationTests\Fixtures\synthetic-truck-baseline.json"
|
||||
LogicalName="AutoForge.UI.SyntheticExamples.synthetic-truck-baseline.json" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
|
|
|||
|
|
@ -11,6 +11,23 @@
|
|||
|
||||
<StatusNotice Tone="@Selection.StatusTone" Message="@Selection.StatusMessage" />
|
||||
|
||||
<section aria-labelledby="registered-targets-heading">
|
||||
<h2 id="registered-targets-heading">Registered provider metadata</h2>
|
||||
@if (Selection.RegisteredProviders.Count == 0)
|
||||
{
|
||||
<p>No execution-target providers are registered.</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<ul>
|
||||
@foreach (var provider in Selection.RegisteredProviders)
|
||||
{
|
||||
<li data-provider="@provider.ProviderIdentifier">@provider.ProviderIdentifier (@provider.Kind)</li>
|
||||
}
|
||||
</ul>
|
||||
}
|
||||
</section>
|
||||
|
||||
<form class="selection-form" @onsubmit="Submit" @onsubmit:preventDefault>
|
||||
<label for="provider-identifier">Provider identifier</label>
|
||||
<input id="provider-identifier" name="providerIdentifier" autocomplete="off"
|
||||
|
|
|
|||
|
|
@ -6,6 +6,8 @@ namespace AutoForge.UI.Features.ExecutionTargets.SelectExecutionTarget;
|
|||
|
||||
public sealed class ExecutionTargetSelectionViewModel(IExecutionTargetResolver resolver)
|
||||
{
|
||||
public IReadOnlyList<ExecutionTargetDescriptor> RegisteredProviders => resolver.RegisteredDescriptors;
|
||||
|
||||
public string ProviderIdentifier { get; set; } = string.Empty;
|
||||
|
||||
public ExecutionTargetKind? SelectedKind { get; set; }
|
||||
|
|
@ -17,7 +19,9 @@ public sealed class ExecutionTargetSelectionViewModel(IExecutionTargetResolver r
|
|||
public StatusNoticeTone StatusTone { get; private set; } = StatusNoticeTone.Warning;
|
||||
|
||||
public string StatusMessage { get; private set; } =
|
||||
"No provider metadata is registered. Choose an explicit provider identifier and target kind; selection will fail until a provider is configured. No connection is attempted.";
|
||||
resolver.RegisteredDescriptors.Count == 0
|
||||
? "No provider metadata is registered. Choose an explicit provider identifier and target kind; selection will fail until a provider is configured. No connection is attempted."
|
||||
: $"{string.Join(", ", resolver.RegisteredDescriptors.Select(descriptor => $"{descriptor.ProviderIdentifier} ({descriptor.Kind})"))} is registered. Resolving metadata does not open a session or connection.";
|
||||
|
||||
public void Select()
|
||||
{
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
using AutoForge.UI.Features.ExecutionTargets.SelectExecutionTarget;
|
||||
using AutoForge.UI.Features.Vehicles.Diagnostics;
|
||||
using AutoForge.UI.Features.Vehicles.Profiles;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
|
|
@ -11,6 +12,7 @@ public static class ServiceCollectionExtensions
|
|||
ArgumentNullException.ThrowIfNull(services);
|
||||
|
||||
services.AddScoped<ExecutionTargetSelectionViewModel>();
|
||||
services.AddScoped<DiagnosticPageViewModel>();
|
||||
services.AddScoped<VehicleProfilePageViewModel>();
|
||||
return services;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,11 +4,14 @@
|
|||
|
||||
<h1>AutoForge foundation</h1>
|
||||
<p>
|
||||
The application shell is ready for future, independently testable feature slices.
|
||||
No vehicle, driver, model, backend or cloud service is required to start.
|
||||
AutoForge includes a clearly synthetic virtual-module diagnostic workflow.
|
||||
It does not connect to a real vehicle and requires no driver, backend or cloud service.
|
||||
</p>
|
||||
<StatusNotice Tone="StatusNoticeTone.Information"
|
||||
Message="Implemented today: explicit execution-target metadata selection. Simulation, diagnostics and hardware operations are not implemented." />
|
||||
Message="Available: explicit target metadata selection and synthetic diagnostic sessions with static module data. Vehicle dynamics and physical hardware operations are not implemented." />
|
||||
<p>
|
||||
<a href="/execution-targets">Review execution-target selection</a>
|
||||
</p>
|
||||
<p>
|
||||
<a href="/diagnostics">Open synthetic diagnostics</a>
|
||||
</p>
|
||||
|
|
|
|||
|
|
@ -0,0 +1,411 @@
|
|||
using AutoForge.Application.Features.Vehicles.Diagnostics;
|
||||
using AutoForge.Application.Features.Vehicles.Profiles;
|
||||
using AutoForge.Application.ExecutionTargets;
|
||||
using AutoForge.Components;
|
||||
using AutoForge.Core.ExecutionTargets;
|
||||
using AutoForge.Core.Vehicles;
|
||||
using AutoForge.Diagnostics;
|
||||
|
||||
namespace AutoForge.UI.Features.Vehicles.Diagnostics;
|
||||
|
||||
public sealed class DiagnosticPageViewModel(
|
||||
IVehicleProfileService profiles,
|
||||
IDiagnosticSessionService sessions)
|
||||
{
|
||||
private CancellationTokenSource? _pending;
|
||||
|
||||
public IReadOnlyList<VehicleProfileReference> AvailableProfiles { get; private set; } = profiles.List();
|
||||
public IReadOnlyList<DiagnosticProviderDescriptor> Providers => sessions.Providers;
|
||||
public string? SelectedProfileIdentifier { get; set; }
|
||||
public int? SelectedProfileRevision { get; set; }
|
||||
public string? SelectedProviderIdentifier { get; set; }
|
||||
public ExecutionTargetKind? SelectedTargetKind { get; set; }
|
||||
public DiagnosticSession? ActiveSession { get; private set; }
|
||||
public IReadOnlyList<DiscoveryEntry> DiscoveredModules { get; private set; } = [];
|
||||
public string? DiscoverySummary { get; private set; }
|
||||
public IReadOnlyDictionary<string, TroubleCodeReadResult> TroubleCodes { get; private set; } =
|
||||
new Dictionary<string, TroubleCodeReadResult>(StringComparer.OrdinalIgnoreCase);
|
||||
public IReadOnlyDictionary<string, SignalSnapshot> Signals { get; private set; } =
|
||||
new Dictionary<string, SignalSnapshot>(StringComparer.OrdinalIgnoreCase);
|
||||
public IReadOnlyList<string> OperationMessages { get; private set; } = [];
|
||||
public bool IsBusy => _pending is not null;
|
||||
public StatusNoticeTone StatusTone { get; private set; } = StatusNoticeTone.Information;
|
||||
|
||||
public string StatusMessage { get; private set; } =
|
||||
sessions.Providers.Count == 0
|
||||
? "No diagnostic providers are available. No session is open."
|
||||
: "Select an exact saved profile revision and provider, then explicitly open a simulation session. Metadata selection alone does not connect.";
|
||||
|
||||
public void LoadSyntheticExample()
|
||||
{
|
||||
try
|
||||
{
|
||||
var imported = profiles.Import(ReadSyntheticProfile());
|
||||
AvailableProfiles = profiles.List();
|
||||
StatusTone = StatusNoticeTone.Success;
|
||||
StatusMessage =
|
||||
$"Loaded synthetic profile '{imported.ProfileIdentifier}' revision {imported.Revision}. Select it explicitly; no session was opened.";
|
||||
}
|
||||
catch (VehicleProfileInterchangeException exception)
|
||||
{
|
||||
SetFailure(exception.Message);
|
||||
}
|
||||
catch (VehicleProfileCatalogException exception)
|
||||
{
|
||||
SetFailure(exception.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task OpenSessionAsync()
|
||||
{
|
||||
if (ActiveSession is not null)
|
||||
{
|
||||
SetFailure("Close the current session before opening another explicit session.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (SelectedProfileIdentifier is null || SelectedProfileRevision is null ||
|
||||
SelectedProviderIdentifier is null || SelectedTargetKind is null)
|
||||
{
|
||||
SetFailure("Select an exact saved profile revision, provider identifier and target kind before opening a session.");
|
||||
return;
|
||||
}
|
||||
|
||||
var cancellation = BeginPending();
|
||||
try
|
||||
{
|
||||
var session = await sessions.OpenAsync(
|
||||
SelectedProfileIdentifier,
|
||||
SelectedProfileRevision.Value,
|
||||
SelectedProviderIdentifier,
|
||||
SelectedTargetKind.Value,
|
||||
cancellation.Token);
|
||||
ActiveSession = session;
|
||||
ResetSessionResults();
|
||||
SetInformation(
|
||||
$"Simulation session {session.Identity.SessionIdentifier} opened for profile '{session.Identity.ProfileIdentifier}' revision {session.Identity.ProfileRevision}. No physical connection was attempted.");
|
||||
}
|
||||
catch (DiagnosticSessionException exception)
|
||||
{
|
||||
SetFailure(exception.Message);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
SetFailure("Opening the simulation session was cancelled.");
|
||||
}
|
||||
catch (VehicleProfileCatalogException exception)
|
||||
{
|
||||
SetFailure(exception.Message);
|
||||
}
|
||||
catch (TargetSelectionException exception)
|
||||
{
|
||||
SetFailure(exception.Message);
|
||||
}
|
||||
catch (ArgumentException exception)
|
||||
{
|
||||
SetFailure(exception.Message);
|
||||
}
|
||||
finally
|
||||
{
|
||||
EndPending(cancellation);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task DiscoverAsync()
|
||||
{
|
||||
var session = ActiveSession;
|
||||
if (session is null)
|
||||
{
|
||||
SetFailure("Open an explicit simulation session before discovery.");
|
||||
return;
|
||||
}
|
||||
|
||||
var cancellation = BeginPending();
|
||||
try
|
||||
{
|
||||
var result = await session.DiscoverAsync(cancellation.Token);
|
||||
if (!IsCurrent(session))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
DiscoveredModules = result.Endpoints;
|
||||
DiscoverySummary =
|
||||
$"Expected endpoints: {result.ExpectedEndpointCount}; validated positive probes: {result.ValidatedProbeCount}; profile-verified identities: {result.IdentifiedModuleCount}.";
|
||||
SetInformation($"Discovery completed. {DiscoverySummary}");
|
||||
OperationMessages = result.Endpoints
|
||||
.SelectMany(endpoint => new[]
|
||||
{
|
||||
endpoint.ProbeError is null
|
||||
? null
|
||||
: $"{endpoint.Endpoint.ModuleIdentifier} probe: {endpoint.ProbeOutcome} — {endpoint.ProbeError}",
|
||||
endpoint.IdentityError is null
|
||||
? null
|
||||
: $"{endpoint.Endpoint.ModuleIdentifier} identity ({endpoint.IdentityStatus}{(endpoint.IdentityOutcome is { } outcome ? $", {outcome}" : string.Empty)}): {endpoint.IdentityError}"
|
||||
})
|
||||
.Where(message => message is not null)
|
||||
.Select(message => message!)
|
||||
.ToArray();
|
||||
if (result.Endpoints.Any(endpoint =>
|
||||
endpoint.ProbeOutcome == DiagnosticOutcome.Cancelled ||
|
||||
endpoint.IdentityOutcome == DiagnosticOutcome.Cancelled))
|
||||
{
|
||||
SetFailure($"Module discovery was cancelled; completed probe evidence is retained without treating any unavailable identity as verified. {DiscoverySummary}");
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
EndPending(cancellation);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task ReadModuleAsync(string moduleIdentifier)
|
||||
{
|
||||
var session = ActiveSession;
|
||||
var discovered = DiscoveredModules.FirstOrDefault(entry =>
|
||||
entry.Identity is not null &&
|
||||
StringComparer.OrdinalIgnoreCase.Equals(entry.Endpoint.ModuleIdentifier, moduleIdentifier));
|
||||
if (session is null || discovered?.Identity is null)
|
||||
{
|
||||
SetFailure("Read requests require a profile-verified identity from the current session's discovery results.");
|
||||
return;
|
||||
}
|
||||
|
||||
var cancellation = BeginPending();
|
||||
try
|
||||
{
|
||||
var dtcResult = discovered.ImplementedServices.Contains(DiagnosticServices.ReadTroubleCodes, StringComparer.Ordinal)
|
||||
? await session.ReadTroubleCodesAsync(discovered.Endpoint, cancellation.Token)
|
||||
: DiagnosticOperationResult<TroubleCodeReadResult>.Failure(
|
||||
DiagnosticOutcome.NegativeResponse,
|
||||
"UNSUPPORTED_SERVICE",
|
||||
"This virtual endpoint does not implement DTC retrieval.");
|
||||
var signalResult = discovered.ImplementedServices.Contains(DiagnosticServices.ReadSignals, StringComparer.Ordinal)
|
||||
? await session.ReadSignalsAsync(discovered.Endpoint, cancellation.Token)
|
||||
: DiagnosticOperationResult<SignalSnapshot>.Failure(
|
||||
DiagnosticOutcome.NegativeResponse,
|
||||
"UNSUPPORTED_SERVICE",
|
||||
"This virtual endpoint does not implement static signal retrieval.");
|
||||
|
||||
if (!IsCurrent(session))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var dtcs = TroubleCodes.ToDictionary(pair => pair.Key, pair => pair.Value, StringComparer.OrdinalIgnoreCase);
|
||||
var signals = Signals.ToDictionary(pair => pair.Key, pair => pair.Value, StringComparer.OrdinalIgnoreCase);
|
||||
if (dtcResult.IsSuccess)
|
||||
{
|
||||
dtcs[moduleIdentifier] = dtcResult.Value!;
|
||||
}
|
||||
if (signalResult.IsSuccess)
|
||||
{
|
||||
signals[moduleIdentifier] = signalResult.Value!;
|
||||
}
|
||||
|
||||
TroubleCodes = dtcs;
|
||||
Signals = signals;
|
||||
OperationMessages = new[]
|
||||
{
|
||||
FormatResult("DTC read", dtcResult.Outcome, dtcResult.Error),
|
||||
FormatResult("Static signal read", signalResult.Outcome, signalResult.Error)
|
||||
}
|
||||
.Where(message => message is not null)
|
||||
.Select(message => message!)
|
||||
.ToArray();
|
||||
if (dtcResult.Outcome == DiagnosticOutcome.Cancelled || signalResult.Outcome == DiagnosticOutcome.Cancelled)
|
||||
{
|
||||
SetFailure($"Diagnostic reads for '{moduleIdentifier}' were cancelled; no cancelled response is presented as data.");
|
||||
}
|
||||
else if (!dtcResult.IsSuccess || !signalResult.IsSuccess)
|
||||
{
|
||||
SetFailure($"One or more diagnostic reads for '{moduleIdentifier}' failed. See the explicit operation outcomes.");
|
||||
}
|
||||
else
|
||||
{
|
||||
SetInformation($"Diagnostic reads completed for '{moduleIdentifier}'. Empty DTC results are valid only when explicitly returned by the module.");
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
EndPending(cancellation);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task ClearTroubleCodesAsync(string moduleIdentifier)
|
||||
{
|
||||
var session = ActiveSession;
|
||||
var discovered = DiscoveredModules.FirstOrDefault(entry =>
|
||||
entry.Identity is not null &&
|
||||
StringComparer.OrdinalIgnoreCase.Equals(entry.Endpoint.ModuleIdentifier, moduleIdentifier));
|
||||
if (session is null || discovered?.Identity is null)
|
||||
{
|
||||
SetFailure("Virtual DTC clear requires a profile-verified identity from the current simulation session.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!discovered.ImplementedServices.Contains(DiagnosticServices.ClearTroubleCodes, StringComparer.Ordinal))
|
||||
{
|
||||
SetFailure("This virtual module does not support DTC clearing.");
|
||||
return;
|
||||
}
|
||||
|
||||
var cancellation = BeginPending();
|
||||
try
|
||||
{
|
||||
var clear = await session.ClearTroubleCodesAndVerifyAsync(discovered.Endpoint, cancellation.Token);
|
||||
if (!IsCurrent(session))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (clear.Readback?.IsSuccess == true)
|
||||
{
|
||||
var dtcs = TroubleCodes.ToDictionary(pair => pair.Key, pair => pair.Value, StringComparer.OrdinalIgnoreCase);
|
||||
dtcs[moduleIdentifier] = clear.Readback.Value!;
|
||||
TroubleCodes = dtcs;
|
||||
}
|
||||
|
||||
if (!clear.IsVerified)
|
||||
{
|
||||
var acknowledgementMessage = clear.Acknowledgement.IsSuccess
|
||||
? $"Virtual clear acknowledgement received ({clear.Acknowledgement.Value!.ClearedCount} item(s))."
|
||||
: $"Virtual clear acknowledgement: {clear.Acknowledgement.Outcome}.";
|
||||
OperationMessages =
|
||||
[
|
||||
acknowledgementMessage,
|
||||
$"Verification failed or is uncertain: {clear.VerificationError} No physical write was performed."
|
||||
];
|
||||
SetFailure(OperationMessages[1]);
|
||||
return;
|
||||
}
|
||||
|
||||
OperationMessages =
|
||||
[
|
||||
$"Virtual clear acknowledgement received ({clear.Acknowledgement.Value!.ClearedCount} item(s)).",
|
||||
"Fresh readback verified that no DTCs remain."
|
||||
];
|
||||
SetInformation($"Fresh readback verified an empty virtual DTC state for '{moduleIdentifier}'. No physical write was performed.");
|
||||
}
|
||||
finally
|
||||
{
|
||||
EndPending(cancellation);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task ResetSessionAsync()
|
||||
{
|
||||
var session = ActiveSession;
|
||||
if (session is null)
|
||||
{
|
||||
SetFailure("There is no session to reset.");
|
||||
return;
|
||||
}
|
||||
|
||||
var cancellation = BeginPending();
|
||||
try
|
||||
{
|
||||
var reset = await sessions.ResetAsync(session, cancellation.Token);
|
||||
ActiveSession = reset;
|
||||
ResetSessionResults();
|
||||
SetInformation($"Session state reset to its configured synthetic initial values. New session: {reset.Identity.SessionIdentifier}.");
|
||||
}
|
||||
catch (DiagnosticSessionException exception)
|
||||
{
|
||||
ActiveSession = null;
|
||||
SetFailure(exception.Message);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
ActiveSession = null;
|
||||
SetFailure("Session reset was cancelled after closing the previous session.");
|
||||
}
|
||||
finally
|
||||
{
|
||||
EndPending(cancellation);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task CloseSessionAsync()
|
||||
{
|
||||
var session = ActiveSession;
|
||||
if (session is null)
|
||||
{
|
||||
SetInformation("No diagnostic session is open.");
|
||||
return;
|
||||
}
|
||||
|
||||
_pending?.Cancel();
|
||||
ActiveSession = null;
|
||||
ResetSessionResults();
|
||||
await session.DisposeAsync();
|
||||
SetInformation($"Session {session.Identity.SessionIdentifier} closed; its isolated virtual state and trace are released.");
|
||||
}
|
||||
|
||||
public void CancelPending() => _pending?.Cancel();
|
||||
|
||||
private CancellationTokenSource BeginPending()
|
||||
{
|
||||
if (_pending is not null)
|
||||
{
|
||||
throw new InvalidOperationException("A diagnostic operation is already pending.");
|
||||
}
|
||||
|
||||
_pending = new CancellationTokenSource();
|
||||
StatusTone = StatusNoticeTone.Information;
|
||||
StatusMessage = "Diagnostic operation is pending. Cancellation remains available.";
|
||||
return _pending;
|
||||
}
|
||||
|
||||
private void EndPending(CancellationTokenSource cancellation)
|
||||
{
|
||||
if (ReferenceEquals(_pending, cancellation))
|
||||
{
|
||||
_pending = null;
|
||||
}
|
||||
|
||||
cancellation.Dispose();
|
||||
}
|
||||
|
||||
private bool IsCurrent(DiagnosticSession session) =>
|
||||
ReferenceEquals(ActiveSession, session) && !session.IsClosed;
|
||||
|
||||
private void ResetSessionResults()
|
||||
{
|
||||
DiscoveredModules = [];
|
||||
DiscoverySummary = null;
|
||||
TroubleCodes = new Dictionary<string, TroubleCodeReadResult>(StringComparer.OrdinalIgnoreCase);
|
||||
Signals = new Dictionary<string, SignalSnapshot>(StringComparer.OrdinalIgnoreCase);
|
||||
OperationMessages = [];
|
||||
}
|
||||
|
||||
private void SetInformation(string message)
|
||||
{
|
||||
StatusTone = StatusNoticeTone.Information;
|
||||
StatusMessage = message;
|
||||
}
|
||||
|
||||
private void SetFailure(string message)
|
||||
{
|
||||
StatusTone = StatusNoticeTone.Error;
|
||||
StatusMessage = message;
|
||||
}
|
||||
|
||||
private void SetOperationFailure(string action, DiagnosticOutcome outcome, string? error)
|
||||
{
|
||||
OperationMessages = [$"{action}: {outcome} — {error ?? "No successful response was received."}"];
|
||||
SetFailure(OperationMessages[0]);
|
||||
}
|
||||
|
||||
private static string? FormatResult(string action, DiagnosticOutcome outcome, string? error) =>
|
||||
outcome == DiagnosticOutcome.PositiveResponse ? null : $"{action}: {outcome} — {error}";
|
||||
|
||||
private static string ReadSyntheticProfile()
|
||||
{
|
||||
using var stream = typeof(DiagnosticPageViewModel).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();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,270 @@
|
|||
@page "/diagnostics"
|
||||
@inject DiagnosticPageViewModel Diagnostics
|
||||
|
||||
<PageTitle>Synthetic diagnostics - AutoForge</PageTitle>
|
||||
|
||||
<h1>Synthetic module diagnostics</h1>
|
||||
<p>
|
||||
This workflow sends synthetic protocol v1 requests through the selected in-process
|
||||
virtual transport. It is not a real vehicle connection, vehicle compatibility
|
||||
determination, live capture or physical operation.
|
||||
</p>
|
||||
|
||||
<StatusNotice Tone="@Diagnostics.StatusTone" Message="@Diagnostics.StatusMessage" />
|
||||
|
||||
@if (Diagnostics.Providers.Count == 0)
|
||||
{
|
||||
<p>No diagnostic provider is available. Replay and physical providers are not substituted.</p>
|
||||
}
|
||||
|
||||
<section aria-labelledby="diagnostic-session-heading">
|
||||
<h2 id="diagnostic-session-heading">Explicit profile and provider selection</h2>
|
||||
<button id="load-synthetic-example" type="button" disabled="@Diagnostics.IsBusy"
|
||||
@onclick="Diagnostics.LoadSyntheticExample">
|
||||
Load synthetic truck example
|
||||
</button>
|
||||
<p>The example import does not select the profile or open a session.</p>
|
||||
|
||||
<label for="diagnostic-profile">Saved profile identifier</label>
|
||||
<select id="diagnostic-profile" @bind="Diagnostics.SelectedProfileIdentifier"
|
||||
disabled="@(Diagnostics.ActiveSession is not null || Diagnostics.IsBusy)">
|
||||
<option value="">Choose an exact saved profile</option>
|
||||
@foreach (var identifier in Diagnostics.AvailableProfiles.Select(profile => profile.ProfileIdentifier).Distinct(StringComparer.OrdinalIgnoreCase))
|
||||
{
|
||||
<option value="@identifier">@identifier</option>
|
||||
}
|
||||
</select>
|
||||
|
||||
<label for="diagnostic-revision">Saved profile revision</label>
|
||||
<select id="diagnostic-revision" @bind="Diagnostics.SelectedProfileRevision"
|
||||
disabled="@(Diagnostics.ActiveSession is not null || Diagnostics.IsBusy || Diagnostics.SelectedProfileIdentifier is null)">
|
||||
<option value="">Choose an exact revision</option>
|
||||
@foreach (var profile in Diagnostics.AvailableProfiles.Where(profile =>
|
||||
StringComparer.OrdinalIgnoreCase.Equals(profile.ProfileIdentifier, Diagnostics.SelectedProfileIdentifier)))
|
||||
{
|
||||
<option value="@profile.Revision">revision @profile.Revision</option>
|
||||
}
|
||||
</select>
|
||||
|
||||
<label for="diagnostic-provider">Diagnostic provider</label>
|
||||
<select id="diagnostic-provider" @bind="Diagnostics.SelectedProviderIdentifier"
|
||||
disabled="@(Diagnostics.ActiveSession is not null || Diagnostics.IsBusy)">
|
||||
<option value="">Choose an explicit provider</option>
|
||||
@foreach (var provider in Diagnostics.Providers)
|
||||
{
|
||||
<option value="@provider.Target.ProviderIdentifier">@provider.Target.ProviderIdentifier (@provider.Target.Kind)</option>
|
||||
}
|
||||
</select>
|
||||
|
||||
<label for="diagnostic-target-kind">Operational target kind</label>
|
||||
<select id="diagnostic-target-kind" @bind="Diagnostics.SelectedTargetKind"
|
||||
disabled="@(Diagnostics.ActiveSession is not null || Diagnostics.IsBusy)">
|
||||
<option value="">Choose an explicit kind</option>
|
||||
<option value="@ExecutionTargetKind.Simulation">Simulation</option>
|
||||
</select>
|
||||
|
||||
@if (Diagnostics.ActiveSession is null)
|
||||
{
|
||||
<button id="open-diagnostic-session" type="button" disabled="@Diagnostics.IsBusy"
|
||||
@onclick="Diagnostics.OpenSessionAsync">
|
||||
Open simulation session
|
||||
</button>
|
||||
}
|
||||
else
|
||||
{
|
||||
<p id="active-diagnostic-session">
|
||||
@Diagnostics.ActiveSession.Identity.Target.Kind target @Diagnostics.ActiveSession.Identity.Target.ProviderIdentifier;
|
||||
session @Diagnostics.ActiveSession.Identity.SessionIdentifier;
|
||||
profile @Diagnostics.ActiveSession.Identity.ProfileIdentifier revision
|
||||
@Diagnostics.ActiveSession.Identity.ProfileRevision;
|
||||
configuration @Diagnostics.ActiveSession.Identity.ConfigurationIdentifier.
|
||||
</p>
|
||||
<button id="discover-modules" type="button" disabled="@Diagnostics.IsBusy"
|
||||
@onclick="Diagnostics.DiscoverAsync">
|
||||
Probe virtual modules
|
||||
</button>
|
||||
<button id="reset-diagnostic-session" type="button" disabled="@Diagnostics.IsBusy"
|
||||
@onclick="Diagnostics.ResetSessionAsync">
|
||||
Reset to synthetic initial state
|
||||
</button>
|
||||
<button id="close-diagnostic-session" type="button" disabled="@Diagnostics.IsBusy"
|
||||
@onclick="Diagnostics.CloseSessionAsync">
|
||||
Close session
|
||||
</button>
|
||||
@if (Diagnostics.IsBusy)
|
||||
{
|
||||
<button id="cancel-diagnostic-operation" type="button" @onclick="Diagnostics.CancelPending">
|
||||
Cancel pending operation
|
||||
</button>
|
||||
}
|
||||
}
|
||||
</section>
|
||||
|
||||
@if (Diagnostics.OperationMessages.Count > 0)
|
||||
{
|
||||
<section aria-labelledby="diagnostic-messages-heading">
|
||||
<h2 id="diagnostic-messages-heading">Operation outcomes</h2>
|
||||
<ul id="diagnostic-operation-messages">
|
||||
@foreach (var message in Diagnostics.OperationMessages)
|
||||
{
|
||||
<li>@message</li>
|
||||
}
|
||||
</ul>
|
||||
</section>
|
||||
}
|
||||
|
||||
@if (Diagnostics.ActiveSession is { } session)
|
||||
{
|
||||
<section aria-labelledby="discovered-modules-heading">
|
||||
<h2 id="discovered-modules-heading">Expected endpoints, validated probes and identified modules</h2>
|
||||
@if (Diagnostics.DiscoverySummary is { } discoverySummary)
|
||||
{
|
||||
<p id="diagnostic-discovery-summary">@discoverySummary</p>
|
||||
}
|
||||
@if (Diagnostics.DiscoveredModules.Count == 0)
|
||||
{
|
||||
<p>Module discovery has not been run for this session.</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<ul id="discovered-modules">
|
||||
@foreach (var module in Diagnostics.DiscoveredModules)
|
||||
{
|
||||
<li data-module="@module.Endpoint.ModuleIdentifier"
|
||||
data-outcome="@module.ProbeOutcome"
|
||||
data-probe-outcome="@module.ProbeOutcome"
|
||||
data-identity-status="@module.IdentityStatus"
|
||||
data-identity-outcome="@module.IdentityOutcome">
|
||||
<h3>@module.Endpoint.ModuleIdentifier at 0x@(module.Endpoint.Address) — Probe: @module.ProbeOutcome; identity: @module.IdentityStatus</h3>
|
||||
@if (module.Identity is { } identity)
|
||||
{
|
||||
<dl>
|
||||
<dt>Role and name</dt>
|
||||
<dd>@identity.Role — @identity.Name</dd>
|
||||
<dt>Hardware/software/firmware/calibration identity</dt>
|
||||
<dd>@(identity.HardwareIdentifier ?? "unknown") / @(identity.SoftwareIdentifier ?? "unknown") / @(identity.FirmwareIdentifier ?? "unknown") / @(identity.CalibrationIdentifier ?? "unknown")</dd>
|
||||
</dl>
|
||||
}
|
||||
else
|
||||
{
|
||||
<p>
|
||||
Identity is unavailable or unverified.
|
||||
@if (module.IdentityOutcome is { } identityOutcome)
|
||||
{
|
||||
<span> Identity exchange outcome: @identityOutcome.</span>
|
||||
}
|
||||
@module.IdentityError
|
||||
@if (module.ProbeSucceeded)
|
||||
{
|
||||
<span> A positive probe confirms only the advertised synthetic services, not identity or authorization.</span>
|
||||
}
|
||||
</p>
|
||||
}
|
||||
|
||||
@if (module.ProbeError is { } probeError)
|
||||
{
|
||||
<p>Probe detail: @probeError</p>
|
||||
}
|
||||
|
||||
@if (module.ProbeSucceeded)
|
||||
{
|
||||
<p>Validated probe advertised virtual services: @string.Join(", ", module.ImplementedServices).</p>
|
||||
}
|
||||
|
||||
@if (module.ImplementedServices.Contains(DiagnosticServices.ReadTroubleCodes, StringComparer.Ordinal) ||
|
||||
module.ImplementedServices.Contains(DiagnosticServices.ReadSignals, StringComparer.Ordinal))
|
||||
{
|
||||
<button type="button" disabled="@(Diagnostics.IsBusy || module.Identity is null)"
|
||||
@onclick="() => Diagnostics.ReadModuleAsync(module.Endpoint.ModuleIdentifier)">
|
||||
Read DTCs and static signals
|
||||
</button>
|
||||
}
|
||||
@if (module.ImplementedServices.Contains(DiagnosticServices.ClearTroubleCodes, StringComparer.Ordinal))
|
||||
{
|
||||
<button type="button" disabled="@(Diagnostics.IsBusy || module.Identity is null)"
|
||||
@onclick="() => Diagnostics.ClearTroubleCodesAsync(module.Endpoint.ModuleIdentifier)">
|
||||
Clear this module's virtual DTCs
|
||||
</button>
|
||||
}
|
||||
@if (module.Identity is null &&
|
||||
(module.ImplementedServices.Contains(DiagnosticServices.ReadTroubleCodes, StringComparer.Ordinal) ||
|
||||
module.ImplementedServices.Contains(DiagnosticServices.ReadSignals, StringComparer.Ordinal) ||
|
||||
module.ImplementedServices.Contains(DiagnosticServices.ClearTroubleCodes, StringComparer.Ordinal)))
|
||||
{
|
||||
<p>Identity-dependent read and clear actions are disabled until profile identity is validated.</p>
|
||||
}
|
||||
|
||||
@if (Diagnostics.TroubleCodes.TryGetValue(module.Endpoint.ModuleIdentifier, out var dtcs))
|
||||
{
|
||||
<h4>Synthetic DTCs returned by this module</h4>
|
||||
@if (dtcs.Codes.Count == 0)
|
||||
{
|
||||
<p>Valid diagnostic response: no DTCs are currently stored in this virtual module.</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<ul>
|
||||
@foreach (var code in dtcs.Codes)
|
||||
{
|
||||
<li>@(code.Code) — @(code.Description) (source @(code.SourceModuleIdentifier))</li>
|
||||
}
|
||||
</ul>
|
||||
}
|
||||
}
|
||||
|
||||
@if (Diagnostics.Signals.TryGetValue(module.Endpoint.ModuleIdentifier, out var signals))
|
||||
{
|
||||
<h4>Static synthetic signal snapshot</h4>
|
||||
<ul>
|
||||
@foreach (var signal in signals.Signals)
|
||||
{
|
||||
<li data-signal="@signal.SignalIdentifier">
|
||||
@signal.SignalIdentifier: @signal.Value (@signal.Unit), @signal.Quality,
|
||||
logical tick @signal.LogicalTimeTicks, origin @signal.Origin,
|
||||
source @signal.ModuleIdentifier.
|
||||
</li>
|
||||
}
|
||||
</ul>
|
||||
}
|
||||
</li>
|
||||
}
|
||||
</ul>
|
||||
}
|
||||
</section>
|
||||
|
||||
<section aria-labelledby="diagnostic-trace-heading">
|
||||
<h2 id="diagnostic-trace-heading">Bounded session communication trace</h2>
|
||||
<p id="trace-loss">Retained @session.Trace.Entries.Count records; dropped @session.Trace.DroppedRecordCount.</p>
|
||||
<ol id="diagnostic-trace">
|
||||
@foreach (var entry in session.Trace.Entries)
|
||||
{
|
||||
<li data-outcome="@entry.Outcome" data-service="@entry.Service">
|
||||
<strong>@entry.Outcome — @entry.Service</strong>;
|
||||
@entry.ModuleIdentifier at 0x@(entry.Address);
|
||||
correlation @entry.CorrelationIdentifier;
|
||||
logical ticks @entry.StartLogicalTicks–@entry.EndLogicalTicks.
|
||||
@if (entry.DecodedSummary is not null)
|
||||
{
|
||||
<span>Decoded: @entry.DecodedSummary.</span>
|
||||
}
|
||||
@if (entry.Error is not null)
|
||||
{
|
||||
<span>Error: @entry.Error</span>
|
||||
}
|
||||
<details>
|
||||
<summary>Raw synthetic protocol v1 payloads</summary>
|
||||
<pre>Request: @System.Text.Encoding.UTF8.GetString(entry.RequestPayload.Span)</pre>
|
||||
@if (entry.ResponsePayload is { } response)
|
||||
{
|
||||
<pre>Response: @System.Text.Encoding.UTF8.GetString(response.Span)</pre>
|
||||
}
|
||||
else
|
||||
{
|
||||
<p>No response payload was received.</p>
|
||||
}
|
||||
</details>
|
||||
</li>
|
||||
}
|
||||
</ol>
|
||||
</section>
|
||||
}
|
||||
|
|
@ -7,6 +7,7 @@
|
|||
<NavLink href="/" Match="NavLinkMatch.All">Home</NavLink>
|
||||
<NavLink href="/execution-targets">Target selection</NavLink>
|
||||
<NavLink href="/vehicle-profiles">Vehicle profiles</NavLink>
|
||||
<NavLink href="/diagnostics">Synthetic diagnostics</NavLink>
|
||||
</nav>
|
||||
</header>
|
||||
|
||||
|
|
|
|||
|
|
@ -3,6 +3,8 @@
|
|||
@using Microsoft.AspNetCore.Components.Web
|
||||
@using AutoForge.Components
|
||||
@using AutoForge.Core.ExecutionTargets
|
||||
@using AutoForge.Diagnostics
|
||||
@using AutoForge.UI.Features.Foundation
|
||||
@using AutoForge.UI.Features.ExecutionTargets.SelectExecutionTarget
|
||||
@using AutoForge.UI.Features.Vehicles.Diagnostics
|
||||
@using AutoForge.UI.Features.Vehicles.Profiles
|
||||
|
|
|
|||
|
|
@ -7,5 +7,7 @@
|
|||
<Project Path="AutoForge.Client/AutoForge.Client.csproj" />
|
||||
<Project Path="AutoForge.Components/AutoForge.Components.csproj" />
|
||||
<Project Path="AutoForge.Core/AutoForge.Core.csproj" />
|
||||
<Project Path="AutoForge.Diagnostics/AutoForge.Diagnostics.csproj" />
|
||||
<Project Path="AutoForge.Simulation/AutoForge.Simulation.csproj" />
|
||||
<Project Path="AutoForge.UI/AutoForge.UI.csproj" />
|
||||
</Solution>
|
||||
|
|
|
|||
|
|
@ -25,6 +25,8 @@
|
|||
<ProjectReference Include="..\..\AutoForge.Application\AutoForge.Application.csproj" />
|
||||
<ProjectReference Include="..\..\AutoForge.Components\AutoForge.Components.csproj" />
|
||||
<ProjectReference Include="..\..\AutoForge.UI\AutoForge.UI.csproj" />
|
||||
<ProjectReference Include="..\..\AutoForge.Diagnostics\AutoForge.Diagnostics.csproj" />
|
||||
<ProjectReference Include="..\..\AutoForge.Simulation\AutoForge.Simulation.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load Diff
|
|
@ -0,0 +1,407 @@
|
|||
using AutoForge.Application.Features.Vehicles.Diagnostics;
|
||||
using AutoForge.Application.Features.Vehicles.Profiles;
|
||||
using AutoForge.Components;
|
||||
using AutoForge.Core.ExecutionTargets;
|
||||
using AutoForge.Diagnostics;
|
||||
using AutoForge.Simulation;
|
||||
using AutoForge.UI;
|
||||
using AutoForge.UI.Features.ExecutionTargets.SelectExecutionTarget;
|
||||
using AutoForge.UI.Features.Vehicles.Diagnostics;
|
||||
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 DiagnosticUiCompositionTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task DiagnosticRoute_ImportsOnlyOnActionAndRendersRealSessionDataTraceAndClearReadback()
|
||||
{
|
||||
using var provider = CreateProvider("http://localhost/diagnostics");
|
||||
var profiles = provider.GetRequiredService<IVehicleProfileService>();
|
||||
var diagnostics = provider.GetRequiredService<DiagnosticPageViewModel>();
|
||||
|
||||
var initialHtml = await RenderRoutesAsync(provider);
|
||||
Assert.Contains("Synthetic module diagnostics", initialHtml);
|
||||
Assert.Contains("Load synthetic truck example", initialHtml);
|
||||
Assert.Contains("Choose an exact saved profile", initialHtml);
|
||||
Assert.Empty(profiles.List());
|
||||
Assert.Null(diagnostics.ActiveSession);
|
||||
|
||||
diagnostics.LoadSyntheticExample();
|
||||
var loaded = Assert.Single(profiles.List());
|
||||
Assert.Null(diagnostics.SelectedProfileIdentifier);
|
||||
diagnostics.SelectedProfileIdentifier = loaded.ProfileIdentifier;
|
||||
diagnostics.SelectedProfileRevision = loaded.Revision;
|
||||
diagnostics.SelectedProviderIdentifier = SimulatedDiagnosticTransportFactory.ProviderIdentifier;
|
||||
diagnostics.SelectedTargetKind = ExecutionTargetKind.Simulation;
|
||||
|
||||
await diagnostics.OpenSessionAsync();
|
||||
Assert.NotNull(diagnostics.ActiveSession);
|
||||
await diagnostics.DiscoverAsync();
|
||||
await diagnostics.ReadModuleAsync("module.engine.primary");
|
||||
var readHtml = await RenderRoutesAsync(provider);
|
||||
|
||||
Assert.Contains("Expected endpoints, validated probes and identified modules", readHtml);
|
||||
Assert.Contains("Synthetic Engine Controller", readHtml);
|
||||
Assert.Contains("at 0x10", readHtml);
|
||||
Assert.Contains("at 0x20", readHtml);
|
||||
Assert.Contains("SYN-P0123", readHtml);
|
||||
Assert.Contains("synthetic.engine.speed", readHtml);
|
||||
Assert.Contains("850", readHtml);
|
||||
Assert.Contains("SYNTHETIC_STATIC", readHtml);
|
||||
Assert.Contains("Bounded session communication trace", readHtml);
|
||||
Assert.Contains("0x10;", readHtml);
|
||||
Assert.Contains("Raw synthetic protocol v1 payloads", readHtml);
|
||||
Assert.Contains("data-outcome=\"PositiveResponse\"", readHtml);
|
||||
Assert.Contains("Configured endpoint did not respond", readHtml);
|
||||
|
||||
await diagnostics.ClearTroubleCodesAsync("module.engine.primary");
|
||||
var clearedHtml = await RenderRoutesAsync(provider);
|
||||
Assert.Contains("Fresh readback verified that no DTCs remain", clearedHtml);
|
||||
Assert.Contains("no DTCs are currently stored in this virtual module", clearedHtml);
|
||||
Assert.Contains("No physical write was performed", diagnostics.StatusMessage);
|
||||
|
||||
await diagnostics.CloseSessionAsync();
|
||||
var closedHtml = await RenderRoutesAsync(provider);
|
||||
Assert.DoesNotContain("active-diagnostic-session", closedHtml);
|
||||
Assert.Contains("closed; its isolated virtual state and trace are released", diagnostics.StatusMessage);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DiagnosticRoute_RendersProbeOnlyPartialIdentityAsUnverifiedAndActionsDisabled()
|
||||
{
|
||||
var definitions = WithoutService(
|
||||
SyntheticDiagnosticExamples.CreateDefinitions(),
|
||||
"module.engine.primary",
|
||||
DiagnosticServices.ReadIdentity);
|
||||
using var provider = CreateProvider(
|
||||
"http://localhost/diagnostics",
|
||||
new SimulatedDiagnosticTransportFactory(definitions));
|
||||
provider.GetRequiredService<IVehicleProfileService>().Import(ReadFixture("synthetic-truck-baseline.json"));
|
||||
var diagnostics = provider.GetRequiredService<DiagnosticPageViewModel>();
|
||||
SelectTruck(diagnostics);
|
||||
await diagnostics.OpenSessionAsync();
|
||||
await diagnostics.DiscoverAsync();
|
||||
|
||||
var html = await RenderRoutesAsync(provider);
|
||||
var engineRowStart = html.IndexOf("data-module=\"module.engine.primary\"", StringComparison.Ordinal);
|
||||
Assert.True(engineRowStart >= 0);
|
||||
var engineRowEnd = html.IndexOf("</li>", engineRowStart, StringComparison.Ordinal);
|
||||
Assert.True(engineRowEnd > engineRowStart);
|
||||
var engineRow = html[engineRowStart..engineRowEnd];
|
||||
|
||||
Assert.Contains(
|
||||
"Expected endpoints: 3; validated positive probes: 2; profile-verified identities: 1.",
|
||||
html);
|
||||
Assert.Contains("data-probe-outcome=\"PositiveResponse\"", engineRow);
|
||||
Assert.Contains("data-identity-status=\"NotAttempted\"", engineRow);
|
||||
Assert.Contains("Identity is unavailable or unverified.", engineRow);
|
||||
Assert.Contains("was not advertised", engineRow);
|
||||
Assert.Contains(DiagnosticServices.Probe, engineRow);
|
||||
Assert.Contains(DiagnosticServices.ClearTroubleCodes, engineRow);
|
||||
Assert.Contains(DiagnosticServices.ReadTroubleCodes, engineRow);
|
||||
Assert.Contains("Identity-dependent read and clear actions are disabled", engineRow);
|
||||
Assert.Contains("<button type=\"button\" disabled", engineRow);
|
||||
Assert.DoesNotContain("Synthetic Engine Controller", engineRow);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecutionTargetRoute_ShowsRealProviderButMetadataResolutionRemainsSeparate()
|
||||
{
|
||||
using var provider = CreateProvider("http://localhost/execution-targets");
|
||||
var selection = provider.GetRequiredService<ExecutionTargetSelectionViewModel>();
|
||||
selection.ProviderIdentifier = SimulatedDiagnosticTransportFactory.ProviderIdentifier;
|
||||
selection.SelectedKind = ExecutionTargetKind.Simulation;
|
||||
selection.Select();
|
||||
|
||||
var html = await RenderRoutesAsync(provider);
|
||||
|
||||
Assert.Contains("autoforge.simulation.synthetic (Simulation)", html);
|
||||
Assert.Contains("Resolved registered metadata", html);
|
||||
Assert.Contains("No connection or operation was performed", html);
|
||||
Assert.DoesNotContain("active-diagnostic-session", html);
|
||||
Assert.Single(provider.GetRequiredService<IDiagnosticSessionService>().Providers);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DiagnosticRoute_RendersDeterministicTimeoutAsAnIncompleteProbe()
|
||||
{
|
||||
var definitions = WithLatency(
|
||||
SyntheticDiagnosticExamples.CreateDefinitions(),
|
||||
"module.engine.primary",
|
||||
6);
|
||||
using var provider = CreateProvider(
|
||||
"http://localhost/diagnostics",
|
||||
new SimulatedDiagnosticTransportFactory(definitions));
|
||||
var profiles = provider.GetRequiredService<IVehicleProfileService>();
|
||||
profiles.Import(ReadFixture("synthetic-truck-baseline.json"));
|
||||
var diagnostics = provider.GetRequiredService<DiagnosticPageViewModel>();
|
||||
SelectTruck(diagnostics);
|
||||
await diagnostics.OpenSessionAsync();
|
||||
await diagnostics.DiscoverAsync();
|
||||
|
||||
var html = await RenderRoutesAsync(provider);
|
||||
|
||||
Assert.Contains("data-module=\"module.engine.primary\" data-outcome=\"Timeout\"", html);
|
||||
Assert.Contains("Virtual response latency 6 exceeded deadline 5", html);
|
||||
Assert.Contains("data-outcome=\"Timeout\"", html);
|
||||
Assert.DoesNotContain("Synthetic Engine Controller", html);
|
||||
Assert.Contains("No response payload was received.", html);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DiagnosticRoute_CancelPendingShowsCancelledTraceAndSuppressesStaleSuccess()
|
||||
{
|
||||
var definitions = WithFault(
|
||||
SyntheticDiagnosticExamples.CreateDefinitions(),
|
||||
"module.engine.primary",
|
||||
DiagnosticServices.Probe,
|
||||
SimulatedFault.HoldUntilCancelled);
|
||||
var factory = new SimulatedDiagnosticTransportFactory(definitions);
|
||||
using var provider = CreateProvider("http://localhost/diagnostics", factory);
|
||||
var profiles = provider.GetRequiredService<IVehicleProfileService>();
|
||||
profiles.Import(ReadFixture("synthetic-truck-baseline.json"));
|
||||
var diagnostics = provider.GetRequiredService<DiagnosticPageViewModel>();
|
||||
SelectTruck(diagnostics);
|
||||
await diagnostics.OpenSessionAsync();
|
||||
|
||||
var discovery = diagnostics.DiscoverAsync();
|
||||
await factory.WaitForPendingRequestForTestAsync(diagnostics.ActiveSession!.Identity.SessionIdentifier);
|
||||
var pendingHtml = await RenderRoutesAsync(provider);
|
||||
Assert.Contains("cancel-diagnostic-operation", pendingHtml);
|
||||
diagnostics.CancelPending();
|
||||
await discovery;
|
||||
var cancelledHtml = await RenderRoutesAsync(provider);
|
||||
|
||||
Assert.Contains("Module discovery was cancelled", cancelledHtml);
|
||||
Assert.Contains("data-outcome=\"Cancelled\"", cancelledHtml);
|
||||
Assert.Contains("No response payload was received.", cancelledHtml);
|
||||
Assert.DoesNotContain("Synthetic Engine Controller", cancelledHtml);
|
||||
await diagnostics.CloseSessionAsync();
|
||||
var closedHtml = await RenderRoutesAsync(provider);
|
||||
Assert.DoesNotContain("active-diagnostic-session", closedHtml);
|
||||
Assert.DoesNotContain("discovered-modules", closedHtml);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DiagnosticRoute_CancellingPendingIdentityKeepsPartialProbeAndThenCloseClearsIt()
|
||||
{
|
||||
var definitions = WithFault(
|
||||
SyntheticDiagnosticExamples.CreateDefinitions(),
|
||||
"module.engine.primary",
|
||||
DiagnosticServices.ReadIdentity,
|
||||
SimulatedFault.HoldUntilCancelled);
|
||||
var factory = new SimulatedDiagnosticTransportFactory(definitions);
|
||||
using var provider = CreateProvider("http://localhost/diagnostics", factory);
|
||||
provider.GetRequiredService<IVehicleProfileService>().Import(ReadFixture("synthetic-truck-baseline.json"));
|
||||
var diagnostics = provider.GetRequiredService<DiagnosticPageViewModel>();
|
||||
SelectTruck(diagnostics);
|
||||
await diagnostics.OpenSessionAsync();
|
||||
|
||||
var discovery = diagnostics.DiscoverAsync();
|
||||
await factory.WaitForPendingRequestForTestAsync(diagnostics.ActiveSession!.Identity.SessionIdentifier);
|
||||
diagnostics.CancelPending();
|
||||
await discovery;
|
||||
|
||||
var cancelledHtml = await RenderRoutesAsync(provider);
|
||||
var engineRowStart = cancelledHtml.IndexOf("data-module=\"module.engine.primary\"", StringComparison.Ordinal);
|
||||
Assert.True(engineRowStart >= 0);
|
||||
var engineRowEnd = cancelledHtml.IndexOf("</li>", engineRowStart, StringComparison.Ordinal);
|
||||
Assert.True(engineRowEnd > engineRowStart);
|
||||
var engineRow = cancelledHtml[engineRowStart..engineRowEnd];
|
||||
|
||||
Assert.Contains("Module discovery was cancelled", diagnostics.StatusMessage);
|
||||
Assert.Contains("Expected endpoints: 3; validated positive probes: 1; profile-verified identities: 0.", cancelledHtml);
|
||||
Assert.Contains("data-probe-outcome=\"PositiveResponse\"", engineRow);
|
||||
Assert.Contains("data-identity-status=\"Unavailable\"", engineRow);
|
||||
Assert.Contains("data-identity-outcome=\"Cancelled\"", engineRow);
|
||||
Assert.Contains("Identity exchange outcome: Cancelled", engineRow);
|
||||
Assert.Contains(DiagnosticServices.ClearTroubleCodes, engineRow);
|
||||
Assert.Contains("<button type=\"button\" disabled", engineRow);
|
||||
Assert.DoesNotContain("Synthetic Engine Controller", engineRow);
|
||||
Assert.DoesNotContain("Synthetic Engine Controller", cancelledHtml);
|
||||
|
||||
var traceCount = diagnostics.ActiveSession!.Trace.Entries.Count;
|
||||
await diagnostics.ReadModuleAsync("module.engine.primary");
|
||||
Assert.Contains("profile-verified identity", diagnostics.StatusMessage);
|
||||
await diagnostics.ClearTroubleCodesAsync("module.engine.primary");
|
||||
Assert.Contains("profile-verified identity", diagnostics.StatusMessage);
|
||||
Assert.Equal(traceCount, diagnostics.ActiveSession.Trace.Entries.Count);
|
||||
|
||||
await diagnostics.CloseSessionAsync();
|
||||
var closedHtml = await RenderRoutesAsync(provider);
|
||||
Assert.DoesNotContain("active-diagnostic-session", closedHtml);
|
||||
Assert.DoesNotContain("discovered-modules", closedHtml);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DiagnosticRoute_ClearAcknowledgementWithRemainingCodesIsNotReportedVerified()
|
||||
{
|
||||
var transportExchange = async (
|
||||
IDiagnosticTransport inner,
|
||||
SyntheticDiagnosticRequest request,
|
||||
ReadOnlyMemory<byte> payload,
|
||||
CancellationToken token) =>
|
||||
{
|
||||
if (request.Service == DiagnosticServices.ClearTroubleCodes)
|
||||
{
|
||||
return new TransportReply(
|
||||
TransportOutcome.Response,
|
||||
SyntheticProtocolV1.EncodePositiveResponse(
|
||||
request,
|
||||
new { moduleIdentifier = "module.engine.primary", clearedCount = 1 }),
|
||||
1);
|
||||
}
|
||||
|
||||
return await inner.SendAsync(payload, token);
|
||||
};
|
||||
var simulation = new SimulatedDiagnosticTransportFactory(SyntheticDiagnosticExamples.CreateDefinitions());
|
||||
var factory = new RewritingDiagnosticTransportFactory(simulation, transportExchange);
|
||||
using var provider = CreateProvider("http://localhost/diagnostics", factory);
|
||||
var profiles = provider.GetRequiredService<IVehicleProfileService>();
|
||||
profiles.Import(ReadFixture("synthetic-truck-baseline.json"));
|
||||
var diagnostics = provider.GetRequiredService<DiagnosticPageViewModel>();
|
||||
SelectTruck(diagnostics);
|
||||
await diagnostics.OpenSessionAsync();
|
||||
await diagnostics.DiscoverAsync();
|
||||
|
||||
await diagnostics.ClearTroubleCodesAsync("module.engine.primary");
|
||||
var html = await RenderRoutesAsync(provider);
|
||||
|
||||
Assert.Equal(StatusNoticeTone.Error, diagnostics.StatusTone);
|
||||
Assert.Contains("SYN-P0123", html);
|
||||
Assert.Contains("verification", diagnostics.StatusMessage, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("was cleared and re-read", diagnostics.StatusMessage, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.Contains("No physical write was performed", diagnostics.StatusMessage);
|
||||
Assert.Equal(["SYN-P0123"], simulation.ReadVirtualDtcStateForTest(
|
||||
diagnostics.ActiveSession!.Identity.SessionIdentifier, "module.engine.primary"));
|
||||
}
|
||||
|
||||
private static ServiceProvider CreateProvider(
|
||||
string uri,
|
||||
IDiagnosticTransportFactory? factory = null)
|
||||
{
|
||||
var services = new ServiceCollection();
|
||||
services.AddLogging();
|
||||
services.AddAutoForgeVehicleProfiles();
|
||||
services.AddAutoForgeDiagnostics([factory ?? new SimulatedDiagnosticTransportFactory(
|
||||
SyntheticDiagnosticExamples.CreateDefinitions())]);
|
||||
services.AddAutoForgeUi();
|
||||
services.AddSingleton<NavigationManager>(new TestNavigationManager(uri));
|
||||
services.AddSingleton<INavigationInterception, TestNavigationInterception>();
|
||||
services.AddSingleton<IScrollToLocationHash, TestScrollToLocationHash>();
|
||||
return services.BuildServiceProvider(new ServiceProviderOptions { ValidateOnBuild = true });
|
||||
}
|
||||
|
||||
private static void SelectTruck(DiagnosticPageViewModel diagnostics)
|
||||
{
|
||||
diagnostics.SelectedProfileIdentifier = "autoforge.synthetic.test-truck";
|
||||
diagnostics.SelectedProfileRevision = 1;
|
||||
diagnostics.SelectedProviderIdentifier = SimulatedDiagnosticTransportFactory.ProviderIdentifier;
|
||||
diagnostics.SelectedTargetKind = ExecutionTargetKind.Simulation;
|
||||
}
|
||||
|
||||
private static IReadOnlyList<SimulationDefinition> WithFault(
|
||||
IReadOnlyList<SimulationDefinition> definitions,
|
||||
string moduleIdentifier,
|
||||
string service,
|
||||
SimulatedFault fault) =>
|
||||
Array.AsReadOnly(definitions.Select(definition => new SimulationDefinition(
|
||||
definition.ProfileIdentifier,
|
||||
definition.ProfileRevision,
|
||||
definition.Modules.Select(module =>
|
||||
{
|
||||
var faults = module.Faults.ToDictionary(pair => pair.Key, pair => pair.Value, StringComparer.Ordinal);
|
||||
if (StringComparer.OrdinalIgnoreCase.Equals(module.ModuleIdentifier, moduleIdentifier))
|
||||
{
|
||||
faults[service] = fault;
|
||||
}
|
||||
|
||||
return CopyModule(module, faults: faults);
|
||||
}))).ToArray());
|
||||
|
||||
private static IReadOnlyList<SimulationDefinition> WithoutService(
|
||||
IReadOnlyList<SimulationDefinition> definitions,
|
||||
string moduleIdentifier,
|
||||
string service) =>
|
||||
Array.AsReadOnly(definitions.Select(definition => new SimulationDefinition(
|
||||
definition.ProfileIdentifier,
|
||||
definition.ProfileRevision,
|
||||
definition.Modules.Select(module => CopyModule(
|
||||
module,
|
||||
services: StringComparer.OrdinalIgnoreCase.Equals(module.ModuleIdentifier, moduleIdentifier)
|
||||
? module.ImplementedServices.Where(candidate => !StringComparer.Ordinal.Equals(candidate, service)).ToArray()
|
||||
: module.ImplementedServices)))).ToArray());
|
||||
|
||||
private static IReadOnlyList<SimulationDefinition> WithLatency(
|
||||
IReadOnlyList<SimulationDefinition> definitions,
|
||||
string moduleIdentifier,
|
||||
long responseLatencyTicks) =>
|
||||
Array.AsReadOnly(definitions.Select(definition => new SimulationDefinition(
|
||||
definition.ProfileIdentifier,
|
||||
definition.ProfileRevision,
|
||||
definition.Modules.Select(module => CopyModule(
|
||||
module,
|
||||
responseLatencyTicks: StringComparer.OrdinalIgnoreCase.Equals(module.ModuleIdentifier, moduleIdentifier)
|
||||
? responseLatencyTicks
|
||||
: module.ResponseLatencyTicks)))).ToArray());
|
||||
|
||||
private static VirtualModuleDefinition CopyModule(
|
||||
VirtualModuleDefinition module,
|
||||
IReadOnlyDictionary<string, SimulatedFault>? faults = null,
|
||||
long? responseLatencyTicks = null,
|
||||
IEnumerable<string>? services = null) =>
|
||||
new(
|
||||
module.ModuleIdentifier,
|
||||
module.Address,
|
||||
module.Identity,
|
||||
services ?? module.ImplementedServices,
|
||||
module.InitialTroubleCodes,
|
||||
module.Signals,
|
||||
faults ?? module.Faults,
|
||||
responseLatencyTicks ?? module.ResponseLatencyTicks);
|
||||
|
||||
private static string ReadFixture(string name) =>
|
||||
File.ReadAllText(Path.Combine(AppContext.BaseDirectory, "Fixtures", name));
|
||||
|
||||
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<AutoForge.UI.Routes>();
|
||||
return component.ToHtmlString();
|
||||
});
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
|
@ -17,7 +17,7 @@ public sealed class ProjectGraphTests
|
|||
.Select(path => Path.GetFullPath(Path.Combine(Path.GetDirectoryName(solutionPath)!, path!)))
|
||||
.ToArray();
|
||||
|
||||
Assert.Equal(7, projectPaths.Length);
|
||||
Assert.Equal(9, projectPaths.Length);
|
||||
|
||||
var projects = projectPaths.ToDictionary(
|
||||
path => Path.GetFileNameWithoutExtension(path),
|
||||
|
|
@ -31,29 +31,37 @@ public sealed class ProjectGraphTests
|
|||
"AutoForge.Client",
|
||||
"AutoForge.Components",
|
||||
"AutoForge.Core",
|
||||
"AutoForge.Diagnostics",
|
||||
"AutoForge.IntegrationTests",
|
||||
"AutoForge.Simulation",
|
||||
"AutoForge.UI",
|
||||
"AutoForge.UnitTests"
|
||||
},
|
||||
projects.Keys.Order(StringComparer.Ordinal));
|
||||
|
||||
AssertReferences(projects, "AutoForge.Core");
|
||||
AssertReferences(projects, "AutoForge.Application", "AutoForge.Core");
|
||||
AssertReferences(projects, "AutoForge.Diagnostics", "AutoForge.Core");
|
||||
AssertReferences(projects, "AutoForge.Simulation", "AutoForge.Core", "AutoForge.Diagnostics");
|
||||
AssertReferences(projects, "AutoForge.Application", "AutoForge.Core", "AutoForge.Diagnostics");
|
||||
AssertReferences(projects, "AutoForge.Components");
|
||||
AssertReferences(projects, "AutoForge.UI", "AutoForge.Application", "AutoForge.Components");
|
||||
AssertReferences(projects, "AutoForge.Client", "AutoForge.Application", "AutoForge.UI");
|
||||
AssertReferences(projects, "AutoForge.UI", "AutoForge.Application", "AutoForge.Components", "AutoForge.Diagnostics");
|
||||
AssertReferences(projects, "AutoForge.Client", "AutoForge.Application", "AutoForge.Simulation", "AutoForge.UI");
|
||||
AssertReferences(
|
||||
projects,
|
||||
"AutoForge.UnitTests",
|
||||
"AutoForge.Application",
|
||||
"AutoForge.Components",
|
||||
"AutoForge.Core");
|
||||
"AutoForge.Core",
|
||||
"AutoForge.Diagnostics",
|
||||
"AutoForge.Simulation");
|
||||
AssertReferences(
|
||||
projects,
|
||||
"AutoForge.IntegrationTests",
|
||||
"AutoForge.Application",
|
||||
"AutoForge.Components",
|
||||
"AutoForge.Core",
|
||||
"AutoForge.Diagnostics",
|
||||
"AutoForge.Simulation",
|
||||
"AutoForge.UI");
|
||||
|
||||
var executables = projects
|
||||
|
|
|
|||
|
|
@ -0,0 +1,37 @@
|
|||
using AutoForge.Core.Vehicles;
|
||||
using AutoForge.Diagnostics;
|
||||
|
||||
namespace AutoForge.IntegrationTests;
|
||||
|
||||
internal sealed class RewritingDiagnosticTransportFactory(
|
||||
IDiagnosticTransportFactory inner,
|
||||
Func<IDiagnosticTransport, SyntheticDiagnosticRequest, ReadOnlyMemory<byte>, CancellationToken, Task<TransportReply>> exchange)
|
||||
: IDiagnosticTransportFactory
|
||||
{
|
||||
public DiagnosticProviderDescriptor Descriptor => inner.Descriptor;
|
||||
|
||||
public IDiagnosticTransport OpenTransport(VehicleProfile profile, DiagnosticSessionIdentity identity) =>
|
||||
new RewritingDiagnosticTransport(inner.OpenTransport(profile, identity), exchange);
|
||||
|
||||
private sealed class RewritingDiagnosticTransport(
|
||||
IDiagnosticTransport innerTransport,
|
||||
Func<IDiagnosticTransport, SyntheticDiagnosticRequest, ReadOnlyMemory<byte>, CancellationToken, Task<TransportReply>> exchange)
|
||||
: IDiagnosticTransport
|
||||
{
|
||||
public IReadOnlyList<DiagnosticEndpoint> ExpectedEndpoints => innerTransport.ExpectedEndpoints;
|
||||
|
||||
public async ValueTask<TransportReply> SendAsync(
|
||||
ReadOnlyMemory<byte> request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
if (!SyntheticProtocolV1.TryDecodeRequest(request, out var decoded) || decoded is null)
|
||||
{
|
||||
return await innerTransport.SendAsync(request, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return await exchange(innerTransport, decoded, request, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
public ValueTask DisposeAsync() => innerTransport.DisposeAsync();
|
||||
}
|
||||
}
|
||||
|
|
@ -1,5 +1,6 @@
|
|||
using AutoForge.Application.ExecutionTargets;
|
||||
using AutoForge.Application.Features.Vehicles.Profiles;
|
||||
using AutoForge.Application.Features.Vehicles.Diagnostics;
|
||||
using AutoForge.Core.ExecutionTargets;
|
||||
using AutoForge.UI;
|
||||
using AutoForge.UI.Features.ExecutionTargets.SelectExecutionTarget;
|
||||
|
|
@ -16,14 +17,14 @@ public sealed class UiCompositionTests
|
|||
[Fact]
|
||||
public async Task Routes_HomePageUsesReusableStatusNoticeAndExplainsCurrentScope()
|
||||
{
|
||||
using var provider = CreateProvider([], "http://localhost/");
|
||||
using var provider = CreateDiagnosticProvider("http://localhost/");
|
||||
|
||||
var html = await RenderRoutesAsync(provider);
|
||||
|
||||
Assert.Contains("<h1>AutoForge foundation</h1>", html);
|
||||
Assert.Contains("Review execution-target selection", html);
|
||||
Assert.Contains("status-notice--information", html);
|
||||
Assert.Contains("Simulation, diagnostics and hardware operations are not implemented.", html);
|
||||
Assert.Contains("synthetic diagnostic sessions with static module data", html);
|
||||
Assert.Contains("Target selection is metadata only", html);
|
||||
}
|
||||
|
||||
|
|
@ -120,7 +121,7 @@ public sealed class UiCompositionTests
|
|||
Assert.Contains("Provider 'synthetic.selected' is registered for Simulation", html);
|
||||
Assert.Contains("not the requested PhysicalHardware", html);
|
||||
Assert.Contains("no fallback is allowed", html);
|
||||
Assert.DoesNotContain("data-provider=", html);
|
||||
Assert.DoesNotContain("data-kind=", html);
|
||||
Assert.Null(selection.SelectedDescriptor);
|
||||
}
|
||||
|
||||
|
|
@ -152,6 +153,21 @@ public sealed class UiCompositionTests
|
|||
return services.BuildServiceProvider();
|
||||
}
|
||||
|
||||
private static ServiceProvider CreateDiagnosticProvider(string uri)
|
||||
{
|
||||
var services = new ServiceCollection();
|
||||
services.AddLogging();
|
||||
services.AddAutoForgeVehicleProfiles();
|
||||
services.AddAutoForgeDiagnostics(
|
||||
[new AutoForge.Simulation.SimulatedDiagnosticTransportFactory(
|
||||
AutoForge.Simulation.SyntheticDiagnosticExamples.CreateDefinitions())]);
|
||||
services.AddAutoForgeUi();
|
||||
services.AddSingleton<NavigationManager>(new TestNavigationManager(uri));
|
||||
services.AddSingleton<INavigationInterception, TestNavigationInterception>();
|
||||
services.AddSingleton<IScrollToLocationHash, TestScrollToLocationHash>();
|
||||
return services.BuildServiceProvider();
|
||||
}
|
||||
|
||||
private static async Task<string> RenderRoutesAsync(IServiceProvider services)
|
||||
{
|
||||
await using var renderer = new HtmlRenderer(
|
||||
|
|
|
|||
|
|
@ -24,6 +24,8 @@
|
|||
<ProjectReference Include="..\..\AutoForge.Components\AutoForge.Components.csproj" />
|
||||
<ProjectReference Include="..\..\AutoForge.Core\AutoForge.Core.csproj" />
|
||||
<ProjectReference Include="..\..\AutoForge.Application\AutoForge.Application.csproj" />
|
||||
<ProjectReference Include="..\..\AutoForge.Diagnostics\AutoForge.Diagnostics.csproj" />
|
||||
<ProjectReference Include="..\..\AutoForge.Simulation\AutoForge.Simulation.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
|
@ -0,0 +1,232 @@
|
|||
using AutoForge.Core.ExecutionTargets;
|
||||
using AutoForge.Diagnostics;
|
||||
using System.Text;
|
||||
using System.Text.Json.Nodes;
|
||||
|
||||
namespace AutoForge.UnitTests;
|
||||
|
||||
public sealed class SyntheticDiagnosticsContractTests
|
||||
{
|
||||
[Fact]
|
||||
public void SyntheticProtocolV1_RoundTripsRequestAndPreservesWireFields()
|
||||
{
|
||||
var request = new SyntheticDiagnosticRequest(
|
||||
"session-01",
|
||||
"profile.test",
|
||||
3,
|
||||
"profile:profile.test@revision:3",
|
||||
"correlation-01",
|
||||
"2a",
|
||||
DiagnosticServices.ReadTroubleCodes,
|
||||
17,
|
||||
5);
|
||||
|
||||
var encoded = SyntheticProtocolV1.EncodeRequest(request);
|
||||
|
||||
Assert.True(SyntheticProtocolV1.TryDecodeRequest(encoded, out var decoded));
|
||||
Assert.NotNull(decoded);
|
||||
Assert.Equal(1, decoded.Version);
|
||||
Assert.Equal("session-01", decoded.SessionIdentifier);
|
||||
Assert.Equal("profile.test", decoded.ProfileIdentifier);
|
||||
Assert.Equal(3, decoded.ProfileRevision);
|
||||
Assert.Equal("profile:profile.test@revision:3", decoded.ConfigurationIdentifier);
|
||||
Assert.Equal("correlation-01", decoded.CorrelationIdentifier);
|
||||
Assert.Equal("2a", decoded.TargetAddress);
|
||||
Assert.Equal(DiagnosticServices.ReadTroubleCodes, decoded.Service);
|
||||
Assert.Equal(17, decoded.LogicalTimeTicks);
|
||||
Assert.Equal(5, decoded.TimeoutTicks);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SyntheticProtocolV1_RequiresExplicitWireVersionAndLogicalTime()
|
||||
{
|
||||
var request = new SyntheticDiagnosticRequest(
|
||||
"session-required",
|
||||
"profile.test",
|
||||
1,
|
||||
"profile:profile.test@revision:1",
|
||||
"correlation-required",
|
||||
"10",
|
||||
DiagnosticServices.ClearTroubleCodes,
|
||||
0,
|
||||
5);
|
||||
var encoded = SyntheticProtocolV1.EncodeRequest(request);
|
||||
|
||||
string[] requiredFields =
|
||||
[
|
||||
"version",
|
||||
"sessionIdentifier",
|
||||
"profileIdentifier",
|
||||
"profileRevision",
|
||||
"configurationIdentifier",
|
||||
"correlationIdentifier",
|
||||
"targetAddress",
|
||||
"service",
|
||||
"logicalTimeTicks",
|
||||
"timeoutTicks"
|
||||
];
|
||||
foreach (var field in requiredFields)
|
||||
{
|
||||
var missing = JsonNode.Parse(encoded)!.AsObject();
|
||||
missing.Remove(field);
|
||||
Assert.False(
|
||||
SyntheticProtocolV1.TryDecodeRequest(Encoding.UTF8.GetBytes(missing.ToJsonString()), out _),
|
||||
$"Missing wire field '{field}' was accepted.");
|
||||
}
|
||||
|
||||
var negativeLogicalTime = JsonNode.Parse(encoded)!.AsObject();
|
||||
negativeLogicalTime["logicalTimeTicks"] = -1;
|
||||
var zeroTimeout = JsonNode.Parse(encoded)!.AsObject();
|
||||
zeroTimeout["timeoutTicks"] = 0;
|
||||
Assert.False(SyntheticProtocolV1.TryDecodeRequest(
|
||||
Encoding.UTF8.GetBytes(negativeLogicalTime.ToJsonString()), out _));
|
||||
Assert.False(SyntheticProtocolV1.TryDecodeRequest(
|
||||
Encoding.UTF8.GetBytes(zeroTimeout.ToJsonString()), out _));
|
||||
Assert.True(SyntheticProtocolV1.TryDecodeRequest(encoded, out var decoded));
|
||||
Assert.Equal(0, decoded!.LogicalTimeTicks);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SyntheticProtocolV1_RejectsDuplicateDispatchAndBindingProperties()
|
||||
{
|
||||
var request = new SyntheticDiagnosticRequest(
|
||||
"session-duplicate",
|
||||
"profile.test",
|
||||
1,
|
||||
"profile:profile.test@revision:1",
|
||||
"correlation-duplicate",
|
||||
"10",
|
||||
DiagnosticServices.ClearTroubleCodes,
|
||||
0,
|
||||
5);
|
||||
var encoded = Encoding.UTF8.GetString(SyntheticProtocolV1.EncodeRequest(request));
|
||||
var ambiguousService = encoded.Replace(
|
||||
"\"service\":\"clear.dtcs\"",
|
||||
"\"service\":\"read.dtcs\",\"service\":\"clear.dtcs\"",
|
||||
StringComparison.Ordinal);
|
||||
using var duplicateDocument = System.Text.Json.JsonDocument.Parse(ambiguousService);
|
||||
|
||||
Assert.Equal(2, duplicateDocument.RootElement.EnumerateObject()
|
||||
.Count(property => property.NameEquals("service")));
|
||||
Assert.False(SyntheticProtocolV1.TryDecodeRequest(
|
||||
Encoding.UTF8.GetBytes(ambiguousService), out _));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SyntheticProtocolV1_RejectsUnknownAndCaseAmbiguousRequestFields()
|
||||
{
|
||||
var request = new SyntheticDiagnosticRequest(
|
||||
"session-unknown",
|
||||
"profile.test",
|
||||
1,
|
||||
"profile:profile.test@revision:1",
|
||||
"correlation-unknown",
|
||||
"10",
|
||||
DiagnosticServices.Probe,
|
||||
0,
|
||||
5);
|
||||
var encoded = Encoding.UTF8.GetString(SyntheticProtocolV1.EncodeRequest(request));
|
||||
var unknownField = encoded.Insert(encoded.Length - 1, ",\"extension\":true");
|
||||
var caseVariant = encoded.Replace(
|
||||
"\"version\":1",
|
||||
"\"Version\":1,\"version\":1",
|
||||
StringComparison.Ordinal);
|
||||
|
||||
Assert.False(SyntheticProtocolV1.TryDecodeRequest(Encoding.UTF8.GetBytes(unknownField), out _));
|
||||
Assert.False(SyntheticProtocolV1.TryDecodeRequest(Encoding.UTF8.GetBytes(caseVariant), out _));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TransportReply_SnapshotsPayloadOnInputAndOutput()
|
||||
{
|
||||
var input = new byte[] { 1, 2, 3 };
|
||||
var reply = new TransportReply(TransportOutcome.Response, input, 4);
|
||||
input[0] = 9;
|
||||
var exposed = reply.Payload.ToArray();
|
||||
exposed[1] = 9;
|
||||
|
||||
Assert.Equal(new byte[] { 1, 2, 3 }, reply.Payload.ToArray());
|
||||
Assert.Equal(4L, reply.ElapsedTicks);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DiagnosticTraceBuffer_IsBoundedOrderedAndReportsDroppedRecords()
|
||||
{
|
||||
var identity = new DiagnosticSessionIdentity(
|
||||
"session.trace",
|
||||
"profile.trace",
|
||||
1,
|
||||
"vehicle.trace",
|
||||
new ExecutionTargetDescriptor("provider.trace", ExecutionTargetKind.Simulation));
|
||||
var trace = new DiagnosticTraceBuffer(2);
|
||||
|
||||
trace.Add(CreateEntry(identity, 1));
|
||||
trace.Add(CreateEntry(identity, 2));
|
||||
trace.Add(CreateEntry(identity, 3));
|
||||
var snapshot = trace.Snapshot();
|
||||
|
||||
Assert.Equal(1, snapshot.DroppedRecordCount);
|
||||
Assert.Equal(new long[] { 2, 3 }, snapshot.Entries.Select(entry => entry.StartLogicalTicks));
|
||||
Assert.All(snapshot.Entries, entry => Assert.Equal(DiagnosticOutcome.PositiveResponse, entry.Outcome));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DiagnosticTraceEntry_SnapshotsRawPayloadsOnInputAndOutput()
|
||||
{
|
||||
var identity = new DiagnosticSessionIdentity(
|
||||
"session.payloads",
|
||||
"profile.payloads",
|
||||
1,
|
||||
"vehicle.payloads",
|
||||
new ExecutionTargetDescriptor("provider.payloads", ExecutionTargetKind.Simulation));
|
||||
var request = new byte[] { 1, 2 };
|
||||
var response = new byte[] { 3, 4 };
|
||||
var entry = new DiagnosticTraceEntry(
|
||||
identity,
|
||||
"module.payloads",
|
||||
"10",
|
||||
"correlation.payloads",
|
||||
DiagnosticServices.Probe,
|
||||
0,
|
||||
1,
|
||||
request,
|
||||
response,
|
||||
DiagnosticOutcome.PositiveResponse,
|
||||
"probe",
|
||||
null);
|
||||
request[0] = 9;
|
||||
response[0] = 9;
|
||||
var exposedRequest = entry.RequestPayload.ToArray();
|
||||
var exposedResponse = entry.ResponsePayload!.Value.ToArray();
|
||||
exposedRequest[1] = 9;
|
||||
exposedResponse[1] = 9;
|
||||
|
||||
Assert.Equal(new byte[] { 1, 2 }, entry.RequestPayload.ToArray());
|
||||
Assert.Equal(new byte[] { 3, 4 }, entry.ResponsePayload!.Value.ToArray());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TransportReply_RejectsResponsePayloadForNoResponseOutcome()
|
||||
{
|
||||
Assert.Throws<ArgumentException>(() =>
|
||||
new TransportReply(TransportOutcome.NoResponse, new byte[] { 1 }, 0));
|
||||
}
|
||||
|
||||
private static DiagnosticTraceEntry CreateEntry(DiagnosticSessionIdentity identity, long tick)
|
||||
{
|
||||
var request = new byte[] { (byte)tick };
|
||||
return new DiagnosticTraceEntry(
|
||||
identity,
|
||||
"module.trace",
|
||||
"10",
|
||||
$"correlation-{tick}",
|
||||
DiagnosticServices.Probe,
|
||||
tick,
|
||||
tick + 1,
|
||||
request,
|
||||
new byte[] { 2 },
|
||||
DiagnosticOutcome.PositiveResponse,
|
||||
"probe response",
|
||||
null);
|
||||
}
|
||||
}
|
||||
Loading…
Reference in New Issue