``` # Step-04B - Reject lifecycle starts before mutating an undrained run Status: COMPLETE (worker implementation and verification; manual orchestrator acceptance of Step-04 remains pending) ## Summary Start and resume now reject before mutating engine lifecycle state when a prior advancement owner is still active or settling. `RunScenarioAsync` follows the same validate-before-mutate ordering, and `StartRunnerLocked` retains its defensive one-owner check. The policy is immediate, side-effect-free rejection; callers retry after the cancelling operation has completed. No wait is performed while holding the gate needed by old-owner cleanup. The original 202 Step-04A tests and numerical gates are preserved. Five new focused cases bring the final total to 126 unit and 81 integration tests (207 total). No project, package, public interface, physics, protocol, schema or physical capability was added or changed. ## Files changed for Step-04B - `src/AutoForge.Simulation/DynamicsEngine.cs` - `src/tests/AutoForge.UnitTests/DynamicsEngineTests.cs` - `src/tests/AutoForge.IntegrationTests/DynamicsWorkflowTests.cs` - `docs/simulation.md` - `docs/build-and-test.md` - `README.md` - `prompts/Step-04B-Report.md` (created) Architecture/interface changes: none. The existing private lifecycle helper is shared by Start/Resume; the equivalent scenario start path validates the owner before changing Stopped/Paused state. Existing run status, controls, services, protocol and UI contracts are unchanged except that the failed overlapping command no longer leaves a mutated Running state. ## Before/after regression evidence The controlled pre-fix reproduction held the old pacer in cancellation cleanup. The three transitions threw the expected owner-rejection exception only after changing state: - Pause -> Resume: expected `Paused`, observed `Running` at step 1 / 0.1 s. - Stop -> Start: expected `Stopped`, observed `Running` at step 1 / 0.1 s. - Reset -> Start: expected `Stopped` at step 0 / 0.0 s, observed `Running` at step 0 / 0.0 s. These were behavioral state assertions, not a compilation failure. The independent duplicate-start/invalid-resume case passed before the fix. After the fix, the unit regression asserts the complete status record and engine sample count before and after each rejected call, verifies cleanup remains blocked until released, awaits old-owner completion, then retries once. It asserts exactly one new step/sample and that pause cancels the new owner at that step. The real IntegrationTests DI/session/UI path also rejects `RunScenario` and Resume during the pending pause cleanup, preserves the status snapshot, and renders an error tone rather than reporting resumed/started success. ## Contract matrix | ID | Outcome | Evidence | |---|---|---| | C-01 | PASSED | After prior cleanup settles, Resume from Paused and Start from Stopped create the new owner; tests observe a distinct delay and exactly one new step/sample. | | C-02 | PASSED | Controlled Pause -> Resume rejection preserves the complete status and sample count. Real SimulationPageViewModel integration also rejects Resume and the equivalent RunScenario path with a visible error while cleanup is blocked. | | C-03 | PASSED | Controlled Stop -> Start and Reset -> Start rejection preserve complete status and sample count; reset remains at step/time zero and stop remains stopped. | | C-04 | PASSED | Releasing the cleanup barrier allows the original transition to finish; one retry advances once, old delay/task does not revive, and a subsequent pause freezes the new owner. | | C-05 | PASSED | Duplicate Start, Resume while Stopped, and Start/Resume after disposal remain explicit failures with intact status/ownership. Existing cancellation, disposal, reset, close and UI-run regressions also pass. | Focused checks: - Unit command: `dotnet test .\src\tests\AutoForge.UnitTests\AutoForge.UnitTests.csproj --configuration Release --no-restore --filter "FullyQualifiedName~StartOrResumeDuringOwnerDrainRejectsWithoutChangingStatus|FullyQualifiedName~DuplicateStartAndInvalidResumeDoNotChangeLifecycleOrOwner"` — exit 0; 4 passed, 0 failed/skipped. - Integration command: `dotnet test .\src\tests\AutoForge.IntegrationTests\AutoForge.IntegrationTests.csproj --configuration Release --no-restore --filter "FullyQualifiedName~ResumeRejectedDuringOwnerDrainIsVisibleThroughRealSimulationPage|FullyQualifiedName~ScenarioOwnerCannotBeReplacedAndResetOrCloseSuppressesOldRunPublication"` — exit 0; 2 passed, 0 failed/skipped. ## Full verification and numerical preservation Commands were run sequentially after the final code changes: - `dotnet build .\src\AutoForge.slnx --configuration Release --no-restore` — exit 0; all nine solution projects built; 0 warnings, 0 errors. - `dotnet test .\src\AutoForge.slnx --configuration Release --no-build` — exit 0; `AutoForge.UnitTests`: 126 passed; `AutoForge.IntegrationTests`: 81 passed; 207 total, 0 failed, 0 skipped. All 202 Step-04A baseline cases are included in those final counts, plus the five owner-drain cases. The full unit suite continues to verify the original deterministic baseline: 3,361 samples / 336.1 virtual seconds; 650 rpm warm idle; acceleration to 20.1473 m/s in 10.3 s with four shifts; all 3,000 cruise samples within the original 45-MPH +/- 1-MPH band while coupled; braking to 0.0000 m/s in 5.8 s; 10.0 s return idle; and 0.518387 kg modeled fuel. No numerical thresholds or model behavior were changed. ## Native Client smoke The actual Windows Client was launched from `src\AutoForge.Client\bin\Release\net10.0-windows10.0.26100.0\win-x64\AutoForge.Client.exe` with task-local WebView2 DevTools port 9347 and an isolated temporary profile. The native `/simulation` UI explicitly loaded profile `autoforge.synthetic.test-truck` revision 1, selected `autoforge.simulation.dynamics`, created the warm-baseline configuration `sha256:v1:e8991ae139b54959ec53a4fe64b08dc9bfc03feb533496cf741f2c9f3a2342da`, and opened a stopped session. The observed UI sequence was: - Start, Pause: `Paused`, 0.7 s / step 7. - Resume, Stop: `Stopped`, 0.8 s / step 8. - Restart, Stop: `Stopped`, 0.9 s / step 9. - Reset: new session `Stopped`, 0.0 s / step 0; protocol-v2 telemetry read included `SYNTHETIC_DYNAMIC` values at step 0. - Close: UI reported the session and its engine/pending work were released. This manual native click-path verifies normal lifecycle/time/telemetry behavior; it does not claim to force the cleanup race. The exact cancellation-drain interleaving is established by the controlled unit and real service/UI integration barriers. The task-launched Client (PID 22924), WebView2 helpers, port 9347 listener and isolated temporary profile were stopped/removed and verified absent. ## Acceptance criteria | ID | Result | Evidence | |---|---|---| | AC-01 | PASSED | C-01 through C-05 are mapped above to controlled pre-fix/post-fix snapshots, owner cleanup/retry, and invalid/closed transition assertions. | | AC-02 | PASSED | Cleanup remains awaitable without holding its gate; controlled retry/cancel/dispose and real UI/service rejection pass. No duplicate owner, stale task revival or false resumed/started success was observed. | | AC-03 | PASSED | Nine-project Release build: exit 0, 0 warnings/errors. Full suites: 126 unit + 81 integration passed. Original numerical gates pass. Native Client lifecycle/reset/telemetry/close smoke completed; forced interleaving is correctly distinguished as headless controlled evidence. | | AC-04 | PASSED | This report contains the contract/evidence matrix and source-path self-review. `docs/simulation.md`, `docs/build-and-test.md` and `README.md` document the policy, evidence and pending acceptance status. | | AC-05 | PASSED | Scope stayed within the listed Step-04B code/tests/docs/report. Protected assignment, ROADMAP, STATE and historical reports were not edited by this work. Existing dirty/untracked Step-04 history was retained; no staging, commit, push, agent or Step-05 work occurred. `git diff --check` exited 0; Git emitted its configured LF-to-CRLF working-copy notice for README. | ## Worker source-path self-review - Start and Resume enter `StartOrResumeAsync`: `EnsureOpen` and `EnsureNoActiveAdvancementOwner` precede `DynamicsEngine.Start/Resume`. - `RunScenarioAsync` performs the same owner check before changing Stopped or Paused lifecycle state. A currently running or draining owner is rejected before a second task can be installed. - `StartRunnerLocked` retains its owner check as a defensive invariant. - Pause/Stop/Reset mutate their intended lifecycle state, cancel the runner, release the gate, and only then await cleanup. The old runner can acquire the gate in its `finally` block and clear its ownership slot. Start/Resume do not wait while holding that gate. - `EnsureOpen` remains ahead of owner validation; invalid, duplicate, closed and disposed requests remain explicit errors. UI lifecycle and scenario wrappers surface rejected commands as error notices; real integration tests assert rejection does not change run state. - Test barriers release in `finally`; controlled tests assert status, sample, cleanup, retry and cancellation behavior without sleeps/polling. - Full Release tests preserve the earlier numerical, protocol and lifecycle regressions. Native evidence verifies the normal Client path only. ## Limitations and handoff The forced cleanup interleaving is not a human-timed native UI scenario; it is covered by deterministic controlled pacers in unit and real DI/session/UI integration tests. Numerical outputs remain synthetic. No other deviation or unresolved implementation issue remains for this assignment. Step-04 acceptance remains the orchestrator's responsibility. No Step-05 work was started. ```