From 997b17fd5ce99870b5800c6b46f543f081c5776f Mon Sep 17 00:00:00 2001 From: GAJ3T Date: Fri, 30 Oct 2026 22:25:58 -0400 Subject: [PATCH] After Step 9 --- README.md | 24 +- docs/README.md | 10 +- docs/architecture.md | 35 +- docs/build-and-test.md | 45 +- docs/calibration-authoring.md | 130 ++++ docs/telemetry-replay.md | 3 +- prompts/ROADMAP.md | 72 ++- prompts/STATE.md | 92 ++- prompts/Step-09-Report.md | 261 ++++++++ prompts/Step-10.md | 313 ++++++++++ .../CalibrationAuthoringService.cs | 229 +++++++ .../Calibration/SyntheticEngineCalibration.cs | 177 ++++++ .../Features/Foundation/AddAutoForgeUi.cs | 2 + .../Features/Foundation/Home.razor | 1 + .../Calibration/CalibrationPage.razor | 319 ++++++++++ src/AutoForge.UI/Layout/MainLayout.razor | 1 + .../CalibrationAuthoringCoexistenceTests.cs | 134 +++++ .../CalibrationAuthoringTests.cs | 561 ++++++++++++++++++ .../CalibrationAuthoringUiTests.cs | 227 +++++++ 19 files changed, 2584 insertions(+), 52 deletions(-) create mode 100644 docs/calibration-authoring.md create mode 100644 prompts/Step-09-Report.md create mode 100644 prompts/Step-10.md create mode 100644 src/AutoForge.Application/Features/Vehicles/Calibration/CalibrationAuthoringService.cs create mode 100644 src/AutoForge.Core/Calibration/SyntheticEngineCalibration.cs create mode 100644 src/AutoForge.UI/Features/Vehicles/Calibration/CalibrationPage.razor create mode 100644 src/tests/AutoForge.IntegrationTests/CalibrationAuthoringCoexistenceTests.cs create mode 100644 src/tests/AutoForge.IntegrationTests/CalibrationAuthoringTests.cs create mode 100644 src/tests/AutoForge.IntegrationTests/CalibrationAuthoringUiTests.cs diff --git a/README.md b/README.md index bc6eb6d..44a484e 100644 --- a/README.md +++ b/README.md @@ -84,7 +84,7 @@ report](prompts/Step-07-Report.md) and [Step-07A corrective worker report](prompts/Step-07A-Report.md) and [Step-07B lock-safety corrective report](prompts/Step-07B-Report.md). -### Implemented, pending manual review +### Accepted recorded replay milestone Step-08 adds `/telemetry-replay`: explicit saved-capture loading without a profile catalogue, vehicle session or running model. One page-owned, @@ -92,12 +92,24 @@ cancellable playback clock projects exact recorded observation prefixes into the shared numeric/bar gauge editor. Navigation, partial-source acknowledgement, recorded provenance and runtime speed are explicit; source archives are never rewritten. See [replay usage and contracts](docs/telemetry-replay.md) and the -[Step-08 worker report](prompts/Step-08-Report.md). Worker completion is not -orchestrator acceptance. +[Step-08 worker report](prompts/Step-08-Report.md). Step-08 was accepted on +2026-10-30. + +### Implemented, pending manual review + +Step-09 adds `/calibration`: one bounded, process-memory synthetic authoring +workspace derived explicitly from a saved immutable dynamics configuration. +Warm-idle scalar and fixed-axis torque proposals have exact source/head +preconditions, immutable linear revisions and structured canonical diffs. +These are Baseline/Proposed authoring values, not ECU backups, Tested/Approved +calibrations or applied model/device changes. See +[calibration authoring contracts](docs/calibration-authoring.md) and the +[Step-09 worker report](prompts/Step-09-Report.md). Step-09 remains pending +manual orchestrator review. ### Planned -Calibration values/editing/backups, AI and real hardware operations +Verified simulated programming, verified backups/approval, AI and real hardware operations require later approved assignments. Saved recordings are local file archives, not crash-durable live streaming. Replay does not resimulate or interpolate. Dynamics estimates are synthetic, @@ -117,7 +129,8 @@ browser-hosted WASM shell, Blazor Server host or second application executable. The application slices provide explicit target metadata resolution, vehicle-profile metadata import/list/select/export, dynamics configuration catalog/import/export, simulation-only diagnostic sessions, bounded session -recording, archive inspection and offline recorded replay, and a shared display-unit preference with a +recording, archive inspection, offline recorded replay, synthetic calibration +authoring and a shared display-unit preference with a native local-preference adapter. The Client composes separate static and dynamics synthetic providers through provider-neutral factory contracts and a session-lifetime in-memory profile/ @@ -231,6 +244,7 @@ acceptance remains the orchestrator's responsibility. - [Live dashboard usage and contracts](docs/live-dashboard.md) - [Telemetry archive schema v1 and recording](docs/telemetry-archive-v1.md) - [Recorded telemetry replay](docs/telemetry-replay.md) +- [Synthetic calibration authoring](docs/calibration-authoring.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) diff --git a/docs/README.md b/docs/README.md index df419fa..bd48f43 100644 --- a/docs/README.md +++ b/docs/README.md @@ -12,7 +12,9 @@ failures. Step-07B moves session cleanup outside the lifetime-registration gate and shares its completion/failure among competing disposers. Corrected Step-07/07A/07B is accepted. Step-08 adds offline saved telemetry replay, exact prefix navigation, one page-owned clock and the shared gauge editor. -Step-08 worker status remains pending manual orchestrator review. +Step-08 is accepted. Step-09 adds bounded synthetic scalar/table authoring with +immutable source-bound proposals and exact diffs, without model/device changes. +Step-09 worker status remains pending manual orchestrator review. - [Architecture](architecture.md): actual nine-project graph, responsibilities, route ownership and provider/reference boundaries. @@ -33,6 +35,9 @@ Step-08 worker status remains pending manual orchestrator review. - [Recorded telemetry replay](telemetry-replay.md): offline RecordedReplay provenance, before-first/time/ordinal semantics, exact quality and last-Good reduction, rates, cancellation/drain, partial acknowledgement and shared gauges. +- [Synthetic calibration authoring](calibration-authoring.md): exact + configuration/module applicability, scalar/fixed-axis template, validate-before- + commit revisions, head preconditions, canonical diffs and pinned torque drafts. - [ADR-0001: Headless .NET 10 foundation](adr-0001-headless-foundation.md): historical foundation decisions; dual-shell/deferred-host decision superseded. - [ADR-0002: Single native shell and feature slices](adr-0002-single-shell-vsa.md): @@ -66,5 +71,6 @@ historical/worker reports for their own execution evidence: [Step-07 worker report](../prompts/Step-07-Report.md) and [Step-07A corrective worker report](../prompts/Step-07A-Report.md) and [Step-07B lock-safety corrective worker report](../prompts/Step-07B-Report.md) and -[Step-08 worker report](../prompts/Step-08-Report.md). +[Step-08 worker report](../prompts/Step-08-Report.md) and +[Step-09 worker report](../prompts/Step-09-Report.md). Handoffs are manual; acceptance remains the orchestrator's responsibility. diff --git a/docs/architecture.md b/docs/architecture.md index 204c25f..1eecf3a 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -11,8 +11,9 @@ There is no web/server host, WASM host or backend process. 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. Step-08 worker status remains pending manual -orchestrator review; its execution evidence is separate from acceptance. +page-owned cancellable clock and is accepted. Step-09 adds source-bound, +process-memory synthetic calibration authoring. Step-09 worker status remains +pending manual orchestrator review; execution evidence is not acceptance. ```mermaid flowchart TD @@ -44,10 +45,10 @@ All nine projects are in [AutoForge.slnx](../src/AutoForge.slnx): | Project | Target and responsibility | Project references | |---|---|---| -| [Core](../src/AutoForge.Core/AutoForge.Core.csproj) | `net10.0`; platform-neutral target/profile invariants and immutable dynamics configuration/status contracts | None | +| [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`; provider/session/transport/control contracts, strict synthetic protocol v1/v2 client, typed results and bounded trace | Core | | [Simulation](../src/AutoForge.Simulation/AutoForge.Simulation.csproj) | `net10.0`; validated static modules, fixed-step engine, isolated state, explicit provider factories and transports | Core, Diagnostics | -| [Application](../src/AutoForge.Application/AutoForge.Application.csproj) | `net10.0`; target/profile/diagnostic-session, dynamics-configuration, display-unit, shared gauge projection, live-dashboard, telemetry-recording/archive and replay feature slices | Core, Diagnostics | +| [Application](../src/AutoForge.Application/AutoForge.Application.csproj) | `net10.0`; target/profile/diagnostic-session, dynamics-configuration, display-unit, shared gauge projection, live-dashboard, telemetry-recording/archive, replay and calibration-authoring feature slices | 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 | @@ -89,6 +90,7 @@ assembly, not the native Client assembly. | `/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 | | 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) @@ -214,6 +216,26 @@ and [simulation guide](simulation.md). ## Honest limitations and safety boundaries +The calibration 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. + 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, @@ -221,8 +243,9 @@ manufacturer accuracy or permission. Static v1 signals remain static. Protocol v2 dynamic telemetry is computed from an explicitly configured simplified model; it is not real sensor data or validated prediction. Virtual DTC clear mutates only selected in-memory module/session state and has no physical write -path. No real vehicle, physical adapter, programming, -calibration values, backups, AI, live streaming, crash-durable capture or cloud +path. Calibration authoring values are synthetic proposals only. No real vehicle, +physical adapter, programming, verified backup/approval, applied 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 diff --git a/docs/build-and-test.md b/docs/build-and-test.md index 71296a3..9b24342 100644 --- a/docs/build-and-test.md +++ b/docs/build-and-test.md @@ -42,12 +42,53 @@ actual vehicle, database, backend, model or cloud account is required. dotnet test .\src\tests\AutoForge.UnitTests\AutoForge.UnitTests.csproj --configuration Release dotnet test .\src\tests\AutoForge.IntegrationTests\AutoForge.IntegrationTests.csproj --configuration Release dotnet test .\src\tests\AutoForge.IntegrationTests\AutoForge.IntegrationTests.csproj --configuration Release --no-restore --filter "FullyQualifiedName~TelemetryReplayTests|FullyQualifiedName~LiveDashboardAcquisitionTests|FullyQualifiedName~DisplayUnitControlTests" +dotnet test .\src\tests\AutoForge.IntegrationTests\AutoForge.IntegrationTests.csproj --configuration Release --no-restore --filter "FullyQualifiedName~CalibrationAuthoringTests" ``` +## Step-09 synthetic authoring verification + +Step-08 is accepted. Step-09 remains pending manual orchestrator review. +The focused authoring command above passed **55 cases**, including real +configuration/profile source resolution, exact 650->1250 rpm and +360->350 N*m diffs/parents, changed-back/no-op/tiny changes, defensive copies, +template/source rejection, controlled competing-head commits and the exact +32/33 history boundary. Real rendered events verify parse/validation failures, +history/diff selection, two stale editors, explicit replacement and pinned +torque units with exact canonical preservation. + +The required sequential Release build completed all nine projects/native +Client with zero warnings/errors, then the complete suite passed **179 unit + +226 integration = 405 cases**, zero failed/skipped. All 350 accepted baseline +cases remain present. A real live dynamics source, its saved recording and +validated replay coexist during authoring with zero additional transport, +model-control and archive Save calls, unchanged source export/fingerprint/ +trace/state/raw bytes and unchanged replay snapshot. + +Native smoke used the actual Release Windows Client and a task-owned WebView2 +profile/local DevTools endpoint. The existing simulation workflow explicitly +created the warm source. Native authoring created its baseline, saved the +1250-rpm scalar proposal and 350-N*m torque cell at 2000 rpm, then inspected +exact baseline and preceding-version diffs. Invalid scalar/cell/source commands +and unconfirmed replacement preserved the head/history. A Metric draft's +unsaved 345 N*m remained 345 after an Imperial toggle; cancelling captured a +new Imperial draft, and an untouched save across another toggle retained +exact source 350 N*m and the same revision. Confirmed replacement explicitly +discarded the old draft/history and returned to baseline. + +The original dynamics configuration export/fingerprint stayed identical with +warm idle 650 rpm and 2000-rpm torque 360 N*m. An explicit subsequent real +diagnostic read at model step 7 / 0.7 seconds returned 631.80416 rpm from the +unchanged warm model, not the proposal. Old simulation/profile/replay routes +and authoring re-entry worked. Restart confirmed no authoring workspace or +configuration persisted; the final binary then repeated the baseline and +two-proposal diff workflow. Native observations are not controlled concurrent/ +stale-head/capacity proof. Exact commands, final results, cleanup and limitations +are in the [Step-09 worker report](../prompts/Step-09-Report.md). + ## Step-08 recorded replay verification -Corrected Step-07/07A/07B is accepted; the Step-08 worker remains pending -orchestrator review. The final focused command above passed 49 cases. It covers +Corrected Step-07/07A/07B and Step-08 are accepted. The recorded Step-08 focused +command passed 49 cases. It covers 37 new replay cases plus accepted live-dashboard/unit-selector regressions. The required sequential nine-project Release build passed with zero warnings and errors, followed by 179 unit and 171 integration tests: **350 passed, diff --git a/docs/calibration-authoring.md b/docs/calibration-authoring.md new file mode 100644 index 0000000..e365bc7 --- /dev/null +++ b/docs/calibration-authoring.md @@ -0,0 +1,130 @@ +# Synthetic calibration authoring + +## Authoring only, not programming + +The `/calibration` route creates **Synthetic configuration-derived baseline** +and **Proposed** revisions in process memory. It does not read an ECU, make a +verified original backup, test or approve a proposal, write to a module, apply +values to a model or change the source configuration. Restart loses all +authoring history; leaving the route loses its unsaved editor draft. Saved +authoring revisions survive route navigation only within the running app. +Step-08 is accepted; Step-09 remains pending manual orchestrator review. +Step-10 verified simulated programming is separate and unimplemented. Physical +writes retain their later independent authorization/evidence gates. + +## Explicit source and bounded synthetic definition + +First create/import a dynamics configuration through the existing explicit +simulation workflow. No configuration, profile or workspace is seeded by +opening authoring. Select an exact saved configuration fingerprint and choose +**Create synthetic authoring baseline**. + +The versioned `autoforge.synthetic.engine-authoring` revision 1 template +supports `autoforge.synthetic.longitudinal` model version 1. Applicability +includes exact configuration fingerprint, profile identifier/revision, +the configuration's actual EngineModuleIdentifier, model identifier/version +and definition identifier/revision. The actual module is resolved through the +selected profile; it is never inferred from a role. Profile/module comparison +is case-insensitive per existing policy; fingerprints, model/definition IDs, +logical keys and units are exact. Supplied optional hardware/software/firmware/ +calibration metadata is retained as metadata, not filled or promoted into proof. + +| Logical value | Source units | Synthetic policy | +|---|---|---| +| `engine.warm-idle-target` | rpm | Finite scalar, inclusive `[Model.IdleSpeedRpm, Model.MaximumEngineSpeedRpm]` | +| `engine.torque-curve` | rpm axis; N*m cells | 2..32 fixed source rows; finite strictly increasing axis in `[0, MaximumEngineSpeedRpm]`; editable finite cells in inclusive `[1,1000]` N*m | + +Only identity value scaling (1, offset 0) is supported. No raw binary layout, +addresses/offsets, adjustable axis, insertion/deletion, sorting, interpolation, +multidimensional maps or arbitrary firmware definition is provided. An otherwise +valid configuration outside this template is rejected, not truncated, clipped +or normalized. These are synthetic authoring constraints, not manufacturer- +safe operating limits or physical compatibility evidence. + +For the warm example, baseline warm idle is 650 rpm with limits 650..5000 rpm. +The source torque rows are exactly `(650,240)`, `(1000,300)`, `(2000,360)`, +`(3200,350)`, `(4200,300)`, `(5000,180)` in rpm/N*m. + +## Immutable linear versions and exact preconditions + +The Application service retains **one** authoring workspace with at most +**32 saved revisions including baseline**. Baseline is revision 1, read-only. +Every valid changed save creates a unique Proposed revision with a monotonic +revision number, exact parent/current-head ID and copied workspace/source +identity. All definition, axis, value, history and diff collections are +defensively copied/read-only. + +A save explicitly supplies the workspace ID, expected head ID, complete +applicability and complete candidate. Required keys, shape/count, unchanged +axis, source units, finite values and inclusive bounds are validated as a whole +before any head/history/version mutation. Invalid or mismatched requests return +typed visible errors with no partial save. Two requests based on the same head +cannot both commit changed proposals: the second is stale, with no merge, +branch or last-writer-wins fallback. + +Content equal to the current head returns that same revision without consuming +capacity. Stale expected heads reject even if their proposed content is +unchanged. At 32 revisions, changed revision 33 rejects; an identical current- +head save remains a no-op. Changing back after a different proposal creates a +new Proposed revision, not a restored device or approved rollback. + +Selecting a different configuration does not silently replace the workspace. +Replacement requires the explicit **I confirm replacement discards the current +in-memory history and unsaved draft** checkbox and replacement action, together +with the prior expected workspace/head. Invalid/stale replacement preserves the +old workspace/draft/history. A new workspace discards service-held old history; +there is no hidden unbounded multi-workspace repository or persistence. + +## Editor, units and history + +The editor captures its expected source/head and copied input strings. Another +editor's save rerenders a stale-head warning but does not silently rebase unsaved +fields. **Cancel draft / reload latest head** is the explicit recovery action. +Inspection of a saved revision does not change the editable head. + +Torque presentation uses the existing shared N*m/lbf*ft converter. rpm remains +rpm. A draft pins its input unit selection until save/cancel; global preference +changes affect read-only presentation, not the meaning of unsaved fields or +saved canonical values. Inputs use round-trip numeric text; display precision +is presentation only. Unedited fields retain their exact original canonical +doubles, avoiding forward/inverse conversion drift. Edited torque converts +once to N*m before complete candidate validation. Canonical source values, +fixed axis and synthetic bounds remain visible. + +Example: typing a torque edit while Metric is active and switching globally +to Imperial leaves that draft in N*m. Cancelling captures a new Imperial +draft in lbf*ft. An untouched subsequent save preserves exact source values +and does not create a proposal merely because displayed units changed. + +## Structured canonical diffs + +Select two explicit saved versions from the same workspace/applicability and +choose **Compare explicit saved revisions**. Output includes only changed +scalars/cells, deterministic ordinal logical-key then numeric axis order, +logical ID, table axis coordinate/unit, original source unit, exact before/ +after doubles and signed delta. No rounded-display comparison or tolerance +hides small changes. Comparisons against foreign/replaced version IDs reject. + +Warm idle 650 -> 1250 produces one scalar entry: before 650, after 1250, +delta +600 rpm. Also changing the 2000-rpm torque cell 360 -> 350 produces +exactly two entries versus baseline, with table delta -10 N*m. Comparing that +third revision against its second-revision parent shows only the table change. +A changed-back Proposed revision may have an empty baseline diff without +changing its authoring-only status. + +## Verification and isolation + +`CalibrationAuthoringTests` constructs real profile/configuration-service +sources and asserts baseline values, exact parents/diffs, malformed values/ +definitions/source tokens, immutable snapshots, deterministic competing-head +commits and the exact history bound. Actual rendered editor events cover +parse/validation failures, history/diff choice, stale editors, replacement and +unit-pinned drafts. A real live dynamics source, saved recording and validated +replay coexist while authoring adds zero transport/model/archive-Save calls, +with unchanged configuration export/fingerprint, raw archive bytes, source +trace/state and replay snapshot. + +Native smoke uses the actual Windows Client and explicitly created warm source; +it is not controlled concurrent/head-capacity proof. Commands, counts, native +observations, limitations and preservation review are in the +[Step-09 worker report](../prompts/Step-09-Report.md). diff --git a/docs/telemetry-replay.md b/docs/telemetry-replay.md index f569956..ab6d4a4 100644 --- a/docs/telemetry-replay.md +++ b/docs/telemetry-replay.md @@ -135,4 +135,5 @@ Native evidence uses the real Windows Client, app storage and saved static-v1/ dynamic-v2 captures; it is not controlled timing, race or fault proof. Commands, counts, native observations and limitations are recorded separately in the [Step-08 worker report](../prompts/Step-08-Report.md). -Step-07/07A/07B is accepted; Step-08 remains pending orchestrator review. +Step-07/07A/07B and Step-08 are accepted. Synthetic calibration authoring is a +separate feature and cannot change replay archives, cursor or playback ownership. diff --git a/prompts/ROADMAP.md b/prompts/ROADMAP.md index 3f7ed17..93183cb 100644 --- a/prompts/ROADMAP.md +++ b/prompts/ROADMAP.md @@ -3,17 +3,18 @@ ## Status and authority - Initialized: 2026-10-28. -- Current phase: recorded telemetry replay accepted; bounded synthetic calibration authoring next. -- Active assignment: [Step-09](Step-09.md), ready for manual worker execution. -- Last accepted milestone: Step-08, accepted 2026-10-30. +- Current phase: synthetic calibration authoring accepted; isolated simulated programming rehearsal next. +- Active assignment: [Step-10](Step-10.md), ready for manual worker execution. +- Last accepted milestone: Step-09, accepted 2026-10-30. - Last accepted correction: Step-07B; all Step-07 findings closed. - Outstanding corrections: none. - Step-05 status: ACCEPTED after Step-05A/Step-05B, 2026-10-29. - Step-06 status: ACCEPTED after Step-06A, 2026-10-30. - Step-07 status: ACCEPTED after Step-07A/Step-07B, 2026-10-30. - Step-08 status: ACCEPTED 2026-10-30; no Step-08A required. -- Step-09 status: READY FOR WORKER; synthetic definitions/proposals/diffs only. -- Step-10 status: verified simulated programming; BLOCKED / NOT ASSIGNED until authoring acceptance. +- Step-09 status: ACCEPTED 2026-10-30; no Step-09A required. +- Step-10 status: READY FOR WORKER; verified supported-image backup/approval/write/readback/restore in an isolated simulation target. +- Step-11 status: local AI/runbooks; BLOCKED / NOT ASSIGNED until programming-rehearsal acceptance. - 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 @@ -213,6 +214,27 @@ state machine, programming service or model integration. A configuration-derived synthetic baseline is not an ECU read or verified backup. Those distinctions are frozen in Step-09's UI/validation/evidence contract, not postponed by implication. +### Step-10 bounded rehearsal contract + +Accepted Step-09 proposals now feed an explicitly opened, isolated simulated +calibration target through a typed programming port. The target's mutable image +is owned by Simulation, not an Application request echo or a configuration +replacement. The supported surface remains the warm-idle scalar and fixed-axis +torque table. Current readback verifies that surface only, not an entire ECU. + +Step-10 adds one guarded mutation lifecycle: independent image read/verified +in-memory backup, exact source/proposal approval, compare-before-write, fresh +readback, visible uncertain outcomes, explicit reconciliation and separately +approved restore. PhysicalHardware and RecordedReplay targets reject. +This is not a general transport/firmware programming implementation. + +The target/backup/results are process-memory rehearsal state. Closing/reopening +creates a new target identity and cannot reuse the old approval/backup. Original +immutable dynamics configurations, existing runs, diagnostics and recording/ +replay stay unchanged. Applying the programmed image to a new dynamics run and +functional performance verification require a later explicit assignment. +No crash-durable backup, real-device recovery or manufacturer safety claim is made. + ## Architecture baseline ### Existing accepted foundation, preserved @@ -403,8 +425,10 @@ accepted: actual bounded capture, source-faithful/strict archives, released ownership, visible I/O failures and deadlock-free source close are supported. Step-08 replay is accepted: exact prefixes/ties, one playback owner, offline RecordedReplay context, source immutability and shared gauges/units are supported. -Step-09 is the only active assignment for bounded synthetic calibration -authoring; simulated programming is separated into Step-10. +Step-09 authoring is accepted: exact source binding, immutable linear proposals, +atomic validation/head checks, precise diffs and zero source side effects are +supported. Step-10 is the only active assignment for isolated simulated +programming rehearsal; there is no physical-write or live-model permission. 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. @@ -430,9 +454,9 @@ evidence; they must not silently discard required capabilities. | 07A | Source-faithful archives, bounded lifetime and visible storage failures | 07 review R-01 through R-04 | ACCEPTED 2026-10-30 AFTER 07B | Archive/typed-validation/normal-release/panel fixes and source-close follow-up all closed | | 07B | Deadlock-free source disposal during capture cleanup | Remaining 07A R-03 safe-close contract | ACCEPTED 2026-10-30 | Shared disposal task published under gate, cleanup outside; actual pre-fix close/reset deadlocks and controlled correction, reported 179 unit/134 integration passes and native baseline | | 08 | Recorded telemetry replay | 07 and corrections accepted | ACCEPTED 2026-10-30 | Exact recorded prefix/tie/navigation, controlled rate/owner/fault cleanup, shared gauges/units and offline native replay; reported 179 unit/171 integration passes | -| 09 | Synthetic calibration authoring and immutable proposals | 08 accepted | READY FOR WORKER | Explicit configuration/module applicability, validated scalar/fixed-axis table revisions, exact diffs and no source/model mutation; in-memory only | -| 10 | Verified simulated programming and recovery | 09 accepted | BLOCKED / NOT ASSIGNED | Verified baseline/backup, exact approval binding, simulated write/readback/unrelated-value checks, audit and supported restore; no physical writes | -| 11 | Local AI, knowledge, and validated runbooks | 10 | PLANNED | Replaceable local inference, applicable knowledge retrieval, structured logical runbook, independent validation/approval and simulation-only execution | +| 09 | Synthetic calibration authoring and immutable proposals | 08 accepted | ACCEPTED 2026-10-30 | Real configuration/profile binding, immutable scalar/table proposals, exact diffs/stale-head/limits and no source mutation; reported 179 unit/226 integration passes | +| 10 | Verified simulated programming and recovery | 09 accepted | READY FOR WORKER | Isolated real simulation image/typed port, supported-image volatile backup, exact approval/source revision, fresh readback/reconciliation/approved restore; no physical writes or live-model changes | +| 11 | Local AI, knowledge, and validated runbooks | 10 accepted | BLOCKED / NOT ASSIGNED | Replaceable local inference, applicable knowledge retrieval, structured logical runbook, independent validation/approval and simulation-only execution | | 12 | Comparative evaluation and complete synthetic demonstration | 11 | PLANNED | Complete demonstration below plus deterministic fault/regression matrix and independent verification of intended and unintended changes | | 13 | Verified OBDX Pro GT read-only integration | 12 plus documented device research/access | PLANNED / HARDWARE GATE | Source-backed device support matrix, explicit physical target, real read-only identification/diagnostics/telemetry recording where supported; no write path | | 14 | Advanced dashboards, analysis, and comparisons | 12; 13 for real captures | PLANNED | Persist configurable layouts/thresholds, linked charts, larger-capture analysis, raw-data inspection and multi-run/multi-vehicle comparisons with lineage/uncertainty | @@ -870,27 +894,43 @@ history, not repeated redesign without evidence. subsequent Step-10 simulated programming under the existing scope policy. Only unassigned future envelopes/dependencies shifted; no completed history or prior assignment/report was renumbered. +- Reviewed Step-09's immutable Core contracts, source-bound authoring service, + complete candidate/head/capacity validation, exact structured diffs, pinned + editor/history/replacement and all new tests/docs. Worker reports 179 unit + + 226 integration passes (405 total, zero failed/skipped), clean full Release + build and native exact proposal/diff/source-isolation/restart checks. +- Accepted Step-09 against C-01..C-12/AC-01..AC-05 without Step-09A. Real + concurrent/defensive-copy/source/no-write tests are distinct from native UI + observations; the orchestrator ran no application checks. +- Prepared [Step-10](Step-10.md) for the bounded isolated-target programming + rehearsal, with explicit volatile backup/approval/readback/unknown/restore + semantics and no existing source/model/physical mutation. No renumbering + is needed in this handoff. ### Remaining -- Worker execution of Step-09, then one consolidated review against its frozen - authoring/applicability/version/diff/UI matrix and shared quality gate. - Correct genuine unmet requirements as Step-09A before simulated programming. -- Step-10 programming is blocked and not assigned. Calibration authoring is - assigned work, not implemented functionality; replay and earlier work are accepted. +- Worker execution of Step-10, then one consolidated review against its frozen + target/backup/approval/mutation/readback/recovery matrix and shared quality gate. + Correct genuine unmet requirements as Step-10A before local-AI work. +- Step-11 AI is blocked and not assigned. Programming rehearsal is assigned + work, not implemented functionality; authoring/replay and earlier work are accepted. - Profile/module metadata, synthetic virtual-module communication and deterministic dynamics/v2 and corrected dashboard are accepted; later features remain planned. Preserve the complete sequence/safety gates. ### Known blockers and uncertainties +No blocking Step-09 deficiency was identified against its frozen contract. +Its authoring-only baseline is not a verified target backup or permission to +program anything. Step-10 must establish those separate rehearsal contracts. + No blocking Step-08 deficiency was identified against its frozen contract. The worker disclosed an existing recording-panel initialization race when a Save-followup refresh is still pending during host navigation. That unchanged recording flow is outside Step-08; no replay check is claimed to cover/fix it. Native preparation was restarted and final-binary replay passed without the error overlay. Retain the issue for a separately scoped recording follow-up, -not a retrospective replay criterion or automatic Step-09 cleanup. +not a retrospective replay/authoring criterion or automatic Step-10 cleanup. No blocking Step-07 deficiency remains. Its source-close follow-up below is historical and closed by accepted Step-07B: diff --git a/prompts/STATE.md b/prompts/STATE.md index 952351a..574ee8d 100644 --- a/prompts/STATE.md +++ b/prompts/STATE.md @@ -5,13 +5,13 @@ | Field | Value | |---|---| | Updated | 2026-10-30 | -| Phase | Recorded replay accepted; bounded synthetic calibration authoring next | -| Active step | Step-09 - Synthetic calibration authoring and immutable proposals | -| Assignment | [Step-09.md](Step-09.md) | +| Phase | Synthetic authoring accepted; isolated simulated programming rehearsal next | +| Active step | Step-10 - Verified simulated programming and recovery | +| Assignment | [Step-10.md](Step-10.md) | | Assignment status | READY FOR WORKER / AWAITING MANUAL HANDOFF | -| Expected worker report | `prompts/Step-09-Report.md` - not yet created | +| Expected worker report | `prompts/Step-10-Report.md` - not yet created | | Last accepted correction | Step-07B - accepted 2026-10-30 | -| Last accepted major milestone | Step-08 - accepted 2026-10-30 | +| Last accepted major milestone | Step-09 - accepted 2026-10-30 | | Outstanding corrections | None | | Step-02 status | ACCEPTED after Step-02A | | Step-03 status | ACCEPTED after Step-03A/Step-03B | @@ -23,10 +23,11 @@ | Step-07 status | ACCEPTED after Step-07A/Step-07B | | Step-07A review | All original corrective criteria closed with Step-07B | | Step-08 status | ACCEPTED 2026-10-30; no correction required | -| Step-09 status | READY FOR WORKER; synthetic definitions/proposals/diffs only | -| Step-10 status | Verified simulated programming; BLOCKED until authoring acceptance | -| Worker execution | Step-08 returned and accepted; Step-09 not invoked | -| Immediate next action | User manually directs the worker to execute Step-09 and shared quality gate only | +| Step-09 status | ACCEPTED 2026-10-30; no correction required | +| Step-10 status | READY FOR WORKER; isolated simulation image and volatile verified-backup/approval/write/readback/restore | +| Step-11 status | Local AI/runbooks; BLOCKED until Step-10 acceptance | +| Worker execution | Step-09 returned and accepted; Step-10 not invoked | +| Immediate next action | User manually directs the worker to execute Step-10 and shared quality gate only | | Next orchestrator action | After manual return, inspect the assignment, report, implementation, tests, Git changes, documentation and recorded command evidence | ## Repository baseline at initialization @@ -1071,6 +1072,55 @@ ECU read or verified backup. Proposal validation grants no Tested/Approved/ Applied status, simulation mutation or hardware authority. No calibration disk format/storage or programming service is assigned in this slice. +## Step-09 acceptance + +Decision: **ACCEPTED**, 2026-10-30. Frozen C-01..C-12 and AC-01..AC-05 are +satisfied on reviewed source and worker evidence. No Step-09A is required. + +Reviewed [Step-09](Step-09.md), its [report](Step-09-Report.md), the complete +Core applicability/definition/value contracts and Application baseline/head/ +validation/version/diff flow, routed copied/pinned editor, all three new test +partials, docs/README, unchanged references and existing Release outputs. + +| Criterion | Decision | Evidence | +|---|---|---| +| AC-01 | ACCEPTED | Real exact configuration/profile/module selection, model/definition identity, full scalar/table/axis/unit/bounds validation, unsupported-template and cross-source atomic rejections | +| AC-02 | ACCEPTED | Exact 650->1250/+600 and 360->350/-10 diffs, immutable parents/source/snapshots, no-op/changed-back/tiny-difference behavior, one-winner controlled stale-head commits and 32/33 capacity | +| AC-03 | ACCEPTED | Actual editor/history/diff/replacement events, parse errors/stale-editor preservation, pinned torque input units and exact unedited canonical values; authoring-only status | +| AC-04 | ACCEPTED ON WORKER EXECUTION EVIDENCE | Reported complete nine-project Release build zero warnings/errors; 179 unit + 226 integration passes (405 total, zero failed/skipped), real live/recording/replay zero-call preservation and native final-binary authoring | +| AC-05 | ACCEPTED | Executable matrix, post-green boundary/identity/defensive-copy/diff self-review additions, accurate docs and protected/history/manual workflow preserved | + +The 55 added integration cases preserve all 350 prior cases. Native checks +include exact scalar/table proposals and version-pair diffs, invalid/stale-source +edits, pinned unit drafts, unchanged original configuration/live diagnostics, +explicit replacement and an empty authoring state after process restart. +They do not claim a tested/applied proposal, verified backup or ECU read. + +The orchestrator ran no application build/test/native/workload command. +Case inventory, graph and existing outputs corroborate worker execution, not +independent runtime verification. SDK patch 10.0.403 remains within the existing +roll-forward policy; no dependency/system change was reported. + +## Step-10 rehearsal handoff + +[Step-10](Step-10.md) supplies one explicit, isolated simulation target whose +mutable supported image is owned by Simulation through a typed Diagnostics port. +It is initialized from the selected immutable configuration but thereafter read/ +written independently; neither the authoring service nor a request echo is readback. + +Only the supported warm-idle scalar and fixed-axis torque table are covered. +Prepare a verified process-memory supported-image backup, approve an exact +immutable proposal/source revision, compare again before dispatch, read back +fresh target state and verify every changed/unchanged value. Unknown outcomes +require explicit reconciliation; restoring the original backup requires a +separate approval bound to that same target instance and current revision. + +Closing/reopening destroys/recreates the rehearsal target; old approvals/backups +cannot act on a new instance. No physical/replay target, running-dynamics mutation, +new wire/firmware format or crash-durable/device-backup claim is assigned. +Connecting the programmed image to a fresh dynamics run and functional evaluation +is later explicit work, not an implied Step-10 feature. Step-11 remains blocked. + ## Prerequisites, limitations, and known issues - Step-01A worker evidence establishes portable and native Windows compatibility @@ -1097,24 +1147,24 @@ format/storage or programming service is assigned in this slice. Step-04B. Step-05's original and follow-up findings are closed. Preserve the 190-/ 202-/207-case reports and original numerical/native evidence distinctly. - Profile metadata/UI, synthetic diagnostics, deterministic dynamics/v2 and the - corrected dashboard/display units/recording archive/replay are accepted. - Calibration authoring/programming, AI and physical hardware operations + corrected dashboard/display units/recording archive/replay/authoring are accepted. + Simulated programming, AI and physical hardware operations remain unimplemented. - No application build or test has been executed by the orchestrator. ## Review and progression gate -On manual return, evaluate Step-09 and its frozen authoring contract/shared gate using the +On manual return, evaluate Step-10 and its frozen programming-rehearsal contract/shared gate using the 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 exact source/definition applicability, immutable baseline/proposal - history, atomic validation/head checks, precise scalar/table diffs and unchanged - model/source behavior. Do not add deferred programming/storage/approval scope. -- If accepted: accept Step-09, update roadmap/state, prepare a bounded Step-10 simulated-programming assignment +- Inspect actual isolated target state, backup/approval/source binding, rejected/ + uncertain mutation and fresh readback/restore, one operation owner and zero + existing-model/source effects. Do not add deferred physics/durable/physical scope. +- If accepted: accept Step-10, update roadmap/state, prepare a bounded Step-11 local-AI/runbook assignment and stop for manual handoff. -- If deficient: issue narrowly scoped Step-09A only for a material unmet contract/ +- If deficient: issue narrowly scoped Step-10A only for a material unmet contract/ regression, then stop. Planned new features are not corrections. - If blocked: retain the active step, document the prerequisite and required worker evidence; do not advance or mark unexecuted checks as successful. @@ -1189,12 +1239,14 @@ claim; do not claim independent runtime verification. | 2026-10-30 | Step-08 returned and ACCEPTED | Frozen replay contract satisfied; reported 350-case/clean Release/offline native evidence, exact prefixes/time/owner/source/units and self-review inspected; no 08A | | 2026-10-30 | Calibration envelope split prospectively | Step-09 authoring/versioning/diffs, Step-10 simulated programming; former unassigned 10-22 become 11-23; completed history preserved | | 2026-10-30 | Step-09 prepared | Configuration-derived synthetic baseline, immutable scalar/table proposals and exact diffs; no model mutation, approval/backup/programming or physical writes | +| 2026-10-30 | Step-09 returned and ACCEPTED | Frozen authoring contract satisfied; reported 405-case/clean Release/native evidence, exact source/head/versions/diffs/limits/no-write and self-review inspected; no 09A | +| 2026-10-30 | Step-10 prepared | Isolated typed simulation target, verified volatile supported-image backup, approval/CAS/write/fresh readback/reconciliation/restore; no existing-model or physical writes, no renumbering | ## Manual handoff instruction -Provide [Step-09.md](Step-09.md) and the shared +Provide [Step-10.md](Step-10.md) and the shared [worker gate](WORKER-QUALITY-GATE.md) to the separate worker and request execution -of that assignment only. The worker must produce `prompts/Step-09-Report.md` -and stop for review. Do not begin Step-10 simulated programming. +of that assignment only. The worker must produce `prompts/Step-10-Report.md` +and stop for review. Do not begin Step-11 local AI/runbooks. Return manually to the orchestrator for review. Reports, including final chat reports, must follow the single plain triple-backtick copy-window requirement. diff --git a/prompts/Step-09-Report.md b/prompts/Step-09-Report.md new file mode 100644 index 0000000..dff5e91 --- /dev/null +++ b/prompts/Step-09-Report.md @@ -0,0 +1,261 @@ +``` +# Step-09 - Synthetic calibration authoring and immutable proposals + +## Status + +COMPLETE. The bounded authoring implementation, all frozen contracts, +post-green self-review, focused tests, nine-project Release build, complete +regressions and required native authoring smoke passed. + +Step-09 remains pending manual orchestrator review; this report does not grant +acceptance. Accepted Step-08 and the existing 350-case baseline are preserved. +Step-10 programming was not started. No agents, automatic handoff, staging, +commit or push occurred. + +## Functions, files and interfaces + +- [SyntheticEngineCalibration.cs](../src/AutoForge.Core/Calibration/SyntheticEngineCalibration.cs): + small immutable applicability, scalar/fixed-axis definition and value + contracts, typed CalibrationAuthoringException/CalibrationFailure, defensive + collection copying and complete supported-template/candidate validation. + Identity scaling is exactly 1/offset 0; no firmware encoding is supplied. +- [CalibrationAuthoringService.cs](../src/AutoForge.Application/Features/Vehicles/Calibration/CalibrationAuthoringService.cs): + CreateBaseline, ReplaceBaseline, Save, Compare and immutable Snapshot. + The service reads only the existing IDynamicsConfigurationService and + IVehicleProfileService. Registration retains one singleton workspace with + at most 32 saved revisions. Each immutable version carries its own + workspace/source identity, revision, kind, exact parent and copied values. + Diffs carry explicit source/version identities and exact changed entries. + No live/model/archive-save/approval/programming port exists in this slice. +- [CalibrationPage.razor](../src/AutoForge.UI/Features/Vehicles/Calibration/CalibrationPage.razor): + /calibration, exact configuration selection, explicit baseline/replacement, + copied expected-head draft, scalar/fixed-axis table editor, pinned torque + units, read-only version inspection, exact version-pair diffs and visible + parse/validation/stale-source/head errors. +- [AddAutoForgeUi.cs](../src/AutoForge.UI/Features/Foundation/AddAutoForgeUi.cs), + [MainLayout.razor](../src/AutoForge.UI/Layout/MainLayout.razor) and + [Home.razor](../src/AutoForge.UI/Features/Foundation/Home.razor): + minimal service composition and shared navigation. + +New executable evidence is the CalibrationAuthoringTests partial class in: + +- [CalibrationAuthoringTests.cs](../src/tests/AutoForge.IntegrationTests/CalibrationAuthoringTests.cs) +- [CalibrationAuthoringUiTests.cs](../src/tests/AutoForge.IntegrationTests/CalibrationAuthoringUiTests.cs) +- [CalibrationAuthoringCoexistenceTests.cs](../src/tests/AutoForge.IntegrationTests/CalibrationAuthoringCoexistenceTests.cs) + +The initial C-01..C-12 source/value/head/limit/defensive-copy/rendered/isolation +contracts were written before production implementation. Post-green review +added exact row boundaries, full profile-revision replacement, case-sensitive +source-token vectors, multi-cell/reverse diffs and malformed table metadata. + +## Frozen C-01..C-12 contract matrix + +All rows below are PASSED. Named methods were executed, not proposed. + +| ID | Named evidence and exact result | +|---|---| +| C-01 | ExplicitBaseline_UsesExactConfigurationAndActualModuleWithoutRoleFallback. The real profile/configuration services yield one explicit immutable baseline at 650 rpm and torque rows (650,240), (1000,300), (2000,360), (3200,350), (4200,300), (5000,180). Applicability binds exact config/profile revision/module/model/definition. Optional firmware remains null. A valid configuration explicitly referencing module.cabin.body resolves that real module and its metadata, not the engine role. There is no implicit workspace on route entry. | +| C-02 | ScalarThenTableProposals_HaveExactLinearParentsAndStructuredDiffs; native workflow. Saving 650->1250 produces unique Proposed revision 2, parent=baseline/head revision 1, and exactly one scalar diff: before=650, after=1250, delta=600 rpm. Baseline and original Model.WarmIdleTargetRpm remain exactly 650. Every version retains workspace/source tokens. | +| C-03 | ScalarThenTableProposals_HaveExactLinearParentsAndStructuredDiffs; MultiCellAndReverseDiffs_AreExactDeterministicAxisOrderedSnapshots; native baseline/preceding diff. Editing only the 2000-rpm cell 360->350 produces revision 3 with exact revision-2 parent, exactly two baseline diff entries (table delta -10 N*m; scalar +600 rpm), and exactly one preceding-revision diff. Unchanged cells and axes are omitted. Parameter order is ordinal logical ID, then numeric axis order. Reverse diffs swap exact before/after and signs. | +| C-04 | InvalidScalar_RejectsBeforeHeadHistorySourceOrCapacityMutation (NaN, both infinities, 649.999, 5000.001); InvalidTorqueCell_RejectsTheEntireCandidateIncludingValidScalarEdit (NaN, both infinities, 0.999, 1000.001); WrongCandidateShapeUnitsKeysAndAxes_RejectWithoutNormalization (13 independent shape/key/unit/axis/count vectors); MalformedDefinitionAndUnloadedCommands_RejectTypedWithoutFabricatedWorkspace; InvalidTableDefinitionMetadata_IsRejectedWithoutAHealthyDefault; SourceTokenMismatch_RejectsWithoutCrossSourceFallback. All return typed visible failures before any snapshot/head/history/source mutation. No clipping, sorting, normalization, omitted-cell save or unknown-key fallback occurs. | +| C-05 | NoOpBoundsChangedBackAndTinyDiff_AreExactNotRoundedOrClipped. The initial identical save returns the very same baseline revision and keeps count 1. Exact lower/upper values 650/5000 rpm and 1/1000 N*m are accepted. A changed-back save creates a new Proposed revision with exact previous parent and empty baseline diff. double.BitIncrement(650) remains an explicit nonzero exact diff, not rounded away. | +| C-06 | StaleSequentialAndBarrierControlledConcurrentHeads_CommitAtMostOneProposal; TwoActualEditorsAndSourceReplacement_RejectStaleOrUnconfirmedLossWithoutMutation. Two actual Save calls released through a two-participant barrier with the same expected head yield exactly one changed proposal and one StaleHead rejection, count 2 and one exact parent chain. Sequential stale changed and unchanged requests also reject. Two real rendered editors preserve the loser draft/error without lost update or implicit rebase. | +| C-07 | DefinitionCandidateHistoryAndDiff_DefensivelyCopyCallerCollections. Mutating source axis/cell arrays, scalar lists and table lists after candidate creation cannot alter baseline/proposal/definition values. Older version and diff values stay 650/1250/+600 after later saves. Definition axes, history and diff entries reject IList mutation. Each version's source/workspace/parent identity remains immutable. | +| C-08 | IdentityComparisonsAndExplicitReplacement_PreservePriorHistoryOnAnyRejection; SourceTokenMismatch_RejectsWithoutCrossSourceFallback (configuration/profile revision/module/model/definition and exact-case variants); FullProfileRevisionChangeAndInvalidEmptyRequests_PreserveTheExactCurrentWorkspace; UnsupportedButValidDynamicsConfiguration_RejectsTemplateBeforeReplacement; real rendered replacement tests. Different or replaced source/head/version IDs cannot cross-save or compare. Invalid/unconfirmed/stale replacement preserves the prior exact snapshot. Confirmed replacement creates a fresh workspace with one baseline; old version IDs reject. Profile/module case variants follow accepted identity policy, while config/model/definition identifiers remain exact. A real profile revision-2 source stays separate from revision 1. | +| C-09 | TorqueDraft_IsPinnedAndUneditedSavePreservesExactCanonicalDoublesAcrossToggles; RealEditor_SaveDiffHistoryAndInvalidInput_UseExactVersionsNotSharedDraftReferences; native draft checks. Unsaved torque strings remain pinned to captured units across global switches/rerenders. Edited torque is converted once and asserted against the exact independent N*m/lbf*ft factor result; unedited values retain canonical doubles without conversion drift. Eight repeated unit/no-op-save cycles keep the identical head and exact cells. Native Metric 345 N*m remained 345 after Imperial switch; untouched Imperial-to-Metric save retained exact 350 N*m and revision 3. | +| C-10 | RealEditor_SaveDiffHistoryAndInvalidInput_UseExactVersionsNotSharedDraftReferences; TwoActualEditorsAndSourceReplacement_RejectStaleOrUnconfirmedLossWithoutMutation; native UI. Real DI/rendered events exercise exact source selection, baseline, parent/head saves, history-only inspection, explicit version-pair diff and typed parse/validation errors. Inspecting baseline does not change the editable revision-3 head. Status is Baseline/Proposed authoring only, never granted Tested/Approved/Applied/verified-backup authority. | +| C-11 | HistoryLimit_IsExactly32IncludingBaselineAndNoOpStillSucceedsAtCapacity. Revisions 2..32 commit with unique IDs and exact monotonic parents. The identical full head is returned without consuming capacity; changed revision 33 rejects HistoryLimit with the same snapshot/revision/count 32. One workspace is retained; replacement resets the service-held history explicitly, not by eviction or hidden accumulation. | +| C-12 | AuthoringWithActualLiveSourceRecordingAndReplay_AddsZeroTransportModelOrStoreSaveCalls. Real live dynamics, saved recording/strict file-store archive and validated replay coexist during baseline/proposals/diff/unit operations. Transport-call delta=0, model-control-call delta=0, archive-Save-call delta=0; no approval/programming boundary exists to invoke. Original profile/config export/fingerprint, live trace/status, recording serialization/raw file bytes and the exact replay snapshot remain unchanged. All 350 baseline tests pass. Final nine-project Release/native checks are below. | + +## Acceptance criteria + +| ID | Result | Evidence | +|---|---|---| +| AC-01 | PASSED | C-01/C-04/C-08 real exact configuration/profile/module selection, bounded supported definition, unknown/mismatched references and atomic template/value/source rejection. | +| AC-02 | PASSED | C-02/C-03/C-05..C-07/C-11 exact immutable versions/parents/diffs, no-op and changed-back semantics, defensive copies, deterministic competing-head commits and 32/33 limit. | +| AC-03 | PASSED | C-09/C-10 actual rendered commands/history/diff/source confirmation, pinned draft units and exact canonical equality; native editor labels remain authoring-only. | +| AC-04 | PASSED | C-12 counted real-source/replay/recording coexistence; 405 final passes, all nine projects/native Release build with zero warnings/errors, and required native authoring checks. | +| AC-05 | PASSED | Executable matrix, own post-green source-path review, directly related docs/README, preserved protected/history/dependency/manual workflow and this single fenced report. | + +## Commands and outcomes + +SDK: dotnet --version -> 10.0.403 under the unchanged global.json policy. +The existing tests use xUnit v2/VSTest. No SDK/package/workload/tool +installation, update, repair or restore occurred. + +The final commands ran sequentially after the review additions: + +| Exact command | Exit | Result | +|---|---:|---| +| dotnet test .\src\tests\AutoForge.IntegrationTests\AutoForge.IntegrationTests.csproj --configuration Release --no-restore --filter "FullyQualifiedName~CalibrationAuthoringTests" | 0 | 55 authoring cases passed, zero failed/skipped. | +| dotnet build .\src\AutoForge.slnx --configuration Release --no-restore | 0 | All nine projects/native Client passed; 0 warnings, 0 errors. MAUI XAML source-generation output was informational. | +| dotnet test .\src\AutoForge.slnx --configuration Release --no-build | 0 | 179 unit + 226 integration = 405 passed, zero failed/skipped. | +| git --no-pager diff --check | 0 | No whitespace errors. Existing Git LF-to-CRLF notices for README/build guide were informational. | +| git --no-pager diff --exit-code -- prompts global.json Directory.Build.props Directory.Packages.props NuGet.Config src\AutoForge.Simulation src\AutoForge.Diagnostics src\AutoForge.Application\Features\Vehicles\Telemetry | 0 | Existing orchestration/history/dependency and Simulation/Diagnostics/recording/replay implementations unchanged before adding this report. | + +Per-project Release build: AutoForge.Core, AutoForge.Diagnostics, +AutoForge.Simulation, AutoForge.Application, AutoForge.Components, +AutoForge.UI, AutoForge.Client, AutoForge.UnitTests and +AutoForge.IntegrationTests all PASSED. Eight projects remain portable net10.0; +Client remains net10.0-windows10.0.26100.0 / win-x64. + +The accepted 350 baseline cases remain 179 unit + 171 integration. This step +adds 55 integration cases and deletes or weakens no baseline test. +Important exact boundaries: 32 saved revisions including baseline; 2..32 fixed +torque rows; finite inclusive model-derived scalar range; finite [1,1000] N*m +cells; identity scaling 1/offset 0. No authoring disk persistence exists. +Existing archive/gauge/replay limits and clock ownership are unchanged. + +Iteration evidence: + +- The initial focused command failed compilation because a concurrency test + used blocking Task.WaitAll/Result, rejected by xUnit1031 under warnings-as- + errors. It was corrected to async Task.WhenAll/WaitAsync; the barrier still + establishes simultaneous real commit attempts without sleeps/stress timing. +- The first executable focused run passed 47 cases with zero failures. + Post-green additions expanded this to 50, then final 55 cases. +- The reviewed full build/test run passed 400 cases; the final run passed 405. + There were no unresolved behavioral or build failures. Compilation failure + is not claimed as a pre-fix behavioral reproduction; authoring did not + exist before this assignment. + +## Native versus controlled evidence + +The real Release Windows Client was launched with a task-owned WebView2 profile +and local DevTools port 9379. A temporary Node/built-in WebSocket helper +operated the actual native WebView controls. There was no second web host, +dependency or production debug feature. + +Native actions and actual results: + +1. Through the existing simulation route, explicitly imported the synthetic + profile, selected its exact revision and created the warm configuration. + No session was opened by authoring. Its original export and fingerprint + were retained for exact comparison: + sha256:v1:e8991ae139b54959ec53a4fe64b08dc9bfc03feb533496cf741f2c9f3a2342da. +2. Selected that exact configuration on /calibration and created the + Synthetic configuration-derived baseline: 650 rpm plus the six original + torque rows. Saved 1250 rpm as Proposed revision 2 and the 2000-rpm + torque edit 350 N*m as Proposed revision 3. +3. Native baseline diff contained exactly the scalar 650->1250, delta +600 rpm + and table cell 360->350, delta -10 N*m. Comparing revision 2 to 3 contained + only the table cell. Baseline history inspection left the editable head + at revision 3. First-run baseline/version IDs were: + 5306f3d1604d4708a204d78d53e5c745 (baseline), + bda2b90206dc42ff91ac6b35fe7d552b (revision 2), + 35600482db3f418ca6d8bc93c6b783f1 (revision 3). +4. Native scalar 600 and torque 1001 saves were rejected visibly with the + same revision/count/head. An unselected/different source rejected with + the exact source-mismatch error; unconfirmed replacement rejected with + the explicit confirmation error and retained history. +5. Typed unsaved 345 while the draft was Metric/N*m, then changed global + units to Imperial. The input stayed 345 and the draft explicitly stayed + Metric/N*m. Cancel loaded a new Imperial draft showing source 350 N*m as + 258.14675224704285 lbf*ft. Switching globally back to Metric and saving + untouched returned the identical revision-3 head and exact 350 N*m, with + no new history entry. +6. Returned to /simulation, selected/exported the original configuration: + its entire export was exactly unchanged, warm idle remained 650 rpm and + 2000-rpm torque remained 360 N*m. An explicit subsequent dynamics session + stepped to 7 / 0.7 seconds and read actual diagnostic-frame engine speed + 631.80416 rpm / Good / SYNTHETIC_DYNAMIC, not the 1250 proposal. This is + an observed unchanged-source model result, not a claim that the proposal + was tested/applied or that the model was at exact idle. +7. Closed that actual session. Reopened authoring with the same saved + revision-3 history. Confirmed explicit replacement discarded an unsaved + 1500-rpm draft/history and created a new baseline with 650 rpm and torque + 360 at 2000 rpm. Profile/simulation/replay routes and authoring re-entry + worked; replay remained explicitly Unloaded. +8. After the final 405-pass build, restarted the actual Client. Authoring had + no workspace and no saved configuration, confirming process-memory + lifetime rather than hidden persistence. Explicitly recreated the warm + source and repeated baseline, 1250-rpm proposal, 350-N*m cell proposal + and exact two-entry diff on the final binary. Final head was revision 3, + ID 62431277f0624fc8ba25ef4a02fcb602 in workspace + fe2a12d0aa0b47c6bbadf63961fc74b7. No native error overlay appeared. + +Native observations verify the real configuration/Application/UI/editor and +normal unit/history/diff/navigation workflow. Exact concurrent/stale-head, +history-capacity, malformed-definition and source-isolation proofs are +controlled real-service tests, not attributed to human-speed native timing. +No real device, backup, approval, programming or physics application is claimed. + +Cleanup PASSED: both task-owned native Client sessions completed. Only their +specific PIDs (38528 and 1512) were terminated. The task-only WebView profile +and helper were removed, no task WebView processes remained and port 9379 had +no listener. The actual app-local recording directory was inspected and +remained empty; no native recording file was created/removed by authoring. +Profiles/configurations/proposals used for native smoke were process-memory +only. Existing/default WebView data and unrelated app files/preferences were +not reset. Original Metric/Road preference values were restored and observed. + +## Own post-green source-path self-review + +Reviewed actual producers/consumers through exact configuration selection and +profile/module validation -> supported immutable definition/baseline -> +complete candidate -> expected workspace/source/head checks -> linear commit -> +structured diff -> routed copied draft/units/history UI. + +Public entry points reviewed: CreateBaseline, ReplaceBaseline, Save, Compare, +Snapshot, template construction/Validate, and route create/replace/save/cancel/ +inspect/compare plus render/unit/lifetime callbacks. Normal, invalid, boundary, +same-content, changed-back, stale/concurrent, cross-source and replacement paths +were walked against the frozen matrix. + +Validation precedes every history/head/version commitment. No-change requests +still require the current source/head. Version creation/capacity mutation occurs +only after complete validation. One lock serializes real commits without an +await-held gate or external asynchronous owner. Definition/value collections +are read-only and defensively copied. Units/rerenders do not save or rebind +drafts. History inspection does not change editable head. No source mutation +or live/store/model/approval dependency is introduced. + +Review improvements completed inside this step: + +- Made every standalone immutable revision explicitly carry its own copied + workspace/source identity, not only inherit context through its container. +- Strengthened edited-unit assertions to exact independent factor results, + not a tolerance that could hide canonical conversion differences. +- Added 2/32 row-boundary assertions, real profile revision-2 replacement, + exact-case source/model/definition rejection, malformed table metadata + and multi-cell/reverse exact diff ordering/sign assertions. +- Improved diff parameter labeling without changing canonical results. + +Affected focused checks, all nine projects and complete regressions were rerun +after review additions; the final binary was then checked natively again. +No known unresolved defect in the assigned exit contract remains. + +## Documentation, scope and preservation + +Updated [README.md](../README.md), +[documentation index](../docs/README.md), +[architecture](../docs/architecture.md), +[build/test guide](../docs/build-and-test.md) and the directly related status/ +isolation note in [replay contracts](../docs/telemetry-replay.md). Added +[calibration authoring guide](../docs/calibration-authoring.md). +They document exact applicability/template bounds, source/head/version/diff +rules, one-workspace/32-revision lifetime, pinned versus canonical units, +no backup/test/approval/apply claims, accepted Step-08 and Step-09 pending +manual review. Step-10 programming stays separate/unimplemented. + +The worktree began clean on main at 866831f and HEAD is unchanged. Existing +prompts/history/roadmap/state/assignment/shared quality gate were not edited; +this is the only new prompts file. No protected instruction file was created +or modified. The index is empty. No staging/commit/push, dependency/project/ +host/schema/protocol changes or agent/automatic orchestration occurred. + +All nine project references are unchanged. Core only gained the approved +calibration contracts; Simulation/Diagnostics implementations/oracles, +recording/replay behavior and source configurations remain unchanged. +Source/tests stay under src and src/tests; technical documentation stays +under docs. The separately disclosed recording refresh/navigation issue was +not changed or worked into this authoring assignment. + +Remaining unassigned capabilities are programming/readback/restore/verified +backup, Tested/Approved workflow, model application, calibration-file +persistence/import/export, editable-axis/multidimensional maps, arbitrary +firmware scaling/memory, AI and hardware operations. No future step is +authorized by this report. + +STOP. +``` diff --git a/prompts/Step-10.md b/prompts/Step-10.md new file mode 100644 index 0000000..530d237 --- /dev/null +++ b/prompts/Step-10.md @@ -0,0 +1,313 @@ +# Step-10 - Verified simulated programming and recovery + +## STEP IDENTIFIER + +Step-10. Step-09 was accepted on 2026-10-30 with no corrective assignment. +This is the sole active implementation assignment. Step-11 local AI is blocked. + +## STEP TITLE + +Rehearse approved logical calibration writes against an isolated simulation +image, verifying backup, changed/unchanged readback and separately approved restore. + +## OBJECTIVE + +One user outcome: take a saved authoring proposal through an explicit simulated +target/backup/approval/write/readback/restore workflow with truthful failure states. +One primary new contract: a guarded target mutation bound to an exact image +revision and immutable approval, not a change to the authoring configuration. + +Read [STATE.md](STATE.md), [ROADMAP.md](ROADMAP.md), +[authoring contracts](../docs/calibration-authoring.md) and +[WORKER-QUALITY-GATE.md](WORKER-QUALITY-GATE.md). Make the frozen matrix executable +before coding, self-review after first green, write `prompts/Step-10-Report.md`, +and STOP. Do not begin local AI or any physical operation. + +## ARCHITECTURAL CONTEXT + +Keep all nine projects, one Client and generic Components. Core holds reusable +calibration values/definitions; Diagnostics exposes a narrow typed simulated +programming target port; Simulation owns its real mutable target image. +Application owns backup/approval/command/reconciliation/verification and UI owns +interaction. Client composes the explicit simulation provider. + +Application/UI must not reference Simulation implementation, read its private +state/oracle, or manufacture target readback from proposal/request/configuration. +Use logical scalar/table operations, not a new wire protocol, binary offset or +unrestricted command channel. No new project/package/host or generic programming/ +workflow framework. Source/tests stay under `src`, tests under `src/tests`. + +## CURRENT IMPLEMENTATION STATE + +Accepted authoring offers one immutable source-bound workspace, Baseline/Proposed +revisions, exact scalar/table values/axes/diffs and guarded head commits. +Worker baseline: 179 unit + 226 integration passes (405 total, zero failed/ +skipped), clean nine-project Release build and native authoring checks. +The orchestrator did not run them. No programming target/service exists yet. + +Use the actual [authoring service](../src/AutoForge.Application/Features/Vehicles/Calibration/CalibrationAuthoringService.cs), +[calibration contracts](../src/AutoForge.Core/Calibration/SyntheticEngineCalibration.cs) +and [configuration service](../src/AutoForge.Application/Features/Vehicles/Simulation/DynamicsConfigurationService.cs). +The supported image is exactly `engine.warm-idle-target` (rpm) and +`engine.torque-curve` (fixed rpm axis, N*m cells), with existing template validation. + +The source warm baseline is 650 rpm; the saved proposal can be 1250 rpm and +360->350 N*m at 2000 rpm. Those are synthetic values, not manufacturer data. +A configuration-derived authoring baseline is not the target backup. Inspect +Git/prior art and preserve accepted behavior, dirty work and historical reports. + +## REQUIRED IMPLEMENTATION + +### Frozen contract matrix + +| ID | Input/precondition | Required result | +|---|---|---| +| C-01 | Explicit current supported authoring workspace/config/module plus Simulation provider | Open one fresh isolated target instance at image revision 0, with complete supported source values. No implicit open/write; physical/replay/wrong-provider/source rejects before target creation or mutation. | +| C-02 | Read target, create original backup and verify with a second independent read | Identity/revision/shape/axes/units/values match exactly; immutable verified volatile backup covers both keys/all cells. Wrong/incomplete/mismatched read rejects before approval; baseline is not used as a fake response. | +| C-03 | Prepare/approve immutable current proposal 650->1250, then Apply | Display exact target-to-proposal diff; approval binds target/source/definition, actual before image/revision, proposal/head and action. Re-read/CAS before dispatch, one write, fresh readback; scalar=1250, every torque cell unchanged, authoring baseline/config remain 650. | +| C-04 | Next saved proposal additionally changes 2000-rpm torque 360->350 | New approval binds fresh target revision; exactly that cell changes, axes and all other values stay intact; full readback equality is checked, not just acknowledgement or selected cell. | +| C-05 | Missing/mismatched backup/confirmation/token/proposal/head/source/target revision, no-op proposal, invalid candidate or wrong target kind | Typed visible rejection before approval consumption/write/target mutation; current backup/image/approval/history remain intact except error notification. No auto-rebase, broad writes or inferred authority. | +| C-06 | Head/workspace/target identity or image changes after approval but before dispatch | Rejected stale approval with zero writes; exact accepted source/proposal/before-image cannot silently follow current data. Reopen creates a new instance and invalidates old approvals/backups. | +| C-07 | Same operation requested twice; competing operation; cancellation/close before or after dispatch | No second mutation or lost ownership. Exact repeated operation shares/returns its outcome; conflicts reject before mutation. Cancel-before-dispatch writes zero; once dispatch may have happened, outcome is not falsely labeled unchanged/success. | +| C-08 | Negative acknowledgement, dropped acknowledgement/exception after actual commit, mismatched fresh readback or read failure | Full fresh readback determines verification. Never label Applied from acknowledgement alone. Unverified/uncertain mutation remains visible RecoveryRequired with reason/evidence; no blind resend or automatic restore. | +| C-09 | Explicit reconcile after an uncertain outcome | Read-only exact current-image evidence identifies unchanged, candidate-matching or divergent/unavailable state; no write or stale cached proof. Only exact target/revision/content evidence may resolve verification; original uncertainty remains in the operation record. | +| C-10 | Prepare and explicitly approve restore of original backup on same live rehearsal target | Bind fresh current revision/image and original verified backup; one guarded restore and full independent readback. Original 650/360 values and all other cells/axes restored, revision advances; no authoring/history/config rewrite. | +| C-11 | Wrong-target backup, failed/unknown restore, pending dispose/late read or failed test | No restore permission, false Restored result or old-generation publication; errors persist, owner/target cleanup drains outside required gates and allows safe close. Barriers/resources released in finally. | +| C-12 | Bounded audit/results, real UI/unit and coexistence paths, full verification | At most 32 dispatched mutation outcomes per target session; exact boundary rejects a new attempt before write. All 405 cases plus new coverage pass; real simulation port and native UI work; no existing diagnostics/model/archive/replay or physical side effects. | + +### A. Explicit isolated simulation target, not a dynamics application + +Introduce one explicit simulation-only provider with a unique identifier such as +`autoforge.simulation.calibration-rehearsal`. Opening requires the exact selected +configuration/profile revision and its actual EngineModuleIdentifier/definition. +Reject PhysicalHardware, RecordedReplay and any unregistered/mismatched provider +or descriptor; metadata/capability claims alone cannot authorize a write. + +The target owns an independently stored immutable-at-read mutable-at-commit +supported image, seeded once from the selected configuration and validated +template. Thereafter Read returns actual target state, and Write/Restore use +compare-and-swap against the exact instance/image revision and full validated +candidate. Revision starts 0 and increments once per successful changed commit. +Validation/conflict/cancellation before commit leaves the image unchanged. + +Preserve unique instance identity across all reads. Each read defensively copies +both supported keys, axis, units and cells. The typed port supplies explicit +outcomes/errors, not a success-shaped fallback. Actual Simulation implementation +is exercised in normal/failure tests; test-only fault forwarding may simulate +lost replies/divergent readback below Application without mocking the workflow. + +This target is an isolated programming rehearsal, not a live dynamics session. +Do not modify `DynamicsConfiguration`, its fingerprint/catalogue, an existing +DynamicsEngine, signal source, diagnostics schema or profile calibration identity. +No model telemetry may claim 1250 rpm merely because the rehearsal image stores +that number. Wiring to a fresh run/functional performance proof is later work. + +Target/backup/results are process-memory only. Close destroys that target; +reopen recreates source values under a new identity. No persist-after-close, +crash recovery, firmware block transfer or real-device backup claim is assigned. + +### B. Independent supported-image backup and explicit approval + +Prepare the original target backup once before the first mutation. Read through +the real target port, validate identity/applicability/revision/complete supported +shape/values and compare against a second independent read of that same target. +If either differs or is unavailable, do not publish VerifiedBackup/Ready status. +Copy the actual observed image; never call an authoring baseline a verified read. + +The backup is explicitly "Verified in-memory backup of supported simulation +image": one scalar plus the complete fixed-axis table, not an entire ECU. +Keep its target instance/source/definition/image revision and immutable contents. +It remains the original backup across multiple writes on that instance. + +Prepare a candidate only from an immutable saved **current Proposed head** of +the accepted authoring workspace, with exact source applicability. Read current +target state to form the actual before-image and precise target-to-candidate diff. +Different head/workspace/source invalidates pending apply approval; do not replace +it silently. An identical target/candidate is a visible no-op rejection, not a +new Applied or verified mutation. + +Explicit user confirmation produces a single-use opaque approval bound to: +action Apply or Restore, target provider/kind/instance/source/definition, +verified original backup identity, expected current image revision/contents, +exact candidate values and selected proposal/workspace/head (for Apply). +Authoring revisions themselves remain Baseline/Proposed, not Approved/Applied. +This local approval records a deliberate rehearsal action, not cryptographic +authorization, manufacturer permission or a physical-write capability. + +Before dispatch, revalidate approval, source/head and a fresh target read against +the approved before-image/revision. The target also atomically compares its actual +revision at commit so a change after that read cannot slip through. +Never consume approval or count a dispatched result before all preconditions +pass. Once dispatch begins, prevent token reuse; if cancellation loses certainty, +do not re-enable the same approval as though no write happened. + +### C. Fresh verification, uncertain outcomes and separately approved restore + +One operation owner serializes target preparation/mutation/reconciliation/close. +Guard eligibility before state changes. Commands carry an opaque operation ID; +repeating the exact active/completed request shares/returns that result rather +than issuing another write. Reusing an ID with different inputs rejects. +Conflicting actions while work/drain is pending reject visibly; no gate is held +across an await needed by cleanup. Close cancels and drains with a shared +completion/generation guard; no stale success may publish into a new target. + +After mutation dispatch, request an independent full Read. Compare target +instance/source/definition/revision, both keys, units, axes and every changed/ +unchanged cell to the exact expected image. A positive acknowledgement or +echoed candidate is not verification. Keep acknowledgement versus readback +separate in the result; do not hide protocol/port/readback errors. + +If dispatch may have committed but fresh proof is missing/divergent, label +RecoveryRequired/Unknown with precise actual evidence and block new Apply. +Never retry a write or restore automatically. Explicit Reconcile is read-only: +compare a fresh complete image to approved before/after plus expected revision. +Classify unchanged/candidate-matching/divergent/unavailable honestly. Exact +identity/revision/content proof may establish VerifiedAppliedAfterReconciliation; +preserve the original lost-ack/verification failure in audit. Divergence never +becomes success merely because one requested value matches. + +Restore is a separate prepared/confirmed operation using the immutable original +backup of that same target instance/source/definition. Read fresh current state, +bind its revision in a new restore approval and use the same atomic CAS/full +readback rules. Restore must work after multiple successful writes; it restores +the original supported values, not the author's latest proposal. Current revision +advances; restored value equality does not pretend time/version went backwards. +Wrong/closed/new instance or invalid backup rejects, and failed/uncertain restore +retains RecoveryRequired rather than a healthy completion. + +Preserve a bounded immutable result/audit list in the owning rehearsal session: +at most 32 **dispatched mutation outcomes** (Apply/Restore, successful or uncertain). +At capacity reject a new dispatch before consuming approval/write; exact operation +replays still return their existing result. Preparation/reconciliation update +bounded current evidence, not a hidden unbounded history. +Include operation/action, proposal/head and target/backup/revision identities, +approval, full before/expected/actual evidence, acknowledgement, verification/ +recovery status/error and explicit timestamps. This audit is volatile/local, +not a new disk format or an external security attestation. + +### D. Actual UI, provenance and existing source isolation + +Extend the existing calibration area or add a clearly named rehearsal route. +Use real Application services and the Simulation target provider composed by +Client. Explicitly open a target, read/prepare backup/proposal, inspect exact +diff/source/preconditions, confirm Apply, inspect separate acknowledgement/ +readback, reconcile if required, prepare/confirm Restore and close. + +Show synthetic/isolated/process-memory scope prominently, current target instance/ +revision, original backup coverage, proposal/head, pending/uncertain/error status +and bounded audit. Never call authoring source metadata a verified ECU identity. +No implicit programming on proposal Save, page entry, unit switch or render. +Unconfirmed/rejected actions leave real target and saved authoring data unchanged. + +Use existing display-unit conversion for human-facing torque; programming and +audit compare canonical rpm/N*m with exact fixed axes. Unit changes cannot mutate +candidate/approval/before-image or dispatch commands. +Old live diagnostics/dynamics/recording/replay remain separate; merely opening +the rehearsal cannot connect/reset/stop or rewrite them. +A closed rehearsal's immutable backup/result can remain inspectable as inactive +evidence, but cannot authorize a new target. Reset/new rehearsal is explicit. + +## FILES OR PROJECTS EXPECTED TO CHANGE + +Narrow Core evidence/target-value contracts if needed, typed Diagnostics target +ports, Simulation-owned rehearsal state, Application guarded workflow/readback/ +audit, calibration UI/Client DI, focused tests and related README/docs. +No existing dynamics model/wire/configuration/schema or authoring status rewrite. +No new project/package/host or private oracle exposed to Application/UI. +Under `prompts`, create only `Step-10-Report.md`. + +## INTERFACE AND DEPENDENCY REQUIREMENTS + +Preserve nine projects/references, one Client, pure Components, accepted exact +source/template/unit/head/value validation, immutable configurations/archives, +recording/replay and lifetime/clock semantics. No physical provider implementation, +unrestricted hardware command, emissions/safety/security bypass or inferred +write permission. Simulation-only actions grant no authority to physical targets. +No broad catch/silent failure/false backup/ack-only verification/automatic restore. +Do not fix the separately disclosed recording navigation/refresh issue here. +No dependency/system/workload install/update/repair/rollback, staging/commit/push +or destructive Git. Preserve protected/history/orchestration files and dirty work. + +## TESTING REQUIREMENTS + +Map C-01..C-12 to meaningful named tests before handoff: + +- Real configuration/profile/authoring plus actual Simulation target reads. + Verify two independent backup reads, complete defensive images, explicit + target/kind/source/definition validation and missing/corrupted reads. +- Apply scalar 650->1250 with all torque cells unchanged; second proposal changes + only 2000-rpm torque 360->350; full changed/unrelated readback and separately + approved original Restore recover 650/360 plus every other value. +- Independent invalid source/head/token/revision/shape/unit/value vectors; + stale mutation between precheck and target CAS; exact prior-state/write-count + assertions. Rejected calls and unit switches cannot consume an approval. +- Faults injected below the real workflow: rejected before commit, commit then + lost ack/cancel, fresh read failure, wrong readback/target identity, divergent + unchanged cell and restore failure. Read-only reconciliation proof uses actual + target values/revision, not a mocked successful service. +- Controlled pending-operation/drain/close/late-publication, same operation ID, + conflicting requests and bounded 32/33 result capacity. Barriers establish + interleavings; no sleeps/polling/stress timing as correctness proof. Release + resources in finally and await owned work. +- Real rendered backup/approval/apply/reconcile/restore/invalid actions, safe + error/status/unit presentation and real diagnostics/dynamics/recording/replay + coexistence with zero unassigned source/model/store writes. + +Run focused cases, then sequentially: + +- `dotnet build .\src\AutoForge.slnx --configuration Release --no-restore` +- `dotnet test .\src\AutoForge.slnx --configuration Release --no-build` + +Preserve 405 baseline cases (179 unit, 226 integration) plus meaningful new +coverage. Map necessary UI-only assertion changes without deleting safety/ +error/source checks. Build all nine projects/native Client. Install/restore +nothing absent a genuine chosen-command missing dependency. + +Native smoke on rebuilt Client: explicitly create source/proposals, open isolated +target, prepare verified volatile backup, approve/apply scalar then table edit, +inspect full readback/audit, explicitly approve/verify original Restore, close/ +reopen and confirm new-instance/no-old-approval behavior. Verify original +configuration/live source remains unchanged and old routes/unit preferences work. +Native normal success is not controlled port/uncertain/race fault proof. +Clean only exact task-owned profiles/artifacts; never reset unrelated app data. + +## DOCUMENTATION REQUIREMENTS + +Update README/index/architecture/build guide and rehearsal usage/contracts: +isolated Simulation typed target (not a new wire/real driver), supported-image +volatile backup coverage, approval/source/CAS/single-use operation semantics, +fresh readback/uncertain/reconcile/approved Restore, bounded audit and actual +normal/control evidence. Step-09 is accepted; Step-10 remains pending manual +review. No crash durability, model application, complete ECU backup, tested +performance, manufacturer compatibility or physical programming is claimed. + +## ACCEPTANCE CRITERIA + +| ID | Criterion | Evidence | +|---|---|---| +| AC-01 | C-01/C-02 actual isolated simulation target, source-kind/applicability gates and independent supported-image backup | Real target/config/port tests with complete defensive reads and no fake source echo | +| AC-02 | C-03..C-06 exact immutable approval/head/backup/revision and atomic validated mutation | Exact scalar/table/unrelated-value results, stale/CAS/negative vectors and zero-write rejected actions | +| AC-03 | C-07..C-11 one operation owner, fresh verification/unknown/reconciliation and separately approved Restore | Controlled real-port/lifetime/idempotence/fault cases and full original-image readback | +| AC-04 | C-12 bounded audit, real UI/native workflow/source isolation, 405 regressions and full Release build | Exact 32/33/no-call/state assertions, native/control distinction and worker commands/results | +| AC-05 | Matrix/self-review/docs/README/history/protection/manual gate accurately describe implemented limits | Own post-green source-path review, named executed evidence and `prompts/Step-10-Report.md` | + +## OUT-OF-SCOPE WORK + +Physical programming/driver/protocol/firmware blocks, dynamics application or +performance reruns, durable calibration/backup/audit format/storage, AI/runbooks, +new template/unit family, arbitrary offsets/commands, new package/project/host +and unrelated cleanup. No future assignment, agents, automatic handoff, +orchestration/shared-gate edit, staging, commit or push. + +## REPORTING REQUIREMENTS + +Save `prompts/Step-10-Report.md` wholly inside exactly one plain triple-backtick +fence, no language tag/outside text/nested fences. Include identifier/title/status, +functions/files/interfaces, C-01..C-12/AC-01..AC-05 matrix with named executed +evidence, exact backup/approval/write/readback/unknown/reconcile/restore/negative/ +owner/audit outcomes and source-isolation counts, commands/exits/warnings/ +per-project counts, native versus controlled coverage, docs/README, own +post-green source-path self-review, limitations/deviations/blockers and +preservation review. COMPLETE requires all assigned checks; otherwise report +INCOMPLETE/BLOCKED with the precise unmet criterion. +Save and STOP; do not begin Step-11. diff --git a/src/AutoForge.Application/Features/Vehicles/Calibration/CalibrationAuthoringService.cs b/src/AutoForge.Application/Features/Vehicles/Calibration/CalibrationAuthoringService.cs new file mode 100644 index 0000000..394cea7 --- /dev/null +++ b/src/AutoForge.Application/Features/Vehicles/Calibration/CalibrationAuthoringService.cs @@ -0,0 +1,229 @@ +using AutoForge.Application.Features.Vehicles.Profiles; +using AutoForge.Application.Features.Vehicles.Simulation; +using AutoForge.Core.Calibration; +using AutoForge.Core.Simulation; +using AutoForge.Core.Vehicles; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; + +namespace AutoForge.Application.Features.Vehicles.Calibration; + +public enum CalibrationVersionKind +{ + Baseline, + Proposed +} + +public sealed record CalibrationModuleMetadata( + string ModuleIdentifier, string? HardwareIdentifier, string? SoftwareIdentifier, + string? FirmwareIdentifier, string? CalibrationIdentifier); + +public sealed class CalibrationVersion +{ + internal CalibrationVersion(string workspaceIdentifier, CalibrationApplicability source, + int revision, string? parent, CalibrationVersionKind kind, CalibrationValues values) + { + Identifier = Guid.NewGuid().ToString("N"); + WorkspaceIdentifier = workspaceIdentifier; + Source = source with { }; + Revision = revision; + ParentIdentifier = parent; + Kind = kind; + Values = new(values.Scalars, values.Tables); + } + public string Identifier { get; } + public string WorkspaceIdentifier { get; } + public CalibrationApplicability Source { get; } + public int Revision { get; } + public string? ParentIdentifier { get; } + public CalibrationVersionKind Kind { get; } + public CalibrationValues Values { get; } + public string Label => Kind == CalibrationVersionKind.Baseline + ? "Synthetic configuration-derived baseline" : "Proposed synthetic authoring revision"; +} + +public sealed class CalibrationWorkspace +{ + internal CalibrationWorkspace(string identifier, SyntheticEngineCalibration definition, + CalibrationModuleMetadata module, IEnumerable history) + { + Identifier = identifier; + Definition = definition; + Module = module with { }; + History = Array.AsReadOnly(history.ToArray()); + } + public string Identifier { get; } + public SyntheticEngineCalibration Definition { get; } + public CalibrationModuleMetadata Module { get; } + public IReadOnlyList History { get; } + public CalibrationVersion Head => History[^1]; + public CalibrationVersion Baseline => History[0]; +} + +public sealed record CalibrationSaveRequest( + string WorkspaceIdentifier, string ExpectedHeadIdentifier, + CalibrationApplicability Source, CalibrationValues Values); + +public sealed record CalibrationDiffEntry( + string LogicalIdentifier, double? AxisCoordinate, string? AxisUnit, string Unit, + double Before, double After, double Delta); + +public sealed record CalibrationDiff( + string WorkspaceIdentifier, CalibrationApplicability Source, + string FromIdentifier, string ToIdentifier, IReadOnlyList Entries); + +public sealed class CalibrationAuthoringService(IDynamicsConfigurationService configurations, IVehicleProfileService profiles) +{ + public const int MaximumRevisions = 32; + private readonly object _gate = new(); + private CalibrationWorkspace? _workspace; + public event Action? Changed; + public CalibrationWorkspace? Snapshot { get { lock (_gate) return _workspace; } } + + public CalibrationWorkspace CreateBaseline(string configurationIdentifier) + { + CalibrationWorkspace workspace; + lock (_gate) + { + if (_workspace is not null) + throw Failure(CalibrationFailure.WorkspaceExists, "An authoring workspace already exists. Explicitly confirm replacement before discarding its in-memory history/draft."); + workspace = BuildBaseline(configurationIdentifier); + _workspace = workspace; + } + Changed?.Invoke(); + return workspace; + } + + public CalibrationWorkspace ReplaceBaseline(string configurationIdentifier, + string expectedWorkspaceIdentifier, string expectedHeadIdentifier, bool confirmDiscard) + { + CalibrationWorkspace workspace; + lock (_gate) + { + var current = RequireWorkspace(expectedWorkspaceIdentifier); + if (!confirmDiscard) + throw Failure(CalibrationFailure.ReplacementNotConfirmed, "Explicitly confirm that replacement discards the old in-memory history and draft."); + EnsureHead(current, expectedHeadIdentifier); + workspace = BuildBaseline(configurationIdentifier); + _workspace = workspace; + } + Changed?.Invoke(); + return workspace; + } + + public CalibrationVersion Save(CalibrationSaveRequest request) + { + CalibrationVersion version; + lock (_gate) + { + if (request is null) throw Failure(CalibrationFailure.InvalidCommand, "An explicit source/head/candidate request is required."); + var current = RequireWorkspace(request.WorkspaceIdentifier); + if (!current.Definition.Applicability.Matches(request.Source)) + throw Failure(CalibrationFailure.SourceMismatch, "The expected authoring source/configuration/profile/module/model/definition does not match this workspace."); + EnsureHead(current, request.ExpectedHeadIdentifier); + current.Definition.Validate(request.Values); + if (current.Head.Values.ContentEquals(request.Values)) return current.Head; + if (current.History.Count >= MaximumRevisions) + throw Failure(CalibrationFailure.HistoryLimit, "Authoring supports at most 32 saved revisions including baseline. Changed revision 33 was rejected; identical head saves remain no-ops."); + version = new(current.Identifier, current.Definition.Applicability, + current.Head.Revision + 1, current.Head.Identifier, CalibrationVersionKind.Proposed, request.Values); + _workspace = new(current.Identifier, current.Definition, current.Module, [.. current.History, version]); + } + Changed?.Invoke(); + return version; + } + + public CalibrationDiff Compare(string workspaceIdentifier, string fromIdentifier, string toIdentifier) + { + lock (_gate) + { + var current = RequireWorkspace(workspaceIdentifier); + var from = FindVersion(current, fromIdentifier); + var to = FindVersion(current, toIdentifier); + var entries = new List(); + var beforeScalar = from.Values.Scalars[0]; + var afterScalar = to.Values.Scalars[0]; + if (beforeScalar.Value != afterScalar.Value) + entries.Add(new(beforeScalar.LogicalIdentifier, null, null, beforeScalar.Unit, + beforeScalar.Value, afterScalar.Value, afterScalar.Value - beforeScalar.Value)); + var beforeTable = from.Values.Tables[0]; + var afterTable = to.Values.Tables[0]; + for (var index = 0; index < beforeTable.Cells.Count; index++) + { + if (beforeTable.Cells[index] != afterTable.Cells[index]) + entries.Add(new(beforeTable.LogicalIdentifier, beforeTable.Axis[index], beforeTable.AxisUnit, + beforeTable.Unit, beforeTable.Cells[index], afterTable.Cells[index], afterTable.Cells[index] - beforeTable.Cells[index])); + } + return new(current.Identifier, current.Definition.Applicability with { }, from.Identifier, to.Identifier, + Array.AsReadOnly(entries.OrderBy(entry => entry.LogicalIdentifier, StringComparer.Ordinal) + .ThenBy(entry => entry.AxisCoordinate).ToArray())); + } + } + + private CalibrationWorkspace BuildBaseline(string identifier) + { + DynamicsConfiguration configuration; + VehicleProfile profile; + try + { + configuration = configurations.Select(identifier); + profile = profiles.Select(configuration.ProfileIdentifier, configuration.ProfileRevision); + configuration.ValidateAgainst(profile); + } + catch (Exception exception) when (exception is DynamicsConfigurationException or VehicleProfileCatalogException or ArgumentException) + { + throw new CalibrationAuthoringException(CalibrationFailure.SourceNotFound, + $"The exact configuration/profile source could not be resolved: {exception.Message}", exception); + } + var module = profile.Modules.SingleOrDefault(item => + StringComparer.OrdinalIgnoreCase.Equals(item.InstanceIdentifier, configuration.EngineModuleIdentifier)) + ?? throw Failure(CalibrationFailure.SourceNotFound, "The configuration's explicit engine module does not exist in its exact profile revision."); + var applicability = new CalibrationApplicability(configuration.ProfileIdentifier, configuration.ProfileRevision, + configuration.ConfigurationIdentifier, configuration.EngineModuleIdentifier, configuration.ModelIdentifier, + configuration.ModelVersion, SyntheticEngineCalibration.DefinitionIdentifier, 1); + var definition = new SyntheticEngineCalibration(applicability, + new(SyntheticEngineCalibration.ScalarIdentifier, "rpm", configuration.Model.IdleSpeedRpm, configuration.Model.MaximumEngineSpeedRpm), + new(SyntheticEngineCalibration.TableIdentifier, "rpm", "N*m", + configuration.Model.EngineTorqueCurve.Select(point => point.EngineSpeedRpm), 1, 1000)); + var values = new CalibrationValues([new(SyntheticEngineCalibration.ScalarIdentifier, "rpm", configuration.Model.WarmIdleTargetRpm)], + [new(SyntheticEngineCalibration.TableIdentifier, "N*m", "rpm", definition.Table.Axis, + configuration.Model.EngineTorqueCurve.Select(point => point.TorqueNewtonMeters))]); + try { definition.Validate(values); } + catch (CalibrationAuthoringException exception) + { + throw new CalibrationAuthoringException(CalibrationFailure.InvalidDefinition, + $"This valid dynamics source is outside the bounded synthetic authoring template: {exception.Message}", exception); + } + var metadata = new CalibrationModuleMetadata(module.InstanceIdentifier, module.HardwareIdentifier, + module.SoftwareIdentifier, module.FirmwareIdentifier, module.CalibrationIdentifier); + var workspaceIdentifier = Guid.NewGuid().ToString("N"); + return new(workspaceIdentifier, definition, metadata, + [new(workspaceIdentifier, applicability, 1, null, CalibrationVersionKind.Baseline, values)]); + } + + private CalibrationWorkspace RequireWorkspace(string identifier) + { + if (_workspace is null) throw Failure(CalibrationFailure.NoWorkspace, "Explicitly create a synthetic authoring baseline first."); + if (!StringComparer.Ordinal.Equals(_workspace.Identifier, identifier)) + throw Failure(CalibrationFailure.SourceMismatch, "The expected workspace/source was replaced or does not match; no cross-source authoring is allowed."); + return _workspace; + } + private static void EnsureHead(CalibrationWorkspace current, string identifier) + { + if (!StringComparer.Ordinal.Equals(current.Head.Identifier, identifier)) + throw Failure(CalibrationFailure.StaleHead, "The expected head is stale. Cancel/reload the latest draft explicitly before saving; no merge or lost update is allowed."); + } + private static CalibrationVersion FindVersion(CalibrationWorkspace current, string identifier) => + current.History.SingleOrDefault(version => StringComparer.Ordinal.Equals(version.Identifier, identifier)) + ?? throw Failure(CalibrationFailure.VersionNotFound, "The explicitly selected revision does not belong to this workspace/source/definition."); + private static CalibrationAuthoringException Failure(CalibrationFailure failure, string message) => new(failure, message); +} + +public static class CalibrationAuthoringServiceCollectionExtensions +{ + public static IServiceCollection AddAutoForgeCalibrationAuthoring(this IServiceCollection services) + { + services.TryAddSingleton(); + return services; + } +} diff --git a/src/AutoForge.Core/Calibration/SyntheticEngineCalibration.cs b/src/AutoForge.Core/Calibration/SyntheticEngineCalibration.cs new file mode 100644 index 0000000..a27b4ad --- /dev/null +++ b/src/AutoForge.Core/Calibration/SyntheticEngineCalibration.cs @@ -0,0 +1,177 @@ +namespace AutoForge.Core.Calibration; + +public enum CalibrationFailure +{ + NoWorkspace, + SourceNotFound, + SourceMismatch, + InvalidDefinition, + InvalidValues, + WorkspaceExists, + ReplacementNotConfirmed, + StaleHead, + VersionNotFound, + HistoryLimit, + InvalidCommand +} + +public sealed class CalibrationAuthoringException( + CalibrationFailure failure, string message, Exception? innerException = null) : Exception(message, innerException) +{ + public CalibrationFailure Failure { get; } = failure; +} + +public sealed record CalibrationApplicability( + string ProfileIdentifier, + int ProfileRevision, + string ConfigurationIdentifier, + string ModuleIdentifier, + string ModelIdentifier, + int ModelVersion, + string DefinitionIdentifier, + int DefinitionRevision) +{ + public bool Matches(CalibrationApplicability? other) => + other is not null && + StringComparer.OrdinalIgnoreCase.Equals(ProfileIdentifier, other.ProfileIdentifier) && + ProfileRevision == other.ProfileRevision && + StringComparer.Ordinal.Equals(ConfigurationIdentifier, other.ConfigurationIdentifier) && + StringComparer.OrdinalIgnoreCase.Equals(ModuleIdentifier, other.ModuleIdentifier) && + StringComparer.Ordinal.Equals(ModelIdentifier, other.ModelIdentifier) && + ModelVersion == other.ModelVersion && + StringComparer.Ordinal.Equals(DefinitionIdentifier, other.DefinitionIdentifier) && + DefinitionRevision == other.DefinitionRevision; +} + +public sealed record CalibrationScalarDefinition( + string LogicalIdentifier, string Unit, double Minimum, double Maximum, double Scale = 1, double Offset = 0); + +public sealed class CalibrationTableDefinition +{ + public CalibrationTableDefinition(string logicalIdentifier, string axisUnit, string unit, + IEnumerable axis, double minimum, double maximum, double scale = 1, double offset = 0) + { + if (axis is null) throw new CalibrationAuthoringException(CalibrationFailure.InvalidDefinition, "The fixed torque axis is required."); + LogicalIdentifier = logicalIdentifier; + AxisUnit = axisUnit; + Unit = unit; + Axis = Array.AsReadOnly(axis.ToArray()); + Minimum = minimum; + Maximum = maximum; + Scale = scale; + Offset = offset; + } + public string LogicalIdentifier { get; } + public string AxisUnit { get; } + public string Unit { get; } + public IReadOnlyList Axis { get; } + public double Minimum { get; } + public double Maximum { get; } + public double Scale { get; } + public double Offset { get; } +} + +public sealed record CalibrationScalarValue(string LogicalIdentifier, string Unit, double Value); + +public sealed class CalibrationTableValue +{ + public CalibrationTableValue(string logicalIdentifier, string unit, string axisUnit, + IEnumerable axis, IEnumerable cells) + { + if (axis is null || cells is null) + throw new CalibrationAuthoringException(CalibrationFailure.InvalidValues, "The complete torque axis and cells are required."); + LogicalIdentifier = logicalIdentifier; + Unit = unit; + AxisUnit = axisUnit; + Axis = Array.AsReadOnly(axis.ToArray()); + Cells = Array.AsReadOnly(cells.ToArray()); + } + public string LogicalIdentifier { get; } + public string Unit { get; } + public string AxisUnit { get; } + public IReadOnlyList Axis { get; } + public IReadOnlyList Cells { get; } +} + +public sealed class CalibrationValues +{ + public CalibrationValues(IEnumerable scalars, IEnumerable tables) + { + if (scalars is null || tables is null) + throw new CalibrationAuthoringException(CalibrationFailure.InvalidValues, "The complete scalar/table candidate is required."); + var scalarCopy = scalars.ToArray(); + var tableCopy = tables.ToArray(); + if (scalarCopy.Any(value => value is null) || tableCopy.Any(value => value is null)) + throw new CalibrationAuthoringException(CalibrationFailure.InvalidValues, "Calibration values cannot contain null."); + Scalars = Array.AsReadOnly(scalarCopy); + Tables = Array.AsReadOnly(tableCopy.Select(value => new CalibrationTableValue( + value.LogicalIdentifier, value.Unit, value.AxisUnit, value.Axis, value.Cells)).ToArray()); + } + public IReadOnlyList Scalars { get; } + public IReadOnlyList Tables { get; } + + public bool ContentEquals(CalibrationValues other) => + Scalars.SequenceEqual(other.Scalars) && + Tables.Count == other.Tables.Count && + Tables.Zip(other.Tables).All(pair => + pair.First.LogicalIdentifier == pair.Second.LogicalIdentifier && + pair.First.Unit == pair.Second.Unit && pair.First.AxisUnit == pair.Second.AxisUnit && + pair.First.Axis.SequenceEqual(pair.Second.Axis) && pair.First.Cells.SequenceEqual(pair.Second.Cells)); +} + +public sealed class SyntheticEngineCalibration +{ + public const string DefinitionIdentifier = "autoforge.synthetic.engine-authoring"; + public const string ModelIdentifier = "autoforge.synthetic.longitudinal"; + public const string ScalarIdentifier = "engine.warm-idle-target"; + public const string TableIdentifier = "engine.torque-curve"; + + public SyntheticEngineCalibration(CalibrationApplicability applicability, + CalibrationScalarDefinition scalar, CalibrationTableDefinition table) + { + if (applicability is null || scalar is null || table is null) + throw InvalidDefinition("Explicit applicability and the scalar/table definition are required."); + if (!IsIdentifier(applicability.ProfileIdentifier) || applicability.ProfileRevision <= 0 || + !IsIdentifier(applicability.ModuleIdentifier) || !IsIdentifier(applicability.ConfigurationIdentifier) || + applicability.ModelIdentifier != ModelIdentifier || applicability.ModelVersion != 1 || + applicability.DefinitionIdentifier != DefinitionIdentifier || applicability.DefinitionRevision != 1) + throw InvalidDefinition("The synthetic authoring definition requires exact configuration/profile/module/model/definition applicability."); + if (scalar.LogicalIdentifier != ScalarIdentifier || scalar.Unit != "rpm" || + !double.IsFinite(scalar.Minimum) || !double.IsFinite(scalar.Maximum) || + scalar.Minimum < 0 || scalar.Maximum <= scalar.Minimum || scalar.Scale != 1 || scalar.Offset != 0) + throw InvalidDefinition("Warm-idle definition must have the exact key/rpm unit, finite ordered bounds and identity scaling."); + if (table.LogicalIdentifier != TableIdentifier || table.Unit != "N*m" || table.AxisUnit != "rpm" || + table.Minimum != 1 || table.Maximum != 1000 || table.Scale != 1 || table.Offset != 0 || + table.Axis.Count is < 2 or > 32 || + table.Axis.Any(value => !double.IsFinite(value) || value < 0 || value > scalar.Maximum) || + table.Axis.Zip(table.Axis.Skip(1), (left, right) => left < right).Any(ordered => !ordered)) + throw InvalidDefinition("Torque definition requires 2..32 fixed, finite, strictly increasing rpm rows within engine limits, N*m cells in [1,1000], and identity scaling."); + Applicability = applicability with { }; + Scalar = scalar with { }; + Table = new(table.LogicalIdentifier, table.AxisUnit, table.Unit, table.Axis, table.Minimum, table.Maximum, table.Scale, table.Offset); + } + public CalibrationApplicability Applicability { get; } + public CalibrationScalarDefinition Scalar { get; } + public CalibrationTableDefinition Table { get; } + + public void Validate(CalibrationValues values) + { + if (values is null || values.Scalars.Count != 1 || values.Tables.Count != 1) + throw InvalidValues("Supply exactly the required warm-idle scalar and torque table; unknown or missing keys are not supported."); + var scalar = values.Scalars[0]; + if (scalar.LogicalIdentifier != Scalar.LogicalIdentifier || scalar.Unit != Scalar.Unit || + !InRange(scalar.Value, Scalar.Minimum, Scalar.Maximum)) + throw InvalidValues($"Warm-idle '{ScalarIdentifier}' must use exact rpm units and a finite value in [{Scalar.Minimum},{Scalar.Maximum}] rpm."); + var table = values.Tables[0]; + if (table.LogicalIdentifier != Table.LogicalIdentifier || table.Unit != Table.Unit || + table.AxisUnit != Table.AxisUnit || !table.Axis.SequenceEqual(Table.Axis) || + table.Cells.Count != Table.Axis.Count || table.Cells.Any(value => !InRange(value, Table.Minimum, Table.Maximum))) + throw InvalidValues("Torque must use the exact key, source N*m/rpm units, unchanged ordered axis and complete finite cells in [1,1000] N*m."); + } + private static bool InRange(double value, double minimum, double maximum) => + double.IsFinite(value) && value >= minimum && value <= maximum; + private static bool IsIdentifier(string value) => + !string.IsNullOrWhiteSpace(value) && StringComparer.Ordinal.Equals(value, value.Trim()); + private static CalibrationAuthoringException InvalidDefinition(string message) => new(CalibrationFailure.InvalidDefinition, message); + private static CalibrationAuthoringException InvalidValues(string message) => new(CalibrationFailure.InvalidValues, message); +} diff --git a/src/AutoForge.UI/Features/Foundation/AddAutoForgeUi.cs b/src/AutoForge.UI/Features/Foundation/AddAutoForgeUi.cs index 757b68a..ef4be4d 100644 --- a/src/AutoForge.UI/Features/Foundation/AddAutoForgeUi.cs +++ b/src/AutoForge.UI/Features/Foundation/AddAutoForgeUi.cs @@ -7,6 +7,7 @@ using AutoForge.Application.Features.Vehicles.Telemetry.LiveDashboard; using AutoForge.Application.Features.Vehicles.Telemetry.Recording; using AutoForge.Application.Features.Vehicles.Telemetry.Replay; using AutoForge.Application.Features.DisplayUnits; +using AutoForge.Application.Features.Vehicles.Calibration; using Microsoft.Extensions.DependencyInjection; namespace AutoForge.UI; @@ -22,6 +23,7 @@ public static class ServiceCollectionExtensions services.AddAutoForgeDisplayUnits(); services.AddAutoForgeTelemetryRecordingFallback(); services.AddAutoForgeTelemetryReplay(); + services.AddAutoForgeCalibrationAuthoring(); services.AddScoped(); services.AddScoped(); services.AddScoped(); diff --git a/src/AutoForge.UI/Features/Foundation/Home.razor b/src/AutoForge.UI/Features/Foundation/Home.razor index a87c615..d64175a 100644 --- a/src/AutoForge.UI/Features/Foundation/Home.razor +++ b/src/AutoForge.UI/Features/Foundation/Home.razor @@ -16,4 +16,5 @@ Open synthetic diagnostics Open vehicle simulation Replay saved telemetry offline (recorded, not live) + Author synthetic calibration proposals (not applied)

diff --git a/src/AutoForge.UI/Features/Vehicles/Calibration/CalibrationPage.razor b/src/AutoForge.UI/Features/Vehicles/Calibration/CalibrationPage.razor new file mode 100644 index 0000000..531e47e --- /dev/null +++ b/src/AutoForge.UI/Features/Vehicles/Calibration/CalibrationPage.razor @@ -0,0 +1,319 @@ +@page "/calibration" +@using AutoForge.Application.Features.Vehicles.Calibration +@using AutoForge.Application.Features.Vehicles.Simulation +@using AutoForge.Core.Calibration +@implements IDisposable +@inject CalibrationAuthoringService Authoring +@inject IDynamicsConfigurationService Configurations + +Synthetic calibration authoring +

Synthetic calibration authoring

+

+ Process-memory proposals only. This is not an ECU read, verified backup, Tested/Approved calibration, + programming or model application. Restart loses saved authoring history; leaving this page loses its unsaved draft. +

+

Explicitly create/import a warm dynamics configuration. No configuration or workspace is seeded here.

+ +
+ + + + @if (Authoring.Snapshot is not null) + { + + + } +
+ +@if (_error is not null) +{ + +} +@if (_status is not null) +{ +

@_status

+} + +@if (Authoring.Snapshot is { } workspace) +{ + var source = workspace.Definition.Applicability; +
+

Exact source binding

+

+ Workspace @workspace.Identifier; profile @source.ProfileIdentifier revision @source.ProfileRevision; + configuration @source.ConfigurationIdentifier; explicit module @source.ModuleIdentifier; + model @source.ModelIdentifier v@(source.ModelVersion); + definition @source.DefinitionIdentifier revision @source.DefinitionRevision. +

+

+ Supplied module metadata only: hardware @(workspace.Module.HardwareIdentifier ?? "unknown"); + software @(workspace.Module.SoftwareIdentifier ?? "unknown"); firmware @(workspace.Module.FirmwareIdentifier ?? "unknown"); + calibration reference @(workspace.Module.CalibrationIdentifier ?? "unknown"). Not verified identity or applicability proof. +

+

History @workspace.History.Count / 32 including baseline. Current editable head revision @workspace.Head.Revision / @workspace.Head.Identifier.

+

+ Synthetic constraints, not manufacturer-safe limits: warm idle + @Exact(workspace.Definition.Scalar.Minimum)..@Exact(workspace.Definition.Scalar.Maximum) rpm; + torque 1..1000 N*m; 2..32 fixed rpm axis rows. Identity scaling: 1, offset 0; no binary encoding. +

+
+ @if (_draftWorkspace is { } draft) + { +
+

Proposal draft (validate before commit)

+

+ Expected workspace @draft.Identifier; expected head revision @draft.Head.Revision / @draft.Head.Identifier. + Source @draft.Definition.Applicability.ConfigurationIdentifier. +

+ @if (draft.Identifier != workspace.Identifier || draft.Head.Identifier != workspace.Head.Identifier) + { +

This draft's source/head is stale. Cancel/reload latest explicitly; saving never merges or overwrites a newer proposal.

+ } +

+ Draft input pinned to @_draftUnits.UnitSystem / @_draftUnits.SpeedMode: + torque in @TorqueUnit; axis and idle in rpm. Global unit changes do not reinterpret unsaved fields. + Canonical source remains N*m/rpm; unchanged fields retain exact source doubles. +

+ + + + + + + @for (var index = 0; index < draft.Definition.Table.Axis.Count; index++) + { + var cell = index; + + + + + + } + +
engine.torque-curve - fixed source axis and editable draft cells
Axis (rpm, read-only)Torque draft (@TorqueUnit)Saved head source (N*m)
@Exact(draft.Definition.Table.Axis[cell]) rpm + + + @Exact(draft.Head.Values.Tables[0].Cells[cell]) N*m
+ + +
+ } +
+

Baseline and Proposed history

+ + + @if (_inspection is { } inspection) + { +

@inspection.Label; revision @inspection.Revision / @inspection.Identifier; parent @(inspection.ParentIdentifier ?? "none (baseline)"). Read-only.

+

Saved source scalar: @Exact(inspection.Values.Scalars[0].Value) rpm.

+ + + + + @for (var index = 0; index < inspection.Values.Tables[0].Cells.Count; index++) + { + var value = inspection.Values.Tables[0].Cells[index]; + var display = DisplayUnitConverter.Project(value, "N*m", DisplaySelection); + + } + +
Read-only saved torque cells; display precision is presentation only
Fixed axisCanonical sourceDisplay
@Exact(inspection.Values.Tables[0].Axis[index]) rpm@Exact(value) N*m@DisplayUnitConverter.Format(display, 3) @display.Unit
+ } +
+
+

Exact canonical diff

+ + + + + + @if (_diff is { } diff) + { +

Compared workspace @diff.WorkspaceIdentifier; source @diff.Source.ConfigurationIdentifier; @diff.FromIdentifier to @diff.ToIdentifier.

+ @if (diff.Entries.Count == 0) + { +

No canonical changes between these explicitly selected versions. This does not restore or verify a device.

+ } + else + { +
    + @foreach (var entry in diff.Entries) + { +
  • + @entry.LogicalIdentifier: + @if (entry.AxisCoordinate is { } axis) + { + at @Exact(axis) @entry.AxisUnit: + } + @Exact(entry.Before) -> @Exact(entry.After) @entry.Unit; signed delta @Signed(entry.Delta) @entry.Unit. +
  • + } +
+ } + } +
+} + +@code { + [CascadingParameter] + public DisplayUnitSelection DisplaySelection { get; set; } = DisplayUnitSelection.Default; + private string _selectedConfiguration = string.Empty; + private CalibrationWorkspace? _draftWorkspace; + private DisplayUnitSelection _draftUnits = DisplayUnitSelection.Default; + private string _scalarText = string.Empty; + private string _originalScalarText = string.Empty; + private string[] _torqueText = []; + private string[] _originalTorqueText = []; + private string _inspectIdentifier = string.Empty; + private string _fromIdentifier = string.Empty; + private string _toIdentifier = string.Empty; + private CalibrationVersion? _inspection; + private CalibrationDiff? _diff; + private string? _error; + private string? _status; + private bool _confirmDiscard; + private bool _disposed; + private string TorqueUnit => DisplayUnitConverter.Project(0, "N*m", _draftUnits).Unit; + + protected override void OnInitialized() + { + Authoring.Changed += OnChanged; + if (Authoring.Snapshot is { } workspace) LoadDraft(workspace); + } + + private void CreateBaseline() => Run(() => LoadDraft(Authoring.CreateBaseline(_selectedConfiguration))); + private void ReplaceBaseline() => Run(() => + { + var expected = RequireDraft(); + LoadDraft(Authoring.ReplaceBaseline(_selectedConfiguration, expected.Identifier, expected.Head.Identifier, _confirmDiscard)); + _confirmDiscard = false; + }); + + private void Save() => Run(() => + { + var draft = RequireDraft(); + var scalar = _scalarText == _originalScalarText ? draft.Head.Values.Scalars[0].Value : ParseFinite(_scalarText, "Warm idle"); + var cells = new double[_torqueText.Length]; + for (var index = 0; index < cells.Length; index++) + { + cells[index] = _torqueText[index] == _originalTorqueText[index] + ? draft.Head.Values.Tables[0].Cells[index] + : DisplayUnitConverter.ConvertToSource(ParseFinite(_torqueText[index], $"Torque row {index + 1}"), "N*m", _draftUnits); + } + var values = new CalibrationValues([new(SyntheticEngineCalibration.ScalarIdentifier, "rpm", scalar)], + [new(SyntheticEngineCalibration.TableIdentifier, "N*m", "rpm", draft.Definition.Table.Axis, cells)]); + var source = draft.Definition.Applicability with { ConfigurationIdentifier = _selectedConfiguration }; + var saved = Authoring.Save(new(draft.Identifier, draft.Head.Identifier, source, values)); + var noChange = saved.Identifier == draft.Head.Identifier; + LoadDraft(Authoring.Snapshot!); + _status = noChange ? $"Identical head: revision {saved.Revision} retained; no history capacity consumed." + : $"Saved Proposed revision {saved.Revision} against parent {saved.ParentIdentifier}. No model or module was changed."; + }); + + private void CancelDraft() => Run(() => + { + var current = Authoring.Snapshot ?? throw new CalibrationAuthoringException(CalibrationFailure.NoWorkspace, "Create a baseline before editing."); + LoadDraft(current); + _status = "Draft cancelled; latest head loaded explicitly."; + }); + + private void Inspect() => Run(() => + { + var workspace = Authoring.Snapshot!; + Authoring.Compare(workspace.Identifier, _inspectIdentifier, _inspectIdentifier); + _inspection = workspace.History.Single(version => version.Identifier == _inspectIdentifier); + }); + private void Compare() => Run(() => + { + var workspace = Authoring.Snapshot!; + _diff = Authoring.Compare(workspace.Identifier, _fromIdentifier, _toIdentifier); + }); + + private void LoadDraft(CalibrationWorkspace workspace) + { + var scalarText = Exact(workspace.Head.Values.Scalars[0].Value); + var torqueText = workspace.Head.Values.Tables[0].Cells.Select(value => + { + var projected = DisplayUnitConverter.Project(value, "N*m", DisplaySelection); + if (!projected.IsAvailable) throw new DisplayUnitConversionException(projected.Error ?? "Torque display conversion unavailable."); + return Exact(projected.Value!.Value); + }).ToArray(); + _draftWorkspace = workspace; + _selectedConfiguration = workspace.Definition.Applicability.ConfigurationIdentifier; + _draftUnits = DisplaySelection; + _scalarText = scalarText; + _originalScalarText = scalarText; + _torqueText = torqueText; + _originalTorqueText = torqueText.ToArray(); + _inspectIdentifier = workspace.Head.Identifier; + _inspection = workspace.Head; + _fromIdentifier = workspace.Baseline.Identifier; + _toIdentifier = workspace.Head.Identifier; + _diff = null; + _status = $"Loaded immutable head revision {workspace.Head.Revision}; authoring only."; + } + + private CalibrationWorkspace RequireDraft() => _draftWorkspace ?? + throw new CalibrationAuthoringException(CalibrationFailure.NoWorkspace, "Explicitly create a baseline before saving/replacing a draft."); + + private void Run(Action action) + { + try { action(); _error = null; } + catch (Exception exception) when (exception is CalibrationAuthoringException or DisplayUnitConversionException) + { + _error = exception.Message; + _status = null; + } + } + private static double ParseFinite(string text, string field) + { + if (!double.TryParse(text, NumberStyles.Float, CultureInfo.InvariantCulture, out var value) || !double.IsFinite(value)) + throw new CalibrationAuthoringException(CalibrationFailure.InvalidValues, $"{field} must be a finite numeric value; the complete proposal was not saved."); + return value; + } + private static string Exact(double value) => value.ToString("R", CultureInfo.InvariantCulture); + private static string Signed(double value) => value > 0 ? $"+{Exact(value)}" : Exact(value); + private void OnChanged() + { + if (_disposed) return; + _ = InvokeAsync(() => + { + if (_disposed) return; + if (_inspection is not null && Authoring.Snapshot?.History.All(version => version.Identifier != _inspection.Identifier) == true) + { + _inspection = null; + _diff = null; + } + StateHasChanged(); + }); + } + public void Dispose() + { + _disposed = true; + Authoring.Changed -= OnChanged; + } +} diff --git a/src/AutoForge.UI/Layout/MainLayout.razor b/src/AutoForge.UI/Layout/MainLayout.razor index 89e10c6..e8428de 100644 --- a/src/AutoForge.UI/Layout/MainLayout.razor +++ b/src/AutoForge.UI/Layout/MainLayout.razor @@ -12,6 +12,7 @@ Synthetic diagnostics Vehicle simulation Recorded telemetry replay + Synthetic calibration authoring
diff --git a/src/tests/AutoForge.IntegrationTests/CalibrationAuthoringCoexistenceTests.cs b/src/tests/AutoForge.IntegrationTests/CalibrationAuthoringCoexistenceTests.cs new file mode 100644 index 0000000..5760a1b --- /dev/null +++ b/src/tests/AutoForge.IntegrationTests/CalibrationAuthoringCoexistenceTests.cs @@ -0,0 +1,134 @@ +using AutoForge.Application.Features.DisplayUnits; +using AutoForge.Application.Features.Vehicles.Calibration; +using AutoForge.Application.Features.Vehicles.Diagnostics; +using AutoForge.Application.Features.Vehicles.Profiles; +using AutoForge.Application.Features.Vehicles.Simulation; +using AutoForge.Application.Features.Vehicles.Telemetry.Recording; +using AutoForge.Application.Features.Vehicles.Telemetry.Replay; +using AutoForge.Core.ExecutionTargets; +using AutoForge.Core.Simulation; +using AutoForge.Core.Vehicles; +using AutoForge.Diagnostics; +using AutoForge.Simulation; +using AutoForge.UI; +using Microsoft.Extensions.DependencyInjection; + +namespace AutoForge.IntegrationTests; + +public sealed partial class CalibrationAuthoringTests +{ + [Fact] + public async Task AuthoringWithActualLiveSourceRecordingAndReplay_AddsZeroTransportModelOrStoreSaveCalls() + { + var directory = Path.Combine(Path.GetTempPath(), $"autoforge-step09-{Guid.NewGuid():N}"); + Directory.CreateDirectory(directory); + try + { + var counts = new SideEffectCounts(); + var store = new CountingCalibrationStore(new FileTelemetryArchiveStore(directory), counts); + var services = new ServiceCollection(); + services.AddLogging(); + services.AddAutoForgeVehicleProfiles(); + services.AddAutoForgeDiagnostics([new CountingCalibrationDynamicsFactory( + new DynamicsDiagnosticTransportFactory(SyntheticDiagnosticExamples.CreateDefinitions()), counts)]); + services.AddAutoForgeUi(); + services.AddSingleton(store); + services.AddSingleton(); + using var provider = services.BuildServiceProvider(); + var warm = CreateWarm(provider); + var configurations = provider.GetRequiredService(); + var export = configurations.Export(warm.ConfigurationIdentifier); + var profileExport = provider.GetRequiredService().Export(ProfileId, 1); + await using var live = await provider.GetRequiredService().OpenDynamicsAsync( + ProfileId, 1, DynamicsDiagnosticTransportFactory.ProviderIdentifier, ExecutionTargetKind.Simulation, warm); + await live.DynamicsControl!.StepAsync(7); + var recording = provider.GetRequiredService(); + recording.Start(live); + Assert.True((await live.ReadSignalsAsync(live.ExpectedEndpoints.Single(item => item.ModuleIdentifier == EngineId))).IsSuccess); + recording.Stop(); + Assert.True(await recording.SaveAsync(false)); + var capture = recording.CurrentCapture!; + var bytes = await File.ReadAllBytesAsync(Path.Combine(directory, capture.Header.CaptureId + ".json")); + await using var player = provider.GetRequiredService().Create(); + await player.LoadAsync(capture.Header.CaptureId); + player.SeekOrdinal(1); + var replayBefore = player.Snapshot; + var captureBefore = TelemetryArchiveCodec.Serialize(capture); + var runBefore = live.DynamicsControl.Status; + var traceBefore = live.Trace.Entries.ToArray(); + var countsBefore = (counts.Transport, counts.Model, counts.Save); + var authoring = provider.GetRequiredService(); + var baseline = authoring.CreateBaseline(warm.ConfigurationIdentifier); + var first = authoring.Save(Request(baseline, Values(baseline, scalar: 1250))); + var torque = ExpectedTorque.ToArray(); + torque[2] = 350; + var second = authoring.Save(Request(authoring.Snapshot!, Values(authoring.Snapshot!, torque: torque))); + Assert.Equal(2, authoring.Compare(baseline.Identifier, baseline.Head.Identifier, second.Identifier).Entries.Count); + var preference = provider.GetRequiredService(); + Assert.True(preference.TrySet(new(DisplayUnitSystem.Metric, SpeedDisplayMode.Road))); + Assert.True(preference.TrySet(DisplayUnitSelection.Default)); + Assert.Equal(countsBefore, (counts.Transport, counts.Model, counts.Save)); + Assert.Same(replayBefore, player.Snapshot); + Assert.Equal(captureBefore, TelemetryArchiveCodec.Serialize(recording.CurrentCapture!)); + Assert.Equal(runBefore, live.DynamicsControl.Status); + Assert.Equal(traceBefore, live.Trace.Entries); + Assert.Equal(export, configurations.Export(warm.ConfigurationIdentifier)); + Assert.Equal(profileExport, provider.GetRequiredService().Export(ProfileId, 1)); + Assert.Equal(bytes, await File.ReadAllBytesAsync(Path.Combine(directory, capture.Header.CaptureId + ".json"))); + Assert.Equal(650, warm.Model.WarmIdleTargetRpm); + Assert.Equal(360, warm.Model.EngineTorqueCurve[2].TorqueNewtonMeters); + Assert.Equal(1250, first.Values.Scalars[0].Value); + } + finally + { + Directory.Delete(directory, recursive: true); + } + } + + private sealed class SideEffectCounts + { + public int Transport { get; set; } + public int Model { get; set; } + public int Save { get; set; } + } + private sealed class CountingCalibrationStore(ITelemetryArchiveStore inner, SideEffectCounts count) : ITelemetryArchiveStore + { + public Task SaveAsync(TelemetryCaptureSnapshot capture, CancellationToken cancellationToken = default) + { count.Save++; return inner.SaveAsync(capture, cancellationToken); } + public Task LoadAsync(string captureId, CancellationToken cancellationToken = default) => inner.LoadAsync(captureId, cancellationToken); + public Task> ListAsync(CancellationToken cancellationToken = default) => inner.ListAsync(cancellationToken); + } + private sealed class CountingCalibrationDynamicsFactory(IDynamicsDiagnosticTransportFactory inner, SideEffectCounts count) : IDynamicsDiagnosticTransportFactory + { + public DiagnosticProviderDescriptor Descriptor => inner.Descriptor; + public IDiagnosticTransport OpenTransport(VehicleProfile profile, DiagnosticSessionIdentity identity) => + throw new InvalidOperationException("Explicit dynamics configuration is required."); + public DynamicsSessionBinding OpenDynamicsTransport(VehicleProfile profile, DiagnosticSessionIdentity identity, DynamicsConfiguration configuration) + { + var binding = inner.OpenDynamicsTransport(profile, identity, configuration); + return new(new CountingCalibrationTransport(binding.Transport, count), new CountingCalibrationControl(binding.Control, count)); + } + } + private sealed class CountingCalibrationTransport(IDiagnosticTransport inner, SideEffectCounts count) : IDiagnosticTransport + { + public IReadOnlyList ExpectedEndpoints => inner.ExpectedEndpoints; + public ValueTask SendAsync(ReadOnlyMemory request, CancellationToken cancellationToken) + { count.Transport++; return inner.SendAsync(request, cancellationToken); } + public ValueTask DisposeAsync() => inner.DisposeAsync(); + } + private sealed class CountingCalibrationControl(IDynamicsControl inner, SideEffectCounts count) : IDynamicsControl + { + public DynamicsRunStatus Status => inner.Status; + public double PacingFactor => inner.PacingFactor; + private Task Invoke(Func> action) { count.Model++; return action(); } + public Task StartAsync(CancellationToken cancellationToken = default) => Invoke(() => inner.StartAsync(cancellationToken)); + public Task PauseAsync(CancellationToken cancellationToken = default) => Invoke(() => inner.PauseAsync(cancellationToken)); + public Task ResumeAsync(CancellationToken cancellationToken = default) => Invoke(() => inner.ResumeAsync(cancellationToken)); + public Task StopAsync(CancellationToken cancellationToken = default) => Invoke(() => inner.StopAsync(cancellationToken)); + public Task ResetAsync(CancellationToken cancellationToken = default) => Invoke(() => inner.ResetAsync(cancellationToken)); + public Task StepAsync(int stepCount = 1, CancellationToken cancellationToken = default) => Invoke(() => inner.StepAsync(stepCount, cancellationToken)); + public Task SetPacingFactorAsync(double factor, CancellationToken cancellationToken = default) => Invoke(() => inner.SetPacingFactorAsync(factor, cancellationToken)); + public Task RunScenarioAsync(CancellationToken cancellationToken = default) => Invoke(() => inner.RunScenarioAsync(cancellationToken)); + public ValueTask DisposeAsync() => inner.DisposeAsync(); + } +} diff --git a/src/tests/AutoForge.IntegrationTests/CalibrationAuthoringTests.cs b/src/tests/AutoForge.IntegrationTests/CalibrationAuthoringTests.cs new file mode 100644 index 0000000..7935745 --- /dev/null +++ b/src/tests/AutoForge.IntegrationTests/CalibrationAuthoringTests.cs @@ -0,0 +1,561 @@ +using System.Text.Json.Nodes; +using AutoForge.Application.Features.Vehicles.Calibration; +using AutoForge.Application.Features.Vehicles.Profiles; +using AutoForge.Application.Features.Vehicles.Simulation; +using AutoForge.Core.Calibration; +using AutoForge.Core.Simulation; +using AutoForge.UI; +using Microsoft.Extensions.DependencyInjection; + +namespace AutoForge.IntegrationTests; + +public sealed partial class CalibrationAuthoringTests +{ + private const string ProfileId = "autoforge.synthetic.test-truck"; + private const string EngineId = "module.engine.primary"; + private const string ScalarId = "engine.warm-idle-target"; + private const string TableId = "engine.torque-curve"; + private static readonly double[] ExpectedAxis = [650, 1000, 2000, 3200, 4200, 5000]; + private static readonly double[] ExpectedTorque = [240, 300, 360, 350, 300, 180]; + + [Fact] + public void ExplicitBaseline_UsesExactConfigurationAndActualModuleWithoutRoleFallback() + { + using var provider = CreateProvider(); + var configurations = provider.GetRequiredService(); + var warm = CreateWarm(provider); + var export = configurations.Export(warm.ConfigurationIdentifier); + var service = provider.GetRequiredService(); + Assert.Null(service.Snapshot); + var workspace = service.CreateBaseline(warm.ConfigurationIdentifier); + var source = workspace.Definition.Applicability; + Assert.Equal(warm.ConfigurationIdentifier, source.ConfigurationIdentifier); + Assert.Equal(ProfileId, source.ProfileIdentifier); + Assert.Equal(1, source.ProfileRevision); + Assert.Equal(EngineId, source.ModuleIdentifier); + Assert.Equal(warm.ModelIdentifier, source.ModelIdentifier); + Assert.Equal(1, source.ModelVersion); + Assert.Equal(SyntheticEngineCalibration.DefinitionIdentifier, source.DefinitionIdentifier); + Assert.Equal(1, source.DefinitionRevision); + Assert.Equal("hardware.synthetic.engine-a", workspace.Module.HardwareIdentifier); + Assert.Null(workspace.Module.FirmwareIdentifier); + Assert.Equal("calibration.synthetic.engine-base", workspace.Module.CalibrationIdentifier); + Assert.Equal(650, workspace.Head.Values.Scalars.Single().Value); + Assert.Equal(ExpectedAxis, workspace.Head.Values.Tables.Single().Axis); + Assert.Equal(ExpectedTorque, workspace.Head.Values.Tables.Single().Cells); + Assert.Equal(650, workspace.Definition.Scalar.Minimum); + Assert.Equal(5000, workspace.Definition.Scalar.Maximum); + Assert.Equal(1, workspace.Definition.Table.Minimum); + Assert.Equal(1000, workspace.Definition.Table.Maximum); + Assert.Equal(1, workspace.Definition.Scalar.Scale); + Assert.Equal(0, workspace.Definition.Scalar.Offset); + Assert.Equal(CalibrationVersionKind.Baseline, workspace.Head.Kind); + Assert.Equal(1, workspace.Head.Revision); + Assert.Null(workspace.Head.ParentIdentifier); + Assert.Contains("Synthetic configuration-derived baseline", workspace.Head.Label); + Assert.Equal(export, configurations.Export(warm.ConfigurationIdentifier)); + + var alternative = ImportVariant(provider, document => + { + document["engineModuleIdentifier"] = "module.cabin.body"; + document["engineCalibrationReference"] = null; + }); + var changed = service.ReplaceBaseline(alternative.ConfigurationIdentifier, + workspace.Identifier, workspace.Head.Identifier, confirmDiscard: true); + Assert.Equal("module.cabin.body", changed.Definition.Applicability.ModuleIdentifier); + Assert.Equal("hardware.synthetic.body", changed.Module.HardwareIdentifier); + Assert.Null(changed.Module.CalibrationIdentifier); + } + + [Fact] + public void ScalarThenTableProposals_HaveExactLinearParentsAndStructuredDiffs() + { + using var provider = CreateProvider(); + var warm = CreateWarm(provider); + var service = provider.GetRequiredService(); + var baseline = service.CreateBaseline(warm.ConfigurationIdentifier); + var first = service.Save(Request(baseline, Values(baseline, scalar: 1250))); + Assert.Equal(CalibrationVersionKind.Proposed, first.Kind); + Assert.Equal(2, first.Revision); + Assert.Equal(baseline.Head.Identifier, first.ParentIdentifier); + Assert.Equal(baseline.Identifier, first.WorkspaceIdentifier); + Assert.Equal(baseline.Definition.Applicability, first.Source); + Assert.NotEqual(baseline.Head.Identifier, first.Identifier); + Assert.Equal(650, baseline.Head.Values.Scalars[0].Value); + Assert.Equal(650, warm.Model.WarmIdleTargetRpm); + var scalar = Assert.Single(service.Compare(baseline.Identifier, baseline.Head.Identifier, first.Identifier).Entries); + Assert.Equal(ScalarId, scalar.LogicalIdentifier); + Assert.Null(scalar.AxisCoordinate); + Assert.Equal("rpm", scalar.Unit); + Assert.Equal(650, scalar.Before); + Assert.Equal(1250, scalar.After); + Assert.Equal(600, scalar.Delta); + var current = service.Snapshot!; + var cells = ExpectedTorque.ToArray(); + cells[2] = 350; + var second = service.Save(Request(current, Values(current, torque: cells))); + Assert.Equal(first.Identifier, second.ParentIdentifier); + Assert.Equal(3, second.Revision); + var diff = service.Compare(baseline.Identifier, baseline.Head.Identifier, second.Identifier); + Assert.Equal(2, diff.Entries.Count); + Assert.Equal([TableId, ScalarId], diff.Entries.Select(entry => entry.LogicalIdentifier)); + var torque = diff.Entries.Single(entry => entry.LogicalIdentifier == TableId); + Assert.Equal(2000, torque.AxisCoordinate); + Assert.Equal("rpm", torque.AxisUnit); + Assert.Equal("N*m", torque.Unit); + Assert.Equal(360, torque.Before); + Assert.Equal(350, torque.After); + Assert.Equal(-10, torque.Delta); + var preceding = Assert.Single(service.Compare(baseline.Identifier, first.Identifier, second.Identifier).Entries); + Assert.Equal(torque, preceding); + Assert.Equal(350, service.Snapshot!.Head.Values.Tables[0].Cells[2]); + Assert.Equal(360, warm.Model.EngineTorqueCurve[2].TorqueNewtonMeters); + } + + [Fact] + public void NoOpBoundsChangedBackAndTinyDiff_AreExactNotRoundedOrClipped() + { + using var provider = CreateProvider(); + var warm = CreateWarm(provider); + var service = provider.GetRequiredService(); + var baseline = service.CreateBaseline(warm.ConfigurationIdentifier); + Assert.Same(baseline.Head, service.Save(Request(baseline, baseline.Head.Values))); + Assert.Single(service.Snapshot!.History); + var cells = ExpectedTorque.ToArray(); + cells[0] = 1; + cells[^1] = 1000; + var high = service.Save(Request(baseline, Values(baseline, scalar: 5000, torque: cells))); + Assert.Equal(5000, high.Values.Scalars[0].Value); + var back = service.Save(Request(service.Snapshot!, baseline.Head.Values)); + Assert.Equal(CalibrationVersionKind.Proposed, back.Kind); + Assert.Equal(3, back.Revision); + Assert.Equal(high.Identifier, back.ParentIdentifier); + Assert.Empty(service.Compare(baseline.Identifier, baseline.Head.Identifier, back.Identifier).Entries); + var tiny = double.BitIncrement(650); + var last = service.Save(Request(service.Snapshot!, Values(baseline, scalar: tiny))); + var diff = Assert.Single(service.Compare(baseline.Identifier, back.Identifier, last.Identifier).Entries); + Assert.Equal(tiny, diff.After); + Assert.Equal(tiny - 650, diff.Delta); + Assert.NotEqual(0, diff.Delta); + } + + [Theory] + [InlineData(double.NaN)] + [InlineData(double.PositiveInfinity)] + [InlineData(double.NegativeInfinity)] + [InlineData(649.999)] + [InlineData(5000.001)] + public void InvalidScalar_RejectsBeforeHeadHistorySourceOrCapacityMutation(double scalar) + { + using var provider = CreateProvider(); + var configuration = CreateWarm(provider); + var service = provider.GetRequiredService(); + var before = service.CreateBaseline(configuration.ConfigurationIdentifier); + AssertRejected(service, () => service.Save(Request(before, Values(before, scalar))), CalibrationFailure.InvalidValues); + Assert.Equal(650, configuration.Model.WarmIdleTargetRpm); + } + + [Theory] + [InlineData(double.NaN)] + [InlineData(double.PositiveInfinity)] + [InlineData(double.NegativeInfinity)] + [InlineData(0.999)] + [InlineData(1000.001)] + public void InvalidTorqueCell_RejectsTheEntireCandidateIncludingValidScalarEdit(double torque) + { + using var provider = CreateProvider(); + var warm = CreateWarm(provider); + var service = provider.GetRequiredService(); + var before = service.CreateBaseline(warm.ConfigurationIdentifier); + var cells = ExpectedTorque.ToArray(); + cells[2] = torque; + AssertRejected(service, () => service.Save(Request(before, Values(before, 1250, cells))), CalibrationFailure.InvalidValues); + Assert.Equal(650, service.Snapshot!.Head.Values.Scalars[0].Value); + } + + [Theory] + [InlineData("missing-scalar")] + [InlineData("extra-scalar")] + [InlineData("wrong-scalar-key")] + [InlineData("wrong-scalar-unit")] + [InlineData("missing-table")] + [InlineData("extra-table")] + [InlineData("wrong-table-key")] + [InlineData("wrong-table-unit")] + [InlineData("wrong-axis-unit")] + [InlineData("changed-axis")] + [InlineData("reversed-axis")] + [InlineData("missing-cell")] + [InlineData("extra-cell")] + public void WrongCandidateShapeUnitsKeysAndAxes_RejectWithoutNormalization(string vector) + { + using var provider = CreateProvider(); + var service = provider.GetRequiredService(); + var before = service.CreateBaseline(CreateWarm(provider).ConfigurationIdentifier); + var scalars = new[] { new CalibrationScalarValue(ScalarId, "rpm", 1250) }; + var axis = ExpectedAxis.ToArray(); + var cells = ExpectedTorque.ToArray(); + var tableId = TableId; + var tableUnit = "N*m"; + var axisUnit = "rpm"; + switch (vector) + { + case "missing-scalar": scalars = []; break; + case "extra-scalar": scalars = [scalars[0], scalars[0]]; break; + case "wrong-scalar-key": scalars = [scalars[0] with { LogicalIdentifier = "ENGINE.WARM-IDLE-TARGET" }]; break; + case "wrong-scalar-unit": scalars = [scalars[0] with { Unit = "RPM" }]; break; + case "wrong-table-key": tableId = "engine.unknown"; break; + case "wrong-table-unit": tableUnit = "lbf*ft"; break; + case "wrong-axis-unit": axisUnit = "RPM"; break; + case "changed-axis": axis[2] = 2001; break; + case "reversed-axis": Array.Reverse(axis); break; + case "missing-cell": cells = cells[..^1]; break; + case "extra-cell": cells = [.. cells, 180]; break; + } + var tables = new[] { new CalibrationTableValue(tableId, tableUnit, axisUnit, axis, cells) }; + if (vector == "missing-table") tables = []; + if (vector == "extra-table") tables = [tables[0], tables[0]]; + AssertRejected(service, () => service.Save(Request(before, new(scalars, tables))), CalibrationFailure.InvalidValues); + } + + [Fact] + public async Task StaleSequentialAndBarrierControlledConcurrentHeads_CommitAtMostOneProposal() + { + using var provider = CreateProvider(); + var service = provider.GetRequiredService(); + var baseline = service.CreateBaseline(CreateWarm(provider).ConfigurationIdentifier); + var firstRequest = Request(baseline, Values(baseline, scalar: 1250)); + var secondRequest = Request(baseline, Values(baseline, scalar: 1300)); + using var barrier = new Barrier(2); + CalibrationFailure? Commit(CalibrationSaveRequest request) + { + if (!barrier.SignalAndWait(TimeSpan.FromSeconds(10))) throw new TimeoutException("Commit barrier failed."); + try { service.Save(request); return null; } + catch (CalibrationAuthoringException exception) { return exception.Failure; } + } + var first = Task.Run(() => Commit(firstRequest)); + var second = Task.Run(() => Commit(secondRequest)); + var results = await Task.WhenAll(first, second).WaitAsync(TimeSpan.FromSeconds(15)); + Assert.True(first.IsCompletedSuccessfully); + Assert.True(second.IsCompletedSuccessfully); + Assert.Single(results, failure => failure is null); + Assert.Single(results, failure => failure == CalibrationFailure.StaleHead); + Assert.Equal(2, service.Snapshot!.History.Count); + Assert.Equal(baseline.Head.Identifier, service.Snapshot.Head.ParentIdentifier); + AssertRejected(service, () => service.Save(firstRequest), CalibrationFailure.StaleHead); + AssertRejected(service, () => service.Save(Request(baseline, baseline.Head.Values)), CalibrationFailure.StaleHead); + } + + [Fact] + public void HistoryLimit_IsExactly32IncludingBaselineAndNoOpStillSucceedsAtCapacity() + { + using var provider = CreateProvider(); + var service = provider.GetRequiredService(); + service.CreateBaseline(CreateWarm(provider).ConfigurationIdentifier); + for (var revision = 2; revision <= 32; revision++) + { + var before = service.Snapshot!; + var saved = service.Save(Request(before, Values(before, scalar: 650 + revision))); + Assert.Equal(revision, saved.Revision); + Assert.Equal(before.Head.Identifier, saved.ParentIdentifier); + } + var full = service.Snapshot!; + Assert.Equal(32, full.History.Count); + Assert.Same(full.Head, service.Save(Request(full, full.Head.Values))); + AssertRejected(service, () => service.Save(Request(full, Values(full, scalar: 1250))), CalibrationFailure.HistoryLimit); + Assert.Equal(32, service.Snapshot!.Head.Revision); + Assert.Equal(32, service.Snapshot.History.Select(version => version.Identifier).Distinct().Count()); + } + + [Fact] + public void DefinitionCandidateHistoryAndDiff_DefensivelyCopyCallerCollections() + { + using var provider = CreateProvider(); + var service = provider.GetRequiredService(); + var baseline = service.CreateBaseline(CreateWarm(provider).ConfigurationIdentifier); + var axis = ExpectedAxis.ToArray(); + var cells = ExpectedTorque.ToArray(); + var table = new CalibrationTableValue(TableId, "N*m", "rpm", axis, cells); + var scalars = new List { new(ScalarId, "rpm", 1250) }; + var tables = new List { table }; + var values = new CalibrationValues(scalars, tables); + axis[0] = -1; + cells[0] = 999; + scalars[0] = scalars[0] with { Value = 1400 }; + tables.Clear(); + var first = service.Save(Request(baseline, values)); + Assert.Equal(1250, first.Values.Scalars[0].Value); + Assert.Equal(650, first.Values.Tables[0].Axis[0]); + Assert.Equal(240, first.Values.Tables[0].Cells[0]); + var diff = service.Compare(baseline.Identifier, baseline.Head.Identifier, first.Identifier); + service.Save(Request(service.Snapshot!, Values(service.Snapshot!, scalar: 1500))); + Assert.Equal(1250, first.Values.Scalars[0].Value); + Assert.Equal(650, baseline.Head.Values.Scalars[0].Value); + Assert.Equal(600, diff.Entries.Single().Delta); + Assert.Throws(() => ((IList)diff.Entries).Clear()); + Assert.Throws(() => ((IList)service.Snapshot!.History).Clear()); + var definitionAxis = ExpectedAxis.ToList(); + var definition = new SyntheticEngineCalibration(baseline.Definition.Applicability, + baseline.Definition.Scalar, new(TableId, "rpm", "N*m", definitionAxis, 1, 1000, 1, 0)); + definitionAxis.Clear(); + Assert.Equal(ExpectedAxis, definition.Table.Axis); + Assert.Throws(() => ((IList)definition.Table.Axis)[0] = 1); + } + + [Theory] + [InlineData("configuration")] + [InlineData("configuration-case")] + [InlineData("profile")] + [InlineData("revision")] + [InlineData("module")] + [InlineData("model")] + [InlineData("model-case")] + [InlineData("model-version")] + [InlineData("definition")] + [InlineData("definition-case")] + [InlineData("definition-revision")] + public void SourceTokenMismatch_RejectsWithoutCrossSourceFallback(string vector) + { + using var provider = CreateProvider(); + var service = provider.GetRequiredService(); + var before = service.CreateBaseline(CreateWarm(provider).ConfigurationIdentifier); + var source = before.Definition.Applicability; + source = vector switch + { + "configuration" => source with { ConfigurationIdentifier = "sha256:v1:other" }, + "configuration-case" => source with { ConfigurationIdentifier = source.ConfigurationIdentifier.ToUpperInvariant() }, + "profile" => source with { ProfileIdentifier = "other" }, + "revision" => source with { ProfileRevision = 2 }, + "module" => source with { ModuleIdentifier = "module.cabin.body" }, + "model" => source with { ModelIdentifier = "other" }, + "model-case" => source with { ModelIdentifier = source.ModelIdentifier.ToUpperInvariant() }, + "model-version" => source with { ModelVersion = 2 }, + "definition" => source with { DefinitionIdentifier = "other" }, + "definition-case" => source with { DefinitionIdentifier = source.DefinitionIdentifier.ToUpperInvariant() }, + "definition-revision" => source with { DefinitionRevision = 2 }, + _ => throw new ArgumentOutOfRangeException(nameof(vector)) + }; + AssertRejected(service, () => service.Save(Request(before, Values(before, scalar: 1250)) with { Source = source }), + CalibrationFailure.SourceMismatch); + } + + [Fact] + public void IdentityComparisonsAndExplicitReplacement_PreservePriorHistoryOnAnyRejection() + { + using var provider = CreateProvider(); + var service = provider.GetRequiredService(); + var warm = CreateWarm(provider); + var baseline = service.CreateBaseline(warm.ConfigurationIdentifier); + var source = baseline.Definition.Applicability with + { + ProfileIdentifier = ProfileId.ToUpperInvariant(), ModuleIdentifier = EngineId.ToUpperInvariant() + }; + service.Save(Request(baseline, Values(baseline, scalar: 1250)) with { Source = source }); + var previous = service.Snapshot!; + AssertRejected(service, () => service.CreateBaseline(warm.ConfigurationIdentifier), CalibrationFailure.WorkspaceExists); + AssertRejected(service, () => service.ReplaceBaseline(warm.ConfigurationIdentifier, previous.Identifier, + previous.Head.Identifier, false), CalibrationFailure.ReplacementNotConfirmed); + AssertRejected(service, () => service.ReplaceBaseline("missing", previous.Identifier, + previous.Head.Identifier, true), CalibrationFailure.SourceNotFound); + AssertRejected(service, () => service.ReplaceBaseline(warm.ConfigurationIdentifier, previous.Identifier, + baseline.Head.Identifier, true), CalibrationFailure.StaleHead); + AssertRejected(service, () => service.Compare(previous.Identifier, "missing", previous.Head.Identifier), CalibrationFailure.VersionNotFound); + var replacement = service.ReplaceBaseline(warm.ConfigurationIdentifier, previous.Identifier, previous.Head.Identifier, true); + Assert.Single(replacement.History); + Assert.NotEqual(previous.Identifier, replacement.Identifier); + AssertRejected(service, () => service.Save(Request(previous, previous.Head.Values)), CalibrationFailure.SourceMismatch); + AssertRejected(service, () => service.Compare(replacement.Identifier, previous.Head.Identifier, replacement.Head.Identifier), + CalibrationFailure.VersionNotFound); + } + + [Theory] + [InlineData("too-many-rows")] + [InlineData("torque-too-low")] + [InlineData("torque-too-high")] + [InlineData("unsupported-model")] + public void UnsupportedButValidDynamicsConfiguration_RejectsTemplateBeforeReplacement(string vector) + { + using var provider = CreateProvider(); + var service = provider.GetRequiredService(); + var warm = CreateWarm(provider); + var original = service.CreateBaseline(warm.ConfigurationIdentifier); + var variant = ImportVariant(provider, document => + { + if (vector == "unsupported-model") document["modelIdentifier"] = "another.synthetic.model"; + else if (vector == "too-many-rows") + { + document["model"]!["engineTorqueCurve"] = new JsonArray(Enumerable.Range(0, 33) + .Select(index => (JsonNode)new JsonObject { ["engineSpeedRpm"] = index * 150, ["torqueNewtonMeters"] = 240 }).ToArray()); + } + else document["model"]!["engineTorqueCurve"]![0]!["torqueNewtonMeters"] = vector == "torque-too-low" ? 0.5 : 1001; + }); + AssertRejected(service, () => service.ReplaceBaseline(variant.ConfigurationIdentifier, original.Identifier, + original.Head.Identifier, true), CalibrationFailure.InvalidDefinition); + Assert.Same(original, service.Snapshot); + } + + [Fact] + public void MalformedDefinitionAndUnloadedCommands_RejectTypedWithoutFabricatedWorkspace() + { + using var provider = CreateProvider(); + var service = provider.GetRequiredService(); + AssertRejected(service, () => service.CreateBaseline("missing"), CalibrationFailure.SourceNotFound); + Assert.Null(service.Snapshot); + var baseline = service.CreateBaseline(CreateWarm(provider).ConfigurationIdentifier); + foreach (var scalar in new[] + { + baseline.Definition.Scalar with { LogicalIdentifier = "other" }, + baseline.Definition.Scalar with { Unit = "RPM" }, + baseline.Definition.Scalar with { Minimum = double.NaN }, + baseline.Definition.Scalar with { Maximum = 649 }, + baseline.Definition.Scalar with { Scale = 2 }, + baseline.Definition.Scalar with { Offset = 1 } + }) + { + var exception = Assert.Throws(() => + new SyntheticEngineCalibration(baseline.Definition.Applicability, scalar, baseline.Definition.Table)); + Assert.Equal(CalibrationFailure.InvalidDefinition, exception.Failure); + } + foreach (var axis in new[] { new[] { 650d }, new[] { 650d, 650 }, new[] { 1000d, 650 }, new[] { -1d, 650 }, new[] { 650d, 5001 }, new[] { 650d, double.NaN } }) + { + Assert.Throws(() => new SyntheticEngineCalibration( + baseline.Definition.Applicability, baseline.Definition.Scalar, new(TableId, "rpm", "N*m", axis, 1, 1000, 1, 0))); + } + Assert.Same(baseline, service.Snapshot); + } + + [Fact] + public void MultiCellAndReverseDiffs_AreExactDeterministicAxisOrderedSnapshots() + { + using var provider = CreateProvider(); + var service = provider.GetRequiredService(); + var baseline = service.CreateBaseline(CreateWarm(provider).ConfigurationIdentifier); + var torque = ExpectedTorque.ToArray(); + torque[4] = 310; + torque[0] = 230; + var changed = service.Save(Request(baseline, Values(baseline, scalar: 700, torque: torque))); + var forward = service.Compare(baseline.Identifier, baseline.Head.Identifier, changed.Identifier); + Assert.Equal([TableId, TableId, ScalarId], forward.Entries.Select(entry => entry.LogicalIdentifier)); + Assert.Equal([650d, 4200d], forward.Entries.Where(entry => entry.AxisCoordinate is not null).Select(entry => entry.AxisCoordinate!.Value)); + Assert.Equal([-10d, 10d, 50d], forward.Entries.Select(entry => entry.Delta)); + var reverse = service.Compare(baseline.Identifier, changed.Identifier, baseline.Head.Identifier); + Assert.Equal([10d, -10d, -50d], reverse.Entries.Select(entry => entry.Delta)); + Assert.All(forward.Entries.Zip(reverse.Entries), pair => + { + Assert.Equal(pair.First.Before, pair.Second.After); + Assert.Equal(pair.First.After, pair.Second.Before); + Assert.Equal(pair.First.AxisCoordinate, pair.Second.AxisCoordinate); + }); + Assert.Empty(service.Compare(baseline.Identifier, changed.Identifier, changed.Identifier).Entries); + } + + [Fact] + public void InvalidTableDefinitionMetadata_IsRejectedWithoutAHealthyDefault() + { + using var provider = CreateProvider(); + var workspace = provider.GetRequiredService().CreateBaseline(CreateWarm(provider).ConfigurationIdentifier); + foreach (var table in new[] + { + new CalibrationTableDefinition("other", "rpm", "N*m", ExpectedAxis, 1, 1000), + new CalibrationTableDefinition(TableId, "RPM", "N*m", ExpectedAxis, 1, 1000), + new CalibrationTableDefinition(TableId, "rpm", "lbf*ft", ExpectedAxis, 1, 1000), + new CalibrationTableDefinition(TableId, "rpm", "N*m", ExpectedAxis, double.NaN, 1000), + new CalibrationTableDefinition(TableId, "rpm", "N*m", ExpectedAxis, 1, 1001), + new CalibrationTableDefinition(TableId, "rpm", "N*m", ExpectedAxis, 1, 1000, 2), + new CalibrationTableDefinition(TableId, "rpm", "N*m", ExpectedAxis, 1, 1000, 1, 1) + }) + { + var exception = Assert.Throws(() => + new SyntheticEngineCalibration(workspace.Definition.Applicability, workspace.Definition.Scalar, table)); + Assert.Equal(CalibrationFailure.InvalidDefinition, exception.Failure); + } + } + + private static ServiceProvider CreateProvider() + { + var services = new ServiceCollection(); + services.AddLogging(); + services.AddAutoForgeVehicleProfiles(); + services.AddAutoForgeUi(); + return services.BuildServiceProvider(); + } + + [Theory] + [InlineData(2)] + [InlineData(32)] + public void TemplateRowBoundaries_AcceptExactSourceShapeWithoutInsertionOrSorting(int count) + { + using var provider = CreateProvider(); + CreateWarm(provider); + var axis = Enumerable.Range(0, count).Select(index => index * (5000d / (count - 1))).ToArray(); + axis[^1] = 5000; + var source = ImportVariant(provider, json => json["model"]!["engineTorqueCurve"] = new JsonArray( + axis.Select(rpm => (JsonNode)new JsonObject { ["engineSpeedRpm"] = rpm, ["torqueNewtonMeters"] = 240 }).ToArray())); + var workspace = provider.GetRequiredService().CreateBaseline(source.ConfigurationIdentifier); + Assert.Equal(count, workspace.Definition.Table.Axis.Count); + Assert.Equal(axis, workspace.Definition.Table.Axis); + Assert.Equal(axis, workspace.Head.Values.Tables[0].Axis); + Assert.All(workspace.Head.Values.Tables[0].Cells, value => Assert.Equal(240, value)); + } + + [Fact] + public void FullProfileRevisionChangeAndInvalidEmptyRequests_PreserveTheExactCurrentWorkspace() + { + using var provider = CreateProvider(); + var warm = CreateWarm(provider); + var service = provider.GetRequiredService(); + var baseline = service.CreateBaseline(warm.ConfigurationIdentifier); + var profiles = provider.GetRequiredService(); + var json = JsonNode.Parse(ReadProfile())!.AsObject(); + json["revision"] = 2; + foreach (var evidence in json["evidence"]!.AsArray()) + evidence!["applicability"]!["profileRevision"] = 2; + profiles.Import(json.ToJsonString()); + var second = provider.GetRequiredService().CreateExample(ProfileId, 2); + var replacement = service.ReplaceBaseline(second.ConfigurationIdentifier, baseline.Identifier, baseline.Head.Identifier, true); + Assert.Equal(2, replacement.Head.Source.ProfileRevision); + Assert.Equal(1, baseline.Head.Source.ProfileRevision); + AssertRejected(service, () => service.Save(Request(baseline, baseline.Head.Values)), CalibrationFailure.SourceMismatch); + AssertRejected(service, () => service.ReplaceBaseline("", replacement.Identifier, replacement.Head.Identifier, true), + CalibrationFailure.SourceNotFound); + AssertRejected(service, () => service.Save(Request(replacement, replacement.Head.Values) with { ExpectedHeadIdentifier = "" }), + CalibrationFailure.StaleHead); + var freshService = new CalibrationAuthoringService(provider.GetRequiredService(), profiles); + Assert.Null(freshService.Snapshot); + AssertRejected(freshService, () => freshService.Save(Request(replacement, replacement.Head.Values)), CalibrationFailure.NoWorkspace); + AssertRejected(freshService, () => freshService.Compare(replacement.Identifier, replacement.Head.Identifier, replacement.Head.Identifier), + CalibrationFailure.NoWorkspace); + } + + private static DynamicsConfiguration CreateWarm(IServiceProvider provider) + { + provider.GetRequiredService().Import(ReadProfile()); + return provider.GetRequiredService().CreateExample(ProfileId, 1); + } + + private static string ReadProfile() => File.ReadAllText(Path.Combine(AppContext.BaseDirectory, "Fixtures", "synthetic-truck-baseline.json")); + + private static DynamicsConfiguration ImportVariant(IServiceProvider provider, Action mutate) + { + var configurations = provider.GetRequiredService(); + var json = JsonNode.Parse(configurations.Export(configurations.List().First().ConfigurationIdentifier))!.AsObject(); + mutate(json); + return configurations.Import(json.ToJsonString()); + } + + private static CalibrationValues Values(CalibrationWorkspace workspace, double? scalar = null, double[]? torque = null) => + new([new(ScalarId, "rpm", scalar ?? workspace.Head.Values.Scalars.Single().Value)], + [new(TableId, "N*m", "rpm", workspace.Definition.Table.Axis, torque ?? workspace.Head.Values.Tables.Single().Cells)]); + + private static CalibrationSaveRequest Request(CalibrationWorkspace workspace, CalibrationValues values) => + new(workspace.Identifier, workspace.Head.Identifier, workspace.Definition.Applicability, values); + + private static void AssertRejected(CalibrationAuthoringService service, Action action, CalibrationFailure failure) + { + var previous = service.Snapshot; + var exception = Assert.Throws(action); + Assert.Equal(failure, exception.Failure); + Assert.False(string.IsNullOrWhiteSpace(exception.Message)); + Assert.Same(previous, service.Snapshot); + } +} diff --git a/src/tests/AutoForge.IntegrationTests/CalibrationAuthoringUiTests.cs b/src/tests/AutoForge.IntegrationTests/CalibrationAuthoringUiTests.cs new file mode 100644 index 0000000..204f65d --- /dev/null +++ b/src/tests/AutoForge.IntegrationTests/CalibrationAuthoringUiTests.cs @@ -0,0 +1,227 @@ +using System.Globalization; +using AutoForge.Application.Features.DisplayUnits; +using AutoForge.Application.Features.Vehicles.Calibration; +using AutoForge.Core.Calibration; +using AutoForge.UI.Features.Vehicles.Calibration; +using Microsoft.AspNetCore.Components; +using Microsoft.AspNetCore.Components.Rendering; +using Microsoft.AspNetCore.Components.RenderTree; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Microsoft.AspNetCore.Components.Web; + +#pragma warning disable BL0006 + +namespace AutoForge.IntegrationTests; + +public sealed partial class CalibrationAuthoringTests +{ + [Fact] + public async Task RealEditor_SaveDiffHistoryAndInvalidInput_UseExactVersionsNotSharedDraftReferences() + { + using var provider = CreateProvider(); + var warm = CreateWarm(provider); + var service = provider.GetRequiredService(); + await using var renderer = new CalibrationEventRenderer(provider); + var root = renderer.Attach(typeof(CalibrationPage)); + await renderer.Dispatcher.InvokeAsync(async () => + { + await renderer.RenderAsync(root); + await renderer.ChangeAsync(root, "calibration-config", warm.ConfigurationIdentifier); + await renderer.ClickAsync(root, "calibration-create"); + var baseline = service.Snapshot!; + Assert.Contains("Synthetic configuration-derived baseline", renderer.Text(root)); + await renderer.ChangeAsync(root, "calibration-scalar", "1250"); + Assert.Equal(650, baseline.Head.Values.Scalars[0].Value); + await renderer.ClickAsync(root, "calibration-save"); + var first = service.Snapshot!; + Assert.Equal(1250, first.Head.Values.Scalars[0].Value); + await renderer.ChangeAsync(root, "calibration-torque-2", DisplayUnitConverter.Project( + 350, "N*m", DisplayUnitSelection.Default).Value!.Value.ToString("R", CultureInfo.InvariantCulture)); + await renderer.ClickAsync(root, "calibration-save"); + var second = service.Snapshot!; + var editedDisplay = DisplayUnitConverter.Project(350, "N*m", DisplayUnitSelection.Default).Value!.Value; + var expectedCanonical = editedDisplay / ((1 / 4.4482216152605) * (1 / 0.3048)); + Assert.Equal(expectedCanonical, second.Head.Values.Tables[0].Cells[2]); + await renderer.ChangeAsync(root, "calibration-diff-from", baseline.Head.Identifier); + await renderer.ChangeAsync(root, "calibration-diff-to", second.Head.Identifier); + await renderer.ClickAsync(root, "calibration-compare"); + Assert.Contains("650 -> 1250", renderer.Text(root)); + Assert.Contains("360 ->", renderer.Text(root)); + Assert.Contains("2000 rpm", renderer.Text(root)); + await renderer.ChangeAsync(root, "calibration-inspect", baseline.Head.Identifier); + Assert.Contains(baseline.Head.Identifier, renderer.Text(root)); + Assert.Equal(second.Head.Identifier, service.Snapshot!.Head.Identifier); + await renderer.ChangeAsync(root, "calibration-scalar", "not-a-number"); + await renderer.ClickAsync(root, "calibration-save"); + Assert.Contains("finite", renderer.Text(root)); + Assert.Same(second, service.Snapshot); + await renderer.ChangeAsync(root, "calibration-scalar", "600"); + await renderer.ClickAsync(root, "calibration-save"); + Assert.Contains("650", renderer.Text(root)); + Assert.Same(second, service.Snapshot); + }); + Assert.Contains(typeof(CalibrationPage).GetCustomAttributes(typeof(RouteAttribute), false).Cast(), + route => route.Template == "/calibration"); + } + + [Fact] + public async Task TorqueDraft_IsPinnedAndUneditedSavePreservesExactCanonicalDoublesAcrossToggles() + { + using var provider = CreateProvider(); + var warm = CreateWarm(provider); + var service = provider.GetRequiredService(); + var before = service.CreateBaseline(warm.ConfigurationIdentifier); + await using var renderer = new CalibrationEventRenderer(provider); + var host = new CalibrationUnitHost(); + var root = renderer.Attach(host); + await renderer.Dispatcher.InvokeAsync(async () => + { + await renderer.RenderAsync(root); + var source = before.Head.Values.Tables[0].Cells.ToArray(); + var originalText = renderer.Attribute(root, "calibration-torque-2", "value")!.ToString(); + var proposal = DisplayUnitConverter.Project(350, "N*m", DisplayUnitSelection.Default).Value!.Value; + await renderer.ChangeAsync(root, "calibration-torque-2", proposal.ToString("R", CultureInfo.InvariantCulture)); + host.SetUnits(new(DisplayUnitSystem.Metric, SpeedDisplayMode.Road)); + Assert.Equal(proposal.ToString("R", CultureInfo.InvariantCulture), + renderer.Attribute(root, "calibration-torque-2", "value")!.ToString()); + Assert.Contains("Draft input pinned to ImperialUS", renderer.Text(root)); + Assert.Equal(source, service.Snapshot!.Head.Values.Tables[0].Cells); + await renderer.ClickAsync(root, "calibration-save"); + var committed = service.Snapshot!; + Assert.Equal(proposal / ((1 / 4.4482216152605) * (1 / 0.3048)), committed.Head.Values.Tables[0].Cells[2]); + var canonical = committed.Head.Values.Tables[0].Cells.ToArray(); + for (var index = 0; index < 8; index++) + { + host.SetUnits(index % 2 == 0 ? DisplayUnitSelection.Default : new(DisplayUnitSystem.Metric, SpeedDisplayMode.Road)); + await renderer.ClickAsync(root, "calibration-save"); + Assert.Same(committed.Head, service.Snapshot!.Head); + Assert.Equal(canonical, service.Snapshot.Head.Values.Tables[0].Cells); + } + Assert.NotNull(originalText); + }); + } + + [Fact] + public async Task TwoActualEditorsAndSourceReplacement_RejectStaleOrUnconfirmedLossWithoutMutation() + { + using var provider = CreateProvider(); + var warm = CreateWarm(provider); + var alternate = ImportVariant(provider, json => json["model"]!["warmIdleTargetRpm"] = 700); + var service = provider.GetRequiredService(); + var baseline = service.CreateBaseline(warm.ConfigurationIdentifier); + await using var renderer = new CalibrationEventRenderer(provider); + var first = renderer.Attach(typeof(CalibrationPage)); + var second = renderer.Attach(typeof(CalibrationPage)); + await renderer.Dispatcher.InvokeAsync(async () => + { + await renderer.RenderAsync(first); + await renderer.RenderAsync(second); + await renderer.ChangeAsync(first, "calibration-scalar", "1250"); + await renderer.ClickAsync(first, "calibration-save"); + var committed = service.Snapshot!; + await renderer.ChangeAsync(second, "calibration-scalar", "1300"); + await renderer.ClickAsync(second, "calibration-save"); + Assert.Contains("head", renderer.Text(second)); + Assert.Same(committed, service.Snapshot); + await renderer.ChangeAsync(first, "calibration-config", alternate.ConfigurationIdentifier); + await renderer.ClickAsync(first, "calibration-save"); + Assert.Contains("source", renderer.Text(first)); + Assert.Same(committed, service.Snapshot); + await renderer.ClickAsync(first, "calibration-replace"); + Assert.Contains("confirm", renderer.Text(first)); + Assert.Same(committed, service.Snapshot); + await renderer.CheckAsync(first, "calibration-replace-confirm", true); + await renderer.ClickAsync(first, "calibration-replace"); + Assert.Single(service.Snapshot!.History); + Assert.Equal(700, service.Snapshot.Head.Values.Scalars[0].Value); + Assert.NotEqual(baseline.Identifier, service.Snapshot.Identifier); + await renderer.ClickAsync(second, "calibration-save"); + Assert.Contains("source", renderer.Text(second)); + Assert.Single(service.Snapshot.History); + }); + } + + private sealed class CalibrationUnitHost : ComponentBase + { + private DisplayUnitSelection _selection = DisplayUnitSelection.Default; + public void SetUnits(DisplayUnitSelection selection) { _selection = selection; StateHasChanged(); } + protected override void BuildRenderTree(RenderTreeBuilder builder) + { + builder.OpenComponent>(0); + builder.AddAttribute(1, "Value", _selection); + builder.AddAttribute(2, "ChildContent", (RenderFragment)(child => + { + child.OpenComponent(0); + child.CloseComponent(); + })); + builder.CloseComponent(); + } + } + + private sealed class CalibrationEventRenderer(IServiceProvider services) + : Renderer(services, services.GetRequiredService()) + { + public override Dispatcher Dispatcher { get; } = Dispatcher.CreateDefault(); + public int Attach(Type type) => AssignRootComponentId(InstantiateComponent(type)); + public int Attach(IComponent component) => AssignRootComponentId(component); + public Task RenderAsync(int root) => RenderRootComponentAsync(root, ParameterView.Empty); + public string Text(int root) => string.Concat(ComponentIds(root).SelectMany(id => + { + var frames = GetCurrentRenderTreeFrames(id); + return frames.Array.Take(frames.Count).Select(frame => frame.FrameType switch + { + RenderTreeFrameType.Text => frame.TextContent, + RenderTreeFrameType.Markup => frame.MarkupContent, + _ => string.Empty + }); + })); + public object? Attribute(int root, string elementId, string attribute) => + Element(root, elementId).Frames.FirstOrDefault(frame => + frame.FrameType == RenderTreeFrameType.Attribute && frame.AttributeName == attribute).AttributeValue; + public Task ChangeAsync(int root, string elementId, string value) => ChangeCoreAsync(root, elementId, value); + public Task CheckAsync(int root, string elementId, bool value) => ChangeCoreAsync(root, elementId, value); + private Task ChangeCoreAsync(int root, string elementId, object value) + { + var node = Element(root, elementId); + var handler = node.Frames.Single(frame => frame.FrameType == RenderTreeFrameType.Attribute && frame.AttributeName == "onchange"); + return DispatchEventAsync(handler.AttributeEventHandlerId, + new EventFieldInfo { ComponentId = node.Id, FieldValue = value }, new ChangeEventArgs { Value = value }); + } + public Task ClickAsync(int root, string elementId) + { + var handler = Element(root, elementId).Frames.Single(frame => + frame.FrameType == RenderTreeFrameType.Attribute && frame.AttributeName == "onclick"); + return DispatchEventAsync(handler.AttributeEventHandlerId, null, new MouseEventArgs()); + } + private (int Id, RenderTreeFrame[] Frames) Element(int root, string elementId) + { + foreach (var id in ComponentIds(root)) + { + var frames = GetCurrentRenderTreeFrames(id); + for (var index = 0; index < frames.Count; index++) + { + if (frames.Array[index].FrameType != RenderTreeFrameType.Element) continue; + var element = frames.Array.Skip(index).Take(frames.Array[index].ElementSubtreeLength).ToArray(); + if (element.Skip(1).TakeWhile(frame => frame.FrameType == RenderTreeFrameType.Attribute) + .Any(frame => frame.AttributeName == "id" && frame.AttributeValue?.ToString() == elementId)) return (id, element); + } + } + throw new InvalidOperationException($"Missing rendered calibration control '{elementId}'."); + } + private IEnumerable ComponentIds(int root) + { + yield return root; + var frames = GetCurrentRenderTreeFrames(root); + for (var index = 0; index < frames.Count; index++) + { + if (frames.Array[index].FrameType != RenderTreeFrameType.Component) continue; + foreach (var nested in ComponentIds(frames.Array[index].ComponentId)) yield return nested; + } + } + protected override void HandleException(Exception exception) => throw new InvalidOperationException("Calibration UI failed.", exception); + protected override Task UpdateDisplayAsync(in RenderBatch renderBatch) => Task.CompletedTask; + } +} + +#pragma warning restore BL0006