@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
@@ -30,8 +30,12 @@ NEEDS_YOU set. The six-word `state` is never read: the agent status is the only
30
30
  one person alone mute; recent marks of several people fall back to the host window for all (presence_marks,
31
31
  device_active).
32
32
  * Payload: `<lane name>: <agent task> — <status>` and, on a second line, the client command that opens the lane
33
- (`lanes-launch lane <id>`). No client registers a URL scheme for it, so the push carries a tappable action only
34
- when `action_url` (a template over `{lane}`, and `{doc}` for a `published` event — `action_url()`) is configured.
33
+ (`lanes-launch lane <id>`). No client registers a URL scheme for it, so the push carries a tappable action
34
+ ("Open lane") only when a template is configured: `lane_url` when set, else `action_url` (templates over `{lane}`,
35
+ `{doc}` and `{ws}` — `action_url()`). With `lane_url` set (BEY-8667 E4) the message is the first line alone: with
36
+ a `lane_url` such as `…/<device>-phone?ws={ws}` the tap opens the lane list of the lane's workspace on that phone
37
+ view, so the push names no command. The topic is the host's, so a desk's ntfy client gets the same message and
38
+ tap. Without `lane_url` the message keeps the command line and the tap target is `action_url`.
35
39
  * A failed send is one journal line (lane id and the failure class — never the topic or the bearer) and is not
36
40
  retried; it never stops the service.
37
41
 
@@ -62,12 +66,19 @@ Config `~/.config/lanes/notify.conf` (`LANES_NOTIFY_CONF` overrides the path), `
62
66
  `url` (ntfy server, http/https, required), `topic` (`[A-Za-z0-9_-]{1,64}`, required), `token_file` (a file holding
63
67
  an ntfy access token, optional — sent as a bearer, never logged; an unreadable one disables sending rather than
64
68
  sending unauthenticated), `quiet_when_device_active_s` (default 120; 0 never suppresses), `action_url` (optional
65
- template, e.g. `https://lanes.example/?lane={lane}`; plan W10 W7 adds `{doc}`, the page `/lanes-docs/d/<id>` of the
66
- document a `published` push names — empty for a needs-you push; the docs service sends those, W4). Without a valid
67
- `url` and `topic` the service only tracks
68
- transitions and sends nothing. The config is re-read when notify.conf OR its `token_file` changes (inode, size,
69
- mtime or ctime, so a token written, rotated, removed or chmod-ed after notify.conf counts), and on every tick while
70
- sending is disabled, so a token that becomes readable switches the pushes on within one interval.
69
+ template, e.g. `action_url=https://<server>:8443{doc}`; plan W10 W7 adds `{doc}`, the page `/lanes-docs/d/<id>` of
70
+ the document a `published` push names — empty for a needs-you push; the docs service sends those, W4) and `lane_url`
71
+ (optional, BEY-8667 E4: the needs-you push's tap target in place of `action_url`, e.g.
72
+ `lane_url=https://<server>:8443/<device>-phone?ws={ws}`, which opens that workspace's lane list on the phone view
73
+ `<device>-phone`; the published push keeps `action_url`; no default, so no push changes until it is set, apart from
74
+ an `action_url` that already holds `{ws}`, which was sent literally before E4). Both templates take `{lane}` (the lane
75
+ id), `{doc}` and `{ws}`, each percent-quoted: `{ws}` is the title of the lane's workspace in registry.json
76
+ (lane_workspaces), empty when unknown (a lane in no board's `lanes`, a title that is not a string or holds a lone
77
+ surrogate) and in every published push, so a template with `{ws}` sends workspace titles to the ntfy server. Without
78
+ a valid `url` and `topic` the service only tracks transitions and sends nothing. The config
79
+ is re-read when notify.conf OR its `token_file` changes (inode, size, mtime or ctime, so a token written, rotated,
80
+ removed or chmod-ed after notify.conf counts), and on every tick while sending is disabled, so a token that becomes
81
+ readable switches the pushes on within one interval.
71
82
 
72
83
  Answering a `PermissionRequest`-held approval FROM the phone needs a request/response channel back into the hook;
73
84
  that is a follow-up design, not part of this module.
@@ -96,7 +107,7 @@ LABELS = tokens.MOBILE_AGENT_LABELS # the phone's words: N
96
107
  PRIORITY = {'needs_approval': 4, 'errored': 4, 'needs_input': 3}
97
108
  DEFAULT_QUIET = 120
98
109
  DEFAULT_CONF = '~/.config/lanes/notify.conf'
99
- KEYS = ('url', 'topic', 'token_file', 'quiet_when_device_active_s', 'action_url')
110
+ KEYS = ('url', 'topic', 'token_file', 'quiet_when_device_active_s', 'action_url', 'lane_url')
100
111
  TOPIC = re.compile(r'^[A-Za-z0-9_-]{1,64}$')
101
112
  UNSAFE = re.compile(r'[\x00-\x1f\x7f-\x9f]') # C0, DEL, C1: never inside a push line
102
113
  TEXT_MAX = 200 # characters of the first payload line
@@ -124,7 +135,8 @@ def _line(text):
124
135
 
125
136
 
126
137
  def read_config(path):
127
- """notify.conf -> {url, topic, token_file, token, quiet_when_device_active_s, action_url, enabled}. Never raises."""
138
+ """notify.conf -> {url, topic, token_file, token, quiet_when_device_active_s, action_url, lane_url, enabled}; an
139
+ absent `action_url` or `lane_url` is ''. Never raises."""
128
140
  raw = {}
129
141
  try:
130
142
  lines = Path(os.path.expanduser(str(path))).read_text().splitlines()
@@ -144,7 +156,8 @@ def read_config(path):
144
156
  url = raw.get('url', '').rstrip('/')
145
157
  topic = raw.get('topic', '')
146
158
  config = {'url': url, 'topic': topic, 'token_file': raw.get('token_file', ''), 'token': None,
147
- 'quiet_when_device_active_s': quiet, 'action_url': raw.get('action_url', '')}
159
+ 'quiet_when_device_active_s': quiet, 'action_url': raw.get('action_url', ''),
160
+ 'lane_url': raw.get('lane_url', '')}
148
161
  enabled = url.startswith(('http://', 'https://')) and bool(TOPIC.match(topic))
149
162
  if enabled and config['token_file']:
150
163
  try:
@@ -180,6 +193,23 @@ def lane_names(registry):
180
193
  return out
181
194
 
182
195
 
196
+ def lane_workspaces(registry):
197
+ """registry.json -> {lane id: its workspace's title} over every workspace's `lanes`: the name of that workspace's
198
+ tabs in a phone view (its lane list is the tab `<title> ☰`), which `{ws}` carries (action_url). A hidden board is
199
+ mapped too; the page ignores a name no tab carries. A title that is not a string, or that holds a lone surrogate
200
+ (JSON can carry one as an escape, json.loads keeps it, and UTF-8 cannot encode it, so quoting it would raise and
201
+ lose the tick's pushes), is skipped: its lanes get an empty `{ws}`."""
202
+ out = {}
203
+ workspaces = registry.get('workspaces') if isinstance(registry, dict) else None
204
+ for ws in workspaces if isinstance(workspaces, list) else ():
205
+ if (isinstance(ws, dict) and isinstance(ws.get('title'), str)
206
+ and not re.search('[\ud800-\udfff]', ws['title'])):
207
+ for lane in ws.get('lanes') or ():
208
+ if isinstance(lane, dict) and isinstance(lane.get('id'), str):
209
+ out[lane['id']] = ws['title']
210
+ return out
211
+
212
+
183
213
  def is_mobile(devices_dir, device):
184
214
  """True when `STATE/devices/<device>.json` says `mobile: true` — the phone layout `lanes prepare|attach
185
215
  --mobile` created, the same mark the device's sidebar reads. Missing or unreadable meta is not mobile."""
@@ -287,26 +317,34 @@ def device_active(clients_dir, window, now, devices_dir=None, users_dir=None, me
287
317
  return any(within(at, window) for _login, at in marks)
288
318
 
289
319
 
290
- def action_url(template, lane_id, doc_id=None):
291
- """notify.conf's `action_url` template made a push's tap target -> the URL, or '' without a template. `{lane}` is
292
- the lane id; `{doc}` (plan W10 W7) the page of the document a `published` event is about, `/lanes-docs/d/<id>`
293
- (docs_store.URL; a docs_store id, else nothing), and nothing for an event without one (a needs-you push) — so
294
- `https://<host>:8443{doc}` opens the document. Both are percent-quoted."""
320
+ def action_url(template, lane_id, doc_id=None, ws=None):
321
+ """A notify.conf tap-target template (`action_url`, or `lane_url` for a needs-you push) made a push's tap target
322
+ -> the URL, or '' without a template. `{lane}` is the lane id; `{doc}` (plan W10 W7) the page of the document a
323
+ `published` event is about, `/lanes-docs/d/<id>` (docs_store.URL; a docs_store id, else nothing), and nothing for
324
+ an event without one (a needs-you push) — so `https://<host>:8443{doc}` opens the document; `{ws}` (BEY-8667 E4)
325
+ the title of the lane's workspace (`ws`, from lane_workspaces), and nothing when `ws` is not a string (an unknown
326
+ lane, and every published push) — so `https://<host>:8443/<device>-phone?ws={ws}` opens that workspace's lane
327
+ list on the phone view `<device>-phone`. All three are percent-quoted; `{doc}` keeps its slashes. `ws` is quoted
328
+ even when the template has no `{ws}`, so it must be a string UTF-8 can encode: one with a lone surrogate raises
329
+ UnicodeEncodeError, and lane_workspaces, which gives the service its `ws`, skips such a title."""
295
330
  if not template:
296
331
  return ''
297
332
  doc = docs_store.URL.format(doc_id) if isinstance(doc_id, str) and docs_store.ID_RE.match(doc_id) else ''
298
333
  return (template.replace('{lane}', urllib.parse.quote(lane_id, safe=''))
299
- .replace('{doc}', urllib.parse.quote(doc, safe='/')))
334
+ .replace('{doc}', urllib.parse.quote(doc, safe='/'))
335
+ .replace('{ws}', urllib.parse.quote(ws if isinstance(ws, str) else '', safe='')))
300
336
 
301
337
 
302
- def _note(lane_id, status, agent, names, config):
338
+ def _note(lane_id, status, agent, names, config, workspaces=None):
303
339
  label = LABELS.get(status, status)
304
340
  name = _text(names.get(lane_id) or lane_id)
305
341
  task = _text(agent.get('name'))
306
342
  first = _line(f'{name}: {task} — {label}' if task else f'{name} — {label}')
343
+ lane_url = config.get('lane_url') or ''
307
344
  note = {'lane': lane_id, 'status': status, 'title': label,
308
- 'message': f'{first}\nlanes-launch lane {lane_id}', 'priority': PRIORITY.get(status, 3)}
309
- url = action_url(config.get('action_url') or '', lane_id)
345
+ 'message': first if lane_url else f'{first}\nlanes-launch lane {lane_id}',
346
+ 'priority': PRIORITY.get(status, 3)}
347
+ url = action_url(lane_url or config.get('action_url') or '', lane_id, ws=(workspaces or {}).get(lane_id))
310
348
  if url:
311
349
  note['click'] = url
312
350
  note['actions'] = [{'action': 'view', 'label': 'Open lane', 'url': url}]
@@ -350,9 +388,11 @@ def notify_published(lane_id, meta, names=None, conf_path=None, state=None, now=
350
388
  return note if send(note, config, opener) else None
351
389
 
352
390
 
353
- def notify_changes(prev_status, new_status, config, names=None, now=None, clients_dir=None, devices_dir=None):
391
+ def notify_changes(prev_status, new_status, config, names=None, now=None, clients_dir=None, devices_dir=None,
392
+ workspaces=None):
354
393
  """The notifications for lanes whose agent status ENTERED needs-you between two status.json documents.
355
- `prev_status` None = the first read: seed only, nothing is news. Empty when a desk device is present."""
394
+ `prev_status` None = the first read: seed only, nothing is news. Empty when a desk device is present. `names`
395
+ (lane_names) names each lane; `workspaces` (lane_workspaces) fills `{ws}` in its tap target."""
356
396
  if prev_status is None:
357
397
  return []
358
398
  before = agent_statuses(prev_status)
@@ -366,7 +406,8 @@ def notify_changes(prev_status, new_status, config, names=None, now=None, client
366
406
  if device_active(clients_dir if clients_dir is not None else L.STATE / 'clients', window, now, devices_dir):
367
407
  return []
368
408
  names = names or {}
369
- return [_note(lane_id, status, lanes[lane_id]['agent'], names, config) for lane_id, status in sorted(changed)]
409
+ return [_note(lane_id, status, lanes[lane_id]['agent'], names, config, workspaces)
410
+ for lane_id, status in sorted(changed)]
370
411
 
371
412
 
372
413
  def enrol_notes(requests, announced, now):
@@ -470,7 +511,7 @@ class Watcher:
470
511
  self.prev = None
471
512
  self.stamps = {}
472
513
  self.config = None
473
- self.names = {}
514
+ self.names, self.workspaces = {}, {}
474
515
  self.enrol_due = True
475
516
  self.announced = read_announced(self.state / ENROL_SEEN)
476
517
  self._config_tick()
@@ -504,7 +545,8 @@ class Watcher:
504
545
  def tick(self):
505
546
  self._config_tick()
506
547
  if self._changed('registry', self.state / 'registry.json'):
507
- self.names = lane_names(L.read_json(self.state / 'registry.json'))
548
+ registry = L.read_json(self.state / 'registry.json')
549
+ self.names, self.workspaces = lane_names(registry), lane_workspaces(registry)
508
550
  return self._status_tick() + self._enrol_tick()
509
551
 
510
552
  def _status_tick(self):
@@ -514,7 +556,8 @@ class Watcher:
514
556
  if not isinstance(document, dict):
515
557
  return [] # a torn or missing file: keep the previous document
516
558
  notes = notify_changes(self.prev, document, self.config, names=self.names, now=self.clock(),
517
- clients_dir=self.state / 'clients', devices_dir=self.state / 'devices')
559
+ clients_dir=self.state / 'clients', devices_dir=self.state / 'devices',
560
+ workspaces=self.workspaces)
518
561
  self.prev = document
519
562
  if not self.config['enabled']:
520
563
  return []
@@ -344,3 +344,8 @@ def reregister(record):
344
344
  raise L.LanesError('Session could not be checked; nothing was registered')
345
345
  data['sessions'].append(saved)
346
346
  return _save(registry, data, board, saved['id'])
347
+
348
+
349
+ # lanes site-hook loader (FLE-388)
350
+ import site_hooks
351
+ site_hooks.apply('actions', globals(), 'registrations')
@@ -301,29 +301,46 @@ def promote_to_registered(workspace_id, entry, registry, name=None):
301
301
  if not socket_name or not session_name:
302
302
  raise L.LanesError('Session has no tmux binding; cannot promote')
303
303
  name = L._title(entry.get('name', session_name) if name is None else name)
304
- data = json.loads(terminals_path.read_text())
305
- terminals = data.get('terminals') or []
306
- lane_block = data.setdefault('lanes', {})
307
- lane_terminals = lane_block.setdefault('terminals', {})
308
- # A session this file already binds — under any name — is promoted already: the next sync lists its lane. A
309
- # second terminal bound to it would give one tmux session two lanes (DEF-1555's shape), and the registry cannot
310
- # say so between the write and the sync that lists it: a `P` on another device, or on this one after the sidebar
311
- # let the row go (S8 fix cycle 1, DEF-1762). So the file is asked, as build_registry reads it. Nothing is written.
312
- for terminal in terminals:
313
- bound = L.declared_tmux(data, terminal.get('name')) or {}
314
- if (bound.get('socketName'), bound.get('sessionName')) == (socket_name, session_name):
315
- raise L.LanesError(f"Already declared as {terminal.get('name')!r}; lanes sync lists it")
316
- # Guard: do not overwrite an existing registered terminal with the same name
317
- if any(t.get('name') == name for t in terminals):
318
- raise L.LanesError(f'A terminal named {name!r} already exists; rename it first')
319
- if name in lane_terminals:
320
- raise L.LanesError(f'A binding for {name!r} already exists; rename it first')
321
- terminals.append({'name': name, 'command': entry.get('create') or ''})
322
- lane_terminals[name] = {'holder': 'tmux', 'tmux': {'socketName': socket_name, 'sessionName': session_name}}
323
- if entry.get('create'):
324
- lane_terminals[name]['create'] = entry['create']
325
- data['terminals'] = terminals
326
- L.atomic_write(terminals_path, json.dumps(data, indent=2, ensure_ascii=False) + '\n', mode=0o644)
304
+ core = L.lane_core()
305
+
306
+ def mutate(text):
307
+ """The promotion as a delta on the file as it is under its lock (BEY-7435: never on bytes read before)."""
308
+ if text is None:
309
+ raise L.LanesError(f'Registry file not found: {terminals_path}')
310
+ data = json.loads(text)
311
+ terminals = data.get('terminals') or []
312
+ lane_block = data.setdefault('lanes', {})
313
+ lane_terminals = lane_block.setdefault('terminals', {})
314
+ # A session this file already binds — under any name — is promoted already: the next sync lists its lane. A
315
+ # second terminal bound to it would give one tmux session two lanes (DEF-1555's shape), and the registry
316
+ # cannot say so between the write and the sync that lists it: a `P` on another device, or on this one after
317
+ # the sidebar let the row go (S8 fix cycle 1, DEF-1762). So the file is asked, as build_registry reads it.
318
+ # Nothing is written.
319
+ for terminal in terminals:
320
+ bound = L.declared_tmux(data, terminal.get('name')) or {}
321
+ if (bound.get('socketName'), bound.get('sessionName')) == (socket_name, session_name):
322
+ raise L.LanesError(f"Already declared as {terminal.get('name')!r}; lanes sync lists it")
323
+ # BEY-7435: a binding that lost its board row is that lane's, not a new one's: a second binding of the same
324
+ # session would leave two declarations of it. `lanes register` puts the row back (repair_dangling).
325
+ for held, binding in core.dangling_bindings(data):
326
+ if core._binding(binding) == (socket_name, session_name):
327
+ raise L.LanesError(f"Its binding {held!r} lost its board row: `lanes register {entry.get('id')}` puts "
328
+ 'the row back; nothing was promoted')
329
+ # Guard: do not overwrite an existing registered terminal with the same name
330
+ if any(t.get('name') == name for t in terminals):
331
+ raise L.LanesError(f'A terminal named {name!r} already exists; rename it first')
332
+ if name in lane_terminals:
333
+ raise L.LanesError(f'A binding for {name!r} already exists; rename it first')
334
+ terminals.append({'name': name, 'command': entry.get('create') or ''})
335
+ lane_terminals[name] = {'holder': 'tmux', 'tmux': {'socketName': socket_name, 'sessionName': session_name}}
336
+ if entry.get('create'):
337
+ lane_terminals[name]['create'] = entry['create']
338
+ data['terminals'] = terminals
339
+ return json.dumps(data, indent=2, ensure_ascii=False) + '\n'
340
+ try:
341
+ core.update_terminals(terminals_path, mutate, root=info['home'])
342
+ except core.LaneError as error:
343
+ raise L.LanesError(str(error)) from error
327
344
  # Remove the user-sessions metadata — the terminal is now governed by the registry
328
345
  meta_path = L.STATE / 'user-sessions' / (entry['id'] + '.json')
329
346
  meta_path.unlink(missing_ok=True)
@@ -342,9 +359,10 @@ class DeclaredRefused(L.LanesError):
342
359
  def unregister_declared(source_path, name, root=None):
343
360
  """Remove the declared terminal `name` from the terminals.json at `source_path` (the HOST path: L.host_path of the
344
361
  lane's `source`) — its `terminals[]` item and its `lanes.terminals` entry — with the editor lane-mcp's
345
- `lanes_unregister` runs in the container (lane_core.terminals_remove through edit_file): one span, re-read before
346
- the atomic write, the file's mode kept, never the root `throttle` object, never a rename or reorder, never the
347
- last terminal. `root` is the container's home volume: a symbolic link at or above the file below it refuses
362
+ `lanes_unregister` runs in the container (lane_core.terminals_remove through update_terminals, BEY-7435): the
363
+ file's lock, the file re-read under it, one span, the atomic write, the file's mode kept, never the root
364
+ `throttle` object, never a rename or reorder, never the last terminal, never another lane's row. `root` is the
365
+ container's home volume: a symbolic link at or above the file below it refuses
348
366
  (`source_link`; from the host it would resolve outside the container, the DEF-1796 class). The session keeps
349
367
  running and shows as an unregistered session once `lanes sync` has run (callers run it; lanes-statusd's
350
368
  hot-sync also starts one within ~15 s of the edit). -> {'path', 'name', 'changed': bool}. DeclaredRefused
@@ -357,12 +375,76 @@ def unregister_declared(source_path, name, root=None):
357
375
  raise core.LaneError(f'{source_path} does not exist', 'source_missing')
358
376
  return core.terminals_remove(text, name)
359
377
  try:
360
- before, after, _backup = core.edit_file(Path(source_path), transform, root=root)
378
+ before, after = core.update_terminals(Path(source_path), transform, root=root, removes=(name,))
361
379
  except core.LaneError as error:
362
380
  raise DeclaredRefused(str(error), error.code or 'refused') from error
363
381
  return {'path': str(source_path), 'name': name, 'changed': before != after}
364
382
 
365
383
 
384
+ def repair_dangling(registry, wanted, workspace=None, status=None, containers=None):
385
+ """`lanes register <id>` on a session whose terminals.json binding lost its board row (BEY-7435): `wanted` is the
386
+ unregistered session's id (as `lanes ls --unregistered` and status.json list it, the binding's tmux target matched
387
+ in its container) or the lane id the binding stands for (its recorded `id`, else the one `lanes sync` derives from
388
+ its declared name: what `lanes doctor` names). The row is put back with the editor lane-mcp's `lanes_register`
389
+ repairs with (lane_core.terminals_redeclare through update_terminals, `root` the container's home volume): the
390
+ same id, the same tmux target, the declared name the binding is keyed by; the binding and the session untouched.
391
+ -> {'outcome': 'repaired_from_binding', 'lane', 'board', 'name', 'source', 'path', 'tmux', 'changed'}, or None
392
+ when `wanted` names no dangling binding (then `lanes register` adopts the session as before). DeclaredRefused for
393
+ a refusal of the editor; LanesError when two files hold such a binding, `workspace` is not the binding's board,
394
+ the id cannot be known, the binding records an id its name does not give (lane_core.lane_id_agrees), or its tmux
395
+ session is no running unregistered session (status.json)."""
396
+ core = L.lane_core()
397
+ status = (L.read_json(L.STATE / 'status.json', {}) or {}) if status is None else status
398
+ containers = (L.read_json(L.STATE / 'containers.json', {}) or {}) if containers is None else containers
399
+ ghost = next((row for rows in (status.get('unregistered') or {}).values() if isinstance(rows, list)
400
+ for row in rows if isinstance(row, dict) and row.get('id') == wanted), None)
401
+ hits = []
402
+ for fact in L.registry_bindings(registry, containers):
403
+ for item in fact['dangling']:
404
+ target = (fact['container'], item['tmux']['socket'], item['tmux']['session'])
405
+ if item['lane_id'] == wanted or (ghost is not None and session_key(ghost) == target):
406
+ hits.append((fact, item))
407
+ if not hits:
408
+ return None
409
+ if workspace is not None:
410
+ mine = [(fact, item) for fact, item in hits if fact['board'] == workspace]
411
+ if not mine:
412
+ raise L.LanesError(f"{wanted} is a binding of board {hits[0][0]['board']}, not of {workspace}")
413
+ hits = mine
414
+ if len({(fact['container'], fact['source']) for fact, _item in hits}) > 1:
415
+ raise L.LanesError(f'{len(hits)} terminals.json files bind {wanted} without a board row: '
416
+ + '; '.join(f"{fact['container']}:{fact['source']}" for fact, _item in hits)
417
+ + ' — put the row back by hand')
418
+ fact, item = hits[0]
419
+ # Validated before anything is written (BEY-7435 review): the id the row will open must be the one the binding's
420
+ # name gives, and the binding's tmux session must be a live session of its container that nothing declares.
421
+ if not item['derived']:
422
+ raise L.LanesError(f"cannot tell which id board {fact['board']} gives {item['name']!r}: its manifest cannot "
423
+ 'be read; nothing was written')
424
+ if item['id'] and not core.lane_id_agrees(item['id'], item['derived']):
425
+ raise L.LanesError(f"the binding {item['name']!r} in {fact['source']} records the lane id {item['id']!r}, but "
426
+ f"its name gives {item['derived']!r}: nothing was written; check that binding by hand")
427
+ target = (fact['container'], item['tmux']['socket'], item['tmux']['session'])
428
+ live = any(isinstance(row, dict) and session_key(row) == target
429
+ for rows in (status.get('unregistered') or {}).values() if isinstance(rows, list) for row in rows)
430
+ if not live:
431
+ raise L.LanesError(f"tmux {target[1]}/{target[2]} of the binding {item['name']!r} is no running unregistered "
432
+ f'session of {target[0]} (status.json lists none): nothing was written')
433
+ lane_id = item['id'] or item['derived']
434
+
435
+ def transform(text):
436
+ if text is None:
437
+ raise core.LaneError(f"{fact['source']} does not exist", 'source_missing')
438
+ return core.terminals_redeclare(text, item['name'], lane_id)
439
+ try:
440
+ before, after = core.update_terminals(fact['path'], transform, root=fact['home'])
441
+ except core.LaneError as error:
442
+ raise DeclaredRefused(str(error), error.code or 'refused') from error
443
+ return {'outcome': 'repaired_from_binding', 'lane': lane_id, 'board': fact['board'], 'name': item['name'],
444
+ 'source': fact['source'], 'path': str(fact['path']), 'tmux': dict(item['tmux']),
445
+ 'changed': before != after}
446
+
447
+
366
448
  def unregister_lane(lane_id, registry=None):
367
449
  """unregister_declared for a lane of the published registry: a DECLARED tmux lane (a terminals.json `source`),
368
450
  never an adopted session (`registered_session`: registered-sessions.json is its authority) or an unregistered
@@ -551,3 +633,8 @@ def _close_session(workspace, entry, unattended=False, *, idle_before=None):
551
633
  for directory in ('resolve.dynamic', 'user-sessions'):
552
634
  path = L.STATE / directory / (entry['id'] + ('.json' if directory == 'user-sessions' else ''))
553
635
  path.unlink(missing_ok=True)
636
+
637
+
638
+ # lanes site-hook loader (FLE-388)
639
+ import site_hooks
640
+ site_hooks.apply('actions', globals(), 'session_actions')