@vibelord/lanes 1.7.6 → 1.8.0

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 (38) hide show
  1. package/README.md +13 -9
  2. package/package.json +1 -1
  3. package/payload/lanes/README.md +2 -2
  4. package/payload/lanes/VERSION +1 -1
  5. package/payload/lanes/bin/lanes +26 -4
  6. package/payload/lanes/bin/lanes-site-serve +4 -8
  7. package/payload/lanes/bin-rs/BINARIES.json +17 -2
  8. package/payload/lanes/bin-rs/THIRD-PARTY-NOTICES +18953 -0
  9. package/payload/lanes/bin-rs/x86_64-unknown-linux-musl/lanes-hook +0 -0
  10. package/payload/lanes/bin-rs/x86_64-unknown-linux-musl/lanes-terminal +0 -0
  11. package/payload/lanes/client/lanes-launch +4 -2
  12. package/payload/lanes/container/lane-mcp +1 -1
  13. package/payload/lanes/container/lane_core.py +4 -3
  14. package/payload/lanes/docs/ARCHITECTURE.md +38 -9
  15. package/payload/lanes/docs/RUNBOOK.md +123 -53
  16. package/payload/lanes/docs/USERGUIDE.md +68 -9
  17. package/payload/lanes/install/lanes-host.service.in +25 -0
  18. package/payload/lanes/install/services.py +243 -0
  19. package/payload/lanes/libexec/agent_state.py +3 -1
  20. package/payload/lanes/libexec/attach.py +139 -21
  21. package/payload/lanes/libexec/cutover.py +24 -4
  22. package/payload/lanes/libexec/doctor_lanes2.py +3 -3
  23. package/payload/lanes/libexec/native.sh +2 -2
  24. package/payload/lanes/libexec/native_bin.py +595 -109
  25. package/payload/lanes/libexec/shadow.py +51 -3
  26. package/payload/lanes/libexec/sidebar.py +208 -35
  27. package/payload/lanes/libexec/sidebar_status.py +190 -80
  28. package/payload/lanes/libexec/update.py +12 -3
  29. package/payload/lanes/site/protocol.py +24 -9
  30. package/payload/lanes/site/relay.py +292 -0
  31. package/payload/lanes/site/server.py +31 -3
  32. package/payload/lanes/web/README.md +6 -6
  33. package/payload/lanes/web/directory.js +10 -8
  34. package/payload/lanes/web/generated/README.md +85 -21
  35. package/payload/lanes/web/generated/lanes2_protocol.d.mts +4190 -188
  36. package/payload/lanes/web/generated/lanes2_protocol.mjs +14218 -351
  37. package/payload/lanes/web/inbox.js +8 -6
  38. package/payload/manifest.json +22 -5
@@ -21,6 +21,7 @@ import contextlib
21
21
  import fcntl
22
22
  import json
23
23
  import os
24
+ import re
24
25
  import secrets
25
26
  import shutil
26
27
  import sys
@@ -78,6 +79,246 @@ def throttle_rc_path(share):
78
79
  return Path(share) / 'bin' / 'throttle-rc'
79
80
 
80
81
 
82
+ # The Lanes 2.0 host (FC-R1, FC-X11; AR 9.4 as amended): lanes-host.service runs `throttle-rc lanes host` and exists
83
+ # only while LANES_RS_HOST is shadow or on — that is, while `lanes rs apply`, the one writer of the flag files, wrote
84
+ # $LANES_STATE/flags/native.host.shadow or native.host. Its template is install/lanes-host.service.in (never in
85
+ # systemd/, whose every file is rendered unconditionally). reconcile_host_unit renders it from the flags and removes it
86
+ # when HOST is off (the file only: a server install starts nothing); reconcile_units, which `lanes rs apply` and
87
+ # `lanes rs uninstall` run, also enables or disables it and stands the Python twins down or up (AR 9.4: both
88
+ # directions, so `lanes rs set <c> off && lanes rs apply` is the whole rollback and a bare systemctl never is).
89
+ HOST_UNIT = 'lanes-host.service'
90
+ HOST_TEMPLATE = Path(__file__).resolve().parent / 'lanes-host.service.in'
91
+ # AR 9.4: the Python twins a duty `on` conflicts with (owner and aggregator mode only; a shadow unit has none).
92
+ HOST_CONFLICTS = (('statusd', 'lanes-statusd.service'), ('notify', 'lanes-notify.service'),
93
+ ('economy', 'lanes-economy.service'), ('site', 'lanes-statusd.service'))
94
+ HOST_DUTY_FLAGS = ('statusd', 'visibility', 'notify', 'economy', 'sync', 'site', 'store', 'routes', 'attention',
95
+ 'lifecycle')
96
+ # AR 9.4 and 7.4: the Python twin units a duty `on` stands down. STATUSD disables lanes-statusd.service; SYNC the sync,
97
+ # ensure, guard and tmpreap timers (W20-F: the lanes host's tasks run the same verbs); on an aggregator SITE disables
98
+ # only the sync timer (its Conflicts= stops statusd, 4.2); NOTIFY and ECONOMY their opt-in services. A duty flag
99
+ # `native.<duty>` exists only while every domain of the duty has an active cutover record for lanes-rs (`lanes rs
100
+ # apply` writes it no other way), so a twin is disabled only after its record reads active (FC-R7) and stands down on
101
+ # the record, never on a request alone (FC-G8).
102
+ TWIN_UNITS = (('statusd', ('lanes-statusd.service',)), ('notify', ('lanes-notify.service',)),
103
+ ('economy', ('lanes-economy.service',)),
104
+ ('sync', ('lanes-sync.timer', 'lanes-ensure.timer', 'lanes-guard.timer', 'lanes-tmpreap.timer')),
105
+ ('site', ('lanes-sync.timer',)))
106
+ # Which twins `lanes rs apply` disabled (so its rollback enables exactly those, never an opt-in unit the operator never
107
+ # enabled): $LANES_STATE/rs/twins.json, `lanes.rs-twins/1` {schema, disabled: [unit]} (DM-LANES2-NATIVE-FLAGS).
108
+ TWIN_RECORD = Path('rs') / 'twins.json'
109
+ TWIN_SCHEMA = 'lanes.rs-twins/1'
110
+ SYSTEMCTL_TIMEOUT = 30 # seconds one `systemctl --user` step of apply may take
111
+ SITE_CONF = Path('.config/lanes/site.conf')
112
+ # lanes_lib.SITE_LINE, the one site.conf line grammar (lanes_core::ident::site too): the last VALID line naming a key
113
+ # wins; a line outside the grammar is no fact at all (test_flags.HostUnit holds this copy to lanes_lib.site_conf).
114
+ SITE_LINE = re.compile(r'^(LANES_[A-Z_]+)=([A-Za-z0-9_.:@/-]*)$')
115
+
116
+
117
+ def host_binary_path(share):
118
+ """The throttle-rc lanes-host.service runs (FC-R1): the `lanes rs install` link bin-rs/throttle-rc when present,
119
+ else the `lanes studio-host install` selection bin/throttle-rc. `lanes rs apply` admitted HOST only for one that
120
+ verifies."""
121
+ installed = Path(share) / 'bin-rs' / 'throttle-rc'
122
+ return installed if os.path.lexists(installed) else throttle_rc_path(share)
123
+
124
+
125
+ def host_role(home):
126
+ """site.conf's LANES_HOST_ROLE as lanes_lib.site_conf reads it (SITE_LINE; the last valid line naming it wins), or
127
+ None: the same fact `lanes rs apply` and `throttle-rc lanes host` read."""
128
+ try:
129
+ text = (Path(home) / SITE_CONF).read_text()
130
+ except (OSError, UnicodeDecodeError):
131
+ return None
132
+ facts = dict(match.groups() for match in map(SITE_LINE.match, text.splitlines()) if match)
133
+ return facts.get('LANES_HOST_ROLE')
134
+
135
+
136
+ def host_unit_mode(home, state):
137
+ """The `--mode` lanes-host.service runs for the flags under `state` and the role in `home`'s site.conf: shadow,
138
+ owner or aggregator, or None when HOST is off (no native.host flag file, or an `on` file on a host that declares
139
+ no role apply would have admitted)."""
140
+ flags = Path(state) / 'flags'
141
+ role = host_role(home)
142
+ if os.path.lexists(flags / 'native.host.shadow') and role == 'owner':
143
+ return 'shadow'
144
+ if os.path.lexists(flags / 'native.host') and role in ('owner', 'aggregator'):
145
+ return role
146
+ return None
147
+
148
+
149
+ def render_host_unit(home, share, state):
150
+ """lanes-host.service's text for the flags under `state` and the role in `home`'s site.conf, or None when HOST is
151
+ off (host_unit_mode)."""
152
+ flags = Path(state) / 'flags'
153
+ mode = host_unit_mode(home, state)
154
+ if mode is None:
155
+ return None
156
+ on = [duty for duty in HOST_DUTY_FLAGS if os.path.lexists(flags / f'native.{duty}')]
157
+ if mode == 'shadow':
158
+ order = 'After=lanes-statusd.service\n'
159
+ else:
160
+ conflicts = sorted({unit for duty, unit in HOST_CONFLICTS if duty in on})
161
+ order = f"Conflicts={' '.join(conflicts)}\n" if conflicts else ''
162
+ content = HOST_TEMPLATE.read_text()
163
+ content = content.replace('@MODE@', mode).replace('@ORDER@\n', order)
164
+ content = content.replace('@THROTTLE_RC@', unit_value(host_binary_path(share), command=True))
165
+ content = content.replace('@STATE@', unit_value(Path(state), command=True))
166
+ content = content.replace('@WATCHDOG@', 'WatchdogSec=60\n' if mode == 'owner' and on else '')
167
+ return '# Generated by lanes/install/services.py; `lanes rs apply` renders or removes it.\n' + content
168
+
169
+
170
+ def reconcile_host_unit(home, share, state, units_dir):
171
+ """Render lanes-host.service into `units_dir` while HOST is shadow or on, remove it while HOST is off -> what
172
+ changed: 'rendered', 'unchanged', 'removed' or None (off, and there was none). The file only: it starts, stops,
173
+ enables and reloads nothing (a server install's re-render; `lanes rs apply` runs reconcile_units, which does)."""
174
+ units = Path(units_dir)
175
+ path = units / HOST_UNIT
176
+ content = render_host_unit(home, share, state)
177
+ if content is None:
178
+ if os.path.lexists(path):
179
+ path.unlink()
180
+ return 'removed'
181
+ return None
182
+ return write_host_unit(units, content)
183
+
184
+
185
+ def write_host_unit(units, content):
186
+ """Write lanes-host.service's `content` into `units` (one rename) -> 'rendered', or 'unchanged' when the file
187
+ already holds it."""
188
+ units = Path(units)
189
+ path = units / HOST_UNIT
190
+ try:
191
+ if not path.is_symlink() and path.read_text() == content:
192
+ return 'unchanged'
193
+ except OSError:
194
+ pass
195
+ units.mkdir(parents=True, exist_ok=True)
196
+ fd, temporary = tempfile.mkstemp(prefix='.lanes-', dir=units)
197
+ try:
198
+ with os.fdopen(fd, 'w') as handle:
199
+ handle.write(content)
200
+ os.chmod(temporary, 0o644)
201
+ os.replace(temporary, path)
202
+ finally:
203
+ if os.path.exists(temporary):
204
+ os.unlink(temporary)
205
+ return 'rendered'
206
+
207
+
208
+ def run_systemctl(args):
209
+ """`systemctl --user <args>` -> (exit status, or None for a timeout; its last line of output)."""
210
+ try:
211
+ done = subprocess.run(['systemctl', '--user', *args], capture_output=True, text=True,
212
+ timeout=SYSTEMCTL_TIMEOUT, stdin=subprocess.DEVNULL)
213
+ except subprocess.TimeoutExpired:
214
+ return None, f'no answer within {SYSTEMCTL_TIMEOUT} s'
215
+ except OSError as error:
216
+ return 127, str(error.strerror or error)
217
+ said = (done.stderr or done.stdout or '').strip().splitlines()
218
+ return done.returncode, said[-1] if said else ''
219
+
220
+
221
+ def read_twin_record(state):
222
+ """The twin units `lanes rs apply` disabled (TWIN_RECORD), as a set; empty without one (or with one that is not
223
+ a lanes.rs-twins/1 document, which the next write replaces)."""
224
+ try:
225
+ document = json.loads((Path(state) / TWIN_RECORD).read_text())
226
+ except (OSError, ValueError):
227
+ return set()
228
+ if not isinstance(document, dict) or document.get('schema') != TWIN_SCHEMA \
229
+ or not isinstance(document.get('disabled'), list):
230
+ return set()
231
+ known = {unit for _duty, units in TWIN_UNITS for unit in units}
232
+ return {unit for unit in document['disabled'] if unit in known}
233
+
234
+
235
+ def write_twin_record(state, disabled):
236
+ """Write TWIN_RECORD atomically (removed when nothing is disabled)."""
237
+ path = Path(state) / TWIN_RECORD
238
+ if not disabled:
239
+ if os.path.lexists(path):
240
+ path.unlink()
241
+ return
242
+ path.parent.mkdir(parents=True, exist_ok=True)
243
+ fd, temporary = tempfile.mkstemp(prefix='.twins-', dir=path.parent)
244
+ try:
245
+ with os.fdopen(fd, 'w') as handle:
246
+ json.dump({'schema': TWIN_SCHEMA, 'disabled': sorted(disabled)}, handle, sort_keys=True)
247
+ handle.write('\n')
248
+ os.chmod(temporary, 0o644)
249
+ os.replace(temporary, path)
250
+ finally:
251
+ if os.path.exists(temporary):
252
+ os.unlink(temporary)
253
+
254
+
255
+ def reconcile_units(home, share, state, units_dir, systemctl=None):
256
+ """`lanes rs apply`'s unit half (AR 9.4 as amended by FC-R1 and FC-R7), in both directions -> (lines, problems).
257
+
258
+ 1. lanes-host.service: while HOST is shadow or on it is rendered (reloading the manager when its text changed),
259
+ enabled, and restarted when its text changed or started when not (Conflicts= then stops the twins of the
260
+ duties on); while HOST is off a unit file still there is disabled and stopped first — the manager still knows
261
+ it — then removed, and the manager reloaded. The host lock and its process go with it: `lanes rs set host off
262
+ && lanes rs apply` is the rollback, no bare systemctl.
263
+ 2. The Python twins (TWIN_UNITS): in owner or aggregator mode each twin of a duty whose flag `native.<duty>`
264
+ exists (its records active for lanes-rs) is disabled and stopped, when it is enabled or running or this apply
265
+ disabled it before; each twin an earlier apply disabled (TWIN_RECORD) whose duty flag is gone is enabled and
266
+ started again. An opt-in twin the operator never enabled stays as it is.
267
+
268
+ `systemctl(args) -> (rc, last line)` runs `systemctl --user <args>` (run_systemctl). Nothing is asked of the
269
+ manager when nothing is to change: no unit, no duty on and no twin recorded. A failed step is a problem (apply
270
+ exits 3) and leaves the record saying what was really done."""
271
+ run = run_systemctl if systemctl is None else systemctl
272
+ lines, problems = [], []
273
+
274
+ def step(*args):
275
+ rc, said = run(list(args))
276
+ if rc != 0:
277
+ problems.append(f"systemctl --user {' '.join(args)}: {'no answer' if rc is None else f'exit {rc}'}"
278
+ + (f': {said}' if said else ''))
279
+ return rc == 0
280
+
281
+ units = Path(units_dir)
282
+ path = units / HOST_UNIT
283
+ mode = host_unit_mode(home, state)
284
+ content = render_host_unit(home, share, state)
285
+ if content is None:
286
+ if os.path.lexists(path):
287
+ step('disable', '--now', HOST_UNIT)
288
+ path.unlink()
289
+ step('daemon-reload')
290
+ lines.append(f'{HOST_UNIT} removed (disabled and stopped: HOST is off)')
291
+ else:
292
+ changed = write_host_unit(units, content)
293
+ if changed == 'rendered':
294
+ step('daemon-reload')
295
+ step('enable', HOST_UNIT)
296
+ step('restart' if changed == 'rendered' else 'start', HOST_UNIT)
297
+ lines.append(f"{HOST_UNIT} {changed} (--mode {mode}; enabled, "
298
+ f"{'restarted' if changed == 'rendered' else 'started'})")
299
+ flags = Path(state) / 'flags'
300
+ standing = set()
301
+ if mode in ('owner', 'aggregator'):
302
+ for duty, twins in TWIN_UNITS:
303
+ if os.path.lexists(flags / f'native.{duty}'):
304
+ standing.update(twins)
305
+ record = read_twin_record(state)
306
+ before = set(record)
307
+ for unit in sorted(standing):
308
+ if unit not in record and run(['is-enabled', unit])[0] != 0 and run(['is-active', unit])[0] != 0:
309
+ continue # an opt-in twin nobody enabled: nothing to stand down
310
+ if step('disable', '--now', unit):
311
+ record.add(unit)
312
+ lines.append(f'{unit} disabled and stopped: its duty belongs to the lanes host')
313
+ for unit in sorted(record - standing):
314
+ if step('enable', '--now', unit):
315
+ record.discard(unit)
316
+ lines.append(f'{unit} enabled and started again: its duty is back with Python')
317
+ if record != before:
318
+ write_twin_record(state, record)
319
+ return lines, problems
320
+
321
+
81
322
  # Units that run throttle-rc (or the installer that resolves its paths): they must see the SAME XDG roots the
82
323
  # installer used, or the config and credential it wrote are not where the supervised Host looks (review round 1).
83
324
  # Review round 3: BOTH roots are pinned ALWAYS — the installer's own, else the defaults as systemd specifiers — never
@@ -287,6 +528,8 @@ def _register(repo, home, share, state, workspaces, economy, notify, xdg, units_
287
528
  finally:
288
529
  if os.path.exists(temporary):
289
530
  os.unlink(temporary)
531
+ # Lanes 2.0: lanes-host.service follows the HOST flag in both directions (FC-R1), rendered by THIS tree's template.
532
+ reconcile_host_unit(home, share, state, units)
290
533
  # The commit point. The tree `current` named becomes `current.previous` when it still exists and is not the tree
291
534
  # being installed (a re-install, or a re-render — which installs the tree `current` names — must not make the
292
535
  # rollback target itself; a pruned tree is no target, so the last one recorded stays). Then the flip; then the
@@ -531,7 +531,9 @@ def claude_sessions(sessions_dir, proc_root, work=None, panes=None):
531
531
  entry = {'harness': 'claude', 'status': status, 'name': str(d.get('name') or ''),
532
532
  'session_id': str(d.get('sessionId') or ''), 'pid': pid,
533
533
  'since': since, 'source': 'claude-session-file'}
534
- if key not in out or entry['since'] >= out[key]['since']:
534
+ if since < 0:
535
+ del entry['since'] # FC-I-6: an instant is an unsigned count; a negative one is no instant
536
+ if key not in out or entry.get('since', -1) >= out[key].get('since', -1):
535
537
  out[key] = entry
536
538
  if work is not None:
537
539
  cwd = d.get('cwd')
@@ -9,10 +9,14 @@ not taken yet is bounded at OUTPUT_LIMIT: beyond it the oldest part is dropped
9
9
  and, once the terminal has caught up, the client is asked for a full repaint.
10
10
  Only a terminal that accepts no byte at all for OUTPUT_AGE ends the display
11
11
  (BEY-6844; the 1.5.1 guard of DEF-1965 also ended slow but healthy displays).
12
+ That is judged on the terminal's consumption as this relay records it
13
+ (StallRecord): past the deadline the pending output is offered once more, and
14
+ only an offer the terminal refuses ends the display (BEY-7309).
12
15
  """
13
16
  import collections
14
17
  import errno
15
18
  import fcntl
19
+ import json
16
20
  import os
17
21
  import pty
18
22
  import re
@@ -40,6 +44,10 @@ NOTICE = 'lanes: the display fell behind; dropping stale frames and repainting'
40
44
  # Operator overrides, read by the `lanes attach` entry below (bin/lanes forwards exactly these two keys).
41
45
  BACKLOG_ENV, BACKLOG_RANGE = 'LANES_DISPLAY_BACKLOG_BYTES', (2 * CHUNK, 256 * 1024 * 1024)
42
46
  STALL_ENV, STALL_RANGE = 'LANES_DISPLAY_STALL_S', (1.0, 600.0)
47
+ # Diagnostics: `1` writes the stall record line to stderr at exit (not forwarded by `lanes attach`).
48
+ STALL_RECORD_ENV = 'LANES_DISPLAY_STALL_RECORD'
49
+ RECENT_PERIODS = 8
50
+ RECORD_PREFIX = 'lanes: display stall record '
43
51
  # CAN cancels a partial escape sequence. Leave the alternate screen and restore
44
52
  # terminal modes even when the child cannot run its own teardown.
45
53
  RESET = (b'\x18\x1b[?2026l\x1b[?1049l\x1b[?1000l\x1b[?1002l\x1b[?1003l'
@@ -101,7 +109,109 @@ def align_pending(pending):
101
109
  return discard
102
110
 
103
111
 
104
- def relay(command, output_limit=OUTPUT_LIMIT, output_age=OUTPUT_AGE):
112
+ class StallRecord:
113
+ """The display's consumption as this relay counts it, and the stall decision taken from it (BEY-6844, BEY-7309);
114
+ the Rust relay's `relay::stall::StallRecord`, rule and record line alike.
115
+
116
+ The stall rule is a progress deadline: while output waits, a terminal that takes no byte for the stall time is
117
+ hung. Every byte the terminal takes is recorded (`took`) and restarts the deadline. While output waits the loop's
118
+ whole stall step is one call, `judge_overdue`: once the deadline has passed it offers the pending output once more
119
+ (the loop's `offer`) and judges what the terminal took, stamped with the look's time; only a refused offer ends
120
+ the display. A relay that was itself descheduled past the deadline (a loaded host) so credits what the
121
+ terminal took meanwhile, because the room the terminal made is still there; before BEY-7309 this loop judged on
122
+ its clock alone, after a step that had not offered, and ended a display that kept reading. A terminal that takes
123
+ nothing is ended at the same moment as before: the extra offer is refused at once.
124
+
125
+ The time output waits is split into stall periods, each a whole stall time of waiting (paused while nothing
126
+ waits). A period closes at the first look after it filled, after that look's overdue offer was judged; a late
127
+ look closes one longer period, never several empty ones. Under the deadline no closed period is empty."""
128
+
129
+ def __init__(self, stall, now):
130
+ self.stall = stall
131
+ self.last_progress = now # the last byte the terminal took, or the last look while nothing waited
132
+ self.tick = None # the last look while output waited (None: nothing waits, the period pauses)
133
+ self.waited = 0.0 # waiting time in the open period
134
+ self.open_bytes = 0
135
+ self.periods = 0
136
+ self.min_period_bytes = None
137
+ self.recent = collections.deque(maxlen=RECENT_PERIODS)
138
+ self.accepted = 0
139
+ self.overdue_offers_taken = 0
140
+ self.longest_wait = 0.0
141
+ self.stalled = False
142
+
143
+ def idle(self, now):
144
+ """Nothing waits at `now`: no deadline runs and the open period pauses."""
145
+ self.last_progress = now
146
+ self.tick = None
147
+
148
+ def judge_overdue(self, now, offer):
149
+ """The loop's step while output waits, the one place the stall is decided: the open period's waiting time
150
+ grows to `now`; once the deadline has passed, `offer()` hands the terminal its pending output once (one
151
+ non-blocking write -> the bytes it took) and that offer is judged, a take stamped `now`; then a period that is
152
+ due closes -> whether the display stalled. An offer that raises is the loop's error and decides nothing."""
153
+ self.waiting(now)
154
+ if self.overdue(now) and self.judge(now, offer()):
155
+ return True
156
+ self.close_due()
157
+ return False
158
+
159
+ def waiting(self, now):
160
+ """Output waits at `now`: the open period's waiting time grows."""
161
+ if self.tick is not None:
162
+ self.waited += max(0.0, now - self.tick)
163
+ self.tick = now
164
+
165
+ def took(self, now, taken):
166
+ """The terminal took `taken` bytes of the relay's output at `now` (0 records nothing)."""
167
+ if taken <= 0:
168
+ return
169
+ self.longest_wait = max(self.longest_wait, now - self.last_progress)
170
+ self.last_progress = now
171
+ self.accepted += taken
172
+ self.open_bytes += taken
173
+
174
+ def overdue(self, now):
175
+ """Whether the deadline has passed at `now`."""
176
+ return now - self.last_progress >= self.stall
177
+
178
+ def judge(self, now, taken):
179
+ """The offer made because the deadline passed took `taken` bytes -> whether the terminal is stalled."""
180
+ if taken > 0:
181
+ self.overdue_offers_taken += 1
182
+ self.took(now, taken)
183
+ return False
184
+ self.longest_wait = max(self.longest_wait, now - self.last_progress)
185
+ self.stalled = True
186
+ return True
187
+
188
+ def close_due(self):
189
+ """Close the open period once it has waited a whole stall time (after the look's overdue offer)."""
190
+ if self.waited < self.stall:
191
+ return
192
+ self.periods += 1
193
+ self.min_period_bytes = (self.open_bytes if self.min_period_bytes is None
194
+ else min(self.min_period_bytes, self.open_bytes))
195
+ self.recent.append(self.open_bytes)
196
+ self.open_bytes = 0
197
+ self.waited = 0.0
198
+
199
+ def line(self):
200
+ """The record line: the prefix and one JSON object, keys in the Rust relay's order."""
201
+ return RECORD_PREFIX + json.dumps({
202
+ 'stall_ms': round(self.stall * 1000),
203
+ 'periods': self.periods,
204
+ 'min_period_bytes': self.min_period_bytes,
205
+ 'recent_periods': list(self.recent),
206
+ 'open_period_bytes': self.open_bytes,
207
+ 'accepted_bytes': self.accepted,
208
+ 'overdue_offers_taken': self.overdue_offers_taken,
209
+ 'longest_wait_ms': int(self.longest_wait * 1000),
210
+ 'decision': 'stalled' if self.stalled else 'kept',
211
+ }, separators=(',', ':'))
212
+
213
+
214
+ def relay(command, output_limit=OUTPUT_LIMIT, output_age=OUTPUT_AGE, record=False):
105
215
  if not command:
106
216
  raise ValueError('No display command supplied')
107
217
  if not os.isatty(0) or not os.isatty(1):
@@ -111,7 +221,7 @@ def relay(command, output_limit=OUTPUT_LIMIT, output_age=OUTPUT_AGE):
111
221
  flags = fcntl.fcntl(1, fcntl.F_GETFL)
112
222
  pending = collections.deque() # bytes the terminal has not taken yet, oldest first; includes partial writes
113
223
  pending_size = 0
114
- last_progress = time.monotonic() # the last write the terminal took (>= 1 byte), or when nothing was pending
224
+ stall = StallRecord(output_age, time.monotonic()) # what the terminal took, and the stall decision
115
225
  redraw_pending = False # output was dropped since the last repaint request
116
226
  last_repaint = None
117
227
  restore_at = None # a repaint's second half: when to give the client the real size again
@@ -163,18 +273,32 @@ def relay(command, output_limit=OUTPUT_LIMIT, output_age=OUTPUT_AGE):
163
273
 
164
274
  def write_now(data):
165
275
  """Write `data` with nothing pending -> whether the terminal took all of it; the rest is queued in order."""
166
- nonlocal pending_size, last_progress
276
+ nonlocal pending_size
167
277
  try:
168
278
  written = os.write(1, data)
169
279
  except BlockingIOError:
170
280
  written = 0
171
- if written:
172
- last_progress = time.monotonic()
281
+ stall.took(time.monotonic(), written)
173
282
  if written < len(data):
174
283
  pending.append(data[written:])
175
284
  pending_size += len(data) - written
176
285
  return written == len(data)
177
286
 
287
+ def offer():
288
+ """Hand the terminal the oldest pending output once, without waiting -> the bytes it took."""
289
+ nonlocal pending_size
290
+ data = pending[0]
291
+ try:
292
+ written = os.write(1, data)
293
+ except BlockingIOError:
294
+ written = 0
295
+ pending_size -= written
296
+ if written == len(data):
297
+ pending.popleft()
298
+ elif written:
299
+ pending[0] = data[written:]
300
+ return written
301
+
178
302
  def repaint():
179
303
  """The terminal holds everything kept: cancel what a cut may have left open, then ask for a full frame."""
180
304
  nonlocal noticed, restore_at, last_repaint, redraw_pending
@@ -226,10 +350,13 @@ def relay(command, output_limit=OUTPUT_LIMIT, output_age=OUTPUT_AGE):
226
350
  status = value
227
351
  now = time.monotonic()
228
352
  if not pending:
229
- last_progress = now
353
+ stall.idle(now)
230
354
  # Stall rule (BEY-6844): a slow terminal still takes bytes; one that takes none for output_age is hung.
231
- # Progress, not the age of the oldest output: an age rule also ended slow but healthy displays.
232
- elif now - last_progress >= output_age:
355
+ # Progress, not the age of the oldest output: an age rule also ended slow but healthy displays. Judged on
356
+ # an offer made at this look (BEY-7309): this step may follow a read and a shed, or a pause of this process
357
+ # on a loaded host, without having offered anything, so the terminal is handed its pending output once
358
+ # more and only a refused offer ends the display.
359
+ elif stall.judge_overdue(now, offer):
233
360
  reason = 'display output stalled'
234
361
  break
235
362
  if eof and not pending:
@@ -245,18 +372,7 @@ def relay(command, output_limit=OUTPUT_LIMIT, output_age=OUTPUT_AGE):
245
372
  readable, writable, _ = select.select(readers, writers, [], 0.05)
246
373
  # Drain first: a writable terminal should not trip the byte limit.
247
374
  if 1 in writable:
248
- data = pending[0]
249
- try:
250
- written = os.write(1, data)
251
- except BlockingIOError:
252
- written = 0
253
- if written:
254
- last_progress = time.monotonic()
255
- pending_size -= written
256
- if written == len(data):
257
- pending.popleft()
258
- elif written:
259
- pending[0] = data[written:]
375
+ stall.took(time.monotonic(), offer())
260
376
  if master in writable:
261
377
  try:
262
378
  written = os.write(master, input_pending)
@@ -320,6 +436,8 @@ def relay(command, output_limit=OUTPUT_LIMIT, output_age=OUTPUT_AGE):
320
436
  'were dropped and the screen repainted.')
321
437
  if reason:
322
438
  lines.append(f'lanes: {reason}; reconnecting the display.')
439
+ if record:
440
+ lines.append(stall.line())
323
441
  if lines:
324
442
  try:
325
443
  os.write(2, ''.join(f'\r\n{line}' for line in lines).encode() + b'\r\n')
@@ -341,7 +459,7 @@ def main(command, environ):
341
459
  output_limit, output_age, refused = settings(environ)
342
460
  for line in refused:
343
461
  print(line, file=sys.stderr, flush=True)
344
- return relay(command, output_limit, output_age)
462
+ return relay(command, output_limit, output_age, record=environ.get(STALL_RECORD_ENV) == '1')
345
463
 
346
464
 
347
465
  if __name__ == '__main__':
@@ -86,6 +86,17 @@ ADMITTING = frozenset({'shadow', 'prepared', 'active', 'rolled_back'})
86
86
  ROLLBACK_FROM = frozenset({'quiesced', 'drained', 'cut_verified'}) # rollback.rs ABORTABLE: fenced, epoch uncommitted
87
87
  COMMITTED = frozenset({'epoch_committed', 'active'}) # only the reverse fence takes these back
88
88
  LEGACY_OWNER = 'lanes-py' # who owns a domain with no record
89
+ NO_LEGACY_OWNER = 'none' # a domain nobody owns before its first record
90
+ # FC-R2: the closed 2.0 domain table and each domain's legacy owner, identical to
91
+ # crates/lanes-runtime/src/cutover/domain.rs DOMAINS and its golden legacy-owners.v1.golden.json
92
+ # (test_cutover.LegacyOwnerTableParity). `observation` and `delivery` are fenced together. A domain outside the
93
+ # table keeps the single LEGACY_OWNER default (the 1.x adoption domains of adopt.py).
94
+ LEGACY_OWNERS = {
95
+ 'observation': 'lanes-py', 'delivery': 'lanes-py', 'lifecycle': 'lanes-py', 'attention': 'studio-host',
96
+ 'visibility': 'lanes-py', 'notify': 'lanes-py', 'economy': 'lanes-py', 'sync': 'lanes-py', 'site': 'lanes-py',
97
+ 'routes': 'lanes-py', 'store': NO_LEGACY_OWNER, 'schedule': NO_LEGACY_OWNER, 'project': NO_LEGACY_OWNER,
98
+ 'connectors': NO_LEGACY_OWNER,
99
+ }
89
100
  DOMAIN_RE = re.compile(r'[a-z][a-z0-9-]{0,31}\Z') # domain.rs StateDomain
90
101
  TOKEN_RE = re.compile(r'[A-Za-z0-9_][A-Za-z0-9_.:-]{0,127}\Z') # lanes_core Token (HostInstanceId)
91
102
  ENDPOINT_RE = re.compile(r'[a-z0-9][a-z0-9._-]{0,63}\Z') # legacy.rs EndpointId
@@ -292,10 +303,18 @@ def records(state, domains=()):
292
303
 
293
304
  # ---------------------------------------------------------------- ownership and rollback
294
305
 
306
+ def legacy_owner(domain):
307
+ """The holder that owns `domain` while it has no record (FC-R2's table; LEGACY_OWNER outside it)."""
308
+ return LEGACY_OWNERS.get(domain, LEGACY_OWNER)
309
+
310
+
295
311
  def may_own(record, holder, readable, legacy=LEGACY_OWNER):
296
- """(True, 'ok' | 'no_cutover') or (False, 'schema_ahead' | 'owned_elsewhere'). With no record only the legacy
297
- owner owns the domain."""
312
+ """(True, 'ok' | 'no_cutover') or (False, 'schema_ahead' | 'owned_elsewhere' | 'no_cutover'). With no record only
313
+ the legacy owner owns the domain; a domain whose legacy owner is NO_LEGACY_OWNER is nobody's until its first
314
+ record."""
298
315
  if record is None:
316
+ if legacy == NO_LEGACY_OWNER:
317
+ return False, 'no_cutover'
299
318
  return (True, 'no_cutover') if holder == legacy else (False, 'owned_elsewhere')
300
319
  if readable < record['schema']:
301
320
  return False, 'schema_ahead'
@@ -579,7 +598,7 @@ def _parser():
579
598
  check.add_argument('--holder', required=True)
580
599
  check.add_argument('--schema', required=True, type=_positive)
581
600
  check.add_argument('--admit', action='store_true')
582
- check.add_argument('--legacy', default=LEGACY_OWNER, help='who owns a domain with no record')
601
+ check.add_argument('--legacy', default=None, help='who owns a domain with no record (default: its FC-R2 legacy owner)')
583
602
  back = commands.add_parser('rollback')
584
603
  back.add_argument('domain')
585
604
  back.add_argument('--to', required=True)
@@ -619,7 +638,8 @@ def main(argv, state=None, out=None):
619
638
  return 1 if any(isinstance(value, Refused) for value in found.values()) else 0
620
639
  if args.command == 'check':
621
640
  record = read_record(state, args.domain)
622
- allowed, code = (may_admit if args.admit else may_own)(record, args.holder, args.schema, args.legacy)
641
+ legacy = args.legacy if args.legacy is not None else legacy_owner(args.domain)
642
+ allowed, code = (may_admit if args.admit else may_own)(record, args.holder, args.schema, legacy)
623
643
  print(code, file=out)
624
644
  return 0 if allowed else EXIT_REFUSED
625
645
  if args.command == 'rollback':
@@ -3,7 +3,7 @@
3
3
 
4
4
  A Lanes 2.0 host keeps one bounded metrics registry (crates/lanes-runtime/src/signals) and exports it as the snapshot
5
5
  `$LANES_STATE/signals/lanes2.json` (`lanes2.signals.snapshot/2`, the manifest docs/contracts/lanes2/manifests/
6
- signals.json revision 2; DM-LANES2-RT16-SIGNALS). The snapshot is self-describing: every signal carries its doctor
6
+ signals.json revision 3; DM-LANES2-RT16-SIGNALS). The snapshot is self-describing: every signal carries its doctor
7
7
  phrase, unit, kind, delay origin, state (ok, warn, alert or unavailable with a reason) and per label its value, its
8
8
  increase in the window (a counter) or its rise (a high-water mark), its state and reason, and the threshold the host
9
9
  resolved from its resource manifest (lane G2), benchmark.json (RT 14.1, 15.3) or the subsystem's own reported cap.
@@ -153,7 +153,7 @@ def check_snapshot(doc):
153
153
 
154
154
  need(isinstance(doc, dict), 'not a JSON object')
155
155
  need(doc.get('schema') == SCHEMA and doc.get('v') == 2, f'not {SCHEMA}')
156
- for key in ('manifest_revision', 'resources_revision', 'written_at_ms', 'refresh_ms', 'stale_after_ms'):
156
+ for key in ('manifest_revision', 'resources_revision', 'written_at_unix_ms', 'refresh_ms', 'stale_after_ms'):
157
157
  need(has(doc, key, is_int), f'`{key}` is not a non-negative integer')
158
158
  for key in ('profile', 'runtime_version'):
159
159
  need(has(doc, key, text), f'`{key}` is not a string')
@@ -199,7 +199,7 @@ def render(doc, now_ms, path):
199
199
  """[(mark, text)] of a parsed snapshot `doc` read from `path` at `now_ms` (Unix ms)."""
200
200
  check_snapshot(doc)
201
201
  host = doc['host_instance'] or 'an unnamed host'
202
- written, stale = doc['written_at_ms'], doc['stale_after_ms']
202
+ written, stale = doc['written_at_unix_ms'], doc['stale_after_ms']
203
203
  lines = [('', f"lanes2 runtime signals: {path}, from {host} (lanes-runtime {doc['runtime_version']}, "
204
204
  f"source {doc['source_revision'] or 'unknown'}, installed {doc['installed_version'] or 'unknown'}, "
205
205
  f"profile {doc['profile']} r{doc['resources_revision']}, manifest r{doc['manifest_revision']})")]
@@ -3,7 +3,7 @@
3
3
  #
4
4
  # lanes_native COMPONENT TREE
5
5
  #
6
- # sets $lanes_native to the native binary COMPONENT (relay, sidebar, key or signal) runs from TREE, or to the empty
6
+ # sets $lanes_native to the native binary COMPONENT (relay, sidebar, key, client or signal) runs from TREE, or to the empty
7
7
  # string for its Python path. Native only while `lanes rs apply` admitted the flag, i.e. while
8
8
  # $LANES_STATE/flags/native.<component> exists ([ -e ]; `shadow` never selects a binary), and then only the FIRST
9
9
  # candidate that exists, in resolve()'s order:
@@ -16,7 +16,7 @@
16
16
  lanes_native() {
17
17
  lanes_native=
18
18
  case $1 in
19
- relay|sidebar|key) lanes_native_binary=lanes-terminal ;;
19
+ relay|sidebar|key|client) lanes_native_binary=lanes-terminal ;;
20
20
  signal) lanes_native_binary=lanes-hook ;;
21
21
  *) return 0 ;;
22
22
  esac