Compare commits

...
64 Commits
Author SHA1 Message Date
UnixNight 404b4b4d4a docs(01): verify bundled checker repair and restart pending UAT 2026-11-14 17:00:38 -05:00
UnixNight 2fe8b40ea5 fix(01): keep bundled Python commands from writing bytecode caches 2026-11-14 16:53:30 -05:00
UnixNight 23ee1c2e47 test(01): reproduce bundled checker creating immutable bytecode caches 2026-11-14 16:50:04 -05:00
UnixNight 07793af9fc docs(01): keep local-only API declaration within preflight limit 2026-11-14 16:33:42 -05:00
UnixNight 898aef7ffa docs(01): normalize final verification report whitespace 2026-11-14 00:41:11 -05:00
UnixNight f7e7033514 docs(01): persist final verification and pending combined-session UAT 2026-11-14 00:40:51 -05:00
UnixNight febb4a9d98 docs(01): express existing verification goal as required user story 2026-11-14 00:32:22 -05:00
UnixNight 08150c0199 docs(pause): preserve final verification continuation at quota reserve 2026-11-13 17:27:15 -05:00
UnixNight 71366e7d45 docs(01): close review and security gates with acceptance pending 2026-11-13 17:22:39 -05:00
UnixNight 02d182f35d fix(01-07): validate actual copy-state artifacts at scenario boundary 2026-11-13 17:18:39 -05:00
UnixNight 48fca0df52 test(01-07): reject copy-state identities without backing artifacts 2026-11-13 17:16:54 -05:00
UnixNight a821754b67 test(01): WR-01 verify readiness after transfer without Git 2026-11-13 17:08:10 -05:00
UnixNight 2608517c37 fix(01): WR-02 recover interrupted Windows runs without invented clocks 2026-11-13 17:07:44 -05:00
UnixNight 548c97aa58 fix(01): WR-01 preserve validated capability history in checkpoint viewer 2026-11-13 17:07:44 -05:00
UnixNight 6e5ee0bd25 fix(01): CR-03 bind lifetime continuity to named copy snapshots 2026-11-13 17:02:22 -05:00
UnixNight bda35e5bf5 fix(01): CR-02 bind original evidence to pristine inventory members 2026-11-13 17:01:42 -05:00
UnixNight 5569bc2b8b fix(01): CR-01 bind review digest to selected receipt bytes 2026-11-13 17:00:47 -05:00
UnixNight 5915128570 docs(01): record final code review findings and disposition 2026-11-13 16:58:55 -05:00
UnixNight 215d01e43e docs(01-07): track completed preparation and open acceptance gate 2026-11-13 16:49:31 -05:00
UnixNight 52a3e2d5ff docs(01-07): record verified preparation and pending human acceptance 2026-11-13 16:48:09 -05:00
UnixNight 472500bf4e test(01-07): integrate counted fidelity regressions and exact local results
Run existing fidelity Python, Node and observer checks with positive-count guards and explicit TAP output. Record the completed 782.05-second local suite and preserve human acceptance at 0/120.
2026-11-13 16:44:59 -05:00
UnixNight b732256751 docs(pause): save quota-guard checkpoint at 01-07 task3 2026-11-13 12:29:02 -05:00
UnixNight fc5e936fd7 docs(01-07): retain pending combined-session acceptance and diagnostic identity 2026-11-13 12:18:43 -05:00
UnixNight 026def9c5a feat(01-07): audit prepared fidelity materials and strict human acceptance 2026-11-13 12:17:46 -05:00
UnixNight d78b13566d test(01-07): specify strict final fidelity acceptance gates 2026-11-13 12:09:46 -05:00
UnixNight d18f551a26 docs(01-06): record reviewed Linux capture tooling and access limits 2026-11-13 12:06:50 -05:00
UnixNight ef021e79f0 docs(01-06): retain SDK planning-state companion 2026-11-13 12:05:41 -05:00
UnixNight 589481218d docs(01-06): advance completed capture plan tracking 2026-11-13 12:05:23 -05:00
UnixNight c60248dbfe docs(01-06): record Linux capture limits and complete open matrix 2026-11-13 12:04:22 -05:00
UnixNight 0172916ffd feat(01-06): preserve full Linux obligation matrix and capture history 2026-11-13 12:02:33 -05:00
UnixNight e17cfbebe3 test(01-06): require full Linux matrix continuity and resume history 2026-11-13 11:57:23 -05:00
UnixNight 16f5e126be feat(01-06): collect bounded Linux capture and honest failed preflight 2026-11-13 11:56:08 -05:00
UnixNight 9c59f60b50 test(01-06): require bounded Linux capture round trip 2026-11-13 11:52:12 -05:00
UnixNight 31ae6a6ab2 docs(01-05): record primary review and retain consumed handoff 2026-11-13 11:48:20 -05:00
UnixNight 1af5217e47 docs(01-05): advance verified checkpoint plan tracking 2026-11-13 11:46:26 -05:00
UnixNight 2d48ee5316 docs(01-05): complete offline Windows checkpoint plan 2026-11-13 11:45:36 -05:00
UnixNight aa4b862a12 fix(01-05): retain executable permissions in offline copies
Preserve source read/write/execute bits without privileged mode bits. Verify copied Linux apphost byte identity and permissions.
2026-11-13 11:43:51 -05:00
UnixNight 857466568d feat(01-05): complete offline Windows collection agenda and selftests
Prepare all session materials, explicit terminal outcomes and raw-media provenance while retaining open acceptance. Verify the package-free collector on synthetic fixtures without redistributing external tools.
2026-11-13 11:36:47 -05:00
UnixNight c9b9f2eba9 feat(workflow): checkpoint GSD before five-hour quota exhaustion 2026-11-13 11:24:53 -05:00
UnixNight 73954e675d docs(handoff): preserve quota-interrupted Windows bundle task 2026-11-13 11:07:44 -05:00
UnixNight 818191c90c test(01-05): require complete Windows session materials and open results 2026-11-12 23:48:52 -05:00
UnixNight 61123394e0 feat(01-05): assemble identified offline Windows checkpoint 2026-11-12 23:48:03 -05:00
UnixNight 446930d2a3 test(01-05): specify immutable offline checkpoint round trip 2026-11-12 23:40:08 -05:00
UnixNight de68796df1 docs(01-04): record reviewed wave two runtime regressions 2026-11-12 23:36:19 -05:00
UnixNight 4bf072d03c docs(01-04): advance sequential observation plan metadata 2026-11-12 23:23:27 -05:00
UnixNight 85e533b629 docs(01-04): complete passive port observation plan 2026-11-12 23:22:36 -05:00
UnixNight ea4dc9b5df feat(01-04): preserve observer identity through control and scene changes 2026-11-12 23:20:14 -05:00
UnixNight 6bccd47b9b test(01-04): require retained session and dialogue observation 2026-11-12 23:10:30 -05:00
UnixNight 72523eebb7 feat(01-04): observe accepted input with bounded passive output 2026-11-12 23:09:01 -05:00
UnixNight 773c228a30 test(01-04): specify passive port input observation 2026-11-12 23:05:18 -05:00
UnixNight e815534895 docs(01-03): verify resumed ledger and clear pause handoff 2026-11-12 23:01:12 -05:00
UnixNight f55ba8eae7 docs(01-03): advance sequential capability ledger progress 2026-11-12 23:00:00 -05:00
UnixNight 564b19ad03 docs(01-03): complete capability ledger plan 2026-11-12 22:59:25 -05:00
UnixNight 4d07d60e2f feat(01-03): reconcile full-game capability and checkpoint coverage
Map all 33 requirements across six groups and reconcile 33 hashed source rows. Preserve startup current/history, unimplemented work and open native/reference acceptance; bind imported receipt identities and generate navigation.
2026-11-12 22:57:22 -05:00
UnixNight fafbd05811 docs(pause): preserve phase one partial ledger continuation 2026-11-12 20:02:30 -05:00
UnixNight c21ed7d7a2 test(01-03): require complete game and checkpoint source coverage 2026-11-12 19:58:32 -05:00
UnixNight e6713ead48 feat(01-03): trace corrected TSK order through capability evidence 2026-11-12 19:57:35 -05:00
UnixNight ded848f78e test(01-03): specify capability applicability and review navigation 2026-11-12 19:53:52 -05:00
UnixNight be18d77ca4 docs(01-02): record sequential viewer progress 2026-11-12 19:48:50 -05:00
UnixNight a789bfa942 docs(01-02): complete local paired review plan 2026-11-12 19:48:18 -05:00
UnixNight 91da92f17d feat(01-02): preserve clocks exclusive audio and complete review tails 2026-11-12 19:46:04 -05:00
UnixNight 75d7ca4279 test(01-02): specify truthful timing audio and failure states 2026-11-12 19:35:57 -05:00
UnixNight 49f874e64c feat(01-02): export and serve validated local media pairs 2026-11-12 19:34:06 -05:00
UnixNight 488c904807 test(01-02): specify contained paired media review 2026-11-12 19:30:43 -05:00
63 changed files with 13903 additions and 102 deletions

No files matched your search

+65
View File
@@ -0,0 +1,65 @@
{
"description": "GamePort quota guard: stop new workers at 20%; checkpoint and pause at 15%.",
"hooks": {
"SessionStart": [
{
"hooks": [
{
"type": "command",
"command": "/usr/bin/python3 \"$(git rev-parse --show-toplevel)/tools/workflow/codex_quota_guard.py\" hook",
"timeout": 5,
"commandWindows": "cmd /c exit 0"
}
]
}
],
"PreModelRequest": [
{
"hooks": [
{
"type": "command",
"command": "/usr/bin/python3 \"$(git rev-parse --show-toplevel)/tools/workflow/codex_quota_guard.py\" hook",
"timeout": 5,
"commandWindows": "cmd /c exit 0"
}
]
}
],
"UserPromptSubmit": [
{
"hooks": [
{
"type": "command",
"command": "/usr/bin/python3 \"$(git rev-parse --show-toplevel)/tools/workflow/codex_quota_guard.py\" hook",
"timeout": 5,
"commandWindows": "cmd /c exit 0"
}
]
}
],
"PreToolUse": [
{
"hooks": [
{
"type": "command",
"command": "/usr/bin/python3 \"$(git rev-parse --show-toplevel)/tools/workflow/codex_quota_guard.py\" hook",
"timeout": 5,
"commandWindows": "cmd /c exit 0"
}
]
}
],
"PostToolUse": [
{
"hooks": [
{
"type": "command",
"command": "/usr/bin/python3 \"$(git rev-parse --show-toplevel)/tools/workflow/codex_quota_guard.py\" hook",
"timeout": 5,
"commandWindows": "cmd /c exit 0"
}
]
}
]
}
}
+69
View File
@@ -0,0 +1,69 @@
{
"version": "1.0",
"timestamp": "2026-11-13T22:26:46.798618+00:00",
"phase": "01",
"phase_name": "Reproducible Fidelity Baseline",
"phase_dir": ".planning/phases/01-reproducible-fidelity-baseline",
"plan": 7,
"task": 3,
"total_tasks": 3,
"status": "consumed",
"completed_tasks": [
{
"id": 1,
"name": "Readiness/audit tooling plus review closure",
"status": "done",
"commit": "026def9",
"fix_head": "02d182f"
},
{
"id": 2,
"name": "Actual combined session status projection",
"status": "partial",
"commit": "fc5e936",
"actual_acceptance": "0/120 OPEN"
},
{
"id": 3,
"name": "Suite integration and review",
"status": "done",
"commit": "472500b",
"review_docs": "71366e7"
}
],
"remaining_tasks": [
{
"id": 2,
"name": "Actual original/native combined session and strict acceptance",
"status": "human_pending"
}
],
"blockers": [
{
"type": "human_action",
"description": "Combined original/native session and ten named UAT checks remain pending; 0/120 accepted."
}
],
"background_processes": {
"tests": "finished",
"verifier": "finished human_needed",
"quota_watcher": "running; no automatic resume"
},
"async_jobs": [],
"human_actions_pending": [
{
"action": "AfterfinalreadinessverificationperformonecombinedWindowsDxWnd/nativeWindows/physicalLinuxreviewsession",
"blocking": true
}
],
"uncommitted_files": [
" M .planning/HANDOFF.json",
" M .planning/ROADMAP.md",
" M .planning/STATE.md",
" M .planning/phases/01-reproducible-fidelity-baseline/.continue-here.md",
" M .planning/phases/01-reproducible-fidelity-baseline/HANDOFF.md",
"?? tools.yaml"
],
"next_action": "Use $gsd-verify-work 1 and docs/evidence/checkpoint-session.md for one combined actual human session; do not repeat completed implementation/tests/review or advance Phase2 automatically.",
"context_notes": "Quota guard explicitly requested pause at15%. Resume completed task01-07-03 and recovered fullsuite exit0 (782.049626s), then reviewed/fixed allfive source-integrity findings. Do NOT redo implementation or tests. Source commits through02d182f, review/coverage/security documentation71366e7. Fullsuite556Python/180fidelity,27Node,23observer,2HUD,51managedentrypoints,36GPUrenderedreceipts,zeroVulkanvalidationerrors,SDLdummychecks,539originalhashes. Latertooling-onlyfixes: all191fidelityregressions PASS43.355s; focused26scenario,23capture,29acceptance,27Node,18LinuxhostedPowerShell. All539originals unchanged. No runtime changes afterfullsuite; no need13minGPUrerun forcurrentPython/collector fixes.\nHistoricalreview5915128: CR01selected-vs-reviewedpath,CR02originalinventory/executablebinding,CR03copy-stateidentity,WR01viewerledgerprojection,WR02interruptedWindowsfinalization. Fixes5569bc2,bda35e5,6e5ee0b,548c97a,2608517,a821754. Independentre-reviewcaughtremaininghash-onlycopy-statebypass; RED48fca0d/GREEN02d182f requiresactual_checked_artifactwithrootinside_scenario_observation; callersupdated. Finalindependentre-reviewallfiveFIXED in01-REVIEW-VERIFY.md; dispositionopen0. Securityauditorfinal22/22mitigated, threats_open0 in01-SECURITY.md. Nyquistautomationcoveragevalidatedall15taskbindings; manualacceptanceopen;191fidelityaggregate43.355sec exceeds30secquicktargethonestly. UIreviewdisabledconfigfalse. No remainingknowncode/securityblockers.\nCurrentfreshfinalbundle dist/fidelity/phase01 has11001immutableentries. Currenthashes/readinessreceipt artifacts/fidelity/verification/01-07-final-checkpoint.json. readyexit0true,strictauditexit1 errors[] accepted0/120,10humanpending; logs artifacts/fidelity/01-review-fixes/readiness-final.json,acceptance-final.json,python-fidelity-final.log. Oldbundlespreserved phase01-pre-review-48100025 andphase01-pre-copy-artifact-7ceebcb3. ActualLinuxfailedpreflightimportedcurrentbundle/results/imported. Runtimepackage source446930d dirty/diff90cef956 unchanged; source/docscommitsmustnotrelabelitsidentity. Original/nativeWindows+DxWnd andphysicalLinuxvisible/audible/browserreviewremainonecombinedhuman session pending. Humanonlycollects/observes/returns; agent-ownedexactnormalizationmapping incheckpoint-session.md. No capture request issued yet because finalphaseverification/handoffpending.\nFinal typed verifier phase01_final_verification was dispatched at21%; quota15% interrupted it, instructedfinishonlyboundedhuman_neededreport/fingerprint thenreturn. It had readall7musthaves/summaries, checked25capabilities/33requirements/0unmapped/6groups/33rows,16/16decisioncoverage,40sourcefilesnoskip/debtscan. A mandatoryMVPgoalformatguard exposed existingROADMAPMode:mvp plainproseGoal. Rootauthorizedformat-only identicalintentuserstory and modifiedROADMAP.md uncommitted: As a tester, I want to reproduce identified original/port comparison scenarios, so that I understand exactly what the current reconstruction proves on each native platform. Validatorvalidtrue; no scope/successcriteriamodified. OneverifiercommandusedwrongunittestclassFidelityAcceptance (loadererror,correctclassAcceptanceTests); twoothernamedbehaviorcheckspassed; don'tmislabelthatcommandassuccess. Priorfulltargeted29passestablishactualcoverage.\nNEXT: Reconcile currentverifier's 01-VERIFICATION.md and CLI verification.status; ifreport/fingerprintabsentfinishthat ONLY beforeanynewphase. FingerprintmustbeownerCLIgenerated, notmanual. Oncehuman_neededstatusvalid, persistUATfromnamedhumanitems, updateSTATE/consumedhandoffs, commitverifiedreport+goalmetadata+handoffdocs andpush verifiedsource/tooling toauthorizedGitea/main. Lastpushedhead remainsd18f551; later01-07/task3/reviewfix/auditcommits arelocalawaitingfinalverification. Preserveunrelatedtools.yaml. Do notadvancephase2orclaimPhase1accepted; allEVIDIDsPending0/120humanacceptance. No source changesuncommittedexceptROADMAPformatandpossiblynewverifierreport.\nNativeagents/sourcewritesallfinishedexceptverifierreportbeingclosed. Quota watcher runs and actual15%steeringworks. Noauto-resume; usermust $gsd-resume-workafterreset. Don'tspendquota rereadingmassiveGSDscriptbodies orrerunningfinished13minfullsuite. Existinglocalpackages/media/originalcopiesstaylocal, noCI/uploads. MaintracksGitea/main, scoped.gitwriteescalation; retainhistoricalhandoffsmarkconsumedratherthandelete (priorautomaticreviewrejecteddeletion).\nRootinterruptedverifieratfinalpause tostopallmodelwork. Reconcileactualreportfileifpresent; ifabsentfinishboundedreport/fingerprintafterreset.\n\n2026-11-14 final typed verifier completed: human_needed,29/42verified13uncertain,all10namedhumanitems saved01-UAT.md. Ownerstatusacceptedreport; verificationfingerprintrefreshedafterfinalstatusnotes. Goalformatfebb4a9committed. Remainingworkisactualcombinedhumanverification, notcoding/fulltests.\n"
}
+17 -9
View File
@@ -30,7 +30,7 @@ Integer phases are planned work; decimal phases may be inserted for urgent recov
## Phase Details
### Phase 1: Reproducible Fidelity Baseline
**Goal:** Testers can reproduce identified original/port comparison scenarios and understand exactly what the current reconstruction proves on each native platform.
**Goal:** As a tester, I want to reproduce identified original/port comparison scenarios, so that I understand exactly what the current reconstruction proves on each native platform.
**Mode:** mvp
**Depends on:** Nothing (existing codebase and evidence are the starting point).
**Requirements:** EVID-01, EVID-02, EVID-03, EVID-04
@@ -39,23 +39,31 @@ Integer phases are planned work; decimal phases may be inserted for urgent recov
2. A tester can reproduce identified whole-original reference scenarios from an isolated generated installation and inspect corresponding input/events, images and audio where applicable; unavailable execution keeps this criterion open.
3. A reviewer can trace every full-game capability from original evidence through current implementation, platform receipts, discrepancies and its remaining acceptance condition.
4. Testers can repeat the same baseline movement/route scenarios on native Linux and native Windows with exact revision identities; Wine/cross-publish receipts remain separately labeled and cannot close missing native execution.
**Plans:** 1/7 plans executed
**Plans:** 7/7 autonomous preparation/reconciliation plans recorded; actual 01-07-02 capture/review and Phase 1 acceptance remain pending.
**Wave 1**
- [x] 01-01-PLAN.md
**Wave 2** *(blocked on Wave 1 completion)*
- [ ] 01-02-PLAN.md
- [ ] 01-03-PLAN.md
- [ ] 01-04-PLAN.md
- [x] 01-02-PLAN.md
- [x] 01-03-PLAN.md
- [x] 01-04-PLAN.md
**Wave 3** *(blocked on Wave 2 completion)*
- [ ] 01-05-PLAN.md
- [x] 01-05-PLAN.md
**Wave 4** *(blocked on Wave 3 completion)*
- [ ] 01-06-PLAN.md
- [x] 01-06-PLAN.md
**Wave 5** *(blocked on Wave 4 completion)*
- [ ] 01-07-PLAN.md
- [x] 01-07-PLAN.md
Autonomous preparation is complete: 11,000 immutable files pass readiness and
the complete local suite passes in 782.05s. Actual task 01-07-02 capture/review
remains human_needed: 0/120 original/native obligations accepted and ten human
findings pending. All EVID requirements remain Pending; Phase 1 is not accepted.
The primary reviews readiness before one combined session. Retained quota
handoff files are historical until primary consumption; the final SUMMARY
records completed task 3 and pending human dependencies. No Phase 2 advancement.
### Phase 2: Faithful Movement and Scene Handoffs
**Goal:** Players move, contact the world and return from scripts/scenes with the original movement, animation, camera and state ownership intact.
@@ -151,7 +159,7 @@ Execution follows 1 → 2 → 3 → 4 → 5 → 6 → 7 → 8, subject to the ex
| Phase | Plans Complete | Status | Completed |
|-------|----------------|--------|-----------|
| 1. Reproducible Fidelity Baseline | 1/7 | In Progress | - |
| 1. Reproducible Fidelity Baseline | 7/7 preparation | Human acceptance pending (0/120) | - |
| 2. Faithful Movement and Scene Handoffs | 0/TBD | Not started | - |
| 3. Original Actors, Hazards and Combat | 0/TBD | Not started | - |
| 4. Complete Gadget and Vehicle Use | 0/TBD | Not started | - |
+38 -19
View File
@@ -2,17 +2,17 @@
gsd_state_version: "1.0"
current_phase: 01
current_phase_name: Reproducible Fidelity Baseline
status: executing
stopped_at: Completed 01-01-PLAN.md
last_updated: "2026-11-13T00:13:22.917Z"
last_activity: 2026-11-12
last_activity_desc: Phase 01 execution started
state_head: ac958e1962f381804f6a5ad6bf9ea2559a652fff
status: awaiting_human_verification
stopped_at: Phase1 verified human_needed; ten UAT checks and combined actual session pending
last_updated: "2026-11-14T05:39:47.960Z"
last_activity: 2026-11-13
last_activity_desc: 01-07 autonomous preparation verified; actual human acceptance pending 0/120
state_head: febb4a9d98071b19998bcecfab4a236d9c0adfce
progress:
total_phases: 8
completed_phases: 0
total_plans: 7
completed_plans: 1
completed_plans: 7
percent: 0
---
@@ -27,29 +27,35 @@ See: .planning/PROJECT.md (updated 2026-11-12)
## Current Position
Phase: 01 (Reproducible Fidelity Baseline) — EXECUTING
Plan: 2 of 7
Status: Ready to execute
Last activity: 2026-11-12 — Phase 01 execution started
Phase: 01 (Reproducible Fidelity Baseline) — HUMAN ACCEPTANCE PENDING
Plan: 7 of 7
Status: Preparation complete; actual original/native acceptance human_needed
Last activity: 2026-11-13 — Task 3 committed, complete local suite passed in 782.05s; final summary committed.
Progress: [░░░░░░░░░░] 0%
## Performance Metrics
- Total plans completed: 0
- Average duration: Not established
- Total execution time: 0 hours
- Autonomous preparation plans recorded: 7/7; accepted phases: 0/8
- Average duration: See per-plan metrics; elapsed intervals include pauses
- Total active execution time: Not continuously measured
| Phase | Plans | Total | Avg/Plan |
|-------|-------|-------|----------|
| - | - | - | - |
Recent trend: No execution plans completed in this roadmap. Existing project work predates initialization and retains its documented bounded evidence.
Recent trend: All seven preparation/reconciliation records exist; actual task 01-07-02 and Phase 1/EVID acceptance remain open. Existing project work retains its documented bounded evidence.
**Per-Plan Metrics:**
| Plan | Duration | Tasks | Files |
|------|----------|-------|-------|
| Phase 01 P01 | 16 min | 2 tasks | 5 files |
| Phase 01 P02 | 16 min | 2 tasks | 6 files |
| Phase 01 P03 | 22 min | 2 tasks | 4 files |
| Phase 01 P04 | 16 min | 2 tasks | 5 files |
| Phase 01 P05 | 12h 4min | 2 tasks | 7 files |
| Phase 01 P06 | 14 min | 2 tasks | 4 files |
| Phase 01 P07 | 4h 36min elapsed incl quota pause; suite 782.05s | 2 tasks | 16 files |
## Accumulated Context
@@ -63,13 +69,26 @@ Recent trend: No execution plans completed in this roadmap. Existing project wor
- [Phase 01]: Version 1 typed hashed receipts keep category, history and actual bytes separate from acceptance; structural readiness never substitutes for native/reference execution.
- [Phase 01]: All eight lifetime/dialogue/input cells require continuous plus four focused obligations on three original/native sides, totaling 120 independently audited obligations.
- [Phase 01]: Retained observations require one session, observed prerequisite departure/return and hashed copy state; each fresh run uses an independent launch/session identity.
- [Phase 01]: Paired review preserves actual speed, separate raw clocks, explicit event and playback drift, exclusive audio and complete recording tails; export never promotes runtime acceptance.
- [Phase 01]: Capability source links are normalized to contained tracked bounded UTF-8 text copies and activated only through exporter-validated local hrefs.
- [Phase 01]: Capability ledger maps all33 requirements and reconciles33 hashed checkpoint rows; documentary coverage, unimplemented work and exact historical content never promote actual original/native acceptance.
- [Phase 01]: One outer observer owns a unique launch/clock identity through Run continuations; simulation ticks remain scene-local and case/session IDs remain declared provenance.
- [Phase 01]: Accepted input means the existing binding's returned gate result, with separately identified post-step ownership; individual command dispatch and independent body/fire work are not inferred.
- [Phase 01]: Observer records are diagnostic source material for later collectors, not receipts or automatic original/native acceptance; fixture classification survives continuations.
- [Phase 01]: READY validates identified offline materials only; original-DxWnd/native Linux/native Windows acceptance remains open 0/120.
- [Phase 01]: Runtime package provenance retains actual completed publish source/dirty/diff identity; selected external tools are identified without redistributing executables.
- [Phase 01]: No display and only auto_null audio yields failed native preflight; all forty Linux obligations retain explicit physical/audible capture dependencies.
- [Phase 01]: Linux matrix history revalidates saved receipt hashes and requires new launch/session IDs; focused captures cannot replace continuous route lifetimes.
- [Phase 01]: Ready materials and local regressions never substitute for actual original/native acceptance; all 120 obligations and ten named human findings remain open.
- [Phase 01]: The integration agent reconciles returned collector records through specified artifact mappings; the tester collects, observes and returns one combined session.
### Pending Todos
None captured separately. Next action: `$gsd-discuss-phase 1` or `$gsd-plan-phase 1`.
Primary readiness review of final 01-07 source/materials, then the single combined human session in docs/evidence/checkpoint-session.md. All EVID requirements remain Pending. Do not launch Phase 2 from preparation counts.
### Blockers/Concerns
- Final 01-07 readiness passes 11,000 immutable files and local suite passes; strict audit still exits 1 with no structural errors, 0/120 accepted obligations and ten pending human findings. This is an actual evidence dependency, not a test failure or auto-approval gate.
- Phase 1: Working whole-original reference capture and current native Windows comparison remain unverified access dependencies. Record limitations; keep acceptance open while independent source-backed recovery continues.
- Phase 2: Real derived responses, helper membership/activation/cleanup, physical order and shared mutable reclip remain live admission gates. Lab/outside capsule stays until its replacement gate closes.
- Full-game completion requires current integrated native Linux/Windows and original-reference evidence. Compilation, copied-original probes and Wine have narrower scopes.
@@ -89,6 +108,6 @@ No original-required category deferred outside full reconstruction. Later phases
## Session Continuity
Last session: 2026-11-13T00:13:05.517Z
Stopped at: Completed 01-01-PLAN.md
Resume file: None
Last session: 2026-11-14T05:39:45.079Z
Stopped at: Phase1 verified human_needed; ten UAT checks and combined actual session pending
Resume file: .planning/phases/01-reproducible-fidelity-baseline/01-UAT.md
+31 -3
View File
@@ -1,10 +1,10 @@
---
schema_version: 1
open_count: 0
open_count: 2
waived_count: 0
fixed_count: 1
total_count: 1
last_updated: 2026-11-13T00:13:04.410Z
total_count: 3
last_updated: 2026-11-13T17:20:49.885Z
---
# Broken Windows Ledger
@@ -16,6 +16,8 @@ last_updated: 2026-11-13T00:13:04.410Z
| id | phase | kind | file | line | description | status | reason | recorded_at | resolved_at |
|----|-------|------|------|------|-------------|--------|--------|-------------|-------------|
| 1 | 01 | deviation | tests/test_fidelity_sessions.py | | Task 2 also strengthens shared receipt security regressions in the task-1 test file; fixed and verified. | fixed | | 2026-11-13T00:12:34.143Z | 2026-11-13T00:13:04.410Z |
| 2 | 01 | unrun-verify | docs/evidence/linux-session.md | | Actual Linux display, physical-input and audible capture remains open: no display session and only auto_null audio; all 40 Linux obligations await the final combined session. | open | | 2026-11-13T17:02:56.623Z | |
| 3 | 01 | unmet-truth | docs/evidence/phase01-baseline.md | | Actual original-DxWnd/native Linux/native Windows capture and combined human review remain OPEN0/120; strict audit human_needed. | open | | 2026-11-13T17:20:49.885Z | |
````json
[
@@ -31,6 +33,32 @@ last_updated: 2026-11-13T00:13:04.410Z
"recorded_at": "2026-11-13T00:12:34.143Z",
"resolved_at": "2026-11-13T00:13:04.410Z",
"milestone": null
},
{
"id": 2,
"kind": "unrun-verify",
"phase": "01",
"file": "docs/evidence/linux-session.md",
"line": null,
"description": "Actual Linux display, physical-input and audible capture remains open: no display session and only auto_null audio; all 40 Linux obligations await the final combined session.",
"status": "open",
"reason": "",
"recorded_at": "2026-11-13T17:02:56.623Z",
"resolved_at": null,
"milestone": null
},
{
"id": 3,
"kind": "unmet-truth",
"phase": "01",
"file": "docs/evidence/phase01-baseline.md",
"line": null,
"description": "Actual original-DxWnd/native Linux/native Windows capture and combined human review remain OPEN0/120; strict audit human_needed.",
"status": "open",
"reason": "",
"recorded_at": "2026-11-13T17:20:49.885Z",
"resolved_at": null,
"milestone": null
}
]
````
@@ -0,0 +1,35 @@
<!-- CONSUMED: final verification completed human_needed on2026-11-14. Current next action: $gsd-verify-work 1 and combined actual human session; historical interrupted-verifier notes below are superseded. -->
---
context: phase
phase: 01-reproducible-fidelity-baseline
plan: "07"
task: 3
total_tasks: 3
status: consumed
last_updated: "2026-11-13T22:26:46.798618+00:00"
---
# Final verification quota checkpoint
Quota guard explicitly requested pause at15%. Resume completed task01-07-03 and recovered fullsuite exit0 (782.049626s), then reviewed/fixed allfive source-integrity findings. Do NOT redo implementation or tests. Source commits through02d182f, review/coverage/security documentation71366e7. Fullsuite556Python/180fidelity,27Node,23observer,2HUD,51managedentrypoints,36GPUrenderedreceipts,zeroVulkanvalidationerrors,SDLdummychecks,539originalhashes. Latertooling-onlyfixes: all191fidelityregressions PASS43.355s; focused26scenario,23capture,29acceptance,27Node,18LinuxhostedPowerShell. All539originals unchanged. No runtime changes afterfullsuite; no need13minGPUrerun forcurrentPython/collector fixes.
Historicalreview5915128: CR01selected-vs-reviewedpath,CR02originalinventory/executablebinding,CR03copy-stateidentity,WR01viewerledgerprojection,WR02interruptedWindowsfinalization. Fixes5569bc2,bda35e5,6e5ee0b,548c97a,2608517,a821754. Independentre-reviewcaughtremaininghash-onlycopy-statebypass; RED48fca0d/GREEN02d182f requiresactual_checked_artifactwithrootinside_scenario_observation; callersupdated. Finalindependentre-reviewallfiveFIXED in01-REVIEW-VERIFY.md; dispositionopen0. Securityauditorfinal22/22mitigated, threats_open0 in01-SECURITY.md. Nyquistautomationcoveragevalidatedall15taskbindings; manualacceptanceopen;191fidelityaggregate43.355sec exceeds30secquicktargethonestly. UIreviewdisabledconfigfalse. No remainingknowncode/securityblockers.
Currentfreshfinalbundle dist/fidelity/phase01 has11001immutableentries. Currenthashes/readinessreceipt artifacts/fidelity/verification/01-07-final-checkpoint.json. readyexit0true,strictauditexit1 errors[] accepted0/120,10humanpending; logs artifacts/fidelity/01-review-fixes/readiness-final.json,acceptance-final.json,python-fidelity-final.log. Oldbundlespreserved phase01-pre-review-48100025 andphase01-pre-copy-artifact-7ceebcb3. ActualLinuxfailedpreflightimportedcurrentbundle/results/imported. Runtimepackage source446930d dirty/diff90cef956 unchanged; source/docscommitsmustnotrelabelitsidentity. Original/nativeWindows+DxWnd andphysicalLinuxvisible/audible/browserreviewremainonecombinedhuman session pending. Humanonlycollects/observes/returns; agent-ownedexactnormalizationmapping incheckpoint-session.md. No capture request issued yet because finalphaseverification/handoffpending.
Final typed verifier phase01_final_verification was dispatched at21%; quota15% interrupted it, instructedfinishonlyboundedhuman_neededreport/fingerprint thenreturn. It had readall7musthaves/summaries, checked25capabilities/33requirements/0unmapped/6groups/33rows,16/16decisioncoverage,40sourcefilesnoskip/debtscan. A mandatoryMVPgoalformatguard exposed existingROADMAPMode:mvp plainproseGoal. Rootauthorizedformat-only identicalintentuserstory and modifiedROADMAP.md uncommitted: As a tester, I want to reproduce identified original/port comparison scenarios, so that I understand exactly what the current reconstruction proves on each native platform. Validatorvalidtrue; no scope/successcriteriamodified. OneverifiercommandusedwrongunittestclassFidelityAcceptance (loadererror,correctclassAcceptanceTests); twoothernamedbehaviorcheckspassed; don'tmislabelthatcommandassuccess. Priorfulltargeted29passestablishactualcoverage.
NEXT: Reconcile currentverifier's 01-VERIFICATION.md and CLI verification.status; ifreport/fingerprintabsentfinishthat ONLY beforeanynewphase. FingerprintmustbeownerCLIgenerated, notmanual. Oncehuman_neededstatusvalid, persistUATfromnamedhumanitems, updateSTATE/consumedhandoffs, commitverifiedreport+goalmetadata+handoffdocs andpush verifiedsource/tooling toauthorizedGitea/main. Lastpushedhead remainsd18f551; later01-07/task3/reviewfix/auditcommits arelocalawaitingfinalverification. Preserveunrelatedtools.yaml. Do notadvancephase2orclaimPhase1accepted; allEVIDIDsPending0/120humanacceptance. No source changesuncommittedexceptROADMAPformatandpossiblynewverifierreport.
Nativeagents/sourcewritesallfinishedexceptverifierreportbeingclosed. Quota watcher runs and actual15%steeringworks. Noauto-resume; usermust $gsd-resume-workafterreset. Don'tspendquota rereadingmassiveGSDscriptbodies orrerunningfinished13minfullsuite. Existinglocalpackages/media/originalcopiesstaylocal, noCI/uploads. MaintracksGitea/main, scoped.gitwriteescalation; retainhistoricalhandoffsmarkconsumedratherthandelete (priorautomaticreviewrejecteddeletion).
## Required Reading
AGENTS.md,parentinstructions,HANDOFF.json,01-07SUMMARY,01-REVIEW-VERIFY,01-SECURITY,01-VALIDATION,and01-VERIFICATIONifpresent.
## Critical Anti-Patterns
| Pattern | Description | Severity | Prevention Mechanism |
|---|---|---|---|
| Redo completed tests | Fullsuiteand191fidelitychecksfinished | advisory | Reconcile savedlogs first; rerunonlyafternewchanges |
| False phase completion | Preparedmaterialsfailactualstrictacceptance0/120 | advisory | KeepEVIDPending andhuman_needed; owner verification.status beforeadvance |
## Infrastructure State
Testsfinished; verifierinterruptedatpause; reportreconciliationpending; localquota watcher running. No sourceworkeractive.
## Next Action
Inspect01-VERIFICATION.md and owner verification.status; finish report/fingerprint/UAT ifneeded, commit/pushverified01-07reviewedwork; neverredo task3/fulltests orautoapprovehumanacceptance.
@@ -0,0 +1,176 @@
---
phase: 01-reproducible-fidelity-baseline
plan: "02"
subsystem: testing
tags: [python, native-media, node, local-http, fidelity, evidence]
requires:
- phase: 01-01
provides: Version 1 validated hashed receipts and scenario contract
provides:
- Self-contained review export with contained read-only loopback GET/HEAD ranges
- Independent event seeks, raw clocks, drift, exclusive audio and preserved tails
- Capability navigation with validated copied source text and explicit missing states
affects: [01-03, 01-05, 01-06, 01-07]
tech-stack:
added: []
patterns: [stdlib-only export, native browser media, independent clocks, opt-in review aids, built-in Node tests]
key-files:
created:
- tools/recon/fidelity_review.py
- tools/recon/fidelity_viewer/index.html
- tools/recon/fidelity_viewer/viewer.mjs
- tools/recon/fidelity_viewer/style.css
- tests/test_fidelity_review.py
- tests/fidelity-viewer.test.mjs
modified: []
key-decisions:
- "Review exports always retain OPEN acceptance; synthetic/history labels and absent original/native recordings stay explicit."
- "Pair playback uses rate 1 with separately observed event anchors, independent clocks, visible drift and explicit recovery; longer tails remain playable."
- "Capability source links are copied only from contained tracked bounded UTF-8 text; the viewer activates only exporter-validated local hrefs."
requirements-completed: [EVID-02, EVID-03, EVID-04]
requirements-acceptance: "OPEN: assigned tooling contributions only; shared EVID IDs remain Pending and real runtime coverage remains 0/120."
coverage:
- id: contained-review
description: Validated receipt export, contained HTTP seeking and local source links
requirement: EVID-02
verification:
- kind: integration
ref: tests/test_fidelity_review.py
status: pass
human_judgment: false
- id: paired-controller
description: Event alignment, raw clocks, drift, exclusive audio, failure states and optional aids
requirement: EVID-03
verification:
- kind: unit
ref: tests/fidelity-viewer.test.mjs
status: pass
- kind: automated_ui
ref: artifacts/fidelity/viewer-smoke-final/browser-result.json
status: pass
human_judgment: false
- id: real-audiovisual-review
description: Actual original/native recordings, audible source switching and browser/codec judgment
requirement: EVID-04
verification: []
human_judgment: true
rationale: "Headless synthetic playback verifies tooling only. Actual identified original/native media and audible review belong to the final combined session."
actuals:
tokens: 18814
tasks: 2
commits: 4
basis: "ceil(chars/4) over the realized six-file production/test diff, excluding planning metadata"
plan_head_before: 6be848480288480208ac737c953b7c9bfc82bd84
plan_head_after: 91da92f17d93ba80ead87f92cf4714b6635133bb
duration: 16 min
started: 2026-11-13T00:30:27Z
completed: 2026-11-13
status: complete
---
# Phase 01 Plan 02: Local Paired Review Summary
**Contained hashed-media export and actual-speed paired playback expose event/playback drift, exclusive audio, optional still differences and complete recording tails.**
## Performance
- Measured implementation window: first persisted RED evidence at 00:30:27 UTC through final verification at 00:46:15 UTC, rounded to 16 minutes. Required setup/context reads preceded this measurement.
- Two tasks; six source/test files; four task commits measured from the persisted ledger.
- Final exact checks: 21 Python review tests, 5.234 seconds including process startup; 27 Node tests, 0.120 seconds. Combined fidelity discovery: 72 tests, 6.318 seconds. Original inventory: 539 unchanged files, 0.268 seconds.
- Full logs and command/exit/time records: ignored `artifacts/fidelity/verification/01-02-*`.
## Accomplishments
- A real subprocess exports imported hashed receipts into a new self-contained directory. Tests read both media links and event metadata over actual loopback HTTP, including HEAD, prefix/open/suffix ranges and invalid-range rejection.
- Both recordings seek to their own observed markers after metadata/seek readiness. Explicit play preserves rate 1, and raw elapsed clocks, event offsets, event drift plus uncertainty, and browser playback drift remain separately visible. No follower seeks, duration normalization or retiming occur.
- Dedicated keyboard-accessible per-side play/pause/seek controls coexist with exclusive soundtrack selection and visibly labeled review-only volume. Buffering, missing media, decoding failure, play rejection, stale asynchronous actions and asymmetric endings remain explicit; the full longer tail can resume.
- Annotations and lossless image differences begin off and leave raw captures unobstructed. Difference eligibility requires identified PNGs, source-media hashes, corresponding observed event timestamps, matching dimensions/viewport/aspect/crop and successful image decoding. Differences have no numerical fidelity score.
- Capability navigation preserves supplied facts/current evidence/history, orders discrepancies by impact, and links copied validated source text. Empty ledger and missing-source states remain explicit.
## Task Commits
1. Task 01-02-01 RED: `488c904` — specify contained paired media review.
2. Task 01-02-01 GREEN: `49f874e` — export and serve validated local media pairs.
3. Task 01-02-02 RED: `75d7ca4` — specify truthful timing, audio and failure states.
4. Task 01-02-02 GREEN: `91da92f` — preserve clocks, exclusive audio and complete review tails.
Normal hooks ran with scoped staging. No tracked files were deleted. The primary owns milestone review and push; this executor did not push.
## Local Invocation and Interfaces
```sh
python3 tools/recon/fidelity_review.py export \
--original PATH/TO/IMPORTED-ORIGINAL/receipt.json \
--port PATH/TO/IMPORTED-PORT/receipt.json \
--ledger PATH/TO/CAPABILITY-EXPORT.json \
--output artifacts/fidelity/review/NEW-PAIR
python3 tools/recon/fidelity_review.py serve \
--root artifacts/fidelity/review/NEW-PAIR --port 8765
```
Open `http://127.0.0.1:8765/`. Either receipt and the ledger may be omitted; absent evidence stays visible. Output must be a new directory. Invalid input exits 2. Serving requires a generated `.review-root.json` manifest and only binds `127.0.0.1`; it never serves the repository or Original directory. The exporter copies/revalidates bytes, retains raw artifacts/derivative ancestry, and never executes receipt argv. Failed publication retains its incomplete temporary sibling.
Python APIs: `export_review(original, port, output, ledger=None)` returns the model; `make_server(root, port=8765, host='127.0.0.1')` returns an owned `ThreadingHTTPServer`. The caller closes/shuts down that server. The generated root contains `review.json`, the three viewer files, side-specific receipt/artifacts and optional `sources/` text.
`review.json` version 1 contains `case_id`, `sides.original/port`, corresponding `events`, `ledger`, and explicit OPEN acceptance. Side records preserve kind/platform/scope/history/limits/identities, hashed `artifacts` with local `url`, selected `media`, observed `events`, `derivatives`, `receipt_url`, missing evidence and warnings. Only markers on the selected video/explicit preview are seekable; a preview without its own observed correspondence has visible gaps. Same case/scope and unambiguous event names are required. No timestamps are inferred from derivatives.
ES module exports: `createPairController`, `safeLocalURL`, `differenceEligibility`, `framePair`, `renderCapabilities`. Controller methods are `selectEvent`, `play`, `playSide`, `seekSide`, `pause`, `snapshot`, `setAudio`, `setGain`, `setOverlay`, `dispose`; media elements and change callback are injected for testing. Volume starts at 1 and can be attenuated from 0 to 1. Both sources are muted before audio selection; dedicated UI controls prevent native media controls independently enabling another soundtrack.
Optional PNG artifact metadata is `frame: {lossless,event,media_sha256,media_seconds,viewport:[w,h],crop:[x,y,w,h],width,height}`. It binds an identified PNG to its own selected source media and observed marker; unmatched provenance/dimensions disable the aid. PNG decoding must agree with declared dimensions. Raw video remains available, and still differences are review aids even when extracted from lossy video.
The coordinated ledger input contract is `{schema_version:1, capabilities:[...]}` with SKELETON fields `id/group/requirement_ids/summary/verified_scope/differences/acceptance/source_links/scenario_ids/evidence/current/history/discrepancies`. Evidence/current/history are rendered read-only without inventing acceptance facts. `source_links` entries are `{label,path,sha256?}` with repo-relative paths. Export resolves containment, rejects symlinks/private/generated/original roots, requires tracked non-NUL UTF-8 text at most 1 MiB, and verifies optional hashes. Exported links add `{href,validated_local,sha256,size,missing}`; only validated `sources/...` hrefs become links. Safe missing/untracked references have `href:null`, `validated_local:false`, and a visible reason. Other imported HTML/commands remain inert.
## Browser and Evidence Limits
Installed Chromium `157.0.8103.38` decoded local synthetic VP8/Vorbis recordings through the real server. A loopback CDP check verified `.500/.750` event seeks while paused, subsequent actual-speed playback, original/port mute exclusivity, visible volume adjustment, opt-in annotations/difference canvas, a 390px layout without horizontal overflow, and explicit longer-tail playback after the 3.003-second recording ended while the 5.003-second recording retained its tail. The copied source-document link returned HTTP 200. No page runtime exceptions were observed.
Ignored evidence is in `artifacts/fidelity/viewer-smoke-final/browser-result.json` and `browser.png`; fixture generation/CDP scripts are retained alongside them. The final generated synthetic viewer is `test-review-v3/` within that directory. Synthetic moving patterns and tones are labeled throughout, and no genuine original reference is implied. Browser media state checks do not prove audible hardware output or human audiovisual adequacy.
The genuine existing port output `artifacts/window-transitions/2-VR04-1280x720.png` was hashed/imported separately as **historical port_fixture** evidence and exported to `historical-review/`. Chromium displayed its historical label, raw still link, missing playable video and missing original reference. This does not establish a new runtime/source revision or applicability receipt.
Actual original-DxWnd, native Linux/Windows scenario recordings, codec variation and audible judgment remain for the one final combined session. Acceptance stays OPEN at 0/120 real obligations. Shared EVID IDs are not marked complete. No gameplay/runtime/package code, originals or shared receipt/scenario implementation changed; no game, DxWnd, Wine, GPU, managed build or Windows execution was performed here.
## TDD Gate Compliance
- Task 1: `artifacts/fidelity/tdd/01-02-01-red.json` retains the complete actual unittest report. The named CLI round-trip target failed its intended CLI-presence assertion before implementation. The classifier returned `RED_EVIDENCE_OK`; semantic inspection confirmed a behavior assertion rather than import/setup failure. The tracer's exact 15-Python/6-Node checks passed again before task 2.
- Task 2: `artifacts/fidelity/tdd/01-02-02-red.json` retains complete TAP. The named buffering test failed because replay incorrectly returned true while readyState was 2. The classifier returned `RED_EVIDENCE_OK`; other absent-API failures were retained rather than used as target evidence. Final suites pass 21 Python and 27 Node tests, with a dynamic minimum registered-count assertion.
- Each RED commit precedes its GREEN in ancestry. No separate refactor was needed. No skipped/todo tests or unrun planned automated checks remain.
## Deviations from Plan
No scope or architecture changes. The initial stylesheet was included with the tracer so its exported review tree was self-contained. The primary confirmed the exact tracked source-link normalization for plan 01-03 during implementation; this fulfills the planned capability navigation boundary without shared schema edits.
## Threat/Test Coverage
| Threat | Controls and evidence |
|---|---|
| T-01-04 | Generated-root manifest allowlist, actual hashes, loopback-only bind, resolved containment, symlink rejection, no listings, GET/HEAD-only reads, bounded single ranges; real HTTP negative/range tests |
| T-01-05 | Text rendering, relative URL allowlist, no imported HTML/argv execution, CSP/nosniff, imported active documents downloaded inertly, validated copied text sources; hostile-label/path/document tests |
| T-01-06 | Explicit category/history/missing labels, independent clocks, rate 1, separate drift/uncertainty, no auto-acceptance; controller/browser/classification tests |
| T-01-SC | Browser/Node/Python built-ins only; no npm/pip installation. Existing ffmpeg produced ignored synthetic smoke media. |
## Threat Flags
| Flag | File | Description |
|---|---|---|
| threat_flag: file-access | tools/recon/fidelity_review.py | Ledger source references cross the repository-text→generated-review boundary. Contained tracked bounded UTF-8-only copies, excluded roots, optional hash checks, inert text MIME and the generated manifest mitigate this planned navigation surface. |
The cooperative offline filesystem boundary matches the shared receipt module; hostile concurrent filesystem replacement is outside that model. Re-export/revalidate after evidence changes. Native media/browser codec support remains a runtime review condition.
## Issues Encountered
The sandbox blocks loopback sockets and causes Node's child test runner to report one file-only result. Authorized local-test escalation produced the real named counts and HTTP results; the file-only result was not counted as validation. A browser-cancelled read exposed a broken-pipe retry; the handler now ends disconnected responses cleanly. Newer seek actions supersede stale metadata waits without cancelling the current action. These fixes remain within planned failure handling.
No implementation stubs remain. Deliberately absent media/ledger states are implemented outcomes, not mock gameplay data. `tools.yaml`, the transient milestone lock and other owners' files were preserved.
## User Setup Required
None for the local tool checks. The planned combined hands-on original/native/audio session remains open; no earlier user execution request was created.
## Next Phase Readiness
Plan 01-03 can emit the coordinated capability/source-link contract; later checkpoint/capture/import plans can supply real receipts. The primary owns root continuity documents, integrated runtime regression gates and push. The existing gameplay and platform evidence limits remain binding.
## Self-Check: PASSED
All six created files exist. All four task commits are ancestors of HEAD and evaluation-scope resolves them on this branch. Exact counted plan checks, all 72 fidelity tests, whitespace checks and the 539-file preservation command pass. No tracked deletions, skipped tests or unexplained new untracked outputs were introduced; generated media/receipts stay ignored.
@@ -0,0 +1,163 @@
---
phase: 01-reproducible-fidelity-baseline
plan: "03"
subsystem: testing
tags: [python, capability-ledger, fidelity, sha256, reconciliation]
requires:
- phase: 01-01
provides: Version 1 receipts and eight-cell scenario protocol
- phase: 01-02
provides: Actual contained viewer export and source-link normalization
provides:
- Authoritative 25-capability ledger covering all 33 full-game requirements
- Exact reconciliation of 16 checkpoint systems, 11 owners and six assumptions
- Scope/content/platform selection, preserved supersession and generated navigation
affects: [01-04, 01-05, 01-06, 01-07, movement, delivery]
tech-stack:
added: []
patterns: [stdlib-only validation, hashed source rows, explicit documentary scope, generated Markdown and JSON]
key-files:
created:
- tools/recon/fidelity_ledger.py
- tests/test_fidelity_ledger.py
- docs/evidence/capabilities.json
- docs/evidence/README.md
modified: []
key-decisions:
- "Full-game coverage includes bounded, unimplemented and tooling work; coverage and report validity never promote native/reference acceptance."
- "Checkpoint reconciliation hashes every system/ownership row and numbered assumption and requires a retained source link from each mapped capability."
- "Current evidence means exact named content/platform/scope applicability; documentation dates and newer source HEAD never substitute for runtime bytes."
patterns-established:
- "One authoritative JSON model generates Markdown and viewer export; equal receipt IDs merge only byte-identical records across the entire ledger."
- "Imported receipt references bind actual receipt digest, category, platform, scope and historical flag; legacy report records remain separately described."
requirements-completed: [EVID-03]
requirements-acceptance: "OPEN: assigned ledger contribution only. EVID-03 remains Pending because other declaring plans and runtime acceptance are unfinished. All 120 actual original/native obligations remain open."
coverage:
- id: capability-accounting
description: All 33 requirements, six groups and 33 checkpoint source rows are explicitly accounted for
requirement: EVID-03
verification:
- kind: integration
ref: tests/test_fidelity_ledger.py
status: pass
- kind: other
ref: python3 tools/recon/fidelity_ledger.py validate --ledger docs/evidence/capabilities.json --requirements .planning/REQUIREMENTS.md
status: pass
human_judgment: false
- id: review-roundtrip
description: Actual ledger CLI and viewer export preserve all capability/current/history/scenario/acceptance data and copied source links
requirement: EVID-03
verification:
- kind: integration
ref: tests/test_fidelity_ledger.py#test_real_startup_capability_cli_and_viewer_roundtrip
status: pass
human_judgment: false
- id: actual-reference-acceptance
description: Identified whole-original and current native Linux/Windows gameplay and audiovisual comparison
verification: []
human_judgment: true
rationale: "Existing reports and bounded historical fixtures are not the required original-DxWnd/native scenario recordings or human review; actual matrix acceptance remains 0/120."
actuals:
tokens: 78646
tasks: 2
commits: 5
basis: "ceil(chars/4) over the realized four-file production/test/model/navigation diff (314583 chars), excluding planning metadata. Commit count is the actual persisted-ledger range, including the intervening pause handoff commit."
plan_head_before: be18d77ca42b1896540ff21122bbc1e684195dc1
plan_head_after: 4d07d60e2fdbfdb065aaa2e7e780055620984521
duration: 22 min
started: 2026-11-13T00:48:50Z
completed: 2026-11-13
status: complete
---
# Phase 01 Plan 03: Full-Game Capability Ledger Summary
**A generated 25-capability ledger maps all 33 requirements, reconciles 33 hashed checkpoint entries and preserves exact startup-order evidence with open native/reference acceptance.**
## Performance
- Two tasks; four created files. Approximate active execution windows total 22 minutes: prior-plan close at 00:48:50 through pause handoff at 01:02:30, then resumed state at 03:49:05 through verification/commit at 03:57:36 UTC. Approximately 189 wall minutes include the explicitly requested usage pause.
- Persisted base-to-production-HEAD range contains five commits: four task RED/GREEN commits and one pause handoff. Evaluation-scope independently resolves the four task commits on this branch.
- Final ledger suite: 31 tests, 0.980 seconds; all fidelity Python suites: 103 tests, 7.149 seconds (7.229 seconds including process overhead); Node: 27 named tests, 82.360 milliseconds. Original inventory: 539 unchanged files.
## Accomplishments
- The authoritative model accounts for movement, contacts/helpers, actors/hazards, gadgets/vehicles/inventory, authored content/progression, frontend/configuration/persistence, visuals/cameras, audio and native delivery. Its six locked navigation groups contain 25 capabilities: 21 bounded, three explicitly unimplemented full-scope workflows and one tooling capability. Coverage is 33 requirements, zero unmapped.
- Reconciliation retains all 16 system rows, 11 ownership rows and six numbered assumptions from `docs/checkpoint/coverage.md`. Each has exact source-row SHA-256, retained source path and mapped capability IDs. Missing, changed, duplicate or extra source rows and absent retained source links fail validation. Baseline wording remains in its source; continuation summaries explicitly refine it.
- The real startup row retains already-corrected TSK story-entry order, separate fresh direct-scene order, valid landing bank, actual source addresses/REA identifier and exact historical ea04210 Linux/Wine classifications. Prior incorrect fresh-story inference stays explicitly superseded with its successor and reason. Report validity is distinct from runtime applicability.
- Markdown and JSON exports come from the same model. A real subprocess ledger export feeds the existing `fidelity_review.export_review` without viewer edits. All 25 rows preserve their current/history/scenario/acceptance/discrepancy fields; all 153 source-link entries resolve to validated copied text files. Current evidence precedes history; discrepancies sort blocking, disruptive, subtle, missing_verification, then stable ID.
- Validation rejects empty/unmapped ledgers, conflicting duplicate capabilities/receipts/history, cycles, unresolved contradictory current claims, unsafe/dead/tampered sources, nonfinite/unbounded data, unknown scenarios, invalid categories and stale artifact hashes. Actual imported receipts are revalidated and bound to their digest/platform/scope/history instead of accepting a relabeled reference.
## Task Commits
1. Task 01-03-01 RED: `ded848f` — specify capability applicability and review navigation.
2. Task 01-03-01 GREEN: `e6713ea` — trace corrected TSK order through capability evidence.
3. Task 01-03-02 RED: `c21ed7d` — require complete game and checkpoint source coverage.
4. Task 01-03-02 GREEN: `4d07d60` — reconcile full-game capability and checkpoint coverage.
Intervening `fafbd05` is the primary's pause handoff, not another task implementation. Normal hooks ran with explicit scoped staging. No tracked production files were deleted. Main commits use the user-authorized configuration; the primary owns integration and push.
## Files and Interfaces
- `docs/evidence/capabilities.json`: schema_version 1 authoritative facts; 25 capabilities, 28 typed documentary/historical evidence records, 33 reconciliation entries, explicit evidence policy. Unimplemented workflows are honest coverage rows, not implementation stubs.
- `tools/recon/fidelity_ledger.py`: `validate_ledger(data, project, requirements=None)`, `export_ledger(...)`, `render_markdown(...)`, `select_current_evidence(records, target)` and `checkpoint_rows(path)`. Invalid input raises `ValueError`; CLI failures exit 2. Full reconciled CLI models automatically use `.planning/REQUIREMENTS.md` if the optional flag is omitted; singleton API fixtures remain renderable.
- `tests/test_fidelity_ledger.py`: 31 behavior/integration regressions, including actual imported synthetic receipts and the genuine historical startup evidence/viewer round trip.
- `docs/evidence/README.md`: generated capability-first navigation, exact current targets, expandable history, remaining acceptance and source reconciliation. It is not independently maintained status.
```sh
python3 tools/recon/fidelity_ledger.py validate --ledger docs/evidence/capabilities.json --requirements .planning/REQUIREMENTS.md
python3 tools/recon/fidelity_ledger.py render --ledger docs/evidence/capabilities.json --output docs/evidence/README.md
python3 tools/recon/fidelity_ledger.py export --ledger docs/evidence/capabilities.json --output artifacts/fidelity/review/ledger.json
python3 tools/recon/fidelity_review.py export --ledger artifacts/fidelity/review/ledger.json --output artifacts/fidelity/review/new-review
```
Viewer input uses the established capability contract and source links `{label,path,sha256?}`. It adds contained copied `href/validated_local/sha256/size/missing` fields. Ledger source text is contained, tracked, UTF-8/non-NUL and at most 1 MiB per file. Optional source hashes and actual artifact identities are checked. Generated output stays local under the project or `/tmp`, rejects symlinks, and cannot overwrite originals/Git metadata or the authoritative input. No new package dependency, service, runtime endpoint or original-binary investigation was introduced.
## Evidence and Acceptance Limits
The expansion's current evidence records are explicitly **static documentary coverage**, bound to retained report content and named documentary scopes. They do not manufacture fresh component or native receipts. Implementation revisions identify recorded code changes separately from runtime/package identity. Existing copied-original/managed/Linux scene results are described with their narrower scope. Historical package revisions remain exact: current packaged924ad2f versus earlier ea04210 Wine64 and later integrated bf876e9 source checks are not conflated. Scooter/Rocketship milestones and current bounded scene limitations remain visible.
No new game, GPU, DxWnd, Wine or Windows execution, build or package was performed. Native Linux/Windows/original reference captures and human audiovisual review remain open at **0/120 actual obligations**. Shared EVID-03 is not checked complete in REQUIREMENTS.md. The preserved TSK correction is implemented, not an untouched defect; no leveling reset, movement replacement, new gadget, actor admission or lab/outside solver replacement was made. Missing generated original/native recordings retain explicit reasons in the startup evidence rather than being dropped.
## TDD Gate Compliance
- Task 1 RED evidence: `artifacts/fidelity/tdd/01-03-01-red.json`, recorded before implementation; the real CLI-presence/round-trip target failed its intended planned behavior assertion. Existing RED/GREEN commits and the previously verified 18-test tracer were reconciled rather than repeated.
- Task 2 RED evidence: `artifacts/fidelity/tdd/01-03-02-red.json`; the named full-game set-equality target ran and failed because only two movement requirements were mapped. The actual 26-test report retains the three expected missing coverage/reconciliation/unimplemented assertions. The classifier was re-run on resume and returned `RED_EVIDENCE_OK`; semantic inspection confirms intended assertions, not setup/import failures. Final suite passes all 31 tests.
- Each RED commit precedes its GREEN by ancestry. No separate refactor was necessary. Both exact counted plan commands and full 33-ID validation pass; singleton/negative cases remain covered. No skipped tests or unrun planned automated checks remain.
## Decisions Made
One JSON source owns all navigation. Current evidence selects exact content/platform/scope, including explicitly named historical bytes; latest documentation dates do not imply newer execution. Full-game rows and source-row reconciliation expose unfinished work without expanding gameplay. Future imported receipt references require exact receipt SHA-256 plus matching platform/scope/category/history.
## Deviations from Plan
No architecture or scope change. During planned validation, report-content hash binding, ledger-wide receipt duplicate checks, complete category validation and actual imported-receipt identity matching were completed as correctness controls for T-01-07/08. These are within the planned evidence-validation boundary and commit `4d07d60`.
## Threat/Test Coverage
| Threat | Implemented controls and verification |
|---|---|
| T-01-07 | Exact named content/platform/scope targets, explicit supersession/cycles and contradictory-current rejection; changed runtime/resource/package, docs-only and imported receipt tests |
| T-01-08 | Byte-identical duplicate merging, global receipt conflicts, stable ordering and 33 hashed source-row reconciliation entries; retained linked source required |
| T-01-09 | Escaped Markdown, bounded contained tracked UTF-8 source references, actual hashes, no imported command execution; hostile source and real viewer-copy tests |
| T-01-SC | Python standard library only; no package installation |
No additional threat surface beyond the plan's existing local file/navigation boundary was introduced. Cooperative local filesystem assumptions remain; revalidate/re-export after evidence changes.
## Issues Encountered
The user-requested pause interrupted task 2 after its RED commit and 41-line patch. Resume preserved those changes, validated ancestry/evidence and completed GREEN. Primary-owned HANDOFF deletion/STATE/continuation edits and untracked `tools.yaml` were preserved. Socket/Node checks used authorized local-test escalation to avoid the known sandbox false failures/file-only results. All-fidelity log: ignored `artifacts/fidelity/verification/01-03-all-python.log`.
No implementation stubs remain. Missing real recordings and unimplemented full-game workflows are intentional transparent evidence/coverage states whose later owning plans/phases remain open.
## User Setup Required
None for these local tooling checks. The combined Windows/original/native capture and human audiovisual session belongs to later plans; no premature hands-on request was created.
## Next Phase Readiness
Plans 01-04 through 01-07 can consume the coordinated ledger and provide real observer/checkpoint/capture receipts. The primary owns root continuity documents, consumed handoff cleanup, wave regression checks and push. Full-game and phase acceptance remain separate from this completed ledger implementation.
## Self-Check: PASSED
All four created files exist; all four task commits are ancestors of HEAD and evaluation-scope resolves them on this branch. Both exact counted plan checks, full 33-requirement/six-group/33-row validation, real CLI/viewer round trip, 103 fidelity Python tests, 27 named Node tests, whitespace checks and 539 original hashes pass. No tracked production deletions, skipped tests, placeholder implementation or unexplained generated untracked output was introduced.
@@ -0,0 +1,197 @@
---
phase: 01-reproducible-fidelity-baseline
plan: "04"
subsystem: testing
tags: [dotnet, passive-observation, jsonl, sdl, vulkan, provenance]
requires:
- phase: 01-01
provides: Version 1 receipts and separately classified scenario observations
provides:
- Optional bounded application observer with requested/accepted input and immutable state snapshots
- One launch clock and ordered departure/arrival records across retained scene composition
- Explicit script/skip/control methods, incomplete failure summaries and observer-on/off regressions
affects: [01-05, 01-06, 01-07, native-capture]
tech-stack:
added: []
patterns: [standalone net10 console tests, streamed bounded UTF-8 JSONL, snapshot-only application diagnostics]
key-files:
created:
- src/GamePort/Application/FidelityObservation.cs
- tests/GamePort.FidelityObservationTests/GamePort.FidelityObservationTests.csproj
- tests/GamePort.FidelityObservationTests/Program.cs
- tests/test_fidelity_observation.py
modified:
- src/GamePort/Program.cs
key-decisions:
- "One outer observer owns a unique launch/clock identity through Run continuations; simulation ticks remain scene-local and case/session IDs remain declared provenance."
- "Accepted input means the existing binding's returned gate result, with separately identified post-step ownership; individual command dispatch and independent body/fire work are not inferred."
- "Observer records are diagnostic source material for later collectors, not receipts or automatic original/native acceptance; fixture classification survives continuations."
patterns-established:
- "Copied values only: no simulation references, gameplay callbacks, setters, extra steps or recovery resets enter the observer."
- "Caller-selected new local output supports standalone checkpoint/transfer folders while rejecting protected asset/Git overlap, aliases, symlink ancestry and reused sessions."
requirements-completed: [EVID-02, EVID-04]
requirements-acceptance: "OPEN: assigned observation contribution only. Shared requirements remain Pending; actual original-DxWnd/native Linux/native Windows comparison acceptance remains 0/120."
coverage:
- id: observer-semantics
description: Bounded requested/accepted input, identity, clocks, disposal and output failure preserve simulation behavior
requirement: EVID-02
verification:
- kind: unit
ref: tests/GamePort.FidelityObservationTests/Program.cs
status: pass
- kind: integration
ref: tests/test_fidelity_observation.py
status: pass
human_judgment: false
- id: retained-observation
description: Real port fixture publishes LV1B to VR04 to LV1B with one ordered launch clock and paired departure sequences
requirement: EVID-04
verification:
- kind: integration
ref: tests/test_fidelity_observation.py#test_retained_continuation_keeps_one_ordered_session_clock
status: pass
human_judgment: false
- id: passive-runtime-comparison
description: Existing bounded headless and native SDL Carl fixtures preserve exact state and four GPU readbacks with observation on/off
verification:
- kind: integration
ref: tests/test_fidelity_observation.py#test_observed_off_fixture_state_and_readbacks_match
status: pass
- kind: other
ref: artifacts/fidelity/verification/01-04-native-1794543576213164551/comparison.json
status: pass
human_judgment: false
- id: actual-scenario-acceptance
description: Identified ordinary full-route original/native audiovisual comparison
verification: []
human_judgment: true
rationale: "Injected fixtures, observer traces and compilation do not supply ordinary play, physical audio/input or native Windows/original-DxWnd review; later capture plans retain these obligations."
actuals:
tokens: 13375
tasks: 2
commits: 4
basis: "ceil(chars/4) over the realized five-file production/test diff (53497 characters), excluding planning metadata; commits measured from the persisted ledger."
plan_head_before: e8155348950e997462f4d097a0e323c7f17b75fb
plan_head_after: ea4dc9b5dfb84b1d590dae049cabb4a262a5138c
duration: 16 min
started: 2026-11-13T04:04:37Z
completed: 2026-11-13
status: complete
---
# Phase 01 Plan 04: Passive Port Observation Summary
**Bounded JSONL observations preserve requested input, the real accepted-input gate, control changes and retained scene identity without changing player ownership or movement.**
## Performance
- Two tasks, five production/test files, four measured task commits. Started 04:04:37 UTC; final production verification/commit completed about 04:20 UTC, 2026-11-13.
- Final focused verification: **23 managed checks**, **7 Python process/interoperability tests in 19.126 seconds**. The tracer passed 10 managed/four process checks and repeated its automated gate before expansion.
- Protected projects: **Movement 28**, **Director 23**, **Checkpoint 4**, **BodyOwnership 3** actual passing groups. Existing projects without aggregate totals were additionally captured and counted from their executed PASS lines in `artifacts/fidelity/verification/01-04-protected.json` and per-project logs.
- Debug build and isolated self-contained Linux x64 Release publish succeed. The existing NU1900 warning concerns unavailable NuGet vulnerability metadata; no package was added or installed. All **539 original hashes** match.
## Accomplishments
- `FidelityObservation` is allocated once beside the outer presentation lifetime and passed through `Run`. A unique `launch_id`/`clock_id`, one Stopwatch and increasing sequence survive actual continuations. Simulation ticks remain explicitly separate and can reset at scene entry. Fresh observer instances get independent launch clocks even if a caller mistakenly repeats its declared session ID.
- The ordinary application input seam records the constructed `PlayerInput` and the actual `playerBinding.Step` return, or the existing direct simulation path. It copies post-step root, Euler, velocity, grounded/mode, retained-order flag and controller/body/effect counters. No recovered gameplay algorithm, orientation/reset policy, callback getter, actor admission or solver changed. Disabled observation allocates no observer or additional asset lookup; snapshots execute only through the optional observer path.
- SDL events are labeled raw before routing; only applicable keyboard/mouse union fields are copied. Requested input, returned gate and post-step control owner remain distinct. Script activity/control snapshots surround existing director calls. Explicit skip methods include startup/fixture, debug menu and actual SDL key paths; a playing-to-stopped boundary during the normal director step is identified as `natural_director_step`, without elapsed-time guesses.
- Scene composition records its actual entry path and retained-player/RETURN facts. Published continuations record departure source/destination and RETURN status; each following entry links the actual `departure_sequence`. The real existing fixture emits **LV1B → VR04 → LV1B**, retains one session/category/clock, and records two paired departures. This proves observer wiring through ordinary composition using fixture-owned setup; it is not ordinary-route acceptance.
- Output failure disables recording, retains an incomplete summary/stderr diagnostic and permits the existing game calls to continue. The managed failure regression compares 120 actual `LabSimulation` steps with failed observation versus off, including exact root/Euler/velocity and controller/body/effect counts. On/off headless and native SDL fixtures additionally preserve the existing locked body/fire/energy, first-neutral/300-idle assertions and held-input restoration.
## Task Commits
1. Task 01-04-01 RED: `773c228` — specify passive port input observation.
2. Task 01-04-01 GREEN: `72523ee` — observe accepted input with bounded passive output.
3. Task 01-04-02 RED: `6bccd47` — require retained session and dialogue observation.
4. Task 01-04-02 GREEN: `ea4dc9b` — preserve observer identity through control and scene changes.
Normal hooks ran, scoped staging preserved `tools.yaml`, and no tracked files were deleted. Main commits use the authorized configuration; the integrating primary owns push and root continuity reports.
## Files and Interfaces
- `src/GamePort/Application/FidelityObservation.cs`: optional `FromArguments`/`Create`, `RecordInput`, `RecordControl`, `RecordTransition`, `RecordSceneEntry`, `RecordRawEvent`, `RecordState`, `Complete` and `Dispose`. It holds copied diagnostic values and output ownership only.
- `src/GamePort/Program.cs`: optional CLI flags, one outer observer and post-owner/input/control/continuation seams. Skip and director-step wrappers preserve the original call and surrounding order. Existing helper-internal fixture steps remain outside this trace.
- Standalone `tests/GamePort.FidelityObservationTests` links focused observer plus existing assets/game sources, uses net10.0 and adds no packages. Its 23 Linux checks cover disabled operation, IDs/clocks, requested/rejected/accepted neutral input, ownership/ticks, bounds, write/flush/disposal failure, duplicate/unsafe output, real simulation parity and retained/fresh sequencing. Two symlink checks are Linux-specific; this run is not native Windows validation.
- `tests/test_fidelity_observation.py`: seven actual-port subprocess checks, hashed receipt interoperability, rejected fixture promotion/missing output, retained composition, explicit skip semantics and exact four-image/state equivalence. It builds current source before launching the actual DLL; if generated fixture resources are absent, it uses the existing local preparation command because the consolidated script runs Python before its own extraction step.
Example diagnostic invocation, with a **new** output directory:
```sh
source scripts/env.sh
dotnet run -- --fidelity-output artifacts/fidelity/new-session \
--fidelity-session unique-launch-session --fidelity-case fresh-natural-ordinary
```
IDs accept 1–128 safe alphanumeric/dot/underscore/hyphen characters. The output directory is caller-selected and need not live in a checkout: standalone package checkpoint results and local transfer folders work. Known original/source asset roots and Git metadata cannot overlap output in either direction. Protected asset aliases are resolved; output symlink ancestry and existing directories/files are rejected. A cooperative exclusive sibling reservation and `CreateNew` owned files prevent session reuse. Hostile concurrent filesystem replacement is outside this cooperative local model.
`events.jsonl` schema 1 fields are `session_id`, `case_id`, `evidence_kind`, unique `launch_id`, `clock_id`, increasing `sequence`, `elapsed_seconds`, separate `simulation_tick`, `name`, `scene`, `method` and immutable `data`. Names include `input_step`, `player_state`, `raw_sdl_event`, `control_observation`, `dialogue_start`, `dialogue_end`, `dialogue_skip`, `scene_departure` and `scene_entry`. Dialogue markers describe observed director script activity and explicit action paths, not inferred per-utterance audio timing. `accepted_input` copies the request only when the existing gate returned true; it does not assert that each input field dispatched an action. Independent body/fire work can continue when that gate is false.
`observation-summary.json` records UTC start/end, elapsed/clock identities, count/bytes, limits, completion/failure and overhead scope. It begins incomplete, remains incomplete after abort/error/bounds/disposal without completion, and is atomically updated after successful flush. A write failure never asks gameplay to retry, reset or step. If even the summary cannot be written, stderr explicitly reports that failure; a reserved prior incomplete summary is never promoted.
The writer uses a 64 Ki-character StreamWriter buffer, no growing record queue, at most **250000 records / 512 MiB**, and normalized UTF-8 LF output. These bounds can truncate long diagnostic sessions explicitly. `observer_seconds` measures serialization/write attempts only; caller snapshots, control comparisons, final flush and summary work are excluded, and this limitation is in provenance. No trace is represented as a clean, zero-overhead audiovisual run.
These are observer records, not shared receipt objects. The later collector must identify actual artifacts and map actual media clocks with uncertainty. Tests build an explicitly bounded `port_fixture` receipt from the trace interval, hash the actual trace, and validate it through the existing schema-1 receipt contract without changing that shared module. They do not invent a video/audio clock or promote native acceptance.
## Native Linux Evidence and Limits
Final evidence: `artifacts/fidelity/verification/01-04-native-1794543576213164551/comparison.json`, on/off `port.log`, eight retained PPM files and the actual observation directory. Both native SDL/Vulkan runs use a private Xvfb X11 display on **NVIDIA GeForce GTX 1070**, enabled validation, 32 frames and **zero Vulkan validation errors**. The existing injected Carl control fixture is muted; both runs exit 0. All four corresponding readbacks are byte-identical:
| Readback | SHA-256 |
|---|---|
| locked-start | f0d76654f1196534da20b7cf9a39c5e58931acb7f0aa22d349e87dad6ce176a2 |
| locked-fall | f0819d2dd9a43ff17b339be2bb3b487c3a94c4683e951015f38cd9b4f7c12e38 |
| returned | 642e15ad552c1c5819f41faf7b1bcbb9106462a26b6786753dd2f87f90cf4229 |
| final | e0e71f3c7f187149fc1b5b9d8c7fb7ff694f5ae3f27275a20948543a4f55fdfa |
The final observed run records **88 records / 65308 bytes**, 1.6721105 session seconds and 0.0365354 measured serialization/write seconds. Whole process durations are 1.5783 seconds off and 1.8555 seconds on; a single ordered pair is not an overhead benchmark. Actual Debug DLL SHA-256 is `778a1827d22c5359216c546b1841cea20fffca6a4bece2266a58057c8d24a348`, 776704 bytes. The report retains the actual pre-commit source identity: HEAD `6bccd47`, dirty true, diff SHA-256 `83eac9c22938f1f8d01200027e2fa3aefbe4ba123a9c58dc7bb6a7d9ce5ac33d`, plus unrelated preserved `tools.yaml` identity. Task GREEN commits that tested source; no clean-runtime claim is inferred from the later commit.
Exact state assertions and readbacks preserve the existing TSK first-story ordering correction, grounded neutral return, heading and legitimate source landing behavior. The fixture's deliberate preparatory calls remain fixture setup, not a newly invented reset. Full original playback, physical input/audio, ordinary full-route play, native Windows and broader platform compatibility remain unverified by this plan. **Actual matrix acceptance remains OPEN 0/120.** Plan 01-06 owns native full-route capture; Windows/original collection and review remain later work.
## TDD Gate Compliance
- Task 1: `artifacts/fidelity/tdd/01-04-01-red.json` contains the actual complete unittest report. The real port help succeeded but the named target failed its intended missing `--fidelity-output` assertion. Classifier result: `RED_EVIDENCE_OK`; semantic inspection confirms a planned behavior assertion rather than build/import/setup failure. The tracer's exact focused checks were repeated before expansion.
- Task 2: `artifacts/fidelity/tdd/01-04-02-red.json` contains the actual complete report. The existing real RETURN fixture succeeded, then the named target failed `[] != ['LV1B', 'VR04', 'LV1B']` because scene-entry observations were absent. Classifier result: `RED_EVIDENCE_OK`; semantic inspection confirms the intended sequencing assertion executed. Final 23 managed/seven process checks pass.
- Both RED commits precede their GREEN by ancestry. No separate refactor was required. No skipped/todo tests or unrun planned automated checks remain.
## Deviations from Plan
No architectural or gameplay scope change. Two bounded correctness adjustments remain within the planned application/test boundary:
1. **[Rule 2 — protected output]** Resolve source asset aliases and protect the checkout's known authoritative sibling even when `--assets` points to a generated copy. Otherwise lexical overlap alone could miss the original boundary. Managed source/output alias negatives pass; `ea4dc9b`.
2. **[Rule 3 — fixture preconditions]** Process tests build the current actual port and prepare missing generated resources through the existing extractor. The consolidated script schedules Python before its normal preparation/build steps; assuming prior generated files would make a clean test environment fail. No shared script or extractor was modified; `ea4dc9b`.
## Threat/Test Coverage
| Threat | Controls and actual verification |
|---|---|
| T-01-10 | New exclusive contained output, protected resolved asset/Git boundaries, symlink/reuse negatives, immutable values only; exact 120-step failed-writer parity and headless/native four-readback equivalence |
| T-01-11 | Fixed buffering, record/byte caps, incomplete initial/failure summaries, flush/disposal failure handling; managed bounds and exception regressions |
| T-01-12 | Distinct raw/requested/gate/post-step owner fields, actual director action methods, unique launch clock, ordered retained entries/departures, persistent fixture classification; process and shared-validator negatives |
| T-01-SC | Existing .NET framework/runtime, Python stdlib and already-installed native tools only; no added packages, services or downloads |
The new filesystem surface is exactly the plan's runtime-observation/local-output boundary; no additional network/auth/gameplay trust surface was introduced. Stub scan found only intentional optional/absent fields and test-only empty receipt identities, not unfinished implementation or UI mock data.
## Issues Encountered
The sandboxed first native-display attempt reported no video device. Authorized local-test escalation with explicit X11 on private Xvfb succeeded; both attempts remain in ignored diagnostics. A second `-o` passed to `scripts/build-linux.sh` was rejected by the .NET CLI, so the equivalent publish invocation used an isolated output to preserve existing `dist/` packages:
```sh
source scripts/env.sh
dotnet publish GamePort.csproj -c Release -r linux-x64 --self-contained true \
--no-restore -o artifacts/fidelity/verification/01-04-linux-publish
python3 tools/recon/inventory.py ../Original --verify docs/original-manifest.json
```
Both commands pass on final code. Existing packaged runtime outputs were not replaced. NU1900 remains a pre-existing offline audit warning, not an observer failure. No new original-binary investigation, REA claim, Wine result or native Windows execution occurred.
## User Setup Required
None for these local checks. The later combined original/native recording and human audiovisual review session remains open; this plan creates no premature hands-on request.
## Next Phase Readiness
Plans 01-05/01-06 can launch the optional observer into a new checkpoint result directory and consume its honest trace/summary while binding actual package/artifact/media provenance separately. The primary owns root progress/tasks/decisions/compatibility integration, broader wave checks and push. Shared EVID-02/EVID-04 remain Pending until all owning plans and actual acceptance conditions close.
## Self-Check: PASSED
All created files exist; all four task commits are ancestors of HEAD and evaluation-scope resolves them on this branch. Exact counted observer commands, positive protected groups, Debug/isolated Linux publish, final native state/four-readback equality and 539 original hashes pass. Native JSONL byte count matches the summary's actual file size. No tracked deletions, skipped tests, implementation stubs or unexplained generated untracked files were introduced; unrelated `tools.yaml` is preserved.
@@ -0,0 +1,166 @@
---
phase: 01-reproducible-fidelity-baseline
plan: "05"
subsystem: testing
tags: [offline, powershell, windows, fidelity, sha256]
requires:
- phase: 01-02
provides: Offline paired review viewer
- phase: 01-03
provides: Capability ledger and identified source links
- phase: 01-04
provides: Passive port observation and package flags
provides:
- Immutable offline checkpoint with identified original and Linux/Windows packages
- Complete eighty-obligation Windows agenda with separate original-DxWnd and native-port collection
- Package-free PowerShell selftests and truthful terminal/media results
affects: [01-06, 01-07]
tech-stack:
added: []
patterns: [exclusive allocation, bounded hashing, atomic publication, explicit open acceptance, inert argument provenance]
key-files:
created:
- tools/recon/fidelity_checkpoint.py
- scripts/prepare-fidelity-checkpoint.sh
- scripts/collect-fidelity-windows.ps1
- scripts/collect-fidelity-windows.cmd
- tests/test_fidelity_checkpoint.py
- tests/fidelity-windows.Tests.ps1
- docs/evidence/windows-session.md
modified: []
key-decisions:
- "READY validates immutable prepared materials only; actual original-DxWnd/native Linux/native Windows acceptance remains open 0/120."
- "Runtime package source/dirty/diff identity stays bound to its actual completed publish, separately from later collector and document commits."
- "Selected external tools are identified without redistributing executables; raw MKV, terminal failures and actual derivation provenance remain local."
requirements-completed: [EVID-01, EVID-02, EVID-04]
requirements-acceptance: "OPEN: assigned preparation contributions are complete; shared requirement IDs remain Pending until unfinished sibling capture/review plans and actual acceptance gates close."
coverage:
- id: offline-checkpoint
description: Identified complete offline bundle, preservation and tamper checks
requirement: EVID-01
verification:
- kind: integration
ref: tests/test_fidelity_checkpoint.py
status: pass
- kind: other
ref: artifacts/fidelity/verification/01-05-complete-bundle.json
status: pass
human_judgment: false
- id: collection-tooling
description: Package-free collector identity/path/argument/process/result functions on synthetic fixtures
requirement: EVID-02
verification:
- kind: integration
ref: tests/fidelity-windows.Tests.ps1
status: pass
human_judgment: false
- id: combined-session-materials
description: Eighty Windows obligations, session instructions and settings/annotation templates are bundled
requirement: EVID-04
verification:
- kind: integration
ref: tests/test_fidelity_checkpoint.py#test_complete_session_materials_and_eighty_windows_obligations
status: pass
human_judgment: false
- id: actual-original-native-acceptance
description: Actual original-DxWnd/native Windows execution, audiovisual preflight and full scenario review
verification: []
human_judgment: true
rationale: "Linux-hosted synthetic PowerShell tests, prepared bytes and apphost help do not establish Windows gameplay, actual browser/audio playback or whole-original fidelity; plan 01-07 owns the combined session."
actuals:
tokens: 21862
tasks: 2
commits: 7
basis: "ceil(chars/4) over the realized seven-file production/test/document diff: 87448 characters. Measured ledger range includes five plan task commits plus the intervening primary handoff and quota-guard commits; no invented task-commit count."
plan_head_before: de68796df15acaacbc7df1ae5701acac770680ce
plan_head_after: aa4b862a123112085660ee14fc0e2bccb251ddfa
duration: 12h 4min
started: 2026-11-13T04:40:08Z
completed: 2026-11-13
status: complete
---
# Phase 01 Plan 05: Offline Windows Checkpoint Summary
**An identified 10,983-file offline checkpoint carries preserved originals, both actual port packages, review/protocol materials and a complete Windows original-DxWnd/native-port collection agenda with open acceptance.**
## Performance
- Two tasks, seven production/test/document files. The recorded wall interval starts at the earliest task RED commit, 04:40:08 UTC, and includes the long quota interruption before task 2 resumed. It is not twelve hours of active execution.
- Final targeted verification: **24 Python checkpoint tests**, **17 actual Linux-hosted PowerShell checks**, four PowerShell-produced synthetic receipts validated by the shared Python validator, shell syntax and **539 unchanged original files**.
- The broader fidelity regression passed **133 tests in 123.784 seconds** with authorized local loopback/process access before the final mode-only correction; the affected checkpoint suite then passed all 24 tests in 4.742 seconds. No skipped tests are represented as passes.
- Actual full-bundle Python and Linux-hosted PowerShell preflights both pass, checking 10,983 immutable entries. The PowerShell traversal took several CPU-active minutes and completed before its explicit 600-second supervisory bound. It did not wait for interactive input.
## Accomplishments and Interfaces
- `fidelity_checkpoint.py` seals actual completed publishes, prepares a fresh offline tree and preflights immutable file identities. Existing outputs, overlaps, aliases, tampering, stale DLLs, interrupted/concurrent assembly and missing dependencies are rejected with local diagnostics. The generated original seed is verified before copying and again against its authoritative inventory. Hashes stream; assembly uses an exclusive reservation and retains incomplete diagnostics on failure.
- The bundle contains `manifest.json`, `READY.json`, `original-pristine/`, `original-runs/`, `port/linux-x64/`, `port/win-x64/`, `review/`, `protocol/`, `results/`, both collector launchers, the session guide and standalone PowerShell selftests. Protocol materials include scenarios, capabilities, original inventory, an **80-obligation Windows agenda** and explicit pending settings/annotation templates. Empty/false fields require actual observations during the later session; they are not fabricated identities or implementation stubs.
- `collect-fidelity-windows.ps1` supports `Preflight`, `Run`, `Retained`, `Finish`, `Skip` and `Abort`. Native port and original-DxWnd receipts keep distinct categories. It identifies actual selected external tools without copying third-party executables/installers, preserves the user's profile plus generated original pre/post state, uses quoted direct process invocation and records honest exit/log information. No original is executed in place, no command from a receipt is evaluated, and no dependency is downloaded.
- Raw MKV and actual audio evidence are required to finalize captured results. Derived artifacts retain source/output references, actual tool/version/argv/time/crop metadata and explicit browser-playback declaration. Synthetic promotion, terminal-outcome promotion, reused results and invalid references are rejected. Failed/skipped/aborted results remain available for collection without inventing successful media. All collector outputs retain open acceptance and require the shared validator and later human review.
- `windows-session.md` gives one ordered agenda: local selections/provenance, package-free checks, separate original/port visual/audio preflights, all eight matrix cells and five obligations, paired browser/exclusive-audio review, collection/postflight, then one local return transfer with hash checks. It recommends offline OBS Display Capture initially while requiring actual selected settings. It does not request capture now.
## Task Commits
1. Task 1 RED: `446930d` — specify immutable offline checkpoint round trip.
2. Task 1 GREEN: `6112339` — assemble identified offline Windows checkpoint.
3. Task 2 RED: `818191c` — require complete Windows session materials and open results.
4. Task 2 GREEN: `8574665` — complete offline Windows collection agenda and selftests.
5. Task 2 correctness follow-up: `aa4b862` — retain executable permissions in offline copies.
Task 1 was already complete and was not repeated during recovery. The partially edited collector and checkpoint module were preserved and completed. Normal Git hooks ran with explicit scoped staging, protected-branch configuration and the supplied-root guard; no tracked files were deleted. Unrelated `tools.yaml`, the primary's quota tooling commit `c9b9f2e` and its ownership were preserved. The primary owns review, integration reports and push.
## Actual Offline Bundle and Package Identities
Fresh final bundle: `artifacts/fidelity/01-05-session-checkpoint`. Durable identity/audit evidence: `artifacts/fidelity/verification/01-05-complete-bundle.json`.
| Material | SHA-256 |
|---|---|
| manifest.json, 2,689,788 bytes | `1098cf07030d5acf71b37d2132ec8bf39360855e9f7b2203cd130c9a7ac011be` |
| READY.json, 358 bytes | `1bb81a44da9f5ce92d5549f1608fcc6f46a47e2010d5160b39dcb471d1e8cccd` |
| Original 539-file canonical tree | `419af98a75a9f1d4ae3eceb5c7807bc9634912c2c3918c308470ad798dcef181` |
| Linux sealed package file-list hash | `124cf271e4952f3822eec5c24358447fcffc9e9e1803aded8d96d4d4472dc5a3` |
| Windows sealed package file-list hash | `335e5b75ec15c0fa904113d8b69d4f50e2cfa403f1f2f225353bd9e586322ef4` |
| Linux GamePort.dll, 734208 bytes | `145de80f2628f836cd77f0e8f66cb1b9d5abb8445088ff8ba8eb82527b6cd150` |
| Windows GamePort.dll, 734208 bytes | `d21c917c1d260f3cd2c5b3d19397ab78ae23108c90b4f393eba4904d80e512a1` |
Both packages already existed under `artifacts/fidelity/01-05-packages`; recovery did not rebuild them. Their actual BUILD-INFO identifies source `446930d2a30d6d616c60ac5e59e4169a840bea09`, **dirty yes**, diff SHA-256 `90cef95669caece53fe2d2c4736cf2ac05ed27f5d25ca03ab572589686bcb73d`. Publish timestamps are 2026-11-13T04:45:41.527524+00:00 and 04:47:05.457630+00:00 respectively. Neither the resumed collector revision nor the later clean task commit is stamped over that runtime provenance. Historical `dist/` packages remain unchanged.
The final copied Linux apphost was permission-repaired from its byte-identical package source to mode 0755, then actually ran `--help` successfully. The generator now preserves ordinary source permissions for future copies while dropping privileged mode bits. That permission-only repair changes no manifest/file byte identity. Apphost help establishes startup/CLI availability only, not gameplay, sound, GPU or platform acceptance.
## Verification Commands and Scope
```sh
python3 -c 'import sys,unittest; s=unittest.defaultTestLoader.discover("tests",pattern="test_fidelity_checkpoint.py"); assert s.countTestCases() >= 16; sys.exit(not unittest.TextTestRunner(verbosity=2).run(s).wasSuccessful())'
bash -n scripts/prepare-fidelity-checkpoint.sh
python3 tools/recon/inventory.py ../Original --verify docs/original-manifest.json
python3 tools/recon/fidelity_checkpoint.py preflight --checkpoint artifacts/fidelity/01-05-session-checkpoint
```
The cached `.tools/powershell-check/root/opt/microsoft/powershell/7/pwsh` is usable with `XDG_CACHE_HOME`, `XDG_CONFIG_HOME` and `XDG_DATA_HOME` set to task-local `/tmp/gameport-pwsh-*` directories. Its default home cache is read-only in the sandbox. No install/download was performed. Actual commands used that executable with `-NoProfile -File tests/fidelity-windows.Tests.ps1 -FixtureOutput /tmp/gameport-01-05-ps-results` and separately `-NoProfile -File scripts/collect-fidelity-windows.ps1 -Action Preflight -Bundle artifacts/fidelity/01-05-session-checkpoint`.
The 17 selftests exercise IDs/paths, hashes/copy identity, arrays/write-once JSON, argument quoting, an actual child with spaced arguments and exit 7, stdout/stderr, timeout/start failure, categories/terminal outcomes, manifest tampering and finish links. Their four captured/failed/skipped/aborted receipts all validate structurally through `fidelity_receipts.validate_receipt`; **all four remain synthetic and unaccepted**. Linux PowerShell is not Windows PowerShell 5.1 execution evidence. The exact native Windows selftest command is included in the future combined agenda.
## TDD Gate Compliance
Both retained RED reports, `artifacts/fidelity/tdd/01-05-01-red.json` and `01-05-02-red.json`, return `RED_EVIDENCE_OK` through the current classifier. Task 1's named target executes its intended missing preparation-API assertion. Task 2's named target completes assembly then fails the planned missing-session-material assertion; its separate missing status-API error remains honestly recorded. Both RED commits precede their GREEN commits by ancestry. No separate refactor was needed. Final targeted tests pass.
## Deviations from Plan
1. **[Rule 1 — collector correctness]** Real PowerShell execution exposed top-level empty arrays serializing incorrectly and asynchronous .NET completion values leaking into the process-result pipeline. `Write-FidelityJson` now uses `ConvertTo-Json -InputObject`; asynchronous completions are suppressed, output closure is bounded and final log size is checked. Standalone serialization/process/terminal tests pass; `8574665`.
2. **[Rule 2 — runnable offline copy]** Final bundle inspection found that byte-only copying dropped Linux apphost execution permission. The generator now preserves ordinary source mode bits, and a regression checks both mode and bytes. The generated apphost was repaired from its verified source and ran help; `aa4b862`. No source/package bytes or gameplay algorithms changed.
No new trust surface beyond the plan's selected-process/local-filesystem boundaries was introduced. The supplied threat mitigations remain applicable: no eval/elevation/downloads, explicit local selections, contained paths, hashes, immutable result IDs and categories that cannot imply acceptance. No implementation stub or skipped mandatory automated verification remains; actual Windows/human checks are intentionally assigned to the later combined session.
## Issues Encountered
Quota interruption required a specific task-2 recovery from the existing RED commit and partial edits. An accidentally duplicated slow preparation was stopped; its incomplete directory and reservation remain under `.01-05-complete-checkpoint*` as diagnostics, and the final assembly uses a new root. No lock was stolen or failed partial tree promoted. The sandboxed broader regression denied loopback sockets and timed out .NET setup; its authorized local rerun passed all 133 tests. The optional full PowerShell preflight was CPU-active and bounded, then passed. No unresolved test failure is hidden by these environment adaptations.
## Next Phase Readiness
The full bundle and session tooling are prepared. Plan 01-06 still owns actual native Linux capture, and plan 01-07 owns the combined original-DxWnd/native Windows session and audiovisual review. The real scenario audit is structurally ready with **accepted 0 / required 120**, all eight cases missing and no invalid receipts. Original launch/profile validity, native Windows execution, real browser playback/audio/crop and full-route fidelity remain open. This plan makes no new original-binary, REA, Wine, native Windows gameplay or whole-original compatibility claim.
Shared EVID-01/EVID-02/EVID-04 IDs remain Pending because `requirements.ready-ids` returns no ready IDs while sibling plans are unfinished. Root progress/tasks/decisions/compatibility integration and consumed-handoff cleanup belong to the primary.
## Self-Check: PASSED
All seven created files exist. All five plan task commits are reachable on this branch, and evaluation-scope resolves the recorded plan commits. Final counted checkpoint/PowerShell checks, shared receipt validation, both full-bundle preflights, shell syntax, Linux apphost help and 539 original hashes pass. The persisted ledger measures seven commits before summary metadata, including the two intervening primary commits explained above. No generated package/media/original is staged, no tracked deletion occurred, and unrelated `tools.yaml` is preserved.
@@ -0,0 +1,200 @@
---
phase: 01-reproducible-fidelity-baseline
plan: "06"
subsystem: testing
tags: [linux, fidelity, capture, ffmpeg, provenance]
requires:
- phase: 01-01
provides: Typed receipts and eight-cell scenario contract
- phase: 01-02
provides: Local paired review export
- phase: 01-04
provides: Passive runtime observer
- phase: 01-05
provides: Identified sealed Linux checkpoint package
provides:
- Bounded local Linux preflight/run/collect and immutable receipt import
- Forty Linux obligations with exact open dependencies and verified attempt history
- Actual host failed-preflight receipt and local review export
affects: [01-07]
tech-stack:
added: []
patterns: [fresh output allocation, owned child deadlines, sealed package checks, explicit open acceptance]
key-files:
created:
- tools/recon/fidelity_capture.py
- scripts/collect-fidelity-linux.sh
- tests/test_fidelity_capture.py
- docs/evidence/linux-session.md
modified: []
key-decisions:
- "A real host with no display and only auto_null audio yields failed native preflight, never synthetic replacement gameplay."
- "One common failed environment dependency can explain all forty open Linux obligations without inventing forty game launches."
- "Retry history revalidates actual saved receipts and requires new launch/session IDs; focused captures never substitute for the continuous journey."
requirements-completed: [EVID-01, EVID-04]
requirements-acceptance: "OPEN: conditional tooling/preparation contributions complete; actual native physical/audible acceptance remains 0/40 Linux and 0/120 overall. Shared IDs remain Pending while plan 01-07 is unfinished."
coverage:
- id: linux-collector
description: Bounded process/media doubles, actual receipt import and classification
requirement: EVID-04
verification:
- kind: integration
ref: tests/test_fidelity_capture.py
status: pass
human_judgment: false
- id: linux-matrix
description: Eight cells and forty continuous/focused obligations with retained/fresh history
requirement: EVID-01
verification:
- kind: integration
ref: artifacts/fidelity/linux/01-06-matrix.json
status: pass
human_judgment: false
- id: actual-native-capture
description: Actual moving gameplay, physical input, real audible output and original/native comparison
verification: []
human_judgment: true
rationale: "Actual host preflight found no display session and only auto_null audio. All physical/audible and full-route obligations remain assigned to the final combined session."
actuals:
tokens: 14371
tasks: 2
commits: 4
basis: "ceil(chars/4) over the realized four-file production/test/procedure diff: 57484 characters; persisted ledger measures four task commits before summary metadata."
plan_head_before: 31ae6a6ab2ab1c342361de376a8756dafafb8227
plan_head_after: 0172916ffd9e3120e57c87c3bd853965f3e4d196
duration: 14 min
started: 2026-11-13T16:49:00Z
completed: 2026-11-13
status: complete
---
# Phase 01 Plan 06: Linux Capture and Open Native Matrix Summary
**A bounded FFmpeg collector preserves package identity, failed native preflight and all forty Linux obligations without substituting synthetic gameplay.**
## Accomplishments
Both conditional plan tasks are complete. The collector provides `preflight`,
`run`, `collect` and `matrix`; the shell launcher does no build, download or
dummy-device fallback. It validates the sealed existing package/resources,
records OS/tools/hash/device/GPU information, and supports installed X11/Pulse
recording with normal `NewGame.tsk --walk` entry and passive observer. Actual
runtime SDL/active GPU/Vulkan versions remain unavailable without a game launch.
Fresh contained output, inert argument arrays, selected local sources, bounded
metadata/log/media sizes, one deadline and owned-child cleanup implement the
plan's process/filesystem trust boundaries. Raw lossless FFV1/PCM MKV, media
probes, logs, clocks and prelaunch identities survive collection/import. Media
emptiness, missing streams, frozen indicators, interrupted/failed children and
post-launch package changes keep observations incomplete. No automatic acceptance,
retiming, volume adjustment or gameplay/movement change was introduced.
The matrix enumerates each lifetime/dialogue/input cell and all five obligations,
including exact events/procedures and continuous lab → VR04 → lab → outside.
Saved retry history is hash-checked; a new attempt needs a new launch/session ID.
Annotations bind contained prerequisite recordings and actual copy-state identity
records without promoting them to physical/audible review. The Linux procedure
joins the single later Windows/original combined agenda.
## Task Commits
1. Task 1 RED: `9c59f60` — require bounded Linux capture round trip.
2. Task 1 GREEN: `16f5e12` — collect bounded Linux capture and honest failed preflight.
3. Task 2 RED: `e17cfbe` — require full Linux matrix continuity and resume history.
4. Task 2 GREEN: `0172916` — preserve full Linux obligation matrix and capture history.
Normal hooks and the supplied-root/protected-branch checks ran. The primary
explicitly authorized recovery after my first guard extraction omitted its bound
assignment; the complete literal guard then passed before any write. No root drift,
tracked deletion, runtime edit or unrelated `tools.yaml` change occurred. Primary
owns integration reports and push.
## Actual Execution and Package Identity
The outside-sandbox host probe found a TTY session, no `DISPLAY`/`WAYLAND_DISPLAY`
or X11 socket, no resolved Xvfb/OBS command and only suspended PipeWire Pulse
`auto_null`/`auto_null.monitor`. FFmpeg/ffprobe are installed distribution version
`6.1.1-3ubuntu5+esm15`; local help confirms the selected frozen-frame filter.
`lspci` succeeded; `vulkaninfo` is absent. The exact observations/tool hashes and
selected settings are retained. No game/recorder was launched, and no raw
video/audio or observed gameplay/input event was fabricated.
The existing package `artifacts/fidelity/01-05-packages/linux-x64` was reused,
without publish or bulk copying. Its file-list hash remains
`124cf271e4952f3822eec5c24358447fcffc9e9e1803aded8d96d4d4472dc5a3`.
Its actual source is `446930d2a30d6d616c60ac5e59e4169a840bea09`, dirty yes,
diff `90cef95669caece53fe2d2c4736cf2ac05ed27f5d25ca03ab572589686bcb73d`;
the collector revision never replaces that runtime provenance.
| Evidence | Exact local result |
|---|---|
| Task-1 diagnostic | `artifacts/fidelity/linux/01-06-focused-preflight/receipt.json`, ID `linux-01-06-focused-preflight-linux`, failed/open |
| Current typed dependency | `artifacts/fidelity/linux/01-06-matrix-preflight/receipt.json`, ID `linux-01-06-matrix-preflight-linux`, failed/open |
| Current applicable import | `artifacts/fidelity/linux-current-receipts/linux-01-06-matrix-preflight-linux/receipt.json` |
| Full Linux checklist | `artifacts/fidelity/linux/01-06-matrix.json`, 8 cells / 40 obligations, all open |
| Current shared audit | `artifacts/fidelity/linux/01-06-audit.json`, accepted 0 / required 120, invalid `[]` |
| Local review | `artifacts/fidelity/linux/01-06-review/index.html`, failed receipt with no fabricated media |
The older task-1 import remains diagnostic history; select the current typed
receipt for scenario audit. The focused failure is an actual preflight result,
not an executed gameplay moment. Every continuous/focused slot retains the exact
current dependency receipt plus its own actual capture/lifetime/human-review
requirement. No native matrix cell was runnable after the shared preflight failed.
## Verification
- Final counted capture verification: **23 tests pass**, exceeding both 10/14
thresholds. Doubles stay synthetic, native automation stays `port_fixture`,
positive retained file/clock binding and invalid retained-session cases pass.
- Broader `test_fidelity*.py` regression: **156 tests pass** in 36.316 seconds,
including local viewer sockets and existing real .NET/observer fixtures outside
sandbox restrictions. This ran before the final capture-size bound regression;
the final focused suite passed all 23 after that bounded collector change.
Complete report: `artifacts/fidelity/linux/01-06-fidelity-tests.log`.
- Shell syntax and `git diff --check` pass. Both actual failed receipts validate
through the shared validator/importer. The current scenario audit has no invalid
receipts and grants no acceptance.
- Original inventory verified **539 unchanged files** before capture preparation
and repeatedly after collection/final changes. No generated package, original,
trace or raw media is staged.
- Task-1 tracer verification reran and passed before matrix expansion. No blanket
fidelity tolerance or native Windows/original execution claim is made.
## TDD Gate Compliance
Actual records `artifacts/fidelity/tdd/01-06-01-red.json` and
`01-06-02-red.json` both return `RED_EVIDENCE_OK`. Task 1's named target executes
the planned missing capture-API assertion, without import/setup failure. Task 2's
named target executes the missing forty-obligation matrix assertion while the
first twelve tests remain green. Both RED commits precede their GREEN commits.
No separate refactor was needed.
## Deviations from Plan
None in scope. The plan's explicit unavailable-native conditional was exercised:
precise failed preflight, usable collector/procedure and complete open matrix
replace unavailable execution, without waiving acceptance. Additional correctness
checks preserve prelaunch identity after package tampering, bind annotation files
and exclude oversized raw media from unbounded import. These implement the
planned T-01-16/17/18/SC mitigations; no new trust surface was introduced.
## Remaining Acceptance and Next Phase
All **40 Linux** and **120 total** actual original/native acceptance obligations
remain OPEN. A usable display, real output/monitor device, physical play, continuous
and focused recordings, audible/visible/browser review and original-DxWnd/native
Windows comparisons are still required in the final combined session. Independent
fresh execution-copy staging and actual same-process retained state remain visible
procedure obligations; no source package is silently relabeled as a fresh copy.
The unavailable physical/native check is recorded as open WINDOWS ledger entry 2
(`unrun-verify`), not as a passed test or waived truth. No implementation stub or
skipped mandatory automated verification remains. Shared EVID-01/EVID-04 IDs stay
Pending because unfinished plan 01-07 owns their remaining gates.
## Self-Check: PASSED
All four implementation/procedure files exist; all four recorded task commits
are ancestors of HEAD. Actual failed/current receipt files, matrix, audit and local
review export exist. The persisted ledger measures four commits over the recorded
before/after range. Original verification, final counted tests and current receipt
audit pass within their stated scope.
@@ -0,0 +1,196 @@
---
phase: 01-reproducible-fidelity-baseline
plan: "07"
status: complete
completion_scope: autonomous preparation and pending-evidence reconciliation
acceptance: human_needed
subsystem: testing
tags: [fidelity, acceptance, checkpoint, local-regressions]
requires:
- phase: 01-06
provides: Linux collector and failed native preflight diagnostic
provides:
- Strict ready/audit gates and fresh local combined-session materials
- Pending original/native/human acceptance and exact reconciliation mapping
- Counted consolidated local regressions and measured final evidence status
affects: [phase01-acceptance, phase02]
tech-stack:
added: []
patterns: [receipt-bound human findings, immutable materials, explicit current selection, positive test counts]
key-files:
created: [tools/recon/fidelity_acceptance.py, tests/test_fidelity_acceptance.py, docs/evidence/checkpoint-session.md, docs/evidence/phase01-baseline.md]
modified: [tools/recon/fidelity_checkpoint.py, tests/test_fidelity_checkpoint.py, docs/evidence/capabilities.json, scripts/test.sh, docs/progress.md, docs/tasks.md, docs/decisions.md, docs/compatibility.md]
key-decisions:
- "Ready materials and local regressions never substitute for actual original/native acceptance; all 120 obligations and ten named human findings remain open."
- "The integration agent reconciles returned collector records through specified artifact mappings; the tester collects, observes and returns one combined session."
requirements-completed: []
actuals:
tokens: 18163
tasks: 2
commits: 5
plan_head_before: d18f551a26f90cd645309dcd545295911b581357
plan_head_after: 472500bf4e191c2080764471b6b08486c1909b3a
duration: "4h 36min observed commit-to-closeout elapsed, including quota pause; full suite 782.05s"
completed: 2026-11-13
coverage:
- id: D1
description: Immutable readiness and strict rejection of missing original/native/human evidence
verification:
- kind: integration
ref: tests/test_fidelity_acceptance.py; 23 checks in completed local suite
status: pass
- kind: integration
ref: fidelity_acceptance.py ready; 11000 immutable files
status: pass
human_judgment: false
- id: D2
description: Actual combined original-DxWnd/native Linux/native Windows capture and review
verification:
- kind: manual_procedural
ref: docs/evidence/checkpoint-session.md; acceptance.json 0/120
status: unknown
human_judgment: true
rationale: Actual moving content, physical input, audibility and paired playback remain unavailable; strict acceptance exits 1.
- id: D3
description: Counted fidelity regressions integrated with the existing complete local suite
verification:
- kind: integration
ref: artifacts/fidelity/01-07-full-suite.json; exit 0 in 782.0496263504028 seconds
status: pass
human_judgment: false
---
# Phase 01 Plan 07: Strict Fidelity Acceptance Checkpoint Summary
**Fresh 11,000-file offline materials pass readiness and the complete local suite; strict acceptance retains 0/120 original/native obligations and ten human judgments.**
Autonomous preparation and truthful pending-status reconciliation are complete.
Tasks 01-07-01 and 01-07-03 are complete. Task 01-07-02's permitted unavailable-
evidence projection is committed; its actual combined capture/review remains
pending. `status: complete` describes that preparation scope, never Phase 1 or
EVID acceptance. All EVID requirements remain Pending. Phase 2 is not advanced.
The stale quota handoff is retained for primary review/consumption separately.
## Performance and Accounting
- Earliest production-task commit: 2026-11-13T17:09:46Z; closeout: approximately 21:46Z.
- Observed elapsed interval includes the quota pause; active execution time was not measured continuously.
- Full authorized local suite: 782.0496263504028s, exit 0; runner reports 783s.
- Realized diff: 72,652 characters / 4 = 18,163 tokens, including committed quota metadata.
- Persisted plan ledger measures five commits before this summary; hashes above bound that measurement.
- Two fully completed tasks; one pending actual human task with its permitted documentation complete.
## Task Commits
| Task | Commit | Result |
|---|---|---|
| 01-07-01 RED | d78b135 | 18 intentional missing-API assertions fail; machine RED_EVIDENCE_OK |
| 01-07-01 GREEN | 026def9 | Strict audit, 23 passing tests, fresh final bundle and reconciliation checklist |
| 01-07-02 pending projection | fc5e936 | Capability ledger retains failed diagnostic and unresolved human states |
| Quota checkpoint | b732256 | Existing handoff/state only; no production behavior change |
| 01-07-03 | 472500b | Counted existing regressions and actual full-suite/status results |
## Verification Results
The complete suite ran once after the scoped reporter correction; its completed
receipt is `artifacts/fidelity/01-07-full-suite.json` and full output is
`artifacts/fidelity/01-07-full-suite.log`. No duplicate final suite was run.
| Verification | Actual result |
|---|---|
| Python discovery | 556 tests in 68.110s; 180 fidelity across all eight modules |
| Fidelity module counts | acceptance 23, capture 23, checkpoint 24, ledger 31, observation 7, review 21, scenarios 22, sessions 29 |
| Node viewer | 27 tests pass with explicit TAP reporter |
| Standalone managed observer | 23 checks pass |
| HUD Python | 2 separate tests in 0.171s |
| Managed entry points/build | All 51 test-project invocations and main build pass |
| Vulkan | 36 rendered receipts across 32 device groups; 27 saved readbacks; zero reported validation errors |
| Material regression | 17 Vulkan material/readback assertions pass, zero validation errors |
| SDL audio | Existing dummy-audio effect/stream/scene/cutscene checks pass; audibility remains unverified |
| Preservation | Verified 539 unchanged original files |
| Final readiness recheck | 11,000 immutable files; materials_ready=true, acceptance=human_needed |
| Final strict audit recheck | Exit 1; errors=[], accepted 0/120; ten human findings pending |
Optional `NEUTRON_WINDOW_TEST=1` checks were not enabled; no new native window,
physical-input, audible, original gameplay or native Windows execution is claimed.
Existing NU1900 unavailable vulnerability-metadata warnings remain unrelated.
First attempt: Python 556 passed in 71.765s and Node 27 passed, but the new TAP
count guard rejected Node's default spec reporter. Its 74.647s attempt/log is
retained as `01-07-full-suite-attempt1.{json,log}`. Explicit TAP passed focused
checks and the completed full rerun.
## Exact Evidence and Package Identity
- Final bundle: `dist/fidelity/phase01`; READY SHA-256 `48100025fbdcbb5310bdae28b5cae1e8f17412aa7b03be5f823616cd88211951`.
- Manifest SHA-256: `46610a4029f1341e7f48147370a81daaa8ff799a60fba388b641a0678d2032aa`.
- Exact tool/package identities: `artifacts/fidelity/verification/01-07-final-checkpoint.json`.
- Runtime source: `446930d2a30d6d616c60ac5e59e4169a840bea09`, dirty true, diff `90cef95669caece53fe2d2c4736cf2ac05ed27f5d25ca03ab572589686bcb73d`. Later tool/docs commits do not relabel existing packages.
- Actual failed receipt: `linux-01-06-matrix-preflight-linux`, imported under final `results/imported/`; diagnostic viewer: `results/failed-linux-review/index.html`.
- Final audit: `dist/fidelity/phase01/results/acceptance.json`; actual capture and human acceptance remain OPEN.
- Capability validation: 25 capabilities, 33 requirements, 33 reconciled rows, six groups; acceptance OPEN.
No runtime source changed in task 3, no package rebuild/relabel occurred, and no
originals, generated packages, media or traces were uploaded. All remain local.
## Files Created/Modified
`fidelity_acceptance.py` and its dedicated tests separate readiness from strict
acceptance. The existing checkpoint assembler/tests add required final materials
and tool provenance. `checkpoint-session.md` prepares one combined review and
`phase01-baseline.md` records actual/pending findings. `capabilities.json` retains
the failed receipt and unresolved current states. `scripts/test.sh` counts the
existing fidelity Python/Node/observer checks; the four root status reports cite
the completed suite, exact identities and pending acceptance. Planning artifacts
record the quota interruption and final autonomous preparation scope.
## Decisions Made
Prepared bytes, diagnostic fixtures and local regression success do not replace
actual original/native receipts or human judgments. Reconciliation remains an
agent-owned operation after one combined tester session; no fragmented early
capture request or new universal fidelity tolerance is introduced.
## Deviations from Plan
- Approved ownership extension: minimal checkpoint MATERIALS expansion, actual tool_source metadata and existing material-membership assertion update make the final immutable bundle contain Linux/audit dependencies; no second assembler/capture subsystem.
- Baseline pending report was created with task 1 because it must exist before immutable assembly; task 2 actual capture acceptance remains open.
- **[Rule 1 - Bug]** Task 3's new positive-count guard expected TAP while installed Node emitted spec. Explicit `--test-reporter=tap` fixes that scoped runner mismatch; focused 27 checks and complete rerun pass. Commit: `472500b`.
- Quota reserve interrupted closeout; the retained quota commit did not add behavior. The completed suite was recovered after reset without repeating it.
## TDD Gate Compliance
Task 1 RED preceded GREEN: `d78b135` then `026def9`. Saved
`artifacts/fidelity/01-07-red.{log,json}` records RED_EVIDENCE_OK. Prior semantic
inspection confirmed the empty-matrix test ran and failed on planned API existence,
without load/setup failure. Final suite executes all 23 acceptance checks.
## Deferred Issues and Human Dependencies
Actual original-DxWnd 40/native Windows 40/native Linux 40 obligations remain OPEN.
A1/A2, both EVID-02/EVID-04 unclassified assumptions, P1/P2/P3, browser,
paired_review and physical_input are the ten pending named findings. No strict
acceptance verification passed; its expected nonzero result records that missing
evidence. `.planning/WINDOWS.md` entry 3 tracks this unmet truth; entry 2 retains
the Linux capture access dependency. The primary reviews readiness before the
single combined human session. The roadmap source-backed continuation exception
does not waive these dependencies or authorize a phase transition here.
## Known Stubs
None preventing autonomous preparation. Checklist JSON metavariables are explicit
human-review templates, never positive findings. Empty review dictionaries in
negative tests and fail-closed audit defaults intentionally exercise missing
evidence; no production UI/data stub was introduced. Existing gameplay admission
gates remain unchanged. No new security surface beyond the planned local evidence
file/import boundaries was introduced.
## Self-Check: PASSED
All created source/test/checklist/baseline files, final local checkpoint, completed
suite receipt and exact identity receipt exist. All five recorded commits are
ancestors of the measured HEAD. Final readiness passes and strict audit retains
errors=[], 0/120 and ten pending findings. Unrelated `tools.yaml` is preserved.
## Independent review closure
Five confirmed findings were fixed and independently verified; see01-REVIEW.md,01-FIX-REPORT.md,01-REVIEW-VERIFY.md and01-REVIEW-DISPOSITION.md. Final refinement02d182f requires actual artifact bytes at the scenario boundary;191 fidelity checks pass43.355s. The new checkpoint has11,001 immutable entries with current local identities in artifacts/fidelity/verification/01-07-final-checkpoint.json; prior identity notes remain historical. All22 planned security threats are closed, while actual0/120 acceptance and ten named human findings stayOPEN. No original/native acceptance or phase advancement is implied.
@@ -0,0 +1,114 @@
---
phase: 01-reproducible-fidelity-baseline
fixed_at: 2026-11-13T22:09:37Z
review_path: .planning/phases/01-reproducible-fidelity-baseline/01-REVIEW.md
iteration: 1
findings_in_scope: 5
fixed: 5
skipped: 0
status: all_fixed
---
# Phase 01: Code Review Fix Report
All five confirmed findings were fixed. Their logic changes require independent
human/reviewer verification; automated results below establish the stated tooling
contracts, never original/native gameplay acceptance. No runtime/gameplay source,
original file, package bytes, review disposition, or phase state was changed.
| Finding | Status | Commit | Applied fix and regression |
|---|---|---|---|
| CR-01 | fixed: requires human verification | `5569bc2` | Carry the actual selected receipt path into digest review. Two different sibling JSON files without a sidecar prove that only the selected file's digest satisfies the human finding; absent/unrelated digests leave findings pending. |
| CR-02 | fixed: requires human verification | `bda35e5` | Supply the complete checkpoint original file inventory, recompute its digest, and bind `identity.executable.original_member` plus size/header/hash to the exact pristine member. Original pre/post/package/resources require full baseline file records and digest. Positive original fixtures retain actual member/executable hashes; wrong executable/member and altered inventory records fail. Writable-copy post changes are separately identified and remain allowed. |
| CR-03 | fixed: requires human verification | `6e5ee0b` | Bind both lifetimes to the validated named `identity.copy_pre` record; retained lifetimes also require `identity.retained_copy`. Unknown hashes and hashes of launcher/package/other state records fail. Fixtures now retain distinct actual copy-state files. |
| WR-01 | fixed: requires human verification | `548c97a` | Assemble the existing validated ledger projection before review export, seal it at `protocol/capability-ledger.json`, and compare viewer current/history against it during readiness. Actual preparation-to-bundled-renderer regression retains the named current and superseded startup records; a sealed viewer missing history is rejected. |
| WR-02 | fixed: requires human verification | `2608517` | Recover missing `run.json` only as aborted from the retained incomplete record. Preserve the raw initial bytes as an importable `recovery-initial.json` diagnostic artifact, retain session/start identity, remove initial placeholder end clocks, and reject captured promotion or launch-aligned events. Shared validation/import permits this open aborted record with absent end clocks. |
WR-01 has one additional positive regression commit, `a821754`, proving readiness
on a standalone copied checkpoint with no source Git checkout. No fix was skipped
or rolled back. Five finding commits plus this verification commit were made.
Modified source: `tools/recon/fidelity_acceptance.py`, `fidelity_receipts.py`,
`fidelity_checkpoint.py`, and `scripts/collect-fidelity-windows.ps1`. Tests:
`tests/test_fidelity_acceptance.py`, `test_fidelity_scenarios.py`,
`test_fidelity_checkpoint.py`, and `fidelity-windows.Tests.ps1`. Field contracts:
`docs/evidence/checkpoint-session.md` and `windows-session.md`. No new source file
or dependency was required.
## Verification
All gates ran locally in the **main checkout**. The primary explicitly authorized
a temporary `workflow.use_worktrees=false` override. Its original absent setting
was restored without staging or committing it; the unused clean worktree was
removed before edits. Unrelated untracked `tools.yaml` remains unchanged. Normal
Git hooks ran for every commit. The WR-01 refinement was folded into its commit
before the primary's no-rebase steering arrived; subsequent history is preserved.
Logs are retained under ignored `artifacts/fidelity/01-review-fixes/`:
- `python-fidelity.log`: all 189 fidelity regressions passed in 40.072 seconds.
Initial sandbox execution hit eight loopback-socket permission errors; the
successful scoped-escalation run permits only the local tests' necessary host
operations. These were environment errors, not accepted failed tests.
- `acceptance-final.log`: 29 acceptance tests passed after the final standalone
transfer regression was added. This includes the refined readiness path; these
tests overlap the 189-test run and are not added to its count.
- `node-viewer-direct.log`: 27 actual Node behavior tests passed. On this host
`node --test` reports an aggregate one-file result; direct execution supplied
the explicit 27-test count. The preparation test also rendered the real bundled
model with the bundled renderer and a DOM double, without claiming browser
playback evidence.
- `powershell.log`: 18 package-free synthetic tooling checks passed under cached
Linux-hosted PowerShell. This is not native Windows execution evidence.
- `recovered-import.log`: the actual incomplete-only PowerShell output passed
shared validation and atomic import; accepted is false. Raw fixture output and
imported bytes are retained in separate `test-windows-results/` and
`test-recovered-imports/` namespaces.
- `original-preservation.log`: all 539 original files unchanged. The same
inventory command passed after assembly as well; preparation independently
checked the original inventory before and after copying.
- Python parse checks and `git diff --check` passed. The prior 13-minute full
managed/GPU suite was not repeated because these changes touch tooling and
evidence contracts only.
## Fresh immutable checkpoint
The final checkpoint was assembled **once**, using unchanged existing
`artifacts/fidelity/01-05-packages/{linux-x64,win-x64}` bytes. The prior tree was
preserved at `dist/fidelity/phase01-pre-review-48100025`; the documented current
path remains `dist/fidelity/phase01`. No sealed member was patched after assembly.
Mutable results contain a fresh import of the existing failed Linux preflight
receipt and the unchanged pending human-review controls; no captured evidence was
invented. The former assembly remains historical evidence.
| Item | Identity/result |
|---|---|
| Current checkpoint | `dist/fidelity/phase01` |
| Immutable members | 11001 |
| READY SHA-256 | `7ceebcb3a22549a59bb9f7032c5c686b4ca4d32cf7b6a7d934e12e37f05e7aba` |
| Manifest SHA-256 | `a4da759bb264d63b716a931ae3b16a410baf01e36a7b2696ae8ed5649f77f7a9` |
| Tool commit | `a821754b6755151a0e33e4ac5065c8efd252b2e6` |
| Tool working-tree provenance | Tracked diff empty; dirty true solely from preserved untracked `tools.yaml`, identified by the manifest |
| Sealed runtime source | `446930d2a30d6d616c60ac5e59e4169a840bea09`, dirty true |
| Runtime publish diff | `90cef95669caece53fe2d2c4736cf2ac05ed27f5d25ca03ab572589686bcb73d` |
| Linux package tree | `124cf271e4952f3822eec5c24358447fcffc9e9e1803aded8d96d4d4472dc5a3` |
| Windows package tree | `335e5b75ec15c0fa904113d8b69d4f50e2cfa403f1f2f225353bd9e586322ef4` |
| Startup viewer projection | Two current and two historical records retained |
| Readiness | Exit 0, `materials_ready: true`, `acceptance: human_needed` |
| Strict acceptance | Exit 1, 0/120, no structural errors, all ten human findings pending |
`prepare-checkpoint.log`, `readiness.json`, `acceptance.json`, and
`failed-linux-import.json` retain the actual results. The readiness and acceptance
reports also reside under the current bundle's mutable `results/` directory.
The ten pending findings remain A1, A2, EVID-02-unclassified,
EVID-04-unclassified, P1, P2, P3, browser, paired_review, and physical_input.
The host still lacks actual original/native Windows capture access and a usable
Linux display/audio session. Independent re-review and the primary's remaining
security/coverage gates precede any combined capture request.
This report is intentionally uncommitted for the primary workflow to review and
commit. No push, package upload, original execution, or original write occurred.
## Final artifact-boundary refinement
CR-03 independent re-review caught pathless hash-only named records. RED48fca0d reproduces fresh/retained missing-file, wrong-size and hash-only cases; GREEN02d182f validates actual named files inside scenario observation with an explicit root. All191 fidelity tests pass in43.355s; focused26 scenario/23 capture/29 acceptance checks pass. Independent reviewer confirms allfive findings fixed; security auditor closes22/22 planned threats. The earlier11001-file bundle is retained locally; current dist/fidelity/phase01 is freshly assembled from corrected source with original runtime package identities unchanged.
@@ -0,0 +1,39 @@
---
phase: 01
review: 01-REVIEW.md
titles: json
findings:
- id: CR-01
severity: critical
disposition: fixed
title: "Human review is checked against a different file from the selected receipt"
- id: CR-02
severity: critical
disposition: fixed
title: "Original applicability never binds the executed executable or preservation inventories"
- id: CR-03
severity: critical
disposition: fixed
title: "Fresh-copy continuity accepts a hash that identifies no artifact"
- id: WR-01
severity: warning
disposition: fixed
title: "Checkpoint assembly bypasses the capability ledger projection"
- id: WR-02
severity: warning
disposition: fixed
title: "An interrupted Windows collector cannot be finalized through the documented recovery command"
open: 0
total: 5
recorded: 2026-11-13T21:58:50.502559+00:00
---
# Phase 01: Code Review Disposition
| Finding | Severity | Disposition | Source |
|---|---|---|---|
| CR-01 | critical | fixed | 01-REVIEW-VERIFY.md; independent re-review |
| CR-02 | critical | fixed | 01-REVIEW-VERIFY.md; independent re-review |
| CR-03 | critical | fixed | 01-REVIEW-VERIFY.md; independent re-review |
| WR-01 | warning | fixed | 01-REVIEW-VERIFY.md; independent re-review |
| WR-02 | warning | fixed | 01-REVIEW-VERIFY.md; independent re-review |
@@ -0,0 +1,75 @@
---
phase: 01-reproducible-fidelity-baseline
verified: 2026-11-13T22:19:18Z
review_path: .planning/phases/01-reproducible-fidelity-baseline/01-REVIEW.md
fix_report_path: .planning/phases/01-reproducible-fidelity-baseline/01-FIX-REPORT.md
verified_head: 02d182f35de643f9d68699b2fff1d219dd132edb
findings_verified: 5
fixed: 5
open: 0
findings:
critical: 0
warning: 0
info: 0
total: 0
status: clean
---
# Phase 01 review-fix verification
All five fixes are verified. The final CR-03 refinement requires actual backing artifacts for named copy-state identities and rejects the hash-only records that survived its first fix. No reviewed finding remains open.
| Finding | Disposition | Independent verification |
|---|---|---|
| CR-01 | FIXED | The selected path is retained and its own digest is compared with the human finding. The sibling-digest and absent-digest regressions leave human checks pending; the actual selected-file digest satisfies that boundary. |
| CR-02 | FIXED | Complete baseline records and their recomputed digest bind original pre/post/package/resources. The explicit executed `original_member` binds executable size/header/hash. Wrong executable/member and inconsistent inventories are rejected; independently identified writable `copy_post` changes remain allowed. |
| CR-03 | FIXED | Scenario validation now checks the actual named copy-pre artifact for both lifetimes and the retained snapshot for retained runs. Previous hash-only reproductions and an isolated retained-snapshot reproduction are rejected; valid named state files still qualify. |
| WR-01 | FIXED | Assembly exports the validated ledger projection; readiness compares current/history with the sealed projection. The preparation-to-bundled-renderer check preserves named current/superseded records. The standalone-transfer check needs no source Git checkout, and missing viewer history is rejected. |
| WR-02 | FIXED | A real Linux-hosted PowerShell finalizer reproduction recovered an incomplete-only synthetic run as aborted. Initial raw bytes and session identity survived, end clocks remained absent, captured promotion was rejected, and shared validation plus atomic import succeeded with acceptance false. |
## CR-03 refinement verified
**Original classification:** BLOCKER
**Current disposition:** FIXED by `02d182f35de643f9d68699b2fff1d219dd132edb`, with regression `48fca0d`.
**File:** `/home/cristian/codex/Neutron/GamePort/tools/recon/fidelity_receipts.py:667-678`
**Related:** `/home/cristian/codex/Neutron/GamePort/tools/recon/fidelity_receipts.py:383-385`
At `a821754`, `_scenario_observation()` compared continuity digests with named identity strings while the generic validator skipped dictionaries without `path`. The refinement now passes the receipt root to scenario validation and calls `_checked_artifact()` on the actual named state records before comparing digests. The scenario audit and Linux capture matrix both pass their artifact root; their direct test callers were updated as well.
The bounded reproduction below uses existing synthetic metadata fixtures and launches no game. It previously demonstrated the gap and now demonstrates rejection for both native lifetimes:
```python
from test_fidelity_scenarios import FidelityScenarios
import fidelity_receipts as receipts
fixture = FidelityScenarios()
fixture.setUp()
try:
for lifetime in ('fresh', 'retained'):
value, root = fixture.receipt(
lifetime + '-natural-ordinary', 'dialogue-return')
value['identity']['copy_pre'] = {'sha256': 'f' * 64}
value['continuity']['copy_pre_sha256'] = 'f' * 64
if lifetime == 'retained':
value['identity']['retained_copy'] = {'sha256': 'e' * 64}
value['continuity']['retained_copy_sha256'] = 'e' * 64
result = receipts.audit_scenarios(
fixture.protocol(), [(value, root)])
print(lifetime, result['accepted'], result['invalid'])
finally:
fixture.doCleanups()
```
Run from the repository with `PYTHONPATH=tests:tools/recon`. Earlier output at `a821754` was `fresh 1 []` and `retained 1 []`. Rerunning at `02d182f` gives zero accepted slots and `Reference must be a bounded relative POSIX path` in each invalid list. A third reproduction retaining valid copy-pre but supplying only a hash for `identity.retained_copy` is rejected independently. The unmodified fresh and retained metadata controls each still accept one slot.
**Additional verification:** Four selected scenario tests passed in **0.424 seconds**: backing-file rejection for both lifetimes, named continuity binding, unrelated retained-snapshot rejection, and complete positive coverage of all 120 metadata slots. The new backing-file test covers hash-only, missing-file and wrong-size state identities, including the retained snapshot. This closes the reported artifact-binding gap without changing the four other verified fixes.
## Verification evidence and limits
Read the historical review, fix report and actual source/test diffs for `5569bc2`, `bda35e5`, `6e5ee0b`, `548c97a`, `2608517`, and `a821754`, then the final `48fca0d` regression and `02d182f` refinement. Initially ran 11 selected Python tests in **2.109 seconds**, all passing: selected-file review binding; original executable/member and inventory rejection; mutable generated-copy allowance; complete positive metadata matrix; standalone readiness without Git; malformed viewer history; actual assembled model through its bundled renderer; named pre/retained continuity; and aborted missing-end-clock import. The additional hash-only identity gap discovered during that verification is closed by the independently repeated checks above.
Separately exercised the actual PowerShell recovery function with a disposable synthetic prepared checkpoint, rejected captured promotion, recovered raw media, compared both raw initial copies byte-for-byte, verified absent end clocks, validated and imported the resulting open aborted receipt. This was Linux-hosted tooling execution, not native Windows evidence.
No full suite, whole 11,001-file checkpoint readiness/hash walk, original execution or gameplay capture was repeated. The primary's current bundle identities and pending 0/120 human acceptance remain separate evidence; this verification does not promote them. Source and tests were read-only, no commit was made, and unrelated concurrent report edits were preserved.
Historical `01-REVIEW.md` is unchanged; its SHA-256 is `493c0b9b7b491f7dcc896d6cfda675ced837f56ee32daf2bbf1cd98f1527f74c`.
@@ -0,0 +1,137 @@
---
phase: 01-reproducible-fidelity-baseline
reviewed: 2026-11-13T21:56:48Z
depth: standard
files_reviewed: 44
files_reviewed_list:
- .codex/hooks.json
- docs/codex-quota-guard.md
- docs/compatibility.md
- docs/decisions.md
- docs/evidence/README.md
- docs/evidence/capabilities.json
- docs/evidence/checkpoint-session.md
- docs/evidence/linux-session.md
- docs/evidence/phase01-baseline.md
- docs/evidence/scenarios.json
- docs/evidence/windows-session.md
- docs/progress.md
- docs/tasks.md
- scripts/collect-fidelity-linux.sh
- scripts/collect-fidelity-windows.cmd
- scripts/collect-fidelity-windows.ps1
- scripts/prepare-fidelity-checkpoint.sh
- scripts/test.sh
- src/GamePort/Application/FidelityObservation.cs
- src/GamePort/Program.cs
- tests/GamePort.FidelityObservationTests/GamePort.FidelityObservationTests.csproj
- tests/GamePort.FidelityObservationTests/Program.cs
- tests/fidelity-viewer.test.mjs
- tests/fidelity-windows.Tests.ps1
- tests/test_codex_quota_guard.py
- tests/test_fidelity_acceptance.py
- tests/test_fidelity_capture.py
- tests/test_fidelity_checkpoint.py
- tests/test_fidelity_ledger.py
- tests/test_fidelity_observation.py
- tests/test_fidelity_review.py
- tests/test_fidelity_scenarios.py
- tests/test_fidelity_sessions.py
- tools/recon/fidelity.py
- tools/recon/fidelity_acceptance.py
- tools/recon/fidelity_capture.py
- tools/recon/fidelity_checkpoint.py
- tools/recon/fidelity_ledger.py
- tools/recon/fidelity_receipts.py
- tools/recon/fidelity_review.py
- tools/recon/fidelity_viewer/index.html
- tools/recon/fidelity_viewer/style.css
- tools/recon/fidelity_viewer/viewer.mjs
- tools/workflow/codex_quota_guard.py
findings:
critical: 3
warning: 2
info: 0
total: 5
necessity: 0
status: issues_found
---
# Phase 01: Code Review Report
**Reviewed:** 2026-11-13T21:56:48Z
**Depth:** standard
**Files Reviewed:** 44
**Status:** issues_found
## Summary
Three acceptance-integrity defects permit mismatched reviewed bytes, unrelated original executable bytes, or an unbound fresh-copy identity to contribute accepted obligations. The prepared capability viewer also omits current/history evidence, and the Windows finalizer cannot recover the interrupted-run state described by its instructions.
Scope is the canonical `/tmp/gameport-phase01-review-scope.json` file union at HEAD `215d01e43e103f3fbb7e26b43607cd09f2856492`. Resolver status is **degraded**, reason `no-task-commit-rows`, using its real phase range from `9aa49970e43bc9ca5470b884757e3481e0c0293a`. The union contains 44 files; all seven SUMMARY key-file lists are covered, and none of these paths is ignored. No structural pre-pass or external reviewer evidence was supplied. The necessity rubric was read; no necessity finding was established.
The pending 0/120 original/native obligations and ten human findings are expected acceptance dependencies, not implementation defects. Findings below concern enforceable identity/continuation contracts. Reproductions used disposable synthetic metadata only; the Windows recovery reproduction used Linux-hosted PowerShell, not native Windows. The existing complete-suite run was not repeated. No original was executed or modified, no source was edited, and no commit was made; unrelated `tools.yaml` was preserved.
## Narrative Findings (AI reviewer)
## Critical Issues
### CR-01: Human review is checked against a different file from the selected receipt
**Classification:** BLOCKER
**File:** `/home/cristian/codex/Neutron/GamePort/tools/recon/fidelity_acceptance.py:134-143`
**Issue:** `current.json` may select any contained receipt filename. The loop reads that path, discards it, then compares the human-review digest against `directory / 'receipt.json'`. A sibling `selected.json` can therefore supply the accepted record while the human finding binds unrelated `receipt.json` bytes. Raw result directories need not have an import sidecar, so `read_receipt` does not close this gap. This defeats the explicit receipt-byte review boundary; the same mismatch can affect every selected slot.
**Evidence:** A bounded synthetic reproduction selected `run/selected.json`, stored a different object at `run/receipt.json`, and supplied the latter's digest in `human-review.json`. The real `audit()` returned `matrix.accepted == 1`, `human_needed == []`, and `errors == []`, despite the selected digest differing from the reviewed digest. Only material readiness was mocked to isolate receipt selection; hash checking, parsing and matrix evaluation ran normally.
**Fix:** Carry the actual selected path/digest alongside each record and compare `receipt_sha256[receipt_id]` with that file. Alternatively, explicitly reject every selected basename other than `receipt.json` before reading it. Missing or different selected-file digests must invalidate the human finding. Add a regression with two different sibling JSON files and no sidecar.
### CR-02: Original applicability never binds the executed executable or preservation inventories
**Classification:** BLOCKER
**File:** `/home/cristian/codex/Neutron/GamePort/tools/recon/fidelity_acceptance.py:81-84`
**Issue:** The original-DxWnd branch checks only a `tree_sha256` string inside the receipt's `original_pre` JSON. It does not compare the actual identified executable against its selected pristine inventory member, validate original package/resource identities against that baseline, or check `original_post`. The generic validator checks each referenced file's own hash, which establishes identity but not applicability. Consequently, attaching a correct original-pre inventory to an unrelated executable is sufficient to pass `_bind`. This is weaker than the concrete executable/pre/post mapping promised in `docs/evidence/checkpoint-session.md:90-94`.
**Evidence:** Starting with the existing complete metadata fixture for an original-DxWnd slot, a synthetic diagnostic replaced only `identity.executable` with the actual size/hash of a new file containing `synthetic wrong original executable`. The expected original-pre record stayed unchanged. `audit_records()` still returned one accepted obligation and no errors. The receipt schema otherwise remained valid; no false artifact hash was required.
**Fix:** Pass the checkpoint's actual pristine file inventory into original binding, retain the exact selected original member path, and compare the receipt executable identity with that member. Validate package/resources and authoritative pre/post inventories against the same baseline; recompute inventory digests from their file records rather than trusting an embedded digest alone. Writable-copy changes must stay separately recorded. Add negative tests for a wrong executable and inconsistent pre/post inventory content.
### CR-03: Fresh-copy continuity accepts a hash that identifies no artifact
**Classification:** BLOCKER
**File:** `/home/cristian/codex/Neutron/GamePort/tools/recon/fidelity_receipts.py:659-669`
**Issue:** All cells require `copy_pre_sha256`, but fresh cells only check its 64-hex syntax. Actual identity membership is checked inside the retained-only branch. Thus a fresh observation can claim a nonexistent copy state and still fill an accepted slot, contrary to the fresh lifetime procedure's separately identified generated execution copy. The executable/package binding does not identify that per-run startup state.
**Evidence:** With `FidelityScenarios.receipt('fresh-natural-ordinary', 'dialogue-return', 'native_port', 'linux')`, replacing `continuity.copy_pre_sha256` with `'f' * 64` produces `audit_scenarios(...).accepted == 1` and `invalid == []`. No identity file has that digest. This reproduction is a synthetic metadata diagnostic, not gameplay evidence.
**Fix:** Require `copy_pre_sha256` to match the validated, explicitly named `identity.copy_pre` record for both lifetimes before branching. Bind retained-copy state to its explicitly named retained snapshot as well, rather than any unrelated identity hash. Add fresh-copy negative tests for an unknown digest and a digest belonging to the launcher/package instead of the per-run copy record.
## Warnings
### WR-01: Checkpoint assembly bypasses the capability ledger projection
**Classification:** WARNING
**File:** `/home/cristian/codex/Neutron/GamePort/tools/recon/fidelity_checkpoint.py:165-167`
**Related:** `/home/cristian/codex/Neutron/GamePort/tools/recon/fidelity_viewer/viewer.mjs:228-244`
**Issue:** Assembly passes authoritative `capabilities.json` directly to `export_review()`. That export validates/copies source links but does not call `export_ledger()`, so its rows retain `evidence` without derived `current` and `history`. The browser renders only `row.current` and `row.history`, displaying `Unrecorded` in both sections and concealing the revision/classification details prepared for the reviewer. The separate CLI ledger-to-viewer test exercises the correct projection, but checkpoint assembly does not use that route.
**Evidence:** In the actual sealed `dist/fidelity/phase01/review/review.json`, all 25 capability rows lack both fields. Applying `export_ledger()` to the authoritative input yields two current and two historical records for `startup-order`; none appears in those viewer sections in the prepared model. This is independent of missing original/native recordings.
**Fix:** Generate the validated ledger projection before checkpoint review export, then preserve its current/history fields through source-link copying. Make `ready()` reject a malformed viewer ledger rather than checking only source hrefs. Add a preparation-to-renderer regression asserting that named current and superseded records survive the actual checkpoint assembly path.
### WR-02: An interrupted Windows collector cannot be finalized through the documented recovery command
**Classification:** WARNING
**File:** `/home/cristian/codex/Neutron/GamePort/scripts/collect-fidelity-windows.ps1:332-336`
**Related:** `/home/cristian/codex/Neutron/GamePort/docs/evidence/windows-session.md:150-152`
**Issue:** Startup writes `incomplete.json` before launching, while `run.json` is written only in the final `finally` block. If the collector is terminated before that block completes, its durable result has only the incomplete record. The instructions explicitly tell the tester to recover that state with `Finish -Outcome aborted`, but `Complete-FidelityRun` unconditionally reads missing `run.json` first. The supplied recovery command therefore cannot retain the interrupted launch's media as a terminal receipt; asking for a fresh launch would misidentify its lifetime.
**Evidence:** A disposable synthetic prepared bundle with `results/interrupted/incomplete.json` and no `run.json` was passed to the real finalizer through Linux-hosted PowerShell. It failed immediately with `Cannot find path '.../results/interrupted/run.json' because it does not exist.` The failed lookup precedes annotation/media recovery. Existing terminal tests always create `run.json` and do not cover this durable interrupted state.
**Fix:** Add an explicit aborted-recovery path using the retained initial record when `run.json` is absent. Preserve its launch identity and raw bytes, prohibit captured/reviewed promotion, and leave unavailable end clocks/observations explicitly missing. Recover media into a new write-once diagnostic receipt without inventing elapsed times. Test an incomplete-only result folder and verify that it remains open and structurally importable.
---
_Reviewed: 2026-11-13T21:56:48Z_
_Reviewer: gsd-code-reviewer_
_Depth: standard_
@@ -0,0 +1,60 @@
---
phase: "01"
slug: reproducible-fidelity-baseline
status: verified
threats_open: 0
threats_total: 22
threats_closed: 22
asvs_level: 1
block_on: high
register_authored_at_plan_time: true
verified_head: 02d182f35de643f9d68699b2fff1d219dd132edb
created: "2026-11-13T22:21:09.119266+00:00"
---
# Phase 01 — Security
The typed security auditor verified all planned mitigation boundaries. The repeated reserved T-01-SC is counted once. All dispositions are mitigate; no accepted or transferred risks.
## Trust Boundaries
Originals → generated copies; local paths → file/process operations; media/receipts → review and acceptance; observer → gameplay; transferred checkpoint → immutable validation.
## Threat Register
| Threat ID | Category | Severity | Disposition | Mitigation evidence | Status |
|---|---|---|---|---|---|
| T-01-01 | Tampering | high | mitigate | fidelity_receipts.py:123,221,239,257 | closed |
| T-01-02 | Spoofing | high | mitigate | fidelity_receipts.py:275,667,672,714 | closed |
| T-01-03 | Tampering | high | mitigate | fidelity_receipts.py:198,212,482,500 | closed |
| T-01-04 | Information disclosure | high | mitigate | fidelity_review.py:202,211,219,274 | closed |
| T-01-05 | Tampering | high | mitigate | viewer.mjs:2,190; fidelity_review.py:238 | closed |
| T-01-06 | Spoofing | medium | mitigate | viewer.mjs:43,79,302,318,324 | closed |
| T-01-07 | Spoofing | high | mitigate | fidelity_ledger.py:97,197,203,285 | closed |
| T-01-08 | Repudiation | medium | mitigate | fidelity_ledger.py:69,220,299,320 | closed |
| T-01-09 | Tampering | medium | mitigate | fidelity_ledger.py:117,339,372 | closed |
| T-01-10 | Tampering | high | mitigate | FidelityObservation.cs:54,78,93,109; test_fidelity_observation.py:130 | closed |
| T-01-11 | Denial of service | medium | mitigate | FidelityObservation.cs:165,171,179,192,233 | closed |
| T-01-12 | Spoofing | high | mitigate | FidelityObservation.cs:47,109,130,166; Program.cs:18,1328 | closed |
| T-01-13 | Elevation of privilege | high | mitigate | collect-fidelity-windows.ps1:128,136,144,253,303 | closed |
| T-01-14 | Tampering | high | mitigate | fidelity_checkpoint.py:103,120,198,215,220 | closed |
| T-01-15 | Spoofing | high | mitigate | collect-fidelity-windows.ps1:176,208,234,285,332 | closed |
| T-01-16 | Tampering | high | mitigate | fidelity_capture.py:154,156,195,239,347 | closed |
| T-01-17 | Spoofing | high | mitigate | fidelity_capture.py:85,98,107,325,338 | closed |
| T-01-18 | Denial of service | medium | mitigate | fidelity_capture.py:30,128,148,202,220,224 | closed |
| T-01-19 | Spoofing | high | mitigate | fidelity_acceptance.py:124; fidelity_receipts.py:275,667,672,714; fidelity_capture.py:390 | closed |
| T-01-20 | Tampering | high | mitigate | fidelity_receipts.py:453,482,488,494,500 | closed |
| T-01-21 | Repudiation | medium | mitigate | fidelity_acceptance.py:127,130,160,184; fidelity_ledger.py:328 | closed |
| T-01-SC | Tampering | high | mitigate | fidelity_checkpoint.py:301; collect-fidelity-windows.ps1:253; observer csproj:1 | closed |
## Accepted Risks Log
No accepted risks.
## Security Audit Trail
Initial source audit identified 20/22 closed and T-01-02/T-01-19 open because hash-only copy identities bypassed file checks. Regression48fca0d reproduced it; fix02d182f validates actual named artifacts at the scenario boundary. Independent auditor reinspection closes both. Code re-review confirms all five findings fixed; see01-REVIEW-VERIFY.md. All191 affected fidelity regressions pass in43.355s.
## Sign-Off
All22 planned threats have implemented, verified mitigations; threats_open=0. This tooling verdict does not approve original/native gameplay, physical input, audio or human findings; runtime acceptance remains0/120 OPEN.
@@ -0,0 +1,74 @@
---
status: testing
phase: 01-reproducible-fidelity-baseline
source: [01-VERIFICATION.md]
started: 2026-11-14T21:56:41.166382+00:00
updated: 2026-11-14T21:56:41.166382+00:00
---
## Current Test
number: 1
name: A1 — Capture and observe the isolated original through the selected DxWnd setup
expected: |
Complete 40 original-Windows-DxWnd obligations; observe moving game imagery and intelligible game audio, retaining actual executable/profile/copy inventories and wrapper/configuration limitations.
awaiting: user response
## Tests
### 1. A1 — Capture and observe the isolated original through the selected DxWnd setup
expected: Complete 40 original-Windows-DxWnd obligations; observe moving game imagery and intelligible game audio, retaining actual executable/profile/copy inventories and wrapper/configuration limitations.
result: [pending]
### 2. A2 — Exercise actual paired recordings in the identified browser
expected: Both real recordings decode, play at actual speed, seek to their own observed events, preserve full tails and switch exclusive audio without concealing elapsed time.
result: [pending]
### 3. EVID-02-unclassified — Review original capture boundaries and limitations
expected: Document observed original/DxWnd launch, crop, aspect, timing, recording boundaries and retained/fresh lifetimes for the actual reference captures.
result: [pending]
### 4. EVID-04-unclassified — Collect and inspect both native platform routes
expected: Complete 40 native Windows and 40 native Linux obligations with actual OS/GPU/driver/Vulkan/SDL/source/package/resource identity and observed route/input/audio continuity.
result: [pending]
### 5. P1 — Resolve the original-preservation prohibition explicitly
expected: Confirm authoritative originals were never executed or changed; compare all 539 recorded hashes and generated-copy pre/retained/post inventories after the session.
result: [pending]
### 6. P2 — Resolve the honest-comparison prohibition explicitly
expected: Confirm genuine original media, no retiming or concealed drift, no mixed simultaneous soundtracks, and visible review gain/derivation provenance.
result: [pending]
### 7. P3 — Resolve the history/full-scope/native-transparency prohibition explicitly
expected: Confirm all 33 requirements and unimplemented content stay visible; conflicting/superseded evidence and native/Wine/component/cross-publish distinctions are preserved after reconciliation.
result: [pending]
### 8. browser — Review the complete local comparison interface
expected: With real captures, verify readable independent clocks/drift, keyboard controls, raw unobstructed default views, optional annotations/differences and visible loading/error/tail states.
result: [pending]
### 9. paired_review — Compare all corresponding actual recordings and record discrepancies
expected: Review matched events, imagery and sound across the required cases, retaining raw drift and justified system-specific observations without invented tolerances.
result: [pending]
### 10. physical_input — Exercise visible native gameplay and actual audible devices
expected: On Linux and Windows use physical supported inputs through lab → VR04 → lab → outside, natural/skipped and fresh/retained cases, held input, banked jumps, landing and idle; confirm real display/audio output.
result: [pending]
## Summary
total: 10
passed: 0
issues: 0
pending: 10
skipped: 0
blocked: 0
## Gaps
No implementation issues reported in this UAT session. All ten actual human checks remain pending; 0/120 capture obligations are accepted. Follow docs/evidence/checkpoint-session.md as one combined session. Prepared materials and prior tests do not supply human approval.
## Session Notes
Restart requested by the user. Readiness then failed on generated tools/recon/__pycache__/fidelity_checkpoint.cpython-312.pyc before any human capture test. Fixed by2fe8b40; real bundled readiness succeeds twice with no bytecode writes. This automated preflight repair does not pass A1 or any other human check.
@@ -1,9 +1,9 @@
---
phase: "01"
slug: "reproducible-fidelity-baseline"
status: draft
nyquist_compliant: false
wave_0_complete: false
status: validated
nyquist_compliant: true
wave_0_complete: true
created: "2026-11-12"
---
@@ -13,12 +13,12 @@ created: "2026-11-12"
| Property | Value |
|---|---|
| Framework | Existing Python stdlib unittest, standalone .NET 10 console projects; proposed Node built-in tests for pure viewer logic |
| Framework | Existing Python stdlib unittest, standalone .NET 10 console projects; Node built-in tests for pure viewer logic |
| Config file | Existing scripts/test.sh and scripts/env.sh; no new package dependencies |
| Quick run command | `python3 -m unittest discover -s tests -p 'test_fidelity_*.py' -v` (new tests created with their owning slice) |
| Viewer quick command | `node --test tests/fidelity-viewer.test.mjs` (new test file created with viewer slice) |
| Full suite command | `scripts/test.sh` plus the viewer quick command |
| Runtime | Quick target below 30 seconds; measure during execution. Full GPU/original-data suite runs at wave boundaries and has a separate measured duration. |
| Quick run command | `python3 -m unittest discover -s tests -p 'test_fidelity_*.py' -v` |
| Viewer quick command | `node --test tests/fidelity-viewer.test.mjs` |
| Full suite command | `scripts/test.sh` (includes counted Python, Node viewer and managed observer checks) |
| Runtime | Broad fidelity run: 40.072 seconds (30-second target exceeded); focused tooling checks typically 1–5 seconds, process/observer checks can take longer. Complete local suite: 782.049626 seconds. |
## Sampling Rate
@@ -30,35 +30,35 @@ created: "2026-11-12"
## Per-Task Verification Map
Final task bindings below reference the exact executable `<automated>` blocks in the named PLAN.md/task. Each block carries its adjacent observable `<fails_when>`; Python commands assert the minimum discovered count before running. These tests are intended new artifacts, not checks already executed.
Final task bindings below reference the exact executable `<automated>` blocks in the named PLAN.md/task. Each block carries its adjacent observable `<fails_when>`; Python commands assert the minimum discovered count before running. The tests exist and have run with positive counts. The status column separates passing automation from actual capture/review still OPEN. Shared EVID requirement acceptance is not implied by any green tooling row.
| Task | Wave | Exact automated command binding | Minimum count / threat refs |
|---|---|---|---|
| 01-01-01 | 1 | 01-01-PLAN.md task 01-01-01: counted `test_fidelity_sessions.py` runner and mandated original inventory invocation | 16; T-01-01/02/03 |
| 01-01-02 | 1 | 01-01-PLAN.md task 01-01-02: counted `test_fidelity_scenarios.py` runner | 12; T-01-02 |
| 01-02-01 | 2 | 01-02-PLAN.md task 01-02-01: counted `test_fidelity_review.py` runner; `node --test tests/fidelity-viewer.test.mjs` | Python 10, Node positive; T-01-04/05/06 |
| 01-02-02 | 2 | 01-02-PLAN.md task 01-02-02: `node --test tests/fidelity-viewer.test.mjs` | 16; T-01-04/05/06 |
| 01-03-01 | 2 | 01-03-PLAN.md task 01-03-01: counted `test_fidelity_ledger.py` runner | 12; T-01-07/08/09 |
| 01-03-02 | 2 | 01-03-PLAN.md task 01-03-02: counted ledger runner; `python3 tools/recon/fidelity_ledger.py validate --ledger docs/evidence/capabilities.json --requirements .planning/REQUIREMENTS.md` | 16 tests, 33 requirements; T-01-07/08/09 |
| 01-04-01 | 2 | 01-04-PLAN.md task 01-04-01: exact sourced-SDK observer command and counted `test_fidelity_observation.py` runner | Managed 8, Python 4; T-01-10/11/12 |
| 01-04-02 | 2 | 01-04-PLAN.md task 01-04-02: sourced-SDK observer/build and MovementTests/DirectorTests/CheckpointTests/BodyOwnershipTests commands | Managed 14 plus positive existing groups; T-01-10/11/12 |
| 01-05-01 | 3 | 01-05-PLAN.md task 01-05-01: counted `test_fidelity_checkpoint.py` runner; `bash -n scripts/prepare-fidelity-checkpoint.sh` | 12; T-01-13/14/15 |
| 01-05-02 | 3 | 01-05-PLAN.md task 01-05-02: counted checkpoint runner; package-free PowerShell command deferred to final human session | Python 16, Windows 8; T-01-13/14/15 |
| 01-06-01 | 4 | 01-06-PLAN.md task 01-06-01: counted `test_fidelity_capture.py` runner | 10; T-01-16/17/18 |
| 01-06-02 | 4 | 01-06-PLAN.md task 01-06-02: counted capture runner and original inventory command | 14; T-01-16/17/18 |
| 01-07-01 | 5 | 01-07-PLAN.md task 01-07-01: counted `test_fidelity_acceptance.py` runner; `python3 tools/recon/fidelity_acceptance.py ready --checkpoint dist/fidelity/phase01` | 14; T-01-19/20/21 |
| 01-07-02 | 5 | `python3 tools/recon/fidelity_acceptance.py audit --checkpoint dist/fidelity/phase01 --results dist/fidelity/phase01/results --require-complete` | Real matrix/native/original/human checks required; T-01-19/20/21 |
| 01-07-03 | 5 | `scripts/test.sh`; `python3 tools/recon/inventory.py ../Original --verify docs/original-manifest.json` | Positive consolidated counts, 539 originals; all threats |
| Task | Wave | Exact automated command binding | Minimum count / threat refs | Actual result |
|---|---|---|---|---|
| 01-01-01 | 1 | 01-01-PLAN.md task 01-01-01: counted `test_fidelity_sessions.py` runner and mandated original inventory invocation | 16; T-01-01/02/03 | green: 29 session tests; 539 originals |
| 01-01-02 | 1 | 01-01-PLAN.md task 01-01-02: counted `test_fidelity_scenarios.py` runner | 12; T-01-02 | green: 25 scenario tests |
| 01-02-01 | 2 | 01-02-PLAN.md task 01-02-01: counted `test_fidelity_review.py` runner; `node --test tests/fidelity-viewer.test.mjs` | Python 10, Node positive; T-01-04/05/06 | green: 21 review + 27 Node tests |
| 01-02-02 | 2 | 01-02-PLAN.md task 01-02-02: `node --test tests/fidelity-viewer.test.mjs` | 16; T-01-04/05/06 | green: 27 Node tests |
| 01-03-01 | 2 | 01-03-PLAN.md task 01-03-01: counted `test_fidelity_ledger.py` runner | 12; T-01-07/08/09 | green: 31 ledger tests |
| 01-03-02 | 2 | 01-03-PLAN.md task 01-03-02: counted ledger runner; `python3 tools/recon/fidelity_ledger.py validate --ledger docs/evidence/capabilities.json --requirements .planning/REQUIREMENTS.md` | 16 tests, 33 requirements; T-01-07/08/09 | green: 31 tests; 33 requirement mappings validated |
| 01-04-01 | 2 | 01-04-PLAN.md task 01-04-01: exact sourced-SDK observer command and counted `test_fidelity_observation.py` runner | Managed 8, Python 4; T-01-10/11/12 | green: 23 managed + 7 process tests |
| 01-04-02 | 2 | 01-04-PLAN.md task 01-04-02: sourced-SDK observer/build and MovementTests/DirectorTests/CheckpointTests/BodyOwnershipTests commands | Managed 14 plus positive existing groups; T-01-10/11/12 | green: observer/build and protected groups 28/23/4/3 |
| 01-05-01 | 3 | 01-05-PLAN.md task 01-05-01: counted `test_fidelity_checkpoint.py` runner; `bash -n scripts/prepare-fidelity-checkpoint.sh` | 12; T-01-13/14/15 | green: 25 checkpoint tests; shell syntax |
| 01-05-02 | 3 | 01-05-PLAN.md task 01-05-02: counted checkpoint runner; package-free PowerShell command deferred to final human session | Python 16, Windows 8; T-01-13/14/15 | green: 25 Python + 18 Linux-hosted PowerShell checks; native Windows session OPEN |
| 01-06-01 | 4 | 01-06-PLAN.md task 01-06-01: counted `test_fidelity_capture.py` runner | 10; T-01-16/17/18 | green: 23 capture tests; actual Linux capture OPEN |
| 01-06-02 | 4 | 01-06-PLAN.md task 01-06-02: counted capture runner and original inventory command | 14; T-01-16/17/18 | green: 23 capture tests; 539 originals; actual matrix OPEN |
| 01-07-01 | 5 | 01-07-PLAN.md task 01-07-01: counted `test_fidelity_acceptance.py` runner; `python3 tools/recon/fidelity_acceptance.py ready --checkpoint dist/fidelity/phase01` | 14; T-01-19/20/21 | green: 29 acceptance tests; readiness exit 0 |
| 01-07-02 | 5 | `python3 tools/recon/fidelity_acceptance.py audit --checkpoint dist/fidelity/phase01 --results dist/fidelity/phase01/results --require-complete` | Real matrix/native/original/human checks required; T-01-19/20/21 | OPEN: strict audit exit 1, errors=[], 0/120; fail-closed behavior covered by passing acceptance tests |
| 01-07-03 | 5 | `scripts/test.sh`; `python3 tools/recon/inventory.py ../Original --verify docs/original-manifest.json` | Positive consolidated counts, 539 originals; all threats | green: completed full suite exit 0; 539 originals |
All plan subcommands/paths are explicitly introduced in their owning tasks before verification. Run every focused task command after that task; at integrated checkpoint run the full suite once and repeat only after changes/failures. Quick checks target below 30 seconds, to be measured. Existing full suite and native runs can take longer and record separate durations. No new runtime/fixture/Windows results are claimed here.
All 15 task bindings were checked against the seven PLAN verify blocks and SUMMARY interfaces. No missing automated contract was found. Task 01-07-02 remains an explicit actual-evidence dependency; its expected nonzero strict audit is not a green acceptance result. Focused commands ran during their owning slices; the completed integrated suite and subsequent tooling regressions are recorded below. No full suite or large checkpoint hash walk was repeated for this audit.
The seven explicit classified spec-less boundaries and two unresolved unclassified manual assumptions are reconciled in 01-SOURCE-AUDIT.md. The two research backstop truths abstain to human_needed if actual original audiovisual capture/browser review is insufficient. Descriptor-less project prohibitions remain flagged-unverified, not silently passed. ASVS1 high/critical threats block acceptance; T-01-SC is reserved across plans.
## Wave 0 Requirements
## Wave 0 Requirements — Complete (Automation)
- Each implementation slice creates meaningful tests together with its production code; no empty stubs counted as validation.
- Create fidelity test fixtures covering changed/missing/added originals, output overlap, symlink/drive/case escape, reused session, tampered hash, invalid marker and unsupported schema.
- Create pure viewer tests including asymmetric durations, missing/buffering tracks, preserved playbackRate 1.0 and exclusive audio switching.
- Implemented fidelity test fixtures covering changed/missing/added originals, output overlap, symlink/drive/case escape, reused session, tampered hash, invalid marker and unsupported schema.
- Implemented pure viewer tests including asymmetric durations, missing/buffering tracks, preserved playbackRate 1.0 and exclusive audio switching.
- No external test-framework installation required. Existing full suite remains available.
## Manual-Only Verifications
@@ -72,14 +72,39 @@ The seven explicit classified spec-less boundaries and two unresolved unclassifi
Unavailable/failed executions are recorded as open dependencies. Completing tools or preparing a bundle does not close EVID-02/EVID-04 or mark Phase 1 accepted. Source-backed later work may continue only under the existing roadmap exception.
## Measured Verification Evidence
- Completed integrated run: `artifacts/fidelity/01-07-full-suite.json` and `.log`, exit 0 in **782.049626 seconds**. Actual output records 556 Python tests (180 fidelity), 27 Node tests, 23 standalone managed observer checks, two separate HUD tests, all 51 managed entry-point invocations/build, 36 rendered Vulkan receipts with zero reported validation errors, SDL dummy-audio checks and 539 unchanged originals. Optional native-window checks were not enabled. Dummy audio does not establish audibility.
- Subsequent code-review fixes: `01-FIX-REPORT.md` and `artifacts/fidelity/01-review-fixes/`. `python-fidelity.log` records **189 passing tests in 40.072 seconds**; `acceptance-final.log` records **29 passing acceptance tests** after the final standalone-transfer regression. These runs overlap; do not add their counts. `node-viewer-direct.log` records 27 behavior tests, `powershell.log` 18 synthetic checks under Linux-hosted PowerShell, and `original-preservation.log` 539 unchanged originals. The initial sandbox socket errors were resolved by the scoped local run; they are not represented as passes.
- Current discovery, without executing runtime loops: acceptance 29, capture 23, checkpoint 25, ledger 31, observation 7, review 21, scenarios 25, sessions 29: **190 current fidelity tests**. The final added acceptance test explains the difference from the earlier 189-test aggregate; it was executed in the final 29-test acceptance run. Discovery alone is not execution evidence.
- Review fixes exercise selected-receipt digest binding, pristine executable/inventory identity, named copy-state lifetime binding, sealed ledger/history projection including standalone transfer, and incomplete-session recovery without captured promotion. They strengthen existing covered contracts; independent review remains separate.
- Fresh immutable checkpoint: **11001 members**, `dist/fidelity/phase01`. Saved `01-review-fixes/readiness.json` reports `materials_ready: true`, `acceptance: human_needed` (command exit 0). Saved `acceptance.json` reports `errors: []`, **0/120**, all ten human findings pending (strict command exit 1). Original-DxWnd, native Windows and native Linux each retain 40 outstanding obligations.
- Focused tooling feedback is generally around 1–5 seconds (session/scenario/ledger around one second, checkpoint 4.742 seconds, review 5.234 seconds in owning summaries); observer process integration measured 19.126 seconds. The broad 40.072-second regression **exceeds** the proposed 30-second quick target. This is a latency WARNING, not a missing behavioral check or evidence acceptance.
## Validation Sign-Off
- [ ] Final plans bind every task to automated checks or explicit human/native evidence
- [ ] Sampling continuity has no three consecutive tasks without automated verification
- [ ] New test files exist and execute nonzero test counts
- [ ] No watch-mode flags
- [ ] Quick feedback latency measured below 30 seconds
- [ ] Native/original capture limitations recorded
- [ ] nyquist_compliant updated only after the implemented validation contract is audited
- [x] Final plans bind every task to automated checks or explicit human/native evidence
- [x] Sampling continuity has no three consecutive tasks without automated verification
- [x] New test files exist and execute nonzero test counts
- [x] No watch-mode flags
- [ ] Broad quick feedback below 30 seconds — measured 40.072 seconds; WARNING retained
- [x] Native/original capture limitations recorded
- [x] Implemented automated validation contract audited; `nyquist_compliant` and `wave_0_complete` refer only to automation coverage
- [ ] Actual combined capture and human review complete — OPEN
- [ ] EVID requirements and Phase 01 acceptance complete — OPEN
**Approval:** Pending execution; final task bindings are planned, while nyquist_compliant and wave_0_complete remain false until actual implementation and validation are audited.
**Automation validation:** Validated on 2026-11-13 from executed tests and retained logs; no new automated gap found, no tests or implementation changed. The latency target remains a documented warning. `status: validated` does not advance the phase or promote any EVID requirement.
**Acceptance dependencies:** A1, A2, EVID-02-unclassified, EVID-04-unclassified, P1, P2, P3, browser, paired_review and physical_input remain OPEN. Follow the single combined agenda in `docs/evidence/checkpoint-session.md` and its Windows/Linux session procedures. Collect actual original-DxWnd/native Windows/native Linux recordings, physical input and audible checks, review real paired playback, return the identified local results, then rerun strict acceptance. The Linux preflight's missing usable display/audio is an explicit dependency. Cross-publish, Wine, headless/synthetic fixtures and preparation cannot close it. Independent review/security gates remain owned by their respective audits.
## Final copy-state refinement
All191 fidelity checks pass in43.355s after02d182f (26 scenario,23 capture,29 acceptance); missing/hash-only/wrong-size state records are explicitly rejected for both lifetimes. The43.355s aggregate still exceeds the30s quick target. No manual acceptance was promoted.
## Validation Audit 2026-11-13
| Metric | Count |
|---|---|
| Gaps found | 0 |
| Resolved | 0 |
| Escalated | 0 |
@@ -0,0 +1,325 @@
---
phase: 01-reproducible-fidelity-baseline
verified: 2026-11-14T05:34:19Z
status: human_needed
score: 29/42 must-haves verified
covered_files: [".planning/REQUIREMENTS.md",".planning/ROADMAP.md",".planning/phases/01-reproducible-fidelity-baseline/01-01-PLAN.md",".planning/phases/01-reproducible-fidelity-baseline/01-01-SUMMARY.md",".planning/phases/01-reproducible-fidelity-baseline/01-02-PLAN.md",".planning/phases/01-reproducible-fidelity-baseline/01-02-SUMMARY.md",".planning/phases/01-reproducible-fidelity-baseline/01-03-PLAN.md",".planning/phases/01-reproducible-fidelity-baseline/01-03-SUMMARY.md",".planning/phases/01-reproducible-fidelity-baseline/01-04-PLAN.md",".planning/phases/01-reproducible-fidelity-baseline/01-04-SUMMARY.md",".planning/phases/01-reproducible-fidelity-baseline/01-05-PLAN.md",".planning/phases/01-reproducible-fidelity-baseline/01-05-SUMMARY.md",".planning/phases/01-reproducible-fidelity-baseline/01-06-PLAN.md",".planning/phases/01-reproducible-fidelity-baseline/01-06-SUMMARY.md",".planning/phases/01-reproducible-fidelity-baseline/01-07-PLAN.md",".planning/phases/01-reproducible-fidelity-baseline/01-07-SUMMARY.md","artifacts/fidelity/01-07-full-suite.json","artifacts/fidelity/01-07-full-suite.log","artifacts/fidelity/01-review-fixes/acceptance-final.json","artifacts/fidelity/01-review-fixes/python-fidelity-final.log","artifacts/fidelity/01-review-fixes/readiness-final.json","artifacts/fidelity/bytecode-fix/acceptance.json","artifacts/fidelity/bytecode-fix/fidelity-tests.log","artifacts/fidelity/bytecode-fix/observer-build.log","artifacts/fidelity/bytecode-fix/observer-retry.log","artifacts/fidelity/bytecode-fix/ready-bundled-1.json","artifacts/fidelity/bytecode-fix/ready-bundled-2.json","artifacts/fidelity/verification/01-07-final-checkpoint.json","docs/compatibility.md","docs/decisions.md","docs/evidence/README.md","docs/evidence/capabilities.json","docs/evidence/checkpoint-session.md","docs/evidence/linux-session.md","docs/evidence/phase01-baseline.md","docs/evidence/scenarios.json","docs/evidence/windows-session.md","docs/original-manifest.json","docs/progress.md","docs/tasks.md","scripts/collect-fidelity-linux.sh","scripts/collect-fidelity-windows.cmd","scripts/collect-fidelity-windows.ps1","scripts/env.sh","scripts/prepare-fidelity-checkpoint.sh","scripts/test.sh","src/GamePort/Application/FidelityObservation.cs","src/GamePort/Program.cs","tests/GamePort.FidelityObservationTests/GamePort.FidelityObservationTests.csproj","tests/GamePort.FidelityObservationTests/Program.cs","tests/fidelity-viewer.test.mjs","tests/fidelity-windows.Tests.ps1","tests/test_fidelity_acceptance.py","tests/test_fidelity_capture.py","tests/test_fidelity_checkpoint.py","tests/test_fidelity_ledger.py","tests/test_fidelity_observation.py","tests/test_fidelity_review.py","tests/test_fidelity_scenarios.py","tests/test_fidelity_sessions.py","tools/recon/fidelity.py","tools/recon/fidelity_acceptance.py","tools/recon/fidelity_capture.py","tools/recon/fidelity_checkpoint.py","tools/recon/fidelity_ledger.py","tools/recon/fidelity_receipts.py","tools/recon/fidelity_review.py","tools/recon/fidelity_viewer/index.html","tools/recon/fidelity_viewer/style.css","tools/recon/fidelity_viewer/viewer.mjs","tools/recon/inventory.py"]
covered_digest: "v4:sha256:acca5bdaa1f405a74d29d69c8ebe048085a6a4ff4c86e3b3f80c97cebfba8ac3"
behavior_unverified: 0
overrides_applied: 0
decision_coverage:
honored: 16
total: 16
not_honored: []
non_inferable_checks:
- truth: "Actual original-DxWnd moving game imagery and intelligible audio are observed and reviewed with wrapper/config limitations recorded."
status: uncertain
reason: insufficient_spec
human_check: A1
- truth: "Actual paired recordings decode, seek and switch exclusive audio in the identified local browser without concealing elapsed time."
status: uncertain
reason: insufficient_spec
human_check: A2
unverified_prohibitions:
- id: P1
statement: "MUST NOT sacrifice authoritative original bytes or execute the authoritative installation to make reference collection convenient."
status: unverified
flag: "unverified-prohibition — human review recommended"
- id: P2
statement: "MUST NOT manufacture apparent parity by retiming recordings, hiding drift, mixing both soundtracks or presenting synthetic media as an original reference."
status: unverified
flag: "unverified-prohibition — human review recommended"
- id: P3
statement: "MUST NOT erase contradictory history, hide unimplemented required content or turn missing evidence into a fidelity-completion claim."
status: unverified
flag: "unverified-prohibition — human review recommended"
human_verification:
- test: "A1 — Capture and observe the isolated original through the selected DxWnd setup"
expected: "Complete 40 original-Windows-DxWnd obligations; observe moving game imagery and intelligible game audio, retaining actual executable/profile/copy inventories and wrapper/configuration limitations."
why_human: "Original execution and audiovisual truth are unobserved; the backstop abstains with insufficient_spec."
- test: "A2 — Exercise actual paired recordings in the identified browser"
expected: "Both real recordings decode, play at actual speed, seek to their own observed events, preserve full tails and switch exclusive audio without concealing elapsed time."
why_human: "Controller tests use media doubles; they cannot establish real codec/browser/physical-audio behavior. Backstop: insufficient_spec."
- test: "EVID-02-unclassified — Review original capture boundaries and limitations"
expected: "Document observed original/DxWnd launch, crop, aspect, timing, recording boundaries and retained/fresh lifetimes for the actual reference captures."
why_human: "This flagged assumption cannot be inferred from prepared settings or synthetic metadata."
- test: "EVID-04-unclassified — Collect and inspect both native platform routes"
expected: "Complete 40 native Windows and 40 native Linux obligations with actual OS/GPU/driver/Vulkan/SDL/source/package/resource identity and observed route/input/audio continuity."
why_human: "Windows is cross-published only; current Linux TTY/auto_null preflight cannot capture native physical gameplay."
- test: "P1 — Resolve the original-preservation prohibition explicitly"
expected: "Confirm authoritative originals were never executed or changed; compare all 539 recorded hashes and generated-copy pre/retained/post inventories after the session."
why_human: "Descriptor-less unresolved prohibition requires explicit disposition; current preserved hashes do not prove future session conduct."
- test: "P2 — Resolve the honest-comparison prohibition explicitly"
expected: "Confirm genuine original media, no retiming or concealed drift, no mixed simultaneous soundtracks, and visible review gain/derivation provenance."
why_human: "Unverified-prohibition — human review recommended; genuine playback and perceived audiovisual comparison require observation."
- test: "P3 — Resolve the history/full-scope/native-transparency prohibition explicitly"
expected: "Confirm all 33 requirements and unimplemented content stay visible; conflicting/superseded evidence and native/Wine/component/cross-publish distinctions are preserved after reconciliation."
why_human: "Unverified-prohibition — human review recommended; final returned-evidence reconciliation requires explicit judgment."
- test: "browser — Review the complete local comparison interface"
expected: "With real captures, verify readable independent clocks/drift, keyboard controls, raw unobstructed default views, optional annotations/differences and visible loading/error/tail states."
why_human: "No actual browser visual/usability/codec review has been performed."
- test: "paired_review — Compare all corresponding actual recordings and record discrepancies"
expected: "Review matched events, imagery and sound across the required cases, retaining raw drift and justified system-specific observations without invented tolerances."
why_human: "No corresponding original/native pair or completed visual/audible comparison exists."
- test: "physical_input — Exercise visible native gameplay and actual audible devices"
expected: "On Linux and Windows use physical supported inputs through lab → VR04 → lab → outside, natural/skipped and fresh/retained cases, held input, banked jumps, landing and idle; confirm real display/audio output."
why_human: "Injected/headless/GPU/dummy-audio fixtures prove narrower behavior and cannot satisfy physical-input or audibility acceptance."
---
# Phase 1: Reproducible Fidelity Baseline Verification Report
**Phase Goal:** As a tester, I want to reproduce identified original/port comparison scenarios, so that I understand exactly what the current reconstruction proves on each native platform.
**Verified:** 2026-11-14T05:34:19Z
**Status:** human_needed
**Re-verification:** No existing VERIFICATION.md; completion of the interrupted initial verification after the MVP goal-format correction (`febb4a9`). No scope change or override.
## User Flow Coverage
| Step | Expected | Evidence | Status |
|---|---|---|---|
| Open the local checkpoint and inspect identities | Identified offline original copy, both port packages, complete agenda and viewer | Final readiness receipt: 11,001 immutable members; materials_ready true | VERIFIED for preparation |
| Reproduce isolated original scenarios | Moving imagery, intelligible audio, input/events and retained/fresh provenance from the actual selected DxWnd configuration | Collector/guide prepared; no returned original gameplay captures; 0/40 accepted | UNCERTAIN — WARNING; A1, EVID-02, P1 |
| Repeat matching native Linux/Windows routes | Same route/cases with physical input, real display/audio and exact runtime identities | Windows cross-publish only; real Linux preflight failed without selected X11/real audio; 0/80 accepted | UNCERTAIN — WARNING; EVID-04, physical_input |
| Inspect paired playback | Actual corresponding media with independent event times, exposed drift and exclusive audio | Controller is implemented/tested; prepared viewer contains no actual pair | UNCERTAIN — WARNING; A2, browser, paired_review, P2 |
| Trace what each capability proves | Source/implementation/platform/scope/discrepancy/remaining-acceptance links across the full game | 25 capabilities, six groups, all 33 requirements; current/history preserved | VERIFIED for traceability; P3 final judgment pending |
| Understand the reconstruction on each native platform | Actual identified original/native evidence plus honest discrepancies and unresolved limitations | Audit: errors [], 0/120 accepted; ten named human findings pending | UNCERTAIN — WARNING; user-story outcome remains open |
The MVP user flow is incomplete. No new technical runtime/test run was started to bypass it. The implementation evidence below records inspected code and already completed local verification; it does not constitute manual acceptance. Phase 1 is not passed and Phase 2 is not advanced by this report.
## Goal Achievement
### Observable Truths
Roadmap criteria are retained in full; PLAN truths add detail and do not reduce them. VERIFIED on a tooling truth certifies its bounded implementation, not original/native fidelity. UNCERTAIN items request human verification rather than asserting missing implementation. No accepted override exists.
| ID | Truth | Status | Evidence |
|---|---|---|---|
| SC1 | A reviewer can verify every original against the recorded inventory and run investigation/reference copies without altering the original installation. | UNCERTAIN — WARNING | `verify_inventory`/staging and saved 539-file check prove current preservation; actual generated-copy reference execution and P1 disposition remain unobserved. |
| SC2 | A tester can reproduce identified whole-original reference scenarios from an isolated generated installation and inspect corresponding input/events, images and audio where applicable; unavailable execution keeps this criterion open. | UNCERTAIN — WARNING | Actual original-DxWnd captures absent; explicit access limitation leaves 40 obligations open (A1/EVID-02). |
| SC3 | A reviewer can trace every full-game capability from original evidence through current implementation, platform receipts, discrepancies and its remaining acceptance condition. | VERIFIED | Ledger validator/export/renderer connect 25 capabilities to all 33 requirements, source paths, implementation revisions, scoped platform records, differences and open acceptance. |
| SC4 | Testers can repeat the same baseline movement/route scenarios on native Linux and native Windows with exact revision identities; Wine/cross-publish receipts remain separately labeled and cannot close missing native execution. | UNCERTAIN — WARNING | No accepted current native baseline capture on either platform: 40 Linux + 40 Windows obligations remain open (EVID-04/physical_input). |
| 01.1 | A reviewer can stage and identify a pristine generated original installation without altering any original byte (EVID-01, D-15). | VERIFIED | `fidelity.py:stage` calls `stage_original`; `verify_inventory` compares all recorded file identities before/after isolated copying. Saved original-preservation log verifies 539 unchanged originals. Actual DxWnd execution remains separately pending. |
| 01.2 | The protocol requires continuous lab → VR04 → lab → outside and focused dialogue-return, left/right banked-jump, landing and idle captures per D-01 and D-04. | VERIFIED | `scenarios.json` requires continuous lab → VR04 → lab → outside plus dialogue-return, left/right bank, landing/idle; `validate_scenario_contract`/`audit_scenarios` enforce obligations. |
| 01.3 | Natural/skipped dialogue and fresh/retained entry are equally required, independently identified dimensions per D-02 and D-03. | VERIFIED | Eight case IDs independently cross fresh/retained, natural/skipped and ordinary/held-input; scenario validator rejects collapsed dimensions. |
| 01.4 | Equal, nested, symlink-aliased and Windows case-aliased source/output paths fail before any staging write; sibling paths merely sharing a textual prefix remain distinct. | VERIFIED | `separated_roots`, symlink rejection and canonical path checks precede staging writes; session regressions cover equal/nested/case/symlink/prefix cases. |
| 01.5 | Empty/missing inventories fail; single-file fixtures round-trip, while changed, missing and added files invalidate identity. | VERIFIED | `identify_tree` rejects empty inventory; exact file-list comparison rejects changed/missing/added files; single-file round-trip regressions are active. |
| 01.6 | Manifest order is canonical relative POSIX path order; case-colliding identities fail instead of acquiring filesystem-dependent order. | VERIFIED | `identify_tree` sorts POSIX paths and rejects casefold collisions; canonical-order regression checks actual list/digest values. |
| 01.7 | Interrupted staging/import leaves an explicit incomplete diagnostic and no completed receipt; simultaneous same-session allocation has one winner, and duplicate receipt imports are idempotent only for byte-identical content. | VERIFIED | `_reserve`, exclusive writes, incomplete siblings and atomic publication implement allocation/import ownership. Named concurrency/interruption/duplicate regressions in `test_fidelity_sessions.py` pass in saved 191-test run. |
| 01.8 | Typed receipt validation retains failures and missing evidence as open acceptance; D-13 Windows availability is not a runtime receipt. | VERIFIED | `validate_receipt`/`audit_scenarios` separate failure, synthetic, component, Wine and native kinds. Current real failed Linux receipt remains OPEN; availability is no receipt. |
| 02.1 | A tester opens a local scenario with paired original/port playback and corresponding image, audio and input/event links per D-05. | UNCERTAIN — WARNING | Exporter/controller support paired validated receipts, but final `review.json` has no actual original/native pair. A1/A2/browser/paired_review remain human checks. |
| 02.2 | Raw captures are unobstructed by default; annotations and provenance-bound image differences are optional overlays per D-06. | VERIFIED | Controller defaults `annotations`/`difference` false; corresponding Node overlay/provenance regressions cover opt-in state. Actual visual unobstruction remains part of browser review. |
| 02.3 | Selecting an event seeks each recording to its own observed time; both play at actual speed with separate elapsed clocks, event drift and playback drift per D-07. | VERIFIED | Named Node event-selection/drift/readiness tests assert separate observed times, rate 1, independent elapsed clocks and exposed drift. This verifies controller behavior, not actual codec/browser playback. |
| 02.4 | The reviewer switches corresponding original/port audio with at most one source audible and visible review gain per D-08. | VERIFIED | Named exclusive-soundtrack/gain tests assert both muted before selecting one and labeled review-only gain. Physical audibility remains pending. |
| 02.5 | Missing, buffering, rejected-play, decoding and asymmetric-end states remain visible and preserve the full recording tails. | VERIFIED | Named rejected-play/buffering/decode/asymmetric-end tests assert paired pause, visible cause and resumable full longer tail. Real browser observation is still A2. |
| 03.1 | Reviewers browse movement, contacts, gadgets, progression, visuals and audio with requirement/source/scenario/platform links per D-09. | VERIFIED | `GROUPS` and ledger contain movement, contacts, gadgets, progression, visuals and audio; exported capability links include source/requirement/scenario/platform. |
| 03.2 | Each capability leads with working behavior, verified scope/platform, known differences and remaining acceptance per D-10. | VERIFIED | Capability rows carry working summary, verified scope, implementation revision, differences and open acceptance; renderer presents supplied facts. |
| 03.3 | Current applicable evidence precedes expandable explicitly superseded revision history per D-11; applicability uses content/scope/platform rather than newest date. | VERIFIED | Scope/content/platform applicability and explicit supersession retain current/history. Final reviewed fix verifies both projections survive bundle export; newest date is not acceptance. |
| 03.4 | Discrepancies order blocking/disruptive failures before subtler differences and missing verification per D-12; all missing evidence keeps acceptance open. | VERIFIED | `IMPACTS` orders blocking/disruptive/subtle/missing_verification; acceptance stays open. Strict current audit has no accepted runtime obligations. |
| 03.5 | All 33 full-game requirements have capability coverage even when unimplemented; an empty ledger fails and one capability remains renderable. | VERIFIED | Ledger covers 25 capabilities and all 33 requirements across six groups; validator rejects empty ledger, renderer supports a singleton. Full-game implementation is not claimed. |
| 03.6 | Equal receipt/content identities merge only when the record bytes match; conflicts remain explicit, and duplicate history rows never silently overwrite evidence. | VERIFIED | Canonical byte conflict checks prevent contradictory receipt/content deduplication and preserve history; ledger regression assertions cover conflicts. |
| 03.7 | Equal-priority entries have deterministic stable ID ordering; explicit supersession cycles and unresolved contradictory current claims fail validation. | VERIFIED | Stable ID sorting, supersession-cycle and contradictory-current validation are implemented and covered by active ledger regressions. |
| 04.1 | An optional passive observer records actual native port input/control/scene events across the continuous route per D-01, without changing gameplay or scene lifetime. | VERIFIED | `Program.cs:18-30` owns one optional observer across outer Run continuations; post-Step calls at 1328-1333 use actual accepted input/state. Managed/process regressions cover observer wiring; no physical route acceptance inferred. |
| 04.2 | Natural/skipped and fresh/retained runs have distinct case identities, with one monotonic session across actual retained continuations per D-02 and D-03. | VERIFIED | One retained observer/monotonic session spans Run continuations; distinct case identity and simulation ticks are preserved. Existing observer tests exercise clock/order/continuation. |
| 04.3 | Held/neutral input, banked jump, landing and idle observations retain their real owner/tick/time per D-04; injected smoke fixtures stay separately classified. | VERIFIED | Actual raw SDL/input/state/control calls include owner/tick/time; smoke/injected paths are separately classified. Managed and process assertions check payload/receipt interoperability. |
| 04.4 | An output failure leaves the observation incomplete and visible rather than reporting acceptance or changing movement/state to finish the recording. | VERIFIED | Observer write failure emits an incomplete diagnostic without completing acceptance; standalone managed failure regressions exercise this path. |
| 05.1 | One complete local checkpoint bundle contains identified port packages, a verified generated original copy, scenarios, viewer and result collection per D-14. | VERIFIED | Final checkpoint receipt identifies 11,001 immutable members, both sealed packages, generated original seed, protocol, viewer and result collectors; readiness true. |
| 05.2 | The available Windows PC is treated as a pending execution environment per D-13; actual OS/GPU/driver/tool identities are collected during the session. | VERIFIED | Windows session guide/collector require actual OS/GPU/driver/tool observations; no native Windows receipt exists. Pending environment is explicitly distinguished from execution. |
| 05.3 | The original launches only from a generated copy through the user's identified DxWnd binary/exported profile, separately from native port receipts, per D-15. | UNCERTAIN — WARNING | Collector protects original-pristine, copies a writable run, retains selected DxWnd/profile and requires GUI launch. Actual user-selected DxWnd execution/configuration is unobserved; A1/P1 pending. |
| 05.4 | All original-reference and port materials are prepared before one combined session per D-16; preparation does not close EVID-02 or EVID-04. | VERIFIED | Readiness validates both package identities and complete 80-obligation Windows agenda; guide also requires 40 Linux obligations. `ready()` always reports human_needed. |
| 05.5 | Launcher preflight or recording failure produces an actionable local failure receipt without inventing successful capture or downloading dependencies. | VERIFIED | Collector/preflight failures retain diagnostic/open states. Actual Linux TTY/null-audio failure is retained; PowerShell recovery checks cover aborted incomplete collection without invented success. |
| 06.1 | An identified native Linux package yields actual input/event and audiovisual captures where execution is available; synthetic/headless replays remain distinct (EVID-04). | UNCERTAIN — WARNING | Native Linux collector invokes identified package/observer and real recorder only after preflight. Current host has no selected real display/audio and produced failed preflight, with no gameplay capture. |
| 06.2 | Continuous route and focused captures cover all natural/skipped, fresh/retained and ordinary/edge cells per D-01–D-04, with missing executions explicitly open. | UNCERTAIN — WARNING | Matrix/scenario implementation requires all 40 Linux obligations and tracks missing cases, but no physical Linux route/focused capture is accepted. |
| 06.3 | Physical input/audio and real visible gameplay require actual native receipts/human review; dummy audio and window-only fixtures cannot complete acceptance. | VERIFIED | Preflight rejects dummy/null devices; native review requires real input/audibility/visibility. Strict audit cannot accept headless/synthetic fixtures. |
| 07.1 | One fully prepared combined session covers original-DxWnd and native Windows cases, local Linux review and real paired playback, per D-13–D-16. | UNCERTAIN — WARNING | Materials and one-session agenda are ready; the combined original/native/browser session has not occurred. |
| 07.2 | Every required original-reference and native Linux/Windows case has exact revision/package/resource/media and observation provenance; absent or failed cases keep EVID-02/EVID-04 open. | UNCERTAIN — WARNING | Strict audit reports 0/120 accepted, no structural errors and every missing obligation. Exact successful runtime/media provenance cannot yet be verified. |
| 07.3 | Paired review of actual original/port captures applies D-05–D-08 and publishes raw drift, discrepancies and audible/visible checks. | UNCERTAIN — WARNING | No actual paired recordings or witnessed drift/audio/visual review returned; paired_review/P2 remain pending. |
| 07.4 | Current capabilities/history/discrepancies are reconciled to returned receipts per D-09–D-12, with full matrix completeness per D-01–D-04. | UNCERTAIN — WARNING | Current baseline and ledger honestly retain missing evidence; returned-receipt reconciliation awaits actual collection and agent-owned normalization/import. |
| 07.5 | Actual original-DxWnd moving game imagery and intelligible audio are observed and reviewed with wrapper/config limitations recorded. | UNCERTAIN — WARNING | UNCERTAIN — insufficient_spec: no observed original-DxWnd moving imagery/intelligible audio and wrapper review (A1); metadata fixtures cannot prove it. |
| 07.6 | Actual paired recordings decode, seek and switch exclusive audio in the identified local browser without concealing elapsed time. | UNCERTAIN — WARNING | UNCERTAIN — insufficient_spec: no actual identified-browser decode/seek/exclusive-audio observation (A2); Node media doubles cannot prove browser codecs or audibility. |
**Score:** 29/42 truths verified; 13 UNCERTAIN. **Present-but-behavior-unverified invariants:** 0. Existing behavioral regressions exercise the tooling transitions; the unverified items concern actual external execution, media, physical experience and final reconciliation. A1/A2 separately abstain with `insufficient_spec`.
### Required Artifacts and Wiring Evidence
Owner `query verify.artifacts` independently returned exit 0 for each of seven PLANs: **21/21 declared artifacts** exist and are substantive. Source inspection then checked their actual callers and data contracts.
| Plan | Declared artifacts | Implementation/wiring evidence | Status |
|---|---|---|---|
| 01-01 | fidelity.py; fidelity_receipts.py; scenarios.json | CLI dispatches stage/identify/import/validate; shared validators consume supplied protocol and real byte inventories | VERIFIED |
| 01-02 | fidelity_review.py; fidelity_viewer/viewer.mjs; fidelity-viewer.test.mjs | Validated receipt export → review.json/local media → fetch → controller/renderer; actual pair absent | VERIFIED implementation; actual browser pending |
| 01-03 | capabilities.json; fidelity_ledger.py; docs/evidence/README.md | Validator checks tracked source/requirements/scenarios; canonical export supplies bundle and viewer current/history projection | VERIFIED |
| 01-04 | FidelityObservation.cs; managed observer test Program.cs; test_fidelity_observation.py | Outer Program continuation owns observer; actual raw/input/control/state hooks feed ordered JSONL; process tests feed receipt contract | VERIFIED bounded observer |
| 01-05 | fidelity_checkpoint.py; collect-fidelity-windows.ps1; windows-session.md | Preparation launcher calls assembler; actual files sealed/preflighted; PowerShell emits same versioned contract for later validated import | VERIFIED implementation; native execution pending |
| 01-06 | fidelity_capture.py; linux-session.md; collect-fidelity-linux.sh | Shell execs collector; selected package/observer/recorder argv and real-device preflight feed failure/capture collection and matrix | VERIFIED implementation; native physical capture pending |
| 01-07 | fidelity_acceptance.py; checkpoint-session.md; phase01-baseline.md | Explicit selected receipts/hashes + complete scenario audit + ten findings decide strict acceptance; baseline accurately leaves evidence open | VERIFIED implementation; final reconciliation pending |
Paths above are the exact declared repository paths shown in each PLAN and fingerprint; no artifact is merely an unused placeholder.
### Key Link Verification
The owner heuristic returned 1/14 literal-path links and exit 1 on each PLAN. It searches literal target paths; Python module imports, C# class use, external schema contracts and prose names do not match. Those negative heuristic results are not treated as verified. Manual traces establish the implemented connections below; runtime-return links stay explicitly pending.
| From → To | Actual connection | Status |
|---|---|---|
| fidelity.py → inventory baseline | stage_original → verify_inventory compares inventory.py-compatible file list with docs/original-manifest.json; no direct inventory.py import is needed | WIRED by shared inventory contract |
| fidelity_receipts.py → scenarios.json | CLI/capture pass loaded protocol to validate_scenario_contract/audit_scenarios; stable IDs and required obligations validated | WIRED |
| fidelity_review.py → fidelity_receipts.py | Imports and calls read_receipt, validate_receipt, contained_path, identify_file before export | WIRED |
| viewer.mjs → generated review/media | fetch('review.json') supplies per-side media/events to createPairController; controller enforces exclusive mute and independent times | WIRED; actual media/browser pending |
| capabilities.json → REQUIREMENTS.md | Validator extracts exact IDs and rejects incomplete coverage; all 33 IDs accounted for | WIRED |
| fidelity_ledger.py → viewer ledger | Canonical export/current/history projection copied during checkpoint assembly and rendered by renderCapabilities | WIRED |
| Program.cs → FidelityObservation.cs | Optional outer using owner passed through Run; real post-Step acceptsInput/state/control/raw SDL hooks call observer | WIRED |
| Observed JSONL → shared receipts | Versioned session/case/elapsed/tick payload validated through process interoperability and collector; synthetic scope preserved | WIRED contract; real route pending |
| prepare-fidelity-checkpoint.sh → fidelity_checkpoint.py | Explicit Python invocation consumes original inventory and completed sealed packages | WIRED |
| Windows collector → shared receipts | Emits schema-versioned raw receipts, exact content identities and failure states; documented agent-owned validation/import normalizes returned reviewed records | WIRED contract; actual returned data pending |
| fidelity_capture.py → Linux package/observer | Uses actual package executable/assets and --fidelity-* arguments after real display/audio preflight | WIRED; hardware execution pending |
| Linux receipts → review/acceptance | Collected diagnostics undergo shared validation/import and explicit current selection; real failed Linux receipt remains open | WIRED failure path; successful route pending |
| Returned Windows/Linux results → strict audit | audit reads current.json, validates contained selected receipts and receipt_sha256 binding, checks all 120 slots and named reviews | WIRED implementation; human return pending |
| phase01-baseline.md → capability ledger | Same open acceptance/current scope retained; documented reconciliation updates receipt-bound current/history after return | WIRED present baseline; future reconciliation pending |
### Data-Flow Trace (Level 4)
| Rendered/accepted value | Actual source and flow | Finding |
|---|---|---|
| Capability navigation/current/history/discrepancies | capabilities.json → validate/export → sealed protocol/capability-ledger.json → review.json → renderCapabilities | FLOWING: real maintained evidence; unimplemented and missing scopes remain visible |
| Paired video/audio/event times | Actual imported receipt artifacts/hashes → _side/_events export → review.json → media/controller | Implementation wired; current source is explicitly missing, not synthetic original footage |
| Observer input/state/elapsed | Actual SDL/control/post-Step data → retained observer → bounded JSONL → collector/receipt validation | FLOWING in bounded regressions; current complete physical capture unavailable |
| Native acceptance totals | Explicit selected actual receipt files + content identities → audit_scenarios + CHECKS → strict report | FLOWING: actual failed diagnostic yields 0/120, errors [], human_needed |
Missing media is expected open evidence and is displayed as such; no hardcoded empty success path or invented original recording closes it.
### Existing Behavioral Evidence Reviewed
This completion pass did not rerun tests or launch services. Commands/results below are from retained execution receipts/logs, not SUMMARY assertions; fresh owner queries covered artifact presence, story validity and decision coverage.
| Evidence | Recorded invocation/result | Limit |
|---|---|---|
| Integrated local suite | artifacts/fidelity/01-07-full-suite.json and .log: scripts/test.sh, exit 0, 782.049626s; 556 Python (180 fidelity), 27 Node, 23 managed observer, 2 HUD, 51 managed entry-point invocations, 36 rendered GPU receipts, zero Vulkan errors, 539 originals | Before later tooling-only review fixes; dummy audio/headless checks are not physical/native baseline capture |
| Final tooling regression | artifacts/fidelity/01-review-fixes/python-fidelity-final.log: 191 tests, 43.355s, OK | Includes final copy-state artifact-root fix; no new runtime change or full GPU rerun claimed |
| Media controller | artifacts/fidelity/01-review-fixes/node-viewer-direct.log: 27 pass, 0 fail/skipped; named independent seek/drift, exclusive mute, rejected play, buffering, decode and full-tail assertions inspected | Media doubles exercise controller transitions, not actual browser decoding/audibility |
| Preservation | artifacts/fidelity/01-review-fixes/original-preservation.log: 539 unchanged originals | Byte preservation at check time; final P1 session conduct still needs disposition |
| Readiness | artifacts/fidelity/01-review-fixes/readiness-final.json plus verification/01-07-final-checkpoint.json: 11,001 members, materials_ready true, human_needed | Sealed runtime provenance retained as 446930d dirty true / diff 90cef956…; later tooling revision does not relabel it |
| Strict acceptance | artifacts/fidelity/01-review-fixes/acceptance-final.json: require-complete exit 1, errors [], accepted 0/120, all ten findings pending | Expected open evidence; no malformed acceptance input or observed code failure |
No phase-declared shell probe requiring a separate new execution was identified; the phase relies on the retained local CLI/test/preflight evidence. No full suite was repeated in this completion pass.
### Requirements Coverage
All four accountable requirement IDs are declared across the seven PLANs; no Phase 1 requirement is orphaned. Pending is retained in REQUIREMENTS.md.
| Requirement | Source PLANs | Evidence and remaining dependency | Disposition |
|---|---|---|---|
| EVID-01 | 01,05,06,07 | 539 unchanged originals; bounded isolated staging, canonical inventory and pre/post checks implemented. Final actual session preservation/P1 remains pending | Pending — current preservation verified; final human disposition required |
| EVID-02 | 01,02,04,05,07 | Original-DxWnd collector/protocol/identity/review tooling ready; 0/40 actual original obligations and A1/original-boundary review open | Pending — NEEDS HUMAN |
| EVID-03 | 02,03,07 | All 33 full-game requirements represented in 25 capabilities/six groups; source/implementation/platform/history/discrepancy/open acceptance traceable. Returned-evidence reconciliation and P3 remain open | Pending — ledger implementation verified; final human/reconciliation dependency |
| EVID-04 | 01,02,04,05,06,07 | Native collectors, observer and exact package binding implemented; failed Linux physical preflight retained, no accepted native route; 0/80 accepted | Pending — NEEDS HUMAN |
### Decision Coverage
Owner query: **16/16** trackable CONTEXT decisions honored, not_honored []. “All trackable CONTEXT.md decisions are honored by shipped artifacts.” Advisory gate only; it does not change acceptance.
### Test Quality and Anti-Patterns
Active tests assert concrete identity bytes, rejection behavior, monotonic ownership/state, media-controller transitions and acceptance classification. Test-generated metadata/media are explicitly synthetic fixtures: they verify validators/controller behavior and are never original/native fidelity oracles. The complete-metadata positive matrix test cannot establish actual physical execution; strict real matrix stays 0/120.
The targeted completion scan found no unreferenced TBD/FIXME/XXX or disabled requirement-test markers in the fidelity source/tests/scripts/observer scope; the prior completed 40-file debt/skip scan is retained. Expected empty initial review and false human-review fields preserve missing evidence. They are not stubs claiming completion. No new blocking anti-pattern was established.
Existing gates remain recorded: security 22/22 mitigated, zero open; validation automation complete with manual checks open; independent review verification closes all five historical findings after 02d182f. UI review was explicitly disabled for this phase by the recorded gate configuration; TDD is inactive. These gates were not reopened. Broad tooling feedback 43.355s exceeds its 30s quick target (WARNING), with no effect on native acceptance.
### Human Verification Required
**Ten named findings remain pending.** Collect, observe and return one complete local result tree following docs/evidence/checkpoint-session.md and its Windows/Linux subguides. The integration agent owns evidence-backed normalization, reviewed-copy creation, hash validation, import, current selection, ledger reconciliation and final strict audit after return. Raw receipts remain immutable. Positive human findings must never be generated automatically.
#### 1. A1 — Capture and observe the isolated original through the selected DxWnd setup
**Test:** A1 — Capture and observe the isolated original through the selected DxWnd setup using the combined-session guide.
**Expected:** Complete 40 original-Windows-DxWnd obligations; observe moving game imagery and intelligible game audio, retaining actual executable/profile/copy inventories and wrapper/configuration limitations.
**Why human:** Original execution and audiovisual truth are unobserved; the backstop abstains with insufficient_spec.
#### 2. A2 — Exercise actual paired recordings in the identified browser
**Test:** A2 — Exercise actual paired recordings in the identified browser using the combined-session guide.
**Expected:** Both real recordings decode, play at actual speed, seek to their own observed events, preserve full tails and switch exclusive audio without concealing elapsed time.
**Why human:** Controller tests use media doubles; they cannot establish real codec/browser/physical-audio behavior. Backstop: insufficient_spec.
#### 3. EVID-02-unclassified — Review original capture boundaries and limitations
**Test:** EVID-02-unclassified — Review original capture boundaries and limitations using the combined-session guide.
**Expected:** Document observed original/DxWnd launch, crop, aspect, timing, recording boundaries and retained/fresh lifetimes for the actual reference captures.
**Why human:** This flagged assumption cannot be inferred from prepared settings or synthetic metadata.
#### 4. EVID-04-unclassified — Collect and inspect both native platform routes
**Test:** EVID-04-unclassified — Collect and inspect both native platform routes using the combined-session guide.
**Expected:** Complete 40 native Windows and 40 native Linux obligations with actual OS/GPU/driver/Vulkan/SDL/source/package/resource identity and observed route/input/audio continuity.
**Why human:** Windows is cross-published only; current Linux TTY/auto_null preflight cannot capture native physical gameplay.
#### 5. P1 — Resolve the original-preservation prohibition explicitly
**Test:** P1 — Resolve the original-preservation prohibition explicitly using the combined-session guide.
**Expected:** Confirm authoritative originals were never executed or changed; compare all 539 recorded hashes and generated-copy pre/retained/post inventories after the session.
**Why human:** Descriptor-less unresolved prohibition requires explicit disposition; current preserved hashes do not prove future session conduct.
#### 6. P2 — Resolve the honest-comparison prohibition explicitly
**Test:** P2 — Resolve the honest-comparison prohibition explicitly using the combined-session guide.
**Expected:** Confirm genuine original media, no retiming or concealed drift, no mixed simultaneous soundtracks, and visible review gain/derivation provenance.
**Why human:** Unverified-prohibition — human review recommended; genuine playback and perceived audiovisual comparison require observation.
#### 7. P3 — Resolve the history/full-scope/native-transparency prohibition explicitly
**Test:** P3 — Resolve the history/full-scope/native-transparency prohibition explicitly using the combined-session guide.
**Expected:** Confirm all 33 requirements and unimplemented content stay visible; conflicting/superseded evidence and native/Wine/component/cross-publish distinctions are preserved after reconciliation.
**Why human:** Unverified-prohibition — human review recommended; final returned-evidence reconciliation requires explicit judgment.
#### 8. browser — Review the complete local comparison interface
**Test:** browser — Review the complete local comparison interface using the combined-session guide.
**Expected:** With real captures, verify readable independent clocks/drift, keyboard controls, raw unobstructed default views, optional annotations/differences and visible loading/error/tail states.
**Why human:** No actual browser visual/usability/codec review has been performed.
#### 9. paired_review — Compare all corresponding actual recordings and record discrepancies
**Test:** paired_review — Compare all corresponding actual recordings and record discrepancies using the combined-session guide.
**Expected:** Review matched events, imagery and sound across the required cases, retaining raw drift and justified system-specific observations without invented tolerances.
**Why human:** No corresponding original/native pair or completed visual/audible comparison exists.
#### 10. physical_input — Exercise visible native gameplay and actual audible devices
**Test:** physical_input — Exercise visible native gameplay and actual audible devices using the combined-session guide.
**Expected:** On Linux and Windows use physical supported inputs through lab → VR04 → lab → outside, natural/skipped and fresh/retained cases, held input, banked jumps, landing and idle; confirm real display/audio output.
**Why human:** Injected/headless/GPU/dummy-audio fixtures prove narrower behavior and cannot satisfy physical-input or audibility acceptance.
### Acceptance Conclusion
Autonomous preparation is complete; the promised real comparison outcome remains human_needed. No implementation BLOCKER was established in this bounded completion. The observable absence of original/native accepted captures is a documented human/external evidence dependency, explicitly kept open by the roadmap contract, not silently passed.
A1/A2 are **unverified non-inferable checks** (`insufficient_spec`); P1/P2/P3 are **unverified-prohibition — human review recommended**, with no automatic resolution. No later phase specifically replaces Phase 1 capture/review obligations, so none are deferred. No phase completion, advancement, commit or push was performed.
The fingerprint was produced by the owner CLI `query verification.fingerprint` over the listed actual source/test/document/evidence inputs; its returned fields are copied verbatim. Planning PLAN/SUMMARY coverage was added by the owner. SUMMARYs supply intended interfaces, not proof of behavior.
---
_Verified: 2026-11-14T05:34:19Z_
_Verifier: gsd-verifier_
## Bounded Verification Follow-up — Bundled Bytecode Fix (2026-11-14)
The first actual UAT readiness command exposed a tooling defect: Python local imports created `__pycache__/*.pyc` inside the sealed checkpoint, so later immutable-tree checks could fail. This qualifies the earlier readiness evidence; it was not an original/native capture or an A1 pass. Historical bundle `phase01-before-bytecode-fix-20261114T215109Z` is preserved. The freshly assembled `dist/fidelity/phase01` retains 11,001 immutable members and existing result/run history.
Independently inspected regression commit `23ee1c2` and implementation commit `2fe8b40`. The regression invokes all five copied bundled CLI entry points using `python -E`, checks that no bytecode appears, invokes copied checkpoint preflight twice, and compares the complete tree identity before/after. The fix sets `sys.dont_write_bytecode = True` only under `__name__ == '__main__'`, before local imports, in acceptance/checkpoint/capture/review/ledger. It adds two required sys imports and changes no gameplay, library algorithm, receipt schema or acceptance decision.
| Retained evidence inspected | Actual result and scope |
|---|---|
| bytecode-fix/ready-bundled-1.json and ready-bundled-2.json | Exact bundled-cwd default-python readiness command succeeded twice without -B: materials_ready true, 11,001 members, human_needed; updated checkpoint identity receipt records zero created bytecode files |
| bytecode-fix/fidelity-tests.log | Initial broad attempt ran 185 test methods, with an observer-class setup ERROR caused by its 90-second .NET build timeout; the run is FAILED, not a passing aggregate. The completed methods include the 26 checkpoint regressions |
| bytecode-fix/observer-build.log | Separate bounded build succeeded in 72.12s, zero errors; one NU1900 vulnerability-index access warning retained |
| bytecode-fix/observer-retry.log | Observer-only retry: seven tests PASS in 24.473s; 192 target checks are covered across the separate runs, not by a successful initial full run |
| bytecode-fix/acceptance.json | Strict audit remains exit 1, errors [], 0/120 accepted, all ten named human findings pending |
| verification/01-07-final-checkpoint.json | Current manifest/READY identities updated for source fix 2fe8b40; package runtime provenance remains separately identified |
Evidence paths above are under `artifacts/fidelity/`. No tests, runtime, full GPU suite or wider audit were rerun by this follow-up verifier. The reviewed change is confined to bundled CLI cache behavior; no new native compatibility or gameplay claim follows. The user-selected UAT restart preserves all ten pending findings and agent-owned result reconciliation.
**Follow-up verdict:** the bounded bytecode defect is corrected by the inspected implementation and retained behavioral evidence. Overall status remains **human_needed**, score **29/42**, with **all ten human checks pending**. Fingerprint refreshed through the owner CLI over the prior 65 inputs plus the six evidence files above; prior proof is retained.
_Follow-up verified: 2026-11-14T21:58:58Z_
@@ -1 +1 @@
No external API integration: Phase 01 implements local filesystem provenance, native process capture, offline media review and a contained loopback file viewer; it consumes existing game/tool executables without adding a hosted service, external SDK integration or remote API capability.
No external API integration: Phase 01 uses local files, native capture, offline media review and a loopback viewer; no hosted API or external SDK is added.
@@ -0,0 +1,35 @@
<!-- CONSUMED: final verification completed human_needed on2026-11-14. Current next action: $gsd-verify-work 1 and combined actual human session; historical interrupted-verifier notes below are superseded. -->
---
context: phase
phase: 01-reproducible-fidelity-baseline
plan: "07"
task: 3
total_tasks: 3
status: consumed
last_updated: "2026-11-13T22:26:46.798618+00:00"
---
# Final verification quota checkpoint
Quota guard explicitly requested pause at15%. Resume completed task01-07-03 and recovered fullsuite exit0 (782.049626s), then reviewed/fixed allfive source-integrity findings. Do NOT redo implementation or tests. Source commits through02d182f, review/coverage/security documentation71366e7. Fullsuite556Python/180fidelity,27Node,23observer,2HUD,51managedentrypoints,36GPUrenderedreceipts,zeroVulkanvalidationerrors,SDLdummychecks,539originalhashes. Latertooling-onlyfixes: all191fidelityregressions PASS43.355s; focused26scenario,23capture,29acceptance,27Node,18LinuxhostedPowerShell. All539originals unchanged. No runtime changes afterfullsuite; no need13minGPUrerun forcurrentPython/collector fixes.
Historicalreview5915128: CR01selected-vs-reviewedpath,CR02originalinventory/executablebinding,CR03copy-stateidentity,WR01viewerledgerprojection,WR02interruptedWindowsfinalization. Fixes5569bc2,bda35e5,6e5ee0b,548c97a,2608517,a821754. Independentre-reviewcaughtremaininghash-onlycopy-statebypass; RED48fca0d/GREEN02d182f requiresactual_checked_artifactwithrootinside_scenario_observation; callersupdated. Finalindependentre-reviewallfiveFIXED in01-REVIEW-VERIFY.md; dispositionopen0. Securityauditorfinal22/22mitigated, threats_open0 in01-SECURITY.md. Nyquistautomationcoveragevalidatedall15taskbindings; manualacceptanceopen;191fidelityaggregate43.355sec exceeds30secquicktargethonestly. UIreviewdisabledconfigfalse. No remainingknowncode/securityblockers.
Currentfreshfinalbundle dist/fidelity/phase01 has11001immutableentries. Currenthashes/readinessreceipt artifacts/fidelity/verification/01-07-final-checkpoint.json. readyexit0true,strictauditexit1 errors[] accepted0/120,10humanpending; logs artifacts/fidelity/01-review-fixes/readiness-final.json,acceptance-final.json,python-fidelity-final.log. Oldbundlespreserved phase01-pre-review-48100025 andphase01-pre-copy-artifact-7ceebcb3. ActualLinuxfailedpreflightimportedcurrentbundle/results/imported. Runtimepackage source446930d dirty/diff90cef956 unchanged; source/docscommitsmustnotrelabelitsidentity. Original/nativeWindows+DxWnd andphysicalLinuxvisible/audible/browserreviewremainonecombinedhuman session pending. Humanonlycollects/observes/returns; agent-ownedexactnormalizationmapping incheckpoint-session.md. No capture request issued yet because finalphaseverification/handoffpending.
Final typed verifier phase01_final_verification was dispatched at21%; quota15% interrupted it, instructedfinishonlyboundedhuman_neededreport/fingerprint thenreturn. It had readall7musthaves/summaries, checked25capabilities/33requirements/0unmapped/6groups/33rows,16/16decisioncoverage,40sourcefilesnoskip/debtscan. A mandatoryMVPgoalformatguard exposed existingROADMAPMode:mvp plainproseGoal. Rootauthorizedformat-only identicalintentuserstory and modifiedROADMAP.md uncommitted: As a tester, I want to reproduce identified original/port comparison scenarios, so that I understand exactly what the current reconstruction proves on each native platform. Validatorvalidtrue; no scope/successcriteriamodified. OneverifiercommandusedwrongunittestclassFidelityAcceptance (loadererror,correctclassAcceptanceTests); twoothernamedbehaviorcheckspassed; don'tmislabelthatcommandassuccess. Priorfulltargeted29passestablishactualcoverage.
NEXT: Reconcile currentverifier's 01-VERIFICATION.md and CLI verification.status; ifreport/fingerprintabsentfinishthat ONLY beforeanynewphase. FingerprintmustbeownerCLIgenerated, notmanual. Oncehuman_neededstatusvalid, persistUATfromnamedhumanitems, updateSTATE/consumedhandoffs, commitverifiedreport+goalmetadata+handoffdocs andpush verifiedsource/tooling toauthorizedGitea/main. Lastpushedhead remainsd18f551; later01-07/task3/reviewfix/auditcommits arelocalawaitingfinalverification. Preserveunrelatedtools.yaml. Do notadvancephase2orclaimPhase1accepted; allEVIDIDsPending0/120humanacceptance. No source changesuncommittedexceptROADMAPformatandpossiblynewverifierreport.
Nativeagents/sourcewritesallfinishedexceptverifierreportbeingclosed. Quota watcher runs and actual15%steeringworks. Noauto-resume; usermust $gsd-resume-workafterreset. Don'tspendquota rereadingmassiveGSDscriptbodies orrerunningfinished13minfullsuite. Existinglocalpackages/media/originalcopiesstaylocal, noCI/uploads. MaintracksGitea/main, scoped.gitwriteescalation; retainhistoricalhandoffsmarkconsumedratherthandelete (priorautomaticreviewrejecteddeletion).
## Required Reading
AGENTS.md,parentinstructions,HANDOFF.json,01-07SUMMARY,01-REVIEW-VERIFY,01-SECURITY,01-VALIDATION,and01-VERIFICATIONifpresent.
## Critical Anti-Patterns
| Pattern | Description | Severity | Prevention Mechanism |
|---|---|---|---|
| Redo completed tests | Fullsuiteand191fidelitychecksfinished | advisory | Reconcile savedlogs first; rerunonlyafternewchanges |
| False phase completion | Preparedmaterialsfailactualstrictacceptance0/120 | advisory | KeepEVIDPending andhuman_needed; owner verification.status beforeadvance |
## Infrastructure State
Testsfinished; verifierinterruptedatpause; reportreconciliationpending; localquota watcher running. No sourceworkeractive.
## Next Action
Inspect01-VERIFICATION.md and owner verification.status; finish report/fingerprint/UAT ifneeded, commit/pushverified01-07reviewedwork; neverredo task3/fulltests orautoapprovehumanacceptance.
+3 -3
View File
@@ -46,8 +46,8 @@
],
"next": {
"command": "$gsd-progress --next",
"label": "Advance to the next step",
"reason": "Phase 1 of 8 · 0% · executing"
"label": "Review prepared Phase 1 checkpoint and pending combined human session",
"reason": "Phase 1 remains open: 7/7 autonomous preparation records, actual acceptance human_needed 0/120; Phase 2 not advanced"
},
"updated_at": "2026-11-13T00:13:04.735Z"
"updated_at": "2026-11-13T21:49:00Z"
}
+81
View File
@@ -0,0 +1,81 @@
# Codex quota guard
This repository has a local Linux watcher and project hooks for the user's
requested GSD quota policy. The watcher polls the existing Codex app-server every
60 seconds; it does not start model turns or read credentials. It uses the
300-minute account window and its actual reset timestamp, preferring the general
`codex` bucket over specialty-model buckets.
- At **20% remaining or less**, `PreToolUse` denies new `Agent`, `spawn_agent`,
and `followup_task` calls. Existing workers may finish their safe checkpoint.
- At **15% remaining or less**, the watcher saves a separate recovery snapshot
and sends each registered active turn one request to checkpoint with
`$gsd-pause-work` and end. Tool hooks also supply that instruction once per turn.
- Missing, expired, or older-than-180-second quota data blocks new worker dispatch
until a fresh reading arrives. Checkpoint tools remain available.
- The watcher never starts a turn, interrupts a process, commits unfinished work,
pushes code, or automatically resumes after reset.
## One-time activation
The source is `tools/workflow/codex_quota_guard.py`; project configuration is
`.codex/hooks.json`. Existing global GSD hooks are preserved and additive.
Open **`/hooks`** in Codex, review and trust the five hooks from this project's
`.codex/hooks.json`. New definitions remain skipped until reviewed; see the
[official hook trust instructions](https://learn.chatgpt.com/docs/hooks#review-and-trust-hooks).
The watcher has been started for this host, but thread registration and tool
blocking require trusted hooks. A later session's `SessionStart` hook starts
another watcher only if one is not already running.
The guard targets this Linux Codex host, not the Windows original-game test
machine. Windows uses a no-op command override. It does not restart Codex or
change provider/model/account settings.
## Commands
From the repository root:
```sh
python3 tools/workflow/codex_quota_guard.py status
python3 tools/workflow/codex_quota_guard.py refresh
python3 tools/workflow/codex_quota_guard.py start
python3 tools/workflow/codex_quota_guard.py stop
```
`status` includes the lock-verified `running` flag, current reading, reset epoch,
and any last poll error type. `refresh` uses the existing local daemon socket and
may need execution outside the agent sandbox. It neither starts a daemon nor a
model turn. `stop` requests termination within a second after any in-flight RPC
finishes; hooks start the watcher again, so disable the project hooks in `/hooks`
when turning the guard off permanently. `start` clears the stop marker when its
singleton watcher starts. No service or cron entry is installed.
After quota resets, send **`$gsd-resume-work`**. The current saved continuation is
phase 01, plan 01-05, task 2; preserve its partial edits and do not repeat task 1.
Resumption remains a user action even after the account has recovered.
## Recovery and limits
Ignored private state is under `artifacts/gsd-quota/`. `quota.json` stores only
counters/timestamps. Per-thread registration stores thread/turn identifiers, not
conversation contents. At low quota, `recovery-<reset>/record.json` saves the Git
HEAD, status, tracked patch (capped at 2 MiB), and existing GSD state/handoff text
(capped at 256 KiB each). It supplements and never replaces the canonical GSD
handoff. Untracked file contents remain in the working tree; this is not a full
backup. Source changes after that one-per-window snapshot rely on the working
tree and the model's final handoff. Files are private to the local account.
The pause is **cooperative**. Polling may lag usage by a minute, a long active
model request may consume the reserve, and no model can guarantee writing a
handoff after the provider exhausts quota. The independent recovery record still
runs without model tokens. Tool hooks cover supported local tool paths; launching
workers through unrelated shell scripts or other clients bypasses this specific
dispatch policy. Weekly and specialty-model limits are not guarded. Inactive or
mismatched turns are never restarted by the watcher.
Verified against local Codex 0.169.0: real Unix WebSocket quota read, project hook
discovery (five hooks awaiting trust), singleton background watcher, and 24 targeted
unit tests. Simulated low-quota tests verify pause steering and snapshot behavior;
no real quota depletion or active gameplay work was induced to test the threshold.
See the [official app-server protocol](https://learn.chatgpt.com/docs/app-server)
and [hook contracts](https://learn.chatgpt.com/docs/hooks).
+122
View File
@@ -1,5 +1,127 @@
# Compatibility and validation
## Bundled checker cache fix — 2026-11-14
A user readiness check created Python bytecode inside the sealed checkpoint and
then rejected it as unexpected immutable material. Regression23ee1c2 reproduces
this; fix2fe8b40 disables bytecode writes before local imports in all five bundled
Python command entry points. All26 checkpoint tests pass, including a real copied
CLI test with environment overrides ignored. The exact bundled readiness command
passes twice without creating pyc files. A fresh11,001-member checkpoint replaces
phase01; the old tree and its cache/results are retained in local history, and
existing results/generated execution copies were copied into the new mutable roots.
The broader attempt ran185 tests but failed observer class setup after a90-second
.NET build timeout. A separate bounded local build passed; the seven observer
checks then passed on their own retry. Thus all192 fidelity checks are covered
across the two runs; the initial full attempt remains recorded as failed.
No runtime implementation changed. Actual original/native acceptance remains
0/120 OPEN and all ten human UAT items remain pending.
## Phase 1 verification — human session pending
Final owner-validated verification is `human_needed`:29/42 truths verified and13
uncertain pending actual observations. Ten named checks are saved in
`.planning/phases/01-reproducible-fidelity-baseline/01-UAT.md`. Autonomous materials,
review fixes, security and automation coverage are complete. Actual acceptance
remains0/120 OPEN; all EVID requirements stay Pending and Phase2 is unadvanced.
The combined session guide is `docs/evidence/checkpoint-session.md`; the local
checkpoint is `dist/fidelity/phase01`. Resume human verification with
`$gsd-verify-work 1`. No new build/test or gameplay claim accompanies this report.
## Final phase 1 review closure
All five review findings are independently verified fixed. The final copy-state
refinement is02d182f; all191 fidelity regressions pass in43.355s, with29 acceptance,
26 scenario and23 capture checks in the affected suites. Earlier review fixes
also pass27 Node and18 Linux-hosted PowerShell checks;539 originals stay unchanged.
The recovered full local suite passed782.049626s before these tooling-only review
fixes:556 Python,27 Node,23 observer,2 HUD,51 managed entry points and36 GPU render
receipts, zero Vulkan validation errors. The full GPU suite was not repeated for
these Python/collector fixes. Independent security audit closes22/22 planned
threats. Current fresh checkpoint is `dist/fidelity/phase01` (11,001 immutable
entries); exact current manifest/READY identities are recorded locally in
`artifacts/fidelity/verification/01-07-final-checkpoint.json`. Earlier bundle
history is preserved locally. All120 actual original/native acceptance obligations
and ten named human findings remainOPEN. Final phase verification is pending.
## Phase 1 final checkpoint — materials ready, runtime acceptance OPEN
Fresh `dist/fidelity/phase01` readiness passes11,000 immutable members. Strict audit
exits1 with0/120 accepted and ten pending human findings. Failed Linux preflight
`linux-01-06-matrix-preflight-linux` identifies no display/auto_null only; it is
diagnostic evidence, not captured gameplay. Native Windows and actual original-
DxWnd remain unexecuted; automated GPU/SDL fixtures cannot establish physical
input/audibility. Runtime packages retain446930d dirty/diff90cef956, separately
from later tools/docs commits; originals and generated packages/media stay local.
Complete local suite: exit 0 in 782.05s (runner: 783s), with 556 Python
(180 fidelity), 27 Node, 23 managed observer, 2 separate HUD Python tests,
51 managed test entry points and the main build. The 36 GPU rendered receipts,
27 saved readbacks and 17 material/readback assertions report zero validation
errors. SDL dummy-audio checks pass; 539 original hashes match. Optional native
window tests were not enabled; dummy consumption supplies no audible proof.
Final exit/duration: `artifacts/fidelity/01-07-full-suite.json`, with the complete
log alongside it; the first74.65s attempt is retained
separately for the corrected Node reporter/count guard failure. Exact final
checkpoint identities: `artifacts/fidelity/verification/01-07-final-checkpoint.json`.
See [remaining acceptance](evidence/phase01-baseline.md). All EVID requirements and
Phase1 acceptance stay OPEN under the roadmap source-backed continuation exception.
## Phase 1 plan 01-06 — reviewed tooling evidence
Primary repeats23 capture tests; executor records156 broader fidelity tests
and539 unchanged originals. Actual host TTY/no-display/auto_null preflight failed
with a structurally valid imported receipt. No Linux gameplay capture was made;
all40 Linux and120 total acceptance obligations remainOPEN.
## Phase 1 plan 01-05 — reviewed tooling evidence
24 checkpoint tests and17 actual PowerShell selftests pass in primary review;
executor records133 broader fidelity checks,539 unchanged originals, and both
Python/PowerShell preflights of the10,983-file offline bundle. Linux copied-apphost
--help passes after executable mode preservation. Actual Windows gameplay,
original-DxWnd comparison and full runtime acceptance remain0/120 OPEN.
## Workflow quota guard — 2026-11-13
Local Codex0.169.0 Linux Unix-WebSocket quota read and watcher verified; five
project hooks discovered, awaiting user trust. Targeted simulated quota, policy,
transport and recovery tests pass. Real exhaustion/active-turn pause is not
induced; pause remains cooperative. Windows hook override is a no-op. No game
build, package or original/native Windows acceptance claim changes.
## Phase 1 wave 2 bounded observer evidence
Full authorized wave2 `scripts/test.sh` exits0:462 Python+2 HUD checks,
all existing managed projects and36 GPU/render checks pass with zero Vulkan
validation errors (GTX1070); SDL stream/lifecycle checks and539 original hashes
pass. The initial sandbox run retained8 denied-loopback errors; no tests were
skipped, and the authorized rerun passed. Viewer27 named Node checks and the
observer23 managed checks retain their separate passing receipts. Logs are
local under `artifacts/fidelity/wave2-test*.log`.
Plan01-04 passes23 managed checks,7 port-process checks and protected groups
Movement28/Director23/Checkpoint4/BodyOwnership3. The real LV1B→VR04→LV1B
fixture retains one observer clock. Native Linux SDL/Vulkan under private Xvfb
on/off passes with4 identical GPU readbacks and zero validation errors, using
actual dirty-source/diff and DLL identities recorded in its local comparison
report. No physical input/audio, full route, original-DxWnd or native Windows
acceptance follows. Debug and isolated Linux self-contained publish pass;
NU1900 is the existing unavailable vulnerability-metadata warning. All539
originals match. Exact receipts/limitations:
`../.planning/phases/01-reproducible-fidelity-baseline/01-04-SUMMARY.md`.
## Phase 1 resumed — capability ledger complete
User resumed from the usage pause. Plan01-03 is complete:25 capabilities cover
all33 requirements and33 checkpoint rows across6 groups. Primary repeats31
ledger tests and103 combined fidelity tests;539 original hashes match. Earlier
viewer27 Node checks and synthetic Chromium smoke remain their bounded evidence.
Full details: `../.planning/phases/01-reproducible-fidelity-baseline/01-03-SUMMARY.md`.
Actual original-DxWnd/native Linux/native Windows acceptance remains OPEN0/120.
Next: plan01-04 passive port observer; no new gameplay behavior or original/native
comparison was established by the ledger work.
## Phase 1 wave 1 tooling verification
Full wave1 `scripts/test.sh` exits0:403 Python checks plus2 HUD checks,
+111
View File
@@ -1,5 +1,116 @@
# Decisions
## Bundled checker cache fix — 2026-11-14
A user readiness check created Python bytecode inside the sealed checkpoint and
then rejected it as unexpected immutable material. Regression23ee1c2 reproduces
this; fix2fe8b40 disables bytecode writes before local imports in all five bundled
Python command entry points. All26 checkpoint tests pass, including a real copied
CLI test with environment overrides ignored. The exact bundled readiness command
passes twice without creating pyc files. A fresh11,001-member checkpoint replaces
phase01; the old tree and its cache/results are retained in local history, and
existing results/generated execution copies were copied into the new mutable roots.
The broader attempt ran185 tests but failed observer class setup after a90-second
.NET build timeout. A separate bounded local build passed; the seven observer
checks then passed on their own retry. Thus all192 fidelity checks are covered
across the two runs; the initial full attempt remains recorded as failed.
No runtime implementation changed. Actual original/native acceptance remains
0/120 OPEN and all ten human UAT items remain pending.
## Phase 1 verification — human session pending
Final owner-validated verification is `human_needed`:29/42 truths verified and13
uncertain pending actual observations. Ten named checks are saved in
`.planning/phases/01-reproducible-fidelity-baseline/01-UAT.md`. Autonomous materials,
review fixes, security and automation coverage are complete. Actual acceptance
remains0/120 OPEN; all EVID requirements stay Pending and Phase2 is unadvanced.
The combined session guide is `docs/evidence/checkpoint-session.md`; the local
checkpoint is `dist/fidelity/phase01`. Resume human verification with
`$gsd-verify-work 1`. No new build/test or gameplay claim accompanies this report.
## Final phase 1 review closure
All five review findings are independently verified fixed. The final copy-state
refinement is02d182f; all191 fidelity regressions pass in43.355s, with29 acceptance,
26 scenario and23 capture checks in the affected suites. Earlier review fixes
also pass27 Node and18 Linux-hosted PowerShell checks;539 originals stay unchanged.
The recovered full local suite passed782.049626s before these tooling-only review
fixes:556 Python,27 Node,23 observer,2 HUD,51 managed entry points and36 GPU render
receipts, zero Vulkan validation errors. The full GPU suite was not repeated for
these Python/collector fixes. Independent security audit closes22/22 planned
threats. Current fresh checkpoint is `dist/fidelity/phase01` (11,001 immutable
entries); exact current manifest/READY identities are recorded locally in
`artifacts/fidelity/verification/01-07-final-checkpoint.json`. Earlier bundle
history is preserved locally. All120 actual original/native acceptance obligations
and ten named human findings remainOPEN. Final phase verification is pending.
## Final fidelity audit — phase 1 plan 01-07
Readiness verifies immutable prepared bytes and current copied materials;
strict acceptance separately requires complete original/native matrix coverage,
matching package/source/resource identities and receipt-bound human judgments.
Structural `--allow-open` success never promotes acceptance. Preserve raw collector
receipts and failed/superseded history; the integration agent performs explicitly
specified evidence-backed post-return normalization, while the tester only
collects, observes and returns local files. A1/A2, both unclassified assumptions
and P1/P2/P3 remain visible until actual review. No universal fidelity tolerance,
automatic physical/audible pass or movement/landing reset is introduced.
Current result: ready11,000 files; strict audit human_needed,0/120. Positive-count
guards cover the existing fidelity suites in one consolidated local run; Node
uses explicit TAP so installed reporter defaults cannot hide the executed count.
The completed local run exits 0 in 782.05s: 556 Python (180 fidelity), 27 Node,
23 observer and 2 separate HUD Python tests; all 51 managed test entry points,
the main build, 36 GPU rendered receipts, 17 material/readback assertions,
dummy-audio checks and 539 original hashes pass. These bounded regression facts
do not resolve physical/audible/native/original acceptance.
## Linux capture access — phase 1 plan 01-06
A common failed native display/audio preflight may explain all40 Linux open
obligations. Do not fabricate40 launches or substitute fixture playback. Preserve
actual package seals, unique session history and retained prerequisite evidence.
Physical input, moving content and audible playback remain human gates.
## Offline checkpoint review — phase 1 plan 01-05
Keep prepared-material readiness separate from runtime acceptance. Identify
external tools without copying their executables; preserve raw media and terminal
results. Retain source executable modes when copying local Linux packages; byte
hashes alone do not establish runnable apphost permissions. Windows collection
selftests on Linux establish tooling behavior only.
## Quota reserve — 2026-11-13
Use actual300-minute account quota and server reset time. Reserve20% for
existing workers and15% for handoff. Poll locally without model turns; preserve
a private independent recovery snapshot and request cooperative GSD pause.
Never auto-resume, commit partial source, restart Codex, or bypass hook trust.
See [guard contract](codex-quota-guard.md).
## Passive evidence observation — phase 1 wave 2
Keep one optional application-owned clock across Run continuations. Record raw,
requested and actual gate-accepted input separately after existing owner calls;
copy state without new gameplay ownership or callback reads. Script activity,
explicit skip actions and transitions carry actual observed provenance. Observer
failures disable recording with incomplete diagnostics and do not reset/retry
simulation. Output is caller-selected for standalone packages, bounded and
exclusive; fixtures/headless/debug-injected runs are labeled port_fixture.
Observer overhead and incomplete coverage stay explicit. Existing algorithms,
TSK retained/fresh ordering and collision admission gates are preserved.
## Phase 1 resumed — capability ledger complete
User resumed from the usage pause. Plan01-03 is complete:25 capabilities cover
all33 requirements and33 checkpoint rows across6 groups. Primary repeats31
ledger tests and103 combined fidelity tests;539 original hashes match. Earlier
viewer27 Node checks and synthetic Chromium smoke remain their bounded evidence.
Full details: `../.planning/phases/01-reproducible-fidelity-baseline/01-03-SUMMARY.md`.
Actual original-DxWnd/native Linux/native Windows acceptance remains OPEN0/120.
Next: plan01-04 passive port observer; no new gameplay behavior or original/native
comparison was established by the ledger work.
## Phase 1 evidence contract — wave 1
Session/receipt schema1 records original/copy/package/media identities separately.
+895
View File
@@ -0,0 +1,895 @@
# Capability evidence ledger
Generated by tools/recon/fidelity_ledger.py from [capabilities.json](capabilities.json).
Capabilities: 25; requirements: 33; unmapped: 0. Acceptance: **OPEN**.
Current means exact named content/platform/scope applicability, including explicitly historical bytes. A report link is not a new execution; date or docs HEAD never promotes proof. Original-DxWnd/native matrix acceptance remains **0/120** until identified captures and review.
Regenerate and validate locally:
```sh
python3 tools/recon/fidelity_ledger.py validate --ledger docs/evidence/capabilities.json --requirements .planning/REQUIREMENTS.md
python3 tools/recon/fidelity_ledger.py render --ledger docs/evidence/capabilities.json --output docs/evidence/README.md
python3 tools/recon/fidelity_ledger.py export --ledger docs/evidence/capabilities.json --output artifacts/fidelity/review/ledger.json
python3 tools/recon/fidelity_review.py export --ledger artifacts/fidelity/review/ledger.json --output artifacts/fidelity/review/new-review
```
Omitting recordings creates an explicitly missing-media review. Add --original and --port imported receipt.json paths when available. Scenario IDs link to the [eight-cell protocol](scenarios.json). Ledger evidence summaries are typed report records; only receipt_path entries reference imported version 1 receipts. Missing local artifacts retain their reasons. Source/implementation links are tracked bounded UTF-8 text; viewer export copies them into its contained sources/ tree.
## Movement
### action-animation
**Working behavior:** Original morph resources and bounded movement/turn/action aliases play; task and script controls have bounded tests.
**Verified scope/platform:** Checkpoint ANIM S/P/M/R and historical Linux renders; loop closure, advance and action aliases are partly port policy.
**Known differences:** Original playback flags/rate, acceptance, interruption and completion callbacks remain incomplete.
**Remaining acceptance — OPEN:** Recover one-shot/loop/end and movement/landing/talk/skip action ownership; compare actual original playback.; Identified whole-original DxWnd and current native Linux/Windows scenario capture/review remain open (0/120 obligations).
**Requirements:** MOVE-03 · **Implementation:** {&#x27;revision&#x27;: &#x27;1ae5f4251c26f3b0446f333e994694f99eab5be6&#x27;, &#x27;paths&#x27;: [&#x27;src/GamePort/Game/PlayerAppearance.cs&#x27;, &#x27;src/GamePort/Game/SceneDirector.cs&#x27;], &#x27;status&#x27;: &#x27;bounded&#x27;, &#x27;note&#x27;: &#x27;Revision identifies the last tracked change to the first implementation path; it is not a runtime/package identity. Unimplemented denotes the named full-scope workflow, not absence of all foundations.&#x27;}
**Sources:** [Retained checkpoint contracts and source-report links](../../docs/checkpoint/coverage.md), [Implementation gates and historical execution ledger](../../docs/checkpoint/implementation-plan.md), [Revision-specific runtime and package status index](../../docs/progress.md), [Platform classifications and limits](../../docs/compatibility.md), [Implementation: PlayerAppearance.cs](../../src/GamePort/Game/PlayerAppearance.cs), [Implementation: SceneDirector.cs](../../src/GamePort/Game/SceneDirector.cs)
**Scenarios:** [fresh-natural-edge](scenarios.json), [fresh-natural-ordinary](scenarios.json), [fresh-skipped-edge](scenarios.json), [fresh-skipped-ordinary](scenarios.json), [retained-natural-edge](scenarios.json), [retained-natural-ordinary](scenarios.json), [retained-skipped-edge](scenarios.json), [retained-skipped-ordinary](scenarios.json)
**Current applicable evidence (only the targets below):**
- {&quot;artifacts&quot;: [], &quot;claim&quot;: {&quot;key&quot;: &quot;action-animation-coverage&quot;, &quot;result&quot;: &quot;Original morph resources and bounded movement/turn/action aliases play; task and script controls have bounded tests.&quot;}, &quot;content&quot;: {&quot;report_sha256&quot;: &quot;4481cb6df6748bc38a8808da64a93206f5e02326bc37e6fa2104f189b9339dea&quot;}, &quot;evidence_kind&quot;: &quot;static&quot;, &quot;historical&quot;: false, &quot;id&quot;: &quot;action-animation-report&quot;, &quot;method&quot;: &quot;Existing documentation inspected and indexed; not new binary recovery, component execution or gameplay capture&quot;, &quot;missing_evidence&quot;: [&quot;Identified whole-original DxWnd and current native Linux/Windows scenario capture/review remain open (0/120 obligations).&quot;], &quot;platform&quot;: {&quot;execution&quot;: &quot;static&quot;, &quot;os&quot;: &quot;source&quot;}, &quot;reason&quot;: null, &quot;receipt_id&quot;: &quot;action-animation-report&quot;, &quot;report_path&quot;: &quot;docs/checkpoint/coverage.md&quot;, &quot;revision&quot;: &quot;bdca29d3aa31face0c0023537ff98783716dbc45&quot;, &quot;scope&quot;: [&quot;action-animation: documentary coverage only&quot;], &quot;status&quot;: &quot;current&quot;, &quot;supersedes&quot;: []}
**Explicit applicability targets:** [{&#x27;id&#x27;: &#x27;action-animation-documentation&#x27;, &#x27;content&#x27;: {&#x27;report_sha256&#x27;: &#x27;4481cb6df6748bc38a8808da64a93206f5e02326bc37e6fa2104f189b9339dea&#x27;}, &#x27;platform&#x27;: {&#x27;os&#x27;: &#x27;source&#x27;, &#x27;execution&#x27;: &#x27;static&#x27;}, &#x27;scope&#x27;: [&#x27;action-animation: documentary coverage only&#x27;]}]
<details><summary>History — exact revisions and supersession retained</summary>
- No superseded evidence recorded.
</details>
**Player-impact discrepancies:**
- **disruptive** · action-animation-remaining: Recover one-shot/loop/end and movement/landing/talk/skip action ownership; compare actual original playback.
- **missing_verification** · action-animation-verification: Identified whole-original DxWnd and current native Linux/Windows scenario capture/review remain open (0/120 obligations).
### controller-phases
**Working behavior:** Recovered ground/air/facing/jump arithmetic and prior-body then registry input ordering support bounded Jimmy movement.
**Verified scope/platform:** Recorded S/P/M/R: 108 controller component comparisons, later 146 air/render observations and native Linux five-jump-alias replays; not whole-original cadence.
**Known differences:** Fixed 60 Hz remains a port policy; mouse/controller, full base wrappers and grouped actor/morph cadence remain incomplete.
**Remaining acceptance — OPEN:** Recover intended device/focus sampling, full movement modes and interacting owner/cadence contracts before broad parity claims.; Identified whole-original DxWnd and current native Linux/Windows scenario capture/review remain open (0/120 obligations).
**Requirements:** MOVE-01 · **Implementation:** {&#x27;revision&#x27;: &#x27;0e2f426d425153d4452a67f288813067caa624da&#x27;, &#x27;paths&#x27;: [&#x27;src/GamePort/Game/JimmyGroundMotion.cs&#x27;, &#x27;src/GamePort/Game/JimmyAirMotion.cs&#x27;, &#x27;src/GamePort/Game/JimmyOrientation.cs&#x27;, &#x27;src/GamePort/Game/FixedStepClock.cs&#x27;], &#x27;status&#x27;: &#x27;bounded&#x27;, &#x27;note&#x27;: &#x27;Revision identifies the last tracked change to the first implementation path; it is not a runtime/package identity. Unimplemented denotes the named full-scope workflow, not absence of all foundations.&#x27;}
**Sources:** [Retained checkpoint contracts and source-report links](../../docs/checkpoint/coverage.md), [Implementation gates and historical execution ledger](../../docs/checkpoint/implementation-plan.md), [Revision-specific runtime and package status index](../../docs/progress.md), [Platform classifications and limits](../../docs/compatibility.md), [Implementation: JimmyGroundMotion.cs](../../src/GamePort/Game/JimmyGroundMotion.cs), [Implementation: JimmyAirMotion.cs](../../src/GamePort/Game/JimmyAirMotion.cs), [Implementation: JimmyOrientation.cs](../../src/GamePort/Game/JimmyOrientation.cs), [Implementation: FixedStepClock.cs](../../src/GamePort/Game/FixedStepClock.cs)
**Scenarios:** [fresh-natural-edge](scenarios.json), [fresh-natural-ordinary](scenarios.json), [fresh-skipped-edge](scenarios.json), [fresh-skipped-ordinary](scenarios.json), [retained-natural-edge](scenarios.json), [retained-natural-ordinary](scenarios.json), [retained-skipped-edge](scenarios.json), [retained-skipped-ordinary](scenarios.json)
**Current applicable evidence (only the targets below):**
- {&quot;artifacts&quot;: [], &quot;claim&quot;: {&quot;key&quot;: &quot;controller-phases-coverage&quot;, &quot;result&quot;: &quot;Recovered ground/air/facing/jump arithmetic and prior-body then registry input ordering support bounded Jimmy movement.&quot;}, &quot;content&quot;: {&quot;report_sha256&quot;: &quot;4481cb6df6748bc38a8808da64a93206f5e02326bc37e6fa2104f189b9339dea&quot;}, &quot;evidence_kind&quot;: &quot;static&quot;, &quot;historical&quot;: false, &quot;id&quot;: &quot;controller-phases-report&quot;, &quot;method&quot;: &quot;Existing documentation inspected and indexed; not new binary recovery, component execution or gameplay capture&quot;, &quot;missing_evidence&quot;: [&quot;Identified whole-original DxWnd and current native Linux/Windows scenario capture/review remain open (0/120 obligations).&quot;], &quot;platform&quot;: {&quot;execution&quot;: &quot;static&quot;, &quot;os&quot;: &quot;source&quot;}, &quot;reason&quot;: null, &quot;receipt_id&quot;: &quot;controller-phases-report&quot;, &quot;report_path&quot;: &quot;docs/checkpoint/coverage.md&quot;, &quot;revision&quot;: &quot;bdca29d3aa31face0c0023537ff98783716dbc45&quot;, &quot;scope&quot;: [&quot;controller-phases: documentary coverage only&quot;], &quot;status&quot;: &quot;current&quot;, &quot;supersedes&quot;: []}
**Explicit applicability targets:** [{&#x27;id&#x27;: &#x27;controller-phases-documentation&#x27;, &#x27;content&#x27;: {&#x27;report_sha256&#x27;: &#x27;4481cb6df6748bc38a8808da64a93206f5e02326bc37e6fa2104f189b9339dea&#x27;}, &#x27;platform&#x27;: {&#x27;os&#x27;: &#x27;source&#x27;, &#x27;execution&#x27;: &#x27;static&#x27;}, &#x27;scope&#x27;: [&#x27;controller-phases: documentary coverage only&#x27;]}]
<details><summary>History — exact revisions and supersession retained</summary>
- No superseded evidence recorded.
</details>
**Player-impact discrepancies:**
- **disruptive** · controller-phases-remaining: Recover intended device/focus sampling, full movement modes and interacting owner/cadence contracts before broad parity claims.
- **missing_verification** · controller-phases-verification: Identified whole-original DxWnd and current native Linux/Windows scenario capture/review remain open (0/120 obligations).
### route-control
**Working behavior:** Lab/VR04/lab/outside, raw versus debug control, body/fire continuation and bounded RETURN state are implemented.
**Verified scope/platform:** Historical Linux route/control and managed checks; startup-order row retains exact ea04210 native fixture and Wine classifications.
**Known differences:** Full shared wrappers/camera/control and complete fresh/retained natural/skipped/edge matrix remain open. Ordinary landing bank is legitimate.
**Remaining acceptance — OPEN:** Capture continuous and focused eight-cell routes, preserving successful TSK retained order and separate fresh direct-scene order.; Identified whole-original DxWnd and current native Linux/Windows scenario capture/review remain open (0/120 obligations).
**Requirements:** MOVE-04, MOVE-05 · **Implementation:** {&#x27;revision&#x27;: &#x27;ea04210f524faae7dc1caff8afbc608fbb8144f4&#x27;, &#x27;paths&#x27;: [&#x27;src/GamePort/Program.cs&#x27;], &#x27;status&#x27;: &#x27;bounded&#x27;, &#x27;note&#x27;: &#x27;Revision identifies the last tracked change to the first implementation path; it is not a runtime/package identity. Unimplemented denotes the named full-scope workflow, not absence of all foundations.&#x27;}
**Sources:** [Retained checkpoint contracts and source-report links](../../docs/checkpoint/coverage.md), [Implementation gates and historical execution ledger](../../docs/checkpoint/implementation-plan.md), [Revision-specific runtime and package status index](../../docs/progress.md), [Platform classifications and limits](../../docs/compatibility.md), [Implementation: Program.cs](../../src/GamePort/Program.cs)
**Scenarios:** [fresh-natural-edge](scenarios.json), [fresh-natural-ordinary](scenarios.json), [fresh-skipped-edge](scenarios.json), [fresh-skipped-ordinary](scenarios.json), [retained-natural-edge](scenarios.json), [retained-natural-ordinary](scenarios.json), [retained-skipped-edge](scenarios.json), [retained-skipped-ordinary](scenarios.json)
**Current applicable evidence (only the targets below):**
- {&quot;artifacts&quot;: [], &quot;claim&quot;: {&quot;key&quot;: &quot;route-control-coverage&quot;, &quot;result&quot;: &quot;Lab/VR04/lab/outside, raw versus debug control, body/fire continuation and bounded RETURN state are implemented.&quot;}, &quot;content&quot;: {&quot;report_sha256&quot;: &quot;4481cb6df6748bc38a8808da64a93206f5e02326bc37e6fa2104f189b9339dea&quot;}, &quot;evidence_kind&quot;: &quot;static&quot;, &quot;historical&quot;: false, &quot;id&quot;: &quot;route-control-report&quot;, &quot;method&quot;: &quot;Existing documentation inspected and indexed; not new binary recovery, component execution or gameplay capture&quot;, &quot;missing_evidence&quot;: [&quot;Identified whole-original DxWnd and current native Linux/Windows scenario capture/review remain open (0/120 obligations).&quot;], &quot;platform&quot;: {&quot;execution&quot;: &quot;static&quot;, &quot;os&quot;: &quot;source&quot;}, &quot;reason&quot;: null, &quot;receipt_id&quot;: &quot;route-control-report&quot;, &quot;report_path&quot;: &quot;docs/checkpoint/coverage.md&quot;, &quot;revision&quot;: &quot;bdca29d3aa31face0c0023537ff98783716dbc45&quot;, &quot;scope&quot;: [&quot;route-control: documentary coverage only&quot;], &quot;status&quot;: &quot;current&quot;, &quot;supersedes&quot;: []}
**Explicit applicability targets:** [{&#x27;id&#x27;: &#x27;route-control-documentation&#x27;, &#x27;content&#x27;: {&#x27;report_sha256&#x27;: &#x27;4481cb6df6748bc38a8808da64a93206f5e02326bc37e6fa2104f189b9339dea&#x27;}, &#x27;platform&#x27;: {&#x27;os&#x27;: &#x27;source&#x27;, &#x27;execution&#x27;: &#x27;static&#x27;}, &#x27;scope&#x27;: [&#x27;route-control: documentary coverage only&#x27;]}]
<details><summary>History — exact revisions and supersession retained</summary>
- No superseded evidence recorded.
</details>
**Player-impact discrepancies:**
- **disruptive** · route-control-remaining: Capture continuous and focused eight-cell routes, preserving successful TSK retained order and separate fresh direct-scene order.
- **missing_verification** · route-control-verification: Identified whole-original DxWnd and current native Linux/Windows scenario capture/review remain open (0/120 obligations).
### startup-order
**Working behavior:** TSK-backed first-story input order is already corrected: retained Jimmy updates before level-game input. Direct fresh scenes keep fresh insertion order; legitimate landing bank and all movement/rotation algorithms are preserved.
**Verified scope/platform:** Source/data lifetime proof; historical ea04210 Linux SDL/Vulkan Carl fixture (first neutral tick, 300 idle, held return) and standalone four-readback replay. Historical Wine64 is preliminary; whole-original/native Windows comparison remains open.
**Known differences:** Source allocation diagnostic required an OS repaint acknowledgement and black frames/timing perturbation; it is not playable original Carl evidence.; Bounded fixture input is not the complete physical-input lab→VR04→lab→outside matrix. Current package924ad2f differs from ea04210; later matching readbacks do not promote all runtime bytes.
**Remaining acceptance — OPEN:** Identified whole-original DxWnd Carl natural/skip and fresh/retained audiovisual comparison; Current native Windows and native Linux full matrix with actual input/audio and human review; 0/120 accepted obligations; Preserve normal landing bank, fresh direct-scene order and independent airborne behavior
**Requirements:** MOVE-04, MOVE-05 · **Implementation:** {&#x27;revision&#x27;: &#x27;ea04210f524faae7dc1caff8afbc608fbb8144f4&#x27;, &#x27;paths&#x27;: [&#x27;src/GamePort/Program.cs&#x27;], &#x27;status&#x27;: &#x27;bounded&#x27;, &#x27;note&#x27;: &#x27;story &#124;&#124; carriedSave != null; unchanged Program source through ledger work&#x27;}
**Sources:** [TSK source lifetime and bounded runtime receipt](../../docs/gameplay/main-menu-player-lifetime.md), [Exact implementation owner](../../src/GamePort/Program.cs), [Platform/history reconciliation](../../docs/compatibility.md), [Checkpoint coverage rows](../../docs/checkpoint/coverage.md)
**Scenarios:** [fresh-natural-ordinary](scenarios.json), [fresh-skipped-edge](scenarios.json), [retained-natural-ordinary](scenarios.json), [retained-skipped-edge](scenarios.json)
**Current applicable evidence (only the targets below):**
- {&quot;artifacts&quot;: [{&quot;path&quot;: &quot;artifacts/main-menu-player-lifetime/package-identity.json&quot;, &quot;sha256&quot;: &quot;6b1c7ab40f26f489d0bc272d6e2962adc257f32d42e8cd78755f5a135f512e8c&quot;, &quot;size&quot;: 845}, {&quot;path&quot;: &quot;artifacts/main-menu-player-lifetime/package-verification.json&quot;, &quot;sha256&quot;: &quot;e8a180991c35f279726c595a70ed32c4ab06df0381d59169735edebf86554e31&quot;, &quot;size&quot;: 2548}, {&quot;path&quot;: &quot;artifacts/main-menu-player-lifetime/native-control-final.log&quot;, &quot;sha256&quot;: &quot;46efc999b3d2d78b1eef3b3dea9d8fee188202c1556dc1d40751e6ee555f8548&quot;, &quot;size&quot;: 1901}, {&quot;path&quot;: &quot;artifacts/main-menu-player-lifetime/package-control-standalone.log&quot;, &quot;sha256&quot;: &quot;09fa452577bbd66b9275cb83045db6b3a117913ec415f5fb6ae52e9a174790e0&quot;, &quot;size&quot;: 1950}, {&quot;path&quot;: &quot;artifacts/main-menu-player-lifetime/native-control-final.returned.ppm&quot;, &quot;sha256&quot;: &quot;2aa0156b1ee0de50a54808cfaac8acd6b9df5c3d947c7fa4f2ee08e6a814e238&quot;, &quot;size&quot;: 6220817}, {&quot;missing_reason&quot;: &quot;No usable whole-original Carl recording exists in this checkpoint&quot;, &quot;path&quot;: &quot;artifacts/fidelity/captures/original-carl-reference.webm&quot;}, {&quot;missing_reason&quot;: &quot;Native Windows Carl recording has not been collected&quot;, &quot;path&quot;: &quot;artifacts/fidelity/captures/windows-native-carl-reference.webm&quot;}], &quot;claim&quot;: {&quot;key&quot;: &quot;neutral-return&quot;, &quot;result&quot;: &quot;First input and 300 idle ticks upright; preserved heading/body/fire; four standalone readbacks identical. Development validation zero errors; standalone validation disabled.&quot;}, &quot;content&quot;: {&quot;package_report_sha256&quot;: &quot;6b1c7ab40f26f489d0bc272d6e2962adc257f32d42e8cd78755f5a135f512e8c&quot;, &quot;runtime_sha256&quot;: &quot;9bee85197c0d7322dc67a8c1aedbe700cf63083f91f99161dd4533c2585501e5&quot;, &quot;verification_report_sha256&quot;: &quot;e8a180991c35f279726c595a70ed32c4ab06df0381d59169735edebf86554e31&quot;}, &quot;evidence_kind&quot;: &quot;port_fixture&quot;, &quot;historical&quot;: true, &quot;id&quot;: &quot;tsk-linux-fixture-ea04210&quot;, &quot;method&quot;: &quot;Historical native Linux SDL/Vulkan control fixture and standalone replay, recorded report/logs; no new execution&quot;, &quot;missing_evidence&quot;: [&quot;No complete original Carl capture&quot;, &quot;No current native Windows comparison&quot;], &quot;platform&quot;: {&quot;execution&quot;: &quot;native&quot;, &quot;os&quot;: &quot;linux&quot;}, &quot;reason&quot;: null, &quot;receipt_id&quot;: &quot;tsk-linux-fixture-ea04210&quot;, &quot;report_path&quot;: &quot;docs/gameplay/main-menu-player-lifetime.md&quot;, &quot;revision&quot;: &quot;ea04210f524faae7dc1caff8afbc608fbb8144f4&quot;, &quot;scope&quot;: [&quot;Carl first neutral input and 300 idle ticks; held movement return&quot;], &quot;status&quot;: &quot;current&quot;, &quot;supersedes&quot;: []}
- {&quot;addresses&quot;: [&quot;46BF2F..46C00A&quot;, &quot;460A50..460A6A&quot;, &quot;43B5A0&quot;, &quot;46E38B/46E45A&quot;], &quot;artifacts&quot;: [{&quot;path&quot;: &quot;artifacts/main-menu-player-lifetime/source.json&quot;, &quot;sha256&quot;: &quot;abfeef8fb990e39e6e7f9395aae8fc8111e8038d92f5c0673a2db7505ec61070&quot;, &quot;size&quot;: 37630}], &quot;claim&quot;: {&quot;key&quot;: &quot;initial-story-order&quot;, &quot;result&quot;: &quot;Retained Jimmy precedes new level-game input; already corrected&quot;}, &quot;content&quot;: {&quot;implementation_sha256&quot;: &quot;2ea2e4cee3816337765b3cb4c07bc9b2a226a4c0951d0f4a7d9e2eb2f8b09e5d&quot;, &quot;report_sha256&quot;: &quot;956dc37ab40b0701564faf7fb227163cd1b7d118aeb73c9847c51f9f9ac61ce9&quot;}, &quot;evidence_kind&quot;: &quot;static&quot;, &quot;historical&quot;: false, &quot;id&quot;: &quot;tsk-source-order-ea04210&quot;, &quot;method&quot;: &quot;Guarded source/data report, not a new execution&quot;, &quot;missing_evidence&quot;: [&quot;No complete original Carl capture&quot;, &quot;No current native Windows comparison&quot;], &quot;original_sha256&quot;: &quot;f5281076e1a2492f2d61f87aae3f4544b6d0f535ebe33f9fbb6f78710fe1aea8&quot;, &quot;platform&quot;: {&quot;execution&quot;: &quot;static&quot;, &quot;os&quot;: &quot;source&quot;}, &quot;rea_evidence&quot;: &quot;ev_0d64cc58fa8f5573fc8e61e0f2c20e36288099212bd2257d3a3121361fd6c904&quot;, &quot;reason&quot;: &quot;Successful TSK requires existing Jimmy; background Level1D constructs him and ordinary loader retains registry node.&quot;, &quot;receipt_id&quot;: &quot;tsk-source-order-ea04210&quot;, &quot;report_path&quot;: &quot;docs/gameplay/main-menu-player-lifetime.md&quot;, &quot;revision&quot;: &quot;ea04210f524faae7dc1caff8afbc608fbb8144f4&quot;, &quot;scope&quot;: [&quot;successful TSK story entry; direct-fresh distinction&quot;], &quot;status&quot;: &quot;current&quot;, &quot;supersedes&quot;: [&quot;tsk-fresh-assumption-dae13ac&quot;]}
**Explicit applicability targets:** [{&#x27;id&#x27;: &#x27;source-order-at-ledger-import&#x27;, &#x27;content&#x27;: {&#x27;report_sha256&#x27;: &#x27;956dc37ab40b0701564faf7fb227163cd1b7d118aeb73c9847c51f9f9ac61ce9&#x27;, &#x27;implementation_sha256&#x27;: &#x27;2ea2e4cee3816337765b3cb4c07bc9b2a226a4c0951d0f4a7d9e2eb2f8b09e5d&#x27;}, &#x27;platform&#x27;: {&#x27;os&#x27;: &#x27;source&#x27;, &#x27;execution&#x27;: &#x27;static&#x27;}, &#x27;scope&#x27;: [&#x27;successful TSK story entry; direct-fresh distinction&#x27;]}, {&#x27;id&#x27;: &#x27;historical-linux-ea04210-only&#x27;, &#x27;content&#x27;: {&#x27;runtime_sha256&#x27;: &#x27;9bee85197c0d7322dc67a8c1aedbe700cf63083f91f99161dd4533c2585501e5&#x27;, &#x27;package_report_sha256&#x27;: &#x27;6b1c7ab40f26f489d0bc272d6e2962adc257f32d42e8cd78755f5a135f512e8c&#x27;, &#x27;verification_report_sha256&#x27;: &#x27;e8a180991c35f279726c595a70ed32c4ab06df0381d59169735edebf86554e31&#x27;}, &#x27;platform&#x27;: {&#x27;os&#x27;: &#x27;linux&#x27;, &#x27;execution&#x27;: &#x27;native&#x27;}, &#x27;scope&#x27;: [&#x27;Carl first neutral input and 300 idle ticks; held movement return&#x27;]}]
<details><summary>History — exact revisions and supersession retained</summary>
- {&quot;artifacts&quot;: [], &quot;claim&quot;: {&quot;key&quot;: &quot;initial-story-order&quot;, &quot;result&quot;: &quot;Prior port incorrectly treated first TSK story as fresh registry order; source report explicitly corrects this&quot;}, &quot;content&quot;: {&quot;implementation_sha256&quot;: &quot;2ea2e4cee3816337765b3cb4c07bc9b2a226a4c0951d0f4a7d9e2eb2f8b09e5d&quot;, &quot;report_sha256&quot;: &quot;956dc37ab40b0701564faf7fb227163cd1b7d118aeb73c9847c51f9f9ac61ce9&quot;}, &quot;evidence_kind&quot;: &quot;inferred&quot;, &quot;historical&quot;: true, &quot;id&quot;: &quot;tsk-fresh-assumption-dae13ac&quot;, &quot;method&quot;: &quot;Prior narrative retained from source report; never accepted as source fact&quot;, &quot;missing_evidence&quot;: [&quot;No complete original Carl capture&quot;, &quot;No current native Windows comparison&quot;], &quot;platform&quot;: {&quot;execution&quot;: &quot;static&quot;, &quot;os&quot;: &quot;source&quot;}, &quot;reason&quot;: null, &quot;receipt_id&quot;: &quot;tsk-fresh-assumption-dae13ac&quot;, &quot;report_path&quot;: &quot;docs/gameplay/main-menu-player-lifetime.md&quot;, &quot;revision&quot;: &quot;dae13ace7391671aee7082c662bb798b285b9124&quot;, &quot;scope&quot;: [&quot;successful TSK story entry; direct-fresh distinction&quot;], &quot;status&quot;: &quot;superseded&quot;, &quot;supersedes&quot;: []}
- {&quot;artifacts&quot;: [{&quot;path&quot;: &quot;artifacts/main-menu-player-lifetime/package-verification.json&quot;, &quot;sha256&quot;: &quot;e8a180991c35f279726c595a70ed32c4ab06df0381d59169735edebf86554e31&quot;, &quot;size&quot;: 2548}], &quot;claim&quot;: {&quot;key&quot;: &quot;wine-control&quot;, &quot;result&quot;: &quot;Historical isolated Wine64 fixture exits 0; preliminary compatibility only&quot;}, &quot;content&quot;: {&quot;package_report_sha256&quot;: &quot;6b1c7ab40f26f489d0bc272d6e2962adc257f32d42e8cd78755f5a135f512e8c&quot;, &quot;runtime_sha256&quot;: &quot;24e1f01be497b920eab005608cf04c8838894d9e63404008c674990627bbc989&quot;, &quot;verification_report_sha256&quot;: &quot;e8a180991c35f279726c595a70ed32c4ab06df0381d59169735edebf86554e31&quot;}, &quot;evidence_kind&quot;: &quot;wine&quot;, &quot;historical&quot;: true, &quot;id&quot;: &quot;tsk-wine64-ea04210&quot;, &quot;method&quot;: &quot;Reported Wine64 fixture; not native Windows; package verification report retained&quot;, &quot;missing_evidence&quot;: [&quot;No complete original Carl capture&quot;, &quot;No current native Windows comparison&quot;], &quot;platform&quot;: {&quot;execution&quot;: &quot;wine&quot;, &quot;os&quot;: &quot;windows&quot;}, &quot;reason&quot;: null, &quot;receipt_id&quot;: &quot;tsk-wine64-ea04210&quot;, &quot;report_path&quot;: &quot;docs/gameplay/main-menu-player-lifetime.md&quot;, &quot;revision&quot;: &quot;ea04210f524faae7dc1caff8afbc608fbb8144f4&quot;, &quot;scope&quot;: [&quot;32-frame packaged Carl/control fixture&quot;], &quot;status&quot;: &quot;historical&quot;, &quot;supersedes&quot;: []}
</details>
**Player-impact discrepancies:**
- **missing_verification** · startup-native-windows: ea04210 Wine64/cross-publish never establishes current native Windows acceptance.
- **missing_verification** · startup-original-reference: Whole-original Carl playback has not been captured; background allocation is narrower evidence.
## Contacts
### actor-policies
**Working behavior:** Bounded Carl/Goddard patrol, pickup/task callbacks, VR04 shrink targets and VR01/VR07 contact consumers exist.
**Verified scope/platform:** Documented managed/source and bounded Linux scene checks; Soldier174 and Jimmy204 are recorded endpoints, not executed full policies.
**Known differences:** Full enemy sensing/RNG/actions, damage/death/recovery, hazards, successful climbs and real special enter/stay/leave consumers are incomplete.
**Remaining acceptance — OPEN:** Recover and implement real class policies and health/combat consumers with original observations before admitting new actors.; Identified whole-original DxWnd and current native Linux/Windows scenario capture/review remain open (0/120 obligations).
**Requirements:** ACT-01, ACT-02, ACT-03 · **Implementation:** {&#x27;revision&#x27;: &#x27;fccc0b9d1b6ae962d32147e4ae1433fce6a1a23e&#x27;, &#x27;paths&#x27;: [&#x27;src/GamePort/Game/ActorPatrol.cs&#x27;, &#x27;src/GamePort/Game/SceneInteractions.cs&#x27;], &#x27;status&#x27;: &#x27;bounded&#x27;, &#x27;note&#x27;: &#x27;Revision identifies the last tracked change to the first implementation path; it is not a runtime/package identity. Unimplemented denotes the named full-scope workflow, not absence of all foundations.&#x27;}
**Sources:** [Retained checkpoint contracts and source-report links](../../docs/checkpoint/coverage.md), [Implementation gates and historical execution ledger](../../docs/checkpoint/implementation-plan.md), [Revision-specific runtime and package status index](../../docs/progress.md), [Platform classifications and limits](../../docs/compatibility.md), [Implementation: ActorPatrol.cs](../../src/GamePort/Game/ActorPatrol.cs), [Implementation: SceneInteractions.cs](../../src/GamePort/Game/SceneInteractions.cs)
**Scenarios:** [fresh-natural-edge](scenarios.json), [fresh-natural-ordinary](scenarios.json), [fresh-skipped-edge](scenarios.json), [fresh-skipped-ordinary](scenarios.json), [retained-natural-edge](scenarios.json), [retained-natural-ordinary](scenarios.json), [retained-skipped-edge](scenarios.json), [retained-skipped-ordinary](scenarios.json)
**Current applicable evidence (only the targets below):**
- {&quot;artifacts&quot;: [], &quot;claim&quot;: {&quot;key&quot;: &quot;actor-policies-coverage&quot;, &quot;result&quot;: &quot;Bounded Carl/Goddard patrol, pickup/task callbacks, VR04 shrink targets and VR01/VR07 contact consumers exist.&quot;}, &quot;content&quot;: {&quot;report_sha256&quot;: &quot;4481cb6df6748bc38a8808da64a93206f5e02326bc37e6fa2104f189b9339dea&quot;}, &quot;evidence_kind&quot;: &quot;static&quot;, &quot;historical&quot;: false, &quot;id&quot;: &quot;actor-policies-report&quot;, &quot;method&quot;: &quot;Existing documentation inspected and indexed; not new binary recovery, component execution or gameplay capture&quot;, &quot;missing_evidence&quot;: [&quot;Identified whole-original DxWnd and current native Linux/Windows scenario capture/review remain open (0/120 obligations).&quot;], &quot;platform&quot;: {&quot;execution&quot;: &quot;static&quot;, &quot;os&quot;: &quot;source&quot;}, &quot;reason&quot;: null, &quot;receipt_id&quot;: &quot;actor-policies-report&quot;, &quot;report_path&quot;: &quot;docs/checkpoint/coverage.md&quot;, &quot;revision&quot;: &quot;bdca29d3aa31face0c0023537ff98783716dbc45&quot;, &quot;scope&quot;: [&quot;actor-policies: documentary coverage only&quot;], &quot;status&quot;: &quot;current&quot;, &quot;supersedes&quot;: []}
**Explicit applicability targets:** [{&#x27;id&#x27;: &#x27;actor-policies-documentation&#x27;, &#x27;content&#x27;: {&#x27;report_sha256&#x27;: &#x27;4481cb6df6748bc38a8808da64a93206f5e02326bc37e6fa2104f189b9339dea&#x27;}, &#x27;platform&#x27;: {&#x27;os&#x27;: &#x27;source&#x27;, &#x27;execution&#x27;: &#x27;static&#x27;}, &#x27;scope&#x27;: [&#x27;actor-policies: documentary coverage only&#x27;]}]
<details><summary>History — exact revisions and supersession retained</summary>
- No superseded evidence recorded.
</details>
**Player-impact discrepancies:**
- **blocking** · actor-policies-remaining: Recover and implement real class policies and health/combat consumers with original observations before admitting new actors.
- **missing_verification** · actor-policies-verification: Identified whole-original DxWnd and current native Linux/Windows scenario capture/review remain open (0/120 obligations).
### body-static-dynamic
**Working behavior:** VR04 ordinary source static body and standalone pair/reclip/normal components preserve published roots, live getters and callback order.
**Verified scope/platform:** Checkpoint S/P/M/R is bounded: 28 pair, 17 context, 14 populated reclip, 30 normal and 100 body ownership comparisons; actual scene admission is narrower.
**Known differences:** Pair discovery and real derived Jimmy/soldier callbacks are not live; lab/outside retain the compatibility capsule.
**Remaining acceptance — OPEN:** Complete actual special callbacks, ordered dynamic context and live getter timing before extending solver admission.; Identified whole-original DxWnd and current native Linux/Windows scenario capture/review remain open (0/120 obligations).
**Requirements:** MOVE-02 · **Implementation:** {&#x27;revision&#x27;: &#x27;c9d0c5be59eedba3a92dcd46d1beb96b2e9e941a&#x27;, &#x27;paths&#x27;: [&#x27;src/GamePort/Game/OriginalBodyPhysics.cs&#x27;, &#x27;src/GamePort/Game/OriginalPairCollision.cs&#x27;, &#x27;src/GamePort/Game/OriginalNormalContacts.cs&#x27;], &#x27;status&#x27;: &#x27;bounded&#x27;, &#x27;note&#x27;: &#x27;Revision identifies the last tracked change to the first implementation path; it is not a runtime/package identity. Unimplemented denotes the named full-scope workflow, not absence of all foundations.&#x27;}
**Sources:** [Retained checkpoint contracts and source-report links](../../docs/checkpoint/coverage.md), [Implementation gates and historical execution ledger](../../docs/checkpoint/implementation-plan.md), [Revision-specific runtime and package status index](../../docs/progress.md), [Platform classifications and limits](../../docs/compatibility.md), [Implementation: OriginalBodyPhysics.cs](../../src/GamePort/Game/OriginalBodyPhysics.cs), [Implementation: OriginalPairCollision.cs](../../src/GamePort/Game/OriginalPairCollision.cs), [Implementation: OriginalNormalContacts.cs](../../src/GamePort/Game/OriginalNormalContacts.cs)
**Scenarios:** [fresh-natural-edge](scenarios.json), [fresh-natural-ordinary](scenarios.json), [fresh-skipped-edge](scenarios.json), [fresh-skipped-ordinary](scenarios.json), [retained-natural-edge](scenarios.json), [retained-natural-ordinary](scenarios.json), [retained-skipped-edge](scenarios.json), [retained-skipped-ordinary](scenarios.json)
**Current applicable evidence (only the targets below):**
- {&quot;artifacts&quot;: [], &quot;claim&quot;: {&quot;key&quot;: &quot;body-static-dynamic-coverage&quot;, &quot;result&quot;: &quot;VR04 ordinary source static body and standalone pair/reclip/normal components preserve published roots, live getters and callback order.&quot;}, &quot;content&quot;: {&quot;report_sha256&quot;: &quot;4481cb6df6748bc38a8808da64a93206f5e02326bc37e6fa2104f189b9339dea&quot;}, &quot;evidence_kind&quot;: &quot;static&quot;, &quot;historical&quot;: false, &quot;id&quot;: &quot;body-static-dynamic-report&quot;, &quot;method&quot;: &quot;Existing documentation inspected and indexed; not new binary recovery, component execution or gameplay capture&quot;, &quot;missing_evidence&quot;: [&quot;Identified whole-original DxWnd and current native Linux/Windows scenario capture/review remain open (0/120 obligations).&quot;], &quot;platform&quot;: {&quot;execution&quot;: &quot;static&quot;, &quot;os&quot;: &quot;source&quot;}, &quot;reason&quot;: null, &quot;receipt_id&quot;: &quot;body-static-dynamic-report&quot;, &quot;report_path&quot;: &quot;docs/checkpoint/coverage.md&quot;, &quot;revision&quot;: &quot;bdca29d3aa31face0c0023537ff98783716dbc45&quot;, &quot;scope&quot;: [&quot;body-static-dynamic: documentary coverage only&quot;], &quot;status&quot;: &quot;current&quot;, &quot;supersedes&quot;: []}
**Explicit applicability targets:** [{&#x27;id&#x27;: &#x27;body-static-dynamic-documentation&#x27;, &#x27;content&#x27;: {&#x27;report_sha256&#x27;: &#x27;4481cb6df6748bc38a8808da64a93206f5e02326bc37e6fa2104f189b9339dea&#x27;}, &#x27;platform&#x27;: {&#x27;os&#x27;: &#x27;source&#x27;, &#x27;execution&#x27;: &#x27;static&#x27;}, &#x27;scope&#x27;: [&#x27;body-static-dynamic: documentary coverage only&#x27;]}]
<details><summary>History — exact revisions and supersession retained</summary>
- No superseded evidence recorded.
</details>
**Player-impact discrepancies:**
- **disruptive** · body-static-dynamic-remaining: Complete actual special callbacks, ordered dynamic context and live getter timing before extending solver admission.
- **missing_verification** · body-static-dynamic-verification: Identified whole-original DxWnd and current native Linux/Windows scenario capture/review remain open (0/120 obligations).
### physical-helper-lifetimes
**Working behavior:** 72 VR04 records/13 classes, 12 original registration cases and 21 helper edges are inventoried; common append differs from Jimmy49E guard.
**Verified scope/platform:** Recorded static/copied-original/managed components only; constructor catalogue is not an observed physical body list.
**Known differences:** Retained helper membership, removal, activation and shared mutable reclip are open; no broad scene binding follows from the catalogue.
**Remaining acceptance — OPEN:** Recover helper re-entry/deletion and real retained physical order across LOAD/RETURN, then verify scene response adapters.; Identified whole-original DxWnd and current native Linux/Windows scenario capture/review remain open (0/120 obligations).
**Requirements:** MOVE-02, SAVE-02 · **Implementation:** {&#x27;revision&#x27;: &#x27;ea04210f524faae7dc1caff8afbc608fbb8144f4&#x27;, &#x27;paths&#x27;: [&#x27;src/GamePort/Program.cs&#x27;], &#x27;status&#x27;: &#x27;bounded&#x27;, &#x27;note&#x27;: &#x27;Revision identifies the last tracked change to the first implementation path; it is not a runtime/package identity. Unimplemented denotes the named full-scope workflow, not absence of all foundations.&#x27;}
**Sources:** [Retained checkpoint contracts and source-report links](../../docs/checkpoint/coverage.md), [Implementation gates and historical execution ledger](../../docs/checkpoint/implementation-plan.md), [Revision-specific runtime and package status index](../../docs/progress.md), [Platform classifications and limits](../../docs/compatibility.md), [Implementation: Program.cs](../../src/GamePort/Program.cs)
**Scenarios:** [fresh-natural-edge](scenarios.json), [fresh-natural-ordinary](scenarios.json), [fresh-skipped-edge](scenarios.json), [fresh-skipped-ordinary](scenarios.json), [retained-natural-edge](scenarios.json), [retained-natural-ordinary](scenarios.json), [retained-skipped-edge](scenarios.json), [retained-skipped-ordinary](scenarios.json)
**Current applicable evidence (only the targets below):**
- {&quot;artifacts&quot;: [], &quot;claim&quot;: {&quot;key&quot;: &quot;physical-helper-lifetimes-coverage&quot;, &quot;result&quot;: &quot;72 VR04 records/13 classes, 12 original registration cases and 21 helper edges are inventoried; common append differs from Jimmy49E guard.&quot;}, &quot;content&quot;: {&quot;report_sha256&quot;: &quot;4481cb6df6748bc38a8808da64a93206f5e02326bc37e6fa2104f189b9339dea&quot;}, &quot;evidence_kind&quot;: &quot;static&quot;, &quot;historical&quot;: false, &quot;id&quot;: &quot;physical-helper-lifetimes-report&quot;, &quot;method&quot;: &quot;Existing documentation inspected and indexed; not new binary recovery, component execution or gameplay capture&quot;, &quot;missing_evidence&quot;: [&quot;Identified whole-original DxWnd and current native Linux/Windows scenario capture/review remain open (0/120 obligations).&quot;], &quot;platform&quot;: {&quot;execution&quot;: &quot;static&quot;, &quot;os&quot;: &quot;source&quot;}, &quot;reason&quot;: null, &quot;receipt_id&quot;: &quot;physical-helper-lifetimes-report&quot;, &quot;report_path&quot;: &quot;docs/checkpoint/coverage.md&quot;, &quot;revision&quot;: &quot;bdca29d3aa31face0c0023537ff98783716dbc45&quot;, &quot;scope&quot;: [&quot;physical-helper-lifetimes: documentary coverage only&quot;], &quot;status&quot;: &quot;current&quot;, &quot;supersedes&quot;: []}
**Explicit applicability targets:** [{&#x27;id&#x27;: &#x27;physical-helper-lifetimes-documentation&#x27;, &#x27;content&#x27;: {&#x27;report_sha256&#x27;: &#x27;4481cb6df6748bc38a8808da64a93206f5e02326bc37e6fa2104f189b9339dea&#x27;}, &#x27;platform&#x27;: {&#x27;os&#x27;: &#x27;source&#x27;, &#x27;execution&#x27;: &#x27;static&#x27;}, &#x27;scope&#x27;: [&#x27;physical-helper-lifetimes: documentary coverage only&#x27;]}]
<details><summary>History — exact revisions and supersession retained</summary>
- No superseded evidence recorded.
</details>
**Player-impact discrepancies:**
- **disruptive** · physical-helper-lifetimes-remaining: Recover helper re-entry/deletion and real retained physical order across LOAD/RETURN, then verify scene response adapters.
- **missing_verification** · physical-helper-lifetimes-verification: Identified whole-original DxWnd and current native Linux/Windows scenario capture/review remain open (0/120 obligations).
## Gadgets
### gadget-use
**Working behavior:** Shrink ray/jetpack, Invisible, Bubble VR01, Baseball VR07 and Grappler VR08 have bounded implementations using original resources.
**Verified scope/platform:** Historical progress/compatibility reports separate copied-original components, managed checks and scene-specific native Linux replays.
**Known differences:** Remote and remaining gadget/actor consumers, other levels, suppression globals and complete enemy interactions are unfinished.
**Remaining acceptance — OPEN:** After movement stabilization, recover missing original gadgets and intended consumers; retain each bounded live scene and its source gate.; Identified whole-original DxWnd and current native Linux/Windows scenario capture/review remain open (0/120 obligations).
**Requirements:** GAD-02 · **Implementation:** {&#x27;revision&#x27;: &#x27;7b5230ceb819e2e6cd551f19d11ef07fad9f1876&#x27;, &#x27;paths&#x27;: [&#x27;src/GamePort/Game/ShrinkRay.cs&#x27;, &#x27;src/GamePort/Game/InvisibleGadget.cs&#x27;, &#x27;src/GamePort/Game/BubbleMotion.cs&#x27;, &#x27;src/GamePort/Game/BaseballGadget.cs&#x27;, &#x27;src/GamePort/Game/GrapplerGadget.cs&#x27;], &#x27;status&#x27;: &#x27;bounded&#x27;, &#x27;note&#x27;: &#x27;Revision identifies the last tracked change to the first implementation path; it is not a runtime/package identity. Unimplemented denotes the named full-scope workflow, not absence of all foundations.&#x27;}
**Sources:** [Retained checkpoint contracts and source-report links](../../docs/checkpoint/coverage.md), [Implementation gates and historical execution ledger](../../docs/checkpoint/implementation-plan.md), [Revision-specific runtime and package status index](../../docs/progress.md), [Platform classifications and limits](../../docs/compatibility.md), [Implementation: ShrinkRay.cs](../../src/GamePort/Game/ShrinkRay.cs), [Implementation: InvisibleGadget.cs](../../src/GamePort/Game/InvisibleGadget.cs), [Implementation: BubbleMotion.cs](../../src/GamePort/Game/BubbleMotion.cs), [Implementation: BaseballGadget.cs](../../src/GamePort/Game/BaseballGadget.cs), [Implementation: GrapplerGadget.cs](../../src/GamePort/Game/GrapplerGadget.cs)
**Scenarios:** [fresh-natural-edge](scenarios.json), [fresh-natural-ordinary](scenarios.json), [fresh-skipped-edge](scenarios.json), [fresh-skipped-ordinary](scenarios.json), [retained-natural-edge](scenarios.json), [retained-natural-ordinary](scenarios.json), [retained-skipped-edge](scenarios.json), [retained-skipped-ordinary](scenarios.json)
**Current applicable evidence (only the targets below):**
- {&quot;artifacts&quot;: [], &quot;claim&quot;: {&quot;key&quot;: &quot;gadget-use-coverage&quot;, &quot;result&quot;: &quot;Shrink ray/jetpack, Invisible, Bubble VR01, Baseball VR07 and Grappler VR08 have bounded implementations using original resources.&quot;}, &quot;content&quot;: {&quot;report_sha256&quot;: &quot;4481cb6df6748bc38a8808da64a93206f5e02326bc37e6fa2104f189b9339dea&quot;}, &quot;evidence_kind&quot;: &quot;static&quot;, &quot;historical&quot;: false, &quot;id&quot;: &quot;gadget-use-report&quot;, &quot;method&quot;: &quot;Existing documentation inspected and indexed; not new binary recovery, component execution or gameplay capture&quot;, &quot;missing_evidence&quot;: [&quot;Identified whole-original DxWnd and current native Linux/Windows scenario capture/review remain open (0/120 obligations).&quot;], &quot;platform&quot;: {&quot;execution&quot;: &quot;static&quot;, &quot;os&quot;: &quot;source&quot;}, &quot;reason&quot;: null, &quot;receipt_id&quot;: &quot;gadget-use-report&quot;, &quot;report_path&quot;: &quot;docs/checkpoint/coverage.md&quot;, &quot;revision&quot;: &quot;bdca29d3aa31face0c0023537ff98783716dbc45&quot;, &quot;scope&quot;: [&quot;gadget-use: documentary coverage only&quot;], &quot;status&quot;: &quot;current&quot;, &quot;supersedes&quot;: []}
**Explicit applicability targets:** [{&#x27;id&#x27;: &#x27;gadget-use-documentation&#x27;, &#x27;content&#x27;: {&#x27;report_sha256&#x27;: &#x27;4481cb6df6748bc38a8808da64a93206f5e02326bc37e6fa2104f189b9339dea&#x27;}, &#x27;platform&#x27;: {&#x27;os&#x27;: &#x27;source&#x27;, &#x27;execution&#x27;: &#x27;static&#x27;}, &#x27;scope&#x27;: [&#x27;gadget-use: documentary coverage only&#x27;]}]
<details><summary>History — exact revisions and supersession retained</summary>
- No superseded evidence recorded.
</details>
**Player-impact discrepancies:**
- **blocking** · gadget-use-remaining: After movement stabilization, recover missing original gadgets and intended consumers; retain each bounded live scene and its source gate.
- **missing_verification** · gadget-use-verification: Identified whole-original DxWnd and current native Linux/Windows scenario capture/review remain open (0/120 obligations).
### gadget-retention
**Working behavior:** Bounded cutscene/unequip/RETURN cleanup and selected route scalar ownership are implemented; independent helpers retain separate lifetimes.
**Verified scope/platform:** S/M/R route/gadget reports; ordinary route carry differs from TSK/debug checkpoint load and process-memory fields.
**Known differences:** Arbitrary LOAD/save, death, helper cleanup and non-RETURN attachment continuity remain incomplete.
**Remaining acceptance — OPEN:** Verify all retained/reset gadget/vehicle/companion fields and helpers across intended interruption and resume paths.; Identified whole-original DxWnd and current native Linux/Windows scenario capture/review remain open (0/120 obligations).
**Requirements:** GAD-04 · **Implementation:** {&#x27;revision&#x27;: &#x27;27be8ed63079ae2e3bf7e965ee205c4a57a96559&#x27;, &#x27;paths&#x27;: [&#x27;src/GamePort/Game/PlayerLevelState.cs&#x27;, &#x27;src/GamePort/Game/SceneGadgets.cs&#x27;], &#x27;status&#x27;: &#x27;bounded&#x27;, &#x27;note&#x27;: &#x27;Revision identifies the last tracked change to the first implementation path; it is not a runtime/package identity. Unimplemented denotes the named full-scope workflow, not absence of all foundations.&#x27;}
**Sources:** [Retained checkpoint contracts and source-report links](../../docs/checkpoint/coverage.md), [Implementation gates and historical execution ledger](../../docs/checkpoint/implementation-plan.md), [Revision-specific runtime and package status index](../../docs/progress.md), [Platform classifications and limits](../../docs/compatibility.md), [Implementation: PlayerLevelState.cs](../../src/GamePort/Game/PlayerLevelState.cs), [Implementation: SceneGadgets.cs](../../src/GamePort/Game/SceneGadgets.cs)
**Scenarios:** [fresh-natural-edge](scenarios.json), [fresh-natural-ordinary](scenarios.json), [fresh-skipped-edge](scenarios.json), [fresh-skipped-ordinary](scenarios.json), [retained-natural-edge](scenarios.json), [retained-natural-ordinary](scenarios.json), [retained-skipped-edge](scenarios.json), [retained-skipped-ordinary](scenarios.json)
**Current applicable evidence (only the targets below):**
- {&quot;artifacts&quot;: [], &quot;claim&quot;: {&quot;key&quot;: &quot;gadget-retention-coverage&quot;, &quot;result&quot;: &quot;Bounded cutscene/unequip/RETURN cleanup and selected route scalar ownership are implemented; independent helpers retain separate lifetimes.&quot;}, &quot;content&quot;: {&quot;report_sha256&quot;: &quot;4481cb6df6748bc38a8808da64a93206f5e02326bc37e6fa2104f189b9339dea&quot;}, &quot;evidence_kind&quot;: &quot;static&quot;, &quot;historical&quot;: false, &quot;id&quot;: &quot;gadget-retention-report&quot;, &quot;method&quot;: &quot;Existing documentation inspected and indexed; not new binary recovery, component execution or gameplay capture&quot;, &quot;missing_evidence&quot;: [&quot;Identified whole-original DxWnd and current native Linux/Windows scenario capture/review remain open (0/120 obligations).&quot;], &quot;platform&quot;: {&quot;execution&quot;: &quot;static&quot;, &quot;os&quot;: &quot;source&quot;}, &quot;reason&quot;: null, &quot;receipt_id&quot;: &quot;gadget-retention-report&quot;, &quot;report_path&quot;: &quot;docs/checkpoint/coverage.md&quot;, &quot;revision&quot;: &quot;bdca29d3aa31face0c0023537ff98783716dbc45&quot;, &quot;scope&quot;: [&quot;gadget-retention: documentary coverage only&quot;], &quot;status&quot;: &quot;current&quot;, &quot;supersedes&quot;: []}
**Explicit applicability targets:** [{&#x27;id&#x27;: &#x27;gadget-retention-documentation&#x27;, &#x27;content&#x27;: {&#x27;report_sha256&#x27;: &#x27;4481cb6df6748bc38a8808da64a93206f5e02326bc37e6fa2104f189b9339dea&#x27;}, &#x27;platform&#x27;: {&#x27;os&#x27;: &#x27;source&#x27;, &#x27;execution&#x27;: &#x27;static&#x27;}, &#x27;scope&#x27;: [&#x27;gadget-retention: documentary coverage only&#x27;]}]
<details><summary>History — exact revisions and supersession retained</summary>
- No superseded evidence recorded.
</details>
**Player-impact discrepancies:**
- **disruptive** · gadget-retention-remaining: Verify all retained/reset gadget/vehicle/companion fields and helpers across intended interruption and resume paths.
- **missing_verification** · gadget-retention-verification: Identified whole-original DxWnd and current native Linux/Windows scenario capture/review remain open (0/120 obligations).
### inventory-energy
**Working behavior:** Owned gadget panel, practice selection, source availability passes and shared energy warnings operate in bounded scenes.
**Verified scope/platform:** Recorded S/M/R route and gadget tests; F1 grants are modern diagnostics, not ordinary acquisition proof.
**Known differences:** Availability differs from ownership; full acquisition paths, selected UI and other per-level availability tails remain incomplete.
**Remaining acceptance — OPEN:** Verify all original acquisition/energy/availability rules through ordinary campaign consumers without debug grants.; Identified whole-original DxWnd and current native Linux/Windows scenario capture/review remain open (0/120 obligations).
**Requirements:** GAD-01 · **Implementation:** {&#x27;revision&#x27;: &#x27;1ae5f4251c26f3b0446f333e994694f99eab5be6&#x27;, &#x27;paths&#x27;: [&#x27;src/GamePort/Game/SceneInventory.cs&#x27;, &#x27;src/GamePort/Game/PlayerEnergy.cs&#x27;, &#x27;src/GamePort/Game/GadgetScreen.cs&#x27;], &#x27;status&#x27;: &#x27;bounded&#x27;, &#x27;note&#x27;: &#x27;Revision identifies the last tracked change to the first implementation path; it is not a runtime/package identity. Unimplemented denotes the named full-scope workflow, not absence of all foundations.&#x27;}
**Sources:** [Retained checkpoint contracts and source-report links](../../docs/checkpoint/coverage.md), [Implementation gates and historical execution ledger](../../docs/checkpoint/implementation-plan.md), [Revision-specific runtime and package status index](../../docs/progress.md), [Platform classifications and limits](../../docs/compatibility.md), [Implementation: SceneInventory.cs](../../src/GamePort/Game/SceneInventory.cs), [Implementation: PlayerEnergy.cs](../../src/GamePort/Game/PlayerEnergy.cs), [Implementation: GadgetScreen.cs](../../src/GamePort/Game/GadgetScreen.cs)
**Scenarios:** [fresh-natural-edge](scenarios.json), [fresh-natural-ordinary](scenarios.json), [fresh-skipped-edge](scenarios.json), [fresh-skipped-ordinary](scenarios.json), [retained-natural-edge](scenarios.json), [retained-natural-ordinary](scenarios.json), [retained-skipped-edge](scenarios.json), [retained-skipped-ordinary](scenarios.json)
**Current applicable evidence (only the targets below):**
- {&quot;artifacts&quot;: [], &quot;claim&quot;: {&quot;key&quot;: &quot;inventory-energy-coverage&quot;, &quot;result&quot;: &quot;Owned gadget panel, practice selection, source availability passes and shared energy warnings operate in bounded scenes.&quot;}, &quot;content&quot;: {&quot;report_sha256&quot;: &quot;4481cb6df6748bc38a8808da64a93206f5e02326bc37e6fa2104f189b9339dea&quot;}, &quot;evidence_kind&quot;: &quot;static&quot;, &quot;historical&quot;: false, &quot;id&quot;: &quot;inventory-energy-report&quot;, &quot;method&quot;: &quot;Existing documentation inspected and indexed; not new binary recovery, component execution or gameplay capture&quot;, &quot;missing_evidence&quot;: [&quot;Identified whole-original DxWnd and current native Linux/Windows scenario capture/review remain open (0/120 obligations).&quot;], &quot;platform&quot;: {&quot;execution&quot;: &quot;static&quot;, &quot;os&quot;: &quot;source&quot;}, &quot;reason&quot;: null, &quot;receipt_id&quot;: &quot;inventory-energy-report&quot;, &quot;report_path&quot;: &quot;docs/checkpoint/coverage.md&quot;, &quot;revision&quot;: &quot;bdca29d3aa31face0c0023537ff98783716dbc45&quot;, &quot;scope&quot;: [&quot;inventory-energy: documentary coverage only&quot;], &quot;status&quot;: &quot;current&quot;, &quot;supersedes&quot;: []}
**Explicit applicability targets:** [{&#x27;id&#x27;: &#x27;inventory-energy-documentation&#x27;, &#x27;content&#x27;: {&#x27;report_sha256&#x27;: &#x27;4481cb6df6748bc38a8808da64a93206f5e02326bc37e6fa2104f189b9339dea&#x27;}, &#x27;platform&#x27;: {&#x27;os&#x27;: &#x27;source&#x27;, &#x27;execution&#x27;: &#x27;static&#x27;}, &#x27;scope&#x27;: [&#x27;inventory-energy: documentary coverage only&#x27;]}]
<details><summary>History — exact revisions and supersession retained</summary>
- No superseded evidence recorded.
</details>
**Player-impact discrepancies:**
- **disruptive** · inventory-energy-remaining: Verify all original acquisition/energy/availability rules through ordinary campaign consumers without debug grants.
- **missing_verification** · inventory-energy-verification: Identified whole-original DxWnd and current native Linux/Windows scenario capture/review remain open (0/120 obligations).
### vehicles
**Working behavior:** Scooter VR05/outside LEV1 and Rocketship VR02 provide bounded summon/mount/control/camera/cleanup with original art.
**Verified scope/platform:** Historical packages: Scooter 62c07a3 then fccc0b9 feedback; Rocketship e77add5 then 62e908e RGBA correction. Native Linux replays and component counts remain report-scoped.
**Known differences:** Scooter modes2..20/mouse/analog, other scenes, mission/hazard/RNG, shared dynamic pairs and whole-original/native Windows comparison remain open.
**Remaining acceptance — OPEN:** Recover remaining source-supported vehicle modes/passenger/collision/camera consumers before enabling broader scenes.; Identified whole-original DxWnd and current native Linux/Windows scenario capture/review remain open (0/120 obligations).
**Requirements:** GAD-03 · **Implementation:** {&#x27;revision&#x27;: &#x27;c9d0c5be59eedba3a92dcd46d1beb96b2e9e941a&#x27;, &#x27;paths&#x27;: [&#x27;src/GamePort/Game/Scooter.cs&#x27;, &#x27;src/GamePort/Game/Rocketship.cs&#x27;], &#x27;status&#x27;: &#x27;bounded&#x27;, &#x27;note&#x27;: &#x27;Revision identifies the last tracked change to the first implementation path; it is not a runtime/package identity. Unimplemented denotes the named full-scope workflow, not absence of all foundations.&#x27;}
**Sources:** [Retained checkpoint contracts and source-report links](../../docs/checkpoint/coverage.md), [Implementation gates and historical execution ledger](../../docs/checkpoint/implementation-plan.md), [Revision-specific runtime and package status index](../../docs/progress.md), [Platform classifications and limits](../../docs/compatibility.md), [Implementation: Scooter.cs](../../src/GamePort/Game/Scooter.cs), [Implementation: Rocketship.cs](../../src/GamePort/Game/Rocketship.cs)
**Scenarios:** [fresh-natural-edge](scenarios.json), [fresh-natural-ordinary](scenarios.json), [fresh-skipped-edge](scenarios.json), [fresh-skipped-ordinary](scenarios.json), [retained-natural-edge](scenarios.json), [retained-natural-ordinary](scenarios.json), [retained-skipped-edge](scenarios.json), [retained-skipped-ordinary](scenarios.json)
**Current applicable evidence (only the targets below):**
- {&quot;artifacts&quot;: [], &quot;claim&quot;: {&quot;key&quot;: &quot;vehicles-coverage&quot;, &quot;result&quot;: &quot;Scooter VR05/outside LEV1 and Rocketship VR02 provide bounded summon/mount/control/camera/cleanup with original art.&quot;}, &quot;content&quot;: {&quot;report_sha256&quot;: &quot;4481cb6df6748bc38a8808da64a93206f5e02326bc37e6fa2104f189b9339dea&quot;}, &quot;evidence_kind&quot;: &quot;static&quot;, &quot;historical&quot;: false, &quot;id&quot;: &quot;vehicles-report&quot;, &quot;method&quot;: &quot;Existing documentation inspected and indexed; not new binary recovery, component execution or gameplay capture&quot;, &quot;missing_evidence&quot;: [&quot;Identified whole-original DxWnd and current native Linux/Windows scenario capture/review remain open (0/120 obligations).&quot;], &quot;platform&quot;: {&quot;execution&quot;: &quot;static&quot;, &quot;os&quot;: &quot;source&quot;}, &quot;reason&quot;: null, &quot;receipt_id&quot;: &quot;vehicles-report&quot;, &quot;report_path&quot;: &quot;docs/checkpoint/coverage.md&quot;, &quot;revision&quot;: &quot;bdca29d3aa31face0c0023537ff98783716dbc45&quot;, &quot;scope&quot;: [&quot;vehicles: documentary coverage only&quot;], &quot;status&quot;: &quot;current&quot;, &quot;supersedes&quot;: []}
**Explicit applicability targets:** [{&#x27;id&#x27;: &#x27;vehicles-documentation&#x27;, &#x27;content&#x27;: {&#x27;report_sha256&#x27;: &#x27;4481cb6df6748bc38a8808da64a93206f5e02326bc37e6fa2104f189b9339dea&#x27;}, &#x27;platform&#x27;: {&#x27;os&#x27;: &#x27;source&#x27;, &#x27;execution&#x27;: &#x27;static&#x27;}, &#x27;scope&#x27;: [&#x27;vehicles: documentary coverage only&#x27;]}]
<details><summary>History — exact revisions and supersession retained</summary>
- No superseded evidence recorded.
</details>
**Player-impact discrepancies:**
- **disruptive** · vehicles-remaining: Recover remaining source-supported vehicle modes/passenger/collision/camera consumers before enabling broader scenes.
- **missing_verification** · vehicles-verification: Identified whole-original DxWnd and current native Linux/Windows scenario capture/review remain open (0/120 obligations).
## Progression
### authored-scenes-tasks
**Working behavior:** All 35 supplied GAMs parse; 33 have geometry. Lab tasks, scripts, objectives, practice/RETURN and bounded optional mechanisms work.
**Verified scope/platform:** Source data/round-trip and bounded managed/Linux route evidence; no full campaign reachability or original gameplay comparison.
**Known differences:** Generic class callbacks/reentrancy, all mission/task/collectible mechanisms and ordinary traversal of every scene remain unfinished.
**Remaining acceptance — OPEN:** Implement authored reachable scene/mission consumers after movement/actor gates, preserving source objective-before-record/per-actor notification order.; Identified whole-original DxWnd and current native Linux/Windows scenario capture/review remain open (0/120 obligations).
**Requirements:** CAMP-01, CAMP-02 · **Implementation:** {&#x27;revision&#x27;: &#x27;62c07a3d59ca6d71a7456957d8586c268d27c439&#x27;, &#x27;paths&#x27;: [&#x27;src/GamePort/Game/SceneDirector.cs&#x27;, &#x27;src/GamePort/Game/TaskActivation.cs&#x27;, &#x27;src/GamePort/Game/SceneMechanisms.cs&#x27;], &#x27;status&#x27;: &#x27;bounded&#x27;, &#x27;note&#x27;: &#x27;Revision identifies the last tracked change to the first implementation path; it is not a runtime/package identity. Unimplemented denotes the named full-scope workflow, not absence of all foundations.&#x27;}
**Sources:** [Retained checkpoint contracts and source-report links](../../docs/checkpoint/coverage.md), [Implementation gates and historical execution ledger](../../docs/checkpoint/implementation-plan.md), [Revision-specific runtime and package status index](../../docs/progress.md), [Platform classifications and limits](../../docs/compatibility.md), [Implementation: SceneDirector.cs](../../src/GamePort/Game/SceneDirector.cs), [Implementation: TaskActivation.cs](../../src/GamePort/Game/TaskActivation.cs), [Implementation: SceneMechanisms.cs](../../src/GamePort/Game/SceneMechanisms.cs)
**Scenarios:** [fresh-natural-edge](scenarios.json), [fresh-natural-ordinary](scenarios.json), [fresh-skipped-edge](scenarios.json), [fresh-skipped-ordinary](scenarios.json), [retained-natural-edge](scenarios.json), [retained-natural-ordinary](scenarios.json), [retained-skipped-edge](scenarios.json), [retained-skipped-ordinary](scenarios.json)
**Current applicable evidence (only the targets below):**
- {&quot;artifacts&quot;: [], &quot;claim&quot;: {&quot;key&quot;: &quot;authored-scenes-tasks-coverage&quot;, &quot;result&quot;: &quot;All 35 supplied GAMs parse; 33 have geometry. Lab tasks, scripts, objectives, practice/RETURN and bounded optional mechanisms work.&quot;}, &quot;content&quot;: {&quot;report_sha256&quot;: &quot;4481cb6df6748bc38a8808da64a93206f5e02326bc37e6fa2104f189b9339dea&quot;}, &quot;evidence_kind&quot;: &quot;static&quot;, &quot;historical&quot;: false, &quot;id&quot;: &quot;authored-scenes-tasks-report&quot;, &quot;method&quot;: &quot;Existing documentation inspected and indexed; not new binary recovery, component execution or gameplay capture&quot;, &quot;missing_evidence&quot;: [&quot;Identified whole-original DxWnd and current native Linux/Windows scenario capture/review remain open (0/120 obligations).&quot;], &quot;platform&quot;: {&quot;execution&quot;: &quot;static&quot;, &quot;os&quot;: &quot;source&quot;}, &quot;reason&quot;: null, &quot;receipt_id&quot;: &quot;authored-scenes-tasks-report&quot;, &quot;report_path&quot;: &quot;docs/checkpoint/coverage.md&quot;, &quot;revision&quot;: &quot;bdca29d3aa31face0c0023537ff98783716dbc45&quot;, &quot;scope&quot;: [&quot;authored-scenes-tasks: documentary coverage only&quot;], &quot;status&quot;: &quot;current&quot;, &quot;supersedes&quot;: []}
**Explicit applicability targets:** [{&#x27;id&#x27;: &#x27;authored-scenes-tasks-documentation&#x27;, &#x27;content&#x27;: {&#x27;report_sha256&#x27;: &#x27;4481cb6df6748bc38a8808da64a93206f5e02326bc37e6fa2104f189b9339dea&#x27;}, &#x27;platform&#x27;: {&#x27;os&#x27;: &#x27;source&#x27;, &#x27;execution&#x27;: &#x27;static&#x27;}, &#x27;scope&#x27;: [&#x27;authored-scenes-tasks: documentary coverage only&#x27;]}]
<details><summary>History — exact revisions and supersession retained</summary>
- No superseded evidence recorded.
</details>
**Player-impact discrepancies:**
- **blocking** · authored-scenes-tasks-remaining: Implement authored reachable scene/mission consumers after movement/actor gates, preserving source objective-before-record/per-actor notification order.
- **missing_verification** · authored-scenes-tasks-verification: Identified whole-original DxWnd and current native Linux/Windows scenario capture/review remain open (0/120 obligations).
### campaign-completion
**Working behavior:** No verified full-campaign completion workflow exists; bounded playable routes are foundations.
**Verified scope/platform:** Explicitly unimplemented full-scope outcome, not a missing audit row; checkpoint route does not prove campaign completion.
**Known differences:** All campaign/optional-route win/loss outcomes without debug grants or warps remain unverified and incomplete.
**Remaining acceptance — OPEN:** Recover reachable endings/branches and implement complete ordinary-play campaign outcomes, then compare original and native platforms.; Identified whole-original DxWnd and current native Linux/Windows scenario capture/review remain open (0/120 obligations).
**Requirements:** CAMP-03 · **Implementation:** {&#x27;revision&#x27;: &#x27;bdca29d3aa31face0c0023537ff98783716dbc45&#x27;, &#x27;paths&#x27;: [], &#x27;status&#x27;: &#x27;unimplemented&#x27;, &#x27;note&#x27;: &#x27;Revision identifies the last tracked change to the first implementation path; it is not a runtime/package identity. Unimplemented denotes the named full-scope workflow, not absence of all foundations.&#x27;}
**Sources:** [Retained checkpoint contracts and source-report links](../../docs/checkpoint/coverage.md), [Implementation gates and historical execution ledger](../../docs/checkpoint/implementation-plan.md), [Revision-specific runtime and package status index](../../docs/progress.md), [Platform classifications and limits](../../docs/compatibility.md)
**Scenarios:** [fresh-natural-edge](scenarios.json), [fresh-natural-ordinary](scenarios.json), [fresh-skipped-edge](scenarios.json), [fresh-skipped-ordinary](scenarios.json), [retained-natural-edge](scenarios.json), [retained-natural-ordinary](scenarios.json), [retained-skipped-edge](scenarios.json), [retained-skipped-ordinary](scenarios.json)
**Current applicable evidence (only the targets below):**
- {&quot;artifacts&quot;: [], &quot;claim&quot;: {&quot;key&quot;: &quot;campaign-completion-coverage&quot;, &quot;result&quot;: &quot;No verified full-campaign completion workflow exists; bounded playable routes are foundations.&quot;}, &quot;content&quot;: {&quot;report_sha256&quot;: &quot;4481cb6df6748bc38a8808da64a93206f5e02326bc37e6fa2104f189b9339dea&quot;}, &quot;evidence_kind&quot;: &quot;static&quot;, &quot;historical&quot;: false, &quot;id&quot;: &quot;campaign-completion-report&quot;, &quot;method&quot;: &quot;Existing documentation inspected and indexed; not new binary recovery, component execution or gameplay capture&quot;, &quot;missing_evidence&quot;: [&quot;Identified whole-original DxWnd and current native Linux/Windows scenario capture/review remain open (0/120 obligations).&quot;], &quot;platform&quot;: {&quot;execution&quot;: &quot;static&quot;, &quot;os&quot;: &quot;source&quot;}, &quot;reason&quot;: null, &quot;receipt_id&quot;: &quot;campaign-completion-report&quot;, &quot;report_path&quot;: &quot;docs/checkpoint/coverage.md&quot;, &quot;revision&quot;: &quot;bdca29d3aa31face0c0023537ff98783716dbc45&quot;, &quot;scope&quot;: [&quot;campaign-completion: documentary coverage only&quot;], &quot;status&quot;: &quot;current&quot;, &quot;supersedes&quot;: []}
**Explicit applicability targets:** [{&#x27;id&#x27;: &#x27;campaign-completion-documentation&#x27;, &#x27;content&#x27;: {&#x27;report_sha256&#x27;: &#x27;4481cb6df6748bc38a8808da64a93206f5e02326bc37e6fa2104f189b9339dea&#x27;}, &#x27;platform&#x27;: {&#x27;os&#x27;: &#x27;source&#x27;, &#x27;execution&#x27;: &#x27;static&#x27;}, &#x27;scope&#x27;: [&#x27;campaign-completion: documentary coverage only&#x27;]}]
<details><summary>History — exact revisions and supersession retained</summary>
- No superseded evidence recorded.
</details>
**Player-impact discrepancies:**
- **blocking** · campaign-completion-remaining: Recover reachable endings/branches and implement complete ordinary-play campaign outcomes, then compare original and native platforms.
- **missing_verification** · campaign-completion-verification: Identified whole-original DxWnd and current native Linux/Windows scenario capture/review remain open (0/120 obligations).
### configuration-workflow
**Working behavior:** Modern CLI/debug display/audio options exist; full original-supported settings persistence workflow is unimplemented.
**Verified scope/platform:** No original defaults/bounds/persistence acceptance is established by CLI availability.
**Known differences:** Player-facing original configuration, exact defaults and persisted input/display/audio bounds remain open.
**Remaining acceptance — OPEN:** Recover original settings workflow and persistence, implement it and verify continued gameplay with those settings.; Identified whole-original DxWnd and current native Linux/Windows scenario capture/review remain open (0/120 obligations).
**Requirements:** UI-02 · **Implementation:** {&#x27;revision&#x27;: &#x27;bdca29d3aa31face0c0023537ff98783716dbc45&#x27;, &#x27;paths&#x27;: [], &#x27;status&#x27;: &#x27;unimplemented&#x27;, &#x27;note&#x27;: &#x27;Revision identifies the last tracked change to the first implementation path; it is not a runtime/package identity. Unimplemented denotes the named full-scope workflow, not absence of all foundations.&#x27;}
**Sources:** [Retained checkpoint contracts and source-report links](../../docs/checkpoint/coverage.md), [Implementation gates and historical execution ledger](../../docs/checkpoint/implementation-plan.md), [Revision-specific runtime and package status index](../../docs/progress.md), [Platform classifications and limits](../../docs/compatibility.md)
**Scenarios:** [fresh-natural-edge](scenarios.json), [fresh-natural-ordinary](scenarios.json), [fresh-skipped-edge](scenarios.json), [fresh-skipped-ordinary](scenarios.json), [retained-natural-edge](scenarios.json), [retained-natural-ordinary](scenarios.json), [retained-skipped-edge](scenarios.json), [retained-skipped-ordinary](scenarios.json)
**Current applicable evidence (only the targets below):**
- {&quot;artifacts&quot;: [], &quot;claim&quot;: {&quot;key&quot;: &quot;configuration-workflow-coverage&quot;, &quot;result&quot;: &quot;Modern CLI/debug display/audio options exist; full original-supported settings persistence workflow is unimplemented.&quot;}, &quot;content&quot;: {&quot;report_sha256&quot;: &quot;4481cb6df6748bc38a8808da64a93206f5e02326bc37e6fa2104f189b9339dea&quot;}, &quot;evidence_kind&quot;: &quot;static&quot;, &quot;historical&quot;: false, &quot;id&quot;: &quot;configuration-workflow-report&quot;, &quot;method&quot;: &quot;Existing documentation inspected and indexed; not new binary recovery, component execution or gameplay capture&quot;, &quot;missing_evidence&quot;: [&quot;Identified whole-original DxWnd and current native Linux/Windows scenario capture/review remain open (0/120 obligations).&quot;], &quot;platform&quot;: {&quot;execution&quot;: &quot;static&quot;, &quot;os&quot;: &quot;source&quot;}, &quot;reason&quot;: null, &quot;receipt_id&quot;: &quot;configuration-workflow-report&quot;, &quot;report_path&quot;: &quot;docs/checkpoint/coverage.md&quot;, &quot;revision&quot;: &quot;bdca29d3aa31face0c0023537ff98783716dbc45&quot;, &quot;scope&quot;: [&quot;configuration-workflow: documentary coverage only&quot;], &quot;status&quot;: &quot;current&quot;, &quot;supersedes&quot;: []}
**Explicit applicability targets:** [{&#x27;id&#x27;: &#x27;configuration-workflow-documentation&#x27;, &#x27;content&#x27;: {&#x27;report_sha256&#x27;: &#x27;4481cb6df6748bc38a8808da64a93206f5e02326bc37e6fa2104f189b9339dea&#x27;}, &#x27;platform&#x27;: {&#x27;os&#x27;: &#x27;source&#x27;, &#x27;execution&#x27;: &#x27;static&#x27;}, &#x27;scope&#x27;: [&#x27;configuration-workflow: documentary coverage only&#x27;]}]
<details><summary>History — exact revisions and supersession retained</summary>
- No superseded evidence recorded.
</details>
**Player-impact discrepancies:**
- **disruptive** · configuration-workflow-remaining: Recover original settings workflow and persistence, implement it and verify continued gameplay with those settings.
- **missing_verification** · configuration-workflow-verification: Identified whole-original DxWnd and current native Linux/Windows scenario capture/review remain open (0/120 obligations).
### content-accounting
**Working behavior:** Original inventory and GAM/OMT preparation account for supplied assets; missing Level3B/E geometry is recorded without substitution.
**Verified scope/platform:** 539-file hash baseline; 35 GAMs/33 geometry scenes; B/E duplicate four-entity records have unresolved normal use.
**Known differences:** No incoming GAM/save selection proves B/E reachable; complete authored reachability/unused classification remains open.
**Remaining acceptance — OPEN:** Account for every resource and authored dependency with evidence; distinguish unreachable/unused from unresolved rather than invent replacements.; Identified whole-original DxWnd and current native Linux/Windows scenario capture/review remain open (0/120 obligations).
**Requirements:** CAMP-04 · **Implementation:** {&#x27;revision&#x27;: &#x27;d62e2ab4dea38ce1c018b1a18ab51c39986ab630&#x27;, &#x27;paths&#x27;: [&#x27;tools/recon/inventory.py&#x27;], &#x27;status&#x27;: &#x27;bounded&#x27;, &#x27;note&#x27;: &#x27;Revision identifies the last tracked change to the first implementation path; it is not a runtime/package identity. Unimplemented denotes the named full-scope workflow, not absence of all foundations.&#x27;}
**Sources:** [Retained checkpoint contracts and source-report links](../../docs/checkpoint/coverage.md), [Implementation gates and historical execution ledger](../../docs/checkpoint/implementation-plan.md), [Revision-specific runtime and package status index](../../docs/progress.md), [Platform classifications and limits](../../docs/compatibility.md), [Implementation: inventory.py](../../tools/recon/inventory.py)
**Scenarios:** [fresh-natural-edge](scenarios.json), [fresh-natural-ordinary](scenarios.json), [fresh-skipped-edge](scenarios.json), [fresh-skipped-ordinary](scenarios.json), [retained-natural-edge](scenarios.json), [retained-natural-ordinary](scenarios.json), [retained-skipped-edge](scenarios.json), [retained-skipped-ordinary](scenarios.json)
**Current applicable evidence (only the targets below):**
- {&quot;artifacts&quot;: [], &quot;claim&quot;: {&quot;key&quot;: &quot;content-accounting-coverage&quot;, &quot;result&quot;: &quot;Original inventory and GAM/OMT preparation account for supplied assets; missing Level3B/E geometry is recorded without substitution.&quot;}, &quot;content&quot;: {&quot;report_sha256&quot;: &quot;4481cb6df6748bc38a8808da64a93206f5e02326bc37e6fa2104f189b9339dea&quot;}, &quot;evidence_kind&quot;: &quot;static&quot;, &quot;historical&quot;: false, &quot;id&quot;: &quot;content-accounting-report&quot;, &quot;method&quot;: &quot;Existing documentation inspected and indexed; not new binary recovery, component execution or gameplay capture&quot;, &quot;missing_evidence&quot;: [&quot;Identified whole-original DxWnd and current native Linux/Windows scenario capture/review remain open (0/120 obligations).&quot;], &quot;platform&quot;: {&quot;execution&quot;: &quot;static&quot;, &quot;os&quot;: &quot;source&quot;}, &quot;reason&quot;: null, &quot;receipt_id&quot;: &quot;content-accounting-report&quot;, &quot;report_path&quot;: &quot;docs/checkpoint/coverage.md&quot;, &quot;revision&quot;: &quot;bdca29d3aa31face0c0023537ff98783716dbc45&quot;, &quot;scope&quot;: [&quot;content-accounting: documentary coverage only&quot;], &quot;status&quot;: &quot;current&quot;, &quot;supersedes&quot;: []}
**Explicit applicability targets:** [{&#x27;id&#x27;: &#x27;content-accounting-documentation&#x27;, &#x27;content&#x27;: {&#x27;report_sha256&#x27;: &#x27;4481cb6df6748bc38a8808da64a93206f5e02326bc37e6fa2104f189b9339dea&#x27;}, &#x27;platform&#x27;: {&#x27;os&#x27;: &#x27;source&#x27;, &#x27;execution&#x27;: &#x27;static&#x27;}, &#x27;scope&#x27;: [&#x27;content-accounting: documentary coverage only&#x27;]}]
<details><summary>History — exact revisions and supersession retained</summary>
- No superseded evidence recorded.
</details>
**Player-impact discrepancies:**
- **disruptive** · content-accounting-remaining: Account for every resource and authored dependency with evidence; distinguish unreachable/unused from unresolved rather than invent replacements.
- **missing_verification** · content-accounting-verification: Identified whole-original DxWnd and current native Linux/Windows scenario capture/review remain open (0/120 obligations).
### frontend-hud
**Working behavior:** Bounded objective/practice/gadget UI and script return operate; persistent window/widescreen/F1/F2 are explicit modern presentation tools.
**Verified scope/platform:** S/M/R: source timer/O/strict input and Linux UI captures; historical layout is not complete original frontend parity.
**Known differences:** Startup/new-game/pause/menu/ending dispatcher and full objective flags/highlights/cursor/layout timing remain incomplete.
**Remaining acceptance — OPEN:** Recover original frontend modes/input/timing while distinguishing modern diagnostics and widescreen policy.; Identified whole-original DxWnd and current native Linux/Windows scenario capture/review remain open (0/120 obligations).
**Requirements:** UI-01 · **Implementation:** {&#x27;revision&#x27;: &#x27;ca08c468ba21a26710891b0029652351b9c2ae23&#x27;, &#x27;paths&#x27;: [&#x27;src/GamePort/Game/ObjectivePanel.cs&#x27;, &#x27;src/GamePort/Game/PracticePrompt.cs&#x27;, &#x27;src/GamePort/Game/GadgetScreen.cs&#x27;], &#x27;status&#x27;: &#x27;bounded&#x27;, &#x27;note&#x27;: &#x27;Revision identifies the last tracked change to the first implementation path; it is not a runtime/package identity. Unimplemented denotes the named full-scope workflow, not absence of all foundations.&#x27;}
**Sources:** [Retained checkpoint contracts and source-report links](../../docs/checkpoint/coverage.md), [Implementation gates and historical execution ledger](../../docs/checkpoint/implementation-plan.md), [Revision-specific runtime and package status index](../../docs/progress.md), [Platform classifications and limits](../../docs/compatibility.md), [Implementation: ObjectivePanel.cs](../../src/GamePort/Game/ObjectivePanel.cs), [Implementation: PracticePrompt.cs](../../src/GamePort/Game/PracticePrompt.cs), [Implementation: GadgetScreen.cs](../../src/GamePort/Game/GadgetScreen.cs)
**Scenarios:** [fresh-natural-edge](scenarios.json), [fresh-natural-ordinary](scenarios.json), [fresh-skipped-edge](scenarios.json), [fresh-skipped-ordinary](scenarios.json), [retained-natural-edge](scenarios.json), [retained-natural-ordinary](scenarios.json), [retained-skipped-edge](scenarios.json), [retained-skipped-ordinary](scenarios.json)
**Current applicable evidence (only the targets below):**
- {&quot;artifacts&quot;: [], &quot;claim&quot;: {&quot;key&quot;: &quot;frontend-hud-coverage&quot;, &quot;result&quot;: &quot;Bounded objective/practice/gadget UI and script return operate; persistent window/widescreen/F1/F2 are explicit modern presentation tools.&quot;}, &quot;content&quot;: {&quot;report_sha256&quot;: &quot;4481cb6df6748bc38a8808da64a93206f5e02326bc37e6fa2104f189b9339dea&quot;}, &quot;evidence_kind&quot;: &quot;static&quot;, &quot;historical&quot;: false, &quot;id&quot;: &quot;frontend-hud-report&quot;, &quot;method&quot;: &quot;Existing documentation inspected and indexed; not new binary recovery, component execution or gameplay capture&quot;, &quot;missing_evidence&quot;: [&quot;Identified whole-original DxWnd and current native Linux/Windows scenario capture/review remain open (0/120 obligations).&quot;], &quot;platform&quot;: {&quot;execution&quot;: &quot;static&quot;, &quot;os&quot;: &quot;source&quot;}, &quot;reason&quot;: null, &quot;receipt_id&quot;: &quot;frontend-hud-report&quot;, &quot;report_path&quot;: &quot;docs/checkpoint/coverage.md&quot;, &quot;revision&quot;: &quot;bdca29d3aa31face0c0023537ff98783716dbc45&quot;, &quot;scope&quot;: [&quot;frontend-hud: documentary coverage only&quot;], &quot;status&quot;: &quot;current&quot;, &quot;supersedes&quot;: []}
**Explicit applicability targets:** [{&#x27;id&#x27;: &#x27;frontend-hud-documentation&#x27;, &#x27;content&#x27;: {&#x27;report_sha256&#x27;: &#x27;4481cb6df6748bc38a8808da64a93206f5e02326bc37e6fa2104f189b9339dea&#x27;}, &#x27;platform&#x27;: {&#x27;os&#x27;: &#x27;source&#x27;, &#x27;execution&#x27;: &#x27;static&#x27;}, &#x27;scope&#x27;: [&#x27;frontend-hud: documentary coverage only&#x27;]}]
<details><summary>History — exact revisions and supersession retained</summary>
- No superseded evidence recorded.
</details>
**Player-impact discrepancies:**
- **disruptive** · frontend-hud-remaining: Recover original frontend modes/input/timing while distinguishing modern diagnostics and widescreen policy.
- **missing_verification** · frontend-hud-verification: Identified whole-original DxWnd and current native Linux/Windows scenario capture/review remain open (0/120 obligations).
### save-load-return
**Working behavior:** Original TSK round-trip/CLI task-item-score state, source departure-root RETURN and bounded retained scene snapshots are implemented.
**Verified scope/platform:** All 12 original saves byte-round-trip; S/P/M/R loader/RETURN route evidence is narrower than complete save UI/resume.
**Known differences:** Matching-task duplicate callbacks/post-task hooks and pickup checkpoint read consumer remain unresolved. TSK does not carry arbitrary actor/helper state.
**Remaining acceptance — OPEN:** Recover full save/load UI and reset/retained ownership across repeated loads and gameplay continuation; do not invent checkpoint respawn semantics.; Identified whole-original DxWnd and current native Linux/Windows scenario capture/review remain open (0/120 obligations).
**Requirements:** SAVE-01, SAVE-02 · **Implementation:** {&#x27;revision&#x27;: &#x27;8d60a68511d1891d68e34feb22d6938c738ba98f&#x27;, &#x27;paths&#x27;: [&#x27;src/GamePort/Game/RuntimeCheckpoint.cs&#x27;, &#x27;src/GamePort/Game/PlayerLevelState.cs&#x27;, &#x27;src/GamePort/Game/SceneInteractions.cs&#x27;], &#x27;status&#x27;: &#x27;bounded&#x27;, &#x27;note&#x27;: &#x27;Revision identifies the last tracked change to the first implementation path; it is not a runtime/package identity. Unimplemented denotes the named full-scope workflow, not absence of all foundations.&#x27;}
**Sources:** [Retained checkpoint contracts and source-report links](../../docs/checkpoint/coverage.md), [Implementation gates and historical execution ledger](../../docs/checkpoint/implementation-plan.md), [Revision-specific runtime and package status index](../../docs/progress.md), [Platform classifications and limits](../../docs/compatibility.md), [Implementation: RuntimeCheckpoint.cs](../../src/GamePort/Game/RuntimeCheckpoint.cs), [Implementation: PlayerLevelState.cs](../../src/GamePort/Game/PlayerLevelState.cs), [Implementation: SceneInteractions.cs](../../src/GamePort/Game/SceneInteractions.cs)
**Scenarios:** [fresh-natural-edge](scenarios.json), [fresh-natural-ordinary](scenarios.json), [fresh-skipped-edge](scenarios.json), [fresh-skipped-ordinary](scenarios.json), [retained-natural-edge](scenarios.json), [retained-natural-ordinary](scenarios.json), [retained-skipped-edge](scenarios.json), [retained-skipped-ordinary](scenarios.json)
**Current applicable evidence (only the targets below):**
- {&quot;artifacts&quot;: [], &quot;claim&quot;: {&quot;key&quot;: &quot;save-load-return-coverage&quot;, &quot;result&quot;: &quot;Original TSK round-trip/CLI task-item-score state, source departure-root RETURN and bounded retained scene snapshots are implemented.&quot;}, &quot;content&quot;: {&quot;report_sha256&quot;: &quot;4481cb6df6748bc38a8808da64a93206f5e02326bc37e6fa2104f189b9339dea&quot;}, &quot;evidence_kind&quot;: &quot;static&quot;, &quot;historical&quot;: false, &quot;id&quot;: &quot;save-load-return-report&quot;, &quot;method&quot;: &quot;Existing documentation inspected and indexed; not new binary recovery, component execution or gameplay capture&quot;, &quot;missing_evidence&quot;: [&quot;Identified whole-original DxWnd and current native Linux/Windows scenario capture/review remain open (0/120 obligations).&quot;], &quot;platform&quot;: {&quot;execution&quot;: &quot;static&quot;, &quot;os&quot;: &quot;source&quot;}, &quot;reason&quot;: null, &quot;receipt_id&quot;: &quot;save-load-return-report&quot;, &quot;report_path&quot;: &quot;docs/checkpoint/coverage.md&quot;, &quot;revision&quot;: &quot;bdca29d3aa31face0c0023537ff98783716dbc45&quot;, &quot;scope&quot;: [&quot;save-load-return: documentary coverage only&quot;], &quot;status&quot;: &quot;current&quot;, &quot;supersedes&quot;: []}
**Explicit applicability targets:** [{&#x27;id&#x27;: &#x27;save-load-return-documentation&#x27;, &#x27;content&#x27;: {&#x27;report_sha256&#x27;: &#x27;4481cb6df6748bc38a8808da64a93206f5e02326bc37e6fa2104f189b9339dea&#x27;}, &#x27;platform&#x27;: {&#x27;os&#x27;: &#x27;source&#x27;, &#x27;execution&#x27;: &#x27;static&#x27;}, &#x27;scope&#x27;: [&#x27;save-load-return: documentary coverage only&#x27;]}]
<details><summary>History — exact revisions and supersession retained</summary>
- No superseded evidence recorded.
</details>
**Player-impact discrepancies:**
- **disruptive** · save-load-return-remaining: Recover full save/load UI and reset/retained ownership across repeated loads and gameplay continuation; do not invent checkpoint respawn semantics.
- **missing_verification** · save-load-return-verification: Identified whole-original DxWnd and current native Linux/Windows scenario capture/review remain open (0/120 obligations).
### final-fidelity-audit
**Working behavior:** Capability/history/discrepancy navigation exists; a successful whole-game comparison and final fidelity audit is unimplemented.
**Verified scope/platform:** This ledger is auditable documentation and tool output, not a whole-original/native runtime result.
**Known differences:** Unresolved gameplay/timing/visual/audio/progression differences and reference/platform access prevent full-fidelity completion.
**Remaining acceptance — OPEN:** Compare complete identified original and native routes, publish remaining differences and require explicit review before final acceptance.; Identified whole-original DxWnd and current native Linux/Windows scenario capture/review remain open (0/120 obligations).
**Requirements:** REL-03 · **Implementation:** {&#x27;revision&#x27;: &#x27;bdca29d3aa31face0c0023537ff98783716dbc45&#x27;, &#x27;paths&#x27;: [], &#x27;status&#x27;: &#x27;unimplemented&#x27;, &#x27;note&#x27;: &#x27;Revision identifies the last tracked change to the first implementation path; it is not a runtime/package identity. Unimplemented denotes the named full-scope workflow, not absence of all foundations.&#x27;}
**Sources:** [Retained checkpoint contracts and source-report links](../../docs/checkpoint/coverage.md), [Implementation gates and historical execution ledger](../../docs/checkpoint/implementation-plan.md), [Revision-specific runtime and package status index](../../docs/progress.md), [Platform classifications and limits](../../docs/compatibility.md)
**Scenarios:** [fresh-natural-edge](scenarios.json), [fresh-natural-ordinary](scenarios.json), [fresh-skipped-edge](scenarios.json), [fresh-skipped-ordinary](scenarios.json), [retained-natural-edge](scenarios.json), [retained-natural-ordinary](scenarios.json), [retained-skipped-edge](scenarios.json), [retained-skipped-ordinary](scenarios.json)
**Current applicable evidence (only the targets below):**
- {&quot;artifacts&quot;: [], &quot;claim&quot;: {&quot;key&quot;: &quot;final-fidelity-audit-coverage&quot;, &quot;result&quot;: &quot;Capability/history/discrepancy navigation exists; a successful whole-game comparison and final fidelity audit is unimplemented.&quot;}, &quot;content&quot;: {&quot;report_sha256&quot;: &quot;4481cb6df6748bc38a8808da64a93206f5e02326bc37e6fa2104f189b9339dea&quot;}, &quot;evidence_kind&quot;: &quot;static&quot;, &quot;historical&quot;: false, &quot;id&quot;: &quot;final-fidelity-audit-report&quot;, &quot;method&quot;: &quot;Existing documentation inspected and indexed; not new binary recovery, component execution or gameplay capture&quot;, &quot;missing_evidence&quot;: [&quot;Identified whole-original DxWnd and current native Linux/Windows scenario capture/review remain open (0/120 obligations).&quot;], &quot;platform&quot;: {&quot;execution&quot;: &quot;static&quot;, &quot;os&quot;: &quot;source&quot;}, &quot;reason&quot;: null, &quot;receipt_id&quot;: &quot;final-fidelity-audit-report&quot;, &quot;report_path&quot;: &quot;docs/checkpoint/coverage.md&quot;, &quot;revision&quot;: &quot;bdca29d3aa31face0c0023537ff98783716dbc45&quot;, &quot;scope&quot;: [&quot;final-fidelity-audit: documentary coverage only&quot;], &quot;status&quot;: &quot;current&quot;, &quot;supersedes&quot;: []}
**Explicit applicability targets:** [{&#x27;id&#x27;: &#x27;final-fidelity-audit-documentation&#x27;, &#x27;content&#x27;: {&#x27;report_sha256&#x27;: &#x27;4481cb6df6748bc38a8808da64a93206f5e02326bc37e6fa2104f189b9339dea&#x27;}, &#x27;platform&#x27;: {&#x27;os&#x27;: &#x27;source&#x27;, &#x27;execution&#x27;: &#x27;static&#x27;}, &#x27;scope&#x27;: [&#x27;final-fidelity-audit: documentary coverage only&#x27;]}]
<details><summary>History — exact revisions and supersession retained</summary>
- No superseded evidence recorded.
</details>
**Player-impact discrepancies:**
- **missing_verification** · final-fidelity-audit-remaining: Compare complete identified original and native routes, publish remaining differences and require explicit review before final acceptance.
- **missing_verification** · final-fidelity-audit-verification: Identified whole-original DxWnd and current native Linux/Windows scenario capture/review remain open (0/120 obligations).
### native-delivery
**Working behavior:** Local shared .NET10/SDL3/Vulkan builds and Linux/Windows self-contained packages have bounded provenance and resource checks.
**Verified scope/platform:** Historical clean924ad2f packages: Linux standalone Carl 4 readbacks match ea04210; Windows cross-publish/resource verification only. Earlier ea04210 Wine64 remains preliminary.
**Known differences:** Current broader integrated runtime evidence bf876e9 does not change packaged924ad2f bytes; native Windows/full-campaign/audio/focus/lifecycle acceptance remains open.
**Remaining acceptance — OPEN:** Rebuild clean identified offline packages at integrated checkpoints; run complete native platform journeys and preserve exact source/resource/package/log identities.; Identified whole-original DxWnd and current native Linux/Windows scenario capture/review remain open (0/120 obligations).
**Requirements:** REL-01, REL-02, REL-04 · **Implementation:** {&#x27;revision&#x27;: &#x27;62c07a3d59ca6d71a7456957d8586c268d27c439&#x27;, &#x27;paths&#x27;: [&#x27;scripts/package.sh&#x27;, &#x27;scripts/build-linux.sh&#x27;, &#x27;scripts/build-windows.sh&#x27;, &#x27;scripts/test.sh&#x27;], &#x27;status&#x27;: &#x27;bounded&#x27;, &#x27;note&#x27;: &#x27;Revision identifies the last tracked change to the first implementation path; it is not a runtime/package identity. Unimplemented denotes the named full-scope workflow, not absence of all foundations.&#x27;}
**Sources:** [Retained checkpoint contracts and source-report links](../../docs/checkpoint/coverage.md), [Implementation gates and historical execution ledger](../../docs/checkpoint/implementation-plan.md), [Revision-specific runtime and package status index](../../docs/progress.md), [Platform classifications and limits](../../docs/compatibility.md), [Implementation: package.sh](../../scripts/package.sh), [Implementation: build-linux.sh](../../scripts/build-linux.sh), [Implementation: build-windows.sh](../../scripts/build-windows.sh), [Implementation: test.sh](../../scripts/test.sh)
**Scenarios:** [fresh-natural-edge](scenarios.json), [fresh-natural-ordinary](scenarios.json), [fresh-skipped-edge](scenarios.json), [fresh-skipped-ordinary](scenarios.json), [retained-natural-edge](scenarios.json), [retained-natural-ordinary](scenarios.json), [retained-skipped-edge](scenarios.json), [retained-skipped-ordinary](scenarios.json)
**Current applicable evidence (only the targets below):**
- {&quot;artifacts&quot;: [], &quot;claim&quot;: {&quot;key&quot;: &quot;native-delivery-coverage&quot;, &quot;result&quot;: &quot;Local shared .NET10/SDL3/Vulkan builds and Linux/Windows self-contained packages have bounded provenance and resource checks.&quot;}, &quot;content&quot;: {&quot;report_sha256&quot;: &quot;4481cb6df6748bc38a8808da64a93206f5e02326bc37e6fa2104f189b9339dea&quot;}, &quot;evidence_kind&quot;: &quot;static&quot;, &quot;historical&quot;: false, &quot;id&quot;: &quot;native-delivery-report&quot;, &quot;method&quot;: &quot;Existing documentation inspected and indexed; not new binary recovery, component execution or gameplay capture&quot;, &quot;missing_evidence&quot;: [&quot;Identified whole-original DxWnd and current native Linux/Windows scenario capture/review remain open (0/120 obligations).&quot;], &quot;platform&quot;: {&quot;execution&quot;: &quot;static&quot;, &quot;os&quot;: &quot;source&quot;}, &quot;reason&quot;: null, &quot;receipt_id&quot;: &quot;native-delivery-report&quot;, &quot;report_path&quot;: &quot;docs/checkpoint/coverage.md&quot;, &quot;revision&quot;: &quot;bdca29d3aa31face0c0023537ff98783716dbc45&quot;, &quot;scope&quot;: [&quot;native-delivery: documentary coverage only&quot;], &quot;status&quot;: &quot;current&quot;, &quot;supersedes&quot;: []}
**Explicit applicability targets:** [{&#x27;id&#x27;: &#x27;native-delivery-documentation&#x27;, &#x27;content&#x27;: {&#x27;report_sha256&#x27;: &#x27;4481cb6df6748bc38a8808da64a93206f5e02326bc37e6fa2104f189b9339dea&#x27;}, &#x27;platform&#x27;: {&#x27;os&#x27;: &#x27;source&#x27;, &#x27;execution&#x27;: &#x27;static&#x27;}, &#x27;scope&#x27;: [&#x27;native-delivery: documentary coverage only&#x27;]}]
<details><summary>History — exact revisions and supersession retained</summary>
- No superseded evidence recorded.
</details>
**Player-impact discrepancies:**
- **missing_verification** · native-delivery-remaining: Rebuild clean identified offline packages at integrated checkpoints; run complete native platform journeys and preserve exact source/resource/package/log identities.
- **missing_verification** · native-delivery-verification: Identified whole-original DxWnd and current native Linux/Windows scenario capture/review remain open (0/120 obligations).
### preservation-reference-tools
**Working behavior:** Local inventory, preserved staging, typed hashed receipt import, eight-cell protocol and paired review tools support reproducible evidence navigation.
**Verified scope/platform:** Tooling and synthetic fixtures only for phase 1; genuine original-DxWnd/native matrix coverage remains 0/120. Existing runtime evidence stays historical and bounded.
**Known differences:** Working whole-original captures, current native Windows and complete native Linux journeys plus human audiovisual review are missing.
**Remaining acceptance — OPEN:** Prepare combined local original/native checkpoint, collect identified input/audio/video/results and audit each obligation; ledger completion does not complete shared EVID requirements.; Identified whole-original DxWnd and current native Linux/Windows scenario capture/review remain open (0/120 obligations).
**Requirements:** EVID-01, EVID-02, EVID-03, EVID-04 · **Implementation:** {&#x27;revision&#x27;: &#x27;32a72654e88ad3709aa1e2f0f108eea06e1b7469&#x27;, &#x27;paths&#x27;: [&#x27;tools/recon/fidelity.py&#x27;, &#x27;tools/recon/fidelity_receipts.py&#x27;, &#x27;tools/recon/fidelity_review.py&#x27;], &#x27;status&#x27;: &#x27;tooling&#x27;, &#x27;note&#x27;: &#x27;Revision identifies the last tracked change to the first implementation path; it is not a runtime/package identity. Unimplemented denotes the named full-scope workflow, not absence of all foundations.&#x27;}
**Sources:** [Retained checkpoint contracts and source-report links](../../docs/checkpoint/coverage.md), [Implementation gates and historical execution ledger](../../docs/checkpoint/implementation-plan.md), [Revision-specific runtime and package status index](../../docs/progress.md), [Platform classifications and limits](../../docs/compatibility.md), [Capability source report](../../docs/evidence/scenarios.json), [Implementation: fidelity.py](../../tools/recon/fidelity.py), [Implementation: fidelity_receipts.py](../../tools/recon/fidelity_receipts.py), [Implementation: fidelity_review.py](../../tools/recon/fidelity_review.py)
**Scenarios:** [fresh-natural-edge](scenarios.json), [fresh-natural-ordinary](scenarios.json), [fresh-skipped-edge](scenarios.json), [fresh-skipped-ordinary](scenarios.json), [retained-natural-edge](scenarios.json), [retained-natural-ordinary](scenarios.json), [retained-skipped-edge](scenarios.json), [retained-skipped-ordinary](scenarios.json)
**Current applicable evidence (only the targets below):**
- {&quot;artifacts&quot;: [], &quot;claim&quot;: {&quot;key&quot;: &quot;preservation-reference-tools-coverage&quot;, &quot;result&quot;: &quot;Local inventory, preserved staging, typed hashed receipt import, eight-cell protocol and paired review tools support reproducible evidence navigation.&quot;}, &quot;content&quot;: {&quot;report_sha256&quot;: &quot;f43abb53db1715ca3c5643159b44cac3742b4b1973b1feaf9a1001f754537743&quot;}, &quot;evidence_kind&quot;: &quot;static&quot;, &quot;historical&quot;: false, &quot;id&quot;: &quot;preservation-reference-tools-report&quot;, &quot;method&quot;: &quot;Existing documentation inspected and indexed; not new binary recovery, component execution or gameplay capture&quot;, &quot;missing_evidence&quot;: [&quot;Identified whole-original DxWnd and current native Linux/Windows scenario capture/review remain open (0/120 obligations).&quot;], &quot;platform&quot;: {&quot;execution&quot;: &quot;static&quot;, &quot;os&quot;: &quot;source&quot;}, &quot;reason&quot;: null, &quot;receipt_id&quot;: &quot;preservation-reference-tools-report&quot;, &quot;report_path&quot;: &quot;docs/evidence/scenarios.json&quot;, &quot;revision&quot;: &quot;32a72654e88ad3709aa1e2f0f108eea06e1b7469&quot;, &quot;scope&quot;: [&quot;preservation-reference-tools: documentary coverage only&quot;], &quot;status&quot;: &quot;current&quot;, &quot;supersedes&quot;: []}
**Explicit applicability targets:** [{&#x27;id&#x27;: &#x27;preservation-reference-tools-documentation&#x27;, &#x27;content&#x27;: {&#x27;report_sha256&#x27;: &#x27;f43abb53db1715ca3c5643159b44cac3742b4b1973b1feaf9a1001f754537743&#x27;}, &#x27;platform&#x27;: {&#x27;os&#x27;: &#x27;source&#x27;, &#x27;execution&#x27;: &#x27;static&#x27;}, &#x27;scope&#x27;: [&#x27;preservation-reference-tools: documentary coverage only&#x27;]}]
<details><summary>History — exact revisions and supersession retained</summary>
- No superseded evidence recorded.
</details>
**Player-impact discrepancies:**
- **missing_verification** · preservation-reference-tools-remaining: Prepare combined local original/native checkpoint, collect identified input/audio/video/results and audit each obligation; ledger completion does not complete shared EVID requirements.
- **missing_verification** · preservation-reference-tools-verification: Identified whole-original DxWnd and current native Linux/Windows scenario capture/review remain open (0/120 obligations).
## Visuals
### shared-camera-projection
**Working behavior:** Source static clipping/ray/gain runs in lab/VR04/outside; all level far overrides and bounded vehicle/script cameras are mapped.
**Verified scope/platform:** S/M/R source/projection and native Linux camera/transition checks; orbit inspector is modern and has separate Left/Right correction.
**Known differences:** Shared viewport eye/aim/default follow ownership, full input/quantization and layer maximum/masks remain open.
**Remaining acceptance — OPEN:** Recover shared old-eye/aim and first-follow handoff plus source projection/layers; preserve separate modern render/noclip policies.; Identified whole-original DxWnd and current native Linux/Windows scenario capture/review remain open (0/120 obligations).
**Requirements:** VIS-03, MOVE-04 · **Implementation:** {&#x27;revision&#x27;: &#x27;62c07a3d59ca6d71a7456957d8586c268d27c439&#x27;, &#x27;paths&#x27;: [&#x27;src/GamePort/Game/OriginalCameraRay.cs&#x27;, &#x27;src/GamePort/Game/GrapplerCamera.cs&#x27;, &#x27;src/GamePort/Game/ScooterCamera.cs&#x27;], &#x27;status&#x27;: &#x27;bounded&#x27;, &#x27;note&#x27;: &#x27;Revision identifies the last tracked change to the first implementation path; it is not a runtime/package identity. Unimplemented denotes the named full-scope workflow, not absence of all foundations.&#x27;}
**Sources:** [Retained checkpoint contracts and source-report links](../../docs/checkpoint/coverage.md), [Implementation gates and historical execution ledger](../../docs/checkpoint/implementation-plan.md), [Revision-specific runtime and package status index](../../docs/progress.md), [Platform classifications and limits](../../docs/compatibility.md), [Implementation: OriginalCameraRay.cs](../../src/GamePort/Game/OriginalCameraRay.cs), [Implementation: GrapplerCamera.cs](../../src/GamePort/Game/GrapplerCamera.cs), [Implementation: ScooterCamera.cs](../../src/GamePort/Game/ScooterCamera.cs)
**Scenarios:** [fresh-natural-edge](scenarios.json), [fresh-natural-ordinary](scenarios.json), [fresh-skipped-edge](scenarios.json), [fresh-skipped-ordinary](scenarios.json), [retained-natural-edge](scenarios.json), [retained-natural-ordinary](scenarios.json), [retained-skipped-edge](scenarios.json), [retained-skipped-ordinary](scenarios.json)
**Current applicable evidence (only the targets below):**
- {&quot;artifacts&quot;: [], &quot;claim&quot;: {&quot;key&quot;: &quot;shared-camera-projection-coverage&quot;, &quot;result&quot;: &quot;Source static clipping/ray/gain runs in lab/VR04/outside; all level far overrides and bounded vehicle/script cameras are mapped.&quot;}, &quot;content&quot;: {&quot;report_sha256&quot;: &quot;4481cb6df6748bc38a8808da64a93206f5e02326bc37e6fa2104f189b9339dea&quot;}, &quot;evidence_kind&quot;: &quot;static&quot;, &quot;historical&quot;: false, &quot;id&quot;: &quot;shared-camera-projection-report&quot;, &quot;method&quot;: &quot;Existing documentation inspected and indexed; not new binary recovery, component execution or gameplay capture&quot;, &quot;missing_evidence&quot;: [&quot;Identified whole-original DxWnd and current native Linux/Windows scenario capture/review remain open (0/120 obligations).&quot;], &quot;platform&quot;: {&quot;execution&quot;: &quot;static&quot;, &quot;os&quot;: &quot;source&quot;}, &quot;reason&quot;: null, &quot;receipt_id&quot;: &quot;shared-camera-projection-report&quot;, &quot;report_path&quot;: &quot;docs/checkpoint/coverage.md&quot;, &quot;revision&quot;: &quot;bdca29d3aa31face0c0023537ff98783716dbc45&quot;, &quot;scope&quot;: [&quot;shared-camera-projection: documentary coverage only&quot;], &quot;status&quot;: &quot;current&quot;, &quot;supersedes&quot;: []}
**Explicit applicability targets:** [{&#x27;id&#x27;: &#x27;shared-camera-projection-documentation&#x27;, &#x27;content&#x27;: {&#x27;report_sha256&#x27;: &#x27;4481cb6df6748bc38a8808da64a93206f5e02326bc37e6fa2104f189b9339dea&#x27;}, &#x27;platform&#x27;: {&#x27;os&#x27;: &#x27;source&#x27;, &#x27;execution&#x27;: &#x27;static&#x27;}, &#x27;scope&#x27;: [&#x27;shared-camera-projection: documentary coverage only&#x27;]}]
<details><summary>History — exact revisions and supersession retained</summary>
- No superseded evidence recorded.
</details>
**Player-impact discrepancies:**
- **disruptive** · shared-camera-projection-remaining: Recover shared old-eye/aim and first-follow handoff plus source projection/layers; preserve separate modern render/noclip policies.
- **missing_verification** · shared-camera-projection-verification: Identified whole-original DxWnd and current native Linux/Windows scenario capture/review remain open (0/120 obligations).
### vulkan-materials
**Working behavior:** Vulkan renders original textured/depth geometry and bounded material/alpha effects; null-material and Rocketship diffuse RGBA contracts are corrected.
**Verified scope/platform:** Historical Linux enabled-validation GPU tests, material/readback checks and source data; no original visual equivalence.
**Known differences:** Lighting/fog/texture stages/layer masks/blending/culling/material options and source widescreen presentation remain incomplete.
**Remaining acceptance — OPEN:** Recover remaining fixed-function equivalents and compare actual original frames with matched viewport/event provenance.; Identified whole-original DxWnd and current native Linux/Windows scenario capture/review remain open (0/120 obligations).
**Requirements:** VIS-02 · **Implementation:** {&#x27;revision&#x27;: &#x27;7b5230ceb819e2e6cd551f19d11ef07fad9f1876&#x27;, &#x27;paths&#x27;: [&#x27;src/GamePort/Rendering/Vulkan/VulkanRenderer.cs&#x27;], &#x27;status&#x27;: &#x27;bounded&#x27;, &#x27;note&#x27;: &#x27;Revision identifies the last tracked change to the first implementation path; it is not a runtime/package identity. Unimplemented denotes the named full-scope workflow, not absence of all foundations.&#x27;}
**Sources:** [Retained checkpoint contracts and source-report links](../../docs/checkpoint/coverage.md), [Implementation gates and historical execution ledger](../../docs/checkpoint/implementation-plan.md), [Revision-specific runtime and package status index](../../docs/progress.md), [Platform classifications and limits](../../docs/compatibility.md), [Implementation: VulkanRenderer.cs](../../src/GamePort/Rendering/Vulkan/VulkanRenderer.cs)
**Scenarios:** [fresh-natural-edge](scenarios.json), [fresh-natural-ordinary](scenarios.json), [fresh-skipped-edge](scenarios.json), [fresh-skipped-ordinary](scenarios.json), [retained-natural-edge](scenarios.json), [retained-natural-ordinary](scenarios.json), [retained-skipped-edge](scenarios.json), [retained-skipped-ordinary](scenarios.json)
**Current applicable evidence (only the targets below):**
- {&quot;artifacts&quot;: [], &quot;claim&quot;: {&quot;key&quot;: &quot;vulkan-materials-coverage&quot;, &quot;result&quot;: &quot;Vulkan renders original textured/depth geometry and bounded material/alpha effects; null-material and Rocketship diffuse RGBA contracts are corrected.&quot;}, &quot;content&quot;: {&quot;report_sha256&quot;: &quot;4481cb6df6748bc38a8808da64a93206f5e02326bc37e6fa2104f189b9339dea&quot;}, &quot;evidence_kind&quot;: &quot;static&quot;, &quot;historical&quot;: false, &quot;id&quot;: &quot;vulkan-materials-report&quot;, &quot;method&quot;: &quot;Existing documentation inspected and indexed; not new binary recovery, component execution or gameplay capture&quot;, &quot;missing_evidence&quot;: [&quot;Identified whole-original DxWnd and current native Linux/Windows scenario capture/review remain open (0/120 obligations).&quot;], &quot;platform&quot;: {&quot;execution&quot;: &quot;static&quot;, &quot;os&quot;: &quot;source&quot;}, &quot;reason&quot;: null, &quot;receipt_id&quot;: &quot;vulkan-materials-report&quot;, &quot;report_path&quot;: &quot;docs/checkpoint/coverage.md&quot;, &quot;revision&quot;: &quot;bdca29d3aa31face0c0023537ff98783716dbc45&quot;, &quot;scope&quot;: [&quot;vulkan-materials: documentary coverage only&quot;], &quot;status&quot;: &quot;current&quot;, &quot;supersedes&quot;: []}
**Explicit applicability targets:** [{&#x27;id&#x27;: &#x27;vulkan-materials-documentation&#x27;, &#x27;content&#x27;: {&#x27;report_sha256&#x27;: &#x27;4481cb6df6748bc38a8808da64a93206f5e02326bc37e6fa2104f189b9339dea&#x27;}, &#x27;platform&#x27;: {&#x27;os&#x27;: &#x27;source&#x27;, &#x27;execution&#x27;: &#x27;static&#x27;}, &#x27;scope&#x27;: [&#x27;vulkan-materials: documentary coverage only&#x27;]}]
<details><summary>History — exact revisions and supersession retained</summary>
- No superseded evidence recorded.
</details>
**Player-impact discrepancies:**
- **disruptive** · vulkan-materials-remaining: Recover remaining fixed-function equivalents and compare actual original frames with matched viewport/event provenance.
- **missing_verification** · vulkan-materials-verification: Identified whole-original DxWnd and current native Linux/Windows scenario capture/review remain open (0/120 obligations).
### models-animation-layout
**Working behavior:** Original geometry/textures/hierarchies/morphs/sprites/UI resources render with bounded full-Euler and source-pivot bridges.
**Verified scope/platform:** Original-data/managed and historical Linux GPU readbacks; air bridge records 146 observations but final OMT decomposition precision differs.
**Known differences:** Modern sole alignment, loop timing, some actor pivots and full source action/morph/layout lifecycle remain explicit differences.
**Remaining acceptance — OPEN:** Recover final OMT decomposition and playback/actor/UI ownership, then compare authored positions and timing against identified original captures.; Identified whole-original DxWnd and current native Linux/Windows scenario capture/review remain open (0/120 obligations).
**Requirements:** VIS-01 · **Implementation:** {&#x27;revision&#x27;: &#x27;27be8ed63079ae2e3bf7e965ee205c4a57a96559&#x27;, &#x27;paths&#x27;: [&#x27;src/GamePort/Game/JimmyRenderTransform.cs&#x27;, &#x27;src/GamePort/Game/PlayerAppearance.cs&#x27;], &#x27;status&#x27;: &#x27;bounded&#x27;, &#x27;note&#x27;: &#x27;Revision identifies the last tracked change to the first implementation path; it is not a runtime/package identity. Unimplemented denotes the named full-scope workflow, not absence of all foundations.&#x27;}
**Sources:** [Retained checkpoint contracts and source-report links](../../docs/checkpoint/coverage.md), [Implementation gates and historical execution ledger](../../docs/checkpoint/implementation-plan.md), [Revision-specific runtime and package status index](../../docs/progress.md), [Platform classifications and limits](../../docs/compatibility.md), [Implementation: JimmyRenderTransform.cs](../../src/GamePort/Game/JimmyRenderTransform.cs), [Implementation: PlayerAppearance.cs](../../src/GamePort/Game/PlayerAppearance.cs)
**Scenarios:** [fresh-natural-edge](scenarios.json), [fresh-natural-ordinary](scenarios.json), [fresh-skipped-edge](scenarios.json), [fresh-skipped-ordinary](scenarios.json), [retained-natural-edge](scenarios.json), [retained-natural-ordinary](scenarios.json), [retained-skipped-edge](scenarios.json), [retained-skipped-ordinary](scenarios.json)
**Current applicable evidence (only the targets below):**
- {&quot;artifacts&quot;: [], &quot;claim&quot;: {&quot;key&quot;: &quot;models-animation-layout-coverage&quot;, &quot;result&quot;: &quot;Original geometry/textures/hierarchies/morphs/sprites/UI resources render with bounded full-Euler and source-pivot bridges.&quot;}, &quot;content&quot;: {&quot;report_sha256&quot;: &quot;4481cb6df6748bc38a8808da64a93206f5e02326bc37e6fa2104f189b9339dea&quot;}, &quot;evidence_kind&quot;: &quot;static&quot;, &quot;historical&quot;: false, &quot;id&quot;: &quot;models-animation-layout-report&quot;, &quot;method&quot;: &quot;Existing documentation inspected and indexed; not new binary recovery, component execution or gameplay capture&quot;, &quot;missing_evidence&quot;: [&quot;Identified whole-original DxWnd and current native Linux/Windows scenario capture/review remain open (0/120 obligations).&quot;], &quot;platform&quot;: {&quot;execution&quot;: &quot;static&quot;, &quot;os&quot;: &quot;source&quot;}, &quot;reason&quot;: null, &quot;receipt_id&quot;: &quot;models-animation-layout-report&quot;, &quot;report_path&quot;: &quot;docs/checkpoint/coverage.md&quot;, &quot;revision&quot;: &quot;bdca29d3aa31face0c0023537ff98783716dbc45&quot;, &quot;scope&quot;: [&quot;models-animation-layout: documentary coverage only&quot;], &quot;status&quot;: &quot;current&quot;, &quot;supersedes&quot;: []}
**Explicit applicability targets:** [{&#x27;id&#x27;: &#x27;models-animation-layout-documentation&#x27;, &#x27;content&#x27;: {&#x27;report_sha256&#x27;: &#x27;4481cb6df6748bc38a8808da64a93206f5e02326bc37e6fa2104f189b9339dea&#x27;}, &#x27;platform&#x27;: {&#x27;os&#x27;: &#x27;source&#x27;, &#x27;execution&#x27;: &#x27;static&#x27;}, &#x27;scope&#x27;: [&#x27;models-animation-layout: documentary coverage only&#x27;]}]
<details><summary>History — exact revisions and supersession retained</summary>
- No superseded evidence recorded.
</details>
**Player-impact discrepancies:**
- **subtle** · models-animation-layout-remaining: Recover final OMT decomposition and playback/actor/UI ownership, then compare authored positions and timing against identified original captures.
- **missing_verification** · models-animation-layout-verification: Identified whole-original DxWnd and current native Linux/Windows scenario capture/review remain open (0/120 obligations).
## Audio
### music-speech-banks
**Working behavior:** Original music/speech and 251 RIFF effects exports feed independent SDL streams; CAM stops music and DEFAULT restores it.
**Verified scope/platform:** S/M/R with Linux dummy-device and bounded package stream checks; queue consumption is not original audible timing.
**Known differences:** Software duration integer boundaries, channel allocation/failure/priority, bank/gate/unload/repeat lifetime and unsupported MPEG-in-RIFF remain open.
**Remaining acceptance — OPEN:** Recover bank/channel lifecycle and source software clock, then verify real scene selection/timing/loop/interruption audibly.; Identified whole-original DxWnd and current native Linux/Windows scenario capture/review remain open (0/120 obligations).
**Requirements:** AUD-01 · **Implementation:** {&#x27;revision&#x27;: &#x27;62c07a3d59ca6d71a7456957d8586c268d27c439&#x27;, &#x27;paths&#x27;: [&#x27;src/GamePort/Audio/SceneAudio.cs&#x27;, &#x27;src/GamePort/Audio/SdlAudio.cs&#x27;], &#x27;status&#x27;: &#x27;bounded&#x27;, &#x27;note&#x27;: &#x27;Revision identifies the last tracked change to the first implementation path; it is not a runtime/package identity. Unimplemented denotes the named full-scope workflow, not absence of all foundations.&#x27;}
**Sources:** [Retained checkpoint contracts and source-report links](../../docs/checkpoint/coverage.md), [Implementation gates and historical execution ledger](../../docs/checkpoint/implementation-plan.md), [Revision-specific runtime and package status index](../../docs/progress.md), [Platform classifications and limits](../../docs/compatibility.md), [Implementation: SceneAudio.cs](../../src/GamePort/Audio/SceneAudio.cs), [Implementation: SdlAudio.cs](../../src/GamePort/Audio/SdlAudio.cs)
**Scenarios:** [fresh-natural-edge](scenarios.json), [fresh-natural-ordinary](scenarios.json), [fresh-skipped-edge](scenarios.json), [fresh-skipped-ordinary](scenarios.json), [retained-natural-edge](scenarios.json), [retained-natural-ordinary](scenarios.json), [retained-skipped-edge](scenarios.json), [retained-skipped-ordinary](scenarios.json)
**Current applicable evidence (only the targets below):**
- {&quot;artifacts&quot;: [], &quot;claim&quot;: {&quot;key&quot;: &quot;music-speech-banks-coverage&quot;, &quot;result&quot;: &quot;Original music/speech and 251 RIFF effects exports feed independent SDL streams; CAM stops music and DEFAULT restores it.&quot;}, &quot;content&quot;: {&quot;report_sha256&quot;: &quot;4481cb6df6748bc38a8808da64a93206f5e02326bc37e6fa2104f189b9339dea&quot;}, &quot;evidence_kind&quot;: &quot;static&quot;, &quot;historical&quot;: false, &quot;id&quot;: &quot;music-speech-banks-report&quot;, &quot;method&quot;: &quot;Existing documentation inspected and indexed; not new binary recovery, component execution or gameplay capture&quot;, &quot;missing_evidence&quot;: [&quot;Identified whole-original DxWnd and current native Linux/Windows scenario capture/review remain open (0/120 obligations).&quot;], &quot;platform&quot;: {&quot;execution&quot;: &quot;static&quot;, &quot;os&quot;: &quot;source&quot;}, &quot;reason&quot;: null, &quot;receipt_id&quot;: &quot;music-speech-banks-report&quot;, &quot;report_path&quot;: &quot;docs/checkpoint/coverage.md&quot;, &quot;revision&quot;: &quot;bdca29d3aa31face0c0023537ff98783716dbc45&quot;, &quot;scope&quot;: [&quot;music-speech-banks: documentary coverage only&quot;], &quot;status&quot;: &quot;current&quot;, &quot;supersedes&quot;: []}
**Explicit applicability targets:** [{&#x27;id&#x27;: &#x27;music-speech-banks-documentation&#x27;, &#x27;content&#x27;: {&#x27;report_sha256&#x27;: &#x27;4481cb6df6748bc38a8808da64a93206f5e02326bc37e6fa2104f189b9339dea&#x27;}, &#x27;platform&#x27;: {&#x27;os&#x27;: &#x27;source&#x27;, &#x27;execution&#x27;: &#x27;static&#x27;}, &#x27;scope&#x27;: [&#x27;music-speech-banks: documentary coverage only&#x27;]}]
<details><summary>History — exact revisions and supersession retained</summary>
- No superseded evidence recorded.
</details>
**Player-impact discrepancies:**
- **disruptive** · music-speech-banks-remaining: Recover bank/channel lifecycle and source software clock, then verify real scene selection/timing/loop/interruption audibly.
- **missing_verification** · music-speech-banks-verification: Identified whole-original DxWnd and current native Linux/Windows scenario capture/review remain open (0/120 obligations).
### spatial-audio-listener
**Working behavior:** Scooter positional frequency/history correction uses the shared listener including parked/script cameras; nominal engine formula is preserved.
**Verified scope/platform:** Historical 11 positional-frequency plus 11 follow traces, managed/dummy and Linux SDL replays at fccc0b9; no new audible or Windows proof.
**Known differences:** Global attenuation/pan/channel scheduling, listener ownership across all states and physical speaker/native Windows comparison remain incomplete.
**Remaining acceptance — OPEN:** Recover all positional volume/frequency/listener policies and compare audible original/native output alongside event/stream checks.; Identified whole-original DxWnd and current native Linux/Windows scenario capture/review remain open (0/120 obligations).
**Requirements:** AUD-02 · **Implementation:** {&#x27;revision&#x27;: &#x27;fccc0b9d1b6ae962d32147e4ae1433fce6a1a23e&#x27;, &#x27;paths&#x27;: [&#x27;src/GamePort/Game/ScooterAudio.cs&#x27;, &#x27;src/GamePort/Audio/SceneAudio.cs&#x27;], &#x27;status&#x27;: &#x27;bounded&#x27;, &#x27;note&#x27;: &#x27;Revision identifies the last tracked change to the first implementation path; it is not a runtime/package identity. Unimplemented denotes the named full-scope workflow, not absence of all foundations.&#x27;}
**Sources:** [Retained checkpoint contracts and source-report links](../../docs/checkpoint/coverage.md), [Implementation gates and historical execution ledger](../../docs/checkpoint/implementation-plan.md), [Revision-specific runtime and package status index](../../docs/progress.md), [Platform classifications and limits](../../docs/compatibility.md), [Implementation: ScooterAudio.cs](../../src/GamePort/Game/ScooterAudio.cs), [Implementation: SceneAudio.cs](../../src/GamePort/Audio/SceneAudio.cs)
**Scenarios:** [fresh-natural-edge](scenarios.json), [fresh-natural-ordinary](scenarios.json), [fresh-skipped-edge](scenarios.json), [fresh-skipped-ordinary](scenarios.json), [retained-natural-edge](scenarios.json), [retained-natural-ordinary](scenarios.json), [retained-skipped-edge](scenarios.json), [retained-skipped-ordinary](scenarios.json)
**Current applicable evidence (only the targets below):**
- {&quot;artifacts&quot;: [], &quot;claim&quot;: {&quot;key&quot;: &quot;spatial-audio-listener-coverage&quot;, &quot;result&quot;: &quot;Scooter positional frequency/history correction uses the shared listener including parked/script cameras; nominal engine formula is preserved.&quot;}, &quot;content&quot;: {&quot;report_sha256&quot;: &quot;4481cb6df6748bc38a8808da64a93206f5e02326bc37e6fa2104f189b9339dea&quot;}, &quot;evidence_kind&quot;: &quot;static&quot;, &quot;historical&quot;: false, &quot;id&quot;: &quot;spatial-audio-listener-report&quot;, &quot;method&quot;: &quot;Existing documentation inspected and indexed; not new binary recovery, component execution or gameplay capture&quot;, &quot;missing_evidence&quot;: [&quot;Identified whole-original DxWnd and current native Linux/Windows scenario capture/review remain open (0/120 obligations).&quot;], &quot;platform&quot;: {&quot;execution&quot;: &quot;static&quot;, &quot;os&quot;: &quot;source&quot;}, &quot;reason&quot;: null, &quot;receipt_id&quot;: &quot;spatial-audio-listener-report&quot;, &quot;report_path&quot;: &quot;docs/checkpoint/coverage.md&quot;, &quot;revision&quot;: &quot;bdca29d3aa31face0c0023537ff98783716dbc45&quot;, &quot;scope&quot;: [&quot;spatial-audio-listener: documentary coverage only&quot;], &quot;status&quot;: &quot;current&quot;, &quot;supersedes&quot;: []}
**Explicit applicability targets:** [{&#x27;id&#x27;: &#x27;spatial-audio-listener-documentation&#x27;, &#x27;content&#x27;: {&#x27;report_sha256&#x27;: &#x27;4481cb6df6748bc38a8808da64a93206f5e02326bc37e6fa2104f189b9339dea&#x27;}, &#x27;platform&#x27;: {&#x27;os&#x27;: &#x27;source&#x27;, &#x27;execution&#x27;: &#x27;static&#x27;}, &#x27;scope&#x27;: [&#x27;spatial-audio-listener: documentary coverage only&#x27;]}]
<details><summary>History — exact revisions and supersession retained</summary>
- No superseded evidence recorded.
</details>
**Player-impact discrepancies:**
- **disruptive** · spatial-audio-listener-remaining: Recover all positional volume/frequency/listener policies and compare audible original/native output alongside event/stream checks.
- **missing_verification** · spatial-audio-listener-verification: Identified whole-original DxWnd and current native Linux/Windows scenario capture/review remain open (0/120 obligations).
## Source-row reconciliation
Every checkpoint row remains explicitly linked; continuation reports refine its claims.
- system:LOOP → controller-phases · [retained source](../../docs/checkpoint/coverage.md)
- system:INPUT → controller-phases · [retained source](../../docs/checkpoint/coverage.md)
- system:MOVE → controller-phases · [retained source](../../docs/checkpoint/coverage.md)
- system:JET → gadget-use · [retained source](../../docs/checkpoint/coverage.md)
- system:COLL → body-static-dynamic · [retained source](../../docs/checkpoint/coverage.md)
- system:ANIM → action-animation · [retained source](../../docs/checkpoint/coverage.md)
- system:SCRIPT → authored-scenes-tasks · [retained source](../../docs/checkpoint/coverage.md)
- system:CONTROL → route-control · [retained source](../../docs/checkpoint/coverage.md)
- system:CAMERA → shared-camera-projection · [retained source](../../docs/checkpoint/coverage.md)
- system:AUDIO → music-speech-banks · [retained source](../../docs/checkpoint/coverage.md)
- system:UI → frontend-hud · [retained source](../../docs/checkpoint/coverage.md)
- system:LOAD → physical-helper-lifetimes · [retained source](../../docs/checkpoint/coverage.md)
- system:INVENTORY → inventory-energy · [retained source](../../docs/checkpoint/coverage.md)
- system:SAVE → save-load-return · [retained source](../../docs/checkpoint/coverage.md)
- system:CHECKPOINT → save-load-return · [retained source](../../docs/checkpoint/coverage.md)
- system:SCOOTER → vehicles · [retained source](../../docs/checkpoint/coverage.md)
- ownership:Task records4FC5FC, name+0/state+64 → authored-scenes-tasks · [retained source](../../docs/checkpoint/coverage.md)
- ownership:Current controlled entity5099E4 → route-control · [retained source](../../docs/checkpoint/coverage.md)
- ownership:Scene actor game interface, body, OMT morph → action-animation · [retained source](../../docs/checkpoint/coverage.md)
- ownership:Objective selector4F8194 / transient timing and flags → frontend-hud · [retained source](../../docs/checkpoint/coverage.md)
- ownership:Departed root complete+9A8 → save-load-return · [retained source](../../docs/checkpoint/coverage.md)
- ownership:Return level/start strings → save-load-return · [retained source](../../docs/checkpoint/coverage.md)
- ownership:Pickup checkpoint complete+1E38/+1E48 → save-load-return · [retained source](../../docs/checkpoint/coverage.md)
- ownership:Music/effects/cutscene voice → music-speech-banks · [retained source](../../docs/checkpoint/coverage.md)
- ownership:Viewport/camera target → shared-camera-projection · [retained source](../../docs/checkpoint/coverage.md)
- ownership:Jimmy mode/hold/owned-fire timer → gadget-retention · [retained source](../../docs/checkpoint/coverage.md)
- ownership:Modern application presentation and debug → frontend-hud · [retained source](../../docs/checkpoint/coverage.md)
- assumption:1 → controller-phases · [retained source](../../docs/checkpoint/coverage.md)
- assumption:2 → body-static-dynamic · [retained source](../../docs/checkpoint/coverage.md)
- assumption:3 → authored-scenes-tasks · [retained source](../../docs/checkpoint/coverage.md)
- assumption:4 → shared-camera-projection · [retained source](../../docs/checkpoint/coverage.md)
- assumption:5 → music-speech-banks · [retained source](../../docs/checkpoint/coverage.md)
- assumption:6 → route-control · [retained source](../../docs/checkpoint/coverage.md)
File diff suppressed because it is too large. Load diff
+169
View File
@@ -0,0 +1,169 @@
# Phase 01 combined acceptance session
Materials preparation is separate from acceptance. The final local checkpoint is
`dist/fidelity/phase01`; all 120 obligations remain OPEN until actual captures and
human review. This document prepares the single combined session; it does not
report that any physical, audible, Windows or original fact has been observed.
Read [Windows/DxWnd instructions](windows-session.md) and
[Linux capture instructions](linux-session.md) together. They contain the exact
collector commands, settings, annotation fields and complete procedures. The
sealed packages retain source `446930d2a30d6d616c60ac5e59e4169a840bea09`, dirty true,
diff `90cef95669caece53fe2d2c4736cf2ac05ed27f5d25ca03ab572589686bcb73d`.
The later tools/checklist revision never replaces that runtime provenance.
1. Recheck immutable materials immediately before local transfer:
`python3 tools/recon/fidelity_acceptance.py ready --checkpoint dist/fidelity/phase01`.
Require `materials_ready: true`, separately `acceptance: human_needed`. A changed
package/resource requires a fresh identified checkpoint. Preserve the old bundle.
2. On the actual Windows PC select already installed DxWnd, its original exported
profile, recorder, browser and media tools. Record versions, executable hashes,
Windows/GPU/driver identities and actual settings. Run the bundled PowerShell
preflight and selftests; save their complete positive counts and failures.
3. Use only generated original copies. Retain pristine/pre/retained/post inventories,
original and relocated DxWnd profiles, wrapper limitations and the actual child
launch method. Observe moving game imagery, intelligible game audio, crop and
aspect before recording scenarios. Black/silent captures remain failed evidence.
4. Follow `protocol/agenda.json`: eight fresh/retained × natural/skipped × ordinary/
held-input cells, each with continuous, dialogue-return, bank-left, bank-right,
landing-idle obligations on original-DxWnd and native Windows (80). Follow the
same 40 obligations on native Linux. Retained departure/return must remain in
one process/clock. Continuous is lab → VR04 → lab → outside. No fixture, warp,
Wine, cross-publish, injected input or second fresh launch fills these slots.
5. Complete Linux real-display, physical-input and actual audible-device checks.
The saved `linux-01-06-matrix-preflight-linux` failure explains the current TTY/
auto_null limitation; it proves no captured gameplay. Retain failed/aborted/
skipped results and use fresh launch IDs for retries.
6. Review actual paired recordings in the identified local browser, including
decode/playback, seeking, complete tails, exclusive audio, corresponding events,
raw elapsed/event drift, actual speed and optional overlays. Keep source MKV,
derivation tool/hash/argv/time mapping and visible review gain. Do not invent
timing/pixel/angle/audio thresholds or hide drift through retiming.
7. Record the following named human findings with reviewer and concrete notes:
`A1` original moving imagery/intelligible audio/DxWnd limits; `A2` actual browser
decode/seek/exclusive audio; `EVID-02-unclassified` original capture boundaries;
`EVID-04-unclassified` native route/input/audio/identity; `P1` preservation;
`P2` honest unretimed/unmixed/non-synthetic comparison; `P3` history/full-scope/
native transparency; `browser`; `paired_review`; `physical_input`. A1/A2 are
separate from the two flagged assumptions. Insufficient observation remains
human_needed; descriptor-less P1/P2/P3 cannot be automatically dismissed.
8. Return the complete tree once by local filesystem/USB/existing local share.
Compare mutable result/original-run inventories with the source transfer
inventory, recheck READY/manifest and every linked hash before atomic import.
Keep packages, original copies and media local and ignored.
## Result reconciliation contract — integration agent only
The human tester collects, observes and returns the tree. The integration agent
performs the following local reconciliation after return; the tester is never
asked to engineer JSON or run the Python tooling. No normalized gameplay receipt
exists yet. Do not run reconciliation on failed/skipped/aborted/incomplete runs as
if they were successful; import those unchanged as diagnostic history.
Keep raw collector receipts immutable. Use the existing receipt importer on a
fresh local result destination; it validates hashes/containment and rejects
conflicting duplicates. Reviewed acceptance receipts are separately authored
records retaining the raw collector identity, actual media/events and limitations;
they must satisfy the shared receipt schema, source/package/resource binding and
full scenario continuity. Raw collection success never becomes review success.
Windows source/package/resources initially identify the exact `fidelity-build.json`
seal. Original reviewed receipts additionally identify the unchanged original
inventory and actual generated-copy pre/post inventories; missing raw collector
fields require evidence-backed normalization, never invented values.
Work on a **fresh sibling derived directory** for each captured raw receipt. Copy
every raw referenced file byte-identically into that directory, copy the raw
`receipt.json` as `raw-receipt.json`, and preserve `raw-receipt.sha256`. Make the
reviewed receipt a new ID ending `-reviewed`; retain the original launch/session
and clock IDs. Add the hashed raw receipt to `artifacts` with role `diagnostic`.
The integration agent uses this exact mapping; every new path is inside that fresh
derived directory and every identity uses `identify_file(actual_path)` including
SHA-256, size and header. No path or command from returned metadata is executed.
| Reviewed field | Actual source and required validation |
|---|---|
| Native executable | Raw identity copy; match manifest package executable SHA-256 |
| Native package | Exact selected RID's copied `fidelity-build.json`; match sealed package SHA-256 |
| Windows native source/resources | Same actual `fidelity-build.json` file; retain its source commit/dirty/diff fields. Resources are proven by exact full seal equality |
| Linux native source | Raw `identity/BUILD-INFO.txt`, with commit/dirty/diff taken from the matching exact package seal |
| Linux native resources | Raw `identity/resources.json`, exactly equal to manifest package resources |
| Original executable | Actual selected executable from the generated run (`Neutron.exe` or the recorded selected variant); retain its exact pristine relative path in `identity.executable.original_member` and compare size/header/hash to that member, retaining any mismatch as open |
| Original package/resources | Both identify hashed `identify_tree(original-pristine)` inventories whose complete file records and recomputed digest equal the checkpoint baseline. Generated-copy pre/post inventories remain separate; preserve all raw original content identities |
| Original pre/post | Save complete actual `identify_tree(original-pristine)` before/after return validation; require files and tree digest equal to the baseline and manifest original_pre. These describe authoritative/pristine preservation, separately from writable copy changes |
| Original copy pre/post/retained | Raw `copy-pre.json`, `copy-post.json`, `retained-copy.json`; preserve exact actual bytes/hashes in `identity.copy_pre`, `identity.copy_post`, `identity.retained_copy`. For both lifetimes bind `copy_pre_sha256` to the named pre record; retained runs also bind `retained_copy_sha256` to the named retained snapshot. Native reviewed runs use the same explicit state-record contract |
| Original source/launcher | Save manifest `tool_source` as `collector-source.json` and identify the actual bundled Windows collector; source commit/dirty/diff describes collector tooling, never recovered original source code |
| Original DxWnd/profile | Retain hashed actual `dxwnd-tool.json`, source profile and relocated export; explicit wrapper settings/limits are required |
| Platform/version/GPU/driver/Vulkan/SDL | Actual raw queries and human device/version records; absent observations remain missing, never guessed |
| Events/continuity/derivatives | Preserve actual raw values and hashed media; supplement only from observed annotations with methods/uncertainty; never generate invented markers |
| Review | Set visible/audible/ordinary_input/human_reviewed true only from the named, receipt-bound actual reviewer findings |
For example a Windows native raw receipt `port-fresh-natural-ordinary-continuous-01`
already identifies `identity/build.json` as source/package/resources. Its reviewed
identity retains that **same file/hash**, keeps source commit/dirty/diff from its
contents, and binds executable to manifest `packages.win-x64.executable`. It does
not substitute BUILD-INFO for that raw source or regenerate a package seal.
The reviewed record's minimal projection looks like this (metavariables below
are populated from the actual retained records by the integration agent):
```json
{
"receipt_id": "port-fresh-natural-ordinary-continuous-01-reviewed",
"session_id": "port-fresh-natural-ordinary-continuous-01",
"status": "reviewed",
"identity": {
"source": {"path":"identity/build.json", "sha256":"ACTUAL_SEAL_HASH", "size":0,
"header":"ACTUAL_HEADER", "commit":"ACTUAL_BUILD_COMMIT", "dirty":true,
"diff_sha256":"ACTUAL_BUILD_DIFF"}
},
"review": {"visible":true,"audible":true,"ordinary_input":true,"human_reviewed":true},
"acceptance": {"state":"accepted","remaining":[]}
}
```
This projection is **not a usable receipt or positive finding**: retain all other
required raw fields, replace every metavariable/size with identified actual values,
keep limitations/discrepancies, and include missing identity mappings above.
Clear `missing_evidence` and acceptance remaining only when each corresponding
fact has actually been supplied and reviewed. Otherwise preserve the gap and
`state: open`. The shared validator and strict audit reject incomplete reviewed
records. Do not overwrite raw receipts or label normalized copies as raw captures.
After writing the complete derived receipt, the agent validates/imports with the
existing API (run from repository root; substitute the actual derived directory):
```sh
PYTHONPATH=tools/recon python3 -c 'from pathlib import Path; from fidelity_receipts import read_receipt,validate_receipt,import_receipt; p=Path("LOCAL_DERIVED/receipt.json"); print(validate_receipt(read_receipt(p),p.parent)); print(import_receipt(p,p.parent,Path("dist/fidelity/phase01/results/imported")))'
```
An absent mapping or unobserved human fact is an OPEN result. Never manufacture
source, original, device, media or review identities to make this command pass.
In `results/current.json`, list the explicit current receipt paths as
`{"receipts":["imported/receipt-id/receipt.json"]}`. Preserve historical/superseded
records outside that selection. Conflicting duplicate slots cannot be selected.
In `results/human-review.json`, use `schema_version: 1`, exact selected
`receipt_ids`, a `receipt_sha256` object mapping each ID to its actual receipt hash,
and `checks` mapping every name above to `{ "observed": true, "reviewer":
"actual reviewer", "notes": "specific observation and limitations" }`. Empty or
false findings remain pending. These fields describe witnessed facts; tools never
generate positive human findings.
Run strict audit on the complete local result tree:
`python3 tools/recon/fidelity_acceptance.py audit --checkpoint dist/fidelity/phase01 --results dist/fidelity/phase01/results --require-complete`.
Nonzero means acceptance remains open. `--allow-open` may return zero for structural
inspection while explicitly reporting human_needed and every missing obligation;
it never satisfies EVID-02/EVID-04. Export actual paired selected receipts with the
existing `fidelity_review.py export` command; the prepared viewer starts empty.
## Pending acceptance checklist
- [ ] Original-DxWnd 40 obligations, actual imagery/audio/input and wrapper review.
- [ ] Native Windows 40 obligations, physical input/audio and exact runtime identity.
- [ ] Native Linux 40 obligations, real display/audio and physical input.
- [ ] Actual paired browser playback, seeking, exclusive audio and exposed drift.
- [ ] Both unclassified assumptions, A1/A2 backstops and P1/P2/P3 dispositions.
- [ ] Returned identities and strict audit passed; current/history discrepancies reconciled.
Phase 1 and all EVID requirements remain pending. The roadmap permits independent
source-backed recovery while these access dependencies remain open; it does not
waive them or authorize broader gameplay admission.
+177
View File
@@ -0,0 +1,177 @@
# Local Linux fidelity capture
This joins the single final combined session described in
[windows-session.md](windows-session.md). Prepare locally; no early hands-on
session is requested. Every original/native acceptance obligation remains open
until actual evidence and human review. No gameplay/movement reset is added.
Use the existing sealed Linux package, not a rebuilt or relabeled package.
The 01-05 package is `artifacts/fidelity/01-05-packages/linux-x64`:
source `446930d2a30d6d616c60ac5e59e4169a840bea09`, dirty yes, publish diff
`90cef95669caece53fe2d2c4736cf2ac05ed27f5d25ca03ab572589686bcb73d`.
Its file-list hash is `124cf271e4952f3822eec5c24358447fcffc9e9e1803aded8d96d4d4472dc5a3`.
The collector checks all sealed bytes before launch and collection. Keep output
outside the package and originals, in a fresh session directory.
Select the actual local X11 display and capture rectangle, real Pulse monitor
source and physical input method. Save a local JSON settings object with these
exact fields (values below are examples, not observed devices):
```json
{"display_method":"x11","display":":0","audio_method":"pulse",
"audio_source":"actual-device.monitor","input_method":"physical",
"size":"1280x720","offset":"0,0"}
```
Inspect `pactl list short sources` and `pactl list short sinks` locally. Null/dummy
devices do not qualify. This collector implements X11/Pulse capture with installed
FFmpeg/ffprobe; it records unsupported Wayland/TTY/dependency conditions as failed
preflight. Do not install or select a guessed alternative automatically. Use a
separately identified existing recorder for unsupported display sources and retain
its actual settings, tool identity, raw recording and timing provenance.
```sh
bash scripts/collect-fidelity-linux.sh preflight --package artifacts/fidelity/01-05-packages/linux-x64 --settings /local/linux-settings.json
bash scripts/collect-fidelity-linux.sh run --package artifacts/fidelity/01-05-packages/linux-x64 --settings /local/linux-settings.json --output artifacts/fidelity/linux/unique-launch --session-id unique-launch --case-id fresh-natural-ordinary --scope dialogue-return --seconds 120
bash scripts/collect-fidelity-linux.sh collect --run artifacts/fidelity/linux/unique-launch --import-to artifacts/fidelity/linux-receipts
```
Nonzero run/collect exits preserve failure/abort output; inspect it, and collect
the failed run too. Recorder starts before the normal `--load-save NewGame.tsk
--walk` process and passive observer. This is the existing story entry, not an
implemented main menu. Close the game normally before the selected duration.
Both children have one bounded deadline; interruption ends only owned children.
Logs and metadata have explicit bounds; raw recording is capped at 8 GiB. Retain
the entire lossless FFV1/PCM MKV and tail; a detected frozen interval is an open
inspection flag, not a claim of failure or parity derived from a numeric tolerance.
Collection probes actual streams/duration and hashes logs/media/observer and
package/source/resource identities. The duplicate MKV audio alias preserves exact
bytes for the shared receipt's distinct audio role. No audio normalization,
retiming, crop repair or preview is implicit. If a browser needs a remux/preview,
retain raw media and explicit derivation command/version/hash/time mapping under
the existing shared derivative contract. The local viewer exporter consumes the
imported receipts; actual playback/seeking/audio/crop remain human review gates.
Record manual event annotations as `{"events":[...]}` using the exact fields in
`scenarios.json`: hashed raw artifact name, media and monotonic elapsed seconds,
method and uncertainty. Supply `collect --annotations /local/annotations.json`.
Port simulation ticks remain separate from raw clocks. Observer gate results
do not prove a physical key was pressed. Automated injection is `port_fixture`;
test doubles are permanently synthetic. No collector output grants acceptance.
## Actual 2026-11-13 preflight
The scoped host probe, outside sandbox device restrictions, found a TTY session,
no `DISPLAY` or `WAYLAND_DISPLAY` and no X11 socket. Existing FFmpeg/ffprobe are
available. Pulse exposes only `auto_null` and `auto_null.monitor` (suspended).
No Xvfb or OBS command resolved. A synthetic display or null audio would not
establish the requested normal visible/audible gameplay, so no game/recorder
was launched and no substitute route/media was fabricated.
The exact failed focused receipt is `linux-01-06-focused-preflight-linux`, at
`artifacts/fidelity/linux/01-06-focused-preflight/receipt.json`, imported into
`artifacts/fidelity/linux-receipts/linux-01-06-focused-preflight-linux/`.
`preflight.json` preserves observed OS, tool versions/hashes, Pulse devices and
available GPU/Vulkan diagnostics; missing SDL/active-instance runtime versions
remain explicit. The selected package/resource seal matches the hash above.
Both the failed result and its import validate structurally, with acceptance open.
Before collection, all 539 original files verified unchanged.
Required next physical session: provide an actual display/game capture source
and real audible device/monitor source, verify moving unobstructed content and
audio, then record physical normal controls and full tails. Inspect capture cost,
crop/aspect and actual browser playback/seeking separately. Preserve this failed
preflight as history; new attempts use new session IDs and fresh output roots.
## Full matrix and the final combined agenda
The current typed dependency receipt is
`linux-01-06-matrix-preflight-linux`, at
`artifacts/fidelity/linux/01-06-matrix-preflight/receipt.json`, imported under
`artifacts/fidelity/linux-current-receipts/`. The earlier task-1 receipt is
retained diagnostic history; select the current typed receipt for scenario audit.
`artifacts/fidelity/linux/01-06-matrix.json` enumerates every obligation, exact
procedures/events, failed attempt ID and shared display/audio dependency.
There were no runnable native cells after that common dependency failed. The
collector does not manufacture 40 failed game launches or unrelated scene clips.
In this table **OPEN** means the exact current dependency receipt above plus
the named cell/obligation's actual recording, lifetime evidence and human review.
| Cell | continuous | dialogue-return | bank-left | bank-right | landing-idle |
|---|---|---|---|---|---|
| fresh-natural-edge | OPEN | OPEN | OPEN | OPEN | OPEN |
| fresh-natural-ordinary | OPEN | OPEN | OPEN | OPEN | OPEN |
| fresh-skipped-edge | OPEN | OPEN | OPEN | OPEN | OPEN |
| fresh-skipped-ordinary | OPEN | OPEN | OPEN | OPEN | OPEN |
| retained-natural-edge | OPEN | OPEN | OPEN | OPEN | OPEN |
| retained-natural-ordinary | OPEN | OPEN | OPEN | OPEN | OPEN |
| retained-skipped-edge | OPEN | OPEN | OPEN | OPEN | OPEN |
| retained-skipped-ordinary | OPEN | OPEN | OPEN | OPEN | OPEN |
Follow `scenarios.json` literally. Continuous recording begins before startup or
retained setup and keeps lab → VR04 → lab → outside in one process/clock and raw
video. Use normal supported controls/gadget/RETURN, without warps/grants. Focused
clips have their own declared setup and never substitute for the continuous run.
Natural dialogue reaches its real end; skipped dialogue records the actual skip
key and observed skip/end boundaries. Ordinary play releases movement at return;
edge play records held input through dialogue and RETURN, release/first-neutral,
independent left/right banked jumps, landing and idle. Preserve legitimate bank,
TSK-retained story input order and distinct fresh direct-scene observations.
No blanket angle/pixel/timing/audio tolerance or leveling repair is implied.
For each fresh observation, use a new launch/session ID and separately identified
generated execution copy; verify its existing seal rather than rebuilding it.
Keep the source package immutable. The collector records the selected package
root and sealed pre/post identities; copying/staging is an explicit local step,
not an invented copy claim. The prepared checkpoint's immutable Linux package is
also available for a verified local copy. Never select the original installation.
For retained observations, keep one actual process, copy and clock across visible
prerequisite lab departure to VR04 and return, then the tested interval. Capture
the real generated-copy state while that process remains alive; a later launch
or synthetic snapshot cannot replace the prerequisite. Use a separate terminal
to save the observed state records inside the run directory before finalization.
Annotations may declare `artifact_roles` mapping contained recording paths to
`prerequisite`, `identity_files` mapping `copy_pre`, `retained_copy`, `copy_post`
to actual contained state-record paths, and `continuity` with `lifetime_id`,
`prerequisite_artifact`, `copy_pre_sha256`, and for retained runs
`departure_session_id`, `return_session_id`, `retained_copy_sha256`.
All hashes refer to actual identity records. The selected prerequisite recording
must have a probed duration, and prerequisite events precede the tested interval.
A byte-identical alias of raw media can identify its prerequisite role without
retiming; preserve its exact bytes. The collector never invents these observations.
`clocks.clock_id` identifies the outer capture clock; preserve the passive observer
clock's separate origin and annotate any alignment/uncertainty explicitly.
Export/update the checklist with an unused output filename:
```sh
bash scripts/collect-fidelity-linux.sh matrix --receipt artifacts/fidelity/linux-current-receipts/linux-01-06-matrix-preflight-linux/receipt.json --dependency-run artifacts/fidelity/linux/01-06-matrix-preflight --output artifacts/fidelity/linux/new-matrix.json
```
For interrupted work, pass `--previous /local/prior-matrix.json` and repeat
`--receipt` for new attempts. Old receipts are re-read and hash-checked; reused
or conflicting session/receipt IDs are rejected. Preserve failed/incomplete
history, retry only missing/incomplete obligations, and use fresh IDs/directories.
Do not hand-edit history to imply completed cells. Shared scenario validation
checks chronological required markers, one recording and retained identity;
the final acceptance audit still owns review and applicability selection.
The single final session adds these Linux actions to the Windows/original agenda:
1. Verify all 539 authoritative originals before staging and after collection with
`python3 tools/recon/inventory.py ../Original --verify docs/original-manifest.json`.
2. Select real display/audio and identified installed recorder/probe; perform a
short moving-content, audible-output, crop/aspect and physical-control check.
3. Record all 40 obligations with their real setup/lifetime; retain raw video/audio,
accepted gate/observer logs, manual input descriptions, clocks and uncertainty.
4. Import current applicable receipts and export local paired review. Verify actual
browser playback/seeking/tails at normal speed and exclusive original/port audio;
retain any preview's exact derivation and raw source. Review capture overhead.
5. Recheck source/package/original identities and matrix history, retain remaining
discrepancies/open dependencies, and transfer results locally together once.
The Linux subset is **0/40 accepted**. The full three-side protocol remains
**0/120 accepted**: original-DxWnd/native Windows/physical audible review are open.
+44
View File
@@ -0,0 +1,44 @@
# Phase 01 evidence baseline — preparation, acceptance OPEN
The final acceptance checkpoint is `dist/fidelity/phase01`, freshly assembled from
the existing sealed 01-05 packages plus the final Linux/audit/session materials.
Prepared identities and generated media remain local and ignored. Runtime source:
`446930d2a30d6d616c60ac5e59e4169a840bea09`, dirty true; publish diff:
`90cef95669caece53fe2d2c4736cf2ac05ed27f5d25ca03ab572589686bcb73d`.
Original files remain governed by `docs/original-manifest.json` (539 files).
| Proof category | Current result | Acceptance |
|---|---|---|
| Immutable local tools/protocol/packages | Separate readiness audit | Materials only |
| Actual original-DxWnd | No returned gameplay recordings | OPEN 0/40 |
| Native Windows | Cross-publish/resource identity only | OPEN 0/40 |
| Native Linux physical/audible route | Failed TTY/null-audio preflight | OPEN 0/40 |
| Actual paired browser/audio review | No original/native recording pair | human_needed |
The retained actual diagnostic receipt is
`linux-01-06-matrix-preflight-linux`, from
`artifacts/fidelity/linux-current-receipts/`. It records no selected X11 display,
only `auto_null.monitor`, absent recording and absent observer events. No game was
launched. This is failed native preflight evidence, not native gameplay acceptance.
Historical Wine/component/GPU results keep their original scope and revision.
The strict audit reports every missing case/obligation and rejects synthetic,
misclassified, stale, wrong-resource, historical/conflicting or unreviewed evidence.
Its metadata unit fixtures exercise both complete coverage and rejection behavior;
their invented media/observations are never imported as runtime proof.
## Remaining discrepancies and judgments
The blocking gaps are actual original-DxWnd and native Windows execution, Linux
display/audio/physical-input access, complete 120-obligation captures, returned
media identity and real paired review. The NewGame.tsk story entry is not the
original main menu. DxWnd wrapper/timing/render behavior must remain separately
identified. No universal timing/pixel/audio tolerance is asserted.
A1 (original moving imagery/intelligible audio) and A2 (actual browser playback,
seek and exclusive audio) remain **human_needed**. EVID-02/EVID-04 unclassified
assumptions remain unresolved/flagged; P1 preservation, P2 honest comparison and
P3 history/native transparency require explicit final judgment. Follow the single
[combined session checklist](checkpoint-session.md). All EVID requirements and
Phase 1 acceptance remain OPEN under the roadmap source-backed continuation
exception. No movement, rendering, gameplay or collision admission changed.
+210
View File
@@ -0,0 +1,210 @@
# One combined local Windows fidelity session
This is the prepared agenda for plan 01-07, not a request to capture now.
`READY.json` means immutable materials are prepared. It never means original,
native Windows, browser, audio or scenario acceptance passed. Linux PowerShell
selftests, cross-publish, Wine and synthetic media cannot fill those slots.
Keep every package, original copy, raw recording and result on local storage.
The checkpoint contains `manifest.json`, `READY.json`, both identified
`port/{linux-x64,win-x64}` packages, `original-pristine/`, writable
`original-runs/`, `protocol/`, offline `review/`, collectors, these instructions,
package-free selftests and `results/`. No SDK or Python is needed on Windows.
The manifest records actual package BUILD-INFO and sealed source identities;
the later bundle revision does not replace the runtime's source identity.
Do not alter immutable materials to make a preflight pass. Mutable results and
generated run copies stay outside that immutable hash set.
## Ordered session agenda
1. **Select local dependencies and capture provenance.** Transfer the entire
prepared checkpoint to a fresh local directory, preferably a short path with
sufficient recording space. Select the actual Windows PC, DxWnd executable,
original exported DxWnd profile, recorder, browser and any media-probe/
derivation executables already installed locally. No download, installer
redistribution, elevation or guessed DxWnd switches are part of this bundle.
Copy `protocol/settings-template.json` into `results/session-settings.json`
and fill observed values. Record each tool's actual local source, version,
SHA-256, settings/export and limitations, Windows build, GPU/driver, Vulkan
and SDL versions as actually available; missing identities remain pending.
The collector hashes selected external tool executables without copying them
into returned results. Retain settings/profile exports, not installers.
Initial recorder recommendation: **offline OBS Display Capture**, with the
actual monitor, capture source, crop/aspect, resolution/frame rate, encoder,
audio device/mix and MKV container recorded. Record notification/desktop
exposure and wrapper timing/rendering limitations in the local notes.
2. **Run immutable preflight and package-free selftests.** From the checkpoint
directory run the following exact commands. Require exit zero, at least eight
executed checks and zero failures; preserve the output in local session notes.
A missing PowerShell or dependency is a failure to record, not a silent pass.
```powershell
powershell.exe -NoProfile -File .\scripts\collect-fidelity-windows.ps1 -Action Preflight
powershell.exe -NoProfile -File .\tests\fidelity-windows.Tests.ps1
```
PowerShell 5.1 is the Windows target; a `pwsh` run on Linux exercises tooling
only. Executables are launched directly with quoted arguments, never from
receipt-supplied commands. Keep script execution subject to the PC's existing
policy; record a policy failure rather than changing security policy here.
3. **Perform separate short original and native-port visual/audio preflights.**
Use new diagnostic IDs for each. Inspect the selected DxWnd distribution's
own local help/config. Import the user's retained exported profile and change
only executable/working-directory paths to the generated copy printed by the
collector; export that relocated profile to the result's artifacts directory.
Do not force timer, renderer or compatibility settings or guess profile syntax.
If automation is unsupported, use the transparent DxWnd GUI launch. Retain
original and relocated exports and describe exact changes. The collector opens
DxWnd with no assumed switches and does not infer the original child's exit.
Never select the authoritative installation or `original-pristine/` as target.
Play each raw preflight: require **visible moving game content, intelligible
game audio, correct crop and aspect**, rather than merely detected ffprobe
streams. Record failures before proceeding. Keep diagnostic runs separate
from required cases. Native port launch uses the existing NewGame.tsk story
entry; absence of a reconstructed menu remains an explicit comparison gap.
4. **Record all matrix cells and obligations.** Use `protocol/agenda.json` as
the checklist: 8 cells × 5 obligations × 2 Windows sides = **80 Windows
obligations**. The separate Linux side contributes 40; all **120** remain
subject to actual receipt validation and human review. The table below and
`protocol/scenarios.json` specify the matrix, actual route, required events
and end conditions. Each fresh run has a new launch ID and original copy.
For retained runs, record prerequisite lab departure to VR04 and return in
the same process/clock before the tested interval; do not relaunch or reset
state. Capture the retained generated-copy identity during that lifetime
with `-Action Retained`, preserving the original pre-copy identity. Start the
recorder before interaction, retain the entire raw MKV and audible tail,
then finalize the specific scope after the process ends. Follow each cell's
natural/skip and ordinary/held-input procedure through its focused setup.
5. **Review paired browser video and exclusive audio.** Open `review/index.html`
using the selected local browser. Return results are imported into a fresh
local review export for pairing; the initially empty viewer does not invent
captures. Preserve actual speed and separate raw clocks, annotate offsets,
playback drift, crop and uncertainty. Listen to only one source at a time.
Require actual browser playback/seeking/audio checks for every preview codec.
A codec name, probe success or file extension is insufficient. Retain raw MKV
even if the browser cannot decode it. If a preview or extracted WAV is needed,
use a selected existing local tool and retain exact executable/version/hash,
inert argv, UTC derivation time, raw/output identities, timestamp mapping and
crop/aspect changes. Never silently retime or discard the source. Record
unsupported codecs or inaudible/missing content as open failures.
6. **Collect, postflight and audit.** Finish each run with actual annotations,
recording files, observer logs, settings, DxWnd exports and limitations.
Include missed, skipped, aborted, crashed and incomplete runs. A process exit
or `captured` means collection only. Original-DxWnd provenance is separate
from native port receipts. Preserve generated originals and their post-run
changes, `copy-pre.json`, `retained-copy.json` where applicable and
`copy-post.json`; never restore them over the authoritative originals.
Re-run immutable preflight after collection and preserve output. Actual
review verdicts and shared schema/matrix validation remain separate gates.
7. **Return once using local transfer.** Copy the complete checkpoint (including
raw recordings, results and original-runs) by USB/local filesystem or existing
local share to a new return directory. Do not upload assets/packages/media.
Recheck manifest/READY SHA-256 and all immutable entries, then rehash all
receipt-linked artifacts on return using the shared Python receipt validator.
Preserve a source-side file/hash inventory for the mutable result and
original-runs trees and compare it with the returned copy before importing.
A mismatch or missing file is an explicit transfer failure. Do not overwrite
the source copy, canonical originals, historical packages or an earlier return.
## Matrix and required procedures
| Case ID | Lifetime | Carl dialogue | Physical input policy |
|---|---|---|---|
| fresh-natural-edge | Independent fresh launch | Natural completion | Held through dialogue/RETURN |
| fresh-natural-ordinary | Independent fresh launch | Natural completion | Ordinary play/release |
| fresh-skipped-edge | Independent fresh launch | Actual supported skip | Held through dialogue/RETURN |
| fresh-skipped-ordinary | Independent fresh launch | Actual supported skip | Ordinary play/release |
| retained-natural-edge | Observed departure/return, same lifetime | Natural completion | Held through dialogue/RETURN |
| retained-natural-ordinary | Observed departure/return, same lifetime | Natural completion | Ordinary play/release |
| retained-skipped-edge | Observed departure/return, same lifetime | Actual supported skip | Held through dialogue/RETURN |
| retained-skipped-ordinary | Observed departure/return, same lifetime | Actual supported skip | Ordinary play/release |
Every cell requires separate `continuous`, `dialogue-return`, `bank-left`,
`bank-right` and `landing-idle` obligations on both original-DxWnd and native
Windows port. Continuous means ordinary **lab → VR04 → lab → outside** in one
uninterrupted recording and process, including Carl dialogue, first neutral
input, both banked jumps/landings, gadget use, RETURN cleanup and outside arrival.
Focused clips retain their actual setup/prerequisite recording. A direct scene,
debug warp or injected fixture cannot replace the route or retained prerequisite.
Record keys, skip action and held/released boundaries as actually performed.
Preserve legitimate landing bank and the implemented TSK lifetime ordering;
do not insert a leveling reset or tune movement for the recording.
## Collector commands and failure results
Replace paths and IDs with actual selections. Commands are examples for the
later combined session; use a fresh unique ID for each independent launch.
Start external recording when prompted and keep the collector alive for the
entire retained setup and tested interval. The recorder/browser are identified,
not automatically driven. The `.cmd` wrapper is an optional equivalent entry.
```powershell
powershell.exe -NoProfile -File .\scripts\collect-fidelity-windows.ps1 -Action Run -Mode port -SessionId port-fresh-natural-ordinary-continuous-01 -CaseId fresh-natural-ordinary -Scope continuous -RecorderPath 'C:\Tools\OBS\bin\64bit\obs64.exe' -BrowserPath 'C:\Tools\Browser\browser.exe' -SettingsPath '.\results\session-settings.json'
powershell.exe -NoProfile -File .\scripts\collect-fidelity-windows.ps1 -Action Run -Mode original -SessionId original-retained-natural-edge-bank-left-01 -CaseId retained-natural-edge -Scope bank-left -DxWndPath 'C:\Tools\DxWnd\dxwnd.exe' -ProfilePath 'C:\Local\exported.dxw' -RecorderPath 'C:\Tools\OBS\bin\64bit\obs64.exe' -BrowserPath 'C:\Tools\Browser\browser.exe' -SettingsPath '.\results\session-settings.json'
powershell.exe -NoProfile -File .\scripts\collect-fidelity-windows.ps1 -Action Retained -SessionId original-retained-natural-edge-bank-left-01
powershell.exe -NoProfile -File .\scripts\collect-fidelity-windows.ps1 -Action Finish -SessionId port-fresh-natural-ordinary-continuous-01 -AnnotationPath '.\results\port-notes.json' -ArtifactsDirectory 'D:\LocalCaptures\port-run-01'
powershell.exe -NoProfile -File .\scripts\collect-fidelity-windows.ps1 -Action Skip -Mode original -SessionId original-missed-01 -CaseId fresh-skipped-edge -Scope bank-left -Reason 'Actual reason this obligation could not run'
```
`Skip`/`Abort` create a new terminal result without requiring recorder/browser
selection. An interrupted active run retains its initial `incomplete.json`;
when safe, collect its artifacts with `Finish -Outcome aborted -Reason '...'`
instead of pretending a separate aborted launch describes its lifetime.
When only `incomplete.json` survived, this command preserves its exact bytes as
a diagnostic artifact and permits only `aborted`. End clocks remain absent;
initial placeholder end values are discarded. Keep recovered media and source
notes, with an empty `events` array because no complete launch interval was
observed. The receipt remains open and importable; recovery does not establish
missing executable identity, process completion, or a captured/reviewed run.
Failed starts preserve `run.json`, `failure.json` and available logs. To collect
failed/skipped/aborted media use `Finish -Outcome failed|skipped|aborted` matching
the prior status, a reason and annotation/artifact directories (empty arrays are
allowed for these outcomes). Never promote a failed or terminal run to captured;
use a new independent session for a retry. Existing evidence is write-once.
## Annotation field contract
Copy `protocol/annotation-template.json` to a mutable result note and fill it
with actual values. Empty templates cannot finalize capture. All paths are
relative, case-unique and contained below `ArtifactsDirectory`; no commands are
read from annotations. Every captured run retains a raw `.mkv` video and actual
audio evidence. If raw audio is embedded, retain a separately named byte-identical
MKV copy with role `audio`, or a proven extracted WAV with derivation provenance.
This preserves unique artifact paths while binding the actual audio bytes.
- `artifacts`: entries `{path, role, duration_seconds}`; roles include `video`,
`audio`, `input_events`, `prerequisite`, `diagnostic`. Preserve raw and preview
as separate entries. Original prerequisite recordings/copy-state records and
port `observer/events.jsonl`, summary, stdout/stderr must be included as
appropriate; do not rename synthetic fixtures as native evidence.
- `events`: `{name, artifact, media_seconds, elapsed_seconds, method,
uncertainty_seconds}` using the exact required names/order in scenarios.json.
Original methods are `manual` or `procedural`; markers describe visible input
and event intervals, never invented original simulation ticks. Port events
map observer data to actual media clocks; `simulation_tick` remains separate.
Preserve observer `launch_id`, `clock_id`, requested/accepted input distinctions,
sequence and possible truncation/overhead. Never reset elapsed clocks at scenes.
All times are finite, nonnegative and within actual recording/run duration.
- `derivatives`: `{path, source, tool, version, argv, created_utc,
timestamp_mapping, crop_aspect, browser_playback_verified}`. The collector
stores argv as inert provenance; it does not execute it. Select true browser
playback only after observed playback. Hash tool binaries and retain source
identity/settings in local session notes, including whether crop/time changed.
- `continuity`: `lifetime_id` equals session ID, `prerequisite_artifact` names a
hashed artifact, `copy_pre_sha256` binds the actual copy-state record. Retained
additionally needs `departure_session_id` and `return_session_id` equal to that
same session ID and `retained_copy_sha256` identifying the retained snapshot.
`prerequisite_departure` and `prerequisite_return` markers precede the tested
interval on the prerequisite artifact. Include these state records as hashed
identities/artifacts, never made-up placeholders. The port's actual package/
startup-state record must be identified separately; missing continuity remains
open rather than treating a second fresh launch as retained.
- `diagnostic`: true for observation overhead, preflight, fixtures or other
diagnostic limitations; `limitations`: actual missing tools, crop/audio/render/
timer/wrapper differences, incomplete transitions, uncertain markers and review
failures. A successful collector does not clear them or acceptance automatically.
`Finish` prefixes local media/event/derivative references with `media/` and hashes
copied bytes. It never accepts an annotation-supplied acceptance verdict. The
shared receipt validator and later full matrix/human review decide applicability.
No universal timing, pixel, angle or audio tolerance is asserted by this agenda.
+133
View File
@@ -1,5 +1,138 @@
# Progress — 2026-11-07
## Bundled checker cache fix — 2026-11-14
A user readiness check created Python bytecode inside the sealed checkpoint and
then rejected it as unexpected immutable material. Regression23ee1c2 reproduces
this; fix2fe8b40 disables bytecode writes before local imports in all five bundled
Python command entry points. All26 checkpoint tests pass, including a real copied
CLI test with environment overrides ignored. The exact bundled readiness command
passes twice without creating pyc files. A fresh11,001-member checkpoint replaces
phase01; the old tree and its cache/results are retained in local history, and
existing results/generated execution copies were copied into the new mutable roots.
The broader attempt ran185 tests but failed observer class setup after a90-second
.NET build timeout. A separate bounded local build passed; the seven observer
checks then passed on their own retry. Thus all192 fidelity checks are covered
across the two runs; the initial full attempt remains recorded as failed.
No runtime implementation changed. Actual original/native acceptance remains
0/120 OPEN and all ten human UAT items remain pending.
## Phase 1 verification — human session pending
Final owner-validated verification is `human_needed`:29/42 truths verified and13
uncertain pending actual observations. Ten named checks are saved in
`.planning/phases/01-reproducible-fidelity-baseline/01-UAT.md`. Autonomous materials,
review fixes, security and automation coverage are complete. Actual acceptance
remains0/120 OPEN; all EVID requirements stay Pending and Phase2 is unadvanced.
The combined session guide is `docs/evidence/checkpoint-session.md`; the local
checkpoint is `dist/fidelity/phase01`. Resume human verification with
`$gsd-verify-work 1`. No new build/test or gameplay claim accompanies this report.
## Final phase 1 review closure
All five review findings are independently verified fixed. The final copy-state
refinement is02d182f; all191 fidelity regressions pass in43.355s, with29 acceptance,
26 scenario and23 capture checks in the affected suites. Earlier review fixes
also pass27 Node and18 Linux-hosted PowerShell checks;539 originals stay unchanged.
The recovered full local suite passed782.049626s before these tooling-only review
fixes:556 Python,27 Node,23 observer,2 HUD,51 managed entry points and36 GPU render
receipts, zero Vulkan validation errors. The full GPU suite was not repeated for
these Python/collector fixes. Independent security audit closes22/22 planned
threats. Current fresh checkpoint is `dist/fidelity/phase01` (11,001 immutable
entries); exact current manifest/READY identities are recorded locally in
`artifacts/fidelity/verification/01-07-final-checkpoint.json`. Earlier bundle
history is preserved locally. All120 actual original/native acceptance obligations
and ten named human findings remainOPEN. Final phase verification is pending.
## Phase 1 final preparation — acceptance human_needed
The fresh local `dist/fidelity/phase01` checkpoint passes readiness over11,000
immutable files. Strict audit exits1:0/120 original-DxWnd/native Linux/native
Windows obligations accepted, all ten human findings pending. The actual failed
`linux-01-06-matrix-preflight-linux` receipt is imported with a diagnostic viewer;
no gameplay was launched. Runtime source remains446930d dirty, diff90cef956;
exact package/tool identities are local in
`artifacts/fidelity/verification/01-07-final-checkpoint.json`.
The consolidated runner now rejects zero fidelity Python/viewer/observer counts.
The complete local suite passed in 782.05s (runner clock: 783s): 556 Python
(180 fidelity), 27 Node, 23 managed observer, 2 separate HUD Python tests and
51 managed test entry points, followed by the main build. The log records
36 GPU rendered receipts, 27 saved readbacks and 17 material/readback assertions,
all with zero Vulkan validation errors; SDL dummy-audio checks pass and all
539 originals remain unchanged. No physical input, audible or window-session
acceptance is inferred. Receipt: `artifacts/fidelity/01-07-full-suite.json`;
full output: `artifacts/fidelity/01-07-full-suite.log`.
The first74.65s attempt passed Python but exposed the new Node reporter/count
guard mismatch; explicit TAP fixes it and the complete rerun is retained.
See [baseline](evidence/phase01-baseline.md) and the single
[combined session](evidence/checkpoint-session.md). All EVID requirements and
Phase1 acceptance remain OPEN; source-backed continuation follows the roadmap
exception. Movement/gameplay/admission and historical runtime evidence are unchanged.
## Phase 1 plan 01-06 — reviewed completion
Linux capture tooling and full40-obligation matrix are complete. Primary repeats
23 capture tests; executor records156 broader fidelity checks and539 unchanged
originals. Actual host preflight has no display and only auto_null audio, saved as
`linux-01-06-matrix-preflight-linux`. No game was launched. Matrix/review artifacts
are under `artifacts/fidelity/linux/`. Phase1 is6/7 plans; all120 runtime acceptance
obligations stayOPEN. Final readiness and combined-session audit are next.
## Phase 1 plan 01-05 — reviewed completion
Offline Windows checkpoint preparation is complete:10,983 identified immutable
files, both full-bundle preflights pass,24 checkpoint Python tests and17 real
Linux-hosted PowerShell checks pass. Primary repeats both targeted suites. The
executor also records133 broader fidelity regressions and539 unchanged originals.
The copied Linux apphost retains executable permissions and runs --help. Generated
bundle: `artifacts/fidelity/01-05-session-checkpoint`; exact identities are in
`artifacts/fidelity/verification/01-05-complete-bundle.json` and the01-05SUMMARY.
Phase1 has5/7 plans complete; Linux capture preparation is next. Actual runtime
acceptance remains0/120 OPEN. No Windows gameplay or original comparison claimed.
## Local quota guard — 2026-11-13
Installed Linux quota watcher and five project hooks; real local account quota
read succeeds, watcher runs, and targeted policy/recovery tests pass. Hook trust
remains a user `/hooks` action. At20% remaining new workers are denied; at15%
remaining recovery is saved and registered active turns receive a cooperative
GSD pause request. See [setup and limits](codex-quota-guard.md). Phase01-05 task2
partial edits remain untouched; no gameplay or acceptance status changed.
## Phase 1 wave 2 — review, ledger and passive observation
Full authorized wave2 `scripts/test.sh` exits0:462 Python+2 HUD checks,
all existing managed projects and36 GPU/render checks pass with zero Vulkan
validation errors (GTX1070); SDL stream/lifecycle checks and539 original hashes
pass. The initial sandbox run retained8 denied-loopback errors; no tests were
skipped, and the authorized rerun passed. Viewer27 named Node checks and the
observer23 managed checks retain their separate passing receipts. Logs are
local under `artifacts/fidelity/wave2-test*.log`.
Plans01-02/03/04 are implemented: paired actual-speed local playback with exclusive
audio/optional overlays;25 capabilities covering33 requirements and33 checkpoint
rows; optional bounded input/control/continuation observations. Observer checks:
23 managed,7 actual subprocesses, protected Movement28/Director23/Checkpoint4/
BodyOwnership3. Private-Xvfb native SDL/Vulkan on/off has4 identical readbacks
and zero validation errors; exact source-diff/binary identities and limits are in
`../.planning/phases/01-reproducible-fidelity-baseline/01-04-SUMMARY.md`.
Linux self-contained publish used an isolated artifact directory. All539 original
hashes match. This is bounded tooling/fixture evidence, not physical input/audio,
whole-original, full-route or native Windows acceptance; actual obligations stay
OPEN0/120. Next: Windows checkpoint bundle (plan01-05).
## Phase 1 resumed — capability ledger complete
User resumed from the usage pause. Plan01-03 is complete:25 capabilities cover
all33 requirements and33 checkpoint rows across6 groups. Primary repeats31
ledger tests and103 combined fidelity tests;539 original hashes match. Earlier
viewer27 Node checks and synthetic Chromium smoke remain their bounded evidence.
Full details: `../.planning/phases/01-reproducible-fidelity-baseline/01-03-SUMMARY.md`.
Actual original-DxWnd/native Linux/native Windows acceptance remains OPEN0/120.
Next: plan01-04 passive port observer; no new gameplay behavior or original/native
comparison was established by the ledger work.
## Phase 1 wave 1 — preserved sessions and scenarios
Full wave1 `scripts/test.sh` exits0:403 Python checks plus2 HUD checks,
+106
View File
@@ -1,5 +1,111 @@
# Tasks
## Bundled checker cache fix — 2026-11-14
A user readiness check created Python bytecode inside the sealed checkpoint and
then rejected it as unexpected immutable material. Regression23ee1c2 reproduces
this; fix2fe8b40 disables bytecode writes before local imports in all five bundled
Python command entry points. All26 checkpoint tests pass, including a real copied
CLI test with environment overrides ignored. The exact bundled readiness command
passes twice without creating pyc files. A fresh11,001-member checkpoint replaces
phase01; the old tree and its cache/results are retained in local history, and
existing results/generated execution copies were copied into the new mutable roots.
The broader attempt ran185 tests but failed observer class setup after a90-second
.NET build timeout. A separate bounded local build passed; the seven observer
checks then passed on their own retry. Thus all192 fidelity checks are covered
across the two runs; the initial full attempt remains recorded as failed.
No runtime implementation changed. Actual original/native acceptance remains
0/120 OPEN and all ten human UAT items remain pending.
## Phase 1 verification — human session pending
Final owner-validated verification is `human_needed`:29/42 truths verified and13
uncertain pending actual observations. Ten named checks are saved in
`.planning/phases/01-reproducible-fidelity-baseline/01-UAT.md`. Autonomous materials,
review fixes, security and automation coverage are complete. Actual acceptance
remains0/120 OPEN; all EVID requirements stay Pending and Phase2 is unadvanced.
The combined session guide is `docs/evidence/checkpoint-session.md`; the local
checkpoint is `dist/fidelity/phase01`. Resume human verification with
`$gsd-verify-work 1`. No new build/test or gameplay claim accompanies this report.
## Final phase 1 review closure
All five review findings are independently verified fixed. The final copy-state
refinement is02d182f; all191 fidelity regressions pass in43.355s, with29 acceptance,
26 scenario and23 capture checks in the affected suites. Earlier review fixes
also pass27 Node and18 Linux-hosted PowerShell checks;539 originals stay unchanged.
The recovered full local suite passed782.049626s before these tooling-only review
fixes:556 Python,27 Node,23 observer,2 HUD,51 managed entry points and36 GPU render
receipts, zero Vulkan validation errors. The full GPU suite was not repeated for
these Python/collector fixes. Independent security audit closes22/22 planned
threats. Current fresh checkpoint is `dist/fidelity/phase01` (11,001 immutable
entries); exact current manifest/READY identities are recorded locally in
`artifacts/fidelity/verification/01-07-final-checkpoint.json`. Earlier bundle
history is preserved locally. All120 actual original/native acceptance obligations
and ten named human findings remainOPEN. Final phase verification is pending.
## Phase 1 final preparation — human session pending
- [x] Strict ready/audit tools:23 acceptance checks and24 checkpoint checks pass.
- [x] Fresh11,000-file offline bundle and actual failed Linux diagnostic import.
- [x] Strict audit rejects acceptance:0/120 obligations; all named human findings pending.
- [x] Integrate positive-count fidelity Python/Node/managed observer checks into runner.
- [x] Complete local suite: exit 0 in 782.05s; 556 Python (180 fidelity),
27 Node, 23 observer, 2 separate HUD Python tests, 51 managed test entry points,
main build, 36 GPU rendered receipts, 17 material/readback assertions,
SDL dummy-audio checks and 539 unchanged originals. No window-session claim.
- [ ] Actual original-DxWnd40/native Windows40/native Linux40 capture obligations.
- [ ] Single combined physical/audible/browser review, A1/A2, both unclassified
assumptions and P1/P2/P3 judgments; post-return agent-owned reconciliation.
- [ ] Phase1/EVID-02/EVID-04 acceptance; retain all EVID requirements Pending.
Full-suite receipt: `artifacts/fidelity/01-07-full-suite.json`; final local bundle:
`dist/fidelity/phase01`. See [complete checklist](evidence/checkpoint-session.md).
The roadmap's independent source-backed recovery exception does not waive these
acceptance dependencies or broaden gameplay admission.
## Phase 1 plan 01-06 — reviewed completion
- [x] Linux collector and23 targeted checks, full40-obligation open matrix.
- [x] Record actual no-display/null-audio host dependency; retain failed receipt.
- [ ]01-07 final readiness/audit/integration and combined human session.
## Phase 1 plan 01-05 — reviewed completion
- [x] Complete offline Windows/DxWnd collection materials and synthetic selftests.
- [x] Verify both10,983-file bundle preflights,24 Python/17 PowerShell checks.
- [ ]01-06 Linux capture preparation, then01-07 combined-session readiness/audit.
- [ ]Actual original/native acceptance0/120 OPEN.
## Quota-aware GSD continuation — 2026-11-13
- [x] Install/test local60-second quota watcher,20% dispatch gate,15% pause request.
- [ ] User review/trust the five project quota hooks via `/hooks`.
- [ ] Resume `$gsd-resume-work` when desired; retain01-05 task2 partial edits.
## Phase 1 execution — wave 2
- [x]01-02 paired local review:21 Python/27 Node checks and real Chromium
synthetic-media smoke; actual audible original/native review stays open.
- [x]01-03 full ledger:25 capabilities/33 requirements/33 checkpoint rows;
31 ledger tests and103 combined fidelity Python tests pass.
- [x]01-04 passive observer:23 managed/7 process tests and protected suites;
native private-Xvfb on/off4 readbacks identical, zero validation errors.
- [ ]01-05 prepare complete Windows/DxWnd local checkpoint bundle.
- [ ]01-06 native Linux captures;01-07 combined hands-on session and strict audit.
- [ ]Actual original/native runtime acceptance OPEN0/120.
## Phase 1 resumed — capability ledger complete
User resumed from the usage pause. Plan01-03 is complete:25 capabilities cover
all33 requirements and33 checkpoint rows across6 groups. Primary repeats31
ledger tests and103 combined fidelity tests;539 original hashes match. Earlier
viewer27 Node checks and synthetic Chromium smoke remain their bounded evidence.
Full details: `../.planning/phases/01-reproducible-fidelity-baseline/01-03-SUMMARY.md`.
Actual original-DxWnd/native Linux/native Windows acceptance remains OPEN0/120.
Next: plan01-04 passive port observer; no new gameplay behavior or original/native
comparison was established by the ledger work.
## Phase 1 execution — wave 1
- [x] Plan01-01: preserved-session stage/identify/import/validate and required
+5
View File
@@ -0,0 +1,5 @@
#!/usr/bin/env bash
# No build, download, device fallback or acceptance promotion.
set -euo pipefail
task_root="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)"
exec python3 "$task_root/tools/recon/fidelity_capture.py" "$@"
+5
View File
@@ -0,0 +1,5 @@
@echo off
setlocal
rem Argument selection happens in PowerShell; never run commands from receipts.
powershell.exe -NoLogo -NoProfile -File "%~dp0collect-fidelity-windows.ps1" %*
exit /b %ERRORLEVEL%
+445
View File
@@ -0,0 +1,445 @@
# Windows PowerShell 5.1 compatible. No SDK/Python, elevation, downloads or eval.
[CmdletBinding()]
param(
[ValidateSet('Preflight','Run','Finish','Skip','Abort','Retained')][string]$Action = 'Preflight',
[ValidateSet('port','original')][string]$Mode = 'port',
[string]$Bundle = (Split-Path -Parent $PSScriptRoot),
[string]$SessionId, [string]$CaseId = 'fresh-natural-ordinary',
[ValidateSet('continuous','dialogue-return','bank-left','bank-right','landing-idle')][string]$Scope = 'continuous',
[string]$DxWndPath, [string]$ProfilePath, [string]$RecorderPath,
[string]$BrowserPath, [string]$SettingsPath, [string]$AnnotationPath,
[string]$ArtifactsDirectory, [string]$Reason,
[ValidateSet('captured','failed','skipped','aborted')][string]$Outcome = 'captured',
[ValidateRange(1,14400)][int]$TimeoutSeconds = 7200,
[switch]$LibraryOnly
)
Set-StrictMode -Version 2
$ErrorActionPreference = 'Stop'
$script:CollectorSource = $PSCommandPath
function Test-FidelityId([string]$Value) {
if ($Value -cnotmatch '^[A-Za-z0-9][A-Za-z0-9_.-]{0,95}$' -or
$Value -match '^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(\.|$)') { throw 'Invalid stable ID' }
return $Value
}
function Get-FidelityPath([string]$Root, [string]$Relative) {
if (-not $Relative -or $Relative.Length -gt 4096 -or $Relative -match '[\\:<>"|?*\x00-\x1f]' -or
$Relative.StartsWith('/') -or $Relative -match '(^|/)(\.{1,2}|)(/|$)') { throw "Unsafe relative path: $Relative" }
foreach ($part in $Relative.Split('/')) {
if ($part.EndsWith(' ') -or $part.EndsWith('.') -or
$part -match '^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(\.|$)') { throw 'Unsafe Windows alias' }
}
$base = [IO.Path]::GetFullPath($Root).TrimEnd([IO.Path]::DirectorySeparatorChar)
$path = [IO.Path]::GetFullPath((Join-Path $base $Relative))
if (-not $path.StartsWith($base + [IO.Path]::DirectorySeparatorChar, [StringComparison]::OrdinalIgnoreCase)) {
throw 'Path escapes checkpoint'
}
$cursor = $path
while ($cursor) {
if (Test-Path -LiteralPath $cursor) {
if (((Get-Item -LiteralPath $cursor -Force).Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0) {
throw "Reparse/symlink path: $cursor"
}
}
$parent = [IO.Path]::GetDirectoryName($cursor)
if ($parent -eq $cursor) { break }
$cursor = $parent
}
return $path
}
function Get-FidelityIdentity([string]$Path) {
$item = Get-Item -LiteralPath $Path -Force
if ($item.PSIsContainer -or ($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0 -or
$item.Length -gt 8589934592) { throw "Not a bounded regular file: $Path" }
$stream = [IO.File]::OpenRead($item.FullName)
$sha = [Security.Cryptography.SHA256]::Create()
try {
$digest = [BitConverter]::ToString($sha.ComputeHash($stream)).Replace('-','').ToLowerInvariant()
return @{size=[long]$item.Length; sha256=$digest}
} finally { $stream.Dispose(); $sha.Dispose() }
}
function Read-FidelityJson([string]$Path) {
if ((Get-Item -LiteralPath $Path).Length -gt 4194304) { throw 'JSON exceeds 4 MiB' }
return [IO.File]::ReadAllText($Path, [Text.Encoding]::UTF8) | ConvertFrom-Json
}
function Write-FidelityJson([string]$Path, $Value) {
$text = (ConvertTo-Json -InputObject $Value -Depth 40) + "`n"
$bytes = (New-Object Text.UTF8Encoding($false)).GetBytes($text)
if ($bytes.Length -gt 4194304) { throw 'JSON exceeds 4 MiB' }
$temporary = $Path + '.incomplete-' + [guid]::NewGuid().ToString('N')
$stream = [IO.File]::Open($temporary, [IO.FileMode]::CreateNew)
try { $stream.Write($bytes,0,$bytes.Length); $stream.Flush() } finally { $stream.Dispose() }
[IO.File]::Move($temporary,$Path)
}
function Get-FidelityTree([string]$Root) {
$base = [IO.Path]::GetFullPath($Root).TrimEnd([IO.Path]::DirectorySeparatorChar)
$seen = @{}
$files = New-Object 'System.Collections.Generic.List[object]'
# Enumerate directories ourselves so reparse points are checked before descent.
$queue = New-Object 'System.Collections.Generic.Queue[string]'
$queue.Enqueue($base)
$count = 0
while ($queue.Count -gt 0) {
foreach ($item in Get-ChildItem -LiteralPath $queue.Dequeue() -Force) {
$count++
if ($count -gt 100000) { throw 'Tree exceeds 100000 entries' }
$name = $item.FullName.Substring($base.Length+1).Replace('\','/')
$null = Get-FidelityPath $base $name
if ($seen.ContainsKey($name)) { throw 'Case-alias in tree' }; $seen[$name] = $true
if ($item.PSIsContainer) { $queue.Enqueue($item.FullName) }
else { $identity = Get-FidelityIdentity $item.FullName; $identity.path = $name; $files.Add($identity) }
}
}
if ($files.Count -eq 0) { throw 'Empty tree' }
return @($files | Sort-Object path -CaseSensitive)
}
function Test-FidelityBundle([string]$Root) {
$ready = Read-FidelityJson (Get-FidelityPath $Root 'READY.json')
if ($ready.schema_version -ne 1 -or $ready.status -ne 'prepared') { throw 'Checkpoint is not READY' }
$id = Get-FidelityIdentity (Get-FidelityPath $Root 'manifest.json')
if ($id.sha256 -ne $ready.manifest.sha256 -or $id.size -ne $ready.manifest.size) { throw 'Manifest tampered' }
$manifest = Read-FidelityJson (Join-Path $Root 'manifest.json')
if ($manifest.schema_version -ne 1 -or $manifest.mutable_roots.Count -ne 2 -or
$manifest.mutable_roots[0] -ne 'results' -or $manifest.mutable_roots[1] -ne 'original-runs') {
throw 'Unsupported checkpoint manifest'
}
$seen = @{}
foreach ($file in $manifest.files) {
if ($seen.ContainsKey($file.path)) { throw 'Duplicate/case-aliased manifest file' }
$seen[$file.path] = $true
$actual = Get-FidelityIdentity (Get-FidelityPath $Root $file.path)
if ($actual.sha256 -ne $file.sha256 -or $actual.size -ne $file.size) { throw "Tampered/missing material: $($file.path)" }
}
foreach ($file in Get-FidelityTree $Root) {
if ($file.path.Split('/')[0] -notin @('results','original-runs') -and
$file.path -notin @('manifest.json','READY.json') -and -not $seen.ContainsKey($file.path)) {
throw "Unexpected immutable material: $($file.path)"
}
}
return $manifest
}
function ConvertTo-FidelityArgument([string]$Value) {
# Windows CommandLineToArgvW/CRT quoting. No cmd.exe, shell or expression eval.
if ($Value -match '[\x00\r\n]') { throw 'Control character in argument' }
$escaped = [regex]::Replace($Value, '(\\*)"', '$1$1\"')
$escaped = [regex]::Replace($escaped, '(\\+)$', '$1$1')
return '"' + $escaped + '"'
}
function Invoke-FidelityProcess([string]$Executable, [string[]]$Arguments,
[string]$WorkingDirectory, [string]$OutputDirectory, [int]$Seconds) {
$null = Get-FidelityIdentity $Executable
if ($Seconds -lt 1 -or $Seconds -gt 14400) { throw 'Process wait must be bounded' }
$info = New-Object Diagnostics.ProcessStartInfo
$info.FileName = $Executable
$info.Arguments = (($Arguments | ForEach-Object { ConvertTo-FidelityArgument $_ }) -join ' ')
$info.WorkingDirectory = $WorkingDirectory
$info.UseShellExecute = $false
$info.RedirectStandardOutput = $true; $info.RedirectStandardError = $true
$process = New-Object Diagnostics.Process
$process.StartInfo = $info
$out = [IO.File]::Open((Join-Path $OutputDirectory 'stdout.txt'),[IO.FileMode]::CreateNew)
$err = [IO.File]::Open((Join-Path $OutputDirectory 'stderr.txt'),[IO.FileMode]::CreateNew)
$timer = [Diagnostics.Stopwatch]::StartNew()
$started = $false
try {
$started = $process.Start()
if (-not $started) { throw 'Process did not start' }
$stdout = $process.StandardOutput.BaseStream.CopyToAsync($out)
$stderr = $process.StandardError.BaseStream.CopyToAsync($err)
while (-not $process.WaitForExit(200)) {
if ($timer.Elapsed.TotalSeconds -gt $Seconds -or $out.Length -gt 67108864 -or $err.Length -gt 67108864) {
$process.Kill(); $process.WaitForExit(); throw 'Process timed out or logs exceeded 64 MiB'
}
}
$remaining = [int][Math]::Max(1,($Seconds - $timer.Elapsed.TotalSeconds) * 1000)
if (-not [Threading.Tasks.Task]::WaitAll([Threading.Tasks.Task[]]@($stdout,$stderr),$remaining)) {
throw 'Process output did not close within the bounded wait'
}
$null = $stdout.GetAwaiter().GetResult(); $null = $stderr.GetAwaiter().GetResult()
if ($out.Length -gt 67108864 -or $err.Length -gt 67108864) { throw 'Process logs exceeded 64 MiB' }
return @{exit_code=$process.ExitCode; elapsed_seconds=$timer.Elapsed.TotalSeconds;
executable=$Executable; argv=@($Executable)+$Arguments; cwd=$WorkingDirectory}
} finally {
if ($started -and -not $process.HasExited) { $process.Kill(); $process.WaitForExit() }
$out.Dispose(); $err.Dispose(); $process.Dispose(); $timer.Stop()
}
}
function Get-FidelityOutcome([string]$Prior, [string]$Requested, [string]$Why) {
if ($Prior -notin @('incomplete','failed','skipped','aborted') -or
$Requested -notin @('captured','failed','skipped','aborted')) { throw 'Invalid outcome' }
if ($Prior -ne 'incomplete' -and $Requested -ne $Prior) { throw 'Failed/terminal run cannot be promoted; use a new session' }
if ($Requested -ne 'captured' -and -not $Why) { throw 'Failure/skip/abort requires a reason' }
return $Requested
}
function Get-FidelityPlatform {
$result = @{os='windows'; execution='native'; version=[Environment]::OSVersion.VersionString;
powershell=$PSVersionTable.PSVersion.ToString(); gpu=''; driver=''; vulkan=''; sdl=''}
if ([Environment]::OSVersion.Platform -ne [PlatformID]::Win32NT) { throw 'Native Windows collector requires Windows; Linux library tests are tooling-only' }
try {
$result.gpu_adapters = @(Get-CimInstance Win32_VideoController | Select-Object Name,DriverVersion,DriverDate,PNPDeviceID)
$result.gpu = ($result.gpu_adapters | ForEach-Object { $_.Name }) -join '; '
$result.driver = ($result.gpu_adapters | ForEach-Object { $_.DriverVersion }) -join '; '
$result.windows = Get-CimInstance Win32_OperatingSystem | Select-Object Caption,Version,BuildNumber,OSArchitecture
} catch { $result.query_failure = $_.Exception.Message }
return $result
}
function Copy-FidelityEvidence([string]$Source, [string]$Run, [string]$Name) {
$target = Get-FidelityPath $Run $Name
$null = [IO.Directory]::CreateDirectory([IO.Path]::GetDirectoryName($target))
$before = Get-FidelityIdentity $Source
[IO.File]::Copy($Source,$target,$false)
$after = Get-FidelityIdentity $target
if ($before.sha256 -ne $after.sha256 -or $before.size -ne $after.size) { throw 'Copy identity changed' }
$after.path = $Name
return $after
}
function New-FidelityReceipt([string]$Id, [string]$Case, [string]$Obligation,
[string]$Kind, [string]$Status, $Platform, $Clocks, [string]$Why) {
$null = Test-FidelityId $Id; $null = Test-FidelityId $Case
if ($Kind -notin @('original_dxwnd','native_port','synthetic') -or
$Status -notin @('incomplete','failed','captured','skipped','aborted')) { throw 'Invalid result classification' }
return @{schema_version=1; receipt_id=$Id; session_id=$Id; case_id=$Case;
scope=$Obligation; obligation_id=$Obligation; evidence_kind=$Kind;
status=$Status; historical=$false; platform=$Platform; identity=@{};
invocation=@{argv=@();cwd=''}; clocks=$Clocks; artifacts=@();derivatives=@();events=@();
limitations=@($Why); missing_evidence=@('Actual audiovisual review and scenario audit remain open');
acceptance=@{state='open';remaining=@('No acceptance from preparation, launch or collector success')}}
}
function Start-FidelityRun {
$null = Test-FidelityId $SessionId
$root = [IO.Path]::GetFullPath($Bundle)
$run = Get-FidelityPath $root ('results/' + $SessionId)
if (Test-Path -LiteralPath $run) { throw 'Session exists; choose an independent new launch ID' }
$null = [IO.Directory]::CreateDirectory((Join-Path $root 'results'))
$reservation = [IO.File]::Open(($run + '.lock'),[IO.FileMode]::CreateNew)
$reservation.Dispose()
$null = [IO.Directory]::CreateDirectory($run)
$watch = [Diagnostics.Stopwatch]::StartNew()
$clock = @{wall_start=[DateTime]::UtcNow.ToString('o'); wall_end=[DateTime]::UtcNow.ToString('o');
monotonic_start=0;monotonic_end=0;clock_id=[guid]::NewGuid().ToString('N')}
$platform = @{os='windows';execution=$(if ($Mode -eq 'original') {'dxwnd'} else {'native'})}
$kind = $(if ($Mode -eq 'original') {'original_dxwnd'} else {'native_port'})
$receipt = New-FidelityReceipt $SessionId $CaseId $Scope $kind 'incomplete' $platform $clock 'Collection pending'
Write-FidelityJson (Join-Path $run 'incomplete.json') $receipt
try {
$manifest = Test-FidelityBundle $root
if ($manifest.tooling_only) { throw 'Synthetic checkpoint cannot launch native/original evidence' }
$protocol = Read-FidelityJson (Join-Path $root 'protocol/scenarios.json')
if ($CaseId -notin @($protocol.cells | ForEach-Object {$_.id})) { throw 'Unknown scenario cell' }
if ($Action -in @('Skip','Abort')) {
$receipt.status = Get-FidelityOutcome 'incomplete' $(if ($Action -eq 'Skip') {'skipped'} else {'aborted'}) $Reason
$receipt.limitations = @($Reason)
return 0
}
$platform = Get-FidelityPlatform
$platform.execution = $(if ($Mode -eq 'original') {'dxwnd'} else {'native'})
$receipt.platform = $platform
$receipt.identity.checkpoint = Copy-FidelityEvidence (Join-Path $root 'manifest.json') $run 'identity/checkpoint.json'
$receipt.identity.launcher = Copy-FidelityEvidence $script:CollectorSource $run 'identity/collector.ps1'
$tools = @{}
foreach ($entry in @(@('recorder',$RecorderPath),@('browser',$BrowserPath),@('settings',$SettingsPath))) {
if (-not $entry[1]) { throw ('Select actual local ' + $entry[0] + ' file; no downloads are performed') }
# Identify external tools; do not redistribute their executables/installers.
$id = Get-FidelityIdentity $entry[1]
$tools[$entry[0]] = @{selected_path=$entry[1]; identity=$id;
version=[Diagnostics.FileVersionInfo]::GetVersionInfo($entry[1]).FileVersion}
}
$receipt.identity.settings = Copy-FidelityEvidence $SettingsPath $run 'identity/settings.json'
Write-FidelityJson (Join-Path $run 'tools.json') $tools
if ($Mode -eq 'port') {
$package = Join-Path $root 'port/win-x64'
$exe = Join-Path $package 'GamePort.exe'
$receipt.identity.executable = Copy-FidelityEvidence $exe $run 'identity/GamePort.exe'
$receipt.identity.runtime_dll = Copy-FidelityEvidence (Join-Path $package 'GamePort.dll') $run 'identity/GamePort.dll'
$build = Read-FidelityJson (Join-Path $package 'fidelity-build.json')
$src = Copy-FidelityEvidence (Join-Path $package 'fidelity-build.json') $run 'identity/build.json'
$src.commit = $build.source.commit; $src.dirty = $build.source.dirty; $src.diff_sha256 = $build.source.diff_sha256
$receipt.identity.source = $src
$receipt.identity.package = $src
$receipt.identity.resources = $src
$sdl = [Diagnostics.FileVersionInfo]::GetVersionInfo((Join-Path $package 'SDL3.dll'))
$platform.sdl_binary_version = $sdl.FileVersion
$arguments = @('--assets',(Join-Path $package 'assets'),'--load-save',(Join-Path $package 'assets/NewGame.tsk'),
'--walk','--fidelity-output',(Join-Path $run 'observer'),'--fidelity-session',$SessionId,'--fidelity-case',$CaseId)
Write-Host 'Start the external raw MKV recording now. Record physical inputs and media clocks. This is the existing TSK story entry, not a reconstructed main menu.'
$null = Read-Host 'Press Enter when recording is running'
$receipt.invocation = @{argv=@($exe)+$arguments;cwd=$run}
$result = Invoke-FidelityProcess $exe $arguments $run $run $TimeoutSeconds
Write-FidelityJson (Join-Path $run 'process.json') $result
if ($result.exit_code -ne 0) { throw "Port exited $($result.exit_code); preserve recording and logs" }
$receipt.limitations = @('Port process exited; media/event mapping and human review pending; observer overhead is diagnostic')
} else {
if (-not $DxWndPath -or -not $ProfilePath) { throw 'Select actual local DxWnd executable and exported profile' }
$dxwndId = Get-FidelityIdentity $DxWndPath
Write-FidelityJson (Join-Path $run 'dxwnd-tool.json') @{selected_path=$DxWndPath;identity=$dxwndId;
version=[Diagnostics.FileVersionInfo]::GetVersionInfo($DxWndPath).FileVersion}
$receipt.identity.dxwnd = @{path='dxwnd-tool.json'} + (Get-FidelityIdentity (Join-Path $run 'dxwnd-tool.json'))
$receipt.identity.dxwnd_config = Copy-FidelityEvidence $ProfilePath $run 'identity/original-profile.dxw'
$copy = Get-FidelityPath $root ('original-runs/' + $SessionId)
if (Test-Path -LiteralPath $copy) { throw 'Original run copy exists' }
$null = [IO.Directory]::CreateDirectory($copy)
$seed = Join-Path $root 'original-pristine'
foreach ($file in Get-FidelityTree $seed) {
$null = Copy-FidelityEvidence (Get-FidelityPath $seed $file.path) $copy $file.path
}
Write-FidelityJson (Join-Path $run 'copy-pre.json') @(Get-FidelityTree $copy)
$receipt.identity.copy_pre = @{path='copy-pre.json'} + (Get-FidelityIdentity (Join-Path $run 'copy-pre.json'))
Write-Host "Generated original copy: $copy"
Write-Host 'Inspect this selected DxWnd distribution help/config. Import the retained exported profile and change ONLY target/working-directory paths to the generated copy; export the relocated profile into this result folder. No switches/settings are assumed.'
Write-Host 'Start external raw MKV recording before original interaction. Launch the original manually through DxWnd. Never select original-pristine or the authoritative installation.'
$info = New-Object Diagnostics.ProcessStartInfo
$info.FileName = [IO.Path]::GetFullPath($DxWndPath); $info.WorkingDirectory = $copy; $info.UseShellExecute = $false
$wrapper = [Diagnostics.Process]::Start($info)
$receipt.invocation = @{argv=@($info.FileName);cwd=$copy;method='manual profile import and GUI launch; original child exit not inferred'}
$null = Read-Host 'After the original has exited and recording stopped, press Enter (keep this collector alive during retained prerequisites)'
$receipt.wrapper_settings = 'Selected profile retained; relocated export/settings and wrapper limitations require annotation review'
$receipt.limitations = @('DxWnd GUI launched; original child invocation/exit and visible/audible behavior require actual session annotations')
$wrapper.Dispose()
}
} catch {
$receipt.status = 'failed'; $receipt.limitations = @($_.Exception.Message)
Write-Warning $_.Exception.Message
} finally {
if ($Mode -eq 'original' -and (Get-Variable copy -ErrorAction SilentlyContinue) -and
(Test-Path -LiteralPath $copy) -and -not (Test-Path -LiteralPath (Join-Path $run 'copy-post.json'))) {
try {
Write-FidelityJson (Join-Path $run 'copy-post.json') @(Get-FidelityTree $copy)
$receipt.identity.copy_post = @{path='copy-post.json'} + (Get-FidelityIdentity (Join-Path $run 'copy-post.json'))
} catch { $receipt.status = 'failed'; $receipt.limitations += ('Postflight failed: ' + $_.Exception.Message) }
}
$clock.wall_end = [DateTime]::UtcNow.ToString('o'); $clock.monotonic_end = $watch.Elapsed.TotalSeconds
Write-FidelityJson (Join-Path $run 'run.json') $receipt
if ($receipt.status -in @('failed','skipped','aborted')) { Write-FidelityJson (Join-Path $run 'failure.json') $receipt }
$watch.Stop()
}
Write-Host "Result: $run ; status=$($receipt.status); acceptance OPEN"
if ($receipt.status -eq 'failed') { return 2 }; return 0
}
function Complete-FidelityRun {
$null = Test-FidelityId $SessionId
$run = Get-FidelityPath $Bundle ('results/' + $SessionId)
$null = Test-FidelityBundle $Bundle
$runPath = Join-Path $run 'run.json'
$recovering = -not (Test-Path -LiteralPath $runPath)
if ($recovering) {
if ($Outcome -ne 'aborted') { throw 'Interrupted initial record can only be finalized as aborted' }
$runPath = Join-Path $run 'incomplete.json'
}
$receipt = Read-FidelityJson $runPath
if ($recovering) {
if ($receipt.status -ne 'incomplete' -or $receipt.session_id -cne $SessionId) { throw 'Interrupted initial record does not match the incomplete session' }
# Initial records from older collectors contain placeholder end values.
# Neither those placeholders nor recovery time observed the process end.
$receipt.clocks.PSObject.Properties.Remove('wall_end')
$receipt.clocks.PSObject.Properties.Remove('monotonic_end')
$receipt.missing_evidence += 'Interrupted collector: end clocks and launch-aligned observations unavailable'
$receipt | Add-Member -Force -NotePropertyName diagnostic -NotePropertyValue $true
}
if (Test-Path -LiteralPath (Join-Path $run 'receipt.json')) { throw 'Result already finalized; preserve it and use a new result ID' }
if (-not $AnnotationPath -or -not $ArtifactsDirectory) { throw 'Finish requires actual annotations and a local artifact directory' }
$annotation = Read-FidelityJson $AnnotationPath
$requested = Get-FidelityOutcome $receipt.status $Outcome $Reason
if ($annotation.schema_version -ne 1) { throw 'Unsupported annotation schema' }
if ($recovering -and @($annotation.events).Count) { throw 'Interrupted run has no observed end interval; retain annotations without launch-aligned events' }
if (@($annotation.artifacts).Count -gt 10000) { throw 'Too many artifacts' }
$names = @{}
foreach ($file in $annotation.artifacts) {
$null = Get-FidelityPath $ArtifactsDirectory $file.path
if ($names.ContainsKey($file.path)) { throw 'Duplicate/case-aliased artifact' }; $names[$file.path] = $file
$null = Get-FidelityIdentity (Get-FidelityPath $ArtifactsDirectory $file.path)
if ($file.PSObject.Properties.Name -contains 'synthetic' -and $file.synthetic) { throw 'Synthetic media cannot be relabeled as native/original' }
}
foreach ($event in $annotation.events) {
if (-not $names.ContainsKey($event.artifact)) { throw 'Event references missing artifact' }
}
if ($requested -eq 'captured') {
if (-not @($annotation.artifacts | Where-Object {$_.role -eq 'video' -and $_.path.EndsWith('.mkv',[StringComparison]::OrdinalIgnoreCase)}).Count) {
throw 'Captured result requires retained raw MKV video'
}
if (-not @($annotation.artifacts | Where-Object {$_.role -eq 'audio'}).Count) { throw 'Captured result requires actual audio evidence' }
}
foreach ($derivative in $annotation.derivatives) {
if (-not $names.ContainsKey($derivative.path) -or -not $names.ContainsKey($derivative.source) -or
-not $derivative.tool -or -not $derivative.version -or -not $derivative.created_utc -or
-not @($derivative.argv).Count -or -not $derivative.timestamp_mapping -or
-not $derivative.crop_aspect -or $derivative.browser_playback_verified -isnot [bool] -or
-not $derivative.browser_playback_verified) {
throw 'Derivative requires source/output, actual tool/version/argv/time/crop and verified browser playback'
}
}
$receipt.artifacts = @()
if ($recovering) {
$initial = Copy-FidelityEvidence $runPath $run 'recovery-initial.json'
$initial.role = 'diagnostic'
$receipt.artifacts += $initial
}
foreach ($file in $annotation.artifacts) {
$source = Get-FidelityPath $ArtifactsDirectory $file.path
$id = Copy-FidelityEvidence $source $run ('media/' + $file.path)
$id.role = $file.role
if ($file.PSObject.Properties.Name -contains 'duration_seconds') { $id.duration_seconds = $file.duration_seconds }
$receipt.artifacts += $id
}
$copied = Copy-FidelityEvidence $AnnotationPath $run 'annotations.json'
$copied.role = 'input_events'; $receipt.artifacts += $copied
$receipt.events = @($annotation.events | ForEach-Object {
if (-not $names.ContainsKey($_.artifact)) { throw 'Event references missing artifact' }
$_.artifact = 'media/' + $_.artifact; $_
})
$receipt.derivatives = @($annotation.derivatives | ForEach-Object {
$_.path = 'media/' + $_.path; $_.source = 'media/' + $_.source; $_
})
$receipt.status = $requested
if ($annotation.PSObject.Properties.Name -contains 'continuity') {
$continuity = $annotation.continuity
if ($continuity.PSObject.Properties.Name -contains 'prerequisite_artifact') {
if (-not $names.ContainsKey($continuity.prerequisite_artifact)) { throw 'Continuity references missing artifact' }
$continuity.prerequisite_artifact = 'media/' + $continuity.prerequisite_artifact
}
$receipt | Add-Member -Force -NotePropertyName continuity -NotePropertyValue $continuity
}
if ($annotation.PSObject.Properties.Name -contains 'diagnostic') { $receipt | Add-Member -Force -NotePropertyName diagnostic -NotePropertyValue ([bool]$annotation.diagnostic) }
if ($Reason) { $receipt.limitations += $Reason }
$receipt.limitations += @($annotation.limitations)
# Human declarations remain source annotations; the shared importer and final
# audit validate times, hashes, category, continuity and actual review later.
$receipt.limitations += 'Imported annotations require shared validation; raw MKV and incomplete/failed cases are retained'
Write-FidelityJson (Join-Path $run 'receipt.json') $receipt
Write-Host "Result saved ($requested); acceptance OPEN. Return full checkpoint locally for validation."
}
if ($LibraryOnly) { return }
try {
if ($Action -eq 'Preflight') {
$manifest = Test-FidelityBundle $Bundle
Write-Host "Prepared materials checked: $($manifest.files.Count) files; acceptance OPEN; actual Windows/tools/media preflight pending"
exit 0
}
if ($Action -eq 'Finish') { Complete-FidelityRun; exit 0 }
if ($Action -eq 'Retained') {
$null = Test-FidelityId $SessionId
$run = Get-FidelityPath $Bundle ('results/' + $SessionId)
$copy = Get-FidelityPath $Bundle ('original-runs/' + $SessionId)
Write-FidelityJson (Join-Path $run 'retained-copy.json') @{observed_utc=[DateTime]::UtcNow.ToString('o');
files=@(Get-FidelityTree $copy);note='Snapshot only; prerequisite recording and actual media timing/uncertainty still required'}
exit 0
}
exit (Start-FidelityRun)
} catch {
Write-Error ('Collector failed; acceptance OPEN: ' + $_.Exception.Message)
exit 2
}
+6
View File
@@ -0,0 +1,6 @@
#!/usr/bin/env bash
set -euo pipefail
source "$(dirname "$0")/env.sh"
# Build first into NEW local output, then prepare a different NEW bundle root.
# Existing dist packages retain their historical bytes and BUILD-INFO.
exec python3 tools/recon/fidelity_checkpoint.py "$@"
+38 -1
View File
@@ -1,7 +1,43 @@
#!/usr/bin/env bash
set -euo pipefail
source "$(dirname "$0")/env.sh"
python3 -m unittest discover -s tests -p 'test_*.py' -v
suite_started=$SECONDS
mkdir -p artifacts/fidelity
python3 - <<'PY'
import sys
import unittest
suite = unittest.defaultTestLoader.discover('tests', pattern='test_*.py')
def cases(node):
for item in node:
if isinstance(item, unittest.TestSuite):
yield from cases(item)
else:
yield item
counts = {}
for case in cases(suite):
module = case.id().split('.')[0]
if module.startswith('test_fidelity_'):
counts[module] = counts.get(module, 0) + 1
required = ('sessions', 'scenarios', 'review', 'ledger', 'observation',
'checkpoint', 'capture', 'acceptance')
assert all(counts.get('test_fidelity_' + name, 0) > 0 for name in required), counts
print('Fidelity Python checks:', sum(counts.values()), counts, flush=True)
sys.exit(not unittest.TextTestRunner(verbosity=2).run(suite).wasSuccessful())
PY
node --test --test-reporter=tap tests/fidelity-viewer.test.mjs | tee artifacts/fidelity/consolidated-viewer.log
python3 - <<'PY'
import re
from pathlib import Path
text = Path('artifacts/fidelity/consolidated-viewer.log').read_text()
assert re.search(r'^# tests [1-9][0-9]*$', text, re.M), 'zero/missing viewer checks'
PY
dotnet run --project tests/GamePort.FidelityObservationTests | tee artifacts/fidelity/consolidated-observer.log
python3 - <<'PY'
import re
from pathlib import Path
text = Path('artifacts/fidelity/consolidated-observer.log').read_text()
assert re.search(r'Fidelity observation checks: [1-9][0-9]* passed', text), 'zero/missing observer checks'
PY
python3 tools/extractors/prepare.py --all-scenes --audio sounds musicsecretlab
dotnet run --project tests/GamePort.DataTests -- ../Original
dotnet run --project tests/GamePort.CollisionTests -- ../Original
@@ -118,3 +154,4 @@ if [[ "${NEUTRON_WINDOW_TEST:-0}" == 1 ]]; then
dotnet run --no-build -- --scene artifacts/extracted/level1b/scene.json --smoke-window --frames 6 --screenshot artifacts/test-window.ppm
dotnet run --no-build -- --smoke-walk --screenshot artifacts/test-walk-window.ppm
fi
printf 'Complete local suite passed in %s seconds; fidelity Python/Node/observer counts verified positive.\n' "$((SECONDS - suite_started))"
@@ -0,0 +1,239 @@
using System.Diagnostics;
using System.Numerics;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
using GamePort.Game;
namespace GamePort.Application;
/// <summary>Optional application diagnostics. Owns only copied observations and output;
/// it never owns a simulation, callback, input source or continuation payload.</summary>
internal sealed class FidelityObservation : IDisposable
{
private static readonly JsonSerializerOptions Json = new() { PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower };
private readonly Stopwatch clock = Stopwatch.StartNew();
private readonly string directory, session, caseId, kind;
private readonly string launchId = Guid.NewGuid().ToString("N");
private readonly DateTimeOffset wallStart = DateTimeOffset.UtcNow;
private readonly int maxRecords;
private const long MaxBytes = 512L * 1024 * 1024;
private TextWriter? writer;
private long sequence, bytes;
private string? failure;
private bool completed, disposed, ownsDirectory;
private double overhead;
private long? pendingDeparture;
private (string Scene, bool Controlled, string? Owner, bool Playing, string? Dialogue)? control;
private FidelityObservation(string directory, string session, string caseId, string kind, int maxRecords)
{ this.directory = directory; this.session = session; this.caseId = caseId; this.kind = kind; this.maxRecords = maxRecords; }
public static FidelityObservation? FromArguments(string[] args, string project, string originals)
{
string? Option(string name)
{
var index = Array.IndexOf(args, name);
if (index < 0) return null;
if (index + 1 == args.Length || args[index + 1].StartsWith("--", StringComparison.Ordinal))
throw new ArgumentException(name + " requires a value");
if (Array.LastIndexOf(args, name) != index) throw new ArgumentException("Repeated " + name);
return args[index + 1];
}
var output = Option("--fidelity-output");
if (output == null) return null;
var session = Option("--fidelity-session") ?? throw new ArgumentException("--fidelity-session required");
var caseId = Option("--fidelity-case") ?? throw new ArgumentException("--fidelity-case required");
var fixture = args.Any(a => a.StartsWith("--smoke-", StringComparison.Ordinal)
|| a.StartsWith("--", StringComparison.Ordinal) && a.EndsWith("-smoke", StringComparison.Ordinal)
|| a is "--headless" or "--story-time" or "--time" or "--inspect" or "--skip-intro"
or "--noclip" or "--debug-menu" or "--debug-page" or "--gadget-menu");
return Create(output, session, caseId, fixture ? "port_fixture" : "native_port", project, originals);
}
public static FidelityObservation Create(string output, string session, string caseId, string kind,
string project, string originals, int maxRecords = 250000, TextWriter? sink = null)
{
foreach (var id in new[] { session, caseId })
if (!Regex.IsMatch(id, "^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$", RegexOptions.CultureInvariant))
throw new ArgumentException("Observation IDs require 1..128 safe characters");
if (kind is not ("port_fixture" or "native_port") || maxRecords < 1 || maxRecords > 250000)
throw new ArgumentException("Invalid observation category or record limit");
var path = Path.TrimEndingDirectorySeparator(Path.GetFullPath(output));
static bool Within(string child, string parent) => child.Equals(parent, StringComparison.OrdinalIgnoreCase)
|| child.StartsWith(Path.TrimEndingDirectorySeparator(parent) + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase);
static string ResolvedDirectory(string value)
{
var full = Path.GetFullPath(value);
var current = Path.GetPathRoot(full)!;
foreach (var part in full[current.Length..].Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries))
{
current = Path.Combine(current, part);
var info = new DirectoryInfo(current);
if (info.LinkTarget != null)
current = info.ResolveLinkTarget(true)?.FullName ?? throw new ArgumentException("Unresolved protected asset link");
}
return Path.TrimEndingDirectorySeparator(current);
}
var protectedRoots = new List<string> { ResolvedDirectory(originals), Path.Combine(ResolvedDirectory(project), ".git") };
// A generated --assets copy must not make the checkout's authoritative sibling writable.
foreach (var candidate in new[] { Path.Combine(project, "..", "Original"), Path.Combine(project, "Original"), Path.Combine(project, "assets") })
if (Directory.Exists(candidate)) protectedRoots.Add(ResolvedDirectory(candidate));
if (protectedRoots.Any(protectedRoot => Within(path, protectedRoot) || Within(protectedRoot, path)))
throw new ArgumentException("Observation output must be separate from original assets and Git metadata");
for (var parent = new DirectoryInfo(path); parent != null; parent = parent.Parent)
if (parent.LinkTarget != null) throw new ArgumentException("Observation output cannot traverse symbolic links");
if (Directory.Exists(path) || File.Exists(path)) throw new IOException("Observation requires a new output directory");
var observer = new FidelityObservation(path, session, caseId, kind, maxRecords);
try
{
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
// A cooperative local reservation prevents two observers reusing the same directory.
var reservation = path + ".fidelity-reservation";
using (new FileStream(reservation, FileMode.CreateNew, FileAccess.Write, FileShare.None))
{
if (Directory.Exists(path) || File.Exists(path)) throw new IOException("Observation directory was reserved by another writer");
Directory.CreateDirectory(path);
observer.ownsDirectory = true;
}
File.Delete(reservation);
observer.WriteSummary(false);
observer.writer = sink ?? new StreamWriter(new FileStream(Path.Combine(path, "events.jsonl"),
FileMode.CreateNew, FileAccess.Write, FileShare.Read), new UTF8Encoding(false), 65536);
observer.writer.NewLine = "\n";
}
catch (Exception error) when (OutputError(error)) { observer.Fail(error.Message); }
return observer;
}
public void RecordInput(string scene, int simulationTick, PlayerInput requested, bool acceptsInput, string controlOwner)
=> Record("input_step", scene, simulationTick, "post_owner_step", new {
requested_input = requested, accepts_input = acceptsInput,
accepted_input = acceptsInput ? (PlayerInput?)requested : null,
control_owner = controlOwner, control_owner_phase = "post_step",
acceptance_scope = "reported binding gate only; individual command dispatch and independent body/fire work are not classified by this boolean" });
public void RecordSceneEntry(string scene, int simulationTick, bool returning, bool retainedPlayer, string entryPath)
{
control = null;
Record("scene_entry", scene, simulationTick, "application_scene_composition", new {
returning, retained_player = retainedPlayer, entry_path = entryPath, departure_sequence = pendingDeparture });
pendingDeparture = null;
}
public void RecordTransition(string scene, string destination, int simulationTick, bool returning)
{
Record("scene_departure", scene, simulationTick, "continuation_published", new { destination, returning });
pendingDeparture = sequence;
}
public void RecordRawEvent(string scene, int simulationTick, uint eventType, uint? scancode, byte? button, byte? repeat)
=> Record("raw_sdl_event", scene, simulationTick, "sdl_poll_before_routing", new {
event_type = eventType, scancode, button, repeat, acceptance = "raw_only; routing may consume or reject this event" });
public void RecordControl(string scene, int simulationTick, bool controlled, string? owner, bool playing, string? dialogue, string boundary)
{
var current = (scene, controlled, owner, playing, dialogue);
var previous = control;
if (previous == current && !boundary.StartsWith("skip:", StringComparison.Ordinal)) return;
var data = new { controlled, control_owner = owner, playing, dialogue };
Record("control_observation", scene, simulationTick, boundary, data);
if (boundary.StartsWith("skip:", StringComparison.Ordinal) && previous is { } before && (before.Playing || !before.Controlled))
Record("dialogue_skip", scene, simulationTick, boundary, data);
if ((previous == null || previous is { Playing: false }) && playing)
Record("dialogue_start", scene, simulationTick, boundary, data);
if (previous is { Playing: true } && !playing)
Record("dialogue_end", scene, simulationTick,
boundary == "director_step" ? "natural_director_step" : boundary, data);
control = current;
}
public void RecordState(string scene, int simulationTick, Vector3 root, Vector3 rotation, Vector3 velocity,
bool grounded, int movementMode, bool inputAfterPlayerUpdate, int controllers, int physics, int effects)
=> Record("player_state", scene, simulationTick, "post_owner_value_snapshot", new {
actor_root = new[] { root.X, root.Y, root.Z }, euler_degrees = new[] { rotation.X, rotation.Y, rotation.Z },
velocity = new[] { velocity.X, velocity.Y, velocity.Z }, grounded, movement_mode = movementMode,
input_after_player_update = inputAfterPlayerUpdate, controller_steps = controllers, physics_steps = physics,
effect_steps = effects, interpretation = "copied state only; bank/landing/idle require explicit review" });
private void Record(string name, string scene, int simulationTick, string method, object data)
{
if (disposed || completed || failure != null) return;
var started = Stopwatch.GetTimestamp();
try
{
if (sequence >= maxRecords) throw new IOException("Observation record limit reached");
var line = JsonSerializer.Serialize(new { schema_version = 1, session_id = session, case_id = caseId,
evidence_kind = kind, launch_id = launchId, clock_id = launchId + ":stopwatch", sequence = sequence + 1,
elapsed_seconds = clock.Elapsed.TotalSeconds, simulation_tick = simulationTick,
name, scene, method, data }, Json);
var length = Encoding.UTF8.GetByteCount(line) + 1;
if (bytes + length > MaxBytes) throw new IOException("Observation byte limit reached");
writer!.WriteLine(line);
sequence++; bytes += length;
}
catch (Exception error) when (OutputError(error)) { Fail(error.Message); }
finally { overhead += Stopwatch.GetElapsedTime(started).TotalSeconds; }
}
public void Complete(int exitCode)
{
if (disposed || completed) return;
if (exitCode != 0) Fail("Port exited with code " + exitCode);
try { writer?.Dispose(); writer = null; }
catch (Exception error) when (OutputError(error)) { Fail(error.Message); }
completed = true;
TrySummary(exitCode == 0 && failure == null);
}
private static bool OutputError(Exception error) => error is IOException or UnauthorizedAccessException
or System.Security.SecurityException or JsonException or ArgumentException or NotSupportedException;
private void Fail(string reason)
{
if (failure != null) return;
failure = reason;
Console.Error.WriteLine("Fidelity observation INCOMPLETE: " + reason);
try { writer?.Dispose(); } catch (Exception error) when (OutputError(error)) { }
writer = null;
TrySummary(false);
}
private void TrySummary(bool success)
{
if (!ownsDirectory) return;
try { WriteSummary(success); }
catch (Exception error) when (OutputError(error))
{ Console.Error.WriteLine("Fidelity observation INCOMPLETE; summary unavailable: " + error.Message); }
}
private void WriteSummary(bool success)
{
var target = Path.Combine(directory, "observation-summary.json");
var temporary = target + "." + Guid.NewGuid().ToString("N") + ".tmp";
var summary = new { schema_version = 1, session_id = session, case_id = caseId, evidence_kind = kind,
launch_id = launchId, clock_id = launchId + ":stopwatch", wall_start = wallStart, wall_end = DateTimeOffset.UtcNow,
elapsed_seconds = clock.Elapsed.TotalSeconds, records = sequence, bytes, incomplete = !success,
status = success ? "recorded" : "incomplete", failure,
diagnostic = true, observer_seconds = overhead, max_records = maxRecords, max_bytes = MaxBytes,
overhead_scope = "Record serialization/write attempts only; excludes caller snapshots, control comparisons, final flush and summaries",
limitations = new[] { "Diagnostic observer adds serialization, buffered disk writes and state-copy overhead; not a clean audiovisual capture.",
"Observation is not a receipt or an acceptance decision; fixture and native full-route evidence remain distinct.",
"No media clock mapping is inferred. Simulation ticks are scene-local and may reset across continuations.",
"Only named application seams are observed; fixture helper-internal steps are not a complete simulation trace." } };
try
{
using (var stream = new FileStream(temporary, FileMode.CreateNew, FileAccess.Write, FileShare.None))
JsonSerializer.Serialize(stream, summary, Json);
File.Move(temporary, target, true);
}
finally { if (File.Exists(temporary)) File.Delete(temporary); }
}
public void Dispose()
{
if (disposed) return;
if (!completed) { Fail("Session ended without successful completion"); TrySummary(false); }
disposed = true;
}
}
+54 -16
View File
@@ -15,6 +15,8 @@ internal static class Program
{
try
{
using var observation = args.Contains("--help") || !args.Contains("--fidelity-output") ? null : FidelityObservation.FromArguments(args,
Directory.GetCurrentDirectory(), AssetPath.FindOriginal(Option(args, "--assets")));
using var presentation = new RenderSession();
OriginalSave? carriedSave = null;
PlayerLevelState? carriedPlayer = null;
@@ -24,8 +26,8 @@ internal static class Program
var grapplerMemory = new GrapplerMemory();
while (true)
{
var result = Run(args, carriedSave, carriedPlayer, returning, diagnostics, presentation, energy, grapplerMemory, out var continuation);
if (result != 0 || continuation == null) return result;
var result = Run(args, carriedSave, carriedPlayer, returning, diagnostics, presentation, energy, grapplerMemory, observation, out var continuation);
if (result != 0 || continuation == null) { observation?.Complete(result); return result; }
args = continuation.Args; carriedSave = continuation.Save; returning = continuation.Returning;
carriedPlayer = continuation.Player;
}
@@ -45,7 +47,7 @@ internal static class Program
private sealed record SceneContinuation(string[] Args, OriginalSave Save, bool Returning, PlayerLevelState? Player);
private static int Run(string[] args, OriginalSave? carriedSave, PlayerLevelState? carriedPlayer, bool returning, DebugDiagnostics diagnostics,
RenderSession presentation, PlayerEnergy energy, GrapplerMemory grapplerMemory, out SceneContinuation? continuation)
RenderSession presentation, PlayerEnergy energy, GrapplerMemory grapplerMemory, FidelityObservation? observation, out SceneContinuation? continuation)
{
continuation = null;
if (args.Contains("--help"))
@@ -69,6 +71,9 @@ internal static class Program
--start TAG Use a named original STRT checkpoint
--load-save PATH Resume original TSK task/items/checkpoint state
--write-save PATH Write checkpoint state as TSK outside asset directory
--fidelity-output PATH New local diagnostic session directory
--fidelity-session ID Stable session identity across scene continuations
--fidelity-case ID Declared comparison case; does not establish acceptance
--mute Disable scene audio
--time SECONDS Fixed animation time for comparisons
--headless Render offscreen through Vulkan
@@ -336,6 +341,24 @@ internal static class Program
var debugCheckpointFile = toolsSmoke ? Path.GetFullPath("artifacts/debug-expansion/checkpoint.tsk")
: Path.Combine(AppContext.BaseDirectory, "debug-checkpoint.tsk");
Vector3 returnRoot = loadedSave?.StoredVector ?? Vector3.Zero;
void ObserveControl(string boundary)
{
if (observation != null && director != null)
observation.RecordControl(level!.Code, simulation?.Steps ?? 0, director.Controlled,
director.ControlledTag, director.Playing, director.CurrentTag, boundary);
}
void SkipObservedDialogue(string source)
{
ObserveControl("before_skip");
director!.Skip();
ObserveControl("skip:" + source);
}
void StepObservedDirector(float delta)
{
ObserveControl("before_director_step");
director?.Step(delta);
ObserveControl("director_step");
}
void RequestTransition(LevelTransition request)
{
if (transitionRequest != null) return;
@@ -588,6 +611,8 @@ internal static class Program
var renderer = presentation.LoadScene(mesh, texture, headless,
walking ? WalkTitle : animations?.WindowTitle ?? "Jimmy Neutron — scene preview | C camera",
width, height, !args.Contains("--no-validation"));
observation?.RecordSceneEntry(level?.Code ?? "preview", simulation?.Steps ?? 0, returning,
carriedPlayer != null, carriedSave != null ? "retained" : loadedSave != null ? "tsk-story" : "fresh-direct-scene");
var window = presentation.Window;
ShrinkSoldier? shrinkVictim = null;
var shrinkPhaseMask = 0;
@@ -663,6 +688,7 @@ internal static class Program
sceneAudio.Music(originalStart!.Text("MusicDatabase") ?? "none", originalStart.Integer("MusicIndex", -1));
}
director.Begin(originalStart!, activateStartTrigger: !returning);
ObserveControl("scene_begin");
gadgets?.Reset();
baseballs?.Reset();
interactions!.Reset();
@@ -680,7 +706,7 @@ internal static class Program
Console.WriteLine($"Practice RETURN: exact saved root={restored}, root={simulation.ActorRoot}, STRT yaw={simulation.Yaw}, intro suppressed={!director.Playing}, companion restored={companionRestored}, retained player input order={simulation.InputAfterPlayerUpdate}, gadget availability={interactions.Inventory.State(0, 3)}.");
if (!restored) throw new InvalidOperationException("RETURN did not restore the live departure root without replaying STRT actions");
}
if (args.Contains("--skip-intro") || jetpackSmoke || shrinkSmoke || invisibleSmoke || bubbleSmoke || baseballSmoke || rocketSmoke || grapplerSmoke || scooterSmoke || gadgetWindowSmoke || debugSmoke || diagnosticsSmoke || toolsSmoke || controlPhaseSmoke) { sceneAudio?.StopSpeech(); director.Skip(); }
if (args.Contains("--skip-intro") || jetpackSmoke || shrinkSmoke || invisibleSmoke || bubbleSmoke || baseballSmoke || rocketSmoke || grapplerSmoke || scooterSmoke || gadgetWindowSmoke || debugSmoke || diagnosticsSmoke || toolsSmoke || controlPhaseSmoke) { sceneAudio?.StopSpeech(); SkipObservedDialogue("startup-option-or-fixture"); }
if (gadgetWindowSmoke) { interactions!.Inventory.SetState(0,3,1); interactions.Inventory.SelectGadget(3); }
if (controlPhaseSmoke)
{
@@ -705,13 +731,13 @@ internal static class Program
{
if (interactions!.Inventory.State(0, 3) != 1)
throw new InvalidOperationException("VR04 PostLoad tail did not re-enable its owned practice jetpack");
director.Skip();
SkipObservedDialogue("fixture-setup");
interactions!.Update(level.Entities.First(e => e.Kind == "LOAD").Position);
if (transitionRequest is not { Returning: true }) throw new InvalidOperationException("VR04 exit did not preserve RETURN identity");
}
if (args.Contains("--smoke-transition"))
{
director.Skip();
SkipObservedDialogue("fixture-setup");
interactions!.Update(level!.Entities.First(e => e.Kind == "LOAD").Position);
if (transitionRequest == null) throw new InvalidOperationException("Original VR01 RETURN contact did not request a transition");
}
@@ -724,9 +750,9 @@ internal static class Program
if (carlSmoke) LabRouteSmoke.StartCarl(level!, director, interactions!, () => practice.Key(17, Vector2.Zero));
if (objectiveSmoke)
{
director.Skip();
SkipObservedDialogue("fixture-setup");
director.Touch(level!.Player!.Tag!, level.Entities.Single(e => e.Tag == "teleportexplanation").Position);
director.Skip();
SkipObservedDialogue("fixture-setup");
if (interactions!.CurrentObjective != 1) throw new InvalidOperationException("Original explanation did not assign objective1");
if (objectiveWindowSmoke) objectivePanel!.Step(9);
}
@@ -734,7 +760,7 @@ internal static class Program
|| practiceReturnSmoke && level.Code == "LV1B" && !returning)
{
if ((!headless && !practiceWindowSmoke) || level?.Code != "LV1B") throw new ArgumentException("Practice smoke requires the original lab");
director.Skip();
SkipObservedDialogue("fixture-setup");
if (practiceReturnSmoke)
{
// Move the real player away from STRT so an accidental
@@ -743,7 +769,7 @@ internal static class Program
director.SyncActor(level.Player!.Tag!, simulation.ActorRoot, simulation.Rotation);
}
director.Touch(level!.Player!.Tag!, level.Entities.Single(e => e.Tag == "teleportexplanation").Position);
director.Skip();
SkipObservedDialogue("fixture-setup");
interactions!.Update(director.FindActor("shrinkray")!.Position);
if (!practice.Active) throw new InvalidOperationException("Original lab pickup did not open practice modal");
if (args.Contains("--smoke-practice-transition") || practiceReturnSmoke) practice.Key(28, Vector2.Zero);
@@ -756,7 +782,7 @@ internal static class Program
interactions!.UpdateEnergy(simulation!.Energy);
foreach (var patrol in patrols.Values) patrol.Step(FixedStepClock.Step);
mechanisms!.Step(FixedStepClock.Step);
director.Step(FixedStepClock.Step);
StepObservedDirector(FixedStepClock.Step);
objectivePanel!.Step(FixedStepClock.Step, director.ControlledTag != null, practice.Active);
if (animations!.SelectAction(director.FindActor(level!.Player!.Tag!)!.Animation)) initialPoseTime = 0;
initialPoseTime += FixedStepClock.Step;
@@ -874,6 +900,7 @@ internal static class Program
if (simulation == null) { debugMenu.Message = "RESET REQUIRES PLAY MODE"; return; }
if (practice.Active) practice.Key(17, Vector2.Zero);
playerBinding?.ResetVehicle();simulation.Reset(); poseTime = 0; sceneAudio?.StopSpeech(); director?.Begin(originalStart!);
ObserveControl("reset_begin");
rocketship?.Reset();
if(scooter!=null)
{
@@ -909,7 +936,7 @@ internal static class Program
case DebugAction.Camera: ToggleCamera(); debugMenu.Close(); break;
case DebugAction.SkipCutscene:
if (director is { Playing: true } or { Blocked: true }||director is{Controlled:false}&&rocketship?.Mounted!=true)
{ sceneAudio?.StopSpeech(); director.Skip(); debugMenu.Message = "CUTSCENE SKIPPED"; }
{ sceneAudio?.StopSpeech(); SkipObservedDialogue("debug-menu"); debugMenu.Message = "CUTSCENE SKIPPED"; }
else debugMenu.Message = "NO ACTIVE CUTSCENE";
break;
case DebugAction.RefillEnergy when simulation != null:
@@ -1132,6 +1159,10 @@ internal static class Program
}
while (!headless && Sdl.SDL_PollEvent(out var e))
{
observation?.RecordRawEvent(level?.Code ?? "preview", simulation?.Steps ?? 0,
e.Type, e.Type is Sdl.KeyDown or Sdl.KeyUp ? e.Scancode : null,
e.Type is Sdl.MouseButtonDown or Sdl.MouseButtonUp ? e.MouseButton : null,
e.Type is Sdl.KeyDown or Sdl.KeyUp ? e.Repeat : null);
if(scooterSmoke&&e.Type==Sdl.KeyDown)
sawScooterKeys|=e.Scancode switch{81=>1,82=>2,80=>4,225=>8,43=>16,60=>32,21=>64,_=>0};
if(grapplerSmoke&&e.Type==Sdl.KeyDown)
@@ -1225,7 +1256,7 @@ internal static class Program
if (smoke && e.Scancode == 79) sawKey = true;
if (e.Scancode is 41 or 44 && e.Repeat == 0 && director is { Controlled: false }&&rocketship?.Mounted!=true
&& (e.Scancode != 44 || simulation?.Noclip != true))
{ sceneAudio?.StopSpeech(); director.Skip(); keys.Clear(); mouseJump = false; }
{ sceneAudio?.StopSpeech(); SkipObservedDialogue("sdl-key-" + e.Scancode); keys.Clear(); mouseJump = false; }
else if (e.Scancode == 41) running = false;
if (inspecting && e.Repeat == 0 && animations?.Select(e.Scancode) == true)
{
@@ -1294,6 +1325,12 @@ internal static class Program
bool acceptsInput;
if (playerBinding != null) acceptsInput = playerBinding.Step(input);
else { simulation.Step(input); acceptsInput = true; }
observation?.RecordInput(level?.Code ?? "preview", simulation.Steps, input, acceptsInput,
director?.ControlledTag ?? (playerBinding == null ? "direct-simulation" : "script"));
observation?.RecordState(level?.Code ?? "preview", simulation.Steps, simulation.ActorRoot,
simulation.Rotation, simulation.Velocity, simulation.Grounded, simulation.MovementMode,
simulation.InputAfterPlayerUpdate, simulation.ControllerSteps, simulation.PhysicsSteps, simulation.EffectSteps);
ObserveControl("player_step");
scooterFixture?.Received(input);
grapplerFixture?.Received(input);
rocketFixture?.Received(input);
@@ -1317,7 +1354,7 @@ internal static class Program
}
mechanisms?.Step(FixedStepClock.Step);
foreach (var patrol in patrols.Values) patrol.Step(FixedStepClock.Step);
director?.Step(FixedStepClock.Step);
StepObservedDirector(FixedStepClock.Step);
objectivePanel?.Key(keys.Contains(18) && director is { Controlled: true, InventoryEnabled: true });
objectivePanel?.Step(FixedStepClock.Step, director?.ControlledTag != null, practice.Active);
var switched = director is { Controlled: false } && !simulation.Noclip
@@ -1518,8 +1555,8 @@ internal static class Program
&& simulation.Energy < 20 && Vector2.Distance(new(simulation.ActorRoot.X, simulation.ActorRoot.Z), new(controlEntry.X, controlEntry.Z)) < .001f;
CutsceneIdleSmoke.LandWhileLocked(playerBinding!, director!, simulation!);
sceneAudio?.StopSpeech();
director!.Skip();
CutsceneIdleSmoke.VerifyReturn(playerBinding!, director, simulation!);
SkipObservedDialogue("control-phase-fixture");
CutsceneIdleSmoke.VerifyReturn(playerBinding!, director!, simulation!);
controlControllers = simulation!.ControllerSteps;
}
if (controlPhaseSmoke && count == 30)
@@ -1866,6 +1903,7 @@ internal static class Program
continuation = new(nextArgs.ToArray(), (debugCheckpointToLoad ?? interactions!.Snapshot()) with {
StartPoint = transitionRequest.StartPoint, StoredVector = debugCheckpointToLoad?.StoredVector ?? returnRoot }, transitionRequest.Returning,
debugCheckpointToLoad == null ? simulation?.CaptureLevelState(interactions!.Inventory.SelectedGadget) : null);
observation?.RecordTransition(level!.Code, transitionRequest.LevelFile, simulation?.Steps ?? 0, transitionRequest.Returning);
Console.WriteLine($"Loading original destination: {transitionRequest.LevelFile}, start={transitionRequest.StartPoint}; fade behavior remains unreconstructed.");
}
if (walkSmoke && !simulation!.SmokePassed) return 2;
@@ -0,0 +1,9 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup><OutputType>Exe</OutputType><TargetFramework>net10.0</TargetFramework><ImplicitUsings>enable</ImplicitUsings><Nullable>enable</Nullable><EnableDefaultCompileItems>false</EnableDefaultCompileItems></PropertyGroup>
<ItemGroup>
<Compile Include="Program.cs"/>
<Compile Include="../../src/GamePort/Application/FidelityObservation.cs"/>
<Compile Include="../../src/GamePort/Assets/*.cs"/>
<Compile Include="../../src/GamePort/Game/*.cs"/>
</ItemGroup>
</Project>
@@ -0,0 +1,124 @@
using System.Text.Json;
using System.Numerics;
using GamePort.Assets;
using GamePort.Application;
using GamePort.Game;
var root = Path.Combine(Path.GetTempPath(), "gameport-observer-tests-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(root);
var checks = 0;
void Check(bool value, string message) { if (!value) throw new Exception(message); checks++; }
FidelityObservation Open(string name, int limit = 250000, TextWriter? sink = null) =>
FidelityObservation.Create(Path.Combine(root, name), "session-1", "fresh-natural-edge", "port_fixture",
Path.GetFullPath("."), Path.Combine(root, "Original"), limit, sink);
JsonElement[] Events(string name) => File.ReadAllLines(Path.Combine(root, name, "events.jsonl"))
.Select(line => JsonDocument.Parse(line).RootElement.Clone()).ToArray();
JsonElement Summary(string name) => JsonDocument.Parse(File.ReadAllText(Path.Combine(root, name, "observation-summary.json"))).RootElement.Clone();
try
{
Check(FidelityObservation.FromArguments([], ".", Path.Combine(root, "Original")) == null, "disabled must allocate no observer");
using (var observer = Open("identity"))
{
observer.RecordInput("LV1B", 17, new(true, false, true, false, true), false, "script");
observer.RecordInput("LV1B", 18, default, true, "Jimmy");
observer.Complete(0);
}
var records = Events("identity");
Check(records.All(e => e.GetProperty("session_id").GetString() == "session-1" && e.GetProperty("case_id").GetString() == "fresh-natural-edge"), "identity must be bound");
Check(records[1].GetProperty("elapsed_seconds").GetDouble() >= records[0].GetProperty("elapsed_seconds").GetDouble(), "one monotonic clock");
Check(records[0].GetProperty("data").GetProperty("requested_input").GetProperty("forward").GetBoolean()
&& !records[0].GetProperty("data").GetProperty("accepts_input").GetBoolean()
&& records[0].GetProperty("data").GetProperty("accepted_input").ValueKind == JsonValueKind.Null, "requested is distinct from accepted");
Check(records[0].GetProperty("simulation_tick").GetInt32() == 17 && records[0].GetProperty("data").GetProperty("control_owner").GetString() == "script", "owner and simulation tick are separate");
using (var observer = Open("bounded", 1))
{ observer.RecordInput("LV1B", 1, default, true, "Jimmy"); observer.RecordInput("LV1B", 2, default, true, "Jimmy"); observer.Complete(0); }
Check(Events("bounded").Length == 1 && Summary("bounded").GetProperty("incomplete").GetBoolean(), "record limit must mark incomplete");
using (var observer = Open("failure", sink: new BrokenWriter()))
{ observer.RecordInput("LV1B", 1, default, true, "Jimmy"); observer.Complete(0); }
Check(Summary("failure").GetProperty("incomplete").GetBoolean(), "write error must not escape or claim completion");
var disposed = Open("disposed"); disposed.Dispose(); disposed.Dispose(); disposed.RecordInput("LV1B", 1, default, true, "Jimmy");
Check(Summary("disposed").GetProperty("incomplete").GetBoolean(), "disposal without completion remains incomplete and idempotent");
Check(!Summary("identity").GetProperty("incomplete").GetBoolean(), "successful flush and complete");
var rejected = false;
try { using var duplicate = Open("identity"); } catch (IOException) { rejected = true; }
Check(rejected, "existing sessions cannot be overwritten");
using (var observer = Open("continuation"))
{
observer.RecordSceneEntry("LV1B", 0, false, false, "tsk-story");
observer.RecordControl("LV1B", 0, false, null, true, "Carl", "owner_snapshot");
observer.RecordInput("LV1B", 1, new(true, false, false, false, false), false, "script");
observer.RecordControl("LV1B", 1, true, "Jimmy", false, null, "director_step");
observer.RecordInput("LV1B", 2, default, true, "Jimmy");
observer.RecordTransition("LV1B", "VR04.gam", 2, false);
observer.RecordSceneEntry("VR04", 0, false, true, "retained");
observer.RecordControl("VR04", 0, false, null, true, "Intro", "owner_snapshot");
observer.RecordControl("VR04", 0, true, "Jimmy", false, null, "skip:test");
observer.RecordTransition("VR04", "LV1B.gam", 0, true);
observer.RecordSceneEntry("LV1B", 0, true, true, "retained");
observer.Complete(0);
}
var continuation = Events("continuation");
Check(continuation.Any(e => e.GetProperty("name").GetString() == "dialogue_end" && e.GetProperty("method").GetString() == "natural_director_step"), "natural completion has actual director-step method");
Check(continuation.Any(e => e.GetProperty("name").GetString() == "dialogue_skip" && e.GetProperty("method").GetString() == "skip:test"), "skip is an explicit action path");
Check(continuation.Where(e => e.GetProperty("name").GetString() == "input_step").Last().GetProperty("data").GetProperty("accepted_input").GetProperty("forward").GetBoolean() == false, "first accepted neutral is copied without mutation");
Check(continuation.Select(e => e.GetProperty("sequence").GetInt64()).SequenceEqual(Enumerable.Range(1, continuation.Length).Select(i => (long)i)), "ordered transitions share sequence");
Check(continuation.Last().GetProperty("scene").GetString() == "LV1B" && continuation.Last().GetProperty("data").GetProperty("returning").GetBoolean(), "RETURN and arrival remain paired");
Check(continuation.Zip(continuation.Skip(1)).All(p => p.First.GetProperty("elapsed_seconds").GetDouble() <= p.Second.GetProperty("elapsed_seconds").GetDouble()), "clock survives scene tick reset");
using (var fresh = FidelityObservation.Create(Path.Combine(root, "fresh"), "independent-session", "fresh-natural-ordinary", "port_fixture", ".", Path.Combine(root, "Original")))
{ fresh.RecordSceneEntry("LV1B", 0, false, false, "fresh-direct-scene"); fresh.Complete(0); }
Check(Events("fresh")[0].GetProperty("clock_id").GetString() != continuation[0].GetProperty("clock_id").GetString()
&& Events("fresh")[0].GetProperty("simulation_tick").GetInt32() == 0 && !Summary("fresh").GetProperty("incomplete").GetBoolean(), "fresh observer owns independent clock from scene ticks");
rejected = false;
try { using var invalid = FidelityObservation.Create(Path.Combine(root, "Original", "unsafe"), "safe", "case", "port_fixture", ".", Path.Combine(root, "Original")); } catch (ArgumentException) { rejected = true; }
Check(rejected && !Directory.Exists(Path.Combine(root, "Original")), "original overlap rejected before write");
using (var failedFlush = Open("flush", sink: new FlushFailureWriter())) { failedFlush.RecordInput("LV1B", 1, default, true, "Jimmy"); failedFlush.Complete(0); }
Check(Summary("flush").GetProperty("incomplete").GetBoolean(), "flush failure cannot claim success");
Check(continuation.Where(e => e.GetProperty("name").GetString() == "scene_entry").Skip(1)
.All(e => continuation.Any(d => d.GetProperty("name").GetString() == "scene_departure"
&& d.GetProperty("sequence").GetInt64() == e.GetProperty("data").GetProperty("departure_sequence").GetInt64())), "arrival links actual departure sequence");
if (!OperatingSystem.IsWindows())
{
Directory.CreateDirectory(Path.Combine(root, "Original"));
Directory.CreateSymbolicLink(Path.Combine(root, "asset-alias"), Path.Combine(root, "Original"));
rejected = false;
try { using var invalid = FidelityObservation.Create(Path.Combine(root, "Original", "unsafe"), "safe", "case", "port_fixture", ".", Path.Combine(root, "asset-alias")); } catch (ArgumentException) { rejected = true; }
Check(rejected && !Directory.Exists(Path.Combine(root, "Original", "unsafe")), "asset aliases cannot bypass original containment");
rejected = false;
try { using var invalid = FidelityObservation.Create(Path.Combine(root, "asset-alias", "unsafe"), "safe", "case", "port_fixture", ".", Path.Combine(root, "unrelated")); } catch (ArgumentException) { rejected = true; }
Check(rejected, "output cannot traverse symbolic-link ancestors");
}
var positions = new[] { new Vector3(-100000, 0, -100000), new Vector3(-100000, 0, 100000), new Vector3(100000, 0, 100000),
new Vector3(-100000, 0, -100000), new Vector3(100000, 0, 100000), new Vector3(100000, 0, -100000) };
var floor = new Mesh(positions.Select(p => new MeshVertex(p, Vector2.Zero, Vector3.One)).ToArray(), [0, 1, 2, 3, 4, 5]);
var standing = new Mesh([new(new(-20, -20, -20), Vector2.Zero, Vector3.One), new(new(20, 80, 20), Vector2.Zero, Vector3.One)], []);
var off = new LabSimulation(new SceneCollision(floor), standing, new Vector3(0, 25, 0), 0f);
var failed = new LabSimulation(new SceneCollision(floor), standing, new Vector3(0, 25, 0), 0f);
using (var observer = Open("failed-simulation", sink: new BrokenWriter()))
{
for (var tick = 0; tick < 120; tick++)
{
var input = new PlayerInput(tick < 80, false, tick > 15 && tick < 45, false, tick < 20);
off.Step(input); failed.Step(input);
observer.RecordInput("fixture-floor", failed.Steps, input, true, "Jimmy");
observer.RecordState("fixture-floor", failed.Steps, failed.ActorRoot, failed.Rotation, failed.Velocity,
failed.Grounded, failed.MovementMode, failed.InputAfterPlayerUpdate, failed.ControllerSteps, failed.PhysicsSteps, failed.EffectSteps);
}
observer.Complete(0);
}
Check(off.ActorRoot == failed.ActorRoot && off.Rotation == failed.Rotation && off.Velocity == failed.Velocity
&& off.Steps == failed.Steps && off.ControllerSteps == failed.ControllerSteps && off.PhysicsSteps == failed.PhysicsSteps
&& off.EffectSteps == failed.EffectSteps && Summary("failed-simulation").GetProperty("incomplete").GetBoolean(),
"write failure preserves actual 120-step movement/body/effect state exactly");
Console.WriteLine($"Fidelity observation checks: {checks} passed");
}
finally { Directory.Delete(root, true); }
sealed class BrokenWriter : StringWriter
{
public override void WriteLine(string? value) => throw new IOException("deliberate output failure");
}
sealed class FlushFailureWriter : StringWriter
{
protected override void Dispose(bool disposing) => throw new IOException("deliberate flush failure");
}
+272
View File
@@ -0,0 +1,272 @@
import nodeTest from 'node:test';
import assert from 'node:assert/strict';
import {existsSync} from 'node:fs';
let declared = 0;
function test(name, action) { declared++; return nodeTest(name, action); }
const modulePath = new URL('../tools/recon/fidelity_viewer/viewer.mjs', import.meta.url);
const api = existsSync(modulePath) ? await import(modulePath) : {};
class Media extends EventTarget {
currentTime = 0; duration = 20; playbackRate = 1; muted = false; volume = 1;
readyState = 4; paused = true; ended = false; seeking = false; error = null;
failPlay = false;
pause() { this.paused = true; }
async play() { if (this.failPlay) throw Error('blocked'); this.paused = false; }
emit(name) { this.dispatchEvent(new Event(name)); }
}
function pair() {
assert.equal(typeof api.createPairController, 'function', 'paired media controller must exist');
const original = new Media(), port = new Media();
const controller = api.createPairController({original, port});
return {original, port, controller};
}
const marker = {name: 'landing', original: {media_seconds: 2, elapsed_seconds: 2, uncertainty_seconds: .02},
port: {media_seconds: 3, elapsed_seconds: 3.2, uncertainty_seconds: .03}};
test('event selection seeks independent observed times and waits for explicit play', async () => {
const {controller, original, port} = pair();
await controller.selectEvent(marker);
assert.equal(original.currentTime, 2); assert.equal(port.currentTime, 3);
assert.ok(original.paused && port.paused);
await controller.play();
assert.equal(original.playbackRate, 1); assert.equal(port.playbackRate, 1);
assert.ok(!original.paused && !port.paused);
});
test('invalid or unmatched event cannot seek either recording', async () => {
const {controller, original} = pair();
for (const invalid of [{...marker, port: null}, {...marker, original: {...marker.original, media_seconds: Infinity}},
{...marker, port: {...marker.port, media_seconds: 99}}]) {
await assert.rejects(controller.selectEvent(invalid));
assert.equal(original.currentTime, 0);
}
});
test('play rejection pauses both and names the cause', async () => {
const {controller, original, port} = pair(); port.failPlay = true;
assert.equal(await controller.play(), false);
assert.ok(original.paused && port.paused);
assert.match(controller.snapshot().problem, /play.*blocked/i);
});
test('relative artifact links reject remote and active URL schemes', () => {
assert.equal(typeof api.safeLocalURL, 'function');
assert.equal(api.safeLocalURL('sides/port/trace.json'), 'sides/port/trace.json');
for (const value of ['https://host/x', 'javascript:alert(1)', '//host/x', '../x', '/etc/passwd', '%2e%2e/x'])
assert.throws(() => api.safeLocalURL(value));
});
test('capability navigation is supplied through a renderer', () => {
assert.equal(typeof api.renderCapabilities, 'function');
});
test('raw elapsed, event drift and playback drift are distinct', async () => {
const {controller, original, port} = pair();
await controller.selectEvent(marker);
original.currentTime = 5; port.currentTime = 6.25;
const s = controller.snapshot();
assert.equal(s.sides.original.recording_seconds, 5);
assert.equal(s.sides.port.recording_seconds, 6.25);
assert.equal(s.sides.original.aligned_elapsed, 3);
assert.equal(s.sides.port.aligned_elapsed, 3.25);
assert.ok(Math.abs(s.eventDrift.seconds - 1.2) < 1e-9);
assert.equal(s.eventDrift.uncertainty_seconds, .05);
assert.equal(s.playbackDrift, .25);
});
test('no selected event means no invented drift', () => {
const {controller} = pair();
assert.equal(controller.snapshot().eventDrift, null);
assert.equal(controller.snapshot().playbackDrift, null);
});
test('exclusive soundtrack switch mutes both before selecting one', () => {
const {controller, original, port} = pair();
assert.ok(original.muted && port.muted);
controller.setAudio('original');
assert.ok(!original.muted && port.muted);
controller.setAudio('port');
assert.ok(original.muted && !port.muted);
controller.setAudio('none');
assert.ok(original.muted && port.muted);
assert.throws(() => controller.setAudio('external'));
});
test('gain is unadjusted by default and visibly review-only when changed', () => {
const {controller, original, port} = pair();
assert.equal(controller.snapshot().gain, 1);
assert.equal(controller.snapshot().gainAdjusted, false);
controller.setGain(.4);
assert.equal(original.volume, .4); assert.equal(port.volume, .4);
assert.equal(controller.snapshot().gainAdjusted, true);
assert.match(controller.snapshot().gainLabel, /review-only/i);
for (const value of [-1, 2, NaN]) assert.throws(() => controller.setGain(value));
});
test('buffering pauses both; explicit recovered play stays at rate one', async () => {
const {controller, original, port} = pair();
await controller.play(); port.readyState = 2; port.emit('waiting');
assert.ok(original.paused && port.paused);
assert.match(controller.snapshot().problem, /port.*buffer/i);
assert.equal(await controller.play(), false);
port.readyState = 4; port.emit('canplay');
assert.ok(original.paused && port.paused, 'readiness must not auto-resume');
assert.equal(await controller.play(), true);
assert.equal(port.playbackRate, 1);
});
test('decode failure is visible and blocks play', async () => {
const {controller, original, port} = pair();
port.error = {code: 3}; port.emit('error');
assert.ok(original.paused && port.paused);
assert.match(controller.snapshot().problem, /port.*decod/i);
assert.equal(await controller.play(), false);
});
test('missing media blocks pair but preserves manual available-side playback', async () => {
const port = new Media();
const controller = api.createPairController({original: null, port});
assert.equal(await controller.play(), false);
assert.match(controller.snapshot().problem, /missing/i);
assert.equal(await controller.playSide('port'), true);
assert.equal(controller.snapshot().sides.original.state, 'missing');
});
test('asymmetric end pauses pair and allows the complete longer tail', async () => {
const {controller, original, port} = pair();
await controller.play(); original.currentTime = original.duration; original.ended = true;
original.emit('ended');
assert.ok(port.paused);
assert.match(controller.snapshot().problem, /tail/i);
assert.equal(await controller.play(), true);
assert.equal(original.currentTime, 20); assert.ok(!port.paused);
port.currentTime = port.duration; port.ended = true; port.emit('ended');
assert.equal(await controller.play(), false);
});
test('manual play and seek never force the other recording to follow', async () => {
const {controller, original, port} = pair();
await controller.selectEvent(marker);
assert.equal(await controller.playSide('port'), true);
assert.ok(original.paused && !port.paused);
await controller.seekSide('port', 8);
assert.equal(original.currentTime, 2); assert.equal(port.currentTime, 8);
assert.ok(original.paused && port.paused);
});
test('external rate changes are corrected to actual speed without seeking', () => {
const {controller, original, port} = pair();
original.currentTime = 7; port.currentTime = 9;
port.playbackRate = 1.5; port.emit('ratechange');
assert.equal(port.playbackRate, 1);
assert.equal(port.currentTime, 9); assert.equal(original.currentTime, 7);
controller.pause();
});
test('event selection waits for asynchronous metadata and seek readiness', async () => {
const original = new Media(), port = new Media(); original.readyState = port.readyState = 0;
let t = 0;
Object.defineProperty(port, 'currentTime', {get: () => t, set: value => {
t = value; port.seeking = true;
setTimeout(() => {port.seeking = false; port.emit('seeked');}, 5);
}});
const controller = api.createPairController({original, port, timeoutMs: 100});
let finished = false;
const seek = controller.selectEvent(marker).then(() => {finished = true;});
await new Promise(resolve => setTimeout(resolve, 2));
assert.equal(finished, false); assert.equal(t, 0);
original.readyState = port.readyState = 4; original.emit('loadedmetadata'); port.emit('loadedmetadata');
await seek;
assert.equal(finished, true); assert.equal(port.currentTime, 3);
assert.ok(original.paused && port.paused);
});
test('seek timeout reports the cause and leaves pair paused', async () => {
const original = new Media(), port = new Media(); port.readyState = 0;
const controller = api.createPairController({original, port, timeoutMs: 10});
await assert.rejects(controller.selectEvent(marker), /readiness|metadata|timed out/i);
assert.match(controller.snapshot().problem, /readiness|metadata|timed out/i);
assert.ok(original.paused && port.paused);
});
test('buffering during a pending play cannot be erased by promise completion', async () => {
const {controller, original, port} = pair();
let release;
port.play = () => new Promise(resolve => { release = () => {port.paused = false; resolve();}; });
const playing = controller.play();
port.readyState = 2; port.emit('waiting'); release();
assert.equal(await playing, false);
assert.ok(original.paused && port.paused);
assert.match(controller.snapshot().problem, /buffer/i);
});
test('overlays start off and unsupported differences explain their gate', () => {
const {controller} = pair();
assert.deepEqual(controller.snapshot().overlays, {annotations: false, difference: false});
controller.setOverlay('annotations', true);
assert.equal(controller.snapshot().overlays.annotations, true);
assert.throws(() => controller.setOverlay('difference', true), /lossless|frame/i);
assert.equal(controller.snapshot().overlays.difference, false);
});
const frame = (sha = 'a'.repeat(64)) => ({url: 'sides/original/still.png', sha256: sha, size: 100,
frame: {lossless: true, event: 'landing', media_sha256: 'b'.repeat(64), media_seconds: 2,
viewport: [640, 480], crop: [0, 0, 640, 480], width: 640, height: 480}});
test('lossless differences need matched frame event viewport aspect and crop', () => {
assert.equal(typeof api.differenceEligibility, 'function');
const a = frame(), b = frame('c'.repeat(64));
assert.equal(api.differenceEligibility(a, b).eligible, true);
for (const patch of [{viewport: [800, 600]}, {crop: [1, 0, 639, 480]},
{event: 'jump'}, {lossless: false}, {media_sha256: null}]) {
const result = api.differenceEligibility(a, {...b, frame: {...b.frame, ...patch}});
assert.equal(result.eligible, false);
assert.ok(result.reason.length);
}
});
test('nonfinite elapsed or uncertainty is rejected before seeking', async () => {
const {controller, original} = pair();
for (const patch of [{elapsed_seconds: NaN}, {uncertainty_seconds: -1}])
await assert.rejects(controller.selectEvent({...marker, original: {...marker.original, ...patch}}));
assert.equal(original.currentTime, 0);
});
class Node {
children = []; textContent = '';
constructor(tag, ownerDocument) { this.tag = tag; this.ownerDocument = ownerDocument; }
append(...items) { this.children.push(...items); }
replaceChildren(...items) { this.children = items; }
get text() { return this.textContent + this.children.map(c => c.text).join(' '); }
}
test('capability renderer preserves facts, impact order, history and inert hostile text', () => {
const doc = {createElement: tag => new Node(tag, doc)};
const container = new Node('section', doc);
api.renderCapabilities(container, {capabilities: [{id: 'move', group: 'movement',
summary: '<script>malicious()</script>', requirement_ids: ['MOVE-01'],
verified_scope: 'bounded fixture', differences: ['unverified'], acceptance: {state: 'open'},
source_links: ['javascript:bad()'], scenario_ids: ['case-a'], current: ['native receipt'],
history: [{superseded: true, revision: 'old'}],
discrepancies: [{id: 'b', impact: 'subtle'}, {id: 'a', impact: 'blocking'}]}]});
assert.match(container.text, /<script>malicious\(\)<\/script>/);
assert.match(container.text, /MOVE-01/); assert.match(container.text, /superseded/);
assert.ok(container.text.indexOf('blocking') < container.text.indexOf('subtle'));
assert.ok(container.children.some(c => c.children?.some(n => n.tag === 'details')));
assert.equal(container.children.some(c => c.tag === 'script'), false);
});
test('empty capability export has an explicit open state', () => {
const doc = {createElement: tag => new Node(tag, doc)};
const container = new Node('section', doc);
api.renderCapabilities(container, {capabilities: []});
assert.match(container.text, /No capability ledger supplied.*open/);
});
test('percent-encoded local filenames remain inert and usable', () => {
assert.equal(api.safeLocalURL('sides/port/frame%20one%23.png'), 'sides/port/frame%20one%23.png');
assert.throws(() => api.safeLocalURL('sides/port/frame.png?redirect=http://host'));
});
test('difference frame must match its own observed source event and timestamp', () => {
const a = frame(), b = frame('c'.repeat(64));
const side = artifact => ({media: {path: 'video.webm', sha256: 'b'.repeat(64), duration_seconds: 10},
artifacts: [artifact], events: [{name: 'landing', artifact: 'video.webm', media_seconds: 2}]});
const model = {sides: {original: side(a), port: side(b)}};
assert.equal(api.framePair(model).port, b);
model.sides.port.events[0].media_seconds = 3;
assert.equal(api.framePair(model).port, undefined);
model.sides.port.events[0].media_seconds = 2;
model.sides.port.media.sha256 = 'd'.repeat(64);
assert.equal(api.framePair(model).port, undefined);
});
test('a newer event seek supersedes pending metadata without cancelling the newer action', async () => {
const original = new Media(), port = new Media(); original.readyState = port.readyState = 0;
const controller = api.createPairController({original, port, timeoutMs: 100});
const old = controller.selectEvent(marker).catch(error => error);
const next = {...marker, name: 'idle', original: {...marker.original, media_seconds: 4}, port: {...marker.port, media_seconds: 5}};
const recent = controller.selectEvent(next);
original.readyState = port.readyState = 4; original.emit('loadedmetadata'); port.emit('loadedmetadata');
assert.match((await old).message, /cancelled/);
await recent;
assert.equal(original.currentTime, 4); assert.equal(port.currentTime, 5);
assert.equal(controller.snapshot().selected.name, 'idle');
assert.equal(controller.snapshot().selecting, false);
assert.equal(await controller.play(), true);
});
test('suite executes at least sixteen registered behavior tests', () => {
assert.ok(declared >= 16, 'runner must register at least sixteen tests');
});
+222
View File
@@ -0,0 +1,222 @@
# Package-free selftests. All bytes/processes are synthetic tooling fixtures.
# Run with Windows PowerShell 5.1 or pwsh; Linux pwsh is NOT Windows evidence.
[CmdletBinding()]
param([string]$FixtureOutput)
Set-StrictMode -Version 2
$ErrorActionPreference = 'Stop'
$collector = Join-Path (Split-Path -Parent $PSScriptRoot) 'scripts/collect-fidelity-windows.ps1'
. $collector -LibraryOnly
$temporary = Join-Path ([IO.Path]::GetTempPath()) ('fidelity-selftest-' + [guid]::NewGuid().ToString('N'))
$null = [IO.Directory]::CreateDirectory($temporary)
$script:Checks = 0
function Assert-True($Condition, [string]$Message) { if (-not $Condition) { throw $Message } }
function Assert-Throws([scriptblock]$Body) {
$thrown = $false
try { & $Body | Out-Null } catch { $thrown = $true }
Assert-True $thrown 'Expected rejection did not occur'
}
function Check([string]$Name, [scriptblock]$Body) {
& $Body
$script:Checks++
Write-Host "PASS $Name"
}
function Fixture-File([string]$Name, [string]$Content) {
$path = Join-Path $temporary $Name
$null = [IO.Directory]::CreateDirectory([IO.Path]::GetDirectoryName($path))
[IO.File]::WriteAllText($path,$Content,(New-Object Text.UTF8Encoding($false)))
return $path
}
try {
Check 'stable IDs reject reserved/path aliases' {
Assert-True ((Test-FidelityId 'session-01') -eq 'session-01') 'ID changed'
foreach ($bad in @('../x','CON','a/b','NUL.txt','')) { Assert-Throws { Test-FidelityId $bad } }
}
Check 'paths reject traversal, drive paths and Windows aliases' {
foreach ($bad in @('../x','a//x','C:/x','/x','a\x','aux.txt','a./x','a /x')) {
Assert-Throws { Get-FidelityPath $temporary $bad }
}
Assert-True ((Get-FidelityPath $temporary 'space dir/a.txt').StartsWith($temporary)) 'Contained path missing'
}
$sample = Fixture-File 'sample.txt' 'abc'
Check 'streamed SHA256 and size match actual bytes' {
$id = Get-FidelityIdentity $sample
Assert-True ($id.size -eq 3 -and $id.sha256 -eq 'ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad') 'Wrong identity'
}
Check 'copies preserve bytes and never overwrite evidence' {
$id = Copy-FidelityEvidence $sample $temporary 'copied/space name.txt'
Assert-True ($id.sha256 -eq (Get-FidelityIdentity $sample).sha256) 'Copy differs'
Assert-Throws { Copy-FidelityEvidence $sample $temporary 'copied/space name.txt' }
}
Check 'JSON keeps empty arrays, Unicode, singleton arrays and write-once results' {
$path = Join-Path $temporary 'json.json'
Write-FidelityJson $path @{empty=@();single=@('one');text='café'}
$value = Read-FidelityJson $path
Assert-True ($value.empty -is [array] -and $value.empty.Count -eq 0) 'Empty list lost'
Assert-True ($value.single -is [array] -and $value.single.Count -eq 1 -and $value.text -eq 'café') 'JSON changed'
Assert-Throws { Write-FidelityJson $path @{} }
$path2 = Join-Path $temporary 'empty.json'
Write-FidelityJson $path2 @()
Assert-True ([IO.File]::ReadAllText($path2).Trim() -eq '[]') 'Top-level empty list lost'
}
Check 'argument quoting preserves empty/spaces/quotes/trailing backslashes' {
Assert-True ((ConvertTo-FidelityArgument '') -ceq '""') 'Empty quoting'
Assert-True ((ConvertTo-FidelityArgument 'a b') -ceq '"a b"') 'Space quoting'
Assert-True ((ConvertTo-FidelityArgument 'a"b') -ceq '"a\"b"') 'Quote escaping'
Assert-True ((ConvertTo-FidelityArgument 'C:\space dir\') -ceq '"C:\space dir\\"') 'Trailing slash escaping'
Assert-Throws { ConvertTo-FidelityArgument "bad`nargument" }
}
$hostExe = [Diagnostics.Process]::GetCurrentProcess().MainModule.FileName
$child = Fixture-File 'child space.ps1' 'param([string]$Value) [Console]::Out.Write($Value); [Console]::Error.Write("child stderr"); exit 7'
Check 'real child arguments, logs and nonzero exit remain distinct from success' {
$logs = Join-Path $temporary 'process'
$null = [IO.Directory]::CreateDirectory($logs)
$result = Invoke-FidelityProcess $hostExe @('-NoProfile','-File',$child,'value with spaces') $temporary $logs 30
Assert-True ($result.exit_code -eq 7 -and $result.elapsed_seconds -ge 0) 'Exit result changed'
Assert-True ([IO.File]::ReadAllText((Join-Path $logs 'stdout.txt')) -ceq 'value with spaces') 'Arguments not preserved'
Assert-True ([IO.File]::ReadAllText((Join-Path $logs 'stderr.txt')) -ceq 'child stderr') 'Stderr missing'
}
Check 'process waits are bounded and timeout preserves logs' {
$sleeper = Fixture-File 'sleep.ps1' 'Start-Sleep -Seconds 30'
$logs = Join-Path $temporary 'timeout'
$null = [IO.Directory]::CreateDirectory($logs)
Assert-Throws { Invoke-FidelityProcess $hostExe @('-NoProfile','-File',$sleeper) $temporary $logs 1 }
Assert-True (Test-Path -LiteralPath (Join-Path $logs 'stdout.txt')) 'Timeout logs lost'
Assert-Throws { Invoke-FidelityProcess $hostExe @() $temporary $logs 0 }
}
Check 'failed process start produces original exception without unstarted process access' {
$notExe = Fixture-File 'not-executable.bin' 'synthetic non executable'
$logs = Join-Path $temporary 'bad-process'
$null = [IO.Directory]::CreateDirectory($logs)
Assert-Throws { Invoke-FidelityProcess $notExe @() $temporary $logs 1 }
}
Check 'failure skip abort cannot become captured and require reasons' {
foreach ($state in @('failed','skipped','aborted')) {
Assert-True ((Get-FidelityOutcome 'incomplete' $state 'observed reason') -eq $state) 'Outcome changed'
Assert-Throws { Get-FidelityOutcome $state 'captured' '' }
Assert-Throws { Get-FidelityOutcome 'incomplete' $state '' }
}
}
Check 'result categories and open acceptance remain explicit' {
foreach ($kind in @('native_port','original_dxwnd','synthetic')) {
$r = New-FidelityReceipt 'selftest' 'fresh-natural-ordinary' 'continuous' $kind 'incomplete' @{} @{} 'fixture'
Assert-True ($r.evidence_kind -eq $kind -and $r.acceptance.state -eq 'open' -and $r.missing_evidence.Count -gt 0) 'False acceptance'
}
Assert-Throws { New-FidelityReceipt 'selftest' 'case' 'continuous' 'wine-as-native' 'captured' @{} @{} '' }
}
$bundleRoot = Join-Path $temporary 'bundle'
$null = [IO.Directory]::CreateDirectory((Join-Path $bundleRoot 'protocol'))
$material = Fixture-File 'bundle/protocol/test.txt' 'synthetic immutable material'
$entry = Get-FidelityIdentity $material; $entry.path = 'protocol/test.txt'
Write-FidelityJson (Join-Path $bundleRoot 'manifest.json') @{schema_version=1;tooling_only=$true;mutable_roots=@('results','original-runs');files=@($entry)}
Write-FidelityJson (Join-Path $bundleRoot 'READY.json') @{schema_version=1;status='prepared';manifest=(Get-FidelityIdentity (Join-Path $bundleRoot 'manifest.json'))}
Check 'prepared bundle validates immutable bytes and permits only declared mutable roots' {
$null = Test-FidelityBundle $bundleRoot
$null = Fixture-File 'bundle/results/local-result.txt' 'diagnostic'
$null = Test-FidelityBundle $bundleRoot
$extra = Fixture-File 'bundle/unlisted.txt' 'unexpected'
Assert-Throws { Test-FidelityBundle $bundleRoot }
[IO.File]::Delete($extra)
}
Check 'tampered immutable bytes fail preflight' {
[IO.File]::AppendAllText($material,'tampered')
Assert-Throws { Test-FidelityBundle $bundleRoot }
[IO.File]::WriteAllText($material,'synthetic immutable material',(New-Object Text.UTF8Encoding($false)))
}
$script:Bundle = $bundleRoot
$script:SessionId = 'fixture-finish'
$run = Join-Path $bundleRoot 'results/fixture-finish'
$null = [IO.Directory]::CreateDirectory($run)
$clock = @{wall_start=[DateTime]::UtcNow.ToString('o');wall_end=[DateTime]::UtcNow.ToString('o');monotonic_start=0;monotonic_end=2}
$r = New-FidelityReceipt $SessionId 'fresh-natural-ordinary' 'continuous' 'synthetic' 'incomplete' @{os='test';execution='synthetic'} $clock 'Tooling-only synthetic fixture'
Write-FidelityJson (Join-Path $run 'run.json') $r
$script:ArtifactsDirectory = Join-Path $temporary 'media'
$null = Fixture-File 'media/raw.mkv' 'synthetic video bytes, no gameplay'
$null = Fixture-File 'media/audio.wav' 'synthetic audio bytes, no gameplay'
$script:AnnotationPath = Join-Path $temporary 'annotations.json'
$annotation = @{schema_version=1;artifacts=@(@{path='raw.mkv';role='video';duration_seconds=2},@{path='audio.wav';role='audio';duration_seconds=2});events=@(@{name='startup';artifact='raw.mkv';media_seconds=0;elapsed_seconds=0;method='manual';uncertainty_seconds=0.1});derivatives=@();limitations=@('synthetic tooling only');continuity=@{prerequisite_artifact='raw.mkv'}}
$script:Outcome = 'captured'
Check 'capture rejects an empty annotation before any media copy' {
Write-FidelityJson $AnnotationPath @{schema_version=1;artifacts=@();events=@();derivatives=@();limitations=@()}
Assert-Throws { Complete-FidelityRun }
Assert-True (-not (Test-Path -LiteralPath (Join-Path $run 'media'))) 'Invalid annotation copied data'
[IO.File]::Delete($AnnotationPath)
}
Check 'capture rejects synthetic promotion and missing event targets before writes' {
$annotation.artifacts[0].synthetic = $true
Write-FidelityJson $AnnotationPath $annotation
Assert-Throws { Complete-FidelityRun }
[IO.File]::Delete($AnnotationPath)
$annotation.artifacts[0].Remove('synthetic')
$annotation.events[0].artifact = 'absent.mkv'
Write-FidelityJson $AnnotationPath $annotation
Assert-Throws { Complete-FidelityRun }
[IO.File]::Delete($AnnotationPath)
$annotation.events[0].artifact = 'raw.mkv'
}
Check 'finish maps hashed media/event/continuity paths and preserves synthetic category' {
Write-FidelityJson $AnnotationPath $annotation
Complete-FidelityRun
$result = Read-FidelityJson (Join-Path $run 'receipt.json')
Assert-True ($result.status -eq 'captured' -and $result.evidence_kind -eq 'synthetic' -and $result.acceptance.state -eq 'open') 'Fixture promoted'
Assert-True ($result.artifacts.Count -eq 3 -and $result.events[0].artifact -eq 'media/raw.mkv' -and $result.continuity.prerequisite_artifact -eq 'media/raw.mkv') 'Broken result links'
Assert-True ($result.artifacts[0].sha256 -eq (Get-FidelityIdentity (Join-Path $run 'media/raw.mkv')).sha256) 'Media identity differs'
Assert-Throws { Complete-FidelityRun }
}
Check 'terminal failed skipped aborted results retain empty artifact lists and cannot be promoted' {
foreach ($state in @('failed','skipped','aborted')) {
$script:SessionId = 'fixture-' + $state
$terminalRun = Join-Path $bundleRoot ('results/' + $SessionId)
$null = [IO.Directory]::CreateDirectory($terminalRun)
$terminal = New-FidelityReceipt $SessionId 'fresh-natural-ordinary' 'continuous' 'synthetic' $state @{os='test';execution='synthetic'} $clock 'synthetic terminal fixture'
Write-FidelityJson (Join-Path $terminalRun 'run.json') $terminal
$script:AnnotationPath = Join-Path $temporary ($state + '-notes.json')
Write-FidelityJson $AnnotationPath @{schema_version=1;artifacts=@();events=@();derivatives=@();limitations=@('synthetic tooling only')}
$script:Outcome = $state; $script:Reason = 'Tooling fixture; no actual capture'
Complete-FidelityRun
$saved = Read-FidelityJson (Join-Path $terminalRun 'receipt.json')
Assert-True ($saved.status -eq $state -and $saved.artifacts.Count -eq 1 -and $saved.events -is [array] -and $saved.events.Count -eq 0 -and $saved.acceptance.state -eq 'open') 'Terminal fixture changed'
}
}
Check 'incomplete-only interrupted recovery preserves launch bytes and absent end clocks' {
$script:SessionId = 'fixture-interrupted'
$interruptedRun = Join-Path $bundleRoot ('results/' + $SessionId)
$null = [IO.Directory]::CreateDirectory($interruptedRun)
$initial = New-FidelityReceipt $SessionId 'fresh-natural-ordinary' 'continuous' 'synthetic' 'incomplete' @{os='test';execution='synthetic'} $clock 'Interrupted synthetic collector'
Write-FidelityJson (Join-Path $interruptedRun 'incomplete.json') $initial
$before = Get-FidelityIdentity (Join-Path $interruptedRun 'incomplete.json')
$script:AnnotationPath = Join-Path $temporary 'interrupted-notes.json'
Write-FidelityJson $AnnotationPath @{schema_version=1;artifacts=@(@{path='raw.mkv';role='video';duration_seconds=2});events=@();derivatives=@();limitations=@('Recovered synthetic media only')}
$script:Reason = 'Interrupted before final collector state'
$script:Outcome = 'captured'
Assert-Throws { Complete-FidelityRun }
Assert-True (-not (Test-Path -LiteralPath (Join-Path $interruptedRun 'receipt.json'))) 'Interrupted record promoted'
$script:Outcome = 'aborted'
[IO.File]::Delete($AnnotationPath)
Write-FidelityJson $AnnotationPath @{schema_version=1;artifacts=@();events=@(@{name='invented';artifact='raw.mkv';elapsed_seconds=1});derivatives=@();limitations=@()}
Assert-Throws { Complete-FidelityRun }
Assert-True (-not (Test-Path -LiteralPath (Join-Path $interruptedRun 'recovery-initial.json'))) 'Invalid recovery wrote evidence'
[IO.File]::Delete($AnnotationPath)
Write-FidelityJson $AnnotationPath @{schema_version=1;artifacts=@(@{path='raw.mkv';role='video';duration_seconds=2});events=@();derivatives=@();limitations=@('Recovered synthetic media only')}
Complete-FidelityRun
$saved = Read-FidelityJson (Join-Path $interruptedRun 'receipt.json')
Assert-True ($saved.status -eq 'aborted' -and $saved.acceptance.state -eq 'open' -and $saved.session_id -ceq $SessionId) 'Recovery changed launch/status'
Assert-True ($saved.clocks.PSObject.Properties.Name -notcontains 'wall_end' -and $saved.clocks.PSObject.Properties.Name -notcontains 'monotonic_end') 'Recovery invented end clocks'
$rawInitial = Read-FidelityJson (Join-Path $interruptedRun 'incomplete.json')
Assert-True ($saved.clocks.wall_start -eq $rawInitial.clocks.wall_start -and $saved.clocks.monotonic_start -eq $rawInitial.clocks.monotonic_start) 'Recovery changed initial clocks'
Assert-True ((Get-FidelityIdentity (Join-Path $interruptedRun 'incomplete.json')).sha256 -eq $before.sha256) 'Recovery changed raw initial bytes'
Assert-True ($saved.artifacts[0].path -eq 'recovery-initial.json' -and $saved.artifacts[0].sha256 -eq $before.sha256) 'Missing raw initial identity'
Assert-True (Test-Path -LiteralPath (Join-Path $interruptedRun 'media/raw.mkv')) 'Missing recovered media'
Assert-Throws { Complete-FidelityRun }
}
if ($FixtureOutput) {
if (Test-Path -LiteralPath $FixtureOutput) { throw 'Fixture output must be new' }
$null = [IO.Directory]::CreateDirectory($FixtureOutput)
foreach ($item in Get-ChildItem -LiteralPath (Join-Path $bundleRoot 'results') -Directory) {
Copy-Item -LiteralPath $item.FullName -Destination $FixtureOutput -Recurse
}
}
Assert-True ($script:Checks -ge 8) 'Fewer than eight executed checks'
Write-Host "PASS: $script:Checks checks; 0 failures; synthetic tooling only; native Windows/original gameplay acceptance OPEN"
} finally {
if (Test-Path -LiteralPath $temporary) { Remove-Item -LiteralPath $temporary -Recurse -Force }
}
+236
View File
@@ -0,0 +1,236 @@
"""Quota policy and recovery tests; no model calls or quota consumption."""
import contextlib
import io
import json
from pathlib import Path
import struct
import tempfile
import unittest
from unittest.mock import patch
from tools.workflow import codex_quota_guard as guard
def limits(used=79, duration=300, reset=2000):
return {'rateLimits': {'primary': {'usedPercent': used, 'windowDurationMins': duration,
'resetsAt': reset}}}
class QuotaTests(unittest.TestCase):
def test_boundary_thresholds(self):
for used, expected in [(0, 'ready'), (79, 'ready'), (80, 'drain'), (84, 'drain'),
(85, 'pause'), (100, 'pause')]:
with self.subTest(used=used):
self.assertEqual(guard.stage(guard.quota(limits(used), 1000), 1000), expected)
def test_actual_window_secondary(self):
data = limits(99, 10080)
data['rateLimits']['secondary'] = limits(40)['rateLimits']['primary']
self.assertEqual(guard.quota(data, 1000)['remaining'], 60)
def test_general_bucket_preferred(self):
data = limits(99)
data['rateLimitsByLimitId'] = {'codex': limits(10)['rateLimits'],
'specialty': limits(100)['rateLimits']}
self.assertEqual(guard.quota(data, 1000)['remaining'], 90)
def test_invalid_windows_never_look_healthy(self):
for data in [limits(50, 10080), limits(50, reset=999), limits(float('nan')),
limits(-1), limits(101), limits(True), {}, {'rateLimits': None}]:
with self.subTest(data=data), self.assertRaises(ValueError):
guard.quota(data, 1000)
def test_stale_and_expired_unknown(self):
sample = guard.quota(limits(), 1000)
self.assertEqual(guard.stage(sample, 1181), 'unknown')
self.assertEqual(guard.stage(dict(sample, checkedAt=1999), 2000), 'unknown')
self.assertEqual(guard.stage(None, 1000), 'unknown')
def test_reset_clears_pause_only_after_fresh_quota(self):
sample = guard.quota(limits(99), 1000)
self.assertEqual(guard.stage(sample, 2000), 'unknown')
fresh = guard.quota(limits(1, reset=20000), 2001)
self.assertEqual(guard.stage(fresh, 2001), 'ready')
def test_worker_denials_leave_checkpoint_tools_available(self):
for used in (80, 85, 100):
sample = guard.quota(limits(used), 1000)
for tool in ('Agent', 'spawn_agent', 'followup_task', 'mcp__local__spawn_agent',
'collaboration.spawn_agent'):
answer = guard.hook_response('PreToolUse', tool, sample, 1000)
self.assertEqual(answer['hookSpecificOutput']['permissionDecision'], 'deny')
for tool in ('Bash', 'apply_patch', 'send_message', 'interrupt_agent'):
answer = guard.hook_response('PreToolUse', tool, sample, 1000)
self.assertNotIn('permissionDecision', answer.get('hookSpecificOutput', {}))
def test_unknown_denies_new_workers(self):
answer = guard.hook_response('PreToolUse', 'spawn_agent', None, 1000)
self.assertEqual(answer['hookSpecificOutput']['permissionDecision'], 'deny')
def test_ready_allows_dispatch(self):
self.assertEqual(guard.hook_response('PreToolUse', 'spawn_agent',
guard.quota(limits(), 1000), 1000), {})
def test_diagnostic_event_does_not_return_context(self):
self.assertEqual(guard.hook_response('PreModelRequest', '',
guard.quota(limits(90), 1000), 1000), {})
class StateTests(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.state = Path(self.temp.name) / 'state'
self.patcher = patch.object(guard, 'STATE', self.state)
self.patcher.start()
self.addCleanup(self.patcher.stop)
def test_atomic_is_private_and_replaces(self):
path = self.state / 'value.json'
guard.atomic(path, {'one': 1})
guard.atomic(path, {'two': 2})
self.assertEqual(guard.read(path), {'two': 2})
self.assertEqual(path.stat().st_mode & 0o777, 0o600)
def test_thread_registration_uses_agent_id(self):
guard.register({'session_id': 'root', 'agent_id': 'child', 'turn_id': 'turn'})
entries = list((self.state / 'threads').glob('*.json'))
self.assertEqual(guard.read(entries[0])['threadId'], 'child')
def test_missing_turn_never_guessed(self):
guard.register({'session_id': 'root'})
self.assertFalse((self.state / 'threads').exists())
def test_context_only_once_per_turn(self):
guard.atomic(self.state / 'quota.json', guard.quota(limits(90), 1000))
payload = {'hook_event_name': 'PostToolUse', 'turn_id': 'turn'}
with patch.object(guard.time, 'time', return_value=1000):
self.assertIn('hookSpecificOutput', guard.handle_hook(payload))
self.assertEqual(guard.handle_hook(payload), {})
payload['turn_id'] = 'next'
self.assertIn('hookSpecificOutput', guard.handle_hook(payload))
def test_only_unambiguous_events_register_thread(self):
with patch.object(guard, 'register') as register:
guard.handle_hook({'hook_event_name': 'PreToolUse', 'session_id': 'root', 'turn_id': 'child'})
register.assert_not_called()
guard.handle_hook({'hook_event_name': 'PreModelRequest', 'session_id': 'root', 'turn_id': 'root-turn'})
register.assert_called_once()
def test_pause_saves_snapshot_and_steers_once(self):
class FakeRPC:
calls = []
def call(self, method, params):
self.calls.append((method, params))
return limits(90)
def close(self):
pass
guard.register({'session_id': 'root', 'turn_id': 'turn'})
with patch.object(guard, 'RPC', FakeRPC), patch.object(guard, 'snapshot') as snapshot, \
patch.object(guard.time, 'time', return_value=1000):
guard.tick()
guard.tick()
self.assertEqual(snapshot.call_count, 2)
steers = [p for m, p in FakeRPC.calls if m == 'turn/steer']
self.assertEqual(len(steers), 1)
self.assertEqual(steers[0]['expectedTurnId'], 'turn')
self.assertEqual(steers[0]['threadId'], 'root')
self.assertFalse(any(m == 'turn/start' for m, _ in FakeRPC.calls))
def test_inactive_turn_is_not_restarted(self):
class FakeRPC:
calls = []
def call(self, method, params):
self.calls.append(method)
if method == 'turn/steer':
raise RuntimeError('inactive')
return limits(90)
def close(self):
pass
guard.register({'session_id': 'root', 'turn_id': 'turn'})
with patch.object(guard, 'RPC', FakeRPC), patch.object(guard, 'snapshot'), \
patch.object(guard.time, 'time', return_value=1000):
guard.tick()
guard.tick()
self.assertEqual(FakeRPC.calls.count('turn/steer'), 1)
self.assertNotIn('turn/start', FakeRPC.calls)
def test_reset_timestamp_jitter_does_not_repeat_pause(self):
class FakeRPC:
steers = 0
reads = 0
def call(self, method, params):
if method == 'turn/steer':
self.steers += 1
return {}
self.reads += 1
return limits(90, reset=2000 + self.reads)
def close(self):
pass
rpc = FakeRPC()
guard.register({'session_id': 'root', 'turn_id': 'turn'})
with patch.object(guard, 'RPC', return_value=rpc), patch.object(guard, 'snapshot'), \
patch.object(guard.time, 'time', return_value=1000):
guard.tick()
guard.tick()
self.assertEqual(rpc.steers, 1)
def test_recovery_preserves_canonical_handoff(self):
project = Path(self.temp.name) / 'project'
(project / '.planning').mkdir(parents=True)
handoff = project / '.planning/HANDOFF.json'
handoff.write_text('{"precise": "continuation"}')
process = unittest.mock.MagicMock()
process.__enter__.return_value = process
process.stdout.read.return_value = b'test git output'
with patch.object(guard, 'ROOT', project), patch.object(guard.subprocess, 'Popen', return_value=process):
guard.snapshot(guard.quota(limits(90), 1000))
guard.snapshot(guard.quota(limits(90, reset=2001), 1000))
self.assertEqual(handoff.read_text(), '{"precise": "continuation"}')
self.assertFalse((self.state / 'recovery-2001').exists())
record = guard.read(self.state / 'recovery-2000/record.json')
self.assertIn('continuation', record['gsd']['.planning/HANDOFF.json'])
class FrameTests(unittest.TestCase):
def rpc(self, data=b''):
rpc = guard.RPC.__new__(guard.RPC)
rpc.sock = unittest.mock.Mock()
rpc.buffer = data
rpc.sequence = 0
return rpc
def test_eof_terminates_instead_of_spinning(self):
rpc = self.rpc()
rpc.sock.recv.return_value = b''
with self.assertRaises(EOFError):
rpc.take(1)
def test_oversize_rejected_before_payload_read(self):
rpc = self.rpc(b'\x81\x7f' + struct.pack('!Q', 2**21))
with self.assertRaises(ValueError):
rpc.message()
rpc.sock.recv.assert_not_called()
def test_ping_and_fragmented_text(self):
rpc = self.rpc(b'\x89\x01x' + b'\x01\x05{"a":' + b'\x80\x021}')
self.assertEqual(rpc.message(), {'a': 1})
rpc.sock.sendall.assert_called_once()
def test_client_masks_outgoing_frames(self):
rpc = self.rpc()
rpc.send({'test': 'value'})
wire = rpc.sock.sendall.call_args.args[0]
self.assertTrue(wire[1] & 128)
mask = wire[2:6]
raw = bytes(c ^ mask[i % 4] for i, c in enumerate(wire[6:]))
self.assertEqual(json.loads(raw), {'test': 'value'})
def test_notifications_skipped_until_matching_response(self):
rpc = self.rpc()
with patch.object(rpc, 'message', side_effect=[{'method': 'notify'}, {'id': 1, 'result': {'ok': True}}]):
self.assertEqual(rpc.call('test', {}), {'ok': True})
if __name__ == '__main__':
unittest.main()
+323
View File
@@ -0,0 +1,323 @@
"""Acceptance metadata doubles are synthetic tests, never runtime proof."""
import copy
import hashlib
import importlib
import json
from pathlib import Path
import subprocess
import sys
import unittest
from unittest import mock
import test_fidelity_scenarios
import test_fidelity_checkpoint
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tools/recon'))
import fidelity_receipts as receipts
from fidelity_review import export_review
try:
acceptance = importlib.import_module('fidelity_acceptance')
except ModuleNotFoundError:
acceptance = None
class AcceptanceTests(unittest.TestCase):
def setUp(self):
self.fixture = test_fidelity_scenarios.FidelityScenarios()
self.fixture.setUp()
self.addCleanup(self.fixture.doCleanups)
self.root = self.fixture.base
self.protocol = self.fixture.protocol()
self.record, self.record_root = self.fixture.receipt()
identity = self.record['identity']
self.package = {'executable': identity['executable'],
'build_info': identity['source'],
'resources': {'assets': {'tree_sha256': 'a' * 64}}}
self.package['build'] = {'source': {k: identity['source'][k]
for k in ('commit', 'dirty', 'diff_sha256')}}
# Bind real hashed metadata files in the test instead of accepting labels.
self.original_files = [dict(path='Neutron.exe', **receipts.identify_file(self.record_root / 'setup.txt'))]
self.original_inventory = {'files': self.original_files,
'tree_sha256': hashlib.sha256(receipts.canonical_bytes(self.original_files)).hexdigest()}
for key, data in [('original_pre', self.original_inventory),
('original_post', self.original_inventory),
('original-package', self.original_inventory),
('original-resources', self.original_inventory),
('package', {'source': self.package['build']['source']}),
('resources', self.package['resources'])]:
path = self.record_root / (key + '.json')
path.write_bytes(receipts.canonical_bytes(data))
identity[key] = dict(receipts.identify_file(path), path=path.name)
self.package['seal'] = identity['package']
self.manifest = {'tooling_only': False, 'packages': {
'linux-x64': self.package, 'win-x64': self.package},
'original_pre': {'tree_sha256': self.original_inventory['tree_sha256'], 'count': 1}}
self.review = {'schema_version': 1,
'checks': {key: {'observed': True, 'reviewer': 'metadata test',
'notes': 'Synthetic unit assertion only'} for key in
('A1', 'A2', 'EVID-02-unclassified', 'EVID-04-unclassified',
'P1', 'P2', 'P3', 'browser', 'paired_review', 'physical_input')},
'receipt_ids': [self.record['receipt_id']]}
def api(self):
self.assertIsNotNone(acceptance, 'strict readiness/acceptance API must exist')
return acceptance
def audit(self, records=None, review=None):
return self.api().audit_records(self.protocol, self.manifest,
[(self.record, self.record_root)] if records is None else records,
self.review if review is None else review, self.original_inventory)
def original_record(self):
value = copy.deepcopy(self.record)
value['evidence_kind'] = 'original_dxwnd'
value['platform'].update(os='windows', execution='dxwnd')
value['identity']['executable']['original_member'] = 'Neutron.exe'
for key in ('package', 'resources'):
value['identity'][key] = value['identity']['original-' + key]
return value
def test_empty_matrix_never_passes(self):
report = self.audit([])
self.assertEqual(report['acceptance'], 'human_needed')
self.assertEqual(len(report['matrix']['missing_obligations']), 120)
def test_identified_valid_cell_covers_only_one_slot(self):
self.assertEqual(self.audit()['matrix']['accepted'], 1)
self.assertEqual(self.audit()['acceptance'], 'human_needed')
def test_complete_metadata_matrix_with_human_findings(self):
records = []
for cell in self.protocol['cells']:
for obligation in cell['obligations']:
for kind, os_name in [('native_port', 'linux'), ('native_port', 'windows'),
('original_dxwnd', 'windows')]:
value, root = self.fixture.receipt(cell['id'], obligation, kind, os_name)
value['identity'] = copy.deepcopy(self.record['identity'])
value['continuity']['copy_pre_sha256'] = value['identity']['copy_pre']['sha256']
value['continuity']['retained_copy_sha256'] = value['identity']['retained_copy']['sha256']
if kind == 'original_dxwnd':
value['identity'] = self.original_record()['identity']
for path in self.record_root.iterdir():
if path.is_file() and root != self.record_root:
(root / path.name).write_bytes(path.read_bytes())
records.append((value, root))
review = copy.deepcopy(self.review)
review['receipt_ids'] = [r['receipt_id'] for r, _ in records]
self.assertEqual(self.audit(records, review)['acceptance'], 'passed')
def test_original_executable_must_match_named_pristine_member(self):
value = self.original_record()
self.assertEqual(self.audit([(value, self.record_root)])['matrix']['accepted'], 1)
wrong = self.record_root / 'wrong.exe'
wrong.write_bytes(b'synthetic wrong original executable')
value['identity']['executable'] = dict(receipts.identify_file(wrong), path=wrong.name,
original_member='Neutron.exe')
self.assertEqual(self.audit([(value, self.record_root)])['matrix']['accepted'], 0)
value = self.original_record()
value['identity']['executable']['original_member'] = 'unselected.exe'
self.assertEqual(self.audit([(value, self.record_root)])['matrix']['accepted'], 0)
def test_original_inventories_require_actual_files_and_digest(self):
for key in ('original_pre', 'original_post', 'package', 'resources'):
with self.subTest(key=key):
value = self.original_record()
path = self.record_root / ('altered-' + key + '.json')
forged = copy.deepcopy(self.original_inventory)
forged['files'][0]['sha256'] = 'f' * 64
path.write_bytes(receipts.canonical_bytes(forged))
value['identity'][key] = dict(receipts.identify_file(path), path=path.name)
self.assertEqual(self.audit([(value, self.record_root)])['matrix']['accepted'], 0)
def test_generated_copy_changes_are_separate_from_original_preservation(self):
value = self.original_record()
path = self.record_root / 'changed-copy.json'
path.write_bytes(receipts.canonical_bytes({'files': [], 'generated_change': True}))
value['identity']['copy_post'] = dict(receipts.identify_file(path), path=path.name)
self.assertEqual(self.audit([(value, self.record_root)])['matrix']['accepted'], 1)
def test_aborted_case_stays_open(self):
self.record['status'] = 'aborted'
self.record['acceptance'] = {'state': 'open', 'remaining': ['aborted']}
self.assertEqual(self.audit()['matrix']['accepted'], 0)
def test_wine_label_cannot_fill_native(self):
self.record['platform']['execution'] = 'wine'
self.assertEqual(self.audit()['matrix']['accepted'], 0)
def test_wrong_package_rejected(self):
self.package['seal'] = {'sha256': '0' * 64}
self.assertTrue(self.audit()['errors'])
def test_wrong_resource_tree_rejected(self):
self.package['resources']['assets']['tree_sha256'] = '0' * 64
self.assertTrue(self.audit()['errors'])
def test_windows_seal_source_and_resource_format_is_supported(self):
source = self.record['identity']['source']
self.record['identity']['source'] = dict(self.record['identity']['package'],
**{k: source[k] for k in ('commit', 'dirty', 'diff_sha256')})
self.record['identity']['resources'] = self.record['identity']['package']
self.package['build']['source']['status_sha256'] = 'not copied into receipt'
path = self.record_root / 'package.json'
path.write_bytes(receipts.canonical_bytes({'source': self.package['build']['source']}))
updated = dict(receipts.identify_file(path), path=path.name)
self.package['seal'] = updated
for key in ('package', 'resources', 'source'):
self.record['identity'][key].update(updated)
self.assertEqual(self.audit()['matrix']['accepted'], 1)
def test_mismatched_source_revision_rejected(self):
self.record['identity']['source']['commit'] = 'wrong revision'
self.assertTrue(self.audit()['errors'])
def test_synthetic_original_rejected(self):
self.record['artifacts'][0]['synthetic'] = True
self.assertEqual(self.audit()['matrix']['accepted'], 0)
def test_absent_visible_audible_reviews_rejected(self):
self.record['review']['audible'] = False
self.assertEqual(self.audit()['matrix']['accepted'], 0)
def test_physical_input_disposition_required(self):
del self.review['checks']['physical_input']
self.assertIn('physical_input', self.audit()['human_needed'])
def test_duplicate_history_conflict_rejected(self):
self.assertTrue(self.audit([(self.record, self.record_root)] * 2)['errors'])
def test_historical_receipt_cannot_be_current(self):
self.record['historical'] = True
self.assertEqual(self.audit()['matrix']['accepted'], 0)
def test_both_unclassified_assumptions_stay_visible(self):
for key in ('EVID-02-unclassified', 'EVID-04-unclassified'):
self.review['checks'][key]['observed'] = False
self.assertTrue(set(('EVID-02-unclassified', 'EVID-04-unclassified')) <=
set(self.audit()['human_needed']))
def test_backstops_and_prohibitions_cannot_be_auto_dismissed(self):
self.assertTrue(set(('A1', 'A2', 'P1', 'P2', 'P3')) <=
set(self.audit(review={})['human_needed']))
def test_review_must_bind_actual_receipt_ids(self):
self.review['receipt_ids'] = ['different']
self.assertTrue(self.audit()['errors'])
def test_review_digest_binds_selected_filename_without_sidecar(self):
checkpoint = self.root / 'checkpoint'
(checkpoint / 'protocol').mkdir(parents=True)
(checkpoint / 'manifest.json').write_bytes(receipts.canonical_bytes(
dict(self.manifest, packages={})))
(checkpoint / 'protocol/scenarios.json').write_bytes(receipts.canonical_bytes(self.protocol))
(checkpoint / 'protocol/original-manifest.json').write_bytes(receipts.canonical_bytes(self.original_inventory))
selected = self.record_root / 'selected.json'
selected.write_bytes(receipts.canonical_bytes(self.record))
sibling = self.record_root / 'receipt.json'
sibling.write_text('{"unrelated": true}')
(self.root / 'current.json').write_bytes(receipts.canonical_bytes(
{'receipts': [selected.relative_to(self.root).as_posix()]}))
for reviewed, expected_pending in ((sibling, True), (None, True), (selected, False)):
review = dict(self.review, receipt_sha256={} if reviewed is None else {
self.record['receipt_id']: receipts.identify_file(reviewed)['sha256']})
(self.root / 'human-review.json').write_bytes(receipts.canonical_bytes(review))
with mock.patch.object(self.api(), 'ready'), mock.patch.object(self.api(), '_bind'):
report = self.api().audit(checkpoint, self.root)
self.assertEqual(bool(report['human_needed']), expected_pending)
self.assertEqual(report['matrix']['accepted'], 1)
def test_actual_failed_linux_receipt_import_and_review_remains_open(self):
source = ROOT / 'artifacts/fidelity/linux-current-receipts/linux-01-06-matrix-preflight-linux'
if not source.exists():
self.assertTrue(self.audit([])['matrix']['missing_obligations'])
return # Local ignored evidence is not a prerequisite on other checkouts.
imported = receipts.import_receipt(source / 'receipt.json', source, self.root / 'imports')
path = Path(imported['path'])
value = receipts.read_receipt(path)
report = self.audit([(value, path.parent)], {})
self.assertEqual(report['matrix']['accepted'], 0)
self.assertEqual(report['acceptance'], 'human_needed')
export_review(None, path, self.root / 'review')
self.assertTrue((self.root / 'review/index.html').is_file())
def test_cli_strict_nonzero_and_allow_open_explicit(self):
api = self.api()
report = self.audit([])
with mock.patch.object(api, 'audit', return_value=report):
self.assertEqual(api.main(['audit', '--checkpoint', str(self.root),
'--results', str(self.root), '--require-complete']), 1)
self.assertEqual(api.main(['audit', '--checkpoint', str(self.root),
'--results', str(self.root), '--allow-open']), 0)
def test_ready_cannot_accept_old_incomplete_material_set(self):
with mock.patch.object(self.api(), 'preflight', return_value={'status': 'ready'}):
with self.assertRaises((ValueError, FileNotFoundError)):
self.api().ready(self.root)
def prepared(self):
fixture = test_fidelity_checkpoint.FidelityCheckpoint()
fixture.setUp()
self.addCleanup(fixture.doCleanups)
fixture.prepare()
root = fixture.output
manifest = receipts.read_json(root / 'manifest.json')
manifest['tooling_only'] = False
(root / 'manifest.json').write_bytes(receipts.canonical_bytes(manifest))
prepared = receipts.read_json(root / 'READY.json')
prepared['manifest'] = dict(receipts.identify_file(root / 'manifest.json'), path='manifest.json')
(root / 'READY.json').write_bytes(receipts.canonical_bytes(prepared))
return root, manifest
def test_ready_validates_all_materials_separately_from_acceptance(self):
root, manifest = self.prepared()
with mock.patch.object(self.api(), '_package', side_effect=lambda _, rid, __: manifest['packages'][rid]):
report = self.api().ready(root)
self.assertTrue(report['materials_ready'])
self.assertEqual(report['acceptance'], 'human_needed')
def test_standalone_transferred_ready_needs_no_source_git_checkout(self):
root, manifest = self.prepared()
self.assertFalse((root / '.git').exists())
with mock.patch.object(self.api(), 'PROJECT', root), mock.patch.object(
self.api(), '_package', side_effect=lambda _, rid, __: manifest['packages'][rid]), \
mock.patch('fidelity_ledger._tracked', side_effect=AssertionError('No source Git on recipient')):
report = self.api().ready(root)
self.assertTrue(report['materials_ready'])
self.assertEqual(report['acceptance'], 'human_needed')
def test_ready_rejects_tampered_final_checklist(self):
root, _ = self.prepared()
(root / 'docs/evidence/checkpoint-session.md').write_text('changed')
with self.assertRaises(ValueError):
self.api().ready(root)
def test_ready_rejects_sealed_viewer_missing_history_projection(self):
root, manifest = self.prepared()
viewer = root / 'review/review.json'
data = receipts.read_json(viewer)
del data['ledger']['capabilities'][0]['history']
viewer.write_bytes(receipts.canonical_bytes(data))
manifest['files'] = [dict(entry, **receipts.identify_file(viewer))
if entry['path'] == 'review/review.json' else entry for entry in manifest['files']]
(root / 'manifest.json').write_bytes(receipts.canonical_bytes(manifest))
seal = receipts.read_json(root / 'READY.json')
seal['manifest'] = dict(path='manifest.json', **receipts.identify_file(root / 'manifest.json'))
(root / 'READY.json').write_bytes(receipts.canonical_bytes(seal))
with mock.patch.object(self.api(), '_package', side_effect=lambda _, rid, __: manifest['packages'][rid]):
with self.assertRaisesRegex(ValueError, 'viewer ledger projection'):
self.api().ready(root)
def test_audit_explicit_selection_reads_actual_failed_linux_hashes(self):
root, manifest = self.prepared()
source = ROOT / 'artifacts/fidelity/linux-current-receipts/linux-01-06-matrix-preflight-linux'
paths = []
if source.exists():
imported = receipts.import_receipt(source / 'receipt.json', source, root / 'results/imported')
paths.append(Path(imported['path']).relative_to(root / 'results').as_posix())
(root / 'results/current.json').write_bytes(receipts.canonical_bytes({'receipts': paths}))
with mock.patch.object(self.api(), '_package', side_effect=lambda _, rid, __: manifest['packages'][rid]):
report = self.api().audit(root, root / 'results')
self.assertEqual(report['acceptance'], 'human_needed')
self.assertEqual(report['matrix']['accepted'], 0)
+282
View File
@@ -0,0 +1,282 @@
"""Capture doubles exercise collection only; no test establishes gameplay acceptance."""
import importlib
import json
from pathlib import Path
import subprocess
import sys
import tempfile
import unittest
from unittest import mock
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tools/recon'))
import fidelity_checkpoint as checkpoint
import fidelity_receipts as receipts
try:
capture = importlib.import_module('fidelity_capture')
except ModuleNotFoundError:
capture = None
class CaptureTests(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.addCleanup(self.tmp.cleanup)
self.root = Path(self.tmp.name)
self.package = self.root / 'package'
self.package.mkdir()
for name in ('GamePort', 'GamePort.dll', 'GamePort.runtimeconfig.json',
'GamePort.deps.json', 'libSDL3.so.0', 'BUILD-INFO.txt',
'assets/NewGame.tsk', 'scenes/level1b/scene.json',
'scenes/VR04/scene.json', 'scenes/level1/scene.json',
'scenes/animations/jimstop/animation.json', 'audio/a.wav', 'Shaders/a.spv'):
path = self.package / name
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(b'test fixture ' + name.encode())
(self.package / 'GamePort').chmod(0o755)
checkpoint.seal_package(self.package, 'linux-x64', {'commit': 'fixture'}, tooling=True)
self.settings = {'display_method': 'x11', 'display': ':11',
'audio_method': 'pulse', 'audio_source': 'hardware.monitor',
'input_method': 'physical', 'size': '1280x720', 'offset': '0,0'}
self.run = self.root / 'test-run'
self.media = {'streams': [{'codec_type': 'video', 'duration': '2'},
{'codec_type': 'audio', 'duration': '2'}],
'format': {'duration': '2'}}
def api(self):
self.assertIsNotNone(capture, 'bounded Linux capture API must exist')
return capture
def probe(self, argv, timeout=10):
output = json.dumps(self.media) if 'ffprobe' in Path(argv[0]).name else 'local test tool\n'
if 'sources' in argv:
output = '1 hardware.monitor module-pipewire float32le 2ch 48000Hz RUNNING\n'
return {'argv': argv, 'exit_code': 0, 'stdout': output, 'error': None}
def spawn(self, argv, **kwargs):
proc = mock.Mock()
proc.pid = 99999999
proc.wait.return_value = 0
proc.poll.return_value = 0
if '-f' in argv and argv[-1].endswith('.mkv'):
Path(argv[-1]).write_bytes(b'fixture recording')
else:
observer = Path(argv[argv.index('--fidelity-output') + 1])
observer.mkdir()
(observer / 'events.jsonl').write_text('{"fixture":true}\n')
return proc
def execute(self, **changes):
options = dict(package=self.package, output=self.run, session_id='test-launch',
case_id='fresh-natural-ordinary', scope='dialogue-return', settings=self.settings,
seconds=2, tooling=True, probe=self.probe, popen=self.spawn)
options.update(changes)
return self.api().run_capture(**options)
def test_capture_probe_hash_import_roundtrip_stays_synthetic(self):
self.execute()
receipt = self.api().collect(self.run, probe=self.probe)
self.assertEqual(receipt['status'], 'captured')
self.assertEqual(receipt['evidence_kind'], 'synthetic')
imported = receipts.import_receipt(self.run / 'receipt.json', self.run, self.root / 'test-imports')
self.assertTrue(Path(imported['path']).exists())
self.assertFalse(receipts.validate_receipt(receipt, self.run)['accepted'])
self.assertTrue(any(a['role'] == 'video' for a in receipt['artifacts']))
def test_missing_display_publishes_failed_preflight_receipt(self):
self.settings['display'] = ''
self.execute()
receipt = self.api().collect(self.run, probe=self.probe)
self.assertEqual(receipt['status'], 'failed')
self.assertTrue(any('display' in s.lower() for s in receipt['missing_evidence']))
def test_null_audio_cannot_be_native_acceptance(self):
self.settings['audio_source'] = 'auto_null.monitor'
report = self.api().preflight(self.package, self.settings, tooling=True, probe=self.probe)
self.assertFalse(report['ready'])
self.assertTrue(any('null' in s for s in report['blockers']))
def test_stale_package_rejected(self):
(self.package / 'GamePort.dll').write_bytes(b'changed')
self.assertFalse(self.api().preflight(self.package, self.settings, tooling=True, probe=self.probe)['ready'])
def test_fixture_package_rejected_in_real_mode(self):
self.assertFalse(self.api().preflight(self.package, self.settings, probe=self.probe)['ready'])
def test_recorder_exit_failure_remains_failed(self):
def bad(argv, **kwargs):
proc = self.spawn(argv, **kwargs)
if '-f' in argv: proc.wait.return_value = 7
return proc
self.execute(popen=bad)
self.assertEqual(self.api().collect(self.run, probe=self.probe)['status'], 'failed')
def test_timeout_aborts_owned_processes(self):
processes = []
def hanging(argv, **kwargs):
proc = self.spawn(argv, **kwargs)
proc.wait.side_effect = [subprocess.TimeoutExpired(argv, 2), 0]
processes.append(proc)
return proc
self.execute(popen=hanging)
self.assertEqual(self.api().collect(self.run, probe=self.probe)['status'], 'aborted')
self.assertTrue(any(p.send_signal.called for p in processes))
def test_empty_media_fails(self):
self.execute()
(self.run / 'raw.mkv').write_bytes(b'')
self.assertEqual(self.api().collect(self.run, probe=self.probe)['status'], 'failed')
def test_missing_audio_stream_fails(self):
self.execute()
self.media['streams'] = self.media['streams'][:1]
self.assertEqual(self.api().collect(self.run, probe=self.probe)['status'], 'failed')
def test_frozen_indicator_keeps_result_incomplete(self):
self.execute()
(self.run / 'recorder.log').write_text('lavfi.freezedetect.freeze_start: 0\n')
result = self.api().collect(self.run, probe=self.probe)
self.assertEqual(result['status'], 'failed')
self.assertTrue(any('frozen' in x for x in result['missing_evidence']))
def test_automated_or_headless_never_physical_category(self):
self.settings['input_method'] = 'automated'
self.execute()
result = self.api().collect(self.run, probe=self.probe)
self.assertEqual(result['evidence_kind'], 'synthetic')
self.assertFalse(result['review']['ordinary_input'])
def test_output_reuse_and_package_overlap_rejected_before_launch(self):
self.execute()
with self.assertRaises(ValueError): self.execute()
with self.assertRaises(ValueError): self.execute(output=self.package / 'capture')
def matrix(self, records=(), **kwargs):
api = self.api()
self.assertTrue(hasattr(api, 'matrix'), 'Linux matrix must enumerate and preserve all forty obligations')
return api.matrix(receipts.read_json(ROOT / 'docs/evidence/scenarios.json'), records, **kwargs)
def test_matrix_enumerates_eight_cells_forty_open_obligations(self):
result = self.matrix(dependency={'receipt_id': 'failed-preflight', 'reasons': ['No real display']})
self.assertEqual(len(result['cells']), 8)
self.assertEqual(sum(len(c['obligations']) for c in result['cells']), 40)
self.assertTrue(all(o['state'] == 'open' and o['dependencies'] for c in result['cells'] for o in c['obligations']))
def test_matrix_preserves_dialogue_lifetime_and_input_procedures(self):
result = self.matrix()
for cell in result['cells']:
self.assertIn(cell['lifetime'], ('fresh', 'retained'))
self.assertIn(cell['dialogue'], ('natural', 'skipped'))
self.assertIn(cell['input'], ('ordinary', 'edge'))
for obligation in cell['obligations']:
if cell['dialogue'] == 'skipped' and obligation['id'] == 'dialogue-return':
self.assertIn('dialogue_skip', obligation['required_events'])
if cell['input'] == 'edge' and obligation['id'] == 'continuous':
self.assertIn('held_return', obligation['required_events'])
def test_continuous_route_cannot_be_replaced_by_focused_capture(self):
self.execute()
receipt = self.api().collect(self.run, probe=self.probe)
result = self.matrix([(receipt, self.run)])
cell = next(c for c in result['cells'] if c['id'] == receipt['case_id'])
continuous = next(o for o in cell['obligations'] if o['id'] == 'continuous')
focused = next(o for o in cell['obligations'] if o['id'] == 'dialogue-return')
self.assertFalse(continuous['attempts'])
self.assertEqual(focused['attempts'][0]['receipt_id'], receipt['receipt_id'])
self.assertEqual(continuous['route'], ['lab', 'VR04', 'lab', 'outside'])
def test_resume_preserves_failed_history_and_requires_new_launch(self):
self.settings['display'] = ''
self.execute()
first = self.api().collect(self.run, probe=self.probe)
previous = self.matrix([(first, self.run)])
new_run = self.root / 'test-second'
self.execute(output=new_run, session_id='test-second')
second = self.api().collect(new_run, probe=self.probe)
resumed = self.matrix([(second, new_run)], previous=previous)
attempts = next(o['attempts'] for c in resumed['cells'] for o in c['obligations'] if o['attempts'])
self.assertEqual([a['session_id'] for a in attempts], ['test-launch', 'test-second'])
second['session_id'] = first['session_id']
with self.assertRaises(ValueError): self.matrix([(second, new_run)], previous=previous)
def test_collection_exposes_shared_scenario_identity_without_claiming_continuity(self):
self.execute()
receipt = self.api().collect(self.run, probe=self.probe)
self.assertEqual(receipt.get('obligation_id'), 'dialogue-return')
self.assertEqual(receipt['clocks'].get('clock_id'), 'test-launch-monotonic')
matrix = self.matrix([(receipt, self.run)])
self.assertEqual(matrix['accepted'], 0)
self.assertFalse(matrix['complete'])
def test_disconnected_or_missing_retained_setup_remains_open(self):
self.execute(case_id='retained-skipped-edge', scope='continuous')
receipt = self.api().collect(self.run, probe=self.probe)
result = self.matrix([(receipt, self.run)])
attempted = next(o for c in result['cells'] for o in c['obligations'] if o['attempts'])
self.assertEqual(attempted['state'], 'open')
self.assertTrue(any('scenario' in x.lower() for x in attempted['dependencies']))
def test_changed_package_after_launch_keeps_prelaunch_identity_and_failure(self):
self.execute()
before = receipts.identify_file(self.run / 'identity/GamePort')['sha256']
(self.package / 'GamePort').write_bytes(b'changed after launch')
receipt = self.api().collect(self.run, probe=self.probe)
self.assertEqual(receipt['identity']['executable']['sha256'], before)
self.assertEqual(receipt['status'], 'failed')
self.assertTrue(any('Post-capture' in reason for reason in receipt['missing_evidence']))
def test_retained_annotations_bind_real_files_and_clock_without_acceptance(self):
self.execute(case_id='retained-natural-ordinary', scope='landing-idle')
(self.run / 'prerequisite.mkv').write_bytes((self.run / 'raw.mkv').read_bytes())
for name in ('copy-pre.json', 'retained-copy.json'):
(self.run / name).write_text(json.dumps({'fixture': name}))
note = self.root / 'annotations.json'
note.write_text(json.dumps({'events': [
dict(name=name, artifact=artifact, media_seconds=i * .0001,
elapsed_seconds=i * .0001, method='manual', uncertainty_seconds=.01)
for i, (name, artifact) in enumerate([
('prerequisite_departure', 'prerequisite.mkv'),
('prerequisite_return', 'prerequisite.mkv'),
('landing', 'raw.mkv'), ('idle', 'raw.mkv')])],
'artifact_roles': {'prerequisite.mkv': 'prerequisite'},
'identity_files': {'copy_pre': 'copy-pre.json', 'retained_copy': 'retained-copy.json'},
'continuity': {'lifetime_id': 'test-launch', 'departure_session_id': 'test-launch',
'return_session_id': 'test-launch', 'prerequisite_artifact': 'prerequisite.mkv',
'copy_pre_sha256': receipts.identify_file(self.run / 'copy-pre.json')['sha256'],
'retained_copy_sha256': receipts.identify_file(self.run / 'retained-copy.json')['sha256']}}))
receipt = self.api().collect(self.run, probe=self.probe, annotations=note)
protocol = receipts.read_json(ROOT / 'docs/evidence/scenarios.json')
cell = next(c for c in protocol['cells'] if c['id'] == receipt['case_id'])
receipts._scenario_observation(protocol, cell, receipt, self.run)
receipt['continuity']['return_session_id'] = 'other-process'
with self.assertRaises(ValueError): receipts._scenario_observation(protocol, cell, receipt, self.run)
self.assertEqual(receipt['acceptance']['state'], 'open')
def test_annotated_prerequisite_cannot_escape_capture_root(self):
self.execute()
note = self.root / 'annotations.json'
note.write_text(json.dumps({'artifact_roles': {'../secret.mkv': 'prerequisite'}}))
with self.assertRaises(ValueError): self.api().collect(self.run, probe=self.probe, annotations=note)
def test_native_automation_remains_fixture_even_after_collection(self):
self.settings['input_method'] = 'automated'
self.execute()
state = receipts.read_json(self.run / 'session.json')
state['tooling_only'] = False
(self.run / 'session.json').write_bytes(receipts.canonical_bytes(state))
receipt = self.api().collect(self.run, probe=self.probe)
self.assertEqual(receipt['evidence_kind'], 'port_fixture')
self.assertFalse(receipts.validate_receipt(receipt, self.run)['accepted'])
def test_oversized_raw_media_is_preserved_without_unbounded_import(self):
self.execute()
with (self.run / 'raw.mkv').open('r+b') as stream:
stream.truncate(self.api().MAX_MEDIA + 1)
result = self.api().collect(self.run, probe=self.probe)
self.assertEqual(result['status'], 'failed')
self.assertFalse(any(a['path'] == 'raw.mkv' for a in result['artifacts']))
self.assertTrue(any('8 GiB' in reason for reason in result['missing_evidence']))
if __name__ == '__main__':
unittest.main()
+290
View File
@@ -0,0 +1,290 @@
"""Offline checkpoint fixtures are tooling tests, never native/reference evidence."""
import concurrent.futures
import importlib
import json
from pathlib import Path
import subprocess
import sys
import tempfile
import unittest
from unittest import mock
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tools/recon'))
import fidelity_receipts as receipts
try:
checkpoint = importlib.import_module('fidelity_checkpoint')
except ModuleNotFoundError:
checkpoint = None
class FidelityCheckpoint(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.addCleanup(self.tmp.cleanup)
self.base = Path(self.tmp.name)
self.original = self.base / 'Original'
self.original.mkdir()
(self.original / 'Jimmy Neutron.exe').write_bytes(b'synthetic original')
self.manifest = self.base / 'original.json'
self.manifest.write_bytes(receipts.canonical_bytes(receipts.identify_tree(self.original)))
self.packages = {}
for rid in ('linux-x64', 'win-x64'):
package = self.base / rid
package.mkdir()
for name in ('GamePort.exe' if rid == 'win-x64' else 'GamePort',
'GamePort.dll', 'GamePort.runtimeconfig.json', 'GamePort.deps.json',
'SDL3.dll' if rid == 'win-x64' else 'libSDL3.so.0',
'assets/NewGame.tsk', 'scenes/level1b/scene.json',
'scenes/VR04/scene.json', 'scenes/level1/scene.json',
'scenes/animations/jimstop/animation.json', 'audio/music.wav', 'Shaders/test.spv'):
path = package / name
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(b'synthetic fixture bytes ' + name.encode())
(package / 'BUILD-INFO.txt').write_text('source_commit=fixture\nsource_dirty=yes\n')
self.packages[rid] = package
self.output = self.base / 'checkpoint'
def api(self):
self.assertIsNotNone(checkpoint, 'offline checkpoint preparation API must exist')
return checkpoint
def prepare(self, output=None):
api = self.api()
for rid, path in self.packages.items():
if not (path / 'fidelity-build.json').exists():
api.seal_package(path, rid, {'commit': 'fixture', 'dirty': True,
'diff_sha256': '0' * 64}, tooling=True)
return api.prepare_checkpoint(self.original, self.manifest, self.packages,
output or self.output, tooling=True)
def test_prepare_preflight_fixture_import_roundtrip(self):
self.prepare()
report = self.api().preflight(self.output)
self.assertEqual(report['status'], 'ready')
self.assertEqual(report['acceptance']['state'], 'open')
run = self.base / 'fixture-result'
run.mkdir()
(run / 'raw.mkv').write_bytes(b'synthetic media, deliberately not decodable')
result = self.api().fixture_result(self.output, run, 'test-run',
'fresh-natural-ordinary', 'continuous', ['raw.mkv'])
self.assertEqual(result['evidence_kind'], 'synthetic')
target = self.base / 'test-imports'
imported = receipts.import_receipt(run / 'receipt.json', run, target)
actual = receipts.read_receipt(Path(imported['path']))
self.assertFalse(receipts.validate_receipt(actual, Path(imported['path']).parent)['accepted'])
self.assertEqual(receipts.identify_tree(self.original)['files'],
receipts.read_json(self.manifest)['files'])
def test_bundled_python_commands_preserve_immutable_tree(self):
self.prepare()
before = receipts.identify_tree(self.output)
for name in ('fidelity_acceptance', 'fidelity_checkpoint', 'fidelity_capture',
'fidelity_review', 'fidelity_ledger'):
result = subprocess.run(
[sys.executable, '-E', 'tools/recon/' + name + '.py', '--help'],
cwd=self.output, capture_output=True, text=True, timeout=20)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertFalse(list((self.output / 'tools/recon').rglob('*.pyc')), name)
for _ in range(2):
result = subprocess.run(
[sys.executable, '-E', 'tools/recon/fidelity_checkpoint.py',
'preflight', '--checkpoint', '.'], cwd=self.output,
capture_output=True, text=True, timeout=20)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(receipts.identify_tree(self.output), before)
def test_actual_package_and_resource_bytes_identified(self):
self.prepare()
manifest = receipts.read_json(self.output / 'manifest.json')
for rid, package in self.packages.items():
self.assertEqual(manifest['packages'][rid]['dll']['sha256'],
receipts.identify_file(package / 'GamePort.dll')['sha256'])
self.assertEqual(manifest['packages'][rid]['resources']['assets']['tree_sha256'],
receipts.identify_tree(package / 'assets')['tree_sha256'])
def test_preparation_preserves_current_and_superseded_records_through_renderer(self):
self.prepare()
model = self.output / 'review/review.json'
row = next(row for row in receipts.read_json(model)['ledger']['capabilities']
if row['id'] == 'startup-order')
self.assertEqual(len(row['current']), 2)
self.assertEqual(len(row['history']), 2)
script = '''
import {readFileSync} from 'node:fs';
const api = await import(process.argv[1]);
const model = JSON.parse(readFileSync(process.argv[2]));
class Element {
constructor(text='') { this.textContent=text; this.children=[]; }
append(...items) { this.children.push(...items); }
replaceChildren(...items) { this.children=items; }
get text() { return this.textContent + this.children.map(x=>x.text??String(x)).join(' '); }
}
const doc={createElement:()=>new Element()};
const container=new Element(); container.ownerDocument=doc;
api.renderCapabilities(container, model.ledger);
process.stdout.write(container.text);
'''
# Render the actual assembled model with its bundled renderer, using only
# a DOM double. This proves fields reach the UI, not browser playback.
rendered = subprocess.run(['node', '--input-type=module', '-e', script,
(self.output / 'review/viewer.mjs').as_uri(), str(model)],
capture_output=True, text=True, timeout=15)
self.assertEqual(rendered.returncode, 0, rendered.stderr)
for record in row['current'] + row['history']:
self.assertIn(record['id'], rendered.stdout)
def test_original_change_rejected_before_output(self):
(self.original / 'Jimmy Neutron.exe').write_bytes(b'changed')
with self.assertRaises(ValueError): self.prepare()
self.assertFalse(self.output.exists())
def test_output_overlap_and_case_alias_rejected(self):
for output in (self.original, self.original / 'nested', self.base / 'original'):
with self.assertRaises(ValueError): self.prepare(output)
def test_output_symlink_rejected(self):
self.output.symlink_to(self.original, target_is_directory=True)
with self.assertRaises(ValueError): self.prepare()
def test_existing_output_never_reused(self):
self.prepare()
before = (self.output / 'manifest.json').read_bytes()
with self.assertRaises(ValueError): self.prepare()
self.assertEqual(before, (self.output / 'manifest.json').read_bytes())
def test_missing_binary_rejected(self):
self.prepare()
(self.output / 'port/win-x64/GamePort.dll').unlink()
with self.assertRaisesRegex(ValueError, 'GamePort.dll'): self.api().preflight(self.output)
def test_stale_binary_rejected(self):
self.prepare()
(self.output / 'port/win-x64/GamePort.dll').write_bytes(b'old binary')
with self.assertRaises(ValueError): self.api().preflight(self.output)
def test_missing_resources_rejected(self):
self.prepare()
(self.output / 'port/win-x64/assets/NewGame.tsk').unlink()
with self.assertRaises(ValueError): self.api().preflight(self.output)
def test_tampered_launcher_rejected(self):
self.prepare()
with (self.output / 'scripts/collect-fidelity-windows.ps1').open('a') as stream:
stream.write('\n#tamper')
with self.assertRaises(ValueError): self.api().preflight(self.output)
def test_tampered_fixture_media_import_rejected(self):
self.prepare()
run = self.base / 'result'
run.mkdir()
(run / 'raw.mkv').write_bytes(b'fixture')
self.api().fixture_result(self.output, run, 'test-media',
'fresh-natural-ordinary', 'continuous', ['raw.mkv'])
(run / 'raw.mkv').write_bytes(b'tampered')
with self.assertRaises(ValueError):
receipts.import_receipt(run / 'receipt.json', run, self.base / 'test-index')
def test_interrupted_assembly_preserves_diagnostics(self):
api = self.api()
with mock.patch.object(api, '_copy_file', side_effect=OSError('simulated interruption')):
with self.assertRaises(OSError): self.prepare()
self.assertFalse(self.output.exists())
self.assertTrue(list(self.base.glob('.checkpoint.incomplete-*')))
with self.assertRaises(ValueError): self.prepare()
def test_concurrent_assembly_has_one_winner(self):
self.prepare(self.base / 'seed') # seal inputs before the concurrent callers
def attempt(_):
try:
self.prepare()
return True
except (ValueError, FileExistsError):
return False
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool:
self.assertEqual(list(pool.map(attempt, range(2))).count(True), 1)
def test_missing_local_dependency_is_actionable(self):
self.prepare()
report = self.api().preflight(self.output, dependencies={'dxwnd': self.base / 'missing.exe'})
self.assertEqual(report['status'], 'blocked')
self.assertIn('dxwnd', ' '.join(report['failures']))
self.assertEqual(report['acceptance']['state'], 'open')
def test_complete_session_materials_and_eighty_windows_obligations(self):
self.prepare()
for name in (*self.api().MATERIALS,
'protocol/annotation-template.json', 'protocol/settings-template.json'):
self.assertTrue((self.output / name).is_file(), 'complete session material missing: ' + name)
agenda = receipts.read_json(self.output / 'protocol/agenda.json')
self.assertEqual(len(agenda['runs']), 80)
self.assertEqual(len({r['case_id'] for r in agenda['runs']}), 8)
self.assertEqual(len({r['obligation_id'] for r in agenda['runs']}), 5)
self.assertEqual({r['side'] for r in agenda['runs']},
{'original-windows-dxwnd', 'port-windows-native'})
def test_package_copy_preserves_source_execution_permissions(self):
apphost = self.packages['linux-x64'] / 'GamePort'
apphost.chmod(0o755)
self.prepare()
copied = self.output / 'port/linux-x64/GamePort'
self.assertEqual(copied.stat().st_mode & 0o777, apphost.stat().st_mode & 0o777)
self.assertEqual(receipts.identify_file(copied), receipts.identify_file(apphost))
def test_skip_abort_remain_open_schema_valid_results(self):
self.prepare()
for status in ('skipped', 'aborted'):
run = self.base / status
run.mkdir()
record = self.api().fixture_result(self.output, run, 'test-' + status,
'fresh-skipped-edge', 'bank-left', [], status=status)
self.assertEqual(record['status'], status)
self.assertFalse(receipts.validate_receipt(record, run)['accepted'])
def test_prepared_materials_never_close_runtime_matrix(self):
self.prepare()
protocol = receipts.read_json(self.output / 'protocol/scenarios.json')
report = receipts.audit_receipt_tree(protocol, self.output / 'results')
self.assertEqual(report['accepted'], 0)
self.assertEqual(report['required'], 120)
self.assertFalse(report['complete'])
def test_synthetic_packages_rejected_for_real_checkpoint(self):
self.prepare()
with self.assertRaisesRegex(ValueError, 'Synthetic'):
self.api().prepare_checkpoint(self.original, self.manifest, self.packages,
self.base / 'runtime', tooling=False)
def test_tampered_ready_manifest_rejected(self):
self.prepare()
(self.output / 'manifest.json').write_text('{}')
with self.assertRaisesRegex(ValueError, 'Manifest'): self.api().preflight(self.output)
def test_added_immutable_material_rejected(self):
self.prepare()
(self.output / 'port/win-x64/unreviewed.exe').write_bytes(b'do not execute')
with self.assertRaisesRegex(ValueError, 'Unexpected'): self.api().preflight(self.output)
def test_mutable_results_allowed_without_weakening_materials(self):
self.prepare()
(self.output / 'results/raw.mkv').write_bytes(b'synthetic')
self.assertEqual(self.api().preflight(self.output)['status'], 'ready')
def test_unknown_case_scope_rejected(self):
self.prepare()
run = self.base / 'unknown-result'
run.mkdir()
with self.assertRaises(ValueError):
self.api().fixture_result(self.output, run, 'test-unknown', 'invented', 'continuous', [])
def test_symlink_ancestor_rejected_before_writes(self):
alias = self.base / 'alias'
target = self.base / 'target'
target.mkdir()
alias.symlink_to(target, target_is_directory=True)
with self.assertRaises(ValueError): self.prepare(alias / 'new')
self.assertFalse((target / 'new').exists())
if __name__ == '__main__':
unittest.main()
+339
View File
@@ -0,0 +1,339 @@
import copy
import importlib
import json
from pathlib import Path
import subprocess
import sys
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tools/recon'))
TOOL = ROOT / 'tools/recon/fidelity_ledger.py'
LEDGER = ROOT / 'docs/evidence/capabilities.json'
def evidence(identifier='proof-a', **changes):
value = {
'id': identifier, 'receipt_id': identifier, 'evidence_kind': 'port_fixture',
'method': 'bounded fixture', 'revision': 'a' * 40, 'historical': True,
'content': {'runtime_sha256': '1' * 64, 'resources_sha256': '2' * 64},
'platform': {'os': 'linux', 'execution': 'native'},
'scope': ['Carl first neutral input'], 'status': 'current',
'claim': {'key': 'neutral-return', 'result': 'upright'},
'supersedes': [], 'reason': None, 'artifacts': [],
'missing_evidence': ['Original and native Windows comparison absent'],
'report_path': 'docs/gameplay/main-menu-player-lifetime.md',
}
value.update(changes)
return value
def target(record=None):
row = record or evidence()
return {key: copy.deepcopy(row[key]) for key in ('content', 'platform', 'scope')}
def capability(identifier='startup-order'):
row = evidence()
return {
'id': identifier, 'group': 'movement', 'requirement_ids': ['MOVE-04'],
'summary': 'TSK story entry preserves retained Jimmy-before-input order.',
'verified_scope': 'Historical Linux fixture; direct fresh scene remains separate.',
'differences': ['Whole-original audiovisual comparison remains absent.'],
'acceptance': {'status': 'open', 'remaining': ['Original and native Windows comparison']},
'source_links': [{'label': 'Source lifetime', 'path': row['report_path']}],
'scenario_ids': ['fresh-natural-ordinary'], 'implementation': {'revision': 'a' * 40,
'paths': ['src/GamePort/Program.cs'], 'status': 'bounded'},
'targets': [dict(id='historical-linux', **target(row))],
'evidence': [row], 'discrepancies': [{'id': 'reference-gap',
'impact': 'missing_verification', 'summary': 'Missing whole-original recording'}],
}
def ledger(*rows):
return {'schema_version': 1, 'capabilities': list(rows)}
class LedgerTests(unittest.TestCase):
def api(self):
self.assertTrue(TOOL.is_file(), 'Capability ledger CLI must exist')
return importlib.import_module('fidelity_ledger')
def test_real_startup_capability_cli_and_viewer_roundtrip(self):
self.assertTrue(TOOL.is_file(), 'Capability ledger CLI must exist')
with tempfile.TemporaryDirectory() as temporary:
exported = Path(temporary) / 'ledger.json'
result = subprocess.run([sys.executable, str(TOOL), 'export', '--ledger', str(LEDGER),
'--output', str(exported)], text=True, capture_output=True)
self.assertEqual(result.returncode, 0, result.stderr)
model = json.loads(exported.read_text())
row = next(row for row in model['capabilities'] if row['id'] == 'startup-order')
self.assertIn('already corrected', row['summary'])
self.assertEqual(row['acceptance']['status'], 'open')
self.assertTrue(row['current'])
self.assertTrue(row['history'])
from fidelity_review import export_review
reviewed = export_review(None, None, Path(temporary) / 'review', exported)
loaded = json.loads((Path(temporary) / 'review/review.json').read_text())
self.assertEqual(reviewed, loaded)
nav = next(row for row in loaded['ledger']['capabilities'] if row['id'] == 'startup-order')
self.assertEqual(nav['current'], row['current'])
self.assertEqual(nav['history'], row['history'])
self.assertTrue(all(link['validated_local'] for link in nav['source_links']))
for link in nav['source_links']:
self.assertTrue((Path(temporary) / 'review' / link['href']).is_file())
self.assertIn('native Windows', str(nav['acceptance']))
self.assertEqual(loaded['acceptance']['state'], 'open')
self.assertEqual(len(loaded['ledger']['capabilities']), len(model['capabilities']))
for exported_row in model['capabilities']:
viewed = next(r for r in loaded['ledger']['capabilities'] if r['id'] == exported_row['id'])
for key in ('current', 'history', 'scenario_ids', 'acceptance', 'discrepancies'):
self.assertEqual(viewed[key], exported_row[key])
self.assertTrue(all(link['validated_local'] for link in viewed['source_links']))
self.assertTrue(all((Path(temporary) / 'review' / link['href']).is_file()
for link in viewed['source_links']))
def test_empty_ledger_fails(self):
with self.assertRaises(ValueError): self.api().validate_ledger(ledger(), ROOT)
def test_single_capability_renders_with_open_acceptance(self):
api = self.api()
text = api.render_markdown(ledger(capability()), ROOT)
self.assertIn('TSK story entry', text)
self.assertIn('OPEN', text)
self.assertIn('History', text)
def test_duplicate_capability_conflict_rejected(self):
row = capability()
other = copy.deepcopy(row)
other['summary'] = 'contradictory'
with self.assertRaises(ValueError): self.api().validate_ledger(ledger(row, other), ROOT)
def test_equal_record_ids_merge_only_equal_records(self):
row = capability()
row['evidence'].append(copy.deepcopy(row['evidence'][0]))
model = self.api().export_ledger(ledger(row), ROOT)
self.assertEqual(len(model['capabilities'][0]['evidence']), 1)
row['evidence'][-1]['method'] = 'changed bytes'
with self.assertRaises(ValueError): self.api().validate_ledger(ledger(row), ROOT)
def test_conflicting_shared_receipt_identity_rejected(self):
row = capability()
row['evidence'].append(evidence('other-id', receipt_id='proof-a', method='different'))
with self.assertRaises(ValueError): self.api().validate_ledger(ledger(row), ROOT)
def test_equal_priority_has_stable_id_order(self):
api = self.api()
a, b = capability('zeta'), capability('alpha')
self.assertEqual([r['id'] for r in api.export_ledger(ledger(a, b), ROOT)['capabilities']],
['alpha', 'zeta'])
def test_supersession_cycle_rejected(self):
row = capability()
row['evidence'] = [evidence('a', supersedes=['b'], reason='replace'),
evidence('b', supersedes=['a'], reason='replace')]
with self.assertRaises(ValueError): self.api().validate_ledger(ledger(row), ROOT)
def test_unresolved_contradictory_current_claims_fail(self):
row = capability()
row['evidence'].append(evidence('other', claim={'key': 'neutral-return', 'result': 'tilted'}))
with self.assertRaises(ValueError): self.api().validate_ledger(ledger(row), ROOT)
def test_explicit_supersession_retains_prior_claim(self):
row = capability()
row['evidence'][0].update(status='superseded')
row['evidence'].append(evidence('new', supersedes=['proof-a'], reason='Source correction',
claim={'key': 'neutral-return', 'result': 'corrected'}))
model = self.api().export_ledger(ledger(row), ROOT)['capabilities'][0]
self.assertEqual([r['id'] for r in model['current']], ['new'])
self.assertEqual([r['id'] for r in model['history']], ['proof-a'])
def test_unsafe_dead_and_tampered_source_links_fail(self):
api = self.api()
for path in ('../Original/Neutron.exe', '/etc/passwd', 'C:/secret',
'artifacts/private.json', 'docs/nonexistent-ledger-source.md'):
with self.subTest(path=path):
row = capability()
row['source_links'][0]['path'] = path
with self.assertRaises(ValueError): api.validate_ledger(ledger(row), ROOT)
row = capability()
row['source_links'][0]['sha256'] = '0' * 64
with self.assertRaises(ValueError): api.validate_ledger(ledger(row), ROOT)
def test_docs_revision_does_not_change_content_applicability(self):
api = self.api()
row = evidence()
current = target(row)
current['source_revision'] = 'b' * 40
self.assertEqual(api.select_current_evidence([row], current), [row])
def test_changed_package_or_resources_is_not_applicable(self):
api = self.api()
for key in ('runtime_sha256', 'resources_sha256', 'package_sha256'):
row = evidence()
changed = target(row)
changed['content'][key] = '3' * 64
self.assertEqual(api.select_current_evidence([row], changed), [])
def test_mismatched_platform_or_scope_is_not_applicable(self):
api = self.api()
for key, value in (('platform', {'os': 'windows', 'execution': 'native'}),
('scope', ['whole campaign'])):
changed = target()
changed[key] = value
self.assertEqual(api.select_current_evidence([evidence()], changed), [])
def test_missing_artifact_is_explicit_and_never_accepted(self):
row = capability()
row['evidence'][0]['artifacts'] = [{'path': 'artifacts/fidelity/never-captured.webm',
'missing_reason': 'No recording was made'}]
exported = self.api().export_ledger(ledger(row), ROOT)['capabilities'][0]
self.assertEqual(exported['acceptance']['status'], 'open')
self.assertIn('No recording', str(exported['evidence']))
row['acceptance']['status'] = 'accepted'
with self.assertRaises(ValueError): self.api().validate_ledger(ledger(row), ROOT)
def test_invalid_receipt_classification_rejected(self):
row = capability()
row['evidence'][0]['evidence_kind'] = 'native_port'
row['evidence'][0]['platform'] = {'os': 'windows', 'execution': 'wine'}
with self.assertRaises(ValueError): self.api().validate_ledger(ledger(row), ROOT)
def test_nonfinite_or_oversized_input_rejected(self):
row = capability()
row['evidence'][0]['elapsed'] = float('nan')
with self.assertRaises(ValueError): self.api().validate_ledger(ledger(row), ROOT)
row = capability()
row['summary'] = 'x' * 20000
with self.assertRaises(ValueError): self.api().validate_ledger(ledger(row), ROOT)
def test_duplicate_history_is_not_silently_overwritten(self):
row = capability()
row['evidence'] = [evidence('old', status='historical'), evidence('old', status='superseded')]
with self.assertRaises(ValueError): self.api().validate_ledger(ledger(row), ROOT)
def test_full_game_has_33_requirements_and_six_groups(self):
api = self.api()
model = json.loads(LEDGER.read_text())
required = set(__import__('re').findall(r'^- \[[ x]\] \*\*([A-Z]+-[0-9]{2})\*\*:',
(ROOT / '.planning/REQUIREMENTS.md').read_text(), __import__('re').M))
mapped = {req for row in model['capabilities'] for req in row['requirement_ids']}
self.assertEqual(mapped, required, 'Every full-game requirement needs capability coverage')
counts = api.validate_ledger(model, ROOT, ROOT / '.planning/REQUIREMENTS.md')
self.assertEqual((counts['requirements'], counts['unmapped'], counts['groups']), (33, 0, 6))
def test_unmapped_requirements_fail_full_validation(self):
with self.assertRaises(ValueError):
self.api().validate_ledger(ledger(capability()), ROOT, ROOT / '.planning/REQUIREMENTS.md')
def test_unimplemented_required_rows_remain_visible_and_open(self):
model = json.loads(LEDGER.read_text())
rows = [row for row in model['capabilities'] if row['implementation']['status'] == 'unimplemented']
self.assertTrue(rows, 'Unimplemented full-game work must be visible')
self.assertTrue(all(row['acceptance']['status'] == 'open' for row in rows))
self.assertIn('CAMP-03', {req for row in rows for req in row['requirement_ids']})
def test_checkpoint_source_rows_are_exhaustively_reconciled(self):
api = self.api()
data = json.loads(LEDGER.read_text())
self.assertIn('reconciliation', data, 'Checkpoint source-row accounting must be explicit')
expected = api.checkpoint_rows(ROOT / 'docs/checkpoint/coverage.md')
self.assertGreaterEqual(len(expected), 32)
self.assertEqual({r['source_row']: r['source_sha256'] for r in data['reconciliation']}, expected)
data['reconciliation'].pop()
with self.assertRaises(ValueError): api.validate_ledger(data, ROOT, ROOT / '.planning/REQUIREMENTS.md')
def test_discrepancy_impact_and_stable_ties(self):
api = self.api()
row = capability()
row['discrepancies'] = [{'id': name, 'impact': impact, 'summary': name}
for name, impact in [('z', 'missing_verification'), ('b', 'blocking'),
('a', 'blocking'), ('d', 'subtle'), ('c', 'disruptive')]]
actual = api.export_ledger(ledger(row), ROOT)['capabilities'][0]['discrepancies']
self.assertEqual([r['id'] for r in actual], ['a', 'b', 'c', 'd', 'z'])
def test_unknown_scenario_and_missing_critical_fields_fail(self):
api = self.api()
row = capability()
row['scenario_ids'] = ['invented-scenario']
with self.assertRaises(ValueError): api.validate_ledger(ledger(row), ROOT)
for key in ('summary', 'verified_scope', 'implementation', 'acceptance', 'source_links'):
broken = capability()
del broken[key]
with self.assertRaises(ValueError): api.validate_ledger(ledger(broken), ROOT)
def test_generated_readme_exactly_matches_authoritative_model(self):
api = self.api()
self.assertEqual((ROOT / 'docs/evidence/README.md').read_text(),
api.render_markdown(json.loads(LEDGER.read_text()), ROOT))
def test_local_artifact_tamper_fails_validation(self):
api = self.api()
with tempfile.TemporaryDirectory(dir=ROOT / 'artifacts') as temporary:
artifact = Path(temporary) / 'proof.log'
artifact.write_text('original fixture log')
import hashlib
row = capability()
row['evidence'][0]['artifacts'] = [{'path': artifact.relative_to(ROOT).as_posix(),
'sha256': hashlib.sha256(artifact.read_bytes()).hexdigest(), 'size': artifact.stat().st_size}]
api.validate_ledger(ledger(row), ROOT)
artifact.write_text('tampered fixture log')
with self.assertRaises(ValueError): api.validate_ledger(ledger(row), ROOT)
def test_receipt_identity_conflict_across_capabilities_rejected(self):
a, b = capability('alpha'), capability('beta')
self.api().validate_ledger(ledger(a, b), ROOT)
b['evidence'][0]['method'] = 'Conflicting bytes under a shared receipt ID'
with self.assertRaises(ValueError): self.api().validate_ledger(ledger(a, b), ROOT)
def test_component_and_inferred_categories_cannot_claim_native_execution(self):
for kind in ('component', 'managed', 'synthetic', 'inferred'):
with self.subTest(kind=kind):
row = capability()
row['evidence'][0]['evidence_kind'] = kind
with self.assertRaises(ValueError): self.api().validate_ledger(ledger(row), ROOT)
def test_reconciliation_requires_actual_retained_source_link(self):
model = json.loads(LEDGER.read_text())
identifier = model['reconciliation'][0]['capability_ids'][0]
row = next(row for row in model['capabilities'] if row['id'] == identifier)
row['source_links'] = [link for link in row['source_links'] if link['path'] != 'docs/checkpoint/coverage.md']
with self.assertRaises(ValueError): self.api().validate_ledger(model, ROOT)
def test_cli_full_model_rejects_unmapped_requirement_without_optional_flag(self):
model = json.loads(LEDGER.read_text())
for row in model['capabilities']:
row['requirement_ids'] = [req for req in row['requirement_ids'] if req != 'EVID-03']
with tempfile.TemporaryDirectory() as temporary:
path = Path(temporary) / 'broken.json'
path.write_text(json.dumps(model))
result = subprocess.run([sys.executable, str(TOOL), 'validate', '--ledger', str(path)],
capture_output=True, text=True)
self.assertEqual(result.returncode, 2)
self.assertIn('Unmapped or unknown requirements', result.stderr)
def test_real_imported_receipt_reference_binds_bytes_scope_and_platform(self):
from test_fidelity_review import fixture
from fidelity_receipts import identify_file
with tempfile.TemporaryDirectory(dir=ROOT / 'artifacts') as temporary:
receipt_path, receipt = fixture(Path(temporary), 'ledger')
row = capability()
record = row['evidence'][0]
record.update(receipt_id=receipt['receipt_id'], evidence_kind='synthetic', historical=False,
platform=receipt['platform'], scope=[receipt['scope']],
receipt_path=receipt_path.relative_to(ROOT).as_posix(),
content={'receipt_sha256': identify_file(receipt_path)['sha256']})
row['targets'] = [dict(id='imported-test', **target(record))]
self.api().validate_ledger(ledger(row), ROOT)
for key, value in [('scope', ['wrong scope']),
('platform', {'os':'wrong host','execution':'synthetic'}),
('content', {'receipt_sha256':'0'*64})]:
broken = copy.deepcopy(row)
broken['evidence'][0][key] = value
broken['targets'] = [dict(id='imported-test', **target(broken['evidence'][0]))]
with self.assertRaises(ValueError): self.api().validate_ledger(ledger(broken), ROOT)
if __name__ == '__main__':
unittest.main()
+156
View File
@@ -0,0 +1,156 @@
"""Actual port-process observation plumbing; fixtures never fill native acceptance."""
import json
from pathlib import Path
import subprocess
import sys
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tools/recon'))
import fidelity_receipts as receipts
class FidelityObservation(unittest.TestCase):
@classmethod
def setUpClass(cls):
result = subprocess.run(['bash', '-lc', 'source scripts/env.sh && dotnet build GamePort.csproj --no-restore'],
cwd=ROOT, capture_output=True, text=True, timeout=90)
if result.returncode:
raise RuntimeError(result.stdout + result.stderr)
required = ['level1b/scene.json', 'VR04/scene.json', 'ui/ui.json', 'animations/jimstop/animation.json']
if not all((ROOT / 'artifacts/extracted' / name).is_file() for name in required):
# The consolidated script runs Python before its preparation step.
# Reuse its local extractor instead of assuming generated fixtures exist.
result = subprocess.run([sys.executable, 'tools/extractors/prepare.py', '--all-scenes',
'--audio', 'sounds', 'musicsecretlab'], cwd=ROOT,
capture_output=True, text=True, timeout=300)
if result.returncode:
raise RuntimeError(result.stdout + result.stderr)
def run_port(self, *args):
# Fixed shell source; caller values are positional argv, never shell code.
return subprocess.run(['bash', '-lc', 'source scripts/env.sh && dotnet bin/Debug/net10.0/GamePort.dll "$@"',
'observer-test', *map(str, args)], cwd=ROOT, text=True,
capture_output=True, timeout=90)
def test_real_port_exposes_observation_options(self):
result = self.run_port('--help')
self.assertEqual(result.returncode, 0, result.stderr)
self.assertIn('--fidelity-output', result.stdout, 'actual port must expose passive observation')
self.assertIn('--fidelity-session', result.stdout)
self.assertIn('--fidelity-case', result.stdout)
def fixture(self, directory, observed=True):
args = ['--headless', '--mute', '--no-validation', '--smoke-control-phases',
'--width', '320', '--height', '240', '--screenshot', directory / 'frame.ppm']
if observed:
args += ['--fidelity-output', directory / 'observation', '--fidelity-session', 'process-session',
'--fidelity-case', 'fresh-skipped-edge']
result = self.run_port(*args)
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
return result
def observed_fixture(self):
temporary = tempfile.TemporaryDirectory(prefix='gameport-observer-')
self.addCleanup(temporary.cleanup)
root = Path(temporary.name)
result = self.fixture(root)
output = root / 'observation'
summary = json.loads((output / 'observation-summary.json').read_text())
records = [json.loads(line) for line in (output / 'events.jsonl').read_text().splitlines()]
self.assertTrue(records, 'real process must emit records')
return root, output, summary, records, result
def receipt(self, output, summary, records):
duration = summary['elapsed_seconds']
return dict(schema_version=1, receipt_id='observer-fixture', session_id=summary['session_id'],
case_id=summary['case_id'], evidence_kind=summary['evidence_kind'], status='captured',
platform={'os': 'linux', 'execution': 'port_fixture'}, historical=False,
scope='observer-wiring', identity={}, invocation={'argv': ['bounded-existing-fixture'], 'cwd': '.'},
clocks={'wall_start': summary['wall_start'], 'wall_end': summary['wall_end'],
'monotonic_start': 0, 'monotonic_end': duration},
artifacts=[dict(receipts.identify_file(output / 'events.jsonl'), path='events.jsonl',
role='input_events', duration_seconds=duration)], derivatives=[],
events=[dict(name=e['name'], artifact='events.jsonl', media_seconds=e['elapsed_seconds'],
elapsed_seconds=e['elapsed_seconds'], method=e['method'], uncertainty_seconds=0,
simulation_tick=e['simulation_tick']) for e in records],
limitations=['Bounded injected fixture; observer perturbs timing'], missing_evidence=[],
acceptance={'state': 'open', 'remaining': ['Full native route and audiovisual review required']})
def test_actual_fixture_emits_requested_and_accepted_input(self):
_, output, summary, records, _ = self.observed_fixture()
self.assertFalse(summary['incomplete'])
self.assertEqual(summary['evidence_kind'], 'port_fixture')
inputs = [e for e in records if e['name'] == 'input_step']
self.assertTrue(any(not e['data']['accepts_input'] and e['data']['requested_input']['forward'] for e in inputs))
self.assertTrue(any(e['data']['accepts_input'] for e in inputs))
result = receipts.validate_receipt(self.receipt(output, summary, records), output)
self.assertTrue(result['valid'])
self.assertFalse(result['accepted'])
def test_fixture_cannot_promote_native_acceptance(self):
_, output, summary, records, _ = self.observed_fixture()
receipt = self.receipt(output, summary, records)
receipt['acceptance']['state'] = 'accepted'
with self.assertRaises(ValueError): receipts.validate_receipt(receipt, output)
def test_missing_output_and_incomplete_records_do_not_qualify(self):
_, output, summary, records, _ = self.observed_fixture()
receipt = self.receipt(output, summary, records)
receipt['status'] = 'aborted'
self.assertFalse(receipts.validate_receipt(receipt, output)['accepted'])
(output / 'events.jsonl').unlink()
with self.assertRaises((ValueError, OSError)): receipts.validate_receipt(receipt, output)
def test_retained_continuation_keeps_one_ordered_session_clock(self):
with tempfile.TemporaryDirectory(prefix='gameport-observer-return-') as temporary:
output = Path(temporary) / 'observation'
result = self.run_port('--headless', '--mute', '--no-validation', '--smoke-practice-return',
'--width', '320', '--height', '240', '--fidelity-output', output,
'--fidelity-session', 'retained-process', '--fidelity-case', 'retained-skipped-edge')
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
records = [json.loads(line) for line in (output / 'events.jsonl').read_text().splitlines()]
entries = [e for e in records if e['name'] == 'scene_entry']
self.assertEqual([e['scene'] for e in entries], ['LV1B', 'VR04', 'LV1B'],
'actual continuation must publish source/destination scene entries')
self.assertEqual([e['data']['returning'] for e in entries], [False, False, True])
self.assertEqual([e['data']['retained_player'] for e in entries], [False, True, True])
departures = [e for e in records if e['name'] == 'scene_departure']
self.assertEqual(len(departures), 2)
self.assertEqual([e['data']['departure_sequence'] for e in entries[1:]],
[e['sequence'] for e in departures])
self.assertEqual(departures[-1]['data']['returning'], True)
self.assertEqual({e['session_id'] for e in records}, {'retained-process'})
self.assertEqual({e['evidence_kind'] for e in records}, {'port_fixture'})
self.assertEqual([e['sequence'] for e in records], list(range(1, len(records) + 1)))
times = [e['elapsed_seconds'] for e in records]
self.assertEqual(times, sorted(times))
def test_observed_off_fixture_state_and_readbacks_match(self):
with tempfile.TemporaryDirectory(prefix='gameport-observer-parity-') as temporary:
root = Path(temporary)
on, off = root / 'on', root / 'off'
on.mkdir(); off.mkdir()
enabled, disabled = self.fixture(on), self.fixture(off, observed=False)
captures = sorted(p.name for p in on.glob('*.ppm'))
self.assertGreaterEqual(len(captures), 4)
self.assertEqual(captures, sorted(p.name for p in off.glob('*.ppm')))
for name in captures:
self.assertEqual((on / name).read_bytes(), (off / name).read_bytes(), name)
prefixes = ('Movement ', 'Carl ', 'Control-phase ', 'Scene sequence:', 'Simulation:')
self.assertEqual([s for s in enabled.stdout.splitlines() if s.startswith(prefixes)],
[s for s in disabled.stdout.splitlines() if s.startswith(prefixes)])
def test_skip_and_natural_paths_are_distinct(self):
_, _, _, records, _ = self.observed_fixture()
skips = [e for e in records if e['name'] == 'dialogue_skip']
self.assertTrue(skips, 'fixture uses actual skip paths')
self.assertTrue(all(e['method'].startswith('skip:') for e in skips))
ends = [e for e in records if e['name'] == 'dialogue_end']
self.assertTrue(any(e['method'].startswith('skip:') for e in ends))
self.assertFalse(any(e['method'] == 'natural_director_step' for e in ends))
if __name__ == '__main__':
unittest.main()
+290
View File
@@ -0,0 +1,290 @@
"""Synthetic media tests prove local review plumbing, never game acceptance."""
import copy
import importlib
import json
from pathlib import Path
import subprocess
import sys
import tempfile
import threading
import unittest
import urllib.error
import urllib.request
import wave
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tools/recon'))
import fidelity_receipts as receipts
try:
review = importlib.import_module('fidelity_review')
except ModuleNotFoundError:
review = None
def fixture(base, side):
bundle = base / side
bundle.mkdir()
for name in ('video.wav', 'audio.wav'):
with wave.open(str(bundle / name), 'wb') as stream:
stream.setparams((1, 2, 8000, 0, 'NONE', 'uncompressed'))
stream.writeframes(b'\0\0' * 16000)
(bundle / 'trace.json').write_text('{"fixture": true}')
items = [dict(receipts.identify_file(bundle / name), path=name, role=role,
synthetic=True, **({'duration_seconds': 2} if role != 'input_events' else {}))
for name, role in [('video.wav', 'video'), ('audio.wav', 'audio'),
('trace.json', 'input_events')]]
value = dict(schema_version=1, receipt_id='test-' + side, session_id='test-session',
case_id='test-only', evidence_kind='synthetic', status='captured',
scope='tooling-test', historical=False, identity={},
platform={'os': 'test', 'execution': 'synthetic'},
invocation={'argv': ['fixture'], 'cwd': '.'},
clocks={'wall_start': '2026-01-01T00:00:00Z',
'wall_end': '2026-01-01T00:00:02Z',
'monotonic_start': 0, 'monotonic_end': 2},
artifacts=items, derivatives=[],
events=[dict(name='landing', artifact='video.wav', media_seconds=0.5,
elapsed_seconds=0.5, method='procedural', uncertainty_seconds=0.02)],
limitations=['Synthetic silent audio fixture; no original execution'],
missing_evidence=[], acceptance={'state': 'open', 'remaining': ['Real capture required']})
path = bundle / 'receipt.json'
path.write_text(json.dumps(value))
imported = receipts.import_receipt(path, bundle, base / 'test-imports')
return Path(imported['path']), value
class FidelityReview(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory(prefix='fidelity-review-test-')
self.addCleanup(self.temp.cleanup)
self.base = Path(self.temp.name)
self.original, self.value = fixture(self.base, 'original')
self.port, _ = fixture(self.base, 'port')
self.output = self.base / 'test-review'
def api(self):
self.assertIsNotNone(review, 'contained review export/server must exist')
return review
def export(self, **kwargs):
return self.api().export_review(kwargs.pop('original', self.original),
kwargs.pop('port', self.port), self.output, **kwargs)
def server(self):
server = self.api().make_server(self.output, port=0)
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
self.addCleanup(server.server_close)
self.addCleanup(thread.join, 2)
self.addCleanup(server.shutdown)
return 'http://127.0.0.1:' + str(server.server_port)
def request(self, url, method='GET', headers=None):
request = urllib.request.Request(url, method=method, headers=headers or {})
try:
return urllib.request.urlopen(request, timeout=3)
except urllib.error.HTTPError as error:
return error
def test_cli_import_export_http_round_trip(self):
cli = ROOT / 'tools/recon/fidelity_review.py'
self.assertTrue(cli.is_file(), 'review CLI must export an imported pair')
result = subprocess.run([sys.executable, str(cli), 'export', '--original', str(self.original),
'--port', str(self.port), '--output', str(self.output)],
capture_output=True, text=True, timeout=15)
self.assertEqual(result.returncode, 0, result.stderr)
url = self.server()
with self.request(url + '/review.json') as response:
model = json.load(response)
self.assertEqual(model['acceptance']['state'], 'open')
self.assertEqual(model['events'][0]['name'], 'landing')
for side in ('original', 'port'):
self.assertEqual(model['sides'][side]['evidence_kind'], 'synthetic')
with self.request(url + '/' + model['sides'][side]['media']['url']) as response:
self.assertTrue(response.read().startswith(b'RIFF'))
def test_export_keeps_raw_derivatives_and_links(self):
data = self.export()
for side in data['sides'].values():
self.assertEqual({x['role'] for x in side['artifacts']}, {'video', 'audio', 'input_events'})
self.assertTrue((self.output / side['receipt_url']).is_file())
self.assertEqual(side['derivatives'], [])
def test_missing_original_explicit(self):
data = self.export(original=None)
self.assertIn('Missing original', data['sides']['original']['missing'])
self.assertIsNone(data['sides']['original']['media'])
def test_empty_review_is_explicit(self):
data = self.export(original=None, port=None)
self.assertEqual(data['events'], [])
self.assertEqual(data['acceptance']['state'], 'open')
def test_tampered_artifact_rejected(self):
(self.port.parent / 'video.wav').write_bytes(b'changed')
with self.assertRaises(ValueError): self.export()
self.assertFalse(self.output.exists())
def test_tampered_receipt_sidecar_rejected(self):
self.port.write_text('{}')
with self.assertRaises(ValueError): self.export()
def test_traversal_absolute_remote_and_symlink_references_rejected(self):
(self.original.parent / 'receipt.sha256').unlink()
for path in ('../secret', '/secret', 'C:/secret', 'https://host/a', 'a\\b'):
value = copy.deepcopy(self.value)
value['artifacts'][0]['path'] = path
raw = self.original.parent / 'raw.json'
raw.write_text(json.dumps(value))
with self.assertRaisesRegex(ValueError, 'reference|Reference'):
self.api().export_review(raw, None, self.output)
(self.original.parent / 'video.wav').unlink()
(self.original.parent / 'video.wav').symlink_to(self.port.parent / 'video.wav')
with self.assertRaises(ValueError): self.export()
def test_labels_are_json_text_never_interpolated_html(self):
value = copy.deepcopy(self.value)
hostile = '</script><img src=x onerror=alert(1)>'
value['limitations'].append(hostile)
raw = self.original.parent / 'raw.json'
raw.write_text(json.dumps(value))
# A new collector bundle has no import sidecar; do not reuse another
# receipt's immutable metadata identity for this changed observation.
(self.original.parent / 'receipt.sha256').unlink()
data = self.api().export_review(raw, None, self.output)
self.assertIn(hostile, data['sides']['original']['limitations'])
self.assertNotIn(hostile, (self.output / 'index.html').read_text())
self.assertNotIn('innerHTML', (self.output / 'viewer.mjs').read_text())
def test_event_out_of_range_rejected(self):
(self.original.parent / 'receipt.sha256').unlink()
value = copy.deepcopy(self.value)
value['events'][0]['media_seconds'] = 3
raw = self.original.parent / 'raw.json'
raw.write_text(json.dumps(value))
with self.assertRaisesRegex(ValueError, 'exceeds'):
self.api().export_review(raw, None, self.output)
def test_duplicate_event_is_ambiguous_not_silently_selected(self):
(self.original.parent / 'receipt.sha256').unlink()
value = copy.deepcopy(self.value)
value['events'].append(copy.deepcopy(value['events'][0]))
raw = self.original.parent / 'raw.json'
raw.write_text(json.dumps(value))
with self.assertRaisesRegex(ValueError, 'Ambiguous'):
self.api().export_review(raw, None, self.output)
def test_cross_case_pair_rejected(self):
(self.original.parent / 'receipt.sha256').unlink()
value = copy.deepcopy(self.value)
value['case_id'] = 'other-case'
raw = self.original.parent / 'raw.json'
raw.write_text(json.dumps(value))
with self.assertRaisesRegex(ValueError, 'same case'):
self.api().export_review(raw, self.port, self.output)
def test_lossless_stills_and_derivative_ancestry_remain_linked(self):
(self.original.parent / 'receipt.sha256').unlink()
value = copy.deepcopy(self.value)
# A byte-identified derivative record tests ancestry retention only;
# browser/PNG validation is separately required before image differences.
(self.original.parent / 'still.png').write_bytes(b'test-only not a PNG')
value['artifacts'].append(dict(receipts.identify_file(self.original.parent / 'still.png'),
path='still.png', role='lossless_still', synthetic=True))
value['derivatives'].append({'path': 'still.png', 'source': 'video.wav',
'tool': 'synthetic fixture', 'argv': ['inert']})
raw = self.original.parent / 'raw.json'
raw.write_text(json.dumps(value))
data = self.api().export_review(raw, None, self.output)
self.assertEqual(data['sides']['original']['derivatives'], value['derivatives'])
self.assertTrue((self.output / 'sides/original/still.png').is_file())
def test_imported_active_document_served_as_attachment(self):
(self.original.parent / 'receipt.sha256').unlink()
value = copy.deepcopy(self.value)
artifact = self.original.parent / 'untrusted.html'
artifact.write_text('<script>alert(1)</script>')
value['artifacts'].append(dict(receipts.identify_file(artifact), path='untrusted.html', role='note'))
raw = self.original.parent / 'raw.json'
raw.write_text(json.dumps(value))
self.api().export_review(raw, None, self.output)
with self.request(self.server() + '/sides/original/untrusted.html') as response:
self.assertEqual(response.headers['Content-Type'], 'application/octet-stream')
self.assertEqual(response.headers['Content-Disposition'], 'attachment')
def test_existing_or_overlapping_output_rejected(self):
with self.assertRaises(ValueError): self.api().export_review(self.original, self.port, self.original.parent)
self.export()
with self.assertRaises(ValueError): self.export()
def test_head_and_ranges_seek_actual_bytes(self):
data = self.export()
url = self.server() + '/' + data['sides']['port']['media']['url']
for range_value, expected in [('bytes=0-3', b'RIFF'), ('bytes=-4', b'\0' * 4),
('bytes=4-', (self.port.parent / 'video.wav').read_bytes()[4:])]:
with self.request(url, headers={'Range': range_value}) as response:
self.assertEqual(response.status, 206)
self.assertEqual(response.read(), expected)
self.assertIn('Content-Range', response.headers)
with self.request(url, 'HEAD', {'Range': 'bytes=0-3'}) as response:
self.assertEqual(response.status, 206)
self.assertEqual(response.headers['Content-Length'], '4')
self.assertEqual(response.read(), b'')
def test_bad_ranges_return_416(self):
self.export()
url = self.server() + '/index.html'
for value in ('bytes=9-2', 'bytes=999999-', 'bytes=0-1,4-5', 'bytes=-0', 'nonsense'):
with self.request(url, headers={'Range': value}) as response:
self.assertEqual(response.status, 416)
def test_server_rejects_escape_symlink_and_directory(self):
self.export()
(self.output / 'escape').symlink_to(self.port.parent / 'video.wav')
url = self.server()
for path in ('/%2e%2e/tools.yaml', '/escape', '/sides/', '/%2fetc/passwd'):
with self.request(url + path) as response:
self.assertIn(response.status, (400, 403, 404))
def test_write_methods_forbidden(self):
self.export()
url = self.server()
for method in ('POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'):
with self.request(url + '/review.json', method) as response:
self.assertEqual(response.status, 405)
def test_only_generated_root_loopback_and_security_headers(self):
with self.assertRaises(ValueError): self.api().make_server(ROOT, port=0)
self.export()
with self.assertRaises(ValueError): self.api().make_server(self.output, port=0, host='0.0.0.0')
with self.request(self.server() + '/') as response:
self.assertEqual(response.status, 200)
self.assertEqual(response.headers['X-Content-Type-Options'], 'nosniff')
self.assertIn("default-src 'none'", response.headers['Content-Security-Policy'])
def test_ledger_sources_are_validated_copied_and_linked(self):
ledger = self.base / 'ledger.json'
ledger.write_text(json.dumps({'schema_version': 1, 'capabilities': [{'id': 'test', 'source_links':
[{'label': 'Progress', 'path': 'docs/progress.md'}, {'label': 'Missing', 'path': 'docs/absent-fixture.md'}]}]}))
data = self.export(ledger=ledger)
links = data['ledger']['capabilities'][0]['source_links']
self.assertTrue(links[0]['validated_local'])
self.assertEqual((self.output / links[0]['href']).read_bytes(), (ROOT / 'docs/progress.md').read_bytes())
self.assertIsNone(links[1]['href'])
self.assertIn('Missing', links[1]['missing'])
with self.request(self.server() + '/' + links[0]['href']) as response:
self.assertEqual(response.headers['Content-Type'], 'text/plain; charset=utf-8')
self.assertTrue(response.read())
def test_ledger_source_paths_and_mismatched_hashes_rejected(self):
ledger = self.base / 'ledger.json'
for path in ('../Original/game.exe', 'https://host/a', '.git/config', 'artifacts/test.log'):
ledger.write_text(json.dumps({'schema_version': 1, 'capabilities': [{'source_links': [{'label': 'bad', 'path': path}]}]}))
with self.assertRaises(ValueError): self.export(ledger=ledger)
ledger.write_text(json.dumps({'schema_version': 1, 'capabilities': [{'source_links':
[{'label': 'bad hash', 'path': 'docs/progress.md', 'sha256': '0' * 64}]}]}))
with self.assertRaisesRegex(ValueError, 'hash mismatch'): self.export(ledger=ledger)
if __name__ == '__main__':
unittest.main()
+61 -3
View File
@@ -89,8 +89,13 @@ class FidelityScenarios(unittest.TestCase):
duration_seconds=100))
identity = {}
for key in ('executable', 'package', 'resources', 'launcher', 'source', 'original_pre',
'original_post', 'copy_pre', 'copy_post', 'dxwnd', 'dxwnd_config'):
identity[key] = dict(api.identify_file(d / 'setup.txt'), path='setup.txt')
'original_post', 'copy_pre', 'copy_post', 'retained_copy', 'dxwnd', 'dxwnd_config'):
if key in ('copy_pre', 'retained_copy'):
path = d / (key + '.json')
path.write_text(json.dumps({'copy_state': key, 'session': d.name}))
else:
path = d / 'setup.txt'
identity[key] = dict(api.identify_file(path), path=path.name)
identity['source'].update(commit='a' * 40, dirty=False, diff_sha256='b' * 64)
required = api.required_events(p, c, obligation)
events = [dict(name=name, artifact='video.txt', media_seconds=index + 2,
@@ -117,7 +122,7 @@ class FidelityScenarios(unittest.TestCase):
'continuity': {'lifetime_id': d.name, 'departure_session_id': d.name,
'return_session_id': d.name, 'prerequisite_artifact': 'setup.txt',
'copy_pre_sha256': identity['copy_pre']['sha256'],
'retained_copy_sha256': identity['copy_post']['sha256']}}
'retained_copy_sha256': identity['retained_copy']['sha256']}}
return value, d
def test_identified_metadata_cell_can_cover_one_obligation(self):
@@ -143,6 +148,41 @@ class FidelityScenarios(unittest.TestCase):
del value['continuity']['retained_copy_sha256']
self.assertEqual(api.audit_scenarios(self.protocol(), [(value, root)])['accepted'], 0)
def test_copy_continuity_requires_named_state_for_both_lifetimes(self):
for lifetime in ('fresh', 'retained'):
for digest in ('f' * 64, 'launcher', 'package'):
with self.subTest(lifetime=lifetime, digest=digest):
value, root = self.receipt(lifetime + '-natural-ordinary', 'dialogue-return')
self.assertEqual(api.audit_scenarios(self.protocol(), [(value, root)])['accepted'], 1)
value['continuity']['copy_pre_sha256'] = (
value['identity'][digest]['sha256'] if digest in value['identity'] else digest)
result = api.audit_scenarios(self.protocol(), [(value, root)])
self.assertEqual(result['accepted'], 0)
self.assertTrue(result['invalid'])
def test_retained_snapshot_cannot_bind_unrelated_identity(self):
for name in ('copy_pre', 'copy_post', 'launcher'):
value, root = self.receipt()
value['continuity']['retained_copy_sha256'] = value['identity'][name]['sha256']
self.assertEqual(api.audit_scenarios(self.protocol(), [(value, root)])['accepted'], 0)
def test_copy_state_requires_backing_files_for_both_lifetimes(self):
for lifetime in ('fresh', 'retained'):
for name in ('copy_pre', 'retained_copy') if lifetime == 'retained' else ('copy_pre',):
for defect in ('hash-only', 'missing-file', 'wrong-size'):
with self.subTest(lifetime=lifetime, name=name, defect=defect):
value, root = self.receipt(lifetime + '-natural-ordinary', 'dialogue-return')
item = value['identity'][name]
if defect == 'hash-only':
value['identity'][name] = {'sha256': item['sha256']}
elif defect == 'missing-file':
(root / item['path']).unlink()
else:
item['size'] += 1
result = api.audit_scenarios(self.protocol(), [(value, root)])
self.assertEqual(result['accepted'], 0)
self.assertTrue(result['invalid'])
def test_reset_timestamps_fail(self):
value, root = self.receipt()
value['events'][-1]['elapsed_seconds'] = 0
@@ -170,6 +210,24 @@ class FidelityScenarios(unittest.TestCase):
value['acceptance'] = {'state': 'open', 'remaining': [status]}
self.assertEqual(api.audit_scenarios(self.protocol(), [(value, root)])['accepted'], 0)
def test_aborted_missing_end_clocks_imports_without_invented_observations(self):
value, root = self.receipt()
value['status'] = 'aborted'
value['acceptance'] = {'state': 'open', 'remaining': ['interrupted']}
value['events'] = []
for field in ('wall_end', 'monotonic_end'):
del value['clocks'][field]
(root / 'receipt.json').write_bytes(api.canonical_bytes(value))
imported = api.import_receipt(root / 'receipt.json', root, self.base / 'imports')
path = Path(imported['path'])
saved = api.read_receipt(path)
result = api.validate_receipt(saved, path.parent)
self.assertFalse(result['accepted'])
self.assertNotIn('wall_end', saved['clocks'])
self.assertNotIn('monotonic_end', saved['clocks'])
value['status'] = 'reviewed'
with self.assertRaises(ValueError): api.validate_receipt(value, root)
def test_missing_event_and_media_out_of_range_rejected(self):
value, root = self.receipt()
value['events'].pop()
+195
View File
@@ -0,0 +1,195 @@
#!/usr/bin/env python3
"""Offline checkpoint readiness and strict original/native acceptance.
Human findings are declarations bound to exact receipts, never inferred from
successful tools. --allow-open is structural inspection, not acceptance.
"""
import argparse
import hashlib
from pathlib import Path
import sys
# A bundled CLI must not create bytecode inside the sealed checkpoint.
if __name__ == '__main__':
sys.dont_write_bytecode = True
from fidelity_checkpoint import MATERIALS, PROJECT, _package, preflight
from fidelity_receipts import (audit_scenarios, canonical_bytes, contained_path,
identify_file, identify_tree, read_json, read_receipt, validate_receipt,
validate_scenario_contract)
CHECKS = ('A1', 'A2', 'EVID-02-unclassified', 'EVID-04-unclassified',
'P1', 'P2', 'P3', 'browser', 'paired_review', 'physical_input')
def ready(checkpoint):
root = Path(checkpoint)
checked = preflight(root)
manifest = read_json(root / 'manifest.json')
if manifest['tooling_only']:
raise ValueError('Synthetic checkpoint is tooling-only, not final materials')
names = {entry['path'] for entry in manifest['files']}
required = set(MATERIALS) | {'protocol/scenarios.json', 'protocol/capabilities.json',
'protocol/agenda.json', 'protocol/settings-template.json', 'protocol/capability-ledger.json',
'protocol/annotation-template.json', 'review/index.html', 'review/viewer.mjs',
'review/review.json'}
if required - names:
raise ValueError('Missing final session materials: ' + ', '.join(sorted(required - names)))
# A source checkout must not hand off an older tooling/checklist copy after
# later edits. On a transferred checkpoint PROJECT is the checkpoint itself.
for name in MATERIALS:
if identify_file(PROJECT / name) != identify_file(root / name):
raise ValueError('Final material differs from current source; assemble a fresh checkpoint: ' + name)
protocol = read_json(root / 'protocol/scenarios.json')
validate_scenario_contract(protocol)
for rid, identity in manifest['packages'].items():
if _package(root / 'port' / rid, rid, False) != identity:
raise ValueError('Package/observer identity inconsistent: ' + rid)
agenda = read_json(root / 'protocol/agenda.json')
expected = {(s, c['id'], o) for s in ('original-windows-dxwnd', 'port-windows-native')
for c in protocol['cells'] for o in c['obligations']}
actual = {(r['side'], r['case_id'], r['obligation_id']) for r in agenda['runs']}
if actual != expected or len(agenda['runs']) != 80:
raise ValueError('Incomplete or duplicate Windows session agenda')
# Exported ledger links are already normalized by the exporter. Recheck
# every active link against the sealed actual materials at final handoff.
ledger = read_json(root / 'review/review.json')['ledger']
expected_ledger = read_json(root / 'protocol/capability-ledger.json')
for field in ('current', 'history'):
if [(row['id'], row.get(field)) for row in ledger['capabilities']] != [
(row['id'], row[field]) for row in expected_ledger['capabilities']]:
raise ValueError('Malformed viewer ledger projection: ' + field)
for capability in ledger['capabilities']:
for link in capability.get('source_links', []):
if link.get('href'):
identify_file(contained_path(root / 'review', link['href']))
return {'schema_version': 1, 'materials_ready': checked['status'] == 'ready',
'checked_files': checked['checked_files'], 'acceptance': 'human_needed',
'required': 120, 'pending': list(CHECKS),
'meaning': 'Identified offline materials only; all execution/review remains separate'}
def _bind(receipt, root, manifest, original_inventory=None):
identity = receipt['identity']
if receipt['evidence_kind'] == 'native_port':
rid = {'linux': 'linux-x64', 'windows': 'win-x64'}[receipt['platform']['os']]
expected = manifest['packages'][rid]
if identity['executable']['sha256'] != expected['executable']['sha256']:
raise ValueError('Wrong current executable identity')
if identity['source']['sha256'] not in (expected['build_info']['sha256'], expected['seal']['sha256']):
raise ValueError('Wrong current source identity')
if any(identity['source'].get(k) != expected['build']['source'].get(k)
for k in ('commit', 'dirty', 'diff_sha256')):
raise ValueError('Wrong source revision/dirty/diff provenance')
package = read_json(contained_path(root, identity['package']['path']))
resources = read_json(contained_path(root, identity['resources']['path']))
if (package.get('source') != expected['build']['source'] or
identity['package']['sha256'] != expected['seal']['sha256']):
raise ValueError('Wrong current package seal/source')
if resources != expected['resources'] and identity['resources']['sha256'] != expected['seal']['sha256']:
raise ValueError('Wrong current resources')
elif receipt['evidence_kind'] == 'original_dxwnd':
files = (original_inventory or {}).get('files')
if not isinstance(files, list) or not files:
raise ValueError('Missing authoritative original file inventory')
digest = hashlib.sha256(canonical_bytes(files)).hexdigest()
if (digest != manifest['original_pre']['tree_sha256'] or
len(files) != manifest['original_pre']['count']):
raise ValueError('Wrong authoritative original inventory')
for key in ('original_pre', 'original_post', 'package', 'resources'):
inventory = read_json(contained_path(root, identity[key]['path']))
if inventory.get('files') != files or inventory.get('tree_sha256') != digest:
raise ValueError('Wrong authoritative original inventory: ' + key)
executable = identity['executable']
member = executable.get('original_member')
expected = next((item for item in files if item['path'] == member), None)
if not expected or any(executable.get(k) != expected[k] for k in ('sha256', 'size', 'header')):
raise ValueError('Wrong selected original executable member identity')
def audit_records(protocol, manifest, records, review, original_inventory=None):
errors, usable, seen = [], [], set()
if manifest.get('tooling_only'):
errors.append('Synthetic checkpoint cannot qualify as runtime evidence')
for receipt, root in records:
label = str(receipt.get('receipt_id', '<missing>'))
try:
if label in seen:
raise ValueError('Duplicate/conflicting receipt ID; retain history outside current selection')
seen.add(label)
valid = validate_receipt(receipt, root)
if receipt.get('superseded_by') or receipt.get('historical'):
raise ValueError('Superseded/historical receipt is not current applicability')
if valid['accepted']:
_bind(receipt, root, manifest, original_inventory)
usable.append((receipt, root))
except (KeyError, TypeError, ValueError, OSError) as error:
errors.append(label + ': ' + str(error))
matrix = audit_scenarios(protocol, usable)
errors.extend(matrix['invalid'])
checks = review.get('checks', {})
human_needed = [key for key in CHECKS if not (isinstance(checks.get(key), dict)
and checks[key].get('observed') is True and checks[key].get('reviewer')
and checks[key].get('notes'))]
if set(review.get('receipt_ids', [])) != seen:
errors.append('Human review must bind the exact selected receipt IDs')
passed = matrix['complete'] and not errors and not human_needed
return {'schema_version': 1, 'materials_ready': True,
'acceptance': 'passed' if passed else 'human_needed', 'matrix': matrix,
'errors': errors, 'human_needed': human_needed,
'meaning': 'Declared reviewed evidence; no automatic physical/audible truth or universal tolerance'}
def audit(checkpoint, results):
root, results = Path(checkpoint), Path(results)
ready(root)
manifest = read_json(root / 'manifest.json')
for rid, package in manifest['packages'].items():
package['seal'] = identify_file(root / 'port' / rid / 'fidelity-build.json')
# A strict, explicit selection prevents newest-date selection and preserves
# failed/superseded histories. The tree walk rejects symlinks/case aliases.
identify_tree(results)
selection = results / 'current.json'
paths = read_json(selection).get('receipts', []) if selection.exists() else []
if not isinstance(paths, list) or len(paths) > 120 or len(set(paths)) != len(paths):
raise ValueError('Current receipt selection must be a bounded unique array')
records, selected = [], []
for name in paths:
path = contained_path(results, name)
records.append((read_receipt(path), path.parent))
selected.append(path)
review_path = results / 'human-review.json'
review = read_json(review_path) if review_path.exists() else {}
# Bind review to actual receipt bytes, not just reusable labels.
for (receipt, _), path in zip(records, selected):
expected = review.get('receipt_sha256', {}).get(receipt['receipt_id'])
if expected != identify_file(path)['sha256']:
review = dict(review, checks={})
break
return audit_records(read_json(root / 'protocol/scenarios.json'), manifest, records, review,
read_json(root / 'protocol/original-manifest.json'))
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
sub = parser.add_subparsers(dest='command', required=True)
prepare = sub.add_parser('ready')
prepare.add_argument('--checkpoint', type=Path, required=True)
check = sub.add_parser('audit')
check.add_argument('--checkpoint', type=Path, required=True)
check.add_argument('--results', type=Path, required=True)
mode = check.add_mutually_exclusive_group(required=True)
mode.add_argument('--require-complete', action='store_true')
mode.add_argument('--allow-open', action='store_true')
args = parser.parse_args(argv)
try:
report = ready(args.checkpoint) if args.command == 'ready' else audit(args.checkpoint, args.results)
print(canonical_bytes(report).decode())
return 0 if args.command == 'ready' or args.allow_open or report['acceptance'] == 'passed' else 1
except (ValueError, OSError, KeyError, TypeError) as error:
print('Fidelity audit failed; acceptance OPEN: ' + str(error), file=sys.stderr)
return 2
if __name__ == '__main__':
sys.exit(main())
+490
View File
@@ -0,0 +1,490 @@
#!/usr/bin/env python3
"""Local Linux capture. Collection never grants physical/audible acceptance.
Only tool-owned argument arrays execute. Immutable package bytes are checked at
both boundaries; output is fresh and disjoint. No original is executed or copied.
X11/Pulse are the implemented external recorder sources; unsupported sources
produce precise failed receipts rather than dummy fallback recordings.
"""
import argparse
import hashlib
import json
import math
import os
from pathlib import Path
import platform
import re
import shutil
import signal
import subprocess
import sys
import tempfile
import time
# A bundled CLI must not create bytecode inside the sealed checkpoint.
if __name__ == '__main__':
sys.dont_write_bytecode = True
from fidelity_checkpoint import _package
from fidelity_receipts import (MAX_JSON_BYTES, _id, _write_json, canonical_bytes,
contained_path, identify_file, import_receipt, read_json, separated_roots,
utc_now, validate_receipt, validate_scenario_contract, required_events,
_scenario_observation, read_receipt)
PROJECT = Path(__file__).resolve().parents[2]
MAX_SECONDS = 3600
MAX_LOG = 32 * 1024**2
MAX_MEDIA = 8 * 1024**3
def command_probe(argv, timeout=10):
"""Bound subprocess lifetime and returned metadata; no unbounded PIPE buffer."""
try:
with tempfile.TemporaryFile() as log:
process = subprocess.Popen(argv, stdout=log, stderr=log, start_new_session=True)
try:
code = process.wait(timeout=timeout)
except subprocess.TimeoutExpired:
os.killpg(process.pid, signal.SIGKILL)
process.wait(timeout=5)
code = None
log.seek(0)
data = log.read(MAX_JSON_BYTES + 1)
error = 'metadata timeout' if code is None else None
if len(data) > MAX_JSON_BYTES:
error = 'metadata exceeds 4 MiB'; data = data[:MAX_JSON_BYTES]
return {'argv': argv, 'exit_code': code, 'stdout': data.decode('utf8', errors='replace'), 'error': error}
except OSError as error:
return {'argv': argv, 'exit_code': None, 'stdout': '', 'error': str(error)}
def _settings(settings):
expected = {'display_method', 'display', 'audio_method', 'audio_source',
'input_method', 'size', 'offset'}
if set(settings) != expected or any(not isinstance(v, str) or len(v) > 256 for v in settings.values()):
raise ValueError('Settings require exactly the documented bounded string fields')
if settings['input_method'] not in ('physical', 'automated', 'headless'):
raise ValueError('Unknown input method')
if not re.fullmatch(r'[1-9][0-9]{1,3}x[1-9][0-9]{1,3}', settings['size']):
raise ValueError('Explicit bounded capture size required')
if not re.fullmatch(r'[0-9]{1,5},[0-9]{1,5}', settings['offset']):
raise ValueError('Explicit nonnegative X11 offset required')
if settings['display'] and not re.fullmatch(r':[0-9]{1,5}(?:\.[0-9]{1,2})?', settings['display']):
raise ValueError('Only local X11 displays are supported')
if settings['audio_source'] and not re.fullmatch(r'[A-Za-z0-9_.-]{1,200}', settings['audio_source']):
raise ValueError('Explicit local Pulse source name required')
return dict(settings)
def preflight(package, settings, tooling=False, probe=command_probe):
settings = _settings(settings)
blockers, observations = [], {}
package = Path(package).resolve(strict=True)
identity = None
try:
identity = _package(package, 'linux-x64', tooling)
if not os.access(package / 'GamePort', os.X_OK):
blockers.append('Identified Linux apphost is not executable')
except (ValueError, OSError) as error:
blockers.append('Package identity: ' + str(error))
if platform.system() != 'Linux': blockers.append('Native Linux host required')
for name, argv in {'recorder': ['ffmpeg', '-version'], 'media_probe': ['ffprobe', '-version'],
'pulse_sources': ['pactl', 'list', 'short', 'sources'],
'pulse_sinks': ['pactl', 'list', 'short', 'sinks'],
'gpu': ['lspci', '-nn'], 'vulkan': ['vulkaninfo', '--summary']}.items():
observations[name] = probe(argv, timeout=10)
executable = shutil.which(argv[0])
if executable:
observations[name]['executable'] = {'path': str(Path(executable).resolve()),
**identify_file(Path(executable).resolve())}
for name in ('recorder', 'media_probe'):
if observations[name]['exit_code'] != 0 or observations[name]['error']:
blockers.append('Unavailable local ' + name)
if settings['display_method'] != 'x11' or not settings['display']:
blockers.append('No selected usable X11 display; Wayland/TTY capture requires a separately verified recorder')
else:
result = probe(['ffmpeg', '-nostdin', '-hide_banner', '-f', 'x11grab',
'-video_size', settings['size'], '-i', settings['display'] + '+' + settings['offset'],
'-frames:v', '1', '-f', 'null', '-'], timeout=10)
observations['display_probe'] = result
if result['exit_code'] != 0 or result['error']: blockers.append('Selected display capture probe failed')
source = settings['audio_source']
if settings['audio_method'] != 'pulse' or not source or any(x in source.lower() for x in ('null', 'dummy')):
blockers.append('No selected real Pulse audio source; null/dummy output cannot prove audible gameplay')
elif observations['pulse_sources']['exit_code'] != 0 or source not in [
line.split()[1] for line in observations['pulse_sources']['stdout'].splitlines() if len(line.split()) >= 2]:
blockers.append('Selected Pulse source is unavailable')
else:
result = probe(['ffmpeg', '-nostdin', '-hide_banner', '-f', 'pulse', '-i', source,
'-t', '0.25', '-f', 'null', '-'], timeout=10)
observations['audio_probe'] = result
if result['exit_code'] != 0 or result['error']: blockers.append('Selected audio capture probe failed')
return {'schema_version': 1, 'ready': not blockers, 'blockers': blockers,
'settings': settings, 'package': identity, 'package_root': str(package),
'host': {'system': platform.system(), 'release': platform.release(),
'machine': platform.machine(), 'session_type': os.environ.get('XDG_SESSION_TYPE'),
'display_env_present': bool(os.environ.get('DISPLAY')),
'wayland_env_present': bool(os.environ.get('WAYLAND_DISPLAY'))},
'observations': observations, 'checked_utc': utc_now(),
'runtime_version_gaps': ['SDL runtime version and active GPU/driver/Vulkan instance require actual game logs'],
'acceptance': {'state': 'open', 'remaining': ['Preflight is not gameplay or audiovisual review']}}
def _stop(process):
"""Signal only a child we own; escalate its own process group after grace."""
try:
process.send_signal(signal.SIGINT)
process.wait(timeout=5)
except subprocess.TimeoutExpired:
try: os.killpg(process.pid, signal.SIGKILL)
except ProcessLookupError: pass
process.wait(timeout=5)
except ProcessLookupError:
pass
def run_capture(package, output, session_id, case_id, scope, settings, seconds=120,
tooling=False, probe=command_probe, popen=subprocess.Popen):
_id(session_id); _id(case_id)
if len(session_id) > 88: raise ValueError('Session ID must leave room for receipt suffix')
protocol = read_json(PROJECT / 'docs/evidence/scenarios.json')
if case_id not in {c['id'] for c in protocol['cells']} or scope not in protocol['obligations']:
raise ValueError('Unknown matrix case or obligation')
if not isinstance(seconds, (int, float)) or not math.isfinite(seconds) or not 1 <= seconds <= MAX_SECONDS:
raise ValueError('Capture duration must be 1..3600 seconds')
package = Path(package).resolve(strict=True)
output = Path(output).absolute()
if any(p.is_symlink() for p in (output, *output.parents)):
raise ValueError('Capture output cannot use symlink aliases')
separated_roots(package, output); separated_roots(PROJECT.parent / 'Original', output)
if output.exists(): raise ValueError('Capture output must be fresh; use a new session ID')
report = preflight(package, settings, tooling, probe)
output.mkdir(parents=True)
_write_json(output / 'preflight.json', report)
identity_dir = output / 'identity'; identity_dir.mkdir()
if report['package']:
for name in ('GamePort', 'fidelity-build.json', 'BUILD-INFO.txt'):
shutil.copyfile(package / name, identity_dir / name)
_write_json(identity_dir / 'resources.json', report['package']['resources'])
shutil.copyfile(Path(__file__), identity_dir / 'collector.py')
start, wall_start = time.monotonic(), utc_now()
game = [str(package / 'GamePort'), '--assets', str(package / 'assets'),
'--load-save', str(package / 'assets/NewGame.tsk'), '--walk',
'--fidelity-output', str(output / 'observer'), '--fidelity-session', session_id,
'--fidelity-case', case_id]
recorder = ['ffmpeg', '-nostdin', '-hide_banner', '-n', '-f', 'x11grab',
'-framerate', '30', '-video_size', settings['size'], '-i',
settings['display'] + '+' + settings['offset'], '-f', 'pulse', '-i',
settings['audio_source'], '-t', str(seconds), '-vf', 'freezedetect=n=-60dB:d=2',
'-c:v', 'ffv1', '-c:a', 'pcm_s16le', '-fs', str(MAX_MEDIA), str(output / 'raw.mkv')]
state = {'schema_version': 1, 'session_id': session_id, 'launch_id': session_id,
'clock_id': session_id + '-monotonic', 'case_id': case_id, 'scope': scope,
'package_root': str(package), 'tooling_only': tooling,
'input_method': settings['input_method'], 'settings': settings,
'invocation': {'argv': game, 'cwd': str(package)}, 'recorder_argv': recorder,
'clocks': {'monotonic_start': start, 'monotonic_end': start,
'wall_start': wall_start, 'wall_end': wall_start,
'clock_id': session_id + '-monotonic'},
'status': 'failed' if not report['ready'] else 'incomplete',
'missing': list(report['blockers']), 'processes': {}}
_write_json(output / 'started.json', state)
processes = []
try:
if report['ready']:
env = dict(os.environ, DISPLAY=settings['display'], SDL_VIDEODRIVER='x11')
if not tooling and (env.get('SDL_AUDIODRIVER') in ('dummy', 'disk') or env.get('SDL_VIDEODRIVER') == 'dummy'):
raise ValueError('Dummy SDL devices cannot be used for native capture')
# Explicit source matches the selected real Pulse system, not a dummy inherited backend.
env['SDL_AUDIODRIVER'] = 'pulseaudio'
with (output / 'recorder.log').open('xb') as recording_log, (output / 'game.log').open('xb') as game_log:
recording = popen(recorder, cwd=output, env=env, stdout=recording_log,
stderr=subprocess.STDOUT, start_new_session=True)
processes.append(recording)
child = popen(game, cwd=package, env=env, stdout=game_log,
stderr=subprocess.STDOUT, start_new_session=True)
processes.append(child)
# One deadline covers both children. Logs/media are checked every wait slice.
deadline = time.monotonic() + seconds + 3
for name, child_process in (('game', child), ('recorder', recording)):
while True:
if any(p.stat().st_size > MAX_LOG for p in (output / 'game.log', output / 'recorder.log')):
raise ValueError('Capture log exceeds 32 MiB bound')
remaining = deadline - time.monotonic()
if remaining <= 0: raise subprocess.TimeoutExpired(game, seconds)
try:
code = child_process.wait(timeout=min(1, remaining))
state['processes'][name] = code
break
except subprocess.TimeoutExpired:
# Doubles and real processes both expose poll; timeout at the
# total deadline remains an abort, never a captured outcome.
if child_process.poll() is not None:
raise
state['status'] = 'captured' if all(c == 0 for c in state['processes'].values()) else 'failed'
if state['status'] == 'failed': state['missing'].append('Game or recorder exited unsuccessfully')
except (KeyboardInterrupt, subprocess.TimeoutExpired):
state['status'] = 'aborted'; state['missing'].append('Capture interrupted or duration deadline exceeded')
except (OSError, ValueError) as error:
state['status'] = 'failed'; state['missing'].append(str(error))
finally:
for process in processes:
if process.poll() is None or state['status'] == 'aborted': _stop(process)
state['clocks'].update(monotonic_end=time.monotonic(), wall_end=utc_now())
_write_json(output / 'session.json', state)
return state
def collect(run, probe=command_probe, annotations=None):
run = Path(run).resolve(strict=True)
state, pre = read_json(run / 'session.json'), read_json(run / 'preflight.json')
if (run / 'receipt.json').exists(): raise ValueError('Receipt already finalized; preserve history')
missing = list(state['missing'])
if pre['package']:
try:
current = _package(Path(state['package_root']), 'linux-x64', state['tooling_only'])
if current != pre['package']: raise ValueError('Package changed since launch')
except (ValueError, OSError) as error:
missing.append('Post-capture package identity failed: ' + str(error))
media = run / 'raw.mkv'
duration = None
if media.exists() and media.stat().st_size > MAX_MEDIA:
missing.append('Raw media exceeds 8 GiB capture bound; preserved locally but excluded from import')
elif media.exists() and media.stat().st_size:
media_probe = probe(['ffprobe', '-v', 'error', '-show_streams', '-show_format',
'-of', 'json', str(media)], timeout=20)
_write_json(run / 'media-probe.json', media_probe)
try:
payload = json.loads(media_probe['stdout'])
duration = float(payload['format']['duration'])
roles = {s.get('codec_type') for s in payload['streams']}
if media_probe['exit_code'] != 0 or media_probe['error'] or not math.isfinite(duration) or duration <= 0:
raise ValueError('Invalid media duration/probe')
if not {'video', 'audio'}.issubset(roles): raise ValueError('Missing video/audio streams')
except (ValueError, KeyError, TypeError) as error:
missing.append('Media inspection failed: ' + str(error)); duration = None
else:
missing.append('Raw video/audio recording missing or empty')
log = run / 'recorder.log'
if log.exists():
if log.stat().st_size > MAX_LOG: missing.append('Recorder log exceeds bounded inspection')
elif 'freeze_start' in log.read_text(errors='replace'):
missing.append('Possible frozen media indicator requires actual visual inspection')
if not (run / 'observer').exists(): missing.append('Passive observer/input events unavailable')
identity = {}
identity_dir = run / 'identity'
if pre['package']:
for key, name in (('executable', 'GamePort'), ('package', 'fidelity-build.json'),
('source', 'BUILD-INFO.txt')):
identity[key] = {'path': 'identity/' + name, **identify_file(identity_dir / name)}
identity['resources'] = {'path': 'identity/resources.json', **identify_file(identity_dir / 'resources.json')}
identity['launcher'] = {'path': 'identity/collector.py', **identify_file(identity_dir / 'collector.py')}
note = read_json(annotations) if annotations else {}
# Explicit local annotations bind actual files; no imported commands execute.
extra_roles = note.get('artifact_roles', {})
if not isinstance(extra_roles, dict) or any(role != 'prerequisite' for role in extra_roles.values()):
raise ValueError('Only explicit prerequisite artifact roles can supplement capture roles')
for name in extra_roles: identify_file(contained_path(run, name))
for key, name in note.get('identity_files', {}).items():
if key not in ('copy_pre', 'retained_copy', 'copy_post'):
raise ValueError('Unsupported annotated copy identity')
identity[key] = {'path': name, **identify_file(contained_path(run, name))}
artifacts = []
count = 0
for path in run.rglob('*'):
count += 1
if count > 10000: raise ValueError('Capture exceeds 10000-entry bound')
if path.is_symlink(): raise ValueError('Symlink in capture output')
if not path.is_file() or path.is_relative_to(identity_dir): continue
bound = MAX_MEDIA if path.suffix == '.mkv' else MAX_LOG
if path.stat().st_size > bound:
missing.append('Artifact exceeds import bound: ' + path.relative_to(run).as_posix())
continue
name = path.relative_to(run).as_posix()
role = 'video' if name == 'raw.mkv' else 'input_events' if name.startswith('observer/') else 'diagnostic'
role = extra_roles.get(name, role)
item = {'path': name, 'role': role, **identify_file(path)}
if state['tooling_only']: item['synthetic'] = True
if name == 'raw.mkv' and duration is not None: item['duration_seconds'] = duration
if role == 'prerequisite' and duration is not None:
if item['sha256'] == identify_file(media)['sha256']:
item['duration_seconds'] = duration
else:
inspection = probe(['ffprobe', '-v', 'error', '-show_format', '-of', 'json', str(path)], timeout=20)
try:
seconds = float(json.loads(inspection['stdout'])['format']['duration'])
if inspection['exit_code'] != 0 or inspection['error'] or not math.isfinite(seconds) or seconds <= 0:
raise ValueError('Invalid prerequisite media duration')
item['duration_seconds'] = seconds
except (ValueError, KeyError, TypeError) as error:
raise ValueError('Cannot identify prerequisite recording duration') from error
artifacts.append(item)
artifacts.sort(key=lambda item: item['path'])
# The same hashed MKV contains both streams; audio role uses a distinct
# byte-identical local alias to satisfy the shared validator's unique paths.
if duration is not None:
shutil.copyfile(media, run / 'raw-audio.mkv')
artifacts.append({'path': 'raw-audio.mkv', 'role': 'audio',
'duration_seconds': duration, **identify_file(run / 'raw-audio.mkv'),
**({'synthetic': True} if state['tooling_only'] else {})})
events = note.get('events', [])
kind = 'synthetic' if state['tooling_only'] else 'native_port' if state['input_method'] == 'physical' else 'port_fixture'
status = state['status']
if status == 'captured' and missing: status = 'failed'
receipt = {'schema_version': 1, 'receipt_id': state['session_id'] + '-linux',
'session_id': state['session_id'], 'case_id': state['case_id'], 'scope': state['scope'],
'obligation_id': state['scope'],
'evidence_kind': kind, 'historical': False, 'status': status,
'platform': {'os': 'linux', 'execution': 'native' if kind == 'native_port' else kind},
'invocation': state['invocation'], 'clocks': state['clocks'], 'identity': identity,
'artifacts': artifacts, 'derivatives': [], 'events': events,
'limitations': ['Collection does not prove visible moving gameplay, physical input or audible output',
'Existing NewGame.tsk entry is not a reconstructed main menu',
'Observer and recording overhead remains part of this identified run'],
'missing_evidence': missing, 'review': {'visible': False, 'audible': False,
'ordinary_input': False, 'human_reviewed': False},
'capture_methods': state['settings'], 'clock_id': state['clock_id'],
'launch_id': state['launch_id'],
'continuity': note.get('continuity', {}),
'acceptance': {'state': 'open', 'remaining': [
'Actual moving-content/crop/clock/physical-input/audibility review',
'Observed scenario markers and lifetime/route continuity validation',
'Original-DxWnd and native Windows comparison']}}
validate_receipt(receipt, run)
_write_json(run / 'receipt.json', receipt)
return receipt
def matrix(protocol, records=(), previous=None, dependency=None):
"""Forty Linux obligations with validated append-only attempt history.
Previous attempts are re-read and hash-checked, never trusted as acceptance.
Distinct failed/incomplete retries require distinct process/session IDs.
A shared environment failure is a dependency, not forty fabricated runs.
"""
validate_scenario_contract(protocol)
cells = {c['id']: c for c in protocol['cells']}
slots = {(c['id'], o): [] for c in protocol['cells'] for o in c['obligations']}
history = []
if previous:
if previous.get('schema_version') != 1 or previous.get('side') != 'port-linux-native':
raise ValueError('Unrecognized previous Linux matrix')
for cell in previous['cells']:
for obligation in cell['obligations']:
for attempt in obligation['attempts']:
path = Path(attempt['receipt_path'])
if identify_file(path)['sha256'] != attempt['receipt_sha256']:
raise ValueError('Historical receipt bytes changed')
history.append((read_receipt(path), path.parent))
seen, sessions = {}, {}
for receipt, root in [*history, *records]:
root = Path(root).resolve(strict=True)
validated = validate_receipt(receipt, root)
key = (receipt['case_id'], receipt.get('obligation_id', receipt['scope']))
if key not in slots: raise ValueError('Unknown Linux matrix slot')
if receipt['platform']['os'] != 'linux': raise ValueError('Linux matrix requires Linux observations')
digest = hashlib.sha256(canonical_bytes(receipt)).hexdigest()
record_id, session_id = receipt['receipt_id'], receipt['session_id']
if record_id in seen:
if seen[record_id] != digest: raise ValueError('Conflicting immutable receipt ID')
continue
if session_id in sessions:
raise ValueError('A new matrix attempt must use a new launch/session ID')
sessions[session_id] = record_id; seen[record_id] = digest
reasons = list(validated['missing_evidence'])
try:
_scenario_observation(protocol, cells[key[0]], receipt, root)
except (ValueError, KeyError, StopIteration) as error:
reasons.append('Scenario continuity: ' + str(error))
if receipt['evidence_kind'] != 'native_port':
reasons.append('Linux native gameplay requires actual native evidence')
path = root / 'receipt.json'
if read_receipt(path) != receipt: raise ValueError('Matrix input differs from saved receipt')
slots[key].append({'receipt_id': record_id, 'session_id': session_id,
'receipt_path': str(path), 'receipt_sha256': identify_file(path)['sha256'],
'status': receipt['status'], 'evidence_kind': receipt['evidence_kind'],
'accepted': validated['accepted'] and not reasons, 'remaining': list(dict.fromkeys(reasons))})
result_cells, accepted = [], 0
for cell in protocol['cells']:
result = {k: cell[k] for k in ('id', 'lifetime', 'dialogue', 'input')}
result['procedures'] = {
'lifetime': protocol['lifetime_procedures'][cell['lifetime']],
'dialogue': protocol['dialogue_procedures'][cell['dialogue']],
'input': protocol['input_procedures'][cell['input']]}
result['obligations'] = []
for obligation_id in cell['obligations']:
attempts = slots[(cell['id'], obligation_id)]
done = any(a['accepted'] for a in attempts)
accepted += int(done)
dependencies = [] if done else list((dependency or {}).get('reasons', []))
if not done:
dependencies += ['Actual Linux ' + cell['id'] + '/' + obligation_id + ' recording and physical/audible review']
dependencies += [reason for a in attempts for reason in a['remaining']]
result['obligations'].append({'id': obligation_id, 'state': 'accepted' if done else 'open',
'attempts': attempts, 'dependencies': list(dict.fromkeys(dependencies)),
'dependency_receipt_id': (dependency or {}).get('receipt_id'),
'required_events': required_events(protocol, cell, obligation_id),
'route': protocol['obligations'][obligation_id].get('route'),
'procedure': protocol['obligations'][obligation_id]})
result_cells.append(result)
return {'schema_version': 1, 'side': 'port-linux-native', 'required': 40,
'accepted': accepted, 'complete': accepted == 40, 'cells': result_cells,
'environment_dependency': dependency,
'acceptance': {'state': 'open', 'remaining': ['Final combined original/native acceptance audit']}}
def main():
parser = argparse.ArgumentParser(description=__doc__)
sub = parser.add_subparsers(dest='action', required=True)
for action in ('preflight', 'run'):
command = sub.add_parser(action)
command.add_argument('--package', type=Path, required=True)
command.add_argument('--settings', type=Path, required=True)
if action == 'run':
command.add_argument('--output', type=Path, required=True)
command.add_argument('--session-id', required=True)
command.add_argument('--case-id', required=True)
command.add_argument('--scope', required=True)
command.add_argument('--seconds', type=float, default=120)
command = sub.add_parser('collect')
command.add_argument('--run', type=Path, required=True)
command.add_argument('--annotations', type=Path)
command.add_argument('--import-to', type=Path)
command = sub.add_parser('matrix')
command.add_argument('--receipt', type=Path, action='append', default=[])
command.add_argument('--previous', type=Path)
command.add_argument('--dependency-run', type=Path)
command.add_argument('--output', type=Path, required=True)
args = parser.parse_args()
if args.action == 'preflight':
result = preflight(args.package, read_json(args.settings))
elif args.action == 'run':
result = run_capture(args.package, args.output, args.session_id, args.case_id,
args.scope, read_json(args.settings), args.seconds)
elif args.action == 'collect':
result = collect(args.run, annotations=args.annotations)
if args.import_to: import_receipt(args.run / 'receipt.json', args.run, args.import_to)
else:
dependency = None
if args.dependency_run:
path = args.dependency_run / 'receipt.json'
receipt = read_receipt(path)
validate_receipt(receipt, path.parent)
pre = read_json(args.dependency_run / 'preflight.json')
if pre['ready'] or not pre['blockers'] or receipt['status'] != 'failed':
raise ValueError('Environment dependency requires an actual failed-preflight receipt')
dependency = {'receipt_id': receipt['receipt_id'], 'receipt_path': str(path.resolve()),
'receipt_sha256': identify_file(path)['sha256'], 'reasons': pre['blockers']}
result = matrix(read_json(PROJECT / 'docs/evidence/scenarios.json'),
[(read_receipt(p), p.parent) for p in args.receipt],
read_json(args.previous) if args.previous else None, dependency)
separated_roots(PROJECT.parent / 'Original', args.output)
if any(p.is_symlink() for p in (args.output.absolute(), *args.output.absolute().parents)):
raise ValueError('Matrix output cannot use symlink aliases')
args.output.parent.mkdir(parents=True, exist_ok=True)
_write_json(args.output, result)
print(canonical_bytes(result).decode(), end='')
return 0 if args.action == 'matrix' or result.get('ready', result.get('status') == 'captured') else 1
if __name__ == '__main__':
raise SystemExit(main())
+347
View File
@@ -0,0 +1,347 @@
#!/usr/bin/env python3
"""Prepare immutable, local-only fidelity checkpoints. READY is never acceptance.
The Windows collector needs no Python or SDK. This module assembles/transfers
identities and imports explicitly synthetic fixture results; it never executes
an original. Cooperative locks/incomplete siblings are retained after failure.
"""
import argparse
import hashlib
import os
from pathlib import Path
import shutil
import subprocess
import sys
import uuid
# A bundled CLI must not create bytecode inside the sealed checkpoint.
if __name__ == '__main__':
sys.dont_write_bytecode = True
from fidelity_receipts import (canonical_bytes, contained_path, identify_file,
identify_tree, read_json, relative_name, separated_roots, source_identity,
utc_now, validate_receipt, validate_scenario_contract, verify_inventory,
_id, _write_json)
from fidelity_review import export_review
from fidelity_ledger import export_ledger
PROJECT = Path(__file__).resolve().parents[2]
RIDS = ('linux-x64', 'win-x64')
FLAGS = ['--fidelity-output', '--fidelity-session', '--fidelity-case']
MAX_FILE_BYTES = 8 * 1024**3
MUTABLE = ('results', 'original-runs')
MATERIALS = ('scripts/collect-fidelity-linux.sh',
'scripts/collect-fidelity-windows.ps1',
'scripts/collect-fidelity-windows.cmd',
'tests/fidelity-windows.Tests.ps1', 'docs/evidence/windows-session.md',
'docs/evidence/linux-session.md', 'docs/evidence/checkpoint-session.md',
'docs/evidence/phase01-baseline.md', 'docs/evidence/scenarios.json',
'docs/evidence/capabilities.json', 'tests/test_fidelity_acceptance.py',
'tests/test_fidelity_scenarios.py',
'tools/recon/fidelity_acceptance.py', 'tools/recon/fidelity_checkpoint.py',
'tools/recon/fidelity_capture.py', 'tools/recon/fidelity_receipts.py',
'tools/recon/fidelity_review.py', 'tools/recon/fidelity_ledger.py',
'tools/recon/fidelity_viewer/index.html',
'tools/recon/fidelity_viewer/viewer.mjs',
'tools/recon/fidelity_viewer/style.css')
def _copy_file(source, target):
target.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(source, target)
if identify_file(source) != identify_file(target):
raise ValueError('Source changed during copy: ' + str(source))
# Byte-identical Unix apphosts still need their source execution permission.
# Do not propagate setuid/setgid/sticky bits into a generated checkpoint.
target.chmod(Path(source).stat().st_mode & 0o777)
def _copy_tree(source, target):
tree = identify_tree(source)
target.mkdir(parents=True)
for entry in tree['files']:
if entry['size'] > MAX_FILE_BYTES:
raise ValueError('File exceeds 8 GiB bound: ' + entry['path'])
_copy_file(contained_path(source, entry['path']), target / entry['path'])
if identify_tree(target)['files'] != tree['files']:
raise ValueError('Copied tree differs: ' + str(source))
def _package_files(package):
return [f for f in identify_tree(package)['files'] if f['path'] != 'fidelity-build.json']
def seal_package(package, rid, source, tooling=False, build_argv=None):
"""Called immediately after the local publish by our wrapper, never on old DLLs.
Build source is captured BEFORE publishing and checked again afterward. This
record binds those claims to bytes, without pretending the hash proves their
compiler provenance. A synthetic seal is permanently tooling-only.
"""
package = Path(package)
if rid not in RIDS:
raise ValueError('Unsupported package RID')
required = ['GamePort.dll', 'GamePort.runtimeconfig.json', 'GamePort.deps.json',
'BUILD-INFO.txt', 'GamePort.exe' if rid == 'win-x64' else 'GamePort',
'SDL3.dll' if rid == 'win-x64' else 'libSDL3.so.0',
'assets/NewGame.tsk', 'scenes/level1b/scene.json', 'scenes/VR04/scene.json',
'scenes/level1/scene.json', 'scenes/animations/jimstop/animation.json']
for name in required:
identify_file(contained_path(package, name))
for name in ('assets', 'scenes', 'audio', 'Shaders'):
identify_tree(package / name)
if not tooling:
dll = (package / 'GamePort.dll').read_bytes()
if not all(flag.encode('utf-16le') in dll for flag in FLAGS):
raise ValueError('Stale DLL: observer flags absent')
if not build_argv or not source.get('commit') or not source.get('diff_sha256'):
raise ValueError('Missing actual pre-publish source/command identity')
record = {'schema_version': 1, 'rid': rid, 'source': source,
'built_utc': utc_now(), 'tooling_only': tooling,
'build_argv': build_argv or ['synthetic fixture, no compiler'],
'observer_flags': FLAGS, 'files': _package_files(package)}
_write_json(package / 'fidelity-build.json', record)
return record
def _package(package, rid, tooling):
record = read_json(package / 'fidelity-build.json')
if (record.get('schema_version') != 1 or record.get('rid') != rid or
record.get('observer_flags') != FLAGS or
record.get('files') != _package_files(package)):
raise ValueError('Stale/missing package bytes or observer identity: ' + rid)
if record.get('tooling_only') and not tooling:
raise ValueError('Synthetic package cannot qualify as runtime materials')
return {'build_info': identify_file(package / 'BUILD-INFO.txt'),
'build': {k: v for k, v in record.items() if k != 'files'},
'package_tree_sha256': hashlib.sha256(canonical_bytes(record['files'])).hexdigest(),
'dll': identify_file(package / 'GamePort.dll'),
'executable': identify_file(package / ('GamePort.exe' if rid == 'win-x64' else 'GamePort')),
'resources': {k: {'tree_sha256': identify_tree(package / k)['tree_sha256']}
for k in ('assets', 'scenes', 'audio', 'Shaders')}}
def prepare_checkpoint(original, original_manifest, packages, output, tooling=False):
unresolved = Path(output).absolute()
if any(p.is_symlink() for p in (unresolved, *unresolved.parents)):
raise ValueError('Checkpoint output cannot use symlink aliases')
original, output = separated_roots(original, output)
# Resolve aliases before allocating; reject symlink ancestry even for missing leaves.
candidate = Path(output)
if any(p.is_symlink() for p in (candidate, *candidate.parents)) or candidate.exists():
raise ValueError('Checkpoint output must be a fresh non-symlink directory')
separated_roots(PROJECT.parent / 'Original', output)
if set(packages) != set(RIDS):
raise ValueError('Both identified offline packages are required')
before = verify_inventory(original, original_manifest)
protocol = read_json(PROJECT / 'docs/evidence/scenarios.json')
validate_scenario_contract(protocol)
identities = {}
for rid in RIDS:
package = Path(packages[rid]).resolve(strict=True)
separated_roots(package, output)
identities[rid] = _package(package, rid, tooling)
# Every raw asset shipped by the package must match the original baseline.
if not tooling:
baseline = {f['path'].casefold(): f for f in before['files']}
for f in identify_tree(package / 'assets')['files']:
expected = baseline.get(f['path'].casefold())
if not expected or any(f[k] != expected[k] for k in ('sha256', 'size', 'header')):
raise ValueError('Package raw resource differs from original: ' + f['path'])
output.parent.mkdir(parents=True, exist_ok=True)
lock = output.with_name('.' + output.name.casefold() + '.lock')
try:
lock.mkdir()
except FileExistsError as error:
raise ValueError('Checkpoint reserved; inspect incomplete assembly, never steal lock') from error
temporary = output.with_name('.' + output.name + '.incomplete-' + uuid.uuid4().hex)
temporary.mkdir()
_write_json(temporary / 'incomplete.json', {'status': 'incomplete', 'started_utc': utc_now()})
# On failure retain both the diagnostic sibling and reservation.
_copy_tree(original, temporary / 'original-pristine')
for rid in RIDS:
_copy_tree(packages[rid], temporary / 'port' / rid)
for name in MATERIALS:
if (PROJECT / name).is_file():
_copy_file(PROJECT / name, temporary / name)
else:
raise ValueError('Missing collector material: ' + name)
_copy_file(original_manifest, temporary / 'protocol/original-manifest.json')
for name in ('scenarios.json', 'capabilities.json'):
_copy_file(PROJECT / 'docs/evidence' / name, temporary / 'protocol' / name)
ledger = temporary / 'protocol/capability-ledger.json'
_write_json(ledger, export_ledger(read_json(PROJECT / 'docs/evidence/capabilities.json'), PROJECT))
export_review(None, None, temporary / 'review', ledger)
for name in MUTABLE:
(temporary / name).mkdir()
# All 80 Windows obligations are prepared; Linux's remaining40 use the same protocol.
agenda = [{'side': side, 'case_id': cell['id'], 'obligation_id': obligation,
'status': 'pending'} for side in ('original-windows-dxwnd', 'port-windows-native')
for cell in protocol['cells'] for obligation in cell['obligations']]
_write_json(temporary / 'protocol/agenda.json', {'schema_version': 1,
'runs': agenda, 'acceptance': {'state': 'open', 'required_all_platforms': 120}})
_write_json(temporary / 'protocol/settings-template.json', {
'schema_version': 1, 'diagnostic': True,
'tools': {k: {'source': '', 'version': '', 'settings': ''}
for k in ('dxwnd', 'recorder', 'browser', 'media_probe', 'derivation')},
'capture': {'source': '', 'monitor': '', 'crop': [], 'aspect': '',
'resolution': [], 'frame_rate': '', 'audio_devices': [],
'encoder': '', 'container': 'MKV', 'timing_limitations': ''},
'preflight': {'original': {'visible_moving_game': False, 'intelligible_game_audio': False,
'correct_crop_aspect': False},
'port': {'visible_moving_game': False, 'intelligible_game_audio': False,
'correct_crop_aspect': False},
'browser': {'actual_playback': False, 'seeking': False,
'exclusive_audio': False}},
'notes': 'Fill actual observed values; false/empty fields remain pending, never acceptance.'})
_write_json(temporary / 'protocol/annotation-template.json', {
'schema_version': 1, 'status': 'incomplete', 'diagnostic': True,
'artifacts': [], 'events': [], 'derivatives': [], 'continuity': {},
'limitations': ['Actual media clocks, uncertainty and human review still required'],
'notes': 'Use windows-session.md field contract; empty template cannot finalize capture.'})
verify_inventory(original, original_manifest)
(temporary / 'incomplete.json').unlink()
files = identify_tree(temporary)['files']
manifest = {'schema_version': 1, 'checkpoint_id': output.name,
'tool_source': source_identity(PROJECT),
'created_utc': utc_now(), 'tooling_only': tooling, 'packages': identities,
'original_manifest': identify_file(original_manifest),
'original_pre': {'tree_sha256': before['tree_sha256'], 'count': len(before['files'])},
'files': files, 'mutable_roots': list(MUTABLE),
'acceptance': {'state': 'open', 'remaining': ['Actual original/native captures and human review']}}
_write_json(temporary / 'manifest.json', manifest)
_write_json(temporary / 'READY.json', {'schema_version': 1, 'status': 'prepared',
'manifest': dict(path='manifest.json', **identify_file(temporary / 'manifest.json')),
'acceptance': {'state': 'open'}, 'meaning': 'Materials prepared only; no runtime acceptance'})
preflight(temporary)
if output.exists():
raise ValueError('Output allocated concurrently')
os.rename(temporary, output)
lock.rmdir()
return manifest
def preflight(root, dependencies=None):
root = Path(root)
if root.is_symlink():
raise ValueError('Checkpoint root cannot be a symlink')
ready = read_json(root / 'READY.json')
if ready.get('schema_version') != 1 or ready.get('status') != 'prepared':
raise ValueError('Checkpoint is incomplete, not READY')
actual = identify_file(root / 'manifest.json')
if any(ready['manifest'].get(k) != actual[k] for k in ('sha256', 'size')):
raise ValueError('Manifest identity differs from READY')
manifest = read_json(root / 'manifest.json')
expected = {item['path']: item for item in manifest['files']}
for name, item in expected.items():
actual = identify_file(contained_path(root, name))
if any(item[k] != actual[k] for k in ('sha256', 'size', 'header')):
raise ValueError('Tampered checkpoint material: ' + name)
# Permit only owned result/copy directories to grow after publication.
for directory, dirs, names in os.walk(root, followlinks=False):
for name in dirs + names:
path = Path(directory) / name
relative = path.relative_to(root).as_posix()
if path.is_symlink():
raise ValueError('Symlink in checkpoint: ' + relative)
if path.is_file() and relative.split('/')[0] not in MUTABLE:
if relative not in expected and relative not in ('READY.json', 'manifest.json'):
raise ValueError('Unexpected immutable material: ' + relative)
failures = []
tools = {}
for label, path in (dependencies or {}).items():
try:
tools[label] = dict(path=str(Path(path).resolve()), **identify_file(path))
except (ValueError, OSError):
failures.append('Missing local dependency ' + label + ': select an existing local file (' + str(path) + ')')
return {'schema_version': 1, 'status': 'blocked' if failures else 'ready',
'checked_files': len(expected), 'tooling_only': manifest['tooling_only'],
'tools': tools, 'failures': failures, 'acceptance': {'state': 'open'}}
def fixture_result(bundle, run, session_id, case_id, scope, artifacts, status='captured'):
"""Tooling-only end-to-end importer fixture; cannot mint native evidence."""
preflight(bundle)
if status not in ('captured', 'failed', 'skipped', 'aborted'):
raise ValueError('Unknown fixture result status')
_id(session_id)
protocol = read_json(Path(bundle) / 'protocol/scenarios.json')
if case_id not in {c['id'] for c in protocol['cells']} or scope not in protocol['obligations']:
raise ValueError('Unknown case/scope')
run = Path(run)
items = [dict(path=str(relative_name(p)), role='diagnostic', synthetic=True,
**identify_file(contained_path(run, p))) for p in artifacts]
receipt = {'schema_version': 1, 'receipt_id': session_id, 'session_id': session_id,
'case_id': case_id, 'obligation_id': scope, 'scope': scope,
'evidence_kind': 'synthetic', 'status': status, 'historical': False,
'platform': {'os': 'test', 'execution': 'synthetic'}, 'identity': {},
'invocation': {'argv': ['fixture result; no executable launched'], 'cwd': str(run)},
'clocks': {'wall_start': utc_now(), 'wall_end': utc_now(),
'monotonic_start': 0, 'monotonic_end': 0},
'artifacts': items, 'derivatives': [], 'events': [],
'limitations': ['Synthetic tooling only'], 'missing_evidence': ['No native/reference execution'],
'acceptance': {'state': 'open', 'remaining': ['Actual identified captures and human review']}}
validate_receipt(receipt, run)
_write_json(run / 'receipt.json', receipt)
return receipt
def publish_packages(output, base):
"""Isolated equivalent of existing builds, preserving historical dist packages."""
output, base = Path(output).resolve(), Path(base).resolve()
if output.exists():
raise ValueError('Publish root must be fresh')
separated_roots(base, output)
source = source_identity(PROJECT)
output.mkdir(parents=True)
for rid in RIDS:
target = output / rid
_copy_tree(base / rid, target)
# The old note identifies historical resource packaging, not this compilation.
(target / 'BUILD-INFO.txt').rename(target / 'RESOURCE-BASE-BUILD-INFO.txt')
old_seal = target / 'fidelity-build.json'
if old_seal.exists():
old_seal.unlink()
argv = ['dotnet', 'publish', 'GamePort.csproj', '-c', 'Release', '-r', rid,
'--self-contained', 'true', '--no-restore', '-o', str(target)]
subprocess.run(argv, cwd=PROJECT, check=True, timeout=600)
if source_identity(PROJECT) != source:
raise ValueError('Source changed during publish; preserve diagnostics and republish')
(target / 'BUILD-INFO.txt').write_text('source_commit=' + source['commit'] +
'\nsource_dirty=' + ('yes' if source['dirty'] else 'no') +
'\nsource_diff_sha256=' + source['diff_sha256'] + '\npublished_utc=' + utc_now() + '\n')
seal_package(target, rid, source, build_argv=argv)
return {'status': 'published', 'output': str(output), 'source': source}
def main():
parser = argparse.ArgumentParser(description=__doc__)
sub = parser.add_subparsers(dest='command', required=True)
prepare = sub.add_parser('prepare')
prepare.add_argument('--original', type=Path, default=PROJECT.parent / 'Original')
prepare.add_argument('--original-manifest', type=Path, default=PROJECT / 'docs/original-manifest.json')
prepare.add_argument('--packages', type=Path, required=True)
prepare.add_argument('--output', type=Path, required=True)
check = sub.add_parser('preflight')
check.add_argument('--checkpoint', type=Path, required=True)
publish = sub.add_parser('publish')
publish.add_argument('--output', type=Path, required=True)
publish.add_argument('--base', type=Path, default=PROJECT / 'dist')
args = parser.parse_args()
try:
if args.command == 'prepare':
result = prepare_checkpoint(args.original, args.original_manifest,
{rid: args.packages / rid for rid in RIDS}, args.output)
print('Prepared checkpoint; acceptance OPEN; files:', len(result['files']))
elif args.command == 'publish':
print(canonical_bytes(publish_packages(args.output, args.base)).decode())
else:
print(canonical_bytes(preflight(args.checkpoint)).decode())
return 0
except (ValueError, OSError, subprocess.SubprocessError) as error:
print('Checkpoint failed (acceptance OPEN): ' + str(error), file=sys.stderr)
return 2
if __name__ == '__main__':
sys.exit(main())
+434
View File
@@ -0,0 +1,434 @@
"""Version 1 capability ledger: source reports are evidence, never new executions.
The authoritative JSON retains all records. Current means applicable to an explicit
content/platform/scope target, including named historical targets; it never means
the newest date or current Git HEAD. A report's identity is not a runtime identity.
Real receipt references are revalidated through fidelity_receipts. Missing captures
remain open. Render/export are generated views, not independent status sources.
Only cooperative local filesystem use is supported; revalidate after changes.
No commands from imported data are executed. No network or package dependencies.
"""
import argparse
import copy
import hashlib
import html
import json
from pathlib import Path
import re
import subprocess
import sys
from urllib.parse import quote
# A bundled CLI must not create bytecode inside the sealed checkpoint.
if __name__ == '__main__':
sys.dont_write_bytecode = True
from fidelity_receipts import (KINDS, MAX_JSON_BYTES, canonical_bytes, contained_path,
identify_file, read_json, validate_receipt)
PROJECT = Path(__file__).resolve().parents[2]
GROUPS = ('movement', 'contacts', 'gadgets', 'progression', 'visuals', 'audio')
IMPACTS = {'blocking': 0, 'disruptive': 1, 'subtle': 2, 'missing_verification': 3}
EXCLUDED = {'original', 'artifacts', 'dist', '.git', '.tools', '.nuget', '.aws', '.codex', '.agents'}
ID = re.compile(r'^[A-Za-z0-9][A-Za-z0-9._:-]{0,159}$')
HASH = re.compile(r'^[a-f0-9]{64}$')
def _text(value, name):
if not isinstance(value, str) or not value.strip() or len(value) > 16384 or '\0' in value:
raise ValueError('Missing or unbounded text: ' + name)
return value
def _id(value):
if not isinstance(value, str) or not ID.fullmatch(value):
raise ValueError('Invalid stable ID')
return value
def _list(value, name, nonempty=False):
if not isinstance(value, list) or len(value) > 4096 or (nonempty and not value):
raise ValueError('Missing or unbounded array: ' + name)
return value
def _bounded(value, depth=0):
if depth > 24:
raise ValueError('Ledger nesting exceeds bound')
if isinstance(value, dict):
if len(value) > 128: raise ValueError('Object exceeds field bound')
for key, item in value.items():
_text(key, 'field name')
_bounded(item, depth + 1)
elif isinstance(value, list):
_list(value, 'array')
for item in value: _bounded(item, depth + 1)
elif isinstance(value, str):
if len(value) > 16384 or '\0' in value: raise ValueError('Text exceeds bound')
elif value is not None and not isinstance(value, (int, float, bool)):
raise ValueError('Non-JSON value')
def _deduplicate(rows, key):
found = {}
for row in rows:
if not isinstance(row, dict): raise ValueError('Expected record object')
identity = _id(row.get(key))
if identity in found and canonical_bytes(found[identity]) != canonical_bytes(row):
raise ValueError('Conflicting duplicate ' + key + ': ' + identity)
found[identity] = row
return [found[key] for key in sorted(found)]
def _identity(record):
content = record.get('content')
if not isinstance(content, dict) or not content:
raise ValueError('Explicit content identity required')
for key, value in content.items():
if not key.endswith('_sha256') or not isinstance(value, str) or not HASH.fullmatch(value):
raise ValueError('Content identities must be actual SHA-256 declarations')
platform = record.get('platform')
if not isinstance(platform, dict): raise ValueError('Platform object required')
_text(platform.get('os'), 'platform.os')
_text(platform.get('execution'), 'platform.execution')
scope = _list(record.get('scope'), 'scope', True)
for item in scope: _text(item, 'scope item')
if len(scope) != len(set(scope)): raise ValueError('Duplicate scope')
return canonical_bytes([content, platform, sorted(scope)])
def select_current_evidence(records, target):
"""Select exact content/platform/scope matches, ignoring docs/source timestamps.
A changed runtime, resource or package digest, missing identity field or
different platform/scope cannot inherit proof. Caller validates the graph.
"""
identity = _identity(target)
records = _deduplicate(records, 'id')
superseded = {old for record in records for old in record.get('supersedes', [])}
return [record for record in records if record.get('status') == 'current'
and record['id'] not in superseded and _identity(record) == identity]
def _tracked(project):
result = subprocess.run(['git', '-C', str(project), 'ls-files', '-z'],
capture_output=True, check=True, timeout=20)
if len(result.stdout) > MAX_JSON_BYTES: raise ValueError('Source inventory exceeds bound')
return set(result.stdout.decode('utf8').split('\0'))
def _source(project, link, tracked):
if not isinstance(link, dict): raise ValueError('Source link must be an object')
_text(link.get('label'), 'source label')
path = contained_path(project, link.get('path'))
name = path.relative_to(project).as_posix()
if name.split('/')[0].lower() in EXCLUDED:
raise ValueError('Original/generated/private source link forbidden')
if name not in tracked or not path.is_file(): raise ValueError('Dead tracked source link: ' + name)
if path.stat().st_size > 1024 * 1024: raise ValueError('Source text exceeds 1 MiB')
raw = path.read_bytes()
raw.decode('utf8')
if b'\0' in raw: raise ValueError('Source link must be UTF-8 text')
digest = hashlib.sha256(raw).hexdigest()
if 'sha256' in link and digest != link['sha256']: raise ValueError('Source hash mismatch: ' + name)
return name
def checkpoint_rows(path):
"""Identity every system/ownership table row and numbered assumption.
Exact line/paragraph bytes are hashed so reconciliation must be reviewed
when its source changes. Top-level narrative remains in the linked report.
"""
text = Path(path).read_text()
result, section = {}, None
for line in text.splitlines():
if line.startswith('| ID / system |'): section = 'system'
elif line.startswith('| State / owner |'): section = 'ownership'
elif line.startswith('#'): section = None
elif section and line.startswith('|') and not line.startswith('|---'):
key = section + ':' + line.split('|')[1].strip()
if key in result: raise ValueError('Ambiguous checkpoint row: ' + key)
result[key] = hashlib.sha256(line.encode()).hexdigest()
marker = '## Assumptions and symptom-level adapters to replace'
if marker not in text: raise ValueError('Missing checkpoint assumptions section')
assumptions = text.split(marker, 1)[1].split('\n## ', 1)[0]
for match in re.finditer(r'^([1-9][0-9]*)\. (.*(?:\n(?!\n|[1-9][0-9]*\. ).*)*)', assumptions, re.M):
result['assumption:' + match[1]] = hashlib.sha256(match[0].encode()).hexdigest()
return result
def _records(row, project, tracked):
records = _deduplicate(_list(row.get('evidence'), 'evidence'), 'id')
_deduplicate(records, 'receipt_id')
by_id = {record['id']: record for record in records}
superseded = set()
claims = {}
for record in records:
identity = _identity(record)
kind = record.get('evidence_kind')
if kind not in KINDS: raise ValueError('Invalid receipt classification')
platform = record['platform']
execution = platform['execution']
if kind == 'native_port' and (execution != 'native' or platform['os'] not in {'linux', 'windows'}):
raise ValueError('Native/fixture classification cannot use Wine or source proof')
if kind == 'port_fixture' and (execution not in {'native', 'port_fixture'} or platform['os'] not in {'linux', 'windows'}):
raise ValueError('Fixture classification requires its declared port host')
if kind in {'component', 'managed', 'synthetic'} and execution != kind:
raise ValueError('Component/managed/synthetic evidence must retain its execution category')
if kind == 'inferred' and execution not in {'static', 'inferred'}:
raise ValueError('Inference cannot become runtime proof')
if kind == 'original_dxwnd' and (platform['os'] != 'windows' or execution != 'dxwnd'):
raise ValueError('Original DxWnd requires Windows/DxWnd')
if kind == 'wine' and execution != 'wine': raise ValueError('Wine must stay Wine')
if kind == 'cross_publish' and execution != 'cross_publish': raise ValueError('Cross-publish is not execution')
if kind == 'static' and execution != 'static': raise ValueError('Static evidence must stay static')
if record.get('status') not in {'current', 'historical', 'superseded'}:
raise ValueError('Invalid applicability status')
if not isinstance(record.get('historical'), bool): raise ValueError('Historical flag required')
_text(record.get('revision'), 'evidence revision')
_text(record.get('method'), 'observation method')
_source(project, {'label': 'Evidence report', 'path': record.get('report_path')}, tracked)
if 'report_sha256' in record['content']:
report = contained_path(project, record['report_path'])
if identify_file(report)['sha256'] != record['content']['report_sha256']:
raise ValueError('Report content identity mismatch')
claim = record.get('claim')
if not isinstance(claim, dict): raise ValueError('Evidence claim required')
_text(claim.get('key'), 'claim key')
_text(claim.get('result'), 'claim result')
parents = _list(record.get('supersedes'), 'supersedes')
if parents: _text(record.get('reason'), 'supersession reason')
for old in parents:
if old not in by_id: raise ValueError('Unknown supersedes ID: ' + str(old))
if by_id[old]['status'] != 'superseded': raise ValueError('Superseded record must retain explicit label')
superseded.add(old)
if record['status'] == 'current':
key = (identity, claim['key'])
if key in claims and claims[key] != claim['result']:
raise ValueError('Contradictory current claim: ' + claim['key'])
claims[key] = claim['result']
for gap in _list(record.get('missing_evidence'), 'missing evidence'):
_text(gap, 'missing evidence')
for artifact in _list(record.get('artifacts'), 'artifacts'):
path = contained_path(project, artifact.get('path'))
if path.relative_to(project).parts[0] != 'artifacts':
raise ValueError('Local evidence artifacts must stay under artifacts/')
if not path.is_file():
_text(artifact.get('missing_reason'), 'missing artifact reason')
else:
actual = identify_file(path)
if actual['sha256'] != artifact.get('sha256') or actual['size'] != artifact.get('size'):
raise ValueError('Artifact identity mismatch: ' + artifact['path'])
if 'receipt_path' in record:
receipt_path = contained_path(project, record['receipt_path'])
receipt = read_json(receipt_path)
validate_receipt(receipt, receipt_path.parent)
if receipt['receipt_id'] != record['receipt_id'] or receipt['evidence_kind'] != kind:
raise ValueError('Receipt reference identity/classification mismatch')
receipt_scope = receipt['scope'] if isinstance(receipt['scope'], list) else [receipt['scope']]
if (receipt['platform'] != record['platform'] or sorted(receipt_scope) != sorted(record['scope'])
or receipt['historical'] != record['historical']):
raise ValueError('Receipt reference platform/scope/history mismatch')
if record['content'].get('receipt_sha256') != identify_file(receipt_path)['sha256']:
raise ValueError('Receipt reference requires its exact content digest')
visiting, visited = set(), set()
def visit(identifier):
if identifier in visiting: raise ValueError('Supersession cycle')
if identifier in visited: return
visiting.add(identifier)
for parent in by_id[identifier]['supersedes']: visit(parent)
visiting.remove(identifier)
visited.add(identifier)
for identifier in by_id: visit(identifier)
for record in records:
if record['status'] == 'superseded' and record['id'] not in superseded:
raise ValueError('Superseded history requires explicit successor/reason')
return records
def validate_ledger(data, project=PROJECT, requirements=None):
"""Return counted structural coverage; no runtime acceptance is inferred."""
project = Path(project).resolve(strict=True)
_bounded(data)
if len(canonical_bytes(data)) > MAX_JSON_BYTES: raise ValueError('Ledger exceeds 4 MiB')
if data.get('schema_version') != 1: raise ValueError('Unsupported ledger version')
rows = _deduplicate(_list(data.get('capabilities'), 'capabilities', True), 'id')
tracked = _tracked(project)
scenarios = read_json(project / 'docs/evidence/scenarios.json')
scenario_ids = {cell['id'] for cell in scenarios['cells']}
mapped, groups, all_records = set(), set(), []
for row in rows:
if row.get('group') not in GROUPS: raise ValueError('Unknown capability group')
groups.add(row['group'])
for key in ('summary', 'verified_scope'): _text(row.get(key), key)
for key in ('differences',):
for item in _list(row.get(key), key, True): _text(item, key)
for req in _list(row.get('requirement_ids'), 'requirements', True):
if not isinstance(req, str) or not re.fullmatch(r'[A-Z]+-[0-9]{2}', req): raise ValueError('Invalid requirement ID')
mapped.add(req)
acceptance = row.get('acceptance')
if not isinstance(acceptance, dict) or acceptance.get('status') != 'open':
raise ValueError('Full-game acceptance remains open until the separate identified audit')
for item in _list(acceptance.get('remaining'), 'remaining acceptance', True): _text(item, 'remaining acceptance')
for link in _list(row.get('source_links'), 'source links', True): _source(project, link, tracked)
for scenario in _list(row.get('scenario_ids'), 'scenario IDs'):
if scenario not in scenario_ids: raise ValueError('Unknown scenario ID')
implementation = row.get('implementation')
if not isinstance(implementation, dict): raise ValueError('Implementation metadata required')
_text(implementation.get('revision'), 'implementation revision')
if implementation.get('status') not in {'bounded', 'unimplemented', 'tooling'}:
raise ValueError('Implementation must distinguish bounded/unimplemented/tooling')
for path in _list(implementation.get('paths'), 'implementation paths'):
_source(project, {'label': 'Implementation', 'path': path}, tracked)
records = _records(row, project, tracked)
all_records.extend(records)
targets = _deduplicate(_list(row.get('targets'), 'applicability targets'), 'id')
for target in targets: _identity(target)
for record in records:
if record['status'] == 'current' and not any(record in select_current_evidence(records, target) for target in targets):
raise ValueError('Current record has no matching explicit applicability target')
discrepancies = _deduplicate(_list(row.get('discrepancies'), 'discrepancies'), 'id')
for gap in discrepancies:
if gap.get('impact') not in IMPACTS: raise ValueError('Invalid discrepancy impact')
_text(gap.get('summary'), 'discrepancy summary')
_deduplicate(all_records, 'id')
_deduplicate(all_records, 'receipt_id')
expected = set()
if requirements is not None:
expected = set(re.findall(r'^- \[[ x]\] \*\*([A-Z]+-[0-9]{2})\*\*:', Path(requirements).read_text(), re.M))
if not expected or expected != mapped: raise ValueError('Unmapped or unknown requirements: ' + str(sorted(expected ^ mapped)))
if groups != set(GROUPS): raise ValueError('All six capability groups are required')
if requirements is not None or 'reconciliation' in data:
expected_rows = checkpoint_rows(project / 'docs/checkpoint/coverage.md')
reconciliation = _list(data.get('reconciliation'), 'checkpoint reconciliation', True)
actual_rows = {}
for record in reconciliation:
source_row = _text(record.get('source_row'), 'source row')
if source_row in actual_rows: raise ValueError('Duplicate source reconciliation row')
actual_rows[source_row] = record.get('source_sha256')
if record.get('source_path') != 'docs/checkpoint/coverage.md': raise ValueError('Wrong checkpoint source')
_source(project, {'label': 'Checkpoint', 'path': record['source_path']}, tracked)
for identifier in _list(record.get('capability_ids'), 'reconciled capability IDs', True):
if identifier not in {row['id'] for row in rows}: raise ValueError('Unknown reconciled capability')
capability = next(row for row in rows if row['id'] == identifier)
if not any(link['path'] == record['source_path'] for link in capability['source_links']):
raise ValueError('Reconciled capability must link the retained checkpoint source')
if actual_rows != expected_rows: raise ValueError('Missing, stale or extra checkpoint source-row reconciliation')
return {'capabilities': len(rows), 'requirements': len(expected or mapped),
'unmapped': len(expected - mapped), 'groups': len(groups),
'reconciled_rows': len(data.get('reconciliation', [])), 'acceptance': 'OPEN'}
def export_ledger(data, project=PROJECT, requirements=None):
counts = validate_ledger(data, project, requirements)
result = copy.deepcopy(data)
rows = _deduplicate(result['capabilities'], 'id')
for row in rows:
row['evidence'] = _deduplicate(row['evidence'], 'id')
selected = {record['id'] for target in row['targets']
for record in select_current_evidence(row['evidence'], target)}
row['current'] = [r for r in row['evidence'] if r['id'] in selected]
row['history'] = [r for r in row['evidence'] if r['id'] not in selected]
row['discrepancies'] = sorted(row['discrepancies'], key=lambda r: (IMPACTS[r['impact']], r['id']))
def order(row):
priority = min((IMPACTS[r['impact']] for r in row['discrepancies']), default=4)
return (GROUPS.index(row['group']), priority, row['id'])
result['capabilities'] = sorted(rows, key=order)
result['counts'] = counts
return result
def _escape(value):
return html.escape(str(value), quote=True).replace('|', '&#124;').replace('`', '&#96;')
def render_markdown(data, project=PROJECT, requirements=None):
model = export_ledger(data, project, requirements)
counts = model['counts']
lines = ['# Capability evidence ledger', '',
'Generated by tools/recon/fidelity_ledger.py from [capabilities.json](capabilities.json).', '',
f"Capabilities: {counts['capabilities']}; requirements: {counts['requirements']}; unmapped: {counts['unmapped']}. Acceptance: **OPEN**.", '',
'Current means exact named content/platform/scope applicability, including explicitly historical bytes. '
'A report link is not a new execution; date or docs HEAD never promotes proof. '
'Original-DxWnd/native matrix acceptance remains **0/120** until identified captures and review.', '',
'Regenerate and validate locally:', '', '```sh',
'python3 tools/recon/fidelity_ledger.py validate --ledger docs/evidence/capabilities.json --requirements .planning/REQUIREMENTS.md',
'python3 tools/recon/fidelity_ledger.py render --ledger docs/evidence/capabilities.json --output docs/evidence/README.md',
'python3 tools/recon/fidelity_ledger.py export --ledger docs/evidence/capabilities.json --output artifacts/fidelity/review/ledger.json',
'python3 tools/recon/fidelity_review.py export --ledger artifacts/fidelity/review/ledger.json --output artifacts/fidelity/review/new-review',
'```', '',
'Omitting recordings creates an explicitly missing-media review. Add --original and --port imported receipt.json paths when available. '
'Scenario IDs link to the [eight-cell protocol](scenarios.json). Ledger evidence summaries are typed report records; '
'only receipt_path entries reference imported version 1 receipts. Missing local artifacts retain their reasons. '
'Source/implementation links are tracked bounded UTF-8 text; viewer export copies them into its contained sources/ tree.', '']
for group in GROUPS:
rows = [row for row in model['capabilities'] if row['group'] == group]
if not rows: continue
lines.extend(['## ' + group.title(), ''])
for row in rows:
lines.extend(['### ' + _escape(row['id']), '', '**Working behavior:** ' + _escape(row['summary']), '',
'**Verified scope/platform:** ' + _escape(row['verified_scope']), '',
'**Known differences:** ' + '; '.join(map(_escape, row['differences'])), '',
'**Remaining acceptance — OPEN:** ' + '; '.join(map(_escape, row['acceptance']['remaining'])), '',
'**Requirements:** ' + ', '.join(row['requirement_ids']) + ' · **Implementation:** ' + _escape(row['implementation']), '',
'**Sources:** ' + ', '.join('[' + _escape(link['label']) + '](../../' + quote(link['path'], safe='/') + ')' for link in row['source_links']), '',
'**Scenarios:** ' + ', '.join('[' + _escape(scenario) + '](scenarios.json)' for scenario in row['scenario_ids']), '',
'**Current applicable evidence (only the targets below):**', ''])
lines.extend(['- ' + _escape(json.dumps(record, sort_keys=True)) for record in row['current']] or ['- No matching identified evidence; acceptance remains open.'])
lines.extend(['', '**Explicit applicability targets:** ' + _escape(row['targets']), '',
'<details><summary>History — exact revisions and supersession retained</summary>', ''])
lines.extend(['- ' + _escape(json.dumps(record, sort_keys=True)) for record in row['history']] or ['- No superseded evidence recorded.'])
lines.extend(['', '</details>', '', '**Player-impact discrepancies:**', ''])
lines.extend('- **' + gap['impact'] + '** · ' + _escape(gap['id']) + ': ' + _escape(gap['summary']) for gap in row['discrepancies'])
lines.append('')
if model.get('reconciliation'):
lines.extend(['## Source-row reconciliation', '', 'Every checkpoint row remains explicitly linked; continuation reports refine its claims.', ''])
for record in model['reconciliation']:
lines.append('- ' + _escape(record['source_row']) + ' → ' + ', '.join(map(_escape, record['capability_ids'])) + ' · [retained source](../../' + quote(record['source_path'], safe='/') + ')')
return '\n'.join(lines) + '\n'
def _write(path, raw):
path = Path(path)
resolved = path.resolve()
if not (resolved.is_relative_to(PROJECT) or resolved.is_relative_to(Path('/tmp'))):
raise ValueError('Generated output must remain in project or local /tmp')
if any(part.lower() in {'original', '.git'} for part in path.parts):
raise ValueError('Cannot write originals or Git metadata')
cursor = path.absolute()
for part in [cursor, *cursor.parents]:
if part.is_symlink(): raise ValueError('Output cannot traverse symlinks')
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(raw)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('command', choices=['validate', 'render', 'export'])
parser.add_argument('--ledger', type=Path, required=True)
parser.add_argument('--requirements', type=Path)
parser.add_argument('--output', type=Path)
args = parser.parse_args()
try:
data = read_json(args.ledger)
requirements = args.requirements
if requirements is None and 'reconciliation' in data:
requirements = PROJECT / '.planning/REQUIREMENTS.md'
counts = validate_ledger(data, PROJECT, requirements)
if args.command != 'validate':
if args.output is None: raise ValueError('--output required')
if args.output.resolve() == args.ledger.resolve(): raise ValueError('Cannot overwrite authoritative ledger')
raw = (render_markdown(data, PROJECT, requirements).encode() if args.command == 'render'
else canonical_bytes(export_ledger(data, PROJECT, requirements)))
_write(args.output, raw)
print(' '.join(f'{key}={value}' for key, value in counts.items()))
return 0
except (ValueError, OSError, UnicodeError, subprocess.SubprocessError, TypeError, KeyError, RecursionError) as error:
print('Ledger invalid: ' + str(error), file=sys.stderr)
return 2
if __name__ == '__main__':
raise SystemExit(main())
+18 -9
View File
@@ -331,9 +331,15 @@ def validate_receipt(receipt, root):
if not isinstance(clocks, dict):
raise ValueError('Clocks must be an object')
start, end = clocks.get('monotonic_start'), clocks.get('monotonic_end')
if not _finite(start) or not _finite(end) or start < 0 or end < start:
missing_end = (status == 'aborted' and receipt.get('acceptance', {}).get('state') == 'open'
and end is None and clocks.get('wall_end') is None)
if not _finite(start) or start < 0 or (not missing_end and (not _finite(end) or end < start)):
raise ValueError('Invalid/reset monotonic clocks')
if missing_end and receipt['events']:
raise ValueError('Missing end clocks cannot bound launch-aligned event observations')
for key in ('wall_start', 'wall_end'):
if key == 'wall_end' and missing_end:
continue
try:
dt = datetime.fromisoformat(clocks[key].replace('Z', '+00:00'))
if dt.tzinfo is None:
@@ -395,6 +401,8 @@ def validate_receipt(receipt, root):
if synthetic and kind != 'synthetic':
raise ValueError('Synthetic artifacts cannot be relabeled as runtime evidence')
missing = list(receipt['missing_evidence']) + list(acceptance['remaining'])
if missing_end:
missing.append('Interrupted collector end clocks unavailable')
if kind not in ('native_port', 'original_dxwnd'):
missing.append(kind + ' is not original/native gameplay acceptance')
if receipt['historical']:
@@ -618,7 +626,7 @@ def required_events(protocol, cell, obligation_id):
return events
def _scenario_observation(protocol, cell, receipt):
def _scenario_observation(protocol, cell, receipt, root):
obligation = receipt['obligation_id']
if receipt.get('scope') != obligation:
raise ValueError('Receipt scope must match its explicit obligation')
@@ -656,17 +664,18 @@ def _scenario_observation(protocol, cell, receipt):
if continuity.get('prerequisite_artifact') not in {
a['path'] for a in receipt['artifacts'] if a.get('role') == 'prerequisite'}:
raise ValueError('Visible identified prerequisite setup required')
if not re.fullmatch('[0-9a-f]{64}', continuity.get('copy_pre_sha256', '')):
raise ValueError('Missing pristine copy/package session identity')
_checked_artifact(receipt['identity'].get('copy_pre'), root)
if (not re.fullmatch('[0-9a-f]{64}', continuity.get('copy_pre_sha256', '')) or
continuity['copy_pre_sha256'] != receipt['identity'].get('copy_pre', {}).get('sha256')):
raise ValueError('Copy pre state must bind the actual named copy_pre identity record')
if cell['lifetime'] == 'retained':
_checked_artifact(receipt['identity'].get('retained_copy'), root)
if (continuity.get('departure_session_id') != receipt['session_id'] or
continuity.get('return_session_id') != receipt['session_id'] or
not re.fullmatch('[0-9a-f]{64}', continuity.get('retained_copy_sha256', ''))):
raise ValueError('Retained departure/return/copy must preserve the same session')
identified = {item.get('sha256') for item in receipt['identity'].values() if isinstance(item, dict)}
if (continuity['copy_pre_sha256'] not in identified or
continuity['retained_copy_sha256'] not in identified):
raise ValueError('Retained copy state must bind actual hashed identity records')
if continuity['retained_copy_sha256'] != receipt['identity'].get('retained_copy', {}).get('sha256'):
raise ValueError('Retained copy state must bind the actual named retained_copy identity record')
prerequisite = [e for e in events if e['artifact'] == continuity['prerequisite_artifact']]
names = [e['name'] for e in prerequisite]
if ('prerequisite_departure' not in names or 'prerequisite_return' not in names or
@@ -702,7 +711,7 @@ def audit_scenarios(protocol, records):
if not result['accepted']:
open_receipts.append(label + ': ' + '; '.join(result['missing_evidence']))
continue
_scenario_observation(protocol, cells[case], receipt)
_scenario_observation(protocol, cells[case], receipt, root)
if cells[case]['lifetime'] == 'fresh':
session_key = (receipt['evidence_kind'], receipt['platform']['os'], receipt['session_id'])
if session_key in fresh_sessions:
+333
View File
@@ -0,0 +1,333 @@
"""Export validated local receipts; serve only the generated, read-only tree.
CLI: export --original IMPORT/receipt.json --port IMPORT/receipt.json --output NEW
serve --root NEW [--port 8765]
Either side may be omitted. Exports are review aids, never acceptance receipts.
The cooperative offline filesystem boundary matches fidelity_receipts: revalidate
before review; hostile concurrent filesystem replacement is outside this model.
"""
import argparse
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import json
import mimetypes
import os
from pathlib import Path
import re
import shutil
import subprocess
import sys
import tempfile
from urllib.parse import quote, unquote, urlsplit
# A bundled CLI must not create bytecode inside the sealed checkpoint.
if __name__ == '__main__':
sys.dont_write_bytecode = True
from fidelity_receipts import (MAX_JSON_BYTES, canonical_bytes, contained_path,
identify_file, read_json, read_receipt, separated_roots,
validate_receipt)
VIEWER = Path(__file__).with_name('fidelity_viewer')
PROJECT = Path(__file__).resolve().parents[2]
STATIC = ('index.html', 'viewer.mjs', 'style.css')
MAX_RANGE = 16 * 1024 * 1024
def _side(path, side):
if path is None:
return {'missing': 'Missing ' + side + ' reference recording', 'media': None,
'artifacts': [], 'events': [], 'derivatives': []}, []
path = Path(path)
if path.is_symlink():
raise ValueError('Receipt must not be a symlink')
path = path.resolve(strict=True)
value = read_receipt(path)
validation = validate_receipt(value, path.parent)
prefix = 'sides/' + side + '/'
paths = {a['path'] for a in value['artifacts']}
paths.update(a['path'] for a in value['identity'].values() if isinstance(a, dict) and 'path' in a)
if any(name.casefold() in ('receipt.json', 'receipt.sha256') for name in paths):
raise ValueError('Artifact collides with exported receipt')
artifacts = [dict(a, url=quote(prefix + a['path'], safe='/')) for a in value['artifacts']]
videos = [a for a in artifacts if a['role'] in ('video', 'preview')]
# A preview is explicit derivative provenance; a raw recording remains linked.
media = next((a for a in videos if a['role'] == 'preview'), next(iter(videos), None))
events = [e for e in value['events'] if media and e['artifact'] == media['path']]
result = {key: value.get(key) for key in ('receipt_id', 'session_id', 'case_id', 'scope',
'evidence_kind', 'status', 'platform', 'historical', 'limitations', 'identity', 'clocks')}
result.update(artifacts=artifacts, media=media, events=events,
derivatives=value['derivatives'], receipt_url=prefix + 'receipt.json',
missing_evidence=validation['missing_evidence'],
missing='' if media else 'Missing ' + side + ' playable video/preview',
reference_warning=('No genuine original reference: this is ' + value['evidence_kind'] + ' evidence')
if side == 'original' and value['evidence_kind'] != 'original_dxwnd' else '',
acceptance={'state': 'open', 'remaining': ['Review export is not acceptance']})
copies = [(contained_path(path.parent, name), prefix + name) for name in sorted(paths)]
copies.append((path, prefix + 'receipt.json'))
return result, copies
def _events(sides):
indexed = {}
for side, record in sides.items():
seen = set()
for event in record['events']:
if event['name'] in seen:
raise ValueError('Ambiguous duplicate event on selected media: ' + event['name'])
seen.add(event['name'])
indexed.setdefault(event['name'], {'name': event['name'], 'original': None, 'port': None})[side] = event
return list(indexed.values())
def _ledger(path):
if path is None:
return {'schema_version': 1, 'capabilities': []}, []
data = read_json(path)
if data.get('schema_version') != 1 or not isinstance(data.get('capabilities'), list):
raise ValueError('Unsupported capability export')
result = subprocess.run(['git', '-C', str(PROJECT), 'ls-files', '-z'],
capture_output=True, check=True, timeout=20)
if len(result.stdout) > MAX_JSON_BYTES:
raise ValueError('Tracked source inventory exceeds bound')
tracked = set(result.stdout.decode('utf8').split('\0'))
copies = {}
for capability in data['capabilities']:
if not isinstance(capability, dict) or not isinstance(capability.get('source_links', []), list):
raise ValueError('Capability source_links must be an array')
links = []
for item in capability.get('source_links', []):
if not isinstance(item, dict) or not isinstance(item.get('label'), str):
raise ValueError('Source link requires label and repo-relative path')
source = contained_path(PROJECT, item.get('path'))
relative = source.relative_to(PROJECT).as_posix()
if relative.split('/')[0] in {'Original', 'original', 'artifacts', 'dist', '.git', '.tools', '.nuget'}:
raise ValueError('Source links cannot expose original/generated/private roots')
link = {'label': item['label'], 'path': relative, 'href': None,
'validated_local': False, 'missing': None}
if relative not in tracked or not source.is_file():
link['missing'] = 'Missing tracked source reference; acceptance remains open'
else:
actual = identify_file(source)
if actual['size'] > 1024 * 1024:
raise ValueError('Source text exceeds 1 MiB bound')
text = source.read_bytes()
text.decode('utf8')
if b'\0' in text:
raise ValueError('Source reference must be text, not an executable or package')
if item.get('sha256') and item['sha256'] != actual['sha256']:
raise ValueError('Source reference hash mismatch')
exported = 'sources/' + relative
copies[exported] = source
link.update(href=quote(exported, safe='/'), validated_local=True,
sha256=actual['sha256'], size=actual['size'])
links.append(link)
capability['source_links'] = links
return data, [(source, name) for name, source in sorted(copies.items())]
def export_review(original, port, output, ledger=None):
"""Return review model and atomically publish a NEW self-contained directory."""
output = Path(output)
if output.is_symlink() or output.exists():
raise ValueError('Review output must be a new directory')
output = output.resolve()
separated_roots(PROJECT.parent / 'Original', output)
sides, copies = {}, []
for side, path in [('original', original), ('port', port)]:
if path:
separated_roots(Path(path).resolve().parent, output)
sides[side], files = _side(path, side)
copies += files
present = [s for s in sides.values() if 'case_id' in s]
if len({(s['case_id'], s['scope']) for s in present}) > 1:
raise ValueError('Paired receipts must describe the same case and scope')
ledger_model, source_copies = _ledger(ledger)
copies += source_copies
model = {'schema_version': 1, 'case_id': present[0]['case_id'] if present else 'empty',
'sides': sides, 'events': _events(sides), 'ledger': ledger_model,
'acceptance': {'state': 'open', 'remaining': ['Actual identified runtime and audiovisual review required']}}
encoded = canonical_bytes(model)
if len(encoded) > MAX_JSON_BYTES:
raise ValueError('Review JSON exceeds bound')
output.parent.mkdir(parents=True, exist_ok=True)
temporary = Path(tempfile.mkdtemp(prefix='.' + output.name + '-incomplete-', dir=output.parent))
# Failure retains the temporary tree for diagnosis; never partially publish.
(temporary / 'incomplete.json').write_text('{"status":"incomplete"}\n')
for source, relative in copies:
target = temporary / relative
target.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(source, target)
if identify_file(source) != identify_file(target):
raise ValueError('Artifact changed during review copy')
for name in STATIC:
shutil.copyfile(VIEWER / name, temporary / name)
(temporary / 'review.json').write_bytes(encoded)
files = list(STATIC) + ['review.json'] + [name for _, name in copies]
manifest = {'schema_version': 1, 'tool': 'fidelity_review', 'files':
[dict(path=name, **identify_file(temporary / name)) for name in files]}
(temporary / '.review-root.json').write_bytes(canonical_bytes(manifest))
(temporary / 'incomplete.json').unlink()
# Recheck the receipt/artifact copies with the shared validator at publication.
for side in ('original', 'port'):
receipt = temporary / 'sides' / side / 'receipt.json'
if receipt.exists():
validate_receipt(read_receipt(receipt), receipt.parent)
if output.exists():
raise ValueError('Review output allocated by another writer')
os.rename(temporary, output)
return model
class ReviewHandler(BaseHTTPRequestHandler):
"""No directory listing, upload, repository root, symlink or remote access."""
def log_message(self, *_args):
pass
def end_headers(self):
self.send_header('X-Content-Type-Options', 'nosniff')
self.send_header('Content-Security-Policy', "default-src 'none'; script-src 'self'; style-src 'self'; "
"media-src 'self'; img-src 'self'; connect-src 'self'; base-uri 'none'; "
"frame-ancestors 'none'; form-action 'none'; object-src 'none'")
self.send_header('Referrer-Policy', 'no-referrer')
self.send_header('Cache-Control', 'no-store')
super().end_headers()
def do_GET(self):
self._read(False)
def do_HEAD(self):
self._read(True)
def _reject(self):
self.send_response(405)
self.send_header('Allow', 'GET, HEAD')
self.send_header('Content-Length', '0')
self.end_headers()
do_POST = do_PUT = do_DELETE = do_PATCH = do_OPTIONS = do_TRACE = do_CONNECT = _reject
def _read(self, head):
try:
parsed = urlsplit(self.path)
if parsed.scheme or parsed.netloc or parsed.query or parsed.fragment:
raise ValueError('Only generated local paths are readable')
name = unquote(parsed.path, errors='strict')
name = 'index.html' if name == '/' else name.removeprefix('/')
path = contained_path(self.server.root, name)
if name not in self.server.allowed or not path.is_file():
self.send_error(404)
return
size = path.stat().st_size
start, end, status = 0, size - 1, 200
range_value = self.headers.get('Range')
if range_value:
match = re.fullmatch(r'bytes=([0-9]{0,20})-([0-9]{0,20})', range_value)
if not match or not any(match.groups()) or size == 0:
raise IndexError('Invalid range')
left, right = match.groups()
if left:
start = int(left)
end = min(int(right), size - 1) if right else size - 1
else:
suffix = int(right)
if suffix <= 0:
raise IndexError('Invalid suffix')
start = max(0, size - suffix)
if start >= size or start > end:
raise IndexError('Unsatisfiable range')
end = min(end, start + MAX_RANGE - 1)
status = 206
self.send_response(status)
mime = 'text/javascript' if name.endswith('.mjs') else mimetypes.guess_type(name)[0]
mime = mime or 'application/octet-stream'
if name.startswith('sources/'):
mime = 'text/plain; charset=utf-8'
# Imported HTML/SVG/scripts never become active same-origin content.
if name not in STATIC and not name.startswith('sources/') and not (mime.startswith(('video/', 'audio/')) or
mime in ('image/png', 'image/jpeg', 'image/webp', 'application/json')):
mime = 'application/octet-stream'
self.send_header('Content-Disposition', 'attachment')
self.send_header('Content-Type', mime)
self.send_header('Accept-Ranges', 'bytes')
self.send_header('Content-Length', str(max(0, end - start + 1)))
if status == 206:
self.send_header('Content-Range', f'bytes {start}-{end}/{size}')
self.end_headers()
if not head:
with path.open('rb') as stream:
stream.seek(start)
remaining = end - start + 1
while remaining > 0:
block = stream.read(min(65536, remaining))
if not block:
break
self.wfile.write(block)
remaining -= len(block)
except IndexError:
self.send_response(416)
self.send_header('Content-Range', f'bytes */{size}')
self.send_header('Content-Length', '0')
self.end_headers()
except (BrokenPipeError, ConnectionResetError):
# Browsers cancel range reads while seeking; the response has already
# started. A second error response would itself write to a dead peer.
return
except (ValueError, UnicodeError, OSError):
self.send_error(403)
def make_server(root, port=8765, host='127.0.0.1'):
if host != '127.0.0.1':
raise ValueError('Viewer binds literal IPv4 loopback only')
root = Path(root)
if root.is_symlink():
raise ValueError('Review root must not be a symlink')
root = root.resolve(strict=True)
separated_roots(PROJECT.parent / 'Original', root)
manifest = read_json(contained_path(root, '.review-root.json'))
if manifest.get('tool') != 'fidelity_review' or manifest.get('schema_version') != 1:
raise ValueError('Only generated review trees can be served')
allowed = set()
for item in manifest.get('files', []):
path = contained_path(root, item['path'])
actual = identify_file(path)
if item['sha256'] != actual['sha256'] or item['size'] != actual['size']:
raise ValueError('Generated review changed; export again')
allowed.add(item['path'])
if not set(STATIC + ('review.json',)).issubset(allowed):
raise ValueError('Incomplete generated review')
server = ThreadingHTTPServer((host, port), ReviewHandler)
server.daemon_threads = True
server.root, server.allowed = root, allowed
return server
def main():
parser = argparse.ArgumentParser(description=__doc__)
commands = parser.add_subparsers(dest='command', required=True)
export = commands.add_parser('export')
export.add_argument('--original', type=Path)
export.add_argument('--port', type=Path)
export.add_argument('--output', type=Path, required=True)
export.add_argument('--ledger', type=Path)
serve = commands.add_parser('serve')
serve.add_argument('--root', type=Path, required=True)
serve.add_argument('--port', type=int, default=8765)
args = parser.parse_args()
try:
if args.command == 'export':
model = export_review(args.original, args.port, args.output, args.ledger)
print(json.dumps({'path': str(args.output / 'index.html'),
'events': len(model['events']), 'acceptance': 'OPEN'}))
else:
with make_server(args.root, args.port) as server:
print(f'Local review: http://127.0.0.1:{server.server_port}/ — acceptance OPEN', flush=True)
server.serve_forever()
except (ValueError, OSError, subprocess.SubprocessError) as error:
parser.exit(2, 'Review error: ' + str(error) + '\n')
except KeyboardInterrupt:
parser.exit(0)
if __name__ == '__main__':
main()
+45
View File
@@ -0,0 +1,45 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>GamePort · Fidelity review</title>
<link rel="stylesheet" href="style.css">
<script type="module" src="viewer.mjs"></script>
</head>
<body>
<header><p class="eyebrow">NEUTRON GAMEPORT / LOCAL EVIDENCE</p><h1>Paired recording review</h1>
<p id="scope">Loading local review…</p><p class="notice">Acceptance OPEN · export and fixture playback do not establish original or native gameplay parity.</p></header>
<main>
<section aria-label="Paired recordings" class="pair">
<article id="original-panel"><h2>Original reference</h2><p class="classification"></p>
<video id="original" preload="metadata" playsinline muted></video>
<button class="side-play" type="button">Play original only</button><button class="side-pause" type="button">Pause</button>
<label>Original elapsed seek <input class="seek" aria-label="Seek original recording" type="range" min="0" max="0" value="0" step="0.01"></label>
<p class="missing"></p><output class="clock"></output><div class="links"></div></article>
<article id="port-panel"><h2>Port recording</h2><p class="classification"></p>
<video id="port" preload="metadata" playsinline muted></video>
<button class="side-play" type="button">Play port only</button><button class="side-pause" type="button">Pause</button>
<label>Port elapsed seek <input class="seek" aria-label="Seek port recording" type="range" min="0" max="0" value="0" step="0.01"></label>
<p class="missing"></p><output class="clock"></output><div class="links"></div></article>
</section>
<section class="review-controls" aria-label="Review controls">
<label>Observed event <select id="events"><option value="">Choose an event</option></select></label>
<button id="play" type="button">Play pair at 1×</button><button id="pause" type="button">Pause pair</button>
<label>Soundtrack <select id="audio"><option value="none">Muted</option><option value="original">Original</option><option value="port">Port</option></select></label>
<label>Review volume <input id="gain" type="range" min="0" max="1" step="0.05" value="1"></label>
<output id="gain-label">Unadjusted · 1.00</output>
<p id="state" role="status" aria-live="polite"></p><p id="drift"></p>
<p>Event selection pauses and seeks each observed marker. Playback resumes only when you press Play. Each recording keeps its complete duration at 1×.</p>
</section>
<section aria-label="Optional review aids"><h2>Review aids</h2>
<label><input id="annotations" type="checkbox"> Show event annotations</label>
<label><input id="difference" type="checkbox"> Show lossless still difference</label>
<p id="difference-state">Differences require matched lossless frame identity, viewport and crop metadata.</p>
<div id="annotation-layer" hidden></div><canvas id="difference-layer" hidden aria-label="Optional lossless still difference"></canvas>
<p>Raw recordings above remain unobstructed. Differences are review aids; lossy video is not a numerical fidelity measure.</p>
</section>
<section id="capabilities" aria-label="Capability evidence"></section>
</main>
</body>
</html>
+28
View File
@@ -0,0 +1,28 @@
:root { color-scheme: dark; font: 16px/1.5 system-ui, sans-serif; background: #111820; color: #e4ecf2; }
body { margin: 0 auto; max-width: 1600px; padding: 1.5rem; }
header { border-bottom: 1px solid #455669; margin-bottom: 1.5rem; }
h1 { font-size: clamp(1.7rem, 3vw, 2.6rem); margin: .3rem 0; }
h2 { font-size: 1.25rem; }
.eyebrow { letter-spacing: .1em; color: #9acac1; font-size: .8rem; }
.notice, .missing { color: #f5cf92; }
.pair { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 1.5rem; }
article, section.review-controls { background: #1a2530; border: 1px solid #455669; border-radius: .5rem; padding: 1rem; }
video { display: block; width: 100%; max-height: 65vh; background: #070a0f; }
section { margin-bottom: 1.5rem; }
label { display: inline-flex; align-items: center; gap: .5rem; margin: .5rem .75rem .5rem 0; }
button, select, input { font: inherit; }
button, select { color: inherit; background: #253e4d; border: 1px solid #809fae; border-radius: .3rem; padding: .5rem; }
button { cursor: pointer; margin: .3rem; }
button:disabled { opacity: .5; cursor: default; }
:focus-visible { outline: 3px solid #efc573; outline-offset: 3px; }
a { color: #9ad9e9; overflow-wrap: anywhere; }
.links { display: flex; flex-wrap: wrap; gap: .7rem; margin-top: .5rem; }
.classification { min-height: 3em; overflow-wrap: anywhere; }
output { font-variant-numeric: tabular-nums; }
dt { font-weight: 600; color: #acd0db; } dd { margin-left: 1rem; overflow-wrap: anywhere; }
h4 { margin: .8rem 0 .3rem; } ul { padding-left: 1.3rem; }
canvas { max-width: 100%; background: #000; }
details { margin: .5rem 0; }
summary { cursor: pointer; }
[hidden] { display: none !important; }
@media (max-width: 760px) { body { padding: .7rem; } .pair { grid-template-columns: 1fr; } label { display: flex; } }
+383
View File
@@ -0,0 +1,383 @@
// Native media, independent clocks. No follower seek or rate-based correction.
export function safeLocalURL(value) {
if (typeof value !== 'string' || value.length > 4096 || !value) throw Error('Missing local link');
const decoded = decodeURIComponent(value);
if (/[?#]/.test(value) || /[\\:<>"\u0000-\u001f]/.test(decoded) || decoded.startsWith('/') ||
decoded.split('/').some(p => !p || p === '.' || p === '..')) throw Error('Unsafe local link');
return value;
}
const finiteNonnegative = value => typeof value === 'number' && Number.isFinite(value) && value >= 0;
const sha = value => typeof value === 'string' && /^[a-f0-9]{64}$/.test(value);
export function differenceEligibility(original, port) {
for (const a of [original, port]) {
const f = a?.frame;
if (!f || !sha(a.sha256) || !sha(f.media_sha256) || !f.lossless ||
!a.url?.toLowerCase().endsWith('.png') || !finiteNonnegative(f.media_seconds) ||
typeof f.event !== 'string' || !f.event || !(a.size > 0))
return {eligible: false, reason: 'Missing identified lossless PNG frame and source-media provenance'};
try { safeLocalURL(a.url); } catch { return {eligible: false, reason: 'Unsafe frame link'}; }
if (![f.width, f.height].every(n => Number.isInteger(n) && n > 0 && n <= 8192) ||
!Array.isArray(f.viewport) || f.viewport.length !== 2 ||
!f.viewport.every(n => Number.isInteger(n) && n > 0 && n <= 8192) ||
!Array.isArray(f.crop) || f.crop.length !== 4 ||
!f.crop.every(n => Number.isInteger(n) && n >= 0) ||
f.crop[2] !== f.width || f.crop[3] !== f.height ||
f.crop[0] + f.width > f.viewport[0] || f.crop[1] + f.height > f.viewport[1])
return {eligible: false, reason: 'Invalid frame dimensions, viewport or crop'};
}
const a = original.frame, b = port.frame;
if (a.event !== b.event || a.width !== b.width || a.height !== b.height ||
JSON.stringify(a.viewport) !== JSON.stringify(b.viewport) || JSON.stringify(a.crop) !== JSON.stringify(b.crop))
return {eligible: false, reason: 'Frame event, viewport/aspect or crop mismatch'};
return {eligible: true, reason: 'Matched identified lossless stills; review aid only'};
}
export function createPairController({original, port, onChange = () => {}, timeoutMs = 5000, frames = {}}) {
const media = {original, port};
let problem = '', selected = null, gain = 1, audio = 'none', generation = 0;
let selecting = false;
const overlays = {annotations: false, difference: false};
const listeners = [];
function snapshot() {
const sides = {};
for (const [side, m] of Object.entries(media)) {
sides[side] = {recording_seconds: m?.currentTime ?? null, duration: m?.duration ?? null,
aligned_elapsed: m && selected?.[side] ? m.currentTime - selected[side].media_seconds : null,
state: !m ? 'missing' : m.error ? 'decoding error' : m.currentTime >= m.duration ? 'ended' :
m.seeking ? 'seeking' : m.readyState < 3 ? 'buffering' : m.paused ? 'paused' : 'playing'};
}
return {problem, selected, sides, gain, audio, gainAdjusted: gain !== 1,
gainLabel: gain === 1 ? 'Unadjusted · 1.00' : 'Review-only volume · ' + gain.toFixed(2),
overlays: {...overlays}, selecting,
eventDrift: selected ? {seconds: selected.port.elapsed_seconds - selected.original.elapsed_seconds,
uncertainty_seconds: selected.original.uncertainty_seconds + selected.port.uncertainty_seconds} : null,
playbackDrift: selected && original && port ? sides.port.aligned_elapsed - sides.original.aligned_elapsed : null};
}
const notify = () => onChange(snapshot());
const pause = () => { generation++; selecting = false; for (const m of Object.values(media)) if (m) m.pause(); notify(); };
const fail = message => { problem = message; pause(); };
function listen(m, event, callback) {
m.addEventListener(event, callback); listeners.push(() => m.removeEventListener(event, callback));
}
function setAudio(side) {
if (!['none', 'original', 'port'].includes(side)) throw Error('Unknown soundtrack');
for (const m of Object.values(media)) if (m && !m.muted) m.muted = true;
audio = side;
if (media[side]) media[side].muted = false;
notify();
}
function setGain(value) {
if (!finiteNonnegative(value) || value > 1) throw Error('Review volume must be between zero and one');
gain = value;
for (const m of Object.values(media)) if (m && m.volume !== gain) m.volume = gain;
notify();
}
for (const [side, m] of Object.entries(media)) {
if (!m) continue;
m.muted = true; m.volume = 1; m.playbackRate = 1;
for (const event of ['waiting', 'stalled']) listen(m, event, () => {
if (!selecting) fail(side + ' buffering; wait for readiness then explicitly play');
});
listen(m, 'error', () => fail(side + ' decoding/media error (code ' + (m.error?.code ?? 'unknown') + ')'));
listen(m, 'ended', () => fail(side + ' ended; the other recording tail remains playable'));
listen(m, 'ratechange', () => { if (m.playbackRate !== 1) m.playbackRate = 1; notify(); });
for (const event of ['timeupdate', 'canplay', 'pause', 'playing', 'seeked']) listen(m, event, notify);
// The UI has dedicated audio controls and per-side play/seek controls.
// Guard external unmute changes as well; never enable a second soundtrack.
listen(m, 'volumechange', () => {
if (!m.muted && audio !== side) { m.muted = true; }
if (m.volume !== gain) m.volume = gain;
notify();
});
}
function waitUntil(m, ready, events, label) {
if (m.error) return Promise.reject(Error('Decode failure during ' + label));
if (ready()) return Promise.resolve();
return new Promise((resolve, reject) => {
let timer;
const clean = () => { clearTimeout(timer); for (const event of [...events, 'error']) m.removeEventListener(event, check); };
const check = () => {
if (m.error) { clean(); reject(Error('Decode failure during ' + label)); }
else if (ready()) { clean(); resolve(); }
};
for (const event of [...events, 'error']) m.addEventListener(event, check);
timer = setTimeout(() => { clean(); reject(Error(label + ' readiness timed out')); }, timeoutMs);
check();
});
}
async function seek(m, value) {
m.playbackRate = 1;
m.currentTime = value;
await waitUntil(m, () => !m.seeking, ['seeked'], 'Seek');
}
async function selectEvent(event) {
pause();
const token = generation;
selecting = true; problem = 'Waiting for event seek readiness'; notify();
try {
for (const side of ['original', 'port']) {
const marker = event?.[side];
if (!media[side] || !marker || !['media_seconds', 'elapsed_seconds', 'uncertainty_seconds']
.every(key => finiteNonnegative(marker[key]))) throw Error('Missing or invalid corresponding event');
}
await Promise.all(Object.values(media).map(m => waitUntil(m, () => m.readyState >= 1,
['loadedmetadata', 'durationchange', 'canplay'], 'Metadata')));
if (token !== generation) throw Error('Event selection cancelled');
for (const side of ['original', 'port']) {
if (!Number.isFinite(media[side].duration) || event[side].media_seconds > media[side].duration)
throw Error('Out-of-range corresponding event');
}
await Promise.all(Object.entries(media).map(([side, m]) => seek(m, event[side].media_seconds)));
if (token !== generation) throw Error('Event selection cancelled');
selected = structuredClone(event); problem = '';
} catch (error) { if (token === generation) fail(error.message); throw error; }
finally { if (token === generation) selecting = false; notify(); }
}
async function seekSide(side, seconds) {
pause();
const m = media[side];
if (!m || !finiteNonnegative(seconds) || !Number.isFinite(m.duration) || seconds > m.duration)
throw Error('Invalid manual seek');
try { await seek(m, seconds); problem = ''; notify(); }
catch (error) { fail(error.message); throw error; }
}
async function start(sides) {
if (selecting) { problem = 'Event seek still pending'; notify(); return false; }
const active = sides.filter(side => media[side] && media[side].currentTime < media[side].duration);
for (const side of active) {
const m = media[side];
if (m.error) { fail(side + ' decoding/media error'); return false; }
if (m.readyState < 3 || m.seeking) { fail(side + ' buffering or seeking; explicit recovery required'); return false; }
}
if (!active.length) { fail('Recordings ended or not ready; seek to review again'); return false; }
const token = ++generation;
try {
const results = await Promise.allSettled(active.map(side => {
media[side].playbackRate = 1;
return media[side].play();
}));
if (generation !== token) { for (const m of Object.values(media)) m?.pause(); notify(); return false; }
const rejected = results.find(r => r.status === 'rejected');
if (rejected) throw rejected.reason;
problem = ''; notify(); return true;
} catch (error) { fail('Play rejected: ' + error.message); return false; }
}
async function play() {
if (!original || !port) { fail('Missing recording; available side has manual controls'); return false; }
return start(['original', 'port']);
}
async function playSide(side) {
if (!media[side]) { fail('Missing ' + side + ' recording'); return false; }
pause();
return start([side]);
}
function setOverlay(name, enabled) {
if (!Object.hasOwn(overlays, name)) throw Error('Unknown overlay');
if (name === 'difference' && enabled) {
const eligible = differenceEligibility(frames.original, frames.port);
if (!eligible.eligible) throw Error(eligible.reason);
}
overlays[name] = Boolean(enabled); notify();
}
function dispose() {
pause(); for (const remove of listeners) remove();
}
return {selectEvent, play, playSide, seekSide, pause, snapshot, setAudio, setGain, setOverlay, dispose};
}
function element(doc, tag, text) { const node = doc.createElement(tag); node.textContent = text; return node; }
function describe(doc, value) {
if (Array.isArray(value)) {
const list = doc.createElement('ul');
for (const item of value) { const li = doc.createElement('li'); li.append(describe(doc, item)); list.append(li); }
if (!value.length) list.append(element(doc, 'li', 'None recorded'));
return list;
}
if (value && typeof value === 'object') {
const list = doc.createElement('dl');
for (const [key, item] of Object.entries(value)) {
const dd = doc.createElement('dd'); dd.append(describe(doc, item));
list.append(element(doc, 'dt', key.replaceAll('_', ' ')), dd);
}
return list;
}
return element(doc, 'span', value == null ? 'Unrecorded' : String(value));
}
export function renderCapabilities(container, ledger) {
const doc = container.ownerDocument;
container.replaceChildren(element(doc, 'h2', 'Capability evidence'));
const rows = ledger?.capabilities ?? [];
if (!rows.length) { container.append(element(doc, 'p', 'No capability ledger supplied. Acceptance remains open.')); return; }
const nav = doc.createElement('nav'); nav.setAttribute?.('aria-label', 'Browse gameplay capabilities');
for (const row of rows) {
const a = element(doc, 'a', row.group + ' · ' + row.id);
a.href = '#capability-' + encodeURIComponent(row.id); nav.append(a, element(doc, 'span', ' · '));
}
container.append(nav);
for (const row of rows) {
const article = doc.createElement('article');
article.id = 'capability-' + encodeURIComponent(row.id);
article.append(element(doc, 'h3', row.group + ' · ' + row.id), element(doc, 'p', row.summary),
element(doc, 'p', 'Requirements: ' + (row.requirement_ids ?? []).join(', ')));
const impact = {blocking: 0, disruptive: 1, subtle: 2, missing_verification: 3};
const discrepancies = [...(row.discrepancies ?? [])].sort((a, b) =>
(impact[a.impact] ?? 4) - (impact[b.impact] ?? 4) || String(a.id).localeCompare(String(b.id)));
for (const [label, value] of [['Verified scope', row.verified_scope], ['Known differences', row.differences],
['Acceptance conditions', row.acceptance], ['Current applicable evidence', row.current],
['Discrepancies by impact', discrepancies], ['Scenarios', row.scenario_ids]]) {
article.append(element(doc, 'h4', label), describe(doc, value));
}
article.append(element(doc, 'h4', 'Source evidence'));
for (const link of row.source_links ?? []) {
if (link.validated_local === true && typeof link.href === 'string' && link.href.startsWith('sources/')) {
try {
const a = element(doc, 'a', link.label + ' · ' + link.path);
a.href = safeLocalURL(link.href); a.target = '_blank'; a.rel = 'noopener'; article.append(a);
} catch { article.append(element(doc, 'p', 'Invalid local source link')); }
} else article.append(element(doc, 'p', (link.label ?? String(link)) + ' · ' + (link.path ?? '') +
' · ' + (link.missing ?? 'Source reference not bundled; acceptance remains open')));
}
const history = doc.createElement('details');
history.append(element(doc, 'summary', 'History / superseded evidence'), describe(doc, row.history));
article.append(history); container.append(article);
}
}
export function framePair(model) {
const candidates = {};
for (const side of ['original', 'port']) {
const s = model.sides[side];
candidates[side] = s.artifacts.filter(a => a.frame && a.frame.media_sha256 === s.media?.sha256 &&
finiteNonnegative(a.frame.media_seconds) && a.frame.media_seconds <= s.media.duration_seconds &&
s.events.some(e => e.name === a.frame.event && e.artifact === s.media.path &&
e.media_seconds === a.frame.media_seconds));
}
for (const a of candidates.original) for (const b of candidates.port) {
if (differenceEligibility(a, b).eligible) return {original: a, port: b};
}
return {original: candidates.original[0], port: candidates.port[0]};
}
async function drawDifference(canvas, frames) {
const eligible = differenceEligibility(frames.original, frames.port);
if (!eligible.eligible) throw Error(eligible.reason);
const images = await Promise.all([frames.original, frames.port].map(a => new Promise((resolve, reject) => {
const image = new Image(); image.onload = () => resolve(image);
image.onerror = () => reject(Error('Lossless still failed to decode'));
image.src = safeLocalURL(a.url);
})));
const {width, height} = frames.original.frame;
if (images.some(i => i.naturalWidth !== width || i.naturalHeight !== height))
throw Error('Decoded still dimensions disagree with identified metadata');
canvas.width = width; canvas.height = height;
const context = canvas.getContext('2d', {willReadFrequently: true});
context.drawImage(images[0], 0, 0);
const a = context.getImageData(0, 0, width, height);
context.drawImage(images[1], 0, 0);
const b = context.getImageData(0, 0, width, height);
for (let i = 0; i < a.data.length; i += 4) {
for (let c = 0; c < 3; c++) a.data[i + c] = Math.abs(a.data[i + c] - b.data[i + c]);
a.data[i + 3] = 255;
}
context.putImageData(a, 0, 0);
}
async function mount() {
const doc = document;
try {
const response = await fetch('review.json');
if (!response.ok) throw Error('Review JSON unavailable');
const model = await response.json();
doc.querySelector('#scope').textContent = 'Case: ' + model.case_id;
const media = {};
for (const side of ['original', 'port']) {
const data = model.sides[side], panel = doc.querySelector('#' + side + '-panel');
const m = doc.querySelector('#' + side);
media[side] = data.media ? m : null;
if (data.media) m.src = safeLocalURL(data.media.url);
panel.querySelector('.missing').textContent = [data.missing, data.reference_warning].filter(Boolean).join(' · ');
panel.querySelector('.classification').textContent = [data.evidence_kind ?? 'missing',
JSON.stringify(data.platform ?? {}), data.scope ?? '', data.historical ? 'HISTORICAL' : '',
...(data.limitations ?? [])].join(' · ');
for (const artifact of data.artifacts) {
const a = element(doc, 'a', artifact.role + ' · ' + artifact.path);
a.href = safeLocalURL(artifact.url); a.target = '_blank'; a.rel = 'noopener';
panel.querySelector('.links').append(a);
}
}
const frames = framePair(model);
const format = n => Number.isFinite(n) ? n.toFixed(3) + ' s' : 'unrecorded';
function display(state) {
doc.querySelector('#state').textContent = state.problem || 'Review at actual recording speed · 1×';
doc.querySelector('#gain-label').textContent = state.gainLabel;
for (const side of ['original', 'port']) {
const panel = doc.querySelector('#' + side + '-panel'), clock = state.sides[side];
panel.querySelector('.clock').textContent = 'Recording elapsed ' + format(clock.recording_seconds) +
' / ' + format(clock.duration) + ' · Event offset ' + format(clock.aligned_elapsed) + ' · ' + clock.state;
const seek = panel.querySelector('.seek');
seek.max = String(Number.isFinite(clock.duration) ? clock.duration : 0);
seek.value = String(clock.recording_seconds ?? 0);
}
doc.querySelector('#drift').textContent = state.eventDrift ?
'Observed scenario-event drift (port − original): ' + format(state.eventDrift.seconds) +
' ± ' + format(state.eventDrift.uncertainty_seconds) +
' · Browser playback drift after selected anchors: ' + format(state.playbackDrift) :
'Select corresponding observed markers to see scenario-event and playback drift separately.';
}
const controller = createPairController({...media, frames, onChange: display});
display(controller.snapshot());
for (const side of ['original', 'port']) {
const panel = doc.querySelector('#' + side + '-panel');
panel.querySelector('.side-play').disabled = !media[side];
panel.querySelector('.seek').disabled = !media[side];
panel.querySelector('.side-play').addEventListener('click', () => controller.playSide(side));
panel.querySelector('.side-pause').addEventListener('click', controller.pause);
panel.querySelector('.seek').addEventListener('change', async event => {
try { await controller.seekSide(side, Number(event.target.value)); }
catch (error) { doc.querySelector('#state').textContent = error.message; }
});
const receipt = model.sides[side].receipt_url;
if (receipt) {
const a = element(doc, 'a', 'Receipt / raw and derivative provenance');
a.href = safeLocalURL(receipt); a.target = '_blank'; a.rel = 'noopener';
panel.querySelector('.links').append(a);
}
}
const events = doc.querySelector('#events');
model.events.forEach((event, i) => { const option = element(doc, 'option', event.name +
(!event.original || !event.port ? ' · missing correspondence' : '')); option.value = String(i); events.append(option); });
events.addEventListener('change', async () => {
if (events.value === '') return;
try { await controller.selectEvent(model.events[Number(events.value)]); }
catch (error) { doc.querySelector('#state').textContent = error.message; }
});
doc.querySelector('#play').addEventListener('click', () => controller.play());
doc.querySelector('#pause').addEventListener('click', controller.pause);
doc.querySelector('#audio').addEventListener('change', event => controller.setAudio(event.target.value));
doc.querySelector('#gain').addEventListener('input', event => controller.setGain(Number(event.target.value)));
const annotations = doc.querySelector('#annotation-layer');
annotations.textContent = model.events.map(e => e.name + ' · Original ' + format(e.original?.media_seconds) +
' · Port ' + format(e.port?.media_seconds)).join(' | ');
doc.querySelector('#annotations').addEventListener('change', event => {
controller.setOverlay('annotations', event.target.checked); annotations.hidden = !event.target.checked;
});
const eligibility = differenceEligibility(frames.original, frames.port);
doc.querySelector('#difference-state').textContent = eligibility.reason;
doc.querySelector('#difference').addEventListener('change', async event => {
const canvas = doc.querySelector('#difference-layer');
try {
controller.setOverlay('difference', event.target.checked);
if (event.target.checked) await drawDifference(canvas, frames);
canvas.hidden = !event.target.checked;
} catch (error) {
event.target.checked = false; controller.setOverlay('difference', false); canvas.hidden = true;
doc.querySelector('#difference-state').textContent = error.message;
}
});
renderCapabilities(doc.querySelector('#capabilities'), model.ledger);
} catch (error) { doc.querySelector('#scope').textContent = 'Review unavailable: ' + error.message; }
}
if (typeof document !== 'undefined') mount();
+340
View File
@@ -0,0 +1,340 @@
#!/usr/bin/env python3
"""Local Linux Codex quota watcher. No model starts, auth-file reads, or commits."""
import argparse
import base64
import contextlib
import hashlib
import json
import math
import os
from pathlib import Path
import socket
import struct
import subprocess
import sys
import time
try:
import fcntl
except ImportError: # Keep repository-wide Python test discovery portable.
fcntl = None
ROOT = Path(__file__).resolve().parents[2]
STATE = ROOT / 'artifacts/gsd-quota'
PAUSE = ('The user enabled the GamePort quota guard. Five-hour quota has reached '
'15% remaining or less. Stop dispatching new work. Reach the nearest safe '
'checkpoint, preserve partial/unverified edits without committing them, '
'and use $gsd-pause-work to save the exact continuation. End the turn after '
'saving. Do not wait in a model loop or resume automatically.')
def atomic(path, value):
path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
temp = path.with_name(path.name + '.' + str(os.getpid()) + '.tmp')
fd = os.open(temp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
with os.fdopen(fd, 'w') as out:
json.dump(value, out, indent=2)
os.replace(temp, path)
def read(path, default=None):
try:
return json.loads(path.read_text())
except (OSError, ValueError):
return default
class RPC:
"""Bounded RFC6455 client for the existing Unix app-server socket."""
def __init__(self, path=None):
self.sock = socket.socket(socket.AF_UNIX)
self.sock.settimeout(6)
self.buffer = b''
self.sequence = 0
try:
self.sock.connect(str(path or Path(os.environ.get('CODEX_HOME', Path.home() / '.codex')) /
'app-server-control/app-server-control.sock'))
key = base64.b64encode(os.urandom(16)).decode()
self.sock.sendall(('GET / HTTP/1.1\r\nHost: localhost\r\nUpgrade: websocket\r\n'
'Connection: Upgrade\r\nSec-WebSocket-Version: 13\r\n'
f'Sec-WebSocket-Key: {key}\r\n\r\n').encode())
while b'\r\n\r\n' not in self.buffer:
self.receive()
if len(self.buffer) > 16384:
raise ValueError('Oversized handshake')
header, self.buffer = self.buffer.split(b'\r\n\r\n', 1)
expected = base64.b64encode(hashlib.sha1(
(key + '258EAFA5-E914-47DA-95CA-C5AB0DC85B11').encode()).digest())
if not header.startswith(b'HTTP/1.1 101 ') or expected.lower() not in header.lower():
raise ValueError('Invalid WebSocket handshake')
self.call('initialize', {'clientInfo': {'name': 'gameport-quota-guard', 'version': '1.0'}})
self.send({'method': 'initialized'})
except Exception:
self.close()
raise
def close(self):
self.sock.close()
def receive(self):
part = self.sock.recv(65536)
if not part:
raise EOFError('Codex daemon closed connection')
self.buffer += part
def take(self, size):
while len(self.buffer) < size:
self.receive()
result, self.buffer = self.buffer[:size], self.buffer[size:]
return result
def frame(self, payload, opcode=1):
mask = os.urandom(4)
size = len(payload)
length = bytes([size | 128]) if size < 126 else b'\xfe' + struct.pack('!H', size)
self.sock.sendall(bytes([128 | opcode]) + length + mask +
bytes(c ^ mask[i % 4] for i, c in enumerate(payload)))
def send(self, obj):
self.frame(json.dumps(obj).encode())
def message(self):
result = b''
while True:
first, second = self.take(2)
length = second & 127
if length == 126:
length = struct.unpack('!H', self.take(2))[0]
elif length == 127:
length = struct.unpack('!Q', self.take(8))[0]
if second & 128 or length + len(result) > 2**20:
raise ValueError('Unsupported or oversized server frame')
payload = self.take(length)
opcode = first & 15
if opcode == 8:
raise EOFError('WebSocket closed')
if opcode == 9:
self.frame(payload, 10)
continue
if opcode == 10:
continue
if opcode not in (0, 1):
raise ValueError('Unsupported WebSocket opcode')
result += payload
if first & 128:
return json.loads(result)
def call(self, method, params):
self.sequence += 1
ident = self.sequence
self.send({'id': ident, 'method': method, 'params': params})
deadline = time.monotonic() + 10
while time.monotonic() < deadline:
response = self.message()
if response.get('id') != ident:
continue
if 'error' in response:
raise RuntimeError(str(response['error'].get('code', 'RPC error')))
return response.get('result', {})
raise TimeoutError('RPC deadline exceeded')
def quota(result, now):
buckets = result.get('rateLimitsByLimitId')
# Do not let unused specialty-model buckets override the general Codex quota.
if isinstance(buckets, dict) and 'codex' in buckets:
snapshots = [buckets['codex']]
else:
snapshots = [result.get('rateLimits', {})]
candidates = []
for snapshot in snapshots:
for name in ('primary', 'secondary'):
window = (snapshot or {}).get(name) or {}
used, reset = window.get('usedPercent'), window.get('resetsAt')
if (window.get('windowDurationMins') == 300 and
isinstance(used, (int, float)) and not isinstance(used, bool) and
math.isfinite(used) and 0 <= used <= 100 and
isinstance(reset, (int, float)) and reset > now):
candidates.append({'remaining': 100 - used, 'resetsAt': reset})
if not candidates:
raise ValueError('No current, complete 300-minute quota window')
return dict(min(candidates, key=lambda x: x['remaining']), checkedAt=now)
def stage(sample, now):
if not sample or now - sample.get('checkedAt', 0) > 180 or sample.get('resetsAt', 0) <= now:
return 'unknown'
remaining = sample['remaining']
return 'pause' if remaining <= 15 else 'drain' if remaining <= 20 else 'ready'
def snapshot(sample):
"""Preserve a separate recovery record; never replace the detailed GSD handoff."""
previous = read(STATE / 'snapshot.json', {})
# Server reset estimates can move by a second between reads.
if abs(previous.get('resetsAt', 0) - sample['resetsAt']) <= 120:
return
folder = STATE / ('recovery-' + str(int(sample['resetsAt'])))
if (folder / 'record.json').exists():
return
folder.mkdir(parents=True, exist_ok=True, mode=0o700)
def git(*args):
# Bounded output, tracked source only; no originals/untracked asset copies.
with subprocess.Popen(['git', *args], cwd=ROOT, stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL) as proc:
data = proc.stdout.read(2**21 + 1)
if len(data) > 2**21:
proc.kill()
proc.wait(timeout=10)
return {'text': data[:2**21].decode('utf-8', 'replace'), 'truncated': len(data) > 2**21}
atomic(folder / 'record.json', {
'savedAt': time.time(), 'quota': sample, 'head': git('rev-parse', 'HEAD'),
'status': git('status', '--short'), 'trackedPatch': git('diff', 'HEAD', '--no-ext-diff', '--no-textconv'),
'gsd': {str(p.relative_to(ROOT)): p.read_text()[:262144] for p in
(ROOT / '.planning/HANDOFF.json', ROOT / '.planning/STATE.md') if p.is_file()},
'limits': 'Tracked patch capped at 2 MiB; untracked contents remain in working tree. '
'This recovery record supplements the canonical GSD handoff.'})
atomic(STATE / 'snapshot.json', {'resetsAt': sample['resetsAt'], 'path': str(folder)})
def dispatch(tool):
return tool.split('__')[-1].split('.')[-1] in ('Agent', 'spawn_agent', 'followup_task')
def hook_response(event, tool, sample, now):
level = stage(sample, now)
if event == 'PreToolUse' and dispatch(tool) and level != 'ready':
return {'hookSpecificOutput': {'hookEventName': event, 'permissionDecision': 'deny',
'permissionDecisionReason': f'Quota guard: {level}. No new agent work until '
'fresh five-hour quota is above 20%. Save a checkpoint if at 15% or less.'}}
if event in ('PreToolUse', 'PostToolUse') and level == 'pause':
return {'hookSpecificOutput': {'hookEventName': event, 'additionalContext': PAUSE}}
return {}
def handle_hook(payload):
event = payload.get('hook_event_name')
if event in ('PreModelRequest', 'UserPromptSubmit'):
register(payload)
sample = read(STATE / 'quota.json')
response = hook_response(event, payload.get('tool_name', ''), sample, time.time())
output = response.get('hookSpecificOutput', {})
if 'additionalContext' in output:
# One reminder per turn/window; tool denials are never suppressed.
key = str(payload.get('turn_id'))
marker = STATE / 'context' / (hashlib.sha256(key.encode()).hexdigest() + '.json')
if marker.exists():
return {}
atomic(marker, {'at': time.time()})
return response
def register(payload):
# Per-thread files avoid races between root and child hooks. Never infer turns.
thread = payload.get('agent_id') or payload.get('session_id')
turn = payload.get('turn_id')
if isinstance(thread, str) and isinstance(turn, str) and thread and turn:
ident = hashlib.sha256(thread.encode()).hexdigest()
atomic(STATE / 'threads' / (ident + '.json'),
{'threadId': thread, 'turnId': turn, 'seenAt': time.time()})
def tick():
with contextlib.closing(RPC()) as rpc:
sample = quota(rpc.call('account/rateLimits/read', {}), time.time())
atomic(STATE / 'quota.json', sample)
if stage(sample, time.time()) == 'pause':
snapshot(sample)
for path in (STATE / 'threads').glob('*.json'):
target = read(path, {})
if time.time() - target.get('seenAt', 0) > 86400:
continue
key = f"{target.get('threadId')}:{target.get('turnId')}"
marker = STATE / 'sent' / (hashlib.sha256(key.encode()).hexdigest() + '.json')
if marker.exists():
continue
try:
rpc.call('turn/steer', {'threadId': target['threadId'],
'expectedTurnId': target['turnId'],
'input': [{'type': 'text', 'text': PAUSE}]})
atomic(marker, {'sentAt': time.time()})
except RuntimeError:
# Inactive/wrong turn: no new turn, no interrupt, no costly retry loop.
atomic(marker, {'inactiveAt': time.time()})
return sample
def start():
STATE.mkdir(parents=True, exist_ok=True, mode=0o700)
with open(STATE / 'watch.lock', 'a') as lock:
try:
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError:
return
with open(STATE / 'watch.log', 'ab') as log:
os.chmod(STATE / 'watch.log', 0o600)
subprocess.Popen([sys.executable, str(Path(__file__).resolve()), 'watch'],
cwd=ROOT, stdin=subprocess.DEVNULL, stdout=log, stderr=log,
start_new_session=True, close_fds=True)
def watch():
STATE.mkdir(parents=True, exist_ok=True, mode=0o700)
with open(STATE / 'watch.lock', 'a') as lock:
try:
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError:
return
stop = STATE / 'stop'
stop.unlink(missing_ok=True)
atomic(STATE / 'watcher.json', {'pid': os.getpid(), 'startedAt': time.time()})
while not stop.exists():
try:
tick()
(STATE / 'error.json').unlink(missing_ok=True)
except (OSError, ValueError, RuntimeError, EOFError, TimeoutError) as error:
atomic(STATE / 'error.json', {'at': time.time(), 'type': type(error).__name__})
for _ in range(60):
if stop.exists():
return
time.sleep(1)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('command', choices=['hook', 'watch', 'start', 'stop', 'status', 'refresh'])
args = parser.parse_args()
if fcntl is None:
parser.error('The quota watcher runs on the Linux Codex host only.')
if args.command == 'hook':
payload = json.load(sys.stdin)
if not Path(payload.get('cwd', '')).resolve().is_relative_to(ROOT):
return
start()
print(json.dumps(handle_hook(payload)))
elif args.command == 'watch':
watch()
elif args.command == 'start':
start()
elif args.command == 'stop':
STATE.mkdir(parents=True, exist_ok=True, mode=0o700)
(STATE / 'stop').touch(mode=0o600)
elif args.command == 'refresh':
print(json.dumps(tick()))
else:
sample = read(STATE / 'quota.json')
running = False
if (STATE / 'watch.lock').exists():
with open(STATE / 'watch.lock', 'a') as lock:
try:
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError:
running = True
print(json.dumps({'stage': stage(sample, time.time()), 'quota': sample,
'running': running,
'watcher': read(STATE / 'watcher.json'),
'error': read(STATE / 'error.json')}))
if __name__ == '__main__':
main()