@vibelord/lanes 1.6.1 → 1.7.1

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.
@@ -1,5 +1,7 @@
1
1
  #!/usr/bin/env python3
2
- """lanes status daemon: observes lanes, never touches them.
2
+ """lanes status daemon: observes lanes, and touches them in two bounded ways only — the name parity retry
3
+ (`names_auto`, below; LANES_NAMES_AUTO=0 turns it off) and the typed delivery of messages waiting in a lane's inbox
4
+ (`deliver_inbox`, W15 L4).
3
5
 
4
6
  Every few seconds: find LIVE tmux servers in each workspace container's own cgroup (`guard`, plain /proc reads;
5
7
  dead sockets are never probed), run one read-only `list-panes -a` per live server that the registry references —
@@ -23,6 +25,30 @@ pressure, inotify ceiling and the biggest workspace containers, from `lanes_lib.
23
25
  previous sample kept in the context — and on every cycle `throttle`, the Throttle pulse's `~/.lz/state/throttle.json`
24
26
  in the daemon's container (one stat, read only when it moved). The one spawn either adds is `rearm_pulse`, between two
25
27
  cycles: one bounded `docker exec -d` at most every PULSE_REARM_EVERY seconds while the pulse file has gone quiet.
28
+
29
+ Addresses and name parity (W15 L2, L2c): every lane row carries `address` and `role` from the registry, and a Claude
30
+ lane's agent{} `messaging` ({socket_present, name}: whether the messaging socket its session file names exists, never
31
+ opened, and its session name) and `name_match` (that name == the address). Between two cycles, never inside one, and
32
+ only while site.conf leaves LANES_NAMES_AUTO on and the host is `ok`, `names_auto` types `/rename <address>` into at
33
+ most NAMES_PER_PASS mismatched Claude lanes at their prompt with no terminal attached, each at most once per
34
+ NAMES_RETRY_S — one of the two things this daemon ever types into a lane (`lanes_lib.rename_claude` re-checks the session
35
+ file first), logged as lane id, address and outcome only.
36
+
37
+ Messages (W15 L4): a lane row carries `inbox: {pending}` while messages wait in the container's
38
+ `~/.lz/state/inbox/<lane>/` (`inbox_scan`: one bounded scandir per container per cycle, a lane's files read only when
39
+ its directory changed). Between two cycles, never inside one and only on an `ok` host, `deliver_inbox` types at most
40
+ INBOX_PER_PASS waiting messages into lanes observed idle with no terminal attached (`ready_for_text`; a Claude lane
41
+ only while its own session file says `idle`; a shell only at its prompt, as a comment line), writes each receipt
42
+ `typed`, and empties the text of messages whose ttl passed — the journal names lane, message id and outcome only.
43
+
44
+ Claude peers (W15 L6, BEY-6843): each workspace container with the lane contract runs one `lane-peerd` loop, which
45
+ registers that container's non-Claude lanes as virtual Claude peers. Between two cycles, never inside one and never on
46
+ a `critical` host, `rearm_peerd` looks (at most every PEERD_CHECK_S per container: three stats through
47
+ /proc/<init>/root) at its `~/.lz/state/peers/peers.json`, and where that file is older than PEERD_REARM_S or absent
48
+ while `~/.lz/bin/lane-peerd` is installed starts the loop with ONE bounded `docker exec -d … tmux -L lanes-peers new
49
+ -d -s peerd ~/.lz/bin/lane-peerd --loop` — at most once per PEERD_REARM_EVERY per container and PEERD_PER_PASS per
50
+ pass; site.conf LANES_PEERS=0 turns the start off. The `~/.claude/sessions` entries lane-peerd writes are never read as
51
+ Claude sessions (`agent_state.claude_sessions` skips them by their socket's directory).
26
52
  """
27
53
  import concurrent.futures
28
54
  import json
@@ -57,18 +83,10 @@ CONTAINER_RETRY = 30 # ... and at most this often while a container is down
57
83
  HOT_SYNC_EVERY_S = 10 # hot_sync starts at most one `lanes sync` per this many seconds (the sidebar's PENDING_S)
58
84
  ACTIVE_WINDOW = 20 # seconds since last output for a lane to count as active
59
85
  STALE_MAX = 300 # a lane nobody could observe for this long is published as 'unknown', no longer as last seen
60
- FIELDS = ['session_name', 'pane_pid', 'pane_dead', 'window_activity', 'pane_current_command',
61
- 'pane_current_path', 'window_width', 'window_height', 'session_attached', 'pane_tty',
62
- 'session_id', 'session_created',
63
- # Alignment contract A4a: the group a session is attached onto (a Throttle Studio browser view is a
64
- # grouped session), and which pane of which window represents the session's state.
65
- 'session_group', 'pane_active', 'window_active',
66
- # Task 5 (`agent{}`): the window bell, the ids a Claude session file names its pane by
67
- # (`<session>:@<win>.%<pane>`), and the pane title Codex writes its status into. APPENDED, so every
68
- # column above keeps its index; the title is the one free-text column and comes LAST, so a tab inside it
69
- # stays in the title (the row is split at most len(FIELDS) - 1 times) instead of shifting the ids.
70
- 'window_bell_flag', 'window_id', 'pane_id', 'pane_title']
71
- FORMAT = '\t'.join('#{' + f + '}' for f in FIELDS)
86
+ # The one `list-panes -a` row of Lanes (`lanes_lib.PANE_FIELDS`, where its columns are explained):
87
+ # `lanes_lib.rename_claude` reads the same row to bind a Claude session to its pane on its tmux server (BEY-6838).
88
+ FIELDS = L.PANE_FIELDS
89
+ FORMAT = L.PANE_FORMAT
72
90
  VIEW_PREFIX = 'view-' # a Throttle Studio browser attach: a grouped session named view-<studio>-<ch>
73
91
  # The docs cockpit (plan W10 W7, LNS-108). A lane row carries `docs: {n, at}` while docs/counts.json
74
92
  # (DM-LANES-DOCS-COUNTS) holds documents for it: ONE stat of that file per cycle, the file read only when it moved.
@@ -343,13 +361,111 @@ GROK_TITLES = {}
343
361
  # Grok title over a tree with no grok left is that harness ended, `grok` / `shell`); and `unknown` WITH a harness pid —
344
362
  # the walk's `grok` whose /proc/<pid>/exe could not be read, Grok Build only when active_sessions.json names its pid.
345
363
  GROK_OBSERVED = ('grok', 'shell')
364
+ # W15 L1: what each Claude session's background-work scan found, kept between cycles (`agent_state.DelegationCache`):
365
+ # a delegating lane costs one stat of its evidence per cycle, an idle one with nothing running one bounded scan per
366
+ # 30-59 s (DELEGATING_RECHECK plus a per-session offset). `agent_signals` starts each cycle with `cycle()`, which
367
+ # forgets the sessions the last one skipped.
368
+ DELEGATION_CACHE = AS.DelegationCache()
369
+
370
+
371
+ # W15 L2: a Claude session's messaging socket, as its session file names it (`messagingSocketPath`, MEASURED on Claude
372
+ # Code 2.1.310: `~/.cache/build-tmp/cc-socks/<pid>.sock`, beside a `<pid>.<hash>.key` file this daemon never opens).
373
+ # The path is read from `<pid>.json` once per session status (keyed by root, pid and `since`), the socket only lstat'ed.
374
+ MESSAGING_FILE_MAX = 64 << 10 # a session file bigger than this is not Claude's: not read
375
+ MESSAGING_PATH_MAX = 4096
376
+ SESSIONS_DIR = tuple(L.CONTAINER_HOME.strip('/').split('/')) + L.CLAUDE_SESSIONS
377
+
378
+
379
+ class MessagingCache:
380
+ """{(container root, pid, since): socket path or None} between cycles. `start_cycle()` starts one and forgets the
381
+ sessions the previous one did not ask about, so a session that ended costs nothing after one cycle."""
382
+
383
+ def __init__(self):
384
+ self.paths, self.seen = {}, set()
385
+
386
+ def start_cycle(self):
387
+ self.paths = {key: value for key, value in self.paths.items() if key in self.seen}
388
+ self.seen = set()
389
+
390
+ def path(self, root, pid, since):
391
+ key = (str(root), pid, since)
392
+ self.seen.add(key)
393
+ if key not in self.paths:
394
+ self.paths[key] = messaging_path(root, pid)
395
+ return self.paths[key]
396
+
397
+
398
+ MESSAGING_CACHE = MessagingCache()
399
+
400
+
401
+ def messaging_path(root, pid):
402
+ """The `messagingSocketPath` of the container's `~/.claude/sessions/<pid>.json`, or None: absent, not an absolute
403
+ path, holding a control character, too long. Walked with `lanes_lib.open_real_dir` (no component a link) and read
404
+ with `read_regular_at` (a regular file of at most MESSAGING_FILE_MAX bytes; never a FIFO, never a link)."""
405
+ try:
406
+ fd = L.open_real_dir(root, SESSIONS_DIR)
407
+ except (OSError, L.LanesError):
408
+ return None
409
+ try:
410
+ data = L.read_regular_at(fd, f'{int(pid)}.json', MESSAGING_FILE_MAX)
411
+ finally:
412
+ os.close(fd)
413
+ try:
414
+ document = json.loads(data) if data is not None else None
415
+ except ValueError:
416
+ return None
417
+ path = document.get('messagingSocketPath') if isinstance(document, dict) else None
418
+ if (not isinstance(path, str) or not path.startswith('/') or len(path) > MESSAGING_PATH_MAX
419
+ or L.CONTROL_CHARS.search(path)):
420
+ return None
421
+ return path
422
+
423
+
424
+ def messaging_check(container, root, claude):
425
+ """The container's `messaging(pane key)` -> {'socket_present': bool, 'name': the session name or None} for a pane a
426
+ live Claude session file claims (`claude`, `agent_state.claude_sessions`'), else None. `socket_present`: the socket
427
+ its file names is a socket now — lstat'ed after resolving every link inside the container (`container_realpath`),
428
+ never connected to and never written. An error costs only that pane its facts (logged)."""
429
+ def check(key):
430
+ entry = claude.get(key)
431
+ if not isinstance(entry, dict):
432
+ return None
433
+ try:
434
+ path = MESSAGING_CACHE.path(root, entry.get('pid'), entry.get('since'))
435
+ found = L.container_lstat(root, L.container_realpath(root, path)) if path else None
436
+ except Exception as error:
437
+ log(f'messaging {container}', error)
438
+ found = None
439
+ return {'socket_present': bool(found) and stat.S_ISSOCK(found.st_mode), 'name': entry.get('name') or None}
440
+ return check
441
+
442
+
443
+ def messaging_of(signals, container, socket, pane):
444
+ """`messaging_check`'s answer for one observed pane of tmux server `socket`, or None (no Claude session file claims
445
+ it). Never raises: it runs inside `observe`'s per-lane guard, and messaging facts must never cost a lane its row."""
446
+ try:
447
+ check = (signals.get(container) or {}).get('messaging')
448
+ return check(AS.bound_key(socket, AS.pane_key(pane))) if check else None
449
+ except Exception as error:
450
+ log(f'messaging {container}', error)
451
+ return None
346
452
 
347
453
 
348
454
  def agent_signals(containers, sessions_by_server, now=None):
349
455
  """The per-container inputs `agent_state.merge` needs, read ONCE per container per cycle through the
350
456
  container's root as the host sees it (`/proc/<init pid>/root`), so liveness is judged in the container's pid
351
457
  namespace and nothing is spawned. -> {container: {'claude': claude_by_pane, 'kimi': kimi_by_pane,
352
- 'grok': grok_by_pane, 'muse': muse_by_pane}}.
458
+ 'grok': grok_by_pane, 'muse': muse_by_pane, 'delegating': the container's `agent_state.delegation_check`}}.
459
+
460
+ BEY-6838: every per-pane index here is keyed `agent_state.bound_key(socket, pane key)` — one container runs many
461
+ tmux servers, and two of them may hold the same `<session>:@<win>.%<pane>` (MEASURED 2026-10-26: seven servers of
462
+ one workspace each with a `coordinator:@0.%0` running its own Claude). The Claude session files are bound to the
463
+ server whose pane of the name they give is an ancestor of their process (`claude_sessions(..., panes=)`), and
464
+ `merged`/`messaging_of` look a pane up by its socket and key.
465
+
466
+ W15 L1: `delegating` is a callable, not a read: `merge` asks it only for a Claude lane whose verdict is idle-like,
467
+ and it scans that session's work files through DELEGATION_CACHE — at most once per cycle per such lane, bounded by
468
+ `agent_state.DELEGATING_STATS`, never for a working, approving or non-Claude lane.
353
469
 
354
470
  Sets `harness` (and `harness_pid` when one was found) on every session row whose harness could be observed, in
355
471
  place (W12, spec §2: `agent_state.HarnessCache` over `harness_walk` — the pane's process tree in the container's
@@ -370,21 +486,30 @@ def agent_signals(containers, sessions_by_server, now=None):
370
486
  walked = set()
371
487
  titled = set()
372
488
  home = tuple(part for part in L.CONTAINER_HOME.split('/') if part)
489
+ DELEGATION_CACHE.cycle()
490
+ MESSAGING_CACHE.start_cycle()
373
491
  for container in sorted({container for container, _socket in sessions_by_server}):
374
492
  info = containers.get(container) or {}
375
493
  if not info.get('pid'):
376
494
  continue
377
495
  root = Path(L.proc_root()) / str(info['pid']) / 'root'
496
+ panes = [(socket, pane) for (owner, socket), sessions in sessions_by_server.items() if owner == container
497
+ for pane in sessions.values() if str(pane.get('pane_pid') or '').isdigit()]
498
+ index = {}
499
+ for socket, pane in panes:
500
+ index.setdefault(socket, {})[AS.pane_key(pane)] = int(pane['pane_pid'])
501
+ work = {}
378
502
  try:
379
- claude = AS.claude_sessions(root / L.CONTAINER_HOME.lstrip('/') / '.claude' / 'sessions', root / 'proc')
503
+ claude = AS.claude_sessions(root / L.CONTAINER_HOME.lstrip('/') / '.claude' / 'sessions', root / 'proc',
504
+ work=work, panes=index)
380
505
  except Exception as error:
381
506
  log(f'agents {container}', error)
382
- claude = {}
383
- signals[container] = mine = {'claude': claude, 'kimi': {}, 'grok': {}, 'muse': {}}
384
- panes = [pane for (owner, _socket), sessions in sessions_by_server.items() if owner == container
385
- for pane in sessions.values() if str(pane.get('pane_pid') or '').isdigit()]
507
+ claude, work = {}, {}
508
+ signals[container] = mine = {'claude': claude, 'kimi': {}, 'grok': {}, 'muse': {},
509
+ 'delegating': delegating_check(container, root, claude, work, now),
510
+ 'messaging': messaging_check(container, root, claude)}
386
511
  observers = {'kimi': {}, 'grok': {}, 'muse': {}}
387
- for pane in panes:
512
+ for socket, pane in panes:
388
513
  try:
389
514
  harness, harness_pid = HARNESS_CACHE.harness(root / 'proc', int(pane['pane_pid']))
390
515
  except Exception as error:
@@ -396,12 +521,13 @@ def agent_signals(containers, sessions_by_server, now=None):
396
521
  pane['harness'] = harness
397
522
  if harness_pid:
398
523
  pane['harness_pid'] = harness_pid
524
+ key = AS.bound_key(socket, AS.pane_key(pane))
399
525
  if harness == 'kimi' and harness_pid:
400
- observers['kimi'][AS.pane_key(pane)] = harness_pid
526
+ observers['kimi'][key] = harness_pid
401
527
  elif harness == 'muse' and harness_pid:
402
- observers['muse'][AS.pane_key(pane)] = harness_pid
528
+ observers['muse'][key] = harness_pid
403
529
  elif harness in GROK_OBSERVED or (harness == 'unknown' and harness_pid):
404
- observers['grok'][AS.pane_key(pane)] = pane
530
+ observers['grok'][key] = pane
405
531
  if observers['kimi']:
406
532
  try:
407
533
  mine['kimi'] = AS.kimi_sessions(root, observers['kimi'], now, home)
@@ -422,9 +548,10 @@ def agent_signals(containers, sessions_by_server, now=None):
422
548
  log(f'grok {container}', error)
423
549
  for gone in set(titles) - set(observers['grok']):
424
550
  del titles[gone]
425
- probe = [pane for pane in panes
551
+ probe = [pane for socket, pane in panes
426
552
  if AS.parse_codex_title(pane.get('pane_title'), pane.get('harness')) and AS._shell_foreground(pane)
427
- and pane.get('harness') not in AS.AGENT_HARNESSES and AS.pane_key(pane) not in claude]
553
+ and pane.get('harness') not in AS.AGENT_HARNESSES
554
+ and AS.bound_key(socket, AS.pane_key(pane)) not in claude]
428
555
  if not probe:
429
556
  continue
430
557
  try:
@@ -442,10 +569,26 @@ def agent_signals(containers, sessions_by_server, now=None):
442
569
  return signals
443
570
 
444
571
 
445
- def merged(pane, signals, sidecar):
446
- """`agent_state.merge` of one pane over its container's `agent_signals` and its lane's hook sidecar."""
572
+ def delegating_check(container, root, claude, work, now):
573
+ """The container's `agent_state.delegation_check` over DELEGATION_CACHE; an error inside a scan is logged and costs
574
+ only that lane its `delegating` (it then shows Claude's own word)."""
575
+ check = AS.delegation_check(root, claude, work, now, L.CONTAINER_HOME, cache=DELEGATION_CACHE)
576
+
577
+ def guarded(key):
578
+ try:
579
+ return check(key)
580
+ except Exception as error:
581
+ log(f'delegating {container}', error)
582
+ return False
583
+ return guarded
584
+
585
+
586
+ def merged(pane, signals, sidecar, socket):
587
+ """`agent_state.merge` of one pane of tmux server `socket` over its container's `agent_signals` and its lane's hook
588
+ sidecar, looked up by `agent_state.bound_key(socket, pane key)` (BEY-6838)."""
447
589
  return AS.merge(pane, signals.get('claude', {}), sidecar, signals.get('kimi', {}), signals.get('grok', {}),
448
- signals.get('muse', {}))
590
+ signals.get('muse', {}), delegating=signals.get('delegating'),
591
+ key=AS.bound_key(socket, AS.pane_key(pane)))
449
592
 
450
593
 
451
594
  SIDECAR_MAX_AGE = 3600 # a hook sidecar whose last event is older than this loses to the live signals
@@ -599,8 +742,11 @@ def probe_all(containers, keys, live, first=()):
599
742
 
600
743
  def observe(registry, containers, live, previous=None, report=None):
601
744
  """previous = the last published payload: what a lane keeps when its server gave no answer this time.
602
- report, when given, receives {'cut': n}: how many probes were still running at the cycle deadline."""
745
+ report, when given, receives {'cut': n}: how many probes were still running at the cycle deadline — and, when it
746
+ holds a `messaging` dict (W15 L2), {lane id: `messaging_check`'s answer or None} for every live session observed
747
+ this cycle, which `with_addresses` turns into agent{}'s `messaging` and `name_match`."""
603
748
  previous = previous or {}
749
+ messaging = report.get('messaging') if isinstance(report, dict) else None
604
750
  now = time.time()
605
751
  lanes, servers, unregistered = {}, {}, {}
606
752
  wanted, owners, counts = {}, {}, {}
@@ -732,7 +878,9 @@ def observe(registry, containers, live, previous=None, report=None):
732
878
  found = lane_entry(pane, now, activities.get(name), viewers.get(name, []),
733
879
  settled(previous, entry['id'], now,
734
880
  merged(pane, signals.get(container, {}),
735
- sidecars.get(container, {}).get(entry['id']))))
881
+ sidecars.get(container, {}).get(entry['id']), socket)))
882
+ if messaging is not None:
883
+ messaging[entry['id']] = messaging_of(signals, container, socket, pane)
736
884
  except Exception as error:
737
885
  log(f'observe {container}/{socket}/{name}', error)
738
886
  continue
@@ -753,7 +901,10 @@ def observe(registry, containers, live, previous=None, report=None):
753
901
  lanes[lane['id']] = lane_entry(pane, now, activities.get(session), viewers.get(session, []),
754
902
  settled(previous, lane['id'], now,
755
903
  merged(pane, signals.get(container, {}),
756
- sidecars.get(container, {}).get(lane['id']))))
904
+ sidecars.get(container, {}).get(lane['id']),
905
+ socket)))
906
+ if messaging is not None:
907
+ messaging[lane['id']] = messaging_of(signals, container, socket, pane)
757
908
  except Exception as error: # a torn row: the session is there, its details are not readable
758
909
  log(f"observe {lane['id']}", error)
759
910
  lanes[lane['id']] = keep(previous, lane['id'], 'error')
@@ -1041,6 +1192,39 @@ def refresh_origin(ctx, level, now=None):
1041
1192
  return True
1042
1193
 
1043
1194
 
1195
+ def address_facts(ctx, registry):
1196
+ """`lanes_lib.lane_addresses(registry)`, computed once per registry load (`ctx['stamp']`), not every cycle."""
1197
+ if ctx.get('address_stamp') != ctx.get('stamp') or 'address_facts' not in ctx:
1198
+ ctx['address_facts'] = L.lane_addresses(registry)
1199
+ ctx['address_stamp'] = ctx.get('stamp')
1200
+ return ctx['address_facts']
1201
+
1202
+
1203
+ def with_addresses(lanes, facts, messaging=None):
1204
+ """`lanes` with W15 L2's keys on every row: `address` and `role` from the registry (`facts`, {lane id: (address,
1205
+ role)}; a row the registry does not list — an unregistered session, a zmx lane — has its derived address and no
1206
+ role), and on a row observed this cycle (its id in `messaging`) whose agent{} is an agent_state verdict: `messaging`
1207
+ ({socket_present, name} for a Claude session file claiming its pane, else None) and `name_match` (a Claude lane:
1208
+ its session name == its address; None for every other agent and for a Claude lane with no session file). A row
1209
+ kept from an earlier cycle keeps the agent{} it was published with. Every row is a NEW dict (DEF-1538: a kept row
1210
+ may be the very object the published payload holds)."""
1211
+ out = {}
1212
+ for lane_id, row in lanes.items():
1213
+ if not isinstance(row, dict):
1214
+ out[lane_id] = row
1215
+ continue
1216
+ address, role = facts.get(lane_id) or (L.address_of(lane_id), None)
1217
+ new = dict(row, address=address, role=role)
1218
+ agent = row.get('agent')
1219
+ if messaging is not None and lane_id in messaging and isinstance(agent, dict) and agent.get('status') in AS.STATUSES:
1220
+ found = messaging[lane_id] if agent.get('harness') == 'claude' else None
1221
+ found = dict(found) if isinstance(found, dict) else None
1222
+ name = (found or {}).get('name')
1223
+ new['agent'] = dict(agent, messaging=found, name_match=(name == address) if name else None)
1224
+ out[lane_id] = new
1225
+ return out
1226
+
1227
+
1044
1228
  def build_payload(ctx, level, reconcile=True):
1045
1229
  """One observation pass -> the payload of status.json (None = there is no registry to observe). Every phase
1046
1230
  fails alone: what it could not observe is republished as last seen (stale), the other phases still run.
@@ -1073,6 +1257,7 @@ def build_payload(ctx, level, reconcile=True):
1073
1257
  for name in sorted(set(unwalkable) - set(ctx.get('unwalkable') or ())):
1074
1258
  log(f'live servers {name}', L.LanesError(f'{unwalkable[name]} — its sockets are probed as unknown, none concluded gone'))
1075
1259
  ctx['unwalkable'] = sorted(unwalkable)
1260
+ messaging = report['messaging'] = {}
1076
1261
  try:
1077
1262
  lanes, servers, unregistered = observe(registry, containers, live, previous, report)
1078
1263
  except Exception as error:
@@ -1108,6 +1293,15 @@ def build_payload(ctx, level, reconcile=True):
1108
1293
  lanes = with_docs(lanes, docs_counts(ctx))
1109
1294
  except Exception as error:
1110
1295
  log('docs', error)
1296
+ try: # W15 L4: `inbox: {pending}` on the rows whose lanes have messages waiting (cached reads of each container)
1297
+ ctx['inbox_waiting'] = inbox_scan(ctx)
1298
+ lanes = with_inbox(lanes, ctx['inbox_waiting'])
1299
+ except Exception as error:
1300
+ log('inbox', error)
1301
+ try: # W15 L2: address and role on every row, messaging and name_match on an observed agent{}
1302
+ lanes = with_addresses(lanes, address_facts(ctx, registry), messaging)
1303
+ except Exception as error:
1304
+ log('addresses', error)
1111
1305
  payload = {'lanes': lanes, 'servers': servers, 'unregistered': unregistered, 'zmx': zmx_groups,
1112
1306
  'containers': {k: {'running': v.get('running', False)} for k, v in containers.items()}}
1113
1307
  if ctx.get('web_origin'): # additive, absent while no origin is known (refresh_origin, main())
@@ -1136,9 +1330,13 @@ def new_context():
1136
1330
  # ------------------------------------------- the in-container projection (LNS-32)
1137
1331
  # `~/.lz/status.json` in each workspace container: that container's slice of the payload, for the in-container Agent
1138
1332
  # API (`lane-mcp`, plan Track M), which cannot read the host's status.json. v1 = {v, at, lanes{<id>: {state, agent?,
1139
- # attached?, viewers?, activity?, size?, stale?, docs?}}, unregistered[{id, name, workspace, boards, tmux, identity}]}.
1140
- # `docs` (plan W10 W7, additive) is the host row's {n, at} verbatim, absent like there.
1141
- CONTAINER_STATUS_FIELDS = ('state', 'agent', 'attached', 'viewers', 'activity', 'size', 'stale', 'docs')
1333
+ # attached?, viewers?, activity?, size?, stale?, docs?, address?, role?, inbox?}}, unregistered[{id, name, workspace, boards,
1334
+ # tmux, identity}]}.
1335
+ # `docs` (plan W10 W7, additive) is the host row's {n, at} verbatim, absent like there. W15 L2 (additive): `address` and
1336
+ # `role`, and agent{}'s `messaging` and `name_match` (carried inside `agent`). W15 L4 (additive): `inbox: {pending}`,
1337
+ # absent while no message waits (the container's own readers count its inbox themselves; this is the boards' copy).
1338
+ CONTAINER_STATUS_FIELDS = ('state', 'agent', 'attached', 'viewers', 'activity', 'size', 'stale', 'docs', 'address',
1339
+ 'role', 'inbox')
1142
1340
  CONTAINER_STATUS_DIR = tuple(L.CONTAINER_HOME.strip('/').split('/')) + ('.lz',)
1143
1341
  CONTAINER_STATUS_FILE = 'status.json'
1144
1342
 
@@ -1496,6 +1694,526 @@ def rearm_pulse(ctx, level, now=None):
1496
1694
  return True
1497
1695
 
1498
1696
 
1697
+ # W15 L6 (BEY-6843): the per-container lane-peerd loop (container/lane-peerd), started and re-armed like the pulse.
1698
+ PEERD_DIR = ('home', 'coder', '.lz', 'state', 'peers') # under /proc/<container init>/root, walked without a link
1699
+ PEERD_FILE = 'peers.json' # renewed at least every 30 s by a running loop (lane-peerd STATE_HEARTBEAT_S)
1700
+ PEERD_PROGRAM = 'lane-peerd'
1701
+ PEERD_CHECK_S = 30 # a container's peers.json is looked at this often, at most
1702
+ PEERD_REARM_S = 90 # = lane_core.PEER_FRESH: an older (or absent) peers.json is a stopped loop ...
1703
+ PEERD_REARM_EVERY = 600 # ... started at most this often per container,
1704
+ PEERD_PER_PASS = 2 # ... and in at most this many containers per pass
1705
+ PEERD_REARM_TIMEOUT = 10
1706
+ PEERD_SITE_KEY = 'LANES_PEERS' # site.conf: 0 = never start it; agents (default) = agent lanes only; all = shells too
1707
+
1708
+
1709
+ def peerd_policy(settings):
1710
+ """None (off), 'agents' or 'all' from site.conf LANES_PEERS: '0' is off, 'all' serves every lane, anything else
1711
+ (unset, '1', 'agents') serves the agent lanes only (BEY-6843: ~160 plain shells here would crowd ListAgents)."""
1712
+ value = str(settings.get(PEERD_SITE_KEY, 'agents')).strip().lower()
1713
+ return None if value == '0' else ('all' if value == 'all' else 'agents')
1714
+
1715
+
1716
+ def peerd_rearm_argv(container, lanes='agents'):
1717
+ """The loop started detached in its own tmux server in the container, as the container user with
1718
+ HOME=CONTAINER_HOME (pulse_rearm_argv's form; tmux -L lanes-peers, session peerd). argv only, no shell."""
1719
+ return ['docker', 'exec', '-d', '-u', str(L.CONTAINER_UID), '-e', f'HOME={L.CONTAINER_HOME}', container, 'tmux',
1720
+ '-L', 'lanes-peers', 'new', '-d', '-s', 'peerd', f'{L.CONTAINER_HOME}/.lz/bin/{PEERD_PROGRAM}', '--loop',
1721
+ '--lanes', lanes]
1722
+
1723
+
1724
+ def peerd_look(pid):
1725
+ """(installed, peers.json mtime or None) in the container whose init is `pid`: ~/.lz/bin/lane-peerd a regular
1726
+ file, and the loop's state file — both through /proc/<pid>/root, no component a link."""
1727
+ installed, mtime = False, None
1728
+ root = Path(L.proc_root()) / str(pid) / 'root'
1729
+ try:
1730
+ fd = L.open_real_dir(root, PULSE_BIN)
1731
+ except (OSError, L.LanesError):
1732
+ return False, None
1733
+ try:
1734
+ installed = stat.S_ISREG(os.stat(PEERD_PROGRAM, dir_fd=fd, follow_symlinks=False).st_mode)
1735
+ except OSError:
1736
+ installed = False
1737
+ finally:
1738
+ os.close(fd)
1739
+ try:
1740
+ fd = L.open_real_dir(root, PEERD_DIR)
1741
+ except (OSError, L.LanesError):
1742
+ return installed, None
1743
+ try:
1744
+ info = os.stat(PEERD_FILE, dir_fd=fd, follow_symlinks=False)
1745
+ mtime = info.st_mtime if stat.S_ISREG(info.st_mode) else None
1746
+ except OSError:
1747
+ mtime = None
1748
+ finally:
1749
+ os.close(fd)
1750
+ return installed, mtime
1751
+
1752
+
1753
+ def rearm_peerd(ctx, level, now=None):
1754
+ """main()'s start of a stopped lane-peerd, between two cycles and never inside one -> the containers it spawned
1755
+ into. Never on a `critical` host, never with site.conf LANES_PEERS=0. Each running container is looked at
1756
+ (peerd_look) at most every PEERD_CHECK_S; one whose lane-peerd is installed and whose peers.json is older than
1757
+ PEERD_REARM_S (or absent) gets ONE bounded `docker exec -d` (peerd_rearm_argv, PEERD_REARM_TIMEOUT s) — at most once
1758
+ per PEERD_REARM_EVERY per container, whatever comes of it, and PEERD_PER_PASS containers per pass — journalled."""
1759
+ now = time.time() if now is None else now
1760
+ if level == 'critical':
1761
+ return []
1762
+ checked, attempts = ctx.setdefault('peerd_checked', {}), ctx.setdefault('peerd_rearm_at', {})
1763
+ due = [(name, info) for name, info in sorted((ctx.get('containers') or {}).items())
1764
+ if isinstance(info, dict) and info.get('pid') and info.get('running')
1765
+ and now - checked.get(name, -PEERD_CHECK_S) >= PEERD_CHECK_S
1766
+ and now - attempts.get(name, -PEERD_REARM_EVERY) >= PEERD_REARM_EVERY]
1767
+ policy = peerd_policy(site_settings())
1768
+ if not due or policy is None:
1769
+ return []
1770
+ spawned = []
1771
+ for name, info in due:
1772
+ if len(spawned) >= PEERD_PER_PASS:
1773
+ break
1774
+ checked[name] = now
1775
+ if not pid_alive(info['pid']):
1776
+ continue
1777
+ installed, mtime = peerd_look(info['pid'])
1778
+ if not installed or (mtime is not None and now - mtime <= PEERD_REARM_S):
1779
+ continue
1780
+ attempts[name] = now
1781
+ argv = peerd_rearm_argv(name, policy)
1782
+ rc, _out, err = L.run_bounded(argv, PEERD_REARM_TIMEOUT)
1783
+ age = 'absent' if mtime is None else f'{int(now - mtime)} s old'
1784
+ if rc is None:
1785
+ outcome = f'no answer within {PEERD_REARM_TIMEOUT} s'
1786
+ else:
1787
+ last_line = err.strip().splitlines()[-1][:160] if rc and err.strip() else ''
1788
+ outcome = f'exit {rc}' + (f': {last_line}' if last_line else '')
1789
+ note('lane peerd', f'{name}: peers.json {age}, started ({outcome}): {" ".join(argv)}')
1790
+ spawned.append(name)
1791
+ return spawned
1792
+
1793
+
1794
+ NAMES_PER_PASS = 2 # renames one names_auto pass types at most (each waits lane_core.ENTER_DELAY before its Enter)
1795
+
1796
+
1797
+ def names_auto(ctx, level, now=None):
1798
+ """main()'s name parity retry (W15 L2c), between two cycles and never inside one -> the lane ids it tried.
1799
+
1800
+ Only while the registry's `names_auto` is on (site.conf LANES_NAMES_AUTO, default on), the host is `ok` and a
1801
+ payload was published: `lanes_lib.names_plan(..., unattached=True)` over the last payload picks the Claude lanes
1802
+ whose session name is not their address and which sit at their prompt — quiet, not delegating, no terminal
1803
+ attached — and at most NAMES_PER_PASS of those not tried within NAMES_RETRY_S get `lanes_lib.rename_claude`, which
1804
+ re-reads the session file before it types `/rename <address>` and Enter. An attempt counts whatever comes of it, so
1805
+ a lane that refuses is not retried every cycle. The journal gets the lane id, the address and the outcome only."""
1806
+ now = time.time() if now is None else now
1807
+ registry, payload = ctx.get('registry'), ctx.get('payload')
1808
+ if not registry or not registry.get('names_auto', True) or level != 'ok' or not isinstance(payload, dict):
1809
+ return []
1810
+ tried = ctx.setdefault('names_tried', {})
1811
+ for lane_id in [lane_id for lane_id, at in tried.items() if now - at >= L.NAMES_RETRY_S]:
1812
+ del tried[lane_id]
1813
+ todo, _deferred, _matched = L.names_plan(registry, payload, unattached=True)
1814
+ done = []
1815
+ for _board, lane, row in todo:
1816
+ if len(done) >= NAMES_PER_PASS:
1817
+ break
1818
+ if lane['id'] in tried:
1819
+ continue
1820
+ tried[lane['id']] = now
1821
+ done.append(lane['id'])
1822
+ address = row.get('address') or L.address_of(lane['id'])
1823
+ info = (ctx.get('containers') or {}).get(lane.get('container')) or {}
1824
+ try:
1825
+ outcome, detail = L.rename_claude(lane, address, info)
1826
+ except Exception as error:
1827
+ log(f"names {lane['id']}", error)
1828
+ continue
1829
+ note('names', f"{lane['id']} -> {address}: {outcome}: {detail}")
1830
+ return done
1831
+
1832
+
1833
+ # ------------------------------------------ messages: the inbox count and the typed delivery (W15 L4, BEY-6842)
1834
+ # Each container's `~/.lz/state/inbox/<lane>/` (DM-LANES-MESSAGE, -RECEIPT, -LOG; lane_core's store) holds the messages
1835
+ # sent to its lanes. Every cycle, through /proc/<init>/root (walked without following a link, like the pulse file and
1836
+ # the status projection): one open and one bounded scandir of the inbox per container, one stat per lane directory,
1837
+ # and the lane's files read only when that directory changed (a rename-only store: every write moves the directory's
1838
+ # mtime; a directory changed within INBOX_RACY_S of the last read is read again — the timestamp granularity). A lane
1839
+ # row carries `inbox: {pending}` while messages wait (absent otherwise, like `docs`). Between two cycles, never inside
1840
+ # one and only on an `ok` host, `deliver_inbox` types at most INBOX_PER_PASS waiting messages — the oldest of a lane,
1841
+ # one lane once a pass, each message at most once per INBOX_RETRY_S — into lanes observed idle with no terminal
1842
+ # attached (a Claude lane only while its own session file says `idle`, never a dialog; a pane without an agent only at
1843
+ # a shell prompt, as a comment line), and empties the text of at most INBOX_PURGE_PER_PASS messages whose ttl passed.
1844
+ # W15 part 2 (the PR #544 review): every message that is not settled is read, however much acknowledged history the
1845
+ # inbox holds (lane_core.inbox_entries); a message is typed only under the lane's dispatch lock
1846
+ # (lane_core.dispatch_lock: /proc/<init>/root/home/coder/.lz/state/dispatch/<lane id>.lock, the inode every writer in
1847
+ # the container takes too), after a recheck there (still waiting, the oldest of its lane, the lane's hook sidecar not
1848
+ # busy, a Claude lane's own word read again), its receipt settled before the lock is let go; a held message
1849
+ # (receipt `unknown`) is never typed; a cleanup that stopped between its two writes is finished (`cleared`).
1850
+ # Its journal lines name the lane, the message id and the outcome, never a text.
1851
+ INBOX_PATH = tuple(L.CONTAINER_HOME.strip('/').split('/')) + ('.lz', 'state', 'inbox')
1852
+ INBOX_PREFIX = tuple(L.CONTAINER_HOME.strip('/').split('/')) + ('.lz',)
1853
+ INBOX_LANES_MAX = 1024 # lane directories of one container's inbox looked at per cycle
1854
+ INBOX_RACY_S = 2 # a directory changed this recently is read again (mtime granularity)
1855
+ INBOX_PER_PASS = 2 # messages one deliver_inbox pass types at most
1856
+ INBOX_RETRY_S = 60 # one message is tried at most this often
1857
+ INBOX_PURGE_PER_PASS = 16 # expired texts one pass removes at most
1858
+
1859
+
1860
+ def inbox_pause(seconds):
1861
+ """time.sleep between a typed message and its Enter, named so a test records it instead of waiting."""
1862
+ time.sleep(seconds)
1863
+
1864
+
1865
+ def inbox_scan(ctx, now=None):
1866
+ """{lane id: [(at, message id, container), …] of its waiting messages, oldest first} for every running container
1867
+ (lane_core.pending: receipt `queued`, its text there, its ttl not passed). Cached per (container, lane) between
1868
+ cycles by the lane directory's (init pid, mtime_ns, inode); `ctx['inbox']` keeps the cache. An error costs only
1869
+ that container its counts (logged once per distinct error)."""
1870
+ now = time.time() if now is None else now
1871
+ C = L.lane_core()
1872
+ cache, errors = ctx.setdefault('inbox', {}), ctx.setdefault('inbox_errors', {})
1873
+ seen, out = set(), {}
1874
+ for name, info in sorted((ctx.get('containers') or {}).items()):
1875
+ pid = info.get('pid')
1876
+ if not pid or not info.get('running'):
1877
+ continue
1878
+ root = Path(L.proc_root()) / str(pid) / 'root'
1879
+ try:
1880
+ fd = L.open_real_dir(root, INBOX_PATH)
1881
+ except FileNotFoundError:
1882
+ continue
1883
+ except (OSError, L.LanesError) as error:
1884
+ _inbox_error(errors, name, error)
1885
+ continue
1886
+ try:
1887
+ with os.scandir(fd) as listing:
1888
+ dirs = [entry for _n, entry in zip(range(INBOX_LANES_MAX), listing)]
1889
+ for entry in dirs:
1890
+ if not C.LANE_RE.fullmatch(entry.name) or not entry.is_dir(follow_symlinks=False):
1891
+ continue
1892
+ info_dir = entry.stat(follow_symlinks=False)
1893
+ stamp, key = (pid, info_dir.st_mtime_ns, info_dir.st_ino), (name, entry.name)
1894
+ seen.add(key)
1895
+ cached = cache.get(key)
1896
+ if not cached or cached['stamp'] != stamp or cached['read_at'] - info_dir.st_mtime_ns / 1e9 < INBOX_RACY_S:
1897
+ cached = cache[key] = {'stamp': stamp, 'read_at': now,
1898
+ 'entries': C.inbox_entries(root, entry.name, prefix=INBOX_PREFIX)}
1899
+ waiting = [(entry_['record'].get('at'), entry_['id'], name) for entry_ in cached['entries']
1900
+ if C.pending(entry_, now)]
1901
+ if waiting:
1902
+ out.setdefault(entry.name, []).extend(waiting)
1903
+ errors.pop(name, None)
1904
+ except OSError as error:
1905
+ _inbox_error(errors, name, error)
1906
+ finally:
1907
+ os.close(fd)
1908
+ for gone in set(cache) - seen:
1909
+ del cache[gone]
1910
+ return {lane: sorted(rows) for lane, rows in out.items()}
1911
+
1912
+
1913
+ def _inbox_error(errors, container, error):
1914
+ message = f'{type(error).__name__}: {error}'
1915
+ if errors.get(container) != message:
1916
+ errors[container] = message
1917
+ log(f'inbox {container}', error)
1918
+
1919
+
1920
+ def with_inbox(lanes, waiting):
1921
+ """`lanes` with `inbox: {pending: n}` on every row whose lane has n > 0 waiting messages, on no other row. A row
1922
+ that changes is a NEW dict (DEF-1538)."""
1923
+ out = {}
1924
+ for lane_id, row in lanes.items():
1925
+ n = len(waiting.get(lane_id) or ())
1926
+ want = {'pending': n} if n else None
1927
+ if not isinstance(row, dict) or row.get('inbox') == want:
1928
+ out[lane_id] = row
1929
+ continue
1930
+ row = {key: value for key, value in row.items() if key != 'inbox'}
1931
+ if want:
1932
+ row['inbox'] = want
1933
+ out[lane_id] = row
1934
+ return out
1935
+
1936
+
1937
+ def lane_places(registry, payload):
1938
+ """{lane id: {'container', 'tmux', 'ws', 'holder'}} of every registry lane and every unregistered session the last
1939
+ payload lists — where a message to it is typed."""
1940
+ places = {}
1941
+ for workspace in (registry or {}).get('workspaces') or []:
1942
+ for lane in workspace.get('lanes') or []:
1943
+ places[lane['id']] = {'container': lane.get('container'), 'tmux': lane.get('tmux'), 'ws': workspace.get('id'),
1944
+ 'holder': lane.get('holder')}
1945
+ for board, entries in ((payload or {}).get('unregistered') or {}).items():
1946
+ for entry in entries or []:
1947
+ if isinstance(entry, dict) and entry.get('id'):
1948
+ places.setdefault(entry['id'], {'container': entry.get('container'), 'tmux': entry.get('tmux'),
1949
+ 'ws': entry.get('workspace') or board, 'holder': 'tmux'})
1950
+ return places
1951
+
1952
+
1953
+ def resolve_lane(registry, payload, text):
1954
+ """The lane id `text` names on this site (W15 L4, `lanes message`): an exact lane id, `@fleet` (the site's fleet
1955
+ admin), a registered address (`lanes_lib.lane_addresses`; an unregistered session's derived one), or a board id
1956
+ (its coordinator) — the `@` optional. LanesError otherwise."""
1957
+ name = text[1:] if isinstance(text, str) and text.startswith('@') else text
1958
+ places = lane_places(registry, payload)
1959
+ if not isinstance(name, str) or not name:
1960
+ raise L.LanesError(f'{text!r} names no lane')
1961
+ if name in places:
1962
+ return name
1963
+ addresses = L.lane_addresses(registry)
1964
+ if name == 'fleet':
1965
+ fleet = (registry or {}).get('fleet_admin')
1966
+ lane = next((lane for lane, (address, _role) in addresses.items() if fleet and address == fleet), None)
1967
+ if lane is None:
1968
+ raise L.LanesError('this site names no fleet admin lane (LANES_FLEET_ADMIN in site.conf)')
1969
+ return lane
1970
+ for lane, (address, _role) in addresses.items():
1971
+ if address == name:
1972
+ return lane
1973
+ for lane in places:
1974
+ if lane not in addresses and L.address_of(lane) == name:
1975
+ return lane
1976
+ board = next((w for w in (registry or {}).get('workspaces') or [] if w['id'] == name), None)
1977
+ if board is not None:
1978
+ if not board.get('coordinator'):
1979
+ raise L.LanesError(f'workspace {name} has no coordinator (lanes address set-coordinator {name} <lane-id>)')
1980
+ return board['coordinator']
1981
+ raise L.LanesError(f'no lane, address or workspace {text!r} (lanes address list shows every address)')
1982
+
1983
+
1984
+ def claude_word_now(place, info, sessions=None):
1985
+ """Claude's own word (`idle`, `busy`, `waiting`, …) in the one live Claude session file naming a pane of the lane's
1986
+ session, read now through /proc/<init>/root (lanes_lib.rename_claude's rule) — None when no file or several do.
1987
+ `sessions` ({init pid: (claude, work)}) keeps one read of a container's session files for a whole pass."""
1988
+ sessions = {} if sessions is None else sessions
1989
+ if info['pid'] not in sessions:
1990
+ root = Path(L.proc_root()) / str(info['pid']) / 'root'
1991
+ work = {}
1992
+ claude = AS.claude_sessions(root / L.CONTAINER_HOME.lstrip('/') / Path(*L.CLAUDE_SESSIONS), root / 'proc',
1993
+ work=work)
1994
+ sessions[info['pid']] = (claude, work)
1995
+ claude, work = sessions[info['pid']]
1996
+ session = (place.get('tmux') or {}).get('session') or ''
1997
+ keys = [key for key in claude if key.startswith(session + ':')]
1998
+ return work.get(keys[0], (None, None))[1] if len(keys) == 1 else None
1999
+
2000
+
2001
+ def ready_for_text(place, row, info, unattached=True, sessions=None):
2002
+ """(ready, why not) for typing a message into the lane NOW (`deliver_inbox`; `lanes message`, which a person asked
2003
+ for, without `unattached`). Only a tmux lane in a running container whose row was observed this cycle — not
2004
+ stale, its pane there and quiet (no output within ACTIVE_WINDOW: a person may be typing), with `unattached` no
2005
+ terminal attached — and: no agent (or a shell) whose pane's foreground command is a shell (lane_core.TYPED_SHELLS:
2006
+ at its prompt); else an agent whose word is one of lanes_lib.NAMES_IDLE and not delegating, and for Claude its own
2007
+ session file's word `idle` (never `waiting`: a dialog a typed line would answer)."""
2008
+ C = L.lane_core()
2009
+ tmux = place.get('tmux') if isinstance(place.get('tmux'), dict) else {}
2010
+ if place.get('holder') != 'tmux' or not tmux.get('socket') or not tmux.get('session'):
2011
+ return False, 'not a tmux lane'
2012
+ if not info.get('pid') or not info.get('running'):
2013
+ return False, 'its container is not running'
2014
+ if not isinstance(row, dict) or row.get('stale') or row.get('state') != 'quiet':
2015
+ return False, f"its pane is {(row or {}).get('state') or 'not observed'}" + (' (stale)' if (row or {}).get('stale') else '')
2016
+ if unattached and (row.get('attached') or 0) > 0:
2017
+ return False, 'a terminal is attached (a person may be typing)'
2018
+ agent = row.get('agent') if isinstance(row.get('agent'), dict) else {}
2019
+ if not agent.get('status') or agent.get('status') == 'shell' or str(agent.get('harness') or '') in C.NO_AGENT:
2020
+ command = row.get('command')
2021
+ return (True, None) if command in C.TYPED_SHELLS else (False, f'its pane runs {command or "nothing known"}')
2022
+ if agent.get('activity') == 'delegating':
2023
+ return False, 'delegating to background work'
2024
+ if agent.get('status') not in L.NAMES_IDLE:
2025
+ return False, f"its agent is {agent.get('status')}"
2026
+ if agent.get('harness') == 'claude':
2027
+ word = claude_word_now(place, info, sessions)
2028
+ if word != 'idle':
2029
+ return False, f'Claude says {word!r} (not idle at its prompt)'
2030
+ return True, None
2031
+
2032
+
2033
+ def type_message(place, row, info, record):
2034
+ """Type one message's envelope (lane_core.envelope; behind lane_core.SHELL_COMMENT into a pane without an agent)
2035
+ into the lane's active pane, the Enter as a second client lane_core.ENTER_DELAY s later (DEF-1803) -> (outcome,
2036
+ detail): 'typed', 'typed-no-enter' or 'failed'."""
2037
+ C = L.lane_core()
2038
+ agent = row.get('agent') if isinstance(row.get('agent'), dict) else {}
2039
+ body = C.envelope(record.get('from'), record.get('from_handle'), record['text'], C.epoch(record.get('at')) or time.time())
2040
+ if not agent.get('status') or agent.get('status') == 'shell' or str(agent.get('harness') or '') in C.NO_AGENT:
2041
+ body = C.SHELL_COMMENT + body
2042
+ socket, target = place['tmux']['socket'], C.target(place['tmux']['session'])
2043
+ outcome, text = L.tmux_probe(info, socket, ['send-keys', '-t', target, '-l', '--', C.tmux_text(body)])
2044
+ if outcome != 'ok':
2045
+ return 'failed', f'tmux did not take it ({outcome}{": " + text if text else ""}): not typed'
2046
+ inbox_pause(C.ENTER_DELAY)
2047
+ outcome, text = L.tmux_probe(info, socket, ['send-keys', '-t', target, 'Enter'])
2048
+ if outcome != 'ok':
2049
+ return 'typed-no-enter', f'typed without its Enter (tmux {outcome})'
2050
+ return 'typed', 'typed'
2051
+
2052
+
2053
+ def settle_message(root, prefix, lane_id, message_id, state, now, drop_text=False, outcome=None):
2054
+ """Write a message's receipt `state` (lane_core.receipt_record) or, with `drop_text`, its record without the text
2055
+ FIRST and then its receipt stamped `cleared` (lane_core.cleared_receipt: a waiting one `expired`; written only
2056
+ after the text left, so a purge that stops between the two is never settled and the next pass finishes it); then
2057
+ one log line (`outcome`, else `state`) -> the record it read, or None (gone)."""
2058
+ C = L.lane_core()
2059
+ fd = C.inbox_fd(root, lane_id, prefix=prefix)
2060
+ try:
2061
+ record = C._read_at(fd, message_id + C.MESSAGE_SUFFIX)
2062
+ if not isinstance(record, dict) or record.get('v') != 1:
2063
+ return None
2064
+ if drop_text:
2065
+ kept = {k: v for k, v in record.items() if k != 'text'}
2066
+ if 'text' in record:
2067
+ C._write_at(fd, message_id + C.MESSAGE_SUFFIX, kept)
2068
+ receipt = C._read_at(fd, message_id + C.RECEIPT_SUFFIX)
2069
+ if not C.settled(receipt):
2070
+ C._write_at(fd, message_id + C.RECEIPT_SUFFIX, C.cleared_receipt(receipt, kept, message_id, now))
2071
+ elif state:
2072
+ C._write_at(fd, message_id + C.RECEIPT_SUFFIX, C.receipt_record(message_id, record.get('to'), state, now))
2073
+ finally:
2074
+ os.close(fd)
2075
+ size = len(record['text'].encode('utf-8')) if isinstance(record.get('text'), str) else 0
2076
+ C.append_log(root, C.log_line(now, record.get('from'), record.get('to'), message_id, size, outcome or state),
2077
+ prefix=prefix)
2078
+ return record
2079
+
2080
+
2081
+ def deliver_one(place, row, info, lane_id, message_id, now, unattached=True, sessions=None):
2082
+ """Type one waiting message into its lane when ready_for_text says so, then settle its receipt `typed` -> (outcome,
2083
+ detail): 'deferred' (not now: nothing typed — not ready, another writer holds the lane's dispatch lock, an older
2084
+ message of the lane goes first, its hook sidecar says busy), 'gone' (acked, expired, held or settled meanwhile:
2085
+ read again at send time), 'typed', 'typed-no-enter' or 'failed' (tmux did not take it: still waiting). W15 part 2:
2086
+ the read, the recheck, the text, its Enter and the settled receipt all happen under the lane's dispatch lock
2087
+ (lane_core.dispatch_lock through /proc/<init>/root), the one every writer in the container takes."""
2088
+ C = L.lane_core()
2089
+ ready, why = ready_for_text(place, row, info, unattached, sessions)
2090
+ if not ready:
2091
+ return 'deferred', why
2092
+ root = Path(L.proc_root()) / str(info['pid']) / 'root'
2093
+ try:
2094
+ with C.dispatch_lock(root, lane_id, prefix=INBOX_PREFIX):
2095
+ waiting = sorted((e for e in C.inbox_entries(root, lane_id, prefix=INBOX_PREFIX, history=0)
2096
+ if C.pending(e, now)), key=lambda e: ((e['record'] or {}).get('at') or '', e['id']))
2097
+ entry = next((e for e in waiting if e['id'] == message_id), None)
2098
+ if entry is None:
2099
+ return 'gone', 'no longer waiting'
2100
+ if waiting[0]['id'] != message_id:
2101
+ return 'deferred', f"an older message of the lane goes first ({waiting[0]['id']})"
2102
+ hook = sidecar_for(info, lane_id) or {} # the agent's own word now, not the cycle's
2103
+ if hook.get('status') in C.BUSY_WORDS:
2104
+ return 'deferred', f"its lane-signal hook says {hook['status']}"
2105
+ ready, why = ready_for_text(place, row, info, unattached, {}) # a Claude lane's own word, read again
2106
+ if not ready:
2107
+ return 'deferred', why
2108
+ outcome, detail = type_message(place, row, info, entry['record'])
2109
+ if outcome != 'failed':
2110
+ settle_message(root, INBOX_PREFIX, lane_id, message_id, 'typed', now)
2111
+ return outcome, detail
2112
+ except C.DispatchBusy as error:
2113
+ return 'deferred', str(error)
2114
+
2115
+
2116
+ def host_message(place, row, info, lane_id, to, sender, text, ttl_s, now=None):
2117
+ """`lanes message` (W15 L4): a person's message (`sender` = `host:<login>`) to a lane of any container -> (message
2118
+ id, outcome, detail). The record (DM-LANES-MESSAGE, its text, 0600) and its `queued` receipt are written into the
2119
+ lane's inbox through the container's home volume (`info['home']`/.lz, walked without following a link; no
2120
+ `~/.lz` there is no lane contract: refused), one log line; then deliver_one types it at once when the lane is
2121
+ ready — without the attached check: a person asked — else it waits for deliver_inbox. LanesError on a refusal."""
2122
+ now = time.time() if now is None else now
2123
+ C = L.lane_core()
2124
+ C.check_message(text)
2125
+ if not C.HOST_SENDER.fullmatch(sender or ''):
2126
+ raise L.LanesError(f'{sender!r} is no host sender (host:<login>)')
2127
+ if not info.get('home'):
2128
+ raise L.LanesError(f"{lane_id}: the home volume of container {place.get('container')} is not known (lanes doctor)")
2129
+ base, prefix = Path(info['home']), ('.lz',)
2130
+ try:
2131
+ fd = C.inbox_fd(base, lane_id, create=True, prefix=prefix)
2132
+ except FileNotFoundError:
2133
+ raise L.LanesError(f"{place.get('container')} has no lane contract (~/.lz): lanes install-container "
2134
+ f"{place.get('container')}") from None
2135
+ except OSError as error:
2136
+ raise L.LanesError(f"{lane_id}: its inbox cannot be written ({error.strerror or error})") from None
2137
+ try:
2138
+ message_id = C.new_message_id(fd, now)
2139
+ C._write_at(fd, message_id + C.MESSAGE_SUFFIX, C.message_record(message_id, sender, 'person', to, now, text,
2140
+ ttl_s))
2141
+ C._write_at(fd, message_id + C.RECEIPT_SUFFIX, C.receipt_record(message_id, to, 'queued', now))
2142
+ finally:
2143
+ os.close(fd)
2144
+ C.append_log(base, C.log_line(now, sender, to, message_id, len(text.encode('utf-8')), 'queued'), prefix=prefix)
2145
+ outcome, detail = deliver_one(place, row, info, lane_id, message_id, now, unattached=False)
2146
+ return message_id, outcome, detail
2147
+
2148
+
2149
+ def deliver_inbox(ctx, level, now=None):
2150
+ """main()'s typed delivery of waiting messages (W15 L4), between two cycles and never inside one -> [(lane id,
2151
+ message id, outcome)] of what it did. Only on an `ok` host with a payload: the oldest waiting message of each lane,
2152
+ the oldest lanes first, at most INBOX_PER_PASS typed, each message tried at most once per INBOX_RETRY_S
2153
+ (deliver_one: ready_for_text, unattached); then at most INBOX_PURGE_PER_PASS messages whose ttl passed lose their
2154
+ text (receipt `expired` for one still waiting). The journal gets the lane, the id and the outcome only."""
2155
+ now = time.time() if now is None else now
2156
+ registry, payload = ctx.get('registry'), ctx.get('payload')
2157
+ if level != 'ok' or not registry or not isinstance(payload, dict):
2158
+ return []
2159
+ C = L.lane_core()
2160
+ tried = ctx.setdefault('inbox_tried', {})
2161
+ for message_id in [m for m, at in tried.items() if now - at >= INBOX_RETRY_S]:
2162
+ del tried[message_id]
2163
+ places, rows = lane_places(registry, payload), payload.get('lanes') or {}
2164
+ containers, sessions = ctx.get('containers') or {}, {}
2165
+ waiting = sorted((rows_[0][0] or '', lane_id, rows_) for lane_id, rows_ in (ctx.get('inbox_waiting') or {}).items())
2166
+ done, typed = [], 0
2167
+ for _oldest, lane_id, messages in waiting:
2168
+ if typed >= INBOX_PER_PASS:
2169
+ break
2170
+ message_id = next((m for _at, m, _c in messages if m not in tried), None)
2171
+ place = places.get(lane_id)
2172
+ if message_id is None or place is None or place.get('container') != messages[0][2]:
2173
+ continue
2174
+ info = containers.get(messages[0][2]) or {}
2175
+ try:
2176
+ outcome, _detail = deliver_one(place, rows.get(lane_id), info, lane_id, message_id, now, sessions=sessions)
2177
+ except Exception as error:
2178
+ log(f'inbox {lane_id}', error)
2179
+ tried[message_id] = now
2180
+ continue
2181
+ if outcome == 'deferred': # not idle now: no attempt, nothing typed
2182
+ continue
2183
+ tried[message_id] = now
2184
+ typed += 1
2185
+ done.append((lane_id, message_id, outcome))
2186
+ note('inbox', f'{lane_id} {message_id}: {outcome}')
2187
+ purged = 0
2188
+ for (container, lane_id), cached in sorted((ctx.get('inbox') or {}).items()):
2189
+ info = containers.get(container) or {}
2190
+ for entry in cached['entries']:
2191
+ if purged >= INBOX_PURGE_PER_PASS:
2192
+ return done
2193
+ record = entry.get('record')
2194
+ if not isinstance(record, dict) or not info.get('pid'):
2195
+ continue
2196
+ # A message still waiting expired undelivered (receipt `expired`); a delivered or held one keeps its word
2197
+ # (lane_core.cleared_receipt). A record whose text is gone and whose receipt does not say so yet is a
2198
+ # cleanup that stopped between its two writes (an ack, a purge): finished here (`cleared`).
2199
+ expiring = 'text' in record and C.expired(entry, now)
2200
+ if not expiring and ('text' in record or C.settled(entry.get('receipt'))):
2201
+ continue
2202
+ root = Path(L.proc_root()) / str(info['pid']) / 'root'
2203
+ outcome = 'expired' if expiring else 'cleared'
2204
+ try:
2205
+ settle_message(root, INBOX_PREFIX, lane_id, entry['id'], None, now, drop_text=True, outcome=outcome)
2206
+ except (OSError, L.LanesError) as error:
2207
+ log(f'inbox {lane_id}', error)
2208
+ continue
2209
+ purged += 1
2210
+ entry['record'] = {k: v for k, v in record.items() if k != 'text'}
2211
+ entry['receipt'] = dict(entry.get('receipt') or {}, cleared=C.iso(now))
2212
+ done.append((lane_id, entry['id'], outcome))
2213
+ note('inbox', f'{lane_id} {entry["id"]}: ' + ('text expired' if expiring else 'cleanup finished'))
2214
+ return done
2215
+
2216
+
1499
2217
  def compared(payload):
1500
2218
  """`payload` as the rewrite decision sees it: without the sample time of `fleet` (new every FLEET_INTERVAL) and
1501
2219
  of `throttle` (the pulse's 60-s heartbeat) — the quantized facts and the stale marks are what may move a rewrite
@@ -1655,6 +2373,18 @@ def main():
1655
2373
  rearm_pulse(ctx, level)
1656
2374
  except Exception as error:
1657
2375
  log('throttle pulse', error)
2376
+ try: # W15 L6: a stopped lane-peerd started again, PEERD_PER_PASS containers at most, never critical
2377
+ rearm_peerd(ctx, level)
2378
+ except Exception as error:
2379
+ log('lane peerd', error)
2380
+ try: # W15 L2c: Claude session names back to their addresses, NAMES_PER_PASS at most, never while not `ok`
2381
+ names_auto(ctx, level)
2382
+ except Exception as error:
2383
+ log('names', error)
2384
+ try: # W15 L4: waiting messages typed into idle lanes, INBOX_PER_PASS at most, never while not `ok`
2385
+ deliver_inbox(ctx, level)
2386
+ except Exception as error:
2387
+ log('inbox', error)
1658
2388
  # Hot-reload: check if any terminals.json changed since we last synced.
1659
2389
  # Rate-limited to at most one triggered sync per HOT_SYNC_EVERY_S to avoid thrashing.
1660
2390
  if time.time() - last_triggered_sync > HOT_SYNC_EVERY_S and ctx['registry']: