@vibelord/lanes 1.7.3 → 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 +252 -30
  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
@@ -1,31 +1,379 @@
1
- """Small, change-only sidebar projections of the canonical host status."""
1
+ """Change-only sidebar projections of the canonical host status: one shared lane directory and the 1.7.2 board files.
2
+
3
+ statusd's cycle publishes everything `projections` yields as `$LANES_STATE/sidebar-status/<name>.json` (one publisher,
4
+ however many devices view a board; `atomic_write_if_changed` skips a write whose bytes the file already holds):
5
+
6
+ - `@directory`: the SHARED DIRECTORY PROJECTION (Lanes 2.0 fan-out lane C7, DM-LANES2-C7-DIRECTORY-TWIN; integrated
7
+ cockpit §5.1: one lane directory for every client, a workspace tab is context, never a directory of its own). Every
8
+ sidebar of the host reads this one document. `@` is outside the board-id alphabet (BOARD), so no board can publish
9
+ under that name. It holds the Day-0 contract document, `directory`, a LaneDirectoryProjection v1
10
+ (docs/contracts/lanes2/schema/lane_directory_projection.schema.json): every board's registered lanes and live
11
+ sessions once, keyed by authority-qualified identity. Beside it is the compatibility body the Python sidebar renders
12
+ from: every board-owned status row restricted to the fields a sidebar renders (RENDERED, so process metadata such as
13
+ pid, tty or cwd never rewrites it), the cross-board facts of every other row (`summary`), every board's
14
+ `unregistered` and `zmx` sessions, and `fleet`, `throttle` and `web_origin`. A sidebar derives its board's view with
15
+ `board_view`, the function that builds the board files below, so both sources paint the same frame.
16
+ Its write decision is compared()-style (BEY-6933): a document whose only news is `fleet.at` or `throttle.at`
17
+ (statusd's sample times: every FLEET_INTERVAL, every pulse) is the previous document, byte for byte, so it is never
18
+ rewritten for that alone. `directory_revision` (also the source's `observed_at_unix_ms` and cursor) is the Unix ms at
19
+ which the content first appeared, so it moves exactly when the content does, and it only grows on this host: a
20
+ restarted statusd starts from the document already on disk (`prior_directory`), so neither a restart nor a clock
21
+ step back lowers it, and a restart over unchanged content writes nothing. Liveness is the health line's `status_at`
22
+ (DM-LANES-HEALTH), never this file's mtime. The rows are ONE page of at most PAGE_ROWS (500); above that the page
23
+ is `incomplete` and names no `next_page` (no continuation is published: an open item for the Rust projector, B9),
24
+ while the compatibility body still carries every lane.
25
+ - `<board>`: the 1.7.2 per-board projection (DM-LANES-SIDEBAR-STATUS), kept as the compatibility stage for a sidebar of
26
+ an older tree. Its bytes and its write interval are unchanged (architecture D5), including the rewrite its
27
+ `fleet.at` causes.
28
+
29
+ The 1 s select tick a Python sidebar polls on is the compatibility stage's coalescing. The directory document names no
30
+ refresh interval, so a client that reads it (the Rust renderer, C2) inherits none (architecture §5.5).
31
+ """
2
32
  import json
33
+ import os
3
34
  import re
35
+ import time
4
36
 
37
+ import agent_state as AS
38
+ import lanes_lib as L
39
+ import tokens
5
40
 
6
- def projections(registry, payload):
7
- rows = payload.get('lanes') or {}
41
+ BOARD = re.compile(r'[A-Za-z0-9_.-]+')
42
+ DIRECTORY = '@directory'
43
+ # The status-row fields a sidebar renders (sidebar.py: the row, the phone row, the seen marks, the fleet strip and the
44
+ # `@` sheet read these and no other). Everything else a row carries (statusd's process metadata: command, cwd, pid,
45
+ # size, attached, tty; its observation diagnostics) stays in status.json: a change there never rewrites the directory,
46
+ # and test_sidebar_budget proves the frames are the same without it.
47
+ RENDERED = ('state', 'activity', 'stale', 'agent', 'viewers', 'docs', 'inbox', 'role', 'address')
48
+ EXTRAS = ('fleet', 'throttle', 'web_origin')
49
+ SAMPLED = ('fleet', 'throttle') # objects whose `at` is a sample time: news only beside a fact (statusd.compared)
50
+ PRESENTATION_REVISION = 3 # lanes/tokens/tokens.v1.json theme.revision (palette v3); a test pins the two together
51
+ PAGE_ROWS = 500 # the contract's rows bound (lanes-protocol PAGE_MAX_ITEMS); this file is one page
52
+ LABEL_BYTES = 256
53
+ TOKEN_BYTES = 128
54
+ AUTHORITY_BYTES = 64
55
+ CONTROL = re.compile('[\x00-\x1f\x7f-\x9f]')
56
+ NOT_TOKEN = re.compile(r'[^\x21-\x7e]|["\\]')
57
+ ATTENTION = {'needs_approval': 'approval', 'errored': 'actionable_error', 'needs_input': 'input'}
58
+ SECTION = {'needs': 'needs_you', 'working': 'working', 'done': 'done_unseen', None: 'remaining'}
59
+ SECTION_ORDER = ('needs_you', 'working', 'done_unseen', 'remaining', 'unregistered')
60
+ ATTENTION_ORDER = ('approval', 'actionable_error', 'input') # sidebar NEEDS_RANK: needs_approval, errored, needs_input
61
+ INF = float('inf')
62
+ PRIOR_BYTES = 64 << 20 # the most of a previous process's directory a restart reads (prior_directory)
63
+ # The attach action's reason when the lane cannot be shown (statusd's words: `absent` = no such session in a running
64
+ # container, `missing` = the container is down, `dead` = the pane's process ended).
65
+ UNHEALTHY = {'absent': 'no such session right now', 'missing': 'its container is not running',
66
+ 'dead': 'the pane has exited'}
67
+ # statusd's process: name -> (comparison key, published text, revision) of the last directory it published. A restart
68
+ # starts empty and its first cycle seeds it from the document on disk (prior_directory), so an unchanged directory is
69
+ # not rewritten and the revision never falls; `projections(memo=...)` gives a caller (a test) its own.
70
+ PUBLISHED = {}
71
+
72
+
73
+ def boards(registry):
74
+ """(id, board) of every registry board whose id can name a file (BOARD; never `.` or `..`), in registry order."""
75
+ for board in (registry or {}).get('workspaces') or []:
76
+ name = board.get('id', '') if isinstance(board, dict) else ''
77
+ if isinstance(name, str) and BOARD.fullmatch(name) and name not in ('.', '..'):
78
+ yield name, board
79
+
80
+
81
+ def summary(row):
82
+ """The facts of one status row every board's sidebar sees: a blocking question (the fleet strip's attention) and
83
+ the fleet admin's identity (the `@` sheet). {} when the row has neither."""
84
+ out = {}
85
+ if not isinstance(row, dict):
86
+ return out
87
+ agent = row.get('agent') or {}
88
+ if isinstance(agent, dict) and agent.get('status') in ('needs_input', 'needs_approval'):
89
+ out['agent'] = {'status': agent['status']}
90
+ if row.get('role') in ('fleet-admin', 'fleet_admin'):
91
+ out.update({field: row[field] for field in ('role', 'address') if field in row})
92
+ return out
93
+
94
+
95
+ def shared_facts(lanes):
96
+ """{lane id: summary} of every row that has one."""
8
97
  shared = {}
98
+ for key, row in lanes.items():
99
+ facts = summary(row)
100
+ if facts:
101
+ shared[key] = facts
102
+ return shared
103
+
104
+
105
+ def listed(value):
106
+ return value if isinstance(value, list) else []
107
+
108
+
109
+ def own_ids(board, ghosts, zmx):
110
+ """The ids a board lists: its registry lanes, its zmx lanes and its unregistered sessions."""
111
+ return {entry.get('id') for entry in list(board.get('lanes') or []) + ghosts + zmx if isinstance(entry, dict)}
112
+
113
+
114
+ def board_view(board, lanes, unregistered, zmx, extras, shared=None):
115
+ """One board's status document: its own rows whole, every other row's `summary`, its unregistered and zmx sessions,
116
+ and `fleet`, `throttle` and `web_origin` from `extras`. statusd publishes it from status.json's rows as the board's
117
+ 1.7.2 file; a sidebar on the shared directory derives it from the directory's body, so both paint the same frame."""
118
+ name = board.get('id', '')
119
+ lanes = lanes if isinstance(lanes, dict) else {}
120
+ ghosts = listed((unregistered if isinstance(unregistered, dict) else {}).get(name, []))
121
+ zmx_rows = listed((zmx if isinstance(zmx, dict) else {}).get(name, []))
122
+ ids = own_ids(board, ghosts, zmx_rows)
123
+ own = {key: row for key, row in lanes.items() if key in ids or key.startswith(name + '--')}
124
+ result = {'v': 1, 'lanes': dict(shared_facts(lanes) if shared is None else shared, **own),
125
+ 'unregistered': {name: ghosts}, 'zmx': {name: zmx_rows}}
126
+ result.update({key: extras[key] for key in EXTRAS if key in extras})
127
+ return result
128
+
129
+
130
+ def compared(document):
131
+ """`document` as the write decision sees it: without the sample time of `fleet` and of `throttle` (statusd.compared's
132
+ rule, which status.json's rewrite follows). A document whose only news is an `at` is the previous one."""
133
+ if not isinstance(document, dict):
134
+ return document
135
+ out = dict(document)
136
+ for key in SAMPLED:
137
+ if isinstance(out.get(key), dict):
138
+ out[key] = {name: value for name, value in out[key].items() if name != 'at'}
139
+ return out
140
+
141
+
142
+ def token(text, limit=TOKEN_BYTES):
143
+ """`text` in the contract's token alphabet (visible ASCII but `"` and `\\`, each other character a `-`), at most
144
+ `limit` bytes; '' when nothing is left."""
145
+ return NOT_TOKEN.sub('-', str(text))[:limit].strip('-')
146
+
147
+
148
+ def label(text):
149
+ """A display label in the contract's text alphabet: control characters dropped, at most LABEL_BYTES of UTF-8 cut on
150
+ a character boundary, never empty."""
151
+ data = CONTROL.sub('', str(text)).strip().encode('utf-8')[:LABEL_BYTES]
152
+ return data.decode('utf-8', 'ignore') or '?'
153
+
154
+
155
+ def millis(value):
156
+ """A Unix time in seconds (a finite real number, not a bool) as whole ms in 0..2^63-1, else 0."""
157
+ if isinstance(value, bool) or not isinstance(value, (int, float)) or not -1e300 < value < 1e300:
158
+ return 0
159
+ return max(0, min(int(value * 1000), (1 << 63) - 1))
160
+
161
+
162
+ def directory_row(lane_id, workspaces, entry, row, authority, unregistered):
163
+ """One LaneDirectoryRow (TI §3, IC §5.1) from the registry `entry` and the status `row` of a lane the boards
164
+ `workspaces` list (the first one minted it). The section is the DEFAULT one: viewed-Done and pins are principal
165
+ preferences each client applies (the Python sidebar keeps its device and profile marks). The revision is 0 until
166
+ `stamp` fills it."""
167
+ row = row if isinstance(row, dict) else {}
168
+ agent = row.get('agent') if isinstance(row.get('agent'), dict) else {}
169
+ status = agent.get('status') if agent.get('status') in tokens.AGENT_GLYPHS else None
170
+ state = row.get('state') if row.get('state') in tokens.GLYPHS else 'unknown'
171
+ stale = row.get('stale') is True or state == 'unknown'
172
+ attention = ATTENTION.get(status, 'none')
173
+ if stale:
174
+ activity = 'stale'
175
+ elif state == 'missing':
176
+ activity = 'disconnected'
177
+ elif state in ('absent', 'dead'):
178
+ activity = 'stopped'
179
+ elif attention != 'none':
180
+ activity = 'waiting_person'
181
+ elif status == 'working':
182
+ activity = 'delegating' if agent.get('activity') == 'delegating' else 'working'
183
+ elif status == 'done' or state != 'active':
184
+ activity = 'finished'
185
+ else:
186
+ activity = 'working'
187
+ section = 'unregistered' if unregistered else SECTION[AS.SECTION.get(status)]
188
+ attach = {'action': 'attach', 'availability': 'available'}
189
+ if state in UNHEALTHY:
190
+ attach = {'action': 'attach', 'availability': 'unhealthy', 'reason': UNHEALTHY[state]}
191
+ return {'v': 1, 'lane': {'authority': authority, 'workspace_id': workspaces[0], 'lane_id': lane_id},
192
+ 'memberships': [{'workspace_id': workspace} for workspace in workspaces],
193
+ 'label': label(entry.get('name') or lane_id), 'activity': activity, 'attention': attention,
194
+ 'section': section,
195
+ 'last_activity_unix_ms': millis(row['activity'] if 'activity' in row else agent.get('since')),
196
+ 'style_token': (tokens.AGENT_GLYPHS[status] if status else tokens.GLYPHS[state])[2],
197
+ 'source': {'owner': 'lanes_host', 'revision': 0, 'freshness': 'stale' if stale else 'fresh'},
198
+ 'actions': [attach]}
199
+
200
+
201
+ def entered_at(agent):
202
+ """When a lane entered its section (Sidebar.agent_rows' stamp): statusd's `agent.stable_since`, else `since` (a
203
+ statusd older than cockpit v3 S1); None when neither is a finite number."""
204
+ for key in ('stable_since', 'since'):
205
+ value = agent.get(key)
206
+ if isinstance(value, (int, float)) and not isinstance(value, bool) and -INF < value < INF:
207
+ return value
208
+ return None
209
+
210
+
211
+ def order_key(row, entered):
212
+ """The directory's default order (IC §5.1: the existing section ordering, Sidebar.sectioned, with the immutable
213
+ identity as the tie-breaker). Needs you by urgency (approval, actionable error, input), then the order lanes
214
+ ENTERED it; Working in entry order; unseen Done the newest entry first; an unknown entry stamp (`entered` None)
215
+ last in each of the three; remaining and Unregistered in identity order (the conformance kit's rule for every
216
+ client). The tie-breaker is the identity TEXT authority/workspace/lane, not a tuple of those fields."""
217
+ section, lane = row['section'], row['lane']
218
+ if section == 'needs_you':
219
+ rank = (ATTENTION_ORDER.index(row['attention']), INF if entered is None else entered)
220
+ elif section == 'working':
221
+ rank = (INF if entered is None else entered,)
222
+ elif section == 'done_unseen':
223
+ rank = (INF if entered is None else -entered,)
224
+ else:
225
+ rank = ()
226
+ identity = '/'.join((lane['authority'], lane['workspace_id'], lane['lane_id']))
227
+ return (SECTION_ORDER.index(section),) + rank + (identity,)
228
+
229
+
230
+ def directory(registry, payload, authority, runtime):
231
+ """The LaneDirectoryProjection v1 of this host, revision fields 0: every lane any board lists (registered, zmx, then
232
+ unregistered sessions) once, its identity (authority, the board that lists it first, lane id) and every board that
233
+ lists it as a membership, in the default order; the counts over all of them."""
234
+ rows = payload.get('lanes') if isinstance(payload.get('lanes'), dict) else {}
235
+ unregistered = payload.get('unregistered') if isinstance(payload.get('unregistered'), dict) else {}
236
+ zmx = payload.get('zmx') if isinstance(payload.get('zmx'), dict) else {}
237
+ found, order = {}, [] # lane id -> [boards, registry entry, unregistered?]
238
+ for name, board in boards(registry):
239
+ for entries, ghost in ((board.get('lanes') or [], False), (listed(zmx.get(name, [])), False),
240
+ (listed(unregistered.get(name, [])), True)):
241
+ for entry in entries:
242
+ lane_id = token(entry.get('id', '')) if isinstance(entry, dict) else ''
243
+ if not lane_id:
244
+ continue
245
+ if lane_id not in found:
246
+ found[lane_id] = [[], entry, ghost]
247
+ order.append(lane_id)
248
+ if name not in found[lane_id][0]:
249
+ found[lane_id][0].append(name)
250
+ built = []
251
+ for lane_id in order:
252
+ workspaces, entry, ghost = found[lane_id]
253
+ row = rows.get(lane_id)
254
+ agent = row.get('agent') if isinstance(row, dict) and isinstance(row.get('agent'), dict) else {}
255
+ made = directory_row(lane_id, workspaces, entry, row, authority, ghost)
256
+ built.append((order_key(made, entered_at(agent)), made))
257
+ built.sort(key=lambda pair: pair[0])
258
+ counts = {'total': len(built), 'needs_you': 0, 'working': 0, 'done_unseen': 0}
259
+ for _key, row in built:
260
+ if row['section'] in counts:
261
+ counts[row['section']] += 1
262
+ complete = len(built) <= PAGE_ROWS and all(row['source']['freshness'] == 'fresh' for _key, row in built)
263
+ return {'v': 1, 'scope': {'principal_id': 'lanes-host', 'authorization_epoch': 0, 'runtime_instance_id': runtime},
264
+ 'directory_revision': 0, 'schema_revision': 1, 'presentation_revision': PRESENTATION_REVISION,
265
+ 'filter': {'workspace_ids': [], 'project_ids': []},
266
+ 'sources': [{'owner': 'lanes_host', 'runtime_instance_id': runtime, 'cursor': 'statusd.0', 'revision': 0,
267
+ 'freshness': 'fresh', 'observed_at_unix_ms': 0}],
268
+ 'completeness': 'complete' if complete else 'incomplete', 'counts': counts,
269
+ 'rows': [row for _key, row in built[:PAGE_ROWS]]}
270
+
271
+
272
+ def rendered(row):
273
+ """A status row restricted to RENDERED (a row that is not an object stays what it is)."""
274
+ return {field: row[field] for field in RENDERED if field in row} if isinstance(row, dict) else row
275
+
276
+
277
+ def document(registry, payload, host):
278
+ """The shared directory document, every revision field 0: `directory`, then the compatibility body."""
279
+ rows = payload.get('lanes') if isinstance(payload.get('lanes'), dict) else {}
280
+ unregistered = payload.get('unregistered') if isinstance(payload.get('unregistered'), dict) else {}
281
+ zmx = payload.get('zmx') if isinstance(payload.get('zmx'), dict) else {}
282
+ owned, ghosts_of, zmx_of = set(), {}, {}
283
+ for name, board in boards(registry):
284
+ ghosts, zmx_rows = listed(unregistered.get(name, [])), listed(zmx.get(name, []))
285
+ ghosts_of[name], zmx_of[name] = ghosts, zmx_rows
286
+ ids = own_ids(board, ghosts, zmx_rows)
287
+ owned.update(key for key in rows if key in ids or key.startswith(name + '--'))
288
+ lanes = {}
9
289
  for key, row in rows.items():
10
- summary = {}
11
- if not isinstance(row, dict):
12
- continue
13
- agent = row.get('agent') or {}
14
- if isinstance(agent, dict) and agent.get('status') in ('needs_input', 'needs_approval'):
15
- summary['agent'] = {'status': agent['status']}
16
- if row.get('role') in ('fleet-admin', 'fleet_admin'):
17
- summary.update({field: row[field] for field in ('role', 'address') if field in row})
18
- if summary:
19
- shared[key] = summary
20
- for board in (registry or {}).get('workspaces') or []:
21
- name = board.get('id', '')
22
- if not re.fullmatch(r'[A-Za-z0-9_.-]+', name) or name in ('.', '..'):
23
- continue
24
- ghosts = (payload.get('unregistered') or {}).get(name, [])
25
- zmx = (payload.get('zmx') or {}).get(name, [])
26
- ids = {entry.get('id') for entry in list(board.get('lanes') or []) + ghosts + zmx}
27
- own = {key: row for key, row in rows.items() if key in ids or key.startswith(name + '--')}
28
- result = {'v': 1, 'lanes': dict(shared, **own),
29
- 'unregistered': {name: ghosts}, 'zmx': {name: zmx}}
30
- result.update({key: payload[key] for key in ('fleet', 'throttle', 'web_origin') if key in payload})
31
- yield name, json.dumps(result, sort_keys=True) + '\n'
290
+ facts = rendered(row) if key in owned else summary(row)
291
+ if key in owned or facts:
292
+ lanes[key] = facts
293
+ host = token(host, AUTHORITY_BYTES - len('host:')) or 'local'
294
+ out = {'v': 1, 'directory': directory(registry, payload, 'host:' + host, 'lanes-host:' + host),
295
+ 'lanes': lanes, 'unregistered': ghosts_of, 'zmx': zmx_of}
296
+ out.update({key: payload[key] for key in EXTRAS if key in payload})
297
+ return out
298
+
299
+
300
+ def stamp(doc, revision):
301
+ """Fill `doc`'s revision fields with `revision` (the Unix ms its content first appeared) -> doc."""
302
+ projection = doc['directory']
303
+ projection['directory_revision'] = revision
304
+ for source in projection['sources']:
305
+ source.update(revision=revision, cursor=f'statusd.{revision}', observed_at_unix_ms=revision)
306
+ for row in projection['rows']:
307
+ row['source']['revision'] = revision
308
+ return doc
309
+
310
+
311
+ def prior_directory(path):
312
+ """(comparison key or None, text, revision) of the directory document a previous statusd process left at `path`,
313
+ or None (no file, more than PRIOR_BYTES, not JSON, or no revision in 0..2^63-1). The key is `compared` of the
314
+ document with its revision fields 0, as publish_directory keys a new one; None when it is not this format."""
315
+ try:
316
+ with open(path, 'rb') as handle:
317
+ data = handle.read(PRIOR_BYTES + 1)
318
+ except OSError:
319
+ return None
320
+ if len(data) > PRIOR_BYTES:
321
+ return None
322
+ try:
323
+ text = data.decode('utf-8')
324
+ doc = json.loads(text)
325
+ revision = doc['directory']['directory_revision']
326
+ except (ValueError, KeyError, TypeError):
327
+ return None
328
+ if isinstance(revision, bool) or not isinstance(revision, int) or not 0 <= revision < 1 << 63:
329
+ return None
330
+ try:
331
+ key = json.dumps(compared(stamp(doc, 0)), sort_keys=True, separators=(',', ':'))
332
+ except (KeyError, TypeError, AttributeError):
333
+ key = None
334
+ return key, text, revision
335
+
336
+
337
+ def publish_directory(registry, payload, memo, now=None, host=None, prior=None):
338
+ """The text of the shared directory document. When its content (everything but the sample times, `compared`, and
339
+ the revision) is what `memo` last published, the SAME text again, so statusd's byte compare writes nothing;
340
+ otherwise a new revision: the Unix ms now, and always above the last one. A `memo` that has published nothing yet
341
+ (a statusd process's first cycle) starts from `prior`, the path of the document already on disk (prior_directory,
342
+ read once): an unchanged content keeps its text and revision, and a new one is stamped above it, so a restart never
343
+ lowers the revision, even after a clock step back."""
344
+ doc = document(registry, payload, os.uname().nodename if host is None else host)
345
+ key = json.dumps(compared(doc), sort_keys=True, separators=(',', ':'))
346
+ last = memo.get(DIRECTORY)
347
+ if last is None and prior is not None:
348
+ last = prior_directory(prior)
349
+ if last and last[0] == key:
350
+ memo[DIRECTORY] = last
351
+ return last[1]
352
+ revision = millis(time.time() if now is None else now)
353
+ if last:
354
+ revision = max(revision, last[2] + 1)
355
+ text = json.dumps(stamp(doc, revision), sort_keys=True, separators=(',', ':')) + '\n'
356
+ memo[DIRECTORY] = (key, text, revision)
357
+ return text
358
+
359
+
360
+ def board_projections(registry, payload):
361
+ """The per-board compatibility files, in publication order. The Rust compatibility writer replays this exact
362
+ production path; the shared directory has its separate identity, revision and client conformance contract."""
363
+ rows = payload.get('lanes') or {}
364
+ shared = shared_facts(rows)
365
+ for name, board in boards(registry):
366
+ view = board_view(board, rows, payload.get('unregistered') or {}, payload.get('zmx') or {}, payload, shared)
367
+ yield name, json.dumps(view, sort_keys=True) + '\n'
368
+
369
+
370
+ def projections(registry, payload, memo=None, now=None, host=None, state=None):
371
+ """(name, text) of every sidebar projection of `payload` (statusd's status.json payload, never mutated) under
372
+ `registry`: each valid board's 1.7.2 file, then the shared directory (DIRECTORY). statusd's call (no `memo`) keeps
373
+ the process's PUBLISHED and seeds it from `$LANES_STATE` (L.STATE); a caller's own `memo` seeds from `state` only
374
+ when it names one."""
375
+ if memo is None:
376
+ memo, state = PUBLISHED, L.STATE if state is None else state
377
+ prior = os.path.join(state, 'sidebar-status', DIRECTORY + '.json') if state is not None else None
378
+ yield from board_projections(registry, payload)
379
+ yield DIRECTORY, publish_directory(registry, payload, memo, now, host, prior)
@@ -642,6 +642,10 @@ def agent_sidecars(containers, wanted, now=None):
642
642
 
643
643
  def probe_server(info, socket, live):
644
644
  """`live` = the live socket names of THIS server's container (`live_in`), or None when nobody knows them."""
645
+ if info.get('transport', L.TRANSPORT_LOCAL) != L.TRANSPORT_LOCAL:
646
+ # H1: a container behind a guest has no init here, and that says nothing about it. Its guest observes it; this
647
+ # host does not before its aggregator duty (Lanes2 W20). Nobody knows: its lanes are kept stale, never missing.
648
+ return 'error', f"behind {info['transport']}: observed by its guest, not from this host before the aggregator"
645
649
  if not info.get('pid'):
646
650
  # Only a docker inspect that ANSWERED "pid 0" says the container is down. No record at all, or one that
647
651
  # carries an error (docker did not answer) = nobody knows.
@@ -1118,7 +1122,9 @@ def update_containers(ctx, registry, level):
1118
1122
  names = {lane['container'] for w in registry['workspaces'] for lane in w['lanes'] if lane.get('container')}
1119
1123
  known = ctx['containers']
1120
1124
  age = time.time() - ctx['containers_at']
1121
- unsettled = set(known) != names or any(not pid_alive(c.get('pid')) for c in known.values())
1125
+ # A container behind a guest (H1: refresh_containers stamped its transport) has no init here by design: no reason.
1126
+ unsettled = set(known) != names or any(not pid_alive(c.get('pid')) for c in known.values()
1127
+ if c.get('transport', L.TRANSPORT_LOCAL) == L.TRANSPORT_LOCAL)
1122
1128
  if age > CONTAINER_RETRY and (unsettled or (age > CONTAINER_REFRESH and level == 'ok')):
1123
1129
  try:
1124
1130
  ctx['containers'] = L.refresh_containers(names)
@@ -1631,6 +1637,52 @@ def throttle_snapshot(ctx, now):
1631
1637
  return dict(document or {}, stale=stale)
1632
1638
 
1633
1639
 
1640
+ # H1 (lanes-site/1, plan row H1): every typed path below asks lanes_lib.write_route how it reaches a container. A
1641
+ # container whose init runs here is typed into as before. One behind a guest (catalog.json `"transport":
1642
+ # "guest:<alias>"`) is its guest's to deliver into, rename and re-arm: the guest's own statusd does all three, and a
1643
+ # relay is never a second actor (AR §3.32); this host neither observes nor spawns there before its aggregator duty
1644
+ # (Lanes2 W20). One with no init here and no guest transport is asked through tmux_probe (a runtime hook may reach
1645
+ # it); only when that answers `noserver` is it "not typed: no write transport for <container>" (BEY-6899, AR §7.5),
1646
+ # journalled once per change and never silently skipped; `lanes doctor` names it too.
1647
+ def typed_routes(ctx):
1648
+ """{container: (route, why)} (lanes_lib.write_route, asked on one of the container's lane sockets) of every
1649
+ container a registry tmux lane names, computed again only when what decides it changed (each container's pid, home,
1650
+ error and transport: no file is read and nothing probed for an unchanged set, so a host of pid-less containers does
1651
+ not read its catalog every pass); a change of a container's route is journalled once."""
1652
+ registry, containers = ctx.get('registry') or {}, ctx.get('containers') or {}
1653
+ sockets = {}
1654
+ for workspace in registry.get('workspaces') or []:
1655
+ for lane in workspace.get('lanes') or []:
1656
+ if lane.get('holder') == 'tmux' and lane.get('container'):
1657
+ sockets.setdefault(lane['container'], (lane.get('tmux') or {}).get('socket'))
1658
+ infos = {name: containers.get(name) if isinstance(containers.get(name), dict) else {} for name in sorted(sockets)}
1659
+ stamp = tuple((name, info.get('pid'), bool(info.get('home')), info.get('error'), info.get('transport'))
1660
+ for name, info in infos.items())
1661
+ cached = ctx.get('typed_routes')
1662
+ if cached and cached[0] == stamp:
1663
+ return cached[1]
1664
+ routes = {name: L.write_route(name, info, sockets[name]) for name, info in infos.items()}
1665
+ said = ctx.setdefault('typed_routes_said', {})
1666
+ for name, (route, why) in routes.items():
1667
+ state = why if route is None and L.no_write_transport(why) else (
1668
+ route if route not in (None, L.TRANSPORT_LOCAL) else None)
1669
+ if state != said.get(name):
1670
+ if state is None:
1671
+ note('transport', f'{name}: typed into from this host again')
1672
+ elif route is None:
1673
+ note('transport', f"{name}: not typed: {why} — statusd's inbox drain and auto-rename type nothing "
1674
+ 'there')
1675
+ elif route == L.TRANSPORT_PROBE:
1676
+ note('transport', f"{name}: no init on this host, reached through tmux_probe (a runtime hook) — "
1677
+ "statusd's inbox drain and auto-rename read its files here and leave it")
1678
+ else:
1679
+ note('transport', f'{name}: behind {route} — its guest delivers, renames and re-arms; not observed '
1680
+ 'from this host before the aggregator (Lanes2 W20)')
1681
+ said[name] = state
1682
+ ctx['typed_routes'] = (stamp, routes)
1683
+ return routes
1684
+
1685
+
1634
1686
  def pulse_rearm_argv(container):
1635
1687
  """The one spawn of the fleet feature: the pulse loop started detached in its own tmux server in the container,
1636
1688
  as the container user (CONTAINER_UID, like every other exec Lanes makes into a container: the loop must write
@@ -1811,11 +1863,12 @@ def names_auto(ctx, level, now=None):
1811
1863
  for lane_id in [lane_id for lane_id, at in tried.items() if now - at >= L.NAMES_RETRY_S]:
1812
1864
  del tried[lane_id]
1813
1865
  todo, _deferred, _matched = L.names_plan(registry, payload, unattached=True)
1866
+ routes = typed_routes(ctx) # H1: a guest's lanes are its own to rename; no transport is journalled there
1814
1867
  done = []
1815
1868
  for _board, lane, row in todo:
1816
1869
  if len(done) >= NAMES_PER_PASS:
1817
1870
  break
1818
- if lane['id'] in tried:
1871
+ if lane['id'] in tried or routes.get(lane.get('container'), (L.TRANSPORT_LOCAL,))[0] != L.TRANSPORT_LOCAL:
1819
1872
  continue
1820
1873
  tried[lane['id']] = now
1821
1874
  done.append(lane['id'])
@@ -2124,6 +2177,15 @@ def host_message(place, row, info, lane_id, to, sender, text, ttl_s, now=None):
2124
2177
  C.check_message(text)
2125
2178
  if not C.HOST_SENDER.fullmatch(sender or ''):
2126
2179
  raise L.LanesError(f'{sender!r} is no host sender (host:<login>)')
2180
+ route, why = L.write_route(place.get('container') or '', info, (place.get('tmux') or {}).get('socket')) # H1
2181
+ if route is None and L.no_write_transport(why):
2182
+ raise L.LanesError(f'not typed: {why}')
2183
+ if route == L.TRANSPORT_PROBE:
2184
+ raise L.LanesError(f"not typed: container {place.get('container')} has no init on this host (tmux_probe "
2185
+ 'reaches it, a runtime hook): its inbox is under a home volume this host does not have')
2186
+ if route not in (None, L.TRANSPORT_LOCAL):
2187
+ raise L.LanesError(f'not typed: {lane_id} runs behind {route}: its inbox is on that guest (lanes message '
2188
+ 'there); lanes-site/1 v1 carries no inbox write')
2127
2189
  if not info.get('home'):
2128
2190
  raise L.LanesError(f"{lane_id}: the home volume of container {place.get('container')} is not known (lanes doctor)")
2129
2191
  base, prefix = Path(info['home']), ('.lz',)
@@ -2162,6 +2224,7 @@ def deliver_inbox(ctx, level, now=None):
2162
2224
  del tried[message_id]
2163
2225
  places, rows = lane_places(registry, payload), payload.get('lanes') or {}
2164
2226
  containers, sessions = ctx.get('containers') or {}, {}
2227
+ routes = typed_routes(ctx) # H1: a guest delivers into its own lanes; no transport is journalled there
2165
2228
  waiting = sorted((rows_[0][0] or '', lane_id, rows_) for lane_id, rows_ in (ctx.get('inbox_waiting') or {}).items())
2166
2229
  done, typed = [], 0
2167
2230
  for _oldest, lane_id, messages in waiting:
@@ -2169,7 +2232,8 @@ def deliver_inbox(ctx, level, now=None):
2169
2232
  break
2170
2233
  message_id = next((m for _at, m, _c in messages if m not in tried), None)
2171
2234
  place = places.get(lane_id)
2172
- if message_id is None or place is None or place.get('container') != messages[0][2]:
2235
+ if message_id is None or place is None or place.get('container') != messages[0][2] \
2236
+ or routes.get(messages[0][2], (L.TRANSPORT_LOCAL,))[0] != L.TRANSPORT_LOCAL:
2173
2237
  continue
2174
2238
  info = containers.get(messages[0][2]) or {}
2175
2239
  try: