@vibelord/lanes 1.7.3 → 1.7.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/README.md +9 -0
  2. package/package.json +1 -1
  3. package/payload/lanes/VERSION +1 -1
  4. package/payload/lanes/bin/lanes +128 -24
  5. package/payload/lanes/bin/lanes-site-serve +15 -0
  6. package/payload/lanes/bin-rs/BINARIES.json +5 -0
  7. package/payload/lanes/container/lane-mcp +108 -5
  8. package/payload/lanes/container/lane_core.py +116 -0
  9. package/payload/lanes/container/throttle-pulse +159 -14
  10. package/payload/lanes/docs/ARCHITECTURE.md +132 -13
  11. package/payload/lanes/docs/DESIGN.md +10 -8
  12. package/payload/lanes/docs/INSTALL.md +1 -1
  13. package/payload/lanes/docs/RUNBOOK.md +436 -8
  14. package/payload/lanes/docs/USERGUIDE.md +82 -9
  15. package/payload/lanes/install/host-install.sh +35 -4
  16. package/payload/lanes/libexec/adopt.py +364 -0
  17. package/payload/lanes/libexec/attach.py +35 -5
  18. package/payload/lanes/libexec/cutover.py +656 -0
  19. package/payload/lanes/libexec/docsd.py +12 -8
  20. package/payload/lanes/libexec/doctor_lanes2.py +284 -0
  21. package/payload/lanes/libexec/economy_poll.py +87 -2
  22. package/payload/lanes/libexec/gc_unregistered.py +407 -0
  23. package/payload/lanes/libexec/lanes_lib.py +474 -2
  24. package/payload/lanes/libexec/native.sh +38 -0
  25. package/payload/lanes/libexec/native_bin.py +670 -0
  26. package/payload/lanes/libexec/session_actions.py +85 -7
  27. package/payload/lanes/libexec/shadow.py +1311 -0
  28. package/payload/lanes/libexec/sidebar.py +252 -30
  29. package/payload/lanes/libexec/sidebar_status.py +373 -25
  30. package/payload/lanes/libexec/statusd.py +67 -3
  31. package/payload/lanes/libexec/tokens.py +99 -131
  32. package/payload/lanes/libexec/tokens.sh +1 -1
  33. package/payload/lanes/libexec/update.py +78 -8
  34. package/payload/lanes/libexec/users.py +282 -0
  35. package/payload/lanes/site/README.md +9 -0
  36. package/payload/lanes/site/conformance.py +280 -0
  37. package/payload/lanes/site/protocol.py +368 -0
  38. package/payload/lanes/site/server.py +314 -0
  39. package/payload/lanes/systemd/lanes-gc.service +1 -1
  40. package/payload/lanes/systemd/lanes-gc.timer +14 -3
  41. package/payload/lanes/tokens/README.md +156 -0
  42. package/payload/lanes/tokens/generate.py +930 -0
  43. package/payload/lanes/tokens/generated/parity.v1.tsv +489 -0
  44. package/payload/lanes/tokens/generated/tokens.resolved.json +835 -0
  45. package/payload/lanes/tokens/tokens.v1.json +763 -0
  46. package/payload/lanes/tokens/tokens.v1.schema.json +143 -0
  47. package/payload/lanes/web/Caddyfile +11 -0
  48. package/payload/lanes/web/README.md +253 -4
  49. package/payload/lanes/web/directory.css +95 -0
  50. package/payload/lanes/web/directory.js +951 -0
  51. package/payload/lanes/web/generated/README.md +107 -0
  52. package/payload/lanes/web/generated/lanes2_protocol.d.mts +1162 -0
  53. package/payload/lanes/web/generated/lanes2_protocol.mjs +2333 -0
  54. package/payload/lanes/web/inbox.js +1140 -0
  55. package/payload/lanes/web/mobile.js +35 -45
  56. package/payload/lanes/web/tokens.css +137 -0
  57. package/payload/manifest.json +7 -4
@@ -53,6 +53,17 @@ person owns (members.owner_for decides ownership, as devices/<device>.json recor
53
53
  (writers that are no device, so an admin's verb over SSH is never somebody at a desk: W9 review F3). Since W11
54
54
  (spec 2026-10-11 §3) the sidebar's `i` writes `look.fleet_collapsed` (set_look_flag) and every sidebar of the
55
55
  person folds or unfolds its fleet block from the profile on its next tick (look_flag).
56
+ * Lanes 2.0 (fan-out plan F5, DM-LANES2-PRESENTATION): presentation() reads a profile's bytes, with the person's
57
+ device files, into the PrincipalPresentationPreferences homes of the integrated cockpit §5.1 table — the shared
58
+ record, each device's local presentation, the legacy stamps, the lanes that could not be placed — exactly as the
59
+ Rust migration (crates/lanes-runtime/src/preferences/legacy.rs) does; both run the fixtures under
60
+ crates/lanes-runtime/src/preferences/fixtures/legacy/. presentation_for() runs it over the live store. Both only
61
+ read: this file stays the profile's one writer and authority until the Rust host is switched on. A `seen` mark is a
62
+ time and a Lanes 2.0 viewed-Done mark a lane's Done revision: given each Done lane's {done_revision, done_at_ms}
63
+ (the directory's facts at the cutover) a mark at or after the Done becomes a mark at that revision and one that
64
+ covers no current Done is dropped (`superseded_seen`); without them the marks stay times (`legacy_seen`), never
65
+ written as revisions. A device file's unfolded look has no 2.0 home; it stays put until a claim folds it
66
+ (`unclaimed_looks`).
56
67
  """
57
68
  import copy
58
69
  import fcntl
@@ -640,3 +651,274 @@ def migrate(login, devices=None, now=None, timeout=LOCK_S):
640
651
  for found in owned:
641
652
  _drop_look(found['device'])
642
653
  return read(login)
654
+
655
+
656
+ # ------------------------------------------------------------------- the Lanes 2.0 presentation record (fan-out F5)
657
+ #
658
+ # The reader twin of crates/lanes-runtime/src/preferences/legacy.rs. Its bounds, parse and refusals are serde_json's and
659
+ # lanes-protocol's, so the two producers refuse and migrate exactly the same files: a file larger than
660
+ # PRESENTATION_MAX_BYTES or nested deeper than PRESENTATION_MAX_DEPTH (check_depth's byte rule) is `out_of_bounds`;
661
+ # NaN/Infinity, a number beyond a finite double and a lone surrogate escape are `not_json`. A login that is not a
662
+ # lanes-protocol wire id (1-128 visible ASCII characters other than `"` and `\`) cannot be a principal id yet.
663
+
664
+ PRESENTATION_MAX_BYTES = 1024 * 1024 # legacy.rs LEGACY_MAX_BYTES
665
+ PRESENTATION_MAX_DEPTH = 32 # legacy.rs LEGACY_MAX_DEPTH
666
+ PRESENTATION_LIST_MAX = 640 # lanes-protocol PREFERENCE_LIST_MAX
667
+ MS_MAX = 2 ** 53 - 1 # a time beyond it in milliseconds is no time
668
+ WIRE_ID_MAX = 128 # lanes-protocol ID_MAX_BYTES
669
+ DEFAULT_THEME = {'theme_id': 'lanes', 'theme_revision': 2} # lanes/tokens/tokens.v1.json
670
+ APPEARANCE = {'theme': 'mode', 'color': 'colour_tier', 'glyphs': 'glyphs'}
671
+ DEVICE_SWITCHES = {'notify': ('1', '0'), 'dim': ('90', '2'), 'editor': ('micro', 'hx', 'nvim', 'vim', 'auto')}
672
+ LEFT_IN_PROFILE = ('name', 'notify.quiet_s') # outside the presentation record: they stay in this file
673
+
674
+
675
+ class _NotJson(ValueError):
676
+ pass
677
+
678
+
679
+ def _wire_id(value):
680
+ return (isinstance(value, str) and 0 < len(value) <= WIRE_ID_MAX
681
+ and all('!' <= char <= '~' and char not in '"\\' for char in value))
682
+
683
+
684
+ def _depth_ok(data, limit):
685
+ """lanes-protocol check_depth: no more than `limit` open brackets outside string literals."""
686
+ depth, in_string, escaped = 0, False, False
687
+ for byte in data:
688
+ if in_string:
689
+ if escaped:
690
+ escaped = False
691
+ elif byte == 0x5c:
692
+ escaped = True
693
+ elif byte == 0x22:
694
+ in_string = False
695
+ elif byte == 0x22:
696
+ in_string = True
697
+ elif byte in (0x5b, 0x7b):
698
+ depth += 1
699
+ if depth > limit:
700
+ return False
701
+ elif byte in (0x5d, 0x7d):
702
+ depth = max(0, depth - 1)
703
+ return True
704
+
705
+
706
+ def _finite_float(text):
707
+ value = float(text)
708
+ if not math.isfinite(value):
709
+ raise _NotJson('a number beyond a finite double')
710
+ return value
711
+
712
+
713
+ def _finite_int(text):
714
+ if not math.isfinite(float(text)):
715
+ raise _NotJson('a number beyond a finite double')
716
+ return int(text)
717
+
718
+
719
+ def _refuse_constant(text):
720
+ raise _NotJson('NaN or Infinity')
721
+
722
+
723
+ def _surrogate(value):
724
+ stack = [value]
725
+ while stack:
726
+ item = stack.pop()
727
+ if isinstance(item, str):
728
+ if any('\ud800' <= char <= '\udfff' for char in item):
729
+ return True
730
+ elif isinstance(item, dict):
731
+ stack.extend(item.keys())
732
+ stack.extend(item.values())
733
+ elif isinstance(item, list):
734
+ stack.extend(item)
735
+ return False
736
+
737
+
738
+ def _strict_json(data):
739
+ """`data` (bytes) decoded as serde_json decodes it, or _NotJson."""
740
+ try:
741
+ value = json.loads(bytes(data).decode('utf-8'), parse_float=_finite_float, parse_int=_finite_int,
742
+ parse_constant=_refuse_constant)
743
+ except (UnicodeDecodeError, ValueError, RecursionError):
744
+ raise _NotJson('not JSON') from None
745
+ if _surrogate(value):
746
+ raise _NotJson('a lone surrogate')
747
+ return value
748
+
749
+
750
+ def _bounded_json(data):
751
+ data = bytes(data)
752
+ if len(data) > PRESENTATION_MAX_BYTES or not _depth_ok(data, PRESENTATION_MAX_DEPTH):
753
+ return None, 'out_of_bounds'
754
+ try:
755
+ return _strict_json(data), None
756
+ except _NotJson:
757
+ return None, 'not_json'
758
+
759
+
760
+ def _ms(value):
761
+ """An epoch-seconds time (_time) as epoch milliseconds, floored; None for no time or one beyond MS_MAX."""
762
+ if not _time(value):
763
+ return None
764
+ product = value * 1000
765
+ if isinstance(product, float) and not math.isfinite(product):
766
+ return None
767
+ ms = math.floor(product)
768
+ return ms if ms <= MS_MAX else None
769
+
770
+
771
+ def _lane_key(identity):
772
+ return identity['authority'], identity['workspace_id'], identity['lane_id']
773
+
774
+
775
+ def _device_presentation(meta):
776
+ """One device file's local presentation — its device_only look (the override) and its switches, each only when
777
+ set — and whether it keeps an unfolded look, which has no device-local home (it stays in the file until a claim
778
+ folds it)."""
779
+ local = {}
780
+ own = device_only(meta)
781
+ if own:
782
+ local['appearance_override'] = {APPEARANCE[key]: value for key, value in own.items()}
783
+ switches = {key: meta[key] for key, allowed in DEVICE_SWITCHES.items()
784
+ if isinstance(meta.get(key), str) and meta[key] in allowed}
785
+ if switches:
786
+ local['switches'] = switches
787
+ return local, bool(unfolded(meta))
788
+
789
+
790
+ def _done_fact(fact):
791
+ """A lane's current Done as the cutover supplies it: {done_revision, done_at_ms}, non-negative integers."""
792
+ return (isinstance(fact, dict) and set(fact) == {'done_revision', 'done_at_ms'}
793
+ and all(type(fact[key]) is int and fact[key] >= 0 for key in fact))
794
+
795
+
796
+ def presentation(login, data, authority, boards=None, devices=(), done=None):
797
+ """The Lanes 2.0 homes of `login`'s profile bytes `data` (integrated cockpit §5.1): -> (migration, None) or (None,
798
+ refusal code), the same JSON value and codes legacy.rs migrate_profile produces. `authority` is the host's authority
799
+ namespace, `boards` the registry's {lane id: board id}, `devices` [(device name, devices/<device>.json bytes)] of
800
+ the devices the login owns, `done` {lane id: {'done_revision', 'done_at_ms'}} of every lane Done now (None: not
801
+ supplied, so no `seen` mark is resolved). A lane is identified by the authority, the board the registry places it on
802
+ (else the board its derived address names, the id before its first `--`) and its id; one with neither, or an id
803
+ longer than a wire id, is listed in `unresolved_lanes`, never guessed. Pure; never raises."""
804
+ if not _wire_id(login):
805
+ return None, 'login_not_wire_id'
806
+ document, problem = _bounded_json(data)
807
+ if problem:
808
+ return None, problem
809
+ if not isinstance(document, dict):
810
+ return None, 'not_object'
811
+ version = document.get('version', VERSION)
812
+ if type(version) is not int or version != VERSION:
813
+ return None, 'other_version'
814
+ if document.get('login') != login:
815
+ return None, 'login_mismatch'
816
+ boards = boards if isinstance(boards, dict) else {}
817
+ unresolved = set()
818
+
819
+ def resolve(lane):
820
+ board = boards.get(lane)
821
+ if not (isinstance(board, str) and _valid(check_workspace, board)):
822
+ head, separator, _tail = lane.partition('--')
823
+ board = head if separator and _valid(check_workspace, head) else None
824
+ if board is None or not _wire_id(lane):
825
+ unresolved.add(lane)
826
+ return None
827
+ return {'authority': authority, 'workspace_id': board, 'lane_id': lane}
828
+
829
+ def section(name):
830
+ value = document.get(name)
831
+ return value if isinstance(value, dict) else {}
832
+
833
+ lanes, spaces, look = section('lanes'), section('workspaces'), section('look')
834
+ hidden = sorted(filter(None, map(resolve, _ids(lanes.get('hidden'), check_lane, MAX_LANES))), key=_lane_key)
835
+ hidden_keys = {_lane_key(identity) for identity in hidden}
836
+ pinned = sorted((identity for identity in map(resolve, _ids(lanes.get('pins'), check_lane, MAX_LANES))
837
+ if identity and _lane_key(identity) not in hidden_keys), key=_lane_key)
838
+
839
+ seen = document.get('seen')
840
+ marks = [(lane, at) for lane, at in (seen.items() if isinstance(seen, dict) else ())
841
+ if _valid(check_lane, lane) and _time(at)]
842
+ marks = sorted(marks, key=lambda mark: (-mark[1], mark[0]))[:MAX_SEEN]
843
+ placed = []
844
+ for lane, at in sorted(marks):
845
+ ms = _ms(at)
846
+ identity = resolve(lane) if ms is not None else None
847
+ if identity:
848
+ placed.append((identity, ms, lane))
849
+ placed = sorted(placed, key=lambda mark: (-mark[1], _lane_key(mark[0])))[:PRESENTATION_LIST_MAX]
850
+ viewed, legacy_seen, superseded = [], [], []
851
+ for identity, ms, lane in placed:
852
+ fact = done.get(lane) if isinstance(done, dict) else None
853
+ if not isinstance(done, dict):
854
+ legacy_seen.append({'lane': identity, 'seen_at_ms': ms})
855
+ elif _done_fact(fact) and fact['done_at_ms'] <= ms:
856
+ viewed.append({'lane': identity, 'done_revision': fact['done_revision']})
857
+ else:
858
+ superseded.append(lane)
859
+ viewed.sort(key=lambda mark: _lane_key(mark['lane']))
860
+ legacy_seen.sort(key=lambda mark: _lane_key(mark['lane']))
861
+
862
+ preferences = {
863
+ 'pinned': pinned, 'hidden': hidden,
864
+ 'hidden_boards': sorted(_ids(spaces.get('hidden'), check_workspace, MAX_WORKSPACES)),
865
+ 'board_order': _ids(spaces.get('order'), check_workspace, MAX_WORKSPACES),
866
+ 'viewed_done': viewed, 'theme': dict(DEFAULT_THEME),
867
+ 'appearance': {APPEARANCE[key]: look[key] for key, allowed in LOOK.items()
868
+ if isinstance(look.get(key), str) and look[key] in allowed},
869
+ 'fleet_fold': look.get('fleet_collapsed') is True,
870
+ }
871
+ opened = document.get('last_opened')
872
+ if isinstance(opened, dict) and _valid(check_lane, opened.get('lane')) \
873
+ and _valid(members.device_name, opened.get('device')):
874
+ ms = _ms(opened.get('at'))
875
+ identity = resolve(opened['lane']) if ms is not None else None
876
+ if identity:
877
+ preferences['resume'] = {'lane': identity, 'at_ms': ms, 'revision': 1}
878
+
879
+ read_devices = {} # one entry per device name; a later file of the same name wins
880
+ for name, raw in devices or ():
881
+ if not _valid(members.device_name, name):
882
+ continue
883
+ meta, problem = _bounded_json(raw)
884
+ if problem or not isinstance(meta, dict):
885
+ continue
886
+ read_devices[name] = _device_presentation(meta)
887
+ device_local = {name: local for name, (local, _unclaimed) in read_devices.items() if local}
888
+
889
+ writer = document.get('updated_by_device')
890
+ return {
891
+ 'record': {'v': 1, 'principal_id': login, 'revision': 1, 'updated_by_device': MIGRATION,
892
+ 'preferences': preferences},
893
+ 'device_local': device_local,
894
+ 'source': {'updated_at_ms': _ms(document.get('updated_at')) or 0,
895
+ 'updated_by_device': writer if _valid(check_writer, writer) else None},
896
+ 'unresolved_lanes': sorted(unresolved),
897
+ 'kept_unknown_keys': sorted(key for key in document if key not in FIELDS),
898
+ 'legacy_seen': legacy_seen,
899
+ 'superseded_seen': sorted(superseded),
900
+ 'unclaimed_looks': sorted(name for name, (_local, unclaimed) in read_devices.items() if unclaimed),
901
+ }, None
902
+
903
+
904
+ def presentation_for(login, authority, boards=None, directory=None, done=None):
905
+ """presentation() over the live store: users/<quoted login>.json and the devices/<device>.json of every device the
906
+ login owns (owned_devices). -> (migration, None), (None, 'no_profile') without a file, or (None, refusal code).
907
+ Reads only; never raises."""
908
+ try:
909
+ file = path(login, directory)
910
+ except L.LanesError:
911
+ return None, 'login_not_wire_id'
912
+ try:
913
+ data = file.read_bytes()
914
+ except FileNotFoundError:
915
+ return None, 'no_profile'
916
+ except OSError:
917
+ return None, 'unreadable'
918
+ devices = []
919
+ for found in owned_devices(login):
920
+ try:
921
+ devices.append((found['device'], (L.STATE / 'devices' / f"{found['device']}.json").read_bytes()))
922
+ except OSError:
923
+ continue
924
+ return presentation(login, data, authority, boards, devices, done)
@@ -38,3 +38,12 @@ SSH refuses changed host keys until the administrator's new fingerprint has been
38
38
  Server-side board catalogs belong in `~/.config/lanes/workspaces/`; real workspaces, credentials and generated
39
39
  state are not part of the software package. Optional server facts such as a public SSH fallback are served from
40
40
  `~/.config/lanes/site.conf` by `lanes client-config`. See [installation](../docs/INSTALL.md).
41
+
42
+ ## Federation files (lanes-site/1)
43
+
44
+ This directory also carries the federation seam a host uses to reach boards whose containers run on other docker
45
+ hosts: `protocol.py` (the wire: framing, ops, typed errors, the tmux read allowlist, exec template ids),
46
+ `server.py` (what a guest runs behind the aggregator's site key, through the forced command `../bin/lanes-site-serve`)
47
+ and `conformance.py` (the suite any adapter must pass). They hold no deployment data. A board opts in with
48
+ `"transport": "guest:<ssh alias>"` in `catalog.json`; see the RUNBOOK's
49
+ [federation section](../docs/RUNBOOK.md#federation-lanes-site1-guests-behind-a-forced-command-key).
@@ -0,0 +1,280 @@
1
+ #!/usr/bin/env python3
2
+ """lanes-site/1 conformance kit: drives ANY adapter that serves the protocol on its stdin/stdout through the suite.
3
+
4
+ python3 conformance.py [--timeout S] -- ADAPTER ARGV...
5
+ python3 conformance.py -- ssh -T -o BatchMode=yes rd-work-site # a guest, through its forced command
6
+ python3 conformance.py -- python3 -S -E -B lanes/site/server.py # the reference server on this host
7
+
8
+ Python 3 stdlib only. One fresh connection per check (a check that needs a greeted connection says hello first).
9
+
10
+ The kit exists to catch an adapter that does NOT conform, so it never aims anything but a harmless read at a real
11
+ target. Every write verb, refused tmux verb, out-of-bound text and exec it sends names an UNREGISTERED target
12
+ (UNREGISTERED_CONTAINER and its socket `default`, UNREGISTERED_LANE): a conforming adapter checks a request's verb
13
+ and text before its recipient (protocol.py's normative check order) and still answers verb_refused, text_too_long or
14
+ text_unprintable; a non-conforming one answers socket_unregistered, lane_unregistered or container_unknown — the
15
+ check fails, and nothing reached a lane, because no registered socket, lane or container was named. A registered
16
+ lane the adapter lists is asked one read only (`has-session`, which changes nothing). Prints
17
+ `pass|fail <check> — detail` per check; exit 0 when nothing failed, 1 otherwise, 2 on a usage error. Every reply of
18
+ the run is also checked for a secret-looking key (protocol.secret_keys). Used by lanes/tests/unit/test_site_protocol.py
19
+ against the reference server and against sabotaged adapters, which it must fail without touching a registered
20
+ target; later against `lanesd site-serve` (AR §3.32)."""
21
+ import os
22
+ import subprocess
23
+ import sys
24
+ from pathlib import Path
25
+
26
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
27
+ import protocol as P # noqa: E402
28
+
29
+ UNREGISTERED_LANE = 'conformance--not-a-registered-lane'
30
+ UNREGISTERED_CONTAINER = 'conformance-not-a-container'
31
+
32
+
33
+ class Connection:
34
+ """One adapter process and its frame reader."""
35
+
36
+ def __init__(self, argv, env=None, timeout=5.0):
37
+ self.timeout, self.next_id, self.replies = timeout, 1, []
38
+ self.child = subprocess.Popen(argv, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
39
+ env=env)
40
+ self.reader = P.FrameReader(self.child.stdout.fileno())
41
+
42
+ def raw(self, data):
43
+ self.child.stdin.write(data)
44
+ self.child.stdin.flush()
45
+
46
+ def send(self, op, args=None, request_id=None, extra=None):
47
+ if request_id is None:
48
+ request_id, self.next_id = self.next_id, self.next_id + 1
49
+ self.raw(P.encode(dict({'id': request_id, 'op': op, 'args': {} if args is None else args}, **(extra or {}))))
50
+ return self.receive()
51
+
52
+ def receive(self):
53
+ reply = self.reader.read(self.timeout)
54
+ if reply is None:
55
+ raise AssertionError('the adapter closed the connection')
56
+ self.replies.append(reply)
57
+ return reply
58
+
59
+ def hello(self):
60
+ reply = self.send('hello', {'client': 'lanes-site-conformance', 'proto': P.PROTO}, request_id=0,
61
+ extra={'lanes_site': P.PROTO})
62
+ if 'ok' not in reply:
63
+ raise AssertionError(f'hello refused: {reply}')
64
+ return reply['ok']
65
+
66
+ def close(self):
67
+ try:
68
+ self.child.stdin.close()
69
+ except OSError:
70
+ pass
71
+ try:
72
+ self.child.wait(timeout=self.timeout)
73
+ except subprocess.TimeoutExpired:
74
+ self.child.kill()
75
+ self.child.wait()
76
+ self.child.stdout.close()
77
+
78
+
79
+ def expect_err(reply, *codes):
80
+ error = reply.get('err')
81
+ if not isinstance(error, dict) or error.get('code') not in codes:
82
+ raise AssertionError(f'expected err {"|".join(codes)}, got {reply}')
83
+ if not isinstance(error.get('human'), str):
84
+ raise AssertionError(f'an err without its human text: {reply}')
85
+
86
+
87
+ def check_op_before_hello(conn):
88
+ expect_err(conn.send('boards.list'), 'hello_required')
89
+
90
+
91
+ def check_newer_major_refused(conn):
92
+ expect_err(conn.send('hello', {'proto': P.PROTO + 1}, request_id=0, extra={'lanes_site': P.PROTO + 1}),
93
+ 'version_unsupported')
94
+
95
+
96
+ def check_hello_fields(conn):
97
+ ok = conn.hello()
98
+ if ok.get('lanes_site') != P.PROTO or ok.get('proto') != P.PROTO:
99
+ raise AssertionError(f'hello names another protocol: {ok}')
100
+ if not isinstance(ok.get('guest_id'), str) or not ok['guest_id'] or not isinstance(ok.get('boot_id'), str):
101
+ raise AssertionError(f'hello without guest_id/boot_id: {ok}')
102
+ if not isinstance(ok.get('versions'), dict):
103
+ raise AssertionError(f'hello without versions: {ok}')
104
+ missing = sorted(set(P.CAPABILITIES) - set(ok.get('capabilities') or [])) + \
105
+ sorted(set(P.OPS) - set(ok.get('ops') or []))
106
+ if missing:
107
+ raise AssertionError(f'hello does not list {missing}')
108
+ epochs = ok.get('epochs')
109
+ if not isinstance(epochs, dict) or not all(isinstance(n, int) and not isinstance(n, bool) and n >= 0
110
+ for n in epochs.values()):
111
+ raise AssertionError(f'hello without epochs {{workspace: N}}: {ok}')
112
+ return 'guest {guest_id}, lanes {lanes}'.format(guest_id=ok['guest_id'], lanes=ok['versions'].get('lanes'))
113
+
114
+
115
+ def check_ids_echoed(conn):
116
+ conn.hello()
117
+ reply = conn.send('boards.list', request_id=7341)
118
+ if reply.get('id') != 7341:
119
+ raise AssertionError(f'reply id {reply.get("id")} for request 7341')
120
+
121
+
122
+ def check_invalid_frame_typed(conn):
123
+ conn.hello()
124
+ conn.raw(b'this is not json\n')
125
+ expect_err(conn.receive(), 'frame_invalid')
126
+ if 'ok' not in conn.send('boards.list'):
127
+ raise AssertionError('the connection did not survive an invalid frame')
128
+
129
+
130
+ def check_unknown_op_typed(conn):
131
+ conn.hello()
132
+ expect_err(conn.send('fs.lock'), 'op_unknown') # AR §3.32: there is no fs.lock and no holder.send_text
133
+ expect_err(conn.send('holder.send_text'), 'op_unknown')
134
+
135
+
136
+ def first_tmux_lane(conn):
137
+ """(container, socket, session) of one registered tmux lane the adapter lists, or None."""
138
+ for board in conn.send('boards.list').get('ok', {}).get('boards') or []:
139
+ for lane in conn.send('boards.lanes', {'board': board.get('id')}).get('ok', {}).get('lanes') or []:
140
+ if lane.get('holder') == 'tmux' and isinstance(lane.get('tmux'), dict):
141
+ return lane.get('container'), lane['tmux'].get('socket'), lane['tmux'].get('session')
142
+ return None
143
+
144
+
145
+ def check_boards(conn):
146
+ conn.hello()
147
+ reply = conn.send('boards.list')
148
+ boards = (reply.get('ok') or {}).get('boards')
149
+ if not isinstance(boards, list) or not all(isinstance(b, dict) and isinstance(b.get('id'), str) for b in boards):
150
+ raise AssertionError(f'boards.list: {reply}')
151
+ for board in boards:
152
+ lanes = (conn.send('boards.lanes', {'board': board['id']}).get('ok') or {}).get('lanes')
153
+ if not isinstance(lanes, list):
154
+ raise AssertionError(f'boards.lanes {board["id"]}: no lanes list')
155
+ expect_err(conn.send('boards.lanes', {'board': 'conformance-no-such-board'}), 'board_unknown')
156
+ return f'{len(boards)} boards'
157
+
158
+
159
+ def check_registered_read(conn):
160
+ """The one request the kit aims at a registered target: a read that changes nothing."""
161
+ conn.hello()
162
+ found = first_tmux_lane(conn)
163
+ if found is None:
164
+ return 'no registered tmux lane listed: nothing read'
165
+ container, socket, session = found
166
+ reply = conn.send('tmux_read', {'container': container, 'socket': socket,
167
+ 'args': ['has-session', '-t', f'={session}']})
168
+ if 'ok' in reply:
169
+ if reply['ok'].get('outcome') not in ('ok', 'noserver', 'timeout', 'error'):
170
+ raise AssertionError(f'tmux_read answered no outcome: {reply}')
171
+ else:
172
+ expect_err(reply, 'container_unavailable')
173
+ return f'{container}/{socket}'
174
+
175
+
176
+ def check_read_refuses_writes(conn):
177
+ conn.hello()
178
+ for words in (['send-keys', '-t', '=x:', '-l', '--', 'x'], ['kill-server'], ['new-session', '-d'],
179
+ ['list-panes', '-a', '-F', '#(id)'], ['list-panes', '-a', '-F', '#{E:pane_title}'],
180
+ ['list-panes', '-a', '-F', '#{pane_start_command}'], ['list-sessions', '-F', '#{@secret}'],
181
+ ['list-sessions', '-F', 'x;'], ['display-message', 'x'],
182
+ ['capture-pane', '-t', '=x:'], ['capture-pane', '-p', '-b', 'buffer0'], ['list-panes', '-aF', 'x'],
183
+ ['set-option', '-g', 'exit-empty', 'off']):
184
+ # An unregistered target: a conforming adapter refuses the verb before it looks the socket up.
185
+ expect_err(conn.send('tmux_read', {'container': UNREGISTERED_CONTAINER, 'socket': 'default', 'args': words}),
186
+ 'verb_refused', 'args_invalid')
187
+
188
+
189
+ def check_read_unregistered_socket(conn):
190
+ conn.hello()
191
+ expect_err(conn.send('tmux_read', {'container': UNREGISTERED_CONTAINER, 'socket': 'default',
192
+ 'args': ['list-sessions']}), 'socket_unregistered')
193
+
194
+
195
+ def check_write_unregistered(conn):
196
+ conn.hello()
197
+ expect_err(conn.send('tmux_write', {'lane': UNREGISTERED_LANE, 'text': 'x', 'enter': False,
198
+ 'intent': 'conformance-1'}), 'lane_unregistered')
199
+ expect_err(conn.send('tmux_write', {'lane': UNREGISTERED_LANE, 'text': 'x', 'enter': 'yes'}), 'args_invalid')
200
+ for intent, epoch in (('a b', None), (7, None), (None, -1), (None, True), (None, '3')):
201
+ args = {'lane': UNREGISTERED_LANE, 'text': 'x', 'enter': False}
202
+ args.update({key: value for key, value in (('intent', intent), ('epoch', epoch)) if value is not None})
203
+ expect_err(conn.send('tmux_write', args), 'args_invalid')
204
+
205
+
206
+ def check_write_bounds(conn):
207
+ conn.hello()
208
+ # An unregistered lane: a conforming adapter refuses the text before it looks the lane up.
209
+ expect_err(conn.send('tmux_write', {'lane': UNREGISTERED_LANE, 'text': 'x' * (P.TEXT_MAX + 1), 'enter': False}),
210
+ 'text_too_long')
211
+ for text in ('a\nb', 'a\rb', '\x03', 'a\x1b[2J', ' ', ''):
212
+ expect_err(conn.send('tmux_write', {'lane': UNREGISTERED_LANE, 'text': text, 'enter': False}),
213
+ 'text_unprintable')
214
+
215
+
216
+ def check_exec_template_only(conn):
217
+ conn.hello()
218
+ expect_err(conn.send('exec', {'argv': ['sh', '-c', 'id']}), 'argv_refused')
219
+ expect_err(conn.send('exec', {'template': 'pulse.rearm', 'args': {'container': UNREGISTERED_CONTAINER,
220
+ 'argv': ['sh', '-c', 'id']}}), 'argv_refused')
221
+ expect_err(conn.send('exec', {'template': 'pulse.rearm', 'command': 'id',
222
+ 'args': {'container': UNREGISTERED_CONTAINER}}), 'argv_refused')
223
+ expect_err(conn.send('exec', {'template': 'sh', 'args': {'container': UNREGISTERED_CONTAINER}}), 'template_unknown')
224
+ for template in sorted(P.EXEC_TEMPLATES):
225
+ expect_err(conn.send('exec', {'template': template, 'args': {'container': UNREGISTERED_CONTAINER}}),
226
+ 'container_unknown')
227
+
228
+
229
+ CHECKS = [('op_before_hello_refused', check_op_before_hello), ('newer_major_refused', check_newer_major_refused),
230
+ ('hello_fields', check_hello_fields), ('ids_echoed', check_ids_echoed),
231
+ ('invalid_frame_typed', check_invalid_frame_typed), ('unknown_op_typed', check_unknown_op_typed),
232
+ ('boards', check_boards), ('registered_read', check_registered_read),
233
+ ('read_refuses_writes', check_read_refuses_writes),
234
+ ('read_unregistered_socket', check_read_unregistered_socket),
235
+ ('write_unregistered_refused', check_write_unregistered), ('write_bounds', check_write_bounds),
236
+ ('exec_template_only', check_exec_template_only)]
237
+
238
+
239
+ def run_suite(argv, env=None, timeout=5.0):
240
+ """[(check, 'pass'|'fail', detail)] of every check against the adapter `argv`, plus `no_secrets` over every reply."""
241
+ results, replies = [], []
242
+ for name, check in CHECKS:
243
+ conn = None
244
+ try:
245
+ conn = Connection(argv, env, timeout)
246
+ detail = check(conn) or ''
247
+ results.append((name, 'pass', detail))
248
+ except (AssertionError, P.ProtocolError, TimeoutError, OSError) as error:
249
+ results.append((name, 'fail', str(error)[:300]))
250
+ finally:
251
+ if conn is not None:
252
+ replies += conn.replies
253
+ conn.close()
254
+ leaked = sorted({key for reply in replies for key in P.secret_keys(reply)})
255
+ results.append(('no_secrets', 'fail' if leaked else 'pass', ', '.join(leaked) or f'{len(replies)} replies'))
256
+ return results
257
+
258
+
259
+ def main(argv):
260
+ timeout, rest = 5.0, list(argv)
261
+ while rest and rest[0] != '--':
262
+ word = rest.pop(0)
263
+ if word == '--timeout' and rest:
264
+ timeout = float(rest.pop(0))
265
+ else:
266
+ print(__doc__.split('\n\n')[1], file=sys.stderr)
267
+ return 2
268
+ if not rest or len(rest) < 2:
269
+ print('usage: conformance.py [--timeout S] -- ADAPTER ARGV...', file=sys.stderr)
270
+ return 2
271
+ results = run_suite(rest[1:], dict(os.environ), timeout)
272
+ for name, status, detail in results:
273
+ print(f'{status:<4} {name}' + (f' — {detail}' if detail else ''))
274
+ failed = [name for name, status, _detail in results if status == 'fail']
275
+ print(f'lanes-site/{P.PROTO} conformance: {len(results) - len(failed)}/{len(results)} pass')
276
+ return 1 if failed else 0
277
+
278
+
279
+ if __name__ == '__main__':
280
+ sys.exit(main(sys.argv[1:]))