Tim Maxwell commited on
Commit ·
c849289
1
Parent(s): f0ce09f
feat: define sealed wall-clock evidence ledgers
Browse files
Standard_Time_Lapses/Provenance/Wall_Clock_Declarations/SCHEMA.md
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Wall-clock declaration ledger schemas, version 1
|
| 2 |
+
|
| 3 |
+
These immutable weekly text packets classify only `claim_type=recording_start`.
|
| 4 |
+
`timing_supported` means a traceable claim-specific observation. It does not
|
| 5 |
+
establish calibrated clock accuracy, elapsed drawing time, continuous capture,
|
| 6 |
+
or a recording stop. Encoded PTS, playback duration, frame count, and frame rate
|
| 7 |
+
cannot create or strengthen a claim and have no declaration basis in this schema.
|
| 8 |
+
|
| 9 |
+
## Common packet metadata
|
| 10 |
+
|
| 11 |
+
Every packet has exactly its documented fields. All three packet types contain:
|
| 12 |
+
|
| 13 |
+
| Field | Contract |
|
| 14 |
+
| --- | --- |
|
| 15 |
+
| `schema` | Exact versioned schema below |
|
| 16 |
+
| `ledger_id` | Nonempty ID matching `[A-Za-z0-9][A-Za-z0-9._-]*` |
|
| 17 |
+
| `ingestion_week` | Valid ISO week in `YYYY-Www` form |
|
| 18 |
+
| `source_revision` | Lowercase 40-hex Git source revision |
|
| 19 |
+
| `cohort` | `active_ingest` or `historical_backfill` |
|
| 20 |
+
|
| 21 |
+
Candidate, event, and seal metadata must agree within a sealed week. The cohort
|
| 22 |
+
identifies membership; active-ingest and historical-backfill denominators remain
|
| 23 |
+
separate. Candidate snapshots may be empty in weeks containing only updates.
|
| 24 |
+
|
| 25 |
+
## Text receipts
|
| 26 |
+
|
| 27 |
+
A receipt is exactly `{ "path": "...", "size_bytes": 123, "sha256": "..." }`.
|
| 28 |
+
`path` is a canonical repository-relative POSIX path: no absolute paths, `..`,
|
| 29 |
+
dot components, repeated or trailing separators, backslashes, colons, or control
|
| 30 |
+
characters. Text artifacts use `.json`, `.csv`, `.md`, `.txt` (case-insensitive),
|
| 31 |
+
or the basename `SHA256SUMS`. Other names are rejected before filesystem access.
|
| 32 |
+
All path components must be free of symlinks. Artifacts must decode as UTF-8
|
| 33 |
+
(an optional BOM is accepted). `size_bytes` is a positive integer, never a boolean;
|
| 34 |
+
`sha256` is lowercase 64-hex. Both bind the exact original bytes without newline,
|
| 35 |
+
encoding, or whitespace normalization. Media payloads must never be opened,
|
| 36 |
+
probed, statted, decoded, or hashed.
|
| 37 |
+
|
| 38 |
+
`receipt(root, relative)` computes a text receipt. `check_receipt(root, declared)`
|
| 39 |
+
verifies a receipt and returns its filesystem path. Invalid data raises `ValueError`.
|
| 40 |
+
|
| 41 |
+
## Candidate packet: `wall-clock-candidates/v1`
|
| 42 |
+
|
| 43 |
+
In addition to common metadata, the packet has `source_files` (a list of text
|
| 44 |
+
receipts binding source indexes) and `candidates` (a list). Each candidate has
|
| 45 |
+
exactly `record_id` (nonblank string), `work_id` (string, empty if unknown), and
|
| 46 |
+
`claim_type` (`recording_start`). `(record_id, claim_type)` must be unique.
|
| 47 |
+
Source receipt paths must be unique. `validate_candidates(packet)` returns the
|
| 48 |
+
validated candidate list without changing it.
|
| 49 |
+
|
| 50 |
+
## Event packet: `wall-clock-events/v1`
|
| 51 |
+
|
| 52 |
+
In addition to common metadata, the packet has an ordered `events` list.
|
| 53 |
+
Every event has exactly these fields:
|
| 54 |
+
|
| 55 |
+
| Field | Contract |
|
| 56 |
+
| --- | --- |
|
| 57 |
+
| `event_id` | Nonblank string, unique within the packet |
|
| 58 |
+
| `record_id` | Nonblank stable record identity |
|
| 59 |
+
| `claim_type` | `recording_start` |
|
| 60 |
+
| `status` | `timing_supported` or `timing_unresolved` |
|
| 61 |
+
| `event_type` | `initial_classification`, `resolution`, or `correction` |
|
| 62 |
+
| `prior_event_id` | `null` for initial events; nonblank preceding event ID for updates |
|
| 63 |
+
| `declared_value` | Explicit-offset ISO-8601 literal for supported events; otherwise `""` |
|
| 64 |
+
| `declaration_basis` | Accepted basis below for supported events; otherwise `""` |
|
| 65 |
+
| `evidence` | List of text receipts with unique paths; nonempty for supported events |
|
| 66 |
+
| `unresolved_reason` | Accepted unresolved reason below; `""` for supported events |
|
| 67 |
+
| `qualification` | String containing any claim qualification; may be empty |
|
| 68 |
+
| `created_at` | Explicit-offset ISO-8601 creation timestamp |
|
| 69 |
+
|
| 70 |
+
The only supported bases are `device_filename_interpreted_in_declared_timezone`,
|
| 71 |
+
`creator_declared_recording_start`, and `contemporaneous_capture_log`. An
|
| 72 |
+
unresolved event requires `missing_declaration`, `conflicting_declarations`, or
|
| 73 |
+
`unverifiable_declaration`. Unresolved evidence may be empty or record the text
|
| 74 |
+
behind a conflict. Timestamp literals use `YYYY-MM-DDTHH:MM:SS[.fraction]` followed
|
| 75 |
+
by `Z` or `+HH:MM` / `-HH:MM`; values are retained literally, never inferred.
|
| 76 |
+
|
| 77 |
+
`validate_events(packet)` returns the validated event list. It checks event
|
| 78 |
+
shape, receipt shape, timestamps, and local event-ID uniqueness. Current-event
|
| 79 |
+
references, candidate coverage, cross-ledger uniqueness, and state transitions
|
| 80 |
+
belong to the later cumulative reduction layer. A self-reference is invalid.
|
| 81 |
+
|
| 82 |
+
## Seal packet: `wall-clock-ledger-seal/v1`
|
| 83 |
+
|
| 84 |
+
In addition to common metadata, the seal has `candidates` and `events` (receipts
|
| 85 |
+
for sibling `candidates.json` and `events.json`), `previous_seal_sha256` (the
|
| 86 |
+
preceding registered seal's exact digest, or `null` for the first seal), and
|
| 87 |
+
`created_at` (an explicit-offset ISO-8601 timestamp). Its filename is `SEAL.json`.
|
| 88 |
+
The ordered registry pins each seal with its own text receipt. Files and seals
|
| 89 |
+
are immutable after registration; later resolution or correction adds an event
|
| 90 |
+
in a later ledger rather than rewriting existing packets.
|
| 91 |
+
|
| 92 |
+
`validate_seal(root, declared_seal, previous_sha256)` validates the seal receipt,
|
| 93 |
+
prior digest, both member receipts and schemas, matching metadata, source-index
|
| 94 |
+
receipts, and every event evidence receipt. It returns `(candidates_packet,
|
| 95 |
+
events_packet)`. Registry order supplies `previous_sha256`; reordering, omission,
|
| 96 |
+
or mutation in the middle of the registered chain fails validation. Anchoring
|
| 97 |
+
the registry and detecting removal of its final entry are registry-level duties.
|
| 98 |
+
All validation is read-only. No authoring or generated projections are defined
|
| 99 |
+
by this foundational contract.
|
tools/test_wall_clock_declarations.py
ADDED
|
@@ -0,0 +1,186 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Text-only contracts for sealed recording-start declaration ledgers."""
|
| 2 |
+
import copy
|
| 3 |
+
import hashlib
|
| 4 |
+
import json
|
| 5 |
+
import tempfile
|
| 6 |
+
import unittest
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
|
| 9 |
+
try:
|
| 10 |
+
from tools import wall_clock_declarations as ledger
|
| 11 |
+
except ImportError:
|
| 12 |
+
ledger = None
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
REVISION = '6fed0d073bdc307cdb81ea1dd8d4db6b1ecb04c7'
|
| 16 |
+
STAMP = '2026-10-24T12:00:00+00:00'
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class WallClockDeclarationTests(unittest.TestCase):
|
| 20 |
+
def setUp(self):
|
| 21 |
+
self.assertIsNotNone(ledger, 'Wall-clock declaration validation is not implemented')
|
| 22 |
+
self.directory = tempfile.TemporaryDirectory()
|
| 23 |
+
self.addCleanup(self.directory.cleanup)
|
| 24 |
+
self.root = Path(self.directory.name)
|
| 25 |
+
(self.root / 'evidence.txt').write_text('Creator declared recording start.\n', encoding='utf-8')
|
| 26 |
+
self.evidence = self.write_receipt('evidence.txt')
|
| 27 |
+
self.metadata = dict(ledger_id='2026-W43-active', ingestion_week='2026-W43',
|
| 28 |
+
source_revision=REVISION, cohort='active_ingest')
|
| 29 |
+
self.candidates = dict(schema='wall-clock-candidates/v1', **self.metadata,
|
| 30 |
+
source_files=[self.evidence], candidates=[dict(
|
| 31 |
+
record_id='record-1', work_id='', claim_type='recording_start')])
|
| 32 |
+
self.event = dict(event_id='2026-W43-active:record-1:initial', record_id='record-1',
|
| 33 |
+
claim_type='recording_start', status='timing_supported',
|
| 34 |
+
event_type='initial_classification', prior_event_id=None,
|
| 35 |
+
declared_value='2026-10-23T20:00:00-04:00',
|
| 36 |
+
declaration_basis='creator_declared_recording_start',
|
| 37 |
+
evidence=[self.evidence], unresolved_reason='', qualification='',
|
| 38 |
+
created_at=STAMP)
|
| 39 |
+
self.events = dict(schema='wall-clock-events/v1', **self.metadata, events=[self.event])
|
| 40 |
+
|
| 41 |
+
def write_receipt(self, relative, value=None):
|
| 42 |
+
path = self.root / relative
|
| 43 |
+
if value is not None:
|
| 44 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 45 |
+
path.write_text(json.dumps(value) + '\n', encoding='utf-8')
|
| 46 |
+
data = path.read_bytes()
|
| 47 |
+
return dict(path=relative, size_bytes=len(data), sha256=hashlib.sha256(data).hexdigest())
|
| 48 |
+
|
| 49 |
+
def seal(self, previous=None):
|
| 50 |
+
members = 'ledgers/2026-W43-active/'
|
| 51 |
+
seal = dict(schema='wall-clock-ledger-seal/v1', **self.metadata,
|
| 52 |
+
candidates=self.write_receipt(members + 'candidates.json', self.candidates),
|
| 53 |
+
events=self.write_receipt(members + 'events.json', self.events),
|
| 54 |
+
previous_seal_sha256=previous, created_at=STAMP)
|
| 55 |
+
return self.write_receipt(members + 'SEAL.json', seal)
|
| 56 |
+
|
| 57 |
+
def test_valid_minimal_week_passes(self):
|
| 58 |
+
self.assertEqual(ledger.receipt(self.root, 'evidence.txt'), self.evidence)
|
| 59 |
+
self.assertEqual(ledger.check_receipt(self.root, self.evidence), self.root / 'evidence.txt')
|
| 60 |
+
self.assertEqual(ledger.validate_candidates(self.candidates), self.candidates['candidates'])
|
| 61 |
+
self.assertEqual(ledger.validate_events(self.events), [self.event])
|
| 62 |
+
self.assertEqual(ledger.validate_seal(self.root, self.seal(), None),
|
| 63 |
+
(self.candidates, self.events))
|
| 64 |
+
unresolved = copy.deepcopy(self.event)
|
| 65 |
+
unresolved.update(status='timing_unresolved', declared_value='', declaration_basis='',
|
| 66 |
+
evidence=[], unresolved_reason='missing_declaration')
|
| 67 |
+
self.events['events'] = [unresolved]
|
| 68 |
+
self.assertEqual(ledger.validate_events(self.events), [unresolved])
|
| 69 |
+
|
| 70 |
+
def test_unsafe_or_mismatched_receipt_fails(self):
|
| 71 |
+
for path in ['', '.', '../evidence.txt', '/evidence.txt', './evidence.txt',
|
| 72 |
+
'a/../evidence.txt', 'a//b.txt', 'a\\b.txt', 'C:evidence.txt',
|
| 73 |
+
'evidence.txt/', 'clip.mp4', 'clip.MOV', 'image.png']:
|
| 74 |
+
with self.subTest(path=path), self.assertRaises(ValueError):
|
| 75 |
+
ledger.receipt(self.root, path)
|
| 76 |
+
for field, value in [('size_bytes', 0), ('size_bytes', True), ('size_bytes', 1),
|
| 77 |
+
('sha256', 'A' * 64), ('sha256', '0' * 64), ('sha256', None)]:
|
| 78 |
+
receipt = dict(self.evidence, **{field: value})
|
| 79 |
+
with self.subTest(field=field, value=value), self.assertRaises(ValueError):
|
| 80 |
+
ledger.check_receipt(self.root, receipt)
|
| 81 |
+
(self.root / 'link.txt').symlink_to(self.root / 'evidence.txt')
|
| 82 |
+
with self.assertRaises(ValueError):
|
| 83 |
+
ledger.receipt(self.root, 'link.txt')
|
| 84 |
+
(self.root / 'empty.txt').write_text('', encoding='utf-8')
|
| 85 |
+
with self.assertRaises(ValueError):
|
| 86 |
+
ledger.receipt(self.root, 'empty.txt')
|
| 87 |
+
|
| 88 |
+
def test_supported_claim_requires_text_evidence(self):
|
| 89 |
+
for evidence in [[], [dict(self.evidence, path='clip.mp4')],
|
| 90 |
+
[dict(self.evidence, size_bytes=0)]]:
|
| 91 |
+
self.event['evidence'] = evidence
|
| 92 |
+
with self.subTest(evidence=evidence), self.assertRaises(ValueError):
|
| 93 |
+
ledger.validate_events(self.events)
|
| 94 |
+
|
| 95 |
+
def test_media_derived_basis_is_not_in_schema(self):
|
| 96 |
+
for basis in ['encoded_media', 'encoded_pts', 'playback_duration', 'frame_count', 'frame_rate']:
|
| 97 |
+
self.event['declaration_basis'] = basis
|
| 98 |
+
with self.subTest(basis=basis), self.assertRaises(ValueError):
|
| 99 |
+
ledger.validate_events(self.events)
|
| 100 |
+
|
| 101 |
+
def test_only_declared_text_bases_pass(self):
|
| 102 |
+
for basis in ['device_filename_interpreted_in_declared_timezone',
|
| 103 |
+
'creator_declared_recording_start', 'contemporaneous_capture_log']:
|
| 104 |
+
self.event['declaration_basis'] = basis
|
| 105 |
+
self.assertEqual(ledger.validate_events(self.events), [self.event])
|
| 106 |
+
|
| 107 |
+
def test_wrong_schemas_claims_status_and_revision_fail(self):
|
| 108 |
+
for validator, packet in [(ledger.validate_candidates, self.candidates),
|
| 109 |
+
(ledger.validate_events, self.events)]:
|
| 110 |
+
for field, value in [('schema', 'wrong/v1'), ('source_revision', 'main'),
|
| 111 |
+
('source_revision', 'a' * 39), ('cohort', 'combined'),
|
| 112 |
+
('ingestion_week', '2026-W54')]:
|
| 113 |
+
changed = dict(packet, **{field: value})
|
| 114 |
+
with self.subTest(field=field), self.assertRaises(ValueError):
|
| 115 |
+
validator(changed)
|
| 116 |
+
self.candidates['candidates'][0]['claim_type'] = 'recording_stop'
|
| 117 |
+
with self.assertRaises(ValueError):
|
| 118 |
+
ledger.validate_candidates(self.candidates)
|
| 119 |
+
for field, value in [('claim_type', 'recording_stop'), ('status', 'supported'),
|
| 120 |
+
('event_type', 'replacement'), ('frame_count', 100)]:
|
| 121 |
+
changed = dict(self.event, **{field: value})
|
| 122 |
+
with self.subTest(field=field), self.assertRaises(ValueError):
|
| 123 |
+
ledger.validate_events(dict(self.events, events=[changed]))
|
| 124 |
+
|
| 125 |
+
def test_duplicate_candidates_and_events_fail(self):
|
| 126 |
+
self.candidates['candidates'] *= 2
|
| 127 |
+
with self.assertRaises(ValueError):
|
| 128 |
+
ledger.validate_candidates(self.candidates)
|
| 129 |
+
self.events['events'] *= 2
|
| 130 |
+
with self.assertRaises(ValueError):
|
| 131 |
+
ledger.validate_events(self.events)
|
| 132 |
+
|
| 133 |
+
def test_literal_time_requires_explicit_offset(self):
|
| 134 |
+
for value in ['2026-10-23T20:00:00', '2026-10-23', '2026-02-30T20:00:00Z',
|
| 135 |
+
'2026-10-23T20:00:00+99:00', '20261023T200000Z', '2026-10-23 20:00:00Z']:
|
| 136 |
+
self.event['declared_value'] = value
|
| 137 |
+
with self.subTest(value=value), self.assertRaises(ValueError):
|
| 138 |
+
ledger.validate_events(self.events)
|
| 139 |
+
self.event['declared_value'] = '2026-10-23T20:00:00Z'
|
| 140 |
+
self.assertEqual(ledger.validate_events(self.events), [self.event])
|
| 141 |
+
|
| 142 |
+
def test_unresolved_reasons_and_event_references(self):
|
| 143 |
+
self.event.update(status='timing_unresolved', declared_value='', declaration_basis='', evidence=[])
|
| 144 |
+
for reason in ['missing_declaration', 'conflicting_declarations', 'unverifiable_declaration']:
|
| 145 |
+
self.event['unresolved_reason'] = reason
|
| 146 |
+
self.assertEqual(ledger.validate_events(self.events), [self.event])
|
| 147 |
+
self.event['unresolved_reason'] = 'unknown'
|
| 148 |
+
with self.assertRaises(ValueError):
|
| 149 |
+
ledger.validate_events(self.events)
|
| 150 |
+
self.event['unresolved_reason'] = 'missing_declaration'
|
| 151 |
+
self.event['event_type'] = 'resolution'
|
| 152 |
+
with self.assertRaises(ValueError):
|
| 153 |
+
ledger.validate_events(self.events)
|
| 154 |
+
self.event['prior_event_id'] = 'prior:record-1'
|
| 155 |
+
self.assertEqual(ledger.validate_events(self.events), [self.event])
|
| 156 |
+
|
| 157 |
+
def test_seal_chain_and_member_tampering_fail(self):
|
| 158 |
+
previous = 'a' * 64
|
| 159 |
+
declared = self.seal(previous)
|
| 160 |
+
self.assertEqual(ledger.validate_seal(self.root, declared, previous),
|
| 161 |
+
(self.candidates, self.events))
|
| 162 |
+
for prior in [None, 'b' * 64, 'not-a-digest']:
|
| 163 |
+
with self.subTest(prior=prior), self.assertRaises(ValueError):
|
| 164 |
+
ledger.validate_seal(self.root, declared, prior)
|
| 165 |
+
(self.root / 'ledgers/2026-W43-active/events.json').write_text('{}', encoding='utf-8')
|
| 166 |
+
with self.assertRaises(ValueError):
|
| 167 |
+
ledger.validate_seal(self.root, declared, previous)
|
| 168 |
+
|
| 169 |
+
def test_seal_binds_metadata_schema_and_evidence(self):
|
| 170 |
+
for mutation in ['schema', 'metadata', 'evidence']:
|
| 171 |
+
declared = self.seal()
|
| 172 |
+
seal_path = self.root / declared['path']
|
| 173 |
+
seal = json.loads(seal_path.read_text(encoding='utf-8'))
|
| 174 |
+
if mutation == 'schema':
|
| 175 |
+
seal['schema'] = 'wrong/v1'
|
| 176 |
+
elif mutation == 'metadata':
|
| 177 |
+
seal['ledger_id'] = 'another-ledger'
|
| 178 |
+
else:
|
| 179 |
+
(self.root / 'evidence.txt').write_text('Changed declaration.\n', encoding='utf-8')
|
| 180 |
+
declared = self.write_receipt(declared['path'], seal)
|
| 181 |
+
with self.subTest(mutation=mutation), self.assertRaises(ValueError):
|
| 182 |
+
ledger.validate_seal(self.root, declared, None)
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
if __name__ == '__main__':
|
| 186 |
+
unittest.main()
|
tools/wall_clock_declarations.py
ADDED
|
@@ -0,0 +1,234 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Validate immutable, text-only recording-start declaration ledger packets.
|
| 2 |
+
|
| 3 |
+
Receipt validation deliberately admits only named text formats and rejects
|
| 4 |
+
symlinks before reading. No media path is probed, statted, opened, or hashed.
|
| 5 |
+
"""
|
| 6 |
+
from __future__ import annotations
|
| 7 |
+
|
| 8 |
+
import hashlib
|
| 9 |
+
import json
|
| 10 |
+
import re
|
| 11 |
+
from datetime import date, datetime
|
| 12 |
+
from pathlib import Path, PurePosixPath
|
| 13 |
+
|
| 14 |
+
PREFIX = Path('Standard_Time_Lapses/Provenance/Wall_Clock_Declarations')
|
| 15 |
+
SUPPORTED_BASES = frozenset({
|
| 16 |
+
'device_filename_interpreted_in_declared_timezone',
|
| 17 |
+
'creator_declared_recording_start',
|
| 18 |
+
'contemporaneous_capture_log',
|
| 19 |
+
})
|
| 20 |
+
UNRESOLVED_REASONS = frozenset({
|
| 21 |
+
'missing_declaration', 'conflicting_declarations', 'unverifiable_declaration',
|
| 22 |
+
})
|
| 23 |
+
METADATA_FIELDS = {'ledger_id', 'ingestion_week', 'source_revision', 'cohort'}
|
| 24 |
+
TEXT_SUFFIXES = {'.json', '.csv', '.md', '.txt'}
|
| 25 |
+
EVENT_FIELDS = {
|
| 26 |
+
'event_id', 'record_id', 'claim_type', 'status', 'event_type',
|
| 27 |
+
'prior_event_id', 'declared_value', 'declaration_basis', 'evidence',
|
| 28 |
+
'unresolved_reason', 'qualification', 'created_at',
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def require(condition, message):
|
| 33 |
+
if not condition:
|
| 34 |
+
raise ValueError(message)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def _fields(value, expected, description):
|
| 38 |
+
require(isinstance(value, dict) and set(value) == expected,
|
| 39 |
+
f'Unexpected or missing {description} fields')
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def _text(value, description, allow_empty=False):
|
| 43 |
+
require(isinstance(value, str) and (allow_empty or bool(value.strip())),
|
| 44 |
+
f'Invalid {description}')
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def _digest(value):
|
| 48 |
+
require(isinstance(value, str) and re.fullmatch(r'[0-9a-f]{64}', value),
|
| 49 |
+
'Invalid receipt SHA-256')
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def relative_path(value):
|
| 53 |
+
"""Reject unsafe and non-text names before any filesystem operation."""
|
| 54 |
+
_text(value, 'receipt path')
|
| 55 |
+
path = PurePosixPath(value)
|
| 56 |
+
require(value != '.' and not path.is_absolute() and '..' not in path.parts
|
| 57 |
+
and '\\' not in value and ':' not in value
|
| 58 |
+
and not any(ord(character) < 32 for character in value), 'Unsafe receipt path')
|
| 59 |
+
require(path.as_posix() == value, 'Noncanonical receipt path')
|
| 60 |
+
require(path.suffix.lower() in TEXT_SUFFIXES or path.name == 'SHA256SUMS',
|
| 61 |
+
'Receipt must reference a text artifact')
|
| 62 |
+
return Path(value)
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def _validate_receipt(declared):
|
| 66 |
+
_fields(declared, {'path', 'size_bytes', 'sha256'}, 'receipt')
|
| 67 |
+
path = relative_path(declared['path'])
|
| 68 |
+
_digest(declared['sha256'])
|
| 69 |
+
require(type(declared['size_bytes']) is int and declared['size_bytes'] > 0,
|
| 70 |
+
'Invalid receipt size')
|
| 71 |
+
return path
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def receipt(root: Path, relative: str) -> dict[str, object]:
|
| 75 |
+
path = relative_path(relative)
|
| 76 |
+
target = Path(root)
|
| 77 |
+
# Never follow a text-named symlink into a media payload or out of root.
|
| 78 |
+
for part in path.parts:
|
| 79 |
+
target = target / part
|
| 80 |
+
require(not target.is_symlink(), 'Symlink receipt path is forbidden')
|
| 81 |
+
try:
|
| 82 |
+
data = target.read_bytes()
|
| 83 |
+
data.decode('utf-8-sig')
|
| 84 |
+
except (OSError, UnicodeError) as error:
|
| 85 |
+
raise ValueError(f'Cannot read UTF-8 text artifact: {relative}') from error
|
| 86 |
+
require(bool(data), 'Invalid receipt size')
|
| 87 |
+
return dict(path=relative, size_bytes=len(data), sha256=hashlib.sha256(data).hexdigest())
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def check_receipt(root: Path, declared: dict[str, object]) -> Path:
|
| 91 |
+
path = _validate_receipt(declared)
|
| 92 |
+
require(receipt(root, declared['path']) == declared,
|
| 93 |
+
f'Receipt mismatch: {declared["path"]}')
|
| 94 |
+
return Path(root) / path
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def _literal_time(value, description):
|
| 98 |
+
_text(value, description)
|
| 99 |
+
require(re.fullmatch(
|
| 100 |
+
r'\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})', value),
|
| 101 |
+
f'{description} requires an explicit-offset ISO-8601 literal')
|
| 102 |
+
try:
|
| 103 |
+
parsed = datetime.fromisoformat(value.replace('Z', '+00:00'))
|
| 104 |
+
except ValueError as error:
|
| 105 |
+
raise ValueError(f'Invalid {description}') from error
|
| 106 |
+
# datetime accepts oversized minute components by normalizing the offset.
|
| 107 |
+
require(value.endswith('Z') or (int(value[-5:-3]) <= 23 and int(value[-2:]) <= 59),
|
| 108 |
+
f'Invalid {description} offset')
|
| 109 |
+
require(parsed.utcoffset() is not None, f'Missing {description} offset')
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def _metadata(packet, schema, extra_fields):
|
| 113 |
+
_fields(packet, {'schema'} | METADATA_FIELDS | extra_fields, 'packet')
|
| 114 |
+
require(packet['schema'] == schema, 'Wrong wall-clock schema')
|
| 115 |
+
_text(packet['ledger_id'], 'ledger ID')
|
| 116 |
+
require(re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9._-]*', packet['ledger_id']), 'Unsafe ledger ID')
|
| 117 |
+
revision = packet['source_revision']
|
| 118 |
+
require(isinstance(revision, str) and re.fullmatch(r'[0-9a-f]{40}', revision),
|
| 119 |
+
'Invalid source revision')
|
| 120 |
+
week = packet['ingestion_week']
|
| 121 |
+
require(isinstance(week, str) and re.fullmatch(r'\d{4}-W\d{2}', week), 'Invalid ingestion week')
|
| 122 |
+
try:
|
| 123 |
+
date.fromisocalendar(int(week[:4]), int(week[-2:]), 1)
|
| 124 |
+
except ValueError as error:
|
| 125 |
+
raise ValueError('Invalid ingestion week') from error
|
| 126 |
+
require(packet['cohort'] in ('active_ingest', 'historical_backfill'), 'Invalid cohort')
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def _receipts(value):
|
| 130 |
+
require(isinstance(value, list), 'Evidence receipts must be a list')
|
| 131 |
+
paths = set()
|
| 132 |
+
for declared in value:
|
| 133 |
+
_validate_receipt(declared)
|
| 134 |
+
require(declared['path'] not in paths, 'Duplicate evidence receipt')
|
| 135 |
+
paths.add(declared['path'])
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def _identity(item):
|
| 139 |
+
_text(item['record_id'], 'record ID')
|
| 140 |
+
require(item['claim_type'] == 'recording_start', 'Unsupported claim type')
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def validate_candidates(packet: dict[str, object]) -> list[dict[str, object]]:
|
| 144 |
+
_metadata(packet, 'wall-clock-candidates/v1', {'source_files', 'candidates'})
|
| 145 |
+
_receipts(packet['source_files'])
|
| 146 |
+
rows = packet['candidates']
|
| 147 |
+
require(isinstance(rows, list), 'Candidates must be a list')
|
| 148 |
+
seen = set()
|
| 149 |
+
for row in rows:
|
| 150 |
+
_fields(row, {'record_id', 'work_id', 'claim_type'}, 'candidate')
|
| 151 |
+
_identity(row)
|
| 152 |
+
_text(row['work_id'], 'work ID', allow_empty=True)
|
| 153 |
+
key = row['record_id'], row['claim_type']
|
| 154 |
+
require(key not in seen, 'Duplicate candidate key')
|
| 155 |
+
seen.add(key)
|
| 156 |
+
return rows
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def validate_events(packet: dict[str, object]) -> list[dict[str, object]]:
|
| 160 |
+
_metadata(packet, 'wall-clock-events/v1', {'events'})
|
| 161 |
+
rows = packet['events']
|
| 162 |
+
require(isinstance(rows, list), 'Events must be a list')
|
| 163 |
+
seen = set()
|
| 164 |
+
for row in rows:
|
| 165 |
+
_fields(row, EVENT_FIELDS, 'event')
|
| 166 |
+
_identity(row)
|
| 167 |
+
_text(row['event_id'], 'event ID')
|
| 168 |
+
require(row['event_id'] not in seen, 'Duplicate event ID')
|
| 169 |
+
seen.add(row['event_id'])
|
| 170 |
+
require(row['event_type'] in ('initial_classification', 'resolution', 'correction'),
|
| 171 |
+
'Invalid event type')
|
| 172 |
+
if row['event_type'] == 'initial_classification':
|
| 173 |
+
require(row['prior_event_id'] is None, 'Initial event cannot have a prior event')
|
| 174 |
+
else:
|
| 175 |
+
_text(row['prior_event_id'], 'prior event ID')
|
| 176 |
+
require(row['prior_event_id'] != row['event_id'], 'Self-referencing event')
|
| 177 |
+
_literal_time(row['created_at'], 'creation timestamp')
|
| 178 |
+
_text(row['qualification'], 'qualification', allow_empty=True)
|
| 179 |
+
_receipts(row['evidence'])
|
| 180 |
+
require(row['status'] in ('timing_supported', 'timing_unresolved'), 'Invalid timing status')
|
| 181 |
+
if row['status'] == 'timing_supported':
|
| 182 |
+
_literal_time(row['declared_value'], 'declared value')
|
| 183 |
+
require(isinstance(row['declaration_basis'], str)
|
| 184 |
+
and row['declaration_basis'] in SUPPORTED_BASES, 'Unsupported declaration basis')
|
| 185 |
+
require(bool(row['evidence']), 'Supported claim requires text evidence')
|
| 186 |
+
require(row['unresolved_reason'] == '', 'Supported claim has unresolved reason')
|
| 187 |
+
else:
|
| 188 |
+
require(isinstance(row['unresolved_reason'], str)
|
| 189 |
+
and row['unresolved_reason'] in UNRESOLVED_REASONS, 'Invalid unresolved reason')
|
| 190 |
+
require(row['declared_value'] == '' and row['declaration_basis'] == '',
|
| 191 |
+
'Unresolved event cannot assert a supported declaration')
|
| 192 |
+
return rows
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
def _json_packet(root, declared):
|
| 196 |
+
path = check_receipt(root, declared)
|
| 197 |
+
try:
|
| 198 |
+
return json.loads(path.read_text(encoding='utf-8-sig'))
|
| 199 |
+
except (OSError, UnicodeError, json.JSONDecodeError) as error:
|
| 200 |
+
raise ValueError(f'Invalid JSON packet: {declared["path"]}') from error
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
def validate_seal(root: Path, declared_seal: dict[str, object],
|
| 204 |
+
previous_sha256: str | None) -> tuple[dict[str, object], dict[str, object]]:
|
| 205 |
+
"""Verify a registered seal and all text receipts before returning members.
|
| 206 |
+
|
| 207 |
+
The caller supplies the preceding registered seal's digest in registry order;
|
| 208 |
+
the first seal requires None. Event-history reduction is a separate layer.
|
| 209 |
+
"""
|
| 210 |
+
if previous_sha256 is not None:
|
| 211 |
+
_digest(previous_sha256)
|
| 212 |
+
seal = _json_packet(root, declared_seal)
|
| 213 |
+
_metadata(seal, 'wall-clock-ledger-seal/v1',
|
| 214 |
+
{'candidates', 'events', 'previous_seal_sha256', 'created_at'})
|
| 215 |
+
_literal_time(seal['created_at'], 'seal creation timestamp')
|
| 216 |
+
require(seal['previous_seal_sha256'] == previous_sha256, 'Prior seal chain mismatch')
|
| 217 |
+
directory = relative_path(declared_seal['path']).parent
|
| 218 |
+
require(Path(declared_seal['path']).name == 'SEAL.json', 'Unexpected seal filename')
|
| 219 |
+
members = []
|
| 220 |
+
for name, validator in [('candidates', validate_candidates), ('events', validate_events)]:
|
| 221 |
+
declared = seal[name]
|
| 222 |
+
member_path = _validate_receipt(declared)
|
| 223 |
+
require(member_path == directory / f'{name}.json', 'Unexpected sealed member path')
|
| 224 |
+
packet = _json_packet(root, declared)
|
| 225 |
+
validator(packet)
|
| 226 |
+
require(all(packet[key] == seal[key] for key in METADATA_FIELDS), 'Sealed metadata mismatch')
|
| 227 |
+
members.append(packet)
|
| 228 |
+
candidates, events = members
|
| 229 |
+
for declared in candidates['source_files']:
|
| 230 |
+
check_receipt(root, declared)
|
| 231 |
+
for event in events['events']:
|
| 232 |
+
for declared in event['evidence']:
|
| 233 |
+
check_receipt(root, declared)
|
| 234 |
+
return candidates, events
|