Compare commits
7
Commits
96c5f2c00f
...
6be8484802
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6be8484802 | ||
|
|
f9f7a7277a | ||
|
|
ac958e1962 | ||
|
|
32a72654e8 | ||
|
|
cc4a5a3e92 | ||
|
|
cd7783ba3a | ||
|
|
597caa0b49 |
No files matched your search
@@ -39,9 +39,9 @@ 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.
|
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.
|
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.
|
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:** 0/7 plans executed
|
**Plans:** 1/7 plans executed
|
||||||
**Wave 1**
|
**Wave 1**
|
||||||
- [ ] 01-01-PLAN.md
|
- [x] 01-01-PLAN.md
|
||||||
|
|
||||||
**Wave 2** *(blocked on Wave 1 completion)*
|
**Wave 2** *(blocked on Wave 1 completion)*
|
||||||
- [ ] 01-02-PLAN.md
|
- [ ] 01-02-PLAN.md
|
||||||
@@ -151,7 +151,7 @@ Execution follows 1 → 2 → 3 → 4 → 5 → 6 → 7 → 8, subject to the ex
|
|||||||
|
|
||||||
| Phase | Plans Complete | Status | Completed |
|
| Phase | Plans Complete | Status | Completed |
|
||||||
|-------|----------------|--------|-----------|
|
|-------|----------------|--------|-----------|
|
||||||
| 1. Reproducible Fidelity Baseline | 0/7 | Planned | - |
|
| 1. Reproducible Fidelity Baseline | 1/7 | In Progress | - |
|
||||||
| 2. Faithful Movement and Scene Handoffs | 0/TBD | Not started | - |
|
| 2. Faithful Movement and Scene Handoffs | 0/TBD | Not started | - |
|
||||||
| 3. Original Actors, Hazards and Combat | 0/TBD | Not started | - |
|
| 3. Original Actors, Hazards and Combat | 0/TBD | Not started | - |
|
||||||
| 4. Complete Gadget and Vehicle Use | 0/TBD | Not started | - |
|
| 4. Complete Gadget and Vehicle Use | 0/TBD | Not started | - |
|
||||||
|
|||||||
+21
-13
@@ -1,18 +1,18 @@
|
|||||||
---
|
---
|
||||||
gsd_state_version: "1.0"
|
gsd_state_version: "1.0"
|
||||||
current_phase: 1
|
current_phase: 01
|
||||||
current_phase_name: Reproducible Fidelity Baseline
|
current_phase_name: Reproducible Fidelity Baseline
|
||||||
status: executing
|
status: executing
|
||||||
stopped_at: "Phase 1 planned and verified; next: gsd-execute-phase 1"
|
stopped_at: Completed 01-01-PLAN.md
|
||||||
last_updated: "2026-11-12T22:38:11.076Z"
|
last_updated: "2026-11-13T00:13:22.917Z"
|
||||||
last_activity: 2026-11-12
|
last_activity: 2026-11-12
|
||||||
last_activity_desc: Phase 1 research and seven plans verified; ready to execute
|
last_activity_desc: Phase 01 execution started
|
||||||
state_head: 36f24e4474909b299c38c07800823f43498a95a9
|
state_head: ac958e1962f381804f6a5ad6bf9ea2559a652fff
|
||||||
progress:
|
progress:
|
||||||
total_phases: 8
|
total_phases: 8
|
||||||
completed_phases: 0
|
completed_phases: 0
|
||||||
total_plans: 7
|
total_plans: 7
|
||||||
completed_plans: 0
|
completed_plans: 1
|
||||||
percent: 0
|
percent: 0
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -23,14 +23,14 @@ progress:
|
|||||||
See: .planning/PROJECT.md (updated 2026-11-12)
|
See: .planning/PROJECT.md (updated 2026-11-12)
|
||||||
|
|
||||||
**Core value:** Match original behavior and presentation as accurately as possible, governed by authoritative evidence and explicit verification.
|
**Core value:** Match original behavior and presentation as accurately as possible, governed by authoritative evidence and explicit verification.
|
||||||
**Current focus:** Phase 1 — Reproducible Fidelity Baseline.
|
**Current focus:** Phase 01 — Reproducible Fidelity Baseline
|
||||||
|
|
||||||
## Current Position
|
## Current Position
|
||||||
|
|
||||||
Phase: 1 (Reproducible Fidelity Baseline) — READY TO EXECUTE
|
Phase: 01 (Reproducible Fidelity Baseline) — EXECUTING
|
||||||
Plan: 0 of 7 executed; next plan 01-01
|
Plan: 2 of 7
|
||||||
Status: Ready to execute
|
Status: Ready to execute
|
||||||
Last activity: 2026-11-12 — Phase 1 research and seven plans verified; ready to execute
|
Last activity: 2026-11-12 — Phase 01 execution started
|
||||||
|
|
||||||
Progress: [░░░░░░░░░░] 0%
|
Progress: [░░░░░░░░░░] 0%
|
||||||
|
|
||||||
@@ -45,6 +45,11 @@ Progress: [░░░░░░░░░░] 0%
|
|||||||
| - | - | - | - |
|
| - | - | - | - |
|
||||||
|
|
||||||
Recent trend: No execution plans completed in this roadmap. Existing project work predates initialization and retains its documented bounded evidence.
|
Recent trend: No execution plans completed in this roadmap. Existing project work predates initialization and retains its documented bounded evidence.
|
||||||
|
**Per-Plan Metrics:**
|
||||||
|
|
||||||
|
| Plan | Duration | Tasks | Files |
|
||||||
|
|------|----------|-------|-------|
|
||||||
|
| Phase 01 P01 | 16 min | 2 tasks | 5 files |
|
||||||
|
|
||||||
## Accumulated Context
|
## Accumulated Context
|
||||||
|
|
||||||
@@ -55,6 +60,9 @@ Recent trend: No execution plans completed in this roadmap. Existing project wor
|
|||||||
- Preserve Jimmy movement and implemented TSK startup-order correction; movement/contact/helper/animation/camera stabilization precedes broader gameplay expansion.
|
- Preserve Jimmy movement and implemented TSK startup-order correction; movement/contact/helper/animation/camera stabilization precedes broader gameplay expansion.
|
||||||
- Cross-cutting checks continue throughout; each requirement has one accountable phase. No original-required category is deferred outside this release.
|
- Cross-cutting checks continue throughout; each requirement has one accountable phase. No original-required category is deferred outside this release.
|
||||||
- Builds/tests/packages stay local; push verified source/tools/docs to existing Gitea. Preserve unrelated working-tree changes.
|
- Builds/tests/packages stay local; push verified source/tools/docs to existing Gitea. Preserve unrelated working-tree changes.
|
||||||
|
- [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.
|
||||||
|
|
||||||
### Pending Todos
|
### Pending Todos
|
||||||
|
|
||||||
@@ -81,6 +89,6 @@ No original-required category deferred outside full reconstruction. Later phases
|
|||||||
|
|
||||||
## Session Continuity
|
## Session Continuity
|
||||||
|
|
||||||
Last session: 2026-11-12T22:37:42.727Z
|
Last session: 2026-11-13T00:13:05.517Z
|
||||||
Stopped at: Phase 1 planned and verified; next: gsd-execute-phase 1
|
Stopped at: Completed 01-01-PLAN.md
|
||||||
Resume file: .planning/phases/01-reproducible-fidelity-baseline/01-01-PLAN.md
|
Resume file: None
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
---
|
||||||
|
schema_version: 1
|
||||||
|
open_count: 0
|
||||||
|
waived_count: 0
|
||||||
|
fixed_count: 1
|
||||||
|
total_count: 1
|
||||||
|
last_updated: 2026-11-13T00:13:04.410Z
|
||||||
|
---
|
||||||
|
|
||||||
|
# Broken Windows Ledger
|
||||||
|
|
||||||
|
> Cross-phase defect register. With `workflow.windows_enforce` enabled, `/gsd-ship` blocks while `open_count > 0`.
|
||||||
|
> Waive with `gsd-tools windows waive <id> "<reason>"` (reason required).
|
||||||
|
> Mark fixed with `gsd-tools windows fixed <id>`.
|
||||||
|
|
||||||
|
| 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 |
|
||||||
|
|
||||||
|
````json
|
||||||
|
[
|
||||||
|
{
|
||||||
|
"id": 1,
|
||||||
|
"kind": "deviation",
|
||||||
|
"phase": "01",
|
||||||
|
"file": "tests/test_fidelity_sessions.py",
|
||||||
|
"line": null,
|
||||||
|
"description": "Task 2 also strengthens shared receipt security regressions in the task-1 test file; fixed and verified.",
|
||||||
|
"status": "fixed",
|
||||||
|
"reason": "",
|
||||||
|
"recorded_at": "2026-11-13T00:12:34.143Z",
|
||||||
|
"resolved_at": "2026-11-13T00:13:04.410Z",
|
||||||
|
"milestone": null
|
||||||
|
}
|
||||||
|
]
|
||||||
|
````
|
||||||
@@ -16,7 +16,8 @@
|
|||||||
"repo_tagging": "single",
|
"repo_tagging": "single",
|
||||||
"phase_branch_template": "gsd/phase-{phase}-{slug}",
|
"phase_branch_template": "gsd/phase-{phase}-{slug}",
|
||||||
"milestone_branch_template": "gsd/{milestone}-{slug}",
|
"milestone_branch_template": "gsd/{milestone}-{slug}",
|
||||||
"quick_branch_template": null
|
"quick_branch_template": null,
|
||||||
|
"allow_default_branch_commits": true
|
||||||
},
|
},
|
||||||
"workflow": {
|
"workflow": {
|
||||||
"research": true,
|
"research": true,
|
||||||
|
|||||||
@@ -0,0 +1,163 @@
|
|||||||
|
---
|
||||||
|
phase: 01-reproducible-fidelity-baseline
|
||||||
|
plan: "01"
|
||||||
|
subsystem: testing
|
||||||
|
tags: [python, sha256, fidelity, preservation, receipts, scenarios]
|
||||||
|
requires: []
|
||||||
|
provides:
|
||||||
|
- Local preserved-session stage/identify/import/validate CLI
|
||||||
|
- Version 1 hashed receipt and read-only relative-reference contract
|
||||||
|
- Eight explicit lifetime/dialogue/input cells with 120 original/native obligations
|
||||||
|
affects: [01-02, 01-03, 01-04, 01-05, 01-06, 01-07]
|
||||||
|
tech-stack:
|
||||||
|
added: []
|
||||||
|
patterns: [stdlib-only tooling, exclusive allocation, atomic directory publication, streaming SHA-256, bounded JSON, explicit open acceptance]
|
||||||
|
key-files:
|
||||||
|
created:
|
||||||
|
- tools/recon/fidelity.py
|
||||||
|
- tools/recon/fidelity_receipts.py
|
||||||
|
- tests/test_fidelity_sessions.py
|
||||||
|
- docs/evidence/scenarios.json
|
||||||
|
- tests/test_fidelity_scenarios.py
|
||||||
|
modified: []
|
||||||
|
key-decisions:
|
||||||
|
- "A valid or reviewed receipt never implies native/original acceptance without identified bytes, compatible category, required artifacts and declared audiovisual review."
|
||||||
|
- "Each matrix cell requires continuous plus dialogue-return, bank-left, bank-right and landing-idle observations on original-DxWnd Windows, native Linux port and native Windows port: 120 obligations."
|
||||||
|
- "Retained runs bind one session, prerequisite departure/return observations and hashed copy state; fresh runs require independent launch/session IDs."
|
||||||
|
patterns-established:
|
||||||
|
- "Import IDs are append-only; only byte-identical duplicate records are idempotent."
|
||||||
|
- "Incomplete temporary publications retain diagnostics; stale locks are never stolen automatically."
|
||||||
|
requirements-completed: [EVID-01, EVID-02, EVID-04]
|
||||||
|
requirements-acceptance: "OPEN: these shared IDs remain Pending in REQUIREMENTS.md; this field records this plan's assigned contribution, not full requirement acceptance."
|
||||||
|
coverage:
|
||||||
|
- id: preserved-sessions
|
||||||
|
description: Preserved staging, actual byte identification and typed hashed imports
|
||||||
|
requirement: EVID-01
|
||||||
|
verification:
|
||||||
|
- kind: integration
|
||||||
|
ref: tests/test_fidelity_sessions.py
|
||||||
|
status: pass
|
||||||
|
- kind: other
|
||||||
|
ref: python3 tools/recon/inventory.py ../Original --verify docs/original-manifest.json
|
||||||
|
status: pass
|
||||||
|
human_judgment: false
|
||||||
|
- id: scenario-contract
|
||||||
|
description: Eight matrix cells, continuous/focused procedures and strict completeness audit
|
||||||
|
requirement: EVID-02
|
||||||
|
verification:
|
||||||
|
- kind: integration
|
||||||
|
ref: tests/test_fidelity_scenarios.py
|
||||||
|
status: pass
|
||||||
|
human_judgment: false
|
||||||
|
- id: runtime-acceptance
|
||||||
|
description: Actual identified original-DxWnd and native Linux/Windows audiovisual comparison
|
||||||
|
requirement: EVID-04
|
||||||
|
verification: []
|
||||||
|
human_judgment: true
|
||||||
|
rationale: "Future capture and human review are required; current real receipt coverage is 0/120. No new game or platform execution occurred in this plan."
|
||||||
|
actuals:
|
||||||
|
tokens: 21054
|
||||||
|
tasks: 2
|
||||||
|
commits: 4
|
||||||
|
basis: "ceil(chars/4) of the realized five-file production/test/protocol diff; excludes planning metadata"
|
||||||
|
plan_head_before: 96c5f2c00fd41e379945300b027e2c5ce9552845
|
||||||
|
plan_head_after: 32a72654e88ad3709aa1e2f0f108eea06e1b7469
|
||||||
|
duration: 16 min
|
||||||
|
started: 2026-11-12T23:56:04Z
|
||||||
|
completed: 2026-11-13
|
||||||
|
status: complete
|
||||||
|
---
|
||||||
|
|
||||||
|
# Phase 01 Plan 01: Preserved Sessions and Scenario Contract Summary
|
||||||
|
|
||||||
|
**Streaming original/copy/package identities, atomic typed receipt imports and eight explicit comparison cells preserve missing native/reference acceptance.**
|
||||||
|
|
||||||
|
## Performance
|
||||||
|
|
||||||
|
- Started: 2026-11-12T23:56:04Z; completed: 2026-11-13 UTC; approximately 16 minutes.
|
||||||
|
- Tasks: 2; source/test/protocol files created: 5; task commits: 4, measured from the persisted plan ledger.
|
||||||
|
- Final counted suites: 29 session tests in 0.698 seconds including process overhead; 22 scenario tests in 0.460 seconds. The combined discovery run executes 51 tests in 1.017 seconds.
|
||||||
|
- Original inventory: 539 unchanged files, final measured invocation 0.229 seconds.
|
||||||
|
|
||||||
|
## Accomplishments
|
||||||
|
|
||||||
|
- Real CLI fixture round trip stages a pristine installation, identifies its copy, imports paired explicitly synthetic WAV artifacts and prints a readable hashed receipt with OPEN acceptance. Hostile output paths and tampered evidence also return nonzero CLI exits.
|
||||||
|
- Preservation checks reject equal/nested/case/symlink aliases, changed/missing/added/empty identities, drive/traversal references, collisions and reuse. Source pre/post identity, pristine copy and post-run copy changes remain separate. Interrupted stage/import attempts retain incomplete diagnostics; concurrent stage allocation has one winner.
|
||||||
|
- Explicit procedures cover all fresh/retained × natural/skipped × ordinary/edge cells. Each has one continuous lab → VR04 → lab → outside journey plus four focused obligations, independently required on three original/native sides.
|
||||||
|
- Validators reject disconnected clips, timestamp resets, missing dimensions/events/artifacts, conflicting slots, reused fresh sessions, broken retained continuity and synthetic/Wine/component/cross-publish substitution. Structural readiness succeeds with visible gaps; strict acceptance exits 1 with 0/120 obligations accepted and all eight missing case IDs.
|
||||||
|
|
||||||
|
## Task Commits
|
||||||
|
|
||||||
|
1. Task 01-01-01 RED: `597caa0` — test preserved sessions and receipt trust boundaries.
|
||||||
|
2. Task 01-01-01 GREEN: `cd7783b` — implement stage/identify/import/validate and historical package identification.
|
||||||
|
3. Task 01-01-02 RED: `cc4a5a3` — test complete journey and lifetime matrix.
|
||||||
|
4. Task 01-01-02 GREEN: `32a7265` — enforce protocol, completeness and additional shared receipt security regressions.
|
||||||
|
|
||||||
|
Commits ran normal hooks, with explicit scoped staging. No tracked files were deleted. The existing user-authorized main workflow uses the primary's `git.allow_default_branch_commits` setting. The primary owns review, milestone status documents, integration and push; this executor did not push.
|
||||||
|
|
||||||
|
## Interfaces for Consumers
|
||||||
|
|
||||||
|
`fidelity_receipts.py` exports `stage_original(source, manifest, output, session_id)`, `identify_tree(root)`, `identify_file(path)`, `postflight_session(session, source, manifest)`, `validate_receipt(receipt, root)`, `import_receipt(path, root, output)`, `read_receipt(path)`, `contained_path(root, relative)`, `source_identity(project)`, `identify_report(...)`, `validate_scenario_contract(protocol)`, `required_events(protocol, cell, obligation_id)`, `audit_scenarios(protocol, [(receipt, root), ...])` and `audit_receipt_tree(protocol, root)`. Invalid input raises `ValueError`; filesystem failures propagate. CLI errors return 2; strict valid-but-open audit returns 1.
|
||||||
|
|
||||||
|
- Schema version 1 receipt: `receipt_id`, `session_id`, `case_id`, `evidence_kind`, `status`, `historical`, `scope`, `platform`, `identity`, `invocation`, `clocks`, `artifacts`, `derivatives`, `events`, `limitations`, `missing_evidence`, `acceptance`.
|
||||||
|
- `platform`: explicit `os`, `execution`; native port uses `native`, original Windows reference uses `dxwnd`, other kinds use their own category. Actual OS version and port GPU/driver/Vulkan/SDL provenance are required for acceptance.
|
||||||
|
- Artifacts/identity references use contained relative POSIX `path`, actual `size` and `sha256`. Artifacts carry `role`; timed media carries `duration_seconds`. Source identity additionally records commit, dirty/diff/status hashes and hashed untracked file identities. Invocations are inert argument arrays and a recorded cwd; imported commands are never executed.
|
||||||
|
- `clocks`: timezone-aware wall start/end plus finite monotonic start/end; scenario observations additionally require `clock_id`. Events use name/artifact/media_seconds/elapsed_seconds/method/uncertainty_seconds. Port simulation ticks are separate; original annotations remain manual/procedural.
|
||||||
|
- Scenario records add `obligation_id` and matching `scope`: `continuous`, `dialogue-return`, `bank-left`, `bank-right`, `landing-idle`; `case_id` equals the explicit cell ID. `continuity` binds lifetime/session and prerequisite artifact; retained cases also bind same departure/return session, identified pre/retained copy hashes and observed prerequisite markers preceding the tested interval.
|
||||||
|
- State-machine documentation lives in the module docstring and `RECEIPT_TRANSITIONS`. Import snapshots are immutable by ID; changing a capture/review requires a new receipt ID, rather than overwriting history. Synthetic imports require a separate output directory containing `test` in its name.
|
||||||
|
- JSON is bounded to 4 MiB, tree enumeration to 100000 entries, and tool-owned Git identity subprocesses to 20 seconds with bounded reads. Hashes stream in 1 MiB blocks. No dependencies were installed.
|
||||||
|
|
||||||
|
## Verification and Evidence Limits
|
||||||
|
|
||||||
|
Both exact counted plan commands passed, as did the mandated inventory command. Full logs and measured exit codes are in ignored `artifacts/fidelity/verification/`; the strict open audit's expected exit 1 is recorded there. Task 1 tracer verification ran again before expansion. Evaluation scope resolves all four task commits on the current branch.
|
||||||
|
|
||||||
|
One real on-disk `dist/linux-x64` package, its DLL/assets/launcher and `docs/gameplay/main-menu-player-lifetime.md` were hashed by the actual CLI. Ignored `artifacts/fidelity/historical-package.json` records package tree SHA-256 `eff9739dc6282ebb9e047f0a4a38e24b3c46e82502435e07c5a4b66bd31f05de` and DLL SHA-256 `8769ddd4e9f5fa8d4600dcca6ca46436385e14223097f44de68489bc4222f83b`. The report's recorded scope remains historical, with no current applicability or new runtime identity inferred from today's source HEAD. Missing-artifact behavior is separately tested.
|
||||||
|
|
||||||
|
The 120-slot positive test uses temporary metadata declarations solely to prove the counting/validation algorithm. The paired WAV fixture is explicitly synthetic and exercises import plumbing only. Neither is imported into the real receipt index. Hashes and declared human-review fields do not independently prove visible/audible content or truthful capture assertions; capture/probe/review/applicability remain later plan responsibilities. No original, DxWnd, Wine, native Windows, native Linux gameplay, browser, GPU, managed runtime, build or package execution was performed by this plan. Legacy `reference_capture.py`, movement, TSK ordering, fresh direct-scene order, legitimate landing bank and admission gates were not edited.
|
||||||
|
|
||||||
|
## TDD Gate Compliance
|
||||||
|
|
||||||
|
- Task 1: the real CLI round-trip target failed its stage-success assertion before implementation; full 25-test report and semantic assessment are in `artifacts/fidelity/tdd/01-01-01-red.json`. The classifier returned `RED_EVIDENCE_OK`; RED precedes GREEN in ancestry. Final suite has 29 passing cases.
|
||||||
|
- Task 2: the eight-cell target failed its explicit protocol-presence assertion before implementation; full 18-test report and semantic assessment are in `artifacts/fidelity/tdd/01-01-02-red.json`. The classifier returned `RED_EVIDENCE_OK`. That report also retains a separate missing-API error; the named target itself executed and failed the intended assertion. Final suite has 22 passing cases.
|
||||||
|
- REFACTOR: no separate refactor was necessary. No skipped/todo tests, unrun planned automated checks or implementation stubs remain.
|
||||||
|
|
||||||
|
## Deviations from Plan
|
||||||
|
|
||||||
|
### Auto-fixed Issues
|
||||||
|
|
||||||
|
**1. [Rule 2 - Missing Critical Functionality] Strengthened shared receipt security while completing scenario validation.**
|
||||||
|
- Found during: Task 2.
|
||||||
|
- Issue: shared import review needed directory-component case-alias checks and receipt-metadata sidecar tamper verification, in addition to file hashes.
|
||||||
|
- Fix: added these checks and regressions, bounded aggregate JSON output, and used actual paired synthetic WAVs. Task 2 consequently also edits `tests/test_fidelity_sessions.py`, beyond its narrow task file list but within the plan's exclusive ownership.
|
||||||
|
- Files: both fidelity modules, session/scenario tests.
|
||||||
|
- Verification: all 51 tests pass, including CLI tamper rejection and prefix-case collision tests.
|
||||||
|
- Commit: `32a7265`.
|
||||||
|
|
||||||
|
Total deviations: 1 correctness/security expansion within the planned boundary; no architectural or gameplay change. Optional broken-windows recording was attempted through the handler.
|
||||||
|
|
||||||
|
## Threat/Test Coverage
|
||||||
|
|
||||||
|
| Threat | Implemented controls | Evidence |
|
||||||
|
|---|---|---|
|
||||||
|
| T-01-01 | Alias/overlap checks before staging writes, exact inventory records, verified pristine copy, source pre/post checks | Session preservation/hostile-path/postflight tests; 539 original hashes |
|
||||||
|
| T-01-02 | Actual file hashes, typed platform/kind, explicit history/open acceptance, independent matrix slots and human review requirements | Tamper/classification/strict-audit and 120-slot metadata tests |
|
||||||
|
| T-01-03 | Exclusive allocation, sibling temporary publication, persistent incomplete diagnostics, exact duplicate bytes and conflicts | Concurrent allocation/interruption/duplicate import tests |
|
||||||
|
| T-01-SC | No package installation | Stdlib-only implementation |
|
||||||
|
|
||||||
|
No new endpoints, authentication paths or schema trust boundaries beyond the plan's local filesystem/import surface were introduced. The workflow serializes cooperative writers; concurrent hostile filesystem mutation is explicitly outside its offline threat boundary. Revalidate after collection and before review.
|
||||||
|
|
||||||
|
## Issues Encountered
|
||||||
|
|
||||||
|
None blocking. Synthetic fixtures stay separate from runtime proof. The unrelated `tools.yaml`, primary-owned config/state changes and milestone lock were preserved.
|
||||||
|
|
||||||
|
## User Setup Required
|
||||||
|
|
||||||
|
None for these tooling tests. Actual original-DxWnd/native capture and audiovisual review remain future combined checkpoint obligations, not requested prematurely here.
|
||||||
|
|
||||||
|
## Next Phase Readiness
|
||||||
|
|
||||||
|
Plans 01-02/03/04 can consume the versioned interfaces and scenario contract. Shared EVID-01/02/04 remain Pending until all declaring plans and actual acceptance conditions finish. Current strict audit is OPEN with 0/120 runtime obligations. The primary will update root continuity/compatibility documents and perform integration tests/push.
|
||||||
|
|
||||||
|
## Self-Check: PASSED
|
||||||
|
|
||||||
|
All five created source/test/protocol files exist. All four task commits are ancestors of current HEAD; evaluation-scope resolves them. Exact counted acceptance commands, original inventory and diff whitespace checks pass. No implementation stubs or unexplained tracked deletions were found.
|
||||||
@@ -49,5 +49,5 @@
|
|||||||
"label": "Advance to the next step",
|
"label": "Advance to the next step",
|
||||||
"reason": "Phase 1 of 8 · 0% · executing"
|
"reason": "Phase 1 of 8 · 0% · executing"
|
||||||
},
|
},
|
||||||
"updated_at": "2026-11-12T22:37:08.492Z"
|
"updated_at": "2026-11-13T00:13:04.735Z"
|
||||||
}
|
}
|
||||||
@@ -1,5 +1,21 @@
|
|||||||
# Compatibility and validation
|
# Compatibility and validation
|
||||||
|
|
||||||
|
## Phase 1 wave 1 tooling verification
|
||||||
|
|
||||||
|
Full wave1 `scripts/test.sh` exits0:403 Python checks plus2 HUD checks,
|
||||||
|
all managed projects and36 rendering checks pass with zero Vulkan validation
|
||||||
|
errors; SDL dummy-device audio lifecycle and539 original hashes pass. NU1900
|
||||||
|
reports unavailable vulnerability metadata; no build error. Log stays local at
|
||||||
|
`artifacts/fidelity/wave1-test.log`. This is baseline regression evidence, not
|
||||||
|
new whole-original/native Windows comparison.
|
||||||
|
|
||||||
|
Preservation/receipt/scenario tooling passes51 Python tests on the development
|
||||||
|
Linux host;539 original hashes are unchanged. This checks local metadata and
|
||||||
|
filesystem behavior, not Windows/DxWnd execution or gameplay comparison. An
|
||||||
|
existing package was identified as historical only; current acceptance stays
|
||||||
|
OPEN at0/120 runtime obligations. No runtime/gameplay/package code changed.
|
||||||
|
Details and exact commits: `../.planning/phases/01-reproducible-fidelity-baseline/01-01-SUMMARY.md`.
|
||||||
|
|
||||||
## Phase 1 planning verification — 2026-11-12
|
## Phase 1 planning verification — 2026-11-12
|
||||||
|
|
||||||
Seven phase plans pass independent review, requirement/decision coverage and
|
Seven phase plans pass independent review, requirement/decision coverage and
|
||||||
|
|||||||
@@ -1,5 +1,18 @@
|
|||||||
# Decisions
|
# Decisions
|
||||||
|
|
||||||
|
## Phase 1 evidence contract — wave 1
|
||||||
|
|
||||||
|
Session/receipt schema1 records original/copy/package/media identities separately.
|
||||||
|
Imported commands are inert data; duplicate IDs are idempotent only for identical
|
||||||
|
bytes. Retained cases bind departure/return and copy-state evidence; fresh cases
|
||||||
|
have independent lifetime IDs. Eight dialogue/lifetime/input cells each require
|
||||||
|
continuous plus dialogue-return, left/right bank and landing-idle scope on original
|
||||||
|
Windows/DxWnd, native Linux port and native Windows port (120 obligations).
|
||||||
|
Synthetic/component/Wine/cross-publish/historical evidence cannot substitute.
|
||||||
|
The GSD worktree fork-base guard selected sequential native executors because
|
||||||
|
origin/HEAD is absent in this Gitea/main repository. Existing user authorization
|
||||||
|
for main commits is encoded in git.allow_default_branch_commits.
|
||||||
|
|
||||||
## Phase 1 execution structure — 2026-11-12
|
## Phase 1 execution structure — 2026-11-12
|
||||||
|
|
||||||
Build the agreed evidence workflow in seven plans/five waves: preservation and
|
Build the agreed evidence workflow in seven plans/five waves: preservation and
|
||||||
|
|||||||
@@ -0,0 +1,99 @@
|
|||||||
|
{
|
||||||
|
"schema_version": 1,
|
||||||
|
"protocol_id": "phase01-baseline-v1",
|
||||||
|
"description": "Procedures and obligations only. No runtime acceptance is asserted by this document.",
|
||||||
|
"decisions": ["D-01", "D-02", "D-03", "D-04", "D-15"],
|
||||||
|
"required_sides": [
|
||||||
|
{"id": "original-windows-dxwnd", "evidence_kind": "original_dxwnd", "os": "windows"},
|
||||||
|
{"id": "port-linux-native", "evidence_kind": "native_port", "os": "linux"},
|
||||||
|
{"id": "port-windows-native", "evidence_kind": "native_port", "os": "windows"}
|
||||||
|
],
|
||||||
|
"cells": [
|
||||||
|
{"id": "fresh-natural-edge", "lifetime": "fresh", "dialogue": "natural", "input": "edge", "obligations": ["continuous", "dialogue-return", "bank-left", "bank-right", "landing-idle"]},
|
||||||
|
{"id": "fresh-natural-ordinary", "lifetime": "fresh", "dialogue": "natural", "input": "ordinary", "obligations": ["continuous", "dialogue-return", "bank-left", "bank-right", "landing-idle"]},
|
||||||
|
{"id": "fresh-skipped-edge", "lifetime": "fresh", "dialogue": "skipped", "input": "edge", "obligations": ["continuous", "dialogue-return", "bank-left", "bank-right", "landing-idle"]},
|
||||||
|
{"id": "fresh-skipped-ordinary", "lifetime": "fresh", "dialogue": "skipped", "input": "ordinary", "obligations": ["continuous", "dialogue-return", "bank-left", "bank-right", "landing-idle"]},
|
||||||
|
{"id": "retained-natural-edge", "lifetime": "retained", "dialogue": "natural", "input": "edge", "obligations": ["continuous", "dialogue-return", "bank-left", "bank-right", "landing-idle"]},
|
||||||
|
{"id": "retained-natural-ordinary", "lifetime": "retained", "dialogue": "natural", "input": "ordinary", "obligations": ["continuous", "dialogue-return", "bank-left", "bank-right", "landing-idle"]},
|
||||||
|
{"id": "retained-skipped-edge", "lifetime": "retained", "dialogue": "skipped", "input": "edge", "obligations": ["continuous", "dialogue-return", "bank-left", "bank-right", "landing-idle"]},
|
||||||
|
{"id": "retained-skipped-ordinary", "lifetime": "retained", "dialogue": "skipped", "input": "ordinary", "obligations": ["continuous", "dialogue-return", "bank-left", "bank-right", "landing-idle"]}
|
||||||
|
],
|
||||||
|
"lifetime_procedures": {
|
||||||
|
"fresh": {
|
||||||
|
"setup": "Allocate an independently verified generated copy and new launch/session ID for each run. Record copy_pre identity. For the port, identify the actual package and its existing startup path; do not reset gameplay state to fit the procedure.",
|
||||||
|
"actions": "Record startup and ordinary New Game/TSK lab entry visibly. A direct fresh-scene fixture is a separate observation, not a replacement for New Game.",
|
||||||
|
"end_condition": "The requested continuous or focused procedure ends in this independently identified launch. Never reuse a fresh-session ID for another required run."
|
||||||
|
},
|
||||||
|
"retained": {
|
||||||
|
"setup": "Begin recording in one verified generated copy/launch. Visibly establish lab departure to VR04 and return as prerequisite setup before the retained test. Hash the prerequisite recording and retained copy state; preserve the original copy_pre identity.",
|
||||||
|
"actions": "Keep departure_session_id and return_session_id equal to the same session_id/lifetime_id. Record prerequisite_departure and prerequisite_return markers on the hashed prerequisite_artifact before the tested interval. Bind copy_pre_sha256 and retained_copy_sha256 to actual identified records. Continue the required scenario without terminating, restaging, loading unrelated state or resetting clocks.",
|
||||||
|
"end_condition": "Evidence includes prerequisite setup, retained copy identity and the actual departure/return in the same process lifetime. A second fresh launch cannot count as retained."
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"dialogue_procedures": {
|
||||||
|
"natural": "Approach Carl through normal play, let dialogue and its return complete naturally, then observe the first resumed input and neutral idle. Do not press skip.",
|
||||||
|
"skipped": "Approach Carl through normal play, visibly perform the supported skip input, record the observed skip and dialogue completion boundary, then observe resumed input and neutral idle. Record the actual chosen key; do not infer original sampling."
|
||||||
|
},
|
||||||
|
"input_procedures": {
|
||||||
|
"ordinary": "Use normal physical play inputs. Release movement at dialogue/control return, observe the first neutral input, perform separately visible left and right banked jumps, land and remain idle. Record actual input description and audible/visual output.",
|
||||||
|
"edge": "Deliberately hold movement through the dialogue boundary, observe resumed held input, then release and record first neutral input. Perform left and right banked jumps, land and remain idle. Hold a declared direction through RETURN and record cleanup/resumption. Preserve legitimate landing bank."
|
||||||
|
},
|
||||||
|
"dialogue_events": {"natural": ["dialogue_end"], "skipped": ["dialogue_skip", "dialogue_end"]},
|
||||||
|
"input_events": {"ordinary": [], "edge": ["resumed_held_input", "held_dialogue", "held_return"]},
|
||||||
|
"obligations": {
|
||||||
|
"continuous": {
|
||||||
|
"route": ["lab", "VR04", "lab", "outside"],
|
||||||
|
"setup": "Apply the cell's lifetime, dialogue and input procedures. Start one uninterrupted video/audio recording before startup/control or retained prerequisite setup. Identify package, copy, launcher and platform.",
|
||||||
|
"actions": "In the lab, complete Carl dialogue according to policy, observe resumed/neutral input, perform left/right banked jumps, land and idle. Depart normally to VR04, use its existing supported gadget, invoke ordinary RETURN, observe gadget cleanup and lab return, then take the ordinary lab exit to outside. Keep one process lifetime and one continuous video for the route. No debug warp, scene snapshots or injected smoke input substitutes.",
|
||||||
|
"end_condition": "Jimmy visibly arrives outside after lab -> VR04 -> lab in the same run; audio/input events and cleanup are reviewable, with missing/failed transitions reported honestly.",
|
||||||
|
"required_events": ["startup", "control", "dialogue_start", "dialogue_end", "first_neutral_input", "jump_left", "bank_left", "landing_left", "jump_right", "bank_right", "landing", "idle", "lab_departure", "vr04_entry", "vr04_use", "return_cleanup", "lab_return", "lab_exit", "outside_arrival"],
|
||||||
|
"required_artifact_roles": ["video", "audio", "input_events", "prerequisite"]
|
||||||
|
},
|
||||||
|
"dialogue-return": {
|
||||||
|
"setup": "Apply the cell's visible lifetime prerequisite, then approach Carl with the chosen natural/skipped and ordinary/held-input policy. Record setup before the focused clip.",
|
||||||
|
"actions": "Observe dialogue activation, actual natural completion or skip, first resumed held input when applicable, release to first neutral input and sustained idle. Record method/uncertainty at each observed boundary.",
|
||||||
|
"end_condition": "Control has resumed and neutral idle is visibly recorded, without inserting any leveling reset.",
|
||||||
|
"required_events": ["dialogue_start", "dialogue_end", "first_neutral_input", "idle"],
|
||||||
|
"required_artifact_roles": ["video", "audio", "input_events", "prerequisite"]
|
||||||
|
},
|
||||||
|
"bank-left": {
|
||||||
|
"setup": "Apply the cell lifetime and record the supported normal standing/moving setup. Preserve the actual selected camera/control state.",
|
||||||
|
"actions": "Use ordinary physical jump and Left/A to visibly bank left, release as prescribed, land and observe the resulting pose. Record exact physical keys and actual elapsed/media markers.",
|
||||||
|
"end_condition": "The left bank and landing are both visible; orientation is observed rather than forced upright.",
|
||||||
|
"required_events": ["jump_left", "bank_left", "landing"],
|
||||||
|
"required_artifact_roles": ["video", "audio", "input_events", "prerequisite"]
|
||||||
|
},
|
||||||
|
"bank-right": {
|
||||||
|
"setup": "Apply the same cell lifetime independently and record the supported normal standing/moving setup.",
|
||||||
|
"actions": "Use ordinary physical jump and Right/D to visibly bank right, release as prescribed, land and observe the resulting pose. Do not mirror or relabel the left recording.",
|
||||||
|
"end_condition": "The right bank and landing are independently visible and audible.",
|
||||||
|
"required_events": ["jump_right", "bank_right", "landing"],
|
||||||
|
"required_artifact_roles": ["video", "audio", "input_events", "prerequisite"]
|
||||||
|
},
|
||||||
|
"landing-idle": {
|
||||||
|
"setup": "Apply the cell lifetime. Record a real jump/landing setup with support visible; retain the actual body and camera state.",
|
||||||
|
"actions": "Observe landing, release movement and record sustained idle at actual speed. Keep any legitimate landing bank and record discrepancies rather than tuning them away.",
|
||||||
|
"end_condition": "Landing and a reviewable idle interval are captured; no universal duration/angle/pixel/audio tolerance is inferred.",
|
||||||
|
"required_events": ["landing", "idle"],
|
||||||
|
"required_artifact_roles": ["video", "audio", "input_events", "prerequisite"]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"event_contract": {
|
||||||
|
"fields": ["name", "artifact", "media_seconds", "elapsed_seconds", "method", "uncertainty_seconds"],
|
||||||
|
"original_method": ["manual", "procedural"],
|
||||||
|
"simulation_ticks": "separate_port_only",
|
||||||
|
"clocks": "Finite monotonic elapsed seconds from one identified clock_id; actual media seconds on hashed raw recordings. Preserve clock offsets and uncertainty. Do not reset or normalize clocks at scene transitions.",
|
||||||
|
"continuity": "Continuous route events reference one video artifact in chronological order. Independent scene snapshots cannot satisfy this obligation.",
|
||||||
|
"derivatives": "Preserve raw recordings; each preview/still links its hashed source, actual tool/version/command and any crop/timing changes. Never silently retime.",
|
||||||
|
"tolerances": "No blanket timing, pixel, angle or audio threshold; later system-specific acceptance needs authoritative evidence."
|
||||||
|
},
|
||||||
|
"protected_observations": {
|
||||||
|
"tsk_retained_order": "Preserve implemented menu/background Jimmy-before-level-input successful TSK entry; docs/gameplay/main-menu-player-lifetime.md.",
|
||||||
|
"fresh_direct_scene_order": "Fresh direct-scene order remains a distinct observation; do not apply retained-story classification universally.",
|
||||||
|
"legitimate_landing_bank": "Observe and preserve legitimate landing bank; never substitute an unsupported leveling reset."
|
||||||
|
},
|
||||||
|
"acceptance": {
|
||||||
|
"structural_readiness": "--allow-open checks the complete protocol while reporting every missing case/obligation. It is not native/reference acceptance.",
|
||||||
|
"complete": "--require-complete requires all 8 cells x 5 obligations x 3 independently identified original/native sides, hashed artifacts, chronological markers, lifetime continuity and actual human audiovisual review. Failed/skipped/aborted/missing captures remain open. D-13 availability, launcher exit zero, fixtures, component probes, Wine and cross-publish do not fill any slot."
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,5 +1,23 @@
|
|||||||
# Progress — 2026-11-07
|
# Progress — 2026-11-07
|
||||||
|
|
||||||
|
## Phase 1 wave 1 — preserved sessions and scenarios
|
||||||
|
|
||||||
|
Full wave1 `scripts/test.sh` exits0:403 Python checks plus2 HUD checks,
|
||||||
|
all managed projects and36 rendering checks pass with zero Vulkan validation
|
||||||
|
errors; SDL dummy-device audio lifecycle and539 original hashes pass. NU1900
|
||||||
|
reports unavailable vulnerability metadata; no build error. Log stays local at
|
||||||
|
`artifacts/fidelity/wave1-test.log`. This is baseline regression evidence, not
|
||||||
|
new whole-original/native Windows comparison.
|
||||||
|
|
||||||
|
Plan01-01 implements bounded fresh-copy staging, hashed receipt import/validation
|
||||||
|
and eight dialogue/lifetime/input cells covering continuous and focused route
|
||||||
|
observations. Primary repeats51 passing Python tests;539 originals match. Exact
|
||||||
|
commits and scoped TDD receipts are in
|
||||||
|
`../.planning/phases/01-reproducible-fidelity-baseline/01-01-SUMMARY.md`.
|
||||||
|
All120 actual original-DxWnd/native Linux/native Windows obligations remain open.
|
||||||
|
No gameplay, build/package or new platform execution is claimed. Next: local
|
||||||
|
viewer, full-game ledger and passive port observer (wave2).
|
||||||
|
|
||||||
## Phase 1 plans verified — 2026-11-12
|
## Phase 1 plans verified — 2026-11-12
|
||||||
|
|
||||||
Phase 1 now has seven executable plans (15 tasks/five waves), research, pattern
|
Phase 1 now has seven executable plans (15 tasks/five waves), research, pattern
|
||||||
|
|||||||
@@ -1,5 +1,15 @@
|
|||||||
# Tasks
|
# Tasks
|
||||||
|
|
||||||
|
## Phase 1 execution — wave 1
|
||||||
|
|
||||||
|
- [x] Plan01-01: preserved-session stage/identify/import/validate and required
|
||||||
|
eight-cell route contract;51 tooling tests and539 original hashes pass.
|
||||||
|
- [ ] Plans01-02/03/04: paired local viewer, capability ledger and passive observer.
|
||||||
|
- [ ] Plans01-05/06/07: prepared Windows bundle, Linux captures, then combined
|
||||||
|
original-DxWnd/native Windows session and actual acceptance audit.
|
||||||
|
- [ ] All120 runtime evidence obligations remain open; tooling tests alone do
|
||||||
|
not establish EVID-02/EVID-04 acceptance.
|
||||||
|
|
||||||
## GSD handoff — 2026-11-12
|
## GSD handoff — 2026-11-12
|
||||||
|
|
||||||
- [x] Initialize full remaining reconstruction scope, research,33 requirements
|
- [x] Initialize full remaining reconstruction scope, research,33 requirements
|
||||||
|
|||||||
@@ -0,0 +1,230 @@
|
|||||||
|
"""Scenario completeness uses temporary metadata fixtures, never real captures."""
|
||||||
|
import copy
|
||||||
|
import importlib
|
||||||
|
import itertools
|
||||||
|
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'))
|
||||||
|
api = importlib.import_module('fidelity_receipts')
|
||||||
|
PROTOCOL = ROOT / 'docs/evidence/scenarios.json'
|
||||||
|
|
||||||
|
|
||||||
|
class FidelityScenarios(unittest.TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
self.tmp = tempfile.TemporaryDirectory()
|
||||||
|
self.addCleanup(self.tmp.cleanup)
|
||||||
|
self.base = Path(self.tmp.name)
|
||||||
|
|
||||||
|
def protocol(self):
|
||||||
|
self.assertTrue(PROTOCOL.is_file(), 'eight-cell executable protocol must exist')
|
||||||
|
return json.loads(PROTOCOL.read_text())
|
||||||
|
|
||||||
|
def test_eight_explicit_cells(self):
|
||||||
|
p = self.protocol()
|
||||||
|
self.assertEqual(len(p['cells']), 8)
|
||||||
|
expected = set(itertools.product(('fresh', 'retained'), ('natural', 'skipped'), ('ordinary', 'edge')))
|
||||||
|
self.assertEqual({(c['lifetime'], c['dialogue'], c['input']) for c in p['cells']}, expected)
|
||||||
|
self.assertEqual(len({c['id'] for c in p['cells']}), 8)
|
||||||
|
|
||||||
|
def test_stable_ids_and_order(self):
|
||||||
|
p = self.protocol()
|
||||||
|
self.assertEqual([c['id'] for c in p['cells']], sorted(c['id'] for c in p['cells']))
|
||||||
|
for c in p['cells']:
|
||||||
|
self.assertEqual(c['id'], '-'.join((c['lifetime'], c['dialogue'], c['input'])))
|
||||||
|
api.validate_scenario_contract(p)
|
||||||
|
|
||||||
|
def test_every_cell_has_continuous_and_focused_obligations(self):
|
||||||
|
p = self.protocol()
|
||||||
|
for cell in p['cells']:
|
||||||
|
self.assertEqual(cell['obligations'], ['continuous', 'dialogue-return', 'bank-left', 'bank-right', 'landing-idle'])
|
||||||
|
self.assertEqual(p['obligations']['continuous']['route'], ['lab', 'VR04', 'lab', 'outside'])
|
||||||
|
for o in p['obligations'].values():
|
||||||
|
for field in ('setup', 'actions', 'end_condition', 'required_events', 'required_artifact_roles'):
|
||||||
|
self.assertTrue(o[field])
|
||||||
|
|
||||||
|
def test_missing_dimension_even_equal_count_rejected(self):
|
||||||
|
p = self.protocol()
|
||||||
|
p['cells'][-1] = copy.deepcopy(p['cells'][0])
|
||||||
|
with self.assertRaises(ValueError): api.validate_scenario_contract(p)
|
||||||
|
|
||||||
|
def test_natural_skipped_are_equal_obligations(self):
|
||||||
|
p = self.protocol()
|
||||||
|
for lifetime, inputs in itertools.product(('fresh', 'retained'), ('ordinary', 'edge')):
|
||||||
|
cells = [c for c in p['cells'] if c['lifetime'] == lifetime and c['input'] == inputs]
|
||||||
|
self.assertEqual(cells[0]['obligations'], cells[1]['obligations'])
|
||||||
|
self.assertIn('dialogue_end', p['dialogue_events']['natural'])
|
||||||
|
self.assertIn('dialogue_skip', p['dialogue_events']['skipped'])
|
||||||
|
|
||||||
|
def test_edge_procedure_includes_held_input_both_banks_landing_idle(self):
|
||||||
|
p = self.protocol()
|
||||||
|
self.assertEqual(set(p['input_events']['edge']), {'resumed_held_input', 'held_dialogue', 'held_return'})
|
||||||
|
self.assertIn('first_neutral_input', p['obligations']['dialogue-return']['required_events'])
|
||||||
|
self.assertIn('landing', p['obligations']['landing-idle']['required_events'])
|
||||||
|
self.assertIn('idle', p['obligations']['landing-idle']['required_events'])
|
||||||
|
|
||||||
|
def test_empty_receipts_structural_readiness_is_not_acceptance(self):
|
||||||
|
result = api.audit_scenarios(self.protocol(), [])
|
||||||
|
self.assertTrue(result['structurally_ready'])
|
||||||
|
self.assertFalse(result['complete'])
|
||||||
|
self.assertEqual(result['required'], 120)
|
||||||
|
self.assertEqual(result['accepted'], 0)
|
||||||
|
self.assertEqual(len(result['missing_case_ids']), 8)
|
||||||
|
|
||||||
|
def receipt(self, cell='retained-skipped-edge', obligation='continuous', kind='native_port', os_name='linux'):
|
||||||
|
p = self.protocol()
|
||||||
|
c = next(c for c in p['cells'] if c['id'] == cell)
|
||||||
|
d = self.base / (cell + '-' + obligation + '-' + kind + '-' + os_name)
|
||||||
|
d.mkdir(exist_ok=True)
|
||||||
|
artifacts = []
|
||||||
|
for name, role in [('video.txt', 'video'), ('audio.txt', 'audio'),
|
||||||
|
('events.txt', 'input_events'), ('setup.txt', 'prerequisite')]:
|
||||||
|
(d / name).write_text('temporary metadata fixture; not native media')
|
||||||
|
artifacts.append(dict(api.identify_file(d / name), path=name, role=role,
|
||||||
|
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')
|
||||||
|
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,
|
||||||
|
elapsed_seconds=index + 2, method='manual', uncertainty_seconds=.1)
|
||||||
|
for index, name in enumerate(required)]
|
||||||
|
if c['lifetime'] == 'retained':
|
||||||
|
events = [dict(name=name, artifact='setup.txt', media_seconds=index,
|
||||||
|
elapsed_seconds=index, method='manual', uncertainty_seconds=.1)
|
||||||
|
for index, name in enumerate(('prerequisite_departure', 'prerequisite_return'))] + events
|
||||||
|
value = {'schema_version': 1, 'receipt_id': d.name, 'session_id': d.name,
|
||||||
|
'case_id': cell, 'obligation_id': obligation, 'evidence_kind': kind,
|
||||||
|
'status': 'reviewed', 'historical': False, 'scope': obligation,
|
||||||
|
'platform': {'os': os_name, 'execution': {'native_port': 'native',
|
||||||
|
'original_dxwnd': 'dxwnd'}.get(kind, kind), 'version': 'unit-fixture',
|
||||||
|
'gpu': 'fixture', 'driver': 'fixture', 'vulkan': 'fixture', 'sdl': 'fixture'},
|
||||||
|
'identity': identity, 'invocation': {'argv': ['fixture'], 'cwd': '.'},
|
||||||
|
'clocks': {'wall_start': '2026-01-01T00:00:00Z', 'wall_end': '2026-01-01T00:01:40Z',
|
||||||
|
'monotonic_start': 0, 'monotonic_end': 100, 'clock_id': d.name},
|
||||||
|
'artifacts': artifacts, 'derivatives': [], 'events': events,
|
||||||
|
'limitations': ['Unit fixture, not imported as runtime proof'], 'missing_evidence': [],
|
||||||
|
'acceptance': {'state': 'accepted', 'remaining': []},
|
||||||
|
'review': dict(visible=True, audible=True, ordinary_input=True, human_reviewed=True),
|
||||||
|
'wrapper_settings': {'description': 'unit fixture only'},
|
||||||
|
'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']}}
|
||||||
|
return value, d
|
||||||
|
|
||||||
|
def test_identified_metadata_cell_can_cover_one_obligation(self):
|
||||||
|
value, root = self.receipt()
|
||||||
|
result = api.audit_scenarios(self.protocol(), [(value, root)])
|
||||||
|
self.assertEqual(result['accepted'], 1)
|
||||||
|
self.assertFalse(result['complete'])
|
||||||
|
|
||||||
|
def test_disconnected_route_snapshots_fail(self):
|
||||||
|
value, root = self.receipt()
|
||||||
|
value['events'][-1]['artifact'] = 'audio.txt'
|
||||||
|
result = api.audit_scenarios(self.protocol(), [(value, root)])
|
||||||
|
self.assertEqual(result['accepted'], 0)
|
||||||
|
self.assertTrue(any('continuous' in error for error in result['invalid']))
|
||||||
|
|
||||||
|
def test_retained_departure_return_must_share_session(self):
|
||||||
|
value, root = self.receipt()
|
||||||
|
value['continuity']['return_session_id'] = 'different-launch'
|
||||||
|
self.assertEqual(api.audit_scenarios(self.protocol(), [(value, root)])['accepted'], 0)
|
||||||
|
|
||||||
|
def test_retained_requires_prerequisite_and_copy_state(self):
|
||||||
|
value, root = self.receipt()
|
||||||
|
del value['continuity']['retained_copy_sha256']
|
||||||
|
self.assertEqual(api.audit_scenarios(self.protocol(), [(value, root)])['accepted'], 0)
|
||||||
|
|
||||||
|
def test_reset_timestamps_fail(self):
|
||||||
|
value, root = self.receipt()
|
||||||
|
value['events'][-1]['elapsed_seconds'] = 0
|
||||||
|
self.assertEqual(api.audit_scenarios(self.protocol(), [(value, root)])['accepted'], 0)
|
||||||
|
|
||||||
|
def test_fresh_sessions_are_independent(self):
|
||||||
|
a, ar = self.receipt('fresh-natural-ordinary')
|
||||||
|
b, br = self.receipt('fresh-natural-edge')
|
||||||
|
b['session_id'] = a['session_id']
|
||||||
|
b['continuity'] = copy.deepcopy(a['continuity'])
|
||||||
|
result = api.audit_scenarios(self.protocol(), [(a, ar), (b, br)])
|
||||||
|
self.assertLess(result['accepted'], 2)
|
||||||
|
self.assertTrue(any('fresh' in error for error in result['invalid']))
|
||||||
|
|
||||||
|
def test_synthetic_wine_component_cannot_substitute_native(self):
|
||||||
|
for kind in ('synthetic', 'wine', 'component', 'cross_publish'):
|
||||||
|
value, root = self.receipt(kind=kind)
|
||||||
|
value['acceptance'] = {'state': 'open', 'remaining': ['not native']}
|
||||||
|
self.assertEqual(api.audit_scenarios(self.protocol(), [(value, root)])['accepted'], 0)
|
||||||
|
|
||||||
|
def test_skipped_aborted_failed_missing_remain_open(self):
|
||||||
|
for status in ('skipped', 'aborted', 'failed', 'missing'):
|
||||||
|
value, root = self.receipt()
|
||||||
|
value['status'] = status
|
||||||
|
value['acceptance'] = {'state': 'open', 'remaining': [status]}
|
||||||
|
self.assertEqual(api.audit_scenarios(self.protocol(), [(value, root)])['accepted'], 0)
|
||||||
|
|
||||||
|
def test_missing_event_and_media_out_of_range_rejected(self):
|
||||||
|
value, root = self.receipt()
|
||||||
|
value['events'].pop()
|
||||||
|
self.assertEqual(api.audit_scenarios(self.protocol(), [(value, root)])['accepted'], 0)
|
||||||
|
value, root = self.receipt()
|
||||||
|
value['events'][-1]['media_seconds'] = 101
|
||||||
|
self.assertEqual(api.audit_scenarios(self.protocol(), [(value, root)])['accepted'], 0)
|
||||||
|
|
||||||
|
def test_cli_readiness_and_strict_verdicts_differ(self):
|
||||||
|
p = self.protocol()
|
||||||
|
path = self.base / 'scenarios.json'
|
||||||
|
path.write_text(json.dumps(p))
|
||||||
|
index = self.base / 'receipts'
|
||||||
|
index.mkdir()
|
||||||
|
args = [sys.executable, str(ROOT / 'tools/recon/fidelity.py'), 'validate',
|
||||||
|
'--scenarios', str(path), '--receipts', str(index)]
|
||||||
|
ready = subprocess.run([*args, '--allow-open'], capture_output=True, text=True, timeout=15)
|
||||||
|
strict = subprocess.run([*args, '--require-complete'], capture_output=True, text=True, timeout=15)
|
||||||
|
self.assertEqual(ready.returncode, 0, ready.stderr)
|
||||||
|
self.assertNotEqual(strict.returncode, 0)
|
||||||
|
self.assertIn('0/120', ready.stdout)
|
||||||
|
self.assertIn('OPEN', strict.stdout)
|
||||||
|
self.assertIn('fresh-natural-edge', strict.stdout)
|
||||||
|
|
||||||
|
def test_protected_observations_and_clock_semantics_recorded(self):
|
||||||
|
p = self.protocol()
|
||||||
|
self.assertEqual(set(p['protected_observations']), {'tsk_retained_order', 'fresh_direct_scene_order', 'legitimate_landing_bank'})
|
||||||
|
self.assertEqual(p['event_contract']['simulation_ticks'], 'separate_port_only')
|
||||||
|
self.assertEqual(p['event_contract']['original_method'], ['manual', 'procedural'])
|
||||||
|
|
||||||
|
def test_all_120_metadata_slots_are_counted_independently(self):
|
||||||
|
p = self.protocol()
|
||||||
|
records = [self.receipt(c['id'], o, side['evidence_kind'], side['os'])
|
||||||
|
for c in p['cells'] for o in c['obligations'] for side in p['required_sides']]
|
||||||
|
result = api.audit_scenarios(p, records)
|
||||||
|
self.assertEqual(result['invalid'], [])
|
||||||
|
self.assertEqual(result['accepted'], 120)
|
||||||
|
self.assertTrue(result['complete'])
|
||||||
|
|
||||||
|
def test_duplicate_slot_cannot_replace_another_case(self):
|
||||||
|
value, root = self.receipt()
|
||||||
|
result = api.audit_scenarios(self.protocol(), [(value, root), (value, root)])
|
||||||
|
self.assertEqual(result['accepted'], 0)
|
||||||
|
self.assertTrue(result['invalid'])
|
||||||
|
|
||||||
|
def test_retained_prerequisite_must_have_observed_departure_and_return(self):
|
||||||
|
value, root = self.receipt()
|
||||||
|
value['events'] = [e for e in value['events'] if e['name'] != 'prerequisite_departure']
|
||||||
|
self.assertEqual(api.audit_scenarios(self.protocol(), [(value, root)])['accepted'], 0)
|
||||||
|
|
||||||
|
def test_retained_copy_hash_must_bind_identified_bytes(self):
|
||||||
|
value, root = self.receipt()
|
||||||
|
value['continuity']['retained_copy_sha256'] = 'f' * 64
|
||||||
|
self.assertEqual(api.audit_scenarios(self.protocol(), [(value, root)])['accepted'], 0)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
unittest.main()
|
||||||
@@ -0,0 +1,295 @@
|
|||||||
|
"""Tiny local fixtures test evidence plumbing, never original/native gameplay."""
|
||||||
|
import concurrent.futures
|
||||||
|
import hashlib
|
||||||
|
import importlib
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
import unittest
|
||||||
|
import wave
|
||||||
|
from unittest import mock
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[1]
|
||||||
|
sys.path.insert(0, str(ROOT / 'tools/recon'))
|
||||||
|
try:
|
||||||
|
receipts = importlib.import_module('fidelity_receipts')
|
||||||
|
except ModuleNotFoundError:
|
||||||
|
receipts = None
|
||||||
|
|
||||||
|
|
||||||
|
class FidelitySessions(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 / 'game.exe').write_bytes(b'fixture original, not executable')
|
||||||
|
self.files = [{'path': 'game.exe', 'size': 32,
|
||||||
|
'sha256': hashlib.sha256((self.original / 'game.exe').read_bytes()).hexdigest(),
|
||||||
|
'header': (self.original / 'game.exe').read_bytes()[:16].hex()}]
|
||||||
|
self.files[0]['size'] = (self.original / 'game.exe').stat().st_size
|
||||||
|
self.manifest = self.base / 'manifest.json'
|
||||||
|
self.manifest.write_text(json.dumps({'files': self.files}))
|
||||||
|
self.output = self.base / 'sessions'
|
||||||
|
|
||||||
|
def api(self):
|
||||||
|
self.assertIsNotNone(receipts, 'preserved-session receipt API must exist')
|
||||||
|
return receipts
|
||||||
|
|
||||||
|
def stage(self, session='test-session', output=None):
|
||||||
|
return self.api().stage_original(self.original, self.manifest,
|
||||||
|
output or self.output, session)
|
||||||
|
|
||||||
|
def cli(self, *args):
|
||||||
|
return subprocess.run([sys.executable, str(ROOT / 'tools/recon/fidelity.py'),
|
||||||
|
*map(str, args)], capture_output=True, text=True, timeout=15)
|
||||||
|
|
||||||
|
def fixture_receipt(self, receipt_id='test-pair'):
|
||||||
|
api = self.api()
|
||||||
|
bundle = self.base / 'synthetic-pair'
|
||||||
|
bundle.mkdir(exist_ok=True)
|
||||||
|
for name in ('original.wav', 'port.wav'):
|
||||||
|
with wave.open(str(bundle / name), 'wb') as audio:
|
||||||
|
audio.setparams((1, 2, 8000, 0, 'NONE', 'not compressed'))
|
||||||
|
audio.writeframes(b'\0\0' * 800)
|
||||||
|
artifacts = [dict(api.identify_file(bundle / name), role=role, path=name,
|
||||||
|
synthetic=True) for name, role in
|
||||||
|
[('original.wav', 'original_audio'), ('port.wav', 'port_audio')]]
|
||||||
|
value = {'schema_version': 1, 'receipt_id': receipt_id,
|
||||||
|
'session_id': 'test-session', 'case_id': 'test-only',
|
||||||
|
'evidence_kind': 'synthetic', 'status': 'captured',
|
||||||
|
'platform': {'os': 'test', 'execution': 'synthetic'},
|
||||||
|
'scope': 'tooling-test', 'historical': False,
|
||||||
|
'identity': {}, 'invocation': {'argv': ['fixture'], 'cwd': '.'},
|
||||||
|
'clocks': {'wall_start': '2026-01-01T00:00:00Z',
|
||||||
|
'wall_end': '2026-01-01T00:00:01Z',
|
||||||
|
'monotonic_start': 0, 'monotonic_end': 1},
|
||||||
|
'artifacts': artifacts, 'derivatives': [], 'events': [],
|
||||||
|
'limitations': ['Synthetic plumbing only'], 'missing_evidence': [],
|
||||||
|
'acceptance': {'state': 'open', 'remaining': ['Real captures required']}}
|
||||||
|
path = bundle / 'receipt.json'
|
||||||
|
path.write_text(json.dumps(value))
|
||||||
|
return bundle, path, value
|
||||||
|
|
||||||
|
def test_cli_round_trip(self):
|
||||||
|
staged = self.cli('stage', '--source', self.original, '--manifest', self.manifest,
|
||||||
|
'--output', self.output, '--session-id', 'test-session')
|
||||||
|
self.assertEqual(staged.returncode, 0, staged.stderr)
|
||||||
|
session = self.output / 'test-session'
|
||||||
|
identified = self.cli('identify', session / 'game')
|
||||||
|
self.assertEqual(identified.returncode, 0, identified.stderr)
|
||||||
|
self.assertEqual(json.loads(identified.stdout)['files'], self.files)
|
||||||
|
bundle, path, _ = self.fixture_receipt()
|
||||||
|
imported = self.cli('import', path, '--root', bundle, '--output', self.base / 'test-index')
|
||||||
|
self.assertEqual(imported.returncode, 0, imported.stderr)
|
||||||
|
target = self.base / 'test-index/test-pair/receipt.json'
|
||||||
|
result = self.cli('validate', target, '--root', target.parent, '--allow-open')
|
||||||
|
self.assertEqual(result.returncode, 0, result.stderr)
|
||||||
|
self.assertIn('synthetic', result.stdout)
|
||||||
|
self.assertIn('OPEN', result.stdout)
|
||||||
|
self.assertTrue((target.parent / 'receipt.sha256').is_file())
|
||||||
|
strict = self.cli('validate', target, '--root', target.parent, '--require-complete')
|
||||||
|
self.assertNotEqual(strict.returncode, 0)
|
||||||
|
self.assertEqual((self.original / 'game.exe').read_bytes(), b'fixture original, not executable')
|
||||||
|
|
||||||
|
def test_single_file_pristine_copy(self):
|
||||||
|
result = self.stage()
|
||||||
|
self.assertEqual(result['source_pre']['files'], self.files)
|
||||||
|
self.assertEqual(result['copy_pre']['files'], self.files)
|
||||||
|
self.assertNotEqual(result['source_root'], result['copy_root'])
|
||||||
|
self.assertEqual(result['status'], 'staged')
|
||||||
|
|
||||||
|
def test_changed_original(self):
|
||||||
|
(self.original / 'game.exe').write_bytes(b'changed')
|
||||||
|
with self.assertRaises(ValueError): self.stage()
|
||||||
|
self.assertFalse(self.output.exists())
|
||||||
|
|
||||||
|
def test_missing_original(self):
|
||||||
|
(self.original / 'game.exe').unlink()
|
||||||
|
with self.assertRaises(ValueError): self.stage()
|
||||||
|
|
||||||
|
def test_added_original(self):
|
||||||
|
(self.original / 'extra').write_bytes(b'added')
|
||||||
|
with self.assertRaises(ValueError): self.stage()
|
||||||
|
|
||||||
|
def test_empty_and_missing_inventory(self):
|
||||||
|
self.manifest.write_text('{"files": []}')
|
||||||
|
with self.assertRaises(ValueError): self.stage()
|
||||||
|
self.manifest.unlink()
|
||||||
|
with self.assertRaises(ValueError): self.stage()
|
||||||
|
|
||||||
|
def test_equal_and_both_nested_outputs_rejected_before_write(self):
|
||||||
|
for output in (self.original, self.original / 'new', self.base):
|
||||||
|
with self.assertRaises(ValueError): self.stage(output=output)
|
||||||
|
self.assertEqual(list(self.original.iterdir()), [self.original / 'game.exe'])
|
||||||
|
|
||||||
|
def test_sibling_prefix_is_distinct(self):
|
||||||
|
result = self.stage(output=self.base / 'Original-copy')
|
||||||
|
self.assertEqual(result['status'], 'staged')
|
||||||
|
|
||||||
|
def test_symlink_output_alias(self):
|
||||||
|
alias = self.base / 'alias'
|
||||||
|
alias.symlink_to(self.original, target_is_directory=True)
|
||||||
|
with self.assertRaises(ValueError): self.stage(output=alias)
|
||||||
|
|
||||||
|
def test_symlink_source_member_rejected(self):
|
||||||
|
(self.original / 'external').symlink_to(self.manifest)
|
||||||
|
with self.assertRaises(ValueError): self.stage()
|
||||||
|
|
||||||
|
def test_windows_case_alias_and_drive_reference_rejected(self):
|
||||||
|
with self.assertRaises(ValueError): self.stage(output=self.base / 'original')
|
||||||
|
api = self.api()
|
||||||
|
for value in ('C:/secret', 'C:secret', '\\\\server\\share', '../secret',
|
||||||
|
'/secret', 'nested\\..\\secret', 'https://example.org/a'):
|
||||||
|
with self.assertRaises(ValueError): api.contained_path(self.base, value)
|
||||||
|
|
||||||
|
def test_case_collisions_fail_and_manifest_order_is_canonical(self):
|
||||||
|
api = self.api()
|
||||||
|
(self.original / 'GAME.EXE').write_bytes(b'collision')
|
||||||
|
with self.assertRaises(ValueError): api.identify_tree(self.original)
|
||||||
|
(self.original / 'GAME.EXE').unlink()
|
||||||
|
(self.original / 'A').write_bytes(b'a')
|
||||||
|
(self.original / 'z').write_bytes(b'z')
|
||||||
|
paths = [f['path'] for f in api.identify_tree(self.original)['files']]
|
||||||
|
self.assertEqual(paths, ['A', 'game.exe', 'z'])
|
||||||
|
|
||||||
|
def test_shell_characters_are_inert(self):
|
||||||
|
result = self.stage(output=self.base / 'copy;$(touch SHOULD_NOT_EXIST)')
|
||||||
|
self.assertEqual(result['status'], 'staged')
|
||||||
|
self.assertFalse((ROOT / 'SHOULD_NOT_EXIST').exists())
|
||||||
|
|
||||||
|
def test_reuse_is_rejected(self):
|
||||||
|
self.stage()
|
||||||
|
with self.assertRaises(ValueError): self.stage()
|
||||||
|
|
||||||
|
def test_concurrent_allocation_has_one_winner(self):
|
||||||
|
self.api()
|
||||||
|
def attempt(_):
|
||||||
|
try: self.stage(); return True
|
||||||
|
except ValueError: return False
|
||||||
|
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool:
|
||||||
|
self.assertEqual(sorted(pool.map(attempt, range(2))), [False, True])
|
||||||
|
|
||||||
|
def test_interrupted_stage_has_diagnostic_without_completed_session(self):
|
||||||
|
api = self.api()
|
||||||
|
with mock.patch.object(api.shutil, 'copyfile', side_effect=KeyboardInterrupt):
|
||||||
|
with self.assertRaises(KeyboardInterrupt): self.stage()
|
||||||
|
self.assertFalse((self.output / 'test-session/session.json').exists())
|
||||||
|
diagnostics = list(self.output.glob('*/incomplete.json'))
|
||||||
|
self.assertEqual(len(diagnostics), 1)
|
||||||
|
self.assertEqual(json.loads(diagnostics[0].read_text())['status'], 'incomplete')
|
||||||
|
|
||||||
|
def test_postrun_copy_mutations_separate_from_source(self):
|
||||||
|
api = self.api()
|
||||||
|
self.stage()
|
||||||
|
(self.output / 'test-session/game/save.dat').write_bytes(b'normal runtime write')
|
||||||
|
result = api.postflight_session(self.output / 'test-session', self.original, self.manifest)
|
||||||
|
self.assertEqual(result['source_post']['files'], self.files)
|
||||||
|
self.assertEqual(result['copy_changes']['added'], ['save.dat'])
|
||||||
|
|
||||||
|
def test_tampered_artifact_rejected(self):
|
||||||
|
bundle, _, value = self.fixture_receipt()
|
||||||
|
(bundle / 'original.wav').write_text('tampered')
|
||||||
|
with self.assertRaises(ValueError): self.api().validate_receipt(value, bundle)
|
||||||
|
|
||||||
|
def test_duplicate_import_identical_only(self):
|
||||||
|
bundle, path, value = self.fixture_receipt()
|
||||||
|
out = self.base / 'test-index'
|
||||||
|
first = self.api().import_receipt(path, bundle, out)
|
||||||
|
second = self.api().import_receipt(path, bundle, out)
|
||||||
|
self.assertEqual(first['receipt_sha256'], second['receipt_sha256'])
|
||||||
|
value['limitations'].append('different content')
|
||||||
|
path.write_text(json.dumps(value))
|
||||||
|
with self.assertRaises(ValueError): self.api().import_receipt(path, bundle, out)
|
||||||
|
|
||||||
|
def test_interrupted_import_retains_incomplete_diagnostic(self):
|
||||||
|
bundle, path, _ = self.fixture_receipt()
|
||||||
|
api = self.api()
|
||||||
|
out = self.base / 'test-index'
|
||||||
|
with mock.patch.object(api.shutil, 'copyfile', side_effect=OSError('interrupted')):
|
||||||
|
with self.assertRaises(OSError): api.import_receipt(path, bundle, out)
|
||||||
|
self.assertFalse((out / 'test-pair/receipt.json').exists())
|
||||||
|
self.assertEqual(len(list(out.glob('*/incomplete.json'))), 1)
|
||||||
|
|
||||||
|
def test_native_acceptance_rejects_narrow_classifications(self):
|
||||||
|
bundle, _, value = self.fixture_receipt()
|
||||||
|
for kind in ('synthetic', 'component', 'wine', 'cross_publish', 'port_fixture'):
|
||||||
|
value['evidence_kind'] = kind
|
||||||
|
value['platform']['execution'] = kind
|
||||||
|
value['acceptance']['state'] = 'accepted'
|
||||||
|
with self.assertRaises(ValueError): self.api().validate_receipt(value, bundle)
|
||||||
|
|
||||||
|
def test_synthetic_relabel_as_native_rejected(self):
|
||||||
|
bundle, _, value = self.fixture_receipt()
|
||||||
|
value.update(evidence_kind='native_port', status='reviewed')
|
||||||
|
value['platform'] = {'os': 'windows', 'execution': 'native'}
|
||||||
|
with self.assertRaises(ValueError): self.api().validate_receipt(value, bundle)
|
||||||
|
|
||||||
|
def test_failed_and_incomplete_remain_open(self):
|
||||||
|
bundle, _, value = self.fixture_receipt()
|
||||||
|
for status in ('failed', 'incomplete'):
|
||||||
|
value['status'] = status
|
||||||
|
self.assertFalse(self.api().validate_receipt(value, bundle)['accepted'])
|
||||||
|
|
||||||
|
def test_relative_artifact_symlink_escape_rejected(self):
|
||||||
|
bundle, _, value = self.fixture_receipt()
|
||||||
|
(bundle / 'original.wav').unlink()
|
||||||
|
(bundle / 'original.wav').symlink_to(self.manifest)
|
||||||
|
with self.assertRaises(ValueError): self.api().validate_receipt(value, bundle)
|
||||||
|
|
||||||
|
def test_bad_schema_and_oversized_json_rejected_by_cli(self):
|
||||||
|
bundle, path, value = self.fixture_receipt()
|
||||||
|
value['schema_version'] = 99
|
||||||
|
path.write_text(json.dumps(value))
|
||||||
|
self.assertNotEqual(self.cli('validate', path, '--root', bundle).returncode, 0)
|
||||||
|
|
||||||
|
def test_historical_report_hashes_actual_bytes_and_retains_missing(self):
|
||||||
|
api = self.api()
|
||||||
|
report = self.base / 'report.md'
|
||||||
|
report.write_text('Historical Wine/component evidence; native Windows open')
|
||||||
|
result = api.identify_report(self.original, report, self.original / 'game.exe',
|
||||||
|
self.base / 'missing-resources')
|
||||||
|
self.assertTrue(result['historical'])
|
||||||
|
self.assertEqual(result['actual']['executable']['sha256'], self.files[0]['sha256'])
|
||||||
|
self.assertIn('Historical Wine/component', result['recorded_scope'])
|
||||||
|
self.assertTrue(any('resources absent' in s for s in result['missing_evidence']))
|
||||||
|
|
||||||
|
def test_import_rejects_case_aliased_directory_components(self):
|
||||||
|
bundle, _, value = self.fixture_receipt()
|
||||||
|
(bundle / 'Media').mkdir()
|
||||||
|
(bundle / 'media').mkdir()
|
||||||
|
(bundle / 'Media/a.wav').write_bytes(b'a')
|
||||||
|
(bundle / 'media/b.wav').write_bytes(b'b')
|
||||||
|
value['artifacts'] = [dict(self.api().identify_file(bundle / path), path=path,
|
||||||
|
role='test', synthetic=True)
|
||||||
|
for path in ('Media/a.wav', 'media/b.wav')]
|
||||||
|
with self.assertRaises(ValueError): self.api().validate_receipt(value, bundle)
|
||||||
|
|
||||||
|
def test_imported_receipt_metadata_tampering_fails_cli(self):
|
||||||
|
bundle, path, _ = self.fixture_receipt()
|
||||||
|
out = self.base / 'test-index'
|
||||||
|
result = self.api().import_receipt(path, bundle, out)
|
||||||
|
stored = Path(result['path'])
|
||||||
|
value = json.loads(stored.read_text())
|
||||||
|
value['limitations'].append('changed metadata')
|
||||||
|
stored.write_text(json.dumps(value))
|
||||||
|
self.assertNotEqual(self.cli('validate', stored, '--root', stored.parent).returncode, 0)
|
||||||
|
|
||||||
|
def test_cli_hostile_output_and_tampering_exit_nonzero(self):
|
||||||
|
result = self.cli('stage', '--source', self.original, '--manifest', self.manifest,
|
||||||
|
'--output', self.original / 'illegal', '--session-id', 'new')
|
||||||
|
self.assertNotEqual(result.returncode, 0)
|
||||||
|
self.assertFalse((self.original / 'illegal').exists())
|
||||||
|
bundle, path, _ = self.fixture_receipt()
|
||||||
|
(bundle / 'port.wav').write_text('changed')
|
||||||
|
self.assertNotEqual(self.cli('import', path, '--root', bundle,
|
||||||
|
'--output', self.base / 'test-index').returncode, 0)
|
||||||
|
path.write_bytes(b' ' * (4 * 1024 * 1024 + 1))
|
||||||
|
self.assertNotEqual(self.cli('validate', path, '--root', bundle).returncode, 0)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
unittest.main()
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Local preserved-session and typed evidence CLI (never launches originals).
|
||||||
|
|
||||||
|
Examples: stage --source ../Original --manifest docs/original-manifest.json
|
||||||
|
--output artifacts/fidelity/sessions --session-id fresh-001; identify dist/linux-x64;
|
||||||
|
import BUNDLE/receipt.json --root BUNDLE --output artifacts/fidelity/receipts;
|
||||||
|
validate RECEIPT --root IMPORTED_DIR --allow-open. Synthetic imports require a
|
||||||
|
separate output directory whose name contains 'test'. All outputs remain local.
|
||||||
|
"""
|
||||||
|
import argparse
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
import sys
|
||||||
|
|
||||||
|
from fidelity_receipts import (identify_tree, identify_report, import_receipt,
|
||||||
|
read_json, read_receipt, stage_original, validate_receipt,
|
||||||
|
audit_receipt_tree, canonical_bytes, MAX_JSON_BYTES)
|
||||||
|
|
||||||
|
|
||||||
|
def main(argv=None):
|
||||||
|
parser = argparse.ArgumentParser(description=__doc__)
|
||||||
|
sub = parser.add_subparsers(dest='command', required=True)
|
||||||
|
stage = sub.add_parser('stage')
|
||||||
|
for flag in ('source', 'manifest', 'output'):
|
||||||
|
stage.add_argument('--' + flag, type=Path, required=True)
|
||||||
|
stage.add_argument('--session-id', required=True)
|
||||||
|
identify = sub.add_parser('identify')
|
||||||
|
identify.add_argument('path', type=Path)
|
||||||
|
for flag in ('report', 'executable', 'resources', 'launcher', 'project'):
|
||||||
|
identify.add_argument('--' + flag, type=Path)
|
||||||
|
imp = sub.add_parser('import')
|
||||||
|
imp.add_argument('receipt', type=Path)
|
||||||
|
imp.add_argument('--root', type=Path, required=True)
|
||||||
|
imp.add_argument('--output', type=Path, required=True)
|
||||||
|
validate = sub.add_parser('validate')
|
||||||
|
validate.add_argument('receipt', type=Path, nargs='?')
|
||||||
|
validate.add_argument('--root', type=Path)
|
||||||
|
validate.add_argument('--scenarios', type=Path)
|
||||||
|
validate.add_argument('--receipts', type=Path)
|
||||||
|
mode = validate.add_mutually_exclusive_group()
|
||||||
|
mode.add_argument('--allow-open', action='store_true')
|
||||||
|
mode.add_argument('--require-complete', action='store_true')
|
||||||
|
args = parser.parse_args(argv)
|
||||||
|
try:
|
||||||
|
if args.command == 'stage':
|
||||||
|
result = stage_original(args.source, args.manifest, args.output, args.session_id)
|
||||||
|
elif args.command == 'identify':
|
||||||
|
result = identify_report(args.path, args.report, args.executable, args.resources,
|
||||||
|
args.launcher, args.project) if any(
|
||||||
|
getattr(args, k) is not None for k in ('report', 'executable', 'resources', 'launcher', 'project')) else identify_tree(args.path)
|
||||||
|
elif args.command == 'import':
|
||||||
|
result = import_receipt(args.receipt, args.root, args.output)
|
||||||
|
else:
|
||||||
|
if args.scenarios:
|
||||||
|
if args.receipt or args.root or not args.receipts:
|
||||||
|
raise ValueError('Scenario validation requires --scenarios PATH --receipts ROOT')
|
||||||
|
result = audit_receipt_tree(read_json(args.scenarios), args.receipts)
|
||||||
|
print('Structural readiness: READY; acceptance: ' + ('COMPLETE' if result['complete'] else 'OPEN'))
|
||||||
|
print('Accepted obligations: {accepted}/{required}'.format(**result))
|
||||||
|
print('Missing case IDs: ' + ', '.join(result['missing_case_ids']))
|
||||||
|
for key in ('missing_obligations', 'open_receipts', 'invalid'):
|
||||||
|
for item in result[key]:
|
||||||
|
print(key + ': ' + item)
|
||||||
|
if result['invalid']:
|
||||||
|
return 2
|
||||||
|
return 1 if args.require_complete and not result['complete'] else 0
|
||||||
|
if args.receipt is None or args.root is None or args.receipts:
|
||||||
|
raise ValueError('Receipt validation requires RECEIPT --root ROOT')
|
||||||
|
result = validate_receipt(read_receipt(args.receipt), args.root)
|
||||||
|
print('Receipt {receipt_id}: {evidence_kind}, status={status}'.format(**result))
|
||||||
|
print('Acceptance: ' + ('ACCEPTED' if result['accepted'] else 'OPEN'))
|
||||||
|
for missing in result['missing_evidence']:
|
||||||
|
print('Missing/open: ' + str(missing))
|
||||||
|
return 1 if args.require_complete and not result['accepted'] else 0
|
||||||
|
data = canonical_bytes(result)
|
||||||
|
if len(data) > MAX_JSON_BYTES:
|
||||||
|
raise ValueError('Result JSON exceeds 4 MiB limit')
|
||||||
|
print(data.decode(), end='')
|
||||||
|
return 0
|
||||||
|
except (ValueError, OSError, KeyError, TypeError) as error:
|
||||||
|
print('Invalid fidelity evidence: ' + str(error), file=sys.stderr)
|
||||||
|
return 2
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
sys.exit(main())
|
||||||
@@ -0,0 +1,753 @@
|
|||||||
|
"""Version 1 local fidelity records; hashes establish identity, never gameplay parity.
|
||||||
|
|
||||||
|
Receipt state machine: incomplete -> failed or captured -> reviewed. Import is
|
||||||
|
append-only: an ID can only be reused for exactly the same input bytes. A review
|
||||||
|
or successful process exit alone cannot accept evidence. Missing/failed/aborted/
|
||||||
|
skipped observations remain open. Synthetic records belong in a test namespace.
|
||||||
|
All artifact/identity references are read-only POSIX paths relative to the bundle;
|
||||||
|
commands are recorded as arrays and are NEVER executed by this module.
|
||||||
|
|
||||||
|
Session state is separate: exclusive reservation -> incomplete temporary sibling
|
||||||
|
-> verified staged tree -> postflight snapshot. A retained run reuses that exact
|
||||||
|
session/copy lifetime; a fresh run requires a new allocation. Staged is not a
|
||||||
|
completed gameplay receipt. A killed writer leaves incomplete.json and its lock
|
||||||
|
for diagnosis; there is deliberately no automatic stale-lock stealing.
|
||||||
|
|
||||||
|
Public APIs return JSON-compatible dictionaries and raise ValueError on invalid
|
||||||
|
input. File-system failures propagate; failed publication preserves diagnostics.
|
||||||
|
Local cooperative writers are serialized; concurrent hostile filesystem mutation
|
||||||
|
is outside this offline workflow (revalidate after collection/before review).
|
||||||
|
"""
|
||||||
|
import hashlib
|
||||||
|
import itertools
|
||||||
|
import json
|
||||||
|
import math
|
||||||
|
import ntpath
|
||||||
|
import os
|
||||||
|
from pathlib import Path, PurePosixPath
|
||||||
|
import re
|
||||||
|
import shutil
|
||||||
|
import subprocess
|
||||||
|
import tempfile
|
||||||
|
import uuid
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
|
SCHEMA_VERSION = 1
|
||||||
|
MAX_JSON_BYTES = 4 * 1024 * 1024
|
||||||
|
MAX_FILES = 100000
|
||||||
|
KINDS = {'static', 'inferred', 'component', 'managed', 'port_fixture',
|
||||||
|
'native_port', 'original_dxwnd', 'wine', 'cross_publish', 'synthetic'}
|
||||||
|
STATUSES = {'incomplete', 'failed', 'captured', 'reviewed', 'skipped', 'aborted', 'missing'}
|
||||||
|
EXECUTION = {'native_port': 'native', 'original_dxwnd': 'dxwnd'}
|
||||||
|
RECEIPT_TRANSITIONS = {'incomplete': ['failed', 'captured', 'aborted', 'skipped'],
|
||||||
|
'captured': ['reviewed'], 'reviewed': [], 'failed': [],
|
||||||
|
'skipped': [], 'aborted': [], 'missing': []}
|
||||||
|
|
||||||
|
|
||||||
|
def utc_now():
|
||||||
|
return datetime.now(timezone.utc).isoformat()
|
||||||
|
|
||||||
|
|
||||||
|
def canonical_bytes(value):
|
||||||
|
return (json.dumps(value, sort_keys=True, indent=2, allow_nan=False) + '\n').encode()
|
||||||
|
|
||||||
|
|
||||||
|
def read_json(path):
|
||||||
|
try:
|
||||||
|
with Path(path).open('rb') as stream:
|
||||||
|
data = stream.read(MAX_JSON_BYTES + 1)
|
||||||
|
if len(data) > MAX_JSON_BYTES:
|
||||||
|
raise ValueError('JSON exceeds 4 MiB limit')
|
||||||
|
def unique(pairs):
|
||||||
|
result = {}
|
||||||
|
for key, value in pairs:
|
||||||
|
if key in result:
|
||||||
|
raise ValueError('Duplicate JSON key: ' + key)
|
||||||
|
result[key] = value
|
||||||
|
return result
|
||||||
|
value = json.loads(data, object_pairs_hook=unique,
|
||||||
|
parse_constant=lambda s: (_ for _ in ()).throw(ValueError('Nonfinite JSON: ' + s)))
|
||||||
|
if not isinstance(value, dict):
|
||||||
|
raise ValueError('JSON root must be an object')
|
||||||
|
return value
|
||||||
|
except (OSError, UnicodeError, RecursionError, json.JSONDecodeError) as error:
|
||||||
|
raise ValueError('Cannot read bounded JSON: ' + str(path)) from error
|
||||||
|
|
||||||
|
|
||||||
|
def identify_file(path):
|
||||||
|
path = Path(path)
|
||||||
|
if path.is_symlink() or not path.is_file():
|
||||||
|
raise ValueError('Expected a regular non-symlink file: ' + str(path))
|
||||||
|
digest = hashlib.sha256()
|
||||||
|
size = 0
|
||||||
|
header = b''
|
||||||
|
with path.open('rb') as stream:
|
||||||
|
while block := stream.read(1024 * 1024):
|
||||||
|
if not header:
|
||||||
|
header = block[:16]
|
||||||
|
size += len(block)
|
||||||
|
digest.update(block)
|
||||||
|
return {'size': size, 'sha256': digest.hexdigest(), 'header': header.hex()}
|
||||||
|
|
||||||
|
|
||||||
|
def relative_name(value):
|
||||||
|
if not isinstance(value, str) or not value or len(value) > 4096:
|
||||||
|
raise ValueError('Reference must be a bounded relative POSIX path')
|
||||||
|
parts = value.split('/')
|
||||||
|
if ('\\' in value or ':' in value or value.startswith('/') or
|
||||||
|
any(ord(c) < 32 or c in '<>"|?*' for c in value) or
|
||||||
|
any(p in ('', '.', '..') or p.endswith((' ', '.')) for p in parts)):
|
||||||
|
raise ValueError('Unsafe relative reference: ' + value)
|
||||||
|
for part in parts:
|
||||||
|
if part.split('.')[0].upper() in {'CON', 'PRN', 'AUX', 'NUL',
|
||||||
|
*('COM' + str(i) for i in range(1, 10)),
|
||||||
|
*('LPT' + str(i) for i in range(1, 10))}:
|
||||||
|
raise ValueError('Windows device alias in path')
|
||||||
|
return PurePosixPath(value)
|
||||||
|
|
||||||
|
|
||||||
|
def contained_path(root, value):
|
||||||
|
name = relative_name(value)
|
||||||
|
root = Path(root).resolve(strict=True)
|
||||||
|
target = root.joinpath(*name.parts)
|
||||||
|
cursor = root
|
||||||
|
for part in name.parts:
|
||||||
|
cursor = cursor / part
|
||||||
|
if cursor.is_symlink():
|
||||||
|
raise ValueError('Symlink in reference: ' + value)
|
||||||
|
if not target.resolve().is_relative_to(root):
|
||||||
|
raise ValueError('Reference escapes root')
|
||||||
|
return target
|
||||||
|
|
||||||
|
|
||||||
|
def separated_roots(source, output):
|
||||||
|
source, output = Path(source).resolve(), Path(output).resolve()
|
||||||
|
# Windows normalization also runs on Linux so transferred roots cannot gain
|
||||||
|
# a different preservation boundary on a case-insensitive receiving host.
|
||||||
|
a, b = [ntpath.normcase(str(p)).rstrip('\\/') for p in (source, output)]
|
||||||
|
if a == b or a.startswith(b + '\\') or b.startswith(a + '\\'):
|
||||||
|
raise ValueError('Source/output roots overlap or alias')
|
||||||
|
return source, output
|
||||||
|
|
||||||
|
|
||||||
|
def identify_tree(root):
|
||||||
|
root = Path(root).resolve(strict=True)
|
||||||
|
if not root.is_dir():
|
||||||
|
raise ValueError('Tree root must be a directory')
|
||||||
|
files, aliases, json_size = [], set(), 0
|
||||||
|
for directory, dirs, names in os.walk(root, followlinks=False):
|
||||||
|
for name in sorted(dirs + names):
|
||||||
|
path = Path(directory) / name
|
||||||
|
relative = path.relative_to(root).as_posix()
|
||||||
|
relative_name(relative)
|
||||||
|
key = relative.casefold()
|
||||||
|
if key in aliases:
|
||||||
|
raise ValueError('Case-colliding tree identity: ' + relative)
|
||||||
|
aliases.add(key)
|
||||||
|
if len(aliases) > MAX_FILES:
|
||||||
|
raise ValueError('Tree exceeds entry bound')
|
||||||
|
if path.is_symlink():
|
||||||
|
raise ValueError('Symlink tree member: ' + relative)
|
||||||
|
if path.is_file():
|
||||||
|
item = {'path': relative, **identify_file(path)}
|
||||||
|
json_size += len(canonical_bytes(item))
|
||||||
|
if json_size > MAX_JSON_BYTES:
|
||||||
|
raise ValueError('Tree identity exceeds JSON size bound')
|
||||||
|
files.append(item)
|
||||||
|
elif not path.is_dir():
|
||||||
|
raise ValueError('Non-regular tree member: ' + relative)
|
||||||
|
files.sort(key=lambda item: item['path'])
|
||||||
|
if not files:
|
||||||
|
raise ValueError('Empty inventories cannot establish identity')
|
||||||
|
return {'schema_version': 1, 'root': str(root), 'files': files,
|
||||||
|
'tree_sha256': hashlib.sha256(canonical_bytes(files)).hexdigest()}
|
||||||
|
|
||||||
|
|
||||||
|
def verify_inventory(root, manifest):
|
||||||
|
"""Use inventory.py's exact files-list comparison, including size/header/order.
|
||||||
|
|
||||||
|
Streaming enumeration emits its existing record format without re-generating
|
||||||
|
or writing the authoritative manifest; root labels are deliberately separate.
|
||||||
|
"""
|
||||||
|
baseline = read_json(manifest).get('files')
|
||||||
|
if not isinstance(baseline, list) or not baseline:
|
||||||
|
raise ValueError('Recorded inventory is empty or missing')
|
||||||
|
actual = identify_tree(root)
|
||||||
|
if actual['files'] != baseline:
|
||||||
|
raise ValueError('Original inventory differs from recorded baseline')
|
||||||
|
return actual
|
||||||
|
|
||||||
|
|
||||||
|
def _id(value):
|
||||||
|
if not isinstance(value, str) or not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9_.-]{0,95}', value):
|
||||||
|
raise ValueError('Invalid stable ID')
|
||||||
|
relative_name(value)
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
def _write_json(path, value):
|
||||||
|
data = canonical_bytes(value)
|
||||||
|
if len(data) > MAX_JSON_BYTES:
|
||||||
|
raise ValueError('Output JSON exceeds bound')
|
||||||
|
with Path(path).open('xb') as stream:
|
||||||
|
stream.write(data)
|
||||||
|
stream.flush()
|
||||||
|
os.fsync(stream.fileno())
|
||||||
|
|
||||||
|
|
||||||
|
def _reserve(output, record_id):
|
||||||
|
# The repository's authoritative installation remains protected even when
|
||||||
|
# an imported bundle comes from an unrelated directory.
|
||||||
|
original = Path(__file__).resolve().parents[3] / 'Original'
|
||||||
|
separated_roots(original, output)
|
||||||
|
output.mkdir(parents=True, exist_ok=True)
|
||||||
|
lock = output / ('.' + _id(record_id).casefold() + '.lock')
|
||||||
|
try:
|
||||||
|
lock.mkdir()
|
||||||
|
except FileExistsError as error:
|
||||||
|
raise ValueError('Session/import ID reserved; inspect existing diagnostics') from error
|
||||||
|
return lock
|
||||||
|
|
||||||
|
|
||||||
|
def _temporary(output, record_id, operation):
|
||||||
|
temporary = output / ('.' + record_id + '.incomplete-' + uuid.uuid4().hex)
|
||||||
|
temporary.mkdir()
|
||||||
|
_write_json(temporary / 'incomplete.json', {'schema_version': 1,
|
||||||
|
'status': 'incomplete', 'id': record_id, 'operation': operation,
|
||||||
|
'started_utc': utc_now(), 'diagnostic': 'Publication not completed; do not use as acceptance'})
|
||||||
|
return temporary
|
||||||
|
|
||||||
|
|
||||||
|
def stage_original(source, manifest, output, session_id):
|
||||||
|
source, output = separated_roots(source, output)
|
||||||
|
_id(session_id)
|
||||||
|
before = verify_inventory(source, manifest)
|
||||||
|
# No writes before all input roots/inventory checks succeed.
|
||||||
|
lock = _reserve(output, session_id)
|
||||||
|
temporary = _temporary(output, session_id, 'stage')
|
||||||
|
final = output / session_id
|
||||||
|
if final.exists():
|
||||||
|
raise ValueError('Session already exists')
|
||||||
|
try:
|
||||||
|
game = temporary / 'game'
|
||||||
|
game.mkdir()
|
||||||
|
for item in before['files']:
|
||||||
|
src = contained_path(source, item['path'])
|
||||||
|
dst = game / item['path']
|
||||||
|
dst.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
shutil.copyfile(src, dst)
|
||||||
|
pristine = verify_inventory(game, manifest)
|
||||||
|
after = verify_inventory(source, manifest)
|
||||||
|
record = {'schema_version': 1, 'session_id': session_id, 'status': 'staged',
|
||||||
|
'source_root': str(source), 'copy_root': str(final / 'game'),
|
||||||
|
'original_manifest': identify_file(manifest), 'source_pre': before,
|
||||||
|
'source_post_stage': after,
|
||||||
|
'copy_pre': dict(pristine, root=str(final / 'game')),
|
||||||
|
'staged_utc': utc_now(), 'acceptance': {'state': 'open',
|
||||||
|
'remaining': ['Staging is not gameplay execution']}}
|
||||||
|
_write_json(temporary / 'session.json', record)
|
||||||
|
os.rename(temporary, final)
|
||||||
|
(final / 'incomplete.json').unlink()
|
||||||
|
return record
|
||||||
|
except BaseException:
|
||||||
|
# Even KeyboardInterrupt leaves the prewritten diagnostic and lock.
|
||||||
|
raise
|
||||||
|
|
||||||
|
|
||||||
|
def postflight_session(session, source, manifest):
|
||||||
|
session, source = Path(session).resolve(strict=True), Path(source).resolve(strict=True)
|
||||||
|
separated_roots(source, session)
|
||||||
|
staged = read_json(session / 'session.json')
|
||||||
|
if staged['source_root'] != str(source):
|
||||||
|
raise ValueError('Source root does not match staged session')
|
||||||
|
source_post = verify_inventory(source, manifest)
|
||||||
|
copy_post = identify_tree(session / 'game')
|
||||||
|
before = {f['path']: f for f in staged['copy_pre']['files']}
|
||||||
|
after = {f['path']: f for f in copy_post['files']}
|
||||||
|
return {'schema_version': 1, 'session_id': staged['session_id'],
|
||||||
|
'source_post': source_post, 'copy_post': copy_post,
|
||||||
|
'copy_changes': {'added': sorted(after.keys() - before.keys()),
|
||||||
|
'missing': sorted(before.keys() - after.keys()),
|
||||||
|
'changed': sorted(k for k in before.keys() & after.keys()
|
||||||
|
if before[k] != after[k])}}
|
||||||
|
|
||||||
|
|
||||||
|
def _checked_artifact(item, root):
|
||||||
|
if not isinstance(item, dict):
|
||||||
|
raise ValueError('Artifact must be an object')
|
||||||
|
path = contained_path(root, item.get('path'))
|
||||||
|
actual = identify_file(path)
|
||||||
|
if item.get('sha256') != actual['sha256'] or item.get('size') != actual['size']:
|
||||||
|
raise ValueError('Artifact identity mismatch: ' + item['path'])
|
||||||
|
return path
|
||||||
|
|
||||||
|
|
||||||
|
def _finite(value):
|
||||||
|
if not isinstance(value, (int, float)) or isinstance(value, bool):
|
||||||
|
return False
|
||||||
|
try:
|
||||||
|
return math.isfinite(value)
|
||||||
|
except OverflowError:
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def validate_receipt(receipt, root):
|
||||||
|
"""Validate structure/actual files; return accepted plus explicit open reasons.
|
||||||
|
|
||||||
|
No execution, parser success, platform label or process exit implies review.
|
||||||
|
Later acceptance owners must additionally validate full matrix/applicability.
|
||||||
|
"""
|
||||||
|
if not isinstance(receipt, dict) or receipt.get('schema_version') != 1:
|
||||||
|
raise ValueError('Unsupported receipt schema_version')
|
||||||
|
for key in ('receipt_id', 'session_id', 'case_id'):
|
||||||
|
_id(receipt.get(key))
|
||||||
|
kind, status = receipt.get('evidence_kind'), receipt.get('status')
|
||||||
|
if kind not in KINDS or status not in STATUSES:
|
||||||
|
raise ValueError('Unknown evidence_kind/status')
|
||||||
|
platform = receipt.get('platform')
|
||||||
|
if not isinstance(platform, dict) or not platform.get('os'):
|
||||||
|
raise ValueError('Platform classification required')
|
||||||
|
expected = EXECUTION.get(kind, kind)
|
||||||
|
if platform.get('execution') != expected:
|
||||||
|
raise ValueError('Evidence kind/platform execution mismatch')
|
||||||
|
if kind == 'native_port' and platform['os'] not in ('linux', 'windows'):
|
||||||
|
raise ValueError('Native port requires Linux or Windows identity')
|
||||||
|
if kind == 'original_dxwnd' and platform['os'] != 'windows':
|
||||||
|
raise ValueError('DxWnd original requires Windows classification')
|
||||||
|
if not isinstance(receipt.get('historical'), bool):
|
||||||
|
raise ValueError('Explicit historical classification required')
|
||||||
|
for key in ('artifacts', 'derivatives', 'events', 'limitations', 'missing_evidence'):
|
||||||
|
if not isinstance(receipt.get(key), list) or len(receipt[key]) > 10000:
|
||||||
|
raise ValueError('Missing or unbounded list: ' + key)
|
||||||
|
for key in ('limitations', 'missing_evidence'):
|
||||||
|
if not all(isinstance(item, str) for item in receipt[key]):
|
||||||
|
raise ValueError('Text list required: ' + key)
|
||||||
|
invocation = receipt.get('invocation')
|
||||||
|
if (not isinstance(invocation, dict) or not isinstance(invocation.get('argv'), list)
|
||||||
|
or not all(isinstance(a, str) for a in invocation['argv'])
|
||||||
|
or not isinstance(invocation.get('cwd'), str)):
|
||||||
|
raise ValueError('Invocation requires inert argv array and recorded cwd')
|
||||||
|
clocks = receipt.get('clocks', {})
|
||||||
|
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:
|
||||||
|
raise ValueError('Invalid/reset monotonic clocks')
|
||||||
|
for key in ('wall_start', 'wall_end'):
|
||||||
|
try:
|
||||||
|
dt = datetime.fromisoformat(clocks[key].replace('Z', '+00:00'))
|
||||||
|
if dt.tzinfo is None:
|
||||||
|
raise ValueError('Timezone required')
|
||||||
|
except (KeyError, TypeError, AttributeError, ValueError) as error:
|
||||||
|
raise ValueError('Timezone-aware wall clocks required') from error
|
||||||
|
artifacts, aliases = {}, set()
|
||||||
|
for item in receipt['artifacts']:
|
||||||
|
_checked_artifact(item, root)
|
||||||
|
key = item['path'].casefold()
|
||||||
|
if key in aliases:
|
||||||
|
raise ValueError('Duplicate/case-colliding artifact')
|
||||||
|
aliases.add(key)
|
||||||
|
artifacts[item['path']] = item
|
||||||
|
for derivative in receipt['derivatives']:
|
||||||
|
if (not isinstance(derivative, dict) or derivative.get('path') not in artifacts or derivative.get('source') not in artifacts
|
||||||
|
or not derivative.get('tool') or not isinstance(derivative.get('argv'), list)):
|
||||||
|
raise ValueError('Derivative requires hashed source/output and tool/argv provenance')
|
||||||
|
for event in receipt['events']:
|
||||||
|
if not isinstance(event, dict):
|
||||||
|
raise ValueError('Event must be an object')
|
||||||
|
artifact = artifacts.get(event.get('artifact'))
|
||||||
|
if not artifact or not event.get('name') or not event.get('method'):
|
||||||
|
raise ValueError('Observed event requires media reference/name/method')
|
||||||
|
for field in ('media_seconds', 'elapsed_seconds', 'uncertainty_seconds'):
|
||||||
|
if not _finite(event.get(field)) or event[field] < 0:
|
||||||
|
raise ValueError('Event requires finite nonnegative timing/uncertainty')
|
||||||
|
duration = artifact.get('duration_seconds')
|
||||||
|
if not _finite(duration) or event['media_seconds'] > duration:
|
||||||
|
raise ValueError('Event exceeds identified media duration')
|
||||||
|
if event['elapsed_seconds'] > end - start:
|
||||||
|
raise ValueError('Event exceeds recorded monotonic interval')
|
||||||
|
if 'simulation_tick' in event and (kind == 'original_dxwnd' or
|
||||||
|
not isinstance(event['simulation_tick'], int) or event['simulation_tick'] < 0):
|
||||||
|
raise ValueError('Simulation ticks are separate port observations')
|
||||||
|
if kind == 'original_dxwnd' and event['method'] not in ('manual', 'procedural'):
|
||||||
|
raise ValueError('Original observation method requires separately proven recorder')
|
||||||
|
identity = receipt.get('identity')
|
||||||
|
if not isinstance(identity, dict):
|
||||||
|
raise ValueError('Identity object required')
|
||||||
|
for item in identity.values():
|
||||||
|
if isinstance(item, dict) and 'path' in item:
|
||||||
|
_checked_artifact(item, root)
|
||||||
|
reference_aliases = {}
|
||||||
|
for name in _receipt_paths(receipt):
|
||||||
|
parts = relative_name(name).parts
|
||||||
|
for length in range(1, len(parts) + 1):
|
||||||
|
prefix = '/'.join(parts[:length])
|
||||||
|
previous = reference_aliases.setdefault(prefix.casefold(), prefix)
|
||||||
|
if previous != prefix:
|
||||||
|
raise ValueError('Case-colliding artifact/identity path components')
|
||||||
|
acceptance = receipt.get('acceptance')
|
||||||
|
if (not isinstance(acceptance, dict) or acceptance.get('state') not in ('open', 'accepted')
|
||||||
|
or not isinstance(acceptance.get('remaining'), list)
|
||||||
|
or not all(isinstance(item, str) for item in acceptance['remaining'])):
|
||||||
|
raise ValueError('Explicit acceptance state/remaining required')
|
||||||
|
synthetic = (kind == 'synthetic' or receipt.get('scope') == 'tooling-test' or
|
||||||
|
any(item.get('synthetic') for item in artifacts.values()))
|
||||||
|
if synthetic and kind != 'synthetic':
|
||||||
|
raise ValueError('Synthetic artifacts cannot be relabeled as runtime evidence')
|
||||||
|
missing = list(receipt['missing_evidence']) + list(acceptance['remaining'])
|
||||||
|
if kind not in ('native_port', 'original_dxwnd'):
|
||||||
|
missing.append(kind + ' is not original/native gameplay acceptance')
|
||||||
|
if receipt['historical']:
|
||||||
|
missing.append('Historical evidence requires explicit current applicability review')
|
||||||
|
if status != 'reviewed':
|
||||||
|
missing.append('Status ' + status + ' has no completed audiovisual review')
|
||||||
|
required = ['executable', 'package', 'resources', 'launcher', 'source']
|
||||||
|
if kind == 'original_dxwnd':
|
||||||
|
required += ['original_pre', 'original_post', 'copy_pre', 'copy_post', 'dxwnd', 'dxwnd_config']
|
||||||
|
for key in required:
|
||||||
|
item = identity.get(key)
|
||||||
|
if not isinstance(item, dict) or 'path' not in item:
|
||||||
|
missing.append('Missing actual identity: ' + key)
|
||||||
|
roles = {a.get('role') for a in artifacts.values() if a.get('size', 0) > 0}
|
||||||
|
for role in ('video', 'audio', 'input_events'):
|
||||||
|
if role not in roles:
|
||||||
|
missing.append('Missing evidence artifact: ' + role)
|
||||||
|
review = receipt.get('review', {})
|
||||||
|
if not isinstance(review, dict):
|
||||||
|
raise ValueError('Review must be an object')
|
||||||
|
if not all(review.get(k) is True for k in ('visible', 'audible', 'ordinary_input', 'human_reviewed')):
|
||||||
|
missing.append('Actual visible/audible/ordinary-input human review remains open')
|
||||||
|
if not platform.get('version'):
|
||||||
|
missing.append('Missing actual OS version')
|
||||||
|
source = identity.get('source', {})
|
||||||
|
if (not source.get('commit') or not isinstance(source.get('dirty'), bool)
|
||||||
|
or not source.get('diff_sha256')):
|
||||||
|
missing.append('Missing exact source/dirty/diff identity')
|
||||||
|
if kind == 'native_port' and not all(platform.get(k) for k in ('gpu', 'driver', 'vulkan', 'sdl')):
|
||||||
|
missing.append('Missing port GPU/driver/Vulkan/SDL provenance')
|
||||||
|
if kind == 'original_dxwnd' and not receipt.get('wrapper_settings'):
|
||||||
|
missing.append('Missing actual DxWnd settings/limitations')
|
||||||
|
missing = list(dict.fromkeys(missing))
|
||||||
|
if acceptance['state'] == 'accepted' and missing:
|
||||||
|
raise ValueError('Unsupported acceptance promotion: ' + '; '.join(missing))
|
||||||
|
return {'valid': True, 'accepted': acceptance['state'] == 'accepted' and not missing,
|
||||||
|
'evidence_kind': kind, 'status': status, 'missing_evidence': missing,
|
||||||
|
'receipt_id': receipt['receipt_id']}
|
||||||
|
|
||||||
|
|
||||||
|
def _receipt_paths(receipt):
|
||||||
|
paths = [item['path'] for item in receipt['artifacts']]
|
||||||
|
paths += [item['path'] for item in receipt['identity'].values()
|
||||||
|
if isinstance(item, dict) and 'path' in item]
|
||||||
|
return sorted(set(paths))
|
||||||
|
|
||||||
|
|
||||||
|
def import_receipt(path, root, output):
|
||||||
|
root, output = separated_roots(root, output)
|
||||||
|
path = Path(path).resolve(strict=True)
|
||||||
|
if not path.is_relative_to(root):
|
||||||
|
raise ValueError('Receipt input must be contained in bundle')
|
||||||
|
receipt = read_json(path)
|
||||||
|
validate_receipt(receipt, root)
|
||||||
|
with path.open('rb') as stream:
|
||||||
|
raw = stream.read(MAX_JSON_BYTES + 1)
|
||||||
|
if len(raw) > MAX_JSON_BYTES:
|
||||||
|
raise ValueError('Receipt exceeds size limit')
|
||||||
|
if json.loads(raw) != receipt:
|
||||||
|
raise ValueError('Receipt changed during import')
|
||||||
|
receipt_id = _id(receipt['receipt_id'])
|
||||||
|
if receipt['evidence_kind'] == 'synthetic' and 'test' not in output.name.casefold():
|
||||||
|
raise ValueError('Synthetic receipt requires a separate test output namespace')
|
||||||
|
reserved = {'receipt.json', 'receipt.sha256', 'incomplete.json'}
|
||||||
|
paths = _receipt_paths(receipt)
|
||||||
|
if any(p.casefold() in reserved for p in paths):
|
||||||
|
raise ValueError('Artifact collides with publication metadata')
|
||||||
|
lock = _reserve(output, receipt_id)
|
||||||
|
final = output / receipt_id
|
||||||
|
sha = hashlib.sha256(raw).hexdigest()
|
||||||
|
try:
|
||||||
|
aliases = [p for p in output.iterdir() if p.name.casefold() == receipt_id.casefold()]
|
||||||
|
if aliases:
|
||||||
|
if len(aliases) != 1 or aliases[0].name != receipt_id:
|
||||||
|
raise ValueError('Case-aliased receipt ID conflict')
|
||||||
|
existing = final / 'receipt.json'
|
||||||
|
if existing.read_bytes() != raw:
|
||||||
|
raise ValueError('Conflicting duplicate receipt ID')
|
||||||
|
validate_receipt(read_json(existing), final)
|
||||||
|
if (final / 'receipt.sha256').read_text().strip() != sha:
|
||||||
|
raise ValueError('Stored receipt hash mismatch')
|
||||||
|
return {'path': str(existing), 'receipt_sha256': sha, 'duplicate': True}
|
||||||
|
temporary = _temporary(output, receipt_id, 'import')
|
||||||
|
for relative in paths:
|
||||||
|
source = contained_path(root, relative)
|
||||||
|
target = temporary / relative
|
||||||
|
target.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
shutil.copyfile(source, target)
|
||||||
|
validate_receipt(receipt, temporary)
|
||||||
|
with (temporary / 'receipt.json').open('xb') as stream:
|
||||||
|
stream.write(raw)
|
||||||
|
stream.flush()
|
||||||
|
os.fsync(stream.fileno())
|
||||||
|
(temporary / 'receipt.sha256').write_text(sha + '\n')
|
||||||
|
os.rename(temporary, final)
|
||||||
|
(final / 'incomplete.json').unlink()
|
||||||
|
return {'path': str(final / 'receipt.json'), 'receipt_sha256': sha, 'duplicate': False}
|
||||||
|
finally:
|
||||||
|
lock.rmdir()
|
||||||
|
|
||||||
|
|
||||||
|
def _git_output(project, *args):
|
||||||
|
# Temporary output avoids unbounded capture_output buffers. No shell or
|
||||||
|
# imported receipt command is executed; every argument here is tool-owned.
|
||||||
|
with tempfile.TemporaryFile() as stream:
|
||||||
|
result = subprocess.run(['git', '-C', str(project), *args], stdout=stream,
|
||||||
|
stderr=subprocess.DEVNULL, timeout=20, check=False)
|
||||||
|
stream.seek(0)
|
||||||
|
data = stream.read(MAX_JSON_BYTES + 1)
|
||||||
|
if result.returncode or len(data) > MAX_JSON_BYTES:
|
||||||
|
raise ValueError('Git identity unavailable or exceeds bound')
|
||||||
|
return data
|
||||||
|
|
||||||
|
|
||||||
|
def source_identity(project):
|
||||||
|
commit = _git_output(project, 'rev-parse', 'HEAD').decode().strip()
|
||||||
|
status = _git_output(project, 'status', '--porcelain=v1', '--untracked-files=all')
|
||||||
|
diff = _git_output(project, 'diff', '--binary', 'HEAD')
|
||||||
|
untracked_names = _git_output(project, 'ls-files', '--others', '--exclude-standard', '-z')
|
||||||
|
untracked = []
|
||||||
|
for name in untracked_names.decode('utf8').split('\0'):
|
||||||
|
if name:
|
||||||
|
untracked.append({'path': name, **identify_file(contained_path(project, name))})
|
||||||
|
return {'commit': commit, 'dirty': bool(status),
|
||||||
|
'diff_sha256': hashlib.sha256(diff).hexdigest(),
|
||||||
|
'status_sha256': hashlib.sha256(status).hexdigest(),
|
||||||
|
'untracked_sha256': hashlib.sha256(canonical_bytes(untracked)).hexdigest(),
|
||||||
|
'untracked_files': untracked}
|
||||||
|
|
||||||
|
|
||||||
|
def identify_report(package, report=None, executable=None, resources=None, launcher=None, project=None):
|
||||||
|
"""Identify actual on-disk bytes; a report's recorded claims stay historical.
|
||||||
|
|
||||||
|
Does not run the package, stamp today's HEAD onto a historical binary, or
|
||||||
|
promote a report's mentioned artifacts into newly observed runtime evidence.
|
||||||
|
"""
|
||||||
|
result = {'schema_version': 1, 'evidence_kind': 'historical_report', 'historical': True,
|
||||||
|
'acceptance': {'state': 'open'}, 'missing_evidence': [], 'actual': {}}
|
||||||
|
for label, path, tree in [('package', package, True), ('report', report, False),
|
||||||
|
('executable', executable, False), ('resources', resources, True),
|
||||||
|
('launcher', launcher, False)]:
|
||||||
|
if path is None or not Path(path).exists():
|
||||||
|
result['missing_evidence'].append(label + ' absent; no identity minted')
|
||||||
|
continue
|
||||||
|
result['actual'][label] = identify_tree(path) if tree else dict(identify_file(path), path=str(Path(path).resolve()))
|
||||||
|
if label == 'report':
|
||||||
|
with Path(path).open('rb') as stream:
|
||||||
|
result['recorded_scope'] = stream.read(16384).decode('utf8', 'replace')
|
||||||
|
result['scope_limit'] = 'Historical text only; referenced artifacts not implicitly verified'
|
||||||
|
if project:
|
||||||
|
result['collector_source'] = source_identity(project)
|
||||||
|
result['missing_evidence'].append('No new runtime execution or current applicability established')
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
OBLIGATION_IDS = ['continuous', 'dialogue-return', 'bank-left', 'bank-right', 'landing-idle']
|
||||||
|
SIDE_KEYS = [('original_dxwnd', 'windows'), ('native_port', 'linux'), ('native_port', 'windows')]
|
||||||
|
BASE_EVENTS = {
|
||||||
|
'continuous': ['startup', 'control', 'dialogue_start', 'dialogue_end', 'first_neutral_input',
|
||||||
|
'jump_left', 'bank_left', 'landing_left', 'jump_right', 'bank_right', 'landing',
|
||||||
|
'idle', 'lab_departure', 'vr04_entry', 'vr04_use', 'return_cleanup', 'lab_return',
|
||||||
|
'lab_exit', 'outside_arrival'],
|
||||||
|
'dialogue-return': ['dialogue_start', 'dialogue_end', 'first_neutral_input', 'idle'],
|
||||||
|
'bank-left': ['jump_left', 'bank_left', 'landing'],
|
||||||
|
'bank-right': ['jump_right', 'bank_right', 'landing'],
|
||||||
|
'landing-idle': ['landing', 'idle']}
|
||||||
|
|
||||||
|
|
||||||
|
def validate_scenario_contract(protocol):
|
||||||
|
if protocol.get('schema_version') != 1:
|
||||||
|
raise ValueError('Unsupported scenario schema')
|
||||||
|
cells = protocol.get('cells', [])
|
||||||
|
expected = sorted('-'.join(parts) for parts in itertools.product(
|
||||||
|
('fresh', 'retained'), ('natural', 'skipped'), ('ordinary', 'edge')))
|
||||||
|
if [c.get('id') for c in cells] != expected:
|
||||||
|
raise ValueError('Required eight uniquely identified, ordered matrix cells are missing/duplicated')
|
||||||
|
for cell in cells:
|
||||||
|
if (cell['id'] != '-'.join(cell.get(k, '') for k in ('lifetime', 'dialogue', 'input'))
|
||||||
|
or cell.get('obligations') != OBLIGATION_IDS):
|
||||||
|
raise ValueError('Matrix dimensions/obligations do not match stable case ID')
|
||||||
|
sides = protocol.get('required_sides', [])
|
||||||
|
if [(s.get('evidence_kind'), s.get('os')) for s in sides] != SIDE_KEYS:
|
||||||
|
raise ValueError('Original-DxWnd and both native-port sides are separately required')
|
||||||
|
if len({s.get('id') for s in sides}) != 3:
|
||||||
|
raise ValueError('Side IDs must be unique')
|
||||||
|
for key in OBLIGATION_IDS:
|
||||||
|
obligation = protocol.get('obligations', {}).get(key, {})
|
||||||
|
if obligation.get('required_events') != BASE_EVENTS[key]:
|
||||||
|
raise ValueError('Required chronological event protocol missing: ' + key)
|
||||||
|
if obligation.get('required_artifact_roles') != ['video', 'audio', 'input_events', 'prerequisite']:
|
||||||
|
raise ValueError('Required artifact obligations missing: ' + key)
|
||||||
|
if not all(isinstance(obligation.get(k), str) and obligation[k].strip()
|
||||||
|
for k in ('setup', 'actions', 'end_condition')):
|
||||||
|
raise ValueError('Executable procedure missing: ' + key)
|
||||||
|
if protocol['obligations']['continuous'].get('route') != ['lab', 'VR04', 'lab', 'outside']:
|
||||||
|
raise ValueError('Continuous journey must be lab -> VR04 -> lab -> outside')
|
||||||
|
if protocol.get('dialogue_events') != {'natural': ['dialogue_end'], 'skipped': ['dialogue_skip', 'dialogue_end']}:
|
||||||
|
raise ValueError('Natural/skipped dialogue require separate observed boundaries')
|
||||||
|
if protocol.get('input_events') != {'ordinary': [], 'edge': ['resumed_held_input', 'held_dialogue', 'held_return']}:
|
||||||
|
raise ValueError('Held input through dialogue/return is required for edge runs')
|
||||||
|
if set(protocol.get('protected_observations', {})) != {
|
||||||
|
'tsk_retained_order', 'fresh_direct_scene_order', 'legitimate_landing_bank'}:
|
||||||
|
raise ValueError('Protected movement observations are missing')
|
||||||
|
event = protocol.get('event_contract', {})
|
||||||
|
if (event.get('original_method') != ['manual', 'procedural'] or
|
||||||
|
event.get('simulation_ticks') != 'separate_port_only'):
|
||||||
|
raise ValueError('Original annotation and port clock categories must remain distinct')
|
||||||
|
return {'valid': True, 'cells': 8, 'required': 120}
|
||||||
|
|
||||||
|
|
||||||
|
def required_events(protocol, cell, obligation_id):
|
||||||
|
events = list(protocol['obligations'][obligation_id]['required_events'])
|
||||||
|
if 'dialogue_end' in events and cell['dialogue'] == 'skipped':
|
||||||
|
events.insert(events.index('dialogue_end'), 'dialogue_skip')
|
||||||
|
if cell['input'] == 'edge':
|
||||||
|
if 'dialogue_start' in events:
|
||||||
|
events.insert(events.index('dialogue_start') + 1, 'held_dialogue')
|
||||||
|
events.insert(events.index('first_neutral_input'), 'resumed_held_input')
|
||||||
|
if 'return_cleanup' in events:
|
||||||
|
events.insert(events.index('return_cleanup'), 'held_return')
|
||||||
|
return events
|
||||||
|
|
||||||
|
|
||||||
|
def _scenario_observation(protocol, cell, receipt):
|
||||||
|
obligation = receipt['obligation_id']
|
||||||
|
if receipt.get('scope') != obligation:
|
||||||
|
raise ValueError('Receipt scope must match its explicit obligation')
|
||||||
|
events = receipt['events']
|
||||||
|
required = required_events(protocol, cell, obligation)
|
||||||
|
# Select in recorded order; repeated names are legitimate only when the
|
||||||
|
# requested boundaries can still be found without reordering observations.
|
||||||
|
selected, cursor = [], 0
|
||||||
|
for name in required:
|
||||||
|
while cursor < len(events) and events[cursor]['name'] != name:
|
||||||
|
cursor += 1
|
||||||
|
if cursor >= len(events):
|
||||||
|
raise ValueError('Missing/out-of-order event: ' + name)
|
||||||
|
selected.append(events[cursor])
|
||||||
|
cursor += 1
|
||||||
|
elapsed = [e['elapsed_seconds'] for e in events]
|
||||||
|
if elapsed != sorted(elapsed):
|
||||||
|
raise ValueError('Event timestamps reset within session')
|
||||||
|
media_paths = {e['artifact'] for e in selected}
|
||||||
|
if len(media_paths) != 1:
|
||||||
|
raise ValueError('continuous/focused observations cannot be disconnected snapshots')
|
||||||
|
times = [e['media_seconds'] for e in selected]
|
||||||
|
if times != sorted(times) or times[-1] <= times[0]:
|
||||||
|
raise ValueError('Media timestamps reset or contain no observed interval')
|
||||||
|
video = next(a for a in receipt['artifacts'] if a['path'] == selected[0]['artifact'])
|
||||||
|
if video.get('role') != 'video':
|
||||||
|
raise ValueError('continuous/focused markers require actual video artifact')
|
||||||
|
roles = {a.get('role') for a in receipt['artifacts']}
|
||||||
|
if not set(protocol['obligations'][obligation]['required_artifact_roles']).issubset(roles):
|
||||||
|
raise ValueError('Missing required scenario artifacts')
|
||||||
|
continuity = receipt.get('continuity', {})
|
||||||
|
if (not receipt['clocks'].get('clock_id') or
|
||||||
|
continuity.get('lifetime_id') != receipt['session_id']):
|
||||||
|
raise ValueError('One explicit monotonic clock and lifetime identity required')
|
||||||
|
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')
|
||||||
|
if cell['lifetime'] == 'retained':
|
||||||
|
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')
|
||||||
|
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
|
||||||
|
names.index('prerequisite_departure') >= names.index('prerequisite_return') or
|
||||||
|
any(e['elapsed_seconds'] >= selected[0]['elapsed_seconds'] for e in prerequisite)):
|
||||||
|
raise ValueError('Retained setup requires observed prerequisite departure/return before test')
|
||||||
|
|
||||||
|
|
||||||
|
def audit_scenarios(protocol, records):
|
||||||
|
"""records is [(receipt_dict, contained_artifact_root), ...]. No writes.
|
||||||
|
|
||||||
|
A complete result describes declared/reviewed receipt coverage, not automatic
|
||||||
|
audiovisual truth or a universal fidelity tolerance. Real capture/review and
|
||||||
|
current applicability remain the responsibility of the acceptance owner.
|
||||||
|
"""
|
||||||
|
validate_scenario_contract(protocol)
|
||||||
|
cells = {c['id']: c for c in protocol['cells']}
|
||||||
|
required = {(c, o, kind, os_name) for c in cells for o in OBLIGATION_IDS
|
||||||
|
for kind, os_name in SIDE_KEYS}
|
||||||
|
filled, seen, invalid, open_receipts, fresh_sessions = set(), set(), [], [], {}
|
||||||
|
for receipt, root in records:
|
||||||
|
label = str(receipt.get('receipt_id', '<missing>'))
|
||||||
|
try:
|
||||||
|
result = validate_receipt(receipt, root)
|
||||||
|
case, obligation = receipt['case_id'], receipt.get('obligation_id')
|
||||||
|
key = (case, obligation, receipt['evidence_kind'], receipt['platform']['os'])
|
||||||
|
if key not in required:
|
||||||
|
raise ValueError('Evidence is not a required original/native matrix slot')
|
||||||
|
if key in seen:
|
||||||
|
filled.discard(key)
|
||||||
|
raise ValueError('Duplicate/conflicting matrix slot; explicitly select applicability first')
|
||||||
|
seen.add(key)
|
||||||
|
if not result['accepted']:
|
||||||
|
open_receipts.append(label + ': ' + '; '.join(result['missing_evidence']))
|
||||||
|
continue
|
||||||
|
_scenario_observation(protocol, cells[case], receipt)
|
||||||
|
if cells[case]['lifetime'] == 'fresh':
|
||||||
|
session_key = (receipt['evidence_kind'], receipt['platform']['os'], receipt['session_id'])
|
||||||
|
if session_key in fresh_sessions:
|
||||||
|
filled.discard(fresh_sessions[session_key])
|
||||||
|
raise ValueError('fresh runs require independently staged launch/session IDs')
|
||||||
|
fresh_sessions[session_key] = key
|
||||||
|
filled.add(key)
|
||||||
|
except (ValueError, KeyError, TypeError) as error:
|
||||||
|
invalid.append(label + ': ' + str(error))
|
||||||
|
gaps = required - filled
|
||||||
|
side_ids = {(s['evidence_kind'], s['os']): s['id'] for s in protocol['required_sides']}
|
||||||
|
return {'schema_version': 1, 'structurally_ready': True,
|
||||||
|
'complete': not gaps and not invalid, 'required': len(required), 'accepted': len(filled),
|
||||||
|
'missing_case_ids': sorted({g[0] for g in gaps}),
|
||||||
|
'missing_obligations': sorted('/'.join((c, o, side_ids[(k, os_name)]))
|
||||||
|
for c, o, k, os_name in gaps),
|
||||||
|
'open_receipts': open_receipts, 'invalid': invalid}
|
||||||
|
|
||||||
|
|
||||||
|
def audit_receipt_tree(protocol, root):
|
||||||
|
root = Path(root)
|
||||||
|
records = []
|
||||||
|
if root.exists():
|
||||||
|
# Reuse tree walker safety/bounds without hashing every video a second
|
||||||
|
# time. Validate each referenced artifact once via validate_receipt.
|
||||||
|
count = 0
|
||||||
|
for directory, dirs, files in os.walk(root, followlinks=False):
|
||||||
|
for name in dirs + files:
|
||||||
|
count += 1
|
||||||
|
if count > MAX_FILES or (Path(directory) / name).is_symlink():
|
||||||
|
raise ValueError('Receipt index unbounded or contains symlinks')
|
||||||
|
if 'receipt.json' in files:
|
||||||
|
path = Path(directory) / 'receipt.json'
|
||||||
|
records.append((read_receipt(path), path.parent))
|
||||||
|
return audit_scenarios(protocol, records)
|
||||||
|
|
||||||
|
|
||||||
|
def read_receipt(path):
|
||||||
|
"""Verify the import sidecar when present; raw collector bundles may lack it."""
|
||||||
|
path = Path(path)
|
||||||
|
receipt = read_json(path)
|
||||||
|
sidecar = path.with_name('receipt.sha256')
|
||||||
|
if sidecar.exists():
|
||||||
|
if sidecar.is_symlink() or sidecar.stat().st_size > 128:
|
||||||
|
raise ValueError('Invalid receipt hash sidecar')
|
||||||
|
if sidecar.read_text().strip() != identify_file(path)['sha256']:
|
||||||
|
raise ValueError('Receipt byte identity mismatch')
|
||||||
|
return receipt
|
||||||
Reference in new issue
Block a user