@vibelord/lanes 1.6.1 → 1.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -56,13 +56,20 @@ through `muse_sessions` (its session log, joined to the pane's Muse pid by the `
56
56
  its spinner title `⠙ <workspace>` was published `codex / working` before W13, because the walk did not know Muse and
57
57
  the Codex title rule reads a spinner on an `unknown` pane (DEF-2030). ZCode keeps its sessions in SQLite and draws no
58
58
  title and no bell: it is observed by its process (`zcode` / `idle`) and its hooks only.
59
+
60
+ W15 L1 (plan `docs/superpowers/plans/2026-10-25-lanes-messaging-bus.md`): a Claude session whose own turn is over (`idle`
61
+ to Claude, so `needs_input` here) while its background subagents, workflows or Bash jobs still run is NOT waiting for
62
+ a person. `merge` publishes it `working` with the additive `activity: 'delegating'` when the session's work files were
63
+ written within DELEGATING_FRESH (`claude_delegating`, the L1 constants below); the vocabulary (STATUSES) is unchanged.
59
64
  """
65
+ import heapq
60
66
  import importlib.util
61
67
  import json
62
68
  import os
63
69
  import stat
64
70
  import sys
65
71
  import time
72
+ import zlib
66
73
  from pathlib import Path
67
74
 
68
75
  SPINNER = set('⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏⠁⠂⠄⡀⢀⠠⠐⠈')
@@ -81,6 +88,42 @@ RANK = {'needs': 3, 'working': 2, 'done': 1, None: 0}
81
88
  DWELL = {'needs': 8, 'working': 5, 'done': 5, None: 0}
82
89
  GONE_DWELL = 5
83
90
 
91
+ # W15 L1: Claude's background work. MEASURED 2026-10-25 on this workspace (Claude Code 2.1.310, 65 live sessions): a
92
+ # session's subagent transcripts are ~/.claude/projects/<project>/<sessionId>/subagents/agent-<id>.jsonl, a workflow's
93
+ # agents two levels further down (subagents/workflows/wf_<id>/agent-<id>.jsonl), its workflow files under `workflows/`
94
+ # and its background Bash output <TMPDIR>/claude-<uid>/<project>/<sessionId>/tasks/<id>.output (TMPDIR = ~/.tmp where
95
+ # the Lanes contract's env.sh set it — 123 such session directories here —, ~/.cache/build-tmp on this workspace's own
96
+ # shells, /tmp Claude's default); `<project>` is the session file's `cwd` with every UTF-16 unit outside
97
+ # [A-Za-z0-9] replaced by `-` (the binary's own rule, `replace(/[^a-zA-Z0-9]/g,"-")`; 57 of 57 sessions whose project
98
+ # directory exists match it), hashed past 200 characters by a function Lanes does not reproduce (no claim then). While
99
+ # that work runs, its files are written every 30-225 s; an append moves only the file's mtime, never its directory's
100
+ # (measured), so the files themselves are stat'ed. Trees reach 16,704 entries (measured, one idle session), so one scan
101
+ # stats at most DELEGATING_STATS entries, newest directory first, DELEGATING_DEPTH levels down; statusd's DelegationCache
102
+ # re-stats the last fresh file first and rescans an idle stretch with nothing fresh only after DELEGATING_RECHECK to
103
+ # 2 x DELEGATING_RECHECK s (an offset per session, so the rescans of many idle lanes spread over the cycles).
104
+ DELEGATING_FRESH = 180 # seconds: a work file written this recently is live delegation
105
+ DELEGATING_FROM = ('needs_input', 'idle', 'done') # merge's words a delegating Claude session is published over
106
+ DELEGATING_STATS = 2048 # entries (and directories opened) one scan looks at, at most
107
+ DELEGATING_DEPTH = 3 # levels below a work directory: subagents/workflows/wf_<id>/agent-<id>.jsonl
108
+ DELEGATING_RECHECK = 30 # seconds (plus a per-session 0..29) an idle stretch found not delegating is believed
109
+ CLAUDE_PROJECT_MAX = 200
110
+ CLAUDE_WORK = ('subagents', 'tasks', 'workflows') # under ~/.claude/projects/<project>/<sessionId>/
111
+ CLAUDE_TMP = 'claude-1000' # Claude's per-user directory in TMPDIR (the container user is uid 1000)
112
+ CLAUDE_TMPDIRS = ('~/.tmp', '~/.cache/build-tmp', '/tmp') # env.sh's TMPDIR, this workspace's, Claude's default
113
+
114
+ # BEY-6838: a Claude session file names its pane by a string LOCAL to one tmux server, `<session>:@<win>.%<pane>`, and one
115
+ # container runs many servers (sockets). MEASURED 2026-10-26 on this workspace: 31 live sockets, and the session-local
116
+ # `coordinator:@0.%0` on 7 of them (the `lanes-shells-<board>` sockets), each pane running its own live Claude whose file
117
+ # says exactly that string. Indexed by the string alone (the code before this fix), the newest of the 7 files stood for
118
+ # all 7 lanes: its word was published on the other 6 rows and decided whether `/rename` was typed into them.
119
+ # `claude_sessions(..., panes=)` binds each file to the socket whose pane of that name has its root process on the file
120
+ # pid's ANCESTRY (the ppid chain, field 4 of /proc/<pid>/stat), and keys it `bound_key(socket, string)`. MEASURED the
121
+ # same day: 69 of 69 live Claude pids reach the root process of the pane their file names within 2 steps (0 for the 7
122
+ # coordinators: Claude is the pane's root there), the file's string equals that pane's listing in all 69, and the socket
123
+ # named by each one's `TMUX` environment variable agrees with the ancestry in all 69. The environment is not what binds:
124
+ # /proc/<pid>/environ needs ptrace-read access to the process, its stat file does not.
125
+ ANCESTRY_DEPTH = 8 # ppid steps walked up from a Claude pid at most
126
+
84
127
  # W12 harness identity (spec §2). The comm (/proc/<pid>/comm, at most 15 bytes) of each harness, and what it is called.
85
128
  # W13 (spec 2026-10-16 §2): ZCode's CLI sets process.title `zcode-cli` (its comm); Muse Code's launcher is a script named
86
129
  # `muse` that execs `muse-bin-<version>` (MEASURED 2026-10-16, muse 1.4.10: comm `muse-bin-1.4.10`, the 15-byte cut of
@@ -115,6 +158,11 @@ KIMI_ENDED = {'completed': 'needs_input', 'cancelled': 'needs_input', 'failed':
115
158
  # directory name relative to the container home (harness_grok.GROK_HOME_DEFAULT and CONTAINER_HOME, the same values).
116
159
  GROK_HOME = '.grok-build'
117
160
  CONTAINER_HOME = '/home/coder'
161
+ # W15 L6 (BEY-6843): lane-peerd writes a `~/.claude/sessions/<pid>.json` for every lane whose agent is not Claude (a
162
+ # virtual peer, so a Claude session's ListAgents/SendMessage reach it), its `messagingSocketPath` in this directory
163
+ # (= lane_core.peers_root(CONTAINER_HOME) + '/', pinned by test_lane_peerd). Such a file is never a Claude session:
164
+ # `claude_sessions` skips it, so a Codex lane is never published as Claude from Lanes' own entry.
165
+ VIRTUAL_PEERS = CONTAINER_HOME + '/.lz/state/peers/'
118
166
  GROK_UNKNOWN = 'unknown' # the Grok observer's word for a pane it sees but cannot join (leader mode): no agent{}
119
167
  _DIR_FLAGS = os.O_RDONLY | os.O_DIRECTORY | getattr(os, 'O_CLOEXEC', 0)
120
168
  _FILE_FLAGS = os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK | getattr(os, 'O_CLOEXEC', 0)
@@ -382,13 +430,54 @@ def parse_codex_title(title, harness=None):
382
430
  return None
383
431
 
384
432
 
385
- def claude_sessions(sessions_dir, proc_root):
386
- """pane key -> agent dict, live pids only. Several files can name one pane (a resumed session leaves the
387
- old pid's file behind): the newest `statusUpdatedAt` among LIVE pids wins. A file whose `procStart` does not
388
- match the pid's current starttime is a recycled pid and is skipped (no `procStart` -> existence only). `proc_root` is the container's
389
- /proc as seen from the host (/proc/<container-pid>/root/proc), so liveness is checked in the container's pid
390
- namespace. A malformed file is skipped, never raised: one bad file costs nobody else their agent."""
391
- out = {}
433
+ def bound_key(socket, key):
434
+ """A pane's key qualified by its tmux server: `<socket>/<session>:@<win>.%<pane>` (BEY-6838). A socket name is an
435
+ IDENT (`lanes_lib.IDENT`, no `/`), so the first `/` ends it. statusd keys every per-pane index of a container this
436
+ way (`agent_signals`) and hands it to `merge` as `key`: two servers of one container may hold the same local key."""
437
+ return f'{socket}/{key}'
438
+
439
+
440
+
441
+ def parent_pid(proc_root, pid):
442
+ """Field 4 (ppid) of /proc/<pid>/stat in `proc_root`, parsed after the last ')' (comm may contain spaces and ')'),
443
+ or None when it cannot be read."""
444
+ try:
445
+ return int(Path(proc_root, str(pid), 'stat').read_text().rsplit(')', 1)[1].split()[1])
446
+ except (OSError, IndexError, ValueError):
447
+ return None
448
+
449
+
450
+ def ancestry(proc_root, pid, depth=ANCESTRY_DEPTH):
451
+ """`pid` and its ancestors in `proc_root`, nearest first, at most `depth` ppid steps up, as a tuple of ints. It ends
452
+ before pid 1 (the container's init: never a pane's root process), at a pid whose stat cannot be read (that pid is
453
+ still in it: it is alive, its parent unknown) and at a loop."""
454
+ chain, current = [], int(pid)
455
+ for _step in range(depth + 1):
456
+ if current <= 1 or current in chain:
457
+ break
458
+ chain.append(current)
459
+ current = parent_pid(proc_root, current)
460
+ if current is None:
461
+ break
462
+ return tuple(chain)
463
+
464
+
465
+ def claude_files(sessions_dir, proc_root, panes=None):
466
+ """The live Claude session files of one container -> [(key, pid, document)], unordered. Live: `pid` (the file name)
467
+ exists in `proc_root` — the container's /proc as the host sees it (/proc/<container-pid>/root/proc), so liveness
468
+ is checked in the container's pid namespace — and, when the file carries `procStart`, still is the process that
469
+ wrote it (`_same_process`: a recycled pid is skipped; no `procStart` -> existence only). `document` is the parsed
470
+ file; its `tmux` must be a non-empty string. A malformed file is skipped, never raised: one bad file costs nobody
471
+ else their agent. Only `<pid>.json` is ever opened (the `<pid>.<hash>.key` beside it never is, DEF-1802).
472
+
473
+ `panes` binds every file to its tmux server (BEY-6838): {socket: {pane key: the pane's root pid}}, the panes of the
474
+ container's servers as their own `list-panes` rows name them. A file then counts only for the socket whose pane of
475
+ the name its `tmux` says has its root process on the file pid's `ancestry` — key `bound_key(socket, tmux)` — and is
476
+ skipped when no socket's pane qualifies (a process outside every listed pane: another server's, one reparented to
477
+ init, or one whose file names a pane it does not run in) or when more than one does. Without `panes` the key is the
478
+ `tmux` string itself, socket-blind: right only where the container runs one tmux server (the pure readers' unit
479
+ fixtures); statusd and `lanes_lib.rename_claude` always bind."""
480
+ out = []
392
481
  try:
393
482
  names = os.listdir(sessions_dir)
394
483
  except OSError:
@@ -403,11 +492,35 @@ def claude_sessions(sessions_dir, proc_root):
403
492
  continue
404
493
  if not isinstance(d, dict):
405
494
  continue
495
+ if str(d.get('messagingSocketPath') or '').startswith(VIRTUAL_PEERS):
496
+ continue # lane-peerd's virtual peer (W15 L6): the lane's agent is not Claude
406
497
  if d.get('procStart') is not None and not _same_process(proc_root, stem, d['procStart']):
407
498
  continue
408
499
  key = d.get('tmux')
409
500
  if not isinstance(key, str) or not key:
410
501
  continue
502
+ if panes is not None:
503
+ sockets = [socket for socket, index in panes.items() if key in index]
504
+ line = ancestry(proc_root, stem) if sockets else ()
505
+ owners = [socket for socket in sockets if panes[socket][key] in line]
506
+ if len(owners) != 1:
507
+ continue
508
+ key = bound_key(owners[0], key)
509
+ out.append((key, int(stem), d))
510
+ return out
511
+
512
+
513
+ def claude_sessions(sessions_dir, proc_root, work=None, panes=None):
514
+ """pane key -> agent dict, live pids only (`claude_files`, which `panes` binds to the tmux server each process runs
515
+ in: the key is then `bound_key(socket, pane key)`, BEY-6838). Several files can name one pane (a resumed session
516
+ leaves the old pid's file behind): the newest `statusUpdatedAt` among LIVE pids wins. A file whose `procStart` does
517
+ not match the pid's current starttime is a recycled pid and is skipped; a malformed file is skipped, never raised.
518
+
519
+ `work`, when a dict, also receives {pane key: (cwd, status)} of each winning file — its `cwd` (None unless a
520
+ string) and Claude's own word (`idle`, `waiting`, ...) — for `delegation_check` (W15 L1); the published entry does
521
+ not carry them."""
522
+ out = {}
523
+ for key, pid, d in claude_files(sessions_dir, proc_root, panes):
411
524
  try:
412
525
  since = int((d.get('statusUpdatedAt') or 0) // 1000)
413
526
  except (TypeError, ValueError):
@@ -416,13 +529,208 @@ def claude_sessions(sessions_dir, proc_root):
416
529
  if d.get('status') == 'waiting' and 'permission' in str(d.get('waitingFor') or '').lower():
417
530
  status = 'needs_approval'
418
531
  entry = {'harness': 'claude', 'status': status, 'name': str(d.get('name') or ''),
419
- 'session_id': str(d.get('sessionId') or ''), 'pid': int(stem),
532
+ 'session_id': str(d.get('sessionId') or ''), 'pid': pid,
420
533
  'since': since, 'source': 'claude-session-file'}
421
534
  if key not in out or entry['since'] >= out[key]['since']:
422
535
  out[key] = entry
536
+ if work is not None:
537
+ cwd = d.get('cwd')
538
+ work[key] = (cwd if isinstance(cwd, str) else None, d.get('status'))
423
539
  return out
424
540
 
425
541
 
542
+ def claude_project(cwd):
543
+ """Claude Code's directory name for a session started in `cwd` — `~/.claude/projects/<this>` and
544
+ `<TMPDIR>/claude-<uid>/<this>` — or None: every UTF-16 unit outside [A-Za-z0-9] becomes `-` (so a character beyond
545
+ the BMP is two), the binary's own rule (MEASURED, the L1 comment above). A name longer than CLAUDE_PROJECT_MAX is
546
+ hashed by Claude with a function not reproduced here, and anything but an absolute path is no session's cwd: None,
547
+ no claim."""
548
+ if not isinstance(cwd, str) or not cwd.startswith('/') or '\x00' in cwd:
549
+ return None
550
+ name = ''.join(c if c.isascii() and c.isalnum() else '--' if ord(c) > 0xFFFF else '-' for c in cwd)
551
+ return name if len(name) <= CLAUDE_PROJECT_MAX else None
552
+
553
+
554
+ def _fresh(mtime, now):
555
+ return abs(now - mtime) <= DELEGATING_FRESH
556
+
557
+
558
+ def _work_roots(home, project, session_id):
559
+ """The session's work directories as path parts below the container root (CLAUDE_WORK under its projects
560
+ directory, then `tasks` under each CLAUDE_TMPDIRS)."""
561
+ home_parts = tuple(part for part in home.split('/') if part)
562
+ roots = [home_parts + ('.claude', 'projects', project, session_id, sub) for sub in CLAUDE_WORK]
563
+ for tmp in CLAUDE_TMPDIRS:
564
+ base = home_parts + tuple(part for part in tmp[2:].split('/') if part) if tmp.startswith('~/') else \
565
+ tuple(part for part in tmp.split('/') if part)
566
+ roots.append(base + (CLAUDE_TMP, project, session_id, 'tasks'))
567
+ return roots
568
+
569
+
570
+ def delegation_scan(root, session_id, cwd, now=None, home=CONTAINER_HOME, budget=DELEGATING_STATS):
571
+ """(delegating, evidence, cost) for one Claude session: is any of its work files (`_work_roots`, DELEGATING_DEPTH
572
+ levels down) or work directories written within DELEGATING_FRESH of `now`? `root` is the container's root as the
573
+ host sees it (`/proc/<init pid>/root`), `cwd` the session file's (`claude_project`). `evidence` = the path parts
574
+ (below `root`) of the fresh entry found, else None; `cost` = the entries stat'ed plus the directories opened, never
575
+ more than `budget`. A directory's own mtime counts (a new entry was just made in it); its entries are looked at
576
+ newest directory first, so a live workflow is reached before the old ones. Every component is opened without
577
+ following a link (`_open_at`) and a link is no work file: through /proc/<pid>/root a link would resolve against the
578
+ HOST's root. A budget spent before anything fresh was found is False: unproven, the session's own word stands."""
579
+ now = time.time() if now is None else now
580
+ project = claude_project(cwd)
581
+ if project is None or not isinstance(session_id, str) or not session_id:
582
+ return False, None, 0
583
+ try:
584
+ root_fd = os.open(str(root), _DIR_FLAGS)
585
+ except OSError:
586
+ return False, None, 0
587
+ cost, fds, queue = 0, [], []
588
+ try:
589
+ for parts in _work_roots(home, project, session_id):
590
+ if cost >= budget:
591
+ break
592
+ try:
593
+ fd = _open_at(root_fd, parts)
594
+ except OSError:
595
+ continue
596
+ fds.append((fd, parts))
597
+ cost += 1
598
+ try:
599
+ mtime = os.fstat(fd).st_mtime
600
+ except OSError:
601
+ continue
602
+ if _fresh(mtime, now):
603
+ return True, parts, cost
604
+ heapq.heappush(queue, (-mtime, len(queue), len(fds) - 1, ()))
605
+ order = len(queue)
606
+ while queue and cost < budget:
607
+ _newest, _order, index, below = heapq.heappop(queue)
608
+ base, parts = fds[index]
609
+ if below:
610
+ try:
611
+ fd = _open_at(base, below)
612
+ except OSError:
613
+ continue
614
+ cost += 1
615
+ else:
616
+ fd = base # a work directory itself: already open (and counted)
617
+ try:
618
+ with os.scandir(fd) as entries:
619
+ for entry in entries:
620
+ if cost >= budget:
621
+ break
622
+ try:
623
+ info = entry.stat(follow_symlinks=False)
624
+ except OSError:
625
+ continue
626
+ cost += 1
627
+ is_dir = stat.S_ISDIR(info.st_mode)
628
+ if not (is_dir or stat.S_ISREG(info.st_mode)):
629
+ continue
630
+ if _fresh(info.st_mtime, now):
631
+ return True, parts + below + (entry.name,), cost
632
+ if is_dir and len(below) + 1 < DELEGATING_DEPTH:
633
+ order += 1
634
+ heapq.heappush(queue, (-info.st_mtime, order, index, below + (entry.name,)))
635
+ except OSError:
636
+ pass
637
+ finally:
638
+ if below:
639
+ os.close(fd)
640
+ finally:
641
+ for fd, _parts in fds:
642
+ os.close(fd)
643
+ os.close(root_fd)
644
+ return False, None, cost
645
+
646
+
647
+ def claude_delegating(root, session_id, cwd, now=None, home=CONTAINER_HOME):
648
+ """True when the Claude session `session_id` started in `cwd` has background work writing now (`delegation_scan`):
649
+ its subagents, workflows or Bash jobs. Reads only, bounded, never follows a link."""
650
+ return delegation_scan(root, session_id, cwd, now, home)[0]
651
+
652
+
653
+ def _still_fresh(root, parts, now):
654
+ """Is the entry at `parts` below `root` (a regular file or a directory, never a link) written within
655
+ DELEGATING_FRESH of `now`? One stat; unreadable is False."""
656
+ try:
657
+ root_fd = os.open(str(root), _DIR_FLAGS)
658
+ except OSError:
659
+ return False
660
+ try:
661
+ fd = _open_at(root_fd, parts[:-1])
662
+ except OSError:
663
+ os.close(root_fd)
664
+ return False
665
+ try:
666
+ info = os.stat(parts[-1], dir_fd=fd, follow_symlinks=False)
667
+ except OSError:
668
+ return False
669
+ finally:
670
+ os.close(fd)
671
+ os.close(root_fd)
672
+ return (stat.S_ISREG(info.st_mode) or stat.S_ISDIR(info.st_mode)) and _fresh(info.st_mtime, now)
673
+
674
+
675
+ class DelegationCache:
676
+ """statusd's memory of `delegation_scan` between cycles, keyed by (container root, session id, cwd). A session found
677
+ delegating keeps its evidence: the next cycle stats that one entry and scans again only once it went stale. A
678
+ session found NOT delegating is believed while its idle stretch lasts (the session file's `since` unchanged: new
679
+ background work starts in a turn, which moves it) for DELEGATING_RECHECK seconds plus an offset of 0 to
680
+ DELEGATING_RECHECK - 1 taken from the key (`zlib.crc32`, the same in every run) — so an idle lane with nothing running
681
+ costs one bounded scan per 30-59 s, not one per cycle, and the rescans of many idle lanes do not fall into one
682
+ cycle (MEASURED 2026-10-25: 47 idle sessions here, 175.8 ms of scans together). `cycle()` starts a statusd cycle and
683
+ forgets the sessions the previous one did not ask about. `scans`/`stats` count the work (the tests' view)."""
684
+
685
+ def __init__(self):
686
+ self.entries = {}
687
+ self.seen = set()
688
+ self.scans = 0
689
+ self.stats = 0
690
+
691
+ def delegating(self, root, session_id, cwd, since, now, home=CONTAINER_HOME):
692
+ key = (str(root), str(session_id), str(cwd))
693
+ self.seen.add(key)
694
+ hit = self.entries.get(key)
695
+ if hit is not None:
696
+ if hit['evidence'] is not None:
697
+ self.stats += 1
698
+ if _still_fresh(root, hit['evidence'], now):
699
+ return True
700
+ elif hit['since'] == since and 0 <= now - hit['at'] < hit['believe']:
701
+ return False
702
+ self.scans += 1
703
+ found, evidence, cost = delegation_scan(root, session_id, cwd, now, home)
704
+ self.stats += cost
705
+ believe = DELEGATING_RECHECK + zlib.crc32(repr(key).encode()) % DELEGATING_RECHECK
706
+ self.entries[key] = {'since': since, 'at': now, 'evidence': evidence, 'believe': believe}
707
+ return found
708
+
709
+ def cycle(self):
710
+ for key in set(self.entries) - self.seen:
711
+ del self.entries[key]
712
+ self.seen = set()
713
+
714
+
715
+ def delegation_check(root, claude_by_pane, work, now=None, home=CONTAINER_HOME, cache=None):
716
+ """The `delegating` callable `merge` takes for one container: pane key (as `claude_by_pane` is keyed: statusd's
717
+ `bound_key`) -> True when the Claude session file that
718
+ claims the pane (`claude_by_pane`, with `work` as `claude_sessions(..., work=)` filled it) says Claude's own `idle`
719
+ and that session's background work is writing (`claude_delegating`, through `cache` when given). Claude's
720
+ `waiting` — a question or a permission dialog put to the person — is never delegation, nor is a pane no session
721
+ file claims. `merge` calls it only for an idle-like Claude verdict, so a working lane costs nothing."""
722
+ def check(key):
723
+ entry = claude_by_pane.get(key)
724
+ cwd, word = work.get(key, (None, None))
725
+ if not entry or word != 'idle' or not cwd or not entry.get('session_id'):
726
+ return False
727
+ at = time.time() if now is None else now
728
+ if cache is None:
729
+ return claude_delegating(root, entry['session_id'], cwd, at, home)
730
+ return cache.delegating(root, entry['session_id'], cwd, entry.get('since'), at, home)
731
+ return check
732
+
733
+
426
734
  def read_sidecar_dict(d, now, max_age, proc_root=None):
427
735
  """A hook-written sidecar (`~/.lz/state/hooks/<lane id>.json`, container `lane-signal`), or None when it is not
428
736
  ours, malformed, older than `max_age` seconds, or written by an agent that no longer runs — an hour-old hook state
@@ -456,7 +764,8 @@ def read_sidecar_dict(d, now, max_age, proc_root=None):
456
764
 
457
765
 
458
766
  def pane_key(pane_row):
459
- """`<session>:@<win>.%<pane>`, the key Claude's session files name a pane by and every per-pane index here uses."""
767
+ """`<session>:@<win>.%<pane>`, the key Claude's session files name a pane by and every per-pane index here uses —
768
+ local to ONE tmux server: statusd qualifies it with the pane's socket (`bound_key`, BEY-6838)."""
460
769
  return f"{pane_row.get('session_name')}:{pane_row.get('window_id')}.{pane_row.get('pane_id')}"
461
770
 
462
771
 
@@ -845,7 +1154,8 @@ def muse_title(pane_row, since):
845
1154
  BELL_LESS = ('muse', 'zcode')
846
1155
 
847
1156
 
848
- def merge(pane_row, claude_by_pane, sidecar, kimi_by_pane=None, grok_by_pane=None, muse_by_pane=None):
1157
+ def merge(pane_row, claude_by_pane, sidecar, kimi_by_pane=None, grok_by_pane=None, muse_by_pane=None, delegating=None,
1158
+ key=None):
849
1159
  """Precedence: hook sidecar (event-driven, every harness) > Claude session file > Kimi session file > Muse session
850
1160
  file (`muse_sessions`, W13) > Grok observer (`grok_sessions`: its session file, else the title with its blink
851
1161
  memory) > the Grok title (`grok_title`, a pane observed as `grok` nothing above claimed) > the Muse title
@@ -863,19 +1173,31 @@ def merge(pane_row, claude_by_pane, sidecar, kimi_by_pane=None, grok_by_pane=Non
863
1173
  idle title is `done`) and are taken as they come. The Grok observer's GROK_UNKNOWN (leader mode: its Grok Build runs a session it
864
1174
  cannot join to the pane) publishes no agent{}: nothing below may guess one. Last rung: a pane whose observed harness
865
1175
  nothing above claimed is that harness, `idle`, `done` with the bell (`source: process`, `pid` the harness pid statusd
866
- found). Returns None when nothing says an agent is here — the sidebar then draws a plain shell."""
1176
+ found). Returns None when nothing says an agent is here — the sidebar then draws a plain shell.
1177
+
1178
+ W15 L1, after all of that (so after the sidecar too): a Claude verdict in DELEGATING_FROM whose session is
1179
+ delegating — `delegating(pane key)`, statusd's `delegation_check`, asked only then — is published `working` with
1180
+ the additive `activity: 'delegating'`; every other key is the verdict's own. A `needs_approval` or `errored` verdict
1181
+ is never in DELEGATING_FROM: a permission prompt or a failed turn is real whatever runs in the background.
1182
+
1183
+ `key` is what every index and `delegating` are looked up by: the pane's `pane_key` by default; statusd passes
1184
+ `bound_key(socket, pane_key)`, its indexes being keyed by tmux server too (BEY-6838: two servers of one container
1185
+ may hold the same local key, and a socket-blind lookup gave one pane's agent to the other's row)."""
867
1186
  observed = pane_row.get('harness')
1187
+ key = pane_key(pane_row) if key is None else key
868
1188
  verdict = _verdict(pane_row, claude_by_pane, sidecar, kimi_by_pane or {}, grok_by_pane or {}, muse_by_pane or {},
869
- observed)
1189
+ observed, key)
870
1190
  if verdict is not None and observed in AGENT_HARNESSES:
871
1191
  verdict['harness'] = observed
1192
+ if (verdict is not None and delegating is not None and verdict.get('harness') == 'claude'
1193
+ and verdict.get('status') in DELEGATING_FROM and delegating(key)):
1194
+ verdict.update(status='working', activity='delegating')
872
1195
  return verdict
873
1196
 
874
1197
 
875
- def _verdict(pane_row, claude_by_pane, sidecar, kimi_by_pane, grok_by_pane, muse_by_pane, observed):
1198
+ def _verdict(pane_row, claude_by_pane, sidecar, kimi_by_pane, grok_by_pane, muse_by_pane, observed, key):
876
1199
  if sidecar and sidecar.get('status') in STATUSES:
877
1200
  return dict(sidecar, source=sidecar.get('source') or 'hook')
878
- key = pane_key(pane_row)
879
1201
  if key in claude_by_pane:
880
1202
  return dict(claude_by_pane[key])
881
1203
  bell = pane_row.get('window_bell_flag') == '1' and observed not in BELL_LESS
@@ -947,7 +1269,8 @@ def settle(prev, raw, now):
947
1269
  * lower section: publish only once the raw word has held for DWELL[section left] — `now - raw_since`;
948
1270
  * no agent at all: the published agent{} stays until GONE_DWELL has passed, then the key goes.
949
1271
 
950
- Published keys: `merge`'s own (harness, name, session_id, pid, source, event) from the verdict that was PUBLISHED —
1272
+ Published keys: `merge`'s own (harness, name, session_id, pid, source, event, and W15 L1's `activity`) from the
1273
+ verdict that was PUBLISHED —
951
1274
  a held status keeps the dict it was published with — plus `status` (the debounced word), `since` (when that status
952
1275
  began: the source's own start, never later than the cycle that first saw it, and kept while the status is
953
1276
  unchanged, so a moving source stamp is no longer a clock), `raw_status` (`merge`'s word this cycle, None while the