"""Text-only contracts for sealed recording-start declaration ledgers.""" import copy import csv import hashlib import io import json import subprocess import sys import tempfile import unittest from contextlib import ExitStack from pathlib import Path from unittest.mock import patch try: from tools import wall_clock_declarations as ledger except ImportError: ledger = None try: from tools import create_wall_clock_ledger as author except ImportError: author = None REVISION = '6fed0d073bdc307cdb81ea1dd8d4db6b1ecb04c7' STAMP = '2026-10-24T12:00:00+00:00' class WallClockDeclarationTests(unittest.TestCase): def setUp(self): self.assertIsNotNone(ledger, 'Wall-clock declaration validation is not implemented') self.directory = tempfile.TemporaryDirectory() self.addCleanup(self.directory.cleanup) self.root = Path(self.directory.name) (self.root / 'evidence.txt').write_text('Creator declared recording start.\n', encoding='utf-8') self.evidence = self.write_receipt('evidence.txt') self.metadata = dict(ledger_id='2026-W43-active', ingestion_week='2026-W43', source_revision=REVISION, cohort='active_ingest') self.candidates = dict(schema='wall-clock-candidates/v1', **self.metadata, source_files=[], candidates=[dict( record_id='record-1', work_id='', claim_type='recording_start')]) self.event = dict(event_id='2026-W43-active:record-1:initial', record_id='record-1', claim_type='recording_start', status='timing_supported', event_type='initial_classification', prior_event_id=None, declared_value='2026-10-23T20:00:00-04:00', declaration_basis='creator_declared_recording_start', evidence=[self.evidence], unresolved_reason='', qualification='', created_at=STAMP) self.events = dict(schema='wall-clock-events/v1', **self.metadata, events=[self.event]) def write_receipt(self, relative, value=None): path = self.root / relative if value is not None: path.parent.mkdir(parents=True, exist_ok=True) path.write_text(json.dumps(value) + '\n', encoding='utf-8') data = path.read_bytes() return dict(path=relative, size_bytes=len(data), sha256=hashlib.sha256(data).hexdigest()) def seal(self, previous=None): members = 'ledgers/2026-W43-active/' seal = dict(schema='wall-clock-ledger-seal/v1', **self.metadata, candidates=self.write_receipt(members + 'candidates.json', self.candidates), events=self.write_receipt(members + 'events.json', self.events), previous_seal_sha256=previous, created_at=STAMP) return self.write_receipt(members + 'SEAL.json', seal) def test_valid_minimal_week_passes(self): self.assertEqual(ledger.receipt(self.root, 'evidence.txt'), self.evidence) self.assertEqual(ledger.check_receipt(self.root, self.evidence), self.root / 'evidence.txt') self.assertEqual(ledger.validate_candidates(self.candidates), self.candidates['candidates']) self.assertEqual(ledger.validate_events(self.events), [self.event]) self.assertEqual(ledger.validate_seal(self.root, self.seal(), None), (self.candidates, self.events)) unresolved = copy.deepcopy(self.event) unresolved.update(status='timing_unresolved', declared_value='', declaration_basis='', evidence=[], unresolved_reason='missing_declaration') self.events['events'] = [unresolved] self.assertEqual(ledger.validate_events(self.events), [unresolved]) def test_unsafe_or_mismatched_receipt_fails(self): for path in ['', '.', '../evidence.txt', '/evidence.txt', './evidence.txt', 'a/../evidence.txt', 'a//b.txt', 'a\\b.txt', 'C:evidence.txt', 'evidence.txt/', 'clip.mp4', 'clip.MOV', 'image.png']: with self.subTest(path=path), self.assertRaises(ValueError): ledger.receipt(self.root, path) for field, value in [('size_bytes', 0), ('size_bytes', True), ('size_bytes', 1), ('sha256', 'A' * 64), ('sha256', '0' * 64), ('sha256', None)]: receipt = dict(self.evidence, **{field: value}) with self.subTest(field=field, value=value), self.assertRaises(ValueError): ledger.check_receipt(self.root, receipt) link_path = self.root / 'link.txt' try: link_path.symlink_to(self.root / 'evidence.txt') except OSError as exc: if getattr(exc, 'winerror', None) != 1314: raise link_path.write_text('placeholder', encoding='utf-8') real_is_symlink = Path.is_symlink with patch.object( Path, 'is_symlink', autospec=True, side_effect=lambda candidate: candidate.name == 'link.txt' or real_is_symlink(candidate), ): with self.assertRaises(ValueError): ledger.receipt(self.root, 'link.txt') else: with self.assertRaises(ValueError): ledger.receipt(self.root, 'link.txt') (self.root / 'empty.txt').write_text('', encoding='utf-8') with self.assertRaises(ValueError): ledger.receipt(self.root, 'empty.txt') def test_supported_claim_requires_text_evidence(self): for evidence in [[], [dict(self.evidence, path='clip.mp4')], [dict(self.evidence, size_bytes=0)]]: self.event['evidence'] = evidence with self.subTest(evidence=evidence), self.assertRaises(ValueError): ledger.validate_events(self.events) def test_media_path_components_are_rejected_before_filesystem_access(self): for relative in ['clip.mp4/evidence.txt', 'nested/clip.MOV/evidence.json', 'image.png/declarations.csv', 'audio.FLAC/notes.md', 'capture.mkv/SHA256SUMS', 'nested/clip.mp4/more/evidence.txt']: with self.subTest(path=relative), ExitStack() as guards: for method in ['is_symlink', 'stat', 'lstat', 'open', 'read_bytes']: guards.enter_context(patch.object( Path, method, side_effect=AssertionError( f'Filesystem access through Path.{method} is forbidden'))) with self.assertRaises(ValueError): ledger.receipt(self.root, relative) def test_unicode_controls_are_rejected_before_filesystem_access(self): # Cc boundaries plus format, surrogate, private-use and unassigned C categories. for character in ['\x00', '\x1f', '\x7f', '\x80', '\x9f', '\u200b', '\ud800', '\ue000', '\u0378']: with self.subTest(character=repr(character)), ExitStack() as guards: for method in ['is_symlink', 'stat', 'lstat', 'open', 'read_bytes']: guards.enter_context(patch.object(Path, method, side_effect=AssertionError( 'Rejected receipt path reached the filesystem'))) with self.assertRaises(ValueError): ledger.receipt(self.root, f'index{character}.csv') for character in [' ', '~', '\u00a0', 'é']: with self.subTest(character=character): self.assertEqual(ledger.relative_path(f'index{character}.csv'), Path(f'index{character}.csv')) def test_media_derived_basis_is_not_in_schema(self): for basis in ['encoded_media', 'encoded_pts', 'playback_duration', 'frame_count', 'frame_rate']: self.event['declaration_basis'] = basis with self.subTest(basis=basis), self.assertRaises(ValueError): ledger.validate_events(self.events) def test_only_declared_text_bases_pass(self): for basis in ['device_filename_interpreted_in_declared_timezone', 'creator_declared_recording_start', 'contemporaneous_capture_log']: self.event['declaration_basis'] = basis self.assertEqual(ledger.validate_events(self.events), [self.event]) def test_wrong_schemas_claims_status_and_revision_fail(self): for validator, packet in [(ledger.validate_candidates, self.candidates), (ledger.validate_events, self.events)]: for field, value in [('schema', 'wrong/v1'), ('source_revision', 'main'), ('source_revision', 'a' * 39), ('cohort', 'combined'), ('ingestion_week', '2026-W54')]: changed = dict(packet, **{field: value}) with self.subTest(field=field), self.assertRaises(ValueError): validator(changed) self.candidates['candidates'][0]['claim_type'] = 'recording_stop' with self.assertRaises(ValueError): ledger.validate_candidates(self.candidates) for field, value in [('claim_type', 'recording_stop'), ('status', 'supported'), ('event_type', 'replacement'), ('frame_count', 100)]: changed = dict(self.event, **{field: value}) with self.subTest(field=field), self.assertRaises(ValueError): ledger.validate_events(dict(self.events, events=[changed])) def test_duplicate_candidates_and_events_fail(self): self.candidates['candidates'] *= 2 with self.assertRaises(ValueError): ledger.validate_candidates(self.candidates) self.events['events'] *= 2 with self.assertRaises(ValueError): ledger.validate_events(self.events) def test_literal_time_requires_explicit_offset(self): for value in ['2026-10-23T20:00:00', '2026-10-23', '2026-02-30T20:00:00Z', '2026-10-23T20:00:00+99:00', '20261023T200000Z', '2026-10-23 20:00:00Z']: self.event['declared_value'] = value with self.subTest(value=value), self.assertRaises(ValueError): ledger.validate_events(self.events) self.event['declared_value'] = '2026-10-23T20:00:00Z' self.assertEqual(ledger.validate_events(self.events), [self.event]) def test_unresolved_reasons_and_event_references(self): self.event.update(status='timing_unresolved', declared_value='', declaration_basis='', evidence=[]) for reason in ['missing_declaration', 'conflicting_declarations', 'unverifiable_declaration']: self.event['unresolved_reason'] = reason self.assertEqual(ledger.validate_events(self.events), [self.event]) self.event['unresolved_reason'] = 'unknown' with self.assertRaises(ValueError): ledger.validate_events(self.events) self.event['unresolved_reason'] = 'missing_declaration' self.event['event_type'] = 'resolution' with self.assertRaises(ValueError): ledger.validate_events(self.events) self.event['prior_event_id'] = 'prior:record-1' self.assertEqual(ledger.validate_events(self.events), [self.event]) def test_seal_chain_and_member_tampering_fail(self): previous = 'a' * 64 declared = self.seal(previous) self.assertEqual(ledger.validate_seal(self.root, declared, previous), (self.candidates, self.events)) for prior in [None, 'b' * 64, 'not-a-digest']: with self.subTest(prior=prior), self.assertRaises(ValueError): ledger.validate_seal(self.root, declared, prior) (self.root / 'ledgers/2026-W43-active/events.json').write_text('{}', encoding='utf-8') with self.assertRaises(ValueError): ledger.validate_seal(self.root, declared, previous) def test_seal_binds_metadata_schema_and_evidence(self): for mutation in ['schema', 'metadata', 'evidence']: declared = self.seal() seal_path = self.root / declared['path'] seal = json.loads(seal_path.read_text(encoding='utf-8')) if mutation == 'schema': seal['schema'] = 'wrong/v1' elif mutation == 'metadata': seal['ledger_id'] = 'another-ledger' else: (self.root / 'evidence.txt').write_text('Changed declaration.\n', encoding='utf-8') declared = self.write_receipt(declared['path'], seal) with self.subTest(mutation=mutation), self.assertRaises(ValueError): ledger.validate_seal(self.root, declared, None) def projection_api(self): for name in ['reduce_events', 'coverage_summary', 'build', 'encode_json']: self.assertTrue(callable(getattr(ledger, name, None)), f'Missing projection API: {name}') def packet(self, name, week='2026-W43', cohort='active_ingest', count=1, unresolved=0): metadata = dict(self.metadata, ledger_id=name, ingestion_week=week, cohort=cohort) candidates, events = [], [] for index in range(count): rid = f'{name}-record-{index}' candidates.append(dict(record_id=rid, work_id='work-1', claim_type='recording_start')) event = copy.deepcopy(self.event) event.update(event_id=f'{name}:initial:{index}', record_id=rid) if index < unresolved: event.update(status='timing_unresolved', declared_value='', declaration_basis='', evidence=[], unresolved_reason='missing_declaration') events.append(event) return dict(seal=dict(path=f'ledgers/{name}/SEAL.json', size_bytes=1, sha256='a' * 64), candidates=dict(schema='wall-clock-candidates/v1', **metadata, source_files=[], candidates=candidates), events=dict(schema='wall-clock-events/v1', **metadata, events=events)) def update_packet(self, initial, name='resolution', week='2026-W44', event_type='resolution'): packet = self.packet(name, week, initial['candidates']['cohort'], count=0) event = copy.deepcopy(self.event) event.update(record_id=initial['events']['events'][0]['record_id'], event_id=f'{name}:update', event_type=event_type, prior_event_id=initial['events']['events'][0]['event_id'], created_at='2026-10-28T12:00:00Z') packet['events']['events'] = [event] return packet def register(self, packets): seals, previous = [], None for packet in packets: metadata = {field: packet['candidates'][field] for field in ledger.METADATA_FIELDS} directory = f'ledgers/{metadata["ledger_id"]}/' seal = dict(schema='wall-clock-ledger-seal/v1', **metadata, candidates=self.write_receipt(directory + 'candidates.json', packet['candidates']), events=self.write_receipt(directory + 'events.json', packet['events']), previous_seal_sha256=previous, created_at=STAMP) declared = self.write_receipt(directory + 'SEAL.json', seal) seals.append(declared) previous = declared['sha256'] self.write_receipt((ledger.PREFIX / 'sources.json').as_posix(), dict(schema='wall-clock-sources/v1', seals=seals)) self.commit_registry() return seals def git(self, *arguments): result = subprocess.run(['git', '-C', str(self.root), *arguments], capture_output=True, text=True, check=False) self.assertEqual(result.returncode, 0, result.stderr) return result.stdout.strip() def commit_registry(self): if not (self.root / '.git').exists(): self.git('init', '--quiet') self.git('add', (ledger.PREFIX / 'sources.json').as_posix()) self.git('-c', 'user.name=Ledger test', '-c', 'user.email=ledger@example.invalid', '-c', 'commit.gpgsign=false', 'commit', '--quiet', '--allow-empty', '-m', 'Trust registry checkpoint') def test_registry_tail_or_all_removal_preserves_generated_outputs(self): initial = self.packet('initial', unresolved=1) seals = self.register([initial, self.update_packet(initial)]) self.assertEqual(self.cli('--write').returncode, 0) destinations = [self.root / ledger.PREFIX / name for name in ['current.json', 'coverage.json']] before = [path.read_bytes() for path in destinations] for remaining in [seals[:-1], []]: self.write_receipt((ledger.PREFIX / 'sources.json').as_posix(), dict(schema='wall-clock-sources/v1', seals=remaining)) with self.subTest(remaining=len(remaining)): result = self.cli('--write') self.assertNotEqual(result.returncode, 0, 'Registry truncation was accepted') self.assertEqual([path.read_bytes() for path in destinations], before) def test_registry_legitimate_append_preserves_trusted_prefix(self): initial = self.packet('initial', unresolved=1) self.register([initial]) checkpoint = self.git('rev-parse', 'HEAD') self.assertEqual(self.cli('--write').returncode, 0) seals = self.register([initial, self.update_packet(initial)]) # The immutable prior revision still trusts only the first seal. result = self.cli('--write', '--prior-registry-revision', checkpoint) self.assertEqual(result.returncode, 0, result.stderr) current = json.loads((self.root / ledger.PREFIX / 'current.json').read_text()) self.assertEqual(current['source_seals'], seals) self.assertEqual(current['current'][0]['status'], 'timing_supported') self.assertEqual(len(current['current'][0]['history']), 2) def test_first_registry_requires_explicit_bootstrap(self): self.git('init', '--quiet') self.git('-c', 'user.name=Ledger test', '-c', 'user.email=ledger@example.invalid', '-c', 'commit.gpgsign=false', 'commit', '--quiet', '--allow-empty', '-m', 'Before registry') self.write_receipt((ledger.PREFIX / 'sources.json').as_posix(), dict(schema='wall-clock-sources/v1', seals=[])) self.assertNotEqual(self.cli('--write').returncode, 0) result = self.cli('--write', '--bootstrap') self.assertEqual(result.returncode, 0, result.stderr) current = json.loads((self.root / ledger.PREFIX / 'current.json').read_text()) self.assertEqual(current['current'], []) self.commit_registry() self.assertEqual(self.cli().returncode, 0) self.assertNotEqual(self.cli('--write', '--bootstrap').returncode, 0) def test_resolution_preserves_initial_event_and_changes_current_state(self): self.projection_api() initial = self.packet('initial', unresolved=1) update = self.update_packet(initial) packets = [initial, update] before = copy.deepcopy(packets) current = ledger.reduce_events(packets) self.assertEqual(packets, before) self.assertEqual(len(current), 1) row = current[0] self.assertEqual(row['status'], 'timing_supported') self.assertEqual(row['event_id'], 'resolution:update') self.assertEqual((row['cohort'], row['ingestion_week'], row['work_id']), ('active_ingest', '2026-W43', 'work-1')) self.assertEqual(row['history'], [ dict(event_id='initial:initial:0', ledger_id='initial', source_seal=initial['seal']), dict(event_id='resolution:update', ledger_id='resolution', source_seal=update['seal'])]) coverage = ledger.coverage_summary(packets, current) self.assertEqual(coverage['weekly'][0]['cohorts']['active_ingest']['unresolved'], 1) self.assertEqual(coverage['weekly'][1]['cohorts']['active_ingest']['candidates'], 0) self.assertEqual(coverage['weekly'][1]['cumulative']['active_ingest']['supported'], 1) self.assertEqual(coverage['cumulative']['active_ingest']['unresolved'], 0) # Returned values cannot mutate the immutable source packets. row['evidence'][0]['path'] = 'changed.txt' row['history'][0]['source_seal']['sha256'] = '0' * 64 self.assertEqual(packets, before) def test_duplicate_initial_or_stale_update_fails(self): self.projection_api() initial = self.packet('initial', unresolved=1) update = self.update_packet(initial) for mutation in ['second_initial', 'stale', 'cross_record', 'missing_initial', 'duplicate_event_id', 'duplicate_candidate', 'cross_cohort']: packets = copy.deepcopy([initial, update]) event = packets[1]['events']['events'][0] if mutation == 'second_initial': event.update(event_type='initial_classification', prior_event_id=None) elif mutation == 'stale': correction = self.update_packet(initial, 'correction', '2026-W45', 'correction') packets.append(correction) elif mutation == 'cross_record': other = self.packet('other', count=1) packets.insert(1, other) event['prior_event_id'] = other['events']['events'][0]['event_id'] elif mutation == 'missing_initial': packets = [packets[1]] elif mutation == 'duplicate_event_id': event['event_id'] = packets[0]['events']['events'][0]['event_id'] elif mutation == 'duplicate_candidate': packets[1]['candidates']['candidates'] = packets[0]['candidates']['candidates'] else: for member in ['candidates', 'events']: packets[1][member]['cohort'] = 'historical_backfill' with self.subTest(mutation=mutation), self.assertRaises(ValueError): ledger.reduce_events(packets) def test_active_ratio_gate_boundaries(self): self.projection_api() for unresolved, count, gate, decimal in [ (0, 0, 'no_candidates', '0.000000'), (3, 10, 'proceed_with_qualifications', '0.300000'), (4, 10, 'pause_systemic_timing_uncertainty', '0.400000'), (1, 3, 'pause_systemic_timing_uncertainty', '0.333333'), ]: packets = [self.packet('gate', count=count, unresolved=unresolved)] with self.subTest(unresolved=unresolved, count=count): coverage = ledger.coverage_summary(packets, ledger.reduce_events(packets)) active = coverage['cumulative']['active_ingest'] self.assertEqual((active['supported'], active['unresolved'], active['candidates']), (count - unresolved, unresolved, count)) self.assertEqual(active['unresolved_ratio'], dict(numerator=unresolved, denominator=count, decimal=decimal)) self.assertEqual(coverage['active_gate'], gate) def test_historical_ratio_never_controls_active_gate(self): self.projection_api() for active_unresolved, historical_unresolved, expected in [ (3, 100, 'proceed_with_qualifications'), (4, 0, 'pause_systemic_timing_uncertainty'), ]: packets = [self.packet('active', count=10, unresolved=active_unresolved), self.packet('historical', cohort='historical_backfill', count=100, unresolved=historical_unresolved)] with self.subTest(active_unresolved=active_unresolved): coverage = ledger.coverage_summary(packets, ledger.reduce_events(packets)) self.assertEqual(coverage['active_gate'], expected) self.assertEqual(coverage['cumulative']['historical_backfill']['candidates'], 100) self.assertEqual(coverage['non_governing']['candidates'], 110) def test_candidate_coverage_and_fixed_historical_membership(self): self.projection_api() for mutation in ['missing_classification', 'unknown_event', 'historical_growth', 'duplicate_ledger', 'out_of_order_week', 'metadata_mismatch']: initial = self.packet('initial', unresolved=1) packets = [initial] if mutation == 'missing_classification': initial['events']['events'] = [] elif mutation == 'unknown_event': initial['events']['events'][0]['record_id'] = 'unregistered' elif mutation == 'historical_growth': packets = [self.packet('history', cohort='historical_backfill'), self.packet('addition', '2026-W44', 'historical_backfill')] elif mutation == 'duplicate_ledger': packets.append(copy.deepcopy(initial)) elif mutation == 'out_of_order_week': packets.append(self.packet('older', '2026-W42')) else: initial['events']['cohort'] = 'historical_backfill' with self.subTest(mutation=mutation), self.assertRaises(ValueError): ledger.reduce_events(packets) def test_correction_chain_and_multiple_same_week_seals(self): self.projection_api() initial = self.packet('initial', unresolved=1) update = self.update_packet(initial) correction = self.update_packet(initial, 'correction', '2026-W45', 'correction') correction['events']['events'][0].update( prior_event_id='resolution:update', status='timing_unresolved', declared_value='', declaration_basis='', evidence=[], unresolved_reason='conflicting_declarations') extra = self.packet('extra', count=1) packets = [initial, extra, update, correction] current = ledger.reduce_events(packets) by_id = {row['record_id']: row for row in current} self.assertEqual(by_id['initial-record-0']['status'], 'timing_unresolved') self.assertEqual([ref['event_id'] for ref in by_id['initial-record-0']['history']], ['initial:initial:0', 'resolution:update', 'correction:update']) coverage = ledger.coverage_summary(packets, current) self.assertEqual([week['ingestion_week'] for week in coverage['weekly']], ['2026-W43', '2026-W44', '2026-W45']) self.assertEqual(coverage['weekly'][0]['cohorts']['active_ingest']['candidates'], 2) self.assertEqual(coverage['weekly'][0]['cumulative']['active_ingest']['unresolved'], 1) self.assertEqual(coverage['weekly'][1]['cumulative']['active_ingest']['unresolved'], 0) self.assertEqual(coverage['weekly'][2]['cumulative']['active_ingest']['unresolved'], 1) def test_projection_is_deterministic(self): self.projection_api() packets = [self.packet('initial', unresolved=1)] packets.append(self.update_packet(packets[0])) source_seals = self.register(packets) # Building projections is read-only, including in an arbitrary output root. with patch.object(Path, 'write_bytes', side_effect=AssertionError('Unexpected write')), \ patch.object(Path, 'write_text', side_effect=AssertionError('Unexpected write')): first = ledger.build(self.root) second = ledger.build(self.root) self.assertEqual(first, second) for projection, schema in zip(first, ['wall-clock-current/v1', 'wall-clock-coverage/v1']): self.assertEqual(projection['schema'], schema) self.assertEqual(projection['authority'], 'generated_projection_only') self.assertEqual(projection['source_seals'], source_seals) self.assertEqual(ledger.encode_json(projection), ledger.encode_json(second[first.index(projection)])) self.assertEqual(first[0]['current'][0]['history'][0]['source_seal'], source_seals[0]) self.assertEqual(ledger.encode_json(dict(z='é', a=1)), b'{\n "a": 1,\n "z": "\xc3\xa9"\n}\n') self.assertEqual(ledger.encode_json(dict(a=1, z='é')), ledger.encode_json(dict(z='é', a=1))) def test_registry_contract_and_chain_are_checked(self): self.projection_api() initial = self.packet('initial', unresolved=1) packets = [initial, self.update_packet(initial)] for mutation in ['schema', 'extra', 'duplicate', 'reorder', 'missing_first', 'tamper']: seals = self.register(packets) registry = dict(schema='wall-clock-sources/v1', seals=seals) if mutation == 'schema': registry['schema'] = 'wrong/v1' elif mutation == 'extra': registry['extra'] = True elif mutation == 'duplicate': registry['seals'].append(seals[0]) elif mutation == 'reorder': registry['seals'].reverse() elif mutation == 'missing_first': registry['seals'] = seals[1:] else: self.write_receipt('ledgers/resolution/events.json', {}) self.write_receipt((ledger.PREFIX / 'sources.json').as_posix(), registry) with self.subTest(mutation=mutation), self.assertRaises(ValueError): ledger.build(self.root) def test_empty_registry_has_explicit_zero_cohorts(self): self.projection_api() self.register([]) current, coverage = ledger.build(self.root) self.assertEqual(current['current'], []) self.assertEqual(coverage['weekly'], []) self.assertEqual(coverage['active_gate'], 'no_candidates') for cohort in ['active_ingest', 'historical_backfill']: self.assertEqual(coverage['cumulative'][cohort], dict( candidates=0, supported=0, unresolved=0, unresolved_ratio=dict(numerator=0, denominator=0, decimal='0.000000'))) def author_api(self): self.assertIsNotNone(author, 'Text-only ledger authoring is not implemented') return author def timing_index(self): rows = [dict(record_id='active-supported', work_id='work-1', file_path='/inaccessible/never-touch.mp4', filename_start_basis='device_filename_interpreted_in_declared_timezone', filename_start_local='2026-10-23T20:00:00-04:00', timing_evidence_path='evidence.txt', timing_evidence_sha256=self.evidence['sha256']), dict(record_id='active-unknown', work_id='', file_path='/inaccessible/never-touch.mp4', filename_start_basis='unknown', filename_start_local='', timing_evidence_path='evidence.txt', timing_evidence_sha256=self.evidence['sha256'])] relative = 'Standard_Time_Lapses/Provenance/Recording_Timing_Current/recording_timing.csv' self.write_csv(relative, rows) return relative, rows def write_csv(self, relative, rows): text = io.StringIO(newline='') writer = csv.DictWriter(text, fieldnames=list(rows[0]), lineterminator='\n') writer.writeheader() writer.writerows(rows) path = self.root / relative path.parent.mkdir(parents=True, exist_ok=True) path.write_text(text.getvalue(), encoding='utf-8') def cli(self, *arguments, script='wall_clock_declarations.py'): return subprocess.run([sys.executable, str(Path(__file__).parent / script), '--root', str(self.root), *arguments], capture_output=True, text=True, check=False) def test_bootstrap_reads_only_text_indexes(self): api = self.author_api() relative, _ = self.timing_index() # Inaccessible placeholder only: never create, stat, or open media. # Guard every Path filesystem entry used by receipt/authoring code. with ExitStack() as guards: for method in ['open', 'stat', 'lstat', 'is_symlink', 'read_bytes', 'read_text', 'exists', 'is_file', 'is_dir', 'iterdir', 'glob', 'rglob', 'resolve', 'mkdir']: original = getattr(Path, method) def guarded(path, *args, _original=original, **kwargs): if any(part.lower().endswith(tuple(ledger.MEDIA_SUFFIXES)) for part in path.parts): raise AssertionError('Attempted media filesystem access') return _original(path, *args, **kwargs) guards.enter_context(patch.object(Path, method, guarded)) paths = api.create_bootstrap(self.root, '2026-W43', REVISION, 'active_ingest', Path('ledgers/active-bootstrap')) self.assertEqual(paths, (self.root / 'ledgers/active-bootstrap/candidates.json', self.root / 'ledgers/active-bootstrap/events.json')) candidates, events = [json.loads(path.read_text(encoding='utf-8')) for path in paths] self.assertEqual(candidates['ledger_id'], 'active-bootstrap') preserved = 'ledgers/active-bootstrap/source_indexes/' + relative self.assertEqual(candidates['source_files'], [self.write_receipt(preserved)]) self.assertEqual((self.root / preserved).read_bytes(), (self.root / relative).read_bytes()) self.assertEqual(candidates['source_revision'], REVISION) self.assertEqual(candidates['candidates'], [ dict(record_id='active-supported', work_id='work-1', claim_type='recording_start'), dict(record_id='active-unknown', work_id='', claim_type='recording_start')]) by_id = {event['record_id']: event for event in events['events']} self.assertEqual(by_id['active-supported']['declared_value'], '2026-10-23T20:00:00-04:00') self.assertEqual(by_id['active-supported']['status'], 'timing_supported') self.assertEqual(by_id['active-supported']['evidence'], [self.evidence]) self.assertEqual(by_id['active-unknown']['status'], 'timing_unresolved') self.assertEqual(by_id['active-unknown']['declared_value'], '') self.assertEqual(by_id['active-unknown']['unresolved_reason'], 'missing_declaration') ledger.validate_candidates(candidates) ledger.validate_events(events) def test_historical_bootstrap_binds_only_two_indexes(self): api = self.author_api() paths = ['metadata.csv', 'Pre_Standard_Time_Lapses/metadata.csv'] for index, relative in enumerate(paths): self.write_csv(relative, [ dict(record_id=f'historical-{index}', work_id='', recording_start_basis='not_in_timing_snapshot', recording_start_local='2020-01-01T00:00:00Z', file_name='/inaccessible/never-touch.mp4'), dict(record_id=f'excluded-{index}', work_id='', recording_start_basis='unknown', recording_start_local='', file_name='/inaccessible/never-touch.mp4')]) candidates_path, events_path = api.create_bootstrap( self.root, '2026-W43', REVISION, 'historical_backfill', Path('ledgers/historical')) candidates = json.loads(candidates_path.read_text(encoding='utf-8')) events = json.loads(events_path.read_text(encoding='utf-8'))['events'] self.assertEqual(candidates['source_files'], [ self.write_receipt('ledgers/historical/source_indexes/' + path) for path in paths]) self.assertEqual([event['evidence'] for event in events], [[declared] for declared in candidates['source_files']]) self.assertEqual([row['record_id'] for row in candidates['candidates']], ['historical-0', 'historical-1']) self.assertEqual([event['status'] for event in events], ['timing_unresolved'] * 2) self.assertTrue(all(event['declared_value'] == '' for event in events)) def test_append_active_adds_only_new_metadata_candidates_and_preserves_source(self): api = self.author_api() initial = self.packet('initial', count=1, unresolved=1) historical = self.packet('history', cohort='historical_backfill', count=1, unresolved=1) self.register([initial, historical]) rows = [ dict(record_id='initial-record-0', work_id='old-active', recording_start_basis='device_filename_interpreted_in_declared_timezone'), dict(record_id='history-record-0', work_id='old-history', recording_start_basis='not_in_timing_snapshot'), dict(record_id='new-b', work_id='work-b', recording_start_basis='not_in_timing_snapshot'), dict(record_id='new-a', work_id='work-a', recording_start_basis='not_in_timing_snapshot'), ] self.write_csv('metadata.csv', rows) self.assertTrue(callable(getattr(api, 'create_active_append', None)), 'Missing incremental active-ingest authoring API') paths = api.create_active_append( self.root, '2026-W44', 'a' * 40, Path('ledgers/active-append')) candidates, events = [json.loads(path.read_text(encoding='utf-8')) for path in paths] preserved = 'ledgers/active-append/source_indexes/metadata.csv' declared = self.write_receipt(preserved) self.assertEqual(candidates['source_files'], [declared]) self.assertEqual((self.root / preserved).read_bytes(), (self.root / 'metadata.csv').read_bytes()) self.assertEqual(candidates['candidates'], [ dict(record_id='new-a', work_id='work-a', claim_type='recording_start'), dict(record_id='new-b', work_id='work-b', claim_type='recording_start'), ]) self.assertEqual([event['record_id'] for event in events['events']], ['new-a', 'new-b']) for event in events['events']: self.assertEqual((event['status'], event['event_type'], event['prior_event_id']), ('timing_unresolved', 'initial_classification', None)) self.assertEqual((event['declared_value'], event['declaration_basis']), ('', '')) self.assertEqual(event['unresolved_reason'], 'missing_declaration') self.assertEqual(event['evidence'], [declared]) self.assertTrue(event['qualification']) def test_append_active_rejects_no_new_duplicate_or_classified_rows(self): api = self.author_api() self.register([self.packet('initial', count=1, unresolved=1)]) cases = { 'no-new': [dict(record_id='initial-record-0', work_id='old', recording_start_basis='unknown')], 'duplicate': [ dict(record_id='new-record', work_id='work', recording_start_basis='not_in_timing_snapshot'), dict(record_id='new-record', work_id='work', recording_start_basis='not_in_timing_snapshot'), ], 'classified': [dict( record_id='new-record', work_id='work', recording_start_basis='device_filename_interpreted_in_declared_timezone')], 'blank-id': [dict(record_id='', work_id='work', recording_start_basis='not_in_timing_snapshot')], } for name, rows in cases.items(): self.write_csv('metadata.csv', rows) output = self.root / 'ledgers' / name with self.subTest(name=name), self.assertRaises(ValueError): api.create_active_append(self.root, '2026-W44', 'a' * 40, output) self.assertFalse(output.exists()) def test_append_active_rejects_unterminated_quoted_csv_before_output(self): api = self.author_api() self.register([self.packet('initial', count=1, unresolved=1)]) malformed = self.root / 'metadata.csv' malformed.write_text( 'record_id,work_id,recording_start_basis,notes\n' 'new-record,new-work,not_in_timing_snapshot,"unterminated\n', encoding='utf-8') output = self.root / 'ledgers/malformed-csv' with self.assertRaisesRegex(ValueError, 'Malformed CSV index: metadata.csv'): api.create_active_append(self.root, '2026-W44', 'a' * 40, output) self.assertFalse(output.exists()) def test_append_active_lifecycle_crosses_exact_active_pause_gate(self): api = self.author_api() active = self.packet('active-bootstrap', count=841, unresolved=234) historical = self.packet( 'historical-bootstrap', cohort='historical_backfill', count=492, unresolved=492) seals = self.register([active, historical]) rows = [dict(record_id=f'new-{index:02d}', work_id=f'work-{index:02d}', recording_start_basis='not_in_timing_snapshot') for index in range(51)] self.write_csv('metadata.csv', rows) paths = api.create_active_append( self.root, '2026-W44', 'a' * 40, Path('ledgers/active-append')) seals.append(api.seal_ledger(self.root, paths[0].parent, seals[-1])) self.write_receipt((ledger.PREFIX / 'sources.json').as_posix(), dict(schema='wall-clock-sources/v1', seals=seals)) result = self.cli('--write') self.assertEqual(result.returncode, 0, result.stderr) current, coverage = ledger.build(self.root) self.assertEqual(len(current['current']), 1384) self.assertEqual(coverage['cumulative']['active_ingest'], dict( candidates=892, supported=607, unresolved=285, unresolved_ratio=dict(numerator=285, denominator=892, decimal='0.319506'))) self.assertEqual(coverage['cumulative']['historical_backfill'], dict( candidates=492, supported=0, unresolved=492, unresolved_ratio=dict(numerator=492, denominator=492, decimal='1.000000'))) self.assertEqual(coverage['non_governing']['candidates'], 1384) self.assertEqual(coverage['active_gate'], 'pause_systemic_timing_uncertainty') def test_live_index_updates_preserve_sealed_sources_across_later_week(self): api = self.author_api() timing, rows = self.timing_index() for relative in ['metadata.csv', 'Pre_Standard_Time_Lapses/metadata.csv']: self.write_csv(relative, [dict(record_id=relative, work_id='', recording_start_basis='not_in_timing_snapshot')]) seals, preserved = [], {} for name, cohort in [('active', 'active_ingest'), ('history', 'historical_backfill')]: paths = api.create_bootstrap(self.root, '2026-W43', REVISION, cohort, Path('ledgers') / name) declared = api.seal_ledger(self.root, paths[0].parent, seals[-1] if seals else None) seals.append(declared) candidates = json.loads(paths[0].read_text()) for item in candidates['source_files']: preserved[item['path']] = (self.root / item['path']).read_bytes() for path in [*paths, self.root / declared['path']]: preserved[path.relative_to(self.root).as_posix()] = path.read_bytes() registry_path = (ledger.PREFIX / 'sources.json').as_posix() self.write_receipt(registry_path, dict(schema='wall-clock-sources/v1', seals=seals)) self.commit_registry() before = ledger.build(self.root) self.write_csv(timing, [dict(rows[0], record_id='later-supported')]) for relative in ['metadata.csv', 'Pre_Standard_Time_Lapses/metadata.csv']: self.write_csv(relative, [dict(record_id='later-indexed', work_id='', recording_start_basis='unknown')]) # Both old seals must still validate after all three live indexes change. try: after = ledger.build(self.root) except ValueError as error: self.fail(f'Live index update invalidated immutable evidence: {error}') self.assertEqual(after, before) paths = api.create_bootstrap(self.root, '2026-W44', 'a' * 40, 'active_ingest', Path('ledgers/later')) seals.append(api.seal_ledger(self.root, paths[0].parent, seals[-1])) self.write_receipt(registry_path, dict(schema='wall-clock-sources/v1', seals=seals)) self.assertEqual(self.cli('--write').returncode, 0) current, coverage = ledger.build(self.root) self.assertEqual(coverage['weekly'][0], before[1]['weekly'][0]) self.assertEqual(coverage['cumulative']['active_ingest']['candidates'], 3) self.assertEqual(coverage['cumulative']['historical_backfill']['candidates'], 2) self.assertEqual(len(current['current']), 5) for relative, data in preserved.items(): self.assertEqual((self.root / relative).read_bytes(), data) def test_preserved_source_mutation_rejects_seal(self): api = self.author_api() live, _ = self.timing_index() live_path = self.root / live live_path.write_bytes(b'\xef\xbb\xbf' + live_path.read_bytes().replace(b'\n', b'\r\n')) paths = api.create_bootstrap(self.root, '2026-W43', REVISION, 'active_ingest', Path('ledgers/active')) declared = api.seal_ledger(self.root, paths[0].parent, None) source = json.loads(paths[0].read_text())['source_files'][0] self.assertNotEqual(source['path'], live, 'Seal still binds a mutable live index') self.assertEqual((self.root / source['path']).read_bytes(), (self.root / live).read_bytes()) (self.root / source['path']).write_bytes(b'corrupt preserved text\n') with self.assertRaisesRegex(ValueError, 'Receipt mismatch'): ledger.validate_seal(self.root, declared, None) def test_sealing_and_validation_reject_live_source_receipts(self): api = self.author_api() live, _ = self.timing_index() paths = api.create_bootstrap(self.root, '2026-W43', REVISION, 'active_ingest', Path('ledgers/active')) candidates = json.loads(paths[0].read_text()) candidates['source_files'] = [ledger.receipt(self.root, live)] self.write_receipt('ledgers/active/candidates.json', candidates) with self.assertRaisesRegex(ValueError, 'preserved source index'): api.seal_ledger(self.root, paths[0].parent, None) self.assertFalse((paths[0].parent / 'SEAL.json').exists()) seal = dict(schema='wall-clock-ledger-seal/v1', **{field: candidates[field] for field in ledger.METADATA_FIELDS}, candidates=ledger.receipt(self.root, 'ledgers/active/candidates.json'), events=ledger.receipt(self.root, 'ledgers/active/events.json'), previous_seal_sha256=None, created_at=STAMP) declared = self.write_receipt('ledgers/active/SEAL.json', seal) with self.assertRaisesRegex(ValueError, 'preserved source index'): ledger.validate_seal(self.root, declared, None) def test_authoring_refuses_existing_output(self): api = self.author_api() self.timing_index() output = self.root / 'ledgers/existing' output.mkdir(parents=True) marker = output / 'events.json' marker.write_bytes(b'Keep this draft.\n') with self.assertRaises((ValueError, FileExistsError)): api.create_bootstrap(self.root, '2026-W43', REVISION, 'active_ingest', output) self.assertEqual(marker.read_bytes(), b'Keep this draft.\n') self.assertFalse((output / 'candidates.json').exists()) fresh = self.root / 'ledgers/fresh' api.create_bootstrap(self.root, '2026-W43', REVISION, 'active_ingest', fresh) sealed = api.seal_ledger(self.root, fresh, None) before = (self.root / sealed['path']).read_bytes() with self.assertRaises((ValueError, FileExistsError)): api.seal_ledger(self.root, fresh, None) self.assertEqual((self.root / sealed['path']).read_bytes(), before) def test_sealing_validates_members_and_previous_seal(self): api = self.author_api() self.timing_index() first = Path('ledgers/first') second = Path('ledgers/second') api.create_bootstrap(self.root, '2026-W43', REVISION, 'active_ingest', first) prior = api.seal_ledger(self.root, first, None) api.create_bootstrap(self.root, '2026-W44', REVISION, 'active_ingest', second) sealed = api.seal_ledger(self.root, second, prior) ledger.validate_seal(self.root, sealed, prior['sha256']) packet = json.loads((self.root / sealed['path']).read_text(encoding='utf-8')) self.assertEqual(packet['previous_seal_sha256'], prior['sha256']) third = Path('ledgers/third') api.create_bootstrap(self.root, '2026-W44', REVISION, 'active_ingest', third) (self.root / 'evidence.txt').write_text('changed evidence\n', encoding='utf-8') with self.assertRaises(ValueError): api.seal_ledger(self.root, third, None) self.assertFalse((self.root / third / 'SEAL.json').exists()) def test_bootstrap_invalid_input_leaves_no_draft(self): api = self.author_api() relative, original = self.timing_index() for mutation in ['digest', 'basis', 'time', 'duplicate', 'media_evidence']: rows = copy.deepcopy(original) if mutation == 'digest': rows[0]['timing_evidence_sha256'] = '0' * 64 elif mutation == 'basis': rows[0]['filename_start_basis'] = 'encoded_pts' elif mutation == 'time': rows[0]['filename_start_local'] = '2026-10-23T20:00:00' elif mutation == 'duplicate': rows.append(dict(rows[0])) else: rows[0]['timing_evidence_path'] = '/inaccessible/never-touch.mp4' self.write_csv(relative, rows) output = self.root / 'ledgers' / mutation with self.subTest(mutation=mutation), self.assertRaises(ValueError): api.create_bootstrap(self.root, '2026-W43', REVISION, 'active_ingest', output) self.assertFalse(output.exists()) def test_bootstrap_cli(self): self.timing_index() result = subprocess.run([ sys.executable, str(Path(__file__).parent / 'create_wall_clock_ledger.py'), 'bootstrap', '--root', str(self.root), '--week', '2026-W43', '--source-revision', REVISION, '--cohort', 'active_ingest', '--output', 'ledgers/cli'], capture_output=True, text=True, check=False) self.assertEqual(result.returncode, 0, result.stderr) self.assertTrue((self.root / 'ledgers/cli/events.json').is_file()) def test_append_active_cli(self): self.register([self.packet('initial', count=1, unresolved=1)]) self.write_csv('metadata.csv', [ dict(record_id='initial-record-0', work_id='old', recording_start_basis='unknown'), dict(record_id='new-record', work_id='new-work', recording_start_basis='not_in_timing_snapshot'), ]) result = subprocess.run([ sys.executable, str(Path(__file__).parent / 'create_wall_clock_ledger.py'), 'append-active', '--root', str(self.root), '--week', '2026-W44', '--source-revision', 'a' * 40, '--output', 'ledgers/active-append'], capture_output=True, text=True, check=False) self.assertEqual(result.returncode, 0, result.stderr) candidates = json.loads( (self.root / 'ledgers/active-append/candidates.json').read_text(encoding='utf-8')) self.assertEqual([row['record_id'] for row in candidates['candidates']], ['new-record']) def test_registered_seal_tamper_fails(self): seals = self.register([self.packet('registered')]) seal_path = self.root / seals[0]['path'] seal_path.write_bytes(seal_path.read_bytes() + b' ') for mode in [[], ['--write']]: result = self.cli(*mode) self.assertNotEqual(result.returncode, 0, 'Tampered registered seal was accepted') self.assertFalse((self.root / ledger.PREFIX / 'current.json').exists()) def test_unregistered_ledger_is_not_incorporated(self): self.register([self.packet('registered')]) self.write_receipt('ledgers/unregistered/SEAL.json', {'invalid': 'never read'}) result = self.cli('--write') self.assertEqual(result.returncode, 0, result.stderr) path = self.root / ledger.PREFIX / 'current.json' self.assertTrue(path.is_file(), 'Write CLI did not create current.json') current = json.loads(path.read_text(encoding='utf-8')) self.assertEqual([row['record_id'] for row in current['current']], ['registered-record-0']) self.assertEqual(self.cli().returncode, 0) def test_invalid_input_does_not_change_generated_outputs(self): self.register([self.packet('registered')]) destinations = [self.root / ledger.PREFIX / name for name in ['current.json', 'coverage.json']] for path, data in zip(destinations, [b'old current\n', b'old coverage\n']): path.write_bytes(data) (self.root / 'ledgers/registered/events.json').write_text('{}\n', encoding='utf-8') result = self.cli('--write') self.assertNotEqual(result.returncode, 0, 'Invalid member was accepted') self.assertEqual([path.read_bytes() for path in destinations], [b'old current\n', b'old coverage\n']) def test_check_cli_rejects_stale_or_missing_exact_bytes_without_writing(self): self.register([]) result = self.cli() self.assertNotEqual(result.returncode, 0, 'Missing generated outputs were accepted') self.assertEqual(self.cli('--write').returncode, 0) destinations = [self.root / ledger.PREFIX / name for name in ['current.json', 'coverage.json']] for path in destinations: canonical = path.read_bytes() path.write_bytes(canonical + b' ') before = [item.read_bytes() for item in destinations] self.assertNotEqual(self.cli().returncode, 0) self.assertEqual([item.read_bytes() for item in destinations], before) self.assertEqual(self.cli('--write').returncode, 0) self.assertEqual(path.read_bytes(), canonical) def test_invalid_second_destination_does_not_partially_write_first(self): self.register([]) current = self.root / ledger.PREFIX / 'current.json' current.write_bytes(b'preserve current\n') (self.root / ledger.PREFIX / 'coverage.json').mkdir() result = self.cli('--write') self.assertNotEqual(result.returncode, 0) self.assertEqual(current.read_bytes(), b'preserve current\n') def test_sealing_rejects_malformed_predecessor_before_writing(self): api = self.author_api() self.timing_index() directory = Path('ledgers/draft') api.create_bootstrap(self.root, '2026-W43', REVISION, 'active_ingest', directory) previous = self.write_receipt('ledgers/prior/SEAL.json', ['not a seal object']) with self.assertRaises(Exception) as caught: api.seal_ledger(self.root, directory, previous) self.assertIsInstance(caught.exception, ValueError) self.assertFalse((self.root / directory / 'SEAL.json').exists()) def test_authoring_rejects_unsafe_output_paths_and_symlinks(self): api = self.author_api() self.timing_index() alias_path = self.root / 'alias' symlink_patch = None try: alias_path.symlink_to(self.root / 'destination') except OSError as exc: if getattr(exc, 'winerror', None) != 1314: raise alias_path.mkdir() real_is_symlink = Path.is_symlink symlink_patch = patch.object( Path, 'is_symlink', autospec=True, side_effect=lambda candidate: candidate.name == 'alias' or real_is_symlink(candidate), ) with ExitStack() as guards: if symlink_patch is not None: guards.enter_context(symlink_patch) for directory in [Path('../escape'), Path('/inaccessible/outside'), Path('never-touch.mp4/ledger'), Path('alias/draft')]: with self.subTest(directory=directory), self.assertRaises(ValueError): api.create_bootstrap(self.root, '2026-W43', REVISION, 'active_ingest', directory) def test_seal_cli_returns_receipt_without_registering(self): api = self.author_api() self.timing_index() api.create_bootstrap(self.root, '2026-W43', REVISION, 'active_ingest', Path('ledgers/cli')) result = subprocess.run([ sys.executable, str(Path(__file__).parent / 'create_wall_clock_ledger.py'), 'seal', '--root', str(self.root), '--ledger-dir', 'ledgers/cli'], capture_output=True, text=True, check=False) self.assertEqual(result.returncode, 0, result.stderr) sealed = json.loads(result.stdout) ledger.validate_seal(self.root, sealed, None) self.assertEqual(sealed['path'], 'ledgers/cli/SEAL.json') self.assertFalse((self.root / ledger.PREFIX / 'sources.json').exists()) if __name__ == '__main__': unittest.main()