@vibelord/lanes 1.8.0 → 1.9.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/package.json +1 -1
  2. package/payload/lanes/README.md +29 -11
  3. package/payload/lanes/VERSION +1 -1
  4. package/payload/lanes/bin/lanes +159 -59
  5. package/payload/lanes/bin-rs/BINARIES.json +2 -17
  6. package/payload/lanes/client/lanes-launch +51 -2
  7. package/payload/lanes/container/lane +142 -19
  8. package/payload/lanes/container/lane-mcp +168 -55
  9. package/payload/lanes/container/lane-peerd +6 -6
  10. package/payload/lanes/container/lane-signal +48 -3
  11. package/payload/lanes/container/lane_core.py +1040 -164
  12. package/payload/lanes/container/throttle-pulse +13 -4
  13. package/payload/lanes/docs/AGENTS-lanes.md +15 -7
  14. package/payload/lanes/docs/ARCHITECTURE.md +478 -101
  15. package/payload/lanes/docs/DESIGN.md +7 -2
  16. package/payload/lanes/docs/INSTALL.md +20 -3
  17. package/payload/lanes/docs/PLAN-1.9.1-SIDEBAR-CODEX.md +128 -0
  18. package/payload/lanes/docs/RUNBOOK.md +1428 -107
  19. package/payload/lanes/docs/USERGUIDE.md +488 -86
  20. package/payload/lanes/holders/tmux.sh +3 -3
  21. package/payload/lanes/install/services.py +68 -11
  22. package/payload/lanes/libexec/agent_state.py +2 -5
  23. package/payload/lanes/libexec/attach.py +11 -3
  24. package/payload/lanes/libexec/cursor_sync.py +22 -2
  25. package/payload/lanes/libexec/docsd.py +38 -4
  26. package/payload/lanes/libexec/lanes_lib.py +377 -39
  27. package/payload/lanes/libexec/mdlite.py +43 -3
  28. package/payload/lanes/libexec/notify.py +69 -26
  29. package/payload/lanes/libexec/registrations.py +5 -0
  30. package/payload/lanes/libexec/session_actions.py +114 -27
  31. package/payload/lanes/libexec/sidebar.py +246 -64
  32. package/payload/lanes/libexec/site_hooks.py +65 -0
  33. package/payload/lanes/libexec/statusd.py +139 -189
  34. package/payload/lanes/libexec/studio_host.py +8 -2
  35. package/payload/lanes/libexec/tokens.py +6 -2
  36. package/payload/lanes/libexec/update.py +13 -5
  37. package/payload/lanes/libexec/view.sh +39 -4
  38. package/payload/lanes/libexec/workspace_keys.py +54 -0
  39. package/payload/lanes/site/protocol.py +15 -5
  40. package/payload/lanes/site/relay.py +5 -2
  41. package/payload/lanes/site/server.py +29 -18
  42. package/payload/lanes/systemd/lanes-economy.service +3 -1
  43. package/payload/lanes/tokens/README.md +10 -0
  44. package/payload/lanes/tokens/generate.py +1 -1
  45. package/payload/lanes/web/Caddyfile +9 -2
  46. package/payload/lanes/web/README.md +2410 -95
  47. package/payload/lanes/web/browser.css +2 -0
  48. package/payload/lanes/web/browser.js +18 -6
  49. package/payload/lanes/web/directory.js +1 -1
  50. package/payload/lanes/web/docs.js +23 -0
  51. package/payload/lanes/web/links.js +157 -0
  52. package/payload/lanes/web/manifest.webmanifest +0 -2
  53. package/payload/lanes/web/mobile.css +30 -32
  54. package/payload/lanes/web/mobile.js +286 -227
  55. package/payload/lanes/web/upload.js +65 -22
  56. package/payload/lanes/web/workspace-keys.js +65 -0
  57. package/payload/lanes/zellij/config.kdl +1 -1
  58. package/payload/manifest.json +5 -22
  59. package/payload/lanes/bin-rs/THIRD-PARTY-NOTICES +0 -18953
  60. package/payload/lanes/bin-rs/x86_64-unknown-linux-musl/lanes-hook +0 -0
  61. package/payload/lanes/bin-rs/x86_64-unknown-linux-musl/lanes-terminal +0 -0
@@ -11,15 +11,25 @@ sees, and `lane-mcp` may write nothing but protocol frames to its stdout.
11
11
  socket nobody serves starts one and leaves its socket file behind; DEF-1797), without a lane identity in its
12
12
  environment (DEF-1559), with stdin closed (lane-mcp's stdin is its protocol stream) and bounded in time (exit
13
13
  124 when tmux does not answer, 127 when it cannot start). Targets are `=<session>:` (a bare `=<session>` is
14
- refused by send-keys and capture-pane). A text and its Enter are two clients ENTER_DELAY s apart (send_keys,
15
- DEF-1803); the one client allowed to start a server (`lanes_new`) gets creation_env(), an allow-list (DEF-1802).
14
+ refused by send-keys and capture-pane). A text and its Enter are two clients ENTER_DELAY s apart (DEF-1803),
15
+ typed into the pane that holds the lane's agent and checked on its screen (agent_pane, send_checked: BEY-8655);
16
+ the one client allowed to start a server (`lanes_new`) gets creation_env(), an allow-list (DEF-1802).
16
17
  * whoami: $LANE_ID, else the pane's session (`display -p -t $TMUX_PANE '#S'` on $TMUX's socket) matched in the
17
18
  registry, then among the container's unregistered sessions. Codex clears an MCP server's environment, so its
18
19
  entry passes these through (`env_vars`, MCP_ENV_VARS); Claude Code's servers inherit them.
19
- * the terminals.json minimal editor: strict JSON only, every byte outside the edited span kept, re-read before the
20
- write (one retry when the file changed meanwhile), atomic replace; never the root `throttle` object, never a
21
- terminal's `name`, never a reorder, never the last terminal. lane-mcp's write tools (LNS-35) and, on the host,
22
- `session_actions.unregister_declared` (the sidebar's `u` on a declared lane) edit through it.
20
+ * the terminals.json minimal editor: strict JSON only, every byte outside the edited span kept, atomic replace;
21
+ never the root `throttle` object, never a terminal's `name`, never a reorder, never the last terminal. Every
22
+ Python writer of a terminals.json goes through ONE path, `update_terminals` (BEY-7435): an flock on the sidecar
23
+ `.terminals.json.lock` (present only while a writer holds it), the file read under it, only the caller's delta
24
+ applied (its `mutate`), temp file + fsync + rename + directory fsync, and `registry_row_vanished` — nothing
25
+ written — when a row, a `lanes.terminals` binding or a root `throttle.terminals` binding that its delta does not
26
+ remove would be gone. lane-mcp's write tools (LNS-35) and, on the host, `session_actions` (the sidebar's `P` and
27
+ `u`, `lanes register`'s repair) and `lanes cursor-sync --write` edit through it. Known exceptions (BEY-7435
28
+ follow-ups) write without the lock: the Rust native `lanes unregister` and `lanes cursor-sync` when routed native
29
+ (flags/native.client, LANES_RS_*), `scripts/propose-terminal-annotations.py --write`, and a container that still
30
+ runs a lane-mcp from before this lock until `lanes install-container` (or the 1.8.1 update) reinstalls it.
31
+ `terminals_redeclare` puts back the row of a dangling binding (a `lanes.terminals` entry no `terminals[]` row
32
+ declares), under an id that agrees with its name (`lane_id_agrees`).
23
33
  * the host's lane-id and recipe rules, ported so the container can predict what `lanes sync` will publish: `slug`,
24
34
  `shown_key`, `lane_trace`, `canonical_recipe`, the id grammar (each pinned equal to its lanes_lib original by
25
35
  test_lane_mcp_write.HostRules), and `declared_name`, which finds a registry lane's declared terminal in its file.
@@ -48,17 +58,20 @@ sees, and `lane-mcp` may write nothing but protocol frames to its stdout.
48
58
  the thread id.
49
59
  * messages (W15 L4, BEY-6842; DM-LANES-MESSAGE/-RECEIPT/-LOG): `message` for `lane message` and lane-mcp's `lanes_message`
50
60
  sends one message to one lane of this container through the first adapter that applies — the sender's own
51
- SendMessage (refused `use_send_message`), `codex queue`, the Throttle bus (LANES_BUS=throttle), typed into an idle
52
- lane — else the recipient's inbox ~/.lz/state/inbox/<lane>/ (`queued`, typed by the host's lanes-statusd when the
53
- lane is next idle); every message in ONE envelope (ENVELOPE), every outcome one metadata-only log line, never its
54
- text. `inbox_summary`/`inbox_pending`/`inbox_counts` read an inbox (every message that is not settled, whatever
55
- the history holds), `message_ack` takes a message's text out of it, `message_retry` hands a held one back.
56
- W15 part 2 (the PR #544 review): native input has ONE authority per recipient, `dispatch_lock` (an flock on
57
- ~/.lz/state/dispatch/<lane>.lock, which the host's lanes-statusd takes too through /proc/<init>/root), held across
58
- the final readiness recheck, the text and its Enter (DM-LANES-DISPATCH-LOCK); a Codex lane is resolved with its
59
- own context at dispatch (`handle(…, fresh=True)`); an adapter whose answer was lost after the request went out is
60
- `unknown` — held, never replayed or handed to another adapter — and the Throttle bus is reached on Throttle's
61
- control listener with the sending harness's own client token (BEY-6869).
61
+ SendMessage (refused `use_send_message`), `codex queue`, the Throttle bus (LANES_BUS=throttle) — else the
62
+ recipient's inbox ~/.lz/state/inbox/<lane>/ (`queued`: its agent reads it there). A message never types into a
63
+ terminal (BEY-7538): a lane only its keyboard reaches is refused `transport_never_types`, or queued; every message
64
+ in ONE envelope (ENVELOPE), except that `codex queue` carries a pointer (ENVELOPE_POINTER, BEY-8673 D: the id and
65
+ `~/.lz/bin/lane inbox ack <id>`, never the text), every outcome one metadata-only log line, never its text.
66
+ `inbox_summary`/`inbox_pending`/`inbox_counts` read an inbox (every message that is not settled, whatever the
67
+ history holds), `message_ack` takes a message's text out of it and answers that text once (taking a message is
68
+ that one recorded act; never read the inbox file), `message_retry` hands a held one back.
69
+ W15 part 2 (the PR #544 review): a person's typing into a lane (lanes_send, `lane send`) has ONE authority per
70
+ recipient, `dispatch_lock` (an flock on ~/.lz/state/dispatch/<lane>.lock, which the host takes too through
71
+ /proc/<init>/root), held across the final readiness recheck, the text and its Enter (DM-LANES-DISPATCH-LOCK); a
72
+ Codex lane is resolved with its own context at dispatch (`handle(…, fresh=True)`); an adapter whose answer was
73
+ lost after the request went out is `unknown` — held, never replayed or handed to another adapter — and the
74
+ Throttle bus is reached on Throttle's control listener with the sending harness's own client token (BEY-6869).
62
75
  * Claude peers (W15 L6, BEY-6843; DM-LANES-PEER, DM-LANES-PEER-FRAME): Claude Code's cross-session messaging spoken by
63
76
  proxy. `container/lane-peerd` registers every lane whose agent is not Claude as a virtual peer (a session entry
64
77
  naming a Lanes socket); `virtual_peers` reads what it serves, `peer_frame`/`parse_peer_frame` are the measured wire
@@ -68,6 +81,7 @@ sees, and `lane-mcp` may write nothing but protocol frames to its stdout.
68
81
  import base64
69
82
  import contextlib
70
83
  import difflib
84
+ import errno
71
85
  import fcntl
72
86
  import hashlib
73
87
  import json
@@ -335,7 +349,10 @@ def pause(seconds):
335
349
  def send_keys(socket, session, text, enter=True, run=None):
336
350
  """Type `text` (send_argvs), wait ENTER_DELAY seconds, press Enter -> [CompletedProcess, …] of the clients that
337
351
  ran: it stops at the first that fails, so one result that failed means nothing was typed, and a failed second
338
- means the text was typed without its Enter. `run` is the caller's tmux runner (default run_tmux)."""
352
+ means the text was typed without its Enter. `run` is the caller's tmux runner (default run_tmux). It types into
353
+ the session's CURRENT window: since BEY-8655 no send path calls it — lanes_send, `lane send` and the site's
354
+ tmux_write type into the agent's pane with send_checked —, and no messaging path ever did (BEY-7538; `message`
355
+ delivers by an adapter or the inbox, never by keystrokes)."""
339
356
  run = run or run_tmux
340
357
  results = []
341
358
  for argv in send_argvs(socket, session, text, enter):
@@ -362,6 +379,284 @@ def last_lines(text, lines):
362
379
  return '\n'.join(rows[-lines:]) + '\n' if rows else ''
363
380
 
364
381
 
382
+ # ------------------------------------------------------------------------------ the agent's pane and a checked Enter
383
+ # BEY-8655 (Fleet's FLE-344 finding of 18 Nov 2026). A text typed for a lane goes into the pane that holds the lane's
384
+ # agent, never into whatever window the session shows: a session may have several windows, and in a shell pane a text
385
+ # with its Enter runs as a command. After the Enter the agent's screen is read, and ONE more Enter is pressed only
386
+ # while its composer still holds exactly the typed text — never a blind second Enter: Enter on an agent's screen
387
+ # accepts whatever is selected ("Trust this folder?", "Update now (runs npm install -g …)", an approval).
388
+ # MEASURED 18 Nov 2026, tmux 3.4, a private server, the forms the judge reads (tests/fixtures/send-screens):
389
+ # * Claude Code 2.1.327: the composer is the last `❯` row (and its indented rows) between the two bottom `─` rules;
390
+ # the transcript echoes a submitted text as `❯ <text>` above it, and a queued one as `❯ <text>` + `⎿ Queued`, with
391
+ # the composer then showing the dim `Press up to edit queued messages`. 1,500 characters show as
392
+ # `[Pasted text #1]`. With Lanes' form (the text, ENTER_DELAY, the Enter) short, 400 and 1,500 characters were
393
+ # submitted; 1,500 characters with their Enter in ONE client stayed as `[Pasted text #2 +1 lines]`, and one more
394
+ # Enter submitted them.
395
+ # * Codex 0.169.1: the composer is the last `›` row and its indented rows, a blank row below; its update menu marks
396
+ # the selected row with `›` too (`› 1. Update now …`). 1,511 characters WITH LANES' FORM WERE NOT SUBMITTED: the
397
+ # first 1,024 became `[Pasted Content 1024 chars]`, the rest stayed as text and the Enter became a newline; one more
398
+ # Enter submitted all 1,511 (the reply quoted a word at character 1,500). Six such texts, three of them through
399
+ # send_checked itself, each reached Codex's session record as ONE user message, a second Enter included; a fresh
400
+ # Codex's first turn kept its composer filled for more than 0.8 s after its Enter (hence SETTLE_S).
401
+ # Other harnesses' screens are not measured: their Enter is pressed once and the answer says `unconfirmed`.
402
+
403
+ PANES_FORMAT = '#{pane_id}\t#{pane_pid}\t#{pane_dead}\t#{window_active}\t#{pane_active}'
404
+ PANE_ID_RE = re.compile(r'%[0-9]{1,9}')
405
+ TREE_DEPTH = 4 # a pane's process tree is walked this deep (Codex: bash -> node -> codex; = lane-peerd WALK_DEPTH)
406
+ TREE_MAX = 64 # processes looked at per pane, at most (= lane-peerd WALK_MAX)
407
+ COMPOSER_GLYPH = {'claude': '❯', 'codex': '›'} # ❯ and ›: the glyph that opens each measured composer row
408
+ PASTED_RE = re.compile(r'\[Pasted (?:text #[0-9]+(?: \+[0-9]+ lines?)?|Content [0-9]+ chars)\]')
409
+ RULE_RE = re.compile(r'[─━]{8,}') # a row of ─ (Claude's rules around its composer)
410
+ HOLD_MIN = 16 # characters (spaces aside) a composer must show of a text it shows only in part
411
+ CHECK_DELAY = 0.8 # s after the Enter before the agent's screen is read (measured: cleared within 0.3 s and 0.5 s)
412
+ CHECK_AGAIN = 1.0 # s between the two reads that must both show the text before the one more Enter
413
+ SETTLE_S = 4.0 # s after that one more Enter in which the composer is read again until it lets the text go
414
+ SETTLE_STEP = 0.5 # s between those reads (a fresh Codex's first turn took over 0.8 s to clear its composer)
415
+ VERDICTS = ('submitted', 'submitted_second_enter', 'not_submitted', 'unconfirmed')
416
+
417
+
418
+ def panes_argv(socket, session):
419
+ """Every pane of the session, in all of its windows (`list-panes -s`), as PANES_FORMAT rows."""
420
+ return tmux_argv(socket, 'list-panes', '-s', '-t', target(session), '-F', PANES_FORMAT)
421
+
422
+
423
+ def pane_rows(text):
424
+ """[{'pane', 'pid', 'active'}] of panes_argv's live panes; `active`: the active pane of the session's current
425
+ window (where `=<session>:` types). A malformed or dead row is left out."""
426
+ rows = []
427
+ for line in (text or '').splitlines():
428
+ fields = line.split('\t')
429
+ if len(fields) != 5 or not PANE_ID_RE.fullmatch(fields[0]) or not fields[1].isdigit() or fields[2] == '1':
430
+ continue
431
+ rows.append({'pane': fields[0], 'pid': int(fields[1]), 'active': fields[3] == '1' and fields[4] == '1'})
432
+ return rows
433
+
434
+
435
+ def process_children(proc, pid):
436
+ """The child pids of `pid`: /proc/<pid>/task/*/children (CONFIG_PROC_CHILDREN), else — a kernel without that file —
437
+ the processes whose parent (field 4 of /proc/<n>/stat) is `pid`. [] when unreadable."""
438
+ out, readable = [], False
439
+ try:
440
+ tasks = os.listdir(str(Path(proc) / str(pid) / 'task'))
441
+ except OSError:
442
+ return out
443
+ for task in tasks:
444
+ data = read_regular(Path(proc) / str(pid) / 'task' / task / 'children', 1 << 16)
445
+ readable = readable or data is not None
446
+ out.extend(int(word) for word in (data or b'').split() if word.isdigit())
447
+ if readable:
448
+ return out
449
+ try:
450
+ names = os.listdir(str(proc))
451
+ except OSError:
452
+ return out
453
+ for name in names:
454
+ if name.isdigit():
455
+ found = _stat(proc, int(name))
456
+ if found and found[1] == pid:
457
+ out.append(int(name))
458
+ return out
459
+
460
+
461
+ def pane_tree(proc, root):
462
+ """[(pid, harness or None)] of `root` and its descendants, breadth first, TREE_DEPTH levels, TREE_MAX processes."""
463
+ out, level = [], [root]
464
+ for _depth in range(TREE_DEPTH + 1):
465
+ following = []
466
+ for pid in level:
467
+ if len(out) >= TREE_MAX:
468
+ return out
469
+ out.append((pid, process_harness(proc, pid)))
470
+ following.extend(process_children(proc, pid))
471
+ level = following
472
+ if not level:
473
+ break
474
+ return out
475
+
476
+
477
+ def agent_pane(socket, session, proc=Path('/proc'), run=None, agent_pid=None, expect_agent=False):
478
+ """{'pane': tmux pane id, 'harness': harness or None} of the pane a text for the lane is typed into (BEY-8655),
479
+ read NOW from the lane's own tmux server (one panes_argv) and the process trees under its panes (pane_tree):
480
+
481
+ * the one pane whose tree holds a harness process; with several, the one whose tree holds `agent_pid` (the
482
+ lane's observed agent), else the active pane when it is one of them, else LaneError `agent_pane_ambiguous`;
483
+ * no harness in any pane: the session's active pane (a shell lane, typed as before) — unless the lane is known
484
+ to run an agent (`expect_agent`): LaneError `agent_pane_not_found`, because a text meant for an agent is never
485
+ typed into a shell.
486
+
487
+ `run` is the caller's tmux runner (default run_tmux); `proc` the /proc the pane pids live in (on the host, the
488
+ container's). LaneError `tmux_unanswered` / `tmux_failed` when tmux does not list the panes (its exit status in the
489
+ error's `rc`), `session_gone` when it lists none that lives (or no active one)."""
490
+ listed = (run or run_tmux)(panes_argv(socket, session))
491
+ if listed.returncode:
492
+ why = (listed.stderr or '').strip().splitlines()
493
+ why = why[0] if why else f'exit {listed.returncode}'
494
+ error = LaneError(f'tmux did not list the panes of {session}: {why}',
495
+ 'tmux_unanswered' if listed.returncode in (124, 127) else 'tmux_failed')
496
+ error.rc = listed.returncode # `lane send` exits with tmux's own status (124: no answer; DEF-1797)
497
+ raise error
498
+ rows = pane_rows(listed.stdout)
499
+ if not rows:
500
+ raise LaneError(f'tmux lists no live pane of {session}', 'session_gone')
501
+ trees = {row['pane']: pane_tree(proc, row['pid']) for row in rows}
502
+ agents = [row for row in rows if any(harness for _pid, harness in trees[row['pane']])]
503
+
504
+ def picked(row, pid=None):
505
+ found = [harness for each, harness in trees[row['pane']] if harness and (pid is None or each == pid)]
506
+ return {'pane': row['pane'], 'harness': (found or [h for _p, h in trees[row['pane']] if h] or [None])[0]}
507
+ if isinstance(agent_pid, int) and not isinstance(agent_pid, bool) and agent_pid > 1:
508
+ holding = [row for row in rows if any(each == agent_pid for each, _h in trees[row['pane']])]
509
+ if len(holding) == 1:
510
+ return picked(holding[0], agent_pid)
511
+ if len(agents) == 1:
512
+ return picked(agents[0])
513
+ if agents:
514
+ active = [row for row in agents if row['active']]
515
+ if len(active) == 1:
516
+ return picked(active[0])
517
+ raise LaneError(f'{len(agents)} panes of {session} run an agent and none is the lane\'s observed one',
518
+ 'agent_pane_ambiguous')
519
+ if expect_agent:
520
+ raise LaneError(f'no pane of {session} runs the lane\'s agent (its {len(rows)} pane(s) hold no harness '
521
+ 'process)', 'agent_pane_not_found')
522
+ active = [row for row in rows if row['active']]
523
+ if len(active) != 1:
524
+ raise LaneError(f'tmux names no active pane of {session}', 'session_gone')
525
+ return {'pane': active[0]['pane'], 'harness': None}
526
+
527
+
528
+ def pane_send_argvs(socket, pane, text, enter=True):
529
+ """send_argvs for one tmux pane id (`%N`): the text literally, then Enter as a second client (DEF-1803)."""
530
+ typed = tmux_argv(socket, 'send-keys', '-t', pane, '-l', '--', tmux_text(text))
531
+ return [typed, tmux_argv(socket, 'send-keys', '-t', pane, 'Enter')] if enter else [typed]
532
+
533
+
534
+ def screen_argv(socket, pane):
535
+ """The visible screen of one tmux pane id, no scrollback (`capture-pane -p`): what the composer judge reads."""
536
+ return tmux_argv(socket, 'capture-pane', '-p', '-t', pane)
537
+
538
+
539
+ def composer_text(screen, harness):
540
+ """The text a measured harness's composer shows on a captured screen -> str, or None when the harness's screen is
541
+ not measured (COMPOSER_GLYPH) or the screen holds no row its glyph opens. The composer is the LAST such row (the
542
+ transcript's echoes and a queued text sit above it) with the indented rows that follow it, up to a blank row or a
543
+ `─` rule; their words are joined by single spaces."""
544
+ glyph = COMPOSER_GLYPH.get(harness)
545
+ if not glyph:
546
+ return None
547
+ rows = (screen or '').split('\n')
548
+ start = None
549
+ for index, row in enumerate(rows):
550
+ if row.lstrip().startswith(glyph):
551
+ start = index
552
+ if start is None:
553
+ return None
554
+ parts = [rows[start].lstrip()[len(glyph):]]
555
+ for row in rows[start + 1:]:
556
+ if not row.strip() or RULE_RE.fullmatch(row.strip()) or not row.startswith(' '):
557
+ break
558
+ parts.append(row)
559
+ return ' '.join(' '.join(part.split()) for part in parts).strip()
560
+
561
+
562
+ def composer_holds(screen, harness, text):
563
+ """Does the agent's composer on `screen` still hold `text`? True / False, or None when no composer can be read
564
+ (composer_text). Spaces are ignored (a composer wraps at words). It holds the text when it shows exactly the text;
565
+ when it shows a paste placeholder (PASTED_RE) and, beside it, nothing or the text's end (Codex keeps the part after
566
+ its first 1,024 characters as plain text); or when it shows a part at least HOLD_MIN characters long of which the
567
+ text is the end (a person's draft before it) or that is the text's end. Anything else — a menu row, a placeholder
568
+ of the program's own, an empty composer, a queued text's hint — is not the text: no second Enter follows it."""
569
+ shown = composer_text(screen, harness)
570
+ if shown is None:
571
+ return None
572
+ want = ''.join((text or '').split())
573
+ rest = ''.join(PASTED_RE.sub('', shown).split())
574
+ if not want:
575
+ return False
576
+ if rest == want:
577
+ return True
578
+ if PASTED_RE.search(shown):
579
+ return rest == '' or want.endswith(rest)
580
+ return (len(want) >= HOLD_MIN and rest.endswith(want)) or (len(rest) >= HOLD_MIN and want.endswith(rest))
581
+
582
+
583
+ def send_checked(socket, pane, text, enter=True, harness=None, run=None, wait=None):
584
+ """Type `text` into tmux pane `pane`, wait ENTER_DELAY, press Enter, and then ask the screen whether the agent took
585
+ it (BEY-8655) -> (results, verdict). `results` are the send-keys clients that ran, as send_keys's: it stops at the
586
+ first that fails, so a failed first means nothing was typed and a failed second that the text waits without its
587
+ Enter (verdict None then, and with `enter` False). Otherwise the verdict (VERDICTS):
588
+
589
+ * `unconfirmed`: the harness's screen is not measured (COMPOSER_GLYPH), or no composer could be read;
590
+ * `submitted`: CHECK_DELAY after the Enter the composer no longer holds the text (composer_holds);
591
+ * `submitted_second_enter`: it still held it, and again CHECK_AGAIN later, so ONE more Enter was pressed (a third
592
+ result), and within SETTLE_S after it (read every SETTLE_STEP) the composer let it go;
593
+ * `not_submitted`: it still held it SETTLE_S after that Enter (or that Enter's client failed). Nothing more is
594
+ pressed.
595
+
596
+ The caller holds the lane's dispatch lock across all of it. `run` is the caller's tmux runner (default run_tmux),
597
+ `wait` its pause (default `pause`, looked up at call time)."""
598
+ run = run or run_tmux
599
+ wait = wait or (lambda seconds: pause(seconds))
600
+ results = []
601
+ for argv in pane_send_argvs(socket, pane, text, enter):
602
+ if results:
603
+ wait(ENTER_DELAY)
604
+ results.append(run(argv))
605
+ if results[-1].returncode:
606
+ return results, None
607
+ if not enter:
608
+ return results, None
609
+ if harness not in COMPOSER_GLYPH:
610
+ return results, 'unconfirmed'
611
+
612
+ def holds():
613
+ screen = run(screen_argv(socket, pane))
614
+ return None if screen.returncode else composer_holds(screen.stdout, harness, text)
615
+ for seconds in (CHECK_DELAY, CHECK_AGAIN):
616
+ wait(seconds)
617
+ held = holds()
618
+ if not held:
619
+ return results, 'submitted' if held is False else 'unconfirmed'
620
+ results.append(run(pane_send_argvs(socket, pane, text)[1]))
621
+ if results[-1].returncode:
622
+ return results, 'not_submitted'
623
+ started = time.monotonic()
624
+ for _read in range(int(SETTLE_S / SETTLE_STEP)): # bounded by count and by time: a read that hangs ends it
625
+ wait(SETTLE_STEP)
626
+ held = holds()
627
+ if held is not True or time.monotonic() - started >= SETTLE_S:
628
+ break
629
+ return results, {True: 'not_submitted', False: 'submitted_second_enter', None: 'unconfirmed'}[held]
630
+
631
+
632
+ def observed_agent(root, lane, proc=Path('/proc')):
633
+ """(expect_agent, agent_pid) for agent_pane, from the lane's two observations read now: its lane-signal hook
634
+ (hook_agent: live, recent, ours) and the host's (status.json's row). Either one naming an agent that is not a
635
+ shell (`status` other than `shell`; for the host's, a harness outside NO_AGENT too) expects one; the pid is the
636
+ hook's, else the host's. A status.json from a newer Lanes reads as no observation."""
637
+ hook = hook_agent(Path(root) / 'state' / 'hooks', lane, proc)
638
+ try:
639
+ row = (container_status(root)['lanes'].get(lane) or {}).get('agent')
640
+ except NewerVersion:
641
+ row = None
642
+ row = row if isinstance(row, dict) else {}
643
+ named = [agent for agent in (hook, row) if agent.get('status') and agent.get('status') != 'shell'
644
+ and (agent is hook or str(agent.get('harness') or '') not in NO_AGENT)]
645
+ pids = [agent.get('pid') for agent in named if isinstance(agent.get('pid'), int)
646
+ and not isinstance(agent.get('pid'), bool) and agent.get('pid') > 1]
647
+ return bool(named), (pids[0] if pids else None)
648
+
649
+
650
+ def verdict_sentence(verdict):
651
+ """What a person reads for a send_checked verdict."""
652
+ return {'submitted': 'the agent took it',
653
+ 'submitted_second_enter': 'the agent took it on a second Enter (its composer still held the text after '
654
+ 'the first)',
655
+ 'not_submitted': 'the text waits in the agent\'s composer: two Enters did not submit it',
656
+ 'unconfirmed': 'Enter pressed; whether the program took it is not checked (its screen form is not '
657
+ 'measured, or no composer could be read)'}.get(verdict, '')
658
+
659
+
365
660
  def new_session_argv(socket, session, cwd, lane_id, ws, command, address=None):
366
661
  """The one tmux client lane-mcp runs WITHOUT -N (`lanes_new`): it creates the session, and starts the socket's
367
662
  server when none runs. The lane's identity reaches the session only through these `-e` flags, the canonical
@@ -691,7 +986,8 @@ ROLES = ('coordinator', 'fleet-admin') # a lane's `ro
691
986
  ADDRESS_RE = re.compile(r'[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}') # an address without its `@` (IDENT, bounded)
692
987
  TARGET_RE = re.compile(r'@?[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}') # a lane id, or an address with an optional `@`
693
988
  HANDLE_KINDS = ('claude-session', 'codex-thread', 'lane', 'claude-peer') # claude-peer: lane-peerd's (W15 L6)
694
- TRANSPORTS = ('send_message', 'codex_queue', 'throttle_turn', 'typed')
989
+ TRANSPORTS = ('send_message', 'codex_queue', 'throttle_turn', 'typed') # `typed`: only a keyboard reaches the lane;
990
+ # a message never takes it (BEY-7538)
695
991
  THREAD_RE = re.compile(r'[A-Za-z0-9_.:-]{1,128}') # a Codex thread id as a sidecar records it
696
992
  NO_AGENT = ('', 'shell', 'none') # harness words that mean no agent in the pane
697
993
 
@@ -830,13 +1126,49 @@ def routing_check(sender_lane, recipient_lane, export):
830
1126
  return 'use_coordinator'
831
1127
 
832
1128
 
1129
+ def remote_routing(sender_lane, address, export):
1130
+ """routing_check for a recipient outside this container (DM-LANES-OUTBOX): the fleet admin's lane elsewhere takes
1131
+ messages from coordinators and the fleet admin only, like one here; every other address of another container is
1132
+ open to any lane."""
1133
+ admin_address, admin = fleet_admin_of(export)
1134
+ if admin_address is None or admin is not None or address != admin_address:
1135
+ return None
1136
+ if sender_lane and lane_role(sender_lane, export, export['lanes'].get(sender_lane)) in ROLES:
1137
+ return None
1138
+ return 'use_coordinator'
1139
+
1140
+
1141
+ # A harness's shared daemon, by a word of its command line (lane-signal's DAEMON_WORDS): Codex's `codex app-server …`
1142
+ # (MEASURED 2026-11-18, codex 0.170.0). One process serves the threads of many lanes and fires their hooks itself.
1143
+ DAEMON_WORDS = ('app-server',)
1144
+
1145
+
1146
+ def shared_daemon(pid, proc=None):
1147
+ """True when process `pid` is a harness's shared daemon: DAEMON_WORDS among the first words after its program's
1148
+ name in /proc/<pid>/cmdline (lane-signal's rule). A hook record that names such a process was written with the
1149
+ daemon's environment, whose LANE_ID is its starter's: the thread it names may be any lane's (BEY-8641). A command
1150
+ line that cannot be read is False."""
1151
+ try:
1152
+ pid = int(pid)
1153
+ except (TypeError, ValueError):
1154
+ return False
1155
+ if pid <= 1:
1156
+ return False
1157
+ data = read_regular(Path(proc or '/proc') / str(pid) / 'cmdline', 1 << 16)
1158
+ if not data:
1159
+ return False
1160
+ words = data.split(b'\0')[1:4]
1161
+ return any(word.encode() in words for word in DAEMON_WORDS)
1162
+
1163
+
833
1164
  def handle(agent, lane=None, root=None, home=None, proc=None, fresh=False):
834
1165
  """How a message reaches the agent in a lane: {'kind', 'name', 'transport'} (plan L2). A Claude session whose
835
1166
  messaging name is known — the host's `agent.messaging.name`, else the `name` of the Claude session file the
836
1167
  verdict came from — is `claude-session`, reached by the sender's own `SendMessage` (`send_message`); a Codex
837
1168
  agent whose thread id the hooks recorded (`session_id`) is `codex-thread` (`codex_queue`); any other harness, or
838
1169
  Claude/Codex without that name, is `lane` (`throttle_turn`, Throttle's next-turn delivery); a pane without an
839
- agent (none, a shell) is `lane` (`typed`). The name is None for `lane`.
1170
+ agent (none, a shell) is `lane` (`typed`: only its keyboard reaches it, and a message never types — BEY-7538;
1171
+ `message` refuses it `transport_never_types` or queues it). The name is None for `lane`.
840
1172
 
841
1173
  W15 L3: given the lane's id and this container's ~/.lz (`lane`, `root`; `home` defaults to its parent, `proc` to
842
1174
  /proc), a Codex agent without a recorded thread id falls back to Codex's own daemon (codex_handles: its cwd and
@@ -857,7 +1189,10 @@ def handle(agent, lane=None, root=None, home=None, proc=None, fresh=False):
857
1189
  if isinstance(name, str) and name.strip() and len(name) <= NAME_MAX \
858
1190
  and not any(unicodedata.category(ch) in ('Cc', 'Cs') for ch in name):
859
1191
  return {'kind': 'claude-session', 'name': name, 'transport': 'send_message'}
860
- if harness == 'codex' and isinstance(agent.get('session_id'), str) and THREAD_RE.fullmatch(agent['session_id']):
1192
+ # A thread id a shared daemon recorded is not this lane's (BEY-8641): it is passed over, and the lane's thread is
1193
+ # found below as if no hook had recorded one.
1194
+ if harness == 'codex' and isinstance(agent.get('session_id'), str) and THREAD_RE.fullmatch(agent['session_id']) \
1195
+ and not shared_daemon(agent.get('pid'), proc):
861
1196
  return {'kind': 'codex-thread', 'name': agent['session_id'], 'transport': 'codex_queue'}
862
1197
  if harness == 'codex' and lane is not None and root is not None:
863
1198
  found = codex_handles(root, home, proc, fresh=fresh).get(lane) or {'thread_id': None, 'why': 'no_match'}
@@ -1332,10 +1667,16 @@ def _codex_handles(root, home, proc):
1332
1667
  threads = codex_threads(home)
1333
1668
  if not threads:
1334
1669
  return {lane: {'thread_id': None, 'why': threads.why or 'no_match'} for lane in wanted}
1335
- lanes = registry_export(root)['lanes']
1336
- ghosts = {row['id']: row for row in status['unregistered']}
1337
1670
  taken = {row['agent']['session_id'] for row in status['lanes'].values() if isinstance(row.get('agent'), dict)
1338
1671
  and row['agent'].get('harness') == 'codex' and isinstance(row['agent'].get('session_id'), str)}
1672
+ facts = _codex_lane_facts(root, status, wanted, proc)
1673
+ assigned = codex_assign(facts, threads, taken)
1674
+ return {lane: {'thread_id': found, 'why': why} for lane, (found, why) in assigned.items()}
1675
+
1676
+
1677
+ def _codex_lane_facts(root, status, wanted, proc):
1678
+ lanes = registry_export(root)['lanes']
1679
+ ghosts = {row['id']: row for row in status['unregistered']}
1339
1680
  panes, facts = {}, {}
1340
1681
  for lane, agent in wanted.items():
1341
1682
  pid = codex_pid(proc, agent.get('pid')) if isinstance(agent.get('pid'), int) else None
@@ -1350,15 +1691,28 @@ def _codex_handles(root, home, proc):
1350
1691
  if found), None)
1351
1692
  facts[lane] = {'cwd': _cwd(proc, pid) if pid else None, 'name': agent.get('name'),
1352
1693
  'source': agent.get('source')}
1353
- assigned = codex_assign(facts, threads, taken)
1354
- return {lane: {'thread_id': found, 'why': why} for lane, (found, why) in assigned.items()}
1694
+ return facts
1695
+
1696
+
1697
+ def codex_shadow_facts(root, proc, now):
1698
+ status = container_status(root, now)
1699
+ if not status['fresh'] or not 0 <= now - status['at'] <= STATUS_FRESH:
1700
+ raise LaneError('fresh container status unavailable')
1701
+ wanted = {lane: row['agent'] for lane, row in status['lanes'].items()
1702
+ if isinstance(row.get('agent'), dict) and row['agent'].get('harness') == 'codex'}
1703
+ facts = _codex_lane_facts(root, status, wanted, proc)
1704
+ for lane, fact in facts.items():
1705
+ agent = wanted[lane]
1706
+ fact.update(status=agent.get('status'), thread=agent.get('session_id'), at=status['at'])
1707
+ return facts
1355
1708
 
1356
1709
 
1357
1710
  # ------------------------------------------------------------------------------------------------ atomic files
1358
1711
 
1359
- def atomic_replace(path, text, mode):
1712
+ def atomic_replace(path, text, mode, sync_dir=False):
1360
1713
  """Replace `path` with `text` (str) atomically: an O_EXCL temp file in the same directory, fsync, chmod, rename
1361
- over whatever the name holds."""
1714
+ over whatever the name holds. With `sync_dir`, the directory is fsynced after the rename too, so the new name
1715
+ survives a crash (update_terminals: a registry write that a power cut undoes would silently drop a lane)."""
1362
1716
  path = Path(path)
1363
1717
  fd, tmp = tempfile.mkstemp(prefix='.' + path.name + '.', dir=str(path.parent))
1364
1718
  try:
@@ -1374,6 +1728,17 @@ def atomic_replace(path, text, mode):
1374
1728
  except OSError:
1375
1729
  pass
1376
1730
  raise
1731
+ if sync_dir:
1732
+ try:
1733
+ directory = os.open(str(path.parent), os.O_RDONLY | getattr(os, 'O_DIRECTORY', 0))
1734
+ except OSError:
1735
+ return
1736
+ try:
1737
+ os.fsync(directory)
1738
+ except OSError: # a filesystem that cannot fsync a directory (EINVAL) has renamed the file all the same
1739
+ pass
1740
+ finally:
1741
+ os.close(directory)
1377
1742
 
1378
1743
 
1379
1744
  EDIT_MAX = 64 << 20 # ~/.claude.json grows with Claude Code's project history
@@ -1757,6 +2122,235 @@ def terminals_add(text, terminal, entry=None):
1757
2122
  return after
1758
2123
 
1759
2124
 
2125
+ def dangling_bindings(doc):
2126
+ """[(declared name, binding)] of the `lanes.terminals` entries of a parsed terminals.json that no `terminals[]` row
2127
+ declares: a binding whose board row is gone (BEY-7435: a concurrent rewrite dropped the row, the binding survived).
2128
+ The host builds no lane from it, so its session shows as unregistered and `terminals_add` refuses that session as
2129
+ `duplicate_binding`; `terminals_redeclare` puts the row back. [] for a document without a `terminals` list."""
2130
+ try:
2131
+ names = set(_terminal_names(doc))
2132
+ except LaneError:
2133
+ return []
2134
+ return [(name, entry) for name, entry in (_lanes_terminals(doc) or {}).items()
2135
+ if name not in names and isinstance(entry, dict)]
2136
+
2137
+
2138
+ def lane_id_agrees(recorded, derived):
2139
+ """Whether a binding's recorded lane id is the one its declared name gives (`derived`, `<ws>--slug(prefix +
2140
+ name)`), or that id with the `-N` suffix build_registry gives a second lane of the same slug. A repair re-declares
2141
+ a row only under an id that agrees (BEY-7435): a stale or foreign id would point the row's `lane open` elsewhere."""
2142
+ return isinstance(recorded, str) and isinstance(derived, str) and (
2143
+ recorded == derived or re.fullmatch(re.escape(derived) + r'-[0-9]+', recorded) is not None)
2144
+
2145
+
2146
+ def terminals_redeclare(text, name, lane_id):
2147
+ """terminals.json with the `terminals[]` row of the DANGLING binding `name` put back (BEY-7435): one item
2148
+ `{name, command: "exec /home/coder/.lz/bin/lane open <lane_id>"}` appended — cursor-sync's shape, the declared name
2149
+ the binding is keyed by, so the host gives the lane the id it had (`lane_id`: the binding's recorded `id`, else the
2150
+ one `lanes sync` derives from the name) and the binding's exact tmux target. The binding itself, every other row
2151
+ and the root `throttle` object are left exactly as they are. Refuses a name a row declares already
2152
+ (`duplicate_name`: nothing dangles), a name with no tmux binding in `lanes.terminals` (`not_declared_here`) and a
2153
+ session another row of the file binds (`duplicate_binding`: that would be two lanes of it)."""
2154
+ doc = strict_json(text, TERMINALS_WHAT)
2155
+ names = _terminal_names(doc)
2156
+ if name in names:
2157
+ raise LaneError(f'{TERMINALS_WHAT} declares {name!r} already: its binding has its row', 'duplicate_name')
2158
+ entries = _lanes_terminals(doc) or {}
2159
+ entry = entries.get(name)
2160
+ pair = _binding(entry)
2161
+ if pair is None:
2162
+ raise LaneError(f'{TERMINALS_WHAT} holds no lanes.terminals tmux binding named {name!r}', 'not_declared_here')
2163
+ for block in (entries, ((doc.get('throttle') or {}).get('terminals') or {})):
2164
+ held = [other for other, value in (block.items() if isinstance(block, dict) else ())
2165
+ if other != name and other in names and _binding(value) == pair]
2166
+ if held:
2167
+ raise LaneError(f'{TERMINALS_WHAT} declares tmux {pair[0]}/{pair[1]} already (as {held[0]!r})',
2168
+ 'duplicate_binding')
2169
+ if not isinstance(lane_id, str) or not LANE_RE.fullmatch(lane_id):
2170
+ raise LaneError(f'{lane_id!r} is no lane id', 'edit_refused')
2171
+ terminal = {'name': name, 'command': LANE_OPEN_COMMAND + lane_id}
2172
+ root = scan(text)
2173
+ after = _append(text, root, root.get('terminals'), lambda indent, unit: _render(terminal, indent, unit))
2174
+ parsed = strict_json(after, TERMINALS_WHAT)
2175
+ _check_terminals(doc, parsed, names + [name])
2176
+ if (_lanes_terminals(parsed) or {}).get(name) != entry:
2177
+ raise LaneError('refused: the edit did not land where it should', 'edit_refused')
2178
+ return after
2179
+
2180
+
2181
+ # One writer at a time per terminals.json (BEY-7435). A registry rewrite that read the file before another writer's
2182
+ # write and replaced it after dropped that writer's row (MEASURED 2026-11-07 13:41Z on a live registry: a declared
2183
+ # lane's `terminals[]` row was gone, its `lanes.terminals` binding survived, its session showed as unregistered). Every
2184
+ # writer — lane-mcp in the container, the host's editors through the container's home volume: one kernel, one lock —
2185
+ # edits through `update_terminals`, which holds an flock on the sidecar `.<name>.lock` across its re-read and its
2186
+ # write. The sidecar lives only while a writer holds it: the holder unlinks it before it lets go, and a writer that won
2187
+ # the lock on a name that no longer leads to its inode opens the name afresh, so two writers never hold two inodes at
2188
+ # once, and no repository keeps a stray file.
2189
+ TERMINALS_LOCK_WAIT = 10.0 # s a writer waits for another one's edit (each holds the lock for milliseconds)
2190
+
2191
+
2192
+ def terminals_lock_path(path):
2193
+ """The sidecar lock of a terminals.json: `.<file name>.lock` in the same directory, present only while held."""
2194
+ path = Path(path)
2195
+ return path.with_name('.' + path.name + '.lock')
2196
+
2197
+
2198
+ def _open_lock(lock, path):
2199
+ """A descriptor of the sidecar `lock` (created when absent), never through a symbolic link and never blocking on
2200
+ a FIFO; read-only when another account's sidecar is there (flock needs no write access). LaneError otherwise: a
2201
+ directory that does not exist is `source_missing`, one this account cannot create the sidecar in (no sidecar
2202
+ there, or a read-only filesystem) `source_unwritable`, a link `source_link`, anything else `source_unreadable`."""
2203
+ flags = getattr(os, 'O_NOFOLLOW', 0) | getattr(os, 'O_CLOEXEC', 0) | getattr(os, 'O_NONBLOCK', 0)
2204
+ try:
2205
+ return os.open(str(lock), os.O_RDWR | os.O_CREAT | flags, 0o644)
2206
+ except OSError as error:
2207
+ failed = error
2208
+ if failed.errno in UNWRITABLE:
2209
+ try:
2210
+ return os.open(str(lock), os.O_RDONLY | flags)
2211
+ except FileNotFoundError:
2212
+ raise LaneError(f'{path.parent} is not writable by this account: the lock (and the edited file) are '
2213
+ 'created there — nothing written', 'source_unwritable') from None
2214
+ except OSError as error:
2215
+ failed = error
2216
+ if failed.errno == errno.ELOOP:
2217
+ raise LaneError(f'{lock} is a symbolic link — left alone', 'source_link') from None
2218
+ if failed.errno == errno.ENOENT:
2219
+ raise LaneError(f'{path.parent} does not exist — nothing written', 'source_missing') from None
2220
+ raise LaneError(f'{lock}: the lock of {path.name} cannot be opened ({failed.strerror or failed}) — nothing '
2221
+ 'written', 'source_unreadable') from None
2222
+
2223
+
2224
+ @contextlib.contextmanager
2225
+ def terminals_lock(path, root=None, wait=TERMINALS_LOCK_WAIT):
2226
+ """The exclusive advisory lock of one terminals.json while the block runs: an flock on terminals_lock_path(path),
2227
+ the sidecar created on entry and unlinked on exit while still held. Waits up to `wait` s for another writer, then
2228
+ refuses `edit_conflict`, nothing written. A symbolic link or anything but a regular file at the sidecar's name
2229
+ refuses (`source_link`, `source_unreadable`), and with `root` so does a link at or above it below `root` (the host
2230
+ reaches the file through a container's home volume: the DEF-1796 class)."""
2231
+ path = Path(path)
2232
+ lock = terminals_lock_path(path)
2233
+ deadline = time.monotonic() + wait
2234
+ while True:
2235
+ if root is not None:
2236
+ no_links(root, lock)
2237
+ fd = _open_lock(lock, path)
2238
+ try:
2239
+ if not stat.S_ISREG(os.fstat(fd).st_mode):
2240
+ raise LaneError(f'{lock} is not a regular file — left alone', 'source_unreadable')
2241
+ while True:
2242
+ try:
2243
+ fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
2244
+ break
2245
+ except BlockingIOError:
2246
+ if time.monotonic() >= deadline:
2247
+ raise LaneError(f'{path} is being edited by another writer (its lock {lock.name} was held '
2248
+ f'for {wait:g} s) — nothing written; run it again', 'edit_conflict') from None
2249
+ time.sleep(0.005)
2250
+ mine = os.fstat(fd)
2251
+ try:
2252
+ named = os.lstat(str(lock))
2253
+ except FileNotFoundError:
2254
+ named = None
2255
+ if named is not None and (named.st_dev, named.st_ino) == (mine.st_dev, mine.st_ino):
2256
+ try:
2257
+ yield lock
2258
+ finally:
2259
+ try:
2260
+ os.unlink(str(lock))
2261
+ except OSError:
2262
+ pass
2263
+ return
2264
+ finally:
2265
+ os.close(fd)
2266
+ # The writer before us unlinked the name while we waited on its inode: lock the name's file afresh.
2267
+
2268
+
2269
+ def terminals_rows(text):
2270
+ """(row names, `lanes.terminals` binding names, root `throttle.terminals` binding names) of a terminals.json's
2271
+ text: every family a lane is declared or bound by. Three empty sets for a missing file (None) or a text that is no
2272
+ JSON object."""
2273
+ try:
2274
+ doc = json.loads(text) if text is not None else None
2275
+ except ValueError:
2276
+ doc = None
2277
+ if not isinstance(doc, dict):
2278
+ return set(), set(), set()
2279
+ terminals = doc.get('terminals')
2280
+ rows = ({item['name'] for item in terminals if isinstance(item, dict) and isinstance(item.get('name'), str)}
2281
+ if isinstance(terminals, list) else set())
2282
+ throttle = doc.get('throttle')
2283
+ annotated = throttle.get('terminals') if isinstance(throttle, dict) else None
2284
+ return rows, set(_lanes_terminals(doc) or ()), set(annotated) if isinstance(annotated, dict) else set()
2285
+
2286
+
2287
+ def _binding_ids(*texts):
2288
+ """{declared name: the lane id its `lanes.terminals` entry records} over terminals.json texts (the first wins)."""
2289
+ ids = {}
2290
+ for text in texts:
2291
+ try:
2292
+ doc = json.loads(text) if text is not None else None
2293
+ except ValueError:
2294
+ continue
2295
+ if isinstance(doc, dict):
2296
+ for name, entry in (_lanes_terminals(doc) or {}).items():
2297
+ if isinstance(entry, dict) and isinstance(entry.get('id'), str):
2298
+ ids.setdefault(name, entry['id'])
2299
+ return ids
2300
+
2301
+
2302
+ UNWRITABLE = (errno.EACCES, errno.EPERM, errno.EROFS)
2303
+
2304
+
2305
+ def update_terminals(path, mutate, root=None, removes=(), new_mode=0o644, wait=TERMINALS_LOCK_WAIT):
2306
+ """THE writer of a terminals.json (BEY-7435) -> (before, after); before == after means nothing was written.
2307
+
2308
+ Lock and merge: the exclusive lock (terminals_lock), the file read UNDER it, and `mutate(text or None)` applies
2309
+ only the caller's own delta to those bytes (a terminals_* transform: append, remove or set one entry), so whatever
2310
+ another writer wrote before is kept. Refused, nothing written (`registry_row_vanished`, naming each one and the
2311
+ lane id its binding records), when a `terminals[]` row, a `lanes.terminals` binding or a root `throttle.terminals`
2312
+ binding of the file as read under the lock would be gone although the caller's delta does not remove it
2313
+ (`removes`: the declared names it takes out; Throttle's annotations are never a Lanes writer's to remove): a delta
2314
+ computed from stale bytes, or one that drops more than its own entry, never silently loses a lane. The check reads
2315
+ the file under the lock only, so another locked writer's unregister made a moment earlier is no refusal. Written
2316
+ like edit_file (temp file in the same directory, fsync, rename, the file's mode kept, `new_mode` for a new one) plus
2317
+ a directory fsync; `source_unwritable` when this account cannot write in the directory; with `root`, a symbolic
2318
+ link at or above the file or its lock below `root` refuses (`source_link`). A writer that bypasses the lock is out
2319
+ of its reach (BEY-7435 follow-ups: the Rust native `lanes unregister` and `lanes cursor-sync`,
2320
+ scripts/propose-terminal-annotations.py --write, and a container still on a lane-mcp from before this lock)."""
2321
+ path = Path(path)
2322
+ with terminals_lock(path, root, wait):
2323
+ ident, before = _snapshot(path, root)
2324
+ after = mutate(before)
2325
+ if after == before:
2326
+ return before, after
2327
+ declared = set(removes)
2328
+ rows_now, bindings_now, annotated_now = terminals_rows(before)
2329
+ rows_after, bindings_after, annotated_after = terminals_rows(after)
2330
+ rows_lost = rows_now - declared - rows_after
2331
+ bindings_lost = bindings_now - declared - bindings_after
2332
+ annotations_lost = annotated_now - annotated_after
2333
+ if rows_lost or bindings_lost or annotations_lost:
2334
+ ids = _binding_ids(before)
2335
+ lost = [{'name': name, 'id': ids.get(name), 'row': name in rows_lost, 'binding': name in bindings_lost,
2336
+ 'throttle': name in annotations_lost}
2337
+ for name in sorted(rows_lost | bindings_lost | annotations_lost)]
2338
+ said = ', '.join(repr(item['name']) + (f' ({item["id"]})' if item['id'] else '') for item in lost)
2339
+ raise _refusal(f'refused: {said} would vanish from {path} — a row or binding this edit does not remove — '
2340
+ 'nothing written; `lanes doctor` names a binding left without its row, `lanes register` '
2341
+ 'repairs it', 'registry_row_vanished', vanished=lost)
2342
+ if root is not None:
2343
+ no_links(root, path)
2344
+ try:
2345
+ atomic_replace(path, after, ident[3] if ident else new_mode, sync_dir=True)
2346
+ except OSError as error:
2347
+ if error.errno in UNWRITABLE:
2348
+ raise LaneError(f'{path.parent} is not writable by this account ({error.strerror or error}) — '
2349
+ 'nothing written', 'source_unwritable') from None
2350
+ raise
2351
+ return before, after
2352
+
2353
+
1760
2354
  # ------------------------------------------------------------------------------------------------ MCP entries
1761
2355
 
1762
2356
  MCP_NAME = 'lanes'
@@ -2500,59 +3094,84 @@ def latest_receipt(root, lane):
2500
3094
  # adapter is tried;
2501
3095
  # 2. the recipient is a Codex thread — its hooks recorded the id, or (W15 L3) its app-server names the one thread
2502
3096
  # that fits the lane, asked now with the recipient's own context (handle(…, fresh=True)) — and `codex` is on PATH:
2503
- # `codex queue --thread <id> --message <envelope>` (served at the thread's next turn). A Codex lane whose
3097
+ # `codex queue --thread <id> --message <pointer>` (served at the thread's next turn). The pointer
3098
+ # (ENVELOPE_POINTER, BEY-8673 D) names the message's id and `~/.lz/bin/lane inbox ack <id>`, never its text: the
3099
+ # text waits in the record and leaves it on the one ack that answers it, so a turn codex serves again takes
3100
+ # nothing twice. A Codex lane whose
2504
3101
  # app-server names several threads (`handle_ambiguous`) or cannot be asked (`handle_unavailable`) gets no thread
2505
3102
  # and nothing typed: refused, or queued with `queue`;
2506
3103
  # 3. LANES_BUS=throttle in the sender's environment and the recipient runs an agent: POST `{to, from, text, ttl_s}`
2507
3104
  # to Throttle's CONTROL listener (127.0.0.1:$LANES_THROTTLE_CONTROL_PORT, else 19181) with the sending harness's
2508
3105
  # own client token (`throttle client-token <pool>`; BEY-6869 — the endpoint is the Throttle lane's, so the
2509
3106
  # adapter is off unless switched on);
2510
- # 4. the recipient's handle is `lane` and it is idle — an agent at its prompt (needs_input, idle, done; not
2511
- # delegating), or a shell at its prompt, which gets the envelope as a comment line (SHELL_COMMENT): typed, under
2512
- # the recipient's dispatch lock (dispatch_lock), after a final recheck there — a fresh observation, the same agent
2513
- # as when it was addressed, still idle, no older message waiting in its inbox (those are typed first: FIFO);
2514
- # 5. else, with `queue`, the message waits in the recipient's inbox (`queued`; lanes-statusd types it when the lane
2515
- # is next idle with no terminal attached), and without it the call is refused `recipient_busy`.
3107
+ # 4. (BEY-7538, 2026-11-08: messages never type into a terminal) the recipient's handle is `lane` and no adapter
3108
+ # above reached it — an agent no bus serves, a pane without an agent: its keyboard is the only way in, and that is
3109
+ # a person's (lanes_send, `lane send`), never a message's. Refused `transport_never_types`, or queued with `queue`;
3110
+ # nothing is typed, and no dispatch lock is taken;
3111
+ # 5. else, with `queue`, the message waits in the recipient's inbox (`queued`) until its agent reads it there
3112
+ # (lanes_status `inbox`, `lane inbox`, taken by lanes_message_ack / `lane inbox ack`, which answer its text once;
3113
+ # the boards count it as ✉) — nothing on the host types it — and without it the call is refused
3114
+ # `recipient_busy`.
2516
3115
  # An adapter that applies and provably took nothing (it could not start, the connection was refused, it answered a
2517
- # refusal) refuses with its own code (`peer_socket_failed`, `codex_queue_failed`, `bus_unavailable`, a tmux code), or
3116
+ # refusal) refuses with its own code (`peer_socket_failed`, `codex_queue_failed`, `bus_unavailable`), or
2518
3117
  # queues when `queue` is true. An adapter that may have taken it — `codex queue` timed out or exited non-zero (its exit
2519
3118
  # codes are not measured: its own answer can time out after the app-server queued it), Throttle's answer was lost or
2520
3119
  # unreadable after the request went out — is `unknown` (the review's 49907f8b): the record keeps its text and an
2521
3120
  # `attempt` {op, adapter, at, outcome, recipient}, the receipt says `unknown`, and nothing sends it again — no other
2522
- # adapter, no lanes-statusd drain — until a person retries it (`lane inbox retry <id> --duplicate-risk`, message_retry)
2523
- # or the recipient acknowledges it. A message from another lane is never a person's consent. A frame lane-peerd takes on a virtual peer's socket comes in as `inbound` (its sender a lane of this
2524
- # container, else `peer:<name>`): never refused `use_send_message` (it came by SendMessage) and always queued rather
2525
- # than refused, so a frame its sender already counts as sent is never dropped.
3121
+ # adapter, nothing on the host — until a person retries it (`lane inbox retry <id> --duplicate-risk`, message_retry)
3122
+ # or the recipient acknowledges it. A message from another lane is never a person's consent. A frame lane-peerd takes
3123
+ # on a virtual peer's socket comes in as `inbound` (its sender a lane of this container, else `peer:<name>`): never
3124
+ # refused `use_send_message` (it came by SendMessage) and always queued rather than refused, so a frame its sender
3125
+ # already counts as sent is never dropped.
2526
3126
 
2527
3127
  MESSAGE_MAX = 4000 # = lane-mcp SEND_MAX: the text, before its envelope
2528
3128
  MESSAGE_TTL_S, MESSAGE_TTL_MIN, MESSAGE_TTL_MAX = 86400, 60, 7 * 86400
2529
3129
  INBOX_DIR = ('state', 'inbox') # under ~/.lz: <lane>/<id>.json, <lane>/<id>.receipt.json, log
3130
+ OUTBOX_DIR = ('state', 'outbox') # DM-LANES-OUTBOX: <sender lane>/<id>.json + receipt, for a lane of
3131
+ # another container; the site's bridge carries it (lane outbox pending)
3132
+ BRIDGE_ORIGIN_RE = re.compile(r'[A-Za-z0-9][A-Za-z0-9_.-]{0,63}') # a container's name, as the bridge says it
2530
3133
  INBOX_LOG = 'log'
2531
3134
  INBOX_LOG_MAX = 1 << 20 # rotated to log.1 past this
2532
3135
  INBOX_FILE_MAX = 64 << 10 # a record or receipt bigger than this is not ours
2533
3136
  INBOX_SCAN_MAX = 512 # settled messages (history) a reader lists, the newest; never fewer
2534
3137
  # than every message that is not settled (settled())
2535
3138
  MESSAGE_SUFFIX = '.json'
2536
- # The envelope every adapter delivers (one constant: the receipt, the log and the reply all follow from it). A person's
3139
+ # The envelope every adapter but `codex queue` delivers (one constant: the receipt, the log and the reply all follow from
3140
+ # it; codex queue carries ENVELOPE_POINTER below). A person's
2537
3141
  # message (`lanes message` on the host, the sidebar's `m`) has no address to reply to: ENVELOPE_PERSON.
2538
3142
  ENVELOPE = '[lanes message from @{sender} ({handle}) {hhmm}Z] {text} — reply: lane message @{sender} "…"'
2539
3143
  ENVELOPE_PERSON = '[lanes message from {sender} (a person) {hhmm}Z] {text}'
2540
3144
  ENVELOPE_PEER = '[lanes message from {sender} (a Claude session outside the lanes) {hhmm}Z] {text}' # W15 L6
2541
- SHELL_COMMENT = '# ' # typed into a shell at its prompt: one comment line, nothing runs (bash's `#`)
2542
- TYPED_SHELLS = ('bash', 'sh', 'dash') # a pane whose foreground command is one of these sits at a prompt
2543
- IDLE_WORDS = ('needs_input', 'idle', 'done') # an agent at its prompt (= lanes_lib.NAMES_IDLE)
2544
- BUSY_WORDS = ('working', 'needs_approval') # a hook sidecar saying one of these: not idle, whatever else says
3145
+ # BEY-8673 mechanism D: what the Codex adapter queues instead (envelope_pointer) — the message's id and how to take its
3146
+ # text, never the text. `codex queue` serves it as a fresh user turn and may serve it again after the lane took the
3147
+ # message from its inbox; the text leaves the inbox on the ONE ack that answers it (message_ack's `text`), so a pointer
3148
+ # served twice takes nothing the second time. The per-call CLI comes FIRST: it runs the installed lane_core on every
3149
+ # call, while a lane-mcp started before an install keeps its old message_ack, which removes the text and answers none.
3150
+ # LIMIT: a lane that reads the inbox FILE without acking and is then served the pointer gets the text once more; the
3151
+ # pointer names the id so it can tell, but nothing mechanical stops it.
3152
+ POINTER_TAKE = ('Take its text with `~/.lz/bin/lane inbox ack {id}` (it answers the text once; lanes_message_ack {id} '
3153
+ 'does too in a current session). If you have taken {id} already, there is nothing to do.')
3154
+ ENVELOPE_POINTER = '[lanes message {id} from @{sender} ({handle}) {hhmm}Z] ' + POINTER_TAKE
3155
+ ENVELOPE_POINTER_PERSON = '[lanes message {id} from {sender} (a person) {hhmm}Z] ' + POINTER_TAKE
3156
+ ENVELOPE_POINTER_PEER = '[lanes message {id} from {sender} (a Claude session outside the lanes) {hhmm}Z] ' + POINTER_TAKE
2545
3157
  # delivered_by -> (picked_up_by, expected_within_s): what lanes_message answers per adapter. `next_turn`: the
2546
- # recipient's harness serves it at its next turn; `when_idle`: lanes-statusd types it when the lane is next idle.
3158
+ # recipient's harness serves it at its next turn; `when_idle`: it waits in the recipient's inbox until its agent reads
3159
+ # it (the word is wire v1's; since BEY-7538 nothing types it, the host included).
2547
3160
  DELIVERY = {'peer_socket': ('the Claude session itself: its transcript, mid-turn', 0),
2548
3161
  'codex_queue': ('codex queue: the thread\'s next turn', 'next_turn'),
2549
3162
  'throttle_turn': ('Throttle: the recipient\'s next model request', 'next_turn'),
2550
- 'typed': ('the program in the lane\'s active pane', 0),
2551
- 'queued': ('lanes-statusd: typed when the lane is next idle', 'when_idle')}
3163
+ 'queued': ('the lane\'s inbox: its agent reads it there (lanes_status `inbox`, `lane inbox`) — never typed',
3164
+ 'when_idle'),
3165
+ 'outbox': ('the site\'s lane bridge: carried into the recipient\'s inbox on its own container, where it '
3166
+ 'waits for the lane\'s agent (DM-LANES-OUTBOX)', 'bridge')}
3167
+ # `typed` (W15 L4 until BEY-7538) is a receipt word no adapter writes any more: a message typed into a lane before the
3168
+ # ruling keeps its receipt, which every reader still reads (and inbox_summary counts as delivered: it was).
3169
+ HISTORICAL = ('typed',)
2552
3170
  # A receipt's `delivered_by`: an adapter, `queued` while it waits, `inbox` when the recipient took it from its inbox
2553
3171
  # itself (`lanes_message_ack`), `expired` when its ttl passed undelivered, `unknown` (W15 part 2, additive) when an
2554
3172
  # adapter may have taken it and its answer never came: held, never sent again by Lanes on its own.
2555
- RECEIPT_STATES = tuple(DELIVERY) + ('inbox', 'expired', 'unknown')
3173
+ RECEIPT_STATES = tuple(DELIVERY) + HISTORICAL + ('inbox', 'expired', 'unknown', 'bridged') # `bridged`: an outbox
3174
+ # record's last word (DM-LANES-OUTBOX)
2556
3175
  UNCONFIRMED = ('nobody: it may have arrived (the adapter\'s answer was lost) — held, never sent again by Lanes; a '
2557
3176
  'person retries it (lane inbox retry <id> --duplicate-risk) or the recipient acknowledges it', None)
2558
3177
  DELIVERED = ('peer_socket', 'codex_queue', 'throttle_turn', 'typed', 'inbox') # what inbox_summary's `delivered` counts
@@ -2625,6 +3244,19 @@ def envelope(sender, sender_handle, text, at):
2625
3244
  return ENVELOPE.format(sender=sender, handle=sender_handle, hhmm=hhmm, text=text)
2626
3245
 
2627
3246
 
3247
+ def envelope_pointer(sender, sender_handle, message_id, at):
3248
+ """BEY-8673 D: the pointer the Codex adapter queues for message `message_id` — ENVELOPE_POINTER, or for a person's
3249
+ `host:<login>` ENVELOPE_POINTER_PERSON and for a Claude session outside the lanes ENVELOPE_POINTER_PEER, as
3250
+ envelope() picks — naming the id and how to take its text (`lane inbox ack <id>` first, then lanes_message_ack),
3251
+ never the text."""
3252
+ hhmm = time.strftime('%H:%M', time.gmtime(at))
3253
+ if HOST_SENDER.fullmatch(sender or ''):
3254
+ return ENVELOPE_POINTER_PERSON.format(id=message_id, sender=sender, hhmm=hhmm)
3255
+ if PEER_SENDER.fullmatch(sender or ''):
3256
+ return ENVELOPE_POINTER_PEER.format(id=message_id, sender=sender, hhmm=hhmm)
3257
+ return ENVELOPE_POINTER.format(id=message_id, sender=sender, handle=sender_handle, hhmm=hhmm)
3258
+
3259
+
2628
3260
  def _open_dir(root, parts, create=False, keep=0):
2629
3261
  """fd of root/<parts…>: `root` opened as given (trusted: ~/.lz in the container, the home volume or
2630
3262
  /proc/<pid>/root on the host), every part a REAL directory — a symbolic link is refused (OSError), never
@@ -2662,6 +3294,13 @@ def inbox_fd(root, lane=None, create=False, prefix=()):
2662
3294
  return _open_dir(root, tuple(prefix) + INBOX_DIR + ((lane,) if lane else ()), create, keep=len(tuple(prefix)))
2663
3295
 
2664
3296
 
3297
+ def outbox_fd(root, lane=None, create=False, prefix=()):
3298
+ """fd of <root>/<prefix…>/state/outbox[/<sender lane>] (DM-LANES-OUTBOX), as inbox_fd."""
3299
+ if lane is not None and not (isinstance(lane, str) and LANE_RE.fullmatch(lane)):
3300
+ raise OSError(f'invalid lane id {lane!r}')
3301
+ return _open_dir(root, tuple(prefix) + OUTBOX_DIR + ((lane,) if lane else ()), create, keep=len(tuple(prefix)))
3302
+
3303
+
2665
3304
  def _read_at(dir_fd, name, limit=INBOX_FILE_MAX):
2666
3305
  """The JSON document of `name` in `dir_fd` when it is a regular file of at most `limit` bytes holding one, else
2667
3306
  None. Never follows a link, never blocks on a FIFO."""
@@ -2776,7 +3415,7 @@ def cleared_receipt(receipt, record, message_id, at):
2776
3415
  state = (receipt or {}).get('delivered_by')
2777
3416
  if state in ('queued', 'unknown', None) and record.get('acked'):
2778
3417
  state = 'inbox'
2779
- elif state in ('queued', None):
3418
+ elif state in ('queued', 'outbox', None):
2780
3419
  state = 'expired'
2781
3420
  if receipt is not None and state == receipt.get('delivered_by'):
2782
3421
  out = dict(receipt)
@@ -2903,6 +3542,35 @@ def held(entry):
2903
3542
  return receipt.get('delivered_by') == 'unknown' and not settled(receipt)
2904
3543
 
2905
3544
 
3545
+ # BEY-8673: the receipt words that say an adapter handed the message to the lane's agent itself — its Claude session
3546
+ # (mid-turn), its Codex thread's queue (served at the thread's next turn), Throttle (its next model request), or its
3547
+ # keyboard before BEY-7538 (`typed`).
3548
+ DELIVERED_TO_AGENT = ('peer_socket', 'codex_queue', 'throttle_turn', 'typed')
3549
+
3550
+
3551
+ def inbox_state(entry, now):
3552
+ """Where one inbox entry stands for its reader (BEY-8673; `lane inbox --json`'s additive `state`): `on_its_way`
3553
+ (no receipt yet), `settled` (its text is gone: acknowledged, purged, bridged), `held` (`unknown`), `waiting`
3554
+ (`queued`, its ttl not passed), `expired` (`queued`, its ttl passed and its text not purged yet) or `delivered` (an
3555
+ adapter of DELIVERED_TO_AGENT handed it to the agent and its text is still kept). A delivered message is history:
3556
+ the agent has it, or its thread's next turn brings it — a reader never lists it as an order to carry out (a resumed
3557
+ Codex lane once read every order its thread had been handed, oldest first, and carried them out again, 18-19 Nov
3558
+ 2026). Any other word that still holds a text reads `waiting`, so no reader loses words it may not have."""
3559
+ receipt = entry.get('receipt')
3560
+ if not isinstance(receipt, dict):
3561
+ return 'on_its_way'
3562
+ if settled(receipt):
3563
+ return 'settled'
3564
+ word, kept = receipt.get('delivered_by'), isinstance((entry.get('record') or {}).get('text'), str)
3565
+ if word == 'unknown':
3566
+ return 'held'
3567
+ if not kept:
3568
+ return 'settled'
3569
+ if word == 'queued' and expired(entry, now):
3570
+ return 'expired'
3571
+ return 'delivered' if word in DELIVERED_TO_AGENT else 'waiting'
3572
+
3573
+
2906
3574
  def inbox_counts(root, lane, now=None, prefix=()):
2907
3575
  """{'pending', 'unknown'}: how many messages wait in `lane`'s inbox (pending()) and how many are held (held()) —
2908
3576
  counted over every message that is not settled, never over a window of the history."""
@@ -2934,7 +3602,8 @@ def inbox_summary(root, lane, now=None, prefix=()):
2934
3602
  out = {'pending': sum(1 for entry in entries if pending(entry, now)),
2935
3603
  'delivered': sum(1 for found in receipts.values() if found.get('delivered_by') in DELIVERED),
2936
3604
  'last': {'id': newest['id'], 'from': record.get('from'), 'at': record.get('at') or receipt.get('at'),
2937
- 'delivered_by': receipt.get('delivered_by')}}
3605
+ 'delivered_by': receipt.get('delivered_by'),
3606
+ **({'origin': record['origin']} if isinstance(record.get('origin'), dict) else {})}}
2938
3607
  unknown = sum(1 for entry in entries if held(entry))
2939
3608
  if unknown:
2940
3609
  out['unknown'] = unknown
@@ -2947,11 +3616,13 @@ def inbox_pending(root, lane, now=None, prefix=()):
2947
3616
 
2948
3617
 
2949
3618
  def message_ack(root, lane, message_id, now=None):
2950
- """`lanes_message_ack` / `lane inbox ack <id>`: the recipient has the message -> {id, lane, from, delivered_by,
2951
- acked, changed}. Its record keeps its metadata and loses its text (`acked` added) FIRST; then its receipt says so
2952
- (cleared_receipt: `cleared`, and a message still `queued` or held `unknown` is the recipient's own take, `inbox`, so
2953
- lanes-statusd never types it). Refused `unknown_message` for an id this lane's inbox does not hold. Acking twice
2954
- changes nothing — except finishing an ack that stopped between its two writes."""
3619
+ """`lanes_message_ack` / `lane inbox ack <id>`: the recipient takes the message -> {id, lane, from, delivered_by,
3620
+ acked, text, changed}. Its record keeps its metadata and loses its text (`acked` added) FIRST; then its receipt says
3621
+ so (cleared_receipt: `cleared`, and a message still `queued` or held `unknown` is the recipient's own take, `inbox`,
3622
+ so nothing counts it as waiting any more). The call that removes the text answers it (`text`, BEY-8673 D): taking a
3623
+ message is that one recorded act, and the Codex adapter's pointer leads here. Refused `unknown_message` for an id
3624
+ this lane's inbox does not hold. Acking twice changes nothing and answers no `text` (`nothing: acknowledged
3625
+ already`) — except finishing an ack that stopped between its two writes."""
2955
3626
  now = time.time() if now is None else now
2956
3627
  if not isinstance(message_id, str) or not PUBLISH_ID.fullmatch(message_id):
2957
3628
  raise LaneError(f'{message_id!r} is not a message id', 'unknown_message')
@@ -2982,15 +3653,17 @@ def message_ack(root, lane, message_id, now=None):
2982
3653
  append_log(root, log_line(now, record.get('from'), record.get('to'), message_id,
2983
3654
  len(record['text'].encode('utf-8')), 'acked'))
2984
3655
  return {'id': message_id, 'lane': lane, 'from': record.get('from'), 'delivered_by': state, 'acked': kept['acked'],
2985
- 'changed': f'{LZ}/{"/".join(INBOX_DIR)}/{lane}/{message_id}{MESSAGE_SUFFIX}: the text removed, its '
2986
- 'metadata and receipt kept'}
3656
+ 'text': record['text'],
3657
+ 'changed': f'{LZ}/{"/".join(INBOX_DIR)}/{lane}/{message_id}{MESSAGE_SUFFIX}: the text removed and answered '
3658
+ 'here (once), its metadata and receipt kept'}
2987
3659
 
2988
3660
 
2989
3661
  def message_retry(root, lane, message_id, duplicate_risk=False, now=None):
2990
3662
  """`lane inbox retry <id> --duplicate-risk` (W15 part 2): a person hands a held message (receipt `unknown`) back to
2991
- the inbox -> {id, lane, from, delivered_by: queued, retry, changed}. Its receipt becomes `queued` — lanes-statusd
2992
- types it when the lane is next idle — and its record gains `retry: {at, duplicate_risk: true}`: the adapter may
2993
- have delivered it already, so it may arrive twice, which `duplicate_risk` says the person accepts. Refused
3663
+ the inbox -> {id, lane, from, delivered_by: queued, retry, changed}. Its receipt becomes `queued` — it waits in the
3664
+ inbox again until the recipient's agent reads it (never typed, BEY-7538) — and its record gains `retry: {at,
3665
+ duplicate_risk: true}`: the adapter may have delivered it already, so it may arrive twice, which `duplicate_risk`
3666
+ says the person accepts. Refused
2994
3667
  `unknown_message` (no such message), `not_held` (it is not `unknown`, or its text is gone or its ttl passed) and
2995
3668
  `duplicate_risk` (without the person's word)."""
2996
3669
  now = time.time() if now is None else now
@@ -3158,13 +3831,14 @@ def bus_post(environ, home, harness, sender_trace, to_trace, text, ttl_s, timeou
3158
3831
  # W15 part 2 (the PR #544 review 8d91d073; Linear BEY-6842, BEY-6843; DM-LANES-DISPATCH-LOCK). Native input — a text and
3159
3832
  # its Enter typed into a lane's pane, ENTER_DELAY s apart — has ONE authority per recipient: an exclusive flock(2) on
3160
3833
  # the container file ~/.lz/state/dispatch/<lane id>.lock (the directory 0700, the file 0600, both created when absent
3161
- # and owned like ~/.lz/state, no component a link). Every writer takes it: lane_core.message's typed adapter (`lane
3162
- # message`, lanes_message, lane-peerd's handler threads — flock conflicts between two opens of one file in one process
3163
- # too), lanes_send and `lane send`, and on the host lanes-statusd (the inbox drain, `lanes message`; the automatic
3164
- # `/rename` of W15 part 1 follows the same convention), which reaches the same inode through
3165
- # /proc/<init pid>/root/home/coder/.lz/state/dispatch/<lane id>.lock.
3166
- # A writer waits at most DISPATCH_WAIT_S, then refuses `recipient_busy` (or queues), and holds it across its final
3167
- # readiness recheck, the text, the Enter and — for a waiting message — its settled receipt. The lock is the file's
3834
+ # and owned like ~/.lz/state, no component a link). Every writer takes it — and since BEY-7538 (2026-11-08) every
3835
+ # writer is a person's typing, never a message: lanes_send and `lane send` in the container, and on the host the
3836
+ # automatic `/rename` of W15 part 1 (lanes_lib.dispatch_lock) and a guest's `tmux_write` (site/server.py, a person's
3837
+ # paste through lanes_lib.lane_write), which reach the same inode through
3838
+ # /proc/<init pid>/root/home/coder/.lz/state/dispatch/<lane id>.lock. lane_core.message, lane-peerd and lanes-statusd's
3839
+ # inbox pass type nothing and take no lock.
3840
+ # A writer waits at most DISPATCH_WAIT_S, then refuses `recipient_busy`, and holds it across its final readiness
3841
+ # recheck, the text and the Enter. The lock is the file's
3168
3842
  # flock, never its content: nothing is written into it and it is never removed; closing the fd releases it.
3169
3843
  DISPATCH_DIR = ('state', 'dispatch')
3170
3844
  DISPATCH_SUFFIX = '.lock'
@@ -3249,41 +3923,6 @@ def dispatch_lock(root, lane, prefix=(), wait=None):
3249
3923
  os.close(fd)
3250
3924
 
3251
3925
 
3252
- def generation(row):
3253
- """Who answers in a lane, as a status.json row says: (harness, pid, session id) of its agent, Nones without one. A
3254
- writer that waited for the dispatch lock types nothing when this moved (the agent was replaced meanwhile)."""
3255
- agent = row.get('agent') if isinstance(row, dict) and isinstance(row.get('agent'), dict) else {}
3256
- return agent.get('harness'), agent.get('pid'), agent.get('session_id')
3257
-
3258
-
3259
- def recipient_idle(found, observed, hook, status_fresh):
3260
- """Adapter 4's rule -> (idle, why not). Never on an observation that is not fresh or a kept (`stale`) row, never
3261
- while the lane's hook sidecar says working or needs_approval. An agent: its status one of IDLE_WORDS and not
3262
- delegating. No agent (a `typed` handle): no output within statusd's active window (state not `active`); the shell
3263
- at its prompt is asked of tmux when typing."""
3264
- if not status_fresh or observed.get('stale'):
3265
- return False, 'the host\'s observation of it is not fresh'
3266
- if isinstance(hook, dict) and hook.get('status') in BUSY_WORDS:
3267
- return False, f'its lane-signal hook says {hook["status"]}'
3268
- agent = observed.get('agent') if isinstance(observed.get('agent'), dict) else {}
3269
- if found['transport'] == 'typed':
3270
- if observed.get('state') != 'quiet':
3271
- return False, f'its pane is {observed.get("state") or "unknown"}'
3272
- return True, None
3273
- if agent.get('activity') == 'delegating':
3274
- return False, 'its agent is delegating to background work'
3275
- if agent.get('status') not in IDLE_WORDS:
3276
- return False, f'its agent is {agent.get("status") or "not observed"}'
3277
- return True, None
3278
-
3279
-
3280
- def pane_command(socket, session, run=None):
3281
- """The foreground command of the session's active pane (`#{pane_current_command}`), or None (no answer)."""
3282
- run = run or run_tmux
3283
- result = run(tmux_argv(socket, 'display', '-p', '-t', target(session), '#{pane_current_command}'))
3284
- return result.stdout.strip() if result.returncode == 0 else None
3285
-
3286
-
3287
3926
  def messaging_name(row):
3288
3927
  """The Claude messaging name a status.json row's agent{} carries (`messaging.name`), or None."""
3289
3928
  agent = row.get('agent') if isinstance(row, dict) else None
@@ -3460,6 +4099,16 @@ def peer_text(body):
3460
4099
  return text[:MESSAGE_MAX - 1] + '…', True
3461
4100
 
3462
4101
 
4102
+ def same_process(proc_root, pid, proc_start):
4103
+ """The recorded start time must match field 22 of /proc/<pid>/stat. Unreadable stat means dead.
4104
+ Shared with statusd's agent_state reader and the lane-signal writer, so PID reuse never preserves ownership."""
4105
+ try:
4106
+ stat = Path(proc_root, pid, 'stat').read_text()
4107
+ return stat.rsplit(')', 1)[1].split()[19] == str(proc_start)
4108
+ except (OSError, IndexError):
4109
+ return False
4110
+
4111
+
3463
4112
  def proc_start(proc, pid):
3464
4113
  """Field 22 (starttime) of /proc/<pid>/stat as Claude writes it into `procStart` (a string), or None."""
3465
4114
  data = read_regular(Path(proc) / str(pid) / 'stat', 1 << 16)
@@ -3477,8 +4126,10 @@ def version_tuple(text):
3477
4126
 
3478
4127
 
3479
4128
  def peer_pin_problem(document):
3480
- """Why a Claude session file is not the protocol Lanes measured (PEER_PIN: `peerProtocol` equal, `version` at
3481
- most the measured one), or None."""
4129
+ """Why a Claude session file is not the protocol Lanes measured, or None. PEER_PIN: `peerProtocol` equal, and the
4130
+ `version` on the measured minor line or before it: Claude Code 2.1.x for the measured 2.1.310. The line, not the
4131
+ patch: protocol 1 was re-measured unchanged on 2.1.327 (2026-11-19, BEY-8660), and a pin on one patch refused every
4132
+ session after Claude Code's next update. A newer minor or major line is refused until it is re-measured."""
3482
4133
  if not isinstance(document, dict):
3483
4134
  return 'no session file'
3484
4135
  if document.get('peerProtocol') != PEER_PIN['peerProtocol']:
@@ -3486,9 +4137,10 @@ def peer_pin_problem(document):
3486
4137
  version = version_tuple(document.get('version'))
3487
4138
  if version is None:
3488
4139
  return 'its session file names no Claude Code version'
3489
- if version > version_tuple(PEER_PIN['claude']):
3490
- return (f'Claude Code {document["version"]} is newer than the measured {PEER_PIN["claude"]} (re-measure: '
3491
- 'RUNBOOK "Claude peers")')
4140
+ pinned = version_tuple(PEER_PIN['claude'])
4141
+ if version[:2] > pinned[:2]:
4142
+ return (f'Claude Code {document["version"]} is newer than the measured {pinned[0]}.{pinned[1]} line '
4143
+ f'({PEER_PIN["claude"]}, re-measured on 2.1.327; re-measure: RUNBOOK "Claude peers")')
3492
4144
  return None
3493
4145
 
3494
4146
 
@@ -3613,11 +4265,13 @@ def message(root, home, sender_lane, to, text, ttl_s=MESSAGE_TTL_S, queue=False,
3613
4265
  and after it answered; one whose answer was lost answers `delivered_by: unknown` with `not_confirmed` and the
3614
4266
  `attempt` (held: never sent again on its own). `inbound` is lane-peerd's alone (W15 L6): {'name', 'mode',
3615
4267
  'msg_id'} of a frame a virtual peer's socket took — the record then carries it as `origin` (metadata),
3616
- `sender_lane` may be `peer:<name>`, no `use_send_message` refusal applies and `queue` is implied.
4268
+ `sender_lane` may be `peer:<name>`, no `use_send_message` refusal applies and `queue` is implied. Nothing here
4269
+ types into a terminal (BEY-7538): a lane whose only way in is its keyboard gets the message in its inbox (`queue`)
4270
+ or the refusal `transport_never_types`, and no tmux client is run.
3617
4271
  Refusals (LaneError; some carry `extra`): `message_too_long`, `unprintable`, `invalid_arguments`, `not_in_lane`,
3618
4272
  the address codes, `not_in_container`, `use_coordinator`, `use_send_message`, `handle_ambiguous`,
3619
4273
  `handle_unavailable`, `peer_pin_failed`, `peer_socket_failed`, `codex_queue_failed`, `bus_unavailable`,
3620
- `tmux_failed`, `tmux_unanswered`, `recipient_busy`."""
4274
+ `transport_never_types`, `recipient_busy`."""
3621
4275
  import shutil
3622
4276
  now = time.time() if now is None else now
3623
4277
  environ = os.environ if environ is None else environ
@@ -3645,16 +4299,27 @@ def message(root, home, sender_lane, to, text, ttl_s=MESSAGE_TTL_S, queue=False,
3645
4299
  append_log(root, log_line(now, sender, address, '-', size, 'refused:' + (error.code or 'refused')))
3646
4300
  raise error
3647
4301
 
4302
+ remote = None # DM-LANES-OUTBOX: `to` names a lane of another container — its address; no entry, no session here
3648
4303
  try:
3649
4304
  lane, entry = resolve_address(root, to, export, status)
3650
4305
  except LaneError as error:
3651
- refused(error)
3652
- ghost = None if entry else next((row for row in status['unregistered'] if row['id'] == lane), None)
3653
- observed = status['lanes'].get(lane) or {}
3654
- address = address_of(lane, entry, observed, ghost) or lane
4306
+ if error.code != 'not_in_container' or peer_sender:
4307
+ refused(error)
4308
+ lane, entry, remote = None, None, fleet_admin_of(export)[0]
4309
+ ghost = None if entry or lane is None else next((row for row in status['unregistered'] if row['id'] == lane), None)
4310
+ observed = (status['lanes'].get(lane) or {}) if lane else {}
4311
+ address = remote or address_of(lane, entry, observed, ghost) or lane
3655
4312
  if entry is None and ghost is None:
3656
- refused(LaneError(f'{to} names {lane}, a lane of another container: out of reach from here',
3657
- 'not_in_container'))
4313
+ if peer_sender: # a frame lane-peerd took is for a lane of this container only
4314
+ refused(LaneError(f'{to} names {lane}, a lane of another container: out of reach from here',
4315
+ 'not_in_container'))
4316
+ if remote_routing(sender_lane, address, export):
4317
+ board = (lanes.get(sender_lane) or {}).get('ws') or board_of(sender_lane)
4318
+ coordinator = coordinator_of(export, board)
4319
+ refused(_refusal(f'@{address} is the fleet admin: it takes messages from coordinators, and {sender_lane} '
4320
+ 'is none', 'use_coordinator', fleet_admin=address,
4321
+ coordinator=address_of(coordinator, lanes.get(coordinator)) if coordinator else None))
4322
+ return outbox_write(root, sender_lane, sender, sender_handle, address, text, ttl_s, now, to_lane=lane)
3658
4323
  if routing_check(None if peer_sender else sender_lane, lane, export):
3659
4324
  board = (lanes.get(sender_lane) or {}).get('ws') or board_of(sender_lane)
3660
4325
  coordinator = coordinator_of(export, board)
@@ -3666,7 +4331,6 @@ def message(root, home, sender_lane, to, text, ttl_s=MESSAGE_TTL_S, queue=False,
3666
4331
  # hooks recorded is asked of its app-server NOW, as lanes_status shows it — never a thread a cache kept.
3667
4332
  found = handle(agent, lane, root, home, proc, fresh=True)
3668
4333
  messaging = (agent or {}).get('messaging') if isinstance((agent or {}).get('messaging'), dict) else {}
3669
- hook = hook_agent(Path(root) / 'state' / 'hooks', lane, proc)
3670
4334
  via, extra, skipped = None, {}, None
3671
4335
  # 1. Claude to a Claude session with a messaging socket: the sender's own SendMessage, never ours.
3672
4336
  name = messaging_name(observed) if harness == 'claude' and messaging.get('socket_present') is True else None
@@ -3702,7 +4366,7 @@ def message(root, home, sender_lane, to, text, ttl_s=MESSAGE_TTL_S, queue=False,
3702
4366
  if inbound: # W15 L6: how it came — by SendMessage, from which session name, in which declared mode
3703
4367
  record['origin'] = peer_origin(inbound)
3704
4368
  _write_at(directory, message_id + MESSAGE_SUFFIX, record)
3705
- body, why_not = envelope(sender, sender_handle, text, now), None
4369
+ body = envelope(sender, sender_handle, text, now)
3706
4370
  pid = (agent or {}).get('pid') if isinstance((agent or {}).get('pid'), int) else None
3707
4371
  recipient = {'lane': lane, 'harness': (agent or {}).get('harness'), 'pid': pid,
3708
4372
  'start': proc_start(proc, pid) if pid else None}
@@ -3737,7 +4401,8 @@ def message(root, home, sender_lane, to, text, ttl_s=MESSAGE_TTL_S, queue=False,
3737
4401
  and shutil.which('codex', path=({**os.environ, **environ}).get('PATH')):
3738
4402
  via, extra = 'codex_queue', {'thread': found['name']}
3739
4403
  attempt('codex_queue', 'sending', thread=found['name'])
3740
- codex_queue(found['name'], body, home, environ)
4404
+ # BEY-8673 D: the queue carries a pointer, never the text — the record keeps it until the ack.
4405
+ codex_queue(found['name'], envelope_pointer(sender, sender_handle, message_id, now), home, environ)
3741
4406
  attempt('codex_queue', 'accepted')
3742
4407
  # 3. the Throttle bus, switched on, for a lane whose agent calls a model.
3743
4408
  if via is None and bus_configured(environ) and found['transport'] != 'typed' and not peer_sender:
@@ -3749,48 +4414,8 @@ def message(root, home, sender_lane, to, text, ttl_s=MESSAGE_TTL_S, queue=False,
3749
4414
  extra = {'bus': bus_post(environ, home, harness, lane_trace(sender_lane, sender_ws) or '',
3750
4415
  lane_trace(lane, ws) or '', body, ttl_s)}
3751
4416
  attempt('throttle_turn', 'accepted', bus_id=extra['bus']['id'])
3752
- # 4. typed into an idle lane whose handle is `lane`: an agent at its prompt, or a shell at its prompt.
3753
- if via is None and found['kind'] == 'lane':
3754
- tmux = (ghost or {}).get('tmux') if isinstance((ghost or {}).get('tmux'), dict) else {}
3755
- pair = tmux_target(entry) if entry else ((tmux['socket'], tmux['session'])
3756
- if tmux.get('socket') and tmux.get('session') else None)
3757
- idle, why_not = recipient_idle(found, observed, hook, status['fresh'])
3758
- if idle and not pair:
3759
- idle, why_not = False, 'it has no tmux session to type into'
3760
- if idle:
3761
- with dispatch_lock(root, lane):
3762
- # The final recheck, under the recipient's dispatch lock (the review's 8d91d073): observed
3763
- # now, the same agent as when it was addressed, still idle, no older message waiting.
3764
- now_status = container_status(root)
3765
- now_observed = now_status['lanes'].get(lane) or {}
3766
- idle, why_not = recipient_idle(found, now_observed,
3767
- hook_agent(Path(root) / 'state' / 'hooks', lane, proc),
3768
- now_status['fresh'])
3769
- if idle and generation(now_observed) != generation(observed):
3770
- idle, why_not = False, 'its agent changed since it was addressed (replaced)'
3771
- older = [other for other in inbox_entries(root, lane, history=0)
3772
- if other['id'] != message_id and pending(other, now)] if idle else []
3773
- if older:
3774
- idle, why_not = False, (f'{len(older)} older message' + (
3775
- 's wait in its inbox: they are' if len(older) > 1 else ' waits in its inbox: it is')
3776
- + ' typed first')
3777
- typed = body
3778
- if idle and found['transport'] == 'typed':
3779
- command = pane_command(*pair)
3780
- idle = command in TYPED_SHELLS
3781
- why_not = f'its pane runs {command or "what tmux did not name"}, not a shell at its prompt'
3782
- typed = SHELL_COMMENT + body
3783
- if idle:
3784
- via, extra = 'typed', {'typed': len(typed)}
3785
- results = send_keys(pair[0], pair[1], typed)
3786
- if results[-1].returncode:
3787
- said = (results[-1].stderr or '').strip().splitlines()
3788
- said = said[0] if said else f'tmux exit {results[-1].returncode}'
3789
- code = 'tmux_unanswered' if results[-1].returncode in (124, 127) else 'tmux_failed'
3790
- if len(results) == 2:
3791
- raise _refusal(f'{lane}: {said} — the message was typed, its Enter was not', code,
3792
- changed=f'typed the message into {lane}, without Enter')
3793
- raise LaneError(f'{lane}: {said} — nothing was typed', code)
4417
+ # 4. (BEY-7538) no keystrokes: a `lane` handle no adapter above reached is answered below — queued or
4418
+ # refused `transport_never_types` — and nothing is typed into its terminal, whether it is idle or not.
3794
4419
  except LaneError as error:
3795
4420
  if isinstance(error, Unconfirmed): # it may have arrived: held, never handed to another adapter
3796
4421
  attempt(record['attempt']['adapter'], 'unknown')
@@ -3799,7 +4424,7 @@ def message(root, home, sender_lane, to, text, ttl_s=MESSAGE_TTL_S, queue=False,
3799
4424
  _unlink_at(directory, message_id + MESSAGE_SUFFIX)
3800
4425
  refused(error)
3801
4426
  else:
3802
- if record.get('attempt'): # the remote adapter provably took nothing: the inbox may type it later
4427
+ if record.get('attempt'): # the remote adapter provably took nothing: it waits in the inbox instead
3803
4428
  attempt(record['attempt']['adapter'], 'unsent')
3804
4429
  via, extra = 'queued', {'not_delivered': f'{error.code}: {error}'}
3805
4430
  if via is None:
@@ -3807,9 +4432,12 @@ def message(root, home, sender_lane, to, text, ttl_s=MESSAGE_TTL_S, queue=False,
3807
4432
  _unlink_at(directory, message_id + MESSAGE_SUFFIX)
3808
4433
  if skipped is not None: # W15 L6: the pin failed and nothing after it applied — say the pin
3809
4434
  refused(_refusal(f'{lane}: {skipped}', skipped.code, lane=lane, address=address))
3810
- refused(_refusal(f'{lane} cannot take a message now: '
3811
- + (why_not or f'no adapter reaches its {found["kind"]} handle from here'),
3812
- 'recipient_busy', lane=lane, address=address))
4435
+ if found['kind'] == 'lane': # 4. (BEY-7538) only its keyboard reaches it: never a message's way in
4436
+ refused(_refusal(f'{lane} has no way to take a message but typing into its terminal, and a message '
4437
+ 'never types into a terminal: nothing was typed or kept',
4438
+ 'transport_never_types', lane=lane, address=address))
4439
+ refused(_refusal(f'{lane} cannot take a message now: no adapter reaches its {found["kind"]} handle '
4440
+ 'from here', 'recipient_busy', lane=lane, address=address))
3813
4441
  via = 'queued'
3814
4442
  if skipped is not None:
3815
4443
  extra = {'not_delivered': f'{skipped.code}: {skipped}'}
@@ -3824,6 +4452,254 @@ def message(root, home, sender_lane, to, text, ttl_s=MESSAGE_TTL_S, queue=False,
3824
4452
  'message': where + MESSAGE_SUFFIX, 'receipt': where + RECEIPT_SUFFIX, **extra}
3825
4453
 
3826
4454
 
4455
+ # ------------------------------------------------------------------------------------------------ DM-LANES-OUTBOX
4456
+ # A message for a lane of ANOTHER container (the fleet admin elsewhere, a board whose coordinator runs elsewhere) was
4457
+ # refused `not_in_container` and dropped (Linear FLE-289: 13 asks for the fleet admin lost in six days, every one
4458
+ # re-sent by hand as a Linear comment). Now it waits in the SENDER'S outbox, `~/.lz/state/outbox/<sender lane>/`, the
4459
+ # same record and receipt as an inbox holds (receipt `outbox`), one log line. The site's bridge — a host process that
4460
+ # reaches every container of the site (Fleet's, on the host that runs the guests; Lanes carries none itself) — lists
4461
+ # what waits (`lane outbox pending --json`), writes each record into the recipient's inbox on its container
4462
+ # (`lane inbox deliver --from-container <name>` there, idempotent on the origin's container and id: a retry after a
4463
+ # lost answer never doubles a message) and settles the outbox record (`lane outbox settle … --bridged <container>:<id>`,
4464
+ # its text leaving; `--failed <why>` keeps it for the next pass). A record whose ttl passes in the outbox is expired
4465
+ # by the next listing (outbox_sweep). Nothing here types into a terminal: the recipient finds a bridged message as it
4466
+ # finds any queued one (lanes_status `inbox`, `lane inbox`), with the sender's address to reply to — a reply crosses
4467
+ # back the same way.
4468
+
4469
+
4470
+ def outbox_write(root, sender_lane, sender, sender_handle, address, text, ttl_s, now, to_lane=None):
4471
+ """message()'s outbox branch: the record (with its text, 0600; additive `to_lane`, the recipient's lane id when this
4472
+ container knew it — a board's coordinator elsewhere — else null, as for the fleet admin named by address only) and
4473
+ its `outbox` receipt in the sender's outbox, one log line -> the same answer shape as a delivered message, `lane`
4474
+ None (it is not of this container). The recipient's container resolves `to_lane` first (bridge_deliver): its own
4475
+ registry may give that lane an address override the sender could not know."""
4476
+ size = len(text.encode('utf-8'))
4477
+ directory = outbox_fd(root, sender_lane, create=True)
4478
+ try:
4479
+ message_id = new_message_id(directory, now)
4480
+ record = message_record(message_id, sender, sender_handle, address, now, text, ttl_s)
4481
+ record['to_lane'] = to_lane if isinstance(to_lane, str) and LANE_RE.fullmatch(to_lane) else None
4482
+ _write_at(directory, message_id + MESSAGE_SUFFIX, record)
4483
+ _write_at(directory, message_id + RECEIPT_SUFFIX, receipt_record(message_id, address, 'outbox', now))
4484
+ finally:
4485
+ os.close(directory)
4486
+ append_log(root, log_line(now, sender, address, message_id, size, 'outbox'))
4487
+ where = f'{LZ}/{"/".join(OUTBOX_DIR)}/{sender_lane}/{message_id}'
4488
+ picked_up_by, within = DELIVERY['outbox']
4489
+ return {'id': message_id, 'lane': None, 'to': address, 'to_lane': record['to_lane'], 'from': sender,
4490
+ 'delivered_by': 'outbox', 'expected_within_s': within, 'picked_up_by': picked_up_by, 'ttl_s': ttl_s,
4491
+ 'bytes': size, 'at': iso(now), 'message': where + MESSAGE_SUFFIX, 'receipt': where + RECEIPT_SUFFIX}
4492
+
4493
+
4494
+ def outbox_entries(root, lane, prefix=(), history=INBOX_SCAN_MAX):
4495
+ """One lane's outbox, as inbox_entries reads an inbox: [{'id', 'record', 'receipt'}] oldest first."""
4496
+ try:
4497
+ fd = outbox_fd(root, lane, prefix=prefix)
4498
+ except (OSError, LaneError):
4499
+ return []
4500
+ try:
4501
+ return _inbox_read(fd, history)[0]
4502
+ except OSError:
4503
+ return []
4504
+ finally:
4505
+ os.close(fd)
4506
+
4507
+
4508
+ def outbox_lanes(root, prefix=()):
4509
+ """The lanes with an outbox directory, sorted."""
4510
+ try:
4511
+ fd = outbox_fd(root, prefix=prefix)
4512
+ except (OSError, LaneError):
4513
+ return []
4514
+ try:
4515
+ return sorted(name for name in os.listdir(fd) if LANE_RE.fullmatch(name))
4516
+ except OSError:
4517
+ return []
4518
+ finally:
4519
+ os.close(fd)
4520
+
4521
+
4522
+ def outbox_waiting(entry, now):
4523
+ """Is `entry` a message still waiting in an outbox: receipt `outbox`, its text there, its ttl not passed."""
4524
+ receipt = entry.get('receipt') or {}
4525
+ return (receipt.get('delivered_by') == 'outbox' and isinstance((entry.get('record') or {}).get('text'), str)
4526
+ and not expired(entry, now))
4527
+
4528
+
4529
+ def outbox_sweep(root, now=None, prefix=()):
4530
+ """Every outbox message whose ttl passed loses its text and its receipt says `expired` (cleared) -> [(lane, id)].
4531
+ The bridge's listing runs it first; a sweep that cannot write is silence."""
4532
+ now = time.time() if now is None else now
4533
+ done = []
4534
+ for lane in outbox_lanes(root, prefix):
4535
+ for entry in outbox_entries(root, lane, prefix):
4536
+ record, receipt = entry.get('record'), entry.get('receipt') or {}
4537
+ if not record or 'text' not in record or receipt.get('delivered_by') != 'outbox' or not expired(entry, now):
4538
+ continue
4539
+ try:
4540
+ fd = outbox_fd(root, lane, prefix=prefix)
4541
+ except (OSError, LaneError):
4542
+ continue
4543
+ try:
4544
+ kept = {key: value for key, value in record.items() if key != 'text'}
4545
+ kept['expired'] = iso(now)
4546
+ _write_at(fd, entry['id'] + MESSAGE_SUFFIX, kept)
4547
+ _write_at(fd, entry['id'] + RECEIPT_SUFFIX, cleared_receipt(receipt, kept, entry['id'], now))
4548
+ except OSError:
4549
+ continue
4550
+ finally:
4551
+ os.close(fd)
4552
+ append_log(root, log_line(now, record.get('from'), record.get('to'), entry['id'],
4553
+ len(record['text'].encode('utf-8')), 'expired'), prefix=prefix)
4554
+ done.append((lane, entry['id']))
4555
+ return done
4556
+
4557
+
4558
+ def outbox_pending(root, now=None, prefix=()):
4559
+ """[{'lane', 'id', 'record', 'receipt'}] of every message waiting in any lane's outbox, oldest first (the record's
4560
+ `at`, then the lane, then the id: ids are ordered within one directory only): what the site's bridge carries.
4561
+ Expired ones are settled first (outbox_sweep)."""
4562
+ now = time.time() if now is None else now
4563
+ outbox_sweep(root, now, prefix)
4564
+ out = []
4565
+ for lane in outbox_lanes(root, prefix):
4566
+ for entry in outbox_entries(root, lane, prefix):
4567
+ if outbox_waiting(entry, now):
4568
+ out.append({'lane': lane, **entry})
4569
+ return sorted(out, key=lambda item: ((item.get('record') or {}).get('at') or '', item['lane'], item['id']))
4570
+
4571
+
4572
+ def outbox_settle(root, lane, message_id, bridged=None, failed=None, now=None):
4573
+ """The bridge's word on one outbox message of `lane` -> {id, lane, to, delivered_by, changed}. `bridged`
4574
+ {'container', 'id'}: the record is in the recipient's inbox there — the text leaves the record (`bridged` added)
4575
+ FIRST, then the receipt says `bridged` and is `cleared` (settled; the log line `bridged`). `failed` <why>: the
4576
+ record stays `outbox` for the next pass, its receipt's additive `attempt` {at, outcome, why} saying what happened
4577
+ (no log line: nothing changed for the sender). Refused `unknown_message`; settling twice changes nothing."""
4578
+ now = time.time() if now is None else now
4579
+ if not isinstance(message_id, str) or not PUBLISH_ID.fullmatch(message_id):
4580
+ raise LaneError(f'{message_id!r} is not a message id', 'unknown_message')
4581
+ if (bridged is None) == (failed is None):
4582
+ raise LaneError('one of bridged or failed', 'invalid_arguments')
4583
+ if bridged is not None and not (isinstance(bridged, dict) and isinstance(bridged.get('container'), str)
4584
+ and BRIDGE_ORIGIN_RE.fullmatch(bridged['container'])
4585
+ and isinstance(bridged.get('id'), str) and PUBLISH_ID.fullmatch(bridged['id'])):
4586
+ raise LaneError('bridged names the recipient container and the message id there', 'invalid_arguments')
4587
+ try:
4588
+ fd = outbox_fd(root, lane)
4589
+ except (OSError, LaneError):
4590
+ raise LaneError(f'{lane} has no outbox: no message {message_id}', 'unknown_message') from None
4591
+ try:
4592
+ record, receipt = _read_at(fd, message_id + MESSAGE_SUFFIX), _read_at(fd, message_id + RECEIPT_SUFFIX)
4593
+ if not (isinstance(record, dict) and record.get('v') == 1 and isinstance(receipt, dict)):
4594
+ raise LaneError(f'{lane}\'s outbox holds no message {message_id}', 'unknown_message')
4595
+ answer = {'id': message_id, 'lane': lane, 'to': record.get('to'), 'delivered_by': receipt.get('delivered_by')}
4596
+ if settled(receipt):
4597
+ return {**answer, 'changed': 'nothing: settled already'}
4598
+ if 'text' not in record: # a settle that stopped between its two writes: the record says bridged, finish the receipt
4599
+ if isinstance(record.get('bridged'), dict):
4600
+ receipt = receipt_record(message_id, record.get('to'), 'bridged', now, cleared=now)
4601
+ receipt['bridged'] = record['bridged']
4602
+ _write_at(fd, message_id + RECEIPT_SUFFIX, receipt)
4603
+ return {**answer, 'delivered_by': 'bridged',
4604
+ 'changed': 'its receipt only: an earlier settle is finished (bridged, cleared)'}
4605
+ return {**answer, 'changed': 'nothing: the record holds no text'}
4606
+ if failed is not None:
4607
+ receipt = dict(receipt)
4608
+ receipt['attempt'] = {'at': iso(now), 'outcome': 'failed', 'why': str(failed)[:200]}
4609
+ _write_at(fd, message_id + RECEIPT_SUFFIX, receipt)
4610
+ return {**answer, 'changed': 'its receipt only: the attempt is recorded; the message waits for the next pass'}
4611
+ kept = {key: value for key, value in record.items() if key != 'text'}
4612
+ kept['bridged'] = {'container': bridged['container'], 'id': bridged['id'], 'at': iso(now)}
4613
+ _write_at(fd, message_id + MESSAGE_SUFFIX, kept) # the text leaves first …
4614
+ receipt = receipt_record(message_id, record.get('to'), 'bridged', now, cleared=now)
4615
+ receipt['bridged'] = kept['bridged']
4616
+ _write_at(fd, message_id + RECEIPT_SUFFIX, receipt) # … then the receipt says so
4617
+ finally:
4618
+ os.close(fd)
4619
+ append_log(root, log_line(now, record.get('from'), record.get('to'), message_id,
4620
+ len(record['text'].encode('utf-8')), 'bridged'))
4621
+ return {**answer, 'delivered_by': 'bridged',
4622
+ 'changed': f'{LZ}/{"/".join(OUTBOX_DIR)}/{lane}/{message_id}{MESSAGE_SUFFIX}: the text removed; it is '
4623
+ f'message {bridged["id"]} in the inbox on {bridged["container"]}'}
4624
+
4625
+
4626
+ def bridge_deliver(root, record, origin, now=None):
4627
+ """The bridge's write on the recipient's side: `record` (a DM-LANES-MESSAGE with its text, from the outbox of a
4628
+ lane of container `origin`) into the inbox of the lane its `to` names HERE (resolve_address; a lane of another
4629
+ container is refused `not_in_container`, as any address code) -> {id, lane, to, from, delivered_by: queued, origin,
4630
+ changed}. Idempotent: an inbox that already holds a message of this origin (container and id) answers it again and
4631
+ writes nothing. The inbox record keeps the sender's address and handle (the recipient replies to it), gets a new id
4632
+ of this inbox, the ttl the original has left, and `origin` {kind: bridge, container, id, at}; its receipt is
4633
+ `queued` (it waits for the lane's agent, like any queued message); one log line `queued`. A record with less than
4634
+ MESSAGE_TTL_MIN left is refused `expired` (never extended); one that is no message, `invalid_arguments`; one whose
4635
+ `from` is a lane of this container, `from_is_local`. The idempotency scan reads every message not yet settled and
4636
+ the newest INBOX_SCAN_MAX settled ones: the bridge settles the outbox right after this answer, so a retry comes
4637
+ seconds later, and a duplicate would need the first copy acknowledged and 512 more acknowledged in between."""
4638
+ now = time.time() if now is None else now
4639
+ if not (isinstance(record, dict) and record.get('v') == 1 and isinstance(record.get('id'), str)
4640
+ and PUBLISH_ID.fullmatch(record['id']) and isinstance(record.get('from'), str)
4641
+ and isinstance(record.get('to'), str) and isinstance(record.get('text'), str)):
4642
+ raise LaneError('a bridged message is a DM-LANES-MESSAGE record with its text', 'invalid_arguments')
4643
+ if not isinstance(origin, str) or not BRIDGE_ORIGIN_RE.fullmatch(origin):
4644
+ raise LaneError('the origin is the name of the container the message comes from', 'invalid_arguments')
4645
+ check_message(record['text'])
4646
+ sender = record['from']
4647
+ if not (ADDRESS_RE.fullmatch(sender) or HOST_SENDER.fullmatch(sender) or PEER_SENDER.fullmatch(sender)):
4648
+ raise LaneError('a bridged message comes from an address, host:<login> or peer:<name>', 'invalid_arguments')
4649
+ at, ttl = epoch(record.get('at')), record.get('ttl_s')
4650
+ if at is None or not isinstance(ttl, int) or isinstance(ttl, bool):
4651
+ raise LaneError('a bridged message carries its time and ttl', 'invalid_arguments')
4652
+ left = int(at + ttl - now)
4653
+ if left < MESSAGE_TTL_MIN: # what the sender asked for is (as good as) over: never extended here
4654
+ raise LaneError(f'message {record["id"]} from {origin} expired on its way', 'expired')
4655
+ export, status = registry_export(root), container_status(root, now)
4656
+ lanes = export['lanes']
4657
+ # A bridged `from` is the bridge's word, not a verified identity: what it can never be is a lane of THIS container
4658
+ # (a bridged message comes from elsewhere by definition), so nobody here can sign as a neighbour.
4659
+ if ADDRESS_RE.fullmatch(sender):
4660
+ try:
4661
+ _lane, _entry = resolve_address(root, '@' + sender, export, status)
4662
+ except LaneError:
4663
+ _lane, _entry = None, None
4664
+ if _lane is not None and (_entry is not None or any(row['id'] == _lane for row in status['unregistered'])):
4665
+ raise LaneError(f'from @{sender} is {_lane}, a lane of this container: a bridged message never is',
4666
+ 'from_is_local')
4667
+ # The recipient: its lane id first (the sender's container may not know this lane's address override), else `to`.
4668
+ to_lane = record.get('to_lane')
4669
+ if isinstance(to_lane, str) and LANE_RE.fullmatch(to_lane) \
4670
+ and (to_lane in lanes or any(row['id'] == to_lane for row in status['unregistered'])):
4671
+ lane, entry = to_lane, lanes.get(to_lane)
4672
+ else:
4673
+ lane, entry = resolve_address(root, record['to'], export, status)
4674
+ ghost = None if entry else next((row for row in status['unregistered'] if row['id'] == lane), None)
4675
+ if entry is None and ghost is None:
4676
+ raise LaneError(f'{record["to"]} names {lane}, a lane of another container', 'not_in_container')
4677
+ observed = status['lanes'].get(lane) or {}
4678
+ address = address_of(lane, entry, observed, ghost) or lane
4679
+ mark = {'kind': 'bridge', 'container': origin, 'id': record['id'], 'at': record.get('at')}
4680
+ for held_ in inbox_entries(root, lane):
4681
+ if (held_.get('record') or {}).get('origin') == mark:
4682
+ return {'id': held_['id'], 'lane': lane, 'to': address, 'from': record['from'],
4683
+ 'delivered_by': (held_.get('receipt') or {}).get('delivered_by'), 'origin': mark,
4684
+ 'changed': 'nothing: this inbox holds it already'}
4685
+ size = len(record['text'].encode('utf-8'))
4686
+ directory = inbox_fd(root, lane, create=True)
4687
+ try:
4688
+ message_id = new_message_id(directory, now)
4689
+ kept = message_record(message_id, record['from'], record.get('from_handle') or 'lane', address, now,
4690
+ record['text'], min(left, MESSAGE_TTL_MAX))
4691
+ kept['origin'] = mark
4692
+ _write_at(directory, message_id + MESSAGE_SUFFIX, kept)
4693
+ _write_at(directory, message_id + RECEIPT_SUFFIX, receipt_record(message_id, address, 'queued', now))
4694
+ finally:
4695
+ os.close(directory)
4696
+ append_log(root, log_line(now, record['from'], address, message_id, size, 'queued'))
4697
+ where = f'{LZ}/{"/".join(INBOX_DIR)}/{lane}/{message_id}'
4698
+ return {'id': message_id, 'lane': lane, 'to': address, 'from': record['from'], 'delivered_by': 'queued',
4699
+ 'origin': mark, 'changed': f'{where}{MESSAGE_SUFFIX} and its receipt: queued ({size} bytes from '
4700
+ f'@{record["from"]} on {origin})'}
4701
+
4702
+
3827
4703
  def _unlink_at(dir_fd, name):
3828
4704
  try:
3829
4705
  os.unlink(name, dir_fd=dir_fd)