feat(orchestrator): hierarchy view from council offices with a separate agent order

The Agents views gain a Hierarchie view: an org chart of the chair and
the line offices read from the council claims. The operator appoints,
hands over and recalls an office there; the page signs each change with
the passkey and a host unit (client/offices.py, offices path unit)
verifies the signature, removes a live holder itself and runs a plain
council.py claim for the successor. council.py loses the --operator
flag, so no agent can override a live holder.

The agent order is now separate from task priority: rasci.py agents
order stores it in agent-order.json beside the register through the
nofollow helpers and never writes a --prio pin. It only breaks ties of
equal task rank, also among the queue grants. The Hierarchie view edits
it as a drag list.

Host units run the installed skill scripts, so orchestrator.sh keeps the
offices unit off while the installed council.py, nofollow.py or rasci.py
differ from the tree. Job files, council files and hub records are read
with O_NOFOLLOW and O_NONBLOCK and size caps; nofollow.rewrite replaces
a claim without creating directories, so a beat never revives a released
office.

🎯 Fix: 92 %
💥 Break: 4 %
💸 Cost: 100 %
⏱️ Time: 79 %
🛡️ Security: 100 %
🏆 Score: 100
🚦 Gate: ✅ 90/5, cost and time <= 100, security 100 %

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Kevin Veen-BirkenbachandClaude Opus 5.5 committed 2026-11-07 17:46:39 +00:00
1 parent 8e180be256
commit 4540494c30
53 files changed
+1821 -211

No files matched your search

+61 -14
View File
@@ -17,12 +17,15 @@ Exit codes:
from __future__ import annotations
import argparse
import contextlib
import datetime
import errno
import importlib.util
import json
import os
import re
import shutil
import stat
import subprocess
import sys
import time
@@ -43,6 +46,7 @@ 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"
CLAIM_MODE = 0o644
WORK_WIDTH = 40
RASCI = Path(__file__).resolve().parents[2] / "kvb-org-rasci" / "scripts" / "rasci.py"
@@ -114,11 +118,50 @@ def write_claim(path: Path, office: str, sid: str, runtime: str, work: str) -> d
"beat": time.time(),
"work": work,
}
(path / CLAIM).write_text(json.dumps(claim), encoding="utf-8")
nofollow.replace(ROOT, path / CLAIM, json.dumps(claim), CLAIM_MODE)
return claim
def make_office(path: Path) -> bool:
*dirs, name = nofollow.parts_below(ROOT, path)
ROOT.mkdir(parents=True, exist_ok=True)
fd = nofollow.directory(ROOT, tuple(dirs), True)
try:
os.mkdir(name, nofollow.DIRECTORY_MODE, dir_fd=fd)
except FileExistsError:
return False
finally:
os.close(fd)
return True
def remove_office(path: Path) -> None:
*dirs, name = nofollow.parts_below(ROOT, path)
try:
fd = nofollow.directory(ROOT, tuple(dirs), False)
except FileNotFoundError:
return
try:
try:
found = os.lstat(name, dir_fd=fd)
except FileNotFoundError:
return
if not stat.S_ISDIR(found.st_mode):
raise OSError(errno.ENOTDIR, "the office is no directory", str(path))
tomb = f"{name}.stale-{os.getpid()}-{time.time_ns()}"
try:
os.rename(name, tomb, src_dir_fd=fd, dst_dir_fd=fd)
except FileNotFoundError:
return
shutil.rmtree(tomb, dir_fd=fd)
finally:
os.close(fd)
def here() -> dict[str, str | None]:
# The Agent Orchestrator's office runner claims from / for the successor: / is no task's workdir.
if os.getcwd() == os.sep:
return {}
try:
head = subprocess.run(
["git", "rev-parse", "--abbrev-ref", "HEAD"], capture_output=True, text=True, check=False
@@ -144,10 +187,12 @@ def register(office: str, holder: str, status: str, **extra: str | None) -> None
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:
created = make_office(path)
except OSError as error:
print(f"council: cannot open {args.office}: {error.strerror}", file=sys.stderr)
return 2
if not created:
claim = read_claim(path)
if claim is not None and claim["session"] == sid:
claim = write_claim(path, args.office, sid, runtime, args.work)
@@ -179,14 +224,11 @@ def cmd_takeover(args: argparse.Namespace) -> int:
args.previous = claim["name"] or claim["session"]
# 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)
try:
remove_office(path)
except OSError as error:
print(f"council: cannot take over {args.office}: {error.strerror}", file=sys.stderr)
return 2
return cmd_claim(args)
@@ -200,7 +242,11 @@ def cmd_release(args: argparse.Namespace) -> int:
if claim["session"] != sid and not is_stale(claim, live_sessions()):
print(json.dumps(claim))
return 3
shutil.rmtree(path)
try:
remove_office(path)
except OSError as error:
print(f"council: cannot release {args.office}: {error.strerror}", file=sys.stderr)
return 2
register(args.office, claim["name"] or claim["session"], "done")
print(f"released {args.office}")
return 0
@@ -211,7 +257,8 @@ def cmd_beat(args: argparse.Namespace) -> int:
for office, claim in claims():
if claim["session"] == sid:
claim["beat"] = time.time()
(ROOT / office / CLAIM).write_text(json.dumps(claim), encoding="utf-8")
with contextlib.suppress(FileNotFoundError):
nofollow.rewrite(ROOT, ROOT / office / CLAIM, json.dumps(claim), CLAIM_MODE)
return 0
+18 -1
View File
@@ -142,8 +142,25 @@ def replace(root: Path, path: Path, text: str, mode: int) -> None:
text: the new content, UTF-8 encoded.
mode: permission bits of the new file.
"""
swap(root, path, text, mode, True)
def rewrite(root: Path, path: Path, text: str, mode: int) -> None:
"""Replace a file below root like replace, inside directories that still exist.
Args:
root: the trusted directory.
path: the file, below root; a missing directory on the way raises
FileNotFoundError and nothing is made.
text: the new content, UTF-8 encoded.
mode: permission bits of the new file.
"""
swap(root, path, text, mode, False)
def swap(root: Path, path: Path, text: str, mode: int, create: bool) -> None:
*dirs, name = parts_below(root, path)
fd = directory(root, tuple(dirs), True)
fd = directory(root, tuple(dirs), create)
try:
temp = f".{name}.{os.urandom(8).hex()}"
flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW | os.O_CLOEXEC
+2
View File
@@ -22,3 +22,5 @@
radio; 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.
- Only the operator, through the Orchestrator's passkey-signed Hierarchie
view, removes a live holder; agents have no override.
+15 -17
View File
@@ -1,25 +1,25 @@
---
name: kvb-org-priority
description: >
Let the operator reorder the agents' priority from a selection; pins their
tasks in that order. Trigger on "prioritaet", "reihenfolge der agents".
Let the operator reorder the agents; it breaks ties of grants and equal task
priority. Trigger on "prioritaet", "reihenfolge der agents".
---
The operator's order of the agents outranks every WSJF score. It is written
as `--prio` pins into the `kvb-org-rasci` register, so the grants of the
`kvb-org-queue` skill follow it. The script is
`${CLAUDE_SKILL_DIR}/../kvb-org-rasci/scripts/rasci.py`.
The agent order is separate from task priority: it lies in
`agent-order.json` beside the `kvb-org-rasci` register, writes no `--prio`
pin and only breaks ties of equal task rank, also among `kvb-org-queue`
grants. The script is `${CLAUDE_SKILL_DIR}/../kvb-org-rasci/scripts/rasci.py`.
```bash
rasci.py agents
rasci.py order "<agent>,<agent>,..."
rasci.py agents order "<agent>,<agent>,..."
```
## Step 1: current order
`rasci.py agents` prints one line per agent with open tasks, in the
register's rank: number, agent, task count, tasks. Show it as a table with
each agent's status and OKR from `rasci.py show --wide`.
`rasci.py agents` prints one line per agent with open tasks or an office, in
stored order, then register rank: number, agent, task count, tasks. Show it as a table with each agent's status and OKR from
`rasci.py show --wide`.
## Step 2: selection
@@ -33,15 +33,13 @@ One `AskUserQuestion`, `multiSelect: false`, the order of each option in its
- The operator's own order arrives through `Other`, as agent names or the
numbers of step 1 (map them to names), comma-separated.
An agent left out of the chosen order loses its pins and ranks by WSJF after
the listed ones; say so in the question.
An agent left out of the chosen order follows the listed ones in register
rank; say so in the question.
## Step 3: apply
`rasci.py order "<A>,<B>,..."` pins the listed agents' tasks 1..n in that
order, keeping each agent's own task order. It writes other sessions' rows:
the operator decides priority, so this is the one exception to "write only
your own rows". Show `rasci.py agents` again, then post the new ranks for the
`rasci.py agents order "<A>,<B>,..."` stores the order and touches no task
row. Show `rasci.py agents` again, then post the new order for the
resource chair of the `kvb-org-organize` skill and every reordered agent as
one `${CLAUDE_SKILL_DIR}/../kvb-org-radio/scripts/radio.py post "<text>"`,
not as wakes.
@@ -50,4 +48,4 @@ not as wakes.
- Never reorder without the operator's pick; a suggestion is not a decision.
- A name the register does not know stops the step with the list of known
agents; never guess the closest one.
agents; never guess the closest one.
+16 -6
View File
@@ -36,7 +36,8 @@ Args:
queue.
--kind: a key of slot_need_gb in the config.
--task: an open task of the kvb-org-rasci register; its rank orders
the queue.
the queue, and the operator's agent order (`rasci.py agents
order`) of the holding session breaks ties.
--need-gb: disk the job takes, in GB; when omitted the need learned
for the command's signature, else slot_need_gb[kind].
--hotfix: the slug of the register row hotfix/<slug> the job proves;
@@ -259,17 +260,19 @@ def store() -> Iterator[dict]:
nofollow.replace(watch.ROOT, STORE, json.dumps(data, indent=1, sort_keys=True), 0o600)
def ordered(waiting: list[dict], ranks: dict[str, int], now: float) -> list[dict]:
def ordered(waiting: list[dict], ranks: dict[str, int], agents: dict[str, int], now: float) -> list[dict]:
def key(entry: dict) -> tuple:
hours = int((now - entry["enqueued"]) // HOUR)
rank = ranks[entry["task"]] if entry["task"] in ranks else len(ranks)
return (not entry["hotfix"], rank - hours, entry["seq"])
agent = agents[entry["name"]] if entry["name"] in agents else len(agents)
return (not entry["hotfix"], rank - hours, agent, entry["seq"])
return sorted(waiting, key=key)
def evaluate(entries: list[dict], free_gb: float, floor: float, stage: str, silenced: bool,
slot_limits: dict[str, int], ranks: dict[str, int], now: float) -> dict[str, str | None]:
slot_limits: dict[str, int], ranks: dict[str, int], agents: dict[str, int],
now: float) -> dict[str, str | None]:
"""Decide every waiting entry in grant order, without disk or processes.
Args:
@@ -281,6 +284,9 @@ def evaluate(entries: list[dict], free_gb: float, floor: float, stage: str, sile
slot_limits: {kind: max concurrent jobs}.
ranks: {task: index in the register's ranking}; a task missing there
ranks after all of them.
agents: {agent name: index in the operator's agent order}; it breaks
ties of equal rank only, an entry whose holder is missing there after
all of them.
now: epoch seconds; each whole hour waited moves an entry one rank up.
Returns:
@@ -293,7 +299,7 @@ def evaluate(entries: list[dict], free_gb: float, floor: float, stage: str, sile
counts = Counter(e["kind"] for e in active)
busy = {e["workdir"] for e in active}
verdicts: dict[str, str | None] = {}
for entry in ordered([e for e in entries if e["status"] == "waiting"], ranks, now):
for entry in ordered([e for e in entries if e["status"] == "waiting"], ranks, agents, now):
kind, need, workdir = entry["kind"], entry["need_gb"], entry["workdir"]
reason = None
if stage in ("stop", "critical"):
@@ -324,6 +330,10 @@ def register_ranks() -> dict[str, int]:
return {task: index for index, task in enumerate(rasci.ranked(rasci.merged(False)))}
def agent_ranks() -> dict[str, int]:
return {name: index for index, name in enumerate(sibling("rasci").agent_order())}
def stage(cfg: dict, free_gb: float, now: float) -> str:
state = watch.read_json(watch.STATE)
return state["stage"] if "stage" in state else watch.stage_for(free_gb, [], cfg, now)
@@ -338,7 +348,7 @@ def decide(cfg: dict, entries: list[dict], free_gb: float, now: float, kinds: di
slots = {kind: limit for kind, (limit, _) in limits(cfg, kinds, entries).items()}
return evaluate(
entries, free_gb, cfg["thresholds_gb"]["stop"], stage(cfg, free_gb, now), silenced(now),
slots, register_ranks(), now,
slots, register_ranks(), agent_ranks(), now,
)
+3 -4
View File
@@ -25,7 +25,7 @@ rasci.py estimate <task> "<party>" --value <fib> --complexity <fib>
rasci.py wsjf [--all]
rasci.py tools
rasci.py agents
rasci.py order "<agent>,<agent>,..."
rasci.py agents order "<agent>,<agent>,..."
```
## Objective and key results
@@ -60,10 +60,9 @@ published). `done` is refused while one is open; a task ended short of them is
tool the task ran (`--tool`): `tools` ranks them for `kvb-dream`.
- Priority is the rank of the `kvb-org-wsjf` skill: an operator's pin
(`--prio`) first, then WSJF from the estimates the chair collects; `show`
prints the rank as Prio and the score as WSJF.
prints the rank as Prio and the score as WSJF; the agent order of
`kvb-org-priority` only breaks ties.
- Write only your own rows; another session's task belongs to that session.
The one exception is `order`, the operator's pick through the
`kvb-org-priority` skill.
- Read `show` (Prio, WSJF, Task, Status, Worker, A; cells cut short) or
`get` instead of asking a peer what it works on. `show --wide` adds OKR,
Artifacts, Start, End and every RASCI letter.
+72 -24
View File
@@ -4,7 +4,10 @@
Environment:
AGENTS_COUNCIL_ROOT: council directory shared by every agent on the host;
the register is <root>/rasci.json, and `show` also lists every work/
and cluster/ claim of the council there. /tmp/agents-council unless set.
and cluster/ claim of the council there. The operator's agent order
(`agents order`) lies beside it in <root>/agent-order.json, apart from
every task row: it breaks ties of equal task priority only.
/tmp/agents-council unless set.
Exit codes:
0 done, 2 usage error.
@@ -28,6 +31,7 @@ from types import ModuleType
ROOT = Path(os.environ.get("AGENTS_COUNCIL_ROOT", "/tmp/agents-council"))
DB = ROOT / "rasci.json"
LOCK = ROOT / "rasci.lock"
AGENT_ORDER = ROOT / "agent-order.json"
FILE_MODE = 0o600
ORGANIZE = Path(__file__).resolve().parents[2] / "kvb-org-organize" / "scripts"
COUNCIL = ORGANIZE / "council.py"
@@ -164,10 +168,21 @@ def track(task: str, holder: str, status: str, *, description: str | None = None
roles[holder] = letters_of(roles.get(holder, ""), "R" if accountable else "RA")
def council_module() -> ModuleType | None:
return script("council", COUNCIL) if COUNCIL.is_file() else None
def office_holders() -> list[str]:
council = council_module()
if council is None:
return []
return [claim["name"] or claim["session"] for _, claim in council.claims()]
def claimed() -> dict[str, dict]:
if not COUNCIL.is_file():
council = council_module()
if council is None:
return {}
council = script("council", COUNCIL)
live = council.live_sessions()
rows = {}
for office, claim in council.claims():
@@ -219,12 +234,26 @@ def wsjf(row: dict) -> tuple[float, float, float] | None:
return value, complexity, round(value / complexity, 2)
def agent_order() -> list[str]:
try:
data = json.loads(nofollow.read_text(ROOT, AGENT_ORDER))
except (OSError, ValueError, RecursionError):
return []
names = data.get("agents") if isinstance(data, dict) else None
if not isinstance(names, list) or not all(isinstance(name, str) for name in names):
return []
return names
def ranked(rows: dict[str, dict]) -> list[str]:
order = {name: index for index, name in enumerate(agent_order())}
def key(task: str) -> tuple:
row = rows[task]
score = wsjf(row)
pinned = row.get("prio")
return (pinned is None, pinned or 0, score is None, -(score[2] if score else 0), task)
agent = order.get(row.get("worker"), len(order))
return (pinned is None, pinned or 0, score is None, -(score[2] if score else 0), agent, task)
return sorted(rows, key=key)
@@ -236,29 +265,45 @@ def by_agent(rows: dict[str, dict]) -> dict[str, list[str]]:
return agents
def cmd_agents(_: argparse.Namespace) -> int:
for rank, (agent, tasks) in enumerate(by_agent(merged(include_done=False)).items(), 1):
print(f"{rank}\t{agent}\t{len(tasks)}\t{', '.join(tasks)}")
def agents_ranked(rows: dict[str, dict]) -> dict[str, list[str]]:
tasks = by_agent(rows)
for holder in office_holders():
tasks.setdefault(holder, [])
listed = [name for name in agent_order() if name in tasks]
return {name: tasks[name] for name in [*listed, *(name for name in tasks if name not in listed)]}
def store_order(text: str) -> int:
names = [name.strip() for name in text.split(",") if name.strip()]
known = agents_ranked(merged(include_done=False))
unknown = [name for name in names if name not in known]
if not names or unknown or len(set(names)) != len(names):
fail(f"agents order needs distinct agents from `agents`; unknown: {', '.join(unknown) or '-'}")
try:
ROOT.mkdir(parents=True, exist_ok=True)
with nofollow.locked(ROOT, LOCK, FILE_MODE, None):
nofollow.replace(ROOT, AGENT_ORDER, json.dumps({"agents": names, "set": stamp()}, indent=1), FILE_MODE)
except OSError as error:
fail(f"agents order cannot write {AGENT_ORDER}: {error.strerror or error}")
print(f"agent order: {', '.join(names)}; the others follow by register rank; task --prio pins unchanged")
return 0
def cmd_agents(args: argparse.Namespace) -> int:
if args.action == "order":
return store_order(args.agents)
for rank, (agent, tasks) in enumerate(agents_ranked(merged(include_done=False)).items(), 1):
print(f"{rank}\t{agent}\t{len(tasks)}\t{', '.join(tasks) or '-'}")
return 0
def cmd_order(args: argparse.Namespace) -> int:
names = [name.strip() for name in args.agents.split(",") if name.strip()]
agents = by_agent(merged(include_done=False))
unknown = [name for name in names if name not in agents]
if not names or unknown or len(set(names)) != len(names):
fail(f"order needs distinct agents from `agents`; unknown: {', '.join(unknown) or '-'}")
with database() as tasks:
prio = 0
for name in names:
for task in agents[name]:
prio += 1
tasks.setdefault(task, {})["prio"] = prio
for name in agents.keys() - set(names):
for task in agents[name]:
tasks.get(task, {}).pop("prio", None)
print(f"pinned {prio} tasks of {len(names)} agents; the others rank by WSJF after them")
return 0
print(
"rasci: `order` is now `agents order`: it stores the agent order beside the register "
"and no longer writes --prio pins",
file=sys.stderr,
)
return store_order(args.agents)
def okr(row: dict) -> str:
@@ -549,7 +594,10 @@ def main() -> int:
p.add_argument("--task")
p.set_defaults(func=cmd_artifacts)
sub.add_parser("tools").set_defaults(func=cmd_tools)
sub.add_parser("agents").set_defaults(func=cmd_agents)
p = sub.add_parser("agents")
p.set_defaults(func=cmd_agents)
order = p.add_subparsers(dest="action").add_parser("order")
order.add_argument("agents")
p = sub.add_parser("order")
p.add_argument("agents")
p.set_defaults(func=cmd_order)