Merge feature/orchestrator/s52-night-per-agent into master

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

# Conflicts:
#	docs/requirements/001-agent-orchestrator.md
#	orchestrator/kvb_orchestrator/view.py
#	orchestrator/templates/page-board.js
#	tests/test_hub_state.py
This commit is contained in:
Kevin Veen-Birkenbach committed 2026-11-11 07:53:40 +00:00
commit c3ab6b7e18
18 files changed
+408 -64

No files matched your search

+2 -1
View File
@@ -6,7 +6,8 @@ description: >
---
Verify first: `${CLAUDE_SKILL_DIR}/../kvb-org-suspend/scripts/night.py status`
prints `you: drain`. On `you: active` or `mode: day` do nothing and say so.
prints `you: drain`, by day too when the operator drained this session alone.
On another `you:` line, or none, do nothing and say so.
The request asks for less, so it needs no operator approval.
Follow steps 2 to 4 of the `kvb-agent-suspend` skill (start nothing, end your
+2 -1
View File
@@ -8,7 +8,8 @@ description: >
Verify first with `${CLAUDE_SKILL_DIR}/../kvb-org-suspend/scripts/night.py
status`:
- **`mode: day`**: `kvb-org-resume` ended the night; resume.
- **No `you:` line, or `you: resumed`**: `kvb-org-resume` ended the night or
the operator lifted this session's part; resume.
- **`you: drain` or `you: suspend`**: only the operator, typing this command in
this session, resumes it alone; a peer's request does not. Run `night.py
resume --alone`: the others stay in the mode, and the night rules of `kvb-org-suspend`
+2 -1
View File
@@ -6,7 +6,8 @@ description: >
---
Verify first: `${CLAUDE_SKILL_DIR}/../kvb-org-suspend/scripts/night.py status`
prints `you: suspend`. On `you: active` or `mode: day` do nothing and say so.
prints `you: suspend`, by day too when the operator suspended this session
alone. On another `you:` line, or none, do nothing and say so.
The request asks for less, so it needs no operator approval, and it ends a
`kvb-org-robot` run at its next safe point; `kvb-agent-resume` resumes it.
+3 -1
View File
@@ -9,7 +9,9 @@ When tokens or rate limits run short, the organisation narrows to one working
agent: the session the operator types this in. Suspend is the hard step;
`kvb-org-drain` is the soft one. `${CLAUDE_SKILL_DIR}/scripts/night.py` keeps
the state for drain, suspend and resume; every agent verifies a request with
`night.py status`.
`night.py status`. `--target=<session id>` on drain, suspend or resume sets or
lifts only that session's part, by day too, as the Agent Orchestrator's agent
picks do; every other session keeps its own.
## Procedure
+77 -31
View File
@@ -9,16 +9,23 @@ Environment:
Args:
drain|suspend [--session <id>]: start the mode with the caller as the
active session; prints every other live session as "<id>\t<name>".
drain|suspend --target=<id> [--target=<id> ...] [--session <id>]: put
only these sessions into the part, by day too; the mode and every
other session keep theirs. Prints the targets as "<id>\t<name>".
status [--session <id>]: print the mode, the active session, since when,
and the caller's part (active, resumed, drain or suspend).
resume [--session <id>]: end the mode; prints every other live session
as "<id>\t<name>".
and the caller's part (active, resumed, drain or suspend); a session
without a part by day gets no "you:" line.
resume [--session <id>]: end the mode and every part; prints every other
live session as "<id>\t<name>".
resume --target=<id> [--target=<id> ...] [--session <id>]: lift these
sessions' parts; during a mode they work like the active session.
resume --alone [--session <id>]: resume the caller alone while the others
stay in the mode; it then works like the active session.
A missing, unreadable or invalid state means day: every agent works. A state
written before the rename (mode evening or sunset, resumed sessions under
awake) reads as drain or suspend.
A missing, unreadable or invalid state means day: every agent works. A
session's own part (night.json "parts") outranks the mode. A state written
before the rename (mode evening or sunset, resumed sessions under awake)
reads as drain or suspend.
Exit codes:
0 done, 2 usage error.
@@ -61,6 +68,22 @@ def migrated(state: object) -> object:
return state
def valid(state: object) -> bool:
if not isinstance(state, dict):
return False
parts = state.get("parts", {})
if not isinstance(parts, dict) or not all(isinstance(mode, str) and mode in PARTS for mode in parts.values()):
return False
if "mode" not in state:
return bool(parts)
return (
isinstance(state["mode"], str)
and state["mode"] in PARTS
and bool(state.get("active"))
and isinstance(state.get("resumed", []), list)
)
def load() -> dict | None:
try:
state = migrated(json.loads(STATE.read_text(encoding="utf-8")))
@@ -68,18 +91,32 @@ def load() -> dict | None:
return None
except (OSError, ValueError):
state = None
if (
not isinstance(state, dict)
or not isinstance(state.get("mode"), str)
or state["mode"] not in PARTS
or not state.get("active")
or not isinstance(state.get("resumed", []), list)
):
if not valid(state):
print(f"night: {STATE} is unreadable or invalid; treated as day", file=sys.stderr)
return None
return state
def part_of(state: dict, sid: str) -> str | None:
if sid in state.get("parts", {}):
return state["parts"][sid]
if "mode" not in state:
return None
if sid == state["active"]:
return "active"
if sid in state.get("resumed", []):
return "resumed"
return state["mode"]
def released(state: dict, sids: list[str]) -> dict:
state = {**state, "parts": {sid: mode for sid, mode in state.get("parts", {}).items() if sid not in sids}}
if "mode" in state:
resumed = state.get("resumed", [])
state["resumed"] = [*resumed, *(sid for sid in dict.fromkeys(sids) if sid != state["active"] and sid not in resumed)]
return state
def peers(live: dict[str, str | None], own: str) -> None:
for sid, name in sorted(live.items(), key=lambda item: (item[1] or "", item[0])):
if sid != own:
@@ -89,6 +126,11 @@ def peers(live: dict[str, str | None], own: str) -> None:
def cmd_set(args: argparse.Namespace, cn: ModuleType) -> int:
sid, _ = cn.caller(args.session)
live = cn.live_sessions()
if args.target:
state = load() or {}
save({**state, "parts": {**state.get("parts", {}), **dict.fromkeys(args.target, args.command)}})
peers({target: live.get(target) for target in args.target}, "")
return 0
save(
{
"mode": args.command,
@@ -103,6 +145,9 @@ def cmd_set(args: argparse.Namespace, cn: ModuleType) -> int:
def save(state: dict) -> None:
if "mode" not in state and not state.get("parts"):
STATE.unlink(missing_ok=True)
return
ROOT.mkdir(parents=True, exist_ok=True)
with tempfile.NamedTemporaryFile("w", dir=ROOT, delete=False, encoding="utf-8") as handle:
json.dump(state, handle)
@@ -114,28 +159,21 @@ def resume_alone(sid: str) -> int:
if state is None:
print("mode: day")
return 0
if sid != state["active"] and sid not in state.get("resumed", []):
state["resumed"] = [*state.get("resumed", []), sid]
save(state)
save(released(state, [sid]))
print(f"resumed: {sid}")
return 0
def cmd_status(args: argparse.Namespace, _: ModuleType) -> int:
state = load()
if state is None:
print("mode: day")
return 0
print(f"mode: {state['mode']}")
print(f"active: {state.get('name') or '-'} {state['active']}")
print(f"since: {state.get('since') or '-'}")
state = load() or {}
print(f"mode: {state.get('mode', 'day')}")
if "mode" in state:
print(f"active: {state.get('name') or '-'} {state['active']}")
print(f"since: {state.get('since') or '-'}")
sid = args.session or os.environ.get("CLAUDE_CODE_SESSION_ID")
if sid == state["active"]:
print("you: active")
elif sid in state.get("resumed", []):
print("you: resumed")
elif sid:
print(f"you: {PARTS[state['mode']]}")
part = part_of(state, sid) if sid else None
if part:
print(f"you: {PARTS.get(part, part)}")
return 0
@@ -143,6 +181,10 @@ def cmd_resume(args: argparse.Namespace, cn: ModuleType) -> int:
sid, _ = cn.caller(args.session)
if args.alone:
return resume_alone(sid)
if args.target:
save(released(load() or {}, args.target))
peers({target: cn.live_sessions().get(target) for target in args.target}, "")
return 0
STATE.unlink(missing_ok=True)
peers(cn.live_sessions(), sid)
return 0
@@ -152,11 +194,15 @@ def main() -> int:
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
sub = parser.add_subparsers(dest="command", required=True)
for mode in PARTS:
sub.add_parser(mode).set_defaults(func=cmd_set)
p = sub.add_parser(mode)
p.add_argument("--target", action="append")
p.set_defaults(func=cmd_set)
p = sub.add_parser("status")
p.set_defaults(func=cmd_status)
p = sub.add_parser("resume")
p.add_argument("--alone", action="store_true")
alone = p.add_mutually_exclusive_group()
alone.add_argument("--alone", action="store_true")
alone.add_argument("--target", action="append")
p.set_defaults(func=cmd_resume)
for p in sub.choices.values():
p.add_argument("--session")