@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.
@@ -54,6 +54,43 @@
54
54
  register undoes it); refused while tmux cannot check it. A record no workspace lists
55
55
  any more is removed from registered-sessions.json. A lane declared in a repository's
56
56
  terminals.json is refused with the file to edit
57
+ lanes address list [<board>] every lane's registered address (<board>.<slug>: its id with `--` turned into `.`, or
58
+ its board manifest's `addresses` override), its role (coordinator / fleet-admin) and
59
+ whether its Claude session name is that address (yes / no / - for no Claude session);
60
+ then the fleet admin and the boards without a coordinator
61
+ lanes address set <lane-id> <board>.<alias>
62
+ give a repository lane another address: `addresses[<terminal name>]` in its
63
+ workspaces.<board>.json (alias: a-z 0-9 . _ -, no `--`, which Claude refuses as a
64
+ name; a leading @ is dropped; its derived address again removes the override), only
65
+ that member rewritten, a .bak-<UTC> copy on the manifest's first write, then synced.
66
+ Refused, nothing written, while another lane answers to the address; a sync that
67
+ refuses the result puts the manifest back
68
+ lanes address set-coordinator <board> <lane-id>
69
+ make one of the board's declared lanes its coordinator (`coordinator` in its manifest:
70
+ `@<board>` reaches it, it alone may message the fleet admin), then sync
71
+ lanes names sync [--board B] [--write]
72
+ Claude lanes whose session name is not their address. Dry run by default: what it would
73
+ type and the lanes it leaves for later (working, waiting for an approval, delegating,
74
+ output in the last 20 s, not observed). --write types `/rename <address>` and Enter
75
+ into each of the others, after reading its session file again (only Claude's own
76
+ `idle`, one session in the lane, a name that differs). Exit 1 when tmux did not take
77
+ one; statusd retries the busy ones while site.conf's LANES_NAMES_AUTO is not 0
78
+ lanes migrate addresses [--write] [--board B]
79
+ the fleet's move to registered addresses, idempotent: `coordinator` in every board
80
+ manifest that has none (the lane whose slug is the board id, else the first declared;
81
+ each choice printed, `lanes address set-coordinator` changes it) and, without --board,
82
+ LANES_FLEET_ADMIN=@fleet-management.fleet-management appended to site.conf when unset;
83
+ collisions among addresses are reported. Dry run by default (the diffs). --write
84
+ copies every file it changes to ~/.local/state/lanes/migrations/<UTC stamp>/ with a
85
+ receipt.json, writes, validates the site again (a board error or a collision that was
86
+ not there before puts every file back, exit 1) and syncs. Exit 0 when nothing is left
87
+ to change
88
+ lanes message [--from <login>] [--ttl S] <lane-id|@address> <text...>
89
+ a person's message to a lane of any container (W15 L4, BEY-6842; the sidebar's `m`):
90
+ sender host:<login> (this account's name without --from), the text in one envelope
91
+ written into the lane's inbox (~/.lz/state/inbox/<lane>/ through the home volume),
92
+ typed at once when the lane is idle at its prompt, else queued — lanes-statusd types
93
+ it when the lane is next idle with no terminal attached; ttl 24 h by default
57
94
  lanes workspaces print the board ids (what the client installer reads)
58
95
  lanes workspaces add <id> --container <name> --repo <path> [--title T] [--session S] [--write]
59
96
  add a board to the site catalog (catalog.json + a new workspaces.<id>.json whose one
@@ -214,7 +251,9 @@
214
251
  (site.conf LANES_THROTTLE_CONTAINER, else the registry's Throttle Monitor container)
215
252
  its loop is started, once: `docker exec -d -u 1000 -e HOME=/home/coder <name> tmux -L
216
253
  lanes-pulse new -d -s pulse ~/.lz/bin/throttle-pulse --loop` (nothing when that
217
- session already runs; exit 1 when docker refused the start)
254
+ session already runs; exit 1 when docker refused the start). lane-peerd (W15 L6) ships
255
+ to every container; lanes-statusd starts its loop there (`tmux -L lanes-peers`,
256
+ site.conf LANES_PEERS=0 never)
218
257
  lanes throttle adopt-token <container>
219
258
  the operator's opt-in to the pulse's burn and money lines: copy env.ANTHROPIC_API_KEY
220
259
  of the container's own ~/.claude/settings.json — the LOCAL Throttle client bearer, it
@@ -303,6 +342,9 @@
303
342
  the lanes per create-recipe class (idempotent / attach-only / null / external /
304
343
  retired-path), lane identity, numeric session names, crowded `default` sockets and
305
344
  orphan tmux socket files (report only; in a container `lane gc --sockets` removes them),
345
+ the lane addresses (⚠ boards without a coordinator, ✗ two lanes on one address, ⚠ the
346
+ fleet admin unset or naming no lane, ⚠ `addresses` keys naming no terminal, and per
347
+ container how many Claude lanes' session names are their addresses),
306
348
  any record left in the retired legacy-sessions/ directory, the devices without an owner
307
349
  (each keeps its look to itself: `lanes device claim`), and the browser/phone half:
308
350
  lanes-web / lanes-mobile units (⚠ not enabled, ✗ enabled but not running), the login-token
@@ -391,6 +433,9 @@
391
433
  Without --yes or off a terminal: the plan, exit 2
392
434
  """
393
435
  import contextlib
436
+ import copy
437
+ import difflib
438
+ import hashlib
394
439
  import json
395
440
  import math
396
441
  import os
@@ -422,6 +467,8 @@ PROC = Path(os.environ.get('LANES_PROC_ROOT') or '/proc') # injectable for the
422
467
  # runs `lanes attach|ensure|rebuild` decides them for the view sessions it creates. A device's recorded LOOK_KEYS still
423
468
  # win over them (sidebar.resolve_modes / resolve_dim_notify).
424
469
  LOOK_ENV = ('LANES_COLOR', 'LANES_THEME', 'LANES_GLYPHS', 'LANES_DIM', 'LANES_NOTIFY')
470
+ # `lanes attach` hands only these to its display supervisor (libexec/attach.py BACKLOG_ENV/STALL_ENV), never to a session.
471
+ DISPLAY_ENV = ('LANES_DISPLAY_BACKLOG_BYTES', 'LANES_DISPLAY_STALL_S')
425
472
 
426
473
 
427
474
  def clean_env(extra=None):
@@ -1169,9 +1216,14 @@ def cmd_attach(args):
1169
1216
  'COLORTERM': os.environ.get('COLORTERM', 'truecolor')})
1170
1217
  if L.run_bounded(['infocmp', env['TERM']], 5)[0] != 0: # unknown here — or no answer: the safe default
1171
1218
  env['TERM'] = 'xterm-256color'
1219
+ for key in DISPLAY_ENV: # the operator's display limits, validated by the supervisor; nothing else passes
1220
+ if os.environ.get(key):
1221
+ env[key] = os.environ[key]
1172
1222
  # Own the terminal backlog as well as SSH's transport. A slow Zellij 0.45.1
1173
1223
  # client can stay alive after its server has dropped it (Exit is behind the
1174
1224
  # queued frames); keepalives alone cannot make lanes-launch reconnect it.
1225
+ # The supervisor keeps reading it, sheds what a slow terminal cannot take
1226
+ # and repaints; only a terminal that takes nothing ends the display.
1175
1227
  os.execve(sys.executable, [sys.executable, str(L.REPO / 'libexec/attach.py'),
1176
1228
  *ZELLIJ_BASE, 'attach', device], env)
1177
1229
 
@@ -1222,7 +1274,9 @@ def hook_env(home):
1222
1274
 
1223
1275
  INSTALL_CONTAINER_USAGE = 'usage: lanes install-container <name> [--no-mcp]'
1224
1276
  # lane_core.py first: `lane` imports it, so no moment has a new `lane` beside an old (or no) lane_core.py.
1225
- CONTRACT_FILES = ('lane_core.py', 'lane-mcp', 'lane', 'lane-run', 'lane-signal', 'lane-edit', 'throttle-pulse')
1277
+ # W15 L6 (BEY-6843): lane-peerd ships to every container too; lanes-statusd starts its loop (statusd.rearm_peerd).
1278
+ CONTRACT_FILES = ('lane_core.py', 'lane-mcp', 'lane', 'lane-run', 'lane-signal', 'lane-edit', 'throttle-pulse',
1279
+ 'lane-peerd')
1226
1280
  # The Throttle pulse (W11): installed everywhere, its loop started only in the daemon's container. As uid 1000 with
1227
1281
  # the container home as HOME, whatever user the image defaults to: it writes ~/.lz/state/throttle.json, which
1228
1282
  # lanes-statusd reads, and reads ~/.lz/throttle-token, which only the container's own user may read (0600).
@@ -1306,6 +1360,30 @@ def install_mcp_entries(home):
1306
1360
  return code
1307
1361
 
1308
1362
 
1363
+ def codex_hook_step(container, home):
1364
+ """W15 L3 (Linear BEY-6841): the gated Codex step `lanes install-container` prints for a container whose home
1365
+ has a real ~/.codex (read before the install writes Codex's MCP entry, which creates it) -> [line]. The Codex
1366
+ hooks record each Codex lane's thread id (lane-signal's `session`), which makes the lane addressable by `codex
1367
+ queue --thread`; they are the operator's opt-in (`lanes hooks install --agent codex`, a dry run until --write;
1368
+ Codex asks a person to trust them). Until then lane-mcp matches a thread through Codex's own app-server
1369
+ (lane_core.codex_handles). Nothing is read through a link: a linked ~/.codex is no Codex home here, a linked
1370
+ hooks.json no install. [] without ~/.codex."""
1371
+ codex = Path(home) / '.codex'
1372
+ try:
1373
+ if not stat.S_ISDIR(os.lstat(codex).st_mode):
1374
+ return []
1375
+ except OSError:
1376
+ return []
1377
+ hooks = lane_core().read_regular(codex / 'hooks.json', 1 << 20)
1378
+ if hooks is not None and b'lane-signal' in hooks:
1379
+ return ['Codex hooks: lane-signal installed — each Codex lane\'s thread id reaches lanes_status `handle` at '
1380
+ 'its next turn']
1381
+ return [f'Codex lanes: lanes hooks install --agent codex --container {container} (a dry run; add --write) records '
1382
+ 'each Codex lane\'s thread id at its next turn, so a lane message reaches it by `codex queue --thread`; '
1383
+ 'Codex asks a person to trust new hooks before it runs them. Until then lane-mcp matches each Codex lane '
1384
+ 'to its thread through Codex\'s app-server (handle `via: app-server`)']
1385
+
1386
+
1309
1387
  def cmd_install_container(args):
1310
1388
  names = [word for word in args if word != '--no-mcp']
1311
1389
  if len(names) != 1 or names[0].startswith('-'):
@@ -1317,6 +1395,7 @@ def cmd_install_container(args):
1317
1395
  raise L.LanesError(f'{container}: home volume not found')
1318
1396
  home = Path(info['home'])
1319
1397
  root = home / '.lz'
1398
+ codex_step = codex_hook_step(container, home) # W15 L3: before the MCP entry creates ~/.codex
1320
1399
  # Every directory is a real one and every file lands by rename (DEF-1798): nothing is written through a link.
1321
1400
  for sub in ('bin', 's', 'meta', 'state', 'hooks'):
1322
1401
  container_dir(home, '.lz', sub)
@@ -1346,11 +1425,13 @@ def cmd_install_container(args):
1346
1425
  if link.is_symlink() or link.exists():
1347
1426
  link.unlink()
1348
1427
  link.symlink_to(root)
1349
- print(f"installed {root}/bin/{{lane,lane_core.py,lane-run,lane-signal,lane-edit,throttle-pulse"
1428
+ print(f"installed {root}/bin/{{lane,lane_core.py,lane-run,lane-signal,lane-edit,throttle-pulse,lane-peerd"
1350
1429
  f"{'' if no_mcp else ',lane-mcp'},zmx-*}}, "
1351
1430
  f'{root}/VERSION, {root}/vimrc, {root}/hooks/' + (f' and {root}/env.sh' if env_file.exists() else '')
1352
1431
  + f'; host link {link} -> {root}')
1353
1432
  pulse = start_pulse(container)
1433
+ for line in codex_step:
1434
+ print(line)
1354
1435
  if no_mcp:
1355
1436
  print('--no-mcp: lane-mcp and the agents\' MCP entries left out (anything an earlier install wrote is kept)')
1356
1437
  return pulse
@@ -5353,6 +5434,9 @@ def cmd_doctor(_args):
5353
5434
  if registry:
5354
5435
  errors = [(w['id'], e) for w in registry['workspaces'] for e in w['errors']]
5355
5436
  check(not errors, 'registry clean', '; '.join(f'{w}: {e}' for w, e in errors))
5437
+ hook = site_hook_old()
5438
+ if hook:
5439
+ print(f'⚠ {hook} (Linear BEY-6912)')
5356
5440
  # Stale registry check: any terminals.json newer than the last sync? A lane's `source` is the container's
5357
5441
  # spelling; doctor runs on the host, so it stats the file under the container's home volume.
5358
5442
  sys.path.insert(0, str(L.REPO / 'libexec'))
@@ -5389,6 +5473,12 @@ def cmd_doctor(_args):
5389
5473
  print(f' {line}')
5390
5474
  for warning in warnings + socket_report(containers, SD.live_by_container):
5391
5475
  print(f'⚠ {warning}')
5476
+ # W15 L2/L2b/L2c: coordinators, unique addresses, the fleet admin, Claude names = addresses per container.
5477
+ for mark, text in address_doctor(registry, L.read_json(L.STATE / 'status.json') or {}):
5478
+ if mark in ('⚠', ''):
5479
+ print(f'{mark or " "} {text}')
5480
+ else:
5481
+ check(mark == '✓', text)
5392
5482
  # Plan Task 19 retired the pre-persistence Docker-shell tracker. A record still in its directory is inert (never
5393
5483
  # observed, never closable from the sidebar): name it, so the operator ends that shell by hand and removes it.
5394
5484
  legacy = sorted(p.stem for p in (L.STATE / 'legacy-sessions').glob('*.json'))
@@ -5545,6 +5635,513 @@ def cmd_rename(args):
5545
5635
  return 0
5546
5636
 
5547
5637
 
5638
+ # ------------------------------------------------------------------ addresses (W15 L2, L2b, L2c, L2d)
5639
+ # A lane's registered address is `<board>.<slug>` (lanes_lib.address_of) or its board manifest's `addresses` override;
5640
+ # a board's coordinator is its manifest's `coordinator`; the fleet admin is site.conf's LANES_FLEET_ADMIN. The verbs
5641
+ # below are their writers, editing a manifest the way `lanes rename` edits `displayNames` (atomic, a `.bak-<UTC>` copy
5642
+ # on the first write) but byte-preserving (lane_core.set_member: only the member that changes is rewritten), then
5643
+ # syncing; a sync that refuses the result gets the manifest back.
5644
+
5645
+ ADDRESS_USAGE = ('usage: lanes address list [<board>] | lanes address set <lane-id> <board>.<alias> | '
5646
+ 'lanes address set-coordinator <board> <lane-id>')
5647
+ NAMES_USAGE = 'usage: lanes names sync [--board B] [--write]'
5648
+ MIGRATE_USAGE = 'usage: lanes migrate addresses [--write] [--board B]'
5649
+ MIGRATIONS = 'migrations' # under the state directory: one <UTC stamp>/ per `lanes migrate addresses --write`
5650
+
5651
+
5652
+ def flag_args(args, usage, flags=('--write',), values=('--board',)):
5653
+ """(set of the `flags` given, {value flag: its value}) of `args`; LanesError(usage) for anything else."""
5654
+ given, found, rest = set(), {}, list(args)
5655
+ while rest:
5656
+ word = rest.pop(0)
5657
+ if word in flags:
5658
+ given.add(word)
5659
+ elif word in values and rest:
5660
+ found[word] = rest.pop(0)
5661
+ else:
5662
+ raise L.LanesError(usage)
5663
+ return given, found
5664
+
5665
+
5666
+ def board_of(registry, board_id):
5667
+ board = next((w for w in registry['workspaces'] if w['id'] == board_id), None)
5668
+ if board is None:
5669
+ raise L.LanesError(f'Unknown workspace: {board_id}')
5670
+ return board
5671
+
5672
+
5673
+ def declared_lane(registry, lane_id, what):
5674
+ """(board, lane) of a lane a repository declares (its terminal is in the board manifest's reach); LanesError for
5675
+ an unknown id and for an adopted session, an SSH pane or a tool, which have no terminal name."""
5676
+ for board in registry['workspaces']:
5677
+ for lane in board['lanes']:
5678
+ if lane['id'] == lane_id:
5679
+ if lane.get('registered_session') or not lane.get('registry_name') or not lane.get('repo'):
5680
+ raise L.LanesError(f'{lane_id} is no repository lane: {what} names a terminal of a '
5681
+ "repository's terminals.json (an adopted session keeps its derived address; "
5682
+ 'promote it with P to name it)')
5683
+ return board, lane
5684
+ raise L.LanesError(f'Unknown lane: {lane_id}')
5685
+
5686
+
5687
+ def manifest_member(text, path, key, value):
5688
+ """`text` (a board manifest) with the member `key` of the object at `path` set to `value` (None: removed) — every
5689
+ other byte kept (lane_core.set_member / remove_member, the in-container terminals.json editor)."""
5690
+ C = L.lane_core()
5691
+ try:
5692
+ return C.set_member(text, path, key, value) if value is not None else C.remove_member(text, path, key)
5693
+ except C.LaneError as error:
5694
+ raise L.LanesError(f'the manifest cannot be edited: {error}') from error
5695
+
5696
+
5697
+ def manifest_addresses(text, name, address):
5698
+ """`text` with `addresses[name]` = `address` (None: the override removed)."""
5699
+ current = json.loads(text).get('addresses')
5700
+ if address is None:
5701
+ return manifest_member(text, ['addresses'], name, None) if isinstance(current, dict) and name in current else text
5702
+ if isinstance(current, dict):
5703
+ return manifest_member(text, ['addresses'], name, address)
5704
+ return manifest_member(text, [], 'addresses', {name: address})
5705
+
5706
+
5707
+ def edit_manifest(path, change):
5708
+ """Read, change and write one board manifest under registry_lock -> its text before (None when `change` changed
5709
+ nothing). Written atomically with its own mode; the first write keeps `<manifest>.bak-<UTC>` beside it
5710
+ (session_actions.rename_registered's idiom)."""
5711
+ path = Path(path)
5712
+ with L.registry_lock():
5713
+ before = path.read_text()
5714
+ after = change(before)
5715
+ if after == before:
5716
+ return None
5717
+ json.loads(after) # the editor keeps JSON valid; a slip here must never reach the file
5718
+ if not any(path.parent.glob(path.name + '.bak-*')):
5719
+ L.atomic_write(path.parent / (path.name + '.bak-' + time.strftime('%Y%m%dT%H%M%SZ', time.gmtime())),
5720
+ before, mode=0o644)
5721
+ L.atomic_write(path, after, mode=stat.S_IMODE(path.stat().st_mode))
5722
+ return before
5723
+
5724
+
5725
+ def publish_manifest(path, before, board_id, what):
5726
+ """`lanes sync` after a manifest edit. A sync that refuses the site (two lanes on one address) or reports an error
5727
+ on this board puts `before` back and syncs again, so the boards show what they showed: LanesError naming why."""
5728
+ try:
5729
+ failed, refused = sync_registry()
5730
+ problem = next((e for w in failed if w['id'] == board_id for e in w['errors']), None)
5731
+ except L.LanesError as error:
5732
+ problem = str(error)
5733
+ if problem:
5734
+ L.atomic_write(path, before, mode=stat.S_IMODE(Path(path).stat().st_mode))
5735
+ try:
5736
+ sync_registry()
5737
+ except L.LanesError:
5738
+ pass
5739
+ raise L.LanesError(f'{what} refused by lanes sync, the manifest is back as it was: {problem}')
5740
+ if refused:
5741
+ raise L.ProjectionRefused(what, refused)
5742
+
5743
+
5744
+ def address_list(board_id=None):
5745
+ registry = L.load_registry()
5746
+ boards = [board_of(registry, board_id)] if board_id else registry['workspaces']
5747
+ rows = (L.read_json(L.STATE / 'status.json') or {}).get('lanes') or {}
5748
+ facts = L.lane_addresses(registry)
5749
+ table = [('LANE', 'ADDRESS', 'ROLE', 'NAME MATCH')]
5750
+ for board in boards:
5751
+ for lane in board['lanes']:
5752
+ address, role = facts[lane['id']]
5753
+ agent = (rows.get(lane['id']) or {}).get('agent') or {}
5754
+ match = agent.get('name_match') if isinstance(agent, dict) else None
5755
+ table.append((lane['id'], address, role or '-', 'yes' if match is True else 'no' if match is False else '-'))
5756
+ widths = [max(len(row[i]) for row in table) for i in range(3)]
5757
+ for row in table:
5758
+ print(' '.join(cell.ljust(widths[i]) for i, cell in enumerate(row[:3])) + ' ' + row[3])
5759
+ fleet = registry.get('fleet_admin')
5760
+ print(f'fleet admin: @{fleet}' if fleet else 'fleet admin: unset (LANES_FLEET_ADMIN in ~/.config/lanes/site.conf; '
5761
+ 'lanes migrate addresses)')
5762
+ without = [board['id'] for board in boards if board.get('lanes') and not board.get('coordinator')
5763
+ and not board.get('attach_only')]
5764
+ if without:
5765
+ print('boards without a coordinator: ' + ', '.join(without) + ' (lanes address set-coordinator <board> <lane-id>)')
5766
+ return 0
5767
+
5768
+
5769
+ def address_set(lane_id, value):
5770
+ registry = L.load_registry()
5771
+ board, lane = declared_lane(registry, lane_id, 'an address override')
5772
+ address = L.check_address(board['id'], L.parse_address(value))
5773
+ name = lane['registry_name']
5774
+ target = None if address == L.address_of(lane_id, board=board['id']) else address
5775
+ trial = copy.deepcopy(registry) # the registry as it would be: refused while another lane answers to it
5776
+ overrides = dict(board_of(trial, board['id']).get('address_overrides') or {})
5777
+ overrides.pop(name, None)
5778
+ if target:
5779
+ overrides[name] = target
5780
+ board_of(trial, board['id'])['address_overrides'] = overrides
5781
+ clash = next((c for c in L.apply_addresses(trial, strict=False) if lane_id in c[1:]), None)
5782
+ if clash:
5783
+ other = clash[1] if clash[2] == lane_id else clash[2]
5784
+ raise L.LanesError(f'{address} is the address of {other}: nothing written')
5785
+ path = L.manifest_path(board['id'])
5786
+ before = edit_manifest(path, lambda text: manifest_addresses(text, name, target))
5787
+ if before is None:
5788
+ print(f'{lane_id}: address {address} already (nothing written)')
5789
+ return 0
5790
+ publish_manifest(path, before, board['id'], 'Address')
5791
+ print(f'{lane_id} ({name!r}): address {address}' + ('' if target else ' (its derived address: override removed)'))
5792
+ return 0
5793
+
5794
+
5795
+ def address_set_coordinator(board_id, lane_id):
5796
+ registry = L.load_registry()
5797
+ board = board_of(registry, board_id)
5798
+ owner, lane = declared_lane(registry, lane_id, 'a coordinator')
5799
+ if owner['id'] != board_id:
5800
+ raise L.LanesError(f'{lane_id} is a lane of {owner["id"]}, not of {board_id}')
5801
+ path = L.manifest_path(board_id)
5802
+ before = edit_manifest(path, lambda text: manifest_member(text, [], 'coordinator', lane['registry_name']))
5803
+ if before is None:
5804
+ print(f'{board_id}: coordinator {lane_id} already (nothing written)')
5805
+ return 0
5806
+ publish_manifest(path, before, board_id, 'Coordinator')
5807
+ print(f"{board_id}: coordinator {lane_id} ({lane['registry_name']!r}, @{lane.get('address') or L.address_of(lane_id)})"
5808
+ + (f' — was {board["coordinator"]}' if board.get('coordinator') else ''))
5809
+ return 0
5810
+
5811
+
5812
+ def cmd_address(args):
5813
+ if args[:1] == ['list'] and len(args) <= 2:
5814
+ return address_list(args[1] if len(args) == 2 else None)
5815
+ if args[:1] == ['set'] and len(args) == 3:
5816
+ return address_set(args[1], args[2])
5817
+ if args[:1] == ['set-coordinator'] and len(args) == 3:
5818
+ return address_set_coordinator(args[1], args[2])
5819
+ raise L.LanesError(ADDRESS_USAGE)
5820
+
5821
+
5822
+ MESSAGE_USAGE = 'usage: lanes message [--from <login>] [--ttl S] [--] <lane-id|@address> <text...>'
5823
+
5824
+
5825
+ def cmd_message(args):
5826
+ """lanes message [--from <login>] [--ttl S] <lane-id|@address> <text...> (W15 L4): a person's message to a lane of
5827
+ any container on this site, sender `host:<login>` (the login given, else this account's name) — written into the
5828
+ lane's inbox through its container's home volume, then typed at once when the lane is idle at its prompt, else left
5829
+ `queued` for lanes-statusd, which types it when the lane is next idle with no terminal attached. The sidebar's `m`
5830
+ runs this verb. Exit 0 once the message is in the inbox, typed or not; a refusal is exit 1 (main's LanesError)."""
5831
+ import pwd as _pwd
5832
+ import statusd as SD
5833
+ C = L.lane_core()
5834
+ rest, login, ttl = list(args), None, C.MESSAGE_TTL_S
5835
+ while rest and rest[0].startswith('--'):
5836
+ word = rest.pop(0)
5837
+ if word == '--':
5838
+ break
5839
+ if word == '--from' and rest:
5840
+ login = rest.pop(0)
5841
+ elif word == '--ttl' and rest and rest[0].isdigit():
5842
+ ttl = int(rest.pop(0))
5843
+ else:
5844
+ raise L.LanesError(MESSAGE_USAGE)
5845
+ if len(rest) < 2:
5846
+ raise L.LanesError(MESSAGE_USAGE)
5847
+ if not C.MESSAGE_TTL_MIN <= ttl <= C.MESSAGE_TTL_MAX:
5848
+ raise L.LanesError(f'--ttl is {C.MESSAGE_TTL_MIN} to {C.MESSAGE_TTL_MAX} seconds')
5849
+ to, text = rest[0], ' '.join(rest[1:])
5850
+ sender = 'host:' + (login or _pwd.getpwuid(os.getuid()).pw_name)
5851
+ if not C.HOST_SENDER.fullmatch(sender):
5852
+ raise L.LanesError(f'--from {login!r}: one login of letters, digits and . _ @ + -')
5853
+ try:
5854
+ C.check_message(text)
5855
+ except C.LaneError as error:
5856
+ raise L.LanesError(f'{error} ({error.code})') from None
5857
+ registry = L.load_registry()
5858
+ payload = L.read_json(L.STATE / 'status.json', {}) or {}
5859
+ lane_id = SD.resolve_lane(registry, payload, to)
5860
+ place = SD.lane_places(registry, payload)[lane_id]
5861
+ address = (L.lane_addresses(registry).get(lane_id) or (L.address_of(lane_id), None))[0]
5862
+ info = (L.read_json(L.STATE / 'containers.json', {}) or {}).get(place.get('container') or '') or {}
5863
+ row = (payload.get('lanes') or {}).get(lane_id)
5864
+ message_id, outcome, detail = SD.host_message(place, row, info, lane_id, address, sender, text, ttl)
5865
+ if outcome in ('typed', 'typed-no-enter'):
5866
+ print(f'message {message_id} to @{address}: {outcome} ({detail})' if outcome != 'typed'
5867
+ else f'message {message_id} to @{address}: typed')
5868
+ else:
5869
+ print(f'message {message_id} to @{address}: queued — lanes-statusd types it when the lane is next idle '
5870
+ f'({detail})')
5871
+ return 0
5872
+
5873
+
5874
+ def cmd_names(args):
5875
+ """lanes names sync [--board B] [--write] (W15 L2c): a Claude lane's session name is its address."""
5876
+ if args[:1] != ['sync']:
5877
+ raise L.LanesError(NAMES_USAGE)
5878
+ given, values = flag_args(args[1:], NAMES_USAGE)
5879
+ registry = L.load_registry()
5880
+ board = values.get('--board')
5881
+ if board:
5882
+ board_of(registry, board)
5883
+ status = L.read_json(L.STATE / 'status.json') or {}
5884
+ todo, deferred, matched = L.names_plan(registry, status, board)
5885
+ containers = L.read_json(L.STATE / 'containers.json') or {}
5886
+ write, counts = '--write' in given, {}
5887
+ for _board, lane, row in todo:
5888
+ address = row.get('address') or lane.get('address') or L.address_of(lane['id'])
5889
+ current = (((row.get('agent') or {}).get('messaging')) or {}).get('name')
5890
+ if not write:
5891
+ print(f"would rename {lane['id']} {current!r} -> {address}")
5892
+ counts['to rename'] = counts.get('to rename', 0) + 1
5893
+ continue
5894
+ outcome, detail = L.rename_claude(lane, address, containers.get(lane['container']) or {})
5895
+ print(f"{outcome:<12} {lane['id']}: {detail}")
5896
+ counts[outcome] = counts.get(outcome, 0) + 1
5897
+ for _board, lane, why in deferred:
5898
+ print(f"deferred {lane['id']}: {why}")
5899
+ counts['deferred'] = counts.get('deferred', 0) + len(deferred)
5900
+ print(', '.join(f'{n} {what}' for what, n in counts.items()) + f', {matched} already match'
5901
+ + ('' if write else ' — dry run: --write types /rename <address> + Enter into each lane to rename'))
5902
+ return 1 if counts.get('failed') else 0
5903
+
5904
+
5905
+ def site_hook_old():
5906
+ """A site hook that replaced `lanes_lib.build_registry` with a callable written for a Lanes before 1.7.0 (no
5907
+ `strict`; rd-control's federation hook, Linear BEY-6912) -> one line saying so, else None. Read from the callable's
5908
+ signature only: a `**kwargs` wrapper that forwards to the real function counts as current."""
5909
+ import inspect
5910
+ try:
5911
+ params = inspect.signature(L.build_registry).parameters
5912
+ except (TypeError, ValueError):
5913
+ return None
5914
+ if 'strict' in params or any(p.kind is inspect.Parameter.VAR_KEYWORD for p in params.values()):
5915
+ return None
5916
+ who = getattr(L.build_registry, '__qualname__', None) or 'something'
5917
+ return (f'{who} replaces lanes_lib.build_registry without `strict` (a site hook written for a Lanes before 1.7.0): '
5918
+ 'two lanes on one address refuse instead of being listed')
5919
+
5920
+
5921
+ def build_site_registry(previous, strict=True):
5922
+ """`L.build_registry(previous, strict=…)`, or the older call when a site hook replaced it (site_hook_old): then a
5923
+ `strict=False` caller is told on stderr once, and a duplicate address raises as it did before 1.7.0 — the verb
5924
+ still runs instead of dying on a TypeError (BEY-6912)."""
5925
+ why = site_hook_old()
5926
+ if why is None:
5927
+ return L.build_registry(previous, strict=strict)
5928
+ if not strict:
5929
+ print(f'lanes: {why} (Linear BEY-6912)', file=sys.stderr)
5930
+ return L.build_registry(previous)
5931
+
5932
+
5933
+ def site_check():
5934
+ """`lanes sync`'s validation without publishing: the registry built from the site as it is now (two lanes on one
5935
+ address left in place, `strict=False`) -> (registry, None), or (None, why) when the site cannot be built at all."""
5936
+ try:
5937
+ return build_site_registry(L.read_json(L.STATE / 'registry.json'), strict=False), None
5938
+ except (L.LanesError, OSError, ValueError, KeyError) as error:
5939
+ return None, str(error)
5940
+
5941
+
5942
+ def site_findings(registry):
5943
+ """(board errors, address clashes) of a `site_check` registry, as sets a before/after comparison can subtract."""
5944
+ errors = {(board['id'], error) for board in registry['workspaces'] for error in board['errors']}
5945
+ clashes = {tuple(clash) for clash in L.apply_addresses(copy.deepcopy(registry), strict=False)}
5946
+ return errors, clashes
5947
+
5948
+
5949
+ def findings_line(errors, clashes):
5950
+ return (f'{len(errors)} board error{"s" if len(errors) != 1 else ""}, {len(clashes)} address '
5951
+ f'clash{"es" if len(clashes) != 1 else ""}')
5952
+
5953
+
5954
+ def migration_plan(registry, board_id):
5955
+ """[(path, text before, text after, what)] of `lanes migrate addresses`, printing each decision."""
5956
+ changes = []
5957
+ for board in registry['workspaces']:
5958
+ if board.get('attach_only') or (board_id and board['id'] != board_id):
5959
+ continue
5960
+ path = L.manifest_path(board['id'])
5961
+ text = path.read_text()
5962
+ current = json.loads(text).get('coordinator')
5963
+ if current is not None:
5964
+ print(f" {board['id']}: coordinator {current!r} kept")
5965
+ continue
5966
+ if board['errors']:
5967
+ print(f" {board['id']}: has errors ({board['errors'][0]}): no coordinator written — fix it, run again")
5968
+ continue
5969
+ declared = [lane for lane in board['lanes'] if lane.get('registry_name') and not lane.get('registered_session')]
5970
+ if not declared:
5971
+ print(f" {board['id']}: no declared lane: no coordinator")
5972
+ continue
5973
+ pick = next((lane for lane in declared if lane['id'] == f"{board['id']}--{board['id']}"), None)
5974
+ rule = 'its slug is the board id' if pick else 'the first declared lane'
5975
+ pick = pick or declared[0]
5976
+ changes.append((path, text, manifest_member(text, [], 'coordinator', pick['registry_name']),
5977
+ f"{board['id']}: coordinator {pick['registry_name']!r}"))
5978
+ print(f" {board['id']}: coordinator {pick['registry_name']!r} = {pick['id']} (@{pick.get('address')}; rule: "
5979
+ f"{rule}) — another: lanes address set-coordinator {board['id']} <lane-id>")
5980
+ if board_id:
5981
+ print(f' site.conf: not considered with --board ({L.FLEET_ADMIN_KEY})')
5982
+ return changes
5983
+ conf = Path.home() / L.SITE_CONF
5984
+ current = L.site_conf().get(L.FLEET_ADMIN_KEY)
5985
+ if current:
5986
+ print(f' site.conf: {L.FLEET_ADMIN_KEY}={current} kept')
5987
+ elif not conf.is_file():
5988
+ print(f'⚠ site.conf: no {conf}: {L.FLEET_ADMIN_KEY} not written (add it by hand)')
5989
+ else:
5990
+ text = conf.read_text()
5991
+ line = f'{L.FLEET_ADMIN_KEY}=@{L.DEFAULT_FLEET_ADMIN}\n'
5992
+ changes.append((conf, text, text + ('\n' if text and not text.endswith('\n') else '') + line,
5993
+ f'site.conf: {line.strip()}'))
5994
+ known = any(lane.get('address') == L.DEFAULT_FLEET_ADMIN for board in registry['workspaces']
5995
+ for lane in board['lanes'])
5996
+ print(f' site.conf: {line.strip()}' + ('' if known else ' (no lane answers to that address yet)'))
5997
+ return changes
5998
+
5999
+
6000
+ def cmd_migrate(args):
6001
+ """lanes migrate addresses [--write] [--board B] (W15 L2d)."""
6002
+ if args[:1] != ['addresses']:
6003
+ raise L.LanesError(MIGRATE_USAGE)
6004
+ given, values = flag_args(args[1:], MIGRATE_USAGE)
6005
+ board_id = values.get('--board')
6006
+ before, why = site_check()
6007
+ if before is None:
6008
+ print(f'✗ site validation before: {why} — nothing written; lanes sync says the same')
6009
+ return 1
6010
+ if board_id:
6011
+ board_of(before, board_id)
6012
+ errors, clashes = site_findings(before)
6013
+ print(f'site validation before: {findings_line(errors, clashes)}')
6014
+ for address, first, second in sorted(clashes):
6015
+ print(f' ✗ {address}: {first} and {second} (lanes address set <lane-id> <board>.<alias>)')
6016
+ changes = migration_plan(before, board_id)
6017
+ if not changes:
6018
+ print('nothing to change')
6019
+ return 0
6020
+ for path, old, new, _what in changes:
6021
+ sys.stdout.writelines(difflib.unified_diff(old.splitlines(True), new.splitlines(True), str(path), str(path), n=1))
6022
+ if '--write' not in given:
6023
+ print(f'dry run: --write applies it (copies under {L.STATE / MIGRATIONS}/<UTC stamp>/)')
6024
+ return 0
6025
+ stamp = time.strftime('%Y%m%dT%H%M%SZ', time.gmtime())
6026
+ backup, n = L.STATE / MIGRATIONS / stamp, 2
6027
+ while backup.exists():
6028
+ backup, n = L.STATE / MIGRATIONS / f'{stamp}-{n}', n + 1
6029
+ files = []
6030
+ with L.registry_lock():
6031
+ for path, old, _new, _what in changes:
6032
+ if path.read_text() != old:
6033
+ raise L.LanesError(f'{path} changed while the migration was planned: nothing written; run it again')
6034
+ backup.mkdir(parents=True, mode=0o700)
6035
+ for index, (path, old, new, what) in enumerate(changes):
6036
+ copy_name = f'{index:02d}-{path.name}'
6037
+ L.atomic_write(backup / copy_name, old, mode=0o600)
6038
+ files.append({'path': str(path), 'backup': copy_name, 'change': what,
6039
+ 'sha256_before': hashlib.sha256(old.encode()).hexdigest(),
6040
+ 'sha256_after': hashlib.sha256(new.encode()).hexdigest()})
6041
+ L.atomic_write(backup / 'receipt.json', json.dumps(
6042
+ {'v': 1, 'verb': 'lanes migrate addresses', 'at': time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime()),
6043
+ 'board': board_id, 'files': files}, indent=1) + '\n', mode=0o600)
6044
+ for path, _old, new, _what in changes:
6045
+ L.atomic_write(path, new, mode=stat.S_IMODE(path.stat().st_mode))
6046
+ print(f'backups: {backup} ({len(changes)} file{"s" if len(changes) != 1 else ""}, receipt.json)')
6047
+ after, why = site_check()
6048
+ if after is not None:
6049
+ errors_after, clashes_after = site_findings(after)
6050
+ why = '; '.join([f'{w}: {e}' for w, e in sorted(errors_after - errors)]
6051
+ + [f'{a}: {x} and {y}' for a, x, y in sorted(clashes_after - clashes)])
6052
+ if why: # worse than before (or no site at all): every file goes back
6053
+ with L.registry_lock():
6054
+ for path, old, _new, _what in changes:
6055
+ L.atomic_write(path, old, mode=stat.S_IMODE(path.stat().st_mode))
6056
+ print(f'✗ site validation after: {why} — every file is back as it was (copies in {backup})')
6057
+ return 1
6058
+ print(f'site validation after: {findings_line(errors_after, clashes_after)}')
6059
+ try:
6060
+ _failed, refused = sync_registry()
6061
+ except L.LanesError as error: # a clash that was there before: written, and the operator's to resolve
6062
+ print(f'✗ written, but lanes sync refuses the site until this is resolved: {error}')
6063
+ return 1
6064
+ if refused:
6065
+ raise L.ProjectionRefused('Migration', refused)
6066
+ return 0
6067
+
6068
+
6069
+ def address_doctor(registry, status):
6070
+ """`lanes doctor`'s address lines (W15 L2, L2b, L2c) -> [(mark, text)]: boards without a coordinator (⚠), two
6071
+ lanes on one address (✗; ✓ when none), the fleet admin (⚠ unset or naming no lane), override keys that name no
6072
+ terminal (⚠) and, per container, how many Claude lanes answer to their address (information). Reads registry.json
6073
+ and status.json only."""
6074
+ trial = copy.deepcopy(registry)
6075
+ clashes = L.apply_addresses(trial, strict=False)
6076
+ boards = [board for board in trial.get('workspaces') or [] if board.get('lanes') and not board.get('attach_only')]
6077
+ lines = []
6078
+ without = [board['id'] for board in boards if not board.get('coordinator')]
6079
+ lines.append(('⚠', f'{len(without)} of {len(boards)} boards without a coordinator: {", ".join(without[:6])}'
6080
+ f'{" …" if len(without) > 6 else ""} — lanes migrate addresses --write, or lanes address '
6081
+ 'set-coordinator <board> <lane-id>') if without else
6082
+ ('', f'coordinators: every board has one ({len(boards)})'))
6083
+ lines.append(('✗', 'lane addresses unique — ' + '; '.join(f'{a}: {x} and {y}' for a, x, y in clashes[:3])
6084
+ + ' (lanes sync refuses the site until one has another address)') if clashes else
6085
+ ('✓', 'lane addresses unique'))
6086
+ fleet = trial.get('fleet_admin')
6087
+ owner = next((lane['id'] for board in trial.get('workspaces') or [] for lane in board.get('lanes') or []
6088
+ if fleet and lane.get('address') == fleet), None)
6089
+ if not fleet:
6090
+ lines.append(('⚠', f'fleet admin unset — {L.FLEET_ADMIN_KEY}=@<address> in ~/.config/lanes/site.conf (lanes '
6091
+ f'migrate addresses --write sets @{L.DEFAULT_FLEET_ADMIN})'))
6092
+ elif not owner:
6093
+ lines.append(('⚠', f'fleet admin @{fleet} is the address of no lane'))
6094
+ else:
6095
+ lines.append(('', f'fleet admin: @{fleet} ({owner})'))
6096
+ for board in boards:
6097
+ names = {lane.get('registry_name') for lane in board['lanes']}
6098
+ orphans = sorted(set(board.get('address_overrides') or {}) - names)
6099
+ if orphans:
6100
+ lines.append(('⚠', f"{board['id']}: addresses for no terminal: {', '.join(map(repr, orphans[:4]))} — "
6101
+ 'remove them from the manifest or set them again'))
6102
+ rows, counts = (status or {}).get('lanes') or {}, {}
6103
+ for board in trial.get('workspaces') or []:
6104
+ for lane in board.get('lanes') or []:
6105
+ agent = (rows.get(lane['id']) or {}).get('agent')
6106
+ if isinstance(agent, dict) and agent.get('harness') == 'claude':
6107
+ tally = counts.setdefault(lane.get('container') or '?', [0, 0])
6108
+ tally[0] += agent.get('name_match') is True
6109
+ tally[1] += 1
6110
+ if counts:
6111
+ lines.append(('', 'Claude names = addresses: ' + ' · '.join(f'{c} {m}/{n}' for c, (m, n) in sorted(counts.items()))
6112
+ + ('' if all(m == n for m, n in counts.values()) else
6113
+ ' (lanes names sync --write; statusd renames the busy ones as they go idle while '
6114
+ f'{L.NAMES_AUTO_KEY} is on)')))
6115
+ codex = codex_addressable(trial, rows)
6116
+ if codex:
6117
+ short = sorted(name for name, (found, total) in codex.items() if found < total)
6118
+ counted = ' · '.join(f'{c} {m} of {n}' for c, (m, n) in sorted(codex.items()))
6119
+ lines.append(('', 'codex lanes addressable: ' + counted
6120
+ + (f' — counted by the thread id the Codex hooks record (lanes hooks install --agent codex '
6121
+ f'--container {short[0]} --write{" and the others" if len(short) > 1 else ""}); until then '
6122
+ "lane-mcp in the container matches each by its cwd through Codex's app-server (lanes_status "
6123
+ '`handle.via`)' if short else '')))
6124
+ return lines
6125
+
6126
+
6127
+ def codex_addressable(registry, rows):
6128
+ """{container: [addressable, live]} over the registry's Codex lanes (W15 L3): `live` counts the lanes whose agent
6129
+ is Codex (status.json; a `shell` word is a Codex that ended), `addressable` those with a thread id the Codex hooks
6130
+ recorded (agent.session_id, lane_core.THREAD_RE). The container-side fallback (lane_core.codex_handles) is not
6131
+ the host's to count."""
6132
+ core, counts = lane_core(), {}
6133
+ for board in registry.get('workspaces') or []:
6134
+ for lane in board.get('lanes') or []:
6135
+ agent = (rows.get(lane['id']) or {}).get('agent')
6136
+ if not isinstance(agent, dict) or agent.get('harness') != 'codex' or agent.get('status') in (None, 'shell'):
6137
+ continue
6138
+ tally = counts.setdefault(lane.get('container') or '?', [0, 0])
6139
+ thread = agent.get('session_id')
6140
+ tally[0] += isinstance(thread, str) and bool(core.THREAD_RE.fullmatch(thread))
6141
+ tally[1] += 1
6142
+ return counts
6143
+
6144
+
5548
6145
  # ------------------------------------------------------------------ preview
5549
6146
  # Ctrl-Alt-m (zellij/config.kdl, spec §5.4) opens a floating pane running `lanes preview --focused`: the markdown file
5550
6147
  # the focused lane printed last, rendered by glow (else `less -R`). Read-only: two zellij listings, one guarded tmux
@@ -6154,7 +6751,8 @@ COMMANDS = {'rebuilt': cmd_rebuilt, 'hello': cmd_hello, 'client-config': cmd_cli
6154
6751
  'sidebar-key': cmd_sidebar_key, 'studio-host': cmd_studio_host,
6155
6752
  'keys': cmd_keys, 'invite': cmd_invite, 'enrol': cmd_enrol, 'offboard': cmd_offboard,
6156
6753
  'token': cmd_token, 'onboard': cmd_onboard, 'user': cmd_user, 'lane': cmd_lane, 'here': cmd_here,
6157
- 'version': cmd_version, 'update': cmd_update, 'docs': cmd_docs}
6754
+ 'version': cmd_version, 'update': cmd_update, 'docs': cmd_docs,
6755
+ 'address': cmd_address, 'names': cmd_names, 'migrate': cmd_migrate, 'message': cmd_message}
6158
6756
 
6159
6757
  if __name__ == '__main__':
6160
6758
  if len(sys.argv) < 2 or sys.argv[1] not in COMMANDS: