This commit is contained in:
GAJ3T 2026-10-28 13:10:02 -04:00
parent 01287d2868
commit 9de82e53d5
33 changed files with 5056 additions and 280 deletions

186
README.md
View File

@ -12,140 +12,148 @@ supported vehicle modules.
## Implementation status
### IMPLEMENTED
### Implemented
- Step-01 repository and headless Core/Application foundation, accepted
2026-10-28; its original report remains historical evidence.
- Step-01A single Windows-first .NET MAUI Blazor Hybrid Client, UI and generic
Components RCLs, plus feature-oriented execution-target selection UI.
- Actual home, metadata-selection and not-found routes in the UI RCL; shared
accessible, text-safe status notices in Components.
- Immutable Simulation, RecordedReplay and PhysicalHardware target descriptors,
explicit provider/kind validation, case-insensitive exact metadata resolution,
no fallback, and DI composition in the in-process application.
- Selection and page messaging clearly state that metadata does not connect to a
vehicle or authorize any operation.
- Step-01 platform-neutral Core/Application foundation and regression coverage.
- Step-01A single Windows-first .NET 10 MAUI Blazor Hybrid Client, UI and generic
Components RCLs. Step-01A was accepted by the orchestrator on 2026-10-28.
- 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.
- UI routes: `/` foundation, `/execution-targets` explicit metadata selection,
`/vehicle-profiles` explicit profile import/revision selection/inspection/export,
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
verified truth or permission.
- Profile import is atomic and unknowns remain explicit. A selected profile is
immutable, process-local metadata; it is not connected to a vehicle.
- Publication/retrieval timestamps require a complete date/time with seconds and
an explicit `Z` or signed `HH:mm` offset; partial dates/times and local-time
defaults are rejected. A null optional module identity in evidence is no
constraint; supplied values must match a known module identity and never fill
unknown module data. See the schema guide for exact grammar and limits.
Step-01A implementation, builds, tests and a native Windows smoke run are complete.
Manual orchestrator review and acceptance are pending; no later milestone has
started. Step-02 remains held and is not authorized by this report.
### In progress
### IN PROGRESS
Manual orchestrator review and acceptance of Step-02 after the Step-02A correction.
Manual Step-01A acceptance by the orchestrator.
### Planned
### PLANNED
Vehicle/module profiles, deterministic AI-independent simulation, diagnostics,
telemetry and replay, calibration and backups, and replaceable local AI with
validated runbooks require later approved assignments. Hardware integration is a
future, initially read-only boundary with separate authorization/evidence gates
for any programming. No capability is implemented merely because it appears in
the product vision or roadmap.
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.
## Architecture
One Windows-first **AutoForge.Client** .NET 10 MAUI Blazor Hybrid executable hosts
the entire application UI via `BlazorWebView`. **AutoForge.UI** owns routing,
navigation, layouts, pages and presentation. **AutoForge.Components** owns
vehicle-independent reusable UI. Application features run in-process in a
modular monolith; the Client is the composition root. There is no backend,
the application UI via `BlazorWebView`. **AutoForge.UI** owns all routes,
navigation, layouts and feature presentation. **AutoForge.Components** owns
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 initial UI features are the foundation home page and explicit
execution-target metadata selection. Selection uses the existing real
Application resolver; the empty Client registration correctly shows
`ProviderNotRegistered`. No fake connected provider is installed to make the UI
look operational.
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.
```mermaid
flowchart TD
Client[MAUI Blazor Hybrid Client] --> UI[UI RCL: routes and feature screens]
Client[MAUI Blazor Hybrid Client] --> UI[UI RCL]
UI --> Components[Reusable Components RCL]
UI --> App[Application feature slices]
Client --> App
App --> Core[Platform-neutral Core contracts]
UnitTests[Headless unit tests] --> Components
UnitTests --> Core
IntegrationTests[Headless rendered integration tests] --> UI
App --> Core[Platform-neutral Core models]
UnitTests[Headless unit tests] --> Core
UnitTests --> App
IntegrationTests[Headless integration and rendered UI tests] --> UI
IntegrationTests --> App
IntegrationTests --> Core
```
`src/AutoForge.Application/Features/ExecutionTargets/SelectExecutionTarget`
owns the explicit selection feature while its public `AutoForge.Application.ExecutionTargets`
namespace remains stable. New application behaviors should form cohesive,
independently testable feature slices. Reusable engines and domain capabilities
stay independent of the UI; add no mediator, generic repository layer or empty
future-feature projects without a concrete need.
Core and Application own their behaviors under feature-focused source folders:
- `AutoForge.Application/Features/ExecutionTargets/SelectExecutionTarget`
- `AutoForge.Application/Features/Vehicles/Profiles`
- `AutoForge.UI/Features/Vehicles/Profiles`
No mediator, generic repository layer, database, or empty future feature is
required. See the [schema-v1 profile guide](docs/vehicle-profile-schema-v1.md)
for stable identifiers/revisions, unknown values, capabilities, provenance and
the strict JSON contract.
## Repository layout
Only `docs`, `src` and `prompts` are top-level project directories. Tests and
synthetic fixtures remain under `src/tests`. No nested repository or root test
project is used.
```text
AutoForge/
docs/ Technical docs and architecture decisions
prompts/ Manual assignments, state and worker evidence
docs/ Technical docs, schemas and ADRs
prompts/ Manual assignments, state and worker reports
src/
AutoForge.slnx
AutoForge.Client/ The sole app executable; Windows MAUI Hybrid
AutoForge.UI/ Complete routed application UI RCL
AutoForge.Components/ Generic, reusable status/notification component
AutoForge.Core/ Platform-neutral target-kind descriptors
AutoForge.Application/ Inward-dependent target-selection feature
AutoForge.Client/ Sole Windows MAUI Hybrid executable
AutoForge.UI/ Application routes and feature presentation
AutoForge.Components/ Generic reusable UI components
AutoForge.Core/ Platform-neutral domain invariants
AutoForge.Application/ In-process application feature slices
tests/
AutoForge.UnitTests/
AutoForge.IntegrationTests/
Fixtures/ Clearly synthetic schema-v1 JSON only
```
## Development and prerequisites
## Build, test and run
Prerequisites for this Windows-first Client build:
Verified Windows prerequisites: .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**. The Client targets
`net10.0-windows10.0.26100.0`/`win-x64`; the other projects target portable
`net10.0`. No automotive driver, actual vehicle, AI model, database, backend or
cloud account is needed.
- .NET SDK **10.0.402**, or a later stable patch in the same **10.0.4xx** feature
band, as pinned in [global.json](global.json).
- Installed `maui-windows` workload (10.0.110 workload manifest) and Windows SDK
target **10.0.26100.0**.
- Windows x64 runtime target and Microsoft Edge WebView2 Runtime. Native smoke
verification used WebView2 **155.0.4283.62**.
- nuget.org access for package restore.
No automotive driver, vehicle, model, backend or cloud account is required.
Other Windows, macOS, Android or iOS targets are not configured or verified.
From the repository root in PowerShell, restore and build the actual native
framework/runtime target:
From the repository root in PowerShell:
```powershell
dotnet restore .\src\AutoForge.Client\AutoForge.Client.csproj --runtime win-x64
dotnet restore .\src\AutoForge.slnx
dotnet build .\src\AutoForge.Client\AutoForge.Client.csproj --configuration Release --no-restore --framework net10.0-windows10.0.26100.0
dotnet build .\src\AutoForge.slnx --configuration Release --no-restore
dotnet test .\src\tests\AutoForge.UnitTests\AutoForge.UnitTests.csproj --configuration Release --no-build
dotnet test .\src\tests\AutoForge.IntegrationTests\AutoForge.IntegrationTests.csproj --configuration Release --no-build
dotnet build .\src\AutoForge.slnx --configuration Release
dotnet test .\src\AutoForge.slnx --configuration Release
dotnet run --project .\src\AutoForge.Client\AutoForge.Client.csproj --configuration Release --framework net10.0-windows10.0.26100.0
```
Start the application on a Windows desktop:
```powershell
dotnet run --project .\src\AutoForge.Client\AutoForge.Client.csproj --framework net10.0-windows10.0.26100.0
```
There is no backend or browser/server startup command. Headless UI/application
integration tests run independently of the native Client; they render the real
RCL components/routes and compose the actual application registration.
Step-02A worker verification includes a seven-project Release build with zero
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.
## Documentation and handoff
- [Documentation index](docs/README.md)
- [Current project graph and UI architecture](docs/architecture.md)
- [Original foundation ADR and its superseded decision](docs/adr-0001-headless-foundation.md)
- [Single-shell and feature-slice ADR](docs/adr-0002-single-shell-vsa.md)
- [Build, test and native smoke guide](docs/build-and-test.md)
- [Architecture and project graph](docs/architecture.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)
- [Step-01 historical report](prompts/Step-01-Report.md)
- [Step-01A assignment](prompts/Step-01A.md) and
[Step-01A worker report](prompts/Step-01A-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)
- [Orchestrator-owned roadmap](prompts/ROADMAP.md) and
[orchestration state](prompts/STATE.md)
Handoffs are manual. Worker completion does not mean orchestrator acceptance or
authorize the held Step-02.
Handoffs are manual. Step-02/Step-02A worker completion does not mean
orchestrator acceptance or authorize Step-03.

View File

@ -1,21 +1,27 @@
# AutoForge documentation
The implemented scope is the accepted Step-01 foundation plus the Step-01A
Windows-first MAUI Blazor Hybrid shell, two RCLs and metadata-selection UI.
Vehicle diagnostics, simulation and operation capabilities remain planned.
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.
- [Architecture](architecture.md): actual seven-project graph, Client/UI/RCL
ownership, feature-slice organization and explicit target-selection contract.
ownership, feature-slice organization, target selection and profile catalog.
- [ADR-0001: Headless .NET 10 foundation](adr-0001-headless-foundation.md):
historical foundation decisions, with its dual-shell/deferred-host decision
explicitly superseded.
historical foundation decisions, with dual-shell/deferred-host superseded.
- [ADR-0002: Single native shell and feature slices](adr-0002-single-shell-vsa.md):
current one-Client/two-RCL/modular-monolith architecture.
one Client, two RCLs and the 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.
- [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.
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), and the
[Step-01A worker report](../prompts/Step-01A-Report.md) for execution evidence.
[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.

View File

@ -1,15 +1,14 @@
# ADR-0002: One native shell, two RCLs, feature-oriented application
- Date: 2026-10-28
- Status: implemented for Step-01A; manual orchestrator acceptance pending
- Status: accepted 2026-10-28; extended by accepted Step-02 profile slice
- Supersedes: ADR-0001's dual-shell and deferred-host decision only
- Scope: initial application composition and organization
## Context
The accepted Step-01 foundation provides real, headless Core/Application
target-selection behavior and regression tests, but no host or UI. The owner
subsequently realigned the architecture before the held Step-02: add a usable
target-selection behavior and regression tests, but no host or UI. The owner subsequently realigned the architecture before Step-02: add a usable
Windows-first native application now, keep work in-process and use vertical
feature slices without unnecessary hosting/infrastructure layers. Preserve the
accepted target-selection feature and every original regression behavior.
@ -66,3 +65,5 @@ accepted target-selection feature and every original regression behavior.
See the [implemented architecture](architecture.md) and
[build/test policy](build-and-test.md) for source paths and concrete evidence.
Step-02 adds a profile metadata slice without changing this shell boundary; its
schema and catalog rules are recorded in [ADR-0003](adr-0003-profile-interchange-v1.md).

View File

@ -0,0 +1,72 @@
# ADR-0003: Strict versioned vehicle-profile metadata interchange
- Date: 2026-10-28
- Status: implemented and worker-verified for Step-02/Step-02A; manual orchestrator acceptance pending
- Scope: vehicle profile metadata model and in-memory JSON interchange
## Context
Step-02 needs a data-driven representation of vehicles, arbitrary module
inventories, operation declarations, unknown facts and provenance. The first
profile slice must remain useful without a database, online service or real
vehicle definition. Silent defaults or permissive JSON mapping could discard
identity/evidence or bind a profile to an unintended revision.
## Decision
1. Core owns immutable vehicle identity, profile revision, module instances,
extensible role/operation identifiers, capability declaration states and
evidence applicability. Profile revision identifies an immutable saved
configuration; schema version identifies the JSON format.
2. The Application feature owns schema-v1 JSON import/export and an in-memory
exact `(profileIdentifier, revision)` catalog. The catalog uses
ordinal case-insensitive identity comparison, rejects duplicates, and never
chooses a latest/closest configuration.
3. Schema v1 requires all defined properties, representing unknown optional facts
with explicit JSON `null`. Reject malformed/unsupported versions, ambiguous
duplicate properties, unknown properties, invalid enums, duplicates and
dangling/conflicting evidence. Incompatible future schemas require an explicit
later version and migration rather than silent downgrade.
4. Provenance applicability is scoped to a vehicle and optionally a model year,
exact profile revision, module instance and module identity values. Null
confidence is unknown; numeric confidence is finite `[0,1]`. A null optional
module identity applicability field is no constraint; each supplied non-null
constraint must match a known target module identity. A supplied constraint
against a mismatched or unknown target is rejected, and no identity is inferred
or filled. Module-scoped evidence may omit all four version-specific constraints.
Classification preserves supplied evidence only and does not independently
verify it or authorize work.
5. Synthetic fixtures remain source-controlled test inputs. The Client catalog is
in-memory per process; the existing UI imports explicitly and requires explicit
selection before displaying or exporting a profile.
6. This is metadata-only. No diagnostic service, simulation, calibration data,
firmware image, operation executor, persistent user-file storage, AI or
hardware authorization is part of this decision.
7. `publishedAt` and `retrievedAt` accept explicit null or only a complete
`YYYY-MM-DDTHH:mm:ss[.fraction](Z|+HH:mm|-HH:mm)` timestamp: uppercase `T`/`Z`,
required seconds, optional 1-7 digit fractional seconds and an explicit valid
whole-minute offset in `-14:00..+14:00`. Parsing never supplies local-zone or
current-date defaults. Invalid input fails with the exact JSON property path
before catalog registration.
## Consequences
- Immutable constructor validation is shared by direct domain construction and
JSON deserialization. Arrays/collections are snapshotted and not exposed.
- Optional evidence identity constraints remain absent when null; known module
identifiers are neither required to be null nor copied into evidence. Supplied
constraints cannot match an unknown target or change classification/authority.
- Timestamp parsing is lexically restricted and calendar-validated before creating
`DateTimeOffset`, so an import cannot inherit machine-local time or today's date.
- The strict v1 policy may reject forward-extended documents until a later schema
version is deliberately implemented; this is preferable to losing unknown
identity or capability data.
- The catalog currently loses imported data on process exit. Persistence needs a
separate approved design and is not implied by JSON export.
- “Supported” and `VERIFIED` remain labels on metadata, not proof of an
implemented operation, vehicle compatibility, authorization or physical access.
See [schema-v1 profile documentation](vehicle-profile-schema-v1.md),
[architecture](architecture.md) and [build/test guidance](build-and-test.md).
Step-02A's worker report records correction regressions and native verification;
manual orchestrator acceptance of Step-02 remains pending.

View File

@ -27,13 +27,13 @@ All seven 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 explicit target-kind and immutable descriptor invariants | None |
| [Application](../src/AutoForge.Application/AutoForge.Application.csproj) | `net10.0`; in-process application use cases, organized by feature | Core |
| [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 |
| [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 and rendered generic component tests | Application, Components, Core |
| [IntegrationTests](../src/tests/AutoForge.IntegrationTests/AutoForge.IntegrationTests.csproj) | `net10.0`; real DI, rendered RCL, application and actual project-graph tests | Application, Components, Core, 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 |
Components has no AutoForge project dependency. UI never references Client.
Core and Application never reference UI/Components/Client or tests. There are no
@ -44,7 +44,9 @@ 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.
No fake connected/available provider is added.
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.
## UI ownership and real routes
@ -55,12 +57,13 @@ assembly, not the native Client assembly.
|---|---|---|
| `/` | `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 |
`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 and not-found pages; isolated CSS bundles from both RCLs
home, target-selection, profile and not-found pages; isolated CSS bundles from both RCLs
are imported through the Client scoped-style bundle.
The target-selection page's feature-local `ExecutionTargetSelectionViewModel`
@ -81,6 +84,22 @@ ordinal case-insensitive comparison, resolves only exact requested metadata and
returns the registered descriptor. Existing typed failures and no-fallback
behavior remain unchanged.
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 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).
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
@ -91,11 +110,14 @@ future slices to demonstrate architecture.
## Honest limitations and safety boundaries
Current work implements application-shell/navigation behavior, accessible status
presentation and **metadata selection only**. It does not implement vehicle
profiles, connection/discovery, simulation, diagnostics, telemetry, replay,
backups, calibration, persistence, AI, cloud services, operation execution or
hardware integration. Physical-kind metadata neither connects nor grants a
capability/write approval.
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.
Future simulation remains deterministic and AI-independent with an isolated
verification oracle. Future initial hardware integration is read-only. Physical

View File

@ -3,92 +3,111 @@
## Prerequisites
- Windows x64, .NET SDK 10.0.402 with its approved .NET 10 patch roll-forward.
- Windows 10 SDK 10.0.26100.0 and the MAUI Windows workload (10.0.110).
- Microsoft Edge WebView2 Runtime for launching the native Blazor Hybrid Client.
- 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.
The Client targets `net10.0-windows10.0.26100.0` and `win-x64`. The Core,
Application, UI, Components and test projects target portable `net10.0`. Headless
tests therefore do not require MAUI or WebView2. The solution uses centralized
package versions; change direct dependencies only through the central package
file and validate the resulting restore.
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.
## Restore and build
## Restore, build and launch
From the repository root in PowerShell:
```powershell
dotnet restore .\src\AutoForge.slnx
dotnet build .\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
```
For an explicit Windows runtime pack restore or native Client build:
For an explicit Windows runtime pack restore or a 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
```
Run the app on Windows:
```powershell
dotnet run --project .\src\AutoForge.Client\AutoForge.Client.csproj --configuration Release --framework net10.0-windows10.0.26100.0
```
The app is a native MAUI window containing the actual `AutoForge.UI` routes in a
BlazorWebView. Its initial provider registration is empty by design. Startup and
selection remain useful to exercise the honest `ProviderNotRegistered` result;
they do not require a backend, a database or vehicle hardware.
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.
## Automated verification
Run the focused portable suites:
Run focused suites while developing:
```powershell
dotnet test .\src\tests\AutoForge.UnitTests\AutoForge.UnitTests.csproj --configuration Release
dotnet test .\src\tests\AutoForge.IntegrationTests\AutoForge.IntegrationTests.csproj --configuration Release
```
Unit tests cover Core/Application behavior and rendered reusable components.
Integration tests cover actual dependency-injection composition, rendered UI
routes with the real Application resolver, and the project-reference graph.
`ProjectGraphTests` reads the project manifests; it guards the production
dependency direction rather than relying on a diagram.
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.
At Step-01A implementation verification, the full Release solution build and the
direct native Client build completed with zero warnings and errors. The portable
suite results were 39 unit tests and 26 integration tests passed (65 total).
All 54 Step-01 tests remain in the expanded suites.
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.
## Native smoke checks
## Native profile smoke procedure
Run the Client on Windows and verify:
Run the actual Windows Client and open `/vehicle-profiles`:
1. The native window opens with the AutoForge home route and no unhandled-error
banner.
2. Navigation reaches `/execution-targets` and displays the explicit
`ProviderNotRegistered` empty-provider state.
3. The UI states that selection is metadata-only and does not connect to a
vehicle or authorize operations.
4. Submitting a valid, explicit provider identifier and defined target kind
returns the honest not-registered result; it does not fall back to another
kind or invent a provider.
5. An unmatched path displays the explicit not-found presentation.
6. Components RCL scoped-style assets load in the WebView.
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.
Automated rendered-route tests cover the route/component/Application behavior;
they are not evidence of native WebView startup. Record the native Client build,
window, route interactions and style asset verification separately in the
Step-01A execution report.
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.
## Guardrails and limitations
## Schema and safety boundaries
- Selection is explicit registered **metadata** only. It is not a connection,
detected capability, health result or authorization.
- The Client's empty provider registry is deliberate. Do not add a fabricated
provider to make the screen look populated.
- No HTTP server, browser-only host, database, cloud service, simulation engine,
diagnostic engine or hardware driver is part of this foundation.
- Keep the native Client dependency and platform surface isolated; preserve
portable testability for UI, Components, Application and Core.
- Step-02 remains held for orchestrator acceptance; completing this build guide
does not authorize later roadmap work.
See the [schema-v1 guide](vehicle-profile-schema-v1.md) for all field, identity,
unknown-value, capability, provenance and strict JSON rules. In brief:
- Every v1 field is required; unknown optional facts are explicit JSON `null`.
Unknown fields and duplicate/case-ambiguous properties are rejected.
- Catalog selection requires exact `(profileIdentifier, revision)`. Duplicate
imports do not replace entries, and failed parsing cannot partially register.
- `publishedAt`/`retrievedAt` accept null or complete
`YYYY-MM-DDTHH:mm:ss[.fraction](Z|+HH:mm|-HH:mm)` timestamps only. The exact
fractional and offset limits and no-default policy are in the schema guide.
- 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.
- 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.

View File

@ -0,0 +1,178 @@
# Vehicle profile metadata and JSON schema version 1
## Scope and identity
Schema v1 is an in-memory interchange format for explicitly selected vehicle and
module metadata. It describes neither a real vehicle nor operational compatibility.
It contains no diagnostic commands, transport details, calibration values, firmware
bytes or programming authorization.
The top-level `schemaVersion` is the format version (`1`). It is separate from the
positive integer profile `revision`. A stable `profileIdentifier` can have multiple
saved revisions, each an immutable configuration snapshot. The catalog key is the
pair `(profileIdentifier, revision)`, compared ordinally without case sensitivity.
The profile contains a stable `vehicleIdentifier`; multiple profile revisions can
refer to the same vehicle. An exact unknown revision fails even if other revisions
exist.
All required strings are non-empty, not automatically trimmed, and may not have
leading/trailing whitespace. Identity uniqueness uses `OrdinalIgnoreCase`.
Custom module `role` and `operationIdentifier` strings are not closed enums.
Repeated roles are allowed when module-instance identifiers differ.
Optional model facts and hardware/software/firmware/calibration identifiers use
explicit JSON `null` to mean **unknown/not supplied**. They are never populated with
fabricated defaults. `modelYear` is null or a positive integer no greater than
9999. A calibration identifier is only a reference label; it does not contain
calibration data.
## Capability declaration contract
Each module may list zero or more operation declarations. Operation identifiers
are unique within that module using ordinal, case-insensitive comparison.
Declarations use exactly these v1 states:
| JSON status | Meaning of supplied metadata |
|---|---|
| `SUPPORTED` | A source declares support; no service, connection, permission or compatibility is implemented by this record. |
| `UNSUPPORTED` | A source explicitly declares the operation unsupported in the stated context. |
| `UNKNOWN` | A source explicitly reports uncertainty or unknown availability. |
| `INACCESSIBLE` | The source indicates the capability cannot currently be accessed; this is distinct from unsupported. |
| `RESTRICTED` | The source describes restrictions/limitations; it does not grant authorization. |
An absent declaration is not support. `ModuleInstance.GetCapability` returns an
explicit not-declared `UNKNOWN` assessment with a reason. The assessment's
`IsDeclared` distinguishes that result from a declared `UNKNOWN` entry. No status
causes the system to connect, discover a capability, execute an operation or
authorize a physical write.
## Provenance and applicability
Profile evidence records are local to one profile revision. Facts and declarations
reference evidence IDs instead of copying source claims. Every evidence record
supplies:
- A unique evidence identifier, classification, source reference and description.
- An applicability context with a required vehicle ID, optional applicable model
year, and optional profile ID + revision (both are required together or both
omitted).
- An optional module instance ID and optional hardware/software/firmware/calibration
identity context. These version-specific fields require a module ID.
- Optional confidence (`null` means unknown); numeric values must be finite and in
the inclusive range `[0, 1]`.
- Optional verification information, publication/retrieval timestamps and known
limitations. Timestamps are explicit source data; validation does not create
them from the current clock.
Classifications are `VERIFIED`, `UNVERIFIED`, `INFERRED` and `SYNTHETIC`. The
classification is supplied metadata and is not independently verified or promoted
by the application. Synthetic records are plainly labelled and include limitations.
Provenance does not grant permission.
Evidence IDs must resolve within the same profile revision. Vehicle, module and
capability evidence references must be applicable to their vehicle/module scope.
Evidence that names a profile revision, vehicle, model year, module or specific
identity must match under the documented identifier comparison when the profile
supplies that same fact. A null optional hardware/software/firmware/calibration
applicability identity means **no constraint was supplied**; it does not assert
that the corresponding module identity is null. A module-scoped record can name a
module while leaving all four optional identity constraints null. Each supplied
non-null constraint must match the corresponding known module identity using
ordinal case-insensitive comparison. A mismatch or a supplied constraint against
an unknown module identity rejects the profile; validation never infers or fills
that module identity. Version-specific constraints still require a module
instance ID, and dangling/wrong module, vehicle, profile/revision or conflicting
known model-year context rejects the profile. These rules apply identically to
module and capability evidence references and to direct Core construction and
JSON/service import.
### Publication and retrieval timestamps
`publishedAt` and `retrievedAt` accept explicit JSON `null` for unknown or exactly
this complete, offset-bearing ISO-8601 subset:
```text
YYYY-MM-DDTHH:mm:ss[.fraction](Z|+HH:mm|-HH:mm)
```
`YYYY` is a four-digit Gregorian year; `T` and `Z` are uppercase literals.
Seconds are required. The optional fraction is a decimal point followed by 1 to 7
ASCII digits (the .NET 100-nanosecond precision supported by `DateTimeOffset`).
The offset is required and is either `Z` for UTC or a signed numeric `HH:mm`
offset; valid offsets are limited to `-14:00` through `+14:00` in whole minutes.
Calendar/time values must be valid and representable with that offset. No
surrounding whitespace, date-only/time-only, missing seconds/year/offset, culture
date, zone name, comma fraction or extra fractional precision is accepted.
Timestamp input is parsed without local-time or current-date defaults. The parsed
wall time, fractional precision and supplied offset are retained semantically;
export uses the round-trip .NET timestamp representation.
Invalid timestamps produce a `VehicleProfileInterchangeException` at the exact
`publishedAt` or `retrievedAt` JSON path, before catalog registration.
## JSON document shape
The root object contains exactly:
- `schemaVersion`, `profileIdentifier`, `revision`
- `vehicle`
- `modules`
- `evidence`
`vehicle` contains its vehicle ID, required manufacturer/model, optional known
identity fields, and evidence references. Each evidence `applicability` object
contains the vehicle ID and nullable applicable model year, plus optional exact
profile-revision and module identity context. `modules` is an arbitrary list of
module instances with identity, role/name, optional IDs, evidence references, and
capability declarations. `evidence` contains the provenance records above.
Every schema-v1 property is required in the document; an optional fact is written
as an explicit `null`, and empty collections are written as `[]`. This makes a
missing value distinct from a known default. See the checked-in
[synthetic truck baseline](../src/tests/AutoForge.IntegrationTests/Fixtures/synthetic-truck-baseline.json),
[variant](../src/tests/AutoForge.IntegrationTests/Fixtures/synthetic-truck-variant.json)
and [alternate vehicle](../src/tests/AutoForge.IntegrationTests/Fixtures/synthetic-orchard-vehicle.json)
for complete examples.
The built-in .NET JSON parser rejects malformed JSON, comments/trailing commas,
duplicate or case-ambiguous object properties, missing properties, wrong types,
unknown properties and unsupported versions. Unknown properties are rejected in
v1 rather than silently discarded. Enum strings are uppercase exact tokens shown
above. Duplicate module IDs, capability operation IDs and evidence IDs are
rejected under ordinal case-insensitive comparison. Domain construction and JSON
import use the same invariants; there is no repair, downgrade, default provider,
random identifier, online lookup or hidden file write.
Future incompatible structure requires a new explicitly supported schema version
and a deliberate migration; v1 import never guesses or migrates future documents.
Failures use `VehicleProfileInterchangeException` with a JSON path and actionable
reason. Catalog duplicate and exact-revision misses use
`VehicleProfileCatalogException`. Full input JSON is not logged.
Step-02 and its Step-02A corrective work are worker-implemented and verified;
manual orchestrator acceptance remains pending. See the [Step-02A report](../prompts/Step-02A-Report.md)
for exact regression, build, test and native evidence.
## Application lifecycle and usage
The `Features/Vehicles/Profiles` Application slice exposes JSON import, list,
exact profile/revision select and export through `IVehicleProfileService`. Import
validates completely before atomic registration. The Client wires one in-memory
catalog for the process; imported data is not persisted and is cleared at app exit.
No database, global active vehicle, connection or AI model is involved.
The UI RCL's `/vehicle-profiles` page accepts explicit JSON paste, lists revisions,
requires a user selection, displays identity/capability/provenance/unknown
metadata, and presents a read-only schema-v1 export for the selected revision.
Import does not auto-select. An invalid or duplicate import does not replace
registered data or the current selection. The profile page is independent of the
existing explicit target resolver.
To try the synthetic path on Windows, start the native
[AutoForge.Client](../src/AutoForge.Client/AutoForge.Client.csproj), open
`/vehicle-profiles`, paste the checked-in baseline JSON and import it, then
explicitly select revision 1. Repeat with the variant as a separate import and
select revision 2 to inspect the distinct synthetic calibration identity. The
alternate fixture demonstrates a different inventory, custom module role and
operation. These records are test metadata only; they do not represent real
manufacturer definitions, services, simulation or working hardware support.

View File

@ -3,11 +3,11 @@
## Status and authority
- Initialized: 2026-10-28.
- Current phase: corrected single-shell foundation accepted; profile/module work next.
- Active assignment: [Step-02](Step-02.md), regenerated for manual worker execution.
- Last accepted step: Step-01A, accepted 2026-10-28 after implementation/evidence review.
- 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.
- Outstanding corrections: none.
- Step-02 status: READY FOR WORKER; explicitly supersedes its unexecuted pre-correction version.
- Step-03 status: READY FOR WORKER; no 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
@ -119,6 +119,12 @@ Telemetry and AI. Do not create their empty directories now. Slice-local request
handler/service, validation and result types are added only when useful.
MediatR, generic repositories/managers and uniform boilerplate are not required.
Step-02 has added Core vehicle/profile models, an Application
`Features/Vehicles/Profiles` import/catalog/select/export feature and the existing
UI's `/vehicle-profiles` page. Step-02A closed the timestamp and optional evidence
constraint gaps; the corrected Step-02 milestone is accepted. Worker verification
now covers 103 unit and 37 integration cases (140 total).
UI feature presentation follows the same feature areas where practical; it calls
application contracts without duplicating business validation. Reusable engines,
protocols, calibration and telemetry capabilities remain independently testable
@ -145,6 +151,15 @@ 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:
`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.
Planned dependency flow:
```mermaid
@ -222,10 +237,10 @@ UI unrestricted programming authority.
## Milestones and acceptance gates
Step-01 and its owner-directed correction Step-01A are accepted. Step-02 has been
regenerated from the corrected seven-project implementation and is the only
active assignment. Its old unexecuted version is explicitly superseded.
All Step-02 and later product capabilities remain unimplemented.
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.
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.
@ -234,8 +249,9 @@ evidence; they must not silently discard required capabilities.
|---|---|---|---|---|
| 01 | Repository and solution foundation | Repository inspection | ACCEPTED 2026-10-28 | Four-project .NET 10 foundation, explicit target-selection behavior, real unit/integration tests, successful recorded build/test evidence, accurate README and architecture docs |
| 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 | READY FOR WORKER | Versioned profile round trips, validation, extensible modules/capabilities/provenance, exact configuration selection, synthetic fixtures and a minimal metadata-only UI feature using application slices |
| 03 | Virtual modules and diagnostic communication | 02 | PLANNED | Application discovers/identifies synthetic modules and reads telemetry/DTCs through a simulated transport; trace, negative responses and deterministic timeout tests |
| 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 |
| 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 |
@ -268,11 +284,18 @@ evidence; they must not silently discard required capabilities.
states, firmware/calibration identity, relationships, provenance, validation,
schema versioning, and multiple synthetic variants. Never imply a diagnostic
capture contains a complete firmware image.
- **02A accepted correction:** strict full-date/time/offset parsing, optional
module evidence constraints, atomic import/UI regressions and aligned docs.
Original reports remain unchanged; acceptance uses the corrected implementation.
- **03:** synthetic module state/storage, identification, telemetry definitions,
DTC retrieval and simulated clearing, request/response semantics, addressing,
session state where appropriate, delays, invalid requests, unsupported services,
interruption and negative responses. Authentic protocol semantics require
sources; synthetic behavior is labeled.
sources; use an explicitly synthetic versioned protocol first rather than
inventing manufacturer behavior. Keep the existing profile schema intact;
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.
- **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
@ -409,6 +432,14 @@ not proven real-world economy improvements.
- D-012: with 01A accepted, Step-02 adds a minimal metadata-only profile consumer
to the existing UI alongside headless feature services. This advances one
cohesive profile slice, not the later simulator/dashboard milestone.
- D-013: profile timestamps must contain their full date/time and explicit offset,
never ambient date/time-zone defaults. A null optional module applicability
identity is an absent constraint, not a requirement that the target identity
also be null; supplied constraints remain validated and grant no authority.
- D-014: Step-03 introduces Diagnostics and Simulation as purposeful separate
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.
The worker records the relevant accepted decisions as technical ADRs when creating
or changing the implementation. Future changes require a reason and roadmap/state
@ -443,17 +474,48 @@ history, not repeated redesign without evidence.
not execute application builds/tests or native startup.
- Regenerated Step-02 against that accepted implementation, with explicit
supersession, feature/RCL boundaries, regressions and worker verification duties.
- Reviewed the completed Step-02: immutable Core metadata, strict object/schema
parsing, profile catalog/DI, UI, fixtures, new tests, Git changes and documentation.
Worker evidence reports 59 unit + 34 integration cases passed, zero failed/skipped,
zero-warning/error solution/native builds and actual profile UI smoke.
- Source counts, restored assets, Release outputs and fixture shape corroborate
those reported checks, not independent runtime execution. Static review found
two untested validation defects; Step-02 was not accepted at that initial review.
- Prepared [Step-02A](Step-02A.md). Original Step-02 assignment/report remain
unchanged; the worker was required to correct and report before a Step-03 handoff.
- Reviewed and accepted Step-02A and corrected Step-02: strict timestamp lexical/
calendar/offset checks, null-as-absent evidence constraints, retained mismatch/
unknown-target failures, actual direct/codec/DI/UI regressions and documentation.
- Reviewed worker-reported pre-fix failures, corrected focused runs, sequential
zero-warning/error complete Release build, 103 unit + 37 integration passes,
zero failed/skipped and native positive/error/original-fixture smoke. Source case
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.
### Remaining
- Worker execution of Step-02, then manual acceptance review and any Step-02A
corrections before Step-03.
- All profile/module and later product capabilities remain planned. Preserve the
complete sequence and safety gates rather than restarting or reducing scope.
- 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.
### Known blockers and uncertainties
No blocking architectural/native verification deficiency remains for Step-02.
No blocking profile-correction deficiency remains. The original Step-02 findings
below are historical and resolved by accepted Step-02A:
- R-01 originally used permissive DateTimeOffset parsing. The replacement requires
complete date/time/seconds and explicit Z/numeric offset, validates its calendar
and offset and preserves exporter precision without ambient defaults.
- R-02 originally required both evidence and target identities null. The corrected
helper treats an absent constraint as absent, while every supplied constraint
still requires a matching known target identity.
The worker supplied actual pre-fix failures and post-fix unit/DI/UI/native evidence.
Neither before/after input case was executed by the orchestrator.
The Step-01A report records SDK 10.0.402, runtime 10.0.13, Windows target
10.0.26100.0/win-x64, MAUI Windows manifest 10.0.110 and WebView2 155.0.4283.62.
Native execution is worker evidence, not an orchestrator rerun. Other platforms,
@ -467,12 +529,12 @@ Non-blocking deviations are retained explicitly:
final Windows builds/tests/smoke passed according to the report. Broader
environment impact is unverified. This is not retroactive authorization.
Do not repeat workload-changing commands or attempt rollback without approval.
- Raw Git whitespace checking flags README CRLF against the mixed-line-ending
tracked baseline. There are no trailing spaces/tabs; a command-local
CR-at-EOL-aware check passes. Step-02 must normalize the already-to-be-updated
Markdown to the existing LF editor convention without changing Git settings.
- README/ADR acceptance-pending lifecycle text is accurate as of worker report
creation; Step-02 must align it with this acceptance while preserving history.
- 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.
No major environment installation, update, repair or rollback is automatically
authorized. Physical definitions/access and programming approval remain future gates.

View File

@ -5,16 +5,17 @@
| Field | Value |
|---|---|
| Updated | 2026-10-28 |
| Phase | Corrected single-shell foundation accepted; vehicle profile slice next |
| Active step | Step-02 - Vehicle profiles and control module model |
| Assignment | [Step-02.md](Step-02.md), regenerated after Step-01A acceptance |
| 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) |
| Assignment status | READY FOR WORKER / AWAITING MANUAL HANDOFF |
| Expected worker report | `prompts/Step-02-Report.md` - not yet created |
| Last accepted step | Step-01A - accepted 2026-10-28 |
| Expected worker report | `prompts/Step-03-Report.md` - not yet created |
| Last accepted step | Step-02 with Step-02A - accepted 2026-10-28 |
| Outstanding corrections | None |
| Step-02 status | READY FOR WORKER; old unexecuted assignment explicitly superseded |
| Worker execution | Step-01A manually completed; Step-02 not invoked |
| Immediate next action | User manually directs the worker to execute regenerated Step-02 only |
| 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 |
| Next orchestrator action | After manual return, inspect the assignment, report, implementation, tests, Git changes, documentation and recorded command evidence |
## Repository baseline at initialization
@ -131,7 +132,8 @@ The old Step-02 was held, not executed.
After acceptance, [Step-02](Step-02.md) was regenerated from the seven-project
implementation and explicitly supersedes the prior unexecuted assignment. It now
uses application feature slices, reusable Core models and a thin profile metadata
consumer in the existing UI. No Step-02 implementation/report exists yet.
consumer in the existing UI. Step-02 implementation/report now exist; acceptance
was initially withheld for the findings below and is now granted after Step-02A.
## Step-01A acceptance review
@ -166,6 +168,106 @@ workload action or a claim that the broader tool environment is unchanged.
The deviations below are non-blocking for this verified Windows foundation and
must remain visible. No environment rollback or source fix was attempted.
## Historical Step-02 review and corrective decision
Initial decision: **REQUIRES CORRECTION**, 2026-10-28. The findings and criterion
table below describe the pre-correction implementation. They are preserved as
history and closed by the Step-02A acceptance review that follows.
Inspected the [assignment](Step-02.md), [worker report](Step-02-Report.md),
complete new Core/profile codec/catalog/DI/UI code, all new unit/integration
tests, synthetic fixtures, existing composition/reference changes, README and
affected technical/schema/ADR documentation.
| Criterion | Review result | Evidence / remaining work |
|---|---|---|
| AC-01 | Preserved on inspected evidence | Same seven-project graph, existing target/UI regressions and manual/protected workflow; no new dependency or shell |
| AC-02 | Present; validation correction required | Immutable profile/revision/module model works for supplied fixtures, but valid partial module-evidence context is rejected |
| AC-03 | Present on inspected evidence | Five capability states, custom operations and explicit undeclared Unknown retained; no operational authority |
| AC-04 | NOT SATISFIED | R-02 treats absent optional evidence identity constraints as exact null matches, rejecting compatible module-scoped evidence |
| AC-05 | NOT SATISFIED | R-01 permits incomplete timestamp strings that infer ambient date or offset, violating explicit schema data |
| AC-06 | Existing path inspected; correction regressions required | Real DI catalog/UI and atomic failed imports exist; both findings need direct/service/UI regression coverage |
| AC-07 | Present on inspected evidence | Three synthetic fixture documents cover baseline, variant, alternate/custom module and all five states |
| AC-08 | Existing suite passed per worker; insufficient coverage | Reported 59 unit + 34 integration passed, zero failed/skipped; solution/native build and native smoke passed; findings are absent from this coverage |
| AC-09 | Corrective alignment required | Documentation exists, but timestamp/optional applicability behavior must match the stated contract and correction status |
| AC-10 | Report/preservation inspected | Required report and scope evidence present; original assignment/report remain unchanged; no Step-03 |
### R-01 - Ambient-dependent timestamp import
[VehicleProfileJsonCodec.cs](../src/AutoForge.Application/Features/Vehicles/Profiles/VehicleProfileJsonCodec.cs),
line 478, delegates to DateTimeOffset.TryParse with RoundtripKind. Official .NET
documentation states that a missing date defaults to the current day, a missing
offset defaults to the local time zone, and RoundtripKind has no effect for this
type. Time-only, date-only and offset-free date/time strings therefore are not
reliably rejected by this supposedly explicit/clock-independent import contract.
Both publishedAt and retrievedAt use this path.
### R-02 - Absent evidence constraints rejected
[VehicleProfile.cs](../src/AutoForge.Core/Vehicles/VehicleProfile.cs), lines 367
and 408, validates each optional module identity using a helper that requires both
values to be null when the evidence field is null. A module with known hardware
cannot accept module-scoped evidence that leaves hardware applicability
unspecified, even when vehicle/profile/module and all supplied constraints match.
This contradicts the documented optional identity context. Fix absence handling
without weakening supplied-constraint or unknown-target checks.
These are source/contract findings, not claims of independently executed failures.
Official API documentation corroborates R-01; Step-02A requires worker
reproduction, corrected regressions and native/UI evidence, now supplied and
reviewed below.
Worker-reported Step-02 execution remains historical: complete seven-project and
direct native Release builds with zero warnings/errors; 59 unit and 34 integration
cases passed, zero failed/skipped; native profile import/select/variant/error/export
and old route/asset checks reported. Static test counts, fixture shape, restore
assets and Release/native artifacts corroborate it. No build/test/native/workload
command was executed by the orchestrator.
## Step-02A acceptance and corrected Step-02
Decision: **ACCEPTED**, 2026-10-28. Step-02A closes R-01/R-02; the corrected
Step-02 milestone is accepted. No Step-02B is required.
Reviewed [Step-02A](Step-02A.md), its [report](Step-02A-Report.md), the complete
new timestamp parser/shared evidence helper, correction unit/real DI/rendered UI
tests, data mutation helpers, schema/ADR/README/testing updates and project scope.
| Criterion | Decision | Evidence |
|---|---|---|
| AC-01 | ACCEPTED | Anchored ASCII full-date/time/offset grammar, exact invariant calendar parse, bounded minute offset and typed property failures; both timestamp fields have positive/negative vectors and exact offset/tick assertions |
| AC-02 | ACCEPTED | Null constraint is absence; non-null requires known matching target; each-field omission/matching/mismatch/unknown-target constructor tests and all-null real DI round-trip inspected |
| AC-03 | ACCEPTED | Actual service/page path accepts module-only evidence, rejects timestamp/supplied mismatch, preserves catalog/current selection and renders explicit errors |
| AC-04 | ACCEPTED | Previous 93 cases remain in the expanded 140-case suite; fixtures, seven-project graph, metadata/target isolation and public contracts retained |
| AC-05 | ACCEPTED ON WORKER EXECUTION EVIDENCE | Reported actual pre-fix failures; focused corrected runs; complete sequential Release build 0 warnings/errors; 103 unit + 37 integration passes, zero failed/skipped; native scenarios and original fixtures observed |
| AC-06 | ACCEPTED | Schema/ADR specify precise grammar/null/offset limits and absent-versus-supplied identity constraints; README/index/test guide preserve historical versus corrective results |
| AC-07 | ACCEPTED | Scope remains two fixes/tests/docs/report; no new package/project/workload action or later-step implementation; historical assignments/reports preserved |
Coverage precision: the direct unit helper's null label retains all known
constraints, while its four named cases omit each constraint individually.
The separate real DI/UI integration test supplies all four nulls and constructs/
round-trips the actual Core model. Acceptance uses that combined inspected
coverage, not an assumption that the unit loop's null label means all-null.
Worker-reported execution: SDK 10.0.402/runtime 10.0.13; Windows target
10.0.26100.0/win-x64; MAUI Windows manifest 10.0.110; WebView2 155.0.4283.62.
Before-fix command outcomes and focused runs are recorded in the unchanged report.
Final build: complete seven-project Release solution, zero warnings/errors.
Final suites: 103 unit and 37 integration passed, zero failed/skipped.
Native observations include full explicit-offset timestamps/partial evidence,
exact invalid-time path, conflicting supplied constraint with unchanged catalog/
selection, original baseline/variant/alternate imports and target metadata route.
Static source case counts, seven-project acyclic references, restored assets,
Release assemblies and native executable corroborate the report. The orchestrator
did not execute application builds/tests/native launch or workload commands.
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.
## Prerequisites, limitations, and known issues
- Step-01A worker evidence establishes portable and native Windows compatibility
@ -179,30 +281,36 @@ must remain visible. No environment rollback or source fix was attempted.
stayed 10.0.110. No rollback occurred. Final Windows checks passed, but broader
impact is unverified. Do not repeat workload-changing commands or repair/rollback
without explicit authorization; this review does not authorize them.
- Raw `git diff --check` failed on README CRLF, against a mixed-line-ending index.
- Historical Step-01A raw `git diff --check` failed on README CRLF, against a mixed-line-ending index.
Read-only byte inspection found 151 CRLF lines and no trailing spaces/tabs.
A command-local CR-at-EOL-aware check passed, with no Git configuration changed.
Require LF normalization during Step-02's already-required README update.
- README/ADR acceptance-pending text is historical to worker completion; Step-02
must align lifecycle statements while preserving original reports/decisions.
- No blocking Step-02 prerequisite is currently identified.
- Simulation, replay, diagnostics, profiles, telemetry, calibration, persistence,
AI and hardware operations remain unimplemented; only foundation UI is present.
Step-02 resolved working-file normalization: 149 LF and zero CRLF lines observed;
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.
- No application build or test has been executed by the orchestrator.
## Review and progression gate
On manual return, evaluate every Step-02 acceptance criterion using the original
On manual return, evaluate Step-03 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 domain/schema invariants, feature organization, profile UI/application
tests, all regressions, native profile smoke evidence and documentation.
- If accepted: record the decision, update roadmap/state, create Step-03 and stop
for manual handoff. Do not execute it.
- If deficient: create `Step-02A.md` with measurable corrections and matching
report requirements, update state, and stop. Do not advance to Step-03.
- 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
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 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.
@ -222,11 +330,17 @@ claim; do not claim independent runtime verification.
| 2026-10-28 | Step-01A returned and ACCEPTED | Seven-project single-shell/RCL/VSA implementation inspected; worker reports successful solution/native builds, 65 passing cases and native route/asset checks |
| 2026-10-28 | Deviations recorded | Unintended workload manifest updates disclosed; no rollback; README CRLF-only diff hygiene noted for next documentation update |
| 2026-10-28 | Step-02 regenerated | Explicitly supersedes unexecuted pre-correction version; actual seven-project baseline and profile feature/UI scope; READY FOR WORKER |
| 2026-10-28 | Step-02 returned for review | Profile models/codec/catalog/UI, tests/fixtures/docs and reported 93-case/native verification inspected |
| 2026-10-28 | Step-02 requires correction | R-01 ambient-dependent timestamp parser and R-02 absent optional applicability constraints; passing reported tests do not cover them |
| 2026-10-28 | Step-02A prepared | Narrow correction with worker regressions/documentation/native checks; Step-03 blocked and not assigned |
| 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 |
## Manual handoff instruction
Provide regenerated [Step-02.md](Step-02.md) to the separate worker and request
execution of that assignment only. The worker must produce
`prompts/Step-02-Report.md` and stop.
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.
Return manually to the orchestrator for review. Reports, including final chat
reports, must follow the single plain triple-backtick copy-window requirement.

267
prompts/Step-02-Report.md Normal file
View File

@ -0,0 +1,267 @@
```
# Step-02 Worker Report
## Status
**COMPLETE** — implementation, complete Release build, all regression tests and
native Windows profile-feature smoke checks are complete. Manual orchestrator
acceptance remains pending. Step-03 was not started.
## Implemented functionality
- Added immutable Core vehicle/profile identity, revisions, vehicle facts, arbitrary
module instances, extensible capability declarations, status assessments,
evidence classification and applicability.
- Added Application schema-v1 JSON import/export, strict validation, atomic
registration, in-memory profile catalog, exact revision listing/selection and
export through a real DI service.
- Added the UI RCL route /vehicle-profiles. It imports explicit JSON, lists
revisions without auto-selection, requires an explicit selection, renders
identity/capability/provenance/unknown information and supplies read-only JSON
export.
- Added source-controlled synthetic truck baseline/variant and alternate-vehicle
fixtures. They are clearly marked synthetic and are not real vehicle definitions.
- Preserved the existing target selection and single-shell project graph. Profile
import/selection does not register or alter execution-target providers.
- Implemented metadata only. There is no vehicle connection/discovery, simulation,
diagnostic transport, calibration data/editor, firmware image, operation
executor, physical authorization, database, AI, cloud service or persistence.
## Domain, schema, catalog and public contracts
Core source is under src/AutoForge.Core/Vehicles/VehicleProfile.cs.
ProfileIdentifier remains stable across positive integer revisions; each revision
is an immutable saved configuration. SchemaVersion 1 is separate from profile
revision. Exact catalog identity is (profileIdentifier, revision), compared using
OrdinalIgnoreCase. Revisions under one profile identifier cannot rebind to another
vehicle or conflict on already-known manufacturer/model/year/optional identity
facts. Multiple revisions can represent distinct metadata configurations of the
same vehicle. Unknown optional facts and identifiers are explicit null.
Vehicle/module roles and operation identifiers are open strings rather than a
closed module-role enum. Module instance identity is distinct from role/name.
Capability status supports Supported, Unsupported, Unknown, Inaccessible and
Restricted. Missing declarations return a distinct not-declared Unknown
assessment. No declared status means a service, connection, permission or
authorization exists.
Evidence classifications are Verified, Unverified, Inferred and Synthetic.
Evidence includes source/description, applicable vehicle and optional model year,
exact profile revision, module and hardware/software/firmware/calibration context,
explicit optional timestamps, verification information, limitations and nullable
confidence. Numeric confidence is finite and in [0,1]. Evidence references must
resolve within the profile revision and match applicable vehicle/module identity.
Classification is supplied data, not independent verification. Evidence never
authorizes an operation.
Application public contracts are IVehicleProfileService,
IVehicleProfileJsonCodec, VehicleProfileServiceCollectionExtensions,
VehicleProfileInterchangeException and VehicleProfileCatalogException. JSON v1
requires every defined property; unknown optional values use explicit null and
collections use []. Unknown properties and duplicate or case-ambiguous object
properties are rejected. Enum tokens are uppercase exact values. Malformed,
missing, unsupported-version, invalid-type/status, duplicate identity and
dangling/conflicting applicability inputs fail explicitly with a JSON path or
catalog failure. No repair, migration, network, generated timestamp or file write
occurs. Failed JSON validation happens before registration; duplicate entries do
not replace existing profiles.
The Client composes a process-lifetime in-memory catalog; application exit clears
it. UI selection lives in the scoped page view model and is never global execution
state. See docs/vehicle-profile-schema-v1.md and ADR-0003 for the complete
documented shape and policy.
## Files created and modified
Created:
- src/AutoForge.Core/Vehicles/VehicleProfile.cs
- src/AutoForge.Application/Features/Vehicles/Profiles/VehicleProfileErrors.cs
- src/AutoForge.Application/Features/Vehicles/Profiles/VehicleProfileJsonCodec.cs
- src/AutoForge.Application/Features/Vehicles/Profiles/VehicleProfileCatalog.cs
- src/AutoForge.Application/Features/Vehicles/Profiles/VehicleProfileServiceCollectionExtensions.cs
- src/AutoForge.UI/Features/Vehicles/Profiles/VehicleProfilePageViewModel.cs
- src/AutoForge.UI/Features/Vehicles/Profiles/VehicleProfilesPage.razor
- src/AutoForge.UI/Features/Vehicles/Profiles/VehicleProfilesPage.razor.css
- src/tests/AutoForge.UnitTests/VehicleProfileDomainTests.cs
- src/tests/AutoForge.UnitTests/VehicleProfileJsonCodecTests.cs
- src/tests/AutoForge.IntegrationTests/VehicleProfileCompositionTests.cs
- src/tests/AutoForge.IntegrationTests/Fixtures/synthetic-truck-baseline.json
- src/tests/AutoForge.IntegrationTests/Fixtures/synthetic-truck-variant.json
- src/tests/AutoForge.IntegrationTests/Fixtures/synthetic-orchard-vehicle.json
- docs/vehicle-profile-schema-v1.md
- docs/adr-0003-profile-interchange-v1.md
- prompts/Step-02-Report.md
Modified:
- src/AutoForge.Client/MauiProgram.cs — register the in-memory profile feature.
- src/AutoForge.UI/Features/Foundation/AddAutoForgeUi.cs — register the scoped
profile page view model.
- src/AutoForge.UI/Layout/MainLayout.razor and _Imports.razor — navigation and
feature namespace.
- src/tests/AutoForge.IntegrationTests/AutoForge.IntegrationTests.csproj —
copy source-controlled JSON fixtures to test output.
- src/tests/AutoForge.IntegrationTests/UiCompositionTests.cs — compose profile
services alongside the existing target-selection test registration.
- README.md, docs/README.md, docs/architecture.md and docs/build-and-test.md.
- docs/adr-0002-single-shell-vsa.md — reflect Step-01A acceptance and document
the later profile slice without changing shell boundaries.
No project, RCL, executable, package dependency, central package pin or test
project was added. No existing Core/Application target behavior was moved or
removed. Only the required Step-02 report was created under prompts.
## Architecture and tests
The existing seven-project graph remains unchanged:
- Client -> UI and Application.
- UI -> Components and Application.
- Application -> Core.
- Components and Core -> no AutoForge project dependency.
- UnitTests -> Core, Application and Components.
- IntegrationTests -> Core, Application, Components and UI.
No production/test edges, cycles, second host or backend were added. The new
Application profile slice is Features/Vehicles/Profiles. The UI page and view
model are in the UI RCL and use the real service by DI. The native Client composes
the same service used in headless tests.
New unit tests cover valid/custom roles, same-role distinct modules, duplicate
module/evidence/operation identifiers, immutable input snapshots, unknown
optional values, all capability states and missing-declaration behavior,
confidence boundaries/non-finite values, classifications, timestamps,
applicability, schema round-trip, duplicate/unknown/missing properties, malformed
and unsupported JSON, invalid status and dangling evidence.
New integration tests load the baseline/variant/alternate fixtures through real
Application DI; assert values, statuses, unknowns, evidence and exact revision
selection; export/reimport; preserve immutable baseline variants; reject duplicate
and conflicting vehicle identities; verify failed imports are atomic; compose
profiles beside the unchanged target resolver; and render the actual routed UI
with metadata, errors and export. The alternate fixture uses a custom module role,
custom operation and unknown model year. The original component, route, target
selection, application and project-graph assertions remain.
## Environment and command results
- Windows 10.0.26200.0; .NET SDK 10.0.402; runtime .NET/ASP.NET Core 10.0.13.
- Windows SDK target 10.0.26100.0; MAUI Windows workload manifest 10.0.110;
read-only workload listing reports workload version 10.0.403.
- WebView2 Runtime 155.0.4283.62.
- Existing central packages and VSTest/xUnit stack were used unchanged.
- No workload-changing inspection, installation, update, repair, uninstall or
rollback command was invoked for Step-02. Read-only dotnet workload list was
used only to inspect installed prerequisites.
Commands and results:
- dotnet restore .\src\AutoForge.slnx — exit 0; all projects up to date.
- dotnet build .\src\AutoForge.slnx --configuration Release --no-restore — exit
0; all seven projects including native Client built, 0 warnings, 0 errors.
- dotnet build .\src\AutoForge.Client\AutoForge.Client.csproj --configuration Release --framework net10.0-windows10.0.26100.0 --no-restore
— exit 0; actual Windows TFM/win-x64 Client, 0 warnings, 0 errors.
- dotnet test .\src\AutoForge.slnx --configuration Release --no-build — exit 0;
UnitTests: 59 passed, 0 failed, 0 skipped. IntegrationTests: 34 passed,
0 failed, 0 skipped. Total 93 passed, 0 failed, 0 skipped.
- Baseline Step-01/Step-01A coverage was 65 cases (39 unit and 26 integration);
it remains present in the expanded total. No required test was skipped or
removed.
## Native Windows profile smoke
Launched the actual Release native executable
src/AutoForge.Client/bin/Release/net10.0-windows10.0.26100.0/win-x64/AutoForge.Client.exe
with an isolated WebView2 profile and temporary local DevTools port. The native
window title was AutoForge and the BlazorWebView loaded at https://0.0.0.1/.
- Home rendered; navigation reached /vehicle-profiles and showed an empty catalog.
- Importing the synthetic truck baseline returned a success notice, listed one
revision and did not auto-select. Explicit revision-1 selection displayed
Synthetic provenance, capability declarations, unknown values and a JSON
export containing the baseline calibration reference and applicable year.
- Importing the separate truck variant listed revision 2. Selecting revision 2
exported its variant calibration identifier and not the baseline calibration;
both revisions remained listed.
- Duplicate baseline import showed an error and retained two entries and the
explicitly selected variant. Malformed JSON also showed an error without
changing the catalog or selected variant.
- Importing/selecting the alternate profile showed its custom module role,
custom operation, and unknown model year.
- Home and /execution-targets still rendered. Target selection showed its honest
empty-provider state; profile operations did not register a provider. The
unknown path rendered the existing not-found route.
- AutoForge.UI and AutoForge.Components scoped CSS assets returned HTTP 200 and
contained the profile/status styles. Healthy route display had no unhandled
error banner.
- Stopped the exact native process and removed its exact temporary WebView2
profile. No screenshot was retained; observations came from the live native
WebView DOM and resource responses.
## Acceptance criteria evidence
| Criterion | Status | Evidence |
|---|---|---|
| AC-01 | PASSED | Existing seven-project graph, target behavior and manual/protected workflow preserved; final complete suite reports all 65 baseline cases within 93 passes. |
| AC-02 | PASSED | Immutable validated profiles/configuration revisions, vehicle identities, arbitrary modules and explicit unknowns in Core; domain positive/negative tests pass. |
| AC-03 | PASSED | All five states and missing-declaration Unknown lookup; duplicate operations rejected and no operational behavior added. Unit and fixture integration assertions pass. |
| AC-04 | PASSED | Provenance classes/source/confidence/timestamps/applicability and explicit model-year/module identities round-trip; mismatch/dangling tests pass. |
| AC-05 | PASSED | Strict schema-v1 parser/serializer round-trips and rejects malformed, missing, future, unknown, duplicate, invalid-status and invalid-reference inputs. |
| AC-06 | PASSED | Real DI catalog supports exact revision selection, immutable revisions and atomic failure; rendered UI imports/lists/selects/exports; native workflow verified. |
| AC-07 | PASSED | Three checked-in synthetic fixtures cover truck baseline/revision variant, alternate inventory, custom role/operation, all capability states and explicit provenance. |
| AC-08 | PASSED | Full Release solution and direct native build each 0 warnings/errors; 59 unit and 34 integration tests pass; native profile/route/assets smoke completed. |
| AC-09 | PASSED | README/index/architecture/build guide/schema guide/ADR reflect actual metadata-only behavior and lifecycle; README working file is LF with no trailing whitespace. |
| AC-10 | PASSED | This report created; protected assignment/orchestration files unchanged; no Step-03, stage, commit or push. |
## Corrected failures and known limitations
- An early domain test exposed that an omitted capability collection was rejected
instead of representing no declarations. The direct constructor now snapshots
an empty collection; the missing lookup explicitly reports Unknown.
- Early tests also exposed incorrect test-input string replacements and a
route-message case mismatch. The test probes were corrected to mutate the
intended JSON property and assert the rendered message accurately.
- A first invalid-applicability test fixture replacement did not alter the JSON.
The test now replaces the first applicability vehicle ID explicitly; it
verifies vehicle mismatch rejection and catalog revision rebind rejection.
- A first native list probe selected by position after sorting rather than by
identity. The corrected native probe selects exact identifiers/revisions and
confirmed variant and alternate selections.
- One build/test pair was initially launched concurrently; MSB3026 reported an
xUnit output-file lock and retry. The subsequent final sequential full build
completed with 0 warnings/0 errors, followed by the successful full test run.
- A PowerShell DevTools helper invocation had a spacing typo and stopped after
native launch; the corrected run completed. A DevTools evaluation during a
navigation was invalidated when the WebView context changed; verification
reconnected and confirmed the not-found page. Neither was an application
failure.
- The catalog is in-memory and clears at process exit. Strict v1 rejects unknown
properties and future schema versions until a deliberate supported migration
is implemented. No real vehicle compatibility or operational support is
implied.
## Documentation, preservation and handoff
Added schema-v1 documentation and ADR-0003. Updated the root README, documentation
index, architecture/build guidance and ADR-0002. ADR-0001 and all prior reports
remain unchanged. Step-01A is described as accepted; Step-02 implementation is
complete for worker review, not yet manually accepted.
The root README working file is LF-normalized (149 LF, 0 CRLF, 0 trailing
whitespace). Git core.autocrlf is true and the existing index README is CRLF, so
Git emits its normal LF-to-CRLF working-copy warning; no global Git setting or
unrelated file was changed to suppress it. The CRLF-aware diff whitespace check
passed.
Final Git/status review found only the expected source, UI, tests, fixtures,
README and technical-documentation changes plus this new report. Prompts/
ROADMAP.md, STATE.md, Step-01/Step-01A assignments and reports, Step-02.md,
protected instructions and Git metadata were unchanged. The only prompts change
is this report. Top-level project directories remain docs, src and prompts.
No dependency pins changed, no workload-changing command was invoked, and no
commit, stage, push, destructive cleanup or automatic handoff occurred.
Implementation and verification are complete for manual orchestrator review.
STOP here; do not begin Step-03.
```

285
prompts/Step-02A-Report.md Normal file
View File

@ -0,0 +1,285 @@
```
# Step-02A Worker Report
## Status
**COMPLETE** for the assigned worker implementation and verification. Both
corrections, regressions, documentation, complete Release build/test suites and
native Windows smoke checks are finished. Manual orchestrator acceptance of
Step-02/Step-02A remains pending. Step-03 was not started.
## Objective and scope
Corrected only the Step-02A findings:
- R-01: timestamp import previously accepted incomplete and ambient-dependent
date/time forms.
- R-02: null optional evidence identity fields were incorrectly treated as
assertions that the corresponding target module identities were also null.
The existing seven-project modular monolith, Client/UI/Components ownership,
Core/Application feature boundaries, real DI, `/vehicle-profiles` UI, catalog
atomicity, exact revision selection and metadata-only safety boundary remain.
No new executable, assembly, project reference, package, persistence layer,
external service or vehicle-operation capability was added.
## R-01 root cause and fix
`VehicleProfileJsonCodec.NullableDate` used `DateTimeOffset.TryParse` with
InvariantCulture and RoundtripKind. That parser could supply today's date for
time-only values, use the machine-local zone when the offset was absent, and
accept whitespace/culture forms outside the v1 timestamp contract. The previous
generic failure text also did not describe the required complete input.
The replacement parser first matches a strict ASCII lexical form and then parses
the date/time portion with `DateTime.TryParseExact`, invariant culture and
`DateTimeStyles.None`. It validates the explicit suffix itself and constructs
`DateTimeOffset` from the exact parsed wall time and supplied offset; no current
date, local time-zone default or assumption style is used. Invalid calendar,
offset and representability values fail as a typed
`VehicleProfileInterchangeException`.
Accepted values are explicit JSON null or exactly:
`YYYY-MM-DDTHH:mm:ss[.fraction](Z|+HH:mm|-HH:mm)`.
The four-digit Gregorian date, uppercase `T`, hours/minutes/seconds and explicit
offset are required. The optional decimal fraction has 1-7 ASCII digits.
Offsets are whole-minute values within -14:00 through +14:00. No surrounding
whitespace, date-only/time-only, missing seconds/year/offset, slash/culture
dates, malformed calendar dates, invalid offsets or extra fractional precision
are accepted. The JSON error identifies the exact `publishedAt` or `retrievedAt`
path. Existing round-trip export remains unchanged.
## R-02 root cause and fix
`VehicleProfile.ValidateEvidenceReferences` used `SameOptional` for each of the
four module-scoped hardware/software/firmware/calibration applicability values.
The helper required a null evidence constraint to match a null module value,
rejecting an otherwise valid module-scoped record whenever it omitted a known
module identity.
The shared helper now interprets null on the evidence side as no constraint.
Every supplied non-null value still must match a known target module value using
ordinal case-insensitive comparison. A mismatch or any supplied value targeting
an unknown module identity is rejected. Nothing is copied into the evidence or
module, inferred, promoted or authorized. A module-scoped evidence record can
omit all four optional identity constraints. Version-specific constraints still
require an explicit module ID. The same profile validation is used for direct
constructors and imported profiles, including both module and capability
evidence references; vehicle/profile/revision/model-year/reference checks remain.
## Before-fix reproductions
The tests were added and run against the original Step-02 implementation before
either correction:
- `dotnet test .\src\tests\AutoForge.UnitTests\AutoForge.UnitTests.csproj --configuration Release --no-restore --filter FullyQualifiedName~VehicleProfileJsonCodecTests`
exited 1: 18 failed, 19 passed, 0 skipped, 37 total. The failures included
accepted date-only, offset-free, time-only and whitespace-padded strings, plus
invalid-offset failures whose generic error did not meet the precise guidance
assertion. Both timestamp property names were exercised.
- `dotnet test .\src\tests\AutoForge.UnitTests\AutoForge.UnitTests.csproj --configuration Release --no-restore --filter FullyQualifiedName~VehicleProfileDomainTests`
exited 1: 1 failed, 24 passed, 0 skipped, 25 total. The module-only evidence
vector with all optional identities null failed direct Core construction
despite matching vehicle/profile/revision/module context and known target
identities.
- `dotnet test .\src\tests\AutoForge.IntegrationTests\AutoForge.IntegrationTests.csproj --configuration Release --no-restore --filter "FullyQualifiedName~PartialModuleEvidence|FullyQualifiedName~InvalidTimestamp"`
exited 1: 2 failed, 0 passed, 0 skipped, 2 total. The real profile-page/service
path rejected partial evidence applicability and accepted a time-only timestamp
instead of displaying the expected property error.
These are actual pre-fix executions, not inferred results. The integration
mutation helper was corrected to update profile applicability revisions when it
creates a new test revision; it also asserts the changed timestamp/identity paths
so the intended failure vectors cannot silently be missed.
## Regression coverage and after-fix results
Unit regressions now cover both `publishedAt` and `retrievedAt` for explicit
null, UTC Z, positive/negative numeric offsets, non-fractional input, one-digit
fractions, seven-digit exporter-style fractional input, and invalid time-only,
date-only, missing-offset, missing-year, culture/slash, padded, malformed-date
and invalid-offset values. Rejections assert the exact property path and
actionable format guidance. Exact `DateTimeOffset.EqualsExact` assertions verify
wall time, fractional ticks and offset. Export/reimport separately verifies the
existing seven-digit format.
Core regressions exercise module-only matching evidence with all four optional
identities null, each field omitted independently, mixed absent/supplied matching
constraints, preservation of known module values and classification, and both
module-level and capability-level evidence references. Negative cases cover
each identity mismatch against a known target and each supplied constraint
against an unknown target. Additional negative cases cover wrong vehicle,
profile, revision and module contexts; existing dangling-reference, conflicting
model-year, duplicate identity and evidence-resolution tests remain.
Real Application DI and actual routed UI integration tests:
- Import, explicitly select, export and reimport module-only evidence with all
four optional applicability identities null while module identities remain
known and unchanged.
- Reject an invalid timestamp on a distinct revision before registration and
show the exact JSON path/guidance; catalog contents and current explicit
selection remain unchanged.
- Reject a supplied conflicting module identity through the same real feature
service, render the scope error and preserve catalog/selection.
- Render the corrected positive import/export route through the actual profile
page/view model and retain existing target-selection isolation assertions.
After the fixes:
- Focused unit command:
`dotnet test .\src\tests\AutoForge.UnitTests\AutoForge.UnitTests.csproj --configuration Release --no-restore --filter "FullyQualifiedName~VehicleProfileJsonCodecTests|FullyQualifiedName~VehicleProfileDomainTests"`
exited 0: 64 passed, 0 failed, 0 skipped.
- Focused integration command:
`dotnet test .\src\tests\AutoForge.IntegrationTests\AutoForge.IntegrationTests.csproj --configuration Release --no-restore --filter FullyQualifiedName~VehicleProfileCompositionTests`
exited 0: 11 passed, 0 failed, 0 skipped.
## Full build and suite results
Commands were run sequentially, not concurrently:
- `dotnet build .\src\AutoForge.slnx --configuration Release --no-restore`
exited 0. All seven solution projects built, including the native Client at
`net10.0-windows10.0.26100.0` / `win-x64`; 0 warnings and 0 errors.
- `dotnet test .\src\AutoForge.slnx --configuration Release --no-build`
exited 0. AutoForge.UnitTests: 103 discovered/executed, 103 passed, 0 failed,
0 skipped. AutoForge.IntegrationTests: 37 discovered/executed, 37 passed,
0 failed, 0 skipped. Total 140 passed, 0 failed, 0 skipped.
The expanded suites include all 93 Step-02 worker-reported cases (59 unit, 34
integration); the prior Step-02 report remains historical evidence and was not
rewritten as if it covered these corrections. The final solution build itself
also built the native Client, so no separate direct Client build was necessary
for launching that exact Release executable. No package restore was needed.
## Native Windows smoke evidence
The actual Release native executable
`src/AutoForge.Client/bin/Release/net10.0-windows10.0.26100.0/win-x64/AutoForge.Client.exe`
was launched twice in a visible MAUI window with isolated WebView2 profiles and
temporary DevTools ports. The WebView title was `AutoForge`; its URL was
`https://0.0.0.1/`. Interactions were issued to the actual WebView DOM and the
resulting page/export values were inspected.
First run, process ID 56960, DevTools port 9338:
- Imported a baseline-derived profile containing a fractional explicit
`+05:30` publication time, UTC retrieval time, and module-only evidence with
all four optional identity fields null. Import did not auto-select. Explicit
revision-1 selection displayed the module's known hardware identity and export
retained all four evidence nulls. The fractional timestamp exported as
`2025-02-03T04:05:06.1234567+05:30`; UTC exported as
`2025-02-03T04:05:06.0000000+00:00`, preserving UTC offset/time/precision
semantics in the existing round-trip format.
- Attempted a time-only timestamp on a new revision. The UI showed
`$.evidence[1].retrievedAt` and explicit-offset format guidance. The catalog
remained at one revision and selected revision 1 remained selected.
- Attempted a conflicting supplied hardware constraint on another revision.
The UI displayed the conflicting module applicability error; catalog count
and explicit selection remained unchanged.
- Imported and explicitly selected the original synthetic truck variant
(revision 2) and verified its distinct `calibration.synthetic.engine-variant`.
- Imported and selected the original alternate orchard fixture and verified
its custom module role and unknown model year.
- Navigated to `/execution-targets`; the existing empty-provider metadata state
rendered and stated that no connection is attempted.
Second run, process ID 51724, DevTools port 9339:
- Imported the untouched source-controlled synthetic truck baseline, selected
revision 1 and verified the three-module export and original
`calibration.synthetic.engine-base`.
- Navigated to `/execution-targets` and verified the empty-provider metadata
route remained functional without connecting.
Both exact Client process IDs were stopped. Their exact temporary profiles
`AutoForge-Step02A-WebView2-9338` and `AutoForge-Step02A-WebView2-9339` were
removed. No screenshot was retained; results are from the live native DOM and
export state. The original source fixtures were not modified.
## Documentation and lifecycle status
Updated:
- `README.md`: Step-02A status, timestamp/absence-constraint behavior, current
worker test/build/native evidence and pending manual acceptance.
- `docs/vehicle-profile-schema-v1.md`: exact timestamp grammar, null/offset
behavior, absence-versus-supplied identity constraints and validation rules.
- `docs/adr-0003-profile-interchange-v1.md`: corrected decision and consequences.
- `docs/build-and-test.md`: current suite counts, distinct historical Step-02
evidence, correction/native smoke steps and safety constraints.
- `docs/README.md`: current worker/acceptance lifecycle and report links.
- Created this required worker report.
The seven-project graph and one Client/two RCL architecture remain unchanged.
Profile data remains process-local metadata. Timestamp/evidence classification
does not verify real-world accuracy, infer unknown identities, establish
compatibility, connect to hardware or authorize any operation.
## Acceptance criteria
| Criterion | Status | Evidence |
|---|---|---|
| AC-01: complete explicit-offset timestamp grammar or null; no ambient defaults | PASSED | Exact regex/date parse and offset validation; both fields tested across valid and invalid vectors, exact path and offset/tick assertions; native invalid-time error. |
| AC-02: absent optional module constraints remain absent; supplied constraints stay strict | PASSED | Direct-constructor all-null/single-null/mixed matrix; matching, known mismatch and unknown-target cases; identities/classification preserved. |
| AC-03: Core, JSON/service and actual UI consistency with atomic failure/selection | PASSED | Real DI/UI positive partial round-trip, exact timestamp failure, conflicting scope failure, unchanged catalog and selection; native paths confirmed. |
| AC-04: original fixtures, metadata, revisions, target isolation, prior 93 cases and architecture | PASSED | Full suite 140/140 includes original suites; actual baseline/variant/alternate native import/select/export and target route; seven-project build unchanged. |
| AC-05: pre-fix reproductions, full build/test and native verification | PASSED | Actual failing runs documented above; focused corrected suites pass; sequential full build has 0 warnings/errors; 103+37 tests and native scenarios pass. |
| AC-06: docs accurately describe contract and lifecycle | PASSED | README, schema guide, ADR-0003, build/test guide and docs index updated; manual acceptance remains pending. |
| AC-07: no unrelated feature/package/workload/orchestration/handoff; report complete | PASSED | Only R-01/R-02 source/tests/docs and required report changed by this worker; no workload-changing command, stage, commit, push, assignment/state/roadmap edit, agent or Step-03. |
## Corrected harness issues and deviations
- The first new integration-test compile surfaced xUnit analyzer xUnit2031 guidance
to use `Assert.Single(collection, predicate)` instead of filtering before
`Assert.Single`; the assertions were corrected before the reproduction run.
- The first partial-evidence integration vector changed the profile revision but
not its exact evidence applicability revision. The helper now updates every
applicable evidence revision and asserts the intended null/conflicting JSON
mutations before invoking the service.
- The first successful native import probe dispatched `input`, but the page
binds its textarea on `change`. The probe was corrected to dispatch `change`;
the actual native import then succeeded.
- An initial native verification compared exported UTC `Z` text lexically. The
existing round-trip exporter writes UTC as `+00:00` with seven fractional
digits. Verification was corrected to check the exact UTC wall time, zero
offset, retained fractional precision, and full `+05:30` value. No code change
was needed; this is the documented schema-v1 export representation.
- The first native summary script evaluated `document` in Node rather than inside
the WebView DevTools context. It was corrected to evaluate through CDP; native
scenarios then completed successfully.
- No scope or architecture deviation. No direct Client-only build was run
because the required full solution build successfully produced the exact
Windows Client target used in native smoke.
## Environment and preservation review
- Windows x64; .NET SDK 10.0.402; runtime 10.0.13.
- Windows SDK target 10.0.26100.0; MAUI Windows manifest 10.0.110; installed
workload version 10.0.403; WebView2 Runtime 155.0.4283.62.
- No packages were added or manifests changed. No restore was required.
- `dotnet workload list` was read-only. No workload install, update, restore,
repair, rollback or uninstall command was invoked.
- The worktree was already dirty before this assignment with Step-02 changes and
orchestrator-owned changes to `prompts/ROADMAP.md`, `prompts/STATE.md` and the
new `prompts/Step-02A.md`. Those pre-existing changes were preserved. This
worker did not modify any assignment, roadmap, state, previous report or
protected instruction file.
- The only file created under `prompts` by this worker is this report. The
`.github/copilot-instructions.md` file remains absent. Top-level project
directories remain `docs`, `src` and `prompts`.
- Modified documentation is LF-only with no trailing whitespace. Git
`core.autocrlf=true` causes the expected warning for the tracked LF
`README.md`, `docs/README.md` and `docs/build-and-test.md` that they will be
replaced by CRLF on a future Git touch; no global setting was changed.
- No staging, commit, push, destructive cleanup, automated handoff or agent
invocation occurred.
## Outstanding items and handoff
No worker implementation or required verification remains. Manual orchestrator
review and acceptance of the corrected Step-02 work remain outstanding. Do not
begin Step-03 until that acceptance and any further manual direction.
STOP here.
```

280
prompts/Step-02A.md Normal file
View File

@ -0,0 +1,280 @@
# Step-02A - Explicit profile timestamps and optional evidence constraints
## STEP IDENTIFIER
Step-02A, corrective assignment for Step-02. Step-02 is NOT ACCEPTED.
This is the sole active assignment. Step-03 is blocked and not assigned.
## STEP TITLE
Correct ambient-dependent timestamp parsing and over-restrictive optional module
evidence applicability, preserving the existing profile feature.
## OBJECTIVE
Fix two specific source/contract defects, add meaningful regressions, verify the
real Application/UI/native path, and align related documentation. Preserve all
other Step-02 behavior and the accepted single-shell/RCL/VSA architecture.
You are the WORKER. Execute only this correction, write
`prompts/Step-02A-Report.md`, and STOP for manual orchestrator review.
## ARCHITECTURAL CONTEXT
Read [STATE.md](STATE.md), [ROADMAP.md](ROADMAP.md), original
[Step-02](Step-02.md), its [report](Step-02-Report.md), the
[schema guide](../docs/vehicle-profile-schema-v1.md) and
[ADR-0003](../docs/adr-0003-profile-interchange-v1.md).
Keep the seven-project modular monolith: Client -> UI -> Components, with
Application feature slices depending on reusable Core contracts. Client remains
the only application executable; no backend, mediator, new host or new assembly.
All application/test projects stay under `src`, tests under `src/tests`.
Only `docs`, `src`, `prompts` are top-level project directories.
The orchestrator found the issues by inspecting source/contracts and official
.NET documentation, without running application builds/tests. Reproduce the
issues yourself; do not treat static findings as already executed regressions.
## CURRENT IMPLEMENTATION STATE
Step-02 introduced:
- Immutable Core vehicle/profile/module/capability/evidence types in
`src/AutoForge.Core/Vehicles/VehicleProfile.cs`.
- Application feature at `Features/Vehicles/Profiles`: strict schema-v1
import/export, an in-memory revision catalog, exact selection and real DI.
- UI `/vehicle-profiles` with explicit JSON import, revision selection,
metadata/provenance inspection and export; no auto-selection or target changes.
- Three synthetic fixtures and expanded tests. The worker reports 59 unit and
34 integration cases passed (93 total, zero failed/skipped), full solution and
direct native Release builds with zero warnings/errors, and native profile smoke.
These reported runs remain valid evidence of their covered cases, not proof
that the two missing cases work.
Step-01/Step-01A remain accepted. There is no simulation, diagnostic transport,
calibration data/editor, physical operation, persistent database/file store or AI.
Preserve previous assignments/reports and any concurrent work. Reinspect Git and
instructions before editing; do not assume the worktree is clean.
## REQUIRED IMPLEMENTATION
### R-01 - Require complete, explicit-offset timestamp input
Location:
[VehicleProfileJsonCodec.cs](../src/AutoForge.Application/Features/Vehicles/Profiles/VehicleProfileJsonCodec.cs),
`NullableDate`, line 478.
Current code uses DateTimeOffset.TryParse with InvariantCulture and RoundtripKind.
The [official TryParse documentation](https://learn.microsoft.com/en-us/dotnet/api/system.datetimeoffset.tryparse?view=net-10.0)
states that a missing date defaults to the current day, a missing offset defaults
to the local zone, and RoundtripKind has no effect for DateTimeOffset. This
accepts forms outside the explicit timestamp contract and can invent metadata
from the execution environment.
Correct both `publishedAt` and `retrievedAt`:
1. Keep explicit JSON null as unknown.
2. Accept a documented, strict ISO-8601 subset containing the complete calendar
date, time including seconds and an explicit `Z` or signed `HH:mm` UTC offset.
Support the existing exporter's round-trip format, including its fractional
seconds and numeric offsets. Preserve supplied instant/offset/precision
semantically; do not invent or silently reinterpret missing parts.
3. Reject time-only, date-only, offset-free date/time, culture-style/slash dates,
missing-year forms, whitespace-padded input, malformed dates and invalid
offsets. Do not replace missing pieces with today, local time, UTC or defaults.
4. Surface VehicleProfileInterchangeException with the precise offending
publication/retrieval JSON path and actionable format guidance. Invalid input
must fail before catalog registration.
5. Use a simple verified .NET implementation. Merely switching culture,
DateTimeStyles.None/AssumeUniversal, or relying on a permissive helper does not
satisfy strictness. Verify the actual lexical and offset behavior.
Do not change the schema version merely to fix behavior that violated the stated
v1 contract. Record the newly explicit supported timestamp subset in schema docs.
Do not alter the system date, time zone or machine settings to test this.
### R-02 - Distinguish an absent identity constraint from an asserted null match
Location:
[VehicleProfile.cs](../src/AutoForge.Core/Vehicles/VehicleProfile.cs),
module applicability validation at line 367 and `SameOptional` at line 408.
The helper currently returns `right is null` whenever the evidence identity is
null. It therefore rejects evidence that specifies a matching module but omits
an optional hardware/software/firmware/calibration constraint whenever the module
has that identity. The schema describes those context fields as optional.
Concrete baseline vector: keep the module's known hardware identity and all
matching vehicle/profile/module context, but set only the evidence's hardware
applicability to explicit null. No hardware constraint was supplied; the otherwise
compatible profile must not be rejected for that omission.
Required behavior:
- A null optional evidence identity means no constraint was supplied for that
field. It does not assert that the corresponding module identity must be null.
- A module-scoped record with no version-specific identity constraints is valid
when its vehicle/profile/module context is valid.
- Validate every supplied non-null constraint. Preserve rejection of mismatched
known values and supplied constraints against unknown target module values.
Do not convert an unknown target into a verified match or fill its identity.
- Preserve rejection of dangling/wrong module IDs, wrong vehicle/profile/revision,
conflicting known model years and invalid evidence references. Version-specific
context without a module instance remains invalid.
- Apply consistent rules across module and capability evidence references,
direct constructors and JSON/service import. Preserve immutable originals,
classifications, limitations, unknowns and lack of operational authorization.
Use the smallest clear shared validation change. Do not duplicate alternative
matching logic in the codec/UI or weaken known-constraint checks to pass tests.
Document precisely the absence-versus-supplied-constraint semantics.
## FILES OR PROJECTS EXPECTED TO CHANGE
- Correct the two existing Core/Application validation paths.
- Extend the existing domain/codec unit tests and real profile composition/UI
integration tests. Add focused fixture variants only if necessary; preserve
the original synthetic baseline/variant/alternate inputs where possible.
- Update schema/build guidance, relevant ADR text, documentation index if needed,
and root README for actual corrective status and verification.
- UI changes only if needed to expose the corrected service failures/results;
no new page/host/engine or scope expansion.
- Create only `prompts/Step-02A-Report.md` under `prompts`.
Do not modify assignments, ROADMAP, STATE, previous reports or protected Copilot
instructions. Do not create override instruction files, initialize Git, stage,
commit, push, discard unrelated changes or perform destructive cleanup.
## INTERFACE AND DEPENDENCY REQUIREMENTS
Preserve existing public feature contracts and seven-project reference graph.
Keep validation in Core/Application; UI remains presentation. Preserve typed
errors, catalog atomicity, exact revision selection, no target substitution and
all prior metadata-only/safety boundaries. No new package, major tool installation,
workload update/restore/repair/rollback or external service is expected or
authorized. Ordinary package restore is distinct from workload-changing commands.
## TESTING REQUIREMENTS
### Reproduction and unit regressions
First add focused tests that demonstrate each issue against the current code,
execute them and record the actual pre-fix failures. Then implement the correction
and rerun them. Do not fabricate before/after results.
For **both** timestamp fields:
- Invalid: time-only, date-only, full time without offset, missing-year,
culture-style date, whitespace-padded, malformed calendar and invalid-offset
input. Assert explicit interchange failure and the correct property path.
- Valid: null; UTC `Z`; positive/negative numeric offsets; non-fractional and
exporter-produced fractional values. Assert the exact expected date/time,
offset and round-trip semantics, not just successful parsing.
- Ensure no format can depend on current day or local zone. Do not change global
clock/time-zone settings. Keep the tests deterministic.
For evidence:
- Module-only matching context with all four optional identity constraints null.
- Each optional constraint independently null while the module's corresponding
value is known, plus mixed supplied/absent matching constraints.
- Supplied non-null constraints matching the module succeed.
- Supplied constraints conflicting with a known value or targeting an unknown
value fail; wrong/dangling module, vehicle/profile/revision and evidence
references continue to fail.
- Assert identities/classification/unknowns are preserved, not inferred or promoted.
### Real DI and UI integration
Import/select/export/reimport through the real profile feature:
1. Invalid timestamp rejects atomically with the expected interchange path and
unchanged catalog/current explicit selection. Do not let a duplicate-key
error mask whether the timestamp was validated.
2. A profile containing valid partial/module-only evidence context imports and
round-trips with the absent fields still null.
3. Invalid supplied identity constraints still reject atomically.
4. Actual routed UI displays the timestamp/scope errors and accepts the corrected
positive case via the same real service; no fake feature/component under test.
Use robust data mutation helpers or assert that test mutations really changed the
intended JSON path. Existing successful string replacements are not proof that
the specific invalid vector was exercised.
### Build, regression and native evidence
Preserve all 93 current cases/invariants, add the missing regressions, and run
focused checks while implementing. Then run, sequentially, the complete Release
solution build and both suites using the existing SDK/runner:
- `dotnet build .\src\AutoForge.slnx --configuration Release --no-restore`
- `dotnet test .\src\AutoForge.slnx --configuration Release --no-build`
- Direct Windows Client build when needed for native target verification, using
the existing `net10.0-windows10.0.26100.0` target; no framework override on
portable projects. Restore packages only when needed.
Record exact commands/exit outcomes, target/configuration, warnings and per-project
discovered/passed/failed/skipped counts. Do not run competing build/test processes
against the same outputs or skip required cases to report success.
Launch the actual native Client and verify a valid explicit timestamp/partial
evidence profile imports/selects/exports, an invalid timestamp shows its specific
error, and a conflicting supplied constraint fails without catalog/selection
replacement. Verify original fixture import and target metadata routes still
work. Record observations separately from headless tests; report any exact
environment blocker and unexecuted check honestly.
## DOCUMENTATION REQUIREMENTS
Update the root README and directly related schema/ADR/testing documentation with:
- The exact accepted timestamp grammar and explicit null/offset rules.
- Absence versus supplied optional evidence constraints, preserved mismatch/
unknown-target handling and the fact that validation never grants authority.
- Step-02/Step-02A worker verification versus pending orchestrator acceptance,
actual test/native evidence and limitations.
- Existing one-shell/two-RCL/VSA architecture and native startup/build instructions.
Keep Markdown LF convention and historical reports intact. Do not rewrite the
original 93-test evidence as though it covered these new cases.
## ACCEPTANCE CRITERIA
| ID | Criterion | Required evidence |
|---|---|---|
| AC-01 | Both timestamp properties accept only the documented complete, explicit-offset grammar or null; no ambient defaults | Positive/negative vectors, exact date/offset assertions and implementation paths |
| AC-02 | Partial/module-only optional evidence context works without mutating unknowns or weakening supplied-constraint validation | Direct constructor matrix covering all four fields and positive/negative identity cases |
| AC-03 | Domain, JSON/service and actual UI paths consistently implement the corrected rules, preserving atomic failed import/explicit selection | Real DI/rendered integration assertions and exact failure paths |
| AC-04 | Original fixtures, metadata statuses/provenance, exact revisions, target isolation, all 93 prior cases and architecture remain intact | Regression mapping, source/project/Git review and per-project results |
| AC-05 | Focused new tests demonstrate actual pre-fix failures and pass after correction; complete solution/native verification succeeds | Before/after commands/results, sequential Release build/test evidence and native observations |
| AC-06 | README/schema/ADR/test guidance accurately describe the corrected v1 contract and corrective lifecycle | Changed documentation list and exact policy summary |
| AC-07 | No unrelated feature, package/workload action, orchestration/protected-file edit or automatic handoff introduced; report complete and worker stops | Preservation/scope evidence and `prompts/Step-02A-Report.md` |
Map every criterion to PASSED, FAILED, NOT EXECUTED or BLOCKED with concrete
evidence. COMPLETE requires all required correction/regression/native checks.
Do not begin Step-03; acceptance belongs to the orchestrator.
## OUT-OF-SCOPE WORK
New vehicle features, simulation/diagnostic engines or protocols, transport/
hardware/provider integration, calibration values/programming, persistence,
research/AI, new shells/RCLs, mediator/generic repository refactors, broad model
redesign and unrelated UI cleanup. All physical safety/prohibited-operation
restrictions remain unchanged.
## REPORTING REQUIREMENTS
Create `prompts/Step-02A-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; functionality and
architectural changes; files created/modified; R-01/R-02 root causes and fixes;
unit/integration tests and before/after evidence; exact build/test commands and
results with per-project counts; native observations; AC-01 through AC-07 mapping;
documentation and README changes; limitations/outstanding issues; deviations;
recommendations; and protected/scope/Git preservation review.
Save the report and STOP. Do not change assignments/roadmap/state, create or begin
Step-03, invoke another agent, automate handoff, stage, commit or push.

423
prompts/Step-03.md Normal file
View File

@ -0,0 +1,423 @@
# Step-03 - Virtual modules and simulated diagnostic communication
## STEP IDENTIFIER
Step-03. Step-02 and its correction Step-02A were accepted on 2026-10-28.
This is the sole active implementation assignment.
## STEP TITLE
Connect an explicitly selected synthetic vehicle through a real simulated
transport; discover virtual modules, inspect identity/DTC/static telemetry and
communication traces, and verify deterministic failures.
## OBJECTIVE
Deliver one complete simulated-diagnostics vertical slice in the existing native
Client. Application features and UI must use provider-neutral diagnostic services
that encode requests, traverse the simulated transport, reach virtual modules,
decode responses and produce truthful results/traces.
This is not the vehicle-dynamics milestone. Telemetry is an explicitly labeled
static synthetic module-state snapshot, not fabricated live physics or a real
vehicle capture. No physical adapter, programming, AI, backend or extra executable.
You are the WORKER. Execute only this assignment, verify it, write
`prompts/Step-03-Report.md`, and STOP for manual orchestrator review.
## ARCHITECTURAL CONTEXT
Read [ROADMAP.md](ROADMAP.md), [STATE.md](STATE.md), the accepted
[profile assignment](Step-02.md), [correction](Step-02A.md) and their reports,
the [architecture](../docs/architecture.md) and
[schema guide](../docs/vehicle-profile-schema-v1.md).
Keep the .NET 10 modular monolith and application Vertical Slice Architecture.
Client is the only application executable; UI owns routes/feature presentation;
Components owns generic reusable controls. Application coordinates domain and
capability libraries, not UI/hardware implementations. No mediator or generic
repository/manager layer is needed.
All source/projects/tests belong under `src`, tests under `src/tests`. Root project
directories remain exactly `docs`, `src`, `prompts`, preserving protected
infrastructure. Handoffs remain manual; no agent automation, watchers or polling.
## CURRENT IMPLEMENTATION STATE
The solution currently contains seven projects:
- Core: explicit execution-target metadata and immutable vehicle/profile/module/
capability/provenance models.
- Application: `Features/ExecutionTargets/SelectExecutionTarget` and
`Features/Vehicles/Profiles`, with validated DI, schema-v1 import/export,
process-local catalog and exact profile/revision selection.
- Components: reusable StatusNotice.
- UI: `/`, `/execution-targets`, `/vehicle-profiles`, layout/navigation and
not-found handling; scoped presentation state invokes actual application services.
- Client: Windows MAUI Blazor Hybrid, native lifecycle/BlazorWebView/composition.
- UnitTests and IntegrationTests: portable Core/Application/RCL/graph tests.
Client -> UI/Application; UI -> Components/Application; Application -> Core.
Components has no AutoForge project reference. No cycle or separate backend.
Accepted correction requires complete date/time/seconds and explicit timestamp
offset, preserves fractional precision, and treats null optional module evidence
identities as absent constraints while validating supplied values. Preserve it.
Worker evidence records a complete seven-project Release build with zero warnings/
errors, 103 unit + 37 integration cases passed (140 total, zero failed/skipped),
and native profile/error/original-fixture smoke. These are previous worker
results, not an orchestrator runtime rerun.
Current target-provider registration is intentionally empty: resolving metadata
does not connect. No diagnostic/provider session, protocol, transport, virtual
module or physics engine exists yet.
Verified worker platform: SDK 10.0.402, runtime 10.0.13, Windows 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
restore/install/update/repair/rollback or other major environment change is
authorized. Ordinary package restore is distinct.
Recheck Git/instructions and preserve pre-existing dirty implementation and all
historical assignments/reports. Do not assume a clean worktree.
## REQUIRED IMPLEMENTATION
### 1. Establish the two actual capability boundaries
Add these purposeful `net10.0` class libraries to the existing solution:
| Project | Responsibility | Allowed project references |
|---|---|---|
| `src/AutoForge.Diagnostics` | Provider/session/transport contracts, diagnostic messages, explicitly synthetic protocol client/codec, decoded identity/DTC/signal results and communication trace | Core |
| `src/AutoForge.Simulation` | Data-driven virtual modules, isolated state, simulated transport/provider, deterministic fault behavior | Core, Diagnostics |
Application may reference Diagnostics but must not reference Simulation.
Client composes the actual Simulation provider through diagnostic interfaces;
it may reference Simulation for composition only. UI calls Application/appropriate
contracts and must not reference Simulation or native adapters. Core, Diagnostics
and Simulation must not depend on UI, Client or their coordinating application
slices. Preserve Components independence and production/test separation.
Expected solution total: nine projects, still one application executable and the
same two test projects. Update the existing project-graph assertions deliberately.
Do not create empty Calibration/Telemetry/AI projects or a new clock/ports assembly.
### 2. Add explicit provider and session selection
Build the smallest provider-neutral connection/session path:
- User selects an exact saved profile/revision and an explicit provider ID/kind.
Reuse the existing target descriptor/resolver invariants; do not create a
competing identity/default-selection scheme.
- A real Simulation provider implements the diagnostic factory/transport path.
Register its descriptor and implementation consistently from one source of
registration data. Duplicate/mismatched IDs or kinds fail explicitly.
- Metadata resolution remains metadata-only. Opening a simulated session is a
separate explicit action, clearly labeled Simulation in UI/results/trace.
- Unknown profile/revision, unregistered provider, mismatched kind or missing
simulation definition fail without choosing a latest/first/demo alternative.
- RecordedReplay and PhysicalHardware remain unavailable for operational
connections; do not substitute Simulation or create fake connected providers.
- Session identity binds the selected profile snapshot, target and configuration.
No mutable global active vehicle/target. Different sessions have isolated
virtual state, traces and cancellation/disposal.
- Closing/resetting a session has explicit lifecycle semantics and releases its
resources; it does not modify the source profile or another session.
Use ordinary DI and async/cancellation where communication requires it.
Do not introduce a plugin framework, hidden server or service locator.
### 3. Define synthetic module behavior as data, not manufacturer assumptions
Create a clearly synthetic diagnostic example with at least three module
instances, including a non-powertrain module. Bind virtual endpoints, identities,
implemented services, initial DTC state and static signal definitions/values to
validated profile/module IDs.
- Use open module roles/instance IDs; do not special-case the engine/TCU list in
application features. Demonstrate another inventory/configuration in tests.
- Validate duplicate addresses/IDs, missing mappings, incompatible profile/revision
and invalid service/signal definitions explicitly.
- Preserve schema-v1 profiles and original fixtures. Put endpoint/service/state
configuration in a separate validated simulation definition rather than adding
silently ignored fields to the strict profile document.
- Profile capability/provenance declarations are metadata, not proof of an
implemented service or authorization. Definition/provider/session availability
must be distinguished from supplied claims and unknown/inaccessible/restricted/
unsupported states. Do not silently relabel them.
- Do not infer implemented service support merely from a role or generic
`diagnostic.read` declaration. The actual virtual service must exist.
- Provide an explicit, documented way to load the synthetic example. A user action
may import its profile; do not auto-import/select a vehicle or silently replace
the user's existing selection when a page opens.
- Source-controlled synthetic definitions belong under `src`; avoid duplicated
fixture copies and no private VIN/calibration/firmware assets.
Store deterministic initial state and allow reset to it. Expose runtime state
only through diagnostics to normal application/UI consumers. Tests may use an
isolated internal/friend test oracle for independent state assertions; do not
publish a general ground-truth interface to Application/UI or future AI tools.
Client needs composition types, not unrestricted runtime state access.
### 4. Implement an actual diagnostic request/response path
Separate addressing/transport, protocol/service encoding, response validation/
decoding and application commands. In-process simulated delivery is sufficient,
but requests must traverse that path rather than directly reading module objects.
Implement a small documented **synthetic protocol version 1** unless a verified
standard is genuinely necessary. Preserve raw immutable request/response payloads
and define framing, target address, correlation, service and negative outcomes.
Do not invent CAN/ISO-TP/UDS/OBD/manufacturer semantics and call them authentic.
Required operations:
1. Discover/probe virtual module endpoints and report actual responders versus
expected/inaccessible/no-response entries. Returning the profile inventory
alone is not discovery.
2. Read module identity through the transport. Validate response address,
correlation and identity against the selected session/definition; wrong
identity must be an explicit failure, not silently mapped to the expected one.
3. Retrieve synthetic diagnostic trouble codes with module/source metadata.
4. Explicitly clear supported **virtual** DTC state and verify by re-reading and
an independent test oracle. Do not clear another module/session or unrelated
data. Unsupported/restricted operations return clear failures.
5. Read a small static telemetry snapshot appropriate to the configured modules.
Preserve signal ID, source module, value/type, unit, data quality, logical time
and simulated/synthetic origin. Unknown values stay unknown.
Virtual DTC clearing is not calibration/firmware programming. It must remain
Simulation-only; no physical command/write path is introduced.
No dynamic engine/transmission/road-load model, scenario engine or live random
sensor generation belongs here. Label static responses honestly; do not claim
fuel economy/physics predictions or actual sensor capture.
Malformed payloads, wrong target/correlation, unsupported versions/services and
negative responses must not produce success-shaped empty data. Distinguish a
valid empty DTC result from a failed/incomplete request.
### 5. Deterministic delays, faults and trace
Provide explicit reproducible fault configuration for at least:
- Unsupported service/negative response.
- Inaccessible or non-responding endpoint and request timeout.
- Malformed response and unexpected module identity/correlation.
- Interrupted/cancelled request or session closure while work is pending.
Use an injected controllable logical diagnostic clock/scheduler or appropriate
verified .NET time abstraction. No Thread.Sleep-based tests or random/wall-clock
fault selection. This is diagnostic timing, not permission to build the complete
Step-04 simulation clock/dynamics engine. Separate optional capture-wall-time
metadata from logical time and documented reproducibility assertions.
Trace must contain ordered immutable request/response/error records with session/
target/profile/module/address/correlation/service, logical timing, raw payload,
decoded summary and explicit positive/negative/timeout/cancelled outcome as
applicable. Do not fabricate a response when none arrived. Preserve enough detail
to diagnose malformed and mismatched messages.
Avoid an unbounded UI/process log. A documented bounded in-memory trace with an
explicit dropped-record count is sufficient; it is not telemetry recording/
replay or persistent audit storage. Trace acquisition must not depend on which
panel is currently visible.
### 6. Application feature slices and real UI
Implement cohesive features for opening/closing a simulated session, discovering
modules, reading identity/DTC/signals and explicitly clearing virtual DTCs.
Group real operations under Vehicles/Diagnostics as useful, with small direct
handlers/services and explicit results; no class per trivial method or mandatory
request/handler boilerplate.
Application/UI must use the diagnostic interfaces, not Simulation internals.
Add a feature page/workflow in the existing UI that:
- Requires explicit saved profile/revision/provider selection and explicit open/
close; clearly shows the Simulation target and selected session identity.
- Displays discovered modules, identity, DTCs and static signals with units/source.
- Offers only supported logical read/virtual-clear actions and visible errors.
- Displays inspectable raw/decoded communication trace and loss indication.
- Handles pending/cancelled/closed states without stale-success presentation.
- Leaves profile JSON/import/export, exact revision semantics and target metadata
resolution unchanged and separate from connection.
Wire the actual Simulation provider into Client. Review every tightly coupled
status surface: the old target-selection view model hardcodes an empty registry,
and home/docs currently say diagnostics are absent. Update these truthful states
for an available simulated provider, while preserving the distinction between
metadata selection and session connection. Do not leave an inaccurate
"no provider registered" notice after registering the real Simulation provider.
Map intentional UI-text changes in tests; do not delete the underlying safety/
error/no-fallback assertions.
Keep Client thin. No new host, backend, native automotive driver or future
dashboard/gauge framework is required. Reuse existing generic components.
## FILES OR PROJECTS EXPECTED TO CHANGE
- Add Diagnostics and Simulation projects, source/definitions and solution entries.
- Extend Application feature slices and required diagnostic project reference.
- Add UI feature presentation, routing/navigation and composition/status changes.
- Add Client composition reference/registration only; no business feature code.
- Extend existing unit/integration suites and project-graph assertions; no new
test project. Preserve synthetic profile fixtures and timestamp/evidence fixes.
- Update root README and actual technical/protocol/simulation/test documentation.
- Add only `prompts/Step-03-Report.md` under `prompts`.
Do not modify assignments/ROADMAP/STATE, historical 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
Preserve typed failures, immutable/snapshotted input/output, explicit selection,
profile/schema compatibility and metadata-versus-operation boundaries.
Cancellation/timeout/protocol failure must be distinguishable from success.
Do not catch broadly or silently select another target/profile/provider.
Diagnostics ports and logical use cases must be reusable by a future physical
adapter, but there is no physical implementation or approval in this step.
Never route physical/replay selection into a simulated transport. No arbitrary
hardware frames, memory offsets, programming, backup or AI execution.
Use existing maintained SDK/test/package conventions. Add a dependency only for
an actual required capability after verifying compatibility; do not add tooling/
containers/services speculatively or change system workloads.
## TESTING REQUIREMENTS
### Unit and protocol/module tests
Exercise actual codec/framing/service logic and virtual state, including:
- Valid request/reply shapes and raw payload snapshots; caller mutation cannot
change already validated messages/trace.
- Duplicate/missing endpoint/definition validation and more than one inventory.
- Discovery/identity, DTC retrieval and static telemetry with exact source/units/
quality; no application bypass of transport.
- Virtual clear/readback and independent oracle assertions; unrelated module/
session/profile data preserved; reset restores known initial state.
- Unsupported/invalid request, wrong version/address/correlation/identity,
malformed payload and negative outcome handling.
- Deterministic deadline/latency/fault vectors and cancellation/close, without
sleeps or arbitrary elapsed-time thresholds.
- Trace order/content/outcomes and bounded-buffer dropped-record accounting.
### Real integration and UI tests
Compose actual profile, target, diagnostic protocol and Simulation implementations:
1. Explicitly load/select a synthetic profile and Simulation provider, open a
session, discover modules and read identity/DTC/signals through actual frames.
2. Clear virtual DTCs and verify fresh diagnostic readback plus the independent
test oracle. Open another session and prove state isolation.
3. Inject deterministic errors through the actual wire/transport path; assert
explicit failure/trace and no false positive results.
4. Reject unknown profile/revision/provider, wrong kind, missing definition,
replay/physical operation attempts and any fallback.
5. Render the real UI with actual application DI: positive module/signal/trace
views, unsupported/timeout/cancelled states and truthful provider metadata
notices. Do not mock the feature/component under test.
6. Preserve profile round-trip/timestamp/optional-applicability behavior, target
metadata-only resolution, no physical operations and correct dependency graph.
Graph assertions must cover all nine projects and allowed references, no reverse
edges/cycles, one production executable and oracle isolation. Source-policy tests
supplement actual behavioral integration; no always-passing/DI-only placeholders.
### Execution and native evidence
Preserve the accepted 140-case baseline invariants (103 unit/37 integration).
Document any intentional presentation assertion updates caused by the new real
Simulation provider; do not remove checks or skip acceptance cases.
Run focused tests during implementation, then sequentially restore as necessary,
build the complete solution Release and run both suites:
- `dotnet build .\src\AutoForge.slnx --configuration Release --no-restore`
- `dotnet test .\src\AutoForge.slnx --configuration Release --no-build`
The full build must include the actual Windows Client and both new libraries,
not a filtered headless subset reported as complete. Use direct native build if
needed for target verification; do not override portable projects with Windows
TFM flags. Record exact commands/exit outcomes, versions/targets, warnings and
per-project discovered/passed/failed/skipped counts.
Launch the actual native Client. Explicitly load/select the synthetic example
and Simulation provider, open a session, discover modules, inspect identity/DTC/
signals, clear supported virtual DTCs and re-read them, inspect raw trace and at
least one visible failure, and close/reset as documented. Verify existing profile,
target-metadata and not-found routes still work. Record observations separately
from headless tests; a running process is not proof of UI/service integration.
Report missing prerequisites honestly without installing workloads or substituting
another host.
## DOCUMENTATION REQUIREMENTS
Update README/index/architecture/build guide and add only useful actual documents:
- Diagnostics/Simulation responsibilities and project/reference graph.
- Synthetic protocol version, request/reply/negative/error/correlation rules,
raw trace shape and explicit non-authentic limitations.
- Data-driven module/profile binding, service availability versus claims,
initial/reset state, static signal definitions and test-oracle boundary.
- Provider/session lifecycle, logical timing/fault reproducibility, cancellation,
trace capacity/loss and source classification.
- Actual feature/UI/native usage, synthetic example loading, tests and limitations.
- A focused ADR for the real capability boundaries/protocol decision.
Align lifecycle text with Step-02/Step-02A acceptance and distinguish Step-03
worker completion from pending orchestrator acceptance. Preserve historical
reports and the schema-v1 contract. Do not present static simulated readings as
vehicle dynamics, real diagnostic compatibility or physical programming support.
## ACCEPTANCE CRITERIA
| ID | Criterion | Required evidence |
|---|---|---|
| AC-01 | Nine-project one-shell modular monolith with Diagnostics/Simulation boundaries, no forbidden references/cycles and isolated oracle | Actual solution/reference/source graph, architecture tests and composition paths |
| AC-02 | Explicit profile/revision/provider/session selection and lifecycle with no metadata-to-connect shortcut, unsupported target or missing-definition fallback | Real positive/negative session tests and native selection observations |
| AC-03 | Discovery and identity traverse encoded requests, simulated transport and decoded responses, not profile/direct-state reads | Raw frame assertions, actual responders versus expectations and mismatch tests |
| AC-04 | Synthetic DTC read/virtual-clear/readback/reset and static telemetry work with exact source/units/quality and isolated state | Behavioral tests, independent oracle, multiple sessions/inventories and original-profile preservation |
| AC-05 | Invalid/unsupported/negative/malformed/timeout/interrupted/cancelled cases are deterministic and never successful empty data | Controlled clock/fault integration vectors with exact failure and lifecycle assertions |
| AC-06 | Raw/decoded trace preserves correlation, context, logical time and real outcomes, with explicit bounded loss | Trace content/order/immutability/capacity tests and native inspection |
| AC-07 | Real application slices/UI consume ports, actual Simulation provider is composed, and all old absence/status wording is truthful | Source paths, rendered integration, provider/metadata/session separation and native workflow |
| AC-08 | Full Release solution/native build, both suites and required native smoke succeed; baseline invariants retained and new real tests added | Exact commands/targets/results, warnings, counts and native observations |
| AC-09 | README, index, architecture/protocol/simulation/testing docs and ADR match actual scope and limitations | Changed document list and implemented/planned/source-fidelity summary |
| AC-10 | Historical work/protected files/manual workflow preserved; complete report saved and worker stops | Preservation/Git/scope review and `prompts/Step-03-Report.md` |
Map every criterion to PASSED, FAILED, NOT EXECUTED or BLOCKED with concrete
evidence. COMPLETE requires required build/test/native checks. Incomplete
communication, verification or missing prerequisites cannot be reported as success.
## OUT-OF-SCOPE WORK
Full vehicle dynamics/clock/scenario engine, live physics-driven gauges, telemetry
recording/replay/comparison, calibration values/editing/programming/backups,
physical adapters/drivers or real vehicle access, AI/research/knowledge services,
databases, cloud/container infrastructure, extra executables/platforms, automatic
handoffs and unrelated refactoring. No emissions defeat, anti-theft bypass,
mileage falsification or safety disabling functionality.
## REPORTING REQUIREMENTS
Create `prompts/Step-03-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/projects created/modified; actual reference graph and interfaces; provider/
session and synthetic wire contract; virtual state/static-signal/fault/trace
semantics; unit/integration tests and baseline/intentional UI assertion mapping;
exact restore/build/test commands/results with per-project counts; native
workflow/trace observations; AC-01 through AC-10 evidence; documentation and
README updates; limitations/outstanding issues; deviations/recommendations; and
protected/scope/Git preservation review.
No unexecuted test may be marked passed. No synthetic data implies hardware
compatibility/authority. Save the report and STOP. Do not change assignments/
roadmap/state, create or begin Step-04, invoke agents, automate handoff, stage,
commit or push.

View File

@ -0,0 +1,133 @@
using AutoForge.Core.Vehicles;
namespace AutoForge.Application.Features.Vehicles.Profiles;
public interface IVehicleProfileService
{
VehicleProfile Import(string json);
IReadOnlyList<VehicleProfileReference> List();
VehicleProfile Select(string profileIdentifier, int revision);
string Export(string profileIdentifier, int revision);
}
public sealed class VehicleProfileService(
IVehicleProfileJsonCodec codec,
InMemoryVehicleProfileCatalog catalog) : IVehicleProfileService
{
public VehicleProfile Import(string json)
{
var profile = codec.Import(json);
catalog.Register(profile);
return profile;
}
public IReadOnlyList<VehicleProfileReference> List() => catalog.List();
public VehicleProfile Select(string profileIdentifier, int revision) =>
catalog.Select(new VehicleProfileReference(profileIdentifier, revision));
public string Export(string profileIdentifier, int revision) =>
codec.Export(Select(profileIdentifier, revision));
}
public sealed class InMemoryVehicleProfileCatalog
{
private readonly object _gate = new();
private readonly Dictionary<ProfileRevisionKey, VehicleProfile> _profiles =
new(ProfileRevisionKeyComparer.Instance);
public void Register(VehicleProfile profile)
{
ArgumentNullException.ThrowIfNull(profile);
var key = new ProfileRevisionKey(profile.ProfileIdentifier, profile.Revision);
lock (_gate)
{
foreach (var existing in _profiles.Values.Where(
item => StringComparer.OrdinalIgnoreCase.Equals(item.ProfileIdentifier, profile.ProfileIdentifier)))
{
if (!CompatibleVehicleIdentity(existing.Vehicle, profile.Vehicle))
{
throw new VehicleProfileCatalogException(
VehicleProfileCatalogFailure.ProfileVehicleIdentityConflict,
profile.ProfileIdentifier,
profile.Revision);
}
}
if (!_profiles.TryAdd(key, profile))
{
throw new VehicleProfileCatalogException(
VehicleProfileCatalogFailure.DuplicateProfileRevision,
profile.ProfileIdentifier,
profile.Revision);
}
}
}
public IReadOnlyList<VehicleProfileReference> List()
{
lock (_gate)
{
var references = _profiles.Values
.OrderBy(profile => profile.ProfileIdentifier, StringComparer.OrdinalIgnoreCase)
.ThenBy(profile => profile.Revision)
.Select(profile => new VehicleProfileReference(profile.ProfileIdentifier, profile.Revision))
.ToArray();
return Array.AsReadOnly(references);
}
}
public VehicleProfile Select(VehicleProfileReference reference)
{
ArgumentNullException.ThrowIfNull(reference);
lock (_gate)
{
if (_profiles.TryGetValue(
new ProfileRevisionKey(reference.ProfileIdentifier, reference.Revision),
out var profile))
{
return profile;
}
}
throw new VehicleProfileCatalogException(
VehicleProfileCatalogFailure.ProfileRevisionNotFound,
reference.ProfileIdentifier,
reference.Revision);
}
private readonly record struct ProfileRevisionKey(string ProfileIdentifier, int Revision);
private static bool CompatibleVehicleIdentity(VehicleIdentity existing, VehicleIdentity incoming) =>
Same(existing.VehicleIdentifier, incoming.VehicleIdentifier) &&
Same(existing.Manufacturer, incoming.Manufacturer) &&
Same(existing.Model, incoming.Model) &&
CompatibleOptional(existing.ModelYear, incoming.ModelYear) &&
CompatibleOptional(existing.Trim, incoming.Trim) &&
CompatibleOptional(existing.Engine, incoming.Engine) &&
CompatibleOptional(existing.Transmission, incoming.Transmission) &&
CompatibleOptional(existing.Drivetrain, incoming.Drivetrain);
private static bool CompatibleOptional<T>(T? existing, T? incoming)
where T : struct, IEquatable<T> =>
existing is null || incoming is null || existing.Value.Equals(incoming.Value);
private static bool CompatibleOptional(string? existing, string? incoming) =>
existing is null || incoming is null || Same(existing, incoming);
private static bool Same(string left, string right) =>
StringComparer.OrdinalIgnoreCase.Equals(left, right);
private sealed class ProfileRevisionKeyComparer : IEqualityComparer<ProfileRevisionKey>
{
public static ProfileRevisionKeyComparer Instance { get; } = new();
public bool Equals(ProfileRevisionKey left, ProfileRevisionKey right) =>
left.Revision == right.Revision &&
StringComparer.OrdinalIgnoreCase.Equals(left.ProfileIdentifier, right.ProfileIdentifier);
public int GetHashCode(ProfileRevisionKey key) =>
HashCode.Combine(StringComparer.OrdinalIgnoreCase.GetHashCode(key.ProfileIdentifier), key.Revision);
}
}

View File

@ -0,0 +1,52 @@
namespace AutoForge.Application.Features.Vehicles.Profiles;
public sealed class VehicleProfileInterchangeException : Exception
{
public VehicleProfileInterchangeException(string path, string message, Exception? innerException = null)
: base($"{path}: {message}", innerException)
{
Path = path;
}
public string Path { get; }
}
public enum VehicleProfileCatalogFailure
{
DuplicateProfileRevision,
ProfileVehicleIdentityConflict,
ProfileRevisionNotFound
}
public sealed class VehicleProfileCatalogException : Exception
{
public VehicleProfileCatalogException(
VehicleProfileCatalogFailure failure,
string profileIdentifier,
int revision)
: base(CreateMessage(failure, profileIdentifier, revision))
{
Failure = failure;
ProfileIdentifier = profileIdentifier;
Revision = revision;
}
public VehicleProfileCatalogFailure Failure { get; }
public string ProfileIdentifier { get; }
public int Revision { get; }
private static string CreateMessage(
VehicleProfileCatalogFailure failure,
string profileIdentifier,
int revision) =>
failure switch
{
VehicleProfileCatalogFailure.DuplicateProfileRevision =>
$"Profile '{profileIdentifier}' revision {revision} is already registered; existing data was not replaced.",
VehicleProfileCatalogFailure.ProfileVehicleIdentityConflict =>
$"Profile '{profileIdentifier}' revision {revision} conflicts with the vehicle identity of another registered revision.",
VehicleProfileCatalogFailure.ProfileRevisionNotFound =>
$"Profile '{profileIdentifier}' revision {revision} is not registered.",
_ => throw new ArgumentOutOfRangeException(nameof(failure), failure, "Specify a defined catalog failure.")
};
}

View File

@ -0,0 +1,655 @@
using System.Globalization;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
using AutoForge.Core.Vehicles;
namespace AutoForge.Application.Features.Vehicles.Profiles;
public interface IVehicleProfileJsonCodec
{
VehicleProfile Import(string json);
string Export(VehicleProfile profile);
}
public sealed class VehicleProfileJsonCodec : IVehicleProfileJsonCodec
{
public const int SupportedSchemaVersion = 1;
private static readonly string[] TimestampDateFormats =
[
"yyyy-MM-dd'T'HH:mm:ss",
"yyyy-MM-dd'T'HH:mm:ss.FFFFFFF"
];
private static readonly Regex ExplicitTimestampPattern = new(
@"\A(?<dateTime>[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(?:\.[0-9]{1,7})?)(?<offset>Z|[+-][0-9]{2}:[0-9]{2})\z",
RegexOptions.CultureInvariant | RegexOptions.Compiled);
public VehicleProfile Import(string json)
{
ArgumentNullException.ThrowIfNull(json);
JsonDocument document;
try
{
document = JsonDocument.Parse(
json,
new JsonDocumentOptions
{
AllowTrailingCommas = false,
CommentHandling = JsonCommentHandling.Disallow,
MaxDepth = 64
});
}
catch (JsonException exception)
{
throw new VehicleProfileInterchangeException("$", "Input is not valid schema-v1 JSON.", exception);
}
using (document)
{
var root = ReadObject(document.RootElement, "$", "schemaVersion", "profileIdentifier", "revision", "vehicle", "modules", "evidence");
var schemaVersion = RequiredInt(root, "schemaVersion", "$");
if (schemaVersion != SupportedSchemaVersion)
{
throw new VehicleProfileInterchangeException(
"$.schemaVersion",
$"Schema version {schemaVersion} is unsupported; this build accepts version {SupportedSchemaVersion} only.");
}
var profileIdentifier = RequiredString(root, "profileIdentifier", "$");
var revision = RequiredInt(root, "revision", "$");
var vehicle = ReadVehicle(Required(root, "vehicle", "$"), "$.vehicle");
var modules = ReadArray(root, "modules", "$")
.EnumerateArray()
.Select((item, index) => ReadModule(item, $"$.modules[{index}]"))
.ToArray();
var evidence = ReadArray(root, "evidence", "$")
.EnumerateArray()
.Select((item, index) => ReadEvidence(item, $"$.evidence[{index}]"))
.ToArray();
try
{
return new VehicleProfile(profileIdentifier, revision, vehicle, modules, evidence);
}
catch (ArgumentException exception)
{
throw new VehicleProfileInterchangeException("$", exception.Message, exception);
}
}
}
public string Export(VehicleProfile profile)
{
ArgumentNullException.ThrowIfNull(profile);
using var stream = new MemoryStream();
using (var writer = new Utf8JsonWriter(stream, new JsonWriterOptions { Indented = true }))
{
writer.WriteStartObject();
writer.WriteNumber("schemaVersion", SupportedSchemaVersion);
writer.WriteString("profileIdentifier", profile.ProfileIdentifier);
writer.WriteNumber("revision", profile.Revision);
writer.WritePropertyName("vehicle");
WriteVehicle(writer, profile.Vehicle);
writer.WritePropertyName("modules");
writer.WriteStartArray();
foreach (var module in profile.Modules)
{
writer.WriteStartObject();
writer.WriteString("instanceIdentifier", module.InstanceIdentifier);
writer.WriteString("role", module.Role);
writer.WriteString("name", module.Name);
WriteNullableString(writer, "hardwareIdentifier", module.HardwareIdentifier);
WriteNullableString(writer, "softwareIdentifier", module.SoftwareIdentifier);
WriteNullableString(writer, "firmwareIdentifier", module.FirmwareIdentifier);
WriteNullableString(writer, "calibrationIdentifier", module.CalibrationIdentifier);
WriteStrings(writer, "evidenceReferences", module.EvidenceReferences);
writer.WritePropertyName("capabilities");
writer.WriteStartArray();
foreach (var capability in module.Capabilities)
{
writer.WriteStartObject();
writer.WriteString("operationIdentifier", capability.OperationIdentifier);
writer.WriteString("status", capability.Status.ToString().ToUpperInvariant());
WriteNullableString(writer, "explanation", capability.Explanation);
WriteStrings(writer, "limitations", capability.Limitations);
WriteStrings(writer, "evidenceReferences", capability.EvidenceReferences);
writer.WriteEndObject();
}
writer.WriteEndArray();
writer.WriteEndObject();
}
writer.WriteEndArray();
writer.WritePropertyName("evidence");
writer.WriteStartArray();
foreach (var evidence in profile.Evidence)
{
writer.WriteStartObject();
writer.WriteString("evidenceIdentifier", evidence.EvidenceIdentifier);
writer.WriteString("classification", evidence.Classification.ToString().ToUpperInvariant());
writer.WriteString("sourceReference", evidence.SourceReference);
writer.WriteString("description", evidence.Description);
writer.WritePropertyName("applicability");
WriteApplicability(writer, evidence.Applicability);
if (evidence.Confidence is { } confidence)
{
writer.WriteNumber("confidence", confidence);
}
else
{
writer.WriteNull("confidence");
}
WriteNullableString(writer, "verificationInformation", evidence.VerificationInformation);
WriteNullableDate(writer, "publishedAt", evidence.PublishedAt);
WriteNullableDate(writer, "retrievedAt", evidence.RetrievedAt);
WriteStrings(writer, "limitations", evidence.Limitations);
writer.WriteEndObject();
}
writer.WriteEndArray();
writer.WriteEndObject();
}
return Encoding.UTF8.GetString(stream.ToArray());
}
private static VehicleIdentity ReadVehicle(JsonElement element, string path)
{
var properties = ReadObject(
element,
path,
"vehicleIdentifier",
"manufacturer",
"model",
"modelYear",
"trim",
"engine",
"transmission",
"drivetrain",
"evidenceReferences");
try
{
return new VehicleIdentity(
RequiredString(properties, "vehicleIdentifier", path),
RequiredString(properties, "manufacturer", path),
RequiredString(properties, "model", path),
NullableInt(properties, "modelYear", path),
NullableString(properties, "trim", path),
NullableString(properties, "engine", path),
NullableString(properties, "transmission", path),
NullableString(properties, "drivetrain", path),
ReadStrings(properties, "evidenceReferences", path));
}
catch (ArgumentException exception)
{
throw new VehicleProfileInterchangeException(path, exception.Message, exception);
}
}
private static ModuleInstance ReadModule(JsonElement element, string path)
{
var properties = ReadObject(
element,
path,
"instanceIdentifier",
"role",
"name",
"hardwareIdentifier",
"softwareIdentifier",
"firmwareIdentifier",
"calibrationIdentifier",
"evidenceReferences",
"capabilities");
var capabilities = ReadArray(properties, "capabilities", path)
.EnumerateArray()
.Select((item, index) => ReadCapability(item, $"{path}.capabilities[{index}]"))
.ToArray();
try
{
return new ModuleInstance(
RequiredString(properties, "instanceIdentifier", path),
RequiredString(properties, "role", path),
RequiredString(properties, "name", path),
NullableString(properties, "hardwareIdentifier", path),
NullableString(properties, "softwareIdentifier", path),
NullableString(properties, "firmwareIdentifier", path),
NullableString(properties, "calibrationIdentifier", path),
capabilities,
ReadStrings(properties, "evidenceReferences", path));
}
catch (ArgumentException exception)
{
throw new VehicleProfileInterchangeException(path, exception.Message, exception);
}
}
private static CapabilityDeclaration ReadCapability(JsonElement element, string path)
{
var properties = ReadObject(
element,
path,
"operationIdentifier",
"status",
"explanation",
"limitations",
"evidenceReferences");
var statusText = RequiredString(properties, "status", path);
if (!TryReadCapabilityStatus(statusText, out var status))
{
throw new VehicleProfileInterchangeException($"{path}.status", $"'{statusText}' is not a defined capability status.");
}
try
{
return new CapabilityDeclaration(
RequiredString(properties, "operationIdentifier", path),
status,
NullableString(properties, "explanation", path),
ReadStrings(properties, "limitations", path),
ReadStrings(properties, "evidenceReferences", path));
}
catch (ArgumentException exception)
{
throw new VehicleProfileInterchangeException(path, exception.Message, exception);
}
}
private static ProfileEvidence ReadEvidence(JsonElement element, string path)
{
var properties = ReadObject(
element,
path,
"evidenceIdentifier",
"classification",
"sourceReference",
"description",
"applicability",
"confidence",
"verificationInformation",
"publishedAt",
"retrievedAt",
"limitations");
var classificationText = RequiredString(properties, "classification", path);
if (!TryReadClassification(classificationText, out var classification))
{
throw new VehicleProfileInterchangeException(
$"{path}.classification",
$"'{classificationText}' is not a defined evidence classification.");
}
var confidence = NullableDouble(properties, "confidence", path);
var applicability = ReadApplicability(Required(properties, "applicability", path), $"{path}.applicability");
try
{
return new ProfileEvidence(
RequiredString(properties, "evidenceIdentifier", path),
classification,
RequiredString(properties, "sourceReference", path),
RequiredString(properties, "description", path),
applicability,
confidence,
NullableString(properties, "verificationInformation", path),
NullableDate(properties, "publishedAt", path),
NullableDate(properties, "retrievedAt", path),
ReadStrings(properties, "limitations", path));
}
catch (ArgumentException exception)
{
throw new VehicleProfileInterchangeException(path, exception.Message, exception);
}
}
private static EvidenceApplicability ReadApplicability(JsonElement element, string path)
{
var properties = ReadObject(
element,
path,
"vehicleIdentifier",
"modelYear",
"profileIdentifier",
"profileRevision",
"moduleInstanceIdentifier",
"hardwareIdentifier",
"softwareIdentifier",
"firmwareIdentifier",
"calibrationIdentifier");
try
{
return new EvidenceApplicability(
RequiredString(properties, "vehicleIdentifier", path),
NullableInt(properties, "modelYear", path),
NullableString(properties, "profileIdentifier", path),
NullableInt(properties, "profileRevision", path),
NullableString(properties, "moduleInstanceIdentifier", path),
NullableString(properties, "hardwareIdentifier", path),
NullableString(properties, "softwareIdentifier", path),
NullableString(properties, "firmwareIdentifier", path),
NullableString(properties, "calibrationIdentifier", path));
}
catch (ArgumentException exception)
{
throw new VehicleProfileInterchangeException(path, exception.Message, exception);
}
}
private static void WriteVehicle(Utf8JsonWriter writer, VehicleIdentity vehicle)
{
writer.WriteStartObject();
writer.WriteString("vehicleIdentifier", vehicle.VehicleIdentifier);
writer.WriteString("manufacturer", vehicle.Manufacturer);
writer.WriteString("model", vehicle.Model);
WriteNullableNumber(writer, "modelYear", vehicle.ModelYear);
WriteNullableString(writer, "trim", vehicle.Trim);
WriteNullableString(writer, "engine", vehicle.Engine);
WriteNullableString(writer, "transmission", vehicle.Transmission);
WriteNullableString(writer, "drivetrain", vehicle.Drivetrain);
WriteStrings(writer, "evidenceReferences", vehicle.EvidenceReferences);
writer.WriteEndObject();
}
private static void WriteApplicability(Utf8JsonWriter writer, EvidenceApplicability applicability)
{
writer.WriteStartObject();
writer.WriteString("vehicleIdentifier", applicability.VehicleIdentifier);
WriteNullableNumber(writer, "modelYear", applicability.ModelYear);
WriteNullableString(writer, "profileIdentifier", applicability.ProfileIdentifier);
WriteNullableNumber(writer, "profileRevision", applicability.ProfileRevision);
WriteNullableString(writer, "moduleInstanceIdentifier", applicability.ModuleInstanceIdentifier);
WriteNullableString(writer, "hardwareIdentifier", applicability.HardwareIdentifier);
WriteNullableString(writer, "softwareIdentifier", applicability.SoftwareIdentifier);
WriteNullableString(writer, "firmwareIdentifier", applicability.FirmwareIdentifier);
WriteNullableString(writer, "calibrationIdentifier", applicability.CalibrationIdentifier);
writer.WriteEndObject();
}
private static Dictionary<string, JsonElement> ReadObject(JsonElement element, string path, params string[] allowedProperties)
{
if (element.ValueKind != JsonValueKind.Object)
{
throw new VehicleProfileInterchangeException(path, "Expected a JSON object.");
}
var allowed = new HashSet<string>(allowedProperties, StringComparer.Ordinal);
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
var properties = new Dictionary<string, JsonElement>(StringComparer.Ordinal);
foreach (var property in element.EnumerateObject())
{
if (!seen.Add(property.Name))
{
throw new VehicleProfileInterchangeException(
path,
$"Duplicate or case-ambiguous property '{property.Name}' is not allowed.");
}
if (!allowed.Contains(property.Name))
{
throw new VehicleProfileInterchangeException(
$"{path}.{property.Name}",
"Unknown properties are not allowed in schema version 1.");
}
properties.Add(property.Name, property.Value);
}
return properties;
}
private static JsonElement Required(
IReadOnlyDictionary<string, JsonElement> properties,
string name,
string path)
{
if (!properties.TryGetValue(name, out var value))
{
throw new VehicleProfileInterchangeException($"{path}.{name}", "Required property is missing.");
}
return value;
}
private static string RequiredString(IReadOnlyDictionary<string, JsonElement> properties, string name, string path)
{
var value = Required(properties, name, path);
if (value.ValueKind != JsonValueKind.String || value.GetString() is not { } text)
{
throw new VehicleProfileInterchangeException($"{path}.{name}", "Expected a non-null string.");
}
return text;
}
private static string? NullableString(IReadOnlyDictionary<string, JsonElement> properties, string name, string path)
{
var value = Required(properties, name, path);
if (value.ValueKind == JsonValueKind.Null)
{
return null;
}
if (value.ValueKind != JsonValueKind.String || value.GetString() is not { } text)
{
throw new VehicleProfileInterchangeException($"{path}.{name}", "Expected a string or explicit null.");
}
return text;
}
private static int RequiredInt(IReadOnlyDictionary<string, JsonElement> properties, string name, string path)
{
var value = Required(properties, name, path);
if (value.ValueKind != JsonValueKind.Number || !value.TryGetInt32(out var result))
{
throw new VehicleProfileInterchangeException($"{path}.{name}", "Expected a 32-bit integer.");
}
return result;
}
private static int? NullableInt(IReadOnlyDictionary<string, JsonElement> properties, string name, string path)
{
var value = Required(properties, name, path);
if (value.ValueKind == JsonValueKind.Null)
{
return null;
}
if (value.ValueKind != JsonValueKind.Number || !value.TryGetInt32(out var result))
{
throw new VehicleProfileInterchangeException($"{path}.{name}", "Expected a 32-bit integer or explicit null.");
}
return result;
}
private static double? NullableDouble(IReadOnlyDictionary<string, JsonElement> properties, string name, string path)
{
var value = Required(properties, name, path);
if (value.ValueKind == JsonValueKind.Null)
{
return null;
}
if (value.ValueKind != JsonValueKind.Number || !value.TryGetDouble(out var result))
{
throw new VehicleProfileInterchangeException($"{path}.{name}", "Expected a finite number or explicit null.");
}
return result;
}
private static DateTimeOffset? NullableDate(IReadOnlyDictionary<string, JsonElement> properties, string name, string path)
{
var value = Required(properties, name, path);
if (value.ValueKind == JsonValueKind.Null)
{
return null;
}
if (value.ValueKind != JsonValueKind.String ||
value.GetString() is not { } text ||
!TryParseExplicitTimestamp(text, out var result))
{
throw new VehicleProfileInterchangeException(
$"{path}.{name}",
"Expected a complete ISO-8601 timestamp with seconds and an explicit UTC offset (Z or +/-HH:mm), optionally with 1-7 fractional digits, or explicit null.");
}
return result;
}
private static bool TryParseExplicitTimestamp(string text, out DateTimeOffset result)
{
result = default;
var match = ExplicitTimestampPattern.Match(text);
if (!match.Success ||
!DateTime.TryParseExact(
match.Groups["dateTime"].Value,
TimestampDateFormats,
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out var dateTime))
{
return false;
}
var offsetText = match.Groups["offset"].Value;
var offset = TimeSpan.Zero;
if (!StringComparer.Ordinal.Equals(offsetText, "Z"))
{
var hours = (offsetText[1] - '0') * 10 + offsetText[2] - '0';
var minutes = (offsetText[4] - '0') * 10 + offsetText[5] - '0';
if (hours > 14 || minutes > 59 || (hours == 14 && minutes != 0))
{
return false;
}
offset = new TimeSpan(hours, minutes, 0);
if (offsetText[0] == '-')
{
offset = -offset;
}
}
try
{
result = new DateTimeOffset(dateTime, offset);
return true;
}
catch (ArgumentException)
{
return false;
}
}
private static JsonElement ReadArray(IReadOnlyDictionary<string, JsonElement> properties, string name, string path)
{
var value = Required(properties, name, path);
if (value.ValueKind != JsonValueKind.Array)
{
throw new VehicleProfileInterchangeException($"{path}.{name}", "Expected an array.");
}
return value;
}
private static IReadOnlyList<string> ReadStrings(IReadOnlyDictionary<string, JsonElement> properties, string name, string path)
{
var result = new List<string>();
var array = ReadArray(properties, name, path);
var index = 0;
foreach (var item in array.EnumerateArray())
{
if (item.ValueKind != JsonValueKind.String || item.GetString() is not { } text)
{
throw new VehicleProfileInterchangeException($"{path}.{name}[{index}]", "Expected a non-null string.");
}
result.Add(text);
index++;
}
return result;
}
private static bool TryReadCapabilityStatus(string text, out CapabilityStatus status) =>
text switch
{
"SUPPORTED" => Set(CapabilityStatus.Supported, out status),
"UNSUPPORTED" => Set(CapabilityStatus.Unsupported, out status),
"UNKNOWN" => Set(CapabilityStatus.Unknown, out status),
"INACCESSIBLE" => Set(CapabilityStatus.Inaccessible, out status),
"RESTRICTED" => Set(CapabilityStatus.Restricted, out status),
_ => Set(default, out status, false)
};
private static bool TryReadClassification(string text, out EvidenceClassification classification) =>
text switch
{
"VERIFIED" => Set(EvidenceClassification.Verified, out classification),
"UNVERIFIED" => Set(EvidenceClassification.Unverified, out classification),
"INFERRED" => Set(EvidenceClassification.Inferred, out classification),
"SYNTHETIC" => Set(EvidenceClassification.Synthetic, out classification),
_ => Set(default, out classification, false)
};
private static bool Set<T>(T value, out T target, bool result = true)
{
target = value;
return result;
}
private static void WriteNullableString(Utf8JsonWriter writer, string name, string? value)
{
if (value is null)
{
writer.WriteNull(name);
}
else
{
writer.WriteString(name, value);
}
}
private static void WriteNullableNumber(Utf8JsonWriter writer, string name, int? value)
{
if (value is null)
{
writer.WriteNull(name);
}
else
{
writer.WriteNumber(name, value.Value);
}
}
private static void WriteNullableDate(Utf8JsonWriter writer, string name, DateTimeOffset? value)
{
if (value is null)
{
writer.WriteNull(name);
}
else
{
writer.WriteString(name, value.Value.ToString("O", CultureInfo.InvariantCulture));
}
}
private static void WriteStrings(Utf8JsonWriter writer, string name, IReadOnlyList<string> values)
{
writer.WritePropertyName(name);
writer.WriteStartArray();
foreach (var value in values)
{
writer.WriteStringValue(value);
}
writer.WriteEndArray();
}
}

View File

@ -0,0 +1,22 @@
using Microsoft.Extensions.DependencyInjection;
namespace AutoForge.Application.Features.Vehicles.Profiles;
public static class VehicleProfileServiceCollectionExtensions
{
public static IServiceCollection AddAutoForgeVehicleProfiles(this IServiceCollection services)
{
ArgumentNullException.ThrowIfNull(services);
if (services.Any(service => service.ServiceType == typeof(IVehicleProfileService)))
{
throw new InvalidOperationException(
"Vehicle profile services are already registered.");
}
services.AddSingleton<IVehicleProfileJsonCodec, VehicleProfileJsonCodec>();
services.AddSingleton<InMemoryVehicleProfileCatalog>();
services.AddSingleton<IVehicleProfileService, VehicleProfileService>();
return services;
}
}

View File

@ -1,5 +1,6 @@
using Microsoft.Extensions.Logging;
using AutoForge.Application.ExecutionTargets;
using AutoForge.Application.Features.Vehicles.Profiles;
using AutoForge.UI;
namespace AutoForge.Client;
@ -14,6 +15,7 @@ public static class MauiProgram
.ConfigureFonts(fonts => fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular"));
builder.Services.AddAutoForgeTargetSelection([]);
builder.Services.AddAutoForgeVehicleProfiles();
builder.Services.AddAutoForgeUi();
builder.Services.AddMauiBlazorWebView();

View File

@ -0,0 +1,501 @@
namespace AutoForge.Core.Vehicles;
public enum CapabilityStatus
{
Supported,
Unsupported,
Unknown,
Inaccessible,
Restricted
}
public enum EvidenceClassification
{
Verified,
Unverified,
Inferred,
Synthetic
}
public sealed class VehicleIdentity
{
public VehicleIdentity(
string vehicleIdentifier,
string manufacturer,
string model,
int? modelYear = null,
string? trim = null,
string? engine = null,
string? transmission = null,
string? drivetrain = null,
IEnumerable<string>? evidenceReferences = null)
{
VehicleIdentifier = ProfileValidation.RequiredIdentifier(vehicleIdentifier, nameof(vehicleIdentifier));
Manufacturer = ProfileValidation.RequiredText(manufacturer, nameof(manufacturer));
Model = ProfileValidation.RequiredText(model, nameof(model));
if (modelYear is <= 0 or > 9999)
{
throw new ArgumentOutOfRangeException(nameof(modelYear), modelYear, "Model year must be unknown or between 1 and 9999.");
}
ModelYear = modelYear;
Trim = ProfileValidation.OptionalText(trim, nameof(trim));
Engine = ProfileValidation.OptionalText(engine, nameof(engine));
Transmission = ProfileValidation.OptionalText(transmission, nameof(transmission));
Drivetrain = ProfileValidation.OptionalText(drivetrain, nameof(drivetrain));
EvidenceReferences = ProfileValidation.CopyIdentifiers(evidenceReferences, nameof(evidenceReferences));
}
public string VehicleIdentifier { get; }
public string Manufacturer { get; }
public string Model { get; }
public int? ModelYear { get; }
public string? Trim { get; }
public string? Engine { get; }
public string? Transmission { get; }
public string? Drivetrain { get; }
public IReadOnlyList<string> EvidenceReferences { get; }
}
public sealed class EvidenceApplicability
{
public EvidenceApplicability(
string vehicleIdentifier,
int? modelYear = null,
string? profileIdentifier = null,
int? profileRevision = null,
string? moduleInstanceIdentifier = null,
string? hardwareIdentifier = null,
string? softwareIdentifier = null,
string? firmwareIdentifier = null,
string? calibrationIdentifier = null)
{
VehicleIdentifier = ProfileValidation.RequiredIdentifier(vehicleIdentifier, nameof(vehicleIdentifier));
if (modelYear is <= 0 or > 9999)
{
throw new ArgumentOutOfRangeException(nameof(modelYear), modelYear, "Applicable model year must be unknown or between 1 and 9999.");
}
ModelYear = modelYear;
ProfileIdentifier = ProfileValidation.OptionalIdentifier(profileIdentifier, nameof(profileIdentifier));
ModuleInstanceIdentifier = ProfileValidation.OptionalIdentifier(moduleInstanceIdentifier, nameof(moduleInstanceIdentifier));
HardwareIdentifier = ProfileValidation.OptionalIdentifier(hardwareIdentifier, nameof(hardwareIdentifier));
SoftwareIdentifier = ProfileValidation.OptionalIdentifier(softwareIdentifier, nameof(softwareIdentifier));
FirmwareIdentifier = ProfileValidation.OptionalIdentifier(firmwareIdentifier, nameof(firmwareIdentifier));
CalibrationIdentifier = ProfileValidation.OptionalIdentifier(calibrationIdentifier, nameof(calibrationIdentifier));
if ((ProfileIdentifier is null) != (profileRevision is null) || profileRevision is <= 0)
{
throw new ArgumentException(
"Profile applicability must specify both a profile identifier and a positive revision, or neither.",
nameof(profileRevision));
}
if (ModuleInstanceIdentifier is null &&
(HardwareIdentifier is not null || SoftwareIdentifier is not null ||
FirmwareIdentifier is not null || CalibrationIdentifier is not null))
{
throw new ArgumentException(
"Module identity context requires an explicit module instance identifier.",
nameof(moduleInstanceIdentifier));
}
ProfileRevision = profileRevision;
}
public string VehicleIdentifier { get; }
public int? ModelYear { get; }
public string? ProfileIdentifier { get; }
public int? ProfileRevision { get; }
public string? ModuleInstanceIdentifier { get; }
public string? HardwareIdentifier { get; }
public string? SoftwareIdentifier { get; }
public string? FirmwareIdentifier { get; }
public string? CalibrationIdentifier { get; }
}
public sealed class ProfileEvidence
{
public ProfileEvidence(
string evidenceIdentifier,
EvidenceClassification classification,
string sourceReference,
string description,
EvidenceApplicability applicability,
double? confidence = null,
string? verificationInformation = null,
DateTimeOffset? publishedAt = null,
DateTimeOffset? retrievedAt = null,
IEnumerable<string>? limitations = null)
{
EvidenceIdentifier = ProfileValidation.RequiredIdentifier(evidenceIdentifier, nameof(evidenceIdentifier));
if (!Enum.IsDefined(classification))
{
throw new ArgumentOutOfRangeException(nameof(classification), classification, "Specify a defined evidence classification.");
}
Classification = classification;
SourceReference = ProfileValidation.RequiredText(sourceReference, nameof(sourceReference));
Description = ProfileValidation.RequiredText(description, nameof(description));
Applicability = applicability ?? throw new ArgumentNullException(nameof(applicability));
if (confidence is { } value && (!double.IsFinite(value) || value is < 0 or > 1))
{
throw new ArgumentOutOfRangeException(nameof(confidence), confidence, "Confidence must be unknown or finite and between 0 and 1.");
}
Confidence = confidence;
VerificationInformation = ProfileValidation.OptionalText(verificationInformation, nameof(verificationInformation));
PublishedAt = publishedAt;
RetrievedAt = retrievedAt;
Limitations = ProfileValidation.CopyText(limitations, nameof(limitations));
}
public string EvidenceIdentifier { get; }
public EvidenceClassification Classification { get; }
public string SourceReference { get; }
public string Description { get; }
public EvidenceApplicability Applicability { get; }
public double? Confidence { get; }
public string? VerificationInformation { get; }
public DateTimeOffset? PublishedAt { get; }
public DateTimeOffset? RetrievedAt { get; }
public IReadOnlyList<string> Limitations { get; }
}
public sealed class CapabilityDeclaration
{
public CapabilityDeclaration(
string operationIdentifier,
CapabilityStatus status,
string? explanation = null,
IEnumerable<string>? limitations = null,
IEnumerable<string>? evidenceReferences = null)
{
OperationIdentifier = ProfileValidation.RequiredIdentifier(operationIdentifier, nameof(operationIdentifier));
if (!Enum.IsDefined(status))
{
throw new ArgumentOutOfRangeException(nameof(status), status, "Specify a defined capability status.");
}
Status = status;
Explanation = ProfileValidation.OptionalText(explanation, nameof(explanation));
Limitations = ProfileValidation.CopyText(limitations, nameof(limitations));
EvidenceReferences = ProfileValidation.CopyIdentifiers(evidenceReferences, nameof(evidenceReferences));
}
public string OperationIdentifier { get; }
public CapabilityStatus Status { get; }
public string? Explanation { get; }
public IReadOnlyList<string> Limitations { get; }
public IReadOnlyList<string> EvidenceReferences { get; }
}
public sealed class ModuleInstance
{
public ModuleInstance(
string instanceIdentifier,
string role,
string name,
string? hardwareIdentifier = null,
string? softwareIdentifier = null,
string? firmwareIdentifier = null,
string? calibrationIdentifier = null,
IEnumerable<CapabilityDeclaration>? capabilities = null,
IEnumerable<string>? evidenceReferences = null)
{
InstanceIdentifier = ProfileValidation.RequiredIdentifier(instanceIdentifier, nameof(instanceIdentifier));
Role = ProfileValidation.RequiredIdentifier(role, nameof(role));
Name = ProfileValidation.RequiredText(name, nameof(name));
HardwareIdentifier = ProfileValidation.OptionalIdentifier(hardwareIdentifier, nameof(hardwareIdentifier));
SoftwareIdentifier = ProfileValidation.OptionalIdentifier(softwareIdentifier, nameof(softwareIdentifier));
FirmwareIdentifier = ProfileValidation.OptionalIdentifier(firmwareIdentifier, nameof(firmwareIdentifier));
CalibrationIdentifier = ProfileValidation.OptionalIdentifier(calibrationIdentifier, nameof(calibrationIdentifier));
Capabilities = ProfileValidation.CopyItems(capabilities ?? [], nameof(capabilities));
EvidenceReferences = ProfileValidation.CopyIdentifiers(evidenceReferences, nameof(evidenceReferences));
ProfileValidation.EnsureUnique(
Capabilities.Select(capability => capability.OperationIdentifier),
StringComparer.OrdinalIgnoreCase,
"Capability operation identifiers must be unique within a module.");
}
public string InstanceIdentifier { get; }
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 IReadOnlyList<CapabilityDeclaration> Capabilities { get; }
public IReadOnlyList<string> EvidenceReferences { get; }
public CapabilityAssessment GetCapability(string operationIdentifier)
{
var requested = ProfileValidation.RequiredIdentifier(operationIdentifier, nameof(operationIdentifier));
var declaration = Capabilities.FirstOrDefault(
capability => StringComparer.OrdinalIgnoreCase.Equals(capability.OperationIdentifier, requested));
return declaration is null
? new CapabilityAssessment(
requested,
CapabilityStatus.Unknown,
false,
"No capability declaration exists for this operation.")
: new CapabilityAssessment(
declaration.OperationIdentifier,
declaration.Status,
true,
declaration.Explanation ?? "The capability declaration has no additional explanation.");
}
}
public sealed record CapabilityAssessment(
string OperationIdentifier,
CapabilityStatus Status,
bool IsDeclared,
string Explanation);
public sealed class VehicleProfile
{
public VehicleProfile(
string profileIdentifier,
int revision,
VehicleIdentity vehicle,
IEnumerable<ModuleInstance>? modules,
IEnumerable<ProfileEvidence>? evidence)
{
ProfileIdentifier = ProfileValidation.RequiredIdentifier(profileIdentifier, nameof(profileIdentifier));
if (revision <= 0)
{
throw new ArgumentOutOfRangeException(nameof(revision), revision, "Profile revision must be positive.");
}
Revision = revision;
Vehicle = vehicle ?? throw new ArgumentNullException(nameof(vehicle));
Modules = ProfileValidation.CopyItems(modules, nameof(modules));
Evidence = ProfileValidation.CopyItems(evidence, nameof(evidence));
ProfileValidation.EnsureUnique(
Modules.Select(module => module.InstanceIdentifier),
StringComparer.OrdinalIgnoreCase,
"Module instance identifiers must be unique within a profile revision.");
ProfileValidation.EnsureUnique(
Evidence.Select(item => item.EvidenceIdentifier),
StringComparer.OrdinalIgnoreCase,
"Evidence identifiers must be unique within a profile revision.");
ValidateEvidenceReferences();
}
public string ProfileIdentifier { get; }
public int Revision { get; }
public VehicleIdentity Vehicle { get; }
public IReadOnlyList<ModuleInstance> Modules { get; }
public IReadOnlyList<ProfileEvidence> Evidence { get; }
public ModuleInstance GetModule(string instanceIdentifier)
{
var requested = ProfileValidation.RequiredIdentifier(instanceIdentifier, nameof(instanceIdentifier));
return Modules.FirstOrDefault(
module => StringComparer.OrdinalIgnoreCase.Equals(module.InstanceIdentifier, requested))
?? throw new KeyNotFoundException($"Module instance '{requested}' is not declared in this profile.");
}
private void ValidateEvidenceReferences()
{
var evidenceById = Evidence.ToDictionary(
item => item.EvidenceIdentifier,
StringComparer.OrdinalIgnoreCase);
ValidateReferences(Vehicle.EvidenceReferences, evidenceById, null, "vehicle");
foreach (var module in Modules)
{
ValidateReferences(module.EvidenceReferences, evidenceById, module, $"module '{module.InstanceIdentifier}'");
foreach (var capability in module.Capabilities)
{
ValidateReferences(
capability.EvidenceReferences,
evidenceById,
module,
$"operation '{capability.OperationIdentifier}' on module '{module.InstanceIdentifier}'");
}
}
foreach (var item in Evidence)
{
var scope = item.Applicability;
if (!StringComparer.OrdinalIgnoreCase.Equals(scope.VehicleIdentifier, Vehicle.VehicleIdentifier))
{
throw new ArgumentException(
$"Evidence '{item.EvidenceIdentifier}' applies to vehicle '{scope.VehicleIdentifier}', not '{Vehicle.VehicleIdentifier}'.",
nameof(Evidence));
}
if (scope.ModelYear is { } applicableYear &&
Vehicle.ModelYear is { } vehicleYear &&
applicableYear != vehicleYear)
{
throw new ArgumentException(
$"Evidence '{item.EvidenceIdentifier}' applies to model year {applicableYear}, not {vehicleYear}.",
nameof(Evidence));
}
if (scope.ProfileIdentifier is not null &&
(!StringComparer.OrdinalIgnoreCase.Equals(scope.ProfileIdentifier, ProfileIdentifier) ||
scope.ProfileRevision != Revision))
{
throw new ArgumentException(
$"Evidence '{item.EvidenceIdentifier}' applies to a different profile identity or revision.",
nameof(Evidence));
}
if (scope.ModuleInstanceIdentifier is not null)
{
var module = Modules.FirstOrDefault(
candidate => StringComparer.OrdinalIgnoreCase.Equals(
candidate.InstanceIdentifier,
scope.ModuleInstanceIdentifier));
if (module is null ||
!SameOptional(scope.HardwareIdentifier, module.HardwareIdentifier) ||
!SameOptional(scope.SoftwareIdentifier, module.SoftwareIdentifier) ||
!SameOptional(scope.FirmwareIdentifier, module.FirmwareIdentifier) ||
!SameOptional(scope.CalibrationIdentifier, module.CalibrationIdentifier))
{
throw new ArgumentException(
$"Evidence '{item.EvidenceIdentifier}' has dangling or conflicting module applicability.",
nameof(Evidence));
}
}
}
}
private static void ValidateReferences(
IReadOnlyList<string> references,
IReadOnlyDictionary<string, ProfileEvidence> evidenceById,
ModuleInstance? module,
string context)
{
foreach (var reference in references)
{
if (!evidenceById.TryGetValue(reference, out var item))
{
throw new ArgumentException(
$"Evidence reference '{reference}' for {context} does not resolve within this profile.",
nameof(Evidence));
}
var scope = item.Applicability;
if (scope.ModuleInstanceIdentifier is not null &&
(module is null ||
!StringComparer.OrdinalIgnoreCase.Equals(scope.ModuleInstanceIdentifier, module.InstanceIdentifier)))
{
throw new ArgumentException(
$"Evidence '{reference}' is not applicable to {context}.",
nameof(Evidence));
}
}
}
private static bool SameOptional(string? constraint, string? target) =>
constraint is null ||
(target is not null && StringComparer.OrdinalIgnoreCase.Equals(constraint, target));
}
public sealed class VehicleProfileReference
{
public VehicleProfileReference(string profileIdentifier, int revision)
{
ProfileIdentifier = ProfileValidation.RequiredIdentifier(profileIdentifier, nameof(profileIdentifier));
if (revision <= 0)
{
throw new ArgumentOutOfRangeException(nameof(revision), revision, "Profile revision must be positive.");
}
Revision = revision;
}
public string ProfileIdentifier { get; }
public int Revision { get; }
}
internal static class ProfileValidation
{
public static string RequiredIdentifier(string? value, string parameterName)
{
ArgumentException.ThrowIfNullOrWhiteSpace(value, parameterName);
if (!StringComparer.Ordinal.Equals(value, value.Trim()))
{
throw new ArgumentException("Identifiers must not contain leading or trailing whitespace.", parameterName);
}
return value;
}
public static string? OptionalIdentifier(string? value, string parameterName) =>
value is null ? null : RequiredIdentifier(value, parameterName);
public static string RequiredText(string? value, string parameterName)
{
ArgumentException.ThrowIfNullOrWhiteSpace(value, parameterName);
if (!StringComparer.Ordinal.Equals(value, value.Trim()))
{
throw new ArgumentException("Text values must not contain leading or trailing whitespace.", parameterName);
}
return value;
}
public static string? OptionalText(string? value, string parameterName) =>
value is null ? null : RequiredText(value, parameterName);
public static IReadOnlyList<string> CopyIdentifiers(IEnumerable<string>? values, string parameterName)
{
var copy = values?.Select(value => RequiredIdentifier(value, parameterName)).ToArray() ?? [];
EnsureUnique(copy, StringComparer.OrdinalIgnoreCase, $"{parameterName} must not contain duplicates.");
return Array.AsReadOnly(copy);
}
public static IReadOnlyList<string> CopyText(IEnumerable<string>? values, string parameterName)
{
var copy = values?.Select(value => RequiredText(value, parameterName)).ToArray() ?? [];
return Array.AsReadOnly(copy);
}
public static IReadOnlyList<T> CopyItems<T>(IEnumerable<T>? values, string parameterName)
where T : class
{
if (values is null)
{
throw new ArgumentNullException(parameterName);
}
var copy = values.ToArray();
if (copy.Any(item => item is null))
{
throw new ArgumentException("Collections must not contain null items.", parameterName);
}
return Array.AsReadOnly(copy);
}
public static void EnsureUnique(IEnumerable<string> values, StringComparer comparer, string message)
{
var set = new HashSet<string>(comparer);
foreach (var value in values)
{
if (!set.Add(value))
{
throw new ArgumentException(message);
}
}
}
}

View File

@ -1,4 +1,5 @@
using AutoForge.UI.Features.ExecutionTargets.SelectExecutionTarget;
using AutoForge.UI.Features.Vehicles.Profiles;
using Microsoft.Extensions.DependencyInjection;
namespace AutoForge.UI;
@ -10,6 +11,7 @@ public static class ServiceCollectionExtensions
ArgumentNullException.ThrowIfNull(services);
services.AddScoped<ExecutionTargetSelectionViewModel>();
services.AddScoped<VehicleProfilePageViewModel>();
return services;
}
}

View File

@ -0,0 +1,70 @@
using AutoForge.Application.Features.Vehicles.Profiles;
using AutoForge.Components;
using AutoForge.Core.Vehicles;
namespace AutoForge.UI.Features.Vehicles.Profiles;
public sealed class VehicleProfilePageViewModel(IVehicleProfileService profiles)
{
public string JsonInput { get; set; } = string.Empty;
public IReadOnlyList<VehicleProfileReference> AvailableProfiles { get; private set; } =
profiles.List();
public VehicleProfile? SelectedProfile { get; private set; }
public string? ExportJson { get; private set; }
public StatusNoticeTone StatusTone { get; private set; } = StatusNoticeTone.Warning;
public string StatusMessage { get; private set; } =
"No vehicle profiles are loaded. Import an explicit schema-v1 JSON profile; no profile is selected automatically.";
public void Import()
{
try
{
var imported = profiles.Import(JsonInput);
AvailableProfiles = profiles.List();
StatusTone = StatusNoticeTone.Success;
StatusMessage =
$"Imported metadata for profile '{imported.ProfileIdentifier}' revision {imported.Revision}. Select it explicitly to inspect or export.";
}
catch (VehicleProfileInterchangeException exception)
{
SetFailure(exception.Message);
}
catch (VehicleProfileCatalogException exception)
{
SetFailure(exception.Message);
}
}
public void SelectProfile(string profileIdentifier, int revision)
{
try
{
var selected = profiles.Select(profileIdentifier, revision);
var export = profiles.Export(profileIdentifier, revision);
SelectedProfile = selected;
ExportJson = export;
StatusTone = StatusNoticeTone.Information;
StatusMessage =
$"Selected metadata for profile '{selected.ProfileIdentifier}' revision {selected.Revision}. It is not a connection, service, compatibility determination or authorization.";
}
catch (VehicleProfileCatalogException exception)
{
SetFailure(exception.Message);
}
catch (ArgumentException exception)
{
SetFailure(exception.Message);
}
}
private void SetFailure(string message)
{
StatusTone = StatusNoticeTone.Error;
StatusMessage = message;
}
}

View File

@ -0,0 +1,140 @@
@page "/vehicle-profiles"
@inject VehicleProfilePageViewModel Profiles
<PageTitle>Vehicle profiles - AutoForge</PageTitle>
<h1>Vehicle profile metadata</h1>
<p>
Import a schema-v1 profile JSON document to inspect explicitly declared metadata.
Imported data stays in memory for this application session; it does not connect
to a vehicle or implement the declared operations.
</p>
<StatusNotice Tone="@Profiles.StatusTone" Message="@Profiles.StatusMessage" />
<section aria-labelledby="profile-import-heading">
<h2 id="profile-import-heading">Import profile JSON</h2>
<label for="profile-json-input">Schema-v1 JSON</label>
<textarea id="profile-json-input" @bind="Profiles.JsonInput" rows="12" spellcheck="false"></textarea>
<button id="import-profile" type="button" @onclick="Profiles.Import">Import profile</button>
</section>
<section aria-labelledby="available-profiles-heading">
<h2 id="available-profiles-heading">Available profile revisions</h2>
@if (Profiles.AvailableProfiles.Count == 0)
{
<p>No profiles are registered in this application session.</p>
}
else
{
<ul class="profile-list">
@foreach (var profile in Profiles.AvailableProfiles)
{
<li>
<span>@profile.ProfileIdentifier — revision @profile.Revision</span>
<button type="button" @onclick="() => Profiles.SelectProfile(profile.ProfileIdentifier, profile.Revision)">
Select this revision
</button>
</li>
}
</ul>
}
</section>
@if (Profiles.SelectedProfile is { } selected)
{
<section aria-labelledby="selected-profile-heading">
<h2 id="selected-profile-heading">Selected metadata</h2>
<p>
Profile @selected.ProfileIdentifier, revision @selected.Revision.
Vehicle identity @selected.Vehicle.VehicleIdentifier;
@selected.Vehicle.Manufacturer @selected.Vehicle.Model;
model year @(selected.Vehicle.ModelYear?.ToString() ?? "unknown").
</p>
<p>
Trim: @(selected.Vehicle.Trim ?? "unknown");
engine: @(selected.Vehicle.Engine ?? "unknown");
transmission: @(selected.Vehicle.Transmission ?? "unknown");
drivetrain: @(selected.Vehicle.Drivetrain ?? "unknown").
</p>
@foreach (var module in selected.Modules)
{
<article class="module-metadata" data-module="@module.InstanceIdentifier">
<h3>@module.Name (@module.Role)</h3>
<dl>
<dt>Module instance</dt>
<dd>@module.InstanceIdentifier</dd>
<dt>Hardware identity</dt>
<dd>@(module.HardwareIdentifier ?? "unknown")</dd>
<dt>Software identity</dt>
<dd>@(module.SoftwareIdentifier ?? "unknown")</dd>
<dt>Firmware identity</dt>
<dd>@(module.FirmwareIdentifier ?? "unknown")</dd>
<dt>Calibration identity</dt>
<dd>@(module.CalibrationIdentifier ?? "unknown")</dd>
</dl>
@if (module.Capabilities.Count == 0)
{
<p>No capability declarations; undeclared status is Unknown, not Supported.</p>
}
else
{
<h4>Capability declarations (metadata only)</h4>
<ul>
@foreach (var capability in module.Capabilities)
{
<li>
<strong>@capability.OperationIdentifier</strong>:
@capability.Status.ToString().ToUpperInvariant().
@(capability.Explanation ?? "No additional explanation.")
@if (capability.Limitations.Count > 0)
{
<span> Limitations: @string.Join("; ", capability.Limitations)</span>
}
</li>
}
</ul>
}
<p>
Evidence references:
@(module.EvidenceReferences.Count == 0 ? "none" : string.Join(", ", module.EvidenceReferences)).
</p>
</article>
}
<h3>Evidence and provenance</h3>
@if (selected.Evidence.Count == 0)
{
<p>No provenance records were supplied.</p>
}
else
{
<ul>
@foreach (var evidence in selected.Evidence)
{
<li data-evidence="@evidence.EvidenceIdentifier">
@evidence.EvidenceIdentifier — @evidence.Classification.ToString().ToUpperInvariant():
@evidence.Description Source: @evidence.SourceReference.
Confidence: @(evidence.Confidence?.ToString("0.##") ?? "unknown").
Applicability: @evidence.Applicability.VehicleIdentifier
@if (evidence.Applicability.ModuleInstanceIdentifier is { } moduleIdentifier)
{
<span>, module @moduleIdentifier</span>
}
@if (evidence.Limitations.Count > 0)
{
<span> Limitations: @string.Join("; ", evidence.Limitations)</span>
}
</li>
}
</ul>
}
<p>Evidence preserves supplied claims; it is not independently verified and never authorizes an operation.</p>
<h3>JSON export for the explicitly selected revision</h3>
<label for="profile-json-export">Read-only schema-v1 JSON</label>
<textarea id="profile-json-export" rows="20" readonly>@Profiles.ExportJson</textarea>
<p>Export contains metadata only, not calibration values, firmware bytes, or operational commands.</p>
</section>
}

View File

@ -0,0 +1,39 @@
section {
margin-block: 1.5rem;
}
textarea {
display: block;
font-family: Consolas, monospace;
margin-block: 0.5rem;
max-width: 100%;
width: 52rem;
}
button {
background: #14283f;
border: 0;
border-radius: 0.25rem;
color: #fff;
cursor: pointer;
font: inherit;
padding: 0.55rem 0.85rem;
}
.profile-list li {
align-items: center;
display: flex;
flex-wrap: wrap;
gap: 0.75rem;
margin-block: 0.5rem;
}
.module-metadata {
border-block-start: 1px solid #bdc9d4;
margin-block: 1rem;
padding-block: 0.5rem;
}
dt {
font-weight: 600;
}

View File

@ -6,6 +6,7 @@
<nav aria-label="Main navigation">
<NavLink href="/" Match="NavLinkMatch.All">Home</NavLink>
<NavLink href="/execution-targets">Target selection</NavLink>
<NavLink href="/vehicle-profiles">Vehicle profiles</NavLink>
</nav>
</header>

View File

@ -5,3 +5,4 @@
@using AutoForge.Core.ExecutionTargets
@using AutoForge.UI.Features.Foundation
@using AutoForge.UI.Features.ExecutionTargets.SelectExecutionTarget
@using AutoForge.UI.Features.Vehicles.Profiles

View File

@ -27,4 +27,8 @@
<ProjectReference Include="..\..\AutoForge.UI\AutoForge.UI.csproj" />
</ItemGroup>
<ItemGroup>
<None Update="Fixtures\**\*.json" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,61 @@
{
"schemaVersion": 1,
"profileIdentifier": "autoforge.synthetic.orchard-cart",
"revision": 1,
"vehicle": {
"vehicleIdentifier": "vehicle.synthetic.orchard-cart",
"manufacturer": "AutoForge Synthetic",
"model": "Orchard Cart",
"modelYear": null,
"trim": null,
"engine": null,
"transmission": null,
"drivetrain": null,
"evidenceReferences": ["evidence.orchard"]
},
"modules": [
{
"instanceIdentifier": "module.custom.sensor-bridge",
"role": "custom.experimental-sensor-bridge",
"name": "Synthetic Sensor Bridge",
"hardwareIdentifier": null,
"softwareIdentifier": "software.synthetic.bridge",
"firmwareIdentifier": null,
"calibrationIdentifier": null,
"evidenceReferences": [],
"capabilities": [
{
"operationIdentifier": "custom.environment.snapshot",
"status": "UNKNOWN",
"explanation": "Custom operation metadata with unknown availability.",
"limitations": ["No operation service exists."],
"evidenceReferences": []
}
]
}
],
"evidence": [
{
"evidenceIdentifier": "evidence.orchard",
"classification": "SYNTHETIC",
"sourceReference": "fixture:synthetic-orchard-cart",
"description": "Fabricated alternate vehicle with unknown optional identity facts.",
"applicability": {
"vehicleIdentifier": "vehicle.synthetic.orchard-cart",
"modelYear": null,
"profileIdentifier": "autoforge.synthetic.orchard-cart",
"profileRevision": 1,
"moduleInstanceIdentifier": null,
"hardwareIdentifier": null,
"softwareIdentifier": null,
"firmwareIdentifier": null,
"calibrationIdentifier": null
},
"confidence": null,
"verificationInformation": null,
"publishedAt": null,
"retrievedAt": null,
"limitations": ["No real vehicle, module, or operation is represented."]
}
]
}

View File

@ -0,0 +1,157 @@
{
"schemaVersion": 1,
"profileIdentifier": "autoforge.synthetic.test-truck",
"revision": 1,
"vehicle": {
"vehicleIdentifier": "vehicle.synthetic.test-truck",
"manufacturer": "AutoForge Synthetic",
"model": "Test Truck",
"modelYear": 2025,
"trim": null,
"engine": "Synthetic inline-six",
"transmission": null,
"drivetrain": "Synthetic 4x4",
"evidenceReferences": ["evidence.vehicle"]
},
"modules": [
{
"instanceIdentifier": "module.engine.primary",
"role": "powertrain.engine-controller",
"name": "Synthetic Engine Controller",
"hardwareIdentifier": "hardware.synthetic.engine-a",
"softwareIdentifier": "software.synthetic.engine-1",
"firmwareIdentifier": null,
"calibrationIdentifier": "calibration.synthetic.engine-base",
"evidenceReferences": ["evidence.engine"],
"capabilities": [
{
"operationIdentifier": "diagnostic.read",
"status": "SUPPORTED",
"explanation": "Synthetic metadata declaration only.",
"limitations": ["Not a diagnostic service or connection."],
"evidenceReferences": ["evidence.engine"]
},
{
"operationIdentifier": "calibration.write",
"status": "RESTRICTED",
"explanation": "Synthetic restriction declaration; no write operation exists.",
"limitations": ["Never authorizes physical programming."],
"evidenceReferences": ["evidence.engine"]
}
]
},
{
"instanceIdentifier": "module.transmission.primary",
"role": "powertrain.transmission-controller",
"name": "Synthetic Transmission Controller",
"hardwareIdentifier": null,
"softwareIdentifier": null,
"firmwareIdentifier": null,
"calibrationIdentifier": null,
"evidenceReferences": [],
"capabilities": [
{
"operationIdentifier": "diagnostic.read",
"status": "INACCESSIBLE",
"explanation": "Synthetic access state is unknown to the application.",
"limitations": ["No communication is implemented."],
"evidenceReferences": []
}
]
},
{
"instanceIdentifier": "module.cabin.body",
"role": "body-control",
"name": "Synthetic Cabin Controller",
"hardwareIdentifier": "hardware.synthetic.body",
"softwareIdentifier": "software.synthetic.body-1",
"firmwareIdentifier": null,
"calibrationIdentifier": null,
"evidenceReferences": ["evidence.body"],
"capabilities": [
{
"operationIdentifier": "configuration.inspect",
"status": "UNSUPPORTED",
"explanation": "This synthetic declaration does not describe a working service.",
"limitations": ["No implementation exists."],
"evidenceReferences": ["evidence.body"]
},
{
"operationIdentifier": "service.inspect",
"status": "UNKNOWN",
"explanation": "The synthetic fixture explicitly records uncertainty.",
"limitations": ["Absence of support is not support."],
"evidenceReferences": ["evidence.body"]
}
]
}
],
"evidence": [
{
"evidenceIdentifier": "evidence.vehicle",
"classification": "SYNTHETIC",
"sourceReference": "fixture:synthetic-truck-baseline",
"description": "Fabricated training fixture; not a real vehicle definition.",
"applicability": {
"vehicleIdentifier": "vehicle.synthetic.test-truck",
"modelYear": 2025,
"profileIdentifier": "autoforge.synthetic.test-truck",
"profileRevision": 1,
"moduleInstanceIdentifier": null,
"hardwareIdentifier": null,
"softwareIdentifier": null,
"firmwareIdentifier": null,
"calibrationIdentifier": null
},
"confidence": null,
"verificationInformation": "Synthetic fixture content is not independently verified.",
"publishedAt": null,
"retrievedAt": null,
"limitations": ["Metadata only.", "No compatibility or operational claims."]
},
{
"evidenceIdentifier": "evidence.engine",
"classification": "SYNTHETIC",
"sourceReference": "fixture:synthetic-truck-baseline",
"description": "Fabricated engine module and identity metadata.",
"applicability": {
"vehicleIdentifier": "vehicle.synthetic.test-truck",
"modelYear": 2025,
"profileIdentifier": "autoforge.synthetic.test-truck",
"profileRevision": 1,
"moduleInstanceIdentifier": "module.engine.primary",
"hardwareIdentifier": "hardware.synthetic.engine-a",
"softwareIdentifier": "software.synthetic.engine-1",
"firmwareIdentifier": null,
"calibrationIdentifier": "calibration.synthetic.engine-base"
},
"confidence": null,
"verificationInformation": null,
"publishedAt": null,
"retrievedAt": null,
"limitations": ["Not a firmware image or calibration data."]
},
{
"evidenceIdentifier": "evidence.body",
"classification": "SYNTHETIC",
"sourceReference": "fixture:synthetic-truck-baseline",
"description": "Fabricated non-powertrain body module metadata.",
"applicability": {
"vehicleIdentifier": "vehicle.synthetic.test-truck",
"modelYear": 2025,
"profileIdentifier": "autoforge.synthetic.test-truck",
"profileRevision": 1,
"moduleInstanceIdentifier": "module.cabin.body",
"hardwareIdentifier": "hardware.synthetic.body",
"softwareIdentifier": "software.synthetic.body-1",
"firmwareIdentifier": null,
"calibrationIdentifier": null
},
"confidence": null,
"verificationInformation": null,
"publishedAt": null,
"retrievedAt": null,
"limitations": ["No diagnostic or service implementation exists."]
}
]
}

View File

@ -0,0 +1,157 @@
{
"schemaVersion": 1,
"profileIdentifier": "autoforge.synthetic.test-truck",
"revision": 2,
"vehicle": {
"vehicleIdentifier": "vehicle.synthetic.test-truck",
"manufacturer": "AutoForge Synthetic",
"model": "Test Truck",
"modelYear": 2025,
"trim": null,
"engine": "Synthetic inline-six",
"transmission": null,
"drivetrain": "Synthetic 4x4",
"evidenceReferences": ["evidence.vehicle.variant"]
},
"modules": [
{
"instanceIdentifier": "module.engine.primary",
"role": "powertrain.engine-controller",
"name": "Synthetic Engine Controller",
"hardwareIdentifier": "hardware.synthetic.engine-a",
"softwareIdentifier": "software.synthetic.engine-1",
"firmwareIdentifier": null,
"calibrationIdentifier": "calibration.synthetic.engine-variant",
"evidenceReferences": ["evidence.engine.variant"],
"capabilities": [
{
"operationIdentifier": "diagnostic.read",
"status": "SUPPORTED",
"explanation": "Synthetic metadata declaration only.",
"limitations": ["Not a diagnostic service or connection."],
"evidenceReferences": ["evidence.engine.variant"]
},
{
"operationIdentifier": "calibration.write",
"status": "RESTRICTED",
"explanation": "Synthetic restriction declaration; no write operation exists.",
"limitations": ["Never authorizes physical programming."],
"evidenceReferences": ["evidence.engine.variant"]
}
]
},
{
"instanceIdentifier": "module.transmission.primary",
"role": "powertrain.transmission-controller",
"name": "Synthetic Transmission Controller",
"hardwareIdentifier": null,
"softwareIdentifier": null,
"firmwareIdentifier": null,
"calibrationIdentifier": null,
"evidenceReferences": [],
"capabilities": [
{
"operationIdentifier": "diagnostic.read",
"status": "INACCESSIBLE",
"explanation": "Synthetic access state is unknown to the application.",
"limitations": ["No communication is implemented."],
"evidenceReferences": []
}
]
},
{
"instanceIdentifier": "module.cabin.body",
"role": "body-control",
"name": "Synthetic Cabin Controller",
"hardwareIdentifier": "hardware.synthetic.body",
"softwareIdentifier": "software.synthetic.body-1",
"firmwareIdentifier": null,
"calibrationIdentifier": null,
"evidenceReferences": ["evidence.body.variant"],
"capabilities": [
{
"operationIdentifier": "configuration.inspect",
"status": "UNSUPPORTED",
"explanation": "This synthetic declaration does not describe a working service.",
"limitations": ["No implementation exists."],
"evidenceReferences": ["evidence.body.variant"]
},
{
"operationIdentifier": "service.inspect",
"status": "UNKNOWN",
"explanation": "The synthetic fixture explicitly records uncertainty.",
"limitations": ["Absence of support is not support."],
"evidenceReferences": ["evidence.body.variant"]
}
]
}
],
"evidence": [
{
"evidenceIdentifier": "evidence.vehicle.variant",
"classification": "SYNTHETIC",
"sourceReference": "fixture:synthetic-truck-variant",
"description": "Fabricated revision 2 fixture; not a real vehicle definition.",
"applicability": {
"vehicleIdentifier": "vehicle.synthetic.test-truck",
"modelYear": 2025,
"profileIdentifier": "autoforge.synthetic.test-truck",
"profileRevision": 2,
"moduleInstanceIdentifier": null,
"hardwareIdentifier": null,
"softwareIdentifier": null,
"firmwareIdentifier": null,
"calibrationIdentifier": null
},
"confidence": null,
"verificationInformation": "Synthetic fixture content is not independently verified.",
"publishedAt": null,
"retrievedAt": null,
"limitations": ["Metadata only.", "No compatibility or operational claims."]
},
{
"evidenceIdentifier": "evidence.engine.variant",
"classification": "SYNTHETIC",
"sourceReference": "fixture:synthetic-truck-variant",
"description": "Fabricated engine module metadata with a distinct calibration reference.",
"applicability": {
"vehicleIdentifier": "vehicle.synthetic.test-truck",
"modelYear": 2025,
"profileIdentifier": "autoforge.synthetic.test-truck",
"profileRevision": 2,
"moduleInstanceIdentifier": "module.engine.primary",
"hardwareIdentifier": "hardware.synthetic.engine-a",
"softwareIdentifier": "software.synthetic.engine-1",
"firmwareIdentifier": null,
"calibrationIdentifier": "calibration.synthetic.engine-variant"
},
"confidence": null,
"verificationInformation": null,
"publishedAt": null,
"retrievedAt": null,
"limitations": ["Not a firmware image or calibration data."]
},
{
"evidenceIdentifier": "evidence.body.variant",
"classification": "SYNTHETIC",
"sourceReference": "fixture:synthetic-truck-variant",
"description": "Fabricated non-powertrain body module metadata.",
"applicability": {
"vehicleIdentifier": "vehicle.synthetic.test-truck",
"modelYear": 2025,
"profileIdentifier": "autoforge.synthetic.test-truck",
"profileRevision": 2,
"moduleInstanceIdentifier": "module.cabin.body",
"hardwareIdentifier": "hardware.synthetic.body",
"softwareIdentifier": "software.synthetic.body-1",
"firmwareIdentifier": null,
"calibrationIdentifier": null
},
"confidence": null,
"verificationInformation": null,
"publishedAt": null,
"retrievedAt": null,
"limitations": ["No diagnostic or service implementation exists."]
}
]
}

View File

@ -1,4 +1,5 @@
using AutoForge.Application.ExecutionTargets;
using AutoForge.Application.Features.Vehicles.Profiles;
using AutoForge.Core.ExecutionTargets;
using AutoForge.UI;
using AutoForge.UI.Features.ExecutionTargets.SelectExecutionTarget;
@ -143,6 +144,7 @@ public sealed class UiCompositionTests
var services = new ServiceCollection();
services.AddLogging();
services.AddAutoForgeTargetSelection(registrations);
services.AddAutoForgeVehicleProfiles();
services.AddAutoForgeUi();
services.AddSingleton<NavigationManager>(new TestNavigationManager(uri));
services.AddSingleton<INavigationInterception, TestNavigationInterception>();

View File

@ -0,0 +1,437 @@
using System.Text.Json.Nodes;
using AutoForge.Application.ExecutionTargets;
using AutoForge.Application.Features.Vehicles.Profiles;
using AutoForge.Core.ExecutionTargets;
using AutoForge.Core.Vehicles;
using AutoForge.UI;
using AutoForge.UI.Features.Vehicles.Profiles;
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 VehicleProfileCompositionTests
{
[Fact]
public void RealApplicationPath_ImportsSelectsAndRoundTripsSyntheticProfileSemantically()
{
using var provider = CreateProvider();
var profiles = provider.GetRequiredService<IVehicleProfileService>();
var originalJson = ReadFixture("synthetic-truck-baseline.json");
var imported = profiles.Import(originalJson);
var selected = profiles.Select("AUTOFORGE.SYNTHETIC.TEST-TRUCK", 1);
var exported = profiles.Export(imported.ProfileIdentifier, imported.Revision);
var roundTripped = new VehicleProfileJsonCodec().Import(exported);
Assert.Equal("vehicle.synthetic.test-truck", selected.Vehicle.VehicleIdentifier);
Assert.Equal(2025, selected.Vehicle.ModelYear);
Assert.Equal(3, selected.Modules.Count);
Assert.Equal("powertrain.engine-controller", selected.Modules[0].Role);
Assert.Equal("body-control", selected.Modules[2].Role);
Assert.Null(selected.Modules[1].HardwareIdentifier);
Assert.Equal(CapabilityStatus.Supported, selected.Modules[0].GetCapability("diagnostic.read").Status);
Assert.Equal(CapabilityStatus.Restricted, selected.Modules[0].GetCapability("calibration.write").Status);
Assert.Equal(CapabilityStatus.Inaccessible, selected.Modules[1].GetCapability("diagnostic.read").Status);
Assert.Equal(CapabilityStatus.Unsupported, selected.Modules[2].GetCapability("configuration.inspect").Status);
Assert.Equal(CapabilityStatus.Unknown, selected.Modules[2].GetCapability("service.inspect").Status);
Assert.False(selected.Modules[2].GetCapability("undeclared.operation").IsDeclared);
Assert.Equal(EvidenceClassification.Synthetic, selected.Evidence[0].Classification);
Assert.Null(selected.Evidence[0].Confidence);
Assert.Equal(selected.Modules.Select(module => module.InstanceIdentifier), roundTripped.Modules.Select(module => module.InstanceIdentifier));
Assert.Equal(selected.Modules.Select(module => module.CalibrationIdentifier), roundTripped.Modules.Select(module => module.CalibrationIdentifier));
Assert.Equal(
selected.Modules.SelectMany(module => module.Capabilities).Select(capability => capability.Status),
roundTripped.Modules.SelectMany(module => module.Capabilities).Select(capability => capability.Status));
Assert.Equal(
selected.Evidence.Select(item => item.Applicability.ModuleInstanceIdentifier),
roundTripped.Evidence.Select(item => item.Applicability.ModuleInstanceIdentifier));
Assert.Contains("fixture:synthetic-truck-baseline", exported);
}
[Fact]
public void Catalog_RequiresExactRevisionPreservesBaselineAndRejectsDuplicateImportAtomically()
{
using var provider = CreateProvider();
var profiles = provider.GetRequiredService<IVehicleProfileService>();
profiles.Import(ReadFixture("synthetic-truck-baseline.json"));
var baseline = profiles.Select("autoforge.synthetic.test-truck", 1);
profiles.Import(ReadFixture("synthetic-truck-variant.json"));
var variant = profiles.Select("autoforge.synthetic.test-truck", 2);
Assert.Equal("calibration.synthetic.engine-base", baseline.Modules[0].CalibrationIdentifier);
Assert.Equal("calibration.synthetic.engine-variant", variant.Modules[0].CalibrationIdentifier);
Assert.Equal("calibration.synthetic.engine-base", profiles.Select("autoforge.synthetic.test-truck", 1).Modules[0].CalibrationIdentifier);
Assert.Equal(2, profiles.List().Count);
Assert.Throws<VehicleProfileCatalogException>(() =>
profiles.Select("autoforge.synthetic.test-truck", 3));
var vehicleRebind = ReadFixture("synthetic-truck-variant.json").Replace(
"vehicle.synthetic.test-truck",
"vehicle.synthetic.other",
StringComparison.Ordinal);
var conflict = Assert.Throws<VehicleProfileCatalogException>(() => profiles.Import(vehicleRebind));
Assert.Equal(VehicleProfileCatalogFailure.ProfileVehicleIdentityConflict, conflict.Failure);
Assert.Equal(2, profiles.List().Count);
var duplicate = Assert.Throws<VehicleProfileCatalogException>(() =>
profiles.Import(ReadFixture("synthetic-truck-baseline.json")));
Assert.Equal(VehicleProfileCatalogFailure.DuplicateProfileRevision, duplicate.Failure);
Assert.Equal(2, profiles.List().Count);
Assert.Equal("calibration.synthetic.engine-base", profiles.Select("autoforge.synthetic.test-truck", 1).Modules[0].CalibrationIdentifier);
}
[Fact]
public void Catalog_LoadsAlternateVehicleAndCustomOperationsWithoutProductionChanges()
{
using var provider = CreateProvider();
var profiles = provider.GetRequiredService<IVehicleProfileService>();
profiles.Import(ReadFixture("synthetic-orchard-vehicle.json"));
var profile = profiles.Select("autoforge.synthetic.orchard-cart", 1);
var module = Assert.Single(profile.Modules);
var assessment = module.GetCapability("CUSTOM.ENVIRONMENT.SNAPSHOT");
Assert.Equal("custom.experimental-sensor-bridge", module.Role);
Assert.Null(profile.Vehicle.ModelYear);
Assert.Equal(CapabilityStatus.Unknown, assessment.Status);
Assert.True(assessment.IsDeclared);
Assert.Equal(EvidenceClassification.Synthetic, Assert.Single(profile.Evidence).Classification);
}
[Fact]
public void InvalidAndAmbiguousImports_FailWithoutPartialCatalogRegistration()
{
using var provider = CreateProvider();
var profiles = provider.GetRequiredService<IVehicleProfileService>();
var validJson = ReadFixture("synthetic-truck-baseline.json");
var invalidCases = new[]
{
"{",
validJson.Replace("\"schemaVersion\": 1", "\"schemaVersion\": 2", StringComparison.Ordinal),
validJson.Replace("\"schemaVersion\": 1,", "\"schemaVersion\": 1,\n \"schemaVersion\": 1,", StringComparison.Ordinal),
validJson.Replace("\"schemaVersion\": 1,", "\"schemaVersion\": 1,\n \"unexpected\": true,", StringComparison.Ordinal),
validJson.Replace("\"revision\": 1,", string.Empty, StringComparison.Ordinal),
validJson.Replace("\"status\": \"SUPPORTED\"", "\"status\": \"ENABLED\"", StringComparison.Ordinal),
validJson.Replace(
"\"instanceIdentifier\": \"module.transmission.primary\"",
"\"instanceIdentifier\": \"module.engine.primary\"",
StringComparison.Ordinal),
validJson.Replace(
"\"operationIdentifier\": \"calibration.write\"",
"\"operationIdentifier\": \"diagnostic.read\"",
StringComparison.Ordinal),
validJson.Replace(
"\"evidenceReferences\": [\"evidence.engine\"]",
"\"evidenceReferences\": [\"evidence.missing\"]",
StringComparison.Ordinal),
ReplaceFirstAfter(
validJson,
"\"applicability\"",
"\"vehicleIdentifier\": \"vehicle.synthetic.test-truck\"",
"\"vehicleIdentifier\": \"vehicle.synthetic.other\"")
};
for (var index = 0; index < invalidCases.Length; index++)
{
var failure = Record.Exception(() => profiles.Import(invalidCases[index]));
Assert.True(
failure is VehicleProfileInterchangeException,
$"Invalid JSON case {index} was accepted or returned {failure?.GetType().Name ?? "no error"}.");
Assert.Empty(profiles.List());
}
profiles.Import(validJson);
Assert.Single(profiles.List());
}
[Fact]
public async Task ProfilePage_UsesRealFeatureServiceAndRendersMetadataUnknownsAndExport()
{
using var provider = CreateProvider();
var page = provider.GetRequiredService<VehicleProfilePageViewModel>();
page.JsonInput = ReadFixture("synthetic-truck-baseline.json");
page.Import();
Assert.Single(page.AvailableProfiles);
Assert.Null(page.SelectedProfile);
page.SelectProfile("autoforge.synthetic.test-truck", 1);
var html = await RenderProfilePageAsync(provider);
Assert.Contains("Vehicle profile metadata", html);
Assert.Contains("status-notice--information", html);
Assert.Contains("Synthetic Engine Controller", html);
Assert.Contains("RESTRICTED", html);
Assert.Contains("unknown", html);
Assert.Contains("SYNTHETIC", html);
Assert.Contains("Read-only schema-v1 JSON", html);
Assert.Contains("not a connection, service, compatibility determination or authorization", html);
Assert.Contains("\"schemaVersion\": 1", page.ExportJson);
Assert.Contains("profile-json-export", html);
Assert.Contains("calibration.synthetic.engine-base", html);
}
[Fact]
public async Task ProfileRoute_EmptyCatalogDoesNotCreateOrSelectSyntheticData()
{
using var provider = CreateProvider();
var html = await RenderProfilePageAsync(provider);
Assert.Contains("Vehicle profile metadata", html);
Assert.Contains("No profiles are registered in this application session.", html);
Assert.Contains("no profile is selected automatically.", html);
Assert.DoesNotContain("Test Truck", html);
}
[Fact]
public async Task ProfilePage_ImportFailuresAndDuplicatesRemainVisibleWithoutReplacement()
{
using var provider = CreateProvider();
var page = provider.GetRequiredService<VehicleProfilePageViewModel>();
page.JsonInput = ReadFixture("synthetic-truck-baseline.json");
page.Import();
page.SelectProfile("autoforge.synthetic.test-truck", 1);
var selected = page.SelectedProfile;
page.JsonInput = "{";
page.Import();
Assert.Contains("valid schema-v1 JSON", page.StatusMessage);
Assert.Single(page.AvailableProfiles);
Assert.Same(selected, page.SelectedProfile);
var invalidHtml = await RenderProfilePageAsync(provider);
Assert.Contains("status-notice--error", invalidHtml);
Assert.Contains("valid schema-v1 JSON", invalidHtml);
page.JsonInput = ReadFixture("synthetic-truck-baseline.json");
page.Import();
Assert.Contains("already registered", page.StatusMessage);
Assert.Single(page.AvailableProfiles);
Assert.Same(selected, page.SelectedProfile);
var duplicateHtml = await RenderProfilePageAsync(provider);
Assert.Contains("status-notice--error", duplicateHtml);
Assert.Contains("already registered", duplicateHtml);
Assert.Contains("calibration.synthetic.engine-base", duplicateHtml);
}
[Fact]
public async Task ProfilePage_PartialModuleEvidenceImportsSelectsAndRoundTripsWithoutFillingConstraints()
{
using var provider = CreateProvider();
var page = provider.GetRequiredService<VehicleProfilePageViewModel>();
var json = MutateProfileJson(ReadFixture("synthetic-truck-baseline.json"), 2, root =>
{
var applicability = root["evidence"]!.AsArray()[1]!["applicability"]!.AsObject();
applicability["hardwareIdentifier"] = null;
applicability["softwareIdentifier"] = null;
applicability["firmwareIdentifier"] = null;
applicability["calibrationIdentifier"] = null;
Assert.All(
new[] { "hardwareIdentifier", "softwareIdentifier", "firmwareIdentifier", "calibrationIdentifier" },
name => Assert.Null(applicability[name]));
});
page.JsonInput = json;
page.Import();
Assert.Contains("Imported metadata", page.StatusMessage);
Assert.Equal(2, page.AvailableProfiles.Single().Revision);
page.SelectProfile("autoforge.synthetic.test-truck", 2);
var selected = Assert.IsType<VehicleProfile>(page.SelectedProfile);
var module = selected.GetModule("module.engine.primary");
var evidence = Assert.Single(selected.Evidence, item => item.EvidenceIdentifier == "evidence.engine");
Assert.Equal("hardware.synthetic.engine-a", module.HardwareIdentifier);
Assert.Null(evidence.Applicability.HardwareIdentifier);
Assert.Null(evidence.Applicability.SoftwareIdentifier);
Assert.Null(evidence.Applicability.FirmwareIdentifier);
Assert.Null(evidence.Applicability.CalibrationIdentifier);
Assert.Equal(EvidenceClassification.Synthetic, evidence.Classification);
Assert.Equal(CapabilityStatus.Supported, module.GetCapability("diagnostic.read").Status);
var roundTripped = new VehicleProfileJsonCodec().Import(page.ExportJson!);
var exportedEvidence = Assert.Single(roundTripped.Evidence, item => item.EvidenceIdentifier == "evidence.engine");
Assert.Null(exportedEvidence.Applicability.HardwareIdentifier);
Assert.Null(exportedEvidence.Applicability.SoftwareIdentifier);
Assert.Null(exportedEvidence.Applicability.FirmwareIdentifier);
Assert.Null(exportedEvidence.Applicability.CalibrationIdentifier);
Assert.Equal("hardware.synthetic.engine-a", roundTripped.GetModule("module.engine.primary").HardwareIdentifier);
Assert.Contains("\"hardwareIdentifier\": null", page.ExportJson);
var html = await RenderProfilePageAsync(provider);
Assert.Contains("Selected metadata", html);
Assert.Contains("Read-only schema-v1 JSON", html);
Assert.Contains("profile-json-export", html);
}
[Fact]
public async Task ProfilePage_InvalidTimestampShowsExactPathAndKeepsCatalogAndSelection()
{
using var provider = CreateProvider();
var page = provider.GetRequiredService<VehicleProfilePageViewModel>();
page.JsonInput = ReadFixture("synthetic-truck-baseline.json");
page.Import();
page.SelectProfile("autoforge.synthetic.test-truck", 1);
var selected = page.SelectedProfile;
page.JsonInput = MutateProfileJson(ReadFixture("synthetic-truck-baseline.json"), 2, root =>
{
var publishedAt = root["evidence"]!.AsArray()[0]!["publishedAt"];
Assert.Null(publishedAt);
root["evidence"]!.AsArray()[0]!["publishedAt"] = "12:34:56Z";
Assert.Equal("12:34:56Z", root["evidence"]!.AsArray()[0]!["publishedAt"]!.GetValue<string>());
});
page.Import();
Assert.Contains("$.evidence[0].publishedAt", page.StatusMessage);
Assert.Contains("complete ISO-8601 timestamp", page.StatusMessage);
Assert.Contains("explicit UTC offset", page.StatusMessage);
Assert.Single(page.AvailableProfiles);
Assert.Same(selected, page.SelectedProfile);
var html = await RenderProfilePageAsync(provider);
Assert.Contains("status-notice--error", html);
Assert.Contains("$.evidence[0].publishedAt", html);
}
[Fact]
public async Task ProfilePage_ConflictingSuppliedModuleConstraintShowsErrorWithoutReplacement()
{
using var provider = CreateProvider();
var page = provider.GetRequiredService<VehicleProfilePageViewModel>();
page.JsonInput = ReadFixture("synthetic-truck-baseline.json");
page.Import();
page.SelectProfile("autoforge.synthetic.test-truck", 1);
var selected = page.SelectedProfile;
page.JsonInput = MutateProfileJson(ReadFixture("synthetic-truck-baseline.json"), 2, root =>
{
var applicability = root["evidence"]!.AsArray()[1]!["applicability"]!.AsObject();
applicability["hardwareIdentifier"] = "hardware.synthetic.conflict";
Assert.Equal("hardware.synthetic.conflict", applicability["hardwareIdentifier"]!.GetValue<string>());
});
page.Import();
Assert.Contains("conflicting module applicability", page.StatusMessage);
Assert.Single(page.AvailableProfiles);
Assert.Same(selected, page.SelectedProfile);
var html = await RenderProfilePageAsync(provider);
Assert.Contains("status-notice--error", html);
Assert.Contains("conflicting module applicability", html);
}
[Fact]
public void ProfileComposition_DoesNotChangeExistingExplicitTargetSelection()
{
using var provider = CreateProvider(includeTarget: true);
var resolver = provider.GetRequiredService<IExecutionTargetResolver>();
var profiles = provider.GetRequiredService<IVehicleProfileService>();
var target = new ExecutionTargetDescriptor("explicit.simulation", ExecutionTargetKind.Simulation);
profiles.Import(ReadFixture("synthetic-truck-baseline.json"));
var selected = resolver.Resolve(target);
Assert.Equal(target.ProviderIdentifier, selected.ProviderIdentifier);
Assert.Equal(target.Kind, selected.Kind);
Assert.Throws<TargetSelectionException>(() =>
resolver.Resolve(new ExecutionTargetDescriptor("explicit.simulation", ExecutionTargetKind.PhysicalHardware)));
}
private static ServiceProvider CreateProvider(bool includeTarget = false)
{
var services = new ServiceCollection();
services.AddLogging();
if (includeTarget)
{
services.AddAutoForgeTargetSelection(
[new ExecutionTargetDescriptor("explicit.simulation", ExecutionTargetKind.Simulation)]);
}
else
{
services.AddAutoForgeTargetSelection([]);
}
services.AddAutoForgeVehicleProfiles();
services.AddAutoForgeUi();
services.AddSingleton<NavigationManager>(new TestNavigationManager("http://localhost/vehicle-profiles"));
services.AddSingleton<INavigationInterception, TestNavigationInterception>();
services.AddSingleton<IScrollToLocationHash, TestScrollToLocationHash>();
return services.BuildServiceProvider();
}
private static async Task<string> RenderProfilePageAsync(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 static string ReadFixture(string name) =>
File.ReadAllText(Path.Combine(AppContext.BaseDirectory, "Fixtures", name));
private static string MutateProfileJson(string json, int revision, Action<JsonObject> mutate)
{
var root = JsonNode.Parse(json)!.AsObject();
root["revision"] = revision;
foreach (var item in root["evidence"]!.AsArray())
{
var applicability = item!["applicability"]!.AsObject();
if (applicability["profileIdentifier"] is not null)
{
applicability["profileRevision"] = revision;
}
}
mutate(root);
Assert.Equal(revision, root["revision"]!.GetValue<int>());
return root.ToJsonString();
}
private static string ReplaceFirstAfter(string source, string anchor, string oldValue, string newValue)
{
var anchorIndex = source.IndexOf(anchor, StringComparison.Ordinal);
var valueIndex = source.IndexOf(oldValue, anchorIndex, StringComparison.Ordinal);
if (anchorIndex < 0 || valueIndex < 0)
{
throw new InvalidOperationException($"Could not find '{oldValue}' after '{anchor}'.");
}
return string.Concat(
source.AsSpan(0, valueIndex),
newValue,
source.AsSpan(valueIndex + oldValue.Length));
}
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;
}
}

View File

@ -0,0 +1,326 @@
using AutoForge.Core.Vehicles;
namespace AutoForge.UnitTests;
public sealed class VehicleProfileDomainTests
{
[Fact]
public void Profile_AllowsCustomRolesAndSnapshotsModuleAndEvidenceCollections()
{
var modules = new List<ModuleInstance>
{
new("module.one", "custom.sensor", "Sensor one"),
new("module.two", "custom.sensor", "Sensor two")
};
var evidence = new List<ProfileEvidence>();
var profile = CreateProfile(modules, evidence);
modules.Clear();
Assert.Equal(2, profile.Modules.Count);
Assert.Equal("custom.sensor", profile.Modules[1].Role);
Assert.Null(profile.Vehicle.ModelYear);
Assert.Empty(profile.Evidence);
Assert.Throws<NotSupportedException>(() => ((IList<ModuleInstance>)profile.Modules).Clear());
}
[Fact]
public void Profile_RejectsCaseInsensitiveDuplicateModuleAndEvidenceIdentifiers()
{
var duplicateModules = new[]
{
new ModuleInstance("module.same", "role.a", "First"),
new ModuleInstance("MODULE.SAME", "role.b", "Second")
};
Assert.Throws<ArgumentException>(() => CreateProfile(duplicateModules, []));
var evidence = new[]
{
CreateEvidence("evidence.same", new EvidenceApplicability("vehicle.test")),
CreateEvidence("EVIDENCE.SAME", new EvidenceApplicability("vehicle.test"))
};
Assert.Throws<ArgumentException>(() => CreateProfile([], evidence));
}
[Fact]
public void Module_RejectsDuplicateOperationIdentifiersAndInvalidStatus()
{
Assert.Throws<ArgumentException>(() => new ModuleInstance(
"module.one",
"role.custom",
"Module",
capabilities:
[
new CapabilityDeclaration("custom.inspect", CapabilityStatus.Unknown),
new CapabilityDeclaration("CUSTOM.INSPECT", CapabilityStatus.Supported)
]));
Assert.Throws<ArgumentOutOfRangeException>(() =>
new CapabilityDeclaration("custom.inspect", (CapabilityStatus)999));
}
[Fact]
public void MissingCapability_IsExplicitUnknownAndNotDeclared()
{
var module = new ModuleInstance("module.one", "role.custom", "Module");
var assessment = module.GetCapability("custom.unknown-operation");
Assert.Equal(CapabilityStatus.Unknown, assessment.Status);
Assert.False(assessment.IsDeclared);
Assert.Contains("No capability declaration", assessment.Explanation);
}
[Theory]
[InlineData(double.NaN)]
[InlineData(double.PositiveInfinity)]
[InlineData(-0.01)]
[InlineData(1.01)]
public void Evidence_RejectsInvalidConfidence(double confidence)
{
Assert.Throws<ArgumentOutOfRangeException>(() => CreateEvidence(
"evidence.test",
new EvidenceApplicability("vehicle.test"),
confidence));
}
[Fact]
public void Evidence_RejectsDanglingAndConflictingApplicabilityReferences()
{
var module = new ModuleInstance(
"module.one",
"role.custom",
"Module",
hardwareIdentifier: "hardware.one",
evidenceReferences: ["evidence.module"]);
Assert.Throws<ArgumentException>(() => CreateProfile(
[new ModuleInstance(
"module.dangling",
"role.custom",
"Module",
evidenceReferences: ["evidence.missing"])],
[]));
var wrongScope = CreateEvidence(
"evidence.module",
new EvidenceApplicability(
"vehicle.test",
profileIdentifier: "profile.test",
profileRevision: 1,
moduleInstanceIdentifier: "module.one",
hardwareIdentifier: "hardware.other"));
Assert.Throws<ArgumentException>(() => CreateProfile([module], [wrongScope]));
}
[Fact]
public void EvidenceApplicability_NullOptionalIdentitiesAreNoConstraintForKnownModule()
{
foreach (var omittedIdentity in new string?[] { null, "hardware", "software", "firmware", "calibration" })
{
var module = CreateKnownIdentityModule();
var applicability = CreateModuleApplicability(omittedIdentity);
var evidence = CreateEvidence("evidence.module", applicability);
var profile = new VehicleProfile(
"profile.test",
1,
new VehicleIdentity("vehicle.test", "AutoForge Synthetic", "Test Vehicle", modelYear: 2025),
[module],
[evidence]);
Assert.Equal(EvidenceClassification.Synthetic, profile.Evidence.Single().Classification);
Assert.Equal("hardware.known", module.HardwareIdentifier);
Assert.Equal("software.known", module.SoftwareIdentifier);
Assert.Equal("firmware.known", module.FirmwareIdentifier);
Assert.Equal("calibration.known", module.CalibrationIdentifier);
Assert.Equal("module.one", profile.Evidence.Single().Applicability.ModuleInstanceIdentifier);
Assert.Equal(omittedIdentity == "hardware" ? null : "hardware.known", profile.Evidence.Single().Applicability.HardwareIdentifier);
Assert.Equal(omittedIdentity == "software" ? null : "software.known", profile.Evidence.Single().Applicability.SoftwareIdentifier);
Assert.Equal(omittedIdentity == "firmware" ? null : "firmware.known", profile.Evidence.Single().Applicability.FirmwareIdentifier);
Assert.Equal(omittedIdentity == "calibration" ? null : "calibration.known", profile.Evidence.Single().Applicability.CalibrationIdentifier);
Assert.Equal("evidence.module", Assert.Single(module.EvidenceReferences));
Assert.Equal("evidence.module", Assert.Single(module.Capabilities[0].EvidenceReferences));
Assert.Equal(CapabilityStatus.Unknown, module.GetCapability("custom.inspect").Status);
}
}
[Theory]
[InlineData("hardware", true)]
[InlineData("software", true)]
[InlineData("firmware", true)]
[InlineData("calibration", true)]
[InlineData("hardware", false)]
[InlineData("software", false)]
[InlineData("firmware", false)]
[InlineData("calibration", false)]
public void EvidenceApplicability_RejectsSuppliedIdentityMismatchOrUnknownTarget(
string identityName,
bool targetHasKnownIdentity)
{
var knownValues = new Dictionary<string, string?>(StringComparer.Ordinal)
{
["hardware"] = "hardware.known",
["software"] = "software.known",
["firmware"] = "firmware.known",
["calibration"] = "calibration.known"
};
var moduleValues = new Dictionary<string, string?>(knownValues, StringComparer.Ordinal);
if (!targetHasKnownIdentity)
{
moduleValues[identityName] = null;
}
knownValues[identityName] = $"{identityName}.other";
var module = new ModuleInstance(
"module.one",
"role.custom",
"Module",
moduleValues["hardware"],
moduleValues["software"],
moduleValues["firmware"],
moduleValues["calibration"]);
var applicability = new EvidenceApplicability(
"vehicle.test",
profileIdentifier: "profile.test",
profileRevision: 1,
moduleInstanceIdentifier: "module.one",
hardwareIdentifier: knownValues["hardware"],
softwareIdentifier: knownValues["software"],
firmwareIdentifier: knownValues["firmware"],
calibrationIdentifier: knownValues["calibration"]);
Assert.Throws<ArgumentException>(() => new VehicleProfile(
"profile.test",
1,
new VehicleIdentity("vehicle.test", "AutoForge Synthetic", "Test Vehicle"),
[module],
[CreateEvidence("evidence.module", applicability)]));
}
[Theory]
[InlineData("vehicle")]
[InlineData("profile")]
[InlineData("revision")]
[InlineData("module")]
public void EvidenceApplicability_RejectsWrongVehicleProfileRevisionAndModule(string mismatch)
{
var module = CreateKnownIdentityModule();
var applicability = mismatch switch
{
"vehicle" => new EvidenceApplicability(
"vehicle.other",
profileIdentifier: "profile.test",
profileRevision: 1,
moduleInstanceIdentifier: "module.one"),
"profile" => new EvidenceApplicability(
"vehicle.test",
profileIdentifier: "profile.other",
profileRevision: 1,
moduleInstanceIdentifier: "module.one"),
"revision" => new EvidenceApplicability(
"vehicle.test",
profileIdentifier: "profile.test",
profileRevision: 2,
moduleInstanceIdentifier: "module.one"),
"module" => new EvidenceApplicability(
"vehicle.test",
profileIdentifier: "profile.test",
profileRevision: 1,
moduleInstanceIdentifier: "module.missing"),
_ => throw new ArgumentOutOfRangeException(nameof(mismatch))
};
Assert.Throws<ArgumentException>(() => new VehicleProfile(
"profile.test",
1,
new VehicleIdentity("vehicle.test", "AutoForge Synthetic", "Test Vehicle"),
[module],
[CreateEvidence("evidence.module", applicability)]));
}
[Fact]
public void Constructors_RejectWhitespaceIdentifiersInvalidRevisionAndModelYear()
{
Assert.Throws<ArgumentException>(() =>
new VehicleIdentity(" vehicle.test", "Synthetic", "Roadster"));
Assert.Throws<ArgumentOutOfRangeException>(() =>
new VehicleProfile("profile.test", 0, new VehicleIdentity("vehicle.test", "Synthetic", "Roadster"), [], []));
Assert.Throws<ArgumentOutOfRangeException>(() =>
new VehicleIdentity("vehicle.test", "Synthetic", "Roadster", modelYear: 0));
}
[Fact]
public void EvidenceApplicability_RequiresCompleteProfileAndModuleContext()
{
Assert.Throws<ArgumentException>(() =>
new EvidenceApplicability("vehicle.test", profileIdentifier: "profile.test"));
Assert.Throws<ArgumentException>(() =>
new EvidenceApplicability("vehicle.test", hardwareIdentifier: "hardware.one"));
}
[Fact]
public void Profile_RejectsEvidenceForConflictingKnownModelYear()
{
var evidence = CreateEvidence(
"evidence.year",
new EvidenceApplicability("vehicle.test", modelYear: 2024));
var vehicle = new VehicleIdentity(
"vehicle.test",
"AutoForge Synthetic",
"Test Vehicle",
modelYear: 2025,
evidenceReferences: ["evidence.year"]);
Assert.Throws<ArgumentException>(() => new VehicleProfile("profile.test", 1, vehicle, [], [evidence]));
}
private static VehicleProfile CreateProfile(
IEnumerable<ModuleInstance> modules,
IEnumerable<ProfileEvidence> evidence) =>
new(
"profile.test",
1,
new VehicleIdentity("vehicle.test", "AutoForge Synthetic", "Test Vehicle"),
modules,
evidence);
private static ProfileEvidence CreateEvidence(
string id,
EvidenceApplicability applicability,
double? confidence = null) =>
new(
id,
EvidenceClassification.Synthetic,
"fixture:unit-test",
"Synthetic unit test evidence.",
applicability,
confidence,
limitations: ["Metadata only."]);
private static ModuleInstance CreateKnownIdentityModule() =>
new(
"module.one",
"role.custom",
"Module",
"hardware.known",
"software.known",
"firmware.known",
"calibration.known",
capabilities: [new CapabilityDeclaration(
"custom.inspect",
CapabilityStatus.Unknown,
evidenceReferences: ["evidence.module"])],
evidenceReferences: ["evidence.module"]);
private static EvidenceApplicability CreateModuleApplicability(string? omittedIdentity) =>
new(
"vehicle.test",
modelYear: 2025,
profileIdentifier: "profile.test",
profileRevision: 1,
moduleInstanceIdentifier: "module.one",
hardwareIdentifier: omittedIdentity == "hardware" ? null : "hardware.known",
softwareIdentifier: omittedIdentity == "software" ? null : "software.known",
firmwareIdentifier: omittedIdentity == "firmware" ? null : "firmware.known",
calibrationIdentifier: omittedIdentity == "calibration" ? null : "calibration.known");
}

View File

@ -0,0 +1,277 @@
using System.Text.Json.Nodes;
using AutoForge.Application.Features.Vehicles.Profiles;
using AutoForge.Core.Vehicles;
namespace AutoForge.UnitTests;
public sealed class VehicleProfileJsonCodecTests
{
private readonly VehicleProfileJsonCodec _codec = new();
[Fact]
public void ExportImport_PreservesIdentityUnknownsCapabilitiesAndEvidence()
{
var profile = CreateProfile();
var json = _codec.Export(profile);
var imported = _codec.Import(json);
Assert.Equal(profile.ProfileIdentifier, imported.ProfileIdentifier);
Assert.Equal(profile.Revision, imported.Revision);
Assert.Null(imported.Vehicle.ModelYear);
Assert.Null(imported.Modules[0].FirmwareIdentifier);
Assert.Equal(CapabilityStatus.Restricted, imported.Modules[0].Capabilities[0].Status);
Assert.Equal(EvidenceClassification.Synthetic, imported.Evidence[0].Classification);
Assert.Null(imported.Evidence[0].Confidence);
Assert.Equal("calibration.synthetic.unknown", imported.Modules[0].CalibrationIdentifier);
}
[Fact]
public void Import_RejectsDuplicateUnknownAndMissingProperties()
{
var json = _codec.Export(CreateProfile());
var duplicate = json.Replace(
"\"schemaVersion\": 1,",
"\"schemaVersion\": 1,\r\n \"schemaVersion\": 1,",
StringComparison.Ordinal);
var unknown = json.Replace(
"\"schemaVersion\": 1,",
"\"schemaVersion\": 1,\r\n \"unexpected\": true,",
StringComparison.Ordinal);
var missing = json.Replace("\"revision\": 3,", string.Empty, StringComparison.Ordinal);
Assert.Contains("Duplicate", Assert.Throws<VehicleProfileInterchangeException>(() => _codec.Import(duplicate)).Message);
Assert.Contains("Unknown properties", Assert.Throws<VehicleProfileInterchangeException>(() => _codec.Import(unknown)).Message);
Assert.Contains("revision", Assert.Throws<VehicleProfileInterchangeException>(() => _codec.Import(missing)).Message);
}
[Fact]
public void Import_RejectsMalformedAndUnsupportedSchema()
{
Assert.Throws<VehicleProfileInterchangeException>(() => _codec.Import("{"));
var unsupported = _codec.Export(CreateProfile()).Replace(
"\"schemaVersion\": 1",
"\"schemaVersion\": 2",
StringComparison.Ordinal);
Assert.Contains(
"unsupported",
Assert.Throws<VehicleProfileInterchangeException>(() => _codec.Import(unsupported)).Message);
}
[Fact]
public void Import_RejectsInvalidCapabilityStatusAndDanglingEvidence()
{
var json = _codec.Export(CreateProfile());
var invalidStatus = json.Replace("\"RESTRICTED\"", "\"ENABLED\"", StringComparison.Ordinal);
var moduleReferenceStart = json.IndexOf("\"evidenceReferences\"", json.IndexOf("\"modules\"", StringComparison.Ordinal), StringComparison.Ordinal);
var evidenceReferenceIndex = json.IndexOf("\"evidence.test\"", moduleReferenceStart, StringComparison.Ordinal);
var dangling = string.Concat(json.AsSpan(0, evidenceReferenceIndex), "\"evidence.missing\"", json.AsSpan(evidenceReferenceIndex + "\"evidence.test\"".Length));
Assert.Contains(
"capability status",
Assert.Throws<VehicleProfileInterchangeException>(() => _codec.Import(invalidStatus)).Message);
Assert.Contains(
"does not resolve",
Assert.Throws<VehicleProfileInterchangeException>(() => _codec.Import(dangling)).Message);
}
[Theory]
[InlineData(EvidenceClassification.Verified, "VERIFIED")]
[InlineData(EvidenceClassification.Unverified, "UNVERIFIED")]
[InlineData(EvidenceClassification.Inferred, "INFERRED")]
[InlineData(EvidenceClassification.Synthetic, "SYNTHETIC")]
public void ExportImport_PreservesEvidenceClassificationAndExplicitPublicationTimes(
EvidenceClassification classification,
string expectedClassification)
{
var publishedAt = new DateTimeOffset(2025, 2, 3, 4, 5, 6, TimeSpan.FromHours(-5));
var evidence = new ProfileEvidence(
"evidence.classification",
classification,
"fixture:classification-tests",
"Classification codec test vector.",
new EvidenceApplicability(
"vehicle.classification",
modelYear: 2025,
profileIdentifier: "profile.classification",
profileRevision: 1),
confidence: 0.75,
verificationInformation: "Test-only information.",
publishedAt: publishedAt,
retrievedAt: publishedAt.AddDays(1),
limitations: ["Test data only."]);
var profile = new VehicleProfile(
"profile.classification",
1,
new VehicleIdentity("vehicle.classification", "AutoForge Synthetic", "Evidence Test", modelYear: 2025),
[],
[evidence]);
var json = _codec.Export(profile);
var imported = _codec.Import(json);
var result = Assert.Single(imported.Evidence);
Assert.Contains($"\"classification\": \"{expectedClassification}\"", json);
Assert.Equal(classification, result.Classification);
Assert.Equal(publishedAt, result.PublishedAt);
Assert.Equal(publishedAt.Offset, result.PublishedAt!.Value.Offset);
Assert.Equal(publishedAt.AddDays(1), result.RetrievedAt);
Assert.Equal(0.75, result.Confidence);
Assert.Equal("profile.classification", result.Applicability.ProfileIdentifier);
Assert.Equal(1, result.Applicability.ProfileRevision);
Assert.Equal(2025, result.Applicability.ModelYear);
}
[Theory]
[InlineData("publishedAt", "12:34:56Z")]
[InlineData("publishedAt", "2025-02-03")]
[InlineData("publishedAt", "2025-02-03T04:05:06")]
[InlineData("publishedAt", "Feb 3 04:05:06Z")]
[InlineData("publishedAt", "02/03/2025 04:05:06Z")]
[InlineData("publishedAt", " 2025-02-03T04:05:06Z")]
[InlineData("publishedAt", "2025-02-03T04:05:06Z ")]
[InlineData("publishedAt", "2025-02-30T04:05:06Z")]
[InlineData("publishedAt", "2025-02-03T04:05:06+14:01")]
[InlineData("retrievedAt", "12:34:56Z")]
[InlineData("retrievedAt", "2025-02-03")]
[InlineData("retrievedAt", "2025-02-03T04:05:06")]
[InlineData("retrievedAt", "Feb 3 04:05:06Z")]
[InlineData("retrievedAt", "02/03/2025 04:05:06Z")]
[InlineData("retrievedAt", " 2025-02-03T04:05:06Z")]
[InlineData("retrievedAt", "2025-02-03T04:05:06Z ")]
[InlineData("retrievedAt", "2025-02-30T04:05:06Z")]
[InlineData("retrievedAt", "2025-02-03T04:05:06+14:01")]
public void Import_RejectsIncompleteOrAmbientDependentTimestamps(string propertyName, string timestamp)
{
var exception = Assert.Throws<VehicleProfileInterchangeException>(
() => _codec.Import(WithTimestamp(propertyName, timestamp)));
Assert.Equal($"$.evidence[0].{propertyName}", exception.Path);
Assert.Contains("complete ISO-8601 timestamp", exception.Message);
Assert.Contains("explicit UTC offset", exception.Message);
}
[Theory]
[InlineData("publishedAt")]
[InlineData("retrievedAt")]
public void Import_PreservesExplicitNullTimestamp(string propertyName)
{
var imported = _codec.Import(WithTimestamp(propertyName, null));
var evidence = Assert.Single(imported.Evidence);
Assert.Null(propertyName == "publishedAt" ? evidence.PublishedAt : evidence.RetrievedAt);
}
[Theory]
[InlineData("publishedAt", "2025-02-03T04:05:06Z", 0, 0)]
[InlineData("publishedAt", "2025-02-03T04:05:06.1Z", 0, 1000000)]
[InlineData("publishedAt", "2025-02-03T04:05:06+05:30", 330, 0)]
[InlineData("publishedAt", "2025-02-03T04:05:06-07:45", -465, 0)]
[InlineData("publishedAt", "2025-02-03T04:05:06.1234567+05:30", 330, 1234567)]
[InlineData("retrievedAt", "2025-02-03T04:05:06Z", 0, 0)]
[InlineData("retrievedAt", "2025-02-03T04:05:06.1Z", 0, 1000000)]
[InlineData("retrievedAt", "2025-02-03T04:05:06+05:30", 330, 0)]
[InlineData("retrievedAt", "2025-02-03T04:05:06-07:45", -465, 0)]
[InlineData("retrievedAt", "2025-02-03T04:05:06.1234567+05:30", 330, 1234567)]
public void Import_PreservesCompleteTimestampAndExplicitOffset(
string propertyName,
string timestamp,
int offsetMinutes,
int fractionalTicks)
{
var imported = _codec.Import(WithTimestamp(propertyName, timestamp));
var actual = propertyName == "publishedAt"
? imported.Evidence[0].PublishedAt
: imported.Evidence[0].RetrievedAt;
var expected = new DateTimeOffset(
2025,
2,
3,
4,
5,
6,
TimeSpan.FromMinutes(offsetMinutes))
.AddTicks(fractionalTicks);
Assert.True(actual.HasValue);
Assert.True(expected.EqualsExact(actual.Value));
}
[Fact]
public void ExportImport_PreservesExporterFractionalTimestampExactly()
{
var publishedAt = new DateTimeOffset(2025, 2, 3, 4, 5, 6, TimeSpan.FromHours(-5))
.AddTicks(1_234_567);
var evidence = new ProfileEvidence(
"evidence.fractional",
EvidenceClassification.Unverified,
"fixture:fractional",
"Exporter fractional timestamp test.",
new EvidenceApplicability("vehicle.fractional"),
publishedAt: publishedAt,
retrievedAt: publishedAt);
var profile = new VehicleProfile(
"profile.fractional",
1,
new VehicleIdentity("vehicle.fractional", "AutoForge Synthetic", "Fractional Test"),
[],
[evidence]);
var json = _codec.Export(profile);
var imported = _codec.Import(json);
Assert.Contains("2025-02-03T04:05:06.1234567-05:00", json);
Assert.True(publishedAt.EqualsExact(imported.Evidence[0].PublishedAt!.Value));
Assert.True(publishedAt.EqualsExact(imported.Evidence[0].RetrievedAt!.Value));
}
private string WithTimestamp(string propertyName, string? timestamp)
{
var root = JsonNode.Parse(_codec.Export(CreateProfile()))!.AsObject();
var evidence = root["evidence"]!.AsArray()[0]!.AsObject();
evidence[propertyName] = timestamp;
return root.ToJsonString();
}
private static VehicleProfile CreateProfile()
{
var evidence = new ProfileEvidence(
"evidence.test",
EvidenceClassification.Synthetic,
"fixture:codec-test",
"Explicit synthetic evidence.",
new EvidenceApplicability(
"vehicle.codec-test",
profileIdentifier: "profile.codec-test",
profileRevision: 3),
limitations: ["Not operational evidence."]);
var module = new ModuleInstance(
"module.test",
"custom.module-role",
"Synthetic module",
calibrationIdentifier: "calibration.synthetic.unknown",
capabilities:
[
new CapabilityDeclaration(
"custom.operation",
CapabilityStatus.Restricted,
"Synthetic metadata only.",
["No service or authorization."],
["evidence.test"])
],
evidenceReferences: ["evidence.test"]);
return new VehicleProfile(
"profile.codec-test",
3,
new VehicleIdentity(
"vehicle.codec-test",
"AutoForge Synthetic",
"Codec Test Vehicle",
evidenceReferences: ["evidence.test"]),
[module],
[evidence]);
}
}