File size: 45,612 Bytes
e516bd2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
"""Push one consistent Lab approval snapshot to the DemoService route library.

Run on the Lab host: python tools/sync_lab_gpx.py --root /home/jovyan/artifacts/...
The receiver must already be deployed with ROUTE_LIBRARY_TOKEN configured.
"""
from __future__ import annotations

import argparse
import base64
from contextlib import contextmanager
from datetime import datetime, timezone
import fcntl
from functools import lru_cache
import hashlib
import importlib.util
import json
import math
import os
import re
import signal
import sqlite3
import time
import urllib.error
import urllib.request
import urllib.parse
import uuid
import xml.etree.ElementTree as ET
from pathlib import Path

DEFAULT_STATE = Path.home() / ".local/share/demoservice-sync/state.sqlite3"
LOCK_PATH = DEFAULT_STATE.parent / "transfer.lock"
STATUS_PATH = DEFAULT_STATE.parent / "status.json"
HALT_PATH = DEFAULT_STATE.parent / "HALTED.json"


class ReceiverUnhealthy(RuntimeError):
    pass


class ApprovalChanged(RuntimeError):
    pass


def write_status(path: Path, value: dict) -> None:
    data = {"updated_at": datetime.now(timezone.utc).isoformat(), "pid": os.getpid(), **value}
    temporary = path.with_name('.'+path.name+'.'+str(os.getpid()))
    descriptor = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_NOFOLLOW, 0o600)
    try:
        with os.fdopen(descriptor, 'w') as output:
            json.dump(data, output, ensure_ascii=False)
            output.write('\n')
        os.replace(temporary, path)
    finally:
        temporary.unlink(missing_ok=True)


def check_health(destination: str) -> None:
    parts = urllib.parse.urlsplit(destination)
    url = urllib.parse.urlunsplit((parts.scheme, parts.netloc, '/health', '', ''))
    with urllib.request.urlopen(url, timeout=30) as response:
        value = json.load(response)
    if not isinstance(value, dict) or value.get('status') != 'ok':
        raise ReceiverUnhealthy('DemoService health is abnormal')


class AlreadyRunning(RuntimeError):
    pass


@contextmanager
def single_instance(lock_path: Path = LOCK_PATH):
    """Keep the same inode locked across every cycle, sleep, and retry."""
    lock_path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
    descriptor = os.open(lock_path, os.O_RDWR | os.O_CREAT | os.O_CLOEXEC | os.O_NOFOLLOW, 0o600)
    try:
        try:
            fcntl.flock(descriptor, fcntl.LOCK_EX | fcntl.LOCK_NB)
        except BlockingIOError:
            raise AlreadyRunning("Another GPX transfer is already running") from None
        os.fchmod(descriptor, 0o600)
        os.ftruncate(descriptor, 0)
        os.write(descriptor, json.dumps({"pid": os.getpid(), "started_at": datetime.now(timezone.utc).isoformat()}).encode())
        yield
    finally:
        os.close(descriptor)
        # Never unlink or replace the lock file: that permits two locked inodes.


@lru_cache(maxsize=8)
def approval_validator(root: Path):
    policy = root / "approval_policy.py"
    spec = importlib.util.spec_from_file_location("lab_approval_policy", policy)
    if spec is None or spec.loader is None:
        raise RuntimeError("Approval policy is unavailable")
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module.valid_review


def approved_rows(root: Path, source_id: str | None = None, *, art: bool = False) -> list[sqlite3.Row]:
    database = (root / "inventory.sqlite3").resolve()
    connection = sqlite3.connect(f"file:{database.as_posix()}?mode=ro", uri=True)
    connection.row_factory = sqlite3.Row
    try:
        connection.execute("PRAGMA query_only=ON")
        connection.execute("BEGIN")
        version = connection.execute("SELECT value FROM settings WHERE key='approval_guards_version'").fetchone()
        if version is None or version[0] != "1":
            raise RuntimeError("Approval guards must be installed before synchronization")
        scope = " WHERE a.item_id=?" if source_id is not None else ""
        parameters = (source_id,) if source_id is not None else ()
        invalid = connection.execute("""
            SELECT count(*) FROM accepted AS a
            LEFT JOIN eligible_approval_items AS i ON i.id=a.item_id
              AND i.label IS a.label AND i.city_id IS a.city_id AND i.design_id IS a.design_id
            LEFT JOIN approval_revocations AS r ON r.item_id=a.item_id
        """ + scope + (" AND " if scope else " WHERE ") + "(i.id IS NULL OR r.item_id IS NOT NULL)", parameters).fetchone()[0]
        if invalid:
            raise RuntimeError("Invalid or revoked entries remain in accepted; refusing the entire snapshot")
        extra = ", i.kind, i.design_id, i.record_path" if art else ""
        rows = connection.execute("""
            SELECT i.id, i.label, i.city_id, i.city_name, i.ai_json,
                   i.geometry_ok, i.seoul_ok, i.status, a.accepted_at
        """ + extra + """
            FROM accepted AS a JOIN items AS i ON i.id = a.item_id
        """ + scope + " ORDER BY i.id", parameters).fetchall()
        validate = approval_validator(root)
        if any(not validate(row['ai_json'], row['label']) for row in rows):
            raise RuntimeError("Two-model approval evidence is invalid; refusing the entire snapshot")
        connection.commit()
        return rows
    finally:
        connection.close()


def prepare_route(root: Path, row: sqlite3.Row, finalized: bool) -> tuple[bytes, dict, str]:
    source_id, label = row['id'], row['label']
    if (not isinstance(source_id, str) or len(source_id) != 64
            or any(c not in '0123456789abcdef' for c in source_id)
            or label not in {'dog','heart','tree','tshirt','candle','pants','star'}):
        raise RuntimeError("Unexpected route ID or label in approval list")
    if row['status'] != 'ai_pass' or row['geometry_ok'] != 1 or row['seoul_ok'] != 1:
        raise RuntimeError("Approval state is invalid")
    gpx = (root/'gpx'/label/(source_id+'.gpx')).read_bytes()
    metadata = {
        'label': label, 'region_code': row['city_id'], 'region_name': row['city_name'],
        'sha256': hashlib.sha256(gpx).hexdigest(), 'accepted_at': row['accepted_at'],
        'review_status': row['status'], 'ai_protocol': json.loads(row['ai_json'])['protocol'],
        'geometry_ok': True, 'seoul_ok': True, 'collection_finalized': finalized,
    }
    signature = hashlib.sha256(json.dumps(metadata, sort_keys=True).encode()).hexdigest()
    return gpx, metadata, signature


def check_only(root: Path, state_path: Path) -> dict:
    """Read-only preflight: no token read, no HTTP requests, no DB writes."""
    rows = approved_rows(root)
    if not rows:
        raise RuntimeError("Empty approval list; refusing to synchronize")
    finalized = (root/'completion.json').is_file()
    signatures = {row['id']: prepare_route(root, row, finalized)[2] for row in rows}
    with sqlite3.connect(state_path.resolve().as_uri()+'?mode=ro', uri=True) as state:
        sent = dict(state.execute('SELECT id,signature FROM sent'))
    return {'approved': len(rows), 'sent': len(sent),
            'unchanged_sent': sum(signatures.get(k) == v for k,v in sent.items()),
            'changed_sent': sum(k in signatures and signatures[k] != v for k,v in sent.items()),
            'revoked_sent': len(set(sent)-set(signatures)),
            'unsent_approved': len(set(signatures)-set(sent)), 'http_requests': 0}


def send(url: str, token: str, method: str, payload: dict | None) -> dict:
    request = urllib.request.Request(
        url, json.dumps(payload, allow_nan=False, separators=(",", ":")).encode() if payload is not None else None,
        {"Authorization": "Bearer " + token, "Content-Type": "application/json"}, method=method,
    )
    with urllib.request.urlopen(request, timeout=30) as response:
        return json.load(response)


def canonical(value):
    return json.dumps(value, sort_keys=True, ensure_ascii=False, allow_nan=False, separators=(",", ":"))


def content_sha(payload):
    data = dict(payload)
    for key in ("session_id", "generation", "payload_sha256", "gpx_base64", "previous_payload_sha256", "reapprove"):
        data.pop(key, None)
    return hashlib.sha256(canonical(data).encode()).hexdigest()


def approved_art_rows(root, source_id=None):
    """Reuse the installation's approval guards and semantic two-model policy."""
    return [dict(row) for row in approved_rows(root, source_id, art=True)]


def verify_source_gpx(raw, expected):
    try:
        if not 0 < len(raw) <= 128 * 1024 or b"<!DOCTYPE" in raw.upper() or b"<!ENTITY" in raw.upper():
            raise ValueError
        document = ET.fromstring(raw)
        tracks = [n for n in document.iter() if n.tag.rsplit("}", 1)[-1] == "trk"]
        segments = [n for n in document.iter() if n.tag.rsplit("}", 1)[-1] == "trkseg"]
        if document.tag.rsplit("}", 1)[-1] != "gpx" or len(tracks) != 1 or len(segments) != 1 or segments[0] not in list(tracks[0]):
            raise ValueError
        points = [(float(n.attrib["lat"]), float(n.attrib["lon"])) for n in segments[0]
                  if n.tag.rsplit("}", 1)[-1] == "trkpt"]
        if not 12 <= len(points) <= 10000 or len(points) != len(expected):
            raise ValueError
        if not all(isinstance(p, (list, tuple)) and len(p) == 2
                   and all(type(v) in (int, float) and math.isfinite(v) for v in p) for p in expected):
            raise ValueError
        if (len(set(points)) < 4 or math.dist(points[0], points[-1]) > 1e-5
                or not all(math.isfinite(lat) and math.isfinite(lon) and abs(lat) <= 90 and abs(lon) <= 180
                           and abs(lat - original[1]) <= 5.01e-8 and abs(lon - original[0]) <= 5.01e-8
                           for (lat, lon), original in zip(points, expected))):
            raise ValueError
    except (ValueError, TypeError, KeyError, IndexError, ET.ParseError):
        raise RuntimeError("GPX does not match approved source GPS") from None


def current_design_review(root, label, template):
    item_id = hashlib.sha256(("design:" + label + ":" + template["design_digest"]).encode()).hexdigest()
    with sqlite3.connect((root / "inventory.sqlite3").as_uri() + "?mode=ro", uri=True) as db:
        db.execute("PRAGMA query_only=ON")
        row = db.execute("SELECT status,ai_json FROM items WHERE id=? AND kind='design'", (item_id,)).fetchone()
        return (row[0], json.loads(row[1] or "{}")) if row else ("unknown", {})


def art_packets(root, probe_id=None, max_routes=None, *, selected_ids=None):
    root = root.resolve()
    rows = approved_art_rows(root)
    if not rows:
        raise RuntimeError("Empty approval list; refusing to synchronize")
    if probe_id:
        rows = [r for r in rows if r["id"] == probe_id]
        if len(rows) != 1:
            raise RuntimeError("Probe ID is not currently approved")
    if selected_ids is not None:
        rows = [r for r in rows if r['id'] in selected_ids]
        if {r['id'] for r in rows} != set(selected_ids):
            raise ApprovalChanged("Selected route approval changed")
    elif max_routes is not None:
        if max_routes <= 0:
            raise RuntimeError("max_routes must be positive")
        rows = rows[:max_routes]
    packets, paths = {}, {}
    finalized = (root / "completion.json").is_file()
    with sqlite3.connect((root / "inventory.sqlite3").as_uri() + "?mode=ro", uri=True) as db:
        db.execute("PRAGMA query_only=ON")
        db.execute("BEGIN")
        for row in rows:
            source_id, label = row["id"], row["label"]
            if (not re.fullmatch(r"[0-9a-f]{64}", source_id) or label not in {"dog", "heart", "tree", "tshirt", "candle", "pants", "star"}
                    or row["kind"] != "route" or row["status"] != "ai_pass" or row["geometry_ok"] != 1 or row["seoul_ok"] != 1):
                raise RuntimeError("Approval state changed")
            record_path = Path(row["record_path"])
            record_raw = record_path.read_bytes()
            record = json.loads(record_raw)
            metadata, route = record["metadata"], record["route"]
            design_path = Path(metadata.get("design_file") or ".")
            if not design_path.is_file():
                design_path = root / "designs" / label / (row["design_id"] + ".json")
            design_raw = design_path.read_bytes()
            design = json.loads(design_raw)
            if not isinstance(design, dict):
                raise RuntimeError("Invalid source design snapshot")
            design_digest = hashlib.sha256(canonical(design).encode()).hexdigest()
            if (design_digest != metadata.get("design_digest") or design.get("design_id") != row["design_id"]
                    or route.get("design_id") != row["design_id"] or str(design.get("version")) != str(route.get("design_version"))):
                raise RuntimeError("Source design identity changed")
            review = json.loads(row["ai_json"])
            if (review.get("status") != "ai_pass" or review.get("expected_label") != label
                    or review.get("blind") is not True or review.get("qwen_performed") is not True
                    or not review.get("siglip_support_angles")):
                raise RuntimeError("Missing route review evidence")
            proof = route.get("verification", {})
            if (not all(proof.get(k) is True for k in ("road_only", "graph_connectivity_verified", "access_checked", "directions_checked"))
                    or type(proof.get("air_length_m")) not in (int, float) or proof["air_length_m"] != 0
                    or record.get("assessment", {}).get("success") is not True
                    or record.get("assessment", {}).get("route_valid") is not True):
                raise RuntimeError("Missing road or geometry evidence")
            graph_hash = metadata.get("graph_sha256", "")
            if not re.fullmatch(r"[0-9a-f]{64}", graph_hash):
                raise RuntimeError("Missing graph digest")
            length = route.get("length_m")
            if type(length) not in (int, float) or not math.isfinite(length) or length <= 0:
                raise RuntimeError("Invalid source road length")
            design_item_id = hashlib.sha256(("design:" + label + ":" + design_digest).encode()).hexdigest()
            design_review = db.execute("SELECT status,ai_json FROM items WHERE id=? AND kind='design'", (design_item_id,)).fetchone()
            design_status = design_review[0] if design_review else "unknown"
            design_evidence = json.loads(design_review[1] or "{}") if design_review else {}
            validate_design(root, design, design_status, design_evidence, label)
            gpx_path = root / "gpx" / label / (source_id + ".gpx")
            gpx = gpx_path.read_bytes()
            verify_source_gpx(gpx, route.get("gps", []))
            packet = {"contract_version": 2, "label": label, "region_code": row["city_id"], "region_name": row["city_name"],
                "sha256": hashlib.sha256(gpx).hexdigest(), "accepted_at": row["accepted_at"], "review_status": "ai_pass",
                "ai_protocol": review["protocol"], "geometry_ok": True, "seoul_ok": True, "collection_finalized": finalized,
                "gpx_base64": base64.b64encode(gpx).decode(),
                "template": {"design_id": design["design_id"], "source_version": str(design["version"]),
                    "design_digest": design_digest, "snapshot": design, "design_ai_status": design_status,
                    "design_ai_evidence": design_evidence},
                "route_ai_evidence": review, "road_verification": proof, "graph_sha256": graph_hash,
                "distance_m": max(1, int(math.floor(length + .5))), "validator_version": "lab-approved-gpx-import-v1"}
            packets[source_id] = packet
            validate_packet(packet)
            paths[source_id] = {str(p): hashlib.sha256(raw).hexdigest() for p, raw in
                                [(record_path, record_raw), (design_path, design_raw), (gpx_path, gpx)]}
    return rows, packets, paths



def validate_design(root, design, status, evidence, label):
    """Keep design classification independent from the accepted route."""
    points = design.get('points')
    if (status not in {'ai_pass', 'ai_reject', 'ai_review', 'unknown'}
            or not isinstance(evidence, dict) or evidence.get('status', status) != status
            or (status == 'ai_pass' and not approval_validator(root)(canonical(evidence), label))
            or not isinstance(design.get('name'), str) or not 0 < len(design['name']) <= 200
            or not isinstance(design.get('outline'), dict)
            or design['outline'].get('coordinate_system') != 'cartesian_y_up'
            or not isinstance(points, list) or not 3 <= len(points) <= 10000
            or not all(isinstance(p, list) and len(p) == 2
                       and all(type(v) in (int, float) and math.isfinite(v) for v in p) for p in points)
            or len(set(map(tuple, points))) < 3 or len(canonical(design).encode()) > 512 * 1024):
        raise RuntimeError("Invalid independent design evidence or snapshot")
    extent = max(max(p[j] for p in points) - min(p[j] for p in points) for j in (0, 1))
    if not math.isfinite(extent) or extent <= 0:
        raise RuntimeError("Invalid source design extent")


def validate_packet(packet):
    template = packet['template']
    accepted = datetime.fromisoformat(packet['accepted_at'].replace('Z', '+00:00'))
    if (accepted.tzinfo is None
            or not re.fullmatch(r'[a-z0-9][a-z0-9_-]{0,95}', template['design_id'])
            or not 1 <= len(template['source_version']) <= 100
            or not isinstance(packet['region_code'], str) or not 1 <= len(packet['region_code']) <= 40
            or not isinstance(packet['region_name'], str) or not 1 <= len(packet['region_name']) <= 200
            or not 1 <= len(packet['ai_protocol']) <= 200
            or not 0 < packet['distance_m'] < 2147483648
            or len(canonical(packet).encode()) > 2 * 1024 * 1024):
        raise RuntimeError("Invalid v2 route metadata")


def normalized_endpoint(destination):
    parts = urllib.parse.urlsplit(destination)
    if (parts.username or parts.password or parts.query or parts.fragment or not parts.hostname
            or (parts.scheme != 'https' and not (parts.scheme == 'http' and parts.hostname in {'localhost', '127.0.0.1', '::1'}))):
        raise RuntimeError("Use an HTTPS API URL without credentials, query or fragment")
    return destination.rstrip('/')


def ledger_ids(state):
    """v1 history counts toward the existing cap, but never proves v2 storage."""
    ids = {row[0] for row in state.execute('SELECT id FROM sent')}
    if state.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name='http_v2_sent'").fetchone():
        ids.update(row[0] for row in state.execute('SELECT id FROM http_v2_sent'))
    return ids


def select_v2_rows(root, state, probe_id=None, max_routes=None):
    if max_routes is not None and (max_routes < 1 or probe_id is not None):
        raise ValueError("max_routes must be positive and cannot be combined with probe_id")
    rows = approved_art_rows(root)
    if not rows:
        raise RuntimeError("Empty approval list; refusing to synchronize")
    total = len(rows)
    if probe_id is not None:
        rows = [r for r in rows if r['id'] == probe_id]
        if len(rows) != 1:
            raise RuntimeError("Probe ID is not currently approved")
    if max_routes is not None:
        sent_ids = ledger_ids(state)
        if sent_ids - {row['id'] for row in rows}:
            raise RuntimeError("Previously sent routes are no longer approved; refusing a limited synchronization")
        if len(sent_ids) > max_routes:
            raise RuntimeError("Previously sent route count already exceeds max_routes")
        retained = [r for r in rows if r['id'] in sent_ids]
        extra = [r for r in rows if r['id'] not in sent_ids]
        rows = sorted(retained + extra[:max_routes - len(retained)], key=lambda r: r['id'])
    return total, {row['id'] for row in rows}


def check_only_v2(root, state_path, destination, probe_id=None, max_routes=None):
    endpoint = normalized_endpoint(destination)
    # mode=ro: no schema creation, lock acquisition, credential read or HTTP.
    with sqlite3.connect(state_path.resolve().as_uri() + '?mode=ro', uri=True) as state:
        state.execute('PRAGMA query_only=ON')
        state.execute('BEGIN')
        total, selected = select_v2_rows(root, state, probe_id, max_routes)
        rows, packets, _ = art_packets(root, selected_ids=selected)
        receipts = {}
        if state.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name='http_v2_sent'").fetchone():
            columns = {r[1] for r in state.execute('PRAGMA table_info(http_v2_sent)')}
            if 'endpoint' in columns:
                receipts = dict(state.execute('SELECT id,signature FROM http_v2_sent WHERE endpoint=?', (endpoint,)))
        confirmed = sum(receipts.get(k) == content_sha(v) for k, v in packets.items())
        return {'contract_version': 2, 'approved': total, 'selected': len(rows),
                'templates': len({(p['label'], p['template']['design_digest']) for p in packets.values()}),
                'v1_history': state.execute('SELECT count(*) FROM sent').fetchone()[0],
                'v2_confirmed': confirmed, 'v2_pending': len(rows) - confirmed,
                'http_requests': 0, 'credential_reads': 0, 'state_writes': 0}


def request_v2(url, token, method, payload, *, before_attempt=None):
    """Bounded retries retain the session request ID and the exact route payload."""
    for attempt in range(3):
        if before_attempt is not None:
            before_attempt()
        try:
            reply = send(url, token, method, payload)
            if not isinstance(reply, dict):
                raise ReceiverUnhealthy("Invalid v2 JSON response")
            return reply
        except urllib.error.HTTPError as exc:
            if exc.code not in {408, 429, 500, 502, 503, 504} or attempt == 2:
                raise
        except (urllib.error.URLError, TimeoutError, ConnectionError):
            if attempt == 2:
                raise
        time.sleep(2 ** attempt)


def validate_session(reply, expected_generation, mode, manifest_hash, session_id=None):
    try:
        received_id = str(uuid.UUID(reply['session_id']))
        if uuid.UUID(received_id).int == 0:
            raise ValueError
    except (KeyError, ValueError, TypeError, AttributeError):
        raise ReceiverUnhealthy("Invalid sync session response") from None
    if (type(reply.get('contract_version')) is not int or reply['contract_version'] != 2
            or type(reply.get('generation')) is not int or reply['generation'] != expected_generation
            or reply.get('mode') != mode or reply.get('manifest_sha256') != manifest_hash
            or reply.get('session_status') not in {'open', 'completed'}
            or (session_id is not None and received_id != session_id)):
        raise ReceiverUnhealthy("Inconsistent or stale sync session response")
    return received_id


def validate_receipt(reply, source_id, packet, previous=None):
    try:
        valid_ids = all(isinstance(reply[k], str) and str(uuid.UUID(reply[k])) == reply[k]
                        and uuid.UUID(reply[k]).int != 0 for k in ('art_template_id', 'art_route_candidate_id'))
    except (KeyError, ValueError, TypeError, AttributeError):
        valid_ids = False
    if (not valid_ids or type(reply.get('contract_version')) is not int or reply['contract_version'] != 2
            or reply.get('status') != 'stored' or reply.get('result') not in {'created', 'updated', 'unchanged'}
            or reply.get('source_id') != source_id or reply.get('sha256') != packet['sha256']
            or reply.get('payload_sha256') != content_sha(packet)
            or reply.get('design_ai_status') != packet['template']['design_ai_status']
            or reply.get('route_validation_status') != 'passed'):
        raise ReceiverUnhealthy("Missing or inconsistent art storage receipt")
    if previous and (reply['art_route_candidate_id'] != previous['candidate_id']
            or (previous['signature'] == content_sha(packet) and reply['art_template_id'] != previous['template_id'])):
        raise ReceiverUnhealthy("Stored art identifiers changed unexpectedly")


def initialize_v2_state(state):
    state.execute('SELECT id,signature FROM sent LIMIT 0')
    state.execute('''CREATE TABLE IF NOT EXISTS http_v2_runs (
        client_request_id TEXT PRIMARY KEY, signature TEXT NOT NULL, expected_generation INTEGER NOT NULL,
        session_id TEXT, generation INTEGER, completed INTEGER NOT NULL DEFAULT 0)''')
    state.execute('''CREATE TABLE IF NOT EXISTS http_v2_sent (
        id TEXT PRIMARY KEY, signature TEXT NOT NULL, session_id TEXT NOT NULL,
        template_id TEXT NOT NULL, candidate_id TEXT NOT NULL, endpoint TEXT NOT NULL DEFAULT '')''')
    columns = {r[1] for r in state.execute('PRAGMA table_info(http_v2_sent)')}
    if 'endpoint' not in columns:
        # Old patch receipts have no destination binding; never reuse them blindly.
        state.execute("ALTER TABLE http_v2_sent ADD COLUMN endpoint TEXT NOT NULL DEFAULT ''")
    state.commit()


def sync_v2(root, destination, token, state_path, probe_id=None, max_routes=None,
            allow_updates=False, allow_reapproval=False, new_session=False):
    root = root.resolve()
    endpoint = normalized_endpoint(destination)
    # Never replace the installation's original ledger with a new empty database.
    state = sqlite3.connect(state_path.resolve().as_uri() + '?mode=rw', uri=True)
    state.row_factory = sqlite3.Row
    try:
        total, selected = select_v2_rows(root, state, probe_id, max_routes)
        rows, packets, paths = art_packets(root, selected_ids=selected)
        manifest = {key: content_sha(packet) for key, packet in packets.items()}
        manifest_hash = hashlib.sha256(canonical(manifest).encode()).hexdigest()
        mode = 'partial' if probe_id is not None or max_routes is not None else 'full'
        signature = hashlib.sha256(canonical([endpoint, str(root), manifest_hash, mode,
                                            allow_updates, allow_reapproval]).encode()).hexdigest()

        def assert_route(row):
            key = row['id']
            if (approved_art_rows(root, key) != [row]
                    or any(hashlib.sha256(Path(p).read_bytes()).hexdigest() != h for p, h in paths[key].items())
                    or current_design_review(root, row['label'], packets[key]['template']) != (
                        packets[key]['template']['design_ai_status'], packets[key]['template']['design_ai_evidence'])):
                raise ApprovalChanged("Approval or source changed; resume from a new snapshot")
            if packets[key]['collection_finalized'] != (root / 'completion.json').is_file():
                raise ApprovalChanged("Collection finalization changed")

        def assert_manifest():
            if mode == 'full' and approved_art_rows(root) != rows:
                raise ApprovalChanged("Approval list changed; snapshot withheld")
            for row in rows:
                assert_route(row)

        # All source validation precedes local schema changes and the first HTTP request.
        initialize_v2_state(state)
        run = None if new_session else state.execute(
            'SELECT * FROM http_v2_runs WHERE signature=? AND completed=0 ORDER BY rowid DESC LIMIT 1', (signature,)).fetchone()
        if run is None:
            remote = request_v2(endpoint + '/sync-state', token, 'GET', None, before_attempt=assert_manifest)
            if (type(remote.get('contract_version')) is not int or remote['contract_version'] != 2
                    or type(remote.get('generation')) is not int or remote['generation'] < 0):
                raise ReceiverUnhealthy("Receiver does not support fenced v2 imports")
            request_id = str(uuid.uuid4())
            if new_session:
                # Do not rediscover an older superseded checkpoint after this run completes.
                state.execute('UPDATE http_v2_runs SET completed=2 WHERE signature=? AND completed=0', (signature,))
            state.execute('INSERT INTO http_v2_runs(client_request_id,signature,expected_generation) VALUES (?,?,?)',
                          (request_id, signature, remote['generation']))
            state.commit()  # Persist before POST; a lost response reuses the same request ID.
            run = state.execute('SELECT * FROM http_v2_runs WHERE client_request_id=?', (request_id,)).fetchone()
        session = request_v2(endpoint + '/sync-sessions', token, 'POST', {'contract_version': 2,
            'client_request_id': run['client_request_id'], 'expected_generation': run['expected_generation'],
            'mode': mode, 'manifest': manifest, 'manifest_sha256': manifest_hash}, before_attempt=assert_manifest)
        generation = run['expected_generation'] + 1
        session_id = validate_session(session, generation, mode, manifest_hash, run['session_id'])
        current = request_v2(endpoint + '/sync-sessions/' + session_id, token, 'GET', None, before_attempt=assert_manifest)
        validate_session(current, generation, mode, manifest_hash, session_id)
        state.execute('UPDATE http_v2_runs SET session_id=?,generation=? WHERE client_request_id=?',
                      (session_id, generation, run['client_request_id']))
        state.commit()
        uploaded = 0
        for row in rows:
            key = row['id']
            assert_route(row)
            previous = state.execute('SELECT * FROM http_v2_sent WHERE id=? AND endpoint=?', (key, endpoint)).fetchone()
            packet = {**packets[key], 'session_id': session_id, 'generation': generation, 'payload_sha256': manifest[key]}
            if previous and previous['session_id'] == session_id and previous['signature'] == manifest[key]:
                # Validate persisted receipt fields before trusting a resumable checkpoint.
                validate_receipt({'contract_version': 2, 'status': 'stored', 'result': 'unchanged',
                    'source_id': key, 'sha256': packet['sha256'], 'payload_sha256': manifest[key],
                    'design_ai_status': packet['template']['design_ai_status'], 'route_validation_status': 'passed',
                    'art_template_id': previous['template_id'], 'art_route_candidate_id': previous['candidate_id']}, key, packet)
                continue
            if previous and allow_updates:
                packet['previous_payload_sha256'] = previous['signature']
            if allow_reapproval:
                packet['reapprove'] = True
            receipt = request_v2(endpoint + '/routes/' + key, token, 'PUT', packet,
                                 before_attempt=lambda row=row: assert_route(row))
            validate_receipt(receipt, key, packet, previous)
            state.execute('''INSERT INTO http_v2_sent(id,signature,session_id,template_id,candidate_id,endpoint)
                VALUES (?,?,?,?,?,?) ON CONFLICT(id) DO UPDATE SET signature=excluded.signature,
                session_id=excluded.session_id,template_id=excluded.template_id,
                candidate_id=excluded.candidate_id,endpoint=excluded.endpoint''',
                (key, manifest[key], session_id, receipt['art_template_id'], receipt['art_route_candidate_id'], endpoint))
            state.commit()
            uploaded += 1
        assert_manifest()
        current = request_v2(endpoint + '/sync-sessions/' + session_id, token, 'GET', None, before_attempt=assert_manifest)
        validate_session(current, generation, mode, manifest_hash, session_id)
        if mode == 'full':
            ids = sorted(manifest)
            result = request_v2(endpoint + '/approval-snapshot', token, 'POST', {'contract_version': 2,
                'session_id': session_id, 'generation': generation, 'manifest_sha256': manifest_hash,
                'ids': ids, 'count': len(ids), 'ids_sha256': hashlib.sha256('\n'.join(ids).encode()).hexdigest(),
                'collection_finalized': packets[ids[0]]['collection_finalized']}, before_attempt=assert_manifest)
            if (type(result.get('active_count')) is not int or result['active_count'] != len(ids)
                    or type(result.get('deactivated_count')) is not int or result['deactivated_count'] < 0):
                raise ReceiverUnhealthy("Invalid approval snapshot response")
        else:
            result = request_v2(endpoint + '/sync-sessions/' + session_id + '/complete?generation=' + str(generation),
                                token, 'POST', {}, before_attempt=assert_manifest)
            validate_session(result, generation, mode, manifest_hash, session_id)
            if (result.get('session_status') != 'completed' or type(result.get('deactivated_count')) is not int
                    or result['deactivated_count'] != 0):
                raise ReceiverUnhealthy("Invalid partial session completion response")
        if (type(result.get('contract_version')) is not int or result['contract_version'] != 2
                or result.get('session_id') != session_id or type(result.get('generation')) is not int
                or result['generation'] != generation):
            raise ReceiverUnhealthy("Inconsistent sync completion response")
        state.execute('UPDATE http_v2_runs SET completed=1 WHERE client_request_id=?', (run['client_request_id'],))
        state.commit()
        return {'contract_version': 2, 'approved': total, 'selected': len(rows), 'uploaded': uploaded,
                'sent_total': len(ledger_ids(state)), 'snapshot_sent': mode == 'full',
                'generation': generation, 'deactivated_count': result['deactivated_count']}
    finally:
        state.close()
        if state_path.exists():
            os.chmod(state_path, 0o600)


def sync(root: Path, destination: str, token: str, state_path: Path,
         probe_id: str | None = None, max_routes: int | None = None) -> dict:
    if max_routes is not None and (max_routes < 1 or probe_id is not None):
        raise ValueError("max_routes must be positive and cannot be combined with probe_id")
    rows = approved_rows(root)
    if not rows:
        raise RuntimeError("Empty approval list; refusing to synchronize")
    approved_count = len(rows)
    if probe_id is not None:
        rows = [row for row in rows if row["id"] == probe_id]
        if len(rows) != 1:
            raise RuntimeError("Probe ID is not in the current approval list")
    # mode=rw refuses to silently create an empty replacement ledger.
    state = sqlite3.connect(state_path.resolve().as_uri()+'?mode=rw', uri=True)
    try:
        state.execute("SELECT id,signature FROM sent LIMIT 0")
        if max_routes is not None:
            sent_ids = {row[0] for row in state.execute("SELECT id FROM sent")}
            approved_ids = {row["id"] for row in rows}
            if sent_ids - approved_ids:
                raise RuntimeError("Previously sent routes are no longer approved; refusing a limited synchronization")
            if len(sent_ids) > max_routes:
                raise RuntimeError("Previously sent route count already exceeds max_routes")
            retained = [row for row in rows if row["id"] in sent_ids]
            additional = [row for row in rows if row["id"] not in sent_ids]
            rows = sorted(retained + additional[:max_routes - len(retained)], key=lambda row: row["id"])
        ids = []
        file_hashes = {}
        uploaded = 0
        finalized = (root/'completion.json').is_file()
        # Validate every file before the first PUT; partial preflight is unsafe.
        prepared = [(row, *prepare_route(root, row, finalized)) for row in rows]
        for row, gpx, metadata, signature in prepared:
            source_id, label = row["id"], row["label"]
            file_hashes[source_id] = metadata['sha256']
            previous = state.execute("SELECT signature FROM sent WHERE id=?", (source_id,)).fetchone()
            if probe_id is not None or not previous or previous[0] != signature:
                current = approved_rows(root, source_id)
                if len(current) != 1 or tuple(current[0]) != tuple(row):
                    raise ApprovalChanged("Approval changed before upload; retry from a new snapshot")
                if hashlib.sha256((root/'gpx'/label/(source_id+'.gpx')).read_bytes()).hexdigest() != metadata['sha256']:
                    raise RuntimeError("GPX changed before upload")
                received = send(destination.rstrip("/") + "/routes/" + source_id, token, "PUT",
                                {**metadata, "gpx_base64": base64.b64encode(gpx).decode()})
                if (not isinstance(received, dict) or received.get('status') != 'stored'
                        or received.get('source_id') != source_id or received.get('sha256') != metadata['sha256']):
                    raise ReceiverUnhealthy('Unexpected route storage response')
                state.execute("INSERT INTO sent VALUES (?, ?) ON CONFLICT(id) DO UPDATE SET signature=excluded.signature",
                              (source_id, signature))
                state.commit()
                uploaded += 1
            ids.append(source_id)
        if probe_id is not None:
            return {"probe_id": probe_id, "uploaded": uploaded, "snapshot_sent": False}
        if max_routes is not None:
            return {"approved": approved_count, "selected": len(rows), "uploaded": uploaded,
                    "sent_total": state.execute("SELECT count(*) FROM sent").fetchone()[0],
                    "max_routes": max_routes, "snapshot_sent": False}
        # Do not revoke from a partial file set or a changing DB approval list.
        if [tuple(row) for row in rows] != [tuple(row) for row in approved_rows(root)]:
            raise ApprovalChanged("Approval list changed during upload; retry from a new snapshot")
        if finalized != (root/'completion.json').is_file():
            raise ApprovalChanged("Collection finalization changed during upload; retry from a new snapshot")
        if any(hashlib.sha256((root / "gpx" / row["label"] / (row["id"] + ".gpx")).read_bytes()).hexdigest()
               != file_hashes[row["id"]] for row in rows):
            raise RuntimeError("GPX files changed during upload; retry from a new snapshot")
        digest = hashlib.sha256("\n".join(ids).encode()).hexdigest()
        result = send(destination.rstrip("/") + "/approval-snapshot", token, "POST", {
            "ids": ids, "count": len(ids), "ids_sha256": digest,
            "collection_finalized": finalized,
        })
        if (not isinstance(result, dict) or type(result.get('active_count')) is not int
                or result['active_count'] != len(ids) or type(result.get('deactivated_count')) is not int
                or result['deactivated_count'] < 0):
            raise ReceiverUnhealthy('Unexpected approval snapshot response')
        return {"approved": len(ids), "uploaded": uploaded, "snapshot_sent": True,
                "active_count": result['active_count'], "deactivated_count": result['deactivated_count'], "error": False}
    finally:
        state.close()
        if state_path.exists():
            os.chmod(state_path, 0o600)


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--root", type=Path, required=True)
    parser.add_argument("--url", required=True, help="Full /api/v1/ai/internal/route-library URL")
    parser.add_argument("--token-file", type=Path, required=True)
    parser.add_argument("--state", type=Path, default=DEFAULT_STATE)
    parser.add_argument("--check-only", action="store_true", help="Read-only preflight; never reads the token or sends HTTP")
    parser.add_argument("--workers", type=int, choices=[1], default=1, help="One sequential upload worker only")
    parser.add_argument("--initial-delay-seconds", type=int, default=0)
    parser.add_argument("--interval-seconds", type=int, default=0, help="Repeat after this delay; 0 runs once")
    parser.add_argument("--probe-id", help="Send one approved GPX without an approval snapshot")
    parser.add_argument("--max-routes", type=int,
                        help="Cap total sent routes, including previous sends; never send an approval snapshot")
    parser.add_argument("--contract-version", type=int, choices=[1, 2], default=1,
                        help="Explicitly opt in to v2 art storage; existing startup stays on v1")
    parser.add_argument("--allow-updates", action="store_true", help="v2 compare-and-swap using a verified previous receipt")
    parser.add_argument("--allow-reapproval", action="store_true", help="v2 explicit reapproval with a later source approval")
    parser.add_argument("--new-session", action="store_true", help="v2 explicitly replace a pending session")
    args = parser.parse_args()
    if args.interval_seconds < 0 or args.initial_delay_seconds < 0:
        parser.error("--interval-seconds must be nonnegative")
    if args.probe_id and args.interval_seconds:
        parser.error("--probe-id cannot be used with --interval-seconds")
    if args.max_routes is not None and (args.max_routes < 1 or args.probe_id or args.interval_seconds):
        parser.error("--max-routes must be positive and cannot be used with --probe-id or --interval-seconds")
    if args.contract_version != 2 and (args.allow_updates or args.allow_reapproval or args.new_session):
        parser.error("Session and update options require --contract-version 2")
    if not args.state.is_file():
        parser.error("Existing state.sqlite3 is required; refusing to create a replacement")
    if args.state.resolve() != DEFAULT_STATE.resolve():
        parser.error("This installation must reuse the original DemoService state.sqlite3")
    # A preflight must not rewrite even the live lock or status file.
    if args.check_only:
        try:
            result = (check_only_v2(args.root, args.state, args.url, args.probe_id, args.max_routes)
                      if args.contract_version == 2 else check_only(args.root, args.state))
        except (OSError, ValueError, RuntimeError, sqlite3.Error, KeyError, TypeError, AttributeError):
            raise SystemExit("Local preflight failed; input details suppressed") from None
        print(json.dumps(result, ensure_ascii=False))
        return
    try:
        with single_instance():
            if HALT_PATH.exists():
                raise SystemExit('Transmission is halted; resolve HALTED.json before resuming')
            token = args.token_file.read_text(encoding="utf-8").strip()
            if not token:
                raise SystemExit("Empty receiver token")
            def stopped(signum, _frame):
                write_status(STATUS_PATH, {'state':'stopped','error':False,'signal':signum,'workers':1})
                raise SystemExit(0)
            signal.signal(signal.SIGTERM, stopped)
            signal.signal(signal.SIGINT, stopped)
            if args.initial_delay_seconds:
                write_status(STATUS_PATH, {'state':'sleeping','error':False,'workers':1,
                                          'next_delay_seconds':args.initial_delay_seconds})
                time.sleep(args.initial_delay_seconds)
            while True:
                try:
                    check_health(args.url)
                    write_status(STATUS_PATH, {'state':'transferring','error':False,'workers':1})
                    if args.contract_version == 2:
                        result = sync_v2(args.root, args.url, token, args.state, args.probe_id, args.max_routes,
                                         args.allow_updates, args.allow_reapproval, args.new_session)
                        args.new_session = False
                    else:
                        result = sync(args.root, args.url, token, args.state, args.probe_id, args.max_routes)
                    check_health(args.url)
                    write_status(STATUS_PATH, {'state':'sleeping' if args.interval_seconds else 'complete',
                                              'workers':1,'interval_seconds':args.interval_seconds,**result})
                    print(json.dumps(result, ensure_ascii=False), flush=True)
                except ApprovalChanged:
                    write_status(STATUS_PATH, {'state':'approval_changed','error':False,'workers':1})
                    if not args.interval_seconds:
                        raise SystemExit('Approval changed during synchronization; completed uploads are retained') from None
                except (OSError, ValueError, RuntimeError, sqlite3.Error, urllib.error.URLError,
                        KeyError, TypeError, AttributeError, OverflowError) as exc:
                    error = {'state':'halted','error':True,'error_type':type(exc).__name__,
                             'http_status':exc.code if isinstance(exc,urllib.error.HTTPError) else None,'workers':1}
                    write_status(HALT_PATH,error)
                    write_status(STATUS_PATH,error)
                    print(json.dumps(error),flush=True)
                    raise SystemExit(1) from None
                if not args.interval_seconds:
                    break
                time.sleep(args.interval_seconds)
    except AlreadyRunning:
        raise SystemExit("Another GPX transfer is already running") from None


if __name__ == "__main__":
    main()