File size: 22,818 Bytes
82789c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
"""Validate immutable, text-only recording-start declaration ledger packets.

Receipt validation deliberately admits only named text formats and rejects
symlinks before reading. No media path is probed, statted, opened, or hashed.
"""
from __future__ import annotations

import argparse
import hashlib
import json
import re
import subprocess
import unicodedata
from copy import deepcopy
from datetime import date, datetime
from pathlib import Path, PurePosixPath

PREFIX = Path('Standard_Time_Lapses/Provenance/Wall_Clock_Declarations')
SUPPORTED_BASES = frozenset({
    'device_filename_interpreted_in_declared_timezone',
    'creator_declared_recording_start',
    'contemporaneous_capture_log',
})
UNRESOLVED_REASONS = frozenset({
    'missing_declaration', 'conflicting_declarations', 'unverifiable_declaration',
})
METADATA_FIELDS = {'ledger_id', 'ingestion_week', 'source_revision', 'cohort'}
TEXT_SUFFIXES = {'.json', '.csv', '.md', '.txt'}
MEDIA_SUFFIXES = {
    '.mp4', '.mov', '.mkv', '.avi', '.webm', '.m4v', '.mpg', '.mpeg', '.mts',
    '.m2ts', '.wmv', '.flv', '.3gp', '.3g2', '.vob', '.ogv', '.mxf',
    '.mp3', '.wav', '.flac', '.m4a', '.aac', '.wma', '.aiff', '.aif', '.aifc',
    '.opus', '.ogg', '.oga', '.png', '.jpg', '.jpeg', '.gif', '.webp', '.bmp',
    '.tif', '.tiff', '.heic', '.heif', '.avif', '.svg', '.ico', '.apng',
    '.raw', '.dng', '.cr2', '.nef', '.arw', '.raf', '.psd', '.exr', '.tga',
}
EVENT_FIELDS = {
    'event_id', 'record_id', 'claim_type', 'status', 'event_type',
    'prior_event_id', 'declared_value', 'declaration_basis', 'evidence',
    'unresolved_reason', 'qualification', 'created_at',
}


def require(condition, message):
    if not condition:
        raise ValueError(message)


def _fields(value, expected, description):
    require(isinstance(value, dict) and set(value) == expected,
            f'Unexpected or missing {description} fields')


def _text(value, description, allow_empty=False):
    require(isinstance(value, str) and (allow_empty or bool(value.strip())),
            f'Invalid {description}')


def _digest(value):
    require(isinstance(value, str) and re.fullmatch(r'[0-9a-f]{64}', value),
            'Invalid receipt SHA-256')


def relative_path(value):
    """Reject unsafe and non-text names before any filesystem operation."""
    _text(value, 'receipt path')
    path = PurePosixPath(value)
    require(value != '.' and not path.is_absolute() and '..' not in path.parts
            and '\\' not in value and ':' not in value
            and not any(unicodedata.category(character).startswith('C') for character in value),
            'Unsafe receipt path')
    require(path.as_posix() == value, 'Noncanonical receipt path')
    require(not any(part.lower().endswith(tuple(MEDIA_SUFFIXES)) for part in path.parts),
            'Receipt path contains a media component')
    require(path.suffix.lower() in TEXT_SUFFIXES or path.name == 'SHA256SUMS',
            'Receipt must reference a text artifact')
    return Path(value)


def _validate_receipt(declared):
    _fields(declared, {'path', 'size_bytes', 'sha256'}, 'receipt')
    path = relative_path(declared['path'])
    _digest(declared['sha256'])
    require(type(declared['size_bytes']) is int and declared['size_bytes'] > 0,
            'Invalid receipt size')
    return path


def receipt(root: Path, relative: str) -> dict[str, object]:
    path = relative_path(relative)
    target = Path(root)
    # Never follow a text-named symlink into a media payload or out of root.
    for part in path.parts:
        target = target / part
        require(not target.is_symlink(), 'Symlink receipt path is forbidden')
    try:
        data = target.read_bytes()
        data.decode('utf-8-sig')
    except (OSError, UnicodeError) as error:
        raise ValueError(f'Cannot read UTF-8 text artifact: {relative}') from error
    require(bool(data), 'Invalid receipt size')
    return dict(path=relative, size_bytes=len(data), sha256=hashlib.sha256(data).hexdigest())


def check_receipt(root: Path, declared: dict[str, object]) -> Path:
    path = _validate_receipt(declared)
    require(receipt(root, declared['path']) == declared,
            f'Receipt mismatch: {declared["path"]}')
    return Path(root) / path


def _literal_time(value, description):
    _text(value, description)
    require(re.fullmatch(
        r'\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})', value),
        f'{description} requires an explicit-offset ISO-8601 literal')
    try:
        parsed = datetime.fromisoformat(value.replace('Z', '+00:00'))
    except ValueError as error:
        raise ValueError(f'Invalid {description}') from error
    # datetime accepts oversized minute components by normalizing the offset.
    require(value.endswith('Z') or (int(value[-5:-3]) <= 23 and int(value[-2:]) <= 59),
            f'Invalid {description} offset')
    require(parsed.utcoffset() is not None, f'Missing {description} offset')


def _metadata(packet, schema, extra_fields):
    _fields(packet, {'schema'} | METADATA_FIELDS | extra_fields, 'packet')
    require(packet['schema'] == schema, 'Wrong wall-clock schema')
    _text(packet['ledger_id'], 'ledger ID')
    require(re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9._-]*', packet['ledger_id']), 'Unsafe ledger ID')
    revision = packet['source_revision']
    require(isinstance(revision, str) and re.fullmatch(r'[0-9a-f]{40}', revision),
            'Invalid source revision')
    week = packet['ingestion_week']
    require(isinstance(week, str) and re.fullmatch(r'\d{4}-W\d{2}', week), 'Invalid ingestion week')
    try:
        date.fromisocalendar(int(week[:4]), int(week[-2:]), 1)
    except ValueError as error:
        raise ValueError('Invalid ingestion week') from error
    require(packet['cohort'] in ('active_ingest', 'historical_backfill'), 'Invalid cohort')


def _receipts(value):
    require(isinstance(value, list), 'Evidence receipts must be a list')
    paths = set()
    for declared in value:
        _validate_receipt(declared)
        require(declared['path'] not in paths, 'Duplicate evidence receipt')
        paths.add(declared['path'])


def _identity(item):
    _text(item['record_id'], 'record ID')
    require(item['claim_type'] == 'recording_start', 'Unsupported claim type')


def validate_candidates(packet: dict[str, object]) -> list[dict[str, object]]:
    _metadata(packet, 'wall-clock-candidates/v1', {'source_files', 'candidates'})
    _receipts(packet['source_files'])
    rows = packet['candidates']
    require(isinstance(rows, list), 'Candidates must be a list')
    seen = set()
    for row in rows:
        _fields(row, {'record_id', 'work_id', 'claim_type'}, 'candidate')
        _identity(row)
        _text(row['work_id'], 'work ID', allow_empty=True)
        key = row['record_id'], row['claim_type']
        require(key not in seen, 'Duplicate candidate key')
        seen.add(key)
    return rows


def validate_events(packet: dict[str, object]) -> list[dict[str, object]]:
    _metadata(packet, 'wall-clock-events/v1', {'events'})
    rows = packet['events']
    require(isinstance(rows, list), 'Events must be a list')
    seen = set()
    for row in rows:
        _fields(row, EVENT_FIELDS, 'event')
        _identity(row)
        _text(row['event_id'], 'event ID')
        require(row['event_id'] not in seen, 'Duplicate event ID')
        seen.add(row['event_id'])
        require(row['event_type'] in ('initial_classification', 'resolution', 'correction'),
                'Invalid event type')
        if row['event_type'] == 'initial_classification':
            require(row['prior_event_id'] is None, 'Initial event cannot have a prior event')
        else:
            _text(row['prior_event_id'], 'prior event ID')
            require(row['prior_event_id'] != row['event_id'], 'Self-referencing event')
        _literal_time(row['created_at'], 'creation timestamp')
        _text(row['qualification'], 'qualification', allow_empty=True)
        _receipts(row['evidence'])
        require(row['status'] in ('timing_supported', 'timing_unresolved'), 'Invalid timing status')
        if row['status'] == 'timing_supported':
            _literal_time(row['declared_value'], 'declared value')
            require(isinstance(row['declaration_basis'], str)
                    and row['declaration_basis'] in SUPPORTED_BASES, 'Unsupported declaration basis')
            require(bool(row['evidence']), 'Supported claim requires text evidence')
            require(row['unresolved_reason'] == '', 'Supported claim has unresolved reason')
        else:
            require(isinstance(row['unresolved_reason'], str)
                    and row['unresolved_reason'] in UNRESOLVED_REASONS, 'Invalid unresolved reason')
            require(row['declared_value'] == '' and row['declaration_basis'] == '',
                    'Unresolved event cannot assert a supported declaration')
    return rows


def _json_packet(root, declared):
    path = check_receipt(root, declared)
    try:
        return json.loads(path.read_text(encoding='utf-8-sig'))
    except (OSError, UnicodeError, json.JSONDecodeError) as error:
        raise ValueError(f'Invalid JSON packet: {declared["path"]}') from error


def check_source_files(root, candidates, directory):
    """Bind source indexes to immutable copies retaining their original paths."""
    for declared in candidates['source_files']:
        path = _validate_receipt(declared)
        try:
            original = path.relative_to(directory / 'source_indexes')
        except ValueError as error:
            raise ValueError('Expected a preserved source index inside this ledger') from error
        relative_path(original.as_posix())
        check_receipt(root, declared)


def validate_seal(root: Path, declared_seal: dict[str, object],
                  previous_sha256: str | None) -> tuple[dict[str, object], dict[str, object]]:
    """Verify a registered seal and all text receipts before returning members.

    The caller supplies the preceding registered seal's digest in registry order;
    the first seal requires None. Event-history reduction is a separate layer.
    """
    if previous_sha256 is not None:
        _digest(previous_sha256)
    seal = _json_packet(root, declared_seal)
    _metadata(seal, 'wall-clock-ledger-seal/v1',
              {'candidates', 'events', 'previous_seal_sha256', 'created_at'})
    _literal_time(seal['created_at'], 'seal creation timestamp')
    require(seal['previous_seal_sha256'] == previous_sha256, 'Prior seal chain mismatch')
    directory = relative_path(declared_seal['path']).parent
    require(Path(declared_seal['path']).name == 'SEAL.json', 'Unexpected seal filename')
    members = []
    for name, validator in [('candidates', validate_candidates), ('events', validate_events)]:
        declared = seal[name]
        member_path = _validate_receipt(declared)
        require(member_path == directory / f'{name}.json', 'Unexpected sealed member path')
        packet = _json_packet(root, declared)
        validator(packet)
        require(all(packet[key] == seal[key] for key in METADATA_FIELDS), 'Sealed metadata mismatch')
        members.append(packet)
    candidates, events = members
    check_source_files(root, candidates, directory)
    for event in events['events']:
        for declared in event['evidence']:
            check_receipt(root, declared)
    return candidates, events


COHORTS = ('active_ingest', 'historical_backfill')


def _reduce_snapshots(ledgers):
    """Reduce registry order, retaining a snapshot at the close of each week.

    Each input is {seal: receipt, candidates: packet, events: packet}. Candidate
    membership is introduced once, and every newly introduced key must receive
    its initial classification in that same ledger. Historical membership is
    fixed by the first historical packet; later packets can only update it.
    """
    members, state = {}, {}
    ledger_ids, event_ids = set(), set()
    historical_registered = False
    week, snapshots = None, []
    for packet in ledgers:
        _fields(packet, {'seal', 'candidates', 'events'}, 'reduction input')
        _validate_receipt(packet['seal'])
        candidates, events = packet['candidates'], packet['events']
        rows = validate_candidates(candidates)
        changes = validate_events(events)
        require(all(candidates[field] == events[field] for field in METADATA_FIELDS),
                'Ledger member metadata mismatch')
        ledger_id, cohort = candidates['ledger_id'], candidates['cohort']
        require(ledger_id not in ledger_ids, 'Duplicate ledger ID')
        ledger_ids.add(ledger_id)
        next_week = candidates['ingestion_week']
        require(week is None or next_week >= week, 'Ingestion weeks are out of order')
        if week is not None and next_week != week:
            snapshots.append((week, [state[key] for key in sorted(state)]))
        week = next_week
        if cohort == 'historical_backfill':
            require(not historical_registered or not rows, 'Historical membership is fixed')
            historical_registered = True
        introduced = set()
        for candidate in rows:
            key = candidate['record_id'], candidate['claim_type']
            require(key not in members, 'Duplicate candidate across ledgers')
            members[key] = dict(work_id=candidate['work_id'], cohort=cohort,
                                ingestion_week=week)
            introduced.add(key)
        for event in changes:
            key = event['record_id'], event['claim_type']
            require(key in members, 'Event has no registered candidate')
            require(members[key]['cohort'] == cohort, 'Event changes candidate cohort')
            require(event['event_id'] not in event_ids, 'Duplicate event ID across ledgers')
            event_ids.add(event['event_id'])
            prior = state.get(key)
            if event['event_type'] == 'initial_classification':
                require(prior is None, 'Duplicate initial classification')
            else:
                require(prior is not None and event['prior_event_id'] == prior['event_id'],
                        'Update must reference the current event for its candidate')
            history = [] if prior is None else prior['history']
            reference = dict(event_id=event['event_id'], ledger_id=ledger_id,
                             source_seal=deepcopy(packet['seal']))
            state[key] = dict(deepcopy(event), **members[key], history=history + [reference])
        require(all(key in state for key in introduced), 'Candidate lacks initial classification')
    if week is not None:
        snapshots.append((week, [state[key] for key in sorted(state)]))
    return [state[key] for key in sorted(state)], snapshots


def reduce_events(ledgers: list[dict[str, object]]) -> list[dict[str, object]]:
    """Return one current claim per key without changing source packets.

    History references remain in registered event order, even though current
    rows are sorted by record ID and claim type for deterministic encoding.
    """
    current, _ = _reduce_snapshots(ledgers)
    return current


def _counts(rows):
    candidates = len(rows)
    unresolved = sum(row['status'] == 'timing_unresolved' for row in rows)
    # Six places, truncated using integers; display precision never sets a gate.
    scaled = unresolved * 1_000_000 // candidates if candidates else 0
    ratio = dict(numerator=unresolved, denominator=candidates,
                 decimal=f'{scaled // 1_000_000}.{scaled % 1_000_000:06d}')
    return dict(supported=candidates - unresolved, unresolved=unresolved,
                candidates=candidates, unresolved_ratio=ratio)


def _cohort_counts(rows):
    return {cohort: _counts([row for row in rows if row['cohort'] == cohort])
            for cohort in COHORTS}


def _active_gate(counts):
    if counts['candidates'] == 0:
        return 'no_candidates'
    if counts['unresolved'] * 10 > counts['candidates'] * 3:
        return 'pause_systemic_timing_uncertainty'
    return 'proceed_with_qualifications'


def coverage_summary(ledgers: list[dict[str, object]],
                     current: list[dict[str, object]]) -> dict[str, object]:
    """Report sealed weekly snapshots and the latest cohort-specific coverage.

    `weekly[].cohorts` describes candidates introduced during that week at its
    close. `weekly[].cumulative` includes all candidates known at that close.
    Later updates change later cumulative snapshots, never earlier weeks.
    """
    expected, snapshots = _reduce_snapshots(ledgers)
    require(current == expected, 'Current state differs from registered event reduction')
    weekly = []
    for week, rows in snapshots:
        cumulative = _cohort_counts(rows)
        weekly.append(dict(ingestion_week=week,
                           cohorts=_cohort_counts([row for row in rows
                                                  if row['ingestion_week'] == week]),
                           cumulative=cumulative,
                           active_gate=_active_gate(cumulative['active_ingest'])))
    cumulative = _cohort_counts(current)
    return dict(weekly=weekly, cumulative=cumulative,
                active_gate=_active_gate(cumulative['active_ingest']),
                non_governing=_counts(current))


def _registry(value):
    _fields(value, {'schema', 'seals'}, 'source registry')
    require(value['schema'] == 'wall-clock-sources/v1', 'Wrong source registry schema')
    _receipts(value['seals'])
    return value['seals']


def _prior_registry(root, revision, bootstrap):
    """Read a trusted committed prefix, never the index or generated outputs."""
    require(revision == 'HEAD' or re.fullmatch(r'[0-9a-f]{40}', revision),
            'Prior registry revision must be HEAD or a full commit ID')

    def git(*arguments):
        result = subprocess.run(['git', '-C', str(root), *arguments],
                                capture_output=True, check=False)
        require(result.returncode == 0, 'Cannot read trusted registry checkpoint from Git')
        return result.stdout

    require(Path(git('rev-parse', '--show-toplevel').decode().strip()).absolute()
            == Path(root).absolute(), 'Root must be the Git repository root')
    # Resolve HEAD once, so every subsequent read uses the same immutable commit.
    commit = git('rev-parse', '--verify', f'{revision}^{{commit}}').decode().strip()
    relative = (PREFIX / 'sources.json').as_posix()
    entry = git('ls-tree', commit, '--', relative)
    if not entry:
        require(bootstrap, 'No prior registry: explicit --bootstrap is required')
        return []
    require(not bootstrap, 'Bootstrap requires a revision with no prior registry')
    require(entry.startswith(b'100644 blob ') or entry.startswith(b'100755 blob '),
            'Trusted registry must be a regular Git blob')
    try:
        return _registry(json.loads(git('show', f'{commit}:{relative}').decode('utf-8-sig')))
    except (UnicodeError, json.JSONDecodeError) as error:
        raise ValueError('Invalid trusted registry checkpoint') from error


def build(root: Path, *, prior_revision='HEAD', bootstrap=False) -> tuple[dict[str, object], dict[str, object]]:
    """Read only registered text seals and build both projections in memory.

    sources.json is exactly {schema: 'wall-clock-sources/v1', seals: [receipt]}.
    Registry order governs the seal chain; unregistered files are never read.
    A trusted committed registry is an exact required prefix. First bootstrap
    requires an explicit opt-in and a commit with no prior registry.
    """
    relative = (PREFIX / 'sources.json').as_posix()
    registry = _json_packet(root, receipt(root, relative))
    seals = _registry(registry)
    prior = _prior_registry(root, prior_revision, bootstrap)
    require(seals[:len(prior)] == prior, 'Registry does not preserve the trusted prior prefix')
    ledgers, previous = [], None
    for declared in registry['seals']:
        candidates, events = validate_seal(root, declared, previous)
        ledgers.append(dict(seal=declared, candidates=candidates, events=events))
        previous = declared['sha256']
    current = reduce_events(ledgers)
    common = dict(authority='generated_projection_only', source_seals=registry['seals'])
    return (dict(schema='wall-clock-current/v1', **deepcopy(common), current=current),
            dict(schema='wall-clock-coverage/v1', **deepcopy(common),
                 **coverage_summary(ledgers, current)))


def encode_json(value: object) -> bytes:
    """Canonical projection bytes: sorted keys, UTF-8, two spaces, final LF."""
    return (json.dumps(value, ensure_ascii=False, sort_keys=True, indent=2,
                       allow_nan=False) + '\n').encode('utf-8')


def main(argv=None):
    """Check exact generated bytes, or rebuild both after complete validation."""
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--root', type=Path, default=Path('.'))
    parser.add_argument('--write', action='store_true', help='Rebuild both generated JSON projections.')
    parser.add_argument('--prior-registry-revision', default='HEAD',
                        help='Trusted prior registry commit (full ID); defaults to HEAD before updates.')
    parser.add_argument('--bootstrap', action='store_true',
                        help='Explicit first registration; prior revision must have no registry.')
    args = parser.parse_args(argv)
    try:
        # Building and encoding BOTH projections precedes either write.
        payloads = [encode_json(value) for value in build(
            args.root, prior_revision=args.prior_registry_revision, bootstrap=args.bootstrap)]
        destinations = [args.root / PREFIX / name for name in ('current.json', 'coverage.json')]
        for destination in destinations:
            target = args.root
            for part in destination.relative_to(args.root).parts:
                target = target / part
                require(not target.is_symlink(), 'Symlink projection destination is forbidden')
            require(not destination.exists() or destination.is_file(),
                    f'Invalid projection destination: {destination}')
        if args.write:
            for destination, payload in zip(destinations, payloads):
                destination.write_bytes(payload)
        else:
            for destination, payload in zip(destinations, payloads):
                require(destination.read_bytes() == payload, f'Stale generated projection: {destination}')
    except (ValueError, OSError) as error:
        parser.exit(1, f'{error}\n')
    print(json.dumps(dict(status='passed', mode='write' if args.write else 'check')))


if __name__ == '__main__':
    main()