agentlanes-cli 0.1.0__py3-none-any.whl
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.
- agentlanes/__init__.py +10 -0
- agentlanes/__main__.py +3 -0
- agentlanes/claims.py +215 -0
- agentlanes/cli.py +323 -0
- agentlanes/core.py +184 -0
- agentlanes/hook.py +166 -0
- agentlanes/jobs.py +126 -0
- agentlanes/landlock.py +257 -0
- agentlanes/onboard.py +364 -0
- agentlanes/procs.py +255 -0
- agentlanes/run.py +201 -0
- agentlanes/slots.py +253 -0
- agentlanes_cli-0.1.0.dist-info/METADATA +323 -0
- agentlanes_cli-0.1.0.dist-info/RECORD +18 -0
- agentlanes_cli-0.1.0.dist-info/WHEEL +5 -0
- agentlanes_cli-0.1.0.dist-info/entry_points.txt +2 -0
- agentlanes_cli-0.1.0.dist-info/licenses/LICENSE +202 -0
- agentlanes_cli-0.1.0.dist-info/top_level.txt +1 -0
agentlanes/slots.py
ADDED
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
"""Slots: an N-slot FIFO queue for a shared resource (heavy builds, browsers, a GPU, a test device).
|
|
2
|
+
|
|
3
|
+
`slot NAME N -- CMD` waits for one of N slots in arrival order, runs CMD holding it and releases it on exit.
|
|
4
|
+
The slot is a flock on <state>/slots/NAME/<i>.lock; the lock fd is inherited by CMD, so the slot stays busy
|
|
5
|
+
as long as CMD runs, even if this wrapper is killed, and is freed by the kernel when CMD dies (also on SIGKILL).
|
|
6
|
+
A holder record (<i>.who) whose lock is free is reported and cleaned as stale.
|
|
7
|
+
Optional memory cap: systemd scope (MemoryMax) when a systemd user session exists, else an RSS watchdog.
|
|
8
|
+
"""
|
|
9
|
+
import fcntl
|
|
10
|
+
import json
|
|
11
|
+
import os
|
|
12
|
+
import re
|
|
13
|
+
import shutil
|
|
14
|
+
import signal
|
|
15
|
+
import subprocess
|
|
16
|
+
import sys
|
|
17
|
+
import threading
|
|
18
|
+
import time
|
|
19
|
+
|
|
20
|
+
from . import core, procs
|
|
21
|
+
|
|
22
|
+
NAME_RE = re.compile(r'^[A-Za-z0-9._-]{1,40}$')
|
|
23
|
+
POLL = 0.25
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def slot_dir(name):
|
|
27
|
+
d = os.path.join(core.state_dir(), 'slots', name)
|
|
28
|
+
os.makedirs(d, exist_ok=True)
|
|
29
|
+
return d
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _try_lock(p):
|
|
33
|
+
fd = os.open(p, os.O_RDWR | os.O_CREAT, 0o644)
|
|
34
|
+
try:
|
|
35
|
+
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
36
|
+
return fd
|
|
37
|
+
except OSError:
|
|
38
|
+
os.close(fd)
|
|
39
|
+
return None
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _lock_free(p):
|
|
43
|
+
fd = _try_lock(p)
|
|
44
|
+
if fd is None:
|
|
45
|
+
return False
|
|
46
|
+
os.close(fd)
|
|
47
|
+
return True
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def status(name, clean=True):
|
|
51
|
+
"""[(slot_no, state, holder_record_or_None)]; state is free / busy / stale. Stale records are cleaned."""
|
|
52
|
+
d = slot_dir(name)
|
|
53
|
+
out = []
|
|
54
|
+
nums = sorted(int(f[:-5]) for f in os.listdir(d) if f.endswith('.lock') and f[:-5].isdigit())
|
|
55
|
+
for i in nums:
|
|
56
|
+
who = core.load_json(os.path.join(d, '%d.who' % i), None)
|
|
57
|
+
if not _lock_free(os.path.join(d, '%d.lock' % i)):
|
|
58
|
+
out.append((i, 'busy', who or {}))
|
|
59
|
+
elif not who:
|
|
60
|
+
out.append((i, 'free', None))
|
|
61
|
+
else:
|
|
62
|
+
out.append((i, 'stale', who))
|
|
63
|
+
if clean:
|
|
64
|
+
try:
|
|
65
|
+
os.remove(os.path.join(d, '%d.who' % i))
|
|
66
|
+
except OSError:
|
|
67
|
+
pass
|
|
68
|
+
core.emit('slot.stale', by=who.get('by'), topic='%s/%d' % (name, i), msg=who.get('cmd'),
|
|
69
|
+
pid=who.get('pid'))
|
|
70
|
+
return out
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def waiters(name):
|
|
74
|
+
q = core.load_json(os.path.join(slot_dir(name), 'queue.json'), [])
|
|
75
|
+
return [w for w in q if procs.same_process(w['pid'], w.get('pstart'))]
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def all_names():
|
|
79
|
+
base = os.path.join(core.state_dir(), 'slots')
|
|
80
|
+
try:
|
|
81
|
+
return sorted(n for n in os.listdir(base) if os.path.isdir(os.path.join(base, n)))
|
|
82
|
+
except OSError:
|
|
83
|
+
return []
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _queue(name, fn):
|
|
87
|
+
"""Run fn(list) under the queue lock with dead waiters pruned; saves the list fn leaves behind."""
|
|
88
|
+
qf = os.path.join(slot_dir(name), 'queue.json')
|
|
89
|
+
with core.locked(qf):
|
|
90
|
+
q = [w for w in core.load_json(qf, []) if procs.same_process(w['pid'], w.get('pstart'))]
|
|
91
|
+
res = fn(q)
|
|
92
|
+
core.save_json(qf, q)
|
|
93
|
+
return res
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def acquire(name, n, wait_s, by):
|
|
97
|
+
"""Block in FIFO order until a slot is free. Returns (slot_no, fd) or (None, None) on timeout."""
|
|
98
|
+
me = {'pid': os.getpid(), 'pstart': procs.start_token(os.getpid()), 'by': by, 't': time.time()}
|
|
99
|
+
_queue(name, lambda q: q.append(me))
|
|
100
|
+
d = slot_dir(name)
|
|
101
|
+
deadline = time.time() + wait_s
|
|
102
|
+
|
|
103
|
+
def attempt(q):
|
|
104
|
+
if not q or q[0]['pid'] != me['pid']:
|
|
105
|
+
if not any(w['pid'] == me['pid'] for w in q): # pruned by mistake (pid check race): rejoin at the end
|
|
106
|
+
q.append(me)
|
|
107
|
+
return None
|
|
108
|
+
for i in range(1, n + 1):
|
|
109
|
+
fd = _try_lock(os.path.join(d, '%d.lock' % i))
|
|
110
|
+
if fd is not None:
|
|
111
|
+
q.pop(0)
|
|
112
|
+
return i, fd
|
|
113
|
+
return None
|
|
114
|
+
|
|
115
|
+
def leave(q):
|
|
116
|
+
q[:] = [w for w in q if w['pid'] != me['pid']]
|
|
117
|
+
try:
|
|
118
|
+
while True:
|
|
119
|
+
got = _queue(name, attempt)
|
|
120
|
+
if got:
|
|
121
|
+
return got
|
|
122
|
+
if time.time() > deadline:
|
|
123
|
+
_queue(name, leave)
|
|
124
|
+
return None, None
|
|
125
|
+
time.sleep(POLL)
|
|
126
|
+
except BaseException:
|
|
127
|
+
_queue(name, leave)
|
|
128
|
+
raise
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _systemd_scope_ok():
|
|
132
|
+
if core.env('NO_SYSTEMD') or not sys.platform.startswith('linux') or not shutil.which('systemd-run'):
|
|
133
|
+
return False
|
|
134
|
+
return os.path.exists('/run/user/%d/systemd/private' % os.getuid())
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def _watch_rss(proc, cap_mb, name, slot_no, by, killed):
|
|
138
|
+
while proc.poll() is None:
|
|
139
|
+
table = procs.process_table()
|
|
140
|
+
if procs.tree_rss_kb(proc.pid, table) // 1024 > cap_mb:
|
|
141
|
+
killed.append(True)
|
|
142
|
+
core.emit('slot.oom', by=by, topic='%s/%d' % (name, slot_no), cap_mb=cap_mb)
|
|
143
|
+
try:
|
|
144
|
+
os.killpg(proc.pid, signal.SIGKILL)
|
|
145
|
+
except OSError:
|
|
146
|
+
pass
|
|
147
|
+
return
|
|
148
|
+
time.sleep(1)
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def run(name, n, cmd, wait_s=1800, mem_free_mb=0, max_mem_mb=0, by=None, out=None):
|
|
152
|
+
out = out or (lambda s: print(s, file=sys.stderr))
|
|
153
|
+
if not NAME_RE.match(name or '') or name in ('status', 'help'):
|
|
154
|
+
out('slot: bad name %r (letters, digits . _ -)' % name)
|
|
155
|
+
return 2
|
|
156
|
+
if n < 1 or not cmd:
|
|
157
|
+
out('usage: slot NAME N [--wait SEC] [--mem-free MB] [--max-mem MB] -- COMMAND...')
|
|
158
|
+
return 2
|
|
159
|
+
by = by or procs.default_by()
|
|
160
|
+
status(name) # clean stale holder records first
|
|
161
|
+
t_start = time.time()
|
|
162
|
+
slot_no, fd = acquire(name, n, wait_s, by)
|
|
163
|
+
cmd_s = ' '.join(cmd)[:80]
|
|
164
|
+
if slot_no is None:
|
|
165
|
+
out('slot %s: no free slot after %d s' % (name, wait_s))
|
|
166
|
+
core.emit('slot.timeout', by=by, topic=name, msg=cmd_s, wait_s=wait_s)
|
|
167
|
+
return 75
|
|
168
|
+
try:
|
|
169
|
+
warned = False
|
|
170
|
+
while mem_free_mb:
|
|
171
|
+
avail = procs.mem_available_mb()
|
|
172
|
+
if avail is None or avail >= mem_free_mb:
|
|
173
|
+
break
|
|
174
|
+
if not warned:
|
|
175
|
+
out('slot %s/%d: waiting for %d MB free memory (now %d MB)' % (name, slot_no, mem_free_mb, avail))
|
|
176
|
+
core.emit('slot.mem_wait', by=by, topic='%s/%d' % (name, slot_no), msg=cmd_s, mem_mb=mem_free_mb)
|
|
177
|
+
warned = True
|
|
178
|
+
time.sleep(2)
|
|
179
|
+
argv, watchdog = list(cmd), False
|
|
180
|
+
if max_mem_mb:
|
|
181
|
+
if _systemd_scope_ok():
|
|
182
|
+
argv = ['systemd-run', '--user', '--scope', '-q', '-p', 'MemoryMax=%dM' % max_mem_mb,
|
|
183
|
+
'-p', 'MemorySwapMax=0', '--'] + argv
|
|
184
|
+
else:
|
|
185
|
+
watchdog = True
|
|
186
|
+
envv = dict(os.environ)
|
|
187
|
+
envv['%s_SLOT' % core.ENV] = str(slot_no)
|
|
188
|
+
wf = os.path.join(slot_dir(name), '%d.who' % slot_no)
|
|
189
|
+
t0 = time.time()
|
|
190
|
+
core.save_json(wf, {'pid': None, 'wrapper': os.getpid(), 'by': by, 'cmd': cmd_s, 'since': t0})
|
|
191
|
+
try:
|
|
192
|
+
proc = subprocess.Popen(argv, pass_fds=(fd,), env=envv, start_new_session=watchdog)
|
|
193
|
+
except OSError as e:
|
|
194
|
+
out('slot: cannot run %s: %s' % (cmd[0], e))
|
|
195
|
+
os.remove(wf)
|
|
196
|
+
return 127
|
|
197
|
+
core.save_json(wf, {'pid': proc.pid, 'wrapper': os.getpid(), 'by': by, 'cmd': cmd_s, 'since': t0})
|
|
198
|
+
core.emit('slot.acquire', by=by, topic='%s/%d' % (name, slot_no), msg=cmd_s, pid=proc.pid,
|
|
199
|
+
wait_s=round(t0 - t_start, 1))
|
|
200
|
+
killed = []
|
|
201
|
+
if watchdog:
|
|
202
|
+
threading.Thread(target=_watch_rss, args=(proc, max_mem_mb, name, slot_no, by, killed),
|
|
203
|
+
daemon=True).start()
|
|
204
|
+
|
|
205
|
+
def forward(sig, _frame):
|
|
206
|
+
if sig == signal.SIGINT and not watchdog:
|
|
207
|
+
return # same process group: the terminal already delivered it to CMD
|
|
208
|
+
try:
|
|
209
|
+
(os.killpg if watchdog else os.kill)(proc.pid, sig)
|
|
210
|
+
except OSError:
|
|
211
|
+
pass
|
|
212
|
+
for sig in (signal.SIGINT, signal.SIGTERM, signal.SIGHUP):
|
|
213
|
+
signal.signal(sig, forward)
|
|
214
|
+
rc = proc.wait()
|
|
215
|
+
if rc < 0:
|
|
216
|
+
rc = 128 - rc
|
|
217
|
+
try:
|
|
218
|
+
os.remove(wf)
|
|
219
|
+
except OSError:
|
|
220
|
+
pass
|
|
221
|
+
core.emit('slot.release', by=by, topic='%s/%d' % (name, slot_no), pid=proc.pid, rc=rc,
|
|
222
|
+
held_s=round(time.time() - t0, 1), oom=bool(killed) or None)
|
|
223
|
+
return rc
|
|
224
|
+
finally:
|
|
225
|
+
os.close(fd)
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def cmd_status(name=None, as_json=False, out=print):
|
|
229
|
+
names = [name] if name else all_names()
|
|
230
|
+
data = {}
|
|
231
|
+
for nm in names:
|
|
232
|
+
data[nm] = {'slots': [{'slot': i, 'state': st, 'holder': who} for i, st, who in status(nm)],
|
|
233
|
+
'waiting': waiters(nm)}
|
|
234
|
+
if as_json:
|
|
235
|
+
out(json.dumps(data, ensure_ascii=False, indent=1))
|
|
236
|
+
return 0
|
|
237
|
+
if not data:
|
|
238
|
+
out('no slots used yet')
|
|
239
|
+
for nm, v in data.items():
|
|
240
|
+
for s in v['slots']:
|
|
241
|
+
who = s['holder']
|
|
242
|
+
if s['state'] == 'busy' and not who:
|
|
243
|
+
out('%s slot %d: busy (starting)' % (nm, s['slot']))
|
|
244
|
+
elif s['state'] == 'busy':
|
|
245
|
+
out('%s slot %d: busy -- %s pid %s for %s: %s' % (nm, s['slot'], who.get('by'), who.get('pid'),
|
|
246
|
+
core.dur(time.time() - who.get('since', time.time())), who.get('cmd')))
|
|
247
|
+
elif s['state'] == 'stale':
|
|
248
|
+
out('%s slot %d: free (stale holder cleaned: %s pid %s)' % (nm, s['slot'], who.get('by'), who.get('pid')))
|
|
249
|
+
else:
|
|
250
|
+
out('%s slot %d: free' % (nm, s['slot']))
|
|
251
|
+
if v['waiting']:
|
|
252
|
+
out('%s waiting: %s' % (nm, ', '.join('%s (pid %d)' % (w['by'], w['pid']) for w in v['waiting'])))
|
|
253
|
+
return 0
|
|
@@ -0,0 +1,323 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: agentlanes-cli
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Claims, slots, an event log and a job queue for several AI coding agents sharing one machine
|
|
5
|
+
Author: Metastaz
|
|
6
|
+
License: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://github.com/metastazorg/agentlanes
|
|
8
|
+
Project-URL: Issues, https://github.com/metastazorg/agentlanes/issues
|
|
9
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
10
|
+
Classifier: Operating System :: POSIX :: Linux
|
|
11
|
+
Classifier: Operating System :: MacOS
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Topic :: Software Development
|
|
14
|
+
Requires-Python: >=3.9
|
|
15
|
+
Description-Content-Type: text/markdown
|
|
16
|
+
License-File: LICENSE
|
|
17
|
+
Dynamic: license-file
|
|
18
|
+
|
|
19
|
+
# agentlanes
|
|
20
|
+
|
|
21
|
+
<p align="center"><img src="https://raw.githubusercontent.com/metastazorg/agentlanes/main/docs/demo.svg" width="800" alt="agentlanes demo: three agents share one file and one build slot, then a real Claude Code session is stopped by Landlock"></p>
|
|
22
|
+
|
|
23
|
+
<sub>A recorded run of <code>./demo.sh</code> (real timing), then a replay of a <a href="examples/landlock/real-session.txt">real Claude Code session</a> under <code>agentlanes run</code>. Regenerate with <code>tools/make_demo_svg.py</code>; video: <a href="docs/demo.mp4">docs/demo.mp4</a>.</sub>
|
|
24
|
+
|
|
25
|
+
Coordination for several AI coding agents (Claude Code, Codex, Cursor, Aider, ...) working on one Linux or macOS machine.
|
|
26
|
+
|
|
27
|
+
## The problem
|
|
28
|
+
|
|
29
|
+
- Two agents edit the same file at the same time and one silently overwrites the other.
|
|
30
|
+
- Two agents start a full build or test suite at once and the machine runs out of memory.
|
|
31
|
+
- Nobody, human or agent, can see who is working on what, or tell when another agent has finished.
|
|
32
|
+
|
|
33
|
+
agentlanes gives agents four small primitives for this: **claims** (leases on topics and paths), **slots** (an N-slot queue
|
|
34
|
+
for heavy commands), an **event log** that agents can block on, and a **job queue**. It is one Python package,
|
|
35
|
+
standard library only, no daemon. State is a directory of JSON files guarded by `flock`.
|
|
36
|
+
|
|
37
|
+
## 60-second quickstart
|
|
38
|
+
|
|
39
|
+
```sh
|
|
40
|
+
pip install agentlanes-cli # Python >= 3.9, no dependencies; the command is `agentlanes`
|
|
41
|
+
cd your-project
|
|
42
|
+
agentlanes init --claude-code --agents-md
|
|
43
|
+
agentlanes doctor # every line should say ok/info; anything else comes with a fix
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
`init` is safe to run again. It creates `.agentlanes/` (this project's state, git-ignored by a `.gitignore` inside it),
|
|
47
|
+
merges a `PreToolUse` hook into `.claude/settings.json` without touching your other settings or hooks (the previous file
|
|
48
|
+
is kept as `settings.json.agentlanes-backup-<time>`), and appends the agent instructions to `AGENTS.md` once, between
|
|
49
|
+
`<!-- agentlanes:begin/end -->` markers. Other targets: `--claude-md`, `--cursor` (`.cursor/rules/agentlanes.mdc`),
|
|
50
|
+
`--strict` (see [Fail-open or fail-closed](#fail-open-or-fail-closed)).
|
|
51
|
+
|
|
52
|
+
From then on your agents (and you) work like this:
|
|
53
|
+
|
|
54
|
+
```sh
|
|
55
|
+
agentlanes claim login-page --paths src/login.py --pid self --desc "add OAuth button"
|
|
56
|
+
agentlanes who src/login.py # -> HELD by claude-4242 (login-page, since 14:02:11) ...
|
|
57
|
+
agentlanes slot heavy 1 -- make -j8 # waits its turn if another agent is already building
|
|
58
|
+
agentlanes release login-page
|
|
59
|
+
agentlanes status # agents, claims, slots, jobs, recent events on one screen
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
In Claude Code the hook refuses an edit to a path another agent has claimed, even if the agent forgot to check
|
|
63
|
+
([a real session](https://github.com/metastazorg/agentlanes/blob/main/examples/claude-code/real-session.txt)). Run `./demo.sh` to see three agents compete for one file and
|
|
64
|
+
one build slot (transcript: [demo-output.txt](demo-output.txt)); on Linux with Landlock it ends with a kernel-lane step.
|
|
65
|
+
|
|
66
|
+
On Linux, start an agent under `agentlanes run` and the kernel itself refuses writes outside its claimed paths, including
|
|
67
|
+
writes made through shell commands that no hook sees ([a real Claude Code session](https://github.com/metastazorg/agentlanes/blob/main/examples/landlock/real-session.txt)):
|
|
68
|
+
|
|
69
|
+
```sh
|
|
70
|
+
agentlanes claim login-page --paths src/auth/ --desc "add OAuth button"
|
|
71
|
+
agentlanes run --allow-tmp --allow-common -- claude # writes only in src/auth/, its temp dir, its own config
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
## Commands
|
|
75
|
+
|
|
76
|
+
### Claims
|
|
77
|
+
|
|
78
|
+
| Command | What it does |
|
|
79
|
+
|---|---|
|
|
80
|
+
| `claim TOPIC [--paths a,b] [--pid self\|PID] [--desc T] [--ttl MIN] [--share]` | Take a named claim. Fails (exit 1) if another agent holds `TOPIC` or any overlapping path. A directory claim covers everything under it. `--share` allows overlap on purpose. |
|
|
81
|
+
| `release TOPIC` | Drop your claim. `--force` drops someone else's. |
|
|
82
|
+
| `renew TOPIC [--ttl MIN]` | Extend your claim. |
|
|
83
|
+
| `who PATH...` | Which claim covers these paths (exit 1 if any). |
|
|
84
|
+
| `check TOPIC` / `list [--json]` / `reap` | Is a topic held; list live claims; drop dead and expired ones now. |
|
|
85
|
+
|
|
86
|
+
Every claim expires after `--ttl` minutes (default 120). With `--pid`, the claim is a **lease**: it ends as soon as that
|
|
87
|
+
process exits, including on `kill -9` or an OOM kill. `--pid self` means the coding-agent process this command runs
|
|
88
|
+
under (found by walking up the process tree to a known agent executable: `claude`, `codex`, `cursor-agent`, `aider`,
|
|
89
|
+
`gemini`, ...; add names with `AGENTLANES_AGENT_NAMES=a,b`). A recycled pid is detected by process start time.
|
|
90
|
+
|
|
91
|
+
Who you are (`--by`) defaults to `$AGENTLANES_AGENT`, else `<agent>-<pid>` of the enclosing agent, else `$USER`.
|
|
92
|
+
|
|
93
|
+
### Slots
|
|
94
|
+
|
|
95
|
+
`agentlanes slot NAME N [--wait SEC] [--mem-free MB] [--max-mem MB] -- COMMAND...`
|
|
96
|
+
|
|
97
|
+
Runs `COMMAND` once one of `N` slots named `NAME` is free. Waiters are served in arrival order (FIFO); a waiter that dies
|
|
98
|
+
leaves the queue. The slot is a `flock` that `COMMAND` inherits, so it stays taken while `COMMAND` runs and the kernel frees
|
|
99
|
+
it when `COMMAND` dies, even if everything was SIGKILLed. A leftover holder record is shown as stale and cleaned.
|
|
100
|
+
|
|
101
|
+
- `--wait SEC`: give up after SEC seconds (default 1800) with exit code 75.
|
|
102
|
+
- `--mem-free MB`: after getting the slot, wait until this much memory is available.
|
|
103
|
+
- `--max-mem MB`: kill `COMMAND` above this size. Uses a systemd user scope (`MemoryMax`) when one is available,
|
|
104
|
+
otherwise a watchdog that sums the RSS of the process tree every second and kills the group.
|
|
105
|
+
- `COMMAND` gets `AGENTLANES_SLOT=<slot number>` in its environment. Exit code is `COMMAND`'s.
|
|
106
|
+
|
|
107
|
+
`agentlanes slots [NAME] [--json]` shows holders, stale holders and waiters.
|
|
108
|
+
|
|
109
|
+
### Events
|
|
110
|
+
|
|
111
|
+
| Command | What it does |
|
|
112
|
+
|---|---|
|
|
113
|
+
| `events emit KIND [--topic T] [--msg TEXT] [key=value...]` | Append an event. Use dotted lower-case kinds, e.g. `build.done`. |
|
|
114
|
+
| `events tail [-n N] [--kind PREFIX] [--since 2h] [-f] [--json]` | Show recent events; `-f` follows. |
|
|
115
|
+
| `events wait --kind PREFIX [--topic T] [--by W] [--timeout SEC]` | Block until a *new* matching event; exit 124 on timeout. Use this instead of sleep loops. |
|
|
116
|
+
| `events stats [--since 24h]` | Counts per kind and per agent. |
|
|
117
|
+
|
|
118
|
+
agentlanes itself writes `claim.add/renew/done/conflict/expire/reap/blocked`, `slot.acquire/release/timeout/stale/oom/mem_wait`
|
|
119
|
+
and `job.add/take/done/drop/requeue`. The log is append-only JSON lines and rotates at 4 MB (`AGENTLANES_EVENTS_MAX_BYTES`).
|
|
120
|
+
|
|
121
|
+
### Jobs
|
|
122
|
+
|
|
123
|
+
`jobs add TITLE [--prio N]`, `jobs list [--all]`, `jobs take [ID] [--pid self|PID|none]`, `jobs done ID [--result T]`,
|
|
124
|
+
`jobs drop ID [--why T]`. Lower `--prio` is taken first. A taken job is tied to the taker's process; if it dies, the job
|
|
125
|
+
returns to the queue (`job.requeue`).
|
|
126
|
+
|
|
127
|
+
### Status, agents, notifications
|
|
128
|
+
|
|
129
|
+
- `agentlanes status`: running agents, claims, slots, jobs, last events and available memory.
|
|
130
|
+
- `agentlanes agents [--all] [--json]`: coding-agent processes with memory (process tree RSS), age and the claims they hold.
|
|
131
|
+
- Notifications: set `AGENTLANES_NOTIFY_CMD` (or `--notify-cmd`, or `"notify_cmd"` in `<state>/config.json`) to any shell
|
|
132
|
+
command. It receives the event as JSON on stdin for `claim.conflict`, `claim.blocked`, `claim.reap`, `slot.stale`,
|
|
133
|
+
`slot.timeout`, `slot.oom` and `job.requeue` (change with `AGENTLANES_NOTIFY_KINDS=kind1,kind2`). Example:
|
|
134
|
+
`AGENTLANES_NOTIFY_CMD='jq -r .kind | xargs notify-send agentlanes'`.
|
|
135
|
+
|
|
136
|
+
### Kernel-enforced lanes (Linux): `agentlanes run`
|
|
137
|
+
|
|
138
|
+
```sh
|
|
139
|
+
agentlanes run [--claim NAME]... [--write PATH]... [--allow-tmp] [--allow-common]
|
|
140
|
+
[--no-net] [--allow-port N]... [--allow-bind N]... [--isolate] [--best-effort] [--dry-run] -- COMMAND...
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
Starts COMMAND (an agent such as `claude` or `codex`, a shell, a build) under a
|
|
144
|
+
[Landlock](https://docs.kernel.org/userspace-api/landlock.html) ruleset that applies to it and to every process it
|
|
145
|
+
starts. No root, no container, no daemon: Landlock is an unprivileged Linux security module (Linux 5.13+).
|
|
146
|
+
|
|
147
|
+
- **Read and execute everywhere**, so compilers, package managers and the agent itself keep working.
|
|
148
|
+
- **Write only** beneath: the paths of the agent's claims (`--claim NAME`, repeatable; default: every live claim held
|
|
149
|
+
by `--by` / `$AGENTLANES_AGENT`), the agentlanes state directory (so the agent can still `claim`, `release` and emit
|
|
150
|
+
events), `--write PATH` (repeatable), and with `--allow-tmp` a private temp dir exported as `TMPDIR` and deleted when
|
|
151
|
+
the command exits. Devices in `/dev` (terminal, `/dev/null`) stay writable but nothing can be created there;
|
|
152
|
+
`/dev/shm` is not writable.
|
|
153
|
+
- `--allow-common` also allows the per-user places agents and build tools write to, if they exist: `~/.cache`,
|
|
154
|
+
`~/.claude`, `~/.claude.json`, `~/.codex`, `~/.cursor`, `~/.gemini`, `~/.aider`, `~/.npm`, `~/.local/state`, ...
|
|
155
|
+
(extend with `AGENTLANES_RUN_COMMON=path1:path2`). It is a flag, not the default, because it is a wider lane than the
|
|
156
|
+
claim. `claude -p` also runs without it (it then cannot save its session history).
|
|
157
|
+
- `--no-net` denies TCP connect and bind; `--allow-port 443` (repeatable) allows connecting to that port and implies
|
|
158
|
+
`--no-net`; `--allow-bind N` allows listening on N. Needs Landlock ABI 4 (Linux 6.7+); on older kernels `run` warns
|
|
159
|
+
and the network is not restricted. Landlock covers TCP only: UDP (including DNS) is not restricted.
|
|
160
|
+
- `--isolate` (ABI 6, Linux 6.12+): processes in the run cannot signal or connect to abstract unix sockets of processes
|
|
161
|
+
outside it.
|
|
162
|
+
- Without Landlock (not Linux, kernel older than 5.13, or Landlock disabled at boot) `run` **refuses** and says why.
|
|
163
|
+
`--best-effort` runs the command unconfined with a warning instead. `agentlanes doctor` prints the kernel's Landlock ABI.
|
|
164
|
+
- The ruleset follows the kernel's best-effort pattern: `run` asks for the ABI version and uses every right that
|
|
165
|
+
version knows (ABI 1 file writes, 2 cross-directory rename/link, 3 truncate, 4 TCP, 5 device ioctl, 6 scoping) and
|
|
166
|
+
warns about what an older ABI leaves open. `--dry-run` prints the exact rules.
|
|
167
|
+
- Events: `run.start` (command, ABI, writable paths, network rule) and `run.stop` (exit code, duration). The exit
|
|
168
|
+
code is the command's.
|
|
169
|
+
|
|
170
|
+
**The lanes are fixed when the command starts.** A claim the agent takes later does not widen a running agent's
|
|
171
|
+
sandbox: restart it, or run that sub-task under its own `agentlanes run --claim NEW -- ...`. A nested `run` can only
|
|
172
|
+
narrow (a path must be allowed by every layer). A file (not directory) claim allows writing that file in place, but not
|
|
173
|
+
tools that replace it through a temp file and rename (`sed -i`, most editors); claim the directory for those.
|
|
174
|
+
|
|
175
|
+
## State directory
|
|
176
|
+
|
|
177
|
+
First match wins: `--state-dir DIR`, `$AGENTLANES_STATE_DIR`, the nearest `.agentlanes/` directory above the current directory
|
|
178
|
+
(create one with `agentlanes init` for per-project state), then `$XDG_STATE_HOME/agentlanes` (default `~/.local/state/agentlanes`).
|
|
179
|
+
All agents that should see each other must use the same directory. Do not put it on a network filesystem: `flock` there
|
|
180
|
+
is not reliable.
|
|
181
|
+
|
|
182
|
+
## Hooks and instructions per agent
|
|
183
|
+
|
|
184
|
+
| Agent | How agentlanes is enforced | Set up |
|
|
185
|
+
|---|---|---|
|
|
186
|
+
| Claude Code | **Hook** (`PreToolUse` on Edit/Write/MultiEdit/NotebookEdit). Tested with a real session. | `agentlanes init --claude-code` |
|
|
187
|
+
| Codex | **Hook** (`PreToolUse` on `apply_patch`; file paths are read from the patch). Written to the Codex hooks documentation and unit-tested with sample payloads; not yet run in a real Codex session. | [examples/codex/config.toml](https://github.com/metastazorg/agentlanes/blob/main/examples/codex/config.toml) + `init --agents-md` |
|
|
188
|
+
| Cursor | **Hook, experimental** (`preToolUse` with matcher `Write`). Cursor documents the event and the `permission: allow/deny` answer, but not the field that carries the file path, so the adapter looks for `file_path`, `path` or `target_file`. Not yet run in real Cursor. | [examples/cursor/hooks.json](https://github.com/metastazorg/agentlanes/blob/main/examples/cursor/hooks.json) + `init --cursor` |
|
|
189
|
+
| Aider, other shell agents | **Instruction-only.** No pre-edit hook to attach to. | `init --agents-md`, then e.g. `aider --read AGENTS.md` |
|
|
190
|
+
|
|
191
|
+
Instruction-only means the agent is told to claim before editing and usually does, but nothing stops it if it does not.
|
|
192
|
+
|
|
193
|
+
### Claude Code hook
|
|
194
|
+
|
|
195
|
+
`agentlanes hook claude-code` reads the hook JSON on stdin. When the target file is covered by a claim held by a
|
|
196
|
+
different agent it answers `permissionDecision: "deny"` with the holder and the claim's description as the reason, which
|
|
197
|
+
Claude sees and can act on. Unclaimed paths and the agent's own claims produce no output, so the normal permission flow
|
|
198
|
+
is unchanged. "Own claim" means the claim was made from the same Claude Code process (or with the same
|
|
199
|
+
`$AGENTLANES_AGENT`). The hook can go in `.claude/settings.json` (project, what `init` writes) or `~/.claude/settings.json`
|
|
200
|
+
(user); see [examples/claude-code/settings.json](https://github.com/metastazorg/agentlanes/blob/main/examples/claude-code/settings.json).
|
|
201
|
+
|
|
202
|
+
### Fail-open or fail-closed
|
|
203
|
+
|
|
204
|
+
By default the hook **fails open**: if it cannot do its job, the edit goes ahead. That covers malformed hook input, a
|
|
205
|
+
corrupt `claims.json`, and an unreadable state directory. It also covers the case we hit ourselves: if `agentlanes` is
|
|
206
|
+
not on the `PATH` that the agent sees, the hook command fails to start, Claude Code treats that as a non-blocking hook
|
|
207
|
+
error, and edits pass silently. `agentlanes doctor` catches this by running the configured hook command once.
|
|
208
|
+
|
|
209
|
+
For fail-closed behaviour, use **strict mode**:
|
|
210
|
+
|
|
211
|
+
- `AGENTLANES_STRICT=1` in the agent's environment: a broken state or malformed input makes the hook deny the edit with
|
|
212
|
+
a message that names the problem and says to run `agentlanes doctor`.
|
|
213
|
+
- `agentlanes init --claude-code --strict` writes a hook command that also covers the missing-command case: it checks
|
|
214
|
+
`command -v agentlanes` first and exits 2 (Claude Code's "block" exit code, with the reason on stderr) if it is absent,
|
|
215
|
+
then runs the hook with `AGENTLANES_STRICT=1`.
|
|
216
|
+
|
|
217
|
+
Strict mode is a choice between "a broken coordination tool stops all edits" and "a broken coordination tool is
|
|
218
|
+
silently ignored". Teams that rely on claims for correctness should pick strict; solo users usually want the default.
|
|
219
|
+
|
|
220
|
+
## Limits
|
|
221
|
+
|
|
222
|
+
- **Hooks alone are a coordination tool, not a security boundary.** The hooks cover the agents' file-editing tools. An
|
|
223
|
+
agent that changes files through shell commands (`cp`, `sed -i`, `>` redirects, a build script) is not stopped by any
|
|
224
|
+
hook, and a determined or confused agent can always ignore instructions.
|
|
225
|
+
- **On Linux 5.13+ `agentlanes run` enforces write lanes in the kernel via Landlock; hooks remain as a fast, friendly
|
|
226
|
+
first line** (they explain who holds a path before the agent even tries). What Landlock under `run` does not cover:
|
|
227
|
+
- **Reads.** Everything stays readable, including secrets in your home directory. `run` limits what an agent can
|
|
228
|
+
change, not what it can see or send.
|
|
229
|
+
- **Already-open file descriptors and other processes.** Files opened before `run` started, and processes that are
|
|
230
|
+
not descendants of the run (your editor, a daemon, another agent, a build server the agent talks to over a socket
|
|
231
|
+
or `docker` API) write wherever they are allowed to. Asking such a process to write is not blocked.
|
|
232
|
+
- **Other users and root.** It confines one process tree of one user; it is not a multi-user boundary.
|
|
233
|
+
- **Network** only with ABI 4+ and only TCP; **signals** to outside processes only with ABI 6 (`--isolate`).
|
|
234
|
+
- Re-opening `/dev/stdout` or `/dev/stderr` fails when that stream is a regular file outside the lanes (write to the
|
|
235
|
+
inherited descriptor instead, which works).
|
|
236
|
+
- **Not Linux** (macOS, BSD, Windows): no Landlock. `run` refuses, or runs unconfined with `--best-effort`.
|
|
237
|
+
- Kernel enforcement that also covers reads, identity and sealed sessions is what Ranix (below) is for.
|
|
238
|
+
- Claims are advisory for agents without a hook (see the table above).
|
|
239
|
+
- `events wait` and slot queues poll (0.2 s) instead of using inotify/kqueue; fine for tens of agents, not thousands.
|
|
240
|
+
- The state directory must be on a local filesystem; `flock` over NFS/SMB is not reliable (`doctor` warns).
|
|
241
|
+
- Windows is not supported (`fcntl.flock`, POSIX process groups).
|
|
242
|
+
|
|
243
|
+
## Platform support: what is tested where
|
|
244
|
+
|
|
245
|
+
**Linux (tested).** All 71 tests pass on Linux aarch64 (kernel 6.8, Landlock ABI 4), Python 3.12, procps `ps`, with
|
|
246
|
+
and without a systemd user session for the memory cap. The Claude Code hook and `agentlanes run` are each tested in a
|
|
247
|
+
real Claude Code session. Landlock ABI 5 and 6 (device ioctl, `--isolate`) are unit-tested only: no such kernel was
|
|
248
|
+
available. x86_64 uses the same Landlock syscall numbers but was not run.
|
|
249
|
+
|
|
250
|
+
**macOS (written, not run on a Mac).** No Mac was available. What we did instead:
|
|
251
|
+
|
|
252
|
+
- Every Linux-only assumption has a portable path: process liveness, start time (pid-reuse check) and parent walk use
|
|
253
|
+
`ps -o stat= / lstart= / ppid= -o args=` with `LC_ALL=C`; the process table uses one `-o field=` per column (the form
|
|
254
|
+
BSD `ps` and procps both accept); working directories use `lsof -d cwd`; free memory uses `vm_stat`; the memory cap
|
|
255
|
+
uses the RSS watchdog instead of systemd; `demo.sh` works without `$BASHPID` (macOS ships bash 3.2).
|
|
256
|
+
- The `ps` paths run for real on Linux in the test suite (`AGENTLANES_NO_PROC=1` turns `/proc` off): leases, reaping,
|
|
257
|
+
pid-reuse detection and `--pid self` discovery all pass that way.
|
|
258
|
+
- The macOS-only parsing (BSD `ps` lines, `vm_stat`, `lsof`, `sys.platform == 'darwin'`) is tested with canned output.
|
|
259
|
+
- **Untested on macOS:** that real macOS `ps`, `vm_stat` and `lsof` print exactly what the canned samples assume; `flock`
|
|
260
|
+
on APFS under load; the RSS watchdog's kill timing; `demo.sh` under bash 3.2; Claude Code process names on macOS.
|
|
261
|
+
If you run it on a Mac, `agentlanes doctor` and `python3 -m unittest discover -s tests` are the quickest report.
|
|
262
|
+
|
|
263
|
+
## FAQ
|
|
264
|
+
|
|
265
|
+
**Why not just use git worktrees or containers?**
|
|
266
|
+
Use them too. A worktree or container gives each agent its own copy of the files, which removes edit collisions inside
|
|
267
|
+
the tree. It does not share or divide what is left over: ports, a local database, the package and build caches, GPU and
|
|
268
|
+
memory, a test phone, and the human who is editing in the main tree at the same time. Two agents in two worktrees can
|
|
269
|
+
still both start a full build on an 8 GB machine, both bind port 3000, or both run migrations against the same dev
|
|
270
|
+
database. And at some point the work has to be merged back, which is where claims on paths help. agentlanes is the
|
|
271
|
+
coordination layer that sits next to worktrees, not a replacement for them.
|
|
272
|
+
|
|
273
|
+
**Do I need a daemon or a server?** No. Every command reads and writes JSON files under a lock and exits.
|
|
274
|
+
|
|
275
|
+
**What happens when an agent crashes while holding something?** Claims taken with `--pid` end when that process
|
|
276
|
+
exits (also on `kill -9`); a slot is a lock inherited by the command, so the kernel frees it; a taken job goes back to
|
|
277
|
+
the queue.
|
|
278
|
+
|
|
279
|
+
**Does it work with agents I do not control?** Only as far as the agent follows instructions, unless it has a hook (see
|
|
280
|
+
the table).
|
|
281
|
+
|
|
282
|
+
## How we use it
|
|
283
|
+
|
|
284
|
+
We are two founders who run many coding agents at once on one Raspberry Pi with 8 GB of RAM: interactive sessions,
|
|
285
|
+
batch agents, and agents started by other agents, next to a few dozen services. Without coordination they overwrote each
|
|
286
|
+
other's edits and started heavy builds together until the machine swapped itself to a stop. Now every agent claims the
|
|
287
|
+
paths it changes, heavy work goes through slots (one heavy build at a time, browsers capped), and the event log tells us
|
|
288
|
+
and the agents who did what. agentlanes is that setup with our internal names taken out.
|
|
289
|
+
|
|
290
|
+
## Relation to Ranix
|
|
291
|
+
|
|
292
|
+
agentlanes comes from the coordination layer we use for our own agents while building Ranix, an independent kernel where
|
|
293
|
+
AI agents and humans work on the same machine. On Ranix these primitives become kernel objects: a lease is owned by a
|
|
294
|
+
process and released by the kernel when it exits, a slot is a counting semaphore with a visible wait queue, and the event
|
|
295
|
+
log is a kernel ring stamped with the sender's identity. On Linux and macOS this package emulates them in user space with
|
|
296
|
+
files, `flock` and process start times. The command-line interface is meant to stay the same on both.
|
|
297
|
+
|
|
298
|
+
## Tests
|
|
299
|
+
|
|
300
|
+
```sh
|
|
301
|
+
python3 -m unittest discover -s tests -v
|
|
302
|
+
```
|
|
303
|
+
|
|
304
|
+
71 tests. Most drive the real CLI in subprocesses: concurrent claims from 16 processes, lease end on holder death and
|
|
305
|
+
pid reuse, TTL expiry, FIFO slot order, slot capacity, stale holder reclaim after SIGKILL, dead waiters, the memory
|
|
306
|
+
watchdog, `events wait`, concurrent emitters, job requeue, the Claude Code, Codex and Cursor hooks, strict mode,
|
|
307
|
+
`init` (fresh project, idempotency, merging into a `settings.json` that already has other hooks, invalid JSON left
|
|
308
|
+
alone) and `doctor`. `tests/test_run.py` runs real commands under Landlock: writes inside a claimed path work, and
|
|
309
|
+
`echo >`, `>>`, `cp`, `sed -i`, `mv` in and out, `rm`, `mkdir`, hard and symbolic links, `mkfifo`, `touch` and
|
|
310
|
+
`truncate` outside it fail with `Permission denied`; renames and links between two lanes work (REFER); `claim`/`release`
|
|
311
|
+
work from inside; a claim taken inside does not widen the lane; nested runs only narrow; the private temp dir works and
|
|
312
|
+
is removed; `--no-net`/`--allow-port` against a local TCP listener; events and exit codes. ABI degradation (ABI 1 to 6),
|
|
313
|
+
the struct size per ABI and the unsupported-kernel paths (ENOSYS, disabled, not Linux, refuse vs `--best-effort`) are
|
|
314
|
+
unit-tested without the kernel. Kernel tests skip themselves where Landlock is missing. `tests/test_portability.py` covers the `ps`-based and macOS code paths.
|
|
315
|
+
|
|
316
|
+
## Renaming
|
|
317
|
+
|
|
318
|
+
The name is a working name. Change `NAME` in `src/agentlanes/__init__.py` (prog name, `AGENTLANES_*` environment prefix,
|
|
319
|
+
state directory and `.agentlanes` marker follow it), the two marked lines in `pyproject.toml`, and rename `src/agentlanes/`.
|
|
320
|
+
|
|
321
|
+
## License
|
|
322
|
+
|
|
323
|
+
Apache-2.0, see [LICENSE](LICENSE). (The Ranix kernel itself is EUPL-1.2.)
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
agentlanes/__init__.py,sha256=mq4oiRfcCBTkvX6ob0RvF3L5BmilJYwmT-T-xuV6GSI,481
|
|
2
|
+
agentlanes/__main__.py,sha256=iqL5sqaJteojUO-yluSE4moQ3YYJvhp0lJWkXincvCQ,32
|
|
3
|
+
agentlanes/claims.py,sha256=pr3SBLljs3e5F_oHgl8Rk5VAw0kKCJvO26v5nfZctts,7265
|
|
4
|
+
agentlanes/cli.py,sha256=DLzm2JRS02oCeJ-P80f-8S8rlOa4PdqZ8iGznd3sWfk,13251
|
|
5
|
+
agentlanes/core.py,sha256=jffUrzzXddIclrryg_nH13-i5UwpoBxrlOabNrgbcXI,5657
|
|
6
|
+
agentlanes/hook.py,sha256=J2dknlc_I3zlpaUv13x6m17hGIefBYeaj6_v0biz6BY,6545
|
|
7
|
+
agentlanes/jobs.py,sha256=-s1hOSM0cfo25-YBwtORkbZ1U1SFy8QSf7h6FtHylmg,4164
|
|
8
|
+
agentlanes/landlock.py,sha256=GL3vjxEcjAkx2TGjsO4kGEdoVFwut1WMN1WfniUBW1E,10055
|
|
9
|
+
agentlanes/onboard.py,sha256=LFxaD5l23frb3hGPnUIFjizfCmjuzPffqA5XtsJd-r0,15357
|
|
10
|
+
agentlanes/procs.py,sha256=Y3ihjukEE9rLltm1RrxFOmfj5dN9kT-7EUQVPnZq86Y,8596
|
|
11
|
+
agentlanes/run.py,sha256=E8kO_kN5qjK3ntosV3Bw25dfAmd8YjZUm0WUHsG1svs,8710
|
|
12
|
+
agentlanes/slots.py,sha256=F3kUX4-izZXM-zxH8Y1lIyOrnfTGkRZ8EtUOCw7ZvTU,9490
|
|
13
|
+
agentlanes_cli-0.1.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
|
|
14
|
+
agentlanes_cli-0.1.0.dist-info/METADATA,sha256=ncUKQOlGf2apryzOLV-UeQ5lU9sFZp1aoe753kS-dvE,22834
|
|
15
|
+
agentlanes_cli-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
16
|
+
agentlanes_cli-0.1.0.dist-info/entry_points.txt,sha256=BxUOuWpmihghfKwXmWdY1QI8B4hL5EKSwn924D19KWE,52
|
|
17
|
+
agentlanes_cli-0.1.0.dist-info/top_level.txt,sha256=ng3MKqqGXinLHmqH94cNwfVGSrbRoUDRBzt2156JMTo,11
|
|
18
|
+
agentlanes_cli-0.1.0.dist-info/RECORD,,
|