feat(org): kvb-org-radio and kvb-org-queue replace chair and peer messages

kvb-org-radio is the default channel to other agents: broadcast and direct reach the receiver on its next prompt, security and pan-pan mid-turn through a PostToolBatch hook, and only mayday or direct --wake wake a session, through the receiver's own asyncRewake Stop hook (a SendMessage fallback is printed for sessions without a listener). It keeps the news.jsonl store and lock, so news.py stays a forwarding shim. A mayday holds radio silence for two hours: watch.py blocks new heavy commands and the operator gets a desktop notice. hotfix.py announces merged hotfixes as security items.

kvb-org-queue grants heavy jobs by rule instead of chair messages: queue.py hold waits under a flock with disk reservation, hotfix-first and register rank order, slot limits, stage and silence checks, then runs the command and releases. Every job is recorded; history.py learns disk need per command and slot limits per kind (p90, five runs), watch.py mirrors the history to ~/.local/state. enable-plugins.js registers the new hooks behind a file check so a missing script never blocks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Kevin Veen-BirkenbachandClaude Opus 5.5 committed 2026-11-04 17:07:24 +01:00
1 parent ed5bb074c5
commit 27559dabc4
18 files changed
+2607 -225

No files matched your search

+9 -10
View File
@@ -27,7 +27,7 @@ outranks them and appoints or recalls at will.
4. Elected: complete the task the claim entered in the `kvb-org-rasci`
register (objective, description, priority, roles); the listed claim
announces it.
5. Not elected: post your findings to the holder via the news and stop.
5. Not elected: radio your findings to the holder (`direct`) and stop.
A hook (`council.py gate`) blocks worktree edits before a claim. Between
machines the earliest announcement by message time wins; each host's claim
@@ -41,9 +41,9 @@ ends or goes stale, or after a restart.
on `grant`.
- `make test`, `make test-lint`, quality gates, deploys, iteration loops,
swarm, image builds, cloud, shared-data cleanup, anything with Docker or
over a few minutes: ask the chair (what, where, how long, disk), wait for
the grant, post the release to the news. In a worktree they run through
`gate.py run` or `gate.py hold` (`kvb-check-gate`).
over a few minutes: run through `queue.py hold` (`kvb-org-queue`), which
grants by rule and releases on exit; the chair only handles exceptions. In
a worktree wrap `gate.py run` or `gate.py hold` (`kvb-check-gate`).
- No running job is cut short for capacity; only the operator orders one
down. Exception: void by a missing merged hotfix (`kvb-git-hotfix`).
`RESOURCE` hook lines address the chair; others adjust plans.
@@ -55,13 +55,12 @@ ends or goes stale, or after a restart.
Read `peers.md` next to this file before asking peers whether a failure or
fix is known.
- Never poll: `council.py list`, the register and the news answer first.
- Never poll: `council.py list`, the register and the radio answer first.
- Hotfixes: `${CLAUDE_SKILL_DIR}/../kvb-git-hotfix/scripts/hotfix.py add` and
`update`, never a message or news post.
- Status that asks nothing (a failure, a freed slot, a result):
`${CLAUDE_SKILL_DIR}/scripts/news.py post "<text>"` (`--to <name>` for one
peer).
- `SendMessage` only when the recipient must act or answer: one batched
`update`; merged ones go out as radio `security` by themselves.
- Agents are reached through `kvb-org-radio`; status that asks nothing as
`broadcast` or `direct`.
- `direct --wake` only when the recipient must act or answer: one batched
message per peer per event, terse, no greeting, at most five lines unless
evidence needs more, nothing already acknowledged. A message asking
nothing gets no reply; end that turn in one line.
+13 -11
View File
@@ -5,17 +5,19 @@
- 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.
- The chair keeps one queue: a hotfix gate (a branch from the default branch
that fixes it) takes the next free gate or test slot before every other
line, the rest follows the WSJF rank of the `kvb-org-wsjf` skill (it asks its
subordinates for the Fibonacci estimates); a running gate is never cut short
for a hotfix's slot, only when the hotfix voids it (`kvb-git-hotfix`). It
answers every request with its queue position through
`news.py post --to <name>` and sends the grant itself as a message (the
requester acts on it), enforces the limits the operator set, and checks
every grant with
`watch.py admit --need-gb <N>` (or `--kind <slot>`; test kinds also need CPU
and RAM below the configured limits).
- The queue of the `kvb-org-queue` skill grants heavy jobs by rule, with no
request, position post or grant message: a hotfix gate (a branch from the
default branch that fixes it, checked against its `hotfix/` register row)
before every other line, the rest by the register rank, that is the
operator's pins, then the WSJF of the `kvb-org-wsjf` skill; slot limits
from `slot_limits` in the config, disk reserved per granted job, CPU and RAM
through `watch.py`, nothing new at the stop stage or during a mayday. A
running gate is never cut short for a hotfix's slot, only when the hotfix
voids it (`kvb-git-hotfix`).
- The chair handles what the rule cannot: it collects the Fibonacci
estimates (an unestimated task ranks last), places a job the rule leaves
waiting too long, and carries out the operator's overrides. `queue.py list`
shows the queue.
- 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
+12 -142
View File
@@ -1,161 +1,31 @@
#!/usr/bin/env python3
"""Share status news between agents without waking them: each session sees it with its next turn.
Environment:
AGENTS_COUNCIL_ROOT: council directory; the news is <root>/news.jsonl and
each session's read mark <root>/news-seen/<session id>.
/tmp/agents-council unless set.
CLAUDE_CODE_SESSION_ID: the calling session.
"""Forward the old news.py calls to radio.py of the kvb-org-radio skill, which owns the same store.
Args:
post "<text>" [--to <name> ...] [--session <id>]: add one item, for every
session or only the named ones.
hook: UserPromptSubmit hook; reads the hook JSON on stdin, prints the items
of the last 24 hours this session has not seen (at most 10, own posts
left out) and marks them seen. Never fails the prompt.
show [--all] [--session <id>]: print the unseen items, or every kept one,
without marking them.
post "<text>" [--to <name> ...] [--session <id>], hook, show [--all]
[--session <id>]: passed to radio.py unchanged; see its docstring.
Exit codes:
0 done, 2 usage error.
radio.py's; when radio.py is missing, 0 for hook and 2 for the rest.
"""
from __future__ import annotations
import argparse
import datetime
import fcntl
import importlib.util
import json
import os
import sys
import tempfile
import time
from pathlib import Path
from types import ModuleType
ROOT = Path(os.environ.get("AGENTS_COUNCIL_ROOT", "/tmp/agents-council"))
NEWS = ROOT / "news.jsonl"
SEEN = ROOT / "news-seen"
LOCK = ROOT / "news.lock"
COUNCIL = Path(__file__).resolve().with_name("council.py")
WINDOW = 86400
SHOWN = 10
KEPT = 500
def fail(message: str) -> None:
print(f"news: {message}", file=sys.stderr)
sys.exit(2)
def council() -> ModuleType:
spec = importlib.util.spec_from_file_location("council", COUNCIL)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def items() -> list[dict]:
try:
lines = NEWS.read_text(encoding="utf-8").splitlines()
except OSError:
return []
rows = []
for line in lines:
try:
row = json.loads(line)
except ValueError:
continue
if isinstance(row, dict) and isinstance(row.get("ts"), int | float):
rows.append(row)
return rows
def unseen(sid: str, name: str | None) -> list[dict]:
try:
mark = float((SEEN / sid).read_text(encoding="utf-8"))
except (OSError, ValueError):
mark = 0.0
floor = max(mark, time.time() - WINDOW)
return [
row
for row in items()
if row["ts"] > floor
and row.get("from") != name
and (not row.get("to") or name in row["to"])
]
def line(row: dict) -> str:
stamp = datetime.datetime.fromtimestamp(row["ts"]).strftime("%H:%M")
target = f" to {', '.join(row['to'])}" if row.get("to") else ""
return f"NEWS {stamp} {row.get('from', '?')}{target}: {row.get('text', '')}"
def cmd_post(args: argparse.Namespace, cn: ModuleType) -> int:
sid, _ = cn.caller(args.session)
text = " ".join(args.text.split())
if not text:
fail("post needs a text")
entry = {"ts": time.time(), "from": cn.live_sessions().get(sid) or sid, "to": args.to or [], "text": text}
ROOT.mkdir(parents=True, exist_ok=True)
with LOCK.open("w") as lock:
fcntl.flock(lock, fcntl.LOCK_EX)
rows = [*items()[-(KEPT - 1):], entry]
with tempfile.NamedTemporaryFile("w", dir=ROOT, delete=False, encoding="utf-8") as handle:
handle.write("".join(json.dumps(row) + "\n" for row in rows))
os.replace(handle.name, NEWS)
print(f"posted to {', '.join(entry['to']) or 'all'}")
return 0
def cmd_hook(_: argparse.Namespace, cn: ModuleType) -> int:
try:
payload = json.load(sys.stdin)
sid = payload.get("session_id") or os.environ.get("CLAUDE_CODE_SESSION_ID")
if not sid:
return 0
rows = unseen(sid, cn.live_sessions().get(sid))
if not rows:
return 0
for row in rows[-SHOWN:]:
print(line(row))
if len(rows) > SHOWN:
print(f"NEWS {len(rows) - SHOWN} older items: news.py show")
SEEN.mkdir(parents=True, exist_ok=True)
(SEEN / sid).write_text(str(rows[-1]["ts"]), encoding="utf-8")
except (OSError, ValueError, AttributeError):
return 0
return 0
def cmd_show(args: argparse.Namespace, cn: ModuleType) -> int:
if args.all:
rows = items()
else:
sid, _ = cn.caller(args.session)
rows = unseen(sid, cn.live_sessions().get(sid))
for row in rows:
print(line(row))
return 0
RADIO = Path(__file__).resolve().parents[2] / "kvb-org-radio" / "scripts" / "radio.py"
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
sub = parser.add_subparsers(dest="command", required=True)
p = sub.add_parser("post")
p.add_argument("text")
p.add_argument("--to", action="append")
p.add_argument("--session")
p.set_defaults(func=cmd_post)
sub.add_parser("hook").set_defaults(func=cmd_hook)
p = sub.add_parser("show")
p.add_argument("--all", action="store_true")
p.add_argument("--session")
p.set_defaults(func=cmd_show)
args = parser.parse_args()
return args.func(args, council())
if not RADIO.is_file():
# A UserPromptSubmit hook exiting 2 blocks every prompt of the session.
if sys.argv[1:2] == ["hook"]:
return 0
print(f"news: {RADIO} is missing; install the kvb-org-radio skill", file=sys.stderr)
return 2
os.execv(sys.executable, [sys.executable, str(RADIO), *sys.argv[1:]])
if __name__ == "__main__":
+59 -5
View File
@@ -3,9 +3,13 @@
Usage:
watch.py watch hook (UserPromptSubmit, PostToolUse): measure at most once
per interval machine-wide, act on the stage, show alerts
per interval machine-wide, act on the stage, show alerts,
and append the kvb-org-queue history rows of
<root>/queue-history.jsonl whose id it lacks to
~/.local/state/agents-council/queue-history.jsonl
watch.py block hook (PreToolUse on Bash): exit 2 for a heavy job while the
stage is stop or critical
stage is stop or critical, or while a kvb-org-radio mayday
holds radio silence (<root>/radio-silence.json, until > now)
watch.py admit (--need-gb N | --kind KIND)
exit 0 when the grant leaves at least the stop threshold
free, 3 otherwise
@@ -35,6 +39,7 @@ kind listed in kinds also needs CPU busy and RAM used below the limits.
from __future__ import annotations
import argparse
import fcntl
import json
import os
import re
@@ -53,7 +58,10 @@ CONFIG = Path(
)
STAGES = ("ok", "warn", "stop", "critical")
STATE = ROOT / "watch.json"
SILENCE = ROOT / "radio-silence.json"
ALERTS = ROOT / "alerts.jsonl"
HISTORY = ROOT / "queue-history.jsonl"
KEPT_HISTORY = Path.home() / ".local" / "state" / "agents-council" / "queue-history.jsonl"
ALERT_TTL = 3600
LOCK_TTL = 1800
GB = 1e9
@@ -180,8 +188,43 @@ def act(cfg: dict, stage: str, previous: str, free: float) -> None:
notify(cfg, f"Agents council: {head}. Heavy jobs blocked; a running stack needs the operator's OK to go.")
def history_rows(text: str) -> list[tuple[str, str]]:
rows = []
for line in text.splitlines():
try:
row = json.loads(line)
except ValueError:
continue
if isinstance(row, dict) and "id" in row:
rows.append((row["id"], line))
return rows
def keep_history() -> None:
# The agents' sandbox cannot write ~/.local/state and /tmp is wiped on reboot, so this hook keeps the rows.
# The kept file takes the source's mtime: an unchanged source is skipped without parsing.
try:
source = HISTORY.stat().st_mtime_ns
if KEPT_HISTORY.exists() and KEPT_HISTORY.stat().st_mtime_ns == source:
return
KEPT_HISTORY.parent.mkdir(parents=True, exist_ok=True)
with KEPT_HISTORY.open("a+", encoding="utf-8") as kept:
fcntl.flock(kept, fcntl.LOCK_EX)
kept.seek(0)
known = {row_id for row_id, _ in history_rows(kept.read())}
for row_id, line in history_rows(HISTORY.read_text(encoding="utf-8")):
if row_id not in known:
known.add(row_id)
kept.write(line + "\n")
kept.flush()
os.utime(KEPT_HISTORY, ns=(source, source))
except (OSError, ValueError, TypeError):
pass
def cmd_watch(cfg: dict) -> int:
payload = json.load(sys.stdin)
keep_history()
now = time.time()
state = read_json(STATE)
if now - state.get("checked", 0) >= cfg["interval_seconds"]:
@@ -216,18 +259,29 @@ def executable_text(command: str) -> str:
return QUOTED.sub("''", HEREDOC.sub("", command))
def silence() -> dict | None:
state = read_json(SILENCE)
return state if state.get("until", 0) > time.time() else None
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"):
mayday = silence()
if stage not in ("stop", "critical") and not mayday:
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"]):
reason = (
f"a mayday by {mayday.get('by', '?')} holds radio silence: {mayday.get('text', '')}; "
"it ends with radio.py clear"
if mayday
else f"resource stage is {stage}; new heavy jobs are blocked until the disk recovers"
)
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.",
f"kvb-org-organize: {reason}. Teardown commands still run. Ask the resource chair.",
file=sys.stderr,
)
return 2