diff --git a/README.md b/README.md index 44a484e..fd095b9 100644 --- a/README.md +++ b/README.md @@ -95,7 +95,7 @@ rewritten. See [replay usage and contracts](docs/telemetry-replay.md) and the [Step-08 worker report](prompts/Step-08-Report.md). Step-08 was accepted on 2026-10-30. -### Implemented, pending manual review +### Accepted synthetic authoring milestone Step-09 adds `/calibration`: one bounded, process-memory synthetic authoring workspace derived explicitly from a saved immutable dynamics configuration. @@ -104,12 +104,23 @@ 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 +[Step-09 worker report](prompts/Step-09-Report.md). Step-09 was accepted on +2026-10-30. + +### Implemented, pending manual review + +Step-10 adds an explicit isolated Simulation rehearsal within `/calibration`. +Its real mutable logical image supports independent volatile backup, +source/head/revision-bound single-use approval, atomic CAS, full readback, +read-only reconciliation and separately approved original Restore. It never +applies authoring values to a dynamics configuration or a physical target. +See [rehearsal contracts](docs/calibration-rehearsal.md) and the +[Step-10 worker report](prompts/Step-10-Report.md). Step-10 remains pending manual orchestrator review. ### Planned -Verified simulated programming, verified backups/approval, AI and real hardware operations +Durable/full-device backups, dynamics application, 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, @@ -130,7 +141,7 @@ 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, offline recorded replay, synthetic calibration -authoring and a shared display-unit preference with a +authoring, isolated simulated programming rehearsal 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/ @@ -245,6 +256,7 @@ acceptance remains the orchestrator's responsibility. - [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) +- [Verified simulated programming rehearsal](docs/calibration-rehearsal.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 bd48f43..a68dbfb 100644 --- a/docs/README.md +++ b/docs/README.md @@ -14,7 +14,9 @@ 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 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. +Step-09 is accepted. Step-10 adds isolated simulated image backup/approval/ +CAS/readback/reconciliation/Restore, without dynamics or physical application. +Step-10 worker status remains pending manual orchestrator review. - [Architecture](architecture.md): actual nine-project graph, responsibilities, route ownership and provider/reference boundaries. @@ -38,6 +40,9 @@ Step-09 worker status remains pending manual orchestrator review. - [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. +- [Verified simulated programming rehearsal](calibration-rehearsal.md): typed + isolated target, independently verified supported-image backup, immutable + single-use approval, exact readback/recovery and bounded volatile audit. - [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): @@ -72,5 +77,6 @@ historical/worker reports for their own execution evidence: [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) and -[Step-09 worker report](../prompts/Step-09-Report.md). +[Step-09 worker report](../prompts/Step-09-Report.md) and +[Step-10 worker report](../prompts/Step-10-Report.md). Handoffs are manual; acceptance remains the orchestrator's responsibility. diff --git a/docs/architecture.md b/docs/architecture.md index 1eecf3a..c0e7fc5 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -12,8 +12,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 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. +process-memory synthetic calibration authoring and is accepted. Step-10 adds +isolated simulated programming rehearsal with independent backup and full +readback/recovery. Step-10 remains pending manual review; execution is not acceptance. ```mermaid flowchart TD @@ -46,9 +47,9 @@ All nine projects are in [AutoForge.slnx](../src/AutoForge.slnx): | Project | Target and responsibility | Project references | |---|---|---| | [Core](../src/AutoForge.Core/AutoForge.Core.csproj) | `net10.0`; platform-neutral target/profile invariants, immutable dynamics contracts and bounded synthetic calibration definition/value/applicability validation | None | -| [Diagnostics](../src/AutoForge.Diagnostics/AutoForge.Diagnostics.csproj) | `net10.0`; 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, replay and calibration-authoring feature slices | Core, Diagnostics | +| [Diagnostics](../src/AutoForge.Diagnostics/AutoForge.Diagnostics.csproj) | `net10.0`; diagnostic contracts/protocol/trace plus a separate narrow typed simulated-calibration target port | Core | +| [Simulation](../src/AutoForge.Simulation/AutoForge.Simulation.csproj) | `net10.0`; static/dynamic providers and a separate mutable logical calibration rehearsal image/CAS owner | Core, Diagnostics | +| [Application](../src/AutoForge.Application/AutoForge.Application.csproj) | `net10.0`; target/profile/diagnostics/dynamics coordination, units/dashboard/recording/replay, authoring and guarded rehearsal workflow | 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 | @@ -216,7 +217,7 @@ and [simulation guide](simulation.md). ## Honest limitations and safety boundaries -The calibration slice has only configuration/profile read dependencies. Core +The authoring slice has only configuration/profile read dependencies. Core owns defensively copied applicability, definition and value contracts for the single synthetic engine template. Application's singleton `CalibrationAuthoringService` retains one workspace, at most 32 saved revisions @@ -236,6 +237,27 @@ model-control, archive-save, approval or programming port, and cannot apply its values to a configuration or active source. See [calibration authoring](calibration-authoring.md) for template bounds and limits. +The separate rehearsal factory creates one page-owned Application session. +Client registers `autoforge.simulation.calibration-rehearsal` as an explicit +`ISimulatedCalibrationTargetFactory`, not a diagnostic transport fallback. +Diagnostics defines typed Identity/Image/Commit/Acknowledgement ports; +Simulation seeds a separate stored logical image once from the exact source, +then owns actual reads and atomic revision CAS. It never changes a dynamics +engine, profile or configuration. Application/UI never reference its concrete +implementation or oracle. + +Application validates two independent original target reads before publishing +a verified volatile supported-image backup. Immutable approval binds actual +before-image/revision, target instance/source, original backup and saved +authoring head/action. Source-head guard and target CAS precede mutation; +one owner serializes operations without holding a cleanup-required gate across +awaits. Full independent readback, not acknowledgement, determines verification. +Uncertain outcomes remain RecoveryRequired with explicit read-only +reconciliation or separately approved original Restore. Closed evidence cannot +authorize a fresh target. At most 32 dispatched Apply/Restore outcomes and only +bounded current preparation/command evidence are retained. See +[rehearsal contracts](calibration-rehearsal.md). + 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, @@ -243,8 +265,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. Calibration authoring values are synthetic proposals only. No real vehicle, -physical adapter, programming, verified backup/approval, applied calibration, +path. Calibration authoring values remain synthetic proposals; rehearsal mutates +only its isolated logical Simulation image. No real vehicle, +physical adapter/programming, full-device or durable backup, applied dynamics calibration, AI, live streaming, crash-durable capture or cloud service is implemented. Saved recordings are local source-sensitive files and must be treated as potentially sensitive data. A `SUPPORTED` declaration, diff --git a/docs/build-and-test.md b/docs/build-and-test.md index 9b24342..327724b 100644 --- a/docs/build-and-test.md +++ b/docs/build-and-test.md @@ -43,11 +43,54 @@ dotnet test .\src\tests\AutoForge.UnitTests\AutoForge.UnitTests.csproj --configu 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" +dotnet test .\src\tests\AutoForge.IntegrationTests\AutoForge.IntegrationTests.csproj --configuration Release --no-restore --filter "FullyQualifiedName~CalibrationRehearsalTests|FullyQualifiedName~RenderedRehearsal|FullyQualifiedName~RehearsalIsolation|FullyQualifiedName~CalibrationAuthoringTests" ``` +## Step-10 simulated programming rehearsal verification + +Step-09 is accepted; Step-10 remains pending manual review. The final focused +command passed **86 cases**: 31 new rehearsal cases plus 55 accepted authoring +cases. They use actual Simulation target storage/CAS through typed Diagnostics +ports, real authoring/configuration/profile services and controlled forwarding +faults. Independent backup, complete scalar/table readback, immutable approval, +stale head/target CAS, cancellation before/after actual commit, exact repeated +operations, negative/echoed/lost acknowledgements, divergent/missing reads, +read-only reconciliation, separately approved Restore, held close/failure +drainage and exact 32/33 audit capacity are verified. + +The required sequential Release build completed all nine projects/native +Client with zero warnings/errors. The full suite passed **179 unit + +257 integration = 436 cases**, zero failed/skipped, preserving all 405 +baseline cases. Real live dynamics/diagnostics, saved recording and validated +replay coexist while rehearsal adds zero calls to their transport/model/archive +Save boundaries and leaves configuration export, live trace/status, archive +bytes, authoring history and replay snapshot unchanged. + +Native smoke used the actual rebuilt Windows Client and task-owned WebView2 +profile/local DevTools port. Within `/calibration`, an explicitly created warm +configuration/proposal opened the distinct Simulation rehearsal target. Two +independent reads produced its verified supported-image backup at revision 0. +Explicit scalar Apply yielded 1250 rpm with all torque cells unchanged at +revision 1. A new proposal changed only 2000-rpm torque 360->350 N*m; its new +approval/full readback yielded revision 2. Separately confirmed original Restore +yielded 650 rpm and every original torque cell/axis at revision 3. Close left +inactive evidence; reopen created a different instance with no old backup/ +approval/audit. Restore without a fresh backup rejected. + +The native source export/fingerprint remained identical, with source warm idle +650 rpm and 2000-rpm torque 360 N*m. A separate actual dynamics read at model +step 7 returned 631.80416 rpm, not the rehearsal's 1250 image. Display units +preserved an unconsumed approval without dispatch; exact repeat dispatched no +second mutation. Original Metric/Road preferences and old replay/home routes +worked. Initial fast automation hit stale-head/DOM-readiness rejections; exact +selected/current-head feedback and settled real controls were then used for +the complete successful workflow. Those are not controlled race/fault proofs. +See the [Step-10 worker report](../prompts/Step-10-Report.md) for exact normal/ +controlled evidence, commands, cleanup and preservation. + ## Step-09 synthetic authoring verification -Step-08 is accepted. Step-09 remains pending manual orchestrator review. +Steps 08 and 09 are accepted. The historical Step-09 worker evidence follows. 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, diff --git a/docs/calibration-authoring.md b/docs/calibration-authoring.md index e365bc7..681dba0 100644 --- a/docs/calibration-authoring.md +++ b/docs/calibration-authoring.md @@ -8,9 +8,11 @@ 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. +Steps 08 and 09 are accepted. The separate [Step-10 rehearsal](calibration-rehearsal.md) +can consume a saved current Proposed head only through explicit isolated target, +backup, approval and readback actions. Saving authoring values never dispatches +programming or rewrites their Baseline/Proposed status. Physical writes retain +their later independent authorization/evidence gates. ## Explicit source and bounded synthetic definition diff --git a/docs/calibration-rehearsal.md b/docs/calibration-rehearsal.md new file mode 100644 index 0000000..f833dd1 --- /dev/null +++ b/docs/calibration-rehearsal.md @@ -0,0 +1,150 @@ +# Verified simulated programming rehearsal + +## Scope and explicit target + +The isolated rehearsal appears within `/calibration`, beside the accepted +authoring editor. It is a **Simulation-only logical image rehearsal**, not a +wire protocol, firmware transfer, real driver, dynamics application or physical +programming capability. Opening the page, saving a proposal, changing display +units and rendering never open a target or dispatch a mutation. + +First explicitly create/select a supported authoring configuration/workspace +and save a current Proposed head. Select the registered +`autoforge.simulation.calibration-rehearsal` provider and choose **Open fresh +isolated Simulation target**. Wrong provider/descriptor, PhysicalHardware, +RecordedReplay or a mismatched source rejects before factory creation. +The target's independent image is seeded once with the selected configuration's +source warm-idle scalar and complete fixed-axis torque table, at revision zero. +Thereafter the actual target owns reads and atomic commits. + +Source configuration/profile revision/actual engine module/model/definition +remain explicit. No diagnostic session is fabricated; source metadata is not a +verified ECU identity or a write permission. Only `engine.warm-idle-target` +(rpm) and `engine.torque-curve` (fixed rpm axis, N*m cells) are supported, +with the accepted [authoring template](calibration-authoring.md). + +## Independent original backup + +Choose **Prepare original backup with two independent reads** before the first +mutation. Both complete actual reads must match exactly in target identity, +source, revision zero, keys, units, axes and every value. A wrong/partial/failed +read cannot publish a verified backup. An authoring baseline is never used as +a synthetic read response. + +The immutable **Verified in-memory backup of supported simulation image** +covers exactly one scalar and all fixed-axis torque cells, not an entire ECU. +It retains original instance/source/revision/value evidence and remains the +original backup across multiple writes. There is no backup file, persistence +after close, crash durability, cryptographic attestation or physical authority. + +## Preparation, confirmation and exact dispatch + +Select the exact current saved Proposed head and prepare Apply. Preparation +reads the actual target before-image, validates source/head, rejects a no-op, +and displays a precise target-to-candidate diff. It does not write or approve. +Old source/head/preparation references are rejected, not automatically rebased. +Selected and current head IDs are shown separately for explicit feedback. + +Confirmation creates a single-use local opaque approval bound to: + +- Apply or Restore action; +- target provider/kind/instance/source/definition; +- original verified backup identity; +- actual before-image and expected image revision; +- exact full candidate, and workspace/saved head for Apply. + +Authoring versions remain Baseline/Proposed. This confirmation is a deliberate +local rehearsal action, not a Tested/Approved calibration or hardware permit. +Before dispatch, Application revalidates source/head and a fresh full target +read against the approved before-image. A narrow authoring-head guard covers +synchronous dispatch admission; target CAS atomically checks the actual +instance/revision at commit, preventing a change after that read. +Only then is approval consumed and a mutation dispatched. Invalid requests, +stale source/image, no-op and capacity errors consume no approval or write. + +Rehearsal-issued opaque operation IDs support exact active/completed mutation +replay. Repeating the same action/approval ID shares or returns its outcome +without another mutation; different inputs conflict. The session retains one +unused issued ID and bounded latest non-mutation command evidence, not an +unbounded preparation-ID history. Issuing another unused ID supersedes the old +one; expired/foreign IDs cannot authorize fresh commands. Completed dispatched +outcomes remain repeatable within that target's bounded audit. + +## Full readback and RecoveryRequired + +After dispatch, a new independent Read verifies target/source/definition, +expected next revision, both keys, exact units/axis and every changed and +unchanged value. Acknowledgement and readback are displayed separately. +Acknowledgement alone, including an echoed positive candidate, is not Applied +proof. A successful changed commit advances revision once; restore never +pretends the revision/time went backwards. + +If a write may have committed but proof is unavailable, invalid or divergent, +the outcome and current state remain **RecoveryRequired**, with precise +evidence/error and no new Apply. Cancellation before dispatch writes zero; +cancellation after actual commit cannot be labeled safely unchanged. Close +invalidates publication, cancels/drains outside cleanup-required gates and +prevents late Applied/Restored evidence from becoming current. + +No write is automatically resent and no restore is automatic. Choose the latest +unresolved dispatched operation and **Read-only reconcile**. A fresh complete +read classifies: + +- **Unchanged**: exact approved before-image and revision; +- **CandidateMatching**: exact candidate, target identity and expected next revision; +- **Divergent**: valid evidence differs in any value or revision; +- **Unavailable**: missing/invalid current evidence. + +Only exact complete evidence may yield VerifiedAppliedAfterReconciliation or +VerifiedRestoredAfterReconciliation, or verified unchanged. Divergence/unavailable +evidence remains RecoveryRequired. The operation preserves its original +failure, initial verification and initial readback alongside reconciliation; +lost acknowledgement is not erased. Cached observations and candidate values +never substitute for missing proof. + +## Separately approved original Restore and close + +Prepare Restore explicitly, using the original verified backup for the same +open target instance/source. Read fresh current values/revision, confirm a new +Restore approval, dispatch one guarded commit and verify full independent +readback. After scalar 650->1250 and 2000-rpm torque 360->350, Restore returns +650/360 and all unchanged cells/axes, with revision progressing 0->1->2->3. +It does not replace the authoring head, source export or dynamics model. +Failed/uncertain restore remains RecoveryRequired, not Restored. + +Close destroys the isolated target. Its immutable backup/results may remain +visible as inactive evidence, but cannot authorize a new instance. Explicit +reopen seeds source values under a new instance/revision-zero identity and +clears old backup/approval/audit. Leaving the calibration page drains its +page-owned rehearsal; re-entry creates a fresh session. + +## Bounded volatile audit and units + +At most **32 dispatched mutation outcomes per target** are retained, including +successful, rejected-at-port and uncertain Apply/Restore attempts. A new 33rd +dispatch rejects before consuming approval or writing. Exact known mutation +repeats consume no slot. Preparation/reconciliation retain bounded current +evidence and update existing audit records, not another unbounded history. + +Audit includes operation/action/approval, target/backup/source/head/revisions, +full before/expected/actual images, acknowledgement, verification/recovery, +original errors, initial evidence and timestamps. An unavailable completion +timestamp is explicitly null/error rather than a fabricated time or lost +already-dispatched audit outcome. Audit is local and volatile, not a disk format +or external security attestation. + +Human torque display uses the existing Metric/Imperial converter. Programming, +backup and audit equality use exact canonical rpm/N*m and fixed source axes. +Unit changes cannot alter preparation, approval, before-image, saved authoring +values or dispatch commands. + +## Verification status + +Step-09 is accepted; Step-10 remains pending manual review. Real-port tests +exercise independent backup, exact scalar/table/CAS/Restore, malformed/stale +requests, real commit with lost acknowledgement/cancel/read failure, full +unchanged-cell checks, reconciliation, held cleanup and exact 32/33 capacity. +Real rendered controls and live diagnostics/recording/replay coexistence are +also tested. Native normal success is distinct from controlled fault/race proof. +See [build/test evidence](build-and-test.md) and the +[Step-10 worker report](../prompts/Step-10-Report.md). diff --git a/prompts/ROADMAP.md b/prompts/ROADMAP.md index 93183cb..2be7214 100644 --- a/prompts/ROADMAP.md +++ b/prompts/ROADMAP.md @@ -3,17 +3,17 @@ ## Status and authority - Initialized: 2026-10-28. -- Current phase: synthetic calibration authoring accepted; isolated simulated programming rehearsal next. -- Active assignment: [Step-10](Step-10.md), ready for manual worker execution. +- Current phase: Step-10 reviewed; pending-reopen close/disposal lifetime correction remains. +- Active assignment: [Step-10A](Step-10A.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. +- Outstanding correction: Step-10 C-07/C-11 close completion can belong to a previous target lifetime during pending reopen. - 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: 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-10 status: REQUIRES FOCUSED CORRECTION / NOT ACCEPTED, reviewed 2026-10-31. - 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 @@ -427,8 +427,9 @@ Step-08 replay is accepted: exact prefixes/ties, one playback owner, offline RecordedReplay context, source immutability and shared gauges/units are supported. 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. +supported. Step-10 implements isolated simulated programming, but its pending- +reopen close/disposal lifetime needs Step-10A. That is the only active assignment; +local AI remains blocked, with 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. @@ -455,8 +456,9 @@ evidence; they must not silently discard required capabilities. | 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 | 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 | +| 10 | Verified simulated programming and recovery | 09 accepted | REQUIRES FOCUSED CORRECTION / NOT ACCEPTED | Target/backup/approval/CAS/readback/recovery and reported 436-case/native evidence supported; cached old Close completion can bypass drainage of a pending reopen | +| 10A | Close/disposal ownership during pending rehearsal reopen | 10 review C-07/C-11 | READY FOR WORKER | Current target lifetime owns its close completion; cancelled reopen cannot publish after Close/Dispose; controlled factory/cleanup evidence, no programming redesign | +| 11 | Local AI, knowledge, and validated runbooks | 10 and corrections 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 | @@ -906,23 +908,52 @@ history, not repeated redesign without evidence. rehearsal, with explicit volatile backup/approval/readback/unknown/restore semantics and no existing source/model/physical mutation. No renumbering is needed in this handoff. +- Reviewed Step-10's real Simulation image/typed port, two-read backup, immutable + approval and authoring-head guard, target CAS/full readback, uncertainty/ + reconciliation/restore, owner/UI and all new tests/docs. Worker reports clean + nine-project Release build and 179 unit + 257 integration passes (436 total, + zero failed/skipped), native full scalar/table Apply/Restore/reopen and unchanged + source/model evidence. The orchestrator ran no application checks. +- Most scope is supported. One original C-07/C-11 lifetime edge remains: + completed Close is cached until successful Open publication; a competing + Close/Dispose during a new pending Open can return the old completion without + cancelling/draining the new owner. Prepared single-issue + [Step-10A](Step-10A.md); no new programming/AI/physical scope. ### Remaining -- 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. +- Worker execution of Step-10A, then review the controlled pending-reopen close/ + disposal and preserved original target/programming evidence before local AI. +- Step-11 AI is blocked and not assigned. Programming rehearsal exists but remains + unaccepted; authoring/replay and earlier work remain 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 +The single Step-10 finding is close-completion ownership during reopen: + +- CloseAsync returns any cached _closeTask immediately. A completed previous + target's close leaves that task cached. +- A new admitted Open clears _closeTask only when its target publishes + successfully. While factory creation is pending, Close therefore returns the + old task without cancellation, a generation change or current-owner drain. +- Dispose sets _disposed, then uses that same old close task. The pending Open's + publication guard does not check _disposed and permits Closed for an opening + owner; it can publish Ready and retain a new target after disposal returns. +- Existing tests close, fully await reopen and then close again; they do not + hold factory publication across a competing close/unmount. + +This is source-path evidence, not an orchestrator-executed reproduction. +Step-10A requires controlled actual-factory forwarding and exact current close/ +cleanup/late-publication assertions. Keep the supported backup/approval/readback/ +restore, audit limits and native results unchanged. + 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. +program anything. Step-10 supplies separate rehearsal contracts, currently +pending its focused lifetime correction. No blocking Step-08 deficiency was identified against its frozen contract. The worker disclosed an existing recording-panel initialization race when a diff --git a/prompts/STATE.md b/prompts/STATE.md index 574ee8d..4fa66de 100644 --- a/prompts/STATE.md +++ b/prompts/STATE.md @@ -4,15 +4,15 @@ | Field | Value | |---|---| -| Updated | 2026-10-30 | -| 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) | +| Updated | 2026-10-31 | +| Phase | Step-10 reviewed; pending-reopen close/disposal correction remains | +| Active step | Step-10A - Close ownership during pending rehearsal reopen | +| Assignment | [Step-10A.md](Step-10A.md) | | Assignment status | READY FOR WORKER / AWAITING MANUAL HANDOFF | -| Expected worker report | `prompts/Step-10-Report.md` - not yet created | +| Expected worker report | `prompts/Step-10A-Report.md` - not yet created | | Last accepted correction | Step-07B - accepted 2026-10-30 | | Last accepted major milestone | Step-09 - accepted 2026-10-30 | -| Outstanding corrections | None | +| Outstanding correction | Step-10 C-07/C-11 cached prior Close task can bypass pending-reopen cancellation/drain | | Step-02 status | ACCEPTED after Step-02A | | Step-03 status | ACCEPTED after Step-03A/Step-03B | | Step-04 status | ACCEPTED after Step-04A/Step-04B | @@ -24,10 +24,10 @@ | Step-07A review | All original corrective criteria closed with Step-07B | | Step-08 status | ACCEPTED 2026-10-30; no correction required | | 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-10 status | REQUIRES FOCUSED CORRECTION / NOT ACCEPTED | | 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 | +| Worker execution | Step-10 returned; Step-10A not invoked | +| Immediate next action | User manually directs the worker to execute Step-10A with original Step-10 and shared quality gate | | Next orchestrator action | After manual return, inspect the assignment, report, implementation, tests, Git changes, documentation and recorded command evidence | ## Repository baseline at initialization @@ -1121,6 +1121,62 @@ 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. +## Step-10 review and focused lifetime correction + +Decision: **REQUIRES FOCUSED CORRECTION / NOT ACCEPTED**, 2026-10-31. +Reviewed [Step-10](Step-10.md), its [report](Step-10-Report.md), complete target/ +port/backup/approval/mutation/reconciliation/close source, changed authoring +guard/diff helper, actual UI and all five new test partials, docs/README, graph +and existing Release outputs. + +| Area | Decision | Evidence | +|---|---|---| +| Explicit target and independent backup | Supported on inspected evidence | Simulation-only factory, actual separately stored image, defensive full reads, two-read revision-zero backup and source/descriptor rejection | +| Approval/head/CAS/full readback | Supported on inspected evidence | Exact immutable proposal/target/backup/revision binding; source-head admission guard and actual atomic target CAS; scalar/table/all-unrelated-value assertions | +| Uncertain outcomes/reconcile/Restore/audit | Supported on inspected evidence | Lost-ack/read/identity/unchanged-cell faults remain explicit; read-only exact reconciliation, separate original Restore and 32/33 audit limit; no authoring/config/model rewrites | +| Owner/close/reopen | Focused correction required | Held precheck/backup/after-commit close paths work on tested lifetimes; cached prior close completion is not retired before a pending reopen, enabling late target publication | +| Full verification/native/source isolation | Positive evidence supported | Worker reports clean complete Release build, 179 unit + 257 integration passes (436 total, zero failed/skipped), full native scalar/table/Restore/reopen and zero existing-source/model/archive effects | + +### Single remaining finding: cached close belongs to an old target lifetime + +[CloseAsync](../src/AutoForge.Application/Features/Vehicles/Calibration/CalibrationRehearsalSession.cs:444) +returns any non-null _closeTask before checking the current owner. +After closing the first target, the completed task remains cached. + +[OpenAsync](../src/AutoForge.Application/Features/Vehicles/Calibration/CalibrationRehearsalSession.cs:59) +admits a fresh opening owner, but clears _closeTask only inside the successful +target-publication lock. Allowed competing flow: + +1. First Close has completed; its task is still cached. +2. Reopen is admitted; hold actual factory target creation/return before publication. +3. A new Close returns the first Close's completed task without cancelling or + draining this Open. Dispose does the same after setting _disposed. +4. Releasing the factory lets EnsureCurrent accept the opening owner (it permits + Closed and does not test _disposed), so Open publishes Ready/new target after + Close or Dispose has returned. + +This violates original C-07/C-11 and the page/unmount/current-generation drainage +contract, not a new feature preference. The existing sequential reopen/native +checks and held-read tests do not establish this interleaving. + +| Original criterion | Decision | Evidence/gap | +|---|---|---| +| AC-01 | SUPPORTED ON INSPECTED EVIDENCE | Actual target/backup/kind/applicability contracts implemented and tested | +| AC-02 | SUPPORTED ON INSPECTED EVIDENCE | Approval/head/negative/CAS/source/whole-image checks implemented and tested | +| AC-03 | PARTIAL / NOT ACCEPTED | Readback/recovery and most owner paths supported; pending reopen can outlive current Close/Dispose | +| AC-04 | POSITIVE WORKER EVIDENCE REVIEWED | Reported 436 cases/native UI/source isolation supported; missing factory-close overlap remains | +| AC-05 | PARTIAL / NOT ACCEPTED | Docs/matrix/self-review/history preserved; current-close lifetime claim needs focused corrective evidence | + +All 405 baseline cases and 31 added cases remain meaningful positive evidence. +Native full original backup/scalar/table/Restore and new-instance checks are +distinct from controlled factory-close proof. The orchestrator executed no +application build/test/native/workload command or failing reproduction. +Preserve [Step-10-Report.md](Step-10-Report.md) unchanged. + +[Step-10A](Step-10A.md) is limited to current close completion/cancellation/drain +ownership and its regression. No target/protocol/backup/approval redesign, +physical-write permission or Step-11 assignment is introduced. + ## Prerequisites, limitations, and known issues - Step-01A worker evidence establishes portable and native Windows compatibility @@ -1148,23 +1204,23 @@ is later explicit work, not an implied Step-10 feature. Step-11 remains blocked. 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/authoring are accepted. - Simulated programming, AI and physical hardware operations - remain unimplemented. + Simulated programming exists but is unaccepted pending its focused lifetime + correction. 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-10 and its frozen programming-rehearsal contract/shared gate using the +On manual return, evaluate Step-10A and the original Step-10 close/lifetime 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 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 +- Inspect controlled pending-reopen Close/Dispose, lifetime-specific shared + completion, cancellation/target cleanup and late-publication rejection, while + preserving original programming/source evidence. Do not add new AI/physical scope. +- If accepted: close Step-10A, accept corrected 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-10A only for a material unmet contract/ +- If deficient: issue narrowly scoped Step-10B 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. @@ -1241,12 +1297,15 @@ claim; do not claim independent runtime verification. | 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 | +| 2026-10-31 | Step-10 returned and reviewed | Target/backup/approval/CAS/readback/reconcile/Restore/audit and reported 436-case/clean Release/native evidence inspected; most original scope supported | +| 2026-10-31 | Step-10 needs focused lifetime correction | Cached old Close completion can bypass cancelling/draining a pending reopened target and allow publication after Close/Dispose; original C-07/C-11 | +| 2026-10-31 | Step-10A prepared | Single close-lifetime correction with controlled actual factory/cleanup evidence; programming results/source semantics preserved and local AI blocked | ## Manual handoff instruction -Provide [Step-10.md](Step-10.md) and the shared +Provide [Step-10A.md](Step-10A.md), original [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-10-Report.md` +of the focused correction only. The worker must produce `prompts/Step-10A-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-10-Report.md b/prompts/Step-10-Report.md new file mode 100644 index 0000000..bcfb600 --- /dev/null +++ b/prompts/Step-10-Report.md @@ -0,0 +1,298 @@ +``` +# Step-10 - Verified simulated programming and recovery + +## Status + +COMPLETE. The isolated Simulation image/typed port, guarded backup/approval/ +dispatch/readback/reconciliation/Restore workflow, executable contracts, +post-green self-review, full nine-project Release build/regressions and actual +native rehearsal checks passed. + +Step-10 remains pending manual orchestrator review. This report does not grant +acceptance. Accepted Step-09 and all 405 baseline cases are preserved. +Step-11 local AI and every physical operation remain unimplemented/unassigned. +No agents, automatic handoff, staging, commit or push occurred. + +## Functions, files and interfaces + +- [CalibrationProgrammingPort.cs](../src/AutoForge.Diagnostics/CalibrationProgrammingPort.cs): + separate narrow ISimulatedCalibrationTargetFactory/ISimulatedCalibrationTarget + contracts and defensive Identity/Image/Commit/Acknowledgement models. + No new wire protocol, raw commands, firmware blocks or hardware driver. +- [SimulatedCalibrationTarget.cs](../src/AutoForge.Simulation/SimulatedCalibrationTarget.cs): + actual explicit autoforge.simulation.calibration-rehearsal provider, independently + stored supported image, unique instance identity, complete actual Read, + validated atomic instance/revision CAS and target destruction on Close. + Seeded once from the exact source configuration; it never changes a + DynamicsEngine/configuration/profile/diagnostic source. +- [CalibrationRehearsalModels.cs](../src/AutoForge.Application/Features/Vehicles/Calibration/CalibrationRehearsalModels.cs): + typed failures/states, immutable verified volatile backup, preparation, + single-use approval and bounded mutation/reconciliation evidence. +- [CalibrationRehearsalSession.cs](../src/AutoForge.Application/Features/Vehicles/Calibration/CalibrationRehearsalSession.cs): + fresh-session factory, NewOperationId, OpenAsync, PrepareBackupAsync, + PrepareApplyAsync, PrepareRestoreAsync, Approve, ExecuteAsync, + ReconcileAsync, CloseAsync/DisposeAsync and immutable Snapshot. + One operation owner, exact request replay/conflict guards, full independent + readback, explicit RecoveryRequired and generation-safe drainage. +- [CalibrationAuthoringService.cs](../src/AutoForge.Application/Features/Vehicles/Calibration/CalibrationAuthoringService.cs): + minimal internal synchronous current-head dispatch guard and shared pure + CalibrationValueDifferences extraction. Existing authoring validation, + Baseline/Proposed status, immutable history and exact diff semantics remain. +- [CalibrationRehearsalPanel.razor](../src/AutoForge.UI/Features/Vehicles/Calibration/CalibrationRehearsalPanel.razor): + actual explicit provider/open/backup/proposal/prepare/confirm/dispatch/ + reconcile/Restore/close controls, selected/current head feedback, distinct + acknowledgement/readback, full image/audit inspection and safe errors. + [CalibrationPage.razor](../src/AutoForge.UI/Features/Vehicles/Calibration/CalibrationPage.razor) + hosts this separate page-owned rehearsal beside the authoring editor. +- [AddAutoForgeUi.cs](../src/AutoForge.UI/Features/Foundation/AddAutoForgeUi.cs) + and [MauiProgram.cs](../src/AutoForge.Client/MauiProgram.cs): + fresh rehearsal factory registration and the explicit real Simulation port. + This is not a diagnostic-provider fallback or a model permission. + +Tests: + +- [CalibrationRehearsalTests.cs](../src/tests/AutoForge.IntegrationTests/CalibrationRehearsalTests.cs) +- [CalibrationRehearsalLifecycleTests.cs](../src/tests/AutoForge.IntegrationTests/CalibrationRehearsalLifecycleTests.cs) +- [CalibrationRehearsalReviewTests.cs](../src/tests/AutoForge.IntegrationTests/CalibrationRehearsalReviewTests.cs) +- [CalibrationRehearsalUiTests.cs](../src/tests/AutoForge.IntegrationTests/CalibrationRehearsalUiTests.cs) +- [CalibrationRehearsalIsolationTests.cs](../src/tests/AutoForge.IntegrationTests/CalibrationRehearsalIsolationTests.cs) + +The initial success/negative/backup/fault/owner/capacity/rendered contracts +were written before production implementation. Post-green review added the +remaining cancellation/head/clock/cleanup/real-coexistence coverage. +Tests forward the actual Simulation target below Application; the workflow +is not mocked and no implementation private state/oracle supplies readback. + +## Frozen C-01..C-12 matrix + +All rows below are PASSED. Named methods were executed tests, not suggestions. + +| ID | Named evidence and exact result | +|---|---| +| C-01 | ExplicitTargetAndIndependentBackup_ReadActualDefensiveRevisionZeroImage; WrongSourceAndDescriptorRejectBeforeTargetFactoryOpens. Explicit valid workspace/source and the registered Simulation provider open one fresh independent target. PhysicalHardware, RecordedReplay, undefined/wrong provider/descriptor/workspace reject with OpenCount=0. Actual source/definition is validated before seed; wrong config/definition rejects. No target opens on authoring Save or render. | +| C-02 | ExplicitTargetAndIndependentBackup_ReadActualDefensiveRevisionZeroImage; IndependentBackupFailure_NeverPublishesFakeVerifiedOrApproval (identity/revision/cell/shape/read-failure). Exactly two independent real-port reads establish revision-zero identity/shape/axis/unit/value equality. Backup covers scalar 650 and all six original torque rows, is defensively copied, and remains the original backup. Wrong/partial/mismatched/unavailable second reads publish no verified backup/approval and write zero. | +| C-03 | ScalarThenTableApplyAndSeparatelyApprovedRestore_VerifyTheFullActualImage; RenderedRehearsal_BackupConfirmationApplyAndRestoreUseActualPortWithoutAuthoringStatusRewrite. Preparation shows actual before 650->candidate 1250, delta +600 rpm. Immutable approval binds exact source/instance/backup/head/before revision/action. Fresh precheck plus source-head guard precede one dispatch. Independent full readback establishes revision 1, scalar 1250 and every torque cell unchanged; source config/baseline remain 650 and authoring remains Proposed. | +| C-04 | The same real target and actual rendered test; native full readback. Saved next proposal changes only 2000-rpm torque 360->350. Fresh approval binds current target revision 1; one dispatch/readback yields revision 2, scalar 1250, fixed original axes and exactly that cell changed. All other cells are checked, not only acknowledgement or selected value. | +| C-05 | InvalidConfirmationTokenActionHeadAndNoOp_RejectBeforeConsumptionOrWrite; ActualTargetRejectsBadIdentityRevisionShapeAndValuesBeforeAtomicCommit; accepted authoring/template regressions. Missing backup, wrong/unconfirmed token/action, stale head/source/image, no-op, wrong kind and invalid shape reject before approval consumption or mutation. Direct real target CAS rejects wrong instance/revision and cancelled/invalid full candidate while image stays revision 0. Required source-unit/shape/value validation is the unchanged tested Core template, not a new weak write validator. | +| C-06 | FreshReadAndActualTargetCas_PreventChangesBeforeAndAfterDispatchPrecheck; AuthoringHeadChangesDuringHeldFreshPrecheck_RejectBeforeApprovalConsumptionOrCommit; CloseReopen_InvalidatesOldTargetBackupApprovalAndRetainsInactiveAudit. Head/workspace changes during held precheck reject StaleSource, zero dispatch and unconsumed approval. Actual image changes before precheck reject with WriteCount=0; change after the read conflicts at actual target CAS and fresh divergent evidence remains RecoveryRequired, not Applied. Reopen creates a new instance and old approval/backup cannot authorize it. | +| C-07 | HeldPrecheck_SharesExactOperationRejectsConflictsAndCancelBeforeDispatchWritesZero; CancellationAfterCommitAndClose_DrainsOutsideGateAndNeverPublishesLateApplied; CancelAfterActualCommitWithoutClose_BlocksNewApplyUntilReadOnlyReconciliation. Exact active request returns the same Task; conflicting ID/action or competing operation rejects. Cancel before dispatch writes zero, keeps approval unconsumed and creates no audit mutation. After actual commit, cancellation consumes approval, retains one RecoveryRequired outcome and blocks new Apply. Close shares/drains completion outside required gates; old-generation late Applied cannot become current evidence. Exact completed mutation repeats return the same existing outcome, including at capacity. | +| C-08 | UncertainCommit_RequiresReadOnlyReconcileAndPreservesOriginalFailure (lost ack/read failure/wrong identity/unchanged-cell mismatch); PositiveEchoWithoutMutation_IsNotAppliedAndFreshRevisionProofResolvesUnchanged; FailedOrLostRestore_RemainsRecoveryRequiredAndOriginalBackupNeverChanges. Acknowledgement alone never establishes Applied. Actual commit with lost acknowledgement/missing proof is RecoveryRequired with precise original evidence. Divergent unchanged cells/identity are not hidden. An echoed positive ack with actual revision 0/value 650 is not Applied. Failed/unknown Restore remains RecoveryRequired, not Restored or healthy unchanged success. | +| C-09 | RejectedPortAndDivergentReconcile_NeverBlindlyRetryOrRestore; UncertainCommit_RequiresReadOnlyReconcileAndPreservesOriginalFailure; rendered lost-ack test. Explicit fresh read-only reconciliation proves unchanged at exact before revision, candidate-matching only at the expected next revision, or divergent/unavailable. Lost-ack actual candidate proof becomes VerifiedAppliedAfterReconciliation while preserving original failure/initial evidence. Divergent/unavailable remains RecoveryRequired. No write is resent and no restore is automatic; write count stays unchanged through reconciliation. | +| C-10 | ScalarThenTableApplyAndSeparatelyApprovedRestore_VerifyTheFullActualImage; FailedOrLostRestore_RemainsRecoveryRequiredAndOriginalBackupNeverChanges. After two successful applies, a distinct fresh Restore preparation/confirmation/approval binds original backup and current revision 2. One full guarded write plus independent readback restores 650 and torque (240,300,360,350,300,180) on unchanged axes, at revision 3. Authoring/configuration/history are not rewritten. Lost-ack Restore can become VerifiedRestoredAfterReconciliation only from exact full revision/content proof. | +| C-11 | HeldBackupReadAfterClose_CannotPublishOldBackupIntoNewInstance; PendingPortFailureDuringClose_PersistsErrorAndSharesFailedCleanupCompletion; CloseReopen_InvalidatesOldTargetBackupApprovalAndRetainsInactiveAudit. Pending/late reads cannot publish a backup after close/new generation. A held real-port failure during close remains visible and repeated close shares the failed completion, while target cleanup still runs. Wrong/new instance has no old-backup restore authority. Test barriers release in finally; owned work is drained and disposal clears subscriptions on failure. | +| C-12 | DispatchedAuditLimit_IsExactly32AndExactOperationReplayConsumesNoSlot; RehearsalIsolation_ActualLiveRecordingReplayAndConfigurationRemainIsolatedFromApplyRestore; RenderedRehearsal_LostAckRecoveryAndUnitRerendersDoNotResendMutation; CompletionClockFailure_CannotLoseAnAlreadyDispatchedAuditOutcome. Exactly 32 dispatched Apply/Restore outcomes are retained; changed attempt 33 rejects before consume/write, while exact known repeat adds no slot. Preparations/command IDs retain bounded current evidence, not hidden unbounded history. Unit rerender changes no approval/read/write. Actual existing live transport/model/store-Save deltas are zero, with unchanged config/export/trace/status/archive/authoring/replay. A failed completion clock explicitly records null/error rather than losing a dispatched outcome. All 405 regressions plus 31 new cases and native workflow passed. | + +## Acceptance criteria + +| ID | Result | Evidence | +|---|---|---| +| AC-01 | PASSED | C-01/C-02 actual independent Simulation target/port, source-kind/applicability validation and two-read supported-image backup; no baseline/request echo substituted for readback. | +| AC-02 | PASSED | C-03..C-06 exact approval/head/backup/revision/content binding, full scalar/table/unrelated-cell results, stale/CAS/negative tests and zero-write rejected paths. | +| AC-03 | PASSED | C-07..C-11 controlled real-port idempotence/cancellation/drain/late/fault/reconciliation, original errors retained and separately approved full original Restore. | +| AC-04 | PASSED | C-12 exact 32/33 capacity, real rendered/native workflow and zero unassigned source calls; all 436 cases and all nine Release projects pass. | +| AC-05 | PASSED | Executable matrix, own post-green producer/consumer review/fixes, truthful docs/README/report, protected history/dependencies/manual workflow and cleanup preserved. | + +## Commands and outcomes + +Current SDK: dotnet --version -> 10.0.403 under unchanged global.json policy. +Tests remain existing xUnit v2/VSTest. No package/SDK/workload/tool was +installed, restored, updated or repaired. + +Final focused, build and complete regression commands ran sequentially: + +| Exact command | Exit | Result | +|---|---:|---| +| dotnet test .\src\tests\AutoForge.IntegrationTests\AutoForge.IntegrationTests.csproj --configuration Release --no-restore --filter "FullyQualifiedName~CalibrationRehearsalTests|FullyQualifiedName~RenderedRehearsal|FullyQualifiedName~RehearsalIsolation|FullyQualifiedName~CalibrationAuthoringTests" | 0 | 86 passed: 31 new rehearsal cases plus 55 accepted authoring cases; zero failed/skipped. | +| dotnet build .\src\AutoForge.slnx --configuration Release --no-restore | 0 | All nine projects/native Client; 0 warnings, 0 errors. XAML source-generation output was informational. | +| dotnet test .\src\AutoForge.slnx --configuration Release --no-build | 0 | 179 unit + 257 integration = 436 passed; zero failed/skipped. | +| git --no-pager diff --check | 0 | No whitespace errors; existing LF-to-CRLF notices for README/build guide only. | +| git --no-pager diff --exit-code -- prompts global.json Directory.Build.props Directory.Packages.props NuGet.Config src\AutoForge.Core src\AutoForge.Diagnostics src\AutoForge.Simulation src\AutoForge.Application\Features\Vehicles\Telemetry | 0 | Existing protected/history/dependency/Core/live/recording/replay tracked implementations unchanged before adding this report. New typed-port/rehearsal files are explicitly in scope. | + +Per-project Release results: AutoForge.Core, AutoForge.Diagnostics, +AutoForge.Simulation, AutoForge.Application, AutoForge.Components, +AutoForge.UI, AutoForge.Client, AutoForge.UnitTests and +AutoForge.IntegrationTests all PASSED. Portable projects remain net10.0; +Client remains net10.0-windows10.0.26100.0 / win-x64. + +405 baseline cases (179 unit + 226 integration) remain present and pass; this +step adds 31 integration cases without deleting/weakening baseline assertions. +The focused UI test was extended to exercise the second saved table proposal, +not only first Apply/Restore. Existing template, authoring, archive, gauge and +replay limits remain unchanged. Rehearsal adds only the explicit 32 dispatched +mutation-outcome bound per target. + +Iteration evidence: + +- Initial compilation failures involved generic owner type inference and one + Razor namespace import. Both were corrected before executable results. +- The first executable focused run had 21 passes/2 failures: a test's + post-write read-failure flag also intercepted the next operation's + precheck after an earlier write. Fault forwarding now binds to the intended + next dispatch count, below the real Application workflow. +- The first green run passed 23 cases. Post-green review expanded coverage + to 31 new cases; the combined accepted-authoring selection passed 86. +- A native second-proposal selection issue was inspected with exact + selected/current-head feedback and an actual rendered second-proposal + event regression (passed). Fast native event/DOM sequencing rejected + stale source without another write; explicit settled current-head selection + then completed the real table Apply/Restore path. Native-helper null + readiness predicates were also corrected; their errors are not claimed + as implementation failures or successful smoke observations. +- Final focused, nine-project build and complete 436-case suite were rerun + after source/head feedback and UI test additions. Compilation failures + are not claimed as behavioral pre-fix reproductions. + +## Native evidence versus controlled proof + +The actual rebuilt Windows Client was operated through a task-owned WebView2 +profile and local DevTools port 9380 with a temporary built-in Node/WebSocket +helper. No second web host, new dependency or production debug/fault feature +was added. + +Normal native workflow: + +1. Explicitly created the warm profile/configuration through the existing + simulation route, retained its exact original export/fingerprint, then + created authoring baseline and saved the 1250-rpm proposal. Rehearsal + remained Inactive/audit 0 on Save; no implicit target or mutation. +2. Selected autoforge.simulation.calibration-rehearsal and opened an isolated + Simulation instance. Two actual independent reads produced the verified + supported-image backup at revision 0. Unconfirmed approval visibly rejected. +3. Confirmed/approved scalar Apply. Unit switch preserved the exact unconsumed + approval text/identity and audit 0. One dispatch/full readback showed + 1250 rpm at revision 1, with all six original torque cells. Repeating the + exact action returned the existing result with audit count 1. +4. Saved the table proposal and explicitly selected its current saved head. + Fresh preparation showed only 2000-rpm torque 360->350, delta -10 N*m. + New confirmation/approval/dispatch produced revision 2 with scalar 1250, + that cell 350, and all unrelated cells/axes unchanged. +5. Prepared original-backup Restore separately. Its diff was table 350->360 + and scalar 1250->650. A new explicit Restore approval/dispatch plus full + independent readback yielded revision 3 with scalar 650 and all torque + cells (240,300,360,350,300,180) on the original six rpm axes. +6. Closed the target. Its backup was explicitly labeled inactive, not + new-instance authority. Reopen created a different instance with audit 0, + no old backup and no approval. Restore without a fresh backup rejected. +7. Original source export stayed byte-for-byte string-identical, fingerprint: + sha256:v1:e8991ae139b54959ec53a4fe64b08dc9bfc03feb533496cf741f2c9f3a2342da. + Original warm-idle parameter remained 650 rpm and original 2000-rpm torque + remained 360 N*m. A separately opened real dynamics session stepped to + model step 7 / 0.7 seconds and read engine speed 631.80416 rpm / Good / + SYNTHETIC_DYNAMIC, not the rehearsal's 1250 image. This is unchanged-source + diagnostic evidence, not performance validation of the proposal. +8. Closed that ordinary dynamics source and exercised replay/home navigation. + Replay was Unloaded; no capture was substituted. Original Metric/Road + preferences were restored and observed. No native unhandled error overlay + appeared during the completed workflow. + +Completed native target/backup/action evidence: + +- Target instance f6c8f8226562440d84b9726e916d42a2. +- Original backup cfc96e2c5dcd4838a9d94625da35ba6c, revision 0. +- Table Apply operation 7ef765105d294289a3bcb6e9fa0be308: + actual revision 2 / CandidateMatching / VerifiedApplied. +- Original Restore operation 0981ac75b8a7419f81c340706cf5a138: + actual revision 3 / CandidateMatching / VerifiedRestored. +- Fresh reopened instance 5a13d4429f744d2db37362026c299b3b: + no prior backup/approval/audit and no old restore permission. + +Native inspection opened the full before/expected/actual details. Exact first +readback was scalar 1250 and torque (240,300,360,350,300,180); second was scalar +1250 and torque (240,300,350,350,300,180); Restore was scalar 650 and the +complete original tuple. Every rpm axis stayed 650,1000,2000,3200,4200,5000. + +Native limitations: normal success/readiness/source feedback is not controlled +port-fault, cancellation, concurrency or 32/33-capacity proof. Those cases use +actual target forwarding plus explicit barriers in headless tests. Initial +fast automated selection caused visible stale-head rejection and a helper +DOM-readiness timeout, preserving the prior one-write state; that incomplete +attempt was closed/destroyed, not represented as restored. The second rebuilt +native session performed the entire successful backup/two-Apply/Restore/ +reopen/source-isolation sequence. + +Cleanup PASSED: both task-owned Client process sessions completed; only their +specific PIDs 8828 and 25884 were terminated after target/source close or page +cleanup. The task-only WebView profile/helper were removed, no task WebView +processes remained and port 9380 had no listener. Native profile/configuration/ +proposal/rehearsal data were volatile only. The real app-local recordings +directory remained empty; no user archive/file or existing/default WebView +data was deleted or reset. Original user preference values were restored. + +## Own post-green source-path review + +Reviewed actual authoring/configuration/profile selection -> registered typed +factory -> Simulation-owned independent image -> two-read backup -> prepared +before/candidate -> confirmation/approval -> fresh precheck/source-head guard -> +actual target CAS -> independent full readback -> audit/reconciliation -> +separately approved Restore -> close/unmount/new generation. + +Public entry points reviewed were target Open/ReadAsync/CommitAsync/DisposeAsync, +rehearsal NewOperationId/Open/PrepareBackup/PrepareApply/PrepareRestore/Approve/ +Execute/Reconcile/Close/Dispose/Snapshot, and actual rendered controls/units/ +authoring notifications. Normal, rejected, no-op, stale, uncertain, capacity, +repeat, cancellation and cleanup paths were walked against C-01..C-12. + +Review fixes/additions completed within Step-10: + +- After a real commit, caller cancellation now publishes RecoveryRequired + into the still-open session, not only its audit, preventing a new Apply + before read-only reconciliation. Close remains generation guarded. +- Immutable dispatched evidence survives completion-clock failure with an + explicit null/error timestamp instead of losing a counted mutation outcome. +- Opening revalidates the current workspace before publication; head dispatch + admission uses a narrow synchronous authoring guard, while target CAS covers + later image changes. No required gate remains held across async cleanup. +- Disposal clears subscriptions even when target/port cleanup reports failure. + Authoring-to-panel notifications marshal UI fields through the dispatcher. +- Added positive-ack-without-real-mutation, held source-head changes, actual + cancellation after commit, failed close completion and real live/recording/ + replay coexistence tests. Original errors/initial evidence remain explicit. +- Added selected/current-head feedback and precise rejection reasons, and + executed actual rendered second-proposal/table Apply before Restore. + +Validation/eligibility precede consume/write/count commitments. Full changed +and unchanged image equality plus exact revision determines proof, never an +ack/request echo. Exact repeats cannot create another write; unknown outcomes +never silently retry/restore. Backup/approval/audit values are copied and +bounded. New instances cannot inherit authority. Application/UI do not read +private Simulation state, and no source configuration/model/authoring status/ +recording/replay is mutated by rehearsal. + +Affected focused/full checks were rerun after these changes, with final 86/436 +passes and native complete workflow. No known unresolved defect in the +assigned exit contract remains. + +## Documentation 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 +[authoring contracts](../docs/calibration-authoring.md); added +[rehearsal usage/contracts](../docs/calibration-rehearsal.md). +They distinguish accepted Step-09 from Step-10 pending review, isolated typed +Simulation target from a real wire/model application, volatile supported-image +backup, single-use exact approval/CAS/readback, RecoveryRequired/read-only +reconciliation/separate Restore, bounded audit and native/control evidence. + +Worktree began clean on main at 997b17f and HEAD is unchanged. Existing +prompts/state/roadmap/assignment/history/shared gate were not edited; this is +the only new prompts file. Protected instruction files were not created or +modified. The index remains empty. No new project/package/host/schema/protocol +or project-reference change, dependency/system operation, agent, automatic +handoff, staging/commit/push occurred. + +Core/source template, existing DynamicsEngine/diagnostic protocols/providers/ +oracles/configuration catalogue, authoring statuses/history and recording/ +replay implementation remain unchanged except the explicitly scoped shared +authoring diff extraction/current-head dispatch guard. New Diagnostics and +Simulation files implement the narrow isolated target only. +Source/tests remain under src/src/tests; docs remain under docs. The separately +disclosed recording navigation/refresh issue was not modified. + +Out of scope remains physical programming/driver/firmware blocks, dynamics +application/performance reruns, durable/full-device calibration backups/audit, +AI/runbooks, new templates/units/offsets and unrelated cleanup. + +STOP. +``` diff --git a/prompts/Step-10A.md b/prompts/Step-10A.md new file mode 100644 index 0000000..ceeecd1 --- /dev/null +++ b/prompts/Step-10A.md @@ -0,0 +1,173 @@ +# Step-10A - Close ownership during pending rehearsal reopen + +## STEP IDENTIFIER + +Step-10A, single-issue correction of existing Step-10 C-07/C-11 / AC-03. +Step-10 is NOT ACCEPTED. Step-09 and earlier accepted work remain accepted. +This is the sole active assignment; Step-11 local AI remains blocked. + +## STEP TITLE + +Bind close/disposal completion to the current rehearsal lifetime so a pending +reopen cannot publish a new target after Close or Dispose has finished. + +## OBJECTIVE + +Fix one current-owner/close-task lifetime issue. Preserve the supported target, +backup, approval, source-head/CAS, fresh verification/recovery/Restore and bounded +audit. Do not redesign programming or implement new features. + +Read [STATE.md](STATE.md), original [Step-10](Step-10.md), its preserved +[report](Step-10-Report.md) and [WORKER-QUALITY-GATE.md](WORKER-QUALITY-GATE.md). +Reproduce the actual interleaving, fix and self-review inside this assignment, +write `prompts/Step-10A-Report.md`, and STOP. + +## ARCHITECTURAL CONTEXT + +Keep all nine projects, one Client, Simulation-owned real target, typed +Diagnostics ports and existing Application/UI rehearsal ownership. +No project/package/host, new protocol, general lifetime framework, physical +driver or model/source mutation. Source/tests stay under `src`, tests under +`src/tests`. Original in-memory supported-image and safety limits remain. + +## CURRENT IMPLEMENTATION STATE + +Worker-reported Step-10 evidence: 179 unit + 257 integration passes (436 total, +zero failed/skipped), clean full nine-project Release build and native complete +backup/scalar/table Apply/Restore/reopen/source-isolation checks. Preserve all +405 prior cases and 31 additions plus their original reports. + +One original lifetime requirement remains in +[CalibrationRehearsalSession](../src/AutoForge.Application/Features/Vehicles/Calibration/CalibrationRehearsalSession.cs): + +- CloseAsync (around line 444) returns any non-null _closeTask immediately. +- Completed Close retains that task. New Open clears it only after successful + factory creation and current-owner publication (around line 90). +- A new admitted Open can therefore be pending while Close returns the previous + lifetime's already-completed task without cancellation/generation change/drain. +- Dispose sets _disposed but also returns via that prior close completion; + EnsureCurrent permits Closed for an opening owner and does not test _disposed. + The pending Open can then publish Ready/new target after disposal returned. + +Existing tests/native checks fully await reopen before closing again; held-read +and post-commit tests do not force this factory-before-publication window. +This is source-inspection evidence, not an orchestrator-executed reproduction. +Reinspect Git and preserve existing worker changes/history before editing. + +## REQUIRED IMPLEMENTATION + +Make the smallest sound coordination/ordering change so a new admitted target +lifetime cannot reuse a previous lifetime's completed or failed close task. +Current Close/Dispose must invalidate/cancel its actual pending owner and wait +for that owner's cleanup before returning; late factory results cannot publish. + +Retain one shared close completion for repeated callers within the same lifetime. +Bind it safely before competing callers can start cleanup twice. Do not publish +success before current work drains, clear it only after successful publication, +or discard the existing single-owner/cancellation/error contract. + +Preserve valid sequential reopen, failed-open state, old inactive evidence, +late-registration/operation rejection, and exact target disposal. A fully disposed +page session remains unusable; successful Close alone may permit explicit fresh +Open. Old approvals/backups never authorize a new instance. +No wait may hold a gate needed by cleanup. + +### Frozen corrective matrix + +| ID | Input/precondition | Required result | +|---|---|---| +| C-01 | Normal close/repeated close and sequential explicit reopen | Existing target closes once; same-lifetime repeated Close shares completion; reopen gets a distinct instance/revision-zero state without old backup/approval | +| C-02 | Prior Close completed; actual factory is held during new admitted Open; competing Close arrives | New Close does not return the old completion or finish while Open/cleanup is held. It cancels/invalidates current Open; after release, created target is disposed exactly once and no Ready/current target is published. | +| C-03 | Same pending reopen, then Dispose/page unmount | Disposal drains the actual opening owner/target and cannot return through the prior close task. No late Ready/backup/approval publication; disposed session rejects further operations. | +| C-04 | Earlier Close failed or pending Open itself fails; current close callers/cleanup also compete | Current lifetime gets its own shared completion/error, not a replay of stale failure. Cleanup executes once, errors remain explicit, rejected opens preserve required inactive evidence and later valid sequential behavior. | +| C-05 | Original target/backup/approval/CAS/readback/reconcile/Restore/audit/units/source/native contracts | All 436 baseline cases and meaningful new regressions pass, limits/data semantics preserved, no existing-model/physical side effects or new AI work | + +## FILES OR PROJECTS EXPECTED TO CHANGE + +Existing rehearsal-session open/close/disposal coordination and, only if a +real coupled assertion requires it, page cleanup. Focused integration tests with +a test-only factory/target barrier wrapper and directly related lifecycle/docs/ +README/verification record. No programming/target/approval/port redesign. +Only `prompts/Step-10A-Report.md` under `prompts`; no assignment, roadmap/state, +gate, previous report or protected-file edit. + +## INTERFACE AND DEPENDENCY REQUIREMENTS + +Preserve nine projects/references, actual Simulation target state, exact +source/instance/revision/head/backup/approval binding, defensive full images, +single owner, volatile audit limit 32, unknown/reconcile/Restore semantics and +unchanged diagnostics/dynamics/recording/replay/source configurations. +No hardware/model write, new schema/unit/template, oracle, silent fallback, +early close-success or error-swallowing shortcut. +No dependency/system/workload install/update/repair/rollback, staging/commit/ +push or destructive Git. Preserve existing dirty work and protected history. + +## TESTING REQUIREMENTS + +1. Establish C-02/C-03 using a controlled wrapper forwarding the actual + SimulatedCalibrationTargetFactory. Hold the second factory creation/return + after Open admission but before publication. Run the held synchronous Open + in a task-owned concurrent test so the competing Close/Dispose can execute. + Do not mock away the rehearsal service or use a production race selector. +2. Record actual pre-fix assertions: prior close completion is reused/finishes + without current drainage, then released Open publishes an active target after + closure/disposal. This must be behavior evidence, not a compilation failure. + If observed behavior differs, report exact results rather than inventing a + failure. Deadlines are cleanup safety guards, not timing-race proof. +3. After the fix, assert current-close completion identity, cancellation/drain, + no late publication, actual created target's dispose count, retained inactive + evidence and further-operation rejection. Exercise both Close and Dispose. +4. Include a prior failed-close case, failing/rejected reopen and repeated current + close callers; preserve visible current cleanup errors and valid normal reopen. +5. Release every barrier and drain opening/closing work in finally before + disposing providers/observers. No stranded workers, sleeps/polling or GC/memory + benchmarks as correctness proof. + +Run focused cases, then sequentially: + +- `dotnet build .\src\AutoForge.slnx --configuration Release --no-restore` +- `dotnet test .\src\AutoForge.slnx --configuration Release --no-build` + +Preserve 436 baseline cases (179 unit, 257 integration) plus meaningful new +assertions. Record exact commands/exits/warnings/per-project counts; build all +nine projects/native Client. Install/restore nothing absent a genuine chosen- +command missing dependency. + +Native recheck: normal isolated target/backup/Apply/Restore/Close/reopen, source/ +unit isolation and calibration route close/re-entry. The pending-factory race is +controlled test proof, not a human-timed native claim. Clean only exact task-owned +profiles/artifacts; preserve unrelated files/preferences. + +## DOCUMENTATION REQUIREMENTS + +Align current target-lifetime close completion/cancellation/drain and matching +evidence with actual behavior. Preserve original Step-10 programming/native +results unchanged; no new backup durability or physical/model claim. +Step-10 remains pending review; Step-11 is not implemented or assigned. + +## ACCEPTANCE CRITERIA + +| ID | Criterion | Evidence | +|---|---|---| +| AC-01 | C-01..C-03 current Close/Dispose drains pending reopen with no old completion reuse or late target publication | Actual safely cleaned pre-fix and controlled post-fix factory/target/cancellation assertions | +| AC-02 | C-04 same-lifetime shared completion, current errors, failed-open/close and valid sequential reopen preserved | Completion identity/dispose-count/error/state tests and source-path ordering review | +| AC-03 | C-05 original 436 regressions, new cases, full Release/native build and required baseline pass | Exact complete worker results and native/control distinction | +| AC-04 | Original scope/history/protection/docs/self-review/report/manual gate preserved | Own post-green source-path review and `prompts/Step-10A-Report.md` | + +## OUT-OF-SCOPE WORK + +Programming/approval/backup/recovery redesign, target/port/model/physics changes, +new durable storage/schema/limits/unit family, local AI/runbooks, hardware, +new project/package/host and unrelated cleanup. No future assignment, agents, +automatic handoff, orchestration/shared-gate edit, staging, commit or push. + +## REPORTING REQUIREMENTS + +Save `prompts/Step-10A-Report.md` entirely inside exactly one plain triple-backtick +fence, no language tag/outside text/nested fences. Include identifier/title/status, +functions/files/interfaces, C-01..C-05/AC-01..AC-04 mapping, actual pre/post +barrier/completion/state/target-disposal results, commands/exits/warnings/ +per-project counts, native versus controlled coverage, docs/README, own post- +green source-path self-review, limitations/deviations/blockers and preservation. +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 index 394cea7..15f7a07 100644 --- a/src/AutoForge.Application/Features/Vehicles/Calibration/CalibrationAuthoringService.cs +++ b/src/AutoForge.Application/Features/Vehicles/Calibration/CalibrationAuthoringService.cs @@ -133,6 +133,15 @@ public sealed class CalibrationAuthoringService(IDynamicsConfigurationService co return version; } + internal T AtCurrentHead(string workspaceIdentifier, string headIdentifier, Func dispatch) + { + lock (_gate) + { + EnsureHead(RequireWorkspace(workspaceIdentifier), headIdentifier); + return dispatch(); + } + } + public CalibrationDiff Compare(string workspaceIdentifier, string fromIdentifier, string toIdentifier) { lock (_gate) @@ -140,23 +149,8 @@ public sealed class CalibrationAuthoringService(IDynamicsConfigurationService co 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())); + CalibrationValueDifferences.Compare(from.Values, to.Values)); } } @@ -219,6 +213,29 @@ public sealed class CalibrationAuthoringService(IDynamicsConfigurationService co private static CalibrationAuthoringException Failure(CalibrationFailure failure, string message) => new(failure, message); } +internal static class CalibrationValueDifferences +{ + public static IReadOnlyList Compare(CalibrationValues before, CalibrationValues after) + { + var entries = new List(); + var beforeScalar = before.Scalars[0]; + var afterScalar = after.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 = before.Tables[0]; + var afterTable = after.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 Array.AsReadOnly(entries.OrderBy(entry => entry.LogicalIdentifier, StringComparer.Ordinal) + .ThenBy(entry => entry.AxisCoordinate).ToArray()); + } +} + public static class CalibrationAuthoringServiceCollectionExtensions { public static IServiceCollection AddAutoForgeCalibrationAuthoring(this IServiceCollection services) diff --git a/src/AutoForge.Application/Features/Vehicles/Calibration/CalibrationRehearsalModels.cs b/src/AutoForge.Application/Features/Vehicles/Calibration/CalibrationRehearsalModels.cs new file mode 100644 index 0000000..95d44e4 --- /dev/null +++ b/src/AutoForge.Application/Features/Vehicles/Calibration/CalibrationRehearsalModels.cs @@ -0,0 +1,55 @@ +using AutoForge.Core.Calibration; +using AutoForge.Diagnostics; + +namespace AutoForge.Application.Features.Vehicles.Calibration; + +public enum CalibrationMutationAction { Apply, Restore } +public enum RehearsalState { Inactive, Ready, RecoveryRequired, Closing, Closed } +public enum RehearsalImageClassification { Unchanged, CandidateMatching, Divergent, Unavailable } +public enum RehearsalVerification +{ + VerifiedApplied, VerifiedRestored, VerifiedUnchanged, RecoveryRequired, + VerifiedAppliedAfterReconciliation, VerifiedRestoredAfterReconciliation +} +public enum RehearsalFailure +{ + InvalidTarget, Closed, Busy, OperationConflict, BackupRequired, InvalidImage, + InvalidApproval, ConfirmationRequired, StaleSource, StaleImage, NoChange, + RecoveryRequired, AuditLimit, InvalidCommand +} +public sealed class CalibrationRehearsalException(RehearsalFailure failure, string message, Exception? inner = null) : Exception(message, inner) +{ + public RehearsalFailure Failure { get; } = failure; +} +public sealed class VerifiedCalibrationBackup +{ + internal VerifiedCalibrationBackup(CalibrationTargetImage image, DateTimeOffset verifiedAt) + { + Identifier = Guid.NewGuid().ToString("N"); + Image = new(image.Identity, image.Revision, image.Values); + VerifiedAt = verifiedAt; + } + public string Identifier { get; } + public CalibrationTargetImage Image { get; } + public DateTimeOffset VerifiedAt { get; } + public string Label => "Verified in-memory backup of supported simulation image"; +} +public sealed record CalibrationPreparation( + string Identifier, CalibrationMutationAction Action, string BackupIdentifier, + CalibrationTargetImage Before, CalibrationValues Candidate, + string? WorkspaceIdentifier, string? HeadIdentifier, IReadOnlyList Diff); +public sealed record CalibrationApproval( + string Identifier, CalibrationPreparation Preparation, bool Consumed, DateTimeOffset ApprovedAt); +public sealed record CalibrationMutationResult( + string OperationIdentifier, string ApprovalIdentifier, CalibrationMutationAction Action, + CalibrationPreparation Preparation, DateTimeOffset StartedAt, DateTimeOffset DispatchedAt, + DateTimeOffset? CompletedAt, CalibrationWriteAcknowledgement? Acknowledgement, + CalibrationTargetImage? Actual, RehearsalVerification Verification, + RehearsalImageClassification Classification, string? OriginalFailure, + RehearsalVerification InitialVerification, CalibrationTargetImage? InitialActual, + DateTimeOffset? ReconciledAt = null, string? ReconciliationError = null); +public sealed record CalibrationRehearsalSnapshot( + RehearsalState State, bool IsBusy, CalibrationTargetIdentity? Identity, + CalibrationTargetImage? CurrentImage, VerifiedCalibrationBackup? Backup, + CalibrationPreparation? Preparation, CalibrationApproval? Approval, + IReadOnlyList Audit, string? Error); diff --git a/src/AutoForge.Application/Features/Vehicles/Calibration/CalibrationRehearsalSession.cs b/src/AutoForge.Application/Features/Vehicles/Calibration/CalibrationRehearsalSession.cs new file mode 100644 index 0000000..500b6a8 --- /dev/null +++ b/src/AutoForge.Application/Features/Vehicles/Calibration/CalibrationRehearsalSession.cs @@ -0,0 +1,539 @@ +using AutoForge.Application.Features.Vehicles.Profiles; +using AutoForge.Application.Features.Vehicles.Simulation; +using AutoForge.Core.Calibration; +using AutoForge.Core.ExecutionTargets; +using AutoForge.Diagnostics; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; + +namespace AutoForge.Application.Features.Vehicles.Calibration; + +public sealed class CalibrationRehearsalFactory( + CalibrationAuthoringService authoring, IDynamicsConfigurationService configurations, + IVehicleProfileService profiles, IEnumerable factories, TimeProvider clock) +{ + private readonly ISimulatedCalibrationTargetFactory[] _factories = factories.ToArray(); + public CalibrationRehearsalSession Create() => new(authoring, configurations, profiles, _factories, clock); +} + +public static class CalibrationRehearsalServiceCollectionExtensions +{ + public static IServiceCollection AddAutoForgeCalibrationRehearsal(this IServiceCollection services) + { + services.TryAddSingleton(); + return services; + } +} + +public sealed class CalibrationRehearsalSession( + CalibrationAuthoringService authoring, IDynamicsConfigurationService configurations, + IVehicleProfileService profiles, IReadOnlyList factories, TimeProvider clock) : IAsyncDisposable +{ + public const string ProviderIdentifier = "autoforge.simulation.calibration-rehearsal"; + public const int MaximumMutationOutcomes = 32; + private readonly object _gate = new(); + private CalibrationRehearsalSnapshot _snapshot = new(RehearsalState.Inactive, false, null, null, null, null, null, [], null); + private ISimulatedCalibrationTarget? _target; + private SyntheticEngineCalibration? _definition; + private string? _workspaceIdentifier; + private string? _issuedId; + private Owner? _owner; + private Owner? _lastOwner; + private Task? _closeTask; + private long _generation; + private bool _disposed; + public event Action? Changed; + public IReadOnlyList Providers => Array.AsReadOnly(factories.Select(factory => factory.Descriptor).ToArray()); + public CalibrationRehearsalSnapshot Snapshot { get { lock (_gate) return _snapshot; } } + + public string NewOperationId() + { + lock (_gate) + { + if (_disposed) throw Reject(RehearsalFailure.Closed, "This rehearsal page session was disposed."); + _issuedId = Guid.NewGuid().ToString("N"); + return _issuedId; + } + } + + public Task OpenAsync(string operationId, string providerIdentifier, ExecutionTargetKind kind, string workspaceIdentifier) => + Start(operationId, $"open:{providerIdentifier}:{kind}:{workspaceIdentifier}", default, async owner => + { + lock (_gate) + { + if (_target is not null) throw Reject(RehearsalFailure.InvalidTarget, "Close the current isolated target before explicitly opening a fresh instance."); + } + if (kind != ExecutionTargetKind.Simulation || providerIdentifier != ProviderIdentifier) + throw Reject(RehearsalFailure.InvalidTarget, "Only the explicitly registered Simulation calibration-rehearsal provider is eligible; physical/replay targets are prohibited."); + var selected = factories.Where(factory => factory.Descriptor.ProviderIdentifier == providerIdentifier && + factory.Descriptor.Kind == kind).ToArray(); + if (selected.Length != 1) + throw Reject(RehearsalFailure.InvalidTarget, "Exactly one matching registered Simulation rehearsal factory is required."); + var workspace = RequireHead(workspaceIdentifier, null, proposed: false); + var configuration = configurations.Select(workspace.Definition.Applicability.ConfigurationIdentifier); + configuration.ValidateAgainst(profiles.Select(configuration.ProfileIdentifier, configuration.ProfileRevision)); + owner.Token.ThrowIfCancellationRequested(); + var target = selected[0].Open(configuration, workspace.Definition); + try + { + if (target.Identity.Target.Kind != kind || target.Identity.Target.ProviderIdentifier != providerIdentifier || + !target.Identity.Source.Matches(workspace.Definition.Applicability) || + string.IsNullOrWhiteSpace(target.Identity.InstanceIdentifier)) + throw Reject(RehearsalFailure.InvalidTarget, "The opened provider returned an incoherent target instance/source."); + RequireHead(workspace.Identifier, null, proposed: false); + lock (_gate) + { + EnsureCurrent(owner); + _target = target; + _definition = workspace.Definition; + _workspaceIdentifier = workspace.Identifier; + _closeTask = null; + _snapshot = new(RehearsalState.Ready, true, target.Identity, null, null, null, null, [], null); + } + return true; + } + catch + { + await target.DisposeAsync().ConfigureAwait(false); + throw; + } + }, opening: true); + + public Task PrepareBackupAsync(string operationId, CancellationToken cancellationToken = default) => + Start(operationId, "backup", cancellationToken, async owner => + { + if (Snapshot.Backup is { } existing) return existing; + var first = await ReadValidatedAsync(owner).ConfigureAwait(false); + var second = await ReadValidatedAsync(owner).ConfigureAwait(false); + if (first.Revision != 0 || !SameImage(first, second)) + throw Reject(RehearsalFailure.InvalidImage, "The two independent original target reads did not match a complete revision-zero image; no verified backup was published."); + var backup = new VerifiedCalibrationBackup(first, clock.GetUtcNow()); + lock (_gate) + { + EnsureCurrent(owner); + _snapshot = _snapshot with { Backup = backup, CurrentImage = second, Error = null }; + } + return backup; + }); + + public Task PrepareApplyAsync(string operationId, string workspaceIdentifier, string headIdentifier, + CancellationToken cancellationToken = default) => + Start(operationId, $"prepare-apply:{workspaceIdentifier}:{headIdentifier}", cancellationToken, async owner => + { + if (Snapshot.State == RehearsalState.RecoveryRequired) + throw Reject(RehearsalFailure.RecoveryRequired, "Explicit read-only reconciliation or approved Restore is required before a new Apply."); + var backup = RequireBackup(); + var workspace = RequireHead(workspaceIdentifier, headIdentifier, proposed: true); + var before = await ReadValidatedAsync(owner).ConfigureAwait(false); + RequireHead(workspaceIdentifier, headIdentifier, proposed: true); + return PublishPreparation(owner, CalibrationMutationAction.Apply, backup, before, workspace.Head.Values, + workspace.Identifier, workspace.Head.Identifier); + }); + + public Task PrepareRestoreAsync(string operationId, CancellationToken cancellationToken = default) => + Start(operationId, "prepare-restore", cancellationToken, async owner => + { + var backup = RequireBackup(); + var before = await ReadValidatedAsync(owner).ConfigureAwait(false); + return PublishPreparation(owner, CalibrationMutationAction.Restore, backup, before, backup.Image.Values, null, null); + }); + + private CalibrationPreparation PublishPreparation(Owner owner, CalibrationMutationAction action, + VerifiedCalibrationBackup backup, CalibrationTargetImage before, CalibrationValues candidate, + string? workspaceIdentifier, string? headIdentifier) + { + _definition!.Validate(candidate); + if (before.Values.ContentEquals(candidate)) + throw Reject(RehearsalFailure.NoChange, "The actual target and candidate are identical; no changed mutation or approval was prepared."); + var preparation = new CalibrationPreparation(Guid.NewGuid().ToString("N"), action, backup.Identifier, + new(before.Identity, before.Revision, before.Values), new(candidate.Scalars, candidate.Tables), + workspaceIdentifier, headIdentifier, CalibrationValueDifferences.Compare(before.Values, candidate)); + lock (_gate) + { + EnsureCurrent(owner); + _snapshot = _snapshot with { Preparation = preparation, Approval = null, CurrentImage = before, Error = null }; + } + return preparation; + } + + public CalibrationApproval Approve(string preparationIdentifier, bool confirm) + { + CalibrationApproval approval; + lock (_gate) + { + EnsureQuiescent(); + var preparation = _snapshot.Preparation; + if (preparation is null || preparation.Identifier != preparationIdentifier) + throw Reject(RehearsalFailure.InvalidApproval, "Choose the exact current prepared candidate before confirmation."); + if (!confirm) throw Reject(RehearsalFailure.ConfirmationRequired, "Explicitly confirm this exact isolated Apply or Restore action."); + if (_snapshot.Approval is { Consumed: true } used && used.Preparation.Identifier == preparationIdentifier) + throw Reject(RehearsalFailure.InvalidApproval, "This preparation already dispatched; prepare a fresh before-image instead of reapproving it."); + ValidatePreparation(preparation); + approval = new(Guid.NewGuid().ToString("N"), preparation, false, clock.GetUtcNow()); + _snapshot = _snapshot with { Approval = approval, Error = null }; + } + Changed?.Invoke(); + return approval; + } + + public Task ExecuteAsync(string operationId, string approvalIdentifier, + CalibrationMutationAction action, CancellationToken cancellationToken = default) + { + lock (_gate) + { + var completed = _snapshot.Audit.SingleOrDefault(result => result.OperationIdentifier == operationId); + if (completed is not null) + { + if (completed.ApprovalIdentifier != approvalIdentifier || completed.Action != action) + throw Reject(RehearsalFailure.OperationConflict, "An operation ID cannot be reused with different approval/action inputs."); + return Task.FromResult(completed); + } + } + return Start(operationId, $"execute:{approvalIdentifier}:{action}", cancellationToken, + owner => ExecuteCoreAsync(owner, approvalIdentifier, action)); + } + + private async Task ExecuteCoreAsync(Owner owner, string approvalIdentifier, CalibrationMutationAction action) + { + var startedAt = clock.GetUtcNow(); + var approval = RequireApproval(approvalIdentifier, action); + var preparation = approval.Preparation; + ValidatePreparation(preparation); + var fresh = await ReadValidatedAsync(owner).ConfigureAwait(false); + if (!SameImage(preparation.Before, fresh)) + throw Reject(RehearsalFailure.StaleImage, "The fresh target image/revision differs from the immutable approved before-image; zero mutation dispatched."); + Task pending; + DateTimeOffset dispatchedAt = default; + CalibrationWriteAcknowledgement? acknowledgement = null; + string? failure = null; + try + { + Task Dispatch() + { + lock (_gate) + { + EnsureCurrent(owner); + RequireApproval(approvalIdentifier, action); + ValidatePreparation(preparation); + if (_snapshot.Audit.Count >= MaximumMutationOutcomes) + throw Reject(RehearsalFailure.AuditLimit, "At most 32 dispatched mutation outcomes per target; approval remains unconsumed and no write was sent."); + dispatchedAt = clock.GetUtcNow(); + _snapshot = _snapshot with { Approval = approval with { Consumed = true } }; + owner.Dispatched = true; + return _target!.CommitAsync(new(preparation.Before.Identity, preparation.Before.Revision, preparation.Candidate), owner.Token); + } + } + pending = action == CalibrationMutationAction.Apply + ? authoring.AtCurrentHead(preparation.WorkspaceIdentifier!, preparation.HeadIdentifier!, Dispatch) + : Dispatch(); + acknowledgement = await pending.ConfigureAwait(false); + if (!acknowledgement.Accepted) failure = $"Negative acknowledgement: {acknowledgement.Error}"; + } + catch (CalibrationAuthoringException exception) when (!owner.Dispatched) + { + throw Reject(RehearsalFailure.StaleSource, $"The source/head changed before dispatch: {exception.Message}"); + } + catch (Exception exception) when (owner.Dispatched) + { + failure = $"Mutation dispatch outcome uncertain: {exception.Message}"; + } + var (actual, classification, readError) = await ReadEvidenceAsync(owner, preparation).ConfigureAwait(false); + failure = Join(failure, readError); + var verification = classification == RehearsalImageClassification.CandidateMatching + ? action == CalibrationMutationAction.Apply ? RehearsalVerification.VerifiedApplied : RehearsalVerification.VerifiedRestored + : action == CalibrationMutationAction.Apply && classification == RehearsalImageClassification.Unchanged && acknowledgement is { Accepted: false } + ? RehearsalVerification.VerifiedUnchanged : RehearsalVerification.RecoveryRequired; + if (verification == RehearsalVerification.RecoveryRequired) + failure = Join(failure, "Independent full image/revision proof did not establish the expected changed result; explicit recovery is required."); + lock (_gate) + { + if (!IsCurrent(owner)) + { + verification = RehearsalVerification.RecoveryRequired; + classification = RehearsalImageClassification.Unavailable; + failure = Join(failure, "Close/cancellation invalidated publication after dispatch; no late Applied/Restored result is current evidence."); + } + DateTimeOffset? completedAt = null; + try { completedAt = clock.GetUtcNow(); } + catch (Exception exception) { failure = Join(failure, $"Completion timestamp unavailable: {exception.Message}"); } + var result = new CalibrationMutationResult(owner.Identifier, approvalIdentifier, action, preparation, startedAt, + dispatchedAt, completedAt, acknowledgement, actual, verification, classification, failure, verification, actual); + _snapshot = _snapshot with { Audit = Array.AsReadOnly(_snapshot.Audit.Append(result).ToArray()), Error = failure }; + if (CanPublish(owner)) PublishEvidence(result); + return result; + } + } + + public Task ReconcileAsync(string operationId, string mutationOperationIdentifier, + CancellationToken cancellationToken = default) => + Start(operationId, $"reconcile:{mutationOperationIdentifier}", cancellationToken, async owner => + { + var previous = Snapshot.Audit.LastOrDefault(); + if (previous is null || previous.OperationIdentifier != mutationOperationIdentifier || + previous.Verification != RehearsalVerification.RecoveryRequired) + throw Reject(RehearsalFailure.InvalidCommand, "Choose the latest unresolved mutation for read-only reconciliation."); + var (actual, classification, error) = await ReadEvidenceAsync(owner, previous.Preparation).ConfigureAwait(false); + var verification = classification switch + { + RehearsalImageClassification.CandidateMatching => previous.Action == CalibrationMutationAction.Apply + ? RehearsalVerification.VerifiedAppliedAfterReconciliation : RehearsalVerification.VerifiedRestoredAfterReconciliation, + RehearsalImageClassification.Unchanged => RehearsalVerification.VerifiedUnchanged, + _ => RehearsalVerification.RecoveryRequired + }; + var result = previous with { Actual = actual, Classification = classification, Verification = verification, + ReconciledAt = clock.GetUtcNow(), ReconciliationError = error }; + lock (_gate) + { + EnsureCurrent(owner); + _snapshot = _snapshot with { Audit = Array.AsReadOnly(_snapshot.Audit.Select(item => + item.OperationIdentifier == result.OperationIdentifier ? result : item).ToArray()) }; + PublishEvidence(result); + } + return result; + }); + + private async Task<(CalibrationTargetImage? Actual, RehearsalImageClassification Classification, string? Error)> ReadEvidenceAsync( + Owner owner, CalibrationPreparation preparation) + { + CalibrationTargetImage? actual = null; + try + { + actual = await _target!.ReadAsync(owner.Token).ConfigureAwait(false); + owner.Token.ThrowIfCancellationRequested(); + ValidateImage(actual); + var classification = SameImage(preparation.Before, actual) ? RehearsalImageClassification.Unchanged : + actual.Revision == checked(preparation.Before.Revision + 1) && actual.Values.ContentEquals(preparation.Candidate) + ? RehearsalImageClassification.CandidateMatching : RehearsalImageClassification.Divergent; + return (actual, classification, classification == RehearsalImageClassification.Divergent + ? "Fresh readback is divergent in identity/revision or changed/unchanged canonical values." : null); + } + catch (Exception exception) + { + return (actual, RehearsalImageClassification.Unavailable, $"Independent readback unavailable/invalid: {exception.Message}"); + } + } + + private void PublishEvidence(CalibrationMutationResult result) => + _snapshot = _snapshot with + { + State = result.Verification == RehearsalVerification.RecoveryRequired ? RehearsalState.RecoveryRequired : RehearsalState.Ready, + CurrentImage = result.Classification == RehearsalImageClassification.Unavailable ? _snapshot.CurrentImage : result.Actual, + Error = Join(result.OriginalFailure, result.ReconciliationError) + }; + + private async Task ReadValidatedAsync(Owner owner) + { + var image = await _target!.ReadAsync(owner.Token).ConfigureAwait(false); + lock (_gate) EnsureCurrent(owner); + ValidateImage(image); + return image; + } + private void ValidateImage(CalibrationTargetImage image) + { + if (image is null || !_snapshot.Identity!.Matches(image.Identity) || image.Revision < 0) + throw Reject(RehearsalFailure.InvalidImage, "The target read returned the wrong instance/provider/kind/source/revision."); + try { _definition!.Validate(image.Values); } + catch (CalibrationAuthoringException exception) + { + throw Reject(RehearsalFailure.InvalidImage, $"The actual target read is not the complete supported image: {exception.Message}"); + } + } + private VerifiedCalibrationBackup RequireBackup() + { + var backup = Snapshot.Backup ?? throw Reject(RehearsalFailure.BackupRequired, "Prepare a verified original target backup with two independent reads first."); + if (!_snapshot.Identity!.Matches(backup.Image.Identity) || backup.Image.Revision != 0) + throw Reject(RehearsalFailure.BackupRequired, "The original verified backup does not belong to this target instance/source."); + _definition!.Validate(backup.Image.Values); + return backup; + } + private CalibrationWorkspace RequireHead(string workspaceIdentifier, string? headIdentifier, bool proposed) + { + var current = authoring.Snapshot; + if (current is null || current.Identifier != workspaceIdentifier || + (_workspaceIdentifier is not null && workspaceIdentifier != _workspaceIdentifier && _target is not null)) + throw Reject(RehearsalFailure.StaleSource, "The selected authoring workspace differs from the opened target source."); + if (headIdentifier is not null && current.Head.Identifier != headIdentifier) + throw Reject(RehearsalFailure.StaleSource, $"Selected saved head '{headIdentifier}' is not current head '{current.Head.Identifier}'; select the exact current Proposed revision."); + if (proposed && current.Head.Kind != CalibrationVersionKind.Proposed) + throw Reject(RehearsalFailure.StaleSource, "Only a saved current Proposed revision can prepare Apply; baseline is not an apply proposal."); + if (_target is not null && !_target.Identity.Source.Matches(current.Definition.Applicability)) + throw Reject(RehearsalFailure.StaleSource, "The current authoring source/definition differs from the opened target source."); + return current; + } + private void ValidatePreparation(CalibrationPreparation preparation) + { + var backup = RequireBackup(); + if (preparation.BackupIdentifier != backup.Identifier || !_snapshot.Identity!.Matches(preparation.Before.Identity)) + throw Reject(RehearsalFailure.InvalidApproval, "Prepared target/backup identity no longer matches this rehearsal."); + _definition!.Validate(preparation.Candidate); + if (preparation.Action == CalibrationMutationAction.Apply) + { + var current = RequireHead(preparation.WorkspaceIdentifier!, preparation.HeadIdentifier, true); + if (!current.Head.Values.ContentEquals(preparation.Candidate)) + throw Reject(RehearsalFailure.StaleSource, "The approved candidate is not the exact saved head."); + } + else if (!backup.Image.Values.ContentEquals(preparation.Candidate)) + throw Reject(RehearsalFailure.InvalidApproval, "Restore candidate is not the full original verified backup."); + } + private CalibrationApproval RequireApproval(string identifier, CalibrationMutationAction action) + { + var approval = Snapshot.Approval; + if (!Enum.IsDefined(action) || approval is null || approval.Identifier != identifier || approval.Consumed || + approval.Preparation.Action != action) + throw Reject(RehearsalFailure.InvalidApproval, "A matching explicit single-use approval is required before dispatch."); + return approval; + } + + private Task Start(string identifier, string key, CancellationToken cancellationToken, Func, Task> run, bool opening = false) + { + Owner owner; + lock (_gate) + { + if (_owner is { } active) + { + if (active.Identifier == identifier && active.Key == key && active is Owner same) return same.Task; + throw Reject(active.Identifier == identifier ? RehearsalFailure.OperationConflict : RehearsalFailure.Busy, + "Another rehearsal operation/cleanup owns the target; conflicting requests cannot mutate it."); + } + if (_snapshot.State == RehearsalState.Closing) throw Reject(RehearsalFailure.Busy, "The previous target is draining cleanup."); + if (_disposed || (!opening && (_target is null || _snapshot.State == RehearsalState.Closed))) + throw Reject(RehearsalFailure.Closed, "No open isolated rehearsal target is available."); + if (_lastOwner is { } previous && previous.Identifier == identifier) + { + if (previous.Key == key && previous is Owner same) return same.Task; + throw Reject(RehearsalFailure.OperationConflict, "The exact previous operation ID cannot change inputs."); + } + if (identifier != _issuedId) throw Reject(RehearsalFailure.OperationConflict, "Use a fresh rehearsal-issued opaque operation ID; expired IDs cannot authorize a new request."); + cancellationToken.ThrowIfCancellationRequested(); + _issuedId = null; + owner = new(identifier, key, _generation, cancellationToken); + owner.Opening = opening; + _owner = owner; + _snapshot = _snapshot with { IsBusy = true }; + } + _ = RunAsync(owner, run); + return owner.Task; + } + private async Task RunAsync(Owner owner, Func, Task> run) + { + T? result = default; + Exception? failure = null; + try { result = await run(owner).ConfigureAwait(false); } + catch (Exception exception) + { + failure = exception; + lock (_gate) _snapshot = _snapshot with { Error = exception is OperationCanceledException + ? "Rehearsal operation cancelled before mutation dispatch or publication." : exception.Message }; + } + finally + { + owner.Release(); + lock (_gate) + { + _owner = null; + _lastOwner = owner; + _snapshot = _snapshot with { IsBusy = false }; + if (failure is OperationCanceledException) owner.Completion.TrySetCanceled(); + else if (failure is not null) owner.Completion.TrySetException(failure); + else owner.Completion.TrySetResult(result!); + } + Changed?.Invoke(); + } + } + + public Task CloseAsync() + { + Owner? owner; + ISimulatedCalibrationTarget? target; + TaskCompletionSource completion; + lock (_gate) + { + if (_closeTask is not null) return _closeTask; + completion = new(TaskCreationOptions.RunContinuationsAsynchronously); + _closeTask = completion.Task; + ++_generation; + owner = _owner; + target = _target; + _snapshot = _snapshot with { State = RehearsalState.Closing }; + } + _ = CloseCoreAsync(owner, target, completion); + return completion.Task; + } + private async Task CloseCoreAsync(Owner? owner, ISimulatedCalibrationTarget? target, TaskCompletionSource completion) + { + Exception? failure = null; + try + { + owner?.Cancel(); + if (owner is not null) + { + try { await owner.UntypedTask.ConfigureAwait(false); } + catch (OperationCanceledException) { } + catch (Exception exception) { failure = exception; } + } + if (target is not null) await target.DisposeAsync().ConfigureAwait(false); + } + catch (Exception exception) { failure = failure is null ? exception : new AggregateException(failure, exception); } + lock (_gate) + { + _target = null; + _snapshot = _snapshot with { State = RehearsalState.Closed, IsBusy = false, + Error = failure is null ? _snapshot.Error : $"Target cleanup failed: {failure.Message}" }; + } + if (failure is null) completion.TrySetResult(); else completion.TrySetException(failure); + Changed?.Invoke(); + } + public async ValueTask DisposeAsync() + { + lock (_gate) _disposed = true; + try { await CloseAsync().ConfigureAwait(false); } + finally { Changed = null; } + } + + private void EnsureQuiescent() + { + if (_owner is not null || _snapshot.State == RehearsalState.Closing) throw Reject(RehearsalFailure.Busy, "Wait for target operation/cleanup before approval."); + if (_target is null) throw Reject(RehearsalFailure.Closed, "This isolated target is closed."); + } + private bool CanPublish(Owner owner) => owner.Generation == _generation && _snapshot.State != RehearsalState.Closing && + _snapshot.State != RehearsalState.Closed; + private bool IsCurrent(Owner owner) => CanPublish(owner) && !owner.Token.IsCancellationRequested; + private void EnsureCurrent(Owner owner) + { + owner.Token.ThrowIfCancellationRequested(); + if (owner.Generation != _generation || _snapshot.State == RehearsalState.Closing || + (_snapshot.State == RehearsalState.Closed && !owner.Opening)) + throw new OperationCanceledException("Old rehearsal generation cannot publish after close."); + } + private CalibrationRehearsalException Reject(RehearsalFailure failure, string message) + { + lock (_gate) _snapshot = _snapshot with { Error = message }; + return new(failure, message); + } + private static bool SameImage(CalibrationTargetImage left, CalibrationTargetImage right) => + left.Identity.Matches(right.Identity) && left.Revision == right.Revision && left.Values.ContentEquals(right.Values); + private static string? Join(string? first, string? second) => + first is null ? second : second is null ? first : $"{first} {second}"; + + private abstract class Owner(string identifier, string key, long generation, CancellationToken external) + { + private readonly object _gate = new(); + private readonly CancellationTokenSource _cancellation = CancellationTokenSource.CreateLinkedTokenSource(external); + private bool _released; + public string Identifier { get; } = identifier; + public string Key { get; } = key; + public long Generation { get; } = generation; + public CancellationToken Token => _cancellation.Token; + public bool Dispatched { get; set; } + public bool Opening { get; set; } + public abstract Task UntypedTask { get; } + public void Cancel() { lock (_gate) { if (!_released) _cancellation.Cancel(); } } + public void Release() { lock (_gate) { _released = true; _cancellation.Dispose(); } } + } + private sealed class Owner(string identifier, string key, long generation, CancellationToken external) : Owner(identifier, key, generation, external) + { + public TaskCompletionSource Completion { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + public Task Task => Completion.Task; + public override Task UntypedTask => Task; + } +} diff --git a/src/AutoForge.Client/MauiProgram.cs b/src/AutoForge.Client/MauiProgram.cs index e3b1bf5..f9e893a 100644 --- a/src/AutoForge.Client/MauiProgram.cs +++ b/src/AutoForge.Client/MauiProgram.cs @@ -27,6 +27,7 @@ public static class MauiProgram new DynamicsDiagnosticTransportFactory(SyntheticDiagnosticExamples.CreateDefinitions()) ]); builder.Services.AddAutoForgeDynamicsConfigurations(); + builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddAutoForgeTelemetryRecording( Path.Combine(FileSystem.AppDataDirectory, "recordings")); diff --git a/src/AutoForge.Diagnostics/CalibrationProgrammingPort.cs b/src/AutoForge.Diagnostics/CalibrationProgrammingPort.cs new file mode 100644 index 0000000..7b8be69 --- /dev/null +++ b/src/AutoForge.Diagnostics/CalibrationProgrammingPort.cs @@ -0,0 +1,50 @@ +using AutoForge.Core.Calibration; +using AutoForge.Core.ExecutionTargets; +using AutoForge.Core.Simulation; + +namespace AutoForge.Diagnostics; + +public sealed record CalibrationTargetIdentity( + ExecutionTargetDescriptor Target, string InstanceIdentifier, CalibrationApplicability Source) +{ + public bool Matches(CalibrationTargetIdentity other) => + Target.Kind == other.Target.Kind && + StringComparer.Ordinal.Equals(Target.ProviderIdentifier, other.Target.ProviderIdentifier) && + StringComparer.Ordinal.Equals(InstanceIdentifier, other.InstanceIdentifier) && + Source.Matches(other.Source); +} + +public sealed class CalibrationTargetImage +{ + public CalibrationTargetImage(CalibrationTargetIdentity identity, long revision, CalibrationValues values) + { + Identity = identity with { Source = identity.Source with { } }; + Revision = revision; + Values = new(values.Scalars, values.Tables); + } + public CalibrationTargetIdentity Identity { get; } + public long Revision { get; } + public CalibrationValues Values { get; } +} + +public sealed class CalibrationTargetCommit(CalibrationTargetIdentity identity, long expectedRevision, CalibrationValues values) +{ + public CalibrationTargetIdentity Identity { get; } = identity with { Source = identity.Source with { } }; + public long ExpectedRevision { get; } = expectedRevision; + public CalibrationValues Values { get; } = new(values.Scalars, values.Tables); +} + +public sealed record CalibrationWriteAcknowledgement(bool Accepted, long? CommittedRevision, string? Error); + +public interface ISimulatedCalibrationTarget : IAsyncDisposable +{ + CalibrationTargetIdentity Identity { get; } + Task ReadAsync(CancellationToken cancellationToken = default); + Task CommitAsync(CalibrationTargetCommit request, CancellationToken cancellationToken = default); +} + +public interface ISimulatedCalibrationTargetFactory +{ + ExecutionTargetDescriptor Descriptor { get; } + ISimulatedCalibrationTarget Open(DynamicsConfiguration configuration, SyntheticEngineCalibration definition); +} diff --git a/src/AutoForge.Simulation/SimulatedCalibrationTarget.cs b/src/AutoForge.Simulation/SimulatedCalibrationTarget.cs new file mode 100644 index 0000000..5b3f875 --- /dev/null +++ b/src/AutoForge.Simulation/SimulatedCalibrationTarget.cs @@ -0,0 +1,73 @@ +using AutoForge.Core.Calibration; +using AutoForge.Core.ExecutionTargets; +using AutoForge.Core.Simulation; +using AutoForge.Diagnostics; + +namespace AutoForge.Simulation; + +public sealed class SimulatedCalibrationTargetFactory : ISimulatedCalibrationTargetFactory +{ + public const string ProviderIdentifier = "autoforge.simulation.calibration-rehearsal"; + public ExecutionTargetDescriptor Descriptor { get; } = new(ProviderIdentifier, ExecutionTargetKind.Simulation); + + public ISimulatedCalibrationTarget Open(DynamicsConfiguration configuration, SyntheticEngineCalibration definition) + { + var source = definition.Applicability; + if (!StringComparer.Ordinal.Equals(source.ConfigurationIdentifier, configuration.ConfigurationIdentifier) || + !StringComparer.OrdinalIgnoreCase.Equals(source.ProfileIdentifier, configuration.ProfileIdentifier) || + source.ProfileRevision != configuration.ProfileRevision || + !StringComparer.OrdinalIgnoreCase.Equals(source.ModuleIdentifier, configuration.EngineModuleIdentifier) || + source.ModelIdentifier != configuration.ModelIdentifier || source.ModelVersion != configuration.ModelVersion || + definition.Scalar.Minimum != configuration.Model.IdleSpeedRpm || + definition.Scalar.Maximum != configuration.Model.MaximumEngineSpeedRpm || + !definition.Table.Axis.SequenceEqual(configuration.Model.EngineTorqueCurve.Select(point => point.EngineSpeedRpm))) + throw new CalibrationAuthoringException(CalibrationFailure.SourceMismatch, "The rehearsal definition does not bind to the exact supplied configuration/module/model."); + 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))]); + definition.Validate(values); + return new SimulatedCalibrationTarget(new(Descriptor, Guid.NewGuid().ToString("N"), source), definition, values); + } +} + +internal sealed class SimulatedCalibrationTarget( + CalibrationTargetIdentity identity, SyntheticEngineCalibration definition, CalibrationValues initial) : ISimulatedCalibrationTarget +{ + private readonly object _gate = new(); + private CalibrationValues? _values = new(initial.Scalars, initial.Tables); + private long _revision; + public CalibrationTargetIdentity Identity { get; } = identity; + public Task ReadAsync(CancellationToken cancellationToken = default) + { + lock (_gate) + { + cancellationToken.ThrowIfCancellationRequested(); + ObjectDisposedException.ThrowIf(_values is null, this); + return Task.FromResult(new CalibrationTargetImage(Identity, _revision, _values)); + } + } + public Task CommitAsync(CalibrationTargetCommit request, CancellationToken cancellationToken = default) + { + lock (_gate) + { + cancellationToken.ThrowIfCancellationRequested(); + ObjectDisposedException.ThrowIf(_values is null, this); + if (!Identity.Matches(request.Identity) || request.ExpectedRevision != _revision) + return Task.FromResult(new CalibrationWriteAcknowledgement(false, null, "Actual target instance/image revision CAS conflict; image unchanged.")); + definition.Validate(request.Values); + if (_values.ContentEquals(request.Values)) + return Task.FromResult(new CalibrationWriteAcknowledgement(false, null, "Identical target image is not a changed commit.")); + var next = new CalibrationValues(request.Values.Scalars, request.Values.Tables); + var revision = checked(_revision + 1); + cancellationToken.ThrowIfCancellationRequested(); + _values = next; + _revision = revision; + return Task.FromResult(new CalibrationWriteAcknowledgement(true, revision, null)); + } + } + public ValueTask DisposeAsync() + { + lock (_gate) _values = null; + return ValueTask.CompletedTask; + } +} diff --git a/src/AutoForge.UI/Features/Foundation/AddAutoForgeUi.cs b/src/AutoForge.UI/Features/Foundation/AddAutoForgeUi.cs index ef4be4d..94c29de 100644 --- a/src/AutoForge.UI/Features/Foundation/AddAutoForgeUi.cs +++ b/src/AutoForge.UI/Features/Foundation/AddAutoForgeUi.cs @@ -24,6 +24,7 @@ public static class ServiceCollectionExtensions services.AddAutoForgeTelemetryRecordingFallback(); services.AddAutoForgeTelemetryReplay(); services.AddAutoForgeCalibrationAuthoring(); + services.AddAutoForgeCalibrationRehearsal(); services.AddScoped(); services.AddScoped(); services.AddScoped(); diff --git a/src/AutoForge.UI/Features/Vehicles/Calibration/CalibrationPage.razor b/src/AutoForge.UI/Features/Vehicles/Calibration/CalibrationPage.razor index 531e47e..f537494 100644 --- a/src/AutoForge.UI/Features/Vehicles/Calibration/CalibrationPage.razor +++ b/src/AutoForge.UI/Features/Vehicles/Calibration/CalibrationPage.razor @@ -178,6 +178,8 @@ } + + @code { [CascadingParameter] public DisplayUnitSelection DisplaySelection { get; set; } = DisplayUnitSelection.Default; diff --git a/src/AutoForge.UI/Features/Vehicles/Calibration/CalibrationRehearsalPanel.razor b/src/AutoForge.UI/Features/Vehicles/Calibration/CalibrationRehearsalPanel.razor new file mode 100644 index 0000000..0031a7d --- /dev/null +++ b/src/AutoForge.UI/Features/Vehicles/Calibration/CalibrationRehearsalPanel.razor @@ -0,0 +1,242 @@ +@using AutoForge.Application.Features.Vehicles.Calibration +@using AutoForge.Core.Calibration +@implements IAsyncDisposable +@inject CalibrationRehearsalFactory Factory +@inject CalibrationAuthoringService Authoring + +
+

Isolated simulated programming rehearsal

+

+ Simulation only; typed logical image, not a wire protocol, real driver or live dynamics application. + Backup, approval and audit are volatile process-memory evidence for one target instance. + No entire ECU backup, performance verification or physical programming authority is provided. +

+ @if (_session is { } session) + { + var snapshot = session.Snapshot; +

@snapshot.State; operation/drain pending @snapshot.IsBusy; dispatched audit @snapshot.Audit.Count / 32.

+ @if (_error is not null) {

@_error

} + @if (snapshot.Error is { } error) { } + + + + + @if (snapshot.Identity is { } identity) + { +

+ Target @identity.Target.ProviderIdentifier / @identity.Target.Kind; instance @identity.InstanceIdentifier; + source configuration @identity.Source.ConfigurationIdentifier; + profile @identity.Source.ProfileIdentifier revision @identity.Source.ProfileRevision; + module @identity.Source.ModuleIdentifier; + model @identity.Source.ModelIdentifier v@(identity.Source.ModelVersion); + definition @identity.Source.DefinitionIdentifier revision @identity.Source.DefinitionRevision. +

+

Last validated observed image revision @(snapshot.CurrentImage?.Revision.ToString() ?? "not yet read"). Cached observations are not current mutation proof, especially during RecoveryRequired or after Close.

+ @if (snapshot.Backup is { } backup) + { +

+ @backup.Label; @backup.Identifier; original instance @backup.Image.Identity.InstanceIdentifier; + revision @backup.Image.Revision; verified @backup.VerifiedAt.ToString("O"). + Coverage: exactly one scalar plus the complete fixed-axis torque table. + @(snapshot.State == RehearsalState.Closed ? "Inactive closed-target evidence; cannot authorize a new instance." : "") +

+ } + else {

No verified target backup. Authoring baseline is not a target read or backup.

} + + + +

Selected saved proposal/head @_head; current authoring head @Authoring.Snapshot?.Head.Identifier.

+ + + @if (snapshot.Preparation is { } preparation) + { +

+ Prepared @preparation.Action / @preparation.Identifier; backup @preparation.BackupIdentifier; + approved-before candidate revision @preparation.Before.Revision; + saved workspace @preparation.WorkspaceIdentifier / head @preparation.HeadIdentifier. + Current authoring head @Authoring.Snapshot?.Head.Identifier. +

+
    + @foreach (var entry in preparation.Diff) + { + var before = DisplayUnitConverter.Project(entry.Before, entry.Unit, DisplaySelection); + var after = DisplayUnitConverter.Project(entry.After, entry.Unit, DisplaySelection); +
  • + @entry.LogicalIdentifier: + @(entry.AxisCoordinate is { } axis ? $"at {Exact(axis)} {entry.AxisUnit};" : "") + source @Exact(entry.Before) -> @Exact(entry.After) @entry.Unit; delta @Exact(entry.Delta) @entry.Unit; + display @DisplayUnitConverter.Format(before, 3) -> @DisplayUnitConverter.Format(after, 3) @after.Unit. +
  • + } +
+ + + } + @if (snapshot.Approval is { } approval) + { +

+ Local single-use approval @approval.Identifier; @approval.Preparation.Action; + consumed @approval.Consumed; approved @approval.ApprovedAt.ToString("O"). + Authoring versions remain Baseline/Proposed. This does not authorize a physical operation. +

+ + } + + + +
    + @foreach (var result in snapshot.Audit) + { +
  1. +

    + Operation @result.OperationIdentifier / @result.Action / @result.Verification; + approval @result.ApprovalIdentifier; target @result.Preparation.Before.Identity.InstanceIdentifier; + backup @result.Preparation.BackupIdentifier; saved head @result.Preparation.HeadIdentifier; + before revision @result.Preparation.Before.Revision; expected changed revision @(result.Preparation.Before.Revision + 1); + actual revision @result.Actual?.Revision; classification @result.Classification. +

    +

    Acknowledgement: @(result.Acknowledgement?.Accepted.ToString() ?? "missing"); reported revision @result.Acknowledgement?.CommittedRevision; @result.Acknowledgement?.Error. An acknowledgement is not readback.

    +

    Initial verification @result.InitialVerification; original failure @result.OriginalFailure. Reconciled @result.ReconciledAt; @result.ReconciliationError.

    +

    Started @result.StartedAt.ToString("O"); dispatched @result.DispatchedAt.ToString("O"); completed @(result.CompletedAt?.ToString("O") ?? "timestamp unavailable (see error)").

    + @foreach (var evidence in Evidence(result)) + { +
    + @evidence.Label + @if (evidence.Values is { } values) + { + @foreach (var scalar in values.Scalars) {

    @scalar.LogicalIdentifier: @Exact(scalar.Value) @scalar.Unit

    } + @foreach (var table in values.Tables) + { +
      + @for (var index = 0; index < table.Cells.Count; index++) + { +
    • @table.LogicalIdentifier; axis @(index < table.Axis.Count ? Exact(table.Axis[index]) : "missing") @table.AxisUnit; cell @Exact(table.Cells[index]) @table.Unit
    • + } +
    + } + } + else {

    No independent readback image available; candidate is not a replacement for missing evidence.

    } +
    + } +
  2. + } +
+ } + } +
+ +@code { + [CascadingParameter] public DisplayUnitSelection DisplaySelection { get; set; } = DisplayUnitSelection.Default; + private CalibrationRehearsalSession? _session; + private string _provider = string.Empty; + private string _head = string.Empty; + private string _operation = string.Empty; + private string? _dispatchOperation; + private string? _dispatchApproval; + private string? _error; + private bool _confirm; + private bool _disposed; + + protected override void OnInitialized() + { + _session = Factory.Create(); + _session.Changed += OnChanged; + Authoring.Changed += OnAuthoringChanged; + _head = Authoring.Snapshot?.Head.Identifier ?? string.Empty; + } + private Task OpenAsync() => RunAsync(async () => + { + var workspace = Authoring.Snapshot ?? throw new CalibrationRehearsalException(RehearsalFailure.StaleSource, "Explicitly create an authoring workspace first."); + await _session!.OpenAsync(_session.NewOperationId(), _provider, ExecutionTargetKind.Simulation, workspace.Identifier); + _dispatchOperation = null; _dispatchApproval = null; _operation = string.Empty; + }); + private Task BackupAsync() => RunAsync(async () => { await _session!.PrepareBackupAsync(_session.NewOperationId()); }); + private Task PrepareApplyAsync() => RunAsync(async () => + { + var workspace = Authoring.Snapshot ?? throw new CalibrationRehearsalException(RehearsalFailure.StaleSource, "No current saved authoring workspace is available."); + await _session!.PrepareApplyAsync(_session.NewOperationId(), workspace.Identifier, _head); + _confirm = false; + }); + private Task PrepareRestoreAsync() => RunAsync(async () => + { + await _session!.PrepareRestoreAsync(_session.NewOperationId()); + _confirm = false; + }); + private void Approve() + { + try + { + var preparation = _session!.Snapshot.Preparation ?? throw new CalibrationRehearsalException(RehearsalFailure.InvalidApproval, "Prepare an exact candidate first."); + _session.Approve(preparation.Identifier, _confirm); + _error = null; + } + catch (CalibrationRehearsalException exception) { _error = exception.Message; } + } + private Task DispatchAsync() => RunAsync(async () => + { + var approval = _session!.Snapshot.Approval ?? throw new CalibrationRehearsalException(RehearsalFailure.InvalidApproval, "Confirm a prepared action first."); + if (_dispatchApproval != approval.Identifier) + { + _dispatchOperation = _session.NewOperationId(); + _dispatchApproval = approval.Identifier; + } + var result = await _session.ExecuteAsync(_dispatchOperation!, approval.Identifier, approval.Preparation.Action); + _operation = result.OperationIdentifier; + }); + private Task ReconcileAsync() => RunAsync(async () => { await _session!.ReconcileAsync(_session.NewOperationId(), _operation); }); + private async Task RunAsync(Func action) + { + try { await action(); _error = null; } + catch (Exception exception) when (exception is CalibrationRehearsalException or CalibrationAuthoringException or IOException or InvalidOperationException or OperationCanceledException) + { + if (!_disposed) _error = exception.Message; + } + } + private void OnAuthoringChanged() + { + if (_disposed) return; + _ = InvokeAsync(() => + { + if (_disposed) return; + if (_session?.Snapshot.Approval is null or { Consumed: true }) + _head = Authoring.Snapshot?.Head.Identifier ?? string.Empty; + StateHasChanged(); + }); + } + private void OnChanged() + { + if (_disposed) return; + _ = InvokeAsync(() => { if (!_disposed) StateHasChanged(); }); + } + private static string Exact(double value) => value.ToString("R", CultureInfo.InvariantCulture); + private static IEnumerable<(string Label, CalibrationValues? Values)> Evidence(CalibrationMutationResult result) + { + yield return ("Full before-image (independent target read)", result.Preparation.Before.Values); + yield return ("Full expected candidate (not readback)", result.Preparation.Candidate); + yield return ("Independent full readback (all changed/unchanged cells)", result.Actual?.Values); + } + public async ValueTask DisposeAsync() + { + _disposed = true; + Authoring.Changed -= OnAuthoringChanged; + if (_session is not null) { _session.Changed -= OnChanged; await _session.DisposeAsync(); } + } +} diff --git a/src/tests/AutoForge.IntegrationTests/CalibrationRehearsalIsolationTests.cs b/src/tests/AutoForge.IntegrationTests/CalibrationRehearsalIsolationTests.cs new file mode 100644 index 0000000..363894e --- /dev/null +++ b/src/tests/AutoForge.IntegrationTests/CalibrationRehearsalIsolationTests.cs @@ -0,0 +1,89 @@ +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.Diagnostics; +using AutoForge.Simulation; +using AutoForge.UI; +using Microsoft.Extensions.DependencyInjection; + +namespace AutoForge.IntegrationTests; + +public sealed partial class CalibrationAuthoringTests +{ + [Fact] + public async Task RehearsalIsolation_ActualLiveRecordingReplayAndConfigurationRemainIsolatedFromApplyRestore() + { + var directory = Path.Combine(Path.GetTempPath(), $"autoforge-step10-{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(); + services.AddSingleton(store); + services.AddSingleton(); + using var provider = services.BuildServiceProvider(); + var warm = CreateWarm(provider); + var configurations = provider.GetRequiredService(); + var export = configurations.Export(warm.ConfigurationIdentifier); + 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 path = Path.Combine(directory, capture.Header.CaptureId + ".json"); + var bytes = await File.ReadAllBytesAsync(path); + await using var player = provider.GetRequiredService().Create(); + await player.LoadAsync(capture.Header.CaptureId); + player.SeekOrdinal(1); + var replayBefore = player.Snapshot; + var runBefore = live.DynamicsControl.Status; + var traceBefore = live.Trace.Entries.ToArray(); + var countBefore = (counts.Transport, counts.Model, counts.Save); + var authoring = provider.GetRequiredService(); + var baseline = authoring.CreateBaseline(warm.ConfigurationIdentifier); + var head = authoring.Save(Request(baseline, Values(baseline, scalar: 1250))); + var authorBefore = authoring.Snapshot; + await using var rehearsal = provider.GetRequiredService().Create(); + await rehearsal.OpenAsync(rehearsal.NewOperationId(), "autoforge.simulation.calibration-rehearsal", + ExecutionTargetKind.Simulation, baseline.Identifier); + await rehearsal.PrepareBackupAsync(rehearsal.NewOperationId()); + var prepared = await rehearsal.PrepareApplyAsync(rehearsal.NewOperationId(), baseline.Identifier, head.Identifier); + var approval = rehearsal.Approve(prepared.Identifier, true); + var applied = await rehearsal.ExecuteAsync(rehearsal.NewOperationId(), approval.Identifier, CalibrationMutationAction.Apply); + Assert.Equal(1250, applied.Actual!.Values.Scalars[0].Value); + var units = provider.GetRequiredService(); + Assert.True(units.TrySet(new(DisplayUnitSystem.Metric, SpeedDisplayMode.Road))); + Assert.True(units.TrySet(DisplayUnitSelection.Default)); + prepared = await rehearsal.PrepareRestoreAsync(rehearsal.NewOperationId()); + approval = rehearsal.Approve(prepared.Identifier, true); + await rehearsal.ExecuteAsync(rehearsal.NewOperationId(), approval.Identifier, CalibrationMutationAction.Restore); + await rehearsal.CloseAsync(); + Assert.Equal(countBefore, (counts.Transport, counts.Model, counts.Save)); + Assert.Same(replayBefore, player.Snapshot); + Assert.Same(authorBefore, authoring.Snapshot); + Assert.Equal(runBefore, live.DynamicsControl.Status); + Assert.Equal(traceBefore, live.Trace.Entries); + Assert.Equal(export, configurations.Export(warm.ConfigurationIdentifier)); + Assert.Equal(bytes, await File.ReadAllBytesAsync(path)); + Assert.Equal(650, warm.Model.WarmIdleTargetRpm); + Assert.Equal(360, warm.Model.EngineTorqueCurve[2].TorqueNewtonMeters); + } + finally { Directory.Delete(directory, recursive: true); } + } +} diff --git a/src/tests/AutoForge.IntegrationTests/CalibrationRehearsalLifecycleTests.cs b/src/tests/AutoForge.IntegrationTests/CalibrationRehearsalLifecycleTests.cs new file mode 100644 index 0000000..a8262d8 --- /dev/null +++ b/src/tests/AutoForge.IntegrationTests/CalibrationRehearsalLifecycleTests.cs @@ -0,0 +1,179 @@ +using AutoForge.Application.Features.Vehicles.Calibration; +using AutoForge.Core.Calibration; +using AutoForge.Diagnostics; + +namespace AutoForge.IntegrationTests; + +public sealed partial class CalibrationRehearsalTests +{ + [Fact] + public async Task HeldPrecheck_SharesExactOperationRejectsConflictsAndCancelBeforeDispatchWritesZero() + { + using var fixture = new Fixture(); + await using var session = fixture.Session; + await fixture.OpenAsync(); + await session.PrepareBackupAsync(session.NewOperationId()); + var head = fixture.Save(1250); + var prep = await session.PrepareApplyAsync(session.NewOperationId(), fixture.Workspace.Identifier, head.Identifier); + var approval = session.Approve(prep.Identifier, true); + var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + fixture.Port.BeforeRead = async () => { entered.TrySetResult(); await release.Task; }; + using var cancellation = new CancellationTokenSource(); + var id = session.NewOperationId(); + var operation = session.ExecuteAsync(id, approval.Identifier, CalibrationMutationAction.Apply, cancellation.Token); + try + { + await entered.Task.WaitAsync(Deadline); + Assert.Same(operation, session.ExecuteAsync(id, approval.Identifier, CalibrationMutationAction.Apply)); + await RejectedAsync(session, () => session.ExecuteAsync(id, approval.Identifier, CalibrationMutationAction.Restore), RehearsalFailure.OperationConflict); + await RejectedAsync(session, () => session.PrepareRestoreAsync(session.NewOperationId()), RehearsalFailure.Busy); + Assert.Equal(0, fixture.Port.WriteCount); + cancellation.Cancel(); + release.TrySetResult(); + await Assert.ThrowsAnyAsync(() => operation); + Assert.Equal(0, fixture.Port.WriteCount); + Assert.Empty(session.Snapshot.Audit); + Assert.False(session.Snapshot.Approval!.Consumed); + } + finally + { + release.TrySetResult(); + fixture.Port.BeforeRead = null; + } + } + + [Fact] + public async Task CancellationAfterCommitAndClose_DrainsOutsideGateAndNeverPublishesLateApplied() + { + using var fixture = new Fixture(); + await using var session = fixture.Session; + await fixture.OpenAsync(); + await session.PrepareBackupAsync(session.NewOperationId()); + var head = fixture.Save(1250); + var prep = await session.PrepareApplyAsync(session.NewOperationId(), fixture.Workspace.Identifier, head.Identifier); + var approval = session.Approve(prep.Identifier, true); + var committed = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + fixture.Port.AfterCommit = async () => { committed.TrySetResult(); await release.Task; }; + var id = session.NewOperationId(); + var operation = session.ExecuteAsync(id, approval.Identifier, CalibrationMutationAction.Apply); + try + { + await committed.Task.WaitAsync(Deadline); + Assert.Equal(1, fixture.Port.WriteCount); + var close = session.CloseAsync(); + Assert.Same(close, session.CloseAsync()); + Assert.False(close.IsCompleted); + await RejectedAsync(session, () => fixture.OpenAsync(), RehearsalFailure.Busy); + release.TrySetResult(); + var result = await operation.WaitAsync(Deadline); + Assert.Equal(RehearsalVerification.RecoveryRequired, result.Verification); + Assert.NotNull(result.OriginalFailure); + await close.WaitAsync(Deadline); + Assert.Equal(RehearsalState.Closed, session.Snapshot.State); + Assert.Single(session.Snapshot.Audit); + Assert.Equal(RehearsalVerification.RecoveryRequired, session.Snapshot.Audit[0].Verification); + Assert.True(session.Snapshot.Approval!.Consumed); + fixture.Port.AfterCommit = null; + await fixture.OpenAsync(); + Assert.Empty(session.Snapshot.Audit); + Assert.Null(session.Snapshot.Backup); + } + finally + { + release.TrySetResult(); + fixture.Port.AfterCommit = null; + } + } + + [Fact] + public async Task HeldBackupReadAfterClose_CannotPublishOldBackupIntoNewInstance() + { + using var fixture = new Fixture(); + await using var session = fixture.Session; + await fixture.OpenAsync(); + var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + fixture.Port.BeforeRead = async () => { entered.TrySetResult(); await release.Task; }; + var backup = session.PrepareBackupAsync(session.NewOperationId()); + try + { + await entered.Task.WaitAsync(Deadline); + var close = session.CloseAsync(); + Assert.False(close.IsCompleted); + release.TrySetResult(); + await Assert.ThrowsAnyAsync(() => backup); + await close.WaitAsync(Deadline); + Assert.Null(session.Snapshot.Backup); + fixture.Port.BeforeRead = null; + await fixture.OpenAsync(); + Assert.Null(session.Snapshot.Backup); + Assert.Equal(0, fixture.Port.WriteCount); + } + finally + { + release.TrySetResult(); + fixture.Port.BeforeRead = null; + } + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task FailedOrLostRestore_RemainsRecoveryRequiredAndOriginalBackupNeverChanges(bool lostAfterCommit) + { + using var fixture = new Fixture(); + await using var session = fixture.Session; + await fixture.OpenAsync(); + var backup = await session.PrepareBackupAsync(session.NewOperationId()); + var head = fixture.Save(1250); + var prep = await session.PrepareApplyAsync(session.NewOperationId(), fixture.Workspace.Identifier, head.Identifier); + var approval = session.Approve(prep.Identifier, true); + await session.ExecuteAsync(session.NewOperationId(), approval.Identifier, CalibrationMutationAction.Apply); + prep = await session.PrepareRestoreAsync(session.NewOperationId()); + approval = session.Approve(prep.Identifier, true); + fixture.Port.RejectWrite = !lostAfterCommit; + fixture.Port.ThrowAfterCommit = lostAfterCommit; + fixture.Port.FailAfterWriteRead = lostAfterCommit; + var operationId = session.NewOperationId(); + var restore = await session.ExecuteAsync(operationId, approval.Identifier, CalibrationMutationAction.Restore); + Assert.Equal(RehearsalVerification.RecoveryRequired, restore.Verification); + Assert.Same(backup, session.Snapshot.Backup); + Assert.Equal(650, backup.Image.Values.Scalars[0].Value); + Assert.Equal(2, fixture.Port.WriteCount); + if (lostAfterCommit) + { + fixture.Port.FailAfterWriteRead = false; + var reconciled = await session.ReconcileAsync(session.NewOperationId(), operationId); + Assert.Equal(RehearsalVerification.VerifiedRestoredAfterReconciliation, reconciled.Verification); + Assert.Equal(650, reconciled.Actual!.Values.Scalars[0].Value); + Assert.Equal(Torque, reconciled.Actual.Values.Tables[0].Cells); + Assert.Equal(2, reconciled.Actual.Revision); + Assert.Equal(restore.OriginalFailure, reconciled.OriginalFailure); + } + } + + [Fact] + public async Task ActualTargetRejectsBadIdentityRevisionShapeAndValuesBeforeAtomicCommit() + { + using var fixture = new Fixture(); + await using var target = new AutoForge.Simulation.SimulatedCalibrationTargetFactory().Open(fixture.Configuration, fixture.Workspace.Definition); + var before = await target.ReadAsync(); + var values = new CalibrationValues([new("engine.warm-idle-target", "rpm", 1250)], before.Values.Tables); + var wrong = await target.CommitAsync(new(before.Identity with { InstanceIdentifier = "wrong" }, 0, values)); + Assert.False(wrong.Accepted); + wrong = await target.CommitAsync(new(before.Identity, 1, values)); + Assert.False(wrong.Accepted); + await Assert.ThrowsAsync(() => target.CommitAsync(new(before.Identity, 0, new([], [])))); + using var cancellation = new CancellationTokenSource(); + cancellation.Cancel(); + await Assert.ThrowsAnyAsync(() => target.CommitAsync(new(before.Identity, 0, values), cancellation.Token)); + var unchanged = await target.ReadAsync(); + Assert.Equal(0, unchanged.Revision); + Assert.True(before.Values.ContentEquals(unchanged.Values)); + Assert.True((await target.CommitAsync(new(before.Identity, 0, values))).Accepted); + Assert.False((await target.CommitAsync(new(before.Identity, 0, values))).Accepted); + Assert.Equal(1, (await target.ReadAsync()).Revision); + } +} diff --git a/src/tests/AutoForge.IntegrationTests/CalibrationRehearsalReviewTests.cs b/src/tests/AutoForge.IntegrationTests/CalibrationRehearsalReviewTests.cs new file mode 100644 index 0000000..2476f86 --- /dev/null +++ b/src/tests/AutoForge.IntegrationTests/CalibrationRehearsalReviewTests.cs @@ -0,0 +1,192 @@ +using AutoForge.Application.Features.Vehicles.Calibration; +using AutoForge.Core.Calibration; +using AutoForge.Core.ExecutionTargets; +using AutoForge.Diagnostics; +using Microsoft.Extensions.DependencyInjection; + +namespace AutoForge.IntegrationTests; + +public sealed partial class CalibrationRehearsalTests +{ + [Fact] + public async Task CancelAfterActualCommitWithoutClose_BlocksNewApplyUntilReadOnlyReconciliation() + { + using var fixture = new Fixture(); + await using var session = fixture.Session; + await fixture.OpenAsync(); + await session.PrepareBackupAsync(session.NewOperationId()); + var head = fixture.Save(1250); + var prep = await session.PrepareApplyAsync(session.NewOperationId(), fixture.Workspace.Identifier, head.Identifier); + var approval = session.Approve(prep.Identifier, true); + var committed = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + fixture.Port.AfterCommit = async () => { committed.TrySetResult(); await release.Task; }; + using var cancellation = new CancellationTokenSource(); + var id = session.NewOperationId(); + var operation = session.ExecuteAsync(id, approval.Identifier, CalibrationMutationAction.Apply, cancellation.Token); + try + { + await committed.Task.WaitAsync(Deadline); + cancellation.Cancel(); + release.TrySetResult(); + var result = await operation.WaitAsync(Deadline); + Assert.Equal(RehearsalVerification.RecoveryRequired, result.Verification); + Assert.Equal(RehearsalState.RecoveryRequired, session.Snapshot.State); + Assert.True(session.Snapshot.Approval!.Consumed); + await RejectedAsync(session, () => session.PrepareApplyAsync(session.NewOperationId(), fixture.Workspace.Identifier, head.Identifier), + RehearsalFailure.RecoveryRequired); + fixture.Port.AfterCommit = null; + var reconciled = await session.ReconcileAsync(session.NewOperationId(), id); + Assert.Equal(RehearsalVerification.VerifiedAppliedAfterReconciliation, reconciled.Verification); + Assert.Equal(1, fixture.Port.WriteCount); + } + finally + { + release.TrySetResult(); + fixture.Port.AfterCommit = null; + } + } + + [Fact] + public async Task AuthoringHeadChangesDuringHeldFreshPrecheck_RejectBeforeApprovalConsumptionOrCommit() + { + using var fixture = new Fixture(); + await using var session = fixture.Session; + await fixture.OpenAsync(); + await session.PrepareBackupAsync(session.NewOperationId()); + var head = fixture.Save(1250); + var prep = await session.PrepareApplyAsync(session.NewOperationId(), fixture.Workspace.Identifier, head.Identifier); + var approval = session.Approve(prep.Identifier, true); + var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + fixture.Port.BeforeRead = async () => { entered.TrySetResult(); await release.Task; }; + var operation = session.ExecuteAsync(session.NewOperationId(), approval.Identifier, CalibrationMutationAction.Apply); + try + { + await entered.Task.WaitAsync(Deadline); + fixture.Save(1300); + release.TrySetResult(); + var exception = await Assert.ThrowsAsync(() => operation); + Assert.Equal(RehearsalFailure.StaleSource, exception.Failure); + Assert.False(session.Snapshot.Approval!.Consumed); + Assert.Equal(0, fixture.Port.WriteCount); + Assert.Empty(session.Snapshot.Audit); + fixture.Authoring.ReplaceBaseline(fixture.Configuration.ConfigurationIdentifier, fixture.Workspace.Identifier, + fixture.Authoring.Snapshot!.Head.Identifier, true); + await RejectedAsync(session, () => session.ExecuteAsync(session.NewOperationId(), approval.Identifier, CalibrationMutationAction.Apply), + RehearsalFailure.StaleSource); + } + finally + { + release.TrySetResult(); + fixture.Port.BeforeRead = null; + } + } + + [Fact] + public async Task PositiveEchoWithoutMutation_IsNotAppliedAndFreshRevisionProofResolvesUnchanged() + { + using var fixture = new Fixture(); + await using var session = fixture.Session; + await fixture.OpenAsync(); + await session.PrepareBackupAsync(session.NewOperationId()); + var head = fixture.Save(1250); + var prep = await session.PrepareApplyAsync(session.NewOperationId(), fixture.Workspace.Identifier, head.Identifier); + var approval = session.Approve(prep.Identifier, true); + fixture.Port.EchoPositiveWithoutCommit = true; + var id = session.NewOperationId(); + var result = await session.ExecuteAsync(id, approval.Identifier, CalibrationMutationAction.Apply); + Assert.True(result.Acknowledgement!.Accepted); + Assert.Equal(0, result.Actual!.Revision); + Assert.Equal(650, result.Actual.Values.Scalars[0].Value); + Assert.Equal(RehearsalVerification.RecoveryRequired, result.Verification); + var resolved = await session.ReconcileAsync(session.NewOperationId(), id); + Assert.Equal(RehearsalVerification.VerifiedUnchanged, resolved.Verification); + Assert.Equal(1, fixture.Port.WriteCount); + Assert.Equal(result.OriginalFailure, resolved.OriginalFailure); + } + + [Fact] + public async Task CompletionClockFailure_CannotLoseAnAlreadyDispatchedAuditOutcome() + { + var clock = new FaultableUtcClock(); + using var fixture = new Fixture(clock); + await using var session = fixture.Session; + await fixture.OpenAsync(); + await session.PrepareBackupAsync(session.NewOperationId()); + var head = fixture.Save(1250); + var prep = await session.PrepareApplyAsync(session.NewOperationId(), fixture.Workspace.Identifier, head.Identifier); + var approval = session.Approve(prep.Identifier, true); + fixture.Port.AfterCommit = () => { clock.Fail = true; return Task.CompletedTask; }; + var result = await session.ExecuteAsync(session.NewOperationId(), approval.Identifier, CalibrationMutationAction.Apply); + Assert.Equal(RehearsalVerification.VerifiedApplied, result.Verification); + Assert.Null(result.CompletedAt); + Assert.Contains("Completion timestamp unavailable", result.OriginalFailure); + Assert.Single(session.Snapshot.Audit); + Assert.Equal(1, fixture.Port.WriteCount); + clock.Fail = false; + } + + [Fact] + public async Task PendingPortFailureDuringClose_PersistsErrorAndSharesFailedCleanupCompletion() + { + using var fixture = new Fixture(); + var session = fixture.Session; + await fixture.OpenAsync(); + var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + fixture.Port.BeforeRead = async () => { entered.TrySetResult(); await release.Task; throw new IOException("held port failed during close"); }; + var backup = session.PrepareBackupAsync(session.NewOperationId()); + try + { + await entered.Task.WaitAsync(Deadline); + var close = session.CloseAsync(); + Assert.Same(close, session.CloseAsync()); + release.TrySetResult(); + await Assert.ThrowsAsync(() => backup); + await Assert.ThrowsAsync(() => close); + Assert.Equal(RehearsalState.Closed, session.Snapshot.State); + Assert.Contains("held port failed during close", session.Snapshot.Error); + Assert.Null(session.Snapshot.Backup); + await Assert.ThrowsAsync(() => session.DisposeAsync().AsTask()); + } + finally + { + release.TrySetResult(); + fixture.Port.BeforeRead = null; + } + } + + [Fact] + public async Task WrongSourceAndDescriptorRejectBeforeTargetFactoryOpens() + { + using var fixture = new Fixture(); + await using var session = fixture.Session; + await RejectedAsync(session, () => session.OpenAsync(session.NewOperationId(), ProviderId, ExecutionTargetKind.Simulation, "wrong-workspace"), + RehearsalFailure.StaleSource); + Assert.Equal(0, fixture.Port.OpenCount); + var wrong = new DescriptorOnlyFactory(); + await using var other = new CalibrationRehearsalSession(fixture.Authoring, fixture.Configurations, + fixture.Provider.GetRequiredService(), + [wrong], TimeProvider.System); + await RejectedAsync(other, () => other.OpenAsync(other.NewOperationId(), ProviderId, ExecutionTargetKind.Simulation, fixture.Workspace.Identifier), + RehearsalFailure.InvalidTarget); + Assert.Equal(0, wrong.OpenCount); + var source = fixture.Workspace.Definition.Applicability with { ConfigurationIdentifier = "another" }; + var definition = new SyntheticEngineCalibration(source, fixture.Workspace.Definition.Scalar, fixture.Workspace.Definition.Table); + Assert.Throws(() => new AutoForge.Simulation.SimulatedCalibrationTargetFactory().Open(fixture.Configuration, definition)); + } + + private sealed class FaultableUtcClock : TimeProvider + { + public bool Fail { get; set; } + public override DateTimeOffset GetUtcNow() => Fail ? throw new InvalidOperationException("controlled UTC failure") : base.GetUtcNow(); + } + private sealed class DescriptorOnlyFactory : ISimulatedCalibrationTargetFactory + { + public int OpenCount { get; private set; } + public ExecutionTargetDescriptor Descriptor { get; } = new(ProviderId, ExecutionTargetKind.PhysicalHardware); + public ISimulatedCalibrationTarget Open(AutoForge.Core.Simulation.DynamicsConfiguration configuration, SyntheticEngineCalibration definition) + { OpenCount++; throw new InvalidOperationException("Forbidden descriptor must not open."); } + } +} diff --git a/src/tests/AutoForge.IntegrationTests/CalibrationRehearsalTests.cs b/src/tests/AutoForge.IntegrationTests/CalibrationRehearsalTests.cs new file mode 100644 index 0000000..7148901 --- /dev/null +++ b/src/tests/AutoForge.IntegrationTests/CalibrationRehearsalTests.cs @@ -0,0 +1,454 @@ +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.ExecutionTargets; +using AutoForge.Diagnostics; +using AutoForge.Simulation; +using AutoForge.UI; +using Microsoft.Extensions.DependencyInjection; + +namespace AutoForge.IntegrationTests; + +public sealed partial class CalibrationRehearsalTests +{ + private const string ProfileId = "autoforge.synthetic.test-truck"; + private const string ProviderId = "autoforge.simulation.calibration-rehearsal"; + private static readonly TimeSpan Deadline = TimeSpan.FromSeconds(10); + private static readonly double[] Torque = [240, 300, 360, 350, 300, 180]; + + [Fact] + public async Task ExplicitTargetAndIndependentBackup_ReadActualDefensiveRevisionZeroImage() + { + using var fixture = new Fixture(); + await using var session = fixture.Session; + Assert.Null(session.Snapshot.Identity); + foreach (var kind in new[] { ExecutionTargetKind.PhysicalHardware, ExecutionTargetKind.RecordedReplay, (ExecutionTargetKind)99 }) + await RejectedAsync(session, () => session.OpenAsync(session.NewOperationId(), ProviderId, kind, fixture.Workspace.Identifier), + RehearsalFailure.InvalidTarget); + await RejectedAsync(session, () => session.OpenAsync(session.NewOperationId(), "unregistered", ExecutionTargetKind.Simulation, + fixture.Workspace.Identifier), RehearsalFailure.InvalidTarget); + Assert.Equal(0, fixture.Port.OpenCount); + await fixture.OpenAsync(); + Assert.Equal(1, fixture.Port.OpenCount); + var identity = session.Snapshot.Identity!; + Assert.Equal(ExecutionTargetKind.Simulation, identity.Target.Kind); + Assert.Equal(ProviderId, identity.Target.ProviderIdentifier); + Assert.True(identity.Source.Matches(fixture.Workspace.Definition.Applicability)); + var backup = await session.PrepareBackupAsync(session.NewOperationId()); + Assert.Equal(2, fixture.Port.ReadCount); + Assert.Equal(0, backup.Image.Revision); + Assert.Equal(650, backup.Image.Values.Scalars[0].Value); + Assert.Equal(Torque, backup.Image.Values.Tables[0].Cells); + Assert.Equal(fixture.Workspace.Definition.Table.Axis, backup.Image.Values.Tables[0].Axis); + Assert.Equal(identity.InstanceIdentifier, backup.Image.Identity.InstanceIdentifier); + Assert.Contains("Verified in-memory backup", backup.Label); + Assert.Throws(() => ((IList)backup.Image.Values.Tables[0].Cells)[0] = 999); + Assert.Same(backup, await session.PrepareBackupAsync(session.NewOperationId())); + Assert.Equal(2, fixture.Port.ReadCount); + Assert.Equal(0, fixture.Port.WriteCount); + } + + [Fact] + public async Task ScalarThenTableApplyAndSeparatelyApprovedRestore_VerifyTheFullActualImage() + { + using var fixture = new Fixture(); + await using var session = fixture.Session; + await fixture.OpenAsync(); + var backup = await session.PrepareBackupAsync(session.NewOperationId()); + var first = fixture.Save(1250); + var prepared = await session.PrepareApplyAsync(session.NewOperationId(), fixture.Workspace.Identifier, first.Identifier); + var scalar = Assert.Single(prepared.Diff); + Assert.Equal(650, scalar.Before); + Assert.Equal(1250, scalar.After); + Assert.Equal(600, scalar.Delta); + var approval = session.Approve(prepared.Identifier, confirm: true); + Assert.Throws(() => ((IList)approval.Preparation.Candidate.Tables[0].Cells)[0] = 999); + Assert.Equal(650, approval.Preparation.Before.Values.Scalars[0].Value); + var operationId = session.NewOperationId(); + var applied = await session.ExecuteAsync(operationId, approval.Identifier, CalibrationMutationAction.Apply); + Assert.Equal(RehearsalVerification.VerifiedApplied, applied.Verification); + Assert.True(applied.Acknowledgement!.Accepted); + Assert.Equal(1, applied.Actual!.Revision); + Assert.Equal(1250, applied.Actual.Values.Scalars[0].Value); + Assert.Equal(Torque, applied.Actual.Values.Tables[0].Cells); + Assert.Equal(1, fixture.Port.WriteCount); + Assert.True(session.Snapshot.Approval!.Consumed); + Assert.Same(applied, await session.ExecuteAsync(operationId, approval.Identifier, CalibrationMutationAction.Apply)); + Assert.Equal(1, fixture.Port.WriteCount); + Assert.Equal(CalibrationVersionKind.Proposed, first.Kind); + var changed = Torque.ToArray(); + changed[2] = 350; + var second = fixture.Save(1250, changed); + var next = await session.PrepareApplyAsync(session.NewOperationId(), fixture.Workspace.Identifier, second.Identifier); + var cell = Assert.Single(next.Diff); + Assert.Equal(2000, cell.AxisCoordinate); + Assert.Equal(-10, cell.Delta); + var nextApproval = session.Approve(next.Identifier, true); + var nextResult = await session.ExecuteAsync(session.NewOperationId(), nextApproval.Identifier, CalibrationMutationAction.Apply); + Assert.Equal(2, nextResult.Actual!.Revision); + Assert.Equal(changed, nextResult.Actual.Values.Tables[0].Cells); + Assert.Same(backup, session.Snapshot.Backup); + var restore = await session.PrepareRestoreAsync(session.NewOperationId()); + Assert.Equal(CalibrationMutationAction.Restore, restore.Action); + var restoreApproval = session.Approve(restore.Identifier, true); + var restored = await session.ExecuteAsync(session.NewOperationId(), restoreApproval.Identifier, CalibrationMutationAction.Restore); + Assert.Equal(RehearsalVerification.VerifiedRestored, restored.Verification); + Assert.Equal(3, restored.Actual!.Revision); + Assert.Equal(650, restored.Actual.Values.Scalars[0].Value); + Assert.Equal(Torque, restored.Actual.Values.Tables[0].Cells); + Assert.Equal(backup.Image.Values.Tables[0].Axis, restored.Actual.Values.Tables[0].Axis); + Assert.Equal(3, fixture.Port.WriteCount); + Assert.Equal(3, session.Snapshot.Audit.Count); + Assert.Throws(() => ((IList)session.Snapshot.Audit).Clear()); + Assert.Equal(0, applied.Preparation.Before.Revision); + Assert.Equal(650, applied.Preparation.Before.Values.Scalars[0].Value); + Assert.Equal(1250, applied.Preparation.Candidate.Scalars[0].Value); + Assert.Equal(1, applied.InitialActual!.Revision); + Assert.True(applied.StartedAt <= applied.DispatchedAt); + Assert.True(applied.DispatchedAt <= applied.CompletedAt); + Assert.Equal(650, fixture.Configuration.Model.WarmIdleTargetRpm); + Assert.Equal(360, fixture.Configuration.Model.EngineTorqueCurve[2].TorqueNewtonMeters); + Assert.Equal(fixture.Export, fixture.Configurations.Export(fixture.Configuration.ConfigurationIdentifier)); + Assert.Equal(3, fixture.Authoring.Snapshot!.History.Count); + Assert.Equal(650, fixture.Workspace.Baseline.Values.Scalars[0].Value); + } + + [Theory] + [InlineData("identity")] + [InlineData("revision")] + [InlineData("cell")] + [InlineData("shape")] + [InlineData("read-failure")] + public async Task IndependentBackupFailure_NeverPublishesFakeVerifiedOrApproval(string fault) + { + using var fixture = new Fixture(); + await using var session = fixture.Session; + await fixture.OpenAsync(); + fixture.Port.ReadTransform = (count, image) => count != 2 ? image : FaultImage(image, fault); + if (fault == "read-failure") fixture.Port.FailReadNumber = 2; + await Assert.ThrowsAnyAsync(() => session.PrepareBackupAsync(session.NewOperationId())); + Assert.Null(session.Snapshot.Backup); + Assert.Null(session.Snapshot.Approval); + Assert.NotNull(session.Snapshot.Error); + Assert.Equal(0, fixture.Port.WriteCount); + Assert.Empty(session.Snapshot.Audit); + } + + [Fact] + public async Task InvalidConfirmationTokenActionHeadAndNoOp_RejectBeforeConsumptionOrWrite() + { + using var fixture = new Fixture(); + await using var session = fixture.Session; + await fixture.OpenAsync(); + var first = fixture.Save(1250); + await RejectedAsync(session, () => session.PrepareApplyAsync(session.NewOperationId(), fixture.Workspace.Identifier, first.Identifier), + RehearsalFailure.BackupRequired); + await session.PrepareBackupAsync(session.NewOperationId()); + var prepared = await session.PrepareApplyAsync(session.NewOperationId(), fixture.Workspace.Identifier, first.Identifier); + Assert.Throws(() => session.Approve(prepared.Identifier, false)); + Assert.Null(session.Snapshot.Approval); + var approval = session.Approve(prepared.Identifier, true); + await RejectedAsync(session, () => session.ExecuteAsync(session.NewOperationId(), "wrong", CalibrationMutationAction.Apply), + RehearsalFailure.InvalidApproval); + await RejectedAsync(session, () => session.ExecuteAsync(session.NewOperationId(), approval.Identifier, CalibrationMutationAction.Restore), + RehearsalFailure.InvalidApproval); + Assert.False(session.Snapshot.Approval!.Consumed); + fixture.Save(1300); + await RejectedAsync(session, () => session.ExecuteAsync(session.NewOperationId(), approval.Identifier, CalibrationMutationAction.Apply), + RehearsalFailure.StaleSource); + Assert.False(session.Snapshot.Approval!.Consumed); + Assert.Equal(0, fixture.Port.WriteCount); + var head = fixture.Authoring.Snapshot!.Head; + var newPreparation = await session.PrepareApplyAsync(session.NewOperationId(), fixture.Workspace.Identifier, head.Identifier); + var newApproval = session.Approve(newPreparation.Identifier, true); + var result = await session.ExecuteAsync(session.NewOperationId(), newApproval.Identifier, CalibrationMutationAction.Apply); + Assert.Equal(RehearsalVerification.VerifiedApplied, result.Verification); + await RejectedAsync(session, () => session.PrepareApplyAsync(session.NewOperationId(), fixture.Workspace.Identifier, head.Identifier), + RehearsalFailure.NoChange); + Assert.Equal(1, fixture.Port.WriteCount); + } + + [Fact] + public async Task FreshReadAndActualTargetCas_PreventChangesBeforeAndAfterDispatchPrecheck() + { + using var fixture = new Fixture(); + await using var session = fixture.Session; + await fixture.OpenAsync(); + await session.PrepareBackupAsync(session.NewOperationId()); + var head = fixture.Save(1250); + var prepared = await session.PrepareApplyAsync(session.NewOperationId(), fixture.Workspace.Identifier, head.Identifier); + var approval = session.Approve(prepared.Identifier, true); + await fixture.Port.ExternalChangeAsync(900); + await RejectedAsync(session, () => session.ExecuteAsync(session.NewOperationId(), approval.Identifier, CalibrationMutationAction.Apply), + RehearsalFailure.StaleImage); + Assert.Equal(0, fixture.Port.WriteCount); + Assert.False(session.Snapshot.Approval!.Consumed); + var next = await session.PrepareApplyAsync(session.NewOperationId(), fixture.Workspace.Identifier, head.Identifier); + var nextApproval = session.Approve(next.Identifier, true); + fixture.Port.BeforeWrite = () => fixture.Port.ExternalChangeAsync(950); + var conflict = await session.ExecuteAsync(session.NewOperationId(), nextApproval.Identifier, CalibrationMutationAction.Apply); + Assert.Equal(RehearsalVerification.RecoveryRequired, conflict.Verification); + Assert.False(conflict.Acknowledgement!.Accepted); + Assert.Equal(950, conflict.Actual!.Values.Scalars[0].Value); + Assert.Equal(1, fixture.Port.WriteCount); + } + + [Theory] + [InlineData("lost-ack")] + [InlineData("read-failure")] + [InlineData("wrong-identity")] + [InlineData("unchanged-cell")] + public async Task UncertainCommit_RequiresReadOnlyReconcileAndPreservesOriginalFailure(string fault) + { + using var fixture = new Fixture(); + await using var session = fixture.Session; + await fixture.OpenAsync(); + await session.PrepareBackupAsync(session.NewOperationId()); + var head = fixture.Save(1250); + var preparation = await session.PrepareApplyAsync(session.NewOperationId(), fixture.Workspace.Identifier, head.Identifier); + var approval = session.Approve(preparation.Identifier, true); + if (fault == "lost-ack") fixture.Port.ThrowAfterCommit = true; + fixture.Port.FailAfterWriteRead = fault is "lost-ack" or "read-failure"; + if (fault == "wrong-identity") fixture.Port.ReadTransform = (_, image) => fixture.Port.WriteCount > 0 ? FaultImage(image, "identity") : image; + if (fault == "unchanged-cell") fixture.Port.ReadTransform = (_, image) => fixture.Port.WriteCount > 0 ? FaultImage(image, "cell") : image; + var operationId = session.NewOperationId(); + var result = await session.ExecuteAsync(operationId, approval.Identifier, CalibrationMutationAction.Apply); + Assert.Equal(RehearsalVerification.RecoveryRequired, result.Verification); + Assert.Equal(RehearsalState.RecoveryRequired, session.Snapshot.State); + Assert.NotNull(result.OriginalFailure); + Assert.Equal(1, fixture.Port.WriteCount); + await RejectedAsync(session, () => session.PrepareApplyAsync(session.NewOperationId(), fixture.Workspace.Identifier, head.Identifier), + RehearsalFailure.RecoveryRequired); + fixture.Port.FailAfterWriteRead = false; + fixture.Port.ReadTransform = null; + var reconciled = await session.ReconcileAsync(session.NewOperationId(), operationId); + Assert.Equal(RehearsalVerification.VerifiedAppliedAfterReconciliation, reconciled.Verification); + Assert.Equal(RehearsalImageClassification.CandidateMatching, reconciled.Classification); + Assert.Equal(result.OriginalFailure, reconciled.OriginalFailure); + Assert.Equal(1250, reconciled.Actual!.Values.Scalars[0].Value); + Assert.Equal(Torque, reconciled.Actual.Values.Tables[0].Cells); + Assert.Equal(1, fixture.Port.WriteCount); + Assert.Single(session.Snapshot.Audit); + Assert.Same(reconciled, await session.ExecuteAsync(operationId, approval.Identifier, CalibrationMutationAction.Apply)); + } + + [Fact] + public async Task RejectedPortAndDivergentReconcile_NeverBlindlyRetryOrRestore() + { + using var fixture = new Fixture(); + await using var session = fixture.Session; + await fixture.OpenAsync(); + await session.PrepareBackupAsync(session.NewOperationId()); + var head = fixture.Save(1250); + var prep = await session.PrepareApplyAsync(session.NewOperationId(), fixture.Workspace.Identifier, head.Identifier); + var approval = session.Approve(prep.Identifier, true); + fixture.Port.RejectWrite = true; + fixture.Port.FailAfterWriteRead = true; + var id = session.NewOperationId(); + var uncertain = await session.ExecuteAsync(id, approval.Identifier, CalibrationMutationAction.Apply); + Assert.Equal(RehearsalVerification.RecoveryRequired, uncertain.Verification); + fixture.Port.FailAfterWriteRead = false; + var unchanged = await session.ReconcileAsync(session.NewOperationId(), id); + Assert.Equal(RehearsalImageClassification.Unchanged, unchanged.Classification); + Assert.Equal(RehearsalVerification.VerifiedUnchanged, unchanged.Verification); + Assert.Equal(0, unchanged.Actual!.Revision); + Assert.Equal(1, fixture.Port.WriteCount); + fixture.Port.RejectWrite = false; + prep = await session.PrepareApplyAsync(session.NewOperationId(), fixture.Workspace.Identifier, head.Identifier); + approval = session.Approve(prep.Identifier, true); + fixture.Port.FailAfterWriteRead = true; + var nextId = session.NewOperationId(); + await session.ExecuteAsync(nextId, approval.Identifier, CalibrationMutationAction.Apply); + fixture.Port.FailAfterWriteRead = false; + await fixture.Port.ExternalChangeAsync(1400); + var divergent = await session.ReconcileAsync(session.NewOperationId(), nextId); + Assert.Equal(RehearsalImageClassification.Divergent, divergent.Classification); + Assert.Equal(RehearsalVerification.RecoveryRequired, divergent.Verification); + fixture.Port.FailReadNumber = fixture.Port.ReadCount + 1; + var unavailable = await session.ReconcileAsync(session.NewOperationId(), nextId); + Assert.Equal(RehearsalImageClassification.Unavailable, unavailable.Classification); + Assert.Equal(RehearsalVerification.RecoveryRequired, unavailable.Verification); + Assert.Equal(2, fixture.Port.WriteCount); + } + + [Fact] + public async Task CloseReopen_InvalidatesOldTargetBackupApprovalAndRetainsInactiveAudit() + { + using var fixture = new Fixture(); + await using var session = fixture.Session; + await fixture.OpenAsync(); + var backup = await session.PrepareBackupAsync(session.NewOperationId()); + var head = fixture.Save(1250); + var prep = await session.PrepareApplyAsync(session.NewOperationId(), fixture.Workspace.Identifier, head.Identifier); + var approval = session.Approve(prep.Identifier, true); + await session.CloseAsync(); + Assert.Equal(RehearsalState.Closed, session.Snapshot.State); + Assert.Same(backup, session.Snapshot.Backup); + await RejectedAsync(session, () => session.ExecuteAsync(session.NewOperationId(), approval.Identifier, CalibrationMutationAction.Apply), + RehearsalFailure.Closed); + await fixture.OpenAsync(); + Assert.NotEqual(backup.Image.Identity.InstanceIdentifier, session.Snapshot.Identity!.InstanceIdentifier); + Assert.Null(session.Snapshot.Backup); + Assert.Null(session.Snapshot.Approval); + Assert.Empty(session.Snapshot.Audit); + await RejectedAsync(session, () => session.PrepareRestoreAsync(session.NewOperationId()), RehearsalFailure.BackupRequired); + await RejectedAsync(session, () => session.ExecuteAsync(session.NewOperationId(), approval.Identifier, CalibrationMutationAction.Apply), + RehearsalFailure.InvalidApproval); + Assert.Equal(0, fixture.Port.WriteCount); + } + + [Fact] + public async Task DispatchedAuditLimit_IsExactly32AndExactOperationReplayConsumesNoSlot() + { + using var fixture = new Fixture(); + await using var session = fixture.Session; + await fixture.OpenAsync(); + await session.PrepareBackupAsync(session.NewOperationId()); + var head = fixture.Save(1250); + CalibrationMutationResult? last = null; + for (var index = 0; index < 32; index++) + { + var action = index % 2 == 0 ? CalibrationMutationAction.Apply : CalibrationMutationAction.Restore; + var preparation = action == CalibrationMutationAction.Apply + ? await session.PrepareApplyAsync(session.NewOperationId(), fixture.Workspace.Identifier, head.Identifier) + : await session.PrepareRestoreAsync(session.NewOperationId()); + var approval = session.Approve(preparation.Identifier, true); + last = await session.ExecuteAsync(session.NewOperationId(), approval.Identifier, action); + Assert.Equal(index + 1, last.Actual!.Revision); + } + Assert.Equal(32, session.Snapshot.Audit.Count); + Assert.Same(last, await session.ExecuteAsync(last!.OperationIdentifier, last.ApprovalIdentifier, last.Action)); + var next = await session.PrepareApplyAsync(session.NewOperationId(), fixture.Workspace.Identifier, head.Identifier); + var nextApproval = session.Approve(next.Identifier, true); + await RejectedAsync(session, () => session.ExecuteAsync(session.NewOperationId(), nextApproval.Identifier, CalibrationMutationAction.Apply), + RehearsalFailure.AuditLimit); + Assert.False(session.Snapshot.Approval!.Consumed); + Assert.Equal(32, fixture.Port.WriteCount); + } + + private static CalibrationTargetImage FaultImage(CalibrationTargetImage image, string fault) + { + if (fault == "read-failure") throw new IOException("controlled backup read failure"); + if (fault == "identity") return new(image.Identity with { InstanceIdentifier = "wrong-instance" }, image.Revision, image.Values); + if (fault == "revision") return new(image.Identity, image.Revision + 1, image.Values); + var cells = image.Values.Tables[0].Cells.ToArray(); + cells[^1] = 181; + var values = fault == "shape" ? new CalibrationValues([], []) : new CalibrationValues(image.Values.Scalars, + [new("engine.torque-curve", "N*m", "rpm", image.Values.Tables[0].Axis, cells)]); + return new(image.Identity, image.Revision, values); + } + + private static async Task RejectedAsync(CalibrationRehearsalSession session, Func action, RehearsalFailure failure) + { + var previous = session.Snapshot; + var exception = await Assert.ThrowsAsync(action); + Assert.Equal(failure, exception.Failure); + Assert.Same(previous.Identity, session.Snapshot.Identity); + Assert.Same(previous.Backup, session.Snapshot.Backup); + Assert.Same(previous.Approval, session.Snapshot.Approval); + Assert.Equal(previous.Audit, session.Snapshot.Audit); + Assert.NotNull(session.Snapshot.Error); + } + + internal sealed class Fixture : IDisposable + { + public ServiceProvider Provider { get; } + public FaultingRehearsalFactory Port { get; } = new(new SimulatedCalibrationTargetFactory()); + public CalibrationAuthoringService Authoring { get; } + public IDynamicsConfigurationService Configurations { get; } + public AutoForge.Core.Simulation.DynamicsConfiguration Configuration { get; } + public CalibrationWorkspace Workspace { get; } + public CalibrationRehearsalSession Session { get; } + public string Export { get; } + public Fixture(TimeProvider? clock = null) + { + var services = new ServiceCollection(); + services.AddLogging(); + services.AddAutoForgeVehicleProfiles(); + services.AddAutoForgeUi(); + services.AddSingleton(Port); + if (clock is not null) services.AddSingleton(clock); + Provider = services.BuildServiceProvider(); + Provider.GetRequiredService().Import(File.ReadAllText( + Path.Combine(AppContext.BaseDirectory, "Fixtures", "synthetic-truck-baseline.json"))); + Configurations = Provider.GetRequiredService(); + Configuration = Configurations.CreateExample(ProfileId, 1); + Export = Configurations.Export(Configuration.ConfigurationIdentifier); + Authoring = Provider.GetRequiredService(); + Workspace = Authoring.CreateBaseline(Configuration.ConfigurationIdentifier); + Session = Provider.GetRequiredService().Create(); + } + public Task OpenAsync() => Session.OpenAsync(Session.NewOperationId(), ProviderId, ExecutionTargetKind.Simulation, Workspace.Identifier); + public CalibrationVersion Save(double scalar, double[]? cells = null) + { + var current = Authoring.Snapshot!; + return Authoring.Save(new(current.Identifier, current.Head.Identifier, current.Definition.Applicability, + new([new("engine.warm-idle-target", "rpm", scalar)], + [new("engine.torque-curve", "N*m", "rpm", current.Definition.Table.Axis, cells ?? current.Head.Values.Tables[0].Cells)]))); + } + public void Dispose() => Provider.Dispose(); + } + + internal sealed class FaultingRehearsalFactory(ISimulatedCalibrationTargetFactory inner) : ISimulatedCalibrationTargetFactory + { + public ExecutionTargetDescriptor Descriptor => inner.Descriptor; + public int OpenCount { get; private set; } + public int ReadCount { get; private set; } + public int WriteCount { get; private set; } + public Func? ReadTransform { get; set; } + public Func? BeforeRead { get; set; } + public Func? BeforeWrite { get; set; } + public Func? AfterCommit { get; set; } + public bool ThrowAfterCommit { get; set; } + public bool RejectWrite { get; set; } + public bool EchoPositiveWithoutCommit { get; set; } + private int? _failAtWriteCount; + public bool FailAfterWriteRead + { + get => _failAtWriteCount is not null; + set => _failAtWriteCount = value ? WriteCount + 1 : null; + } + public int? FailReadNumber { get; set; } + private ISimulatedCalibrationTarget? _target; + public ISimulatedCalibrationTarget Open(AutoForge.Core.Simulation.DynamicsConfiguration configuration, SyntheticEngineCalibration definition) + { + OpenCount++; + _target = inner.Open(configuration, definition); + return new ForwardingTarget(_target, this); + } + public async Task ExternalChangeAsync(double scalar) + { + var actual = await _target!.ReadAsync(); + var values = new CalibrationValues([new("engine.warm-idle-target", "rpm", scalar)], actual.Values.Tables); + var ack = await _target.CommitAsync(new(actual.Identity, actual.Revision, values)); + Assert.True(ack.Accepted); + } + private sealed class ForwardingTarget(ISimulatedCalibrationTarget target, FaultingRehearsalFactory owner) : ISimulatedCalibrationTarget + { + public CalibrationTargetIdentity Identity => target.Identity; + public async Task ReadAsync(CancellationToken cancellationToken = default) + { + owner.ReadCount++; + if (owner.BeforeRead is { } before) await before(); + if (owner.ReadCount == owner.FailReadNumber || + (owner._failAtWriteCount is { } failCount && owner.WriteCount >= failCount)) + throw new IOException("controlled fresh read failure"); + var actual = await target.ReadAsync(cancellationToken); + return owner.ReadTransform?.Invoke(owner.ReadCount, actual) ?? actual; + } + public async Task CommitAsync(CalibrationTargetCommit request, CancellationToken cancellationToken = default) + { + owner.WriteCount++; + if (owner.BeforeWrite is { } before) await before(); + if (owner.RejectWrite) return new(false, null, "controlled negative acknowledgement"); + if (owner.EchoPositiveWithoutCommit) return new(true, request.ExpectedRevision + 1, null); + var result = await target.CommitAsync(request, cancellationToken); + if (owner.AfterCommit is { } after) await after(); + if (owner.ThrowAfterCommit) throw new IOException("actual commit followed by lost acknowledgement"); + return result; + } + public ValueTask DisposeAsync() => target.DisposeAsync(); + } + } +} diff --git a/src/tests/AutoForge.IntegrationTests/CalibrationRehearsalUiTests.cs b/src/tests/AutoForge.IntegrationTests/CalibrationRehearsalUiTests.cs new file mode 100644 index 0000000..257908c --- /dev/null +++ b/src/tests/AutoForge.IntegrationTests/CalibrationRehearsalUiTests.cs @@ -0,0 +1,110 @@ +using AutoForge.Application.Features.Vehicles.Calibration; +using AutoForge.Core.Calibration; +using AutoForge.Diagnostics; +using AutoForge.Simulation; +using AutoForge.UI; +using AutoForge.UI.Features.Vehicles.Calibration; +using AutoForge.Application.Features.Vehicles.Profiles; +using Microsoft.Extensions.DependencyInjection; + +namespace AutoForge.IntegrationTests; + +public sealed partial class CalibrationAuthoringTests +{ + [Fact] + public async Task RenderedRehearsal_LostAckRecoveryAndUnitRerendersDoNotResendMutation() + { + using var fixture = new CalibrationRehearsalTests.Fixture(); + fixture.Save(1250); + await using var renderer = new CalibrationEventRenderer(fixture.Provider); + var host = new CalibrationUnitHost(); + var root = renderer.Attach(host); + await renderer.Dispatcher.InvokeAsync(async () => + { + await renderer.RenderAsync(root); + await renderer.ChangeAsync(root, "rehearsal-provider", "autoforge.simulation.calibration-rehearsal"); + await renderer.ClickAsync(root, "rehearsal-open"); + await renderer.ClickAsync(root, "rehearsal-backup"); + await renderer.ClickAsync(root, "rehearsal-prepare-apply"); + await renderer.CheckAsync(root, "rehearsal-confirm", true); + await renderer.ClickAsync(root, "rehearsal-approve"); + var reads = fixture.Port.ReadCount; + host.SetUnits(new(AutoForge.Application.Features.DisplayUnits.DisplayUnitSystem.Metric, + AutoForge.Application.Features.DisplayUnits.SpeedDisplayMode.Road)); + Assert.Equal(reads, fixture.Port.ReadCount); + Assert.Equal(0, fixture.Port.WriteCount); + fixture.Port.ThrowAfterCommit = true; + fixture.Port.FailAfterWriteRead = true; + await renderer.ClickAsync(root, "rehearsal-dispatch"); + Assert.Contains("RecoveryRequired", renderer.Text(root)); + Assert.Contains("lost acknowledgement", renderer.Text(root)); + await renderer.ClickAsync(root, "rehearsal-dispatch"); + Assert.Equal(1, fixture.Port.WriteCount); + fixture.Port.FailAfterWriteRead = false; + await renderer.ClickAsync(root, "rehearsal-reconcile"); + Assert.Contains("VerifiedAppliedAfterReconciliation", renderer.Text(root)); + Assert.Contains("lost acknowledgement", renderer.Text(root)); + Assert.Equal(1, fixture.Port.WriteCount); + }); + } + + [Fact] + public async Task RenderedRehearsal_BackupConfirmationApplyAndRestoreUseActualPortWithoutAuthoringStatusRewrite() + { + var services = new ServiceCollection(); + services.AddLogging(); + services.AddAutoForgeVehicleProfiles(); + services.AddAutoForgeUi(); + services.AddSingleton(); + using var provider = services.BuildServiceProvider(); + var configuration = CreateWarm(provider); + var authoring = provider.GetRequiredService(); + var baseline = authoring.CreateBaseline(configuration.ConfigurationIdentifier); + authoring.Save(Request(baseline, Values(baseline, scalar: 1250))); + 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, "rehearsal-provider", "autoforge.simulation.calibration-rehearsal"); + await renderer.ClickAsync(root, "rehearsal-open"); + await renderer.ClickAsync(root, "rehearsal-prepare-apply"); + Assert.Contains("backup", renderer.Text(root)); + await renderer.ClickAsync(root, "rehearsal-backup"); + Assert.Contains("Verified in-memory backup", renderer.Text(root)); + await renderer.ClickAsync(root, "rehearsal-prepare-apply"); + await renderer.ClickAsync(root, "rehearsal-approve"); + Assert.Contains("confirm", renderer.Text(root)); + await renderer.CheckAsync(root, "rehearsal-confirm", true); + await renderer.ClickAsync(root, "rehearsal-approve"); + await renderer.ClickAsync(root, "rehearsal-dispatch"); + Assert.Contains("VerifiedApplied", renderer.Text(root)); + Assert.Contains("1250 rpm", renderer.Text(root)); + Assert.Contains("Acknowledgement", renderer.Text(root)); + Assert.Contains("Independent full readback", renderer.Text(root)); + var torque = AutoForge.Application.Features.DisplayUnits.DisplayUnitConverter.Project( + 350, "N*m", AutoForge.Application.Features.DisplayUnits.DisplayUnitSelection.Default); + await renderer.ChangeAsync(root, "calibration-torque-2", torque.Value!.Value.ToString("R", System.Globalization.CultureInfo.InvariantCulture)); + await renderer.ClickAsync(root, "calibration-save"); + await renderer.ChangeAsync(root, "rehearsal-proposal", authoring.Snapshot!.Head.Identifier); + await renderer.ClickAsync(root, "rehearsal-prepare-apply"); + Assert.Contains("source 360 ->", renderer.Text(root)); + await renderer.CheckAsync(root, "rehearsal-confirm", true); + await renderer.ClickAsync(root, "rehearsal-approve"); + await renderer.ClickAsync(root, "rehearsal-dispatch"); + await renderer.ClickAsync(root, "rehearsal-prepare-restore"); + await renderer.CheckAsync(root, "rehearsal-confirm", true); + await renderer.ClickAsync(root, "rehearsal-approve"); + await renderer.ClickAsync(root, "rehearsal-dispatch"); + Assert.Contains("VerifiedRestored", renderer.Text(root)); + Assert.Contains("650 rpm", renderer.Text(root)); + Assert.Equal(CalibrationVersionKind.Proposed, authoring.Snapshot!.Head.Kind); + Assert.Equal(1250, authoring.Snapshot.Head.Values.Scalars[0].Value); + Assert.Equal(650, configuration.Model.WarmIdleTargetRpm); + await renderer.ClickAsync(root, "rehearsal-close"); + Assert.Contains("Closed", renderer.Text(root)); + await renderer.ClickAsync(root, "rehearsal-open"); + Assert.Contains("No verified target backup", renderer.Text(root)); + }); + } +}