AutoForge/docs/architecture.md

338 lines
23 KiB
Markdown

# Implemented architecture
## Application shape
AutoForge is an in-process modular monolith with exactly one application
executable: the Windows-first MAUI Blazor Hybrid Client. The application uses
Razor component libraries for the complete routed UI and generic shared controls.
There is no web/server host, WASM host or backend process.
## Current milestone status
Steps 04/04A/04B, 05/05A/05B, 06/06A and corrected 07/07A/07B are accepted.
Step-08 adds archive-only recorded replay with exact prefix reduction and one
page-owned cancellable clock and is accepted. Step-09 adds source-bound,
process-memory synthetic calibration authoring and is accepted. Step-10 adds
isolated simulated programming rehearsal with independent backup and full
readback/recovery and is accepted after Step-10A. Step-11 adds strict read-only
manual runbook validation/preview and is accepted. Step-12 adds optional bounded
local-only generation. The original missing-model inspection is historical;
Completion/Step-12A verify the installed exact local model. Real-model verification
now passes under corrected owner-directed Step-12A setup with a verified current
cloud-disabled:true runtime and actual original native intent/pending evidence.
A narrow event/owner-execution dispatch fix keeps HTTP work from blocking Hybrid
controls. Worker completion is pending manual acceptance; Step-13 is not started.
```mermaid
flowchart TD
Client[AutoForge.Client: MAUI startup, BlazorWebView and DI] --> UI[AutoForge.UI: routes and feature presentation]
UI --> Components[AutoForge.Components: reusable generic UI]
UI --> App[AutoForge.Application: cohesive feature slices]
Client --> App
App --> Diagnostics[AutoForge.Diagnostics: provider-neutral protocol and contracts]
App --> Core[AutoForge.Core: platform-neutral models]
Diagnostics --> Core
Client --> Simulation[AutoForge.Simulation: synthetic provider and transport]
Simulation --> Diagnostics
Simulation --> Core
UnitTests[AutoForge.UnitTests] --> Components
UnitTests --> Core
UnitTests --> App
UnitTests --> Diagnostics
UnitTests --> Simulation
IntegrationTests[AutoForge.IntegrationTests] --> UI
IntegrationTests --> App
IntegrationTests --> Core
IntegrationTests --> Diagnostics
IntegrationTests --> Simulation
```
## Projects and dependency boundaries
All nine projects are in [AutoForge.slnx](../src/AutoForge.slnx):
| Project | Target and responsibility | Project references |
|---|---|---|
| [Core](../src/AutoForge.Core/AutoForge.Core.csproj) | `net10.0`; platform-neutral target/profile invariants, immutable dynamics contracts and bounded synthetic calibration definition/value/applicability validation | None |
| [Diagnostics](../src/AutoForge.Diagnostics/AutoForge.Diagnostics.csproj) | `net10.0`; diagnostic contracts/protocol/trace plus a separate narrow typed simulated-calibration target port | Core |
| [Simulation](../src/AutoForge.Simulation/AutoForge.Simulation.csproj) | `net10.0`; static/dynamic providers and a separate mutable logical calibration rehearsal image/CAS owner | Core, Diagnostics |
| [Application](../src/AutoForge.Application/AutoForge.Application.csproj) | `net10.0`; target/profile/diagnostics/dynamics coordination, units/dashboard/recording/replay, authoring/rehearsal and strict read-only runbook preview | Core, Diagnostics |
| [Components](../src/AutoForge.Components/AutoForge.Components.csproj) | `net10.0` RCL; generic `StatusNotice` and numeric/bar gauge with accessible state and safe rendering | None |
| [UI](../src/AutoForge.UI/AutoForge.UI.csproj) | `net10.0` RCL; all application routes, navigation, layout and presentation, including shared dashboard and recording/archive inspection controls | Application, Components, Diagnostics |
| [Client](../src/AutoForge.Client/AutoForge.Client.csproj) | `net10.0-windows10.0.26100.0`; only MAUI Blazor Hybrid application executable, native preference adapter and app-local archive root | Application, Simulation, UI |
| [UnitTests](../src/tests/AutoForge.UnitTests/AutoForge.UnitTests.csproj) | `net10.0`; Core/Application/contracts, protocol and reusable component tests | Application, Components, Core, Diagnostics, Simulation |
| [IntegrationTests](../src/tests/AutoForge.IntegrationTests/AutoForge.IntegrationTests.csproj) | `net10.0`; real DI, fixtures, provider transport/session and rendered UI/project-graph tests | Application, Components, Core, Diagnostics, Simulation, UI |
Components has no AutoForge project dependency. UI never references Client or
Simulation. Application never references Simulation, UI, Components or Client.
Core, Diagnostics and Simulation do not reference Application/UI/Client.
The static provider's DTC oracle is limited to IntegrationTests; the fixed-step
engine test surface is limited to UnitTests. Neither is part of production
Application/Diagnostics/UI contracts. There are
no cycles or production-to-test edges. Tests render UI directly and never
reference or launch Client.
The Client composes the unchanged static `SimulatedDiagnosticTransportFactory`
and the separate `DynamicsDiagnosticTransportFactory`. The static provider
remains `autoforge.simulation.synthetic` and uses strict protocol v1; the dynamics
provider is `autoforge.simulation.dynamics` and requires an explicit versioned
configuration, run identity, control capability and protocol-v2 frames.
`AddAutoForgeDiagnostics` registers both factory descriptors from the same
factory registrations used for transport resolution. Target
metadata resolution remains a separate, metadata-only action. The profile
catalog is process-local; importing does not select a revision or open a session.
RecordedReplay is an archive-only Application context, not a diagnostic
provider or simulated connection. Physical kinds have no operational
implementation; neither kind is substituted with Simulation.
## UI ownership and real routes
All Razor routes and layouts are owned by the UI RCL; `Routes` scans the UI
assembly, not the native Client assembly.
| Route | UI owner | Implemented behavior |
|---|---|---|
| `/` | `Features/Foundation/Home.razor` | Describes the synthetic diagnostic workflow and distinguishes it from dynamics and physical operations |
| `/execution-targets` | `Features/ExecutionTargets/SelectExecutionTarget/ExecutionTargetSelectionPage.razor` | Explicitly resolves registered provider metadata only; does not open a session |
| `/vehicle-profiles` | `Features/Vehicles/Profiles/VehicleProfilesPage.razor` | Explicit schema-v1 import, exact revision selection, metadata/provenance inspection and read-only export |
| `/diagnostics` | `Features/Vehicles/Diagnostics/DiagnosticsPage.razor` | Explicit saved profile/revision/provider/kind selection, static-v1 session lifecycle, separate expected/probed/identified counts, retained partial probe services, identity-gated DTC/static signal operations, clear acknowledgement plus fresh-empty-readback verification, raw/decoded trace, shared live dashboard and session recording/archive inspection |
| `/simulation` | `Features/Vehicles/Simulation/SimulationPage.razor` | Explicit profile/config/provider selection, JSON import/export, stopped-by-default dynamics session, lifecycle/step/pacing/scenario controls, source/unit/quality/model-time/config/run-aware telemetry over diagnostic protocol v2, and the same dashboard and recording/archive controls |
| `/telemetry-replay` | `Features/Vehicles/Telemetry/Replay/TelemetryReplayPage.razor` | Strict saved capture selection/load, distinct RecordedReplay instance and immutable original metadata, exact time/ordinal prefix navigation, one cancellable clock, partial acknowledgement and shared recorded numeric/bar gauges |
| `/calibration` | `Features/Vehicles/Calibration/CalibrationPage.razor` | Explicit configuration-derived synthetic baseline, immutable Proposed history, complete scalar/table validation, exact head/source tokens and diffs, pinned torque-unit drafts; no application or programming |
| `/runbooks` | `Features/Vehicles/Runbooks/RunbookPage.razor` | Manual schema-v1 input/template, explicit validation and immutable canonical preview/diff with current/Stale source status; no Save, approval, target/model/command access |
| Any unmatched route | `Features/Foundation/NotFoundPage.razor` via UI `Routes.razor` | Explicit not-found page and supported navigation |
The generic [StatusNotice](../src/AutoForge.Components/StatusNotice.razor)
provides accessible status/error feedback. The diagnostics page loads its
source-controlled synthetic profile example only after the user clicks its
import action; it does not select the new profile. Every operational action
requires an explicitly opened Simulation session. The page labels values as
static synthetic snapshots and exposes transport outcomes instead of treating
timeouts/no-responses as empty data.
Discovery preserves a validated positive probe independently from optional
profile-verified identity. Partial rows state the identity phase and reason;
advertised services alone never enable identity-dependent read/clear actions.
The shared live dashboard panel is UI composition over the Application
`ILiveDashboardFeed` for the page's actual `DiagnosticSession`; its reusable
numeric/bar renderer remains in Components and has no AutoForge dependency.
Bindings are offered only after identity-verified signal reads by that feed.
Definitions are in-memory (zero through eight gauges), use exact source units,
and are validated before replacing the current set. The shared display-unit
preference is persisted by the native Client through MAUI Preferences; portable
composition must supply an explicit store, and the UI-only unavailable store
reports failure rather than silently using memory. Conversions are a pure
presentation projection and never alter source snapshots, SI model state or
canonical gauge bounds. One feed polls once per
eligible module every cycle, independent of gauge visibility or render count.
The UI subscribes only for render notifications; hiding or disposing a panel
does not stop acquisition. The owning session and feature scope cancel and drain
the feed on close/replacement/disposal. See the [dashboard contract](live-dashboard.md)
for quality, range, sample-time and usage details.
The shared recording panel consumes the Application
`TelemetryRecordingWorkspace`, not the live dashboard feed or its bounded
200-entry UI trace. Diagnostics publishes immutable observations after each
validated trace commit; a capture subscribes to that actual operation stream
for one explicit session, preserving request/response bytes and attaching only
the successful `read.signals` result from the same operation. Start excludes
prior history; Stop detaches and drains already-dispatched callbacks. The
capture is memory-only until explicit Stop and Save, bounded at 4,096
observations, 16 MiB encoded observations, 1 MiB encoded header and 32 MiB
archive input/output. A rejected next observation freezes an explicitly
incomplete prefix. Close/reset stops capture but retains the old source context
for inspection/save. UI unmount does not own or stop capture.
Stopped, failed or discarded capture owners are removed from the diagnostic
session's lifetime-resource list; the workspace retains only the current
inspection/save data. An active capture is still drained on source close.
Close marks the session closed, snapshots registrations and publishes the
shared disposal task under the lifetime gate, then releases the gate before
cancellation or resource/control/transport disposal begins. Concurrent
disposers await that same completed task or failure; late registrations are
rejected after close ownership is established. This keeps observer draining
and capture unregistration outside the registration lock.
The Client persists only explicitly saved archives under its app-local
`recordings` directory. Application owns schema-v1 validation and file-storage
contracts; save writes and flushes a task-specific temporary file before
no-overwrite publication. Readback uses a new store instance and does not
rebind profiles or sessions. The format preserves capture elapsed time,
diagnostic logical ticks and model time as distinct values. This is local
archive persistence, not live disk streaming, crash durability or cryptographic
authenticity. V2 archive checks share the source validator for
signal IDs, units, JSON kinds and finite values; v1 retains its opaque value
contract. Missing first-use storage is an empty catalogue, while invalid roots,
listing failures and save failures remain visible. See the
[archive-v1 guide](telemetry-archive-v1.md).
The replay factory creates a fresh `TelemetryReplaySession` for each routed
page. Its only inputs are the existing archive store, monotonic `TimeProvider`
and cancellable wait seam; it cannot resolve profiles, open diagnostic sessions,
call models or save archives. Explicit strict load commits a new replay identity
only after validation, preserving the previous context on failure/cancellation.
The current kind is `RecordedReplay`; original provider/target/profile/session/
config/run and source completion remain unchanged archive metadata.
The page drains loading/playback on close or unmount. Gauges own only render
subscriptions. Playback uses capture elapsed ticks and a bounded prefix rebuild,
not UTC, diagnostic ticks or model time. Binding pre-indexing contains metadata,
never current values. Shared `DashboardGaugeProjection` enforces definitions,
unit/origin, quality, range and last-Good rules for both live and recorded data.
The existing panel shares its editor/conversions/generic renderer through
separate live-session or replay inputs; it creates no dummy live feed for replay.
See [replay contracts](telemetry-replay.md) for owner/drain and partial-data rules.
The feature-local target-selection view model adapts explicit input to the
existing Application resolver. The same target resolver is populated from the
diagnostic factories' descriptors, so `/execution-targets` shows the actual
provider metadata without implying connection. Static sessions bind the exact
profile revision, vehicle and target. Dynamics identity additionally binds the
versioned configuration fingerprint and a separate operational run/session
identifier. Closing releases per-run engine, control and transport state;
reset opens a new session using the exact configuration snapshot held by the
original session, not a newer catalog selection.
The Application session use case keeps low-level `clear.dtcs` acknowledgement
distinct from verified clear. It performs a fresh read and only marks the
operation verified when the valid returned DTC list is empty. Failed or
nonempty readback remains a visible failure/uncertainty; valid remaining codes
are retained in the UI.
## Application and capability boundaries
The accepted target-selection use case remains grouped under
`Application/Features/ExecutionTargets/SelectExecutionTarget/`. It snapshots
registrations, rejects duplicate IDs using ordinal case-insensitive comparison,
resolves only exact requested metadata and preserves typed no-fallback failures.
The vehicle profile slice remains under `Application/Features/Vehicles/Profiles/`.
Core owns immutable profile identity/revision, vehicle facts, arbitrary module
roles, capability states and provenance context. Application owns strict
schema-v1 JSON interchange and an in-memory catalog with exact
`(profileIdentifier, revision)` selection. Existing schema-v1 profile JSON is
unchanged.
`AutoForge.Diagnostics` defines provider-neutral endpoint, transport, session,
protocol-client, logical-clock, operation-result, dynamics-control and trace
contracts. Protocol v1 remains the static diagnostics wire path. Protocol v2 is
an explicit dynamic telemetry path with a separate run/configuration-bound
payload; neither path dispatches through the other provider. Simulation owns
the numerical engine and diagnostic transports. Application owns configuration
import/export/catalog and session coordination; UI consumes shared controls and
diagnostic results only. The profile/module IDs, endpoint addresses and
identities are validated against the exact selected profile. See the [v1
guide](synthetic-diagnostics-v1.md), [v2 guide](synthetic-diagnostics-v2.md)
and [simulation guide](simulation.md).
## Honest limitations and safety boundaries
The runbook slice receives only `CalibrationAuthoringService`, using its
read-only immutable snapshot and narrow current-head guard. Application owns
the strict bounded allowlisted parser, complete template validation and pure
exact diff. All syntax/source/value checks precede last-success publication
under the actual current-head guard. The preview service retains only one
successful immutable result and computes source freshness from the actual
current snapshot, without rebasing. Snapshot reading releases the preview gate
before reading the source gate; no inverse lock ordering is introduced.
The UI separately owns manual input/errors and last-successful preview labels,
and source/unit notifications only rerender. It never validates on render.
The slice has no diagnostic/rehearsal/transport/model/archive/network dependency
or Save/approval/Execute control. Optional generated text uses this same strict
boundary; the manual validator itself has no inference/retrieval dependency.
See [runbook schema/preview contracts](runbooks-v1.md).
The separate optional local-generation slice exposes `ILocalInferencePort`,
one exactly applicable synthetic knowledge provider and a page-owned
`LocalRunbookGenerationSession`. Client registers the fixed-loopback Ollama
transport with redirects/proxies/cookies/credentials disabled; portable UI
compositions use an explicit unavailable port. Entry/renders do not make requests.
Metadata selection and pre/post-chat eligibility verify exact name/digest,
positive local GGUF size/details and completion capability, rejecting cloud/
remote/ambiguous data. Operator acknowledgement is required but is not proof
of the actual server's cloud-disabled configuration.
One cancellable owner captures goal/model/source/head/knowledge/prior-preview,
with a 180-second deadline and bounded HTTP bodies. Original completed content
is not repaired. Generated preview admission reuses manual parsing/template/
diff logic and atomically checks captured source/head, cancellation and expected
prior-preview under the same guarded publication. Generation holds its owner
gate only across synchronous admission, never cleanup awaits. New manual previews
cannot be overwritten. Cancel/unmount drains only page requests, never shared
Ollama; source/authoring/rehearsal/recording/replay writes are unreachable.
See [local generation contracts](local-runbook-generation.md). Real generation
remains unverified until operator prerequisites are satisfied.
The authoring slice has only configuration/profile read dependencies. Core
owns defensively copied applicability, definition and value contracts for the
single synthetic engine template. Application's singleton
`CalibrationAuthoringService` retains one workspace, at most 32 saved revisions
including baseline. Explicit source resolution uses the configuration's actual
EngineModuleIdentifier, not a role lookup. Every immutable version includes
workspace/source identity and parent lineage. Complete validation and expected
head/source checks precede commit; identical head content is a no-op, stale
requests reject, and replacement requires confirmation plus the old expected
workspace/head. There is no workspace registry or persistence.
The routed editor owns copied, unit-pinned unsaved fields. Display preferences
rerender presentation only; unedited values preserve source doubles and edited
torque converts once before validation. History inspection never rebinds the
editable head. Diff results compare exact canonical values within one workspace/
applicability, in parameter/axis order. The authoring slice has no diagnostic,
model-control, archive-save, approval or programming port, and cannot apply its
values to a configuration or active source. See
[calibration authoring](calibration-authoring.md) for template bounds and limits.
The separate rehearsal factory creates one page-owned Application session.
Client registers `autoforge.simulation.calibration-rehearsal` as an explicit
`ISimulatedCalibrationTargetFactory`, not a diagnostic transport fallback.
Diagnostics defines typed Identity/Image/Commit/Acknowledgement ports;
Simulation seeds a separate stored logical image once from the exact source,
then owns actual reads and atomic revision CAS. It never changes a dynamics
engine, profile or configuration. Application/UI never reference its concrete
implementation or oracle.
Application validates two independent original target reads before publishing
a verified volatile supported-image backup. Immutable approval binds actual
before-image/revision, target instance/source, original backup and saved
authoring head/action. Source-head guard and target CAS precede mutation;
one owner serializes operations without holding a cleanup-required gate across
awaits. Full independent readback, not acknowledgement, determines verification.
Uncertain outcomes remain RecoveryRequired with explicit read-only
reconciliation or separately approved original Restore. Closed evidence cannot
authorize a fresh target. At most 32 dispatched Apply/Restore outcomes and only
bounded current preparation/command evidence are retained. See
[rehearsal contracts](calibration-rehearsal.md).
A newly admitted opening owner establishes its target lifetime under the
rehearsal state gate, before the synchronous factory may return. At that point
the prior lifetime's cached close completion is retired, including a prior
failed close. Competing Close/disposal publishes one new shared completion,
invalidates/cancels that actual owner and waits for its cleanup outside the
gate. A late factory target cannot publish into a closed/disposed lifetime and
is disposed by its opening owner exactly once. Closed state and its close
completion publish atomically after drainage; disposed page sessions reject
reuse, while ordinary Close permits a fresh explicit opening.
Implemented diagnostics and dynamics are synthetic, in-process and
Simulation-only. They prove encoded request/response handling and deterministic
model behavior, not vehicle compatibility, access, authenticity, real capture,
manufacturer accuracy or permission. Static v1 signals remain static. Protocol
v2 dynamic telemetry is computed from an explicitly configured simplified
model; it is not real sensor data or validated prediction. Virtual DTC clear
mutates only selected in-memory module/session state and has no physical write
path. Calibration authoring values remain synthetic proposals; rehearsal mutates
only its isolated logical Simulation image. No real vehicle,
physical adapter/programming, full-device or durable backup, applied dynamics calibration,
AI, live streaming, crash-durable capture or cloud
service is implemented. Saved recordings are local source-sensitive files and
must be treated as potentially sensitive data. A `SUPPORTED` declaration,
`VERIFIED` provenance label, physical
metadata kind or calibration reference does not implement or authorize an
operation.
The original [ADR-0001](adr-0001-headless-foundation.md) preserves valid
foundation decisions but marks its dual-shell/deferred-host decision
superseded. [ADR-0002](adr-0002-single-shell-vsa.md) is the current host and
feature-slice decision. [ADR-0004](adr-0004-synthetic-diagnostics.md) records
the Step-03 provider/protocol boundary. Worker completion remains distinct from
manual orchestrator acceptance.