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/landlock.py ADDED
@@ -0,0 +1,257 @@
1
+ """Linux Landlock: kernel-enforced write lanes for `agentlanes run`, without root.
2
+
3
+ The ruleset is applied to the launched command and everything it starts (Landlock domains are inherited across
4
+ fork/exec and can only get narrower). Policy: read + execute everywhere, write only beneath the allowed paths.
5
+
6
+ ABI handling follows the kernel's documented best-effort pattern: ask the running kernel for its ABI version and
7
+ drop every access right it does not know, so the same binary works from Linux 5.13 (ABI 1) to the newest ABI.
8
+ Syscall numbers 444/445/446 are the same on every architecture Linux supports (they were allocated after the
9
+ syscall tables were unified), so no per-arch table is needed.
10
+ """
11
+ import ctypes
12
+ import ctypes.util
13
+ import errno
14
+ import os
15
+ import sys
16
+
17
+ SYS_CREATE_RULESET, SYS_ADD_RULE, SYS_RESTRICT_SELF = 444, 445, 446
18
+ CREATE_RULESET_VERSION = 1 << 0
19
+ RULE_PATH_BENEATH, RULE_NET_PORT = 1, 2
20
+ PR_SET_NO_NEW_PRIVS = 38
21
+
22
+ # Filesystem access rights (include/uapi/linux/landlock.h)
23
+ FS_EXECUTE = 1 << 0
24
+ FS_WRITE_FILE = 1 << 1
25
+ FS_READ_FILE = 1 << 2
26
+ FS_READ_DIR = 1 << 3
27
+ FS_REMOVE_DIR = 1 << 4
28
+ FS_REMOVE_FILE = 1 << 5
29
+ FS_MAKE_CHAR = 1 << 6
30
+ FS_MAKE_DIR = 1 << 7
31
+ FS_MAKE_REG = 1 << 8
32
+ FS_MAKE_SOCK = 1 << 9
33
+ FS_MAKE_FIFO = 1 << 10
34
+ FS_MAKE_BLOCK = 1 << 11
35
+ FS_MAKE_SYM = 1 << 12
36
+ FS_REFER = 1 << 13 # ABI 2: link/rename across directories
37
+ FS_TRUNCATE = 1 << 14 # ABI 3
38
+ FS_IOCTL_DEV = 1 << 15 # ABI 5
39
+ NET_BIND_TCP = 1 << 0 # ABI 4
40
+ NET_CONNECT_TCP = 1 << 1 # ABI 4
41
+ SCOPE_ABSTRACT_UNIX_SOCKET = 1 << 0 # ABI 6
42
+ SCOPE_SIGNAL = 1 << 1 # ABI 6
43
+
44
+ FS_V1 = (1 << 13) - 1 # EXECUTE .. MAKE_SYM
45
+ FS_READ = FS_EXECUTE | FS_READ_FILE | FS_READ_DIR
46
+ FS_FILE_ONLY = FS_EXECUTE | FS_WRITE_FILE | FS_READ_FILE | FS_TRUNCATE | FS_IOCTL_DEV # rights valid on a non-dir
47
+
48
+ # Device files a normal tool writes to (terminal, /dev/null, ...). Everything in /dev except shared-memory and
49
+ # message-queue directories gets file-level write + ioctl, never create/remove.
50
+ DEV_SKIP = {'shm', 'mqueue', 'hugepages'}
51
+
52
+
53
+ def fs_rights(abi):
54
+ """All filesystem rights the given ABI understands (what the ruleset 'handles' = denies unless allowed)."""
55
+ if abi < 1:
56
+ return 0
57
+ r = FS_V1
58
+ if abi >= 2:
59
+ r |= FS_REFER
60
+ if abi >= 3:
61
+ r |= FS_TRUNCATE
62
+ if abi >= 5:
63
+ r |= FS_IOCTL_DEV
64
+ return r
65
+
66
+
67
+ def net_rights(abi):
68
+ return NET_BIND_TCP | NET_CONNECT_TCP if abi >= 4 else 0
69
+
70
+
71
+ def scope_rights(abi):
72
+ return SCOPE_ABSTRACT_UNIX_SOCKET | SCOPE_SIGNAL if abi >= 6 else 0
73
+
74
+
75
+ class Unsupported(Exception):
76
+ pass
77
+
78
+
79
+ class _RulesetAttr(ctypes.Structure):
80
+ _fields_ = [('handled_access_fs', ctypes.c_uint64), ('handled_access_net', ctypes.c_uint64),
81
+ ('scoped', ctypes.c_uint64)]
82
+
83
+
84
+ class _PathBeneath(ctypes.Structure):
85
+ _pack_ = 1
86
+ _fields_ = [('allowed_access', ctypes.c_uint64), ('parent_fd', ctypes.c_int32)]
87
+
88
+
89
+ class _NetPort(ctypes.Structure):
90
+ _fields_ = [('allowed_access', ctypes.c_uint64), ('port', ctypes.c_uint64)]
91
+
92
+
93
+ _libc = None
94
+
95
+
96
+ def _syscall():
97
+ global _libc
98
+ if _libc is None:
99
+ _libc = ctypes.CDLL(ctypes.util.find_library('c') or None, use_errno=True)
100
+ _libc.syscall.restype = ctypes.c_long
101
+ _libc.prctl.restype = ctypes.c_int
102
+ return _libc
103
+
104
+
105
+ def _call(nr, *args):
106
+ libc = _syscall()
107
+ ctypes.set_errno(0)
108
+ r = libc.syscall(ctypes.c_long(nr), *args)
109
+ if r < 0:
110
+ e = ctypes.get_errno()
111
+ raise OSError(e, os.strerror(e))
112
+ return r
113
+
114
+
115
+ def abi_version():
116
+ """Landlock ABI of the running kernel (>= 1), or raise Unsupported with the reason."""
117
+ if not sys.platform.startswith('linux'):
118
+ raise Unsupported('Landlock is a Linux feature (this is %s)' % sys.platform)
119
+ try:
120
+ return _call(SYS_CREATE_RULESET, None, ctypes.c_size_t(0), ctypes.c_uint32(CREATE_RULESET_VERSION))
121
+ except OSError as e:
122
+ if e.errno == errno.ENOSYS:
123
+ raise Unsupported('this kernel has no Landlock (needs Linux 5.13+ built with CONFIG_SECURITY_LANDLOCK)')
124
+ if e.errno == errno.EOPNOTSUPP:
125
+ raise Unsupported('Landlock is built in but disabled; add "landlock" to the lsm= boot parameter')
126
+ raise Unsupported('Landlock version query failed: %s' % e)
127
+ except (AttributeError, TypeError) as e: # no syscall() in this libc
128
+ raise Unsupported('cannot call syscall(): %s' % e)
129
+
130
+
131
+ def describe_abi():
132
+ """One line for `doctor`. Returns (level, text)."""
133
+ try:
134
+ abi = abi_version()
135
+ except Unsupported as e:
136
+ return ('info' if not sys.platform.startswith('linux') else 'warn'), 'Landlock unavailable: %s' % e
137
+ have = ['filesystem writes']
138
+ if abi >= 2:
139
+ have.append('cross-dir rename/link (REFER)')
140
+ if abi >= 3:
141
+ have.append('truncate')
142
+ if abi >= 4:
143
+ have.append('TCP bind/connect')
144
+ if abi >= 5:
145
+ have.append('device ioctl')
146
+ if abi >= 6:
147
+ have.append('signal/abstract-socket scoping')
148
+ return 'ok', 'Landlock ABI %d: `run` can enforce %s' % (abi, ', '.join(have))
149
+
150
+
151
+ class Policy:
152
+ """What to allow. Paths that do not exist are reported in `skipped` (a rule needs an open fd)."""
153
+
154
+ def __init__(self, write=(), no_net=False, connect_ports=(), bind_ports=(), isolate=False, dev=True):
155
+ self.write = [os.path.realpath(os.path.expanduser(p)) for p in write]
156
+ self.no_net = no_net or bool(connect_ports) or bool(bind_ports)
157
+ self.connect_ports = sorted({int(p) for p in connect_ports})
158
+ self.bind_ports = sorted({int(p) for p in bind_ports})
159
+ self.isolate = isolate
160
+ self.dev = dev
161
+
162
+
163
+ def plan(policy, abi, listdir=os.listdir, isdir=os.path.isdir, exists=os.path.exists, islink=os.path.islink):
164
+ """Pure function: the ruleset for POLICY on ABI. Returns dict with handled masks, rules and warnings.
165
+
166
+ Kept free of syscalls so ABI degradation can be unit-tested on any kernel."""
167
+ fs = fs_rights(abi)
168
+ out = {'abi': abi, 'handled_fs': fs, 'handled_net': 0, 'scoped': 0, 'rules': [], 'net_rules': [],
169
+ 'warnings': [], 'skipped': []}
170
+
171
+ def add(path, rights):
172
+ if not exists(path):
173
+ out['skipped'].append(path)
174
+ return
175
+ if not isdir(path):
176
+ rights &= FS_FILE_ONLY
177
+ out['rules'].append((path, rights & fs))
178
+
179
+ add('/', FS_READ)
180
+ if policy.dev and exists('/dev'):
181
+ for name in sorted(listdir('/dev')):
182
+ if name not in DEV_SKIP and not islink('/dev/' + name): # stdin/fd/... point into /proc
183
+ add('/dev/' + name, FS_READ | FS_WRITE_FILE | FS_TRUNCATE | FS_IOCTL_DEV)
184
+ for p in policy.write:
185
+ add(p, fs)
186
+ if abi < 2:
187
+ out['warnings'].append('Landlock ABI 1: renaming or hard-linking a file into another directory is always '
188
+ 'denied (EXDEV), even inside allowed paths; tools that do that may fail')
189
+ if abi < 3:
190
+ out['warnings'].append('Landlock ABI %d: truncate() is not restricted (ABI 3+); a file outside the lanes can '
191
+ 'still be emptied with truncate, though not written' % abi)
192
+ if policy.no_net:
193
+ if abi >= 4:
194
+ out['handled_net'] = net_rights(abi)
195
+ out['net_rules'] = ([(p, NET_CONNECT_TCP) for p in policy.connect_ports] +
196
+ [(p, NET_BIND_TCP) for p in policy.bind_ports])
197
+ else:
198
+ out['warnings'].append('network restriction needs Landlock ABI 4 (Linux 6.7+); this kernel has ABI %d, '
199
+ 'so TCP is NOT restricted' % abi)
200
+ if policy.isolate:
201
+ if abi >= 6:
202
+ out['scoped'] = scope_rights(abi)
203
+ else:
204
+ out['warnings'].append('--isolate needs Landlock ABI 6 (Linux 6.12+); this kernel has ABI %d, so signals '
205
+ 'to outside processes are NOT restricted' % abi)
206
+ return out
207
+
208
+
209
+ def summary(p):
210
+ w = [path for path, r in p['rules'] if r & FS_MAKE_REG or r & FS_WRITE_FILE and not path.startswith('/dev/')]
211
+ s = {'abi': p['abi'], 'write': w, 'tcp': 'unrestricted'}
212
+ if p['handled_net']:
213
+ s['tcp'] = 'connect %s; bind %s' % (
214
+ ','.join(str(x) for x, r in p['net_rules'] if r == NET_CONNECT_TCP) or 'none',
215
+ ','.join(str(x) for x, r in p['net_rules'] if r == NET_BIND_TCP) or 'none')
216
+ if p['scoped']:
217
+ s['scoped'] = 'signals+abstract-unix'
218
+ if p['skipped']:
219
+ s['skipped'] = p['skipped']
220
+ return s
221
+
222
+
223
+ def build(p):
224
+ """Create the kernel ruleset for plan P. Returns the ruleset fd (O_CLOEXEC)."""
225
+ abi = p['abi']
226
+ attr = _RulesetAttr(p['handled_fs'], p['handled_net'], p['scoped'])
227
+ size = 8 if abi < 4 else 16 if abi < 6 else 24 # older kernels reject unknown trailing fields
228
+ fd = _call(SYS_CREATE_RULESET, ctypes.byref(attr), ctypes.c_size_t(size), ctypes.c_uint32(0))
229
+ try:
230
+ for path, rights in p['rules']:
231
+ if not rights:
232
+ continue
233
+ pfd = os.open(path, os.O_PATH | os.O_CLOEXEC)
234
+ try:
235
+ rule = _PathBeneath(rights, pfd)
236
+ _call(SYS_ADD_RULE, ctypes.c_int(fd), ctypes.c_int(RULE_PATH_BENEATH), ctypes.byref(rule),
237
+ ctypes.c_uint32(0))
238
+ except OSError as e:
239
+ raise OSError(e.errno, 'landlock_add_rule(%s): %s' % (path, e.strerror))
240
+ finally:
241
+ os.close(pfd)
242
+ for port, rights in p['net_rules']:
243
+ rule = _NetPort(rights, port)
244
+ _call(SYS_ADD_RULE, ctypes.c_int(fd), ctypes.c_int(RULE_NET_PORT), ctypes.byref(rule), ctypes.c_uint32(0))
245
+ except Exception:
246
+ os.close(fd)
247
+ raise
248
+ return fd
249
+
250
+
251
+ def restrict_self(fd):
252
+ """Enforce ruleset FD on the calling process (and its future children). Safe to call between fork and exec."""
253
+ libc = _syscall()
254
+ if libc.prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) != 0:
255
+ e = ctypes.get_errno()
256
+ raise OSError(e, 'prctl(NO_NEW_PRIVS): ' + os.strerror(e))
257
+ _call(SYS_RESTRICT_SELF, ctypes.c_int(fd), ctypes.c_uint32(0))
agentlanes/onboard.py ADDED
@@ -0,0 +1,364 @@
1
+ """`init` (set a project up) and `doctor` (check an install). Both are safe to run again and again."""
2
+ import json
3
+ import os
4
+ import shlex
5
+ import shutil
6
+ import subprocess
7
+ import sys
8
+ import time
9
+
10
+ from . import ENV, NAME, PROJECT_MARKER, __version__, core, procs
11
+
12
+ BEGIN = '<!-- %s:begin -->' % NAME
13
+ END = '<!-- %s:end -->' % NAME
14
+
15
+ SNIPPET = """## Working alongside other agents
16
+
17
+ Other coding agents may be working on this machine at the same time. Coordinate through `{n}`:
18
+
19
+ 1. Before editing, run `{n} list` to see what others hold.
20
+ 2. Claim what you will change:
21
+ `{n} claim <short-topic> --paths <files-or-dirs> --pid self --desc "<one line: what you are doing>"`
22
+ If it prints `HELD` or `PATH HELD`, do not edit those paths. Pick other work, or wait with
23
+ `{n} events wait --kind claim.done --timeout 600` and try again.
24
+ 3. When finished (or when you give up), run `{n} release <short-topic>`.
25
+ If you exit or crash, the claim ends by itself because of `--pid self`.
26
+ 4. Run heavy commands (full builds, full test suites, browsers, model runs) through a slot:
27
+ `{n} slot heavy 1 -- <command>`. Never start a second copy of a heavy command in parallel.
28
+ 5. Claims expire after 120 minutes; run `{n} renew <short-topic>` if you need longer.
29
+ 6. To wait for another agent, use `{n} events wait --kind <kind>` instead of sleep loops.
30
+ """.format(n=NAME)
31
+
32
+ CURSOR_RULE = """---
33
+ description: Coordinate with other coding agents on this machine through {n}
34
+ alwaysApply: true
35
+ ---
36
+ """.format(n=NAME) + SNIPPET
37
+
38
+ HOOK_MATCHER = 'Edit|Write|MultiEdit|NotebookEdit'
39
+
40
+
41
+ def self_command():
42
+ """How a hook should call us: the bare name if it is on PATH, else the absolute path of this checkout."""
43
+ if shutil.which(NAME):
44
+ return NAME
45
+ argv0 = os.path.realpath(sys.argv[0]) if sys.argv and sys.argv[0] else ''
46
+ if argv0 and os.path.basename(argv0) == NAME and os.path.isfile(argv0):
47
+ return '%s %s' % (shlex.quote(sys.executable), shlex.quote(argv0))
48
+ return '%s -m %s' % (shlex.quote(sys.executable), NAME)
49
+
50
+
51
+ def hook_command(strict=False, cmd=None):
52
+ cmd = cmd or self_command()
53
+ if not strict:
54
+ return '%s hook claude-code' % cmd
55
+ first = shlex.split(cmd)[0]
56
+ # Exit 2 makes Claude Code block the tool call and show stderr to the model, even when the tool is missing.
57
+ return ('command -v %s >/dev/null 2>&1 || { echo "%s is not installed or not on PATH; edits are blocked '
58
+ '(strict mode). Install it or remove the hook." >&2; exit 2; }; %s_STRICT=1 %s hook claude-code'
59
+ % (shlex.quote(first), NAME, ENV, cmd))
60
+
61
+
62
+ def _is_our_hook(h):
63
+ return isinstance(h, dict) and ' hook claude-code' in str(h.get('command', '')) and NAME in str(h.get('command'))
64
+
65
+
66
+ def merge_settings(settings, command):
67
+ """Add our PreToolUse hook to a Claude Code settings dict in place. Returns 'added', 'updated' or 'present'."""
68
+ hooks = settings.setdefault('hooks', {})
69
+ if not isinstance(hooks, dict):
70
+ raise ValueError('"hooks" in settings is not an object')
71
+ pre = hooks.setdefault('PreToolUse', [])
72
+ if not isinstance(pre, list):
73
+ raise ValueError('"hooks.PreToolUse" in settings is not a list')
74
+ for group in pre:
75
+ for h in (group.get('hooks') or []) if isinstance(group, dict) else []:
76
+ if _is_our_hook(h):
77
+ if h.get('command') == command:
78
+ return 'present'
79
+ h['command'] = command
80
+ return 'updated'
81
+ pre.append({'matcher': HOOK_MATCHER, 'hooks': [{'type': 'command', 'command': command, 'timeout': 10}]})
82
+ return 'added'
83
+
84
+
85
+ def _write(p, text):
86
+ tmp = '%s.%d.tmp' % (p, os.getpid())
87
+ with open(tmp, 'w', encoding='utf-8') as fh:
88
+ fh.write(text)
89
+ os.replace(tmp, p)
90
+
91
+
92
+ def wire_claude_code(root, strict=False, out=print, command=None):
93
+ """Merge the hook into ROOT/.claude/settings.json; back the old file up first. Returns exit code."""
94
+ d = os.path.join(root, '.claude')
95
+ p = os.path.join(d, 'settings.json')
96
+ settings, original = {}, None
97
+ if os.path.exists(p):
98
+ with open(p, encoding='utf-8') as fh:
99
+ original = fh.read()
100
+ try:
101
+ settings = json.loads(original) if original.strip() else {}
102
+ except ValueError as e:
103
+ out('error: %s is not valid JSON (%s); left untouched. Fix it and run init again.' % (p, e))
104
+ return 1
105
+ if not isinstance(settings, dict):
106
+ out('error: %s is not a JSON object; left untouched.' % p)
107
+ return 1
108
+ try:
109
+ what = merge_settings(settings, hook_command(strict, command))
110
+ except ValueError as e:
111
+ out('error: %s: %s; left untouched.' % (p, e))
112
+ return 1
113
+ if what == 'present':
114
+ out('ok Claude Code hook already in %s' % p)
115
+ return 0
116
+ os.makedirs(d, exist_ok=True)
117
+ if original is not None:
118
+ bak = '%s.%s-backup-%s' % (p, NAME, time.strftime('%Y%m%d-%H%M%S'))
119
+ _write(bak, original)
120
+ out(' backup of the previous settings: %s' % bak)
121
+ _write(p, json.dumps(settings, indent=2, ensure_ascii=False) + '\n')
122
+ out('%s Claude Code hook in %s%s' % ('added ' if what == 'added' else 'update', p, ' (strict)' if strict else ''))
123
+ return 0
124
+
125
+
126
+ def append_snippet(p, body=SNIPPET, out=print):
127
+ """Append the agent instructions to P between markers, once."""
128
+ old = ''
129
+ if os.path.exists(p):
130
+ with open(p, encoding='utf-8') as fh:
131
+ old = fh.read()
132
+ if BEGIN in old:
133
+ out('ok instructions already in %s' % p)
134
+ return 0
135
+ sep = ''
136
+ if old: # exactly one blank line between the existing text and ours
137
+ sep = ('' if old.endswith('\n') else '\n') + ('' if old.endswith('\n\n') else '\n')
138
+ os.makedirs(os.path.dirname(p) or '.', exist_ok=True)
139
+ _write(p, old + sep + BEGIN + '\n' + body.rstrip('\n') + '\n' + END + '\n')
140
+ out('added instructions to %s' % p)
141
+ return 0
142
+
143
+
144
+ def init(root=None, claude_code=False, agents_md=False, claude_md=False, cursor=False, strict=False, out=print):
145
+ root = os.path.abspath(root or os.getcwd())
146
+ d = os.path.join(root, PROJECT_MARKER)
147
+ os.makedirs(d, exist_ok=True)
148
+ gi = os.path.join(d, '.gitignore')
149
+ if not os.path.exists(gi):
150
+ _write(gi, '# runtime coordination state, never commit\n*\n')
151
+ out('ok state directory %s (ignored by git)' % d)
152
+ rc = 0
153
+ if claude_code:
154
+ rc |= wire_claude_code(root, strict, out)
155
+ if agents_md:
156
+ rc |= append_snippet(os.path.join(root, 'AGENTS.md'), out=out)
157
+ if claude_md:
158
+ rc |= append_snippet(os.path.join(root, 'CLAUDE.md'), out=out)
159
+ if cursor:
160
+ p = os.path.join(root, '.cursor', 'rules', NAME + '.mdc')
161
+ if os.path.exists(p):
162
+ out('ok Cursor rule already at %s' % p)
163
+ else:
164
+ os.makedirs(os.path.dirname(p), exist_ok=True)
165
+ _write(p, CURSOR_RULE)
166
+ out('added Cursor rule %s' % p)
167
+ if not (claude_code or agents_md or claude_md or cursor):
168
+ out('next: `%s init --claude-code --agents-md` wires the Claude Code hook and agent instructions' % NAME)
169
+ if not shutil.which(NAME):
170
+ out('warn `%s` is not on PATH; agents and hooks need it there (pip install .)' % NAME)
171
+ return rc
172
+
173
+
174
+ # ------------------------------------------------------------------ doctor
175
+
176
+ def _flock_excludes(state):
177
+ """True if a second process really cannot take a lock we hold (catches filesystems where flock is a no-op)."""
178
+ import fcntl
179
+ p = os.path.join(state, '.doctor.lock')
180
+ with open(p, 'a') as fh:
181
+ fcntl.flock(fh, fcntl.LOCK_EX)
182
+ code = ('import fcntl,sys\nf=open(sys.argv[1],"a")\ntry:\n fcntl.flock(f,fcntl.LOCK_EX|fcntl.LOCK_NB)\n'
183
+ ' sys.exit(1)\nexcept OSError:\n sys.exit(0)\n')
184
+ r = subprocess.run([sys.executable, '-c', code, p], timeout=20)
185
+ fcntl.flock(fh, fcntl.LOCK_UN)
186
+ try:
187
+ os.remove(p)
188
+ except OSError:
189
+ pass
190
+ return r.returncode == 0
191
+
192
+
193
+ def fs_type(path):
194
+ """Filesystem type of PATH on Linux (from /proc/mounts), else None."""
195
+ if not procs.LINUX:
196
+ return None
197
+ best, typ = '', None
198
+ real = os.path.realpath(path)
199
+ try:
200
+ with open('/proc/mounts') as fh:
201
+ for line in fh:
202
+ f = line.split()
203
+ if len(f) >= 3:
204
+ mnt = f[1].replace('\\040', ' ')
205
+ if (real == mnt or real.startswith(mnt.rstrip('/') + '/')) and len(mnt) > len(best):
206
+ best, typ = mnt, f[2]
207
+ except OSError:
208
+ return None
209
+ return typ
210
+
211
+
212
+ def _state_source():
213
+ if core.env('STATE_DIR'):
214
+ return '$%s_STATE_DIR' % ENV
215
+ cur = os.getcwd()
216
+ while True:
217
+ if os.path.isdir(os.path.join(cur, PROJECT_MARKER)):
218
+ return 'project marker'
219
+ parent = os.path.dirname(cur)
220
+ if parent == cur:
221
+ return 'user default'
222
+ cur = parent
223
+
224
+
225
+ def _project_root():
226
+ d = core.state_dir()
227
+ if os.path.basename(d) == PROJECT_MARKER:
228
+ return os.path.dirname(d)
229
+ return os.getcwd()
230
+
231
+
232
+ def _hook_files(root):
233
+ return [os.path.join(root, '.claude', 'settings.json'), os.path.join(root, '.claude', 'settings.local.json'),
234
+ os.path.expanduser('~/.claude/settings.json')]
235
+
236
+
237
+ def find_hooks(root):
238
+ """[(settings_file, command)] for every agentlanes Claude Code hook found."""
239
+ found = []
240
+ for p in _hook_files(root):
241
+ s = core.load_json(p, None)
242
+ if not isinstance(s, dict):
243
+ continue
244
+ for group in ((s.get('hooks') or {}).get('PreToolUse') or []) if isinstance(s.get('hooks'), dict) else []:
245
+ for h in (group.get('hooks') or []) if isinstance(group, dict) else []:
246
+ if _is_our_hook(h):
247
+ found.append((p, h['command']))
248
+ return found
249
+
250
+
251
+ def _hook_runs(command):
252
+ """Feed the hook a harmless Edit on an unclaimed path; it must exit 0 with no deny."""
253
+ probe = json.dumps({'hook_event_name': 'PreToolUse', 'tool_name': 'Edit',
254
+ 'tool_input': {'file_path': os.path.join(core.state_dir(), '.doctor-probe')}})
255
+ try:
256
+ r = subprocess.run(command, shell=True, input=probe, capture_output=True, text=True, timeout=20)
257
+ except Exception as e:
258
+ return False, str(e)
259
+ if r.returncode != 0:
260
+ return False, 'exit %d: %s' % (r.returncode, (r.stderr or r.stdout).strip()[:200])
261
+ if 'deny' in r.stdout:
262
+ return False, 'denied an unclaimed path: %s' % r.stdout.strip()[:200]
263
+ return True, ''
264
+
265
+
266
+ def doctor(out=print):
267
+ """Print one line per check. Exit 1 if any check FAILs (warnings do not fail)."""
268
+ results = []
269
+
270
+ def rep(level, what, fix=None):
271
+ results.append(level)
272
+ out('%-5s %s' % (level, what))
273
+ if fix:
274
+ out(' fix: %s' % fix)
275
+
276
+ rep('info', '%s %s, Python %s, %s' % (NAME, __version__, sys.version.split()[0], sys.platform))
277
+ exe = shutil.which(NAME)
278
+ if exe:
279
+ rep('ok', 'on PATH: %s' % exe)
280
+ else:
281
+ rep('FAIL', '`%s` is not on PATH, so agents and hooks cannot call it' % NAME,
282
+ 'pip install . (or pipx install .), or add the bin/ directory of this checkout to PATH')
283
+ # state dir
284
+ try:
285
+ state = core.state_dir()
286
+ rep('ok', 'state directory %s (%s)' % (state, _state_source()))
287
+ probe = os.path.join(state, '.doctor-write')
288
+ with open(probe, 'w') as fh:
289
+ fh.write('x')
290
+ os.remove(probe)
291
+ rep('ok', 'state directory is writable')
292
+ except OSError as e:
293
+ state = None
294
+ rep('FAIL', 'state directory not usable: %s' % e,
295
+ 'set %s_STATE_DIR to a writable local directory, or run `%s init` in the project' % (ENV, NAME))
296
+ if state:
297
+ typ = fs_type(state)
298
+ if typ and (typ.startswith('nfs') or typ in ('cifs', 'smb3', 'smbfs', 'fuse.sshfs', '9p', 'virtiofs')):
299
+ rep('warn', 'state directory is on %s; flock there may not exclude other machines or may not work' % typ,
300
+ 'use a local disk for %s_STATE_DIR' % ENV)
301
+ try:
302
+ if _flock_excludes(state):
303
+ rep('ok', 'flock excludes a second process')
304
+ else:
305
+ rep('FAIL', 'flock does not exclude a second process on this filesystem',
306
+ 'use a local disk for %s_STATE_DIR' % ENV)
307
+ except Exception as e:
308
+ rep('FAIL', 'flock test failed: %s' % e, 'use a local disk for %s_STATE_DIR' % ENV)
309
+ claims_f = os.path.join(state, 'claims.json')
310
+ if os.path.exists(claims_f):
311
+ try:
312
+ with open(claims_f, encoding='utf-8') as fh:
313
+ json.load(fh)
314
+ rep('ok', 'claims.json parses')
315
+ except ValueError as e:
316
+ rep('FAIL', 'claims.json is corrupt (%s); claims in it are ignored' % e,
317
+ 'move it aside: mv %s %s.bad' % (shlex.quote(claims_f), shlex.quote(claims_f)))
318
+ # process inspection
319
+ if procs.LINUX:
320
+ rep('ok', 'process inspection via /proc')
321
+ elif shutil.which('ps'):
322
+ tok = procs.start_token(os.getpid())
323
+ if tok:
324
+ rep('ok', 'process inspection via ps (start time: %s)' % tok)
325
+ else:
326
+ rep('FAIL', '`ps -o lstart=` gave nothing; leases cannot detect recycled pids')
327
+ else:
328
+ rep('FAIL', 'no /proc and no `ps`: leases (--pid) cannot work')
329
+ apid, kind = procs.agent_self()
330
+ rep('info', 'enclosing coding agent: %s' % ('%s pid %d' % (kind, apid) if apid else
331
+ 'none found (fine in a plain shell; `--pid self` needs one)'))
332
+ # kernel-enforced write lanes
333
+ from . import landlock
334
+ lvl, txt = landlock.describe_abi()
335
+ rep(lvl, txt, None if lvl != 'warn' else '`%s run` refuses without Landlock (or runs unconfined with '
336
+ '--best-effort); hooks still apply' % NAME)
337
+ # memory caps
338
+ from . import slots
339
+ if slots._systemd_scope_ok():
340
+ rep('ok', 'slot --max-mem uses a systemd user scope (MemoryMax)')
341
+ else:
342
+ rep('info', 'slot --max-mem uses the RSS watchdog (no systemd user session%s)'
343
+ % ('' if sys.platform.startswith('linux') else ' on this OS'))
344
+ m = procs.mem_available_mb()
345
+ rep('ok' if m is not None else 'warn', 'available memory: %s' % ('%d MB' % m if m is not None else 'unknown'),
346
+ None if m is not None else 'slot --mem-free will not wait')
347
+ # hook
348
+ root = _project_root()
349
+ hooks = find_hooks(root)
350
+ if not hooks:
351
+ rep('warn', 'no Claude Code hook found in %s' % ', '.join(_hook_files(root)),
352
+ '`%s init --claude-code` (only needed if you use Claude Code)' % NAME)
353
+ for p, cmd in hooks:
354
+ ok, why = _hook_runs(cmd)
355
+ if ok:
356
+ rep('ok', 'Claude Code hook in %s runs%s' % (p, ' (strict)' if '_STRICT=1' in cmd else ' (fail-open)'))
357
+ else:
358
+ rep('FAIL', 'Claude Code hook in %s does not run: %s' % (p, why),
359
+ 'make sure `%s` is on PATH for Claude Code, or rerun `%s init --claude-code`' % (NAME, NAME))
360
+ from .hook import strict
361
+ rep('info', 'strict mode in this shell (%s_STRICT): %s' % (ENV, 'on' if strict() else 'off, hooks fail open'))
362
+ bad = results.count('FAIL')
363
+ out('%d problem(s)' % bad if bad else 'all checks passed')
364
+ return 1 if bad else 0