@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,325 @@
1
+ #!/usr/bin/env python3
2
+ """adopt.py — installed adoption of the Lanes 2.0 store (lanes2 Round 2 S12; Rust runtime specification §17.1, the
3
+ adoption half; P32; BEY-6988). Python 3 stdlib.
4
+
5
+ python3 libexec/adopt.py adopt [--state DIR] [--tree DIR] [--json] adopt every domain; exit 0 every domain adopted,
6
+ 3 a domain refused, 1 an I/O failure, 2 usage
7
+ python3 libexec/adopt.py status [--state DIR] [--json] what is adopted, verified on disk; exit 0 every
8
+ domain verified, 3 otherwise (or none adopted)
9
+ python3 libexec/adopt.py doctor [--state DIR] `lanes doctor`'s lines (doctor_lines)
10
+
11
+ WHAT ADOPTION IS. An existing 1.x install gains the Lanes 2.0 state layout without a manual step: `lanes update`'s
12
+ post-commit runs `adopt` from the tree it just installed (update.py ADOPT_STEP), on every update, idempotently. For
13
+ every state domain of DOMAINS it makes sure the domain's cutover record exists (DM-LANES2-CUTOVER-RECORD,
14
+ `$LANES_STATE/cutover/<domain>.json`, written through cutover.py's compare-and-swap writer): a domain without one gets
15
+ exactly the record the Rust fence would create on its first open (`DomainFence::open`): phase `shadow`, epoch 1, owner
16
+ `lanes-py`, no previous owner, schema 1, nothing fenced. A domain that already has a record keeps it untouched, whatever
17
+ its phase or owner (a cutover in progress, a domain a Rust owner took): adoption never moves ownership. It creates the
18
+ store's directory `$LANES_STATE/store/` (0700) and never the store itself: the host coordinator's store owner creates
19
+ `coordination.sqlite` and migrates it on its first open (lane B3; a second migrator would be a second schema
20
+ authority). Last, it writes the adoption record `$LANES_STATE/lanes2/adoption.json` (`lanes2.adoption/1`, 0600):
21
+
22
+ {"v": 1, "kind": "lanes2.adoption/1", "adopted_at": "<UTC>", "release": "<tree VERSION>",
23
+ "store": "<state>/store/coordination.sqlite", "domains": [<every domain verified>],
24
+ "refused": [{"domain": D, "code": C}]}
25
+
26
+ `domains` lists a domain only after its record was read back from disk and parsed (verify_domain): a domain whose
27
+ write failed or was skipped is never reported adopted, and `refused` names it with its code (`record_malformed`,
28
+ `record_unreadable`, `journal_conflict`, `record_missing`, ...).
29
+
30
+ WHAT IT NEVER DOES. No flag: `$LANES_STATE/flags/native.*` and site.conf's `LANES_RS_*` keys are lane H2's and stay as
31
+ they are (every component off); no unit, no daemon, no import of legacy data (a domain's records are imported by its
32
+ cutover fence, RT 17.1, never by adoption); no Rust binary is run. With the records owned by `lanes-py`, a Rust host
33
+ that recovers (crates/lanes-runtime/src/recovery) comes up fenced, read-only, until a domain's cutover activates it.
34
+
35
+ DOCTOR. doctor_lines(state) -> [(mark, text)] in `lanes doctor`'s protocol: nothing before the first adoption; then one
36
+ information line for the store and the flags, and one line per domain of DOMAINS: ✓ adopted (phase, owner, epoch and
37
+ where its 1.x owner keeps it), ⚠ a fence in progress or interrupted (a phase between quiesced and epoch_committed), ⚠
38
+ not adopted yet (a refusal's code, or a domain a newer release added), ✗ listed as adopted but its record is missing
39
+ or unreadable.
40
+ """
41
+ import argparse
42
+ import json
43
+ import os
44
+ import stat
45
+ import sys
46
+ import time
47
+ from pathlib import Path
48
+
49
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
50
+ import cutover # noqa: E402 (H3's record format and writer: the one journal of record)
51
+
52
+ KIND = 'lanes2.adoption/1'
53
+ LEGACY_OWNER = cutover.LEGACY_OWNER # 'lanes-py'
54
+ LEGACY_SCHEMA = 1 # the schema epoch the Python owner reads
55
+ ADOPTION = Path('lanes2') / 'adoption.json' # under $LANES_STATE
56
+ STORE_DIR = Path('store') # under $LANES_STATE (AR 4.4)
57
+ STORE_FILE = 'coordination.sqlite'
58
+ EXIT_IO, EXIT_USAGE, EXIT_REFUSED = 1, 2, 3
59
+ ADOPTION_MAX = 64 * 1024
60
+ # The Lanes 2.0 state domains (RT 6.2 "the store includes ..." and the Round-2 slices), each with what it holds and
61
+ # where its 1.x owner keeps it. Order is doctor order.
62
+ DOMAINS = (
63
+ ('owner-epochs', 'workspace owner epochs', 'none in 1.x: one host owns its workspaces'),
64
+ ('bindings', 'native-generation bindings', 'registry.json and resolve/ (lanes sync)'),
65
+ ('receipts', 'command receipts', 'none in 1.x'),
66
+ ('attention', 'prompt and answer state', 'status.json and the containers\' .sent markers (statusd)'),
67
+ ('effects', 'external effects', 'the containers\' .sent markers'),
68
+ ('inbox-outbox', 'inbox and outbox records', 'the containers\' ~/.lz/state/inbox'),
69
+ ('projects', 'project and work claims', 'none in 1.x'),
70
+ ('schedules', 'schedule occurrences', 'none in 1.x'),
71
+ ('connectors', 'connector cursors', 'none in 1.x'),
72
+ ('projections', 'projection checkpoints', 'sidebar-status/ and status.json (statusd)'),
73
+ ('preferences', 'presentation preferences', 'users/<login>.json'),
74
+ ('builds', 'build references', 'none in 1.x: buildctl owns the jobs'),
75
+ ('notify', 'notification groups', 'notify.enrol-seen.json (lanes-notify)'),
76
+ ('drafts', 'retained drafts', 'none in 1.x'),
77
+ )
78
+ DOMAIN_NAMES = tuple(name for name, _, _ in DOMAINS)
79
+ FENCED_PHASES = frozenset({'quiesced', 'drained', 'cut_verified', 'epoch_committed'})
80
+
81
+
82
+ def default_state():
83
+ return Path(os.environ.get('LANES_STATE') or Path.home() / '.local/state/lanes')
84
+
85
+
86
+ def utc(at=None):
87
+ return time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime(at))
88
+
89
+
90
+ def tree_release(tree):
91
+ """The VERSION of `tree`, or '' when it has none."""
92
+ try:
93
+ return (Path(tree) / 'VERSION').read_text().strip()[:64]
94
+ except (OSError, UnicodeDecodeError):
95
+ return ''
96
+
97
+
98
+ def initial_record(domain):
99
+ """The record DomainFence::open creates for a domain the legacy owner holds (cutover/fence.rs `open`)."""
100
+ return {'v': 1, 'kind': cutover.KIND, 'domain': domain, 'phase': 'shadow', 'epoch': 1, 'owner': LEGACY_OWNER,
101
+ 'previous': None, 'schema': LEGACY_SCHEMA, 'fenced_through': None}
102
+
103
+
104
+ def ensure_record(state, domain):
105
+ """The domain's record after making sure one exists: an existing one untouched, else the initial one written by
106
+ compare-and-swap from 'no record' (a writer that got there first wins and its record is kept). Raises
107
+ cutover.Refused for an unreadable or malformed record, OSError for an I/O failure."""
108
+ current = cutover.read_record(state, domain)
109
+ if current is not None:
110
+ return current
111
+ try:
112
+ return cutover.write_record(state, initial_record(domain), None)
113
+ except cutover.Refused as refused:
114
+ if refused.code != 'journal_conflict':
115
+ raise
116
+ return cutover.read_record(state, domain)
117
+
118
+
119
+ def verify_domain(state, domain):
120
+ """(record, None) when the domain's record is on disk and canonical, else (None, code)."""
121
+ try:
122
+ record = cutover.read_record(state, domain)
123
+ except cutover.Refused as refused:
124
+ return None, refused.code
125
+ except OSError:
126
+ return None, 'record_unreadable'
127
+ if record is None:
128
+ return None, 'record_missing'
129
+ return record, None
130
+
131
+
132
+ def _private_dir(path):
133
+ path = Path(path)
134
+ path.mkdir(mode=0o700, parents=True, exist_ok=True)
135
+ if not stat.S_ISDIR(os.lstat(path).st_mode):
136
+ raise OSError(f'{path} is not a directory')
137
+ return path
138
+
139
+
140
+ def _atomic_write(path, text):
141
+ path = Path(path)
142
+ temp = path.with_name(f'.{path.name}.{os.getpid()}.tmp')
143
+ fd = os.open(temp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_NOFOLLOW, 0o600)
144
+ try:
145
+ with os.fdopen(fd, 'w') as handle:
146
+ handle.write(text)
147
+ handle.flush()
148
+ os.fsync(handle.fileno())
149
+ os.replace(temp, path)
150
+ except BaseException:
151
+ try:
152
+ os.unlink(temp)
153
+ except OSError:
154
+ pass
155
+ raise
156
+
157
+
158
+ def store_path(state):
159
+ return Path(state) / STORE_DIR / STORE_FILE
160
+
161
+
162
+ def adopt(state, tree=None, now=None):
163
+ """Adopt every domain of DOMAINS into `state` -> the adoption record written. Every domain is attempted; a domain
164
+ is listed in `domains` only once verify_domain read its record back, else it is in `refused`. Raises OSError when
165
+ the store directory or the adoption record cannot be written."""
166
+ state = Path(state)
167
+ _private_dir(state / STORE_DIR)
168
+ adopted, refused = [], []
169
+ for domain in DOMAIN_NAMES:
170
+ try:
171
+ ensure_record(state, domain)
172
+ except cutover.Refused as error:
173
+ refused.append({'domain': domain, 'code': error.code})
174
+ continue
175
+ except OSError as error:
176
+ refused.append({'domain': domain, 'code': f'io:{error.strerror or type(error).__name__}'})
177
+ continue
178
+ record, code = verify_domain(state, domain)
179
+ if record is None:
180
+ refused.append({'domain': domain, 'code': code})
181
+ else:
182
+ adopted.append(domain)
183
+ document = {'v': 1, 'kind': KIND, 'adopted_at': utc(now), 'release': tree_release(tree) if tree else '',
184
+ 'store': str(store_path(state)), 'domains': adopted, 'refused': refused}
185
+ _private_dir(state / ADOPTION.parent)
186
+ _atomic_write(state / ADOPTION, json.dumps(document, indent=1) + '\n')
187
+ return document
188
+
189
+
190
+ def read_adoption(state):
191
+ """The adoption record, None when there is none, or raises ValueError when it is not one."""
192
+ path = Path(state) / ADOPTION
193
+ try:
194
+ raw = path.read_bytes()
195
+ except FileNotFoundError:
196
+ return None
197
+ if len(raw) > ADOPTION_MAX:
198
+ raise ValueError(f'longer than {ADOPTION_MAX} bytes')
199
+ document = json.loads(raw)
200
+ domains = document.get('domains') if isinstance(document, dict) else None
201
+ if (not isinstance(document, dict) or document.get('kind') != KIND or not isinstance(domains, list)
202
+ or not all(isinstance(name, str) for name in domains)):
203
+ raise ValueError(f'not a {KIND} record')
204
+ return document
205
+
206
+
207
+ def status(state):
208
+ """{adopted: bool, record, domains: [{domain, listed, record, code}]}: every domain of DOMAINS checked on disk.
209
+ `adopted` is True only when every domain is listed and its record verifies."""
210
+ document = read_adoption(state)
211
+ listed = set(document['domains']) if document else set()
212
+ rows = []
213
+ for domain in DOMAIN_NAMES:
214
+ record, code = verify_domain(state, domain)
215
+ rows.append({'domain': domain, 'listed': domain in listed, 'record': record, 'code': code})
216
+ adopted = document is not None and all(row['listed'] and row['record'] is not None for row in rows)
217
+ return {'adopted': adopted, 'record': document, 'domains': rows}
218
+
219
+
220
+ def _store_text(state, document):
221
+ path = Path(document.get('store') or store_path(state))
222
+ try:
223
+ size = path.stat().st_size
224
+ except OSError:
225
+ return f'store {path}: not created yet (the host coordinator creates and migrates it on its first open)'
226
+ return f'store {path}: present, {size} B'
227
+
228
+
229
+ def _flags_text(state):
230
+ try:
231
+ names = sorted(name for name in os.listdir(Path(state) / 'flags') if name.startswith('native.'))
232
+ except OSError:
233
+ names = []
234
+ return 'flags: every LANES_RS_* off' if not names else 'flags: ' + ', '.join(names)
235
+
236
+
237
+ def doctor_lines(state=None):
238
+ """`lanes doctor`'s Lanes 2.0 adoption lines -> [(mark, text)], mark ✓ | ✗ | ⚠ | '' (information). Nothing before
239
+ the first adoption (`lanes update` adopts)."""
240
+ state = default_state() if state is None else Path(state)
241
+ try:
242
+ document = read_adoption(state)
243
+ except (OSError, ValueError) as error:
244
+ return [('✗', f'lanes2 adoption: {state / ADOPTION} unreadable ({error}) — lanes update adopts again')]
245
+ if document is None:
246
+ return []
247
+ release = document.get('release') or '?'
248
+ lines = [('', f"lanes2: adopted {document.get('adopted_at') or '?'} by {release}; {_store_text(state, document)}; "
249
+ f'{_flags_text(state)}')]
250
+ listed = set(document['domains'])
251
+ refused = {entry.get('domain'): entry.get('code') for entry in document.get('refused') or ()
252
+ if isinstance(entry, dict)}
253
+ for domain, what, legacy in DOMAINS:
254
+ record, code = verify_domain(state, domain)
255
+ if domain not in listed:
256
+ why = refused.get(domain) or 'added by a newer release'
257
+ lines.append(('⚠', f'lanes2 {domain} ({what}): not adopted ({why}) — lanes update adopts it'))
258
+ elif record is None:
259
+ lines.append(('✗', f'lanes2 {domain} ({what}): listed as adopted but its cutover record is {code} — '
260
+ 'lanes update adopts it again'))
261
+ elif record['phase'] in FENCED_PHASES:
262
+ lines.append(('⚠', f"lanes2 {domain} ({what}): fenced in {record['phase']} (owner {record['owner']}, "
263
+ f"epoch {record['epoch']}) — a cutover is in progress or was interrupted: "
264
+ f'python3 libexec/cutover.py status {domain}'))
265
+ else:
266
+ keeper = f'; 1.x: {legacy}' if record['owner'] == LEGACY_OWNER else ''
267
+ lines.append(('✓', f"lanes2 {domain} ({what}): adopted — {record['phase']}, owner {record['owner']}, "
268
+ f"epoch {record['epoch']}{keeper}"))
269
+ return lines
270
+
271
+
272
+ def parser():
273
+ top = argparse.ArgumentParser(prog='adopt.py', description='installed adoption of the Lanes 2.0 store (S12)')
274
+ commands = top.add_subparsers(dest='command', required=True)
275
+ for name in ('adopt', 'status', 'doctor'):
276
+ command = commands.add_parser(name)
277
+ command.add_argument('--state', default=None)
278
+ if name == 'adopt':
279
+ command.add_argument('--tree', default=None)
280
+ if name != 'doctor':
281
+ command.add_argument('--json', action='store_true')
282
+ return top
283
+
284
+
285
+ def main(argv=None, out=None):
286
+ out = sys.stdout if out is None else out
287
+ try:
288
+ args = parser().parse_args(argv)
289
+ except SystemExit as exit_:
290
+ return EXIT_USAGE if exit_.code else 0
291
+ state = Path(args.state) if args.state else default_state()
292
+ if args.command == 'doctor':
293
+ for mark, text in doctor_lines(state):
294
+ print(f'{mark or " "} {text}', file=out)
295
+ return 0
296
+ if args.command == 'adopt':
297
+ tree = Path(args.tree) if args.tree else Path(__file__).resolve().parent.parent
298
+ try:
299
+ document = adopt(state, tree)
300
+ except OSError as error:
301
+ print(f'adopt: {error.strerror or error}', file=out)
302
+ return EXIT_IO
303
+ if args.json:
304
+ print(json.dumps(document), file=out)
305
+ else:
306
+ print(f"adopt: {len(document['domains'])} of {len(DOMAIN_NAMES)} domains adopted"
307
+ + ''.join(f"; {entry['domain']} refused ({entry['code']})" for entry in document['refused']),
308
+ file=out)
309
+ return 0 if not document['refused'] else EXIT_REFUSED
310
+ try:
311
+ report = status(state)
312
+ except (OSError, ValueError) as error:
313
+ print(f'adopt: {state / ADOPTION} unreadable ({error})', file=out)
314
+ return EXIT_REFUSED
315
+ if args.json:
316
+ print(json.dumps(report), file=out)
317
+ else:
318
+ for row in report['domains']:
319
+ word = 'adopted' if row['listed'] and row['record'] else (row['code'] or 'not listed')
320
+ print(f"{row['domain']}: {word}", file=out)
321
+ return 0 if report['adopted'] else EXIT_REFUSED
322
+
323
+
324
+ if __name__ == '__main__':
325
+ sys.exit(main())