Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions phase6c/LEGACY_CLOSEOUT.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,22 @@ run. Historical artifacts produced before this attestation was added cannot
satisfy the closeout gate; repeat the private observation with the attested
workflow instead of retroactively issuing identity claims for an old run.

MIDI summaries also bind every retained per-stem observation by relative path
and SHA-256, recheck its identity and execution fields, and require each
candidate representative to match the corresponding donor member. Older
summaries without those bindings do not satisfy the strengthened gate; rerun
the private workflow rather than adding unsupported claims to old evidence.
The MIDI pre-upload audit rejects raw IT/audio payloads as well as MIDI/ZIP
inputs, including renamed files with recognized headers.

Historical donor validation checks the declared workflow revision and retained
`itmodule2.c` bytes against the committed blob at that revision (not a dirty
worktree copy). The retained probe hash and ELF
file-type check establish artifact consistency only: this lane does not yet
independently attest that the donor executable was rebuilt from those sources.
A self-consistent substituted ELF cannot be excluded by these checks alone.
That remaining build-provenance boundary must not be described as closed.

`COMPONENTS_REVALIDATED` means summary integrity under those existing contracts.
It is narrower than an independent execution replay or a new original-reference
behavioral verdict. Missing artifacts stay `PENDING_PRIVATE_DISPATCH`; malformed
Expand Down
29 changes: 29 additions & 0 deletions scripts/phase6c-historical-it.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

ROOT = pathlib.Path(__file__).resolve().parents[1]
MANIFEST = ROOT / "phase6c/evidence/legacy-module-import/historical-sickmaate.json"
DONOR_SOURCE = ROOT / "cpsycle/audio/src/itmodule2.c"
EXPECTED_CONTRACT = "legacy-impulse-tracker-import-reference"
SUMMARY_CONTRACT = "legacy-impulse-tracker-three-way-summary"
EXPECTED_REFERENCE_BUILD = "Psycle 1.12.0 x86"
Expand Down Expand Up @@ -313,6 +314,33 @@ def require_original_reference_identity(original: dict[str, Any]) -> None:
die("original historical receipt is bound to the wrong Psycle executable SHA-256")


def validate_donor_source_identity(donor_path: pathlib.Path, donor: dict[str, Any]) -> None:
"""Bind retained source to this checkout; do not attest a donor rebuild."""
try:
revision = subprocess.check_output(
["git", "-C", str(ROOT), "rev-parse", "HEAD"], text=True
).strip()
except (OSError, subprocess.CalledProcessError) as exc:
die(f"cannot resolve donor repository revision: {exc}")
if donor.get("source_revision") != revision:
die("historical donor source revision differs from the checked-out workflow head")
try:
source = subprocess.check_output(
["git", "-C", str(ROOT), "show",
f"{revision}:{DONOR_SOURCE.relative_to(ROOT).as_posix()}"],
)
except (OSError, subprocess.CalledProcessError) as exc:
die(f"cannot read committed historical donor source: {exc}")
if donor.get("source_file_sha256") != sha256_bytes(source):
die("retained historical donor source does not match committed itmodule2.c")
probe = donor_path.parent / donor["probe_executable"]
with probe.open("rb") as handle:
if handle.read(4) != b"\x7fELF":
die("historical donor probe artifact is not an ELF executable")
# The support-file check binds the retained probe bytes to its receipt. ELF
# magic is only a file-type check, not proof of build origin or execution.


def validate_summary_components(
*,
source: dict[str, Any],
Expand Down Expand Up @@ -353,6 +381,7 @@ def validate_summary_components(
donor.get("probe_executable_sha256"),
"donor probe",
)
validate_donor_source_identity(donor_path, donor)
require_hash(donor.get("raw_output_sha256"), "donor raw_output_sha256")

require_common_receipt(
Expand Down
7 changes: 1 addition & 6 deletions scripts/phase6c-legacy-closeout.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,13 +141,8 @@ def audit_artifact(root: pathlib.Path) -> None:
# Reject links before the lane validators read any support file.
if root.is_symlink() or any(path.is_symlink() for path in root.rglob("*")):
fail("observation artifacts must not contain symlinks")
# Use the same payload guard as the private MIDI workflow before upload.
load_helper("phase6c-midi-corpus.py").audit_public_tree(root)
for path in root.rglob("*"):
if path.is_file():
prefix = path.read_bytes()[:12]
wave = prefix[:4] in {b"RIFF", b"RIFX", b"RF64"} and prefix[8:12] == b"WAVE"
if path.suffix.lower() in {".it", ".wav"} or prefix.startswith(b"IMPM") or wave:
fail("observation artifact contains raw IT/audio payload")


def revalidate_summary(root: pathlib.Path, lane: str) -> dict[str, Any]:
Expand Down
92 changes: 87 additions & 5 deletions scripts/phase6c-midi-corpus.py
Original file line number Diff line number Diff line change
Expand Up @@ -1222,11 +1222,17 @@ def audit_public_tree(root: pathlib.Path) -> None:
if not path.is_file():
continue
relative = path.relative_to(root).as_posix()
if path.suffix.lower() in {".mid", ".midi", ".zip"}:
if path.suffix.lower() in {".mid", ".midi", ".zip", ".it", ".wav"}:
leaks.append(relative)
continue
data = path.read_bytes()
prefix = data[:4]
if prefix == b"IMPM":
leaks.append(relative)
continue
if prefix in {b"RIFF", b"RIFX", b"RF64"} and data[8:12] == b"WAVE":
leaks.append(relative)
continue
if contains_structural_smf(data):
leaks.append(relative)
continue
Expand Down Expand Up @@ -1821,11 +1827,19 @@ def donor_summary(
render_sha = obs.get("render_sha256")
if not isinstance(render_sha, str) or len(render_sha) != 64:
die(f"{stem['stem_id']}: donor render SHA-256 is invalid")
try:
observation_name = path.resolve().relative_to(output.parent.resolve()).as_posix()
except ValueError:
die(f"{stem['stem_id']}: observation must be retained inside the donor artifact")
obs["_observation"] = observation_name
obs["_observation_sha256"] = sha256_file(path)
observations.append(obs)
set_spec = manifest_by_name[set_info["name"]]
stem_records = [
{
"stem_id": item["stem_id"],
"observation": item["_observation"],
"observation_sha256": item["_observation_sha256"],
"source_relative_name": item["source_relative_name"],
"source_sha256": item["source_sha256"],
"source_size_bytes": item["source_size_bytes"],
Expand Down Expand Up @@ -1860,6 +1874,12 @@ def donor_summary(
],
"tempo_map_digest_fnv64": item["tempo_map_digest_fnv64"],
"import_event_digest_fnv64": item["import_event_digest_fnv64"],
"imported_notes": item["imported_notes"],
"projection_notes": item["projection_notes"],
"projection_beats": item["projection_beats"],
"render_frames": item["render_frames"],
"render_peak": item["render_peak"],
"render_size_bytes": item["render_size_bytes"],
"render_sha256": item["render_sha256"],
}
for item in observations
Expand Down Expand Up @@ -1924,19 +1944,26 @@ def require_support(
relative_name: Any,
expected_sha: Any,
label: str,
) -> None:
if not isinstance(relative_name, str) or not relative_name:
) -> pathlib.Path:
if not isinstance(relative_name, str) or not relative_name or "\\" in relative_name:
die(f"{label} support path is missing")
relative = pathlib.PurePosixPath(relative_name)
if relative.is_absolute() or ".." in relative.parts:
die(f"{label} support path escapes its artifact root")
path = receipt_path.parent / pathlib.Path(*relative.parts)
if (
not path.resolve().is_relative_to(receipt_path.parent.resolve())
or any((receipt_path.parent / pathlib.Path(*relative.parts[:index])).is_symlink()
for index in range(1, len(relative.parts) + 1))
):
die(f"{label} support path escapes or links outside its artifact contract")
if not path.is_file():
die(f"{label} support file is missing: {relative_name}")
if not isinstance(expected_sha, str) or len(expected_sha) != 64:
die(f"{label} support SHA-256 is invalid")
if sha256_file(path) != expected_sha.lower():
die(f"{label} support file hash mismatch: {relative_name}")
return path

current_revision = repository_commit()
canonical_donor_source_sha = sha256_file(DONOR_SOURCE)
Expand Down Expand Up @@ -2028,7 +2055,7 @@ def require_support(
or not isinstance(relative_name, str)
or not isinstance(source_sha, str)
or len(source_sha) != 64
or not isinstance(source_size, int)
or type(source_size) is not int
or source_size <= 0
or not isinstance(analysis_sha, str)
or len(analysis_sha) != 64
Expand Down Expand Up @@ -2163,6 +2190,51 @@ def require_support(
die(f"donor {name} tick-zero tempo total differs from source aggregate")
if sorted(observed_channels) != item["source_aggregate"].get("channels"):
die(f"donor {name} imported MIDI channel union differs from source analysis")
for record in stem_records:
observation_path = require_support(
donor_path, record.get("observation"), record.get("observation_sha256"),
f"donor {record['stem_id']} observation",
)
observation = load_json(observation_path)
required = {
"schema_version": 1, "phase": "6C", "contract": DONOR_CONTRACT,
"evidence_role": "cpsycle-donor-observation", "set_name": name,
"source_revision": current_revision, "load_result": "accepted",
"machines_before_projection": 0, "non_silent_projection": True,
"projection_kind": "deterministic-sampler", "projection_beats": 16,
"private_input_required": True,
"fixture_redistributed": False, "parity_status": "UNKNOWN",
}
for field, expected in required.items():
if type(observation.get(field)) is not type(expected) or observation[field] != expected:
die(f"donor {record['stem_id']} observation {field} is invalid")
# Compare the retained producer receipt with its summary projection.
# Raw private SMF/audio bytes are deliberately not replayed here.
for field in (
"stem_id", "source_relative_name", "source_sha256", "source_size_bytes",
"source_analysis_sha256", "midi_channel_mask", "release_channel_mask",
"releases", "note_event_digest_fnv64", "midi_cc", "midi_cc_digest_fnv64",
"song_bpm", "tempo_commands", "tempo_map_digest_fnv64",
"import_event_digest_fnv64", "render_sha256",
):
if type(observation.get(field)) is not type(record[field]) or observation[field] != record[field]:
die(f"donor {record['stem_id']} observation {field} differs from its summary")
for field in ("imported_notes", "projection_notes", "render_frames", "render_peak", "render_size_bytes"):
if type(record.get(field)) is not int or record[field] <= 0:
die(f"donor {record['stem_id']} observation summary {field} is invalid")
if type(observation.get(field)) is not int or observation[field] <= 0:
die(f"donor {record['stem_id']} observation {field} is invalid")
if observation[field] != record[field]:
die(f"donor {record['stem_id']} observation {field} differs from its summary")
if type(record.get("projection_beats")) is not int or record["projection_beats"] != 16:
die(f"donor {record['stem_id']} observation summary projection_beats is invalid")
output_sha = observation.get("probe_output_sha256")
if not isinstance(output_sha, str) or len(output_sha) != 64:
die(f"donor {record['stem_id']} observation probe-output SHA-256 is invalid")
try:
int(output_sha, 16)
except ValueError:
die(f"donor {record['stem_id']} observation probe-output SHA-256 is invalid")

require_support(
donor_path,
Expand Down Expand Up @@ -2260,10 +2332,20 @@ def require_support(
or not rep_id.endswith("-" + rep_sha[:12])
or not isinstance(rep_name, str)
or not rep_name
or not isinstance(rep_size, int)
or type(rep_size) is not int
or rep_size <= 0
):
die(f"candidate {item.get('set_name')} representative identity is incomplete")
donor_set = next(entry for entry in donor["sets"] if entry["name"] == set_name)
matches = [
record for record in donor_set["stems"]
if record["stem_id"] == rep_id
and record["source_relative_name"] == rep_name
and record["source_sha256"] == rep_sha
and record["source_size_bytes"] == rep_size
]
if len(matches) != 1:
die(f"candidate {set_name} representative does not match one donor corpus member")
if not isinstance(raw_sha, str) or len(raw_sha) != 64:
die(f"candidate {item.get('set_name')} raw-output SHA-256 is invalid")
try:
Expand Down
46 changes: 41 additions & 5 deletions tests/phase6c_legacy_closeout.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import importlib.util
import json
import tempfile
from unittest import mock
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
Expand Down Expand Up @@ -72,14 +73,14 @@ def rejected(operation, message):
(root / "link").symlink_to(ROOT / "README.md")
rejected(lambda: helper.audit_artifact(root), "symlinks")
(root / "link").unlink()
for name, payload in (
("renamed.log", b"IMPMprivate module"),
("audio.wav", b"audio"),
("renamed-audio.log", b"RIFF\x04\x00\x00\x00WAVE"),
for name, payload, message in (
("renamed.log", b"IMPMprivate module", "raw corpus"),
("audio.wav", b"audio", "raw corpus"),
("renamed-audio.log", b"RIFF\x04\x00\x00\x00WAVE", "raw corpus"),
):
path = root / name
path.write_bytes(payload)
rejected(lambda: helper.audit_artifact(root), "raw IT/audio")
rejected(lambda: helper.audit_artifact(root), message)
path.unlink()
midi = helper.load_helper("phase6c-midi-corpus.py")
midi.write_synthetic_fixture(root / "renamed.log")
Expand All @@ -101,7 +102,15 @@ def support(directory, name):
return name, helper.digest(path)

donor_source, donor_sha = support("donor", "source.c")
donor_source_path = root / "donor" / donor_source
donor_source_path.write_bytes(historical.DONOR_SOURCE.read_bytes())
donor_sha = helper.digest(donor_source_path)
probe, probe_sha = support("donor", "probe")
probe_path = root / "donor" / probe
# Inert file-type marker only: this fixture is never executed and does not
# establish that a donor probe was built from the declared source revision.
probe_path.write_bytes(b"\x7fELFproject-owned donor fixture")
probe_sha = helper.digest(probe_path)
player, player_sha = support("candidate", "player")
player_path = root / "candidate" / player
player_path.write_bytes(b"\x7fELFproject-owned candidate fixture")
Expand All @@ -122,6 +131,7 @@ def support(directory, name):
attestation = midi.candidate_attestation_document(identity, player_sha)
attestation_path.write_text(json.dumps(attestation))
donor = dict(common, evidence_role="cpsycle-donor-observation", source_sha256=source["sha256"], source_size_bytes=source["size_bytes"], load_result="accepted", non_silent_playback=True, fixture_redistributed=False, private_input_required=True, source_file=donor_source, source_file_sha256=donor_sha, probe_executable=probe, probe_executable_sha256=probe_sha, raw_output_sha256="1" * 64)
donor["source_revision"] = midi.repository_commit()
candidate = dict(common, evidence_role="candidate-observation", source_sha256=source["sha256"], source_size_bytes=source["size_bytes"], direct_it_load="rejected", diagnostic_could_not_load_song_file=True, exit_code=2, private_input_required=True, player=player, player_sha256=player_sha, raw_output_sha256="2" * 64)
candidate.update(identity, build_attestation=attestation_path.name, build_attestation_sha256=helper.digest(attestation_path))
original = dict(common, evidence_role="original", fixture_sha256=source["sha256"], fixture_distribution="external-hash-bound", fixture_redistributed=False, original_psycle_observed=True, reference_build=historical.EXPECTED_REFERENCE_BUILD, reference_file=historical.EXPECTED_REFERENCE_FILE, reference_installer_sha256=historical.EXPECTED_REFERENCE_INSTALLER_SHA256, reference_installer_size_bytes=historical.EXPECTED_REFERENCE_INSTALLER_SIZE, reference_executable_sha256=historical.EXPECTED_REFERENCE_EXECUTABLE_SHA256, load_result="inconclusive", observation="project-owned summary validation fixture")
Expand All @@ -144,6 +154,32 @@ def support(directory, name):
assert one_lane["observation_summaries_revalidated"] is False
assert one_lane["priority_hold"] == "AWAITING_OBSERVATION_REVIEW"

# Bind the committed source blob, never mutable worktree bytes. No native
# source is edited: an inert mock fails if this check reads a filesystem hash.
with mock.patch.object(historical, "sha256_file", side_effect=AssertionError("unexpected worktree hash")):
historical.validate_donor_source_identity(donor_path, donor)

# A self-consistent component hash cannot substitute for checkout identity.
for revision in (None, "0" * 40):
changed_donor = dict(donor, source_revision=revision)
donor_path.write_text(json.dumps(changed_donor))
rejected(lambda: helper.revalidate_summary(root, "historical-sickmaate"), "source revision differs")
donor_path.write_text(json.dumps(donor))
original_donor_source = donor_source_path.read_bytes()
donor_source_path.write_text("project-owned substituted source\n")
changed_donor = dict(donor, source_file_sha256=helper.digest(donor_source_path))
donor_path.write_text(json.dumps(changed_donor))
rejected(lambda: helper.revalidate_summary(root, "historical-sickmaate"), "does not match committed itmodule2.c")
donor_source_path.write_bytes(original_donor_source)
donor_path.write_text(json.dumps(donor))
original_probe = probe_path.read_bytes()
probe_path.write_text("project-owned non-executable fixture\n")
changed_donor = dict(donor, probe_executable_sha256=helper.digest(probe_path))
donor_path.write_text(json.dumps(changed_donor))
rejected(lambda: helper.revalidate_summary(root, "historical-sickmaate"), "not an ELF executable")
probe_path.write_bytes(original_probe)
donor_path.write_text(json.dumps(donor))

for field, bad in (
("repository_commit", "0" * 40),
("candidate_baseline_sha256", "0" * 64),
Expand Down
Loading
Loading