@vibelord/lanes 1.7.2 → 1.7.4

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 (50) 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 +97 -17
  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 +105 -5
  8. package/payload/lanes/container/lane_core.py +110 -0
  9. package/payload/lanes/container/throttle-pulse +159 -14
  10. package/payload/lanes/docs/ARCHITECTURE.md +108 -11
  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 +297 -5
  14. package/payload/lanes/docs/USERGUIDE.md +11 -6
  15. package/payload/lanes/install/host-install.sh +14 -3
  16. package/payload/lanes/libexec/adopt.py +325 -0
  17. package/payload/lanes/libexec/cutover.py +656 -0
  18. package/payload/lanes/libexec/docsd.py +12 -8
  19. package/payload/lanes/libexec/doctor_lanes2.py +213 -0
  20. package/payload/lanes/libexec/economy_poll.py +87 -2
  21. package/payload/lanes/libexec/lanes_lib.py +465 -2
  22. package/payload/lanes/libexec/native.sh +38 -0
  23. package/payload/lanes/libexec/native_bin.py +668 -0
  24. package/payload/lanes/libexec/shadow.py +1311 -0
  25. package/payload/lanes/libexec/sidebar.py +269 -28
  26. package/payload/lanes/libexec/sidebar_status.py +373 -25
  27. package/payload/lanes/libexec/statusd.py +67 -3
  28. package/payload/lanes/libexec/tokens.py +99 -131
  29. package/payload/lanes/libexec/tokens.sh +1 -1
  30. package/payload/lanes/libexec/update.py +48 -5
  31. package/payload/lanes/libexec/users.py +282 -0
  32. package/payload/lanes/site/README.md +9 -0
  33. package/payload/lanes/site/conformance.py +280 -0
  34. package/payload/lanes/site/protocol.py +368 -0
  35. package/payload/lanes/site/server.py +314 -0
  36. package/payload/lanes/tokens/README.md +156 -0
  37. package/payload/lanes/tokens/generate.py +930 -0
  38. package/payload/lanes/tokens/generated/parity.v1.tsv +489 -0
  39. package/payload/lanes/tokens/generated/tokens.resolved.json +835 -0
  40. package/payload/lanes/tokens/tokens.v1.json +763 -0
  41. package/payload/lanes/tokens/tokens.v1.schema.json +143 -0
  42. package/payload/lanes/web/README.md +132 -4
  43. package/payload/lanes/web/directory.css +95 -0
  44. package/payload/lanes/web/directory.js +951 -0
  45. package/payload/lanes/web/generated/README.md +107 -0
  46. package/payload/lanes/web/generated/lanes2_protocol.d.mts +1162 -0
  47. package/payload/lanes/web/generated/lanes2_protocol.mjs +2333 -0
  48. package/payload/lanes/web/mobile.js +17 -21
  49. package/payload/lanes/web/tokens.css +137 -0
  50. package/payload/manifest.json +7 -4
@@ -0,0 +1,668 @@
1
+ #!/usr/bin/env python3
2
+ """Lanes 2.0 native (Rust) binaries and flags on a host (lanes2 Round 1 H2; AR 7.3, 9.3, D9; RT 3.1, 3.2). Python 3 stdlib.
3
+
4
+ lanes rs install --from PATH --sha256 HEX
5
+ place a locally built native binary (the development and offline route, mirroring `lanes studio-host
6
+ install --from`). PATH is a regular executable file named after a native binary (BINARIES: the `[[bin]]`
7
+ targets the lanes crates declare, lanes-terminal and lanes-hook). Refused before anything is written unless
8
+ its sha256 is HEX (`--sha256` is required: nothing is placed on a digest nobody stated). Under the lock
9
+ ~/.local/share/lanes/bin-rs/.lock it is copied to bin-rs/<name>-<sha12> (the copy hashed again before its
10
+ rename), INSTALLED.json records that file, and only then is the link bin-rs/<name> pointed at it in one
11
+ rename: a crash leaves the old link with its own record, never a link without one. Changes no flag and
12
+ restarts nothing. Exit 0 installed, 2 usage, 3 refused (binary_mismatch, installed_malformed, busy)
13
+ lanes rs uninstall NAME
14
+ remove the link bin-rs/NAME under the same lock (the placed file and its record stay), so the release tree's
15
+ own binary runs again, then remove every flags/native.* file whose binary no longer verifies (prune_flags).
16
+ Exit 0 removed (or nothing was installed), 2 usage, 3 refused (bin-rs/NAME is no link `lanes rs install` made)
17
+ lanes rs verify [--tree]
18
+ this tree's bin-rs/BINARIES.json (the npm payload's list, npm/lanes/scripts/build-payload.mjs) against the
19
+ files beside it — every listed binary present, executable, with its size and sha256, nothing there the list
20
+ does not name — and, without --tree, every binary `lanes rs install` linked; a `WARN` line names an install
21
+ that runs instead of a shipped binary with other bytes. Exit 0 all match (or there is none), 3 a mismatch
22
+ lanes rs status
23
+ each component's site.conf mode, its flag file and what runs (the verified native binary, or python). Exit 0
24
+ lanes rs apply
25
+ the one writer of the flag files: site.conf's LANES_RS_<COMPONENT>=off|shadow|on becomes the existence-only
26
+ files $LANES_STATE/flags/native.<component> (on) and native.<component>.shadow (shadow), each only for a mode
27
+ admit() accepts; every other native.* file is removed. Exit 0 every flag as asked, 3 a flag refused (kept off)
28
+ or a LANES_RS_ line not understood, 2 usage
29
+ python3 libexec/native_bin.py verify-tree TREE [--state DIR] [--prune-flags]
30
+ TREE's own binaries only (no share), for install/host-install.sh right before its commit and update.py's
31
+ post-commit step `verify bin-rs`; --prune-flags then removes every flags/native.* file whose binary does not
32
+ verify against TREE. Exit 0, 3 a mismatch (nothing pruned) or a flag file that could not be removed, 2 usage
33
+
34
+ Components are AR 7.3's. Each runs one payload binary (COMPONENT_BINARY), or none yet: AGENTD and MCP have no crate
35
+ that declares a binary (binary_absent), and STATUSD, VISIBILITY, NOTIFY, ECONOMY, SYNC, SITE and STORE are duties of
36
+ the host coordinator, a Rust library the throttle-rc Studio Host composes (RT 3.1): RT 3.2 allows one host owner per
37
+ state root and no lanesd beside an active Studio host, so no payload binary or unit serves them and their flags are
38
+ refused (host_composed) until the cutover fence (lanes2 H3) activates them in that composition. A binary is used only
39
+ when it verifies (resolve): first the `lanes rs install` link ~/.local/share/lanes/bin-rs/<name>, else the running
40
+ tree's bin-rs/<target>/<name> against BINARIES.json; a candidate that exists but does not verify is refused, never
41
+ passed over for the next. The shell readers' half (libexec/native.sh, for the view and sidebar hooks lane C7 owns)
42
+ stops at the same first candidate. Every way `current` moves keeps the flags true to the tree it moves to:
43
+ host-install.sh refuses a staged tree whose binaries do not verify and prunes the flags against it before its flip;
44
+ update.py's rollback prunes them against the tree it rolls back to before its flip."""
45
+ import contextlib
46
+ import fcntl
47
+ import hashlib
48
+ import json
49
+ import os
50
+ from pathlib import Path
51
+ import platform
52
+ import re
53
+ import secrets
54
+ import shutil
55
+ import sys
56
+ import tempfile
57
+ import time
58
+
59
+ import lanes_lib as L
60
+
61
+ TARGETS = {'x86_64': 'x86_64-unknown-linux-musl'} # `uname -m` -> the target the payload ships binaries for
62
+ # AR 7.3's strangler components, in its order: the `LANES_RS_<COMPONENT>` keys (upper case) and the flag files
63
+ # (lower case). Every one ships `off`.
64
+ COMPONENTS = ('signal', 'mcp', 'agentd', 'statusd', 'visibility', 'notify', 'economy', 'sync', 'site', 'store',
65
+ 'relay', 'sidebar', 'key')
66
+ # The duties of the host coordinator (RT 3.1: a Rust library composed by throttle-rc; RT 3.2: one host owner, no lanesd
67
+ # beside the Studio host): no payload binary runs them.
68
+ HOST_DUTIES = frozenset({'statusd', 'visibility', 'notify', 'economy', 'sync', 'site', 'store'})
69
+ # The payload binary a component runs: a `[[bin]]` target of the lanes crates. The Day-0 freeze (PR #626) declares
70
+ # lanes-terminal (RT 4: the CLI, TUI and attachment relay — the relay as its `relay` mode with connection.py's
71
+ # arguments, the sidebar as its `sidebar` mode, the hot keys lane C6's) and lanes-hook (RT 3.1: the hook emitter behind
72
+ # lane-signal). A component absent here has no binary yet. test_flags pins every name against the crates' Cargo.toml
73
+ # files; libexec/native.sh repeats them.
74
+ COMPONENT_BINARY = {'signal': 'lanes-hook', 'relay': 'lanes-terminal', 'sidebar': 'lanes-terminal',
75
+ 'key': 'lanes-terminal'}
76
+ # AR 7.4: the components whose strangler row has a shadow step. `shadow` for a component with a binary but no shadow
77
+ # step is refused (shadow_unsupported): a flag file that says shadow while nothing shadows is state no reader honours.
78
+ SHADOW_STEP = frozenset({'mcp', 'agentd', 'statusd', 'visibility', 'notify', 'economy', 'sync', 'site'})
79
+ BINARIES = frozenset(COMPONENT_BINARY.values())
80
+ MODES = ('off', 'shadow', 'on')
81
+ KEY = re.compile(r'^LANES_RS_([A-Z][A-Z_]*)$')
82
+ SETTINGS = frozenset({'LANES_RS_MCP_EXCLUDE'}) # AR 7.3: a LANES_RS_ key that is a setting, not a component
83
+ FLAG_PREFIX = 'native.' # $LANES_STATE/flags/native.<component>[.shadow]
84
+ NAME = re.compile(r'^lanes-[a-z0-9][a-z0-9-]{0,39}$') # build-payload.mjs RS_NAME
85
+ HEX64 = re.compile(r'^[0-9a-f]{64}$')
86
+ COMMIT = re.compile(r'^[0-9a-f]{40}$')
87
+ LIST = Path('bin-rs/BINARIES.json') # inside a tree (DM-LANES2-PAYLOAD-BINARIES)
88
+ LIST_SCHEMA = 'lanes.bin-rs/1'
89
+ LIST_ASIDE = frozenset({'BINARIES.json', 'THIRD-PARTY-NOTICES'}) # the files of bin-rs/ that are no target directory
90
+ INSTALLED = 'INSTALLED.json' # under $LANES_SHARE/bin-rs
91
+ INSTALLED_SCHEMA = 'lanes.bin-rs-installed/1'
92
+ LOCK = '.lock' # under $LANES_SHARE/bin-rs: install and uninstall hold it
93
+ LOCK_WAIT = 10 # seconds an install or uninstall waits for the lock
94
+ NOT_EXECUTABLE = 'not executable'
95
+ USAGE = ('usage: lanes rs install --from PATH --sha256 HEX | lanes rs uninstall NAME | lanes rs verify [--tree] | '
96
+ 'lanes rs status | lanes rs apply')
97
+ TREE_USAGE = 'usage: native_bin.py verify-tree TREE [--state DIR] [--prune-flags]'
98
+
99
+
100
+ class Refusal(Exception):
101
+ def __init__(self, code, message, rc=3):
102
+ super().__init__(message)
103
+ self.code, self.rc = code, rc
104
+
105
+
106
+ def host_target(machine=None):
107
+ """The payload target of this machine (`uname -m`), or None: only x86_64 has binaries; any other stays Python."""
108
+ return TARGETS.get(machine if machine is not None else platform.machine())
109
+
110
+
111
+ def flag_file(component, mode):
112
+ """The flag file name (under $LANES_STATE/flags) of `component` in `mode` (on or shadow)."""
113
+ return FLAG_PREFIX + component + ('' if mode == 'on' else '.shadow')
114
+
115
+
116
+ def parse_flag_file(name):
117
+ """(component, mode) a flag file name stands for, or None for a native.* name no known component projects."""
118
+ if not name.startswith(FLAG_PREFIX):
119
+ return None
120
+ component, mode = name[len(FLAG_PREFIX):], 'on'
121
+ if component.endswith('.shadow'):
122
+ component, mode = component[:-len('.shadow')], 'shadow'
123
+ return (component, mode) if component in COMPONENTS else None
124
+
125
+
126
+ def native_flags(conf):
127
+ """site.conf facts ({key: value}, L.site_conf) -> ({component: mode} for every component, [problem]). A missing key
128
+ is `off`; a value outside MODES is `off` with a problem; a LANES_RS_<X> naming no component is a problem and changes
129
+ nothing (the key never becomes a flag file)."""
130
+ modes, problems = {component: 'off' for component in COMPONENTS}, []
131
+ for key in sorted(conf):
132
+ found = KEY.match(key)
133
+ if not found or key in SETTINGS:
134
+ continue
135
+ component, value = found.group(1).lower(), conf[key]
136
+ if component not in modes:
137
+ problems.append(f'{key}: unknown component (known: {" ".join(c.upper() for c in COMPONENTS)}); ignored')
138
+ elif value not in MODES:
139
+ problems.append(f'{key}={value}: not one of {"|".join(MODES)}; read as off')
140
+ else:
141
+ modes[component] = value
142
+ return modes, problems
143
+
144
+
145
+ def sha256_file(path):
146
+ """(sha256 hex, size) of the file at `path`."""
147
+ digest, size = hashlib.sha256(), 0
148
+ with open(path, 'rb') as handle:
149
+ for block in iter(lambda: handle.read(1 << 20), b''):
150
+ digest.update(block)
151
+ size += len(block)
152
+ return digest.hexdigest(), size
153
+
154
+
155
+ def read_list(tree):
156
+ """The binaries `tree`'s bin-rs/BINARIES.json lists -> [{name, target, sha256, size, commit}]; [] when the tree has
157
+ no list (a tree from before 2.0, a checkout). Raises Refusal('list_malformed') for a list that is not well formed —
158
+ an entry without its digest among them: a binary is never shipped, or used, on a digest nobody recorded."""
159
+ path = Path(tree) / LIST
160
+ try:
161
+ document = json.loads(path.read_text())
162
+ except FileNotFoundError:
163
+ return []
164
+ except (OSError, ValueError) as error:
165
+ raise Refusal('list_malformed', f'{path}: {error}')
166
+ if not isinstance(document, dict) or document.get('schema') != LIST_SCHEMA \
167
+ or not isinstance(document.get('binaries'), list):
168
+ raise Refusal('list_malformed', f'{path}: not a {LIST_SCHEMA} document')
169
+ entries, seen = [], set()
170
+ for entry in document['binaries']:
171
+ if not isinstance(entry, dict):
172
+ raise Refusal('list_malformed', f'{path}: an entry is not an object')
173
+ name, target, sha, size, commit = (entry.get(key) for key in ('name', 'target', 'sha256', 'size', 'commit'))
174
+ problem = ('name' if not isinstance(name, str) or not NAME.match(name) else
175
+ 'target' if target not in TARGETS.values() else
176
+ 'sha256' if not isinstance(sha, str) or not HEX64.match(sha) else
177
+ 'size' if not isinstance(size, int) or isinstance(size, bool) or size < 0 else
178
+ 'commit' if not isinstance(commit, str) or not COMMIT.match(commit) else None)
179
+ if problem:
180
+ raise Refusal('list_malformed', f'{path}: entry {name!r} has no valid {problem}')
181
+ if (target, name) in seen:
182
+ raise Refusal('list_malformed', f'{path}: {target}/{name} is listed twice')
183
+ seen.add((target, name))
184
+ entries.append({'name': name, 'target': target, 'sha256': sha, 'size': size, 'commit': commit})
185
+ return entries
186
+
187
+
188
+ def carries_binaries(tree):
189
+ """Whether `tree` has native binaries to verify: a list naming one, a list that is not well formed, or anything in
190
+ bin-rs/ besides the list and the notices (a binary the list may fail to name). False for a tree with no bin-rs/, or
191
+ with an empty list alone (a payload with zero binaries)."""
192
+ try:
193
+ if read_list(tree):
194
+ return True
195
+ except Refusal:
196
+ return True
197
+ try:
198
+ return any(entry.name not in LIST_ASIDE for entry in (Path(tree) / 'bin-rs').iterdir())
199
+ except OSError:
200
+ return False
201
+
202
+
203
+ def check_file(path, sha, size):
204
+ """None when `path` is a regular file (not a link) of `size` bytes hashing to `sha` that this account may execute,
205
+ else what is wrong (NOT_EXECUTABLE for the last)."""
206
+ path = Path(path)
207
+ if path.is_symlink() or not path.is_file():
208
+ return 'missing'
209
+ try:
210
+ actual, length = sha256_file(path)
211
+ except OSError as error:
212
+ return f'unreadable ({error.strerror or error})'
213
+ if size is not None and length != size:
214
+ return f'size {length}, recorded {size}'
215
+ if actual != sha:
216
+ return f'sha256 {actual}, recorded {sha}'
217
+ if not os.access(path, os.X_OK):
218
+ return NOT_EXECUTABLE
219
+ return None
220
+
221
+
222
+ def refusal_code(problem):
223
+ """The flag refusal a check_file/check_installed problem stands for."""
224
+ return 'not_executable' if problem == NOT_EXECUTABLE else 'digest_mismatch'
225
+
226
+
227
+ def verify_tree(tree):
228
+ """[(label, problem or None)] for every binary of `tree`'s bin-rs/: each listed one checked, then every file in a
229
+ target directory the list does not name (`unlisted`: shipped without a digest), and any unknown directory."""
230
+ tree = Path(tree)
231
+ try:
232
+ entries = read_list(tree)
233
+ except Refusal as error:
234
+ return [('BINARIES.json', str(error))]
235
+ results, listed = [], set()
236
+ for entry in entries:
237
+ relative = f"bin-rs/{entry['target']}/{entry['name']}"
238
+ listed.add(relative)
239
+ results.append((relative, check_file(tree / relative, entry['sha256'], entry['size'])))
240
+ root = tree / 'bin-rs'
241
+ try:
242
+ directories = sorted(root.iterdir())
243
+ except OSError:
244
+ directories = []
245
+ for directory in directories:
246
+ if directory.name in LIST_ASIDE:
247
+ continue
248
+ if directory.name not in TARGETS.values() or directory.is_symlink() or not directory.is_dir():
249
+ results.append((f'bin-rs/{directory.name}', 'not a target directory'))
250
+ continue
251
+ for item in sorted(directory.iterdir()):
252
+ relative = f'bin-rs/{directory.name}/{item.name}'
253
+ if relative not in listed:
254
+ results.append((relative, 'unlisted: BINARIES.json records no digest for it'))
255
+ return results
256
+
257
+
258
+ def read_installed(share):
259
+ """{placed file name: record} of INSTALLED.json under `share`/bin-rs ({} without one). Raises
260
+ Refusal('installed_malformed') for one that is not well formed: never read as empty, which would drop every other
261
+ binary's record."""
262
+ path = Path(share) / 'bin-rs' / INSTALLED
263
+ try:
264
+ document = json.loads(path.read_text())
265
+ except FileNotFoundError:
266
+ return {}
267
+ except (OSError, ValueError) as error:
268
+ raise Refusal('installed_malformed', f'{path}: {error}')
269
+ if not isinstance(document, dict) or document.get('schema') != INSTALLED_SCHEMA \
270
+ or not isinstance(document.get('files'), dict):
271
+ raise Refusal('installed_malformed', f'{path}: not a {INSTALLED_SCHEMA} document')
272
+ return document['files']
273
+
274
+
275
+ def placed_name(name, sha):
276
+ """The file name `lanes rs install` places the binary `name` with digest `sha` under: <name>-<sha12>."""
277
+ return f'{name}-{sha[:12]}'
278
+
279
+
280
+ def check_installed(share, name, files=None):
281
+ """None when `share`/bin-rs/<name> is a link `lanes rs install` made — to a file <name>-<sha12> beside it that
282
+ INSTALLED.json records under that file name — and that file matches its record, else what is wrong. `files`
283
+ (read_installed) is read here when not given."""
284
+ directory = Path(share) / 'bin-rs'
285
+ link = directory / name
286
+ if not link.is_symlink():
287
+ return 'not the link `lanes rs install` makes (a file placed by hand)'
288
+ target = os.readlink(link)
289
+ if not re.fullmatch(re.escape(name) + r'-[0-9a-f]{12}', target):
290
+ return f'links to {target!r}, not to a {name}-<sha12> file `lanes rs install` placed'
291
+ try:
292
+ files = read_installed(share) if files is None else files
293
+ except Refusal as error:
294
+ return str(error)
295
+ record = files.get(target)
296
+ if not isinstance(record, dict) or record.get('name') != name or not isinstance(record.get('sha256'), str) \
297
+ or not HEX64.match(record['sha256']) or placed_name(name, record['sha256']) != target:
298
+ return f'{INSTALLED} has no record of {target}'
299
+ return check_file(directory / target, record['sha256'], record.get('size'))
300
+
301
+
302
+ def installed_names(share):
303
+ """The native binaries `lanes rs install` linked under `share`: a bin-rs/<name> entry exists, whatever it is."""
304
+ directory = Path(share) / 'bin-rs'
305
+ return sorted(name for name in BINARIES if os.path.lexists(directory / name))
306
+
307
+
308
+ def verify_installed(share):
309
+ """[(label, problem or None)] for every binary linked under `share` (nothing when none is)."""
310
+ names = installed_names(share)
311
+ if not names:
312
+ return []
313
+ try:
314
+ files = read_installed(share)
315
+ except Refusal as error:
316
+ return [(INSTALLED, str(error))]
317
+ return [(f'share bin-rs/{name}', check_installed(share, name, files)) for name in names]
318
+
319
+
320
+ def shadowing(tree, share, machine=None):
321
+ """`WARN` lines for every explicit install that runs instead of a binary `tree` ships with other bytes."""
322
+ target = host_target(machine)
323
+ try:
324
+ shipped = {entry['name']: entry for entry in read_list(tree) if entry['target'] == target}
325
+ files = read_installed(share)
326
+ except Refusal:
327
+ return []
328
+ lines = []
329
+ for name in installed_names(share):
330
+ link = Path(share) / 'bin-rs' / name
331
+ record = files.get(os.readlink(link)) if link.is_symlink() else None
332
+ entry = shipped.get(name)
333
+ if entry and isinstance(record, dict) and record.get('sha256') != entry['sha256']:
334
+ lines.append(f"WARN share bin-rs/{name} ({str(record.get('sha256'))[:12]}) runs instead of this tree's "
335
+ f"bin-rs/{target}/{name} ({entry['sha256'][:12]}); `lanes rs uninstall {name}` returns to it")
336
+ return lines
337
+
338
+
339
+ def resolve(component, tree, share, machine=None):
340
+ """(path, None) of the verified binary `component` runs, or (None, reason). The explicitly installed one wins
341
+ (`lanes rs install`); else the tree's for this machine's target. A candidate that exists but does not verify is
342
+ refused (digest_mismatch, not_executable), never passed over for the next: what runs is what was checked."""
343
+ name = COMPONENT_BINARY.get(component)
344
+ if name is None:
345
+ return None, f'binary_absent: no lanes crate declares a binary for {component.upper()} yet'
346
+ installed = Path(share) / 'bin-rs' / name
347
+ if os.path.lexists(installed):
348
+ problem = check_installed(share, name)
349
+ return (installed, None) if problem is None else (None, f'{refusal_code(problem)}: {installed}: {problem}')
350
+ target = host_target(machine)
351
+ if target is None:
352
+ return None, f'arch_unsupported: no {name} for {platform.machine() if machine is None else machine}'
353
+ shipped = Path(tree) / 'bin-rs' / target / name
354
+ if not os.path.lexists(shipped):
355
+ return None, f'binary_absent: no {name} installed (lanes rs install) or in {Path(tree) / LIST}'
356
+ try:
357
+ entry = next((e for e in read_list(tree) if e['name'] == name and e['target'] == target), None)
358
+ except Refusal as error:
359
+ return None, f'digest_mismatch: {error}'
360
+ if entry is None:
361
+ return None, f'digest_mismatch: {shipped}: unlisted: BINARIES.json records no digest for it'
362
+ problem = check_file(shipped, entry['sha256'], entry['size'])
363
+ return (shipped, None) if problem is None else (None, f'{refusal_code(problem)}: {shipped}: {problem}')
364
+
365
+
366
+ def admit(component, mode, tree, share, machine=None):
367
+ """(path, None) when `component` may run natively in `mode` (on or shadow) from `tree`, else (None, reason): a host
368
+ duty never (host_composed), a component without a binary never (binary_absent), `shadow` only with a shadow step
369
+ (shadow_unsupported), and otherwise exactly when resolve() verifies its binary."""
370
+ if component in HOST_DUTIES:
371
+ return None, (f'host_composed: {component.upper()} is a duty of the host coordinator, which the throttle-rc '
372
+ 'Studio Host composes (RT 3.1); no payload binary serves it and no second host owner starts '
373
+ 'beside the Studio host (RT 3.2); its activation is the cutover fence (lanes2 H3)')
374
+ if component in COMPONENT_BINARY and mode == 'shadow' and component not in SHADOW_STEP:
375
+ return None, f'shadow_unsupported: {component.upper()} has no shadow step (AR 7.4); set on or off'
376
+ return resolve(component, tree, share, machine)
377
+
378
+
379
+ def flag_files(state):
380
+ """The native.* names present under `state`/flags (sorted; [] without the directory)."""
381
+ try:
382
+ return sorted(entry.name for entry in (Path(state) / 'flags').iterdir() if entry.name.startswith(FLAG_PREFIX))
383
+ except OSError:
384
+ return []
385
+
386
+
387
+ def remove_flag(state, name, problems):
388
+ """Remove `state`/flags/<name> -> True when it went; a failure is added to `problems` (a directory someone made
389
+ there: reported, never followed)."""
390
+ try:
391
+ (Path(state) / 'flags' / name).unlink()
392
+ return True
393
+ except FileNotFoundError:
394
+ return False
395
+ except OSError as error:
396
+ problems.append(f'flags/{name}: could not remove ({error.strerror or error})')
397
+ return False
398
+
399
+
400
+ def prune_flags(state, tree, share, machine=None):
401
+ """Remove every flags/native.* file that `tree` and `share` do not admit -> ([(name, reason)] removed, [problem]).
402
+ `tree` is the one `current` is about to name (host-install.sh, a rollback) or names (uninstall)."""
403
+ removed, problems = [], []
404
+ for name in flag_files(state):
405
+ parsed = parse_flag_file(name)
406
+ reason = ('no known component projects this file' if parsed is None
407
+ else admit(parsed[0], parsed[1], tree, share, machine)[1])
408
+ if reason and remove_flag(state, name, problems):
409
+ removed.append((name, reason))
410
+ return removed, problems
411
+
412
+
413
+ def apply_flags(state, conf, tree, share, machine=None):
414
+ """`lanes rs apply`: make $LANES_STATE/flags/native.* say what site.conf `conf` asks for and admit() allows -> a
415
+ report {modes, problems, refused: [(component, mode, reason)], created: [name], removed: [name]}. Existence only:
416
+ a flag file is created empty and never rewritten; every native.* file outside the wanted set is removed."""
417
+ modes, problems = native_flags(conf)
418
+ effective, refused = dict(modes), []
419
+ for component, mode in modes.items():
420
+ if mode != 'off':
421
+ path, reason = admit(component, mode, tree, share, machine)
422
+ if path is None:
423
+ refused.append((component, mode, reason))
424
+ effective[component] = 'off'
425
+ wanted = {flag_file(component, mode) for component, mode in effective.items() if mode != 'off'}
426
+ flags = Path(state) / 'flags'
427
+ created, removed = [], []
428
+ if wanted:
429
+ flags.mkdir(parents=True, exist_ok=True)
430
+ for name in sorted(wanted):
431
+ if not os.path.lexists(flags / name):
432
+ os.close(os.open(flags / name, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o644))
433
+ created.append(name)
434
+ for name in flag_files(state):
435
+ if name not in wanted and remove_flag(state, name, problems):
436
+ removed.append(name)
437
+ return {'modes': effective, 'problems': problems, 'refused': refused, 'created': created, 'removed': removed}
438
+
439
+
440
+ def apply_lines(report):
441
+ """`lanes rs apply`'s lines: the problems, refusals and changes, then one summary."""
442
+ lines = [f'! {problem}' for problem in report['problems']]
443
+ lines += [f'! LANES_RS_{component.upper()}={mode} refused, kept off: {reason}'
444
+ for component, mode, reason in report['refused']]
445
+ lines += [f'flags/{name} created' for name in report['created']]
446
+ lines += [f'flags/{name} removed' for name in report['removed']]
447
+ lit = [f'{component.upper()}={mode}' for component, mode in report['modes'].items() if mode != 'off']
448
+ lines.append(f"native flags: {' '.join(lit) if lit else 'every component off'}; a view or sidebar picks a change "
449
+ 'up when it starts again (lanes reload-views)')
450
+ return lines
451
+
452
+
453
+ def status_lines(state, conf, tree, share, machine=None):
454
+ """`lanes rs status`: one line per component — site.conf's mode, the flag file, what runs — then the warnings."""
455
+ modes, problems = native_flags(conf)
456
+ present = set(flag_files(state))
457
+ lines = [f'! {problem}' for problem in problems]
458
+ lines.append(f"{'component':<11} {'site.conf':<9} {'flag':<6} runs")
459
+ for component in COMPONENTS:
460
+ flag = next((mode for mode in ('on', 'shadow') if flag_file(component, mode) in present), 'off')
461
+ runs = 'python'
462
+ if flag != 'off':
463
+ path, reason = admit(component, flag, tree, share, machine)
464
+ runs = str(path) if path else f'python (the flag is no longer admitted: {reason})'
465
+ if modes[component] != flag:
466
+ runs += f'; site.conf says {modes[component]}: lanes rs apply'
467
+ lines.append(f'{component.upper():<11} {modes[component]:<9} {flag:<6} {runs}')
468
+ lines += [f'! flags/{name}: no known component projects it; lanes rs apply removes it'
469
+ for name in sorted(present) if parse_flag_file(name) is None]
470
+ return lines + shadowing(tree, share, machine)
471
+
472
+
473
+ def swap_link(link, target):
474
+ """Point `link` at `target` (a name in the same directory) in one rename(2)."""
475
+ temporary = link.parent / f'.{link.name}.{os.getpid()}.{secrets.token_hex(4)}'
476
+ os.symlink(target, temporary)
477
+ try:
478
+ os.replace(temporary, link)
479
+ except BaseException:
480
+ if os.path.lexists(temporary):
481
+ os.unlink(temporary)
482
+ raise
483
+
484
+
485
+ @contextlib.contextmanager
486
+ def share_lock(directory, wait=None):
487
+ """The exclusive flock(2) on `directory`/.lock that install and uninstall hold while they change bin-rs/; another
488
+ holder for longer than `wait` seconds (default LOCK_WAIT) refuses (busy)."""
489
+ directory.mkdir(parents=True, exist_ok=True)
490
+ descriptor = os.open(directory / LOCK, os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW | os.O_CLOEXEC, 0o600)
491
+ try:
492
+ deadline = time.monotonic() + (LOCK_WAIT if wait is None else wait)
493
+ while True:
494
+ try:
495
+ fcntl.flock(descriptor, fcntl.LOCK_EX | fcntl.LOCK_NB)
496
+ break
497
+ except BlockingIOError:
498
+ if time.monotonic() >= deadline:
499
+ raise Refusal('busy', f'another lanes rs install or uninstall holds {directory / LOCK}')
500
+ time.sleep(0.1)
501
+ yield
502
+ finally:
503
+ os.close(descriptor)
504
+
505
+
506
+ def install_local(share, source, expected):
507
+ """`lanes rs install --from PATH --sha256 HEX` -> the INSTALLED.json record of the binary placed, with `file`."""
508
+ if not isinstance(expected, str) or not HEX64.match(expected):
509
+ raise Refusal('usage', '--sha256 must be 64 lowercase hex', 2)
510
+ source = Path(source)
511
+ if source.is_symlink() or not source.is_file():
512
+ raise Refusal('usage', f'{source} is not a regular file (a symbolic link is refused: name the file itself)', 2)
513
+ if not os.access(source, os.X_OK):
514
+ raise Refusal('usage', f'{source} is not executable', 2)
515
+ name = source.name
516
+ if name not in BINARIES:
517
+ raise Refusal('usage', f'{name} is not a native binary\'s name (one of {", ".join(sorted(BINARIES))})', 2)
518
+ actual, size = sha256_file(source)
519
+ if actual != expected:
520
+ raise Refusal('binary_mismatch', f'{source} hashed {actual}, not the --sha256 given; nothing installed')
521
+ directory = Path(share) / 'bin-rs'
522
+ with share_lock(directory):
523
+ files = read_installed(share) # a malformed record refuses here, before anything is placed
524
+ placed = placed_name(name, actual)
525
+ fd, temporary = tempfile.mkstemp(prefix=f'.{name}-', dir=directory)
526
+ try:
527
+ with os.fdopen(fd, 'wb') as out, open(source, 'rb') as src:
528
+ shutil.copyfileobj(src, out)
529
+ os.chmod(temporary, 0o755)
530
+ copied, _ = sha256_file(temporary)
531
+ if copied != expected: # the source changed while it was copied
532
+ raise Refusal('binary_mismatch', f'the copy hashed {copied}, not {expected}; nothing installed')
533
+ os.replace(temporary, directory / placed)
534
+ finally:
535
+ if os.path.exists(temporary):
536
+ os.unlink(temporary)
537
+ record = {'name': name, 'sha256': actual, 'size': size, 'from': str(source.resolve()),
538
+ 'installed_at': time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime())}
539
+ files[placed] = record
540
+ # The record first, the link last: a crash between them leaves the previous link, which its own record still
541
+ # vouches for, beside a record of a file nothing links yet.
542
+ L.atomic_write(directory / INSTALLED, json.dumps({'schema': INSTALLED_SCHEMA, 'files': files}, indent=1,
543
+ sort_keys=True) + '\n')
544
+ swap_link(directory / name, placed)
545
+ return dict(record, file=placed)
546
+
547
+
548
+ def uninstall_local(share, name):
549
+ """`lanes rs uninstall NAME`: remove the link bin-rs/NAME -> True when it went, False when there was none. The
550
+ placed file and its INSTALLED.json record stay (no pruning yet); a later install of the same bytes reuses them."""
551
+ if name not in BINARIES:
552
+ raise Refusal('usage', f'{name} is not a native binary\'s name (one of {", ".join(sorted(BINARIES))})', 2)
553
+ directory = Path(share) / 'bin-rs'
554
+ if not os.path.lexists(directory / name):
555
+ return False
556
+ with share_lock(directory):
557
+ link = directory / name
558
+ if not os.path.lexists(link):
559
+ return False
560
+ if not link.is_symlink():
561
+ raise Refusal('not_a_link', f'{link} is no link `lanes rs install` made; remove it by hand')
562
+ link.unlink()
563
+ return True
564
+
565
+
566
+ def verify_lines(tree, share, tree_only, machine=None):
567
+ """(lines, rc) of `lanes rs verify [--tree]`."""
568
+ results = verify_tree(tree) + ([] if tree_only else verify_installed(share))
569
+ lines = [f'ok {label}' if problem is None else f'FAIL {label}: {problem}' for label, problem in results]
570
+ if not tree_only:
571
+ lines += shadowing(tree, share, machine)
572
+ bad = [label for label, problem in results if problem is not None]
573
+ lines.append(f'{len(results) - len(bad)} of {len(results)} native binaries verified' if results
574
+ else 'no native binaries')
575
+ return lines, 3 if bad else 0
576
+
577
+
578
+ def tree_main(args, out, share=None):
579
+ """`native_bin.py verify-tree TREE [--state DIR] [--prune-flags]` (host-install.sh, update.py) -> exit status."""
580
+ rest, state, prune = list(args), L.STATE, False
581
+ if not rest or rest[0].startswith('-'):
582
+ print(TREE_USAGE, file=out)
583
+ return 2
584
+ tree = Path(rest.pop(0))
585
+ while rest:
586
+ item = rest.pop(0)
587
+ if item == '--prune-flags' and not prune:
588
+ prune = True
589
+ elif item == '--state' and rest:
590
+ state = Path(rest.pop(0))
591
+ else:
592
+ print(TREE_USAGE, file=out)
593
+ return 2
594
+ lines, rc = verify_lines(tree, None, True)
595
+ if carries_binaries(tree): # a tree without native binaries (every release so far) says nothing here
596
+ for line in lines:
597
+ print(f'native binaries of {tree}: {line}', file=out)
598
+ if rc:
599
+ print(f'refused: {tree} ships a native binary that does not verify; nothing changed', file=out)
600
+ return rc
601
+ if prune:
602
+ removed, problems = prune_flags(state, tree, L.SHARE if share is None else share)
603
+ for name, reason in removed:
604
+ print(f'native flag flags/{name} removed: {reason}', file=out)
605
+ for problem in problems:
606
+ print(f'! native flags: {problem}', file=out)
607
+ if problems:
608
+ return 3
609
+ return 0
610
+
611
+
612
+ def main(args, out=None, tree=None, share=None, state=None, home=None, machine=None):
613
+ """`lanes rs …` (bin/lanes cmd_rs) -> exit status. `tree` defaults to the tree this code runs from (the installed
614
+ release when run as `lanes`), `share`/`state` to $LANES_SHARE/$LANES_STATE, `home` to this account's (site.conf)."""
615
+ out = sys.stdout if out is None else out
616
+ tree = L.REPO if tree is None else Path(tree)
617
+ share = L.SHARE if share is None else Path(share)
618
+ state = L.STATE if state is None else Path(state)
619
+ try:
620
+ if args[:1] == ['install']:
621
+ options, rest = {}, list(args[1:])
622
+ while rest:
623
+ item = rest.pop(0)
624
+ if item not in ('--from', '--sha256') or not rest or item in options:
625
+ raise Refusal('usage', USAGE, 2)
626
+ options[item] = rest.pop(0)
627
+ if '--from' not in options or '--sha256' not in options:
628
+ raise Refusal('usage', f'{USAGE} (both --from and --sha256 are required)', 2)
629
+ record = install_local(share, options['--from'], options['--sha256'])
630
+ print(f"installed {record['name']} {record['sha256'][:12]} at {share / 'bin-rs' / record['name']}; no flag "
631
+ 'changed (site.conf LANES_RS_<COMPONENT>, then lanes rs apply)', file=out)
632
+ return 0
633
+ if args[:1] == ['uninstall'] and len(args) == 2:
634
+ if not uninstall_local(share, args[1]):
635
+ print(f'{args[1]} is not installed under {share / "bin-rs"}; nothing changed', file=out)
636
+ return 0
637
+ print(f'uninstalled {args[1]}: where its flag stays on, the release tree\'s own binary runs', file=out)
638
+ removed, problems = prune_flags(state, tree, share, machine)
639
+ for name, reason in removed:
640
+ print(f'flags/{name} removed: {reason}', file=out)
641
+ for problem in problems:
642
+ print(f'! {problem}', file=out)
643
+ return 3 if problems else 0
644
+ if args in (['verify'], ['verify', '--tree']):
645
+ lines, rc = verify_lines(tree, share, args == ['verify', '--tree'], machine)
646
+ for line in lines:
647
+ print(line, file=out)
648
+ return rc
649
+ if args == ['status']:
650
+ for line in status_lines(state, L.site_conf(home), tree, share, machine):
651
+ print(line, file=out)
652
+ return 0
653
+ if args == ['apply']:
654
+ report = apply_flags(state, L.site_conf(home), tree, share, machine)
655
+ for line in apply_lines(report):
656
+ print(line, file=out)
657
+ return 3 if report['problems'] or report['refused'] else 0
658
+ raise Refusal('usage', USAGE, 2)
659
+ except Refusal as error:
660
+ print(f'lanes rs: {error}' if error.code == 'usage' else f'lanes rs: refused ({error.code}): {error}', file=out)
661
+ return error.rc
662
+
663
+
664
+ if __name__ == '__main__':
665
+ if sys.argv[1:2] == ['verify-tree']:
666
+ sys.exit(tree_main(sys.argv[2:], sys.stdout))
667
+ print(TREE_USAGE, file=sys.stderr)
668
+ sys.exit(2)