refactor(skills)!: rename every skill to kvb-<category>-<name>

All 38 first-party skills move to kvb-<category>-<name> with the categories think, create, code, ci, git, check, org and skills; kvb-cleanup and kvb-help are the only uncategorized names. tests/test_naming.py pins the schema, the Agent Skills name rules and the README organigram. enable-plugins.js repoints hook commands of renamed skills in settings.local.json so a stale script path cannot block tools.

BREAKING CHANGE: the old skill names and slash commands (/commit-next, /dream, /autotune, ...) are gone; use their kvb- successors listed in the README organigram.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Kevin Veen-BirkenbachandClaude Opus 5.5 committed 2026-11-01 00:47:23 +01:00
1 parent 64403cefca
commit 624baccfc4
59 files changed
+504 -312

No files matched your search

+201
View File
@@ -0,0 +1,201 @@
---
name: kvb-org-organize
description: >
Keep parallel agents from duplicating work: the first to claim it owns it;
line representatives and a resource chair coordinate. Run AUTOMATICALLY
before work another agent might also do (failure, cluster, feature, gate,
deploy, cleanup), and on /kvb-org-organize.
---
Two agents doing the same work waste the second run and then collide in the
merge. The remedy is an election nobody has to hold: whoever starts first owns
the work. The structure is anarcho-syndicalist: councils (soviets) of
delegates with a bound mandate, organised as a matrix, recallable by the
operator at any time.
## Offices
- **President of a piece of work**: the first agent that starts it. It does
the whole piece. Every later agent hands its findings to the president and
moves on to other work; it never builds a second version.
- **Representative of an organisational line**: the first agent that works in
the line. Lines come in as many dimensions as are useful: functional domain
(security, GUI, identity, i18n), repository, branch line, host, cloud
account. An agent belongs to one line per dimension.
- **Organiser of a work cluster**: the first agent that starts a cluster
cutting across lines (a failure cluster from `kvb-ci-triage`, a cost cluster from
`kvb-code-tune`, a feature touching several domains). It works the strand end to end
and informs the representative of every line the strand touches before it
changes that line's files.
- **Chair**: the earliest-elected president still running. It chairs the
council of all representatives and organisers and allocates the resources of
the whole system everyone runs on. There is exactly one allocator at any
time.
Every office is a mandate, not a rank: it coordinates and allocates, it never
takes over or directs the content of another agent's work. The operator
outranks every office and appoints or recalls at will; an operator
appointment outranks the election.
## Election
The first to claim wins, and the claim is atomic, so two agents can never both
be first. `${CLAUDE_SKILL_DIR}/scripts/council.py` keeps the claims in
`/tmp/agents-council`; other runtimes call the same script from their skills
directory with `--session <id>`.
1. **Name the office**: `work/<slug>`, `cluster/<slug>`,
`<dimension>/<line>` for a representative, or `chair`. The slug names the
work concretely: the issue number, the failing line, the cost's log line.
2. **Look first**: `council.py list`. A claim for the same work under another
slug counts as first.
3. **Claim**: `council.py claim <office> --work "<what, evidence, branch or
worktree>"`. Exit 0: elected, or already yours. Exit 3: a live agent holds
it, and its claim is printed. Exit 4: the holder's session is dead (see
Succession).
4. **Elected**: continue with the Peer protocol; its message is the
announcement.
5. **Not elected**: send the holder your findings and stop on that work.
A Claude Code session cannot edit a file in a git worktree before it holds a
claim: a PreToolUse hook (`council.py gate`) blocks the edit.
Peers on other machines cannot see this host's claims. Between machines the
earliest announcement by message time wins, and each host's claim directory
records the result.
## Chair and resource allocation
- The first agent elected on the system while `chair` is vacant also claims
`chair`, in the same way.
- An operator-appointed allocator holds the chair: its claim says
`appointed: operator`, and no election replaces it while its session runs and
the operator has not ended the appointment.
- Before starting anything that consumes shared capacity (gates, deploys,
iteration loops, swarm or cloud resources, cleanup of shared data), an agent
sends the chair what, where, for how long and its expected disk need, waits
for the grant, and reports the release. The chair keeps one queue, answers
every request with its position, enforces the limits the operator set,
checks every grant with `watch.py admit --need-gb <N>` (or `--kind <slot>`;
test kinds also need CPU and RAM below the configured limits).
- A running job (deploy, gate, test, swarm run, build) is never cut short to
free capacity. The chair neither asks nor orders its owner to stop, take
down or kill it, not for an operator-prioritised slot and not for a
projected disk stop. It grants nothing new, frees idle items through the
`kvb-cleanup` flow, asks the operator for an exception, or waits. An owner's
own disk guard only alerts the chair and takes nothing down; only the
operator can order a running job down. The one exception is a hang: an
agent may end its own job, a stuck step inside it, or a process its own
ended session left behind, once at least 60 minutes passed without log
progress and a probe shows standstill (no fresh child process, no network
traffic, CPU time not moving). It secures the live state first and then
reports the timestamp, the step, the probe and the command. A peer's hung
job goes to its owner, and to the operator when the owner does not answer.
- Handover is explicit: the outgoing chair sends every peer the new holder,
the queue and the running grants, and keeps allocating until the incoming
chair confirms. Two allocators never run at once.
## Resource watch
The chair keeps the system from running out instead of reacting once it has.
`${CLAUDE_SKILL_DIR}/scripts/watch.py` does the measuring as hooks in every
session, so no agent probes the disk by hand; it reads its thresholds, job
patterns, cleanup commands and cache directories from
`~/.config/agents-council/config.json` (keys in the script's docstring) and
stays silent below the thresholds.
- **Warn**: the chair and every session get the biggest consumers; the chair
plans a cleanup and grants no large slot.
- **Stop**: new heavy jobs are blocked in every session (teardown commands
never), and the hook runs the configured low-risk cleanup by itself; it
skips every worktree where a gate or deploy process still runs.
- **Critical**: additionally a desktop alarm to the operator. Running jobs
and their stacks still keep running; only the operator can make an
exception.
- A measured fall that would reach the critical threshold within the
projection window raises the stage by one at once.
- Caches together stay under their budget; the least recently used go first.
`watch.py status` shows the last measurement. A `RESOURCE` line in a hook's
context is addressed to the chair; any other session only adjusts its own
plans to it.
## Succession
- A piece of work or a cluster ends with its result, a proposal, or an
abandoned attempt, reported to the peers who heard the claim. The holder
then runs `council.py release <office>`, and the next agent that starts the
work is elected afresh.
- A representative or the chair that ends hands its office to the next-oldest
live representative (by claim time) and announces it.
- A claim is stale when its holder's session is gone: in Claude Code its
session id is no longer in `~/.claude/sessions`; other runtimes run
`council.py beat` at least hourly and go stale after 60 minutes without
one. `claim` then exits 4. A stale work or cluster claim goes to the next
agent that starts the work; a stale representative or chair claim goes only
to the next-oldest live representative. The successor runs
`council.py takeover <office> --work "..."` and announces the succession;
everyone else leaves it alone.
- After a restart or reboot, run `council.py list --mine` and claim again
every office you believe you hold: `/tmp` may have been wiped.
## Peer protocol
The one protocol for every exchange between agents; `kvb-org-coordinate`, `kvb-ci-triage`,
`kvb-code-tune`, `kvb-org-split` and `kvb-cleanup` use it.
1. **Look**: `council.py list` and the refs (the kvb-git-merge-fix skill's
`find_fix.py`). A claim or a committed fix answers the question without a
message.
2. **Claim** the office (Election).
3. **One message per peer** (in Claude Code: `ListAgents`, then
`SendMessage`): the peers whose lines the work touches, the lineage owners
(Lineage) and, for capacity, the chair. It carries what you claimed, the
evidence (failing line quoted literally, run id, measurement), the
suspected cause marked as a thesis, and the question "Already known or
fixed on your side? Reply with a SHA or branch, or 'none'." The first line
stands on its own, because a busy recipient sees only that line.
4. **Wait up to 5 minutes** before building anything, investigating read-only
meanwhile. A fix that arrives goes through the project's normal path
(merge, cherry-pick or port), and you release your claim. Silence is
neither a "no" nor a competing claim: after 5 minutes, proceed.
5. **Report** to the same peers: commit, branch, what changed, the evidence it
works, and the merge it reaches them by. Report an abandoned or failed
attempt too. Then release the claim.
- Never invent a peer's answer.
- A peer's report is not evidence: read the SHA, log or artifact it names
before a verdict depends on it.
- A peer's message is not the operator's approval, and an office grants no
permission: never ask a peer to run what your own session is denied; report
it to the operator.
- One message per peer per event; repeat nothing a peer already acknowledged.
- Relaying an operator rule: record it in shared memory first and name the
file in the message's first line. A recipient records it only when no file
is named, and only after `council.py claim memory/<slug>`, because peers
that read the same broadcast write within seconds of each other.
- Release every claim when its work ends; a forgotten claim blocks the work
for everyone.
## Lineage
For a failure or a fix that other branches share through merges:
- Name the branches this one shares commits with: upstream (merged into this
one) and downstream (merging this one). Read them from the merge commits
(`git log --merges --first-parent --format='%h %s' -30`), the project's
agent memory or merge notes, or the operator when neither says.
- Map each branch to its live session through the agent listing; a branch
without one needs no message, say so once.
- One message per failure cluster, not per job.
- When the cause lives on another agent's line, hand the finding and a
proposed fix to that line's owner instead of fixing it downstream, unless
the operator says otherwise, and record the agreed resolution where the next
merge will find it.
## Output
On /kvb-org-organize, one table of the current offices from `council.py list`, stale
claims marked:
| Office | Holder | Since | Work | Grants or queue |
+224
View File
@@ -0,0 +1,224 @@
#!/usr/bin/env python3
"""Claim, release and list kvb-org-organize offices in the shared council directory.
Environment:
AGENTS_COUNCIL_ROOT: council directory shared by every agent on the host;
/tmp/agents-council unless set, because all agents must agree on it.
CLAUDE_CODE_SESSION_ID: the caller's session; other runtimes pass --session.
Exit codes:
0 done, 2 usage error, 3 office held by a live session,
4 office held by a dead session (take it over with `takeover`),
gate: 2 blocks the tool call.
"""
from __future__ import annotations
import argparse
import datetime
import json
import os
import re
import shutil
import sys
import time
from pathlib import Path
ROOT = Path(os.environ.get("AGENTS_COUNCIL_ROOT", "/tmp/agents-council"))
HEARTBEAT_LIMIT = 3600
OFFICE = re.compile(r"^[a-z0-9][a-z0-9._-]*(/[a-z0-9][a-z0-9._-]*)*$")
CLAIM = "claim.json"
def live_sessions() -> dict[str, str | None]:
found: dict[str, str | None] = {}
for path in (Path.home() / ".claude" / "sessions").glob("*.json"):
try:
data = json.loads(path.read_text(encoding="utf-8"))
except (OSError, ValueError):
continue
if data.get("sessionId"):
found[data["sessionId"]] = data.get("name")
return found
def caller(session: str | None) -> tuple[str, str]:
if session:
return session, "other"
env = os.environ.get("CLAUDE_CODE_SESSION_ID")
if env:
return env, "claude-code"
print("council: no session id; pass --session", file=sys.stderr)
sys.exit(2)
def office_dir(office: str) -> Path:
if not OFFICE.match(office):
print(f"council: invalid office {office!r}", file=sys.stderr)
sys.exit(2)
return ROOT / office
def read_claim(path: Path) -> dict | None:
try:
return json.loads((path / CLAIM).read_text(encoding="utf-8"))
except (FileNotFoundError, ValueError):
return None
def is_stale(claim: dict | None, live: dict[str, str | None]) -> bool:
if claim is None:
return False
if claim["runtime"] == "claude-code":
return claim["session"] not in live
return time.time() - claim["beat"] > HEARTBEAT_LIMIT
def claims() -> list[tuple[str, dict]]:
found = []
for path in sorted(ROOT.glob(f"**/{CLAIM}")):
claim = read_claim(path.parent)
if claim is not None:
found.append((path.parent.relative_to(ROOT).as_posix(), claim))
return found
def write_claim(path: Path, office: str, sid: str, runtime: str, work: str) -> None:
claim = {
"office": office,
"session": sid,
"runtime": runtime,
"name": live_sessions().get(sid),
"since": datetime.datetime.now(datetime.UTC).isoformat(timespec="seconds"),
"beat": time.time(),
"work": work,
}
(path / CLAIM).write_text(json.dumps(claim), encoding="utf-8")
def cmd_claim(args: argparse.Namespace) -> int:
sid, runtime = caller(args.session)
path = office_dir(args.office)
path.parent.mkdir(parents=True, exist_ok=True)
try:
path.mkdir()
except FileExistsError:
claim = read_claim(path)
if claim is not None and claim["session"] == sid:
write_claim(path, args.office, sid, runtime, args.work)
print(f"held {args.office}")
return 0
print(json.dumps(claim) if claim else f"{args.office}: claim in progress")
return 4 if is_stale(claim, live_sessions()) else 3
write_claim(path, args.office, sid, runtime, args.work)
print(f"elected {args.office}")
return 0
def cmd_takeover(args: argparse.Namespace) -> int:
path = office_dir(args.office)
claim = read_claim(path)
if path.exists() and not is_stale(claim, live_sessions()):
print(json.dumps(claim) if claim else f"{args.office}: claim in progress")
return 3
# Two successors racing between this check and the rename can both win;
# kvb-org-organize names exactly one successor per office to keep that window closed.
if path.exists():
tomb = path.with_name(f"{path.name}.stale-{os.getpid()}-{time.time_ns()}")
try:
path.rename(tomb)
except FileNotFoundError:
pass
else:
shutil.rmtree(tomb)
return cmd_claim(args)
def cmd_release(args: argparse.Namespace) -> int:
sid, _ = caller(args.session)
path = office_dir(args.office)
claim = read_claim(path)
if claim is None:
print(f"{args.office}: not claimed")
return 0
if claim["session"] != sid and not is_stale(claim, live_sessions()):
print(json.dumps(claim))
return 3
shutil.rmtree(path)
print(f"released {args.office}")
return 0
def cmd_beat(args: argparse.Namespace) -> int:
sid, _ = caller(args.session)
for office, claim in claims():
if claim["session"] == sid:
claim["beat"] = time.time()
(ROOT / office / CLAIM).write_text(json.dumps(claim), encoding="utf-8")
return 0
def cmd_list(args: argparse.Namespace) -> int:
live = live_sessions()
sid = None
if args.mine:
sid, _ = caller(args.session)
for office, claim in claims():
if sid is not None and claim["session"] != sid:
continue
state = "stale" if is_stale(claim, live) else "live"
holder = claim["name"] or claim["session"]
print(f"{office}\t{holder}\t{claim['since']}\t{state}\t{claim['work']}")
return 0
def in_git_worktree(target: Path) -> bool:
return any((path / ".git").exists() for path in (target, *target.parents))
def cmd_gate(_: argparse.Namespace) -> int:
payload = json.load(sys.stdin)
tool_input = payload.get("tool_input") or {}
target = tool_input.get("file_path") or tool_input.get("notebook_path")
if not target or not in_git_worktree(Path(target).resolve()):
return 0
if any(claim["session"] == payload.get("session_id") for _, claim in claims()):
return 0
script = Path(__file__).resolve()
print(
"kvb-org-organize: this session holds no claim, so it may not edit files in a git "
f"worktree. Claim the work first: python3 {script} claim work/<slug> "
"--work '<one line>'. Exit 3 or 4 means another agent holds it; read the "
"kvb-org-organize skill.",
file=sys.stderr,
)
return 2
def main() -> int:
parser = argparse.ArgumentParser(prog="council")
sub = parser.add_subparsers(dest="cmd", required=True)
for name, func in (("claim", cmd_claim), ("takeover", cmd_takeover)):
cmd = sub.add_parser(name)
cmd.add_argument("office")
cmd.add_argument("--work", required=True)
cmd.add_argument("--session")
cmd.set_defaults(func=func)
release = sub.add_parser("release")
release.add_argument("office")
release.add_argument("--session")
release.set_defaults(func=cmd_release)
beat = sub.add_parser("beat")
beat.add_argument("--session")
beat.set_defaults(func=cmd_beat)
listing = sub.add_parser("list")
listing.add_argument("--mine", action="store_true")
listing.add_argument("--session")
listing.set_defaults(func=cmd_list)
sub.add_parser("gate").set_defaults(func=cmd_gate)
args = parser.parse_args()
return args.func(args)
if __name__ == "__main__":
sys.exit(main())
+422
View File
@@ -0,0 +1,422 @@
#!/usr/bin/env python3
"""Watch disk, Docker and caches for the kvb-org-organize resource chair.
Usage:
watch.py watch hook (UserPromptSubmit, PostToolUse): measure at most once
per interval machine-wide, act on the stage, show alerts
watch.py block hook (PreToolUse on Bash): exit 2 for a heavy job while the
stage is stop or critical
watch.py admit (--need-gb N | --kind KIND)
exit 0 when the grant leaves at least the stop threshold
free, 3 otherwise
watch.py cleanup (--caches | --full)
trim caches to their budget; --full also runs the
configured low-risk cleanup commands
watch.py status print the last measurement
Environment:
AGENTS_COUNCIL_ROOT: shared state directory; /tmp/agents-council unless set,
because every agent on the host must agree on it.
AGENTS_COUNCIL_CONFIG: config file; ~/.config/agents-council/config.json
unless set. Without a config file every command exits 0 and does nothing.
Config keys, all required: disk, thresholds_gb {warn, stop, critical},
projection_minutes, interval_seconds, cache_interval_seconds, heavy_commands,
never_block (regexes), cleanup (shell commands), worktree_cleanup (shell
commands with {worktree}), worktrees_command (shell command printing the
running stacks' worktree paths, one per line), worktree_marker (path relative
to a worktree that must exist), busy_processes (process names; a worktree
where one of them runs is skipped), cache_dirs, cache_budget_percent,
slot_need_gb {kind: GB}, notify (argv the alert text is appended to),
load_limits {cpu_percent, mem_percent, sample_seconds, kinds}: admit for a
kind listed in kinds also needs CPU busy and RAM used below the limits.
"""
from __future__ import annotations
import argparse
import json
import os
import re
import shlex
import subprocess
import sys
import time
from pathlib import Path
ROOT = Path(os.environ.get("AGENTS_COUNCIL_ROOT", "/tmp/agents-council"))
CONFIG = Path(
os.environ.get(
"AGENTS_COUNCIL_CONFIG",
str(Path.home() / ".config" / "agents-council" / "config.json"),
)
)
STAGES = ("ok", "warn", "stop", "critical")
STATE = ROOT / "watch.json"
ALERTS = ROOT / "alerts.jsonl"
ALERT_TTL = 3600
LOCK_TTL = 1800
GB = 1e9
def load_config() -> dict | None:
if not CONFIG.is_file():
return None
return json.loads(CONFIG.read_text(encoding="utf-8"))
def disk(cfg: dict) -> tuple[float, float]:
st = os.statvfs(cfg["disk"])
return st.f_bavail * st.f_frsize / GB, st.f_blocks * st.f_frsize / GB
def read_json(path: Path) -> dict:
try:
return json.loads(path.read_text(encoding="utf-8"))
except (OSError, ValueError):
return {}
def write_json(path: Path, data: dict) -> None:
# A full disk refuses the write; the stage must still act, so it is dropped.
try:
path.parent.mkdir(parents=True, exist_ok=True)
tmp = path.with_name(f"{path.name}.{os.getpid()}")
tmp.write_text(json.dumps(data), encoding="utf-8")
tmp.replace(path)
except OSError:
pass
def stage_for(free: float, samples: list[list[float]], cfg: dict, now: float) -> str:
limits = cfg["thresholds_gb"]
level = 0
for index, name in ((1, "warn"), (2, "stop"), (3, "critical")):
if free < limits[name]:
level = index
window = cfg["projection_minutes"] * 60
recent = [s for s in samples if now - s[0] <= window and now > s[0]]
if recent and level < 3:
then, before = recent[0]
rate = (before - free) / (now - then)
if rate > 0 and (free - limits["critical"]) / rate < window:
level += 1
return STAGES[level]
def alert(stage: str, text: str) -> None:
try:
ROOT.mkdir(parents=True, exist_ok=True)
with ALERTS.open("a", encoding="utf-8") as handle:
handle.write(json.dumps({"id": time.time_ns(), "stage": stage, "text": text}) + "\n")
except OSError:
pass
def unseen_alerts(session: str) -> list[str]:
seen_path = ROOT / "seen" / session
try:
seen = int(seen_path.read_text(encoding="utf-8"))
except (OSError, ValueError):
seen = 0
try:
lines = ALERTS.read_text(encoding="utf-8").splitlines()
except OSError:
return []
cutoff = time.time_ns() - ALERT_TTL * 10**9
fresh = [json.loads(line) for line in lines if line]
fresh = [a for a in fresh if a["id"] > max(seen, cutoff)]
if fresh:
write_text(seen_path, str(fresh[-1]["id"]))
return [a["text"] for a in fresh]
def write_text(path: Path, text: str) -> None:
try:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(text, encoding="utf-8")
except OSError:
pass
def consumers() -> str:
try:
out = subprocess.run(
["docker", "system", "df", "--format", "{{.Type}}: {{.Size}} ({{.Reclaimable}} reclaimable)"],
capture_output=True, text=True, timeout=30, check=False,
).stdout.strip()
except (OSError, subprocess.TimeoutExpired):
return "docker system df unavailable"
return "; ".join(out.splitlines()) or "docker system df printed nothing"
def notify(cfg: dict, text: str) -> None:
try:
subprocess.run([*cfg["notify"], text], capture_output=True, timeout=10, check=False)
except (OSError, subprocess.TimeoutExpired):
alert("critical", f"RESOURCE: desktop notification failed: {cfg['notify'][0]}")
def spawn_cleanup(mode: str) -> None:
subprocess.Popen(
[sys.executable, str(Path(__file__).resolve()), "cleanup", mode],
stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
start_new_session=True,
)
def act(cfg: dict, stage: str, previous: str, free: float) -> None:
limits = cfg["thresholds_gb"]
head = f"/ has {free:.1f} GB free (warn < {limits['warn']}, stop < {limits['stop']}, critical < {limits['critical']} GB)"
if STAGES.index(stage) < STAGES.index(previous):
alert(stage, f"RESOURCE {stage.upper()}: recovered, {head}.")
return
if stage == "warn":
alert(stage, f"RESOURCE WARN: {head}. Biggest consumers: {consumers()}. Chair: plan a cleanup; peers: request no large slot.")
elif stage in ("stop", "critical"):
alert(stage, f"RESOURCE {stage.upper()}: {head}. New heavy jobs are blocked; low-risk cleanup is running. {consumers()}")
spawn_cleanup("--full")
if stage == "critical":
notify(cfg, f"Agents council: {head}. Heavy jobs blocked; a running stack needs the operator's OK to go.")
def cmd_watch(cfg: dict) -> int:
payload = json.load(sys.stdin)
now = time.time()
state = read_json(STATE)
if now - state.get("checked", 0) >= cfg["interval_seconds"]:
free, _ = disk(cfg)
samples = [s for s in state.get("samples", []) if now - s[0] <= cfg["projection_minutes"] * 60]
stage = stage_for(free, samples, cfg, now)
previous = state.get("stage", "ok")
samples.append([now, free])
state.update(checked=now, free=free, stage=stage, samples=samples)
due = now - state.get("caches_checked", 0) >= cfg["cache_interval_seconds"]
if due:
state["caches_checked"] = now
write_json(STATE, state)
if stage != previous:
act(cfg, stage, previous, free)
elif due:
spawn_cleanup("--caches")
texts = unseen_alerts(payload["session_id"])
if texts:
print(json.dumps({"hookSpecificOutput": {
"hookEventName": payload["hook_event_name"],
"additionalContext": "\n".join(texts),
}}))
return 0
HEREDOC = re.compile(r"<<-?\s*(['\"]?)(\w+)\1[^\n]*\n.*?\n\s*\2(?=\s|\)|$)", re.DOTALL)
QUOTED = re.compile(r"'[^']*'|\"(?:\\.|[^\"\\])*\"")
def executable_text(command: str) -> str:
return QUOTED.sub("''", HEREDOC.sub("", command))
def cmd_block(cfg: dict) -> int:
payload = json.load(sys.stdin)
command = executable_text((payload.get("tool_input") or {}).get("command", ""))
stage = read_json(STATE).get("stage", "ok")
if stage not in ("stop", "critical"):
return 0
if any(re.search(p, command) for p in cfg["never_block"]):
return 0
if any(re.search(p, command) for p in cfg["heavy_commands"]):
print(
f"kvb-org-organize: resource stage is {stage}; new heavy jobs are blocked until "
"the disk recovers. Teardown commands still run. Ask the resource chair.",
file=sys.stderr,
)
return 2
return 0
def cpu_times() -> tuple[int, int]:
fields = [int(v) for v in Path("/proc/stat").read_text(encoding="utf-8").split("\n", 1)[0].split()[1:]]
return sum(fields), fields[3] + fields[4]
def cpu_busy_percent(before: tuple[int, int], after: tuple[int, int]) -> float:
total = after[0] - before[0]
idle = after[1] - before[1]
return 100.0 * (total - idle) / total
def mem_used_percent(meminfo: str) -> float:
values = {}
for line in meminfo.splitlines():
key, _, rest = line.partition(":")
if rest:
values[key] = int(rest.split()[0])
return 100.0 * (1 - values["MemAvailable"] / values["MemTotal"])
def load(cfg: dict) -> tuple[float, float]:
before = cpu_times()
time.sleep(cfg["load_limits"]["sample_seconds"])
cpu = cpu_busy_percent(before, cpu_times())
return cpu, mem_used_percent(Path("/proc/meminfo").read_text(encoding="utf-8"))
def cmd_admit(cfg: dict, args: argparse.Namespace) -> int:
need = args.need_gb if args.need_gb is not None else cfg["slot_need_gb"][args.kind]
free, _ = disk(cfg)
left = free - need
floor = cfg["thresholds_gb"]["stop"]
passed = [left >= floor]
report = [f"free {free:.1f} GB, need {need} GB, leaves {left:.1f} GB (floor {floor} GB)"]
limits = cfg["load_limits"]
if args.kind in limits["kinds"]:
cpu, mem = load(cfg)
passed += [cpu < limits["cpu_percent"], mem < limits["mem_percent"]]
report.append(
f"cpu {cpu:.0f} % (limit {limits['cpu_percent']}), ram {mem:.0f} % (limit {limits['mem_percent']})"
)
verdict = "grant" if all(passed) else "deny"
print(f"{verdict}: {'; '.join(report)}")
return 0 if verdict == "grant" else 3
def cache_files(dirs: list[str]) -> list[tuple[float, int, str]]:
files = []
for root in dirs:
for base, _, names in os.walk(os.path.expanduser(root)):
for name in names:
path = os.path.join(base, name)
try:
st = os.lstat(path)
except OSError:
continue
files.append((st.st_atime, st.st_size, path))
return files
def trim_caches(cfg: dict) -> float:
_, total = disk(cfg)
budget = total * GB * cfg["cache_budget_percent"] / 100
files = sorted(cache_files(cfg["cache_dirs"]))
used = sum(size for _, size, _ in files)
freed = 0
for _, size, path in files:
if used - freed <= budget:
break
try:
os.remove(path)
freed += size
except OSError:
continue
return freed / GB
def running_worktrees(cfg: dict) -> list[str]:
try:
out = subprocess.run(
cfg["worktrees_command"], shell=True, capture_output=True, text=True, timeout=60, check=False
).stdout
except subprocess.TimeoutExpired:
return []
trees = sorted({line.strip() for line in out.splitlines() if line.strip()})
return [t for t in trees if os.path.exists(os.path.join(t, cfg["worktree_marker"]))]
def busy(tree: str, names: list[str]) -> bool:
root = os.path.realpath(tree)
for pid in filter(str.isdigit, os.listdir("/proc")):
try:
if Path(f"/proc/{pid}/comm").read_text(encoding="utf-8").strip() not in names:
continue
cwd = os.readlink(f"/proc/{pid}/cwd")
except OSError:
continue
if cwd == root or cwd.startswith(root + os.sep):
return True
return False
def run_cleanup(cfg: dict) -> list[str]:
commands = list(cfg["cleanup"])
for tree in running_worktrees(cfg):
if busy(tree, cfg["busy_processes"]):
continue
commands += [t.format(worktree=shlex.quote(tree)) for t in cfg["worktree_cleanup"]]
results = []
for command in commands:
try:
code = subprocess.run(command, shell=True, capture_output=True, timeout=900, check=False).returncode
except subprocess.TimeoutExpired:
code = "timeout"
results.append(f"{'ok' if code == 0 else f'failed ({code})'}: {command}")
return results
def cmd_cleanup(cfg: dict, args: argparse.Namespace) -> int:
lock = ROOT / "cleanup.lock"
ROOT.mkdir(parents=True, exist_ok=True)
try:
if time.time() - lock.stat().st_mtime > LOCK_TTL:
lock.rmdir()
except FileNotFoundError:
pass
try:
lock.mkdir()
except FileExistsError:
return 0
try:
before, _ = disk(cfg)
results = run_cleanup(cfg) if args.full else []
cache_gb = trim_caches(cfg)
after, _ = disk(cfg)
failed = [r for r in results if not r.startswith("ok")]
if args.full or cache_gb:
alert(
"cleanup",
f"RESOURCE CLEANUP: freed {after - before:.1f} GB ({cache_gb:.1f} GB caches), "
f"/ now {after:.1f} GB free; {len(results) - len(failed)} commands ok"
+ (f", failed: {' | '.join(failed)}" if failed else "."),
)
finally:
lock.rmdir()
return 0
def cmd_status(cfg: dict) -> int:
state = read_json(STATE)
free, total = disk(cfg)
print(f"stage={state.get('stage', 'unmeasured')} free={free:.1f}GB total={total:.1f}GB samples={len(state.get('samples', []))}")
return 0
def main() -> int:
parser = argparse.ArgumentParser(prog="watch")
sub = parser.add_subparsers(dest="cmd", required=True)
sub.add_parser("watch")
sub.add_parser("block")
admit = sub.add_parser("admit")
need = admit.add_mutually_exclusive_group(required=True)
need.add_argument("--need-gb", type=float)
need.add_argument("--kind")
cleanup = sub.add_parser("cleanup")
mode = cleanup.add_mutually_exclusive_group(required=True)
mode.add_argument("--caches", action="store_true")
mode.add_argument("--full", action="store_true")
sub.add_parser("status")
args = parser.parse_args()
cfg = load_config()
if cfg is None:
return 0
if args.cmd == "watch":
return cmd_watch(cfg)
if args.cmd == "block":
return cmd_block(cfg)
if args.cmd == "admit":
return cmd_admit(cfg, args)
if args.cmd == "cleanup":
return cmd_cleanup(cfg, args)
return cmd_status(cfg)
if __name__ == "__main__":
sys.exit(main())