@vibelord/lanes 1.8.0 → 1.9.3

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 (61) hide show
  1. package/package.json +1 -1
  2. package/payload/lanes/README.md +29 -11
  3. package/payload/lanes/VERSION +1 -1
  4. package/payload/lanes/bin/lanes +159 -59
  5. package/payload/lanes/bin-rs/BINARIES.json +2 -17
  6. package/payload/lanes/client/lanes-launch +51 -2
  7. package/payload/lanes/container/lane +142 -19
  8. package/payload/lanes/container/lane-mcp +168 -55
  9. package/payload/lanes/container/lane-peerd +6 -6
  10. package/payload/lanes/container/lane-signal +48 -3
  11. package/payload/lanes/container/lane_core.py +1040 -164
  12. package/payload/lanes/container/throttle-pulse +13 -4
  13. package/payload/lanes/docs/AGENTS-lanes.md +15 -7
  14. package/payload/lanes/docs/ARCHITECTURE.md +478 -101
  15. package/payload/lanes/docs/DESIGN.md +7 -2
  16. package/payload/lanes/docs/INSTALL.md +20 -3
  17. package/payload/lanes/docs/PLAN-1.9.1-SIDEBAR-CODEX.md +128 -0
  18. package/payload/lanes/docs/RUNBOOK.md +1428 -107
  19. package/payload/lanes/docs/USERGUIDE.md +488 -86
  20. package/payload/lanes/holders/tmux.sh +3 -3
  21. package/payload/lanes/install/services.py +68 -11
  22. package/payload/lanes/libexec/agent_state.py +2 -5
  23. package/payload/lanes/libexec/attach.py +11 -3
  24. package/payload/lanes/libexec/cursor_sync.py +22 -2
  25. package/payload/lanes/libexec/docsd.py +38 -4
  26. package/payload/lanes/libexec/lanes_lib.py +377 -39
  27. package/payload/lanes/libexec/mdlite.py +43 -3
  28. package/payload/lanes/libexec/notify.py +69 -26
  29. package/payload/lanes/libexec/registrations.py +5 -0
  30. package/payload/lanes/libexec/session_actions.py +114 -27
  31. package/payload/lanes/libexec/sidebar.py +246 -64
  32. package/payload/lanes/libexec/site_hooks.py +65 -0
  33. package/payload/lanes/libexec/statusd.py +139 -189
  34. package/payload/lanes/libexec/studio_host.py +8 -2
  35. package/payload/lanes/libexec/tokens.py +6 -2
  36. package/payload/lanes/libexec/update.py +13 -5
  37. package/payload/lanes/libexec/view.sh +39 -4
  38. package/payload/lanes/libexec/workspace_keys.py +54 -0
  39. package/payload/lanes/site/protocol.py +15 -5
  40. package/payload/lanes/site/relay.py +5 -2
  41. package/payload/lanes/site/server.py +29 -18
  42. package/payload/lanes/systemd/lanes-economy.service +3 -1
  43. package/payload/lanes/tokens/README.md +10 -0
  44. package/payload/lanes/tokens/generate.py +1 -1
  45. package/payload/lanes/web/Caddyfile +9 -2
  46. package/payload/lanes/web/README.md +2410 -95
  47. package/payload/lanes/web/browser.css +2 -0
  48. package/payload/lanes/web/browser.js +18 -6
  49. package/payload/lanes/web/directory.js +1 -1
  50. package/payload/lanes/web/docs.js +23 -0
  51. package/payload/lanes/web/links.js +157 -0
  52. package/payload/lanes/web/manifest.webmanifest +0 -2
  53. package/payload/lanes/web/mobile.css +30 -32
  54. package/payload/lanes/web/mobile.js +286 -227
  55. package/payload/lanes/web/upload.js +65 -22
  56. package/payload/lanes/web/workspace-keys.js +65 -0
  57. package/payload/lanes/zellij/config.kdl +1 -1
  58. package/payload/manifest.json +5 -22
  59. package/payload/lanes/bin-rs/THIRD-PARTY-NOTICES +0 -18953
  60. package/payload/lanes/bin-rs/x86_64-unknown-linux-musl/lanes-hook +0 -0
  61. package/payload/lanes/bin-rs/x86_64-unknown-linux-musl/lanes-terminal +0 -0
@@ -55,6 +55,152 @@ def site_conf(home=None):
55
55
  return dict(match.groups() for match in map(SITE_LINE.match, text.splitlines()) if match)
56
56
 
57
57
 
58
+ # The Throttle control URL the fleet block's pulse polls (BEY-6845): `LANES_THROTTLE_CONTROL=<url>` in site.conf, the
59
+ # one declared place. In a fleet container the daemon's control port is not forwarded (only the data planes), so the
60
+ # pulse's loopback default answers `connection refused` and the block can show nothing; the operator names a reachable
61
+ # forward here, and every start of the pulse's loop carries it as `--control <url>` (bin/lanes start_pulse, statusd's
62
+ # re-arm and lanes-runtime's PulseRearm template, byte for byte, DEF-1940). The same line is the economy unit's
63
+ # LANES_THROTTLE_CONTROL when the installer's environment does not set it (install/services.py economy_settings,
64
+ # which validates and normalises either source with this table and refuses the install on a refused value).
65
+ # `none`/`off` declare no URL (the pulse keeps its default; the economy poller sends nothing). A value is a plain
66
+ # `http(s)://host:port`, an optional trailing `/`: no user part (credentials never belong in site.conf), no path, no
67
+ # query or fragment, an explicit port, no whitespace anywhere — judged as written, so a value this accepts is a line
68
+ # SITE_LINE admits and no reader (site_conf, enrold.server_site, lanes-core site_facts) drops a line `lanes sync`
69
+ # accepted. Stricter than the pulse's own `--control` check, which admits a user part and a port-less host. The Rust
70
+ # twin is lanes-core `ident::site::throttle_control`.
71
+ THROTTLE_CONTROL_KEY = 'LANES_THROTTLE_CONTROL'
72
+ THROTTLE_CONTROL_OFF = ('none', 'off')
73
+ _HOST_LABEL = re.compile(r'^[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\Z', re.ASCII)
74
+
75
+
76
+ def throttle_control(value):
77
+ """site.conf's LANES_THROTTLE_CONTROL -> (url without its trailing `/`, None) for a plain `http(s)://host:port[/]`;
78
+ (None, None) when unset, blank or `none`/`off` (whitespace around those words alone is forgiven: SITE_LINE drops
79
+ such a line and every reader then sees the same nothing); (None, why) when a URL is written and refused — a space
80
+ before or after it included, since a line with one is dropped by every reader and the setting would be silently
81
+ ignored — the caller then names the key and starts nothing with a guessed default."""
82
+ if value is None:
83
+ return None, None
84
+ value = str(value)
85
+ if not value.strip() or value.strip().lower() in THROTTLE_CONTROL_OFF:
86
+ return None, None
87
+ if re.search(r'\s', value):
88
+ return None, 'a space or a comment'
89
+ if not value.startswith(('http://', 'https://')):
90
+ return None, 'not an http(s) URL'
91
+ scheme, _sep, rest = value.partition('://')
92
+ authority, _slash, path = rest.partition('/')
93
+ if '?' in rest or '#' in rest:
94
+ return None, 'a query or fragment'
95
+ if path:
96
+ return None, 'a path (the base URL only)'
97
+ if '@' in authority:
98
+ return None, 'a user part'
99
+ host, colon, port = authority.rpartition(':')
100
+ if not colon:
101
+ return None, 'no port'
102
+ if not port.isdigit() or len(port) > 5:
103
+ return None, 'not a port'
104
+ if not 0 < int(port) < 65536:
105
+ return None, 'port out of range'
106
+ labels = host.split('.')
107
+ if not host or len(host) > 253 or not all(_HOST_LABEL.match(label) for label in labels):
108
+ return None, 'not a plain host name or address'
109
+ return f'{scheme}://{authority}', None
110
+
111
+
112
+ def site_problems(home=None):
113
+ """site.conf lines that name a validated key with a value it refuses -> [(key, why)], judged on the RAW last line
114
+ naming the key (a line SITE_LINE does not admit — a space, a `?` — is refused here, never read as unset; a value
115
+ the validator accepts is always one SITE_LINE admits, so the readers see exactly what was accepted). [] when there
116
+ is no file or every validated key is unset or accepted. `lanes sync` refuses the whole sync on any, naming the
117
+ key; `lanes install-container`, statusd's re-arm (pulse_control) and the installer's economy rendering
118
+ (install/services.py economy_settings) then start or write nothing."""
119
+ try:
120
+ text = ((Path(home) if home is not None else Path.home()) / SITE_CONF).read_text()
121
+ except (OSError, UnicodeDecodeError, KeyError, RuntimeError):
122
+ return []
123
+ values = [line.split('=', 1)[1] for line in text.splitlines() if line.startswith(THROTTLE_CONTROL_KEY + '=')]
124
+ if not values:
125
+ return []
126
+ _url, why = throttle_control(values[-1])
127
+ return [(THROTTLE_CONTROL_KEY, why)] if why else []
128
+
129
+
130
+ def site_declares(key, home=None):
131
+ """True when site.conf has a line naming `key` at all, accepted or not (the RAW file, as site_problems reads it):
132
+ `lanes update` then lets that line, not the value carried from the previously rendered economy unit, stand for
133
+ LANES_THROTTLE_CONTROL (update.carried_settings). False without a readable file."""
134
+ try:
135
+ text = ((Path(home) if home is not None else Path.home()) / SITE_CONF).read_text()
136
+ except (OSError, UnicodeDecodeError, KeyError, RuntimeError):
137
+ return False
138
+ return any(line.startswith(f'{key}=') for line in text.splitlines())
139
+
140
+
141
+ # Whether a view session ends with the Host tab, a login shell on the server (BEY-8423, 13 Nov 2026: the fleet views
142
+ # leave it out): only `LANES_HOST_TAB=1` in site.conf adds it; no line or `0` leaves it out. Any other value is refused
143
+ # by `lanes sync` (sync_registry, through host_tab_problem), naming the key, and reads as off meanwhile. Only the view
144
+ # layout reads the key (bin/lanes tab_specs / layout_kdl and upgrade-session): the pulse and the installer never do,
145
+ # so it is not one of site_problems' keys.
146
+ HOST_TAB_KEY = 'LANES_HOST_TAB'
147
+
148
+
149
+ def host_tab(home=None):
150
+ """True only when site.conf's LANES_HOST_TAB (site_conf: the last line naming it) is `1` (BEY-8423); no line, `0`
151
+ or a refused value is off."""
152
+ return site_conf(home).get(HOST_TAB_KEY) == '1'
153
+
154
+
155
+ def host_tab_problem(home=None):
156
+ """Why site.conf's LANES_HOST_TAB line is refused, judged on the RAW last line naming the key (as site_problems
157
+ judges its own: a line SITE_LINE does not admit is refused here, never read as unset) -> a reason, or None when
158
+ there is no such line or it is `0` or `1`."""
159
+ try:
160
+ text = ((Path(home) if home is not None else Path.home()) / SITE_CONF).read_text()
161
+ except (OSError, UnicodeDecodeError, KeyError, RuntimeError):
162
+ return None
163
+ values = [line.split('=', 1)[1] for line in text.splitlines() if line.startswith(HOST_TAB_KEY + '=')]
164
+ if not values or values[-1] in ('0', '1'):
165
+ return None
166
+ return f'{values[-1]!r} is neither 0 (no Host tab, the default) nor 1 (a Host tab at the end of every view)'
167
+
168
+
169
+ def pulse_control(home=None):
170
+ """The `--control <url>` the Throttle pulse's loop is started with -> (url, None); (None, None) when site.conf
171
+ declares none (the pulse polls its own default); (None, why) when the line is refused (site_problems)."""
172
+ problems = site_problems(home)
173
+ if problems:
174
+ return None, problems[0][1]
175
+ return throttle_control(site_conf(home).get(THROTTLE_CONTROL_KEY))
176
+
177
+
178
+ def pulse_control_args(url):
179
+ """The argv tail every start of the pulse's loop appends for a declared control URL: `--control <url>`, else
180
+ nothing (DEF-1940: bin/lanes start_pulse, statusd.pulse_rearm_argv and the Rust PulseRearm template agree)."""
181
+ return ['--control', url] if url else []
182
+
183
+
184
+ # The pulse's failure classes that mean its GET never reached a daemon (lanes/container/throttle-pulse failure_class),
185
+ # as against `HTTP N`, where a daemon answered and refused. An unreached daemon is not known to be down: the fleet block
186
+ # and `lanes doctor` say WHERE the pulse could not reach it (its `control_url`) instead of `down` (BEY-6845).
187
+ PULSE_UNREACHED = ('connection refused', 'timed out', 'unreachable')
188
+
189
+
190
+ def pulse_unreached(error):
191
+ """True when a pulse document's `error` says no connection reached the daemon (PULSE_UNREACHED, `unreachable: …`
192
+ included); False for an answer (`HTTP 503`), a reader-mode failure, no error at all or no string."""
193
+ return isinstance(error, str) and error.split(':', 1)[0].strip() in PULSE_UNREACHED
194
+
195
+
196
+ def pulse_control_host(url):
197
+ """A pulse document's `control_url` as a row shows it: `host:port`, the scheme dropped; '' when it is no string
198
+ or no http(s) URL (a reader-mode pulse writes null)."""
199
+ if not isinstance(url, str) or not url.startswith(('http://', 'https://')):
200
+ return ''
201
+ return url.split('://', 1)[1].rstrip('/')
202
+
203
+
58
204
  def staged_tree(path):
59
205
  """Whether `path` is a tree the npm wrapper staged, not a checkout: it sits in the default pkg root
60
206
  (`…/pkg/<version>`), or it carries the wrapper's stamp (PACKAGE_STAMP, a regular file lanes-install.mjs stage()
@@ -140,7 +286,7 @@ def tree_file_at(words, name):
140
286
  lanes tree, else None: an absolute path ending in `/<name>`. Since W9 U1 a layout names its files through CURRENT
141
287
  (`…/current/<name>`), a layout built before names the `pkg/<version>` tree that built it, a checkout names itself —
142
288
  and one session can hold panes of each after an update. They are the same pane, so a reader (device_sync's tab
143
- identities, bin/lanes focused_view and stale_picker_layouts) matches the suffix, never one tree's full path; a
289
+ identities, bin/lanes focused_view and stale_phone_layouts) matches the suffix, never one tree's full path; a
144
290
  relative path, or a file that only ends like it (`/opt/myview.sh`), runs no tree file."""
145
291
  suffix = '/' + name
146
292
  return next((index for index, word in enumerate(words) if word.startswith('/') and word.endswith(suffix)), None)
@@ -276,16 +422,22 @@ class ProjectionRefused(LanesError):
276
422
  super().__init__(f'{what} saved; {self.pending}')
277
423
 
278
424
 
279
- def atomic_write(path, text, mode=0o600):
425
+ def atomic_write(path, text, mode=0o600, mtime_ns=None):
280
426
  """Replace `path` with `text` atomically (temp file in the same directory, chmod, rename). `text` may be bytes:
281
427
  then it is written byte for byte, never through the locale's encoding (keys.py keeps foreign authorized_keys
282
- lines exactly)."""
428
+ lines exactly). `mtime_ns`, when given, becomes the file's atime and mtime (ns), set on the temp file after its
429
+ last byte and before the rename, so the name never shows another: a writer that publishes a revision through
430
+ stat (statusd's projections, atomic_write_stamped, BEY-7606) chooses it instead of the file system's clock. None
431
+ (every other caller) leaves the clock's."""
283
432
  path = Path(path)
284
433
  path.parent.mkdir(parents=True, exist_ok=True)
285
434
  fd, tmp = tempfile.mkstemp(prefix='.' + path.name + '.', dir=str(path.parent))
286
435
  try:
287
436
  with os.fdopen(fd, 'wb' if isinstance(text, bytes) else 'w') as handle:
288
437
  handle.write(text)
438
+ if mtime_ns is not None:
439
+ handle.flush() # every byte first: a write after the stamp would move the mtime again
440
+ os.utime(handle.fileno() if os.utime in os.supports_fd else tmp, ns=(mtime_ns, mtime_ns))
289
441
  os.chmod(tmp, mode)
290
442
  os.replace(tmp, path)
291
443
  except BaseException:
@@ -296,17 +448,47 @@ def atomic_write(path, text, mode=0o600):
296
448
  raise
297
449
 
298
450
 
299
- def atomic_write_if_changed(path, text, mode=0o600):
451
+ def atomic_write_if_changed(path, text, mode=0o600, mtime_ns=None):
300
452
  """atomic_write, skipped when the file already holds exactly `text` -> True when it wrote. Readers that reload
301
453
  on mtime (statusd and notify on registry.json, every sidebar) then do not wake for a projection that did not
302
454
  change, and the timer-driven sync stops rewriting the container volumes every two minutes. Bytes compare and
303
- write as bytes."""
455
+ write as bytes. `mtime_ns` is atomic_write's, applied only when it writes (a skipped write keeps the file's)."""
304
456
  try:
305
457
  if (Path(path).read_bytes() if isinstance(text, bytes) else Path(path).read_text()) == text:
306
458
  return False
307
459
  except (OSError, ValueError):
308
460
  pass
309
- atomic_write(path, text, mode)
461
+ if mtime_ns is None: # the call every caller made before mtime_ns (and every stand-in of atomic_write takes)
462
+ atomic_write(path, text, mode)
463
+ else:
464
+ atomic_write(path, text, mode, mtime_ns=mtime_ns)
465
+ return True
466
+
467
+
468
+ def atomic_write_stamped(path, text, stamps, mode=0o600, now_ns=None):
469
+ """atomic_write_if_changed whose write carries a publish stamp as the file's mtime -> True when it wrote. The
470
+ stamp is P = max(now_ns, last + 1) for `path`, set on the temp file before the rename (atomic_write's
471
+ `mtime_ns`), so a reader that keys on one stat per tick (a sidebar on statusd's projections, BEY-7606: the C7
472
+ tick budget) sees every publish without a read, however close in time, on any file system that stores
473
+ nanosecond timestamps (a coarser one truncates the stamp; the rename's new inode still tells two writes apart,
474
+ sidebar.file_stamp). `stamps` is the writer's memo, {str(path): last stamp} (statusd keeps it in
475
+ sidebar_status.PUBLISHED): a path it lacks starts from the file's own st_mtime_ns (0 when there is none), so
476
+ neither a restarted writer (an empty memo) nor a clock step back lowers the stamp (FC-I-9's clock rule, the
477
+ directory revision's). A skipped write keeps the file's mtime and the memo. The stamp is the clock's reading
478
+ whenever the clock is past the last stamp; inside one tick it runs ahead by a few ns, after a step back by the
479
+ step until the clock catches up."""
480
+ key = str(path)
481
+ last = stamps.get(key)
482
+ if last is None:
483
+ try:
484
+ last = os.stat(path).st_mtime_ns
485
+ except OSError:
486
+ last = 0
487
+ stamps[key] = last
488
+ at = max(time.time_ns() if now_ns is None else now_ns, last + 1)
489
+ if not atomic_write_if_changed(path, text, mode, mtime_ns=at):
490
+ return False
491
+ stamps[key] = at
310
492
  return True
311
493
 
312
494
 
@@ -1250,15 +1432,43 @@ def guest_probe(info, socket_name, args, timeout=5):
1250
1432
  return outcome, text if isinstance(text, str) else ''
1251
1433
 
1252
1434
 
1435
+ def probe_runner(probe, info, socket_name, timeout=5):
1436
+ """A lane_core tmux runner (argv -> subprocess.CompletedProcess) over a tmux_probe-shaped `probe(info, socket,
1437
+ args, timeout) -> (outcome, text)`, so lane_core.agent_pane and send_checked reach a container's server from the
1438
+ host (BEY-8655). lane_core's argv is `tmux -N -L <socket> ARGS…`: ARGS go to the probe. 'ok' is exit 0 with the
1439
+ text as stdout, 'timeout' exit 124, anything else exit 1 with the text as stderr; `run.outcomes` keeps each
1440
+ outcome in order (a caller tells 'noserver' from a failure by it)."""
1441
+ import subprocess
1442
+
1443
+ def run(argv):
1444
+ outcome, text = probe(info, socket_name, list(argv[4:]), timeout)
1445
+ run.outcomes.append(outcome)
1446
+ text = text if isinstance(text, str) else ''
1447
+ if outcome == 'ok':
1448
+ return subprocess.CompletedProcess(argv, 0, text, '')
1449
+ return subprocess.CompletedProcess(argv, 124 if outcome == 'timeout' else 1, '', text or f'tmux {outcome}\n')
1450
+ run.outcomes = []
1451
+ return run
1452
+
1453
+
1454
+ def container_proc(info):
1455
+ """The /proc of a container whose init runs here, as the host reaches it (/proc/<init pid>/root/proc): the pane
1456
+ pids tmux names live in its pid namespace."""
1457
+ return Path(proc_root()) / str((info or {}).get('pid') or 0) / 'root' / 'proc'
1458
+
1459
+
1253
1460
  def lane_write(lane, info, text, enter=False):
1254
- """Type `text` (and, with `enter`, an Enter as a second client lane_core.ENTER_DELAY s later) into the active pane
1255
- of a tmux lane through its container's transport -> (outcome, detail): 'typed', 'typed-no-enter', 'failed' (not
1256
- typed), 'no_transport' (not typed: no write transport, AR §7.5), 'unknown' (the guest gave no answer: whether it
1257
- was typed is not known, and it is not resent). Local — a container whose init runs here, or one with no init here
1258
- and no guest transport — through tmux_probe send-keys, as `lanes upload --paste` always typed: tmux_probe is looked
1259
- up at call time, so a runtime hook that reaches the container keeps typing, and only its `noserver` (with no init
1260
- of the container running here) is `no_transport`. Guest: the guest's `tmux_write`, which takes the lane's dispatch
1261
- lock there."""
1461
+ """Type `text` (and, with `enter`, an Enter as a second client lane_core.ENTER_DELAY s later) into the pane that
1462
+ holds the lane's agent (BEY-8655: lane_core.agent_pane; a lane without one, its active pane) of a tmux lane through
1463
+ its container's transport -> (outcome, detail): 'typed', 'typed-no-enter' (the text waits at the prompt: its Enter
1464
+ failed, or two Enters did not submit it — lane_core.send_checked), 'failed' (not typed), 'no_transport' (not
1465
+ typed: no write transport, AR §7.5), 'unknown' (the guest gave no answer: whether it was typed is not known, and
1466
+ it is not resent). Local — a container whose init runs here, or one with no init here and no guest transport —
1467
+ through tmux_probe, as `lanes upload --paste` always typed: tmux_probe is looked up at call time, so a runtime hook
1468
+ that reaches the container keeps typing, and only its `noserver` (with no init of the container running here) is
1469
+ `no_transport`. Through such a hook no process of the container is readable, so the text goes to the session's
1470
+ active pane (`=<session>:`) as before and its Enter is not checked. Guest: the guest's `tmux_write`, which takes
1471
+ the lane's dispatch lock there."""
1262
1472
  tmux = lane.get('tmux') if isinstance(lane.get('tmux'), dict) else {}
1263
1473
  if lane.get('holder') != 'tmux' or not tmux.get('socket') or not tmux.get('session'):
1264
1474
  return 'failed', 'not typed: not a tmux lane'
@@ -1267,29 +1477,45 @@ def lane_write(lane, info, text, enter=False):
1267
1477
  if route is None:
1268
1478
  return 'no_transport', f'not typed: {why}'
1269
1479
  if route == TRANSPORT_LOCAL:
1270
- target = f"={tmux['session']}:"
1271
- literal = text[:-1] + '\\;' if text.endswith(';') else text # = lane_core.tmux_text, without loading it
1272
- outcome, detail = tmux_probe(info, tmux['socket'], ['send-keys', '-t', target, '-l', '--', literal])
1273
- if outcome == 'noserver' and not os.path.exists(f"{proc_root()}/{info.get('pid')}"):
1274
- why = _untypable(container, info)
1275
- return ('no_transport' if no_write_transport(why) else 'failed'), f'not typed: {why}'
1276
- if outcome != 'ok':
1277
- return 'failed', f'not typed: tmux did not take it ({outcome}{": " + detail if detail else ""})'
1480
+ C = lane_core()
1481
+ run = probe_runner(lambda *args: tmux_probe(*args), info, tmux['socket'])
1482
+
1483
+ def untypable(): # tmux_probe's noserver with no init of the container here: AR §7.5's no_transport
1484
+ if run.outcomes[-1:] == ['noserver'] and not os.path.exists(f"{proc_root()}/{info.get('pid')}"):
1485
+ why = _untypable(container, info)
1486
+ return ('no_transport' if no_write_transport(why) else 'failed'), f'not typed: {why}'
1487
+ return None
1488
+ if info.get('pid'):
1489
+ try:
1490
+ found = C.agent_pane(tmux['socket'], tmux['session'], container_proc(info), run=run)
1491
+ except C.LaneError as error:
1492
+ return untypable() or ('failed', f'not typed: {error} ({error.code})')
1493
+ else: # a hooked tmux_probe (TRANSPORT_PROBE): no process of the container is readable from here
1494
+ found = {'pane': C.target(tmux['session']), 'harness': None}
1495
+ results, verdict = C.send_checked(tmux['socket'], found['pane'], text, enter, found['harness'], run=run,
1496
+ wait=names_pause)
1497
+ if results[0].returncode:
1498
+ detail = (results[0].stderr or '').strip()
1499
+ return untypable() or ('failed', f'not typed: tmux did not take it ({run.outcomes[-1]}'
1500
+ f'{": " + detail if detail else ""})')
1278
1501
  if not enter:
1279
1502
  return 'typed', 'typed'
1280
- names_pause(lane_core().ENTER_DELAY)
1281
- outcome, _detail = tmux_probe(info, tmux['socket'], ['send-keys', '-t', target, 'Enter'])
1282
- return ('typed', 'typed') if outcome == 'ok' else ('typed-no-enter', f'typed without its Enter (tmux {outcome})')
1503
+ if verdict is None:
1504
+ return 'typed-no-enter', f'typed without its Enter (tmux {run.outcomes[-1]})'
1505
+ if verdict == 'not_submitted':
1506
+ return 'typed-no-enter', f'typed; {C.verdict_sentence(verdict)}'
1507
+ return 'typed', f'typed: {C.verdict_sentence(verdict)}'
1283
1508
  try:
1284
1509
  answer = site_client(_guest_alias(route)).call('tmux_write', {'lane': lane.get('id'), 'text': text,
1285
1510
  'enter': bool(enter)},
1286
- site_protocol().WRITE_DEADLINE_S)
1511
+ site_protocol().TMUX_WRITE_DEADLINE_S)
1287
1512
  except SiteError as error:
1288
1513
  if error.code == 'no_answer':
1289
1514
  return 'unknown', f'not known whether it was typed: {error.human}; not resent'
1290
1515
  return 'failed', f'not typed: {route} refused it: {error.human} ({error.code})'
1291
- if enter and not answer.get('enter'):
1292
- return 'typed-no-enter', f'typed through {route} without its Enter'
1516
+ if enter and (not answer.get('enter') or answer.get('submitted') == 'not_submitted'):
1517
+ return 'typed-no-enter', f'typed through {route} without its Enter' if not answer.get('enter') else \
1518
+ f'typed through {route}; two Enters did not submit it'
1293
1519
  return 'typed', f'typed through {route}'
1294
1520
 
1295
1521
 
@@ -1364,7 +1590,8 @@ def transport_report(registry, containers, greet=True):
1364
1590
  # Host pressure from PLAIN FILES only — no subprocess: this is read exactly when spawning is what hurts.
1365
1591
 
1366
1592
  GIB = 2 ** 30
1367
- HEALTH_LINE = ('at', 'level', 'mem_some10', 'mem_full10', 'io_some10', 'cpu_some10', 'swap_pct', 'load1', 'status_at')
1593
+ HEALTH_LINE = ('at', 'level', 'mem_some10', 'mem_full10', 'io_some10', 'cpu_some10', 'swap_pct', 'load1', 'status_at',
1594
+ 'reason') # BEY-8678: the figure that set the level; last, so readers of at= and level= are unaffected
1368
1595
 
1369
1596
 
1370
1597
  def _text(path):
@@ -1433,15 +1660,25 @@ def _int_file(path):
1433
1660
  return int(text) if text.isdigit() else None
1434
1661
 
1435
1662
 
1436
- def health_level(health):
1663
+ def health_verdict(health):
1664
+ """(level, reason): the host's level and the figure that set it, in the level's own order: memory, then io, then
1665
+ load; '-' while ok (BEY-8678: design 9.0.0's health glance names that figure, so it is data, never re-derived)."""
1437
1666
  if health['mem_some10'] >= 40 or health['mem_full10'] >= 15:
1438
- return 'critical'
1667
+ return 'critical', 'memory'
1439
1668
  # Load is a last resort only (4 x cores): on a host that runs ~170 agents the load average sits near 1.5 x cores
1440
1669
  # all day (measured: 100-150 on 64 cpus with memory and io pressure at 0-2 %), and a permanent 'busy' would both
1441
1670
  # wear the banner out and keep statusd's size reconciler switched off. Pressure (PSI) is the signal.
1442
- if health['mem_some10'] >= 10 or health['io_some10'] >= 25 or health['load1'] >= 4 * health['ncpu']:
1443
- return 'busy'
1444
- return 'ok'
1671
+ if health['mem_some10'] >= 10:
1672
+ return 'busy', 'memory'
1673
+ if health['io_some10'] >= 25:
1674
+ return 'busy', 'io'
1675
+ if health['load1'] >= 4 * health['ncpu']:
1676
+ return 'busy', 'load'
1677
+ return 'ok', '-'
1678
+
1679
+
1680
+ def health_level(health):
1681
+ return health_verdict(health)[0]
1445
1682
 
1446
1683
 
1447
1684
  def compute_health(paths=None, sample=False):
@@ -1470,7 +1707,7 @@ def compute_health(paths=None, sample=False):
1470
1707
  'io_some10': _psi10(pressure['io'], 'some'), 'cpu_some10': _psi10(pressure['cpu'], 'some'),
1471
1708
  'swap_pct': int(round(100 * (swap_total - meminfo.get('SwapFree', 0)) / swap_total)) if swap_total else 0,
1472
1709
  'load1': load1, 'ncpu': int(paths.get('ncpu') or os.cpu_count() or 1), 'containers': {}}
1473
- health['level'] = health_level(health)
1710
+ health['level'], health['reason'] = health_verdict(health)
1474
1711
  raw = None
1475
1712
  if sample and health['level'] != 'critical':
1476
1713
  kib = {key: meminfo[key] * 1024 if key in meminfo else None for key in ('MemTotal', 'MemAvailable')}
@@ -1549,7 +1786,8 @@ def fleet_facts(sample, previous, health, host_name):
1549
1786
 
1550
1787
  def health_line(health, status_at):
1551
1788
  """The one line of $STATE/health (sh and python read it without JSON). Key order is part of the format."""
1552
- values = dict(health, at=int(health['at']), load1=f"{health['load1']:.2f}", status_at=int(status_at))
1789
+ values = dict(health, at=int(health['at']), load1=f"{health['load1']:.2f}", status_at=int(status_at),
1790
+ reason=health.get('reason') or '-')
1553
1791
  return ' '.join(f'{key}={values[key]}' for key in HEALTH_LINE) + '\n'
1554
1792
 
1555
1793
 
@@ -1561,7 +1799,7 @@ def read_health(state_dir=None):
1561
1799
  key, equals, value = token.partition('=')
1562
1800
  if equals:
1563
1801
  try:
1564
- health[key] = value if key == 'level' else float(value) if key == 'load1' else int(value)
1802
+ health[key] = value if key in ('level', 'reason') else float(value) if key == 'load1' else int(value)
1565
1803
  except ValueError:
1566
1804
  pass
1567
1805
  return health
@@ -1701,6 +1939,101 @@ def declared_tmux(registry_doc, name):
1701
1939
  .get('tmux'))
1702
1940
 
1703
1941
 
1942
+ def binding_consistency(doc, repo=None):
1943
+ """BEY-7435: {'rows', 'dangling', 'unbound'} of one parsed terminals.json; None when it holds no `terminals` list.
1944
+ `dangling` lists every `lanes.terminals` binding no `terminals[]` row declares — a row a concurrent rewrite
1945
+ dropped while its binding survived: build_registry makes no lane of it, so its session shows as unregistered, and
1946
+ `lanes register` puts the row back (session_actions.repair_dangling) — as {'name', 'id': the lane id it records or
1947
+ None, 'tmux': {socket, session}}. `unbound` lists the rows no binding reaches: their own or the `throttle` block's
1948
+ (declared_tmux), or, with `repo` (the board manifest's repositories[] entry), its `bindingRecoveries` and
1949
+ `bindingOverrides`; None without `repo`, which the file alone cannot tell (build_registry refuses such a board:
1950
+ `Missing explicit tmux binding`)."""
1951
+ terminals = doc.get('terminals') if isinstance(doc, dict) else None
1952
+ if not isinstance(terminals, list):
1953
+ return None
1954
+ rows = [item['name'] for item in terminals if isinstance(item, dict) and isinstance(item.get('name'), str)]
1955
+ block = doc.get('lanes') if isinstance(doc.get('lanes'), dict) else {}
1956
+ own = block.get('terminals') if isinstance(block.get('terminals'), dict) else {}
1957
+ dangling = []
1958
+ for name, entry in own.items():
1959
+ if name in rows or not isinstance(entry, dict):
1960
+ continue
1961
+ tmux = entry.get('tmux') if isinstance(entry.get('tmux'), dict) else {}
1962
+ recorded = entry.get('id')
1963
+ dangling.append({'name': name, 'id': recorded if isinstance(recorded, str) and IDENT.match(recorded) else None,
1964
+ 'tmux': {'socket': tmux.get('socketName'), 'session': tmux.get('sessionName')}})
1965
+ unbound = None
1966
+ if isinstance(repo, dict):
1967
+ held = set()
1968
+ for key in ('bindingRecoveries', 'bindingOverrides'):
1969
+ if isinstance(repo.get(key), dict):
1970
+ held.update(repo[key])
1971
+ try:
1972
+ unbound = [name for name in rows if name not in held and not declared_tmux(doc, name)]
1973
+ except (AttributeError, TypeError): # a `lanes` or `throttle` block that is no object: build_registry's error
1974
+ unbound = None
1975
+ return {'rows': rows, 'dangling': dangling, 'unbound': unbound}
1976
+
1977
+
1978
+ def _registry_document(path, cache=None):
1979
+ """One terminals.json parsed; with `cache` ({path: (stat key, document)}) re-read only when its inode, size or
1980
+ mtime changed (statusd asks every cycle)."""
1981
+ if cache is None:
1982
+ return json.loads(Path(path).read_text())
1983
+ info = os.stat(path)
1984
+ key = (info.st_ino, info.st_size, info.st_mtime_ns)
1985
+ hit = cache.get(str(path))
1986
+ if hit is not None and hit[0] == key:
1987
+ return hit[1]
1988
+ document = json.loads(Path(path).read_text())
1989
+ cache[str(path)] = (key, document)
1990
+ return document
1991
+
1992
+
1993
+ def registry_bindings(registry, containers=None, manifests=True, cache=None):
1994
+ """BEY-7435: one record per terminals.json the registry's boards read (a lane's `source`, reached through its
1995
+ container's home volume), the first board that reads it naming it: {'board', 'container', 'source', 'path', 'home',
1996
+ 'repo', 'rows', 'dangling', 'unbound'} — binding_consistency's lists, each dangling binding with its `derived` id
1997
+ (the one `lanes sync` gives its declared name: lane_id_for, the board manifest's prefix; None when unknown) and
1998
+ its `lane_id`: the id it records, else the derived one. `manifests` False reads no manifest (statusd, every
1999
+ cycle): then `unbound` and `derived` are None and a binding that records no id has no `lane_id`. A file that
2000
+ cannot be read or holds no `terminals` list is skipped (doctor's `registry clean` names that board's error).
2001
+ `cache`: _registry_document's."""
2002
+ containers = (read_json(STATE / 'containers.json', {}) or {}) if containers is None else containers
2003
+ out, seen = [], set()
2004
+ for board in (registry or {}).get('workspaces') or []:
2005
+ repos = None
2006
+ for lane in board.get('lanes') or []:
2007
+ source, container = lane.get('source'), lane.get('container')
2008
+ if not source or not container or (container, source) in seen:
2009
+ continue
2010
+ seen.add((container, source))
2011
+ info = containers.get(container) or ((registry.get('containers') or {}).get(container)) or {}
2012
+ try:
2013
+ path = host_path(info, source)
2014
+ document = _registry_document(path, cache)
2015
+ except (LanesError, OSError, ValueError):
2016
+ continue
2017
+ if manifests and repos is None:
2018
+ try:
2019
+ listed = read_site_json(manifest_path(board['id'])).get('repositories') or []
2020
+ repos = {item.get('id'): item for item in listed if isinstance(item, dict)}
2021
+ except (LanesError, OSError, ValueError, KeyError, TypeError, AttributeError):
2022
+ repos = {}
2023
+ repo = (repos or {}).get(lane.get('repo')) if manifests else None
2024
+ facts = binding_consistency(document, repo)
2025
+ if facts is None:
2026
+ continue
2027
+ for item in facts['dangling']:
2028
+ derived = (lane_id_for(board['id'], {'name': (repo.get('prefix') or '') + item['name']})
2029
+ if isinstance(repo, dict) else None)
2030
+ item['derived'] = derived # what sync gives the name: a repair checks the recorded id against it
2031
+ item['lane_id'] = item['id'] or derived
2032
+ out.append(dict(facts, board=board['id'], container=container, source=source, path=path,
2033
+ home=info.get('home'), repo=lane.get('repo')))
2034
+ return out
2035
+
2036
+
1704
2037
  def _workspace_lanes(manifest, containers):
1705
2038
  """Port of coder-launch/manage.mjs: explicit tmux bindings only; nothing is ever executed."""
1706
2039
  lanes = []
@@ -2139,7 +2472,7 @@ def _claude_in_lane(info, socket, session, sessions, proc):
2139
2472
  that server (only that session's rows), `records` = `agent_state.claude_files` bound by it — each file's process
2140
2473
  descends from the root process of the pane its `tmux` string names on THIS server. A file of another server whose
2141
2474
  local key is the same is not among them. tmux not answering is a failure: nothing can be typed."""
2142
- import agent_state as AS # libexec; agent_state imports nothing of lanes_lib
2475
+ import agent_state as AS # libexec; the shared liveness helper loads lane_core lazily
2143
2476
  outcome, text = tmux_probe(info, socket, ['list-panes', '-a', '-F', PANE_FORMAT])
2144
2477
  if outcome != 'ok':
2145
2478
  return None, ('failed', f'tmux did not answer ({outcome}{": " + text if text else ""}): not typed')
@@ -2166,7 +2499,7 @@ def rename_claude(lane, address, info):
2166
2499
  process is the same — and only then types the text into that pane by its tmux pane id, and the Enter as a second
2167
2500
  client `lane_core.ENTER_DELAY` seconds later (DEF-1803) if the process is still the same. Never reads anything but
2168
2501
  the `<pid>.json` session files: the messaging key files beside them are not opened (DEF-1802)."""
2169
- import agent_state as AS # libexec; agent_state imports nothing of lanes_lib
2502
+ import agent_state as AS # libexec; the shared liveness helper loads lane_core lazily
2170
2503
  refusal = names_refusal(lane, info) # H1: no write transport, a guest, a tmux_probe-only route: never an exit 0
2171
2504
  if refusal:
2172
2505
  return 'failed', refusal
@@ -2631,3 +2964,8 @@ def find_lane(registry, lane_id):
2631
2964
  if lane['id'] == lane_id:
2632
2965
  return workspace, lane
2633
2966
  raise LanesError(f'Unknown lane: {lane_id}')
2967
+
2968
+
2969
+ # lanes site-hook loader (FLE-388)
2970
+ import site_hooks
2971
+ site_hooks.apply('library', globals())
@@ -18,7 +18,12 @@ cell); rules --- *** ___. Not in the subset: setext headings, indented code, HTM
18
18
  typed), hard line breaks, footnotes, task lists, blocks inside list items.
19
19
 
20
20
  Inline: `code`, **strong**, *em* / _em_ (CommonMark delimiter runs, without the rule of three), backslash escapes of
21
- ASCII punctuation, [text](url "title"), <scheme:...> and <user@host> autolinks, ![alt](src "title"). A link's href must
21
+ ASCII punctuation, [text](url "title"), <scheme:...> and <user@host> autolinks, ![alt](src "title"), and a bare http://
22
+ or https:// address in text (BEY-8667 E1b-2): not after a letter or digit, never in a link's text, the link is its run
23
+ to the next space, <, > or backtick, less a trailing ? ! . , : ; * _ ~ ' " and any ) or ] the run does not open; it
24
+ needs a host after the scheme (a letter or digit, in any script, or the [ of an IPv6 address), one the href rules below
25
+ refuse stays text, and each such run is matched once: no address is tried again inside it, which keeps the scan linear
26
+ (matching again from each later character would be quadratic). A link's href must
22
27
  start with http:// https:// mailto: /lanes-docs/ or # and hold no space, control or DEL character (a space inside
23
28
  <...> becomes %20), no backslash, and — checked after the backslash escapes are resolved — no `.` or `..` segment in
24
29
  its path, `%2e` spellings in any case included, and on this site no `%2f`/`%5c` in it (a browser resolves dot
@@ -264,7 +269,7 @@ def _render_list(ordered, start, items, top):
264
269
  # ---------------------------------------------------------------------------------------------------------------------
265
270
  # Inline
266
271
 
267
- _SPECIAL = re.compile(r'[\\`*_!\[<]')
272
+ _SPECIAL = re.compile(r'[\\`*_!\[<]|(?i:https?://)')
268
273
  _RUN = re.compile(r'`+')
269
274
  _DELIMS = re.compile(r'\*+|_+')
270
275
  _BRACKET_TOKEN = re.compile(r'\\[\s\S]|`+|[\[\]]')
@@ -285,6 +290,10 @@ _DOT_SEGMENT = re.compile(r'(?:\.|%2e){1,2}', re.I) # fullmatch: `.
285
290
  _PATH_END = re.compile(r'[?#]')
286
291
  _ENCODED_SLASH = re.compile(r'%(?:2f|5c)', re.I)
287
292
  _EXTERNAL = ' rel="noopener noreferrer" target="_blank"'
293
+ _BARE = re.compile(r'(?i:https?://)[^\s<>`]+') # a bare address: its run to a space, <, > or `
294
+ _BARE_HOST = re.compile(r'(?i:https?://)(?:[^\W_]|\[[0-9A-Fa-f:])') # ... with a host: a letter or digit, or IPv6's [
295
+ _TRAILING = frozenset('?!.,:;*_~\'"') # punctuation that ends a run is not part of it
296
+ _CLOSER = {')': '(', ']': '['} # ... nor a closer the run does not open
288
297
 
289
298
 
290
299
  def _runs(s):
@@ -477,13 +486,42 @@ def _autolink(s, at):
477
486
  return None
478
487
 
479
488
 
489
+ def _bare(s, at):
490
+ """(the link or None, the end of its run) for a bare http(s) address at `at`: the run up to a space, `<`, `>` or a
491
+ backtick, less trailing ? ! . , : ; * _ ~ ' " and any `)` or `]` the run does not open. None (the run stays text,
492
+ as before) when no host follows the scheme (a letter or digit, or `[`), _BAD_URL finds a backslash or control
493
+ character, or _href_ok refuses it (a dot segment). The caller tries no bare address again before the run's end, so
494
+ each run is matched once: matching it again from each later `https://` inside it would be quadratic."""
495
+ m = _BARE.match(s, at)
496
+ if m is None:
497
+ return None, at
498
+ end, unmatched = m.end(), {}
499
+ while end > at:
500
+ c = s[end - 1]
501
+ if c in _TRAILING:
502
+ end -= 1
503
+ continue
504
+ if c in _CLOSER:
505
+ if c not in unmatched: # counted once per kind: the trim stays linear
506
+ unmatched[c] = s.count(c, at, end) - s.count(_CLOSER[c], at, end)
507
+ if unmatched[c] > 0:
508
+ unmatched[c] -= 1
509
+ end -= 1
510
+ continue
511
+ break
512
+ url = s[at:end]
513
+ if _BAD_URL.search(url) or not _BARE_HOST.match(url) or not _href_ok(url):
514
+ return None, m.end()
515
+ return (f'<a href="{_esc(url)}"{_EXTERNAL}>{_esc(url)}</a>', end), m.end()
516
+
517
+
480
518
  def _inline(s, in_link=False):
481
519
  """One block's inline text as HTML: text escaped once, the constructs above as tags."""
482
520
  if _SPECIAL.search(s) is None:
483
521
  return _esc(s)
484
522
  runs = _runs(s) if '`' in s else {}
485
523
  brackets = _brackets(s, runs) if '[' in s else {}
486
- nodes, text, i, n, delims = [], [], 0, len(s), False
524
+ nodes, text, i, n, delims, bare_from = [], [], 0, len(s), False, 0
487
525
  search, append = _SPECIAL.search, text.append
488
526
  while i < n:
489
527
  m = search(s, i)
@@ -532,6 +570,8 @@ def _inline(s, in_link=False):
532
570
  done = _link(s, j, brackets[j])
533
571
  elif c == '<' and not in_link:
534
572
  done = _autolink(s, j)
573
+ elif c in 'hH' and not in_link and j >= bare_from and (j == 0 or not s[j - 1].isalnum()):
574
+ done, bare_from = _bare(s, j)
535
575
  if done is None:
536
576
  append(c)
537
577
  i = j + 1