Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion .github/fork-ci-tests.txt
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,14 @@ fork-ci/actions/test-select/test-select.test.py ~26s unittest
fork-ci/actions/test-select/trace-check.test.py unittest
fork-ci/actions/weakened-tests/weakened_tests.test.py unittest
fork-ci/laws/laws.test.py unittest
fork-kit/agent-guards/tests/actions-disable.test.py ~45s unittest
fork-kit/agent-guards/tests/agent-slots.test.py unittest
fork-kit/agent-guards/tests/bg-guard.test.py unittest
fork-kit/agent-guards/tests/capacity-pipe.test.py unittest
fork-kit/agent-guards/tests/config.test.py unittest
fork-kit/agent-guards/tests/install.test.py ~20s unittest
fork-kit/agent-guards/tests/memory-index.test.py unittest
fork-kit/agent-guards/tests/wiring.test.py unittest
fork-kit/cleaner/tests/compress.test.py ~15s unittest
fork-kit/cleaner/tests/daily.test.py ~19s unittest
fork-kit/cleaner/tests/dedupe.test.py ~22s unittest
Expand All @@ -108,7 +116,7 @@ fork-kit/cleaner/tests/report.test.py unittest
fork-kit/cleaner/tests/scratch.test.py unittest
fork-kit/cleaner/tests/worktrees.test.py ~43s unittest
fork-kit/common/tests/free_contract.test.py ~6s unittest
fork-kit/common/tests/kit_install.test.py ~93s unittest
fork-kit/common/tests/kit_install.test.py ~125s unittest
fork-kit/common/tests/machine_file.test.py unittest
fork-kit/desk/tests/install.test.py ~103s unittest
fork-kit/desk/tests/windows.test.py ~65s unittest
Expand Down
3 changes: 2 additions & 1 deletion fork-kit/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ Every kit follows the same pattern:

| Kit | What |
| ---------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [agent-guards](agent-guards/README.md) | Claude Code hooks that guard every agent on a machine: no disabling Actions, no piped capacity check, a memory index in budget, no stop with a background command, agent slots (Linux) |
| [cleaner](cleaner/README.md) | `fork-cleaner`: free disk space by rules (`worktrees` with merged branches, `tmp`, `agent-scratch`, `docker`; `compress-cold` and `dedupe` delete no content) and never what could be needed; daily timer (Linux, systemd) |
| [desk](desk/README.md) | A desktop's side of a fork fleet desk pool: runner users, walls, desk agent; one folder (Linux, WSL2) |
| [gh-apps](gh-apps/README.md) | GitHub App tokens for agents through `gh-as`, without giving agents the keys (Linux) |
Expand All @@ -27,7 +28,7 @@ Every kit follows the same pattern:

[common](common/README.md) is code the kits share, copied into each kit's version folder: the loader of the one
private machine file (`/etc/fork-kit/machine.json`) where the facts of one machine live, and the installer and
bootstrap of the cleaner, golive and schedule-kick kits.
bootstrap of the agent-guards, cleaner, golive and schedule-kick kits.

[review](review/README.md) is the one kit with no installer: a skill, docs and tools an agent uses from a checkout
of the fork, beside the merge gate whose parser it imports.
202 changes: 202 additions & 0 deletions fork-kit/agent-guards/README.md

Large diffs are not rendered by default.

3,514 changes: 3,514 additions & 0 deletions fork-kit/agent-guards/bin/actions-disable-guard

Large diffs are not rendered by default.

184 changes: 184 additions & 0 deletions fork-kit/agent-guards/bin/agent-guards
Original file line number Diff line number Diff line change
@@ -0,0 +1,184 @@
#!/usr/bin/python3 -IB
"""agent-guards: the command of the agent-guards kit (fork-kit/agent-guards/README.md).

agent-guards self-check the machine file's "agent-guards" section, the hook files, the managed
settings drop-in (exit 1 on a problem)
agent-guards check [--settings F] run each hook wired in F (default: the managed settings drop-in) with one
case it must refuse and one it must pass (exit 1 on a problem). As root,
F must be root's and only root may write it (its commands are run)
agent-guards hooks [--bin DIR] print the "hooks" settings of every hook of the kit, for a settings file
agent-guards approve [--hours N] [--cwd DIR] --command 'CMD'
as root: approve ONE command that actions-disable-guard refuses, run in
DIR (default: this folder), once, within N hours (default 1, at most 24);
prints the code the command must end with
agent-guards approve --revoke as root: end the approval now
"""
import argparse, grp, json, os, pwd, subprocess, sys

_kit = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
sys.path.insert(0, os.path.join(_kit, 'lib'))

PROG = 'agent-guards'
ROOT_UID = 0 # tests only


def root_ways(user):
"""How `user` can become root without the owner (sudo without a password, the docker group): one text each.
The approval file and the managed settings are root's; such a user can write them."""
out = []
try:
pw = pwd.getpwnam(user)
docker = grp.getgrnam('docker')
if user in docker.gr_mem or pw.pw_gid == docker.gr_gid:
out.append(f'{user} is in the docker group (a container can write any root file)')
except KeyError:
pass
try:
if os.geteuid() == ROOT_UID:
r = subprocess.run(['sudo', '-n', '-l', '-U', user], capture_output=True, text=True, timeout=10)
if 'NOPASSWD' in r.stdout:
out.append(f'{user} may run sudo without a password (NOPASSWD)')
else:
r = subprocess.run(['sudo', '-n', 'true'], capture_output=True, text=True, timeout=10)
if r.returncode == 0:
out.append(f'{user} can run sudo now without typing a password')
except (OSError, subprocess.SubprocessError):
pass
return out


def self_check(bin_dir, drop_in, links_dir=None):
from agent_guards import approval, config, wiring
links_dir = links_dir or wiring.BIN
problems, notes = [], []
settings, cfg_problems = config.load_all()
problems += [f'machine file: {p}' for p in cfg_problems]
for hook in wiring.HOOKS:
if not os.access(os.path.join(bin_dir, hook), os.R_OK):
problems.append(f'{os.path.join(bin_dir, hook)} is missing or cannot be read')
wired = False
try:
with open(drop_in, encoding='utf-8') as f:
text = f.read()
if json.loads(text) != {'hooks': wiring.hooks()}:
problems.append(f'{drop_in} is not the kit\'s drop-in of this release: run the installer again '
'(agent-guards-install install ... --settings)')
else:
wired = True
notes.append(f'{drop_in}: every hook is wired in managed settings')
except FileNotFoundError:
notes.append(f'{drop_in} is not there: the hooks are not in managed settings (installer --settings, or '
'by hand from `agent-guards hooks`)')
except (OSError, ValueError) as e:
problems.append(f'{drop_in} cannot be read ({e})')
for hook in wiring.HOOKS: # what the settings entries run: the links, not this version folder
link = os.path.join(links_dir, hook)
if os.path.realpath(link) != os.path.realpath(os.path.join(bin_dir, hook)):
(problems if wired else notes).append(
f'{link} is not this kit\'s {hook} ({os.path.realpath(link) if os.path.lexists(link) else "missing"})')
data, why = approval.read()
if data is not None:
import time
left = data['until'] - time.time()
notes.append(f'an owner approval for actions-disable-guard is open for {int(left // 60)} more minutes '
f'(one command, run once in {data["cwd"]})'
if left > 0 else 'an owner approval file is there, its time is over')
user = os.environ.get('SUDO_USER') or pwd.getpwuid(os.getuid()).pw_name
if user == 'root':
notes.append('run the self-check as the agents\' user, or through sudo, to see whether that user can become '
'root without the owner')
for way in root_ways(user) if user != 'root' else ():
notes.append(f'WARNING: {way}: an agent of that user can become root, and then write the managed settings, '
'the machine file and the approval file; the hooks do not hold against it')
for hook, s in settings.items():
notes.append(f'{hook}: {json.dumps(s, sort_keys=True)}')
for n in notes:
print(f'note: {n}')
for p in problems:
print(f'PROBLEM: {p}')
print(f'{PROG} self-check: ' + ('OK' if not problems else f'{len(problems)} problem(s)'))
return 0 if not problems else 1


def main(argv):
if argv in (['-h'], ['--help']):
print(__doc__.strip())
return 0
from agent_guards import check, wiring
ap = argparse.ArgumentParser(prog=PROG)
sub = ap.add_subparsers(dest='cmd', required=True)
sub.add_parser('self-check')
c = sub.add_parser('check')
c.add_argument('--settings', default=wiring.DROP_IN)
h = sub.add_parser('hooks')
h.add_argument('--bin', default=wiring.BIN)
p = sub.add_parser('approve')
p.add_argument('--hours', type=float, default=1.0)
p.add_argument('--revoke', action='store_true')
p.add_argument('--command', help='the one command approved (exactly; blanks may differ)')
p.add_argument('--cwd', help='the folder it runs in (default: this one)')
a = ap.parse_args(argv)
if a.cmd == 'self-check':
return self_check(os.path.dirname(os.path.realpath(__file__)), wiring.DROP_IN)
if a.cmd == 'hooks':
print(json.dumps({'hooks': wiring.hooks(a.bin)}, indent=2))
return 0
if a.cmd == 'approve':
return approve(a)
try:
settings = json.loads(read_settings(a.settings))
except (OSError, ValueError) as e:
print(f'{PROG}: cannot read {a.settings} ({e})', file=sys.stderr)
return 1
return check.run(settings, a.settings)


def read_settings(path):
"""The text of a settings file whose commands `check` runs. As root only a file root owns, that only root can
write, in folders only root can write (else anyone who can write it runs commands as root)."""
if os.geteuid() != ROOT_UID:
with open(path, encoding='utf-8') as f:
return f.read()
from agent_guards import approval # noqa: F401 - puts fork-kit/common on the path
import machine_file
try:
return machine_file.read_protected_text(os.path.abspath(path), ROOT_UID)
except machine_file.MachineFileError as e:
raise OSError(f'not safe to run as root: {e}') from None


def approve(a):
from agent_guards import approval
if os.geteuid() != ROOT_UID:
print(f'{PROG} approve: run this as root (sudo {PROG} approve): only root can write the approval',
file=sys.stderr)
return 1
if a.revoke:
print(f'{PROG}: approval removed' if approval.revoke() else f'{PROG}: there was no approval')
return 0
if not 0 < a.hours <= approval.MAX_HOURS:
print(f'{PROG} approve: --hours must be above 0 and at most {approval.MAX_HOURS}', file=sys.stderr)
return 1
if not a.command or not approval.normalise(a.command):
print(f'{PROG} approve: name the one command you approve: --command \'<the exact command>\' (the approval '
'passes that command only, once)', file=sys.stderr)
return 1
cwd = os.path.realpath(a.cwd or os.getcwd())
code = approval.new_code()
try:
data = approval.write(code, a.hours, a.command, cwd)
except (OSError, ValueError) as e:
print(f'{PROG} approve: cannot write {approval.PATH} ({e})', file=sys.stderr)
return 1
import time
until = time.strftime('%Y-%m-%d %H:%M UTC', time.gmtime(data['until']))
print(f'Approved, once, until {until}: this command, run in {cwd}:\n'
f' {approval.normalise(a.command)}\n'
f'Give the agent this marker; the command passes actions-disable-guard with it at its end:\n'
f' {approval.MARK}{code}\n'
f'Any other command, or a second run, is refused. End it early with `sudo {PROG} approve --revoke`.')
return 0


if __name__ == '__main__':
sys.exit(main(sys.argv[1:]))
119 changes: 119 additions & 0 deletions fork-kit/agent-guards/bin/agent-slots
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
#!/usr/bin/python3 -IB
"""Claude Code hook for orchestrator sessions: "agent slots free + ready queue not empty = don't stop yet".
Part of fork-kit/agent-guards (README.md there: install, settings entries, the machine file's "agent-guards" section).

UserPromptSubmit: adds one line of context: live agent processes, free slots, the first items of the ready queue.
Stop: if slots are free and the ready queue has items, blocks the stop once (not again while stop_hook_active).
Acts only for the session ids in sessionsFile; every other session exits at once (one file read). Read only: it
writes nothing, so two at once need no lock.

General (any project, any Claude config dir). Project facts come from the machine file (agentSlots):
sessionsFile one session id per line, # comments (default "": the hook does nothing)
queue a markdown file; its ready list is the "- " lines under readyHeading (default "## Ready")
maxAlive agent processes at most (default 10); processName the process counted (default "claude")
note extra text for the context line, e.g. a build-agent limit (default "")
Never fails a call because of its own error. A broken machine file section: the defaults (so it does nothing) and
one line on stderr. Tests: fork-kit/agent-guards/tests/agent-slots.test.py
"""
import json, os, subprocess, sys

NAME = 'agent-slots'


def _settings():
"""(agentSlots settings, problem or None); a copy without the kit's lib keeps the defaults and says so."""
try:
sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), 'lib'))
from agent_guards import config
c, problem = config.load('agentSlots')
for k in ('sessionsFile', 'queue'):
c[k] = config.expand(c[k])
return c, problem
except BaseException as e: # noqa: BLE001
return ({'sessionsFile': '', 'queue': '', 'readyHeading': '## Ready', 'maxAlive': 10, 'processName': 'claude',
'note': ''}, f'cannot load the kit\'s config code ({type(e).__name__}: {e})')


def lines(path):
try:
with open(path) as f:
return f.read().split('\n')
except OSError:
return []


def ready_items(c):
out, on = [], False
for line in lines(c['queue']):
if line.startswith('## '):
on = line.strip().lower() == c['readyHeading'].strip().lower()
elif on and line.startswith('- '):
out.append(line[2:].strip())
return out


def alive(c):
r = subprocess.run(['pgrep', '-c', '-x', c['processName']], capture_output=True, text=True)
return int((r.stdout or '0').strip() or 0)


def decide(data, c):
sessions = {l.strip() for l in lines(c['sessionsFile']) if l.strip() and not l.startswith('#')}
if not c['sessionsFile'] or data.get('session_id') not in sessions:
return None
event = data.get('hook_event_name', '')
n = alive(c)
mx = int(c['maxAlive'])
free = max(0, mx - n)
ready = ready_items(c)
head = '; '.join(ready[:3])
msg = (f'Agent slots: {n}/{mx} {c["processName"]} processes alive, {free} free'
+ (f' ({c["note"]})' if c['note'] else '') + '. '
f'Ready queue ({c["queue"]}): {len(ready)} item(s){": " + head if head else ""}.')
if event == 'UserPromptSubmit':
return {'hookSpecificOutput': {'hookEventName': 'UserPromptSubmit', 'additionalContext': msg}}
if event == 'Stop' and not data.get('stop_hook_active') and free and ready:
return {'decision': 'block', 'reason': msg + ' Fill the free slots from the ready queue before ending the '
'turn (read the issue first). If an item cannot start now, move it out of the ready list with the reason.'}
return None


def _notice(problem, event, out):
"""`out` with a config problem added where the agent and the owner see it (and one line on stderr)."""
if not problem:
return out
try:
from agent_guards import config
config.warn(NAME, problem)
return config.notice(NAME, problem, event, out)
except BaseException: # noqa: BLE001 - no lib: say it plainly
text = f'{NAME}: {problem}; built-in defaults used. Tell the owner.'
try:
sys.stderr.write(text + '\n')
except Exception: # noqa: BLE001
pass
return dict(out or {}, systemMessage=text)


def main():
if sys.argv[1:]:
sys.stderr.write('usage: agent-slots (hook: UserPromptSubmit or Stop JSON on stdin)\n')
return 1
event, problem = None, None
try:
c, problem = _settings()
event = json.load(sys.stdin)
out = decide(event, c)
except Exception: # never break a call because of this hook
out = None
try:
out = _notice(problem, event, out)
except Exception: # noqa: BLE001
pass
if out:
print(json.dumps(out))
return 0


if __name__ == '__main__':
sys.exit(main())
Loading
Loading