@vibelord/lanes 1.7.4 → 1.7.5
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.
- package/package.json +1 -1
- package/payload/lanes/VERSION +1 -1
- package/payload/lanes/bin/lanes +31 -7
- package/payload/lanes/bin-rs/BINARIES.json +1 -1
- package/payload/lanes/container/lane-mcp +17 -14
- package/payload/lanes/container/lane_core.py +13 -7
- package/payload/lanes/docs/ARCHITECTURE.md +29 -7
- package/payload/lanes/docs/RUNBOOK.md +165 -29
- package/payload/lanes/docs/USERGUIDE.md +71 -3
- package/payload/lanes/install/host-install.sh +21 -1
- package/payload/lanes/libexec/adopt.py +49 -10
- package/payload/lanes/libexec/attach.py +35 -5
- package/payload/lanes/libexec/doctor_lanes2.py +113 -42
- package/payload/lanes/libexec/gc_unregistered.py +407 -0
- package/payload/lanes/libexec/lanes_lib.py +13 -4
- package/payload/lanes/libexec/native_bin.py +12 -10
- package/payload/lanes/libexec/session_actions.py +85 -7
- package/payload/lanes/libexec/update.py +34 -7
- package/payload/lanes/systemd/lanes-gc.service +1 -1
- package/payload/lanes/systemd/lanes-gc.timer +14 -3
- package/payload/lanes/web/Caddyfile +11 -0
- package/payload/lanes/web/README.md +123 -2
- package/payload/lanes/web/inbox.js +1140 -0
- package/payload/lanes/web/mobile.js +20 -26
- package/payload/manifest.json +3 -3
|
@@ -0,0 +1,407 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""`lanes gc --unregistered [--write] [--board B]`: end the unregistered tmux sessions in which nothing runs.
|
|
3
|
+
Python 3 stdlib.
|
|
4
|
+
|
|
5
|
+
Ending a lane stays a person's call (lanes/docs/ARCHITECTURE.md "What stays with a person"). This sweep is the
|
|
6
|
+
operator's standing instruction for one site ("unless they are running live"), and it is opt-in: site.conf
|
|
7
|
+
`LANES_GC_UNREGISTERED=1` (default off) makes the daily `lanes gc` (lanes-gc.timer, at midnight) run it in write mode
|
|
8
|
+
after its other tasks; `LANES_GC_IDLE_S` (seconds, default 21600 = 6 h, at least 3600) is how long a session's last
|
|
9
|
+
output must lie back. A raw site.conf line naming a LANES_GC_ key that lanes_lib.SITE_LINE refuses (a trailing comment,
|
|
10
|
+
quotes, a space) refuses the sweep — nothing is ended, `lanes doctor` names the line — rather than being read as unset.
|
|
11
|
+
It reads only status.json's `unregistered` rows (statusd's tmux sessions no registry declares — unregistered, including
|
|
12
|
+
a lane a person unregistered while it ran), so a registered lane is never one.
|
|
13
|
+
|
|
14
|
+
The rule (decided in the review of PR #750): a session is ended only on POSITIVE evidence that nothing runs in it —
|
|
15
|
+
1. its agent's status is `shell` (the harness ended into its shell), or it has no agent and its pane's command is a
|
|
16
|
+
bare shell (agent_state.SHELL_COMMANDS, normalised as agent_state does), or its pane is dead; and
|
|
17
|
+
2. just before the close, a live probe of every pane of the session (every window: `list-panes -s`, through
|
|
18
|
+
L.tmux_probe, the typed route close_session asks) shows each pane dead, or a bare shell with no process under it
|
|
19
|
+
(agent_state.child_liveness over the container's /proc: a harness started as `bash -c '<harness> …'` leaves the
|
|
20
|
+
shell as tmux's foreground command, so the command alone is no evidence).
|
|
21
|
+
Every other agent — errored, done, needs_input, needs_approval, working, idle, or a status this sweep does not know —
|
|
22
|
+
keeps the session: every harness prompt survives, as Lanes' own "Needs you" and "Done stays until you open the lane".
|
|
23
|
+
|
|
24
|
+
Each session gets one line, `<verdict>: <reason> — <id> (<container> <socket>/<session>)`. A session is kept when ANY
|
|
25
|
+
of these holds, checked in this order (the first one found is the reason):
|
|
26
|
+
|
|
27
|
+
keep: not closable (…) no closable tmux row (a retired legacy shell, a row marked unclosable)
|
|
28
|
+
keep: behind guest:<alias> (…) its container is reached through a guest: the guest's own Lanes sweeps it
|
|
29
|
+
keep: not typed here (…) no local write route: reached only through a tmux_probe hook, or not at all
|
|
30
|
+
keep: unobserved (…) status.json older than STATUS_FRESH_S, no row, a `stale` row, state
|
|
31
|
+
`unknown`, a row without its client counts or (no agent) its pane command:
|
|
32
|
+
no evidence is never "idle"
|
|
33
|
+
keep: attached a terminal is attached to it (or to a session viewing it)
|
|
34
|
+
keep: viewers N N sessions view it (a Studio browser's grouped `view-…` session)
|
|
35
|
+
keep: agent <status> an agent whose status is not `shell`: errored, done, needs_input,
|
|
36
|
+
needs_approval, working, idle, … (a harness prompt is live)
|
|
37
|
+
keep: runs <command> no agent, and the pane's command is no bare shell (vim, python3, ssh, tail)
|
|
38
|
+
keep: active <age> ago state `active`, or output newer than LANES_GC_IDLE_S
|
|
39
|
+
keep: state <state> any state but `quiet` or `dead`
|
|
40
|
+
keep: no output time the row carries no `activity` (the newest window_activity): fail closed
|
|
41
|
+
keep: runs <command> the pane probe: another pane runs it (a Claude in window 1 behind a bash)
|
|
42
|
+
keep: runs a process under <shell> the pane probe: a live bare-shell pane has a child process
|
|
43
|
+
keep: panes not checked (…) the pane probe did not answer, listed no pane or a line it cannot read, or a
|
|
44
|
+
pane's children could not be read
|
|
45
|
+
reap: idle <age>, <what>, no client everything else (<what>: `agent shell`, `pane dead` or `no agent`)
|
|
46
|
+
|
|
47
|
+
Without --write nothing is ended; the dry run still probes each `reap` candidate's panes (read-only), so it says what a
|
|
48
|
+
write would do. With --write each candidate is read again from a fresh status.json, judged again, its panes probed,
|
|
49
|
+
and ended through session_actions.close_idle_session. Under the registry lock it rechecks cached eligibility and
|
|
50
|
+
every pane's process evidence. The final tmux predicate requires the exact identity, no client or session group,
|
|
51
|
+
and positive, old activity on every window. GC never kills a viewer to make the session eligible. Its line becomes `ended: …` (the
|
|
52
|
+
journal line: under the timer stdout is `journalctl --user -u lanes-gc.service`) or `not ended: <why> — …`; a write
|
|
53
|
+
records the run in $LANES_STATE/gc-unregistered.json (DM-LANES-GC-UNREGISTERED: `by` is `timer` when systemd started
|
|
54
|
+
the process — it sets INVOCATION_ID for every unit it runs — else `hand`), which `lanes doctor` reads. Exit 0 whatever
|
|
55
|
+
was found.
|
|
56
|
+
"""
|
|
57
|
+
import json
|
|
58
|
+
import math
|
|
59
|
+
import os
|
|
60
|
+
import time
|
|
61
|
+
from pathlib import Path
|
|
62
|
+
|
|
63
|
+
import agent_state as AS
|
|
64
|
+
import lanes_lib as L
|
|
65
|
+
|
|
66
|
+
SWITCH = 'LANES_GC_UNREGISTERED' # site.conf: 1 = the daily `lanes gc` runs the sweep with --write; else off
|
|
67
|
+
IDLE_KEY = 'LANES_GC_IDLE_S' # site.conf: seconds since the last output before a session may be ended
|
|
68
|
+
KEY_PREFIX = 'LANES_GC_' # a raw site.conf line naming such a key that SITE_LINE refuses refuses the sweep
|
|
69
|
+
IDLE_DEFAULT = 21600 # 6 h
|
|
70
|
+
IDLE_MIN = 3600 # a smaller value is refused: the sweep then ends nothing
|
|
71
|
+
STATUS_FRESH_S = 30 # status.json older than this (statusd rewrites it every 15 s): nothing is observed
|
|
72
|
+
STATE_FILE = 'gc-unregistered.json' # under $LANES_STATE: the last write run
|
|
73
|
+
REAPABLE_AGENT = ('shell',) # agent_state.STATUSES: the one word that says the harness ended into its shell
|
|
74
|
+
REAPABLE_STATE = ('quiet', 'dead') # statusd's `state` words a session may be ended in (never `active`)
|
|
75
|
+
# The pane probe: every pane of the session (`-s`: all its windows), its foreground command, whether it is dead and its
|
|
76
|
+
# root pid (the container's pid: its children are read in the container's /proc).
|
|
77
|
+
PANES_FORMAT = '#{pane_current_command}\t#{pane_dead}\t#{pane_pid}'
|
|
78
|
+
PROBE_TIMEOUT = 5 # seconds, as close_session's own tmux questions
|
|
79
|
+
SHOWN_MAX = 160 # characters of a refused site.conf line a message repeats
|
|
80
|
+
USAGE = 'usage: lanes gc [--unregistered [--write] [--board B]]'
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def is_count(value):
|
|
84
|
+
return isinstance(value, int) and not isinstance(value, bool) and value >= 0
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def ago(seconds):
|
|
88
|
+
"""A coarse age: `45s`, `12m`, `7h`, `3d` (days from two on)."""
|
|
89
|
+
seconds = max(0, int(seconds))
|
|
90
|
+
if seconds >= 2 * 86400:
|
|
91
|
+
return f'{seconds // 86400}d'
|
|
92
|
+
if seconds >= 3600:
|
|
93
|
+
return f'{seconds // 3600}h'
|
|
94
|
+
if seconds >= 60:
|
|
95
|
+
return f'{seconds // 60}m'
|
|
96
|
+
return f'{seconds}s'
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def span(seconds):
|
|
100
|
+
"""An exact setting: `6h`, `1h30m`, `90s`."""
|
|
101
|
+
hours, rest = divmod(int(seconds), 3600)
|
|
102
|
+
minutes, secs = divmod(rest, 60)
|
|
103
|
+
if secs:
|
|
104
|
+
return f'{int(seconds)}s'
|
|
105
|
+
return (f'{hours}h' if hours else '') + (f'{minutes}m' if minutes else '') or '0s'
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def switch_text(settings):
|
|
109
|
+
"""`on (LANES_GC_UNREGISTERED=1)`, `off (LANES_GC_UNREGISTERED unset)` or `off (LANES_GC_UNREGISTERED=<value>)`."""
|
|
110
|
+
value = settings.get(SWITCH)
|
|
111
|
+
if value == '1':
|
|
112
|
+
return f'on ({SWITCH}=1)'
|
|
113
|
+
return f'off ({SWITCH} unset)' if value is None else f'off ({SWITCH}={value})'
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def printable(text):
|
|
117
|
+
return ''.join(char if char.isprintable() else '?' for char in str(text))
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def read_site(home=None):
|
|
121
|
+
"""(settings, refused): site.conf's LANES_* facts read as lanes_lib.site_conf reads them (SITE_LINE; the last line
|
|
122
|
+
naming a key wins), and the raw lines that name a LANES_GC_ key outside a comment (before any `#`) but SITE_LINE
|
|
123
|
+
refuses — a trailing comment, quotes, a trailing space, a leading blank, an `export`. Such a line is REFUSED, never
|
|
124
|
+
read as unset (that would leave the switch silently off, or the floor silently IDLE_DEFAULT): the sweep ends nothing
|
|
125
|
+
and `lanes doctor` names it, as bin/lanes fleet_dashboard_url judges its own key's raw lines. A comment line (`#`
|
|
126
|
+
first) names nothing, and neither does another key's line whose comment mentions one. ({}, []) without a readable
|
|
127
|
+
file."""
|
|
128
|
+
try:
|
|
129
|
+
text = ((Path(home) if home is not None else Path.home()) / L.SITE_CONF).read_text()
|
|
130
|
+
except (OSError, UnicodeDecodeError, KeyError, RuntimeError):
|
|
131
|
+
return {}, []
|
|
132
|
+
lines = text.splitlines()
|
|
133
|
+
settings = dict(match.groups() for match in map(L.SITE_LINE.match, lines) if match)
|
|
134
|
+
refused = [line for line in lines if KEY_PREFIX in line.split('#', 1)[0] and not L.SITE_LINE.match(line)]
|
|
135
|
+
return settings, refused
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def refusal(refused):
|
|
139
|
+
"""The words for read_site's refused lines: the first one, quoted, and how many more."""
|
|
140
|
+
first = printable(refused[0])
|
|
141
|
+
first = first if len(first) <= SHOWN_MAX else first[:SHOWN_MAX - 1] + '…'
|
|
142
|
+
more = f' (and {len(refused) - 1} more)' if len(refused) > 1 else ''
|
|
143
|
+
return (f'site.conf line `{first}`{more} is refused: a LANES_GC_ line is KEY=VALUE alone '
|
|
144
|
+
'(no comment, quote or space after the value)')
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def invoker(environ=None):
|
|
148
|
+
"""The run record's `by`: `timer` when systemd started this process (it sets INVOCATION_ID for every unit it runs —
|
|
149
|
+
lanes-gc.service, under lanes-gc.timer), else `hand`."""
|
|
150
|
+
return 'timer' if (os.environ if environ is None else environ).get('INVOCATION_ID') else 'hand'
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def idle_floor(settings, refused=()):
|
|
154
|
+
"""(seconds, None) from site.conf's LANES_GC_IDLE_S (default IDLE_DEFAULT), or (None, why): a LANES_GC_ line
|
|
155
|
+
SITE_LINE refused (`refused`, read_site's), or a value that is not a whole number of seconds of at least IDLE_MIN."""
|
|
156
|
+
if refused:
|
|
157
|
+
return None, refusal(refused)
|
|
158
|
+
value = settings.get(IDLE_KEY)
|
|
159
|
+
if value is None:
|
|
160
|
+
return IDLE_DEFAULT, None
|
|
161
|
+
if not value.isdigit() or int(value) < IDLE_MIN:
|
|
162
|
+
return None, f'{IDLE_KEY}={value} is not a whole number of seconds ≥ {IDLE_MIN}'
|
|
163
|
+
return int(value), None
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def who(entry):
|
|
167
|
+
binding = entry.get('tmux') if isinstance(entry.get('tmux'), dict) else {}
|
|
168
|
+
return printable(f"{entry.get('id')} ({entry.get('container')} {binding.get('socket')}/{binding.get('session')})")
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def bare_shell(command):
|
|
172
|
+
"""Whether a pane's foreground command is a bare shell, by agent_state's own test (`_shell_foreground`: a login
|
|
173
|
+
shell's `-bash` and a path normalised, SHELL_COMMANDS); anything else, an empty or absent command included, is not."""
|
|
174
|
+
return isinstance(command, str) and AS._shell_foreground({'pane_current_command': command})
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def verdict(entry, row, info, now, floor, status_age):
|
|
178
|
+
"""('keep' | 'reap', reason) for one `unregistered` entry: `row` its status.json `lanes` row (None: none), `info`
|
|
179
|
+
its container's containers.json record, `status_age` the seconds since statusd wrote status.json. See the module
|
|
180
|
+
docstring for the order; anything this function cannot read is a keep."""
|
|
181
|
+
if entry.get('holder') != 'tmux' or entry.get('legacy') or not entry.get('closable'):
|
|
182
|
+
return 'keep', 'not closable (no tmux session the sidebar could close)'
|
|
183
|
+
binding = entry.get('tmux') if isinstance(entry.get('tmux'), dict) else {}
|
|
184
|
+
route, why = L.write_route(entry.get('container'), info, binding.get('socket'))
|
|
185
|
+
if route is None:
|
|
186
|
+
return 'keep', f'not typed here ({why})'
|
|
187
|
+
if route.startswith(L.GUEST_PREFIX):
|
|
188
|
+
return 'keep', f'behind {route} (its guest sweeps)'
|
|
189
|
+
if route != L.TRANSPORT_LOCAL:
|
|
190
|
+
return 'keep', f'not typed here ({route}: no local write route; its own host sweeps)'
|
|
191
|
+
if not math.isfinite(status_age) or status_age < 0:
|
|
192
|
+
return 'keep', 'unobserved (invalid status timestamp)'
|
|
193
|
+
if status_age > STATUS_FRESH_S:
|
|
194
|
+
return 'keep', f'unobserved (status.json {ago(status_age)} old: is lanes-statusd running?)'
|
|
195
|
+
if not isinstance(row, dict):
|
|
196
|
+
return 'keep', 'unobserved (no status row)'
|
|
197
|
+
if row.get('stale'):
|
|
198
|
+
return 'keep', 'unobserved (stale: its tmux server did not answer)'
|
|
199
|
+
if row.get('state') in (None, 'unknown'):
|
|
200
|
+
return 'keep', 'unobserved (unknown)'
|
|
201
|
+
clients, viewers = row.get('attached'), row.get('viewers', 0)
|
|
202
|
+
if not is_count(clients) or not is_count(viewers):
|
|
203
|
+
return 'keep', 'unobserved (no client count)'
|
|
204
|
+
if row['attached'] > 0:
|
|
205
|
+
return 'keep', 'attached'
|
|
206
|
+
if viewers > 0:
|
|
207
|
+
return 'keep', f'viewers {viewers}'
|
|
208
|
+
agent, state = row.get('agent'), row.get('state')
|
|
209
|
+
status = agent.get('status') if isinstance(agent, dict) else None
|
|
210
|
+
if agent is not None and status not in REAPABLE_AGENT:
|
|
211
|
+
return 'keep', f'agent {printable(status) if isinstance(status, str) else "?"}'
|
|
212
|
+
command = row.get('command')
|
|
213
|
+
if agent is None and state != 'dead':
|
|
214
|
+
if not isinstance(command, str) or not command:
|
|
215
|
+
return 'keep', 'unobserved (no pane command)'
|
|
216
|
+
if not bare_shell(command):
|
|
217
|
+
return 'keep', f'runs {printable(command)}'
|
|
218
|
+
activity = row.get('activity')
|
|
219
|
+
known = (isinstance(activity, (int, float)) and not isinstance(activity, bool)
|
|
220
|
+
and math.isfinite(activity) and activity > 0)
|
|
221
|
+
if row.get('state') == 'active':
|
|
222
|
+
return 'keep', f'active {ago(now - activity)} ago' if known else 'active now'
|
|
223
|
+
if state not in REAPABLE_STATE:
|
|
224
|
+
return 'keep', f'state {printable(state)}'
|
|
225
|
+
if not known:
|
|
226
|
+
return 'keep', 'no output time'
|
|
227
|
+
idle = now - activity
|
|
228
|
+
if idle < floor:
|
|
229
|
+
return 'keep', f'active {ago(idle)} ago'
|
|
230
|
+
what = f'agent {status}' if agent is not None else ('pane dead' if state == 'dead' else 'no agent')
|
|
231
|
+
return 'reap', f'idle {ago(idle)}, {what}, no client'
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def nothing_runs(entry, info):
|
|
235
|
+
"""The second half of the rule, asked live -> (True, None) when every pane of `entry`'s session (`list-panes -s`:
|
|
236
|
+
every window) is dead, or a bare shell (bare_shell) with no process under it (agent_state.child_liveness over the
|
|
237
|
+
container's /proc, read from this host: False); else (False, why) — `runs <command>`, `runs a process under
|
|
238
|
+
<shell>`, or `panes not checked (…)` for a probe that did not answer `ok`, listed no pane or a line it cannot read,
|
|
239
|
+
or a child read that failed. One read-only tmux question through L.tmux_probe (the typed route close_session asks),
|
|
240
|
+
the session named `=<name>:` as there (exact; a trailing `;` cannot end the tmux command). `info` is the container's
|
|
241
|
+
containers.json record."""
|
|
242
|
+
binding = entry.get('tmux') if isinstance(entry.get('tmux'), dict) else {}
|
|
243
|
+
outcome, listing = L.tmux_probe(info, binding.get('socket'),
|
|
244
|
+
['list-panes', '-s', '-t', '=' + str(binding.get('session')) + ':',
|
|
245
|
+
'-F', PANES_FORMAT], PROBE_TIMEOUT)
|
|
246
|
+
if outcome != 'ok':
|
|
247
|
+
return False, f'panes not checked ({printable(outcome)})'
|
|
248
|
+
panes = [line.split('\t') for line in (listing or '').splitlines() if line]
|
|
249
|
+
if not panes:
|
|
250
|
+
return False, 'panes not checked (none listed)'
|
|
251
|
+
shells = {}
|
|
252
|
+
for fields in panes:
|
|
253
|
+
if len(fields) != 3 or fields[1] not in ('0', '1'):
|
|
254
|
+
return False, 'panes not checked (a line it cannot read)'
|
|
255
|
+
command, dead, pid = fields
|
|
256
|
+
if dead == '1':
|
|
257
|
+
continue
|
|
258
|
+
if not bare_shell(command):
|
|
259
|
+
return False, f'runs {printable(command) or "?"}'
|
|
260
|
+
if not pid.isdigit() or int(pid) <= 0:
|
|
261
|
+
return False, 'panes not checked (no pane pid)'
|
|
262
|
+
shells[int(pid)] = command
|
|
263
|
+
if shells:
|
|
264
|
+
live = AS.child_liveness(Path(L.proc_root()) / str(info.get('pid')) / 'root' / 'proc', sorted(shells))
|
|
265
|
+
for pid, command in sorted(shells.items()):
|
|
266
|
+
if live.get(pid) is None:
|
|
267
|
+
return False, f'panes not checked (what runs under pane pid {pid} could not be read)'
|
|
268
|
+
if live[pid]:
|
|
269
|
+
return False, f'runs a process under {printable(command)}'
|
|
270
|
+
return True, None
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def listed(status, board=None):
|
|
274
|
+
"""[(board, entry)] of status.json's `unregistered` rows, each session once (a session no board could claim is
|
|
275
|
+
listed under every owner of its socket, with one id), in board order; only `board`'s when given. The board is the
|
|
276
|
+
one close_session is asked under: the entry's own `workspace` when that board lists it, else the first that does."""
|
|
277
|
+
owners, order = {}, []
|
|
278
|
+
groups = status.get('unregistered') if isinstance(status.get('unregistered'), dict) else {}
|
|
279
|
+
for name in sorted(groups):
|
|
280
|
+
if board is not None and name != board:
|
|
281
|
+
continue
|
|
282
|
+
for entry in groups[name] or ():
|
|
283
|
+
if isinstance(entry, dict) and isinstance(entry.get('id'), str) and entry['id']:
|
|
284
|
+
if entry['id'] not in owners:
|
|
285
|
+
owners[entry['id']] = []
|
|
286
|
+
order.append(entry)
|
|
287
|
+
owners[entry['id']].append(name)
|
|
288
|
+
return [(entry['workspace'] if entry.get('workspace') in owners[entry['id']] else owners[entry['id']][0], entry)
|
|
289
|
+
for entry in order]
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def judge(status, entry, containers, floor, now):
|
|
293
|
+
"""verdict() for `entry` as `status` (a whole status.json) shows it."""
|
|
294
|
+
rows = status.get('lanes') if isinstance(status.get('lanes'), dict) else {}
|
|
295
|
+
updated = status.get('updated_at')
|
|
296
|
+
age = now - updated if isinstance(updated, (int, float)) and not isinstance(updated, bool) else float('inf')
|
|
297
|
+
return verdict(entry, rows.get(entry['id']), containers.get(entry.get('container')) or {}, now, floor, age)
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
def read_status():
|
|
301
|
+
status = L.read_json(L.STATE / 'status.json')
|
|
302
|
+
return status if isinstance(status, dict) else {}
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
def sweep(write, board=None, by=None, out=print):
|
|
306
|
+
"""One pass: a line per session, then the summary; without `write` each `reap` candidate's panes are probed
|
|
307
|
+
(nothing_runs) so the line says what a write would do; with `write`, each candidate is ended (end) and the run
|
|
308
|
+
recorded, `by` (default invoker()). -> 0. Raises LanesError for a refused setting or an unknown board."""
|
|
309
|
+
settings, refused = read_site()
|
|
310
|
+
floor, problem = idle_floor(settings, refused)
|
|
311
|
+
if problem:
|
|
312
|
+
raise L.LanesError(f'gc unregistered: {problem}; nothing was ended')
|
|
313
|
+
status = read_status()
|
|
314
|
+
if board is not None:
|
|
315
|
+
registry = L.read_json(L.STATE / 'registry.json') or {}
|
|
316
|
+
known = {w.get('id') for w in registry.get('workspaces') or () if isinstance(w, dict)}
|
|
317
|
+
if board not in known | set(status.get('unregistered') or {}):
|
|
318
|
+
raise L.LanesError(f'Unknown workspace: {board}')
|
|
319
|
+
containers = L.read_json(L.STATE / 'containers.json') or {}
|
|
320
|
+
out(f'gc unregistered: {switch_text(settings)}, idle ≥ {span(floor)}'
|
|
321
|
+
+ ('' if write else ' — dry run: --write ends each reap'))
|
|
322
|
+
counts = {'ended': 0, 'not ended': 0, 'reap': 0, 'keep': 0}
|
|
323
|
+
for name, entry in listed(status, board):
|
|
324
|
+
said, reason = judge(status, entry, containers, floor, time.time())
|
|
325
|
+
if said == 'reap' and write:
|
|
326
|
+
said, reason = end(name, entry, containers, floor)
|
|
327
|
+
elif said == 'reap':
|
|
328
|
+
quiet, why = nothing_runs(entry, containers.get(entry.get('container')) or {})
|
|
329
|
+
if not quiet:
|
|
330
|
+
said, reason = 'keep', why
|
|
331
|
+
counts[said] += 1
|
|
332
|
+
out(f'{said}: {reason} — {who(entry)}')
|
|
333
|
+
if write:
|
|
334
|
+
record = {'v': 1, 'at': int(time.time()), 'by': invoker() if by is None else by, 'idle_s': floor,
|
|
335
|
+
'ended': counts['ended'],
|
|
336
|
+
'not_ended': counts['not ended'], 'kept': counts['keep']}
|
|
337
|
+
L.atomic_write(L.STATE / STATE_FILE, json.dumps(record) + '\n')
|
|
338
|
+
out(f"gc unregistered: ended {counts['ended']}, not ended {counts['not ended']}, kept {counts['keep']}")
|
|
339
|
+
else:
|
|
340
|
+
out(f"gc unregistered: {counts['reap']} to end, {counts['keep']} kept — "
|
|
341
|
+
'lanes gc --unregistered --write ends them')
|
|
342
|
+
return 0
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
def end(board, entry, containers, floor):
|
|
346
|
+
"""End one session judged `reap`: read status.json again and judge its row again (a person may have attached since
|
|
347
|
+
the listing), probe every pane (nothing_runs), then the guarded session_actions.close_idle_session
|
|
348
|
+
(cached policy and pane evidence under lock; live identity/client/group/activity condition) -> (verdict, reason)."""
|
|
349
|
+
import session_actions
|
|
350
|
+
status = read_status()
|
|
351
|
+
fresh = next((e for b, e in listed(status, board) if e['id'] == entry['id']), None)
|
|
352
|
+
if (fresh is None or session_actions.session_key(fresh) != session_actions.session_key(entry)
|
|
353
|
+
or fresh.get('identity') != entry.get('identity')):
|
|
354
|
+
return 'keep', 'gone or changed since the listing'
|
|
355
|
+
said, reason = judge(status, fresh, containers, floor, time.time())
|
|
356
|
+
if said != 'reap':
|
|
357
|
+
return 'keep', f'{reason} (since the listing)'
|
|
358
|
+
quiet, why = nothing_runs(fresh, containers.get(fresh.get('container')) or {})
|
|
359
|
+
if not quiet:
|
|
360
|
+
return 'keep', why
|
|
361
|
+
try:
|
|
362
|
+
session_actions.close_idle_session(board, fresh, idle_s=floor)
|
|
363
|
+
except (L.LanesError, OSError, ValueError) as error:
|
|
364
|
+
return 'not ended', str(error) or type(error).__name__
|
|
365
|
+
return 'ended', reason
|
|
366
|
+
|
|
367
|
+
|
|
368
|
+
def daily(out=print):
|
|
369
|
+
"""What the plain `lanes gc` (lanes-gc.timer) runs after its other tasks: nothing, silently, unless site.conf has
|
|
370
|
+
LANES_GC_UNREGISTERED=1; then the sweep with --write. A LANES_GC_ line SITE_LINE refuses (whatever the switch says)
|
|
371
|
+
or a refused LANES_GC_IDLE_S is one line, nothing ended."""
|
|
372
|
+
settings, refused = read_site()
|
|
373
|
+
if refused:
|
|
374
|
+
out(f'gc unregistered: {refusal(refused)}; nothing was ended')
|
|
375
|
+
return 0
|
|
376
|
+
if settings.get(SWITCH) != '1':
|
|
377
|
+
return 0
|
|
378
|
+
try:
|
|
379
|
+
return sweep(True, out=out)
|
|
380
|
+
except L.LanesError as error:
|
|
381
|
+
out(str(error))
|
|
382
|
+
return 0
|
|
383
|
+
|
|
384
|
+
|
|
385
|
+
def doctor_line(state=None, settings=None, refused=None):
|
|
386
|
+
"""`lanes doctor`'s one line -> (mark, text): an information line ('') with the switch, the idle floor and the last
|
|
387
|
+
write run (gc-unregistered.json; `(by hand)` unless the timer ran it); ⚠ naming a LANES_GC_ line SITE_LINE refuses
|
|
388
|
+
(whatever the switch says), or when the sweep is on but LANES_GC_IDLE_S is refused. `settings`/`refused` default to
|
|
389
|
+
read_site()'s."""
|
|
390
|
+
if settings is None:
|
|
391
|
+
settings, read = read_site()
|
|
392
|
+
refused = read if refused is None else refused
|
|
393
|
+
refused = refused or []
|
|
394
|
+
record = L.read_json((L.STATE if state is None else state) / STATE_FILE)
|
|
395
|
+
last = ''
|
|
396
|
+
if isinstance(record, dict) and is_count(record.get('at')):
|
|
397
|
+
when = time.strftime('%Y-%m-%d %H:%M UTC', time.gmtime(record['at']))
|
|
398
|
+
ended = record['ended'] if is_count(record.get('ended')) else '?'
|
|
399
|
+
last = f", last sweep {when}{' (by hand)' if record.get('by') == 'hand' else ''}: ended {ended}"
|
|
400
|
+
if refused:
|
|
401
|
+
return '⚠', f'gc unregistered: {refusal(refused)}: the sweep ends nothing'
|
|
402
|
+
if settings.get(SWITCH) != '1':
|
|
403
|
+
return '', f'gc unregistered: {switch_text(settings)}{last}'
|
|
404
|
+
floor, problem = idle_floor(settings)
|
|
405
|
+
if problem:
|
|
406
|
+
return '⚠', f'gc unregistered: on, but {problem}: the daily sweep ends nothing'
|
|
407
|
+
return '', f"gc unregistered: on, idle ≥ {span(floor)}{last or ', no sweep yet (lanes-gc.timer, at midnight)'}"
|
|
@@ -1064,9 +1064,16 @@ def _untypable(container, info):
|
|
|
1064
1064
|
return f"{NO_WRITE_TRANSPORT} {container} (its recorded init pid {info['pid']} does not run on this host)"
|
|
1065
1065
|
if info.get('home') and not info.get('error'):
|
|
1066
1066
|
return f'container {container} is not running'
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1067
|
+
if info.get('error'):
|
|
1068
|
+
detail = f"docker gave no answer about it: {info['error']}"
|
|
1069
|
+
elif container in _catalog()['routes']:
|
|
1070
|
+
detail = ('docker has no such container on this host, catalog.json names no "transport" for its board, and '
|
|
1071
|
+
'tmux_probe reaches no server there')
|
|
1072
|
+
else:
|
|
1073
|
+
# A registry lane of a container no catalog board names (a runtime hook folded a guest's lanes in: rd-control):
|
|
1074
|
+
# the remedy is a board, not a key on one.
|
|
1075
|
+
detail = ('docker has no such container on this host, no catalog.json board names it, and tmux_probe reaches '
|
|
1076
|
+
'no server there')
|
|
1070
1077
|
return f'{NO_WRITE_TRANSPORT} {container} ({detail})'
|
|
1071
1078
|
|
|
1072
1079
|
|
|
@@ -1323,9 +1330,11 @@ def transport_report(registry, containers, greet=True):
|
|
|
1323
1330
|
for name, socket in sorted(sockets.items()):
|
|
1324
1331
|
route, why = write_route(name, (containers or {}).get(name), socket)
|
|
1325
1332
|
if route is None and no_write_transport(why):
|
|
1333
|
+
remedy = ('name its board\'s "transport" in catalog.json' if name in _catalog()['routes'] else
|
|
1334
|
+
'give it a catalog.json board, with a manifest that names it and a "transport"')
|
|
1326
1335
|
lines.append((False, f'write transport for {name}',
|
|
1327
1336
|
f'not typed: {why} — upload --paste, lanes message, names sync, statusd\'s inbox drain and '
|
|
1328
|
-
'auto-rename type nothing into its lanes;
|
|
1337
|
+
f'auto-rename type nothing into its lanes; {remedy} '
|
|
1329
1338
|
'(guest:<ssh alias>, lanes-site/1: lanes/docs/RUNBOOK.md "Federation")'))
|
|
1330
1339
|
elif route == TRANSPORT_PROBE:
|
|
1331
1340
|
lines.append((True, f'write transport for {name}', 'tmux_probe reaches it with no init on this host (a '
|
|
@@ -31,11 +31,12 @@
|
|
|
31
31
|
post-commit step `verify bin-rs`; --prune-flags then removes every flags/native.* file whose binary does not
|
|
32
32
|
verify against TREE. Exit 0, 3 a mismatch (nothing pruned) or a flag file that could not be removed, 2 usage
|
|
33
33
|
|
|
34
|
-
Components are AR 7.3's
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
34
|
+
Components are AR 7.3's, and ROUTES (RT 12.4's first-party docs and enrolment routes, lane R2-ROUTES). Each runs one
|
|
35
|
+
payload binary (COMPONENT_BINARY), or none yet: AGENTD and MCP have no crate that declares a binary (binary_absent),
|
|
36
|
+
and STATUSD, VISIBILITY, NOTIFY, ECONOMY, SYNC, SITE, STORE and ROUTES are duties of the host coordinator, a Rust
|
|
37
|
+
library the throttle-rc Studio Host composes (RT 3.1): RT 3.2 allows one host owner per state root and no lanesd beside
|
|
38
|
+
an active Studio host, so no payload binary or unit serves them and their flags are refused (host_composed) until the
|
|
39
|
+
cutover fence (lanes2 H3) activates them in that composition. A binary is used only
|
|
39
40
|
when it verifies (resolve): first the `lanes rs install` link ~/.local/share/lanes/bin-rs/<name>, else the running
|
|
40
41
|
tree's bin-rs/<target>/<name> against BINARIES.json; a candidate that exists but does not verify is refused, never
|
|
41
42
|
passed over for the next. The shell readers' half (libexec/native.sh, for the view and sidebar hooks lane C7 owns)
|
|
@@ -59,13 +60,14 @@ import time
|
|
|
59
60
|
import lanes_lib as L
|
|
60
61
|
|
|
61
62
|
TARGETS = {'x86_64': 'x86_64-unknown-linux-musl'} # `uname -m` -> the target the payload ships binaries for
|
|
62
|
-
# AR 7.3's strangler components, in its order
|
|
63
|
-
#
|
|
63
|
+
# AR 7.3's strangler components, in its order, then `routes` (RT 12.4: the first-party docs and enrolment routes,
|
|
64
|
+
# lanes2 Round 2 R2-ROUTES, crates/lanes-runtime/src/http/mode.rs reads its flag files): the `LANES_RS_<COMPONENT>` keys
|
|
65
|
+
# (upper case) and the flag files (lower case). Every one ships `off`.
|
|
64
66
|
COMPONENTS = ('signal', 'mcp', 'agentd', 'statusd', 'visibility', 'notify', 'economy', 'sync', 'site', 'store',
|
|
65
|
-
'relay', 'sidebar', 'key')
|
|
67
|
+
'relay', 'sidebar', 'key', 'routes')
|
|
66
68
|
# The duties of the host coordinator (RT 3.1: a Rust library composed by throttle-rc; RT 3.2: one host owner, no lanesd
|
|
67
69
|
# beside the Studio host): no payload binary runs them.
|
|
68
|
-
HOST_DUTIES = frozenset({'statusd', 'visibility', 'notify', 'economy', 'sync', 'site', 'store'})
|
|
70
|
+
HOST_DUTIES = frozenset({'statusd', 'visibility', 'notify', 'economy', 'sync', 'site', 'store', 'routes'})
|
|
69
71
|
# The payload binary a component runs: a `[[bin]]` target of the lanes crates. The Day-0 freeze (PR #626) declares
|
|
70
72
|
# lanes-terminal (RT 4: the CLI, TUI and attachment relay — the relay as its `relay` mode with connection.py's
|
|
71
73
|
# arguments, the sidebar as its `sidebar` mode, the hot keys lane C6's) and lanes-hook (RT 3.1: the hook emitter behind
|
|
@@ -75,7 +77,7 @@ COMPONENT_BINARY = {'signal': 'lanes-hook', 'relay': 'lanes-terminal', 'sidebar'
|
|
|
75
77
|
'key': 'lanes-terminal'}
|
|
76
78
|
# AR 7.4: the components whose strangler row has a shadow step. `shadow` for a component with a binary but no shadow
|
|
77
79
|
# step is refused (shadow_unsupported): a flag file that says shadow while nothing shadows is state no reader honours.
|
|
78
|
-
SHADOW_STEP = frozenset({'mcp', 'agentd', 'statusd', 'visibility', 'notify', 'economy', 'sync', 'site'})
|
|
80
|
+
SHADOW_STEP = frozenset({'mcp', 'agentd', 'statusd', 'visibility', 'notify', 'economy', 'sync', 'site', 'routes'})
|
|
79
81
|
BINARIES = frozenset(COMPONENT_BINARY.values())
|
|
80
82
|
MODES = ('off', 'shadow', 'on')
|
|
81
83
|
KEY = re.compile(r'^LANES_RS_([A-Z][A-Z_]*)$')
|
|
@@ -399,13 +399,73 @@ def unregister_lane(lane_id, registry=None):
|
|
|
399
399
|
return dict(unregister_declared(path, name, root=info['home']), lane=lane_id, source=lane['source'])
|
|
400
400
|
|
|
401
401
|
|
|
402
|
-
|
|
403
|
-
|
|
402
|
+
# The unattended close's in-tmux condition (`lanes gc --unregistered`, gc_unregistered.end; PR #750 review): the
|
|
403
|
+
# session's creation time AND no client attached to it, both evaluated by the tmux server in the same if-shell as the
|
|
404
|
+
# kill, so a person who attaches between the sweep's last look and the kill keeps the session. `%s` is the creation-time
|
|
405
|
+
# check every close carries. UNATTENDED_REFUSED is what the server answers when the condition is false.
|
|
406
|
+
UNATTENDED_CONDITION = '#{&&:%s,#{==:#{session_attached},0}}'
|
|
407
|
+
UNATTENDED_REFUSED = 'attached-or-replaced'
|
|
408
|
+
|
|
409
|
+
|
|
410
|
+
def close_session(workspace, entry, unattended=False):
|
|
411
|
+
"""Close the exact observed session, never an identically named replacement or a registered lane. `unattended` is
|
|
412
|
+
conservative close mode, never a person's `x`: it refuses while any view member (a Studio
|
|
413
|
+
browser's grouped `view-…` session) shows the session and never kills one, and tmux kills only while no client is
|
|
414
|
+
attached to it, checked inside the server together with the creation time (UNATTENDED_CONDITION)."""
|
|
404
415
|
with L.registry_lock():
|
|
405
|
-
return _close_session(workspace, entry)
|
|
416
|
+
return _close_session(workspace, entry, unattended)
|
|
406
417
|
|
|
407
418
|
|
|
408
|
-
def
|
|
419
|
+
def close_idle_session(workspace, entry, *, idle_s):
|
|
420
|
+
"""GC's close: recheck policy under the registry lock, then guard live facts inside tmux.
|
|
421
|
+
|
|
422
|
+
BEY-7156: a fresh status.json is still a cached observation. The ordinary
|
|
423
|
+
human close may end an attached session and its Studio views; GC may not.
|
|
424
|
+
"""
|
|
425
|
+
import gc_unregistered as gc
|
|
426
|
+
if not isinstance(idle_s, int) or isinstance(idle_s, bool) or idle_s < gc.IDLE_MIN:
|
|
427
|
+
raise L.LanesError('Invalid idle floor; nothing was closed')
|
|
428
|
+
with L.registry_lock():
|
|
429
|
+
status = gc.read_status()
|
|
430
|
+
current = next((row for board, row in gc.listed(status, workspace)
|
|
431
|
+
if row['id'] == entry['id']), None)
|
|
432
|
+
if (current is None or session_key(current) != session_key(entry)
|
|
433
|
+
or current.get('identity') != entry.get('identity')):
|
|
434
|
+
raise L.LanesError('Session changed; nothing was closed')
|
|
435
|
+
now = time.time()
|
|
436
|
+
containers = L.read_json(L.STATE / 'containers.json') or {}
|
|
437
|
+
said, reason = gc.judge(status, current, containers, idle_s, now)
|
|
438
|
+
if said != 'reap':
|
|
439
|
+
raise L.LanesError(f'Session no longer idle: {reason}; nothing was closed')
|
|
440
|
+
quiet, why = gc.nothing_runs(current, containers.get(current.get('container')) or {})
|
|
441
|
+
if not quiet:
|
|
442
|
+
raise L.LanesError(f'Session no longer idle: {why}; nothing was closed')
|
|
443
|
+
return _close_session(workspace, current, unattended=True, idle_before=int(now) - idle_s)
|
|
444
|
+
|
|
445
|
+
|
|
446
|
+
def _idle_condition(created, idle_before):
|
|
447
|
+
"""One tmux-format predicate over this exact session and ALL its windows.
|
|
448
|
+
|
|
449
|
+
Empty/malformed activity is not old activity. A window loop contributes a
|
|
450
|
+
marker for every unobserved or recent window; only an empty result is idle.
|
|
451
|
+
No shell is run between evaluating this predicate and the queued close.
|
|
452
|
+
"""
|
|
453
|
+
window_known = '#{&&:#{m/r:^[0-9]+$,#{window_activity}},#{>:#{window_activity},0}}'
|
|
454
|
+
window_idle = '#{&&:' + window_known + ',#{<=:#{window_activity},' + str(idle_before) + '}}'
|
|
455
|
+
conditions = [
|
|
456
|
+
'#{==:#{session_created},' + created + '}',
|
|
457
|
+
'#{==:#{session_attached},0}',
|
|
458
|
+
'#{==:#{session_grouped},0}',
|
|
459
|
+
'#{>:#{session_windows},0}',
|
|
460
|
+
'#{==:#{W:#{?' + window_idle + ',,busy}},}',
|
|
461
|
+
]
|
|
462
|
+
result = conditions.pop()
|
|
463
|
+
for condition in reversed(conditions):
|
|
464
|
+
result = '#{&&:' + condition + ',' + result + '}'
|
|
465
|
+
return result
|
|
466
|
+
|
|
467
|
+
|
|
468
|
+
def _close_session(workspace, entry, unattended=False, *, idle_before=None):
|
|
409
469
|
import registrations
|
|
410
470
|
registry = registrations.apply(L.load_registry())
|
|
411
471
|
current = (L.read_json(L.STATE / 'status.json', {}) or {}).get('unregistered', {}).get(workspace, [])
|
|
@@ -439,6 +499,8 @@ def _close_session(workspace, entry):
|
|
|
439
499
|
if not sid.startswith('$') or not sid[1:].isdigit() or not created.isdigit():
|
|
440
500
|
raise L.LanesError('Session identity is not ready; wait for the next status update')
|
|
441
501
|
info = (L.read_json(L.STATE / 'containers.json', {}) or {}).get(container) or {}
|
|
502
|
+
if idle_before is not None and L.write_route(container, info, socket)[0] != L.TRANSPORT_LOCAL:
|
|
503
|
+
raise L.LanesError('No local write route; nothing was closed')
|
|
442
504
|
outcome, actual = L.tmux_probe(info, socket,
|
|
443
505
|
['display-message', '-p', '-t', '=' + name + ':',
|
|
444
506
|
'#{session_id}\t#{session_created}'], 5)
|
|
@@ -456,17 +518,33 @@ def _close_session(workspace, entry):
|
|
|
456
518
|
if outcome != 'ok':
|
|
457
519
|
raise L.LanesError('Could not read the session groups; nothing was closed')
|
|
458
520
|
views, strangers = L.grouped_members(listing, name)
|
|
521
|
+
if idle_before is not None and (views or strangers):
|
|
522
|
+
raise L.LanesError('Session is viewed or grouped; nothing was closed')
|
|
459
523
|
if strangers:
|
|
460
524
|
raise L.LanesError(
|
|
461
525
|
f'{len(strangers)} session(s) are grouped onto it and would keep its panes alive: '
|
|
462
526
|
+ ', '.join(sorted(strangers)[:3]) + ' — end them first; nothing was closed')
|
|
527
|
+
if unattended and views:
|
|
528
|
+
# A view is a person looking (a Studio browser). A person's `x` ends the Host's view first; the sweep never
|
|
529
|
+
# does: it leaves the session to the next night.
|
|
530
|
+
raise L.LanesError(f'{len(views)} view(s) show it: ' + ', '.join(sorted(views)[:3])
|
|
531
|
+
+ ' — someone is looking; nothing was closed')
|
|
463
532
|
for member in views:
|
|
464
|
-
# Named by the listing, targeted exactly, and only ever a name the Studio Host mints
|
|
533
|
+
# Named by the listing, targeted exactly, and only ever a name the Studio Host mints (never unattended: refused
|
|
534
|
+
# above).
|
|
465
535
|
L.tmux_probe(info, socket, ['kill-session', '-t', '=' + member + ':'], 5)
|
|
466
536
|
# The conditional executes inside tmux: even a replacement between the check and kill is protected.
|
|
537
|
+
condition = ('#{==:#{session_created},' + created + '}' if idle_before is None
|
|
538
|
+
else _idle_condition(created, idle_before))
|
|
539
|
+
refusal = 'stale-session' if idle_before is None else 'session-live-or-unobserved'
|
|
540
|
+
if unattended and idle_before is None:
|
|
541
|
+
condition = UNATTENDED_CONDITION % condition
|
|
542
|
+
refusal = UNATTENDED_REFUSED
|
|
467
543
|
outcome, error = L.tmux_probe(info, socket,
|
|
468
|
-
['if-shell', '-F', '-t', sid,
|
|
469
|
-
'kill-session -t ' + shlex.quote(sid), 'display-message -p
|
|
544
|
+
['if-shell', '-F', '-t', sid, condition,
|
|
545
|
+
'kill-session -t ' + shlex.quote(sid), 'display-message -p ' + refusal], 5)
|
|
546
|
+
if unattended and outcome == 'ok' and error.strip() == UNATTENDED_REFUSED:
|
|
547
|
+
raise L.LanesError('A client attached, or the session was replaced, before the close; nothing was closed')
|
|
470
548
|
if outcome != 'ok' or error.strip():
|
|
471
549
|
raise L.LanesError('Could not confirm close: ' + (error or outcome))
|
|
472
550
|
clear_viewers(entry['id'])
|