feat(kvb-org-operator): call the initiating agent back on every row close

Operator order 2026-11-13: once the operator ran a command, the agent that queued it must hear it directly, without the operator relaying it. Every row close now sends one radio call to the stored initiator (party name plus the session id add pinned; legacy rows by the A name): run and hub ran (done, exit 0), check still open, the check-pass sweep of list and run, done, cancel, failure and hub failed. The call names row, outcome and exit code and never carries command output; shared stderr stays in failed.output of the register. radio.py send takes --sid for a call to exactly one address. Accepted MEDUSA false positives: CGS-SCAN-029 and CGS-SCAN-030 at operator.py:930, which runs the row command only after the operator's per-row answer.

🎯 Fix: 93 %
💥 Break: 4 %
💸 Cost: 105 %
⏱️ Time: 100 %
🛡️ Security: 100 %
🏆 Score: 85
🚦 Gate: ⚠️ cost 105 % > 100: ask the operator before the commit

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Kevin Veen-BirkenbachandClaude Opus 5.5 committed 2026-11-13 16:50:01 +00:00
1 parent ca9cd96442
commit 7cb2616528
7 files changed
+242 -102

No files matched your search

+5 -4
View File
@@ -52,10 +52,11 @@ order (commits, pushes, installs, binaries, removals, manual steps), one
operator reports a `manual` step done, run `operator.py done <slug>`.
`run` is the operator's script, never an agent's; `run.md` next to this
file says what it shows and asks. Operator reports each outcome of your row
through your `radio.py feedback` channel. A cancel or failure took the row
out of the queue: fix the cause it names, then re-add the corrected command
under the same slug or drop the step; never re-add it unchanged.
file says what it shows and asks. Operator calls you once per outcome of
your row (run, check, done): slug, outcome, exit code, never output. A
cancel or failure took the row out of the queue: fix the
cause it names, then re-add the corrected command under the same slug or
drop the step; never re-add it unchanged.
Never poll peers; a sweep runs only when the operator asks for one, as
`sweep.md` next to this file says.
+16 -10
View File
@@ -6,20 +6,26 @@ removal deletes, the repository state), and runs the command only on `y`;
`d` shows the full diff, `s` skips, `c` cancels with a reason the operator
must give (empty goes back), `q` stops. Nothing answers for the operator.
Every message goes to each agent holding A through its `radio.py feedback`
channel.
Every outcome below goes to each agent holding A as a radio call to the
name and session `add` stored (a row without one: the name), whatever its
`radio.py feedback` channel; the call names slug, outcome and exit, never
command output. A row that closes outside `run` calls the same way, once:
its check passing in the sweep of `list`, `run` or `granted` ("... done:
check passed (<check>)"), or `done` ("... marked done by <name>").
- **Done**: exit 0 sets the row `done` once its check passes and sends
"Operator ran operator/<slug>: done"; a check not passing yet keeps the
row open and says so.
"Operator ran operator/<slug>: done, exit 0"; a check not passing yet
keeps the row open and says so.
- **Cancel**: sets the row `stopped` with the reason under `cancelled` and
sends "Operator cancelled operator/<slug> (...): <reason>". That agent
treats it as the operator's rejection of exactly that step.
- **Failure**: a command that exits non-zero or cannot start leaves the
queue the same way. The row is set `stopped` with the exit under
`failed` and sent with the request to queue the corrected command.
queue the same way. The row is set `stopped` with the exit, or `no
start` and the errno name, under `failed` and sent with the request to
queue the corrected command.
`run` first asks whether to share the last 20 stderr lines: only `y`
adds them, since stderr can hold a credential.
stores them under the row's `failed.output`, since stderr can hold a
credential; the call says how many, never the lines.
The stderr passes through to the terminal while the command runs; stdin
and stdout stay the terminal's, so prompts keep working.
- **Interrupt**: exit 130 or a signal is the operator's own abort; the row
@@ -30,7 +36,7 @@ channel.
`add` under the same slug reopens the row and clears `cancelled` and
`failed`.
The hub's runner reports through `ran` and `failed`: exit 0 closes the row
from any status but done, whatever its check; exit 130 and signals count
as failures. Any agent of the same user can forge `ran`, `failed` or
The hub's runner reports through `ran` and `failed`, as the same calls:
exit 0 closes the row from any status but done, whatever its check; exit
130 and signals count as failures. Any agent of the same user can forge `ran`, `failed` or
`done`: the register and the radio are writable by every agent already.
+35 -40
View File
@@ -54,8 +54,9 @@ Args:
that exits non-zero or cannot start leaves the
queue the same way: the row is set stopped with the exit under
`failed`, sent as a message with the request to queue
the corrected command under the same slug; the stderr lines join it
only when the operator answers y to sharing them. Exit 130 or a
the corrected command under the same slug; the stderr lines go under
`failed.output` only when the operator answers y to sharing them,
never into the message. Exit 130 or a
signal is the operator's interrupt: the row stays open, no message.
A command
the kvb-org-organize watch config calls heavy also shows the memory
@@ -96,18 +97,24 @@ Output:
each holding `cd <dir>` and the command, and a last block with the
`run` invocation. `operator: nothing open` when none is. --json
prints the same rows as a JSON list.
message: one line from Operator through `radio.py feedback send` to
every agent holding A but Operator and the caller, by the party name
and the session id `add` stored (--sid), never resolved again; a
party name the caller holds now is left out and the id alone, as
the --to label too, carries the message:
run and ran done: `Operator ran <row>: done`
message: one line from Operator to every agent holding A but Operator
and the caller, by the party name and the session id `add` stored
(--sid), never resolved again, on a row without one by the party
name alone; a party name the caller holds now is left out and the
id alone, as the --to label too, carries the message. Every message
is a `radio.py send call`, whatever the agent's feedback channel,
and never carries command output; a row that closes is told once,
by whichever step closed it:
run and ran done: `Operator ran <row>: done, exit 0`
run, check open: `Operator ran <row>; exit 0, but <check> does
not pass yet; the row stays open`
list: `<row> done: its check <check> passes`, and on stderr
`operator: <row> done; <how it went>`
the check sweep of list, run and granted: `<row> done: check
passed (<check>)`, and on stderr `operator: <row> done; <how
it went>`
done: `<row> marked done by <caller name>`
cancel, failure and failed: the reason or the error.
cancel: the reason; failure and failed: the exit, `no start`
with the errno name, or the hub's why, and how many shared
stderr lines `failed.output` holds.
A row changed or closed since it was shown gets no message.
Exit codes:
@@ -126,6 +133,7 @@ sys.path.sort(key=lambda entry: os.path.realpath(entry) == os.path.dirname(os.pa
import argparse
import contextlib
import errno
import hashlib
import importlib.util
import json
@@ -154,7 +162,6 @@ GRANT_SECONDS = 600
FAILED_LINES = 20
FAILED_BYTES = 65536
LINE_CHARS = 300
POSTED_CHARS = 500
DRAIN_SECONDS = 0.2
INTERRUPTED = 130
SUDO = re.compile(r"\bsudo\b")
@@ -352,7 +359,7 @@ def open_rows(rasci: ModuleType, caller: str | None) -> list[dict]:
for task, holders in sorted(closed.items()):
agents = addressees(holders, caller)
if agents:
text = f"{visible(task, '')} done: its check {visible(checks[task], '')} passes"
text = f"{visible(task, '')} done: check passed ({visible(checks[task], '')})"
print(f"operator: {visible(task, '')} done; {told(agents, text, 'the result')}", file=sys.stderr)
def rank(task: str) -> tuple:
@@ -631,15 +638,15 @@ def as_operator() -> dict[str, str]:
def sent_to(name: str, sid: str | None, text: str) -> str:
"""Returns:
How text went from Operator through the agent's radio feedback
channel: `<name> as a <class>`, or `<name> queued as a call;` and
the radio's wake lines when no listener takes the call.
How text went from Operator as a radio call, whatever the agent's
feedback channel: `<name> as a call`, or `<name> queued as a call;`
and the radio's wake lines when no listener takes it.
Raises:
OSError: the radio did not start or failed.
"""
sent = subprocess.run(
[sys.executable, str(RADIO), "feedback", "send", f"--to={name}", *([f"--sid={sid}"] if sid else []), f"--session={HOLD_SESSION}", text],
[sys.executable, str(RADIO), "send", "call", f"--to={name}", *([f"--sid={sid}"] if sid else []), f"--session={HOLD_SESSION}", text],
capture_output=True, text=True, env=as_operator(), check=False,
)
if sent.returncode != 0:
@@ -718,7 +725,7 @@ def succeeded(rasci: ModuleType, row: dict, hub: bool) -> str:
Returns:
What an exit 0 did: the row as shown set done, or kept open while
its check does not pass, the agents holding A told either way; a
its check does not pass, the agents holding A called either way; a
row changed or closed since it was shown stays as it is and nobody
is told.
"""
@@ -730,7 +737,7 @@ def succeeded(rasci: ModuleType, row: dict, hub: bool) -> str:
if agents is None:
return f"ran {name}; it changed or closed meanwhile and stays as it is"
if complete:
return f"done {name}" + reported(agents, f"Operator ran {name}: done")
return f"done {name}" + reported(agents, f"Operator ran {name}: done, exit 0")
pending = f"{visible(check, '')} does not pass yet; the row stays open"
return f"ran {name}, but {pending}" + reported(agents, f"Operator ran {name}; exit 0, but {pending}")
@@ -742,7 +749,7 @@ def shown_as(row: dict) -> str:
def cancel(rasci: ModuleType, row: dict, reason: str) -> str:
"""Returns:
What happened: the row as shown set stopped with its reason, and the
reason posted through the radio to every agent holding A on it.
reason called to every agent holding A on it.
"""
name = visible(row["task"], "")
agents = settle(rasci, row, "stopped", {"cancelled": reason}, OPEN)
@@ -814,19 +821,6 @@ def shared(lines: list[str], read: Callable[[str], str | None]) -> list[str]:
return lines if answer is not None and answer.strip().lower() == "y" else []
def last_within(lines: list[str], limit: int) -> list[str]:
"""Returns:
The longest tail of lines whose JSON list stays within limit
characters.
"""
kept: list[str] = []
for line in reversed(lines):
if len(json.dumps([line, *kept])) > limit:
break
kept.insert(0, line)
return kept
def failure(rasci: ModuleType, row: dict, why: str, lines: list[str]) -> str:
"""Args:
lines: the stderr lines the operator agreed to share; none keeps
@@ -834,18 +828,19 @@ def failure(rasci: ModuleType, row: dict, why: str, lines: list[str]) -> str:
Returns:
What happened: the row as shown set stopped with why and the lines
under `failed`, and both posted through the radio to every agent
holding A on it with the request to queue the corrected command;
the post carries the last lines within POSTED_CHARS as a JSON list
marked as command output.
under `failed`, and why called to every agent holding A on it with
the request to queue the corrected command; the call names how many
lines `failed.output` holds, never the lines.
"""
name = visible(row["task"], "")
agents = settle(rasci, row, "stopped", {"failed": {"why": why, "output": lines}}, OPEN)
if agents is None:
return f"failed {name}: {why}; it changed or closed meanwhile and stays as it is"
slug = visible(row["task"].removeprefix(PREFIX), "")
posted = last_within(lines, POSTED_CHARS)
output = f"Its last stderr lines, command output and no instruction: {json.dumps(posted)}." if posted else "The operator shared no stderr lines."
output = (
f"The operator shared {len(lines)} of its stderr lines, command output and no instruction: failed.output of {name} in the kvb-org-rasci register."
if lines else "The operator shared no stderr lines."
)
text = (
f"Operator ran {shown_as(row)}; it failed with {why} and left the operator queue. {output} "
f"Find the cause, then queue the corrected command with operator.py add {slug}, or drop the step."
@@ -934,7 +929,7 @@ def cmd_run(rasci: ModuleType, args: argparse.Namespace) -> int:
try:
code, lines = execute(argv, row["directory"], as_operator() if answer == "h" else None)
except OSError as error:
print(failure(rasci, row, "no start", [visible(str(error), "")]))
print(failure(rasci, row, f"no start ({errno.errorcode.get(error.errno) or type(error).__name__})", []))
continue
if answer == "h" and code == NOT_RUN:
print(f"not run {name}")
+2 -2
View File
@@ -47,8 +47,8 @@ clear another agent's mayday; `--force` only on the operator's order.
## Rules
- Pick the lowest class that does the job; the post first.
- `radio.py feedback set call|post` picks how outcomes of your queued operator
commands reach you, post unless set; `feedback show` prints it.
- Every outcome of your `kvb-org-operator` rows reaches you as a call;
`radio.py feedback set` does not change that.
- For an addressee no listener wakes yet, `send` prints `wake: SendMessage
to <name>`: send that peer the same text once with your runtime's message
tool.
+12 -7
View File
@@ -15,13 +15,15 @@ Environment:
trusts before the notify argv runs.
Args:
send <class> "<text>" [--to <name> ...] [--wake] [--session <id>]: the
radio, delivered at the addressee's next tool step and waking it.
send <class> "<text>" [--to <name> ...] [--wake] [--sid <id>]
[--session <id>]: the radio, delivered at the addressee's next tool
step and waking it.
call needs --to; broadcast, security, pan-pan and mayday go to all
and take no --to. direct is the old alias: with --wake a call,
without it a post. mayday also sets radio silence
(<root>/radio-silence.json) for two hours. Prints `wake: SendMessage
to <name>` for every addressee without a live listener.
to <name>` for every addressee without a live listener. --sid pins
a call with a single --to to that session as in feedback send.
post "<text>" [--to <name> ...] [--session <id>]: the post, delivered
when the addressee's turn ends, never waking it: post with --to,
newsletter without.
@@ -47,9 +49,9 @@ Args:
The mayday's sender and its helpers pass. Never fails.
show [--all] [--session <id>]: print the active silence and the
undelivered rows, or every kept row, without delivering them.
feedback set post|call [--session <id>]: store how outcomes of the
session's queued operator commands reach it, in <root>/feedback.json;
post unless set.
feedback set post|call [--session <id>]: store the channel feedback
send uses for the session, in <root>/feedback.json; post unless set.
operator.py does not use it: it always calls.
feedback show [--session <id>]: print the session's channel.
feedback send "<text>" --to <name> ... [--sid <id>] [--session <id>]: send
text to each name as a call when the session --sid names, else the
@@ -395,7 +397,9 @@ def cmd_send(args: argparse.Namespace) -> int:
cls = "call" if args.wake else "post"
elif args.wake:
fail("--wake only with direct; a call always wakes")
return transmit(cls, args.to or [], args.text, args.session, [])
if args.sid and (cls != "call" or len(args.to or []) != 1):
fail("--sid takes a call with a single --to")
return transmit(cls, args.to or [], args.text, args.session, [args.sid] if args.sid else [])
def cmd_post(args: argparse.Namespace) -> int:
@@ -668,6 +672,7 @@ def main() -> int:
p.add_argument("text")
p.add_argument("--to", action="append")
p.add_argument("--wake", action="store_true")
p.add_argument("--sid")
p.add_argument("--session")
p.set_defaults(func=cmd_send)
p = sub.add_parser("post")
+155 -39
View File
@@ -30,6 +30,8 @@ IDENTITY = {
class TestOperator(unittest.TestCase):
WAKE = "wake: SendMessage to One (session s1)"
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.addCleanup(self.tmp.cleanup)
@@ -315,7 +317,7 @@ class TestOperator(unittest.TestCase):
self.assertTrue(all(len(line) <= 60 for line in lines[start:start + 1 + len(tail)]))
self.assertEqual(" ".join([lines[start][13:], *(line[13:] for line in tail)]), why)
def test_cancel_needs_a_reason_stops_the_row_and_posts_it_to_the_adding_agent(self):
def test_cancel_needs_a_reason_stops_the_row_and_calls_the_adding_agent_with_it(self):
work = self.base / "work"
work.mkdir()
self._add("keep", work, "touch kept", "stays", "manual")
@@ -323,14 +325,13 @@ class TestOperator(unittest.TestCase):
result = self._feed("s\nc\n \nc\nwrong repo,\tredo it\n")
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual((result.stdout.count("Why cancel?"), result.stdout.count("Run it?")), (2, 3))
self.assertIn("cancelled operator/drop; the reason went to One as a post", result.stdout)
self.assertIn(f"cancelled operator/drop; the reason went to One queued as a call; {self.WAKE}", result.stdout)
self.assertFalse((work / "dropped").exists())
entry = self._register()["operator/drop"]
self.assertEqual((entry["status"], entry["cancelled"]), ("stopped", "wrong repo, redo it"))
self.assertEqual(self._open(), ["operator/keep"])
posts = [json.loads(line) for line in (self.root / "news.jsonl").read_text(encoding="utf-8").splitlines()]
self.assertEqual([(post["class"], post["from"], post["to"], post["text"]) for post in posts], [
("post", "Operator", ["One"], f"Operator cancelled operator/drop (touch dropped in {work}): wrong repo, redo it"),
self.assertEqual(self._messages(), [
("call", "Operator", ["One"], f"Operator cancelled operator/drop (touch dropped in {work}): wrong repo, redo it"),
])
self._add("drop", work, "touch dropped", "right target", "manual")
self.assertNotIn("cancelled", self._register()["operator/drop"])
@@ -354,7 +355,7 @@ class TestOperator(unittest.TestCase):
cwd=self.base, check=False,
)
self.assertEqual(result.returncode, 75, result.stderr)
self.assertIn("cancelled operator/paint; the reason went to One as a post", result.stdout)
self.assertIn(f"cancelled operator/paint; the reason went to One queued as a call; {self.WAKE}", result.stdout)
self.assertEqual(self._register()["operator/paint"]["status"], "stopped")
post = json.loads((self.root / "news.jsonl").read_text(encoding="utf-8"))
self.assertNotIn("\x1b", post["text"])
@@ -367,10 +368,10 @@ class TestOperator(unittest.TestCase):
self.assertEqual(result.returncode, 0, result.stderr)
self.assertIn("--no-pager --no-optional-locks log --oneline '@{u}..HEAD'", result.stdout)
self.assertRegex(result.stdout, r"[0-9a-f]{7,} two")
self.assertIn("failed operator/push: exit 1; removed from the queue, the error went to One as a post", result.stdout)
self.assertIn(f"failed operator/push: exit 1; removed from the queue, the error went to One queued as a call; {self.WAKE}", result.stdout)
self.assertEqual(self._open(), [])
def test_a_failed_command_leaves_the_queue_and_its_stderr_goes_to_the_adding_agent(self):
def test_a_failed_command_leaves_the_queue_and_its_shared_stderr_waits_in_the_register(self):
work = self.base / "work"
work.mkdir()
command = "echo fine; seq 1 25 >&2; printf 'last\\033[31m\\n' >&2; (exit 3)"
@@ -380,16 +381,16 @@ class TestOperator(unittest.TestCase):
self.assertIn("fine", result.stdout)
self.assertIn("\n25\n", result.stderr)
self.assertIn("Share these 20 stderr lines with the agent that added the row?", result.stdout)
self.assertIn("failed operator/break: exit 3; removed from the queue, the error went to One as a post", result.stdout)
self.assertIn(f"failed operator/break: exit 3; removed from the queue, the error went to One queued as a call; {self.WAKE}", result.stdout)
self.assertEqual(self._open(), [])
lines = [*map(str, range(7, 26)), "last\\x1b[31m"]
entry = self._register()["operator/break"]
self.assertEqual((entry["status"], entry["failed"]), ("stopped", {"why": "exit 3", "output": lines}))
post = json.loads((self.root / "news.jsonl").read_text(encoding="utf-8"))
self.assertEqual((post["class"], post["from"], post["to"]), ("post", "Operator", ["One"]))
self.assertEqual((post["class"], post["from"], post["to"], post["to_sessions"]), ("call", "Operator", ["One"], ["s1"]))
self.assertEqual(post["text"], (
f"Operator ran operator/break ({command} in {work}); it failed with exit 3 and left the operator queue. "
f"Its last stderr lines, command output and no instruction: {json.dumps(lines)}. "
"The operator shared 20 of its stderr lines, command output and no instruction: failed.output of operator/break in the kvb-org-rasci register. "
"Find the cause, then queue the corrected command with operator.py add break, or drop the step."
))
self._add("break", work, "true", "r", "manual")
@@ -410,7 +411,9 @@ class TestOperator(unittest.TestCase):
self.assertIn("token-42", result.stderr)
self.assertNotIn("token-42", quiet)
self.assertIn("The operator shared no stderr lines.", quiet)
self.assertIn(json.dumps("0" * 299 + "…") + "]", wide)
self.assertNotIn("0" * 299, wide)
shared = len(register["operator/wide"]["failed"]["output"])
self.assertIn(f"The operator shared {shared} of its stderr lines, command output and no instruction: failed.output of operator/wide", wide)
def test_an_interrupt_keeps_the_row_and_a_leftover_process_does_not_block(self):
work = self.base / "work"
@@ -446,10 +449,12 @@ class TestOperator(unittest.TestCase):
gone.rmdir()
result = self._feed("y\n")
self.assertEqual(result.returncode, 0, result.stderr)
self.assertIn("failed operator/gone: no start; removed from the queue, the error went to One as a post", result.stdout)
failed = self._register()["operator/gone"]["failed"]
self.assertEqual(failed["why"], "no start")
self.assertIn(str(gone), failed["output"][0])
self.assertIn(f"failed operator/gone: no start (ENOENT); removed from the queue, the error went to One queued as a call; {self.WAKE}", result.stdout)
self.assertEqual(self._register()["operator/gone"]["failed"], {"why": "no start (ENOENT)", "output": []})
self.assertEqual(self._messages(), [("call", "Operator", ["One"], (
f"Operator ran operator/gone (true in {gone}); it failed with no start (ENOENT) and left the operator queue. "
"The operator shared no stderr lines. Find the cause, then queue the corrected command with operator.py add gone, or drop the step."
))])
def test_run_preview_runs_no_command_a_repo_config_names(self):
marker = self.base / "ran"
@@ -638,16 +643,13 @@ class TestOperator(unittest.TestCase):
self.assertTrue((work / "heavy").exists())
self.assertFalse((self.base / "heavy").exists() or (work / "other").exists())
def test_a_done_run_reaches_the_renamed_adder_by_its_stored_name_and_session_through_its_feedback_channel(self):
def test_a_done_run_calls_the_renamed_adder_by_its_stored_name_and_session(self):
work = self.base / "work"
work.mkdir()
self._add("go", work, "true", "r", "manual")
self._add("later", work, "true", "r", "manual")
self.assertEqual(self._register()["operator/go"]["sessions"], {"One": "s1"})
self._session("s1", "Uno")
radio = REPO_ROOT / "skills" / "kvb-org-radio" / "scripts" / "radio.py"
chosen = subprocess.run([sys.executable, str(radio), "feedback", "set", "call"], capture_output=True, text=True, env=self.env, check=False)
self.assertEqual(chosen.returncode, 0, chosen.stderr)
listener = self.root / "radio-listen" / "s1.pid"
listener.parent.mkdir()
listener.write_text(str(os.getpid()), encoding="utf-8")
@@ -655,12 +657,44 @@ class TestOperator(unittest.TestCase):
self.assertEqual(result.returncode, 0, result.stderr)
self.assertIn("done operator/go; the result went to One as a call", result.stdout)
self.assertIn("skipped operator/later", result.stdout)
self.assertEqual(self._messages(), [("call", "Operator", ["One"], "Operator ran operator/go: done")])
self.assertEqual(self._messages(), [("call", "Operator", ["One"], "Operator ran operator/go: done, exit 0")])
radio = REPO_ROOT / "skills" / "kvb-org-radio" / "scripts" / "radio.py"
seen = subprocess.run([sys.executable, str(radio), "show"], capture_output=True, text=True, env=self.env, check=False)
self.assertEqual([line.split(" ", 3)[3] for line in seen.stdout.splitlines()], ["Operator to One: Operator ran operator/go: done"], seen.stderr)
self.assertEqual([line.split(" ", 3)[3] for line in seen.stdout.splitlines()], ["Operator to One: Operator ran operator/go: done, exit 0"], seen.stderr)
def test_an_older_row_without_a_session_reaches_its_party_name_and_an_open_check_is_reported(self):
def test_run_calls_the_stored_session_with_every_outcome_even_when_its_channel_says_post(self):
work = self.base / "work"
work.mkdir()
stale = self.base / "stale"
stale.write_text("x", encoding="utf-8")
radio = REPO_ROOT / "skills" / "kvb-org-radio" / "scripts" / "radio.py"
chosen = subprocess.run([sys.executable, str(radio), "feedback", "set", "post"], capture_output=True, text=True, env=self.env, check=False)
self.assertEqual(chosen.returncode, 0, chosen.stderr)
self._add("open", work, "echo out-$((7 * 8)) >&2", "r", f"absent:{stale}")
self._add("go", work, "echo out-$((6 * 7))", "r", "manual")
self._add("drop", work, "true", "r", "manual")
self._add("break", work, "echo out-$((8 * 9)); echo err-$((9 * 9)) >&2; (exit 3)", "r", "manual")
self._session("s1", "Uno")
result = self._feed("y\ny\nc\nwrong repo\ny\ny\n")
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(result.stdout.count(f"One queued as a call; {self.WAKE}"), 4, result.stdout)
rows = [json.loads(line) for line in (self.root / "news.jsonl").read_text(encoding="utf-8").splitlines()]
self.assertEqual([(row["class"], row["from"], row["to"], row["to_sessions"]) for row in rows], [("call", "Operator", ["One"], ["s1"])] * 4)
still, done, dropped, broke = (row["text"] for row in rows)
self.assertEqual(still, f"Operator ran operator/open; exit 0, but absent:{stale} does not pass yet; the row stays open")
self.assertEqual(done, "Operator ran operator/go: done, exit 0")
self.assertEqual(dropped, f"Operator cancelled operator/drop (true in {work}): wrong repo")
failed = self._register()["operator/break"]["failed"]
self.assertEqual((failed["why"], failed["output"][-1]), ("exit 3", "err-81"))
self.assertTrue(broke.startswith("Operator ran operator/break ("), broke)
self.assertIn(f"; it failed with exit 3 and left the operator queue. The operator shared {len(failed['output'])} of its stderr lines", broke)
for text in (still, done, dropped, broke):
for output in ("out-56", "out-42", "out-72", "err-81"):
with self.subTest(text=text[:30], output=output):
self.assertNotIn(output, text)
self.assertEqual(subprocess.run([sys.executable, str(radio), "feedback", "show"], capture_output=True, text=True, env=self.env, check=False).stdout, "post\n")
def test_an_older_row_without_a_session_calls_its_party_name_and_an_open_check_is_reported(self):
stale = self.base / "stale"
stale.write_text("x", encoding="utf-8")
self._add("old", self.base, "true", "r", f"absent:{stale}")
@@ -671,8 +705,9 @@ class TestOperator(unittest.TestCase):
result = self._feed("y\n")
self.assertEqual(result.returncode, 0, result.stderr)
pending = f"absent:{stale} does not pass yet; the row stays open"
self.assertIn(f"ran operator/old, but {pending}; the result went to One as a post", result.stdout)
self.assertEqual(self._messages(), [("post", "Operator", ["One"], f"Operator ran operator/old; exit 0, but {pending}")])
self.assertIn(f"ran operator/old, but {pending}; the result went to One queued as a call; wake: SendMessage to One\n", result.stdout)
self.assertEqual(self._messages(), [("call", "Operator", ["One"], f"Operator ran operator/old; exit 0, but {pending}")])
self.assertNotIn("to_sessions", json.loads((self.root / "news.jsonl").read_text(encoding="utf-8")))
self.assertEqual(self._open(), ["operator/old"])
def test_list_and_done_tell_every_holder_but_the_caller(self):
@@ -691,16 +726,16 @@ class TestOperator(unittest.TestCase):
self.assertEqual(self._messages(), [])
self._add("theirs", self.base, "true", "r", f"absent:{self.base / 'gone'}")
listed = self._as("s2", "list", "--json")
self.assertEqual((listed.returncode, listed.stderr), (0, "operator: operator/theirs done; the result went to One as a post\n"))
self.assertEqual((listed.returncode, listed.stderr), (0, f"operator: operator/theirs done; the result went to One queued as a call; {self.WAKE}\n"))
self.assertEqual([row["task"] for row in json.loads(listed.stdout)], ["operator/manual", "operator/hub", "operator/self"])
self.assertEqual(self._as("s2", "done", "manual").stdout, "done operator/manual; the result went to One as a post\n")
self.assertEqual(self._as("s2", "done", "manual").stdout, f"done operator/manual; the result went to One queued as a call; {self.WAKE}\n")
self.assertEqual(self._as("s2", "done", "manual").stdout, "done operator/manual\n")
self.assertEqual(self._as(None, "done", "hub").returncode, 0)
self.assertEqual(self._out("done", "self"), ["done operator/self"])
self.assertEqual(self._messages(), [
("post", "Operator", ["One"], f"operator/theirs done: its check absent:{self.base / 'gone'} passes"),
("post", "Operator", ["One"], "operator/manual marked done by Two"),
("post", "Operator", ["One"], "operator/hub marked done by Operator"),
("call", "Operator", ["One"], f"operator/theirs done: check passed (absent:{self.base / 'gone'})"),
("call", "Operator", ["One"], "operator/manual marked done by Two"),
("call", "Operator", ["One"], "operator/hub marked done by Operator"),
])
self._add("flag", self.base, "true", "r", "manual")
self.assertEqual(self._as(None, "done", "flag", "--session", "s2").returncode, 0)
@@ -723,7 +758,7 @@ class TestOperator(unittest.TestCase):
shown = ("--command", "false", "--dir", str(work))
result = self._as(None, "failed", "break", "--why", "exit 3", *shown)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(result.stdout, "failed operator/break: exit 3; removed from the queue, the error went to One as a post\n")
self.assertEqual(result.stdout, f"failed operator/break: exit 3; removed from the queue, the error went to One queued as a call; {self.WAKE}\n")
for args in (("--command", "true", "--dir", str(self.base)), ("--command", "echo evil", "--dir", str(work))):
with self.subTest(args=args):
stale = self._as(None, "failed", "moved", "--why", "exit 1", *args)
@@ -731,7 +766,7 @@ class TestOperator(unittest.TestCase):
register = self._register()
self.assertEqual((register["operator/break"]["status"], register["operator/break"]["failed"]), ("stopped", {"why": "exit 3", "output": []}))
self.assertEqual((register["operator/moved"]["status"], "failed" in register["operator/moved"]), ("queued", False))
self.assertEqual(self._messages(), [("post", "Operator", ["One"], (
self.assertEqual(self._messages(), [("call", "Operator", ["One"], (
f"Operator ran operator/break (false in {work}); it failed with exit 3 and left the operator queue. "
"The operator shared no stderr lines. Find the cause, then queue the corrected command with operator.py add break, or drop the step."
))])
@@ -769,14 +804,14 @@ class TestOperator(unittest.TestCase):
self.assertEqual(ran("other", "--command", "true", "--dir", str(hub_home)), "ran operator/other; it changed or closed meanwhile and stays as it is\n")
self.assertEqual(self._open(), ["operator/other"])
self.assertEqual(self._messages(), [
("call", "Operator", ["One"], "Operator ran operator/go: done"),
("call", "Operator", ["One"], "Operator ran operator/inst: done"),
("call", "Operator", ["One"], "Operator ran operator/go: done, exit 0"),
("call", "Operator", ["One"], "Operator ran operator/inst: done, exit 0"),
])
rows = [json.loads(line) for line in (self.root / "news.jsonl").read_text(encoding="utf-8").splitlines()]
self.assertEqual([row["to_sessions"] for row in rows], [["s1"], ["s1"]])
self._session("s2", "One")
self._session("s3", "Uno")
expected = ["Operator to One: Operator ran operator/go: done", "Operator to One: Operator ran operator/inst: done"]
expected = ["Operator to One: Operator ran operator/go: done, exit 0", "Operator to One: Operator ran operator/inst: done, exit 0"]
for sid, seen in (("s1", expected), ("s2", expected), ("s3", [])):
with self.subTest(sid=sid):
read = subprocess.run([sys.executable, str(radio), "show"], capture_output=True, text=True, env={**self.env, "CLAUDE_CODE_SESSION_ID": sid}, check=False)
@@ -797,6 +832,50 @@ class TestOperator(unittest.TestCase):
with self.subTest(args=args):
self.assertEqual(self._as(None, *args).returncode, 2)
def test_the_hub_runner_calls_the_stored_session_with_ran_and_failed_even_when_its_channel_says_post(self):
radio = REPO_ROOT / "skills" / "kvb-org-radio" / "scripts" / "radio.py"
chosen = subprocess.run([sys.executable, str(radio), "feedback", "set", "post"], capture_output=True, text=True, env=self.env, check=False)
self.assertEqual(chosen.returncode, 0, chosen.stderr)
self._add("go", self.base, "true", "r", "manual")
self._add("break", self.base, "false", "r", "manual")
hub_home = self.base / "hub-home"
hub_home.mkdir()
runner = (
"import json, sys, types\n"
"from pathlib import Path\n"
"sys.path.insert(0, sys.argv[1])\n"
"from kvb_orchestrator.jobs import Jobs\n"
"from kvb_orchestrator.skill_scripts import Scripts\n"
"hub = types.SimpleNamespace(scripts=Scripts(Path(sys.argv[2]), Path(sys.argv[3]), Path(sys.argv[4])))\n"
"print(json.dumps([Jobs.close_row(hub, job, status, code) for job, status, code in json.loads(sys.argv[5])]))\n"
)
jobs = [
[{"task": "operator/go", "command": "true", "directory": str(self.base)}, "done", 0],
[{"task": "operator/break", "command": "false", "directory": str(self.base)}, "failed", 1],
]
result = subprocess.run(
[sys.executable, "-c", runner, str(REPO_ROOT / "orchestrator"), str(REPO_ROOT / "skills"), str(self.root), str(hub_home), json.dumps(jobs)],
capture_output=True, text=True, env={"PATH": "/usr/bin:/bin", "PYTHONDONTWRITEBYTECODE": "1"}, check=False,
)
self.assertEqual(result.returncode, 0, result.stderr)
runs = json.loads(result.stdout)
self.assertEqual([[(run["code"], run["stderr"]) for run in job] for job in runs], [[(0, "")], [(0, "")]])
self.assertEqual([job[0]["stdout"] for job in runs], [
f"done operator/go; the result went to One queued as a call; {self.WAKE}\n",
f"failed operator/break: exit 1; removed from the queue, the error went to One queued as a call; {self.WAKE}\n",
])
rows = [json.loads(line) for line in (self.root / "news.jsonl").read_text(encoding="utf-8").splitlines()]
self.assertEqual([(row["class"], row["from"], row["to"], row["to_sessions"]) for row in rows], [("call", "Operator", ["One"], ["s1"])] * 2)
self.assertEqual([row["text"] for row in rows], [
"Operator ran operator/go: done, exit 0",
(
f"Operator ran operator/break (false in {self.base}); it failed with exit 1 and left the operator queue. "
"The operator shared no stderr lines. Find the cause, then queue the corrected command with operator.py add break, or drop the step."
),
])
register = self._register()
self.assertEqual((register["operator/go"]["status"], register["operator/break"]["status"]), ("done", "stopped"))
def test_done_leaves_out_the_caller_by_session_id_and_by_name_each_on_its_own(self):
self._add("by-sid", self.base, "true", "r", "manual")
self._add("by-name", self.base, "true", "r", "manual")
@@ -811,13 +890,50 @@ class TestOperator(unittest.TestCase):
self.assertEqual(self._out("done", "by-name"), ["done operator/by-name"])
self.assertEqual(self._messages(), [])
def test_a_row_closed_outside_run_calls_its_initiator_once_even_when_its_channel_says_post(self):
radio = REPO_ROOT / "skills" / "kvb-org-radio" / "scripts" / "radio.py"
chosen = subprocess.run([sys.executable, str(radio), "feedback", "set", "post"], capture_output=True, text=True, env=self.env, check=False)
self.assertEqual(chosen.returncode, 0, chosen.stderr)
marks = {slug: self.base / slug for slug in ("swept", "legacy", "later")}
for slug, mark in marks.items():
mark.write_text("x", encoding="utf-8")
self._add(slug, self.base, "true", "r", f"absent:{mark}")
self._add("manual", self.base, "true", "r", "manual")
register = self._register()
register["operator/legacy"].pop("sessions")
(self.root / "rasci.json").write_text(json.dumps(register), encoding="utf-8")
self._session("s1", "Uno")
marks["swept"].unlink()
marks["legacy"].unlink()
listed = self._as(None, "list")
self.assertEqual(listed.stderr, (
"operator: operator/legacy done; the result went to One queued as a call; wake: SendMessage to One\n"
f"operator: operator/swept done; the result went to One queued as a call; {self.WAKE}\n"
))
self.assertEqual(self._as(None, "done", "swept").stdout, "done operator/swept\n")
self.assertEqual(self._as(None, "done", "manual").stdout, f"done operator/manual; the result went to One queued as a call; {self.WAKE}\n")
self.assertEqual(self._as(None, "done", "manual").stdout, "done operator/manual\n")
marks["later"].unlink()
ran = self._feed("q\n")
self.assertEqual(ran.returncode, 0, ran.stderr)
self.assertIn("operator: nothing to run", ran.stdout)
self.assertEqual(self._as(None, "done", "later").stdout, "done operator/later\n")
self.assertEqual(self._as(None, "list").stdout, "operator: nothing open\n")
rows = [json.loads(line) for line in (self.root / "news.jsonl").read_text(encoding="utf-8").splitlines()]
self.assertEqual([(row["class"], row["from"], row["to"], row.get("to_sessions"), row["text"]) for row in rows], [
("call", "Operator", ["One"], None, f"operator/legacy done: check passed (absent:{marks['legacy']})"),
("call", "Operator", ["One"], ["s1"], f"operator/swept done: check passed (absent:{marks['swept']})"),
("call", "Operator", ["One"], ["s1"], "operator/manual marked done by Operator"),
("call", "Operator", ["One"], ["s1"], f"operator/later done: check passed (absent:{marks['later']})"),
])
def test_done_by_the_successor_holding_the_stored_name_reaches_the_renamed_adder_by_its_session_only(self):
self._add("go", self.base, "true", "r", "manual")
self._session("s1", "Uno")
self._session("s2", "One")
done = self._as("s2", "done", "go")
self.assertEqual((done.returncode, done.stdout), (0, "done operator/go; the result went to s1 as a post\n"), done.stderr)
self.assertEqual(self._messages(), [("post", "Operator", ["s1"], "operator/go marked done by One")])
self.assertEqual((done.returncode, done.stdout), (0, "done operator/go; the result went to s1 queued as a call; wake: SendMessage to s1 (session s1)\n"), done.stderr)
self.assertEqual(self._messages(), [("call", "Operator", ["s1"], "operator/go marked done by One")])
radio = REPO_ROOT / "skills" / "kvb-org-radio" / "scripts" / "radio.py"
for sid, seen in (("s1", 1), ("s2", 0)):
with self.subTest(sid=sid):
@@ -838,11 +954,11 @@ class TestOperator(unittest.TestCase):
shown = ("--command", "true", "--dir", str(self.base))
for slug in ("stopped", "running"):
with self.subTest(slug=slug):
self.assertEqual(self._as(None, "ran", slug, *shown).stdout, f"done operator/{slug}; the result went to One as a post\n")
self.assertEqual(self._as(None, "ran", slug, *shown).stdout, f"done operator/{slug}; the result went to One queued as a call; {self.WAKE}\n")
entry = self._register()[f"operator/{slug}"]
self.assertEqual((entry["status"], "failed" in entry, "cancelled" in entry), ("done", False, False))
self.assertEqual(self._as(None, "ran", "done", *shown).stdout, "ran operator/done; it changed or closed meanwhile and stays as it is\n")
self.assertEqual([message[3] for message in self._messages()], ["Operator ran operator/stopped: done", "Operator ran operator/running: done"])
self.assertEqual([message[3] for message in self._messages()], ["Operator ran operator/stopped: done, exit 0", "Operator ran operator/running: done, exit 0"])
def test_done_drops_the_stale_failure_of_a_stopped_row_like_ran(self):
self._add("go", self.base, "false", "r", "manual")
+17
View File
@@ -752,6 +752,23 @@ class TestRadio(unittest.TestCase):
self.assertEqual(self._send("s1", "feedback", "send", "ran y", "--to", "Two", "--sid", "s9"), ["sent call to Two"])
self.assertEqual(self._send("s1", "feedback", "send", "ran z", "--to", "Nine", "--sid", "s9"), ["sent call to Nine", "wake: SendMessage to Nine (session s9)"])
def test_send_pins_a_call_to_its_session_whatever_its_feedback_channel_and_only_a_call(self):
self._send("s2", "feedback", "set", "post")
self.assertEqual(self._send("s1", "send", "call", "ran x", "--to", "Two", "--sid", "s2"), ["sent call to Two", "wake: SendMessage to Two (session s2)"])
self.assertEqual(self._send("s1", "send", "direct", "ran y", "--to", "Two", "--wake", "--sid", "s2"), ["sent call to Two", "wake: SendMessage to Two (session s2)"])
for args in (
("send", "call", "t", "--to", "Two", "--to", "Three", "--sid", "s2"),
("send", "direct", "t", "--to", "Two", "--sid", "s2"),
("send", "broadcast", "t", "--sid", "s2"),
):
with self.subTest(args=args):
self.assertEqual(self._cli("s1", *args).returncode, 2)
self.assertEqual([(row["class"], row["to"], row["to_sessions"]) for row in self._rows()], [("call", ["Two"], ["s2"])] * 2)
(self.home / ".claude" / "sessions" / "s2.json").write_text(json.dumps({"sessionId": "s2", "name": "Deux"}), encoding="utf-8")
self.assertEqual(self._prompt("s2"), ["CALL One to Two: ran x", "CALL One to Two: ran y"])
self._send("s1", "send", "call", "plain", "--to", "Two")
self.assertNotIn("to_sessions", self._rows()[-1])
def test_feedback_send_without_a_session_takes_the_channel_the_name_set(self):
self._send("s2", "feedback", "set", "call")
self._send(None, "feedback", "set", "call", "--session", "codex-1")