After Step 10

This commit is contained in:
GAJ3T 2026-10-31 05:28:02 -04:00
parent f2a8c37335
commit bccb7979dc
11 changed files with 1099 additions and 75 deletions

View File

@ -118,6 +118,13 @@ 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.
Step-10A corrects close ownership while a new rehearsal factory return is
pending: a newly admitted opening lifetime cannot reuse the previous close
completion, and Close/disposal drains its actual owner before returning.
The [corrective report](prompts/Step-10A-Report.md) records controlled
pre/post behavior and native recheck. Step-10 remains not accepted pending
manual review of the correction; no programming scope or limits were added.
### Planned
Durable/full-device backups, dynamics application, AI and real hardware operations

View File

@ -17,6 +17,8 @@ immutable source-bound proposals and exact diffs, without model/device changes.
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.
Step-10A corrects the pending-reopen close/disposal completion lifetime.
Original Step-10 evidence is preserved; acceptance awaits corrective review.
- [Architecture](architecture.md): actual nine-project graph, responsibilities,
route ownership and provider/reference boundaries.
@ -78,5 +80,6 @@ historical/worker reports for their own execution evidence:
[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) and
[Step-10 worker report](../prompts/Step-10-Report.md).
[Step-10 worker report](../prompts/Step-10-Report.md) and
[Step-10A corrective report](../prompts/Step-10A-Report.md).
Handoffs are manual; acceptance remains the orchestrator's responsibility.

View File

@ -258,6 +258,16 @@ authorize a fresh target. At most 32 dispatched Apply/Restore outcomes and only
bounded current preparation/command evidence are retained. See
[rehearsal contracts](calibration-rehearsal.md).
A newly admitted opening owner establishes its target lifetime under the
rehearsal state gate, before the synchronous factory may return. At that point
the prior lifetime's cached close completion is retired, including a prior
failed close. Competing Close/disposal publishes one new shared completion,
invalidates/cancels that actual owner and waits for its cleanup outside the
gate. A late factory target cannot publish into a closed/disposed lifetime and
is disposed by its opening owner exactly once. Closed state and its close
completion publish atomically after drainage; disposed page sessions reject
reuse, while ordinary Close permits a fresh explicit opening.
Implemented diagnostics and dynamics are synthetic, in-process and
Simulation-only. They prove encoded request/response handling and deterministic
model behavior, not vehicle compatibility, access, authenticity, real capture,

View File

@ -44,8 +44,46 @@ dotnet test .\src\tests\AutoForge.IntegrationTests\AutoForge.IntegrationTests.cs
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"
dotnet test .\src\tests\AutoForge.IntegrationTests\AutoForge.IntegrationTests.csproj --configuration Release --no-restore --filter "FullyQualifiedName~CalibrationRehearsalReopenTests|FullyQualifiedName~CalibrationRehearsalTests|FullyQualifiedName~RenderedRehearsal|FullyQualifiedName~RehearsalIsolation"
```
## Step-10A pending-reopen close ownership verification
Step-10 remains not accepted pending manual corrective review. Original
Step-10 results below and its worker report are preserved.
Before the fix, the two `PendingReopenCloseOrDispose_DrainsCurrentOwnerWithoutPriorCompletionReplay`
cases executed against the actual Simulation factory and failed with:
prior close reused=True, Close/Dispose completed while factory held=True,
released Open error=none, state=Ready and new target dispose count=0.
Barriers were released and actual targets drained in finally, so the test
runner exited with two behavioral failures rather than stranded workers.
After the correction, all six new cases passed. They assert a new current-close
completion, cancellation/drain while factory return and actual target cleanup
are held, no Ready publication, retained inactive evidence, exactly one real
target disposal and unusable disposed sessions. Prior failed close, current
factory/cleanup failure, rejected reopen and later valid sequential reopen
are exercised. The combined corrective/original rehearsal selector above
passed **37 cases**, zero failed/skipped.
The required sequential nine-project Release build passed with **0 warnings,
0 errors**, followed by **179 unit + 263 integration = 442 passed**,
zero failed/skipped. All 436 baseline cases remain unchanged.
The rebuilt native Client rechecked explicit source/proposal/target selection,
two-read backup, confirmed Apply/full readback, separately confirmed original
Restore, repeated Close, new-instance/zero-revision reopen and calibration
route close/re-entry. A combined proposal stored 1250 rpm and 350 N*m at
2000 rpm in the isolated image at revision 1; original Restore recovered
650/360 and every other cell/axis at revision 2. Source export/fingerprint
remained identical; a separate ordinary dynamics read at step 7 returned
631.80416 rpm from the unchanged model. Units preserved approval without
dispatch, and original preferences/old replay route remained intact.
The pending-factory race is controlled test proof, not native timing evidence.
Exact commands, observations, cleanup and limitations are in the
[Step-10A corrective report](../prompts/Step-10A-Report.md).
## Step-10 simulated programming rehearsal verification
Step-09 is accepted; Step-10 remains pending manual review. The final focused

View File

@ -118,6 +118,18 @@ 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.
Close completion belongs to the current admitted target lifetime, not merely
the last successfully published target. A new opening owner retires the old
completed/failed close task under the state gate before factory execution.
Close or page disposal during that pending factory invalidates/cancels the
owner and drains its late-created target cleanup before returning. Repeated
current Close calls share one completion/error; none returns a prior lifetime's
success or failure. No cleanup await holds the required state gate.
Closed state/completion publish together after drainage. Rejected/failed opens
retain inactive backup/approval evidence without granting new-target authority;
disposed sessions cannot publish or reopen, whereas completed ordinary Close
allows another explicit fresh instance.
## Bounded volatile audit and units
At most **32 dispatched mutation outcomes per target** are retained, including
@ -144,6 +156,9 @@ 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.
Step-10A adds controlled actual-factory return/disposal barriers for pending
reopen against Close/Dispose, including prior failed close and current failures.
This interleaving is test evidence, not a claim about human-timed native races.
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

View File

@ -3,18 +3,19 @@
## Status and authority
- Initialized: 2026-10-28.
- 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 correction: Step-10 C-07/C-11 close completion can belong to a previous target lifetime during pending reopen.
- Current phase: corrected programming rehearsal accepted; deterministic runbook validation/preview next.
- Active assignment: [Step-11](Step-11.md), ready for manual worker execution.
- Last accepted milestone: Step-10 with Step-10A, accepted 2026-10-31.
- Last accepted correction: Step-10A; all Step-10 findings closed.
- Outstanding corrections: none.
- Step-05 status: ACCEPTED after Step-05A/Step-05B, 2026-10-29.
- Step-06 status: ACCEPTED after Step-06A, 2026-10-30.
- Step-07 status: ACCEPTED after Step-07A/Step-07B, 2026-10-30.
- Step-08 status: ACCEPTED 2026-10-30; no Step-08A required.
- Step-09 status: ACCEPTED 2026-10-30; no Step-09A required.
- 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.
- Step-10 status: ACCEPTED after Step-10A, 2026-10-31.
- Step-11 status: READY FOR WORKER; deterministic simulation runbook validation/preview only.
- Step-12 status: local AI/knowledge integration; BLOCKED / NOT ASSIGNED until the validation boundary is accepted.
- Current state and handoff: [STATE.md](STATE.md).
- Authority: the master charter, repository/handoff amendment, and the owner's
2026-10-28 architectural realignment. The latest decision cancels the dual-shell
@ -235,6 +236,26 @@ replay stay unchanged. Applying the programmed image to a new dynamics run and
functional performance verification require a later explicit assignment.
No crash-durable backup, real-device recovery or manufacturer safety claim is made.
## Prospective runbook/inference scope split - 2026-10-31
The former local-AI/knowledge/runbook envelope would introduce model/runtime
integration, retrieved context, a structured planning format and a permission/
validation boundary together. Apply the existing sizing policy before execution:
- Step-11: deterministic schema-v1 runbook validation and read-only preview of
one allowlisted synthetic calibration proposal against an explicit authoring
workspace/head. Manually supplied JSON exercises the boundary without a model.
- Step-12: replaceable local inference and applicable knowledge feeding that
accepted boundary. No model output may bypass deterministic validation or the
separately approved rehearsal mutation workflow. Not assigned yet.
- Former unassigned Steps 12-23 become 13-24 below. Completed assignments/history
retain their numbering; planned capabilities are not corrective letters.
Step-11 does not install/run an LLM, retrieve knowledge, save an authoring proposal,
approve a mutation or execute a runbook. A valid preview is not an authorization
token or target verification. Later inference may propose structured data;
existing deterministic source/head/template and approval checks remain required.
## Architecture baseline
### Existing accepted foundation, preserved
@ -427,9 +448,10 @@ 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 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.
supported. Corrected Step-10/10A is accepted: isolated target backup/approval/
CAS/readback/recovery and current-lifetime close drainage are supported.
Step-11 is the only active assignment for deterministic runbook preview;
local inference/knowledge is the following Step-12, not bundled into validation.
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.
@ -456,23 +478,24 @@ 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 | 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 |
| 15 | Broader diagnostic protocols and hardware adapters | 13 | PLANNED | Conformance-backed additional CAN/ISO-TP/UDS/KWP2000/J2534 or legacy adapters where verified; same application ports and capability restrictions |
| 16 | Curated vehicle knowledge and research workflow | 11; 15 where needed | PLANNED | Sourced profile/module/calibration knowledge, review/promotion workflow, exact applicability, licensing/access controls; research cannot authorize writes |
| 17 | Higher-fidelity simulation and virtual module coverage | 12; 16 for verified datasets | PLANNED | Validated model extensions, richer transmissions/environment/module interactions and reproducible fault coverage; published fidelity limits |
| 18 | AI evaluation and optional specialization | 11, 12, 16 and adequate datasets | PLANNED | Held-out deterministic runbook evaluations, refusal/uncertainty cases, memory/latency measurements; LoRA/QLoRA only if justified by measured benefit |
| 19 | Programming qualification without physical writes | 10, 12, 13, applicable 15/16 evidence | PLANNED | Module-specific safety case, bench plan, voltage/state/identity checks, interruption/recovery tests in simulation, legal authorization and defined go/no-go criteria |
| 20 | Explicitly authorized controlled bench programming | 19 and separate user authorization | PLANNED / AUTHORIZATION GATE | Authorized supported bench target only; verified backup completeness, transfer/readback/recovery evidence and audit; no general vehicle-write enablement |
| 21 | Approved vehicle/module-specific programming | 20 and separate vehicle-operation authorization | PLANNED / AUTHORIZATION GATE | Explicit per-operation approvals, compatibility/operating-state/power/security checks and proven recovery limits; strict module-specific support matrix |
| 22 | Packaging, extensibility, and additional platforms | 06, 12; feature-specific gates remain | PLANNED | Offline-friendly reproducible releases, documented supported hosts, feature manifests/DI, compatibility/migration regression evidence |
| 23 | Optional MCP and firmware-emulation research | 11, 16; isolated research approvals | OPTIONAL / PLANNED | Concrete benefit and separate ADR; restricted tools retain validator/approval boundary; emulation limitations and proprietary-data rights documented |
| 10 | Verified simulated programming and recovery | 09 accepted | ACCEPTED 2026-10-31 AFTER 10A | Isolated supported-image backup, exact approval/CAS/full readback/reconcile/Restore and current close ownership; no physical writes/model application |
| 10A | Close/disposal ownership during pending rehearsal reopen | 10 review C-07/C-11 | ACCEPTED 2026-10-31 | Old close task retired at admission, disposed/generation guards and atomic close completion; actual pre-fix/controlled cleanup plus reported 179 unit/263 integration passes |
| 11 | Deterministic simulation runbook validation and preview | 10 and corrections accepted | READY FOR WORKER | Strict bounded schema-v1/allowlist/source-head/template validation, immutable exact proposal preview and stale status; no model, save, approval or execution |
| 12 | Local AI and applicable knowledge integration | 11 accepted | BLOCKED / NOT ASSIGNED | Replaceable local inference/context returns structured data through the accepted validator; missing/disconnected/invalid outcomes explicit, no bypass of mutation approval |
| 13 | Comparative evaluation and complete synthetic demonstration | 12 | PLANNED | Complete demonstration below plus deterministic fault/regression matrix and independent verification of intended and unintended changes |
| 14 | Verified OBDX Pro GT read-only integration | 13 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 |
| 15 | Advanced dashboards, analysis, and comparisons | 13; 14 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 |
| 16 | Broader diagnostic protocols and hardware adapters | 14 | PLANNED | Conformance-backed additional CAN/ISO-TP/UDS/KWP2000/J2534 or legacy adapters where verified; same application ports and capability restrictions |
| 17 | Curated vehicle knowledge and research workflow | 12; 16 where needed | PLANNED | Sourced profile/module/calibration knowledge, review/promotion workflow, exact applicability, licensing/access controls; research cannot authorize writes |
| 18 | Higher-fidelity simulation and virtual module coverage | 13; 17 for verified datasets | PLANNED | Validated model extensions, richer transmissions/environment/module interactions and reproducible fault coverage; published fidelity limits |
| 19 | AI evaluation and optional specialization | 12, 13, 17 and adequate datasets | PLANNED | Held-out deterministic runbook evaluations, refusal/uncertainty cases, memory/latency measurements; LoRA/QLoRA only if justified by measured benefit |
| 20 | Programming qualification without physical writes | 10, 13, 14, applicable 16/17 evidence | PLANNED | Module-specific safety case, bench plan, voltage/state/identity checks, interruption/recovery tests in simulation, legal authorization and defined go/no-go criteria |
| 21 | Explicitly authorized controlled bench programming | 20 and separate user authorization | PLANNED / AUTHORIZATION GATE | Authorized supported bench target only; verified backup completeness, transfer/readback/recovery evidence and audit; no general vehicle-write enablement |
| 22 | Approved vehicle/module-specific programming | 21 and separate vehicle-operation authorization | PLANNED / AUTHORIZATION GATE | Explicit per-operation approvals, compatibility/operating-state/power/security checks and proven recovery limits; strict module-specific support matrix |
| 23 | Packaging, extensibility, and additional platforms | 06, 13; feature-specific gates remain | PLANNED | Offline-friendly reproducible releases, documented supported hosts, feature manifests/DI, compatibility/migration regression evidence |
| 24 | Optional MCP and firmware-emulation research | 12, 17; isolated research approvals | OPTIONAL / PLANNED | Concrete benefit and separate ADR; restricted tools retain validator/approval boundary; emulation limitations and proprietary-data rights documented |
### Scope details for Steps 02-13
### Scope details for Steps 02-14
- **01A accepted prerequisite:** one thin MAUI Client, two RCLs, feature-organized
target selection, actual headless rendered tests and worker native build/smoke
@ -529,7 +552,7 @@ evidence; they must not silently discard required capabilities.
unavailable/stale/error states, with one source/session-aware acquisition owner.
Supply a contract matrix for invalid ranges, missing signals and session
replacement before coding. No charts, drag/drop or new clock/protocol/backend.
Larger dashboard composition remains Step-14 scope. Client stays thin and no
Larger dashboard composition remains Step-15 scope. Client stays thin and no
alternate host is introduced. Dashboard configuration is in-memory only for
this slice; persistence/schema work is not bundled into the feed state machine.
- **06:** newly approved display-only unit preference and conversions, Imperial
@ -548,19 +571,22 @@ evidence; they must not silently discard required capabilities.
- **10:** verified simulated baseline/backup, approval bound to source/proposal,
write/readback/unrelated-value checks, audit, restore and explicit recovery.
No physical writes or assumed manufacturer calibration knowledge.
- **11:** local inference provider configuration, structured queries plus optional
- **11:** bounded deterministic simulation-only runbook input, exact source/head/
template validation and read-only proposed scalar/table preview. Manual input
first; no LLM, knowledge retrieval, proposal Save or mutation execution.
- **12:** local inference provider configuration, structured queries plus optional
semantic retrieval, source-backed applicability checks, versioned runbook schema
and restricted tools. Include natural-language diagnostics, driving scenarios,
and calibration planning; AI cannot emit arbitrary hardware frames/offset writes.
Missing knowledge and disconnected inference produce explicit outcomes without
disabling non-AI functionality.
- **12:** equivalent baseline/modified scenarios and initial state, independent
- **13:** equivalent baseline/modified scenarios and initial state, independent
calibration oracle, behavioral/fuel/shift comparisons with confidence labels,
fault reports, replay/raw-trace inspection and an auditable verification report.
Include timeout, unsupported service, malformed response, wrong identity/version,
interruption, corruption/checksum, partial write, reset, incompatible config,
DTC and failed-verification cases.
- **13:** verify OBDX Pro GT protocols, drivers, OS/architecture constraints,
- **14:** verify OBDX Pro GT protocols, drivers, OS/architecture constraints,
manufacturer libraries/SDKs, actual J2534 support and C# integration using
attributable sources before implementation. Missing device/driver access means
real-hardware verification is blocked, not passed by mocks. Restrict services to
@ -569,7 +595,7 @@ evidence; they must not silently discard required capabilities.
### Longer-term scope preservation
Steps 14-23 retain richer gauges/clusters/charts and dashboard editing, comparison
Steps 15-24 retain richer gauges/clusters/charts and dashboard editing, comparison
and analysis, more vehicle/module/protocol coverage, independently validated
research, curated datasets, advanced dynamics and transmission modeling, local
model evaluation/specialization, authorized programming, and supported release
@ -586,7 +612,7 @@ continue only independent safe work through an explicit new assignment.
## Required synthetic end-to-end demonstration
Target acceptance: Step-12. Use the explicitly synthetic AutoForge test truck,
Target acceptance: Step-13. Use the explicitly synthetic AutoForge test truck,
initial warm idle 650 RPM and proposed warm idle 1,250 RPM. These values and any
memory layout are synthetic, not manufacturer calibration data.
@ -914,25 +940,38 @@ history, not repeated redesign without evidence.
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:
- At that review most scope was supported, but one C-07/C-11 lifetime edge remained:
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.
- Reviewed and accepted Step-10A's admission-time close-task retirement,
disposed/current-generation guards and atomic Closed/completion publication.
Actual factory-return/disposal barriers establish the pre-fix Close/Dispose
failures and corrected current owner/cleanup/error semantics.
- Worker reports 179 unit + 263 integration passes (442 total, zero failed/
skipped), clean complete Release build and actual native backup/Apply/Restore/
repeated Close/reopen/unmount/source/unit checks. The orchestrator ran no
application checks. Corrected Step-10/10A is accepted with no Step-10B.
- Prepared [Step-11](Step-11.md), separating deterministic runbook validation/
preview from subsequent Step-12 local inference/knowledge. Only unassigned
future envelopes/dependencies shifted; completed history is unchanged.
### Remaining
- 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.
- Worker execution of Step-11, then review its frozen schema/allowlist/source/
head/template/preview/no-side-effect matrix and shared quality gate.
Correct genuine unmet requirements as Step-11A before local inference.
- Step-12 AI is blocked and not assigned. Runbook preview is assigned work,
not implemented functionality; programming rehearsal and earlier work are accepted.
- Profile/module metadata, synthetic virtual-module communication and deterministic
dynamics/v2 and corrected dashboard are accepted; later features remain planned.
Preserve the complete sequence/safety gates.
### Known blockers and uncertainties
The single Step-10 finding is close-completion ownership during reopen:
No blocking Step-10 deficiency remains. Its pending-reopen finding below is
historical and closed by accepted Step-10A:
- CloseAsync returns any cached _closeTask immediately. A completed previous
target's close leaves that task cached.
@ -945,15 +984,15 @@ The single Step-10 finding is close-completion ownership during reopen:
- 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.
That was source-path evidence, not an orchestrator-executed reproduction.
Step-10A supplied actual pre-fix failure observations and controlled post-fix
factory/target-disposal/current-completion assertions, retaining original
backup/approval/readback/restore/audit/native evidence.
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 supplies separate rehearsal contracts, currently
pending its focused lifetime correction.
program anything. Corrected Step-10 supplies the separate accepted rehearsal
backup/approval/write/readback/restore contracts.
No blocking Step-08 deficiency was identified against its frozen contract.
The worker disclosed an existing recording-panel initialization race when a
@ -961,7 +1000,7 @@ Save-followup refresh is still pending during host navigation. That unchanged
recording flow is outside Step-08; no replay check is claimed to cover/fix it.
Native preparation was restarted and final-binary replay passed without the
error overlay. Retain the issue for a separately scoped recording follow-up,
not a retrospective replay/authoring criterion or automatic Step-10 cleanup.
not a retrospective replay/authoring criterion or automatic Step-11 cleanup.
No blocking Step-07 deficiency remains. Its source-close follow-up below is
historical and closed by accepted Step-07B:

View File

@ -5,14 +5,14 @@
| Field | Value |
|---|---|
| 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) |
| Phase | Corrected programming rehearsal accepted; deterministic runbook preview next |
| Active step | Step-11 - Deterministic simulation runbook validation and preview |
| Assignment | [Step-11.md](Step-11.md) |
| Assignment status | READY FOR WORKER / AWAITING MANUAL HANDOFF |
| 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 correction | Step-10 C-07/C-11 cached prior Close task can bypass pending-reopen cancellation/drain |
| Expected worker report | `prompts/Step-11-Report.md` - not yet created |
| Last accepted correction | Step-10A - accepted 2026-10-31 |
| Last accepted major milestone | Step-10 with Step-10A - accepted 2026-10-31 |
| Outstanding corrections | None |
| 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,11 @@
| 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 | REQUIRES FOCUSED CORRECTION / NOT ACCEPTED |
| Step-11 status | Local AI/runbooks; BLOCKED until Step-10 acceptance |
| 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 |
| Step-10 status | ACCEPTED after Step-10A |
| Step-11 status | READY FOR WORKER; deterministic simulation runbook preview only |
| Step-12 status | Local inference/knowledge; BLOCKED until validator acceptance |
| Worker execution | Step-10A returned and accepted; Step-11 not invoked |
| Immediate next action | User manually directs the worker to execute Step-11 and shared quality gate only |
| Next orchestrator action | After manual return, inspect the assignment, report, implementation, tests, Git changes, documentation and recorded command evidence |
## Repository baseline at initialization
@ -1119,11 +1120,12 @@ Closing/reopening destroys/recreates the rehearsal target; old approvals/backups
cannot act on a new instance. No physical/replay target, running-dynamics mutation,
new wire/firmware format or crash-durable/device-backup claim is assigned.
Connecting the programmed image to a fresh dynamics run and functional evaluation
is later explicit work, not an implied Step-10 feature. Step-11 remains blocked.
is later explicit work, not an implied Step-10 feature. At that handoff the
combined Step-11 AI/runbook envelope was blocked pending rehearsal acceptance.
## Step-10 review and focused lifetime correction
## Historical Step-10 review and focused lifetime correction
Decision: **REQUIRES FOCUSED CORRECTION / NOT ACCEPTED**, 2026-10-31.
Decision at that review: **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
@ -1177,6 +1179,57 @@ Preserve [Step-10-Report.md](Step-10-Report.md) unchanged.
ownership and its regression. No target/protocol/backup/approval redesign,
physical-write permission or Step-11 assignment is introduced.
## Step-10A acceptance and corrected Step-10
Decision: **ACCEPTED**, 2026-10-31. Frozen C-01..C-05/AC-01..AC-04 are satisfied.
Corrected Step-10 with Step-10A is accepted; no Step-10B is required.
Reviewed [Step-10A](Step-10A.md), its [report](Step-10A-Report.md), the complete
surgical session diff, all six actual-factory/target cleanup regressions,
related docs/README and unchanged project graph/Release artifacts.
| Criterion | Decision | Evidence |
|---|---|---|
| AC-01 | ACCEPTED | Actual pre-fix old task reuse/early closure/late Ready for both Close and Dispose; old completion retired at new-open admission, disposed/generation guards, held actual factory and target disposal prove correct drainage/no publication |
| AC-02 | ACCEPTED | Previous/current close failures, rejected/failed factory reopen, same-lifetime shared completion and exact one-disposal assertions; inactive evidence preserved and valid sequential reopen works |
| AC-03 | ACCEPTED ON WORKER EXECUTION EVIDENCE | Reported complete nine-project Release build zero warnings/errors; 179 unit + 263 integration passes (442 total, zero failed/skipped), real native target/backup/Apply/Restore/reopen/unmount/source/unit recheck |
| AC-04 | ACCEPTED | Post-green atomic Closed/completion refinement, safe barrier/target cleanup, accurate native/control and pre/post evidence, original history/scope/dependencies/manual workflow preserved |
The six added cases preserve all 436 original cases. Admission and close-task/
owner publication occur under one gate before factory execution; cleanup occurs
outside it. Closed state and shared success/failure publish together, so a new
open cannot enter through a Closed-before-completion gap. Late factory targets
are disposed by their opening owner exactly once.
The orchestrator ran no application builds/tests/native/workload commands and
did not execute the reproduction. Source/graph/artifacts corroborate worker
evidence, not independent runtime verification. Original Step-10 programming/
backup/CAS/readback/recovery and its native evidence remain intact.
## Prospective runbook/inference split and Step-11 handoff
The former local-AI/knowledge/runbook envelope combines inference/runtime,
context retrieval, structured planning and deterministic permission/validation.
Apply the existing bounded-scope policy before execution:
- Step-11: strict bounded schema-v1 input and read-only preview of one allowlisted
synthetic calibration proposal against explicit authoring workspace/head.
- Step-12: replaceable local inference and applicable knowledge feeding that
accepted boundary, with no bypass of deterministic checks/approval.
- Former unassigned Steps 12-23 become 13-24; completed assignments/history
retain their numbering and corrective letters remain actual fixes only.
[Step-11](Step-11.md) exercises the deterministic boundary with manually supplied
JSON, not an LLM. A valid preview cannot save an authoring proposal, approve/open/
mutate a target, execute a runbook or claim live/backup/physical verification.
Only one last successful preview is retained; invalid inputs preserve it with a
visible error, and changed source/head marks it stale rather than silently rebasing.
No inference/model/knowledge retrieval or app-level Git backup integration is
implemented/assigned in this slice. Current domain source/head/target checks
remain necessary; the earlier Git discussion did not authorize a persistence
rewrite of the accepted volatile rehearsal.
## Prerequisites, limitations, and known issues
- Step-01A worker evidence establishes portable and native Windows compatibility
@ -1204,23 +1257,23 @@ physical-write permission or Step-11 assignment is introduced.
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 exists but is unaccepted pending its focused lifetime
correction. AI and physical hardware operations remain unimplemented.
Corrected simulated programming is accepted. Runbook validation/preview,
local inference/knowledge 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-10A and the original Step-10 close/lifetime contract/shared gate using the
On manual return, evaluate Step-11 and its frozen runbook-preview 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 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
- Inspect strict schema/limits/allowlist, exact current source/head/template,
immutable preview/diff/staleness, real UI and zero save/approval/model effects.
Do not add deferred inference/retrieval/execution/persistence requirements.
- If accepted: accept Step-11, update roadmap/state, prepare a bounded Step-12 local-inference/knowledge assignment
and stop for manual handoff.
- If deficient: issue narrowly scoped Step-10B only for a material unmet contract/
- If deficient: issue narrowly scoped Step-11A 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.
@ -1300,12 +1353,16 @@ claim; do not claim independent runtime verification.
| 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 |
| 2026-10-31 | Step-10A returned and ACCEPTED | Frozen current-close/reopen contract satisfied; actual pre-fix failures, six controlled cleanup cases and reported 442-case/clean Release/native evidence inspected |
| 2026-10-31 | Corrected Step-10 ACCEPTED | Original and 10A criteria closed; backup/approval/CAS/readback/restore/source safety preserved; no 10B |
| 2026-10-31 | Runbook/inference envelope split prospectively | Step-11 deterministic validation/preview, Step-12 local inference/knowledge; former unassigned 12-23 become 13-24, completed history preserved |
| 2026-10-31 | Step-11 prepared | One allowlisted simulation proposal, strict source/head/template/JSON validation and immutable no-execution preview; manual handoff pending |
## Manual handoff instruction
Provide [Step-10A.md](Step-10A.md), original [Step-10.md](Step-10.md) and the shared
Provide [Step-11.md](Step-11.md) and the shared
[worker gate](WORKER-QUALITY-GATE.md) to the separate worker and request execution
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.
of that assignment only. The worker must produce `prompts/Step-11-Report.md`
and stop for review. Do not begin Step-12 local inference/knowledge.
Return manually to the orchestrator for review. Reports, including final chat
reports, must follow the single plain triple-backtick copy-window requirement.

228
prompts/Step-10A-Report.md Normal file
View File

@ -0,0 +1,228 @@
```
# Step-10A - Close ownership during pending rehearsal reopen
## Status
COMPLETE. The actual pre-fix interleaving was reproduced safely, the narrow
open/close/disposal coordination fix is implemented, all corrective/original
tests and nine-project Release build pass, and the required native recheck
passed. Step-10 remains NOT ACCEPTED pending manual corrective review.
Step-09/earlier accepted work and original Step-10 reports/evidence remain
unchanged. Step-11 was not started.
## Implementation and files
[CalibrationRehearsalSession.cs](../src/AutoForge.Application/Features/Vehicles/Calibration/CalibrationRehearsalSession.cs)
contains the only production change:
- Start retires the previous completed/failed _closeTask under the existing
state gate when a new opening owner without a current target is admitted.
This happens together with owner publication, before synchronous factory
execution, rather than only after target publication succeeds.
- Open no longer clears the close task on successful target publication.
- EnsureCurrent/CanPublish reject disposed lifetime publication in addition
to existing cancellation/generation/close checks.
- After outside-gate drainage, Closed state and shared close completion/failure
publish together under the state gate. Continuations remain asynchronous;
no cleanup await holds that gate.
CloseAsync retains its existing same-lifetime shared completion, owner
cancellation, target cleanup and explicit failure contract. No public signature,
programming/backup/approval/CAS/audit/target/port design or page implementation
was changed. The production diff is 5 added and 4 removed lines.
[CalibrationRehearsalReopenTests.cs](../src/tests/AutoForge.IntegrationTests/CalibrationRehearsalReopenTests.cs)
adds six focused cases. ReopenBarrierFactory forwards actual
SimulatedCalibrationTargetFactory creation and wraps the actual target. It
holds the second synchronous factory return on a task-owned concurrent Open,
then holds its target disposal independently. Disposal invocation/completion
counts and actual disposed-port reads are checked. There is no production race
selector, workflow mock, oracle, sleep or stress/GC proxy.
## Actual pre-fix reproduction
Command:
dotnet test .\src\tests\AutoForge.IntegrationTests\AutoForge.IntegrationTests.csproj --configuration Release --no-restore --filter "FullyQualifiedName~PendingReopenCloseOrDispose_DrainsCurrentOwnerWithoutPriorCompletionReplay"
Exit 1: 2 failed, 0 passed/skipped. Compilation succeeded.
Both theory cases established the same actual ordering:
1. Open real target A; independently prepare backup/approval; fully await its
first Close and verify one target disposal.
2. Admit a new Open on a task-owned thread. The real factory creates target B,
then signals/holds its second return before Application publication.
3. Call Close or Dispose while factory return is held; inspect its completion
and the current Close task against the old lifetime's close task.
4. Release factory, observe Open completion/state and B's disposal count before
finally draining/closing all owned work and targets.
Exact failure observations for BOTH Close and Dispose:
PriorTaskReused=True
CloseOrDisposeFinishedWhileFactoryHeld=True
OpenError=none
StateAfterFactoryRelease=Ready
CreatedTargetDisposeCount=0
ActualTargetDisposed=False
The Dispose observation means disposal returned through the prior close
completion and then the opening owner published Ready; it does not claim
the disposed session could authorize a physical operation. The reproduction
released barriers and explicitly closed/drained the late target in finally.
The test process exited normally; no stranded worker/process required killing.
The 10/20-second deadlines are cleanup safety guards, not timing-race evidence.
## Frozen corrective matrix
All rows below are PASSED after the fix.
| ID | Named executed evidence and exact post-fix outcome |
|---|---|
| C-01 | PendingReopenCloseOrDispose_DrainsCurrentOwnerWithoutPriorCompletionReplay(dispose:false), RejectedReopen_PreservesInactiveEvidenceAndDoesNotReuseCompletedClose and original CloseReopen tests. Normal target closes once; repeated same-lifetime Close shares one Task. Later explicit Open gets a different instance, no inherited backup/approval and independently read revision-zero scalar 650. |
| C-02 | PendingReopenCloseOrDispose_DrainsCurrentOwnerWithoutPriorCompletionReplay(dispose:false). Current Close is not prior Close, remains incomplete while actual second factory return is held and remains incomplete while target disposal is held. Repeated current Close shares that new completion. After releases, Open is cancelled, state remains Closed, old inactive backup/approval references remain, B disposal invocation=1/completion=true, and its actual Read throws ObjectDisposedException. No late Ready/current target is published. |
| C-03 | The same regression with dispose:true. Dispose cannot finish through old close completion; it drains current Open and the one real B disposal. Closed/no-busy state and inactive evidence remain. After disposal completes, NewOperationId and Open reject Closed; no Ready/backup/approval publication or disposed-session reuse occurs. Native calibration unmount/re-entry also passed as normal lifecycle evidence. |
| C-04 | PendingReopenAfterFailedClose_CurrentCleanupHasItsOwnSharedOutcome (current cleanup succeeds/fails), PendingFactoryFailure_CurrentCloseDrainsItsOwnFailureAndRetainsInactiveEvidence, RejectedReopen_PreservesInactiveEvidenceAndDoesNotReuseCompletedClose. Prior failed close is not replayed as current completion. Current Close shares its own unfinished Task; actual cleanup occurs once. Current factory/target errors remain explicit IOException/current-error evidence, not stale failure or swallowed success. Rejected/failed Open preserves inactive backup state. A later valid sequential Open remains usable with fresh identity/backup state. |
| C-05 | Combined corrective/original rehearsal selector: 37 passed. Full build/test: all nine Release projects, 179 unit + 263 integration = 442 passes, zero failed/skipped, preserving every one of the 436 baseline cases. Native actual target/backup/Apply/Restore/repeated Close/reopen/route cleanup plus source/unit isolation passed. No target/port/model/programming redesign, physical operation or AI work. |
## Acceptance criteria
| ID | Result | Evidence |
|---|---|---|
| AC-01 | PASSED | Safely cleaned actual pre-fix Close/Dispose reproduction and post-fix factory-return/disposal barriers prove current completion, cancellation/drain, one real disposal and no late publication. |
| AC-02 | PASSED | Prior/current failed close, factory failure, rejected Open, shared completion/error, retained inactive evidence and later valid sequential Open cases; own source-path ordering review. |
| AC-03 | PASSED | All 436 baseline cases plus 6 new cases pass; nine-project Release build has 0 warnings/errors; actual native normal recheck/source-unit/route cleanup passed. |
| AC-04 | PASSED | Surgical session-only production change, directly related docs/README, protected/history/dependencies/manual gate preserved, this single fenced report saved and worker stops. |
## Commands and final outcomes
Current SDK: dotnet --version -> 10.0.403. Existing xUnit v2/VSTest is
unchanged. No package/SDK/workload/tool install, restore, update or repair.
Focused checks, required full build and full regressions ran sequentially:
| Exact command | Exit | Result |
|---|---:|---|
| dotnet test .\src\tests\AutoForge.IntegrationTests\AutoForge.IntegrationTests.csproj --configuration Release --no-restore --filter "FullyQualifiedName~CalibrationRehearsalReopenTests" | 0 | 6 corrective cases passed, zero failed/skipped. |
| dotnet test .\src\tests\AutoForge.IntegrationTests\AutoForge.IntegrationTests.csproj --configuration Release --no-restore --filter "FullyQualifiedName~CalibrationRehearsalReopenTests|FullyQualifiedName~CalibrationRehearsalTests|FullyQualifiedName~RenderedRehearsal|FullyQualifiedName~RehearsalIsolation" | 0 | 37 corrective/original rehearsal cases passed, zero failed/skipped. |
| dotnet build .\src\AutoForge.slnx --configuration Release --no-restore | 0 | All nine projects/native Client; 0 warnings, 0 errors. MAUI XAML source-generation notice was informational. |
| dotnet test .\src\AutoForge.slnx --configuration Release --no-build | 0 | 179 unit + 263 integration = 442 passed, zero failed/skipped. |
| git --no-pager diff --check | 0 | No whitespace errors. Existing README/build-guide LF-to-CRLF notices 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.Client src\AutoForge.UI src\AutoForge.Application\Features\Vehicles\Telemetry | 0 | Existing assignments/history/dependencies, targets/ports/models, Client/UI and recording/replay implementations unchanged before adding this report. |
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. The portable projects remain net10.0;
Client remains net10.0-windows10.0.26100.0 / win-x64.
The 436 baseline cases are unchanged (179 unit/257 integration); only six
integration cases were added. Audit maximum remains 32 dispatched outcomes;
supported scalar/table, source/axis/unit/value validation, original backup,
approval/CAS/readback/unknown/reconcile/Restore and authoring/recording/replay
limits and semantics remain unchanged.
## Native versus controlled evidence
The actual rebuilt Windows Client was operated through a task-only WebView2
profile/local DevTools port 9381 using a temporary built-in Node/WebSocket
helper. There was no new host/dependency/production fault selector.
Native recheck:
- Explicit warm configuration/authoring proposal creation remained isolated:
saving 1250 rpm and 350 N*m at 2000 rpm left rehearsal Inactive/audit 0.
- Explicit target Open and two-read backup succeeded at revision 0.
Target was bdfed79dadeb44c5a74f46ec20f0320b; original backup
efc45e9fd5a5418d9b33730d1fa0de9f.
- A Metric->Imperial switch preserved the complete unconsumed approval and
audit 0. Confirmed Apply produced VerifiedApplied/revision 1 with scalar
1250, torque cells (240,300,350,350,300,180) and all original rpm axes.
This was one explicitly combined scalar/table proposal, not a claim to
replace the preserved Step-10 two-Apply native evidence.
- Separately prepared/confirmed original Restore produced VerifiedRestored/
revision 2: scalar 650, original torque (240,300,360,350,300,180), with
axes 650,1000,2000,3200,4200,5000 unchanged. Restore operation was
42fa9450fe8144e8997718c4f93e9034.
- Close/repeated Close completed normally and labeled the old backup inactive.
Fresh Open produced a4d9d812ee394efa85b32e04dddfc14e with no prior backup,
approval or audit. Its independently prepared fresh backup
b8ea82c74a034c008f07144abd468ee6 was revision zero.
- Navigating away with that fresh target and returning to calibration showed
a new Inactive page session, audit 0 and no old target identity.
- Original configuration export stayed exactly identical, fingerprint
sha256:v1:e8991ae139b54959ec53a4fe64b08dc9bfc03feb533496cf741f2c9f3a2342da.
Source warm-idle parameter remained 650 and torque at 2000 rpm remained 360.
A separate ordinary dynamics read at model step 7 / 0.7 seconds returned
631.80416 rpm / Good / SYNTHETIC_DYNAMIC from the unchanged model.
- Original Metric/Road preference values were restored and observed.
Existing replay and Home routes worked; replay remained Unloaded.
No unhandled native error overlay occurred.
The pending synchronous factory-return race is controlled test proof, not a
human-timed native claim. Native recheck verifies normal current-lifetime
behavior only. No new physical/model write, durable backup or AI capability is
claimed; original Step-10 programming/native evidence is preserved unchanged.
Cleanup PASSED: task-owned Client PID 43960 completed after route cleanup.
Only task-owned specific PIDs were targeted; transient WebView PIDs 40112/
44776 were checked against the task profile before cleanup. No owned WebView
process/listener remained; port 9381 was closed. Exact task profile/helper
were removed. Native source/proposal/rehearsal data were process-memory only,
and the app-local recordings directory remained empty. No unrelated archive,
default WebView data, user file or preference was reset.
## Own post-green source-path review
Reviewed NewOperationId/Start admission -> actual synchronous factory return ->
Open publication/failed-target cleanup -> Close ownership/cancellation ->
opening-owner and target drainage -> Closed/shared completion ->
Dispose/permanent-use rejection. Reviewed the existing UI disposal consumer
to confirm it invokes the same corrected service lifetime path; no UI change
was required.
Normal, repeated, pending, cancelled, disposed, prior failed-close, current
failed-open/cleanup and later sequential-reopen paths were walked against the
matrix. The old completion is retired only for a newly admitted opening owner,
not an exact cached command replay. Reset and owner publication occur under
the same gate before factory execution. Current Close binds its shared task
before cancellation, invalidates the real owner and awaits outside the gate.
Disposed/generation guards prohibit late publication. Opening owner cleanup
owns a late unregistered target, avoiding double disposal.
After the first six-case green run, the review made Closed state and current
close completion/failure publication atomic under the state gate, eliminating
an exposed Closed-before-completion admission window. Async continuations
remain outside cleanup-required waiting. The test wrapper also safely disposes
an already-created target if its factory safety deadline expires.
Affected focused/original checks and full build/regressions were rerun:
37/442 passed. Barriers are released and opening/closing/provider resources
drained in finally; real target disposal is asserted. No known unresolved
defect in the assigned corrective 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
[rehearsal lifecycle contracts](../docs/calibration-rehearsal.md).
They align admission-time close ownership, current completion/error,
cancellation/drain/disposal and normal versus controlled evidence. Original
Step-10 result counts/native observations/report were not rewritten.
Step-10 remains not accepted pending manual corrective review; Step-11 remains
blocked and unimplemented.
Worktree began clean on main at f2a8c37 and HEAD is unchanged. Existing
prompts/state/roadmap/assignments/shared gate/reports and protected files were
not edited; this is the only new prompts file. The index remains empty.
All nine projects/references/dependencies and real target/port/model/core/UI/
Client/recording/replay/source contracts are preserved.
Source/tests stay under src/src/tests; docs stay under docs.
No project/package/host/protocol/schema/template/unit-limit/programming
redesign, hardware/model mutation, system installation, agent, automatic
handoff, staging, commit, push, destructive Git or unrelated cleanup occurred.
STOP.
```

275
prompts/Step-11.md Normal file
View File

@ -0,0 +1,275 @@
# Step-11 - Deterministic simulation runbook validation and preview
## STEP IDENTIFIER
Step-11. Corrected Step-10/10A was accepted on 2026-10-31.
This is the sole active implementation assignment. Local inference/knowledge
is Step-12 and remains blocked until this deterministic boundary is accepted.
## STEP TITLE
Validate one source-bound synthetic calibration runbook and preview its exact
candidate/diff without saving, approving or executing anything.
## OBJECTIVE
One user outcome: explicitly supply structured JSON, then inspect a valid,
current-source proposal preview or a precise handled rejection.
One primary new contract: a strict allowlisted schema/source/head/template
boundary that future local inference must also use.
This is manual JSON input and read-only preview, not an LLM, retrieval system,
authoring Save, rehearsal approval/target operation or executable runbook.
Read [STATE.md](STATE.md), [ROADMAP.md](ROADMAP.md),
[authoring contracts](../docs/calibration-authoring.md),
[rehearsal contracts](../docs/calibration-rehearsal.md) and
[WORKER-QUALITY-GATE.md](WORKER-QUALITY-GATE.md).
Establish the frozen matrix before coding, self-review after first green,
write `prompts/Step-11-Report.md`, and STOP.
## ARCHITECTURAL CONTEXT
Keep all nine projects, one Client, generic Components and existing Application
feature boundaries. Application owns parsing/validation/preview against the
read-only authoring snapshot; UI owns a route/input/error/preview.
Core may hold small immutable data contracts if justified, not a new engine.
Reuse [SyntheticEngineCalibration](../src/AutoForge.Core/Calibration/SyntheticEngineCalibration.cs)
for complete scalar/table validation and
[CalibrationAuthoringService](../src/AutoForge.Application/Features/Vehicles/Calibration/CalibrationAuthoringService.cs)
for actual workspace/head/applicability. Reuse the existing pure exact diff
helper rather than implementing another version/diff system.
No new project/package/host, generic workflow/permission framework or schema
change to profiles/configurations/archives. Source/tests stay under `src`,
tests under `src/tests`.
## CURRENT IMPLEMENTATION STATE
Accepted authoring provides exact applicability, immutable Baseline/Proposed
heads, complete supported scalar/table values, synthetic constraints and exact
diffs. Accepted rehearsal separately verifies/approves/commits/reads/restores an
isolated Simulation image; it is not reachable through a runbook preview.
Worker baseline: 179 unit + 263 integration passes (442 total, zero failed/
skipped), clean nine-project Release build and native rehearsal recheck.
The orchestrator did not run those commands. No runbook validator, model runtime
or inference/knowledge feature exists yet.
Inspect Git/prior art and preserve dirty work, accepted behavior and all
historical assignments/reports. This step does not implement app-level Git
backup/persistence or change the accepted volatile domain snapshots.
## REQUIRED IMPLEMENTATION
### Frozen contract matrix
| ID | Input/precondition | Required result |
|---|---|---|
| C-01 | Explicit actual authoring source/head, supported schema and unchanged full values | Valid read-only NoChanges preview with exact immutable source/head/values and empty diff; no implicit workspace/template/preview on route entry |
| C-02 | Warm baseline 650 rpm; candidate 1250 plus 2000-rpm torque 360->350 | Exactly two canonical diff entries: scalar +600 rpm and axis-keyed table -10 N*m, with before/after/units; authoring/config/target untouched |
| C-03 | Malformed/missing/duplicate/unknown/version/type/enum JSON fields | Typed visible schema rejection before preview publication; previous successful preview and all source state remain intact |
| C-04 | Wrong operation, multiple/empty steps, physical/replay target, arbitrary SQL/script/frame/offset/approval fields | Allowlist rejects; no command/target access, automatic save/approval or inference of authority from rationale |
| C-05 | Each wrong workspace/head/applicability component or case policy | Exact current-source/head rejection, no catalogue/role/latest-head fallback. Profile/module case variants retain existing policy; fingerprint/model/definition/key/unit are exact. |
| C-06 | Invalid scalar/cell/axis/unit/key/shape, non-finite number, valid exact bounds/tiny change | Reuse full template rules; invalid rejects atomically, valid bounds and canonical differences remain exact without clipping/rounding/sorting |
| C-07 | Source/head changes before validation or after a valid preview | Stale request rejects; existing preview becomes visibly stale against current source/head and never silently rebases or grants execution. Revalidate requires explicit correct input. |
| C-08 | Maximum payload/rationale/identifier/depth and one-over inputs | UTF-8 input <=128 KiB, rationale <=2000 UTF-16 code units, step ID 1..128 trimmed code units and parser depth <=32; over/invalid input handled without replacing prior preview |
| C-09 | Caller changes input collections, rerender/unit changes or invalid attempt after prior success | Immutable copied last-successful preview; bounded one preview, distinct input-error/old-preview labels; original canonical values/diff/source remain unchanged |
| C-10 | Actual route with live diagnostics/replay/rehearsal present; full verification | Real validator/source/UI path and 442 regressions preserved; zero authoring Save/approval/target read-write/model/archive/network calls from preview; no model/physical execution |
### A. Exact small schema v1 and one allowlisted operation
Define/document a strict schema-v1 input with these exact camelCase object fields:
- Root: `schemaVersion`, `runbookIdentifier`, `targetKind`, `rationale`, `steps`.
- Source is carried inside the step: `stepIdentifier`, `operation`, `source`,
`values` are that step's exact fields.
- Source: `workspaceIdentifier`, `expectedHeadIdentifier`, `profileIdentifier`,
`profileRevision`, `configurationIdentifier`, `moduleIdentifier`,
`modelIdentifier`, `modelVersion`, `definitionIdentifier`, `definitionRevision`.
- Values: `scalars`, `tables`.
- Scalar value: `logicalIdentifier`, `unit`, `value`.
- Table value: `logicalIdentifier`, `unit`, `axisUnit`, `axis`, `cells`.
All are required. `schemaVersion` is integer 1; `runbookIdentifier` is a lowercase
GUID in N format; `targetKind` is the exact string `simulation`.
`steps` is an array with exactly one step, whose exact operation is
`proposeCalibration`. Step identifier is nonblank, trimmed and at most 128
UTF-16 code units; rationale is a string of at most 2000 such code units and
is informational only (empty permitted).
Profile/model/definition revision fields are positive JSON integers; source/
workspace/head identifiers are explicit nonblank trimmed strings and must match
the actual source, not just syntactically resemble a fingerprint.
Limit the original input to 128 KiB (131,072 bytes of UTF-8, not string.Length)
and JSON parsing depth 32. Reject duplicate/unknown/missing properties at every
schema object, wrong JSON kinds, comments/trailing data, unsupported versions,
undefined target/operation tokens and invalid numbers through a typed handled
error. Do not return a healthy default/no-op for malformed input.
The values are exactly the existing supported warm-idle scalar and fixed-axis
torque table, not arbitrary JSON, a partial patch or firmware payload.
Keep finite inclusive bounds, logical IDs, fixed axis/count/source units and
complete shape validation from the existing template.
No shell, SQL, raw frame, offset, route/function name, provider write command,
approval flag or execution switch is permitted. Rationale is rendered as safe
text and is never interpreted as policy, instructions or a command.
Do not install/run a model or retrieve context. Future Step-12 generated text
will have to satisfy this same parser/validator, not a privileged alternative.
### B. Actual source/head validation and immutable exact preview
Require an explicitly created current authoring workspace. Parse the supplied
source token and compare every workspace/head/applicability component with that
snapshot, following existing field-specific identity rules. Validate the complete
candidate through its real SyntheticEngineCalibration definition.
Both Baseline and Proposed current heads may be used as a preview source.
Never resolve stale IDs to latest, infer a module from a role or create a missing
profile/configuration/workspace during validation.
Use consistent source/head at publication, reusing the existing narrow current-
head guard if appropriate. All parsing/reference/template checks precede any
last-successful-preview replacement. There is no authoring Save, approval or
target command hidden inside this operation.
Preview contains copied runbook/step/source/head identity, rationale, canonical
candidate, exact current-head-to-candidate scalar/table diff and a truthful
NoChanges/ChangesProposed indication. ChangesProposed is not a saved Proposed
revision or a tested/approved/applied target state. No authorization token is
generated by validation.
Use exact canonical doubles and deterministic logical-ID/axis ordering. Preserve
zero/tiny differences and actual before/after/delta/units; no display precision,
conversion or tolerance can alter the input or diff.
Return defensive/read-only snapshots; retain only one last successful preview,
not unbounded history or a custom repository/branch/merge layer.
The source can change after validation. Preview's captured identity/content
remains immutable; separately compare it to the actual current workspace/head
whenever status is shown and label mismatched/replaced previews **Stale**.
Never silently rewrite the expected head, rerun validation on render or present
an old diff as a current actionable plan. Explicit updated input/revalidation is
required. A later executor would still need its own fresh checks and approval;
none is implemented here.
### C. Real local UI with no execution path
Add a clearly named `/runbooks` route and existing shared navigation. Provide
manual JSON input, explicit Validate/Preview, last-successful preview/source/
canonical candidate/diff/status and visible error details.
An explicit **Create input template from selected current source** action may
copy that actual workspace/head/values into a draft to make entry practical.
It must not automatically validate, save a proposal, open a target or create
authoring data. Empty/unavailable source is a visible error; no seeded fallback.
Identify draft input separately from the previous successful preview after an
invalid attempt. Subscribe to authoring changes only to render source staleness,
not to mutate/rebase the draft. Display global unit preferences only as optional
read-only projection alongside canonical source values, using existing helpers.
Unit changes and rerenders cannot validate/save a plan or change preview contents.
Scope is preview only: no Execute/Apply/Approve/Save-to-authoring control or code
path. Safe text/accessibility and existing routes remain intact.
## FILES OR PROJECTS EXPECTED TO CHANGE
Focused Application runbook contracts/parser/validation/preview/DI, UI route/
navigation/template/error/preview, tests and directly related docs/README.
Reuse existing calibration/template/diff contracts and narrow source/head guard.
Core data additions only if necessary; no Simulation/Diagnostics programming/
model/transport or existing authoring-save behavior changes.
No new dependency/project/host or model/retrieval/tool server.
Only `prompts/Step-11-Report.md` under `prompts`.
## INTERFACE AND DEPENDENCY REQUIREMENTS
Preserve all nine projects/references, one Client, independent Components, exact
authoring/source/head/units/template limits and isolated rehearsal approval/CAS/
backup/readback/recovery. Profiles/configurations/archives/physics remain unchanged.
No inference/cloud/network/upload, physical/replay target permission, source
mutation, implicit save, command execution, broad catch or success-shaped rejection.
The validator is not a general version-control or backup framework.
Do not fix the separately disclosed recording refresh/navigation issue here.
No package/system/workload install/update/repair/rollback, staging/commit/push or
destructive Git; preserve dirty work and protected/history/orchestration files.
## TESTING REQUIREMENTS
Map C-01..C-10 to named meaningful tests before handoff:
- Real authoring/profile/configuration source, exact template/current-head and
whole candidate; NoChanges and independent 650->1250/+600, 360->350/-10,
multiple cells/reverse/tiny-difference canonical diff vectors.
- Independent wrong JSON object/property/type/version/target/operation/source/
head/value/unit/axis/shape vectors; assert typed rejection and exact preserved
last preview/source/head/history. Do not cite a test count as boundary proof.
- Exact payload 131,072 bytes and one more using otherwise valid document
whitespace; rationale length 2000/2001, step-ID boundaries and controlled
excessive-depth/malformed JSON. UTF-8/UTF-16 limits are distinct.
- Source-head change before validation rejects; change/replacement after success
marks prior result stale without modifying it or the input. Defensive-copy
and one-preview-retention assertions; no validation triggered by renders.
- Actual rendered template/validate/error/stale/diff controls, safe rationale
text, original/canonical versus display units, and zero unassigned side effects.
Use real existing live/recording/replay/rehearsal instances plus counted ports
around feature invocation; verification reads outside that invocation are
not validator calls. Do not mock away the validator/authoring source.
Run focused cases, then sequentially:
- `dotnet build .\src\AutoForge.slnx --configuration Release --no-restore`
- `dotnet test .\src\AutoForge.slnx --configuration Release --no-build`
Preserve 442 baseline cases (179 unit, 263 integration) plus meaningful new
coverage. Map required UI-only assertion changes without deleting safety/source
checks. Build all nine projects/native Client. Install/restore nothing absent
a genuine chosen-command missing dependency.
Native smoke: explicit source creation through existing UI, input template,
valid exact preview, malformed/wrong-target/head/invalid-value rejection with
previous preview retained, source change/stale status and explicit revalidation.
Verify original source/history/target/replay are not changed by preview and that
global units/old routes still work. No model, knowledge or physical target.
Native normal UI is not controlled concurrency/limit proof. Clean only exact
task-owned artifacts/profiles and preserve unrelated user data/preferences.
## DOCUMENTATION REQUIREMENTS
Update README/index/architecture/build guide and runbook-schema/preview usage:
exact fields/limits/allowlist, source/head/template rules, immutable diff/stale
semantics, manual input/no model/no save/no execution/no authorization scope
and actual verification. Step-10/10A is accepted; Step-11 stays pending manual
review. Local inference/knowledge and later executor integration are future,
not implemented capabilities or implicit mutation authority.
## ACCEPTANCE CRITERIA
| ID | Criterion | Evidence |
|---|---|---|
| AC-01 | C-03..C-06/C-08 strict bounded schema/allowlist/types/source/head/full template validation | Independent input vectors, exact limits and typed atomic negative assertions |
| AC-02 | C-01/C-02/C-07/C-09 immutable precise preview/diff/no-op, current-versus-stale status and bounded retained result | Exact source/value/delta/tiny-change/defensive-copy/staleness tests |
| AC-03 | C-10 actual local UI/service path with no execution/save/approval/model/network effects | Rendered/native actions, real-source/target/coexistence counters and unchanged state |
| AC-04 | All 442 regressions/new coverage, complete nine-project Release build and required native smoke pass | Exact commands/exits/warnings/per-project counts and native/control distinction |
| AC-05 | Matrix/self-review/docs/history/protection/manual gate describe actual implementation and limits | Own post-green producer/consumer review, named evidence and `prompts/Step-11-Report.md` |
## OUT-OF-SCOPE WORK
LLM/model/runtime/server install or integration, knowledge retrieval/vector/RAG,
runbook execution/tool invocation, authoring Save/target programming/approval,
app-level Git/plan persistence, multiple operations/step orchestration, new units/
templates/schema changes to other features, physical/AI hardware authority,
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-11-Report.md` wholly inside exactly one plain triple-backtick
fence, no language tag/outside text/nested fences. Include identifier/title/status,
functions/files/interfaces, C-01..C-10/AC-01..AC-05 mapping with named executed
evidence, exact schema/limits/negative/source/head/preview/diff/stale/no-side-
effect 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 review.
COMPLETE requires all assigned checks; otherwise report INCOMPLETE/BLOCKED with
the precise unmet criterion. Save and STOP; do not begin Step-12.

View File

@ -87,7 +87,6 @@ public sealed class CalibrationRehearsalSession(
_target = target;
_definition = workspace.Definition;
_workspaceIdentifier = workspace.Identifier;
_closeTask = null;
_snapshot = new(RehearsalState.Ready, true, target.Identity, null, null, null, null, [], null);
}
return true;
@ -408,6 +407,8 @@ public sealed class CalibrationRehearsalSession(
_issuedId = null;
owner = new(identifier, key, _generation, cancellationToken);
owner.Opening = opening;
// A pending reopen owns a new lifetime before its target is published.
if (opening && _target is null) _closeTask = null;
_owner = owner;
_snapshot = _snapshot with { IsBusy = true };
}
@ -479,8 +480,8 @@ public sealed class CalibrationRehearsalSession(
_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()
@ -495,13 +496,13 @@ public sealed class CalibrationRehearsalSession(
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 &&
private bool CanPublish(Owner owner) => !_disposed && 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 ||
if (_disposed || owner.Generation != _generation || _snapshot.State == RehearsalState.Closing ||
(_snapshot.State == RehearsalState.Closed && !owner.Opening))
throw new OperationCanceledException("Old rehearsal generation cannot publish after close.");
}

View File

@ -0,0 +1,351 @@
using AutoForge.Application.Features.Vehicles.Calibration;
using AutoForge.Application.Features.Vehicles.Profiles;
using AutoForge.Core.Calibration;
using AutoForge.Core.ExecutionTargets;
using AutoForge.Core.Simulation;
using AutoForge.Diagnostics;
using AutoForge.Simulation;
using Microsoft.Extensions.DependencyInjection;
namespace AutoForge.IntegrationTests;
public sealed class CalibrationRehearsalReopenTests
{
private static readonly TimeSpan Deadline = TimeSpan.FromSeconds(10);
private const string ProviderId = "autoforge.simulation.calibration-rehearsal";
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task PendingReopenCloseOrDispose_DrainsCurrentOwnerWithoutPriorCompletionReplay(bool dispose)
{
using var fixture = new CalibrationRehearsalTests.Fixture();
using var factory = new ReopenBarrierFactory();
var session = CreateSession(fixture, factory);
Task? opening = null;
Task? ending = null;
try
{
await OpenAsync(session, fixture.Workspace.Identifier);
var backup = await session.PrepareBackupAsync(session.NewOperationId());
var proposal = fixture.Save(1250);
var preparation = await session.PrepareApplyAsync(session.NewOperationId(), fixture.Workspace.Identifier, proposal.Identifier);
var approval = session.Approve(preparation.Identifier, true);
var priorClose = session.CloseAsync();
await priorClose.WaitAsync(Deadline);
Assert.Equal(1, factory.Targets[0].DisposeCount);
var operationId = session.NewOperationId();
opening = Task.Run(() => session.OpenAsync(operationId, ProviderId, ExecutionTargetKind.Simulation, fixture.Workspace.Identifier));
await factory.SecondFactoryEntered.Task.WaitAsync(Deadline);
Assert.True(session.Snapshot.IsBusy);
ending = dispose ? session.DisposeAsync().AsTask() : session.CloseAsync();
var currentClose = session.CloseAsync();
var replayedPrior = ReferenceEquals(priorClose, currentClose);
var finishedDuringFactory = ending.IsCompleted;
var currentCloseShared = ReferenceEquals(currentClose, session.CloseAsync());
factory.ReleaseFactory();
var finishedDuringCleanup = false;
if (!finishedDuringFactory)
{
await factory.SecondDisposeEntered.Task.WaitAsync(Deadline);
finishedDuringCleanup = ending.IsCompleted;
}
factory.ReleaseDisposal();
var openError = await ObserveAsync(opening);
var closeError = await ObserveAsync(ending);
var second = factory.Targets[1];
var observedState = session.Snapshot.State;
Assert.True(!replayedPrior && !finishedDuringFactory,
$"PriorTaskReused={replayedPrior}; CloseOrDisposeFinishedWhileFactoryHeld={finishedDuringFactory}; " +
$"OpenError={openError?.GetType().Name ?? "none"}; StateAfterFactoryRelease={observedState}; " +
$"CreatedTargetDisposeCount={second.DisposeCount}; ActualTargetDisposed={second.IsDisposed}.");
Assert.True(currentCloseShared);
Assert.False(finishedDuringCleanup);
Assert.IsAssignableFrom<OperationCanceledException>(openError);
Assert.Null(closeError);
Assert.Equal(RehearsalState.Closed, observedState);
Assert.False(session.Snapshot.IsBusy);
Assert.Same(backup, session.Snapshot.Backup);
Assert.Same(approval, session.Snapshot.Approval);
Assert.Equal(1, second.DisposeCount);
Assert.True(second.IsDisposed);
await Assert.ThrowsAsync<ObjectDisposedException>(() => second.ReadAsync());
if (dispose)
{
var error = Assert.Throws<CalibrationRehearsalException>(() => session.NewOperationId());
Assert.Equal(RehearsalFailure.Closed, error.Failure);
error = await Assert.ThrowsAsync<CalibrationRehearsalException>(() =>
session.OpenAsync(operationId, ProviderId, ExecutionTargetKind.Simulation, fixture.Workspace.Identifier));
Assert.Equal(RehearsalFailure.Closed, error.Failure);
}
else
{
await OpenAsync(session, fixture.Workspace.Identifier);
Assert.NotEqual(backup.Image.Identity.InstanceIdentifier, session.Snapshot.Identity!.InstanceIdentifier);
Assert.Null(session.Snapshot.Backup);
Assert.Null(session.Snapshot.Approval);
var fresh = await session.PrepareBackupAsync(session.NewOperationId());
Assert.Equal(0, fresh.Image.Revision);
Assert.Equal(650, fresh.Image.Values.Scalars[0].Value);
}
}
finally
{
factory.ReleaseAll();
if (opening is not null) await ObserveAsync(opening);
if (ending is not null) await ObserveAsync(ending);
await ObserveAsync(session.CloseAsync());
await ObserveAsync(session.DisposeAsync().AsTask());
Assert.All(factory.Targets, target => Assert.True(target.IsDisposed));
}
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task PendingReopenAfterFailedClose_CurrentCleanupHasItsOwnSharedOutcome(bool failCurrentCleanup)
{
using var fixture = new CalibrationRehearsalTests.Fixture();
using var factory = new ReopenBarrierFactory { FailFirstDispose = true, FailSecondDispose = failCurrentCleanup };
var session = CreateSession(fixture, factory);
Task? opening = null;
Task? closing = null;
try
{
await OpenAsync(session, fixture.Workspace.Identifier);
var backup = await session.PrepareBackupAsync(session.NewOperationId());
var priorClose = session.CloseAsync();
var previousFailure = await Assert.ThrowsAsync<IOException>(() => priorClose);
Assert.Contains("previous target cleanup failure", previousFailure.Message);
Assert.Equal(RehearsalState.Closed, session.Snapshot.State);
Assert.True(factory.Targets[0].IsDisposed);
var operationId = session.NewOperationId();
opening = Task.Run(() => session.OpenAsync(operationId, ProviderId, ExecutionTargetKind.Simulation, fixture.Workspace.Identifier));
await factory.SecondFactoryEntered.Task.WaitAsync(Deadline);
closing = session.CloseAsync();
var priorReplayed = ReferenceEquals(priorClose, closing);
var finishedDuringFactory = closing.IsCompleted;
Assert.Same(closing, session.CloseAsync());
factory.ReleaseFactory();
var finishedDuringCleanup = false;
if (!finishedDuringFactory)
{
await factory.SecondDisposeEntered.Task.WaitAsync(Deadline);
finishedDuringCleanup = closing.IsCompleted;
}
factory.ReleaseDisposal();
var openError = await ObserveAsync(opening);
var closeError = await ObserveAsync(closing);
Assert.False(priorReplayed,
$"PreviousFailureReplayed={priorReplayed}; EarlyCompletion={finishedDuringFactory}; " +
$"CurrentError={closeError?.Message}; StateAfterRelease={session.Snapshot.State}.");
Assert.False(finishedDuringFactory);
Assert.False(finishedDuringCleanup);
Assert.Same(backup, session.Snapshot.Backup);
Assert.Equal(RehearsalState.Closed, session.Snapshot.State);
Assert.Equal(1, factory.Targets[1].DisposeCount);
Assert.True(factory.Targets[1].IsDisposed);
if (failCurrentCleanup)
{
Assert.IsType<IOException>(openError);
Assert.IsType<IOException>(closeError);
Assert.Contains("current target cleanup failure", session.Snapshot.Error);
Assert.Contains("current target cleanup failure", closeError!.Message);
Assert.Same(closing, session.CloseAsync());
}
else
{
Assert.IsAssignableFrom<OperationCanceledException>(openError);
Assert.Null(closeError);
}
await OpenAsync(session, fixture.Workspace.Identifier);
Assert.Null(session.Snapshot.Backup);
Assert.Equal(RehearsalState.Ready, session.Snapshot.State);
}
finally
{
factory.ReleaseAll();
if (opening is not null) await ObserveAsync(opening);
if (closing is not null) await ObserveAsync(closing);
await ObserveAsync(session.CloseAsync());
await ObserveAsync(session.DisposeAsync().AsTask());
Assert.All(factory.Targets, target => Assert.True(target.IsDisposed));
}
}
[Fact]
public async Task PendingFactoryFailure_CurrentCloseDrainsItsOwnFailureAndRetainsInactiveEvidence()
{
using var fixture = new CalibrationRehearsalTests.Fixture();
using var factory = new ReopenBarrierFactory { FailSecondOpen = true };
var session = CreateSession(fixture, factory);
Task? opening = null;
Task? closing = null;
try
{
await OpenAsync(session, fixture.Workspace.Identifier);
var backup = await session.PrepareBackupAsync(session.NewOperationId());
var prior = session.CloseAsync();
await prior;
var id = session.NewOperationId();
opening = Task.Run(() => session.OpenAsync(id, ProviderId, ExecutionTargetKind.Simulation, fixture.Workspace.Identifier));
await factory.SecondFactoryEntered.Task.WaitAsync(Deadline);
closing = session.CloseAsync();
Assert.NotSame(prior, closing);
Assert.Same(closing, session.CloseAsync());
Assert.False(closing.IsCompleted);
factory.ReleaseFactory();
var openError = await ObserveAsync(opening);
var closeError = await ObserveAsync(closing);
Assert.IsType<IOException>(openError);
Assert.IsType<IOException>(closeError);
Assert.Contains("current factory failure", session.Snapshot.Error);
Assert.Same(backup, session.Snapshot.Backup);
Assert.Equal(RehearsalState.Closed, session.Snapshot.State);
Assert.Single(factory.Targets);
Assert.Equal(1, factory.Targets[0].DisposeCount);
await OpenAsync(session, fixture.Workspace.Identifier);
Assert.Equal(RehearsalState.Ready, session.Snapshot.State);
Assert.Null(session.Snapshot.Backup);
}
finally
{
factory.ReleaseAll();
if (opening is not null) await ObserveAsync(opening);
if (closing is not null) await ObserveAsync(closing);
await ObserveAsync(session.CloseAsync());
await ObserveAsync(session.DisposeAsync().AsTask());
Assert.All(factory.Targets, target => Assert.True(target.IsDisposed));
}
}
[Fact]
public async Task RejectedReopen_PreservesInactiveEvidenceAndDoesNotReuseCompletedClose()
{
using var fixture = new CalibrationRehearsalTests.Fixture();
using var factory = new ReopenBarrierFactory { BlockSecond = false };
var session = CreateSession(fixture, factory);
try
{
await OpenAsync(session, fixture.Workspace.Identifier);
var backup = await session.PrepareBackupAsync(session.NewOperationId());
var prior = session.CloseAsync();
await prior;
var error = await Assert.ThrowsAsync<CalibrationRehearsalException>(() =>
session.OpenAsync(session.NewOperationId(), "unregistered", ExecutionTargetKind.Simulation, fixture.Workspace.Identifier));
Assert.Equal(RehearsalFailure.InvalidTarget, error.Failure);
Assert.Same(backup, session.Snapshot.Backup);
Assert.Equal(RehearsalState.Closed, session.Snapshot.State);
Assert.Single(factory.Targets);
var current = session.CloseAsync();
Assert.NotSame(prior, current);
Assert.Same(current, session.CloseAsync());
await current;
Assert.Contains("registered", session.Snapshot.Error);
await OpenAsync(session, fixture.Workspace.Identifier);
Assert.NotEqual(backup.Image.Identity.InstanceIdentifier, session.Snapshot.Identity!.InstanceIdentifier);
Assert.Null(session.Snapshot.Backup);
}
finally
{
factory.ReleaseAll();
await ObserveAsync(session.CloseAsync());
await ObserveAsync(session.DisposeAsync().AsTask());
Assert.All(factory.Targets, target => Assert.True(target.IsDisposed));
}
}
private static CalibrationRehearsalSession CreateSession(CalibrationRehearsalTests.Fixture fixture, ReopenBarrierFactory factory) =>
new(fixture.Authoring, fixture.Configurations, fixture.Provider.GetRequiredService<IVehicleProfileService>(), [factory], TimeProvider.System);
private static Task OpenAsync(CalibrationRehearsalSession session, string workspace) =>
session.OpenAsync(session.NewOperationId(), ProviderId, ExecutionTargetKind.Simulation, workspace);
private static async Task<Exception?> ObserveAsync(Task task)
{
try { await task.WaitAsync(Deadline); return null; }
catch (Exception exception) when (exception is OperationCanceledException or IOException or CalibrationRehearsalException)
{
return exception;
}
}
private sealed class ReopenBarrierFactory : ISimulatedCalibrationTargetFactory, IDisposable
{
private readonly SimulatedCalibrationTargetFactory _inner = new();
private readonly object _gate = new();
private readonly List<TrackedTarget> _targets = [];
private readonly ManualResetEventSlim _releaseFactory = new(false);
private readonly TaskCompletionSource _releaseDisposal = new(TaskCreationOptions.RunContinuationsAsynchronously);
private int _opens;
public ExecutionTargetDescriptor Descriptor => _inner.Descriptor;
public bool BlockSecond { get; init; } = true;
public bool FailFirstDispose { get; init; }
public bool FailSecondDispose { get; init; }
public bool FailSecondOpen { get; init; }
public TaskCompletionSource SecondFactoryEntered { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
public TaskCompletionSource SecondDisposeEntered { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
public IReadOnlyList<TrackedTarget> Targets { get { lock (_gate) return _targets.ToArray(); } }
public ISimulatedCalibrationTarget Open(DynamicsConfiguration configuration, SyntheticEngineCalibration definition)
{
var ordinal = Interlocked.Increment(ref _opens);
if (ordinal == 2 && FailSecondOpen)
{
HoldFactory();
throw new IOException("current factory failure");
}
var target = new TrackedTarget(_inner.Open(configuration, definition), ordinal, this);
lock (_gate) _targets.Add(target);
try
{
if (ordinal == 2 && BlockSecond) HoldFactory();
}
catch (TimeoutException)
{
ReleaseDisposal();
target.DisposeAsync().AsTask().GetAwaiter().GetResult();
throw;
}
return target;
}
private void HoldFactory()
{
SecondFactoryEntered.TrySetResult();
if (!_releaseFactory.Wait(TimeSpan.FromSeconds(20)))
throw new TimeoutException("The controlled factory return was not released.");
}
public void ReleaseFactory() => _releaseFactory.Set();
public void ReleaseDisposal() => _releaseDisposal.TrySetResult();
public void ReleaseAll() { ReleaseFactory(); ReleaseDisposal(); }
public void Dispose() => _releaseFactory.Dispose();
public sealed class TrackedTarget(ISimulatedCalibrationTarget inner, int ordinal, ReopenBarrierFactory factory) : ISimulatedCalibrationTarget
{
private int _disposals;
public CalibrationTargetIdentity Identity => inner.Identity;
public int DisposeCount => Volatile.Read(ref _disposals);
public bool IsDisposed { get; private set; }
public Task<CalibrationTargetImage> ReadAsync(CancellationToken cancellationToken = default) => inner.ReadAsync(cancellationToken);
public Task<CalibrationWriteAcknowledgement> CommitAsync(CalibrationTargetCommit request, CancellationToken cancellationToken = default) =>
inner.CommitAsync(request, cancellationToken);
public async ValueTask DisposeAsync()
{
Interlocked.Increment(ref _disposals);
if (ordinal == 2 && factory.BlockSecond)
{
factory.SecondDisposeEntered.TrySetResult();
await factory._releaseDisposal.Task;
}
await inner.DisposeAsync();
IsDisposed = true;
if (ordinal == 1 && factory.FailFirstDispose) throw new IOException("previous target cleanup failure");
if (ordinal == 2 && factory.FailSecondDispose) throw new IOException("current target cleanup failure");
}
}
}
}