feat(orchestrator): S5 Tasks with choices, Gantt, estimates and burn charts

Requirement 001 phase 6, S5:

- Tasks tab: every pending ask, rule request, operator row and choice
  card shows under "waits on Operator"; a choice request goes out on a
  fixed channel button, post and call with an agent multi-select, and a
  click on an option sends a passkey-signed answer the agent checks with
  operator_message. The unsigned /api/decisions/<id>/choose route is
  gone, and a decision, choice answer or choice recipient whose name
  holds "*" is refused, so a signed answer never reaches every agent.
- Gantt view: one bar per task from start to end (running to now), one
  arrow per explicit, branch-base and queue-order edge, hatched forecast
  bars (always, points only, real only) from the median duration or
  points times median hours per point.
- rasci.py set --after/--drop-after stores task dependencies and refuses
  unknown tasks and cycles.
- Estimation toggle (No estimate default, Story points) is stored in the
  hub settings; burndown and burnup per whole register, list filter or
  one agent or line, counting tasks or summing complexity with the
  unestimated tasks as their own line.
- New skill kvb-org-queue-estimate: "Request estimates" (story points
  mode, passkey-signed board action) or the skill sends exactly one
  newsletter listing every unestimated task with its RASCI parties; a
  party name that is no plain name shows as "unnamed party".
- Business value per task or in bulk is stored only with a verified
  passkey assertion over the exact ids and values; WSJF uses it instead
  of the median. The task list sorts by every decision-50 mode both ways.
- e2e: the walk's pending ask lives an hour instead of 60 s, and the
  CDP and BiDi drivers retry removing the browser profile while the
  browser exits (ENOTEMPTY).

Evidence: make test 709 OK, ruff and markdownlint clean
(/tmp/s5-make-test-fix-2.log); e2e 26 OK in Chromium and Firefox
(/tmp/s5-e2e-fix-2.log); MEDUSA 50 files, an independent skeptic
rejected four holes (unsigned choose route, unsigned estimates request,
free-text party names, "*" recipients incl. normalizer bypasses), all
fixed and re-verified, the 8 remaining pattern hits accepted, rescan 0
open.

🎯 Fix: 92 %
💥 Break: 4 %
💸 Cost: 100 %
⏱️ Time: –
🛡️ Security: 100 %
🏆 Score: 88
🚦 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-09 06:53:55 +00:00
1 parent 5c8b69d53d
commit d9eb121d12
49 files changed
+2162 -148

No files matched your search

+9 -4
View File
@@ -4,6 +4,7 @@ import secrets
import time
from .asking import ask_state
from .choosing import answer_signed
from .cleanup import cleanup_request
from .denying import DENIABLE, DENY_KEYS, denial_note, request_status, request_words
from .errors import Conflict, Missing, ToolError
@@ -35,7 +36,8 @@ def inbox_item(raw: dict, label: str, title: str, gate: str, subject: dict | Non
label: the chosen option of a decision, else empty.
title: what the stream logs for the item.
gate: the review gate, else empty.
subject: what an approval signs; None for a decision.
subject: what an approval signs; for a decision the answer post to
the asking agent.
requester: the requesting agent's name for a denial, else empty.
Returns:
@@ -105,14 +107,15 @@ class Approving:
Returns:
The proof to relay, None when nothing needs a signature. The hub
verifies the signature of a denial itself, since it acts on it;
of an approval it checks the shape, and the executors verify.
of an approval it checks the shape, and the executors verify,
the hub itself for a choice answer when it sends it.
"""
if not signed:
if proof is not None:
raise ToolError("proof must be null when no item needs a signature")
return None
if not isinstance(proof, dict):
raise ToolError("not signed: an approval of an ask, review or operator command needs the passkey signature")
raise ToolError("not signed: an approval of an ask, review, choice or operator command needs the passkey signature")
expect(proof, ("payload", "assertion"))
try:
payload = signing.checked_approval(proof["payload"], now)
@@ -162,6 +165,8 @@ class Approving:
record, changed = self.asks.decide(item["id"], {"status": "allowed" if approve else "denied", "proof": proof})
elif item["kind"] == "review":
record, changed = self.reviews.decide(item["id"], {"status": "approved" if approve else "rejected", "proof": proof})
elif item["signed"] is not None:
return self.answer_choice(item, proof)
else:
record, changed = self.decisions.decide(item["id"], {"status": "decided", "choice": item["label"]})
if record is None:
@@ -218,7 +223,7 @@ class Approving:
if kind_name == "rule":
return inbox_item(raw, "", f"Rule {request_words(record)}", "", request_signed(record), self.requester(raw, record["agent"]))
title = {"review": record.get("title"), "ask": f"{record.get('tool')} {record.get('command')}", "decision": record.get("question")}[kind_name]
subject = {"review": review_signed, "ask": ask_signed}[kind_name](record) if kind_name != "decision" else None
subject = {"review": review_signed, "ask": ask_signed}[kind_name](record) if kind_name != "decision" else answer_signed(record, label)
return inbox_item(raw, label, title, record.get("gate", ""), subject, self.requester(raw, record["session"] if kind_name == "ask" else ""))
def checked(self, raw: object) -> list[dict]:
+13 -16
View File
@@ -2,6 +2,7 @@ from __future__ import annotations
import time
from .choosing import EVERYONE, answer_text
from .errors import Conflict, Missing, ToolError
from .fields import (
COMMAND_LIMIT,
@@ -35,7 +36,13 @@ def ask_row(ask: dict, names: dict[str, str]) -> dict:
def decision_state(decision: dict) -> dict:
return {key: decision[key] for key in ("id", "status", "choice", "decided")}
"""Returns:
The status and choice, with the id and text of the operator's
passkey-signed answer when a click chose it, else None for both.
"""
message = decision.get("message")
answer = None if message is None else answer_text(decision, decision["choice"])
return {**{key: decision[key] for key in ("id", "status", "choice", "decided")}, "message": message, "answer": answer}
def decision_row(decision: dict) -> dict:
@@ -87,20 +94,7 @@ class Asking:
if not changed:
raise Conflict(ask_state(decided, time.time()))
return ask_state(decided, time.time())
if kind_name != "decisions" or verb != "choose":
raise Missing(verb)
payload = decode(body)
expect(payload, ("label",))
label = field(payload, "label")
record = self.decisions.get(item_id)
if record is None:
raise Missing(item_id)
if label not in [option["label"] for option in record["options"]]:
raise ToolError(f"label must be one of the options of decision {item_id}")
decided, changed = self.decisions.decide(item_id, {"status": "decided", "choice": label})
if not changed:
raise Conflict(decision_state(decided))
return decision_state(decided)
raise Missing(verb)
def decision_request(self, arguments: dict) -> dict:
expect(arguments, ("question", "options", "agent", "recommended"))
@@ -114,7 +108,10 @@ class Asking:
recommended = arguments["recommended"]
if not isinstance(recommended, str) or recommended.strip() not in ["", *(option["label"] for option in parsed)]:
raise ToolError("recommended must be one of the option labels or an empty string")
fields = {"question": question, "options": parsed, "agent": field(arguments, "agent").strip(), "recommended": recommended.strip()}
asker = field(arguments, "agent").strip()
if EVERYONE in asker:
raise ToolError(f"agent names the asking agent, never a name with {EVERYONE}")
fields = {"question": question, "options": parsed, "agent": asker, "recommended": recommended.strip()}
record = self.decisions.add({**fields, "status": "pending", "choice": None, "decided": None, "created_ts": time.time()})
self.automate("decision", record)
return {"id": record["id"], "status": record["status"], "url": self.url()}
+100
View File
@@ -0,0 +1,100 @@
from __future__ import annotations
from .council import agent
from .errors import ToolError
from .fields import decode, expect, field
from .messaging import DIRECT, EVERYONE, TO_ALL
from .signed import signing
CHOICE_REQUEST = "send me your open decisions as choices"
CHANNELS = {**DIRECT, **TO_ALL}
CHOICE_KEYS = ("class", "to")
RECIPIENT_LIMIT = 40
ANSWER_CLASS = "post"
QUESTION_SHOWN = 200
def answer_text(decision: dict, label: str) -> str:
question = " ".join(decision["question"].split())[:QUESTION_SHOWN]
return f"Choice for decision {decision['id']} ({question}): {label}"
def answer_signed(decision: dict, label: str) -> dict:
"""Returns:
The post to the asking agent that a click on the option label
signs: the operator's answer operator_message proves.
"""
if EVERYONE in decision["agent"]:
raise ToolError(f"a choice answer goes to the asking agent, never to a name with {EVERYONE}")
return signing.message_item(agent(decision["agent"]), ANSWER_CLASS, answer_text(decision, label), "", "", "")
def recipients(payload: dict) -> list[str]:
"""Args:
payload: the page's class and to: 1 to RECIPIENT_LIMIT distinct
agent names for post and call, [EVERYONE] for a class to all.
"""
cls, names = payload["class"], payload["to"]
if not isinstance(cls, str) or cls not in CHANNELS:
raise ToolError(f"class must be one of {', '.join(CHANNELS)}")
if not isinstance(names, list) or not all(isinstance(name, str) for name in names):
raise ToolError("to must be a list of agent names")
if cls in TO_ALL:
if names != [EVERYONE]:
raise ToolError(f"a choice request to all names to [{EVERYONE}]")
return names
targets = [field({"to": name}, "to").strip() for name in names]
if not 1 <= len(targets) <= RECIPIENT_LIMIT or any(EVERYONE in target for target in targets):
raise ToolError(f"a post or a call names 1 to {RECIPIENT_LIMIT} agents, never a name with {EVERYONE}")
if len({agent(target) for target in targets}) != len(targets):
raise ToolError("to must name distinct agents")
return targets
class Choosing:
def choice_items(self, payload: dict) -> list[dict]:
return [signing.message_item(target, payload["class"], CHOICE_REQUEST, "", "", "") for target in recipients(payload)]
def sign_choices(self, body: bytes) -> dict:
payload = decode(body)
expect(payload, CHOICE_KEYS)
return self.challenge_for(self.choice_items(payload))
def request_choices(self, body: bytes) -> dict:
"""Returns:
The ids of the stored requests, one per recipient, once one
passkey assertion signed each of them; nothing is stored or sent
before every item verified.
"""
payload = decode(body)
expect(payload, (*CHOICE_KEYS, "proof"))
items = self.choice_items(payload)
for item in items:
self.operator_proven(payload["proof"], item)
records = [self.stored_message(item, payload["proof"], None) for item in items]
runs = [self.radioed(record, CHANNELS[payload["class"]]) for record in records]
return {"ids": [record["id"] for record in records], "ok": all(run["code"] == 0 for run in runs), "runs": runs}
def answer_choice(self, item: dict, proof: dict) -> str:
"""Args:
item: a checked decision item whose signed is answer_signed().
proof: the relayed signature; the hub sends the answer itself,
so it verifies the signature here, once.
Returns:
The outcome words for the stream.
"""
record = self.decisions.get(item["id"])
if record is None:
return "unknown"
if record["status"] != "pending":
return f"already {record['status']}"
self.operator_proven(proof, item["signed"])
message = self.stored_message(item["signed"], proof, None)
decided, changed = self.decisions.decide(item["id"], {"status": "decided", "choice": item["label"], "message": message["id"]})
if not changed:
self.messages.remove(message["id"])
return f"already {decided['status']}"
run = self.radioed(message, CHANNELS[ANSWER_CLASS])
where = f"{ANSWER_CLASS} to {message['address']}"
return f"decided · {where}" if run["code"] == 0 else f"decided · {where} failed ({run['code']})"
+8 -2
View File
@@ -17,7 +17,7 @@ TTS_ROUTE = "/api/tts"
WAV_TYPE = "audio/wav"
STT_ROUTE = "/api/stt"
ROUTE = re.compile(r"/reviews/([0-9a-f]{16})/(page|files|approve|reject)")
ITEM = re.compile(r"/api/(asks|decisions)/([0-9a-f]{16})(?:/(allow|deny|choose))?")
ITEM = re.compile(r"/api/(asks|decisions)/([0-9a-f]{16})(?:/(allow|deny))?")
ENTRY = re.compile(r"/api/stream/([0-9]{1,12})")
BOARD = re.compile(r"/api/board/([a-z-]{1,32})")
UPLOADS = "/api/uploads"
@@ -48,8 +48,10 @@ VOICE_ITEM = re.compile(r"/api/voice/([0-9a-f]{16})(\.wav)?")
MESSAGE_SIGN_ROUTE = "/api/messages/sign"
BOARD_SIGN_ROUTE = "/api/board/sign"
SETTINGS_SIGN_ROUTE = "/api/settings/sign"
CHOICES_ROUTE = "/api/choices"
CHOICES_SIGN_ROUTE = "/api/choices/sign"
WAV_POSTS = (STT_ROUTE, VOICE_ROUTE)
ACTION_POSTS = ("/api/rules", "/api/nl", SETTINGS_ROUTE, TTS_ROUTE, STT_ROUTE, SIGN_ROUTE, RULE_SIGN_ROUTE, CLEANUP_ROUTE, OFFICES_ROUTE, TASKS_ROUTE, VOICE_ROUTE, MESSAGE_SIGN_ROUTE, SETTINGS_SIGN_ROUTE)
ACTION_POSTS = ("/api/rules", "/api/nl", SETTINGS_ROUTE, TTS_ROUTE, STT_ROUTE, SIGN_ROUTE, RULE_SIGN_ROUTE, CLEANUP_ROUTE, OFFICES_ROUTE, TASKS_ROUTE, VOICE_ROUTE, MESSAGE_SIGN_ROUTE, SETTINGS_SIGN_ROUTE, CHOICES_ROUTE, CHOICES_SIGN_ROUTE)
class Handler(Exchange):
@@ -182,6 +184,10 @@ class Handler(Exchange):
return lambda body: self.answer(lambda: hub.voice_notes.submit(body), HTTPStatus.ACCEPTED)
if path == MESSAGE_SIGN_ROUTE:
return lambda body: self.answer(lambda: hub.sign_message(body), HTTPStatus.OK)
if path == CHOICES_SIGN_ROUTE:
return lambda body: self.answer(lambda: hub.sign_choices(body), HTTPStatus.OK)
if path == CHOICES_ROUTE:
return lambda body: self.answer(lambda: hub.request_choices(body), HTTPStatus.CREATED)
return None
def posted(self, path: str) -> bool:
+2 -1
View File
@@ -11,6 +11,7 @@ from .approving import Approving
from .artifacts import Touched
from .asking import Asking
from .batches import Pending
from .choosing import Choosing
from .cleanup import Cleaning, Spool
from .denying import Denying
from .engines import Engines, Speech
@@ -62,7 +63,7 @@ def environment(templates: Path) -> jinja2.Environment:
@dataclass(frozen=True)
class Hub(Mcp, Reviewing, Asking, Messaging, Approving, Denying, Requesting, Cleaning, Offices, Tasking, Inbox, Rules, Jobs, Sources, Timeline, View, Language):
class Hub(Mcp, Reviewing, Asking, Messaging, Choosing, Approving, Denying, Requesting, Cleaning, Offices, Tasking, Inbox, Rules, Jobs, Sources, Timeline, View, Language):
council: Path
pages: Path
public_port: int
+9 -5
View File
@@ -5,6 +5,7 @@ from http import HTTPStatus
from . import NAME
from .asking import OPTION_LIMIT
from .choosing import CHOICE_REQUEST
from .errors import RpcError, ToolError
from .fields import WAIT_CAP
from .requesting import AGENT_CAP
@@ -64,19 +65,22 @@ class Mcp:
tool("review_list", "List the pending reviews.", {}),
tool(
"decision_request",
"Ask the operator to pick one of several options in the Agent Orchestrator; each option becomes a button. "
"Returns the decision id and the hub URL.",
"Ask the operator to pick one of several options in the Agent Orchestrator; the question shows as a choice card "
"under Waits on Operator in the Tasks tab and each option becomes a button. When an operator message asks "
f'"{CHOICE_REQUEST}", send each open decision of kvb-think-choice through this tool. Returns the decision id and the hub URL.',
{
"question": text_property("The question, plain text."),
"options": {"type": "array", "minItems": 1, "maxItems": OPTION_LIMIT, "items": option, "description": "The choices, at least one."},
"agent": text_property("Your agent name, shown with the question."),
"agent": text_property("Your agent name, shown with the question; the operator's signed answer is a post to it."),
"recommended": text_property("The label of the option you recommend, or an empty string."),
},
),
tool(
"decision_wait",
f"Wait until the operator picks an option or the timeout passes, then return the status "
f"(pending, decided) and the chosen label. Waits at most {WAIT_CAP} seconds.",
"Wait until the operator picks an option or the timeout passes, then return the status "
"(pending, decided), the chosen label and, for a click, message and answer: the id and text of the operator's "
"passkey-signed answer, a post to the asking agent; check it with operator_message(message, answer, your name) "
f"before acting on the choice. Waits at most {WAIT_CAP} seconds.",
{"id": text_property("Decision id that decision_request returned."), "timeout_seconds": wait},
),
tool(
+30 -11
View File
@@ -5,12 +5,12 @@ import secrets
import time
from .council import HUMAN, agent, ordered, read_claims
from .errors import Missing, ToolError
from .errors import Conflict, Missing, ToolError
from .fields import NAME_LIMIT, ORDER_NAME, decode, expect, field, message_text, single
from .records import write_atomic
from .register import REGISTER, agent_order, read_register
from .signed import message_signed, signing
from .skill_scripts import NIGHT, RADIO, RASCI
from .skill_scripts import ESTIMATE, NIGHT, RADIO, RASCI
NIGHTS = {
"drain": (["drain"], "Operator ran kvb-org-drain in the Agent Orchestrator: run kvb-agent-drain; verify with night.py status."),
@@ -23,7 +23,7 @@ TO_ALL = {"newsletter": ["post"], **{cls: ["send", cls] for cls in ("broadcast",
EVERYONE = "*"
DENIED = "Denied by the operator."
MESSAGE_KEYS = ("to", "text", "upload", "class", "voice")
SIGNED_BOARD = ("clear-mayday", *NIGHTS)
SIGNED_BOARD = ("clear-mayday", *NIGHTS, "estimates")
def chosen(payload: dict, choices: dict[str, list[str]]) -> list[str]:
@@ -142,17 +142,31 @@ class Messaging:
item, _, _ = self.composed(payload, {**DIRECT, **TO_ALL})
return self.challenge_for([item])
def stored_message(self, item: dict, proof: dict, upload: dict | None) -> dict:
"""Args:
item: the message item a pinned key signed.
proof: that signature, kept so operator_message can prove it.
upload: the attached upload or None.
Returns:
The stored record, addressed to the radio address the claims
give the recipient.
"""
target = item["to"]
claims = read_claims(self.council)
address = next((claim["address"] for claim in claims if claim["agent"] == target and claim["address"]), target)
fields = {"to": target, "address": address, "text": item["text"], "upload": upload, "voice": item["voice"] or None, "voice_sha256": item["voice_sha256"], "class": item["class"]}
return self.messages.add({**fields, "proof": proof, "created_ts": time.time()})
def radioed(self, record: dict, command: list[str]) -> dict:
targets = [] if record["to"] == EVERYONE else ["--to", record["address"]]
return self.scripts.run(RADIO, [*command, *targets, "--session", HUMAN, f"[kvb-orchestrator msg {record['id']}] {self.relayed(record)}"])
def relay(self, payload: dict, choices: dict[str, list[str]]) -> dict:
with self.voice_notes.held(payload["voice"]):
item, command, upload = self.composed(payload, choices)
proof = self.operator_proven(payload["proof"], item)
target = item["to"]
claims = read_claims(self.council)
address = next((claim["address"] for claim in claims if claim["agent"] == target and claim["address"]), target)
fields = {"to": target, "address": address, "text": item["text"], "upload": upload, "voice": item["voice"] or None, "voice_sha256": item["voice_sha256"], "class": item["class"]}
record = self.messages.add({**fields, "proof": proof, "created_ts": time.time()})
targets = [] if target == EVERYONE else ["--to", address]
run = self.scripts.run(RADIO, [*command, *targets, "--session", HUMAN, f"[kvb-orchestrator msg {record['id']}] {self.relayed(record)}"])
record = self.stored_message(item, self.operator_proven(payload["proof"], item), upload)
run = self.radioed(record, command)
return {"id": record["id"], "ok": run["code"] == 0, "runs": [run]}
def message(self, body: bytes) -> dict:
@@ -191,6 +205,11 @@ class Messaging:
if unknown:
raise ToolError(f"unknown agents: {', '.join(unknown)[:300]}; the register and the council know {', '.join(known)[:600] or 'none'}")
runs = [self.scripts.run(RASCI, ["agents", "order", ",".join(names)])]
elif action == "estimates":
estimation = self.settings.get()["estimation"]
if estimation != "points":
raise Conflict({"estimation": estimation, "reason": "estimates are requested only in story points mode"})
runs = [self.scripts.run(ESTIMATE, ["request", "--session", HUMAN])]
elif action in NIGHTS:
command, text = NIGHTS[action]
runs = [self.scripts.run(NIGHT, [*command, "--session", HUMAN])]
@@ -14,6 +14,7 @@ from .fields import FIELDS, NAME_LIMIT, expect
from .records import read_json, write_atomic
THEMES = ("sky", "light", "dark", "custom")
ESTIMATIONS = ("none", "points")
TONES = ("mayday", "review", "direct", "radio")
COLOR = re.compile(r"#[0-9a-f]{6}")
CLOCK = re.compile(r"(?:[01][0-9]|2[0-3]):[0-5][0-9]")
@@ -44,6 +45,7 @@ SETTINGS = {
"graph": {"axis": "none", "yaw": 30.0, "pitch": 20.0, "zoom": 1.0, "pan_x": 0.0, "pan_y": 0.0},
"sky": {"azimuth": 180.0, "altitude": 0.0, "fov": 180.0},
},
"estimation": "none",
}
SPACE_AXES = ("none", "time", "spawn")
SPACE_LIMITS = {
@@ -189,6 +191,8 @@ def valid_settings(raw: object) -> dict:
raise ToolError(f"theme must be one of {', '.join(THEMES)}")
if not isinstance(data["streams"], list) or len(data["streams"]) > STREAMS_LIMIT:
raise ToolError(f"streams must be a list of at most {STREAMS_LIMIT} entries")
if not isinstance(data["estimation"], str) or data["estimation"] not in ESTIMATIONS:
raise ToolError(f"estimation must be one of {', '.join(ESTIMATIONS)}")
return {
"latitude": number_in(data["latitude"], "latitude", -90.0, 90.0),
"longitude": number_in(data["longitude"], "longitude", -180.0, 180.0),
@@ -201,6 +205,7 @@ def valid_settings(raw: object) -> dict:
"streams": [stream_entry(entry, index) for index, entry in enumerate(data["streams"])],
"speech": speech_setting(data["speech"]),
"space": space_setting(data["space"]),
"estimation": data["estimation"],
}
@@ -13,6 +13,7 @@ RADIO = "kvb-org-radio/scripts/radio.py"
RASCI = "kvb-org-rasci/scripts/rasci.py"
NIGHT = "kvb-org-suspend/scripts/night.py"
OPERATOR_SCRIPT = "kvb-org-operator/scripts/operator.py"
ESTIMATE = "kvb-org-queue-estimate/scripts/estimate.py"
class Runner(Protocol):
+5 -3
View File
@@ -9,7 +9,7 @@ from .register import REGISTER, read_register, status_of
from .signed import signing
from .tasks import editable
CHANGE_LIMIT = 10
CHANGE_LIMIT = 100
CHANGE_KEYS = ("kind", "id", "argv")
@@ -25,7 +25,9 @@ class Tasking:
def task_changes(self, raw: object) -> list[dict]:
"""Args:
raw: the page's items, each {"kind": "task", "id", "argv"} with
the rasci.py arguments of one priority pin or WSJF estimate.
the rasci.py arguments of one priority pin, WSJF estimate or
operator business value; a bulk change over a selection is
one item per task under one passkey assertion.
Returns:
The signed items, each for an open register task outside
@@ -60,7 +62,7 @@ class Tasking:
items = self.task_changes(payload["items"])
proof = self.covered(payload["proof"], items, time.time())
for item in items:
self.still_signed(proof, item)
self.operator_proven(proof, item)
ids = []
for item in items:
fields = {"kind": TASK_JOB, "task": item["id"], "argv": item["argv"], "command": shown_command(item["argv"]), "directory": "", "sha256": "", "status": "queued", "proof": proof}
+119 -9
View File
@@ -3,8 +3,8 @@ from __future__ import annotations
import itertools
import statistics
from .council import agent
from .records import iso_epoch, shown
from .council import HUMAN, agent
from .records import epoch, iso_epoch, shown
from .register import ENDED, OPERATOR, parties, register_row, status_of
from .signed import signing
from .tree import inside
@@ -13,11 +13,13 @@ ENDED_SHOWN = 100
OPEN_SHOWN = 300
QUEUE_SHOWN = 100
PARTIES_SHOWN = 40
AFTER_SHOWN = 40
TEXT_SHOWN = 500
FIBONACCI = (1, 2, 3, 5, 8, 13, 21, 34, 55, 89)
LETTERS = "RASCI"
HOTFIX = "hotfix/"
QUEUE = "queue/"
HOUR = 3600
def kind_of(task: str) -> str:
@@ -36,23 +38,42 @@ def fibonacci(value: object) -> bool:
def estimates_of(row: dict) -> dict[str, dict]:
"""Returns:
Each party's Fibonacci business value and complexity; the
Operator's complexity is None where it recorded a business value
alone.
"""
raw = row.get("estimates")
found = {}
for party, entry in itertools.islice(raw.items(), PARTIES_SHOWN) if isinstance(raw, dict) else ():
if isinstance(entry, dict) and fibonacci(entry.get("value")) and fibonacci(entry.get("complexity")):
found[str(party)[:TEXT_SHOWN]] = {"value": entry["value"], "complexity": entry["complexity"]}
alone = party == HUMAN and isinstance(entry, dict) and "complexity" not in entry
if isinstance(entry, dict) and fibonacci(entry.get("value")) and (alone or fibonacci(entry.get("complexity"))):
found[str(party)[:TEXT_SHOWN]] = {"value": entry["value"], "complexity": entry.get("complexity")}
return found
def business_value(estimates: dict[str, dict]) -> float | None:
if HUMAN in estimates:
return estimates[HUMAN]["value"]
return statistics.median(entry["value"] for entry in estimates.values()) if estimates else None
def points(estimates: dict[str, dict]) -> float | None:
sized = [entry["complexity"] for entry in estimates.values() if entry["complexity"] is not None]
return statistics.median(sized) if sized else None
def wsjf(estimates: dict[str, dict]) -> dict | None:
"""Returns:
Median business value, median complexity and their quotient, the
same reading as rasci.py's wsjf(); None without an estimate.
Business value, median complexity and their quotient, the same
reading as rasci.py's wsjf(): the Operator's business value where
it gave one, else the median; None while no estimate carries a
complexity.
"""
if not estimates:
complexity = points(estimates)
if complexity is None:
return None
value = statistics.median(entry["value"] for entry in estimates.values())
complexity = statistics.median(entry["complexity"] for entry in estimates.values())
value = business_value(estimates)
return {"value": value, "complexity": complexity, "score": round(value / complexity, 2)}
@@ -96,6 +117,11 @@ def located(row: dict, trees: list[dict], open_task: bool) -> dict:
return {"worktree": tree["path"], "worktree_branch": tree["branch"], "repo": tree["repo"], "flow": tree["flow"], "open_work": [*own, *tree["open_work"]]}
def after_of(row: dict) -> list[str]:
raw = row.get("after")
return [other for other in raw[:AFTER_SHOWN] if isinstance(other, str) and len(other) <= TEXT_SHOWN] if isinstance(raw, list) else []
def task_row(task: str, row: dict, trees: list[dict]) -> dict:
estimates = estimates_of(row)
ended = status_of(row) in ENDED
@@ -108,6 +134,12 @@ def task_row(task: str, row: dict, trees: list[dict]) -> dict:
"prio": prio_of(row),
"estimates": estimates,
"wsjf": wsjf(estimates),
"value": business_value(estimates),
"points": points(estimates),
"start": iso_epoch(row.get("start")),
"end": iso_epoch(row.get("end")) if ended else None,
"after": after_of(row),
"base": shown(row.get("base"))[:TEXT_SHOWN],
"roles": roles_of(row),
"queue": None,
**located(row, trees, not ended),
@@ -134,6 +166,12 @@ def queue_row(entry: dict, created: float, trees: list[dict]) -> dict:
"prio": None,
"estimates": {},
"wsjf": None,
"value": None,
"points": None,
"start": (epoch(entry.get("granted")) or created) if entry.get("status") == "active" else None,
"end": None,
"after": [],
"base": "-",
"roles": {},
"queue": {"kind": text["kind"], "parent": text["task"], "enqueued": created},
**located(entry, trees, False),
@@ -165,3 +203,75 @@ def task_rows(tasks: dict[str, dict], queue: list[tuple[dict, float]], scan: dic
*(queue_row(entry, created, trees) for entry, created in jobs),
*(task_row(task, tasks[task], trees) for task in ended[:ENDED_SHOWN]),
]
def register_ranks(tasks: dict[str, dict], agents: list[str]) -> dict[str, int]:
"""Returns:
Each open task's index in rasci.py's ranked(): pin, WSJF, the
worker's place in the operator's agent order, then the name.
"""
order = {name: index for index, name in enumerate(agents)}
def key(task: str) -> tuple:
worker = tasks[task].get("worker")
return (*rank(task, tasks[task])[:4], order.get(worker, len(order)) if isinstance(worker, str) else len(order), task)
current = sorted((task for task, row in tasks.items() if status_of(row) not in ENDED), key=key)
return {task: index for index, task in enumerate(current)}
def queue_chain(queue: list[tuple[dict, float]], tasks: dict[str, dict], agents: list[str], now: float) -> list[tuple[str, bool]]:
"""Args:
queue: the kvb-org-queue entries with their enqueue time.
tasks: the register rows by task.
agents: the operator's agent order.
now: epoch seconds.
Returns:
The entry ids in grant order, each with whether it waits: the
active ones by grant time, then the waiting ones as queue.py's
ordered() sorts them (hotfix first, then the register rank less one
per whole hour waited, then the holder's agent order, then the
enqueue sequence).
"""
ranks = register_ranks(tasks, agents)
order = {name: index for index, name in enumerate(agents)}
def waiting_key(pair: tuple[dict, float]) -> tuple:
entry, created = pair
task, name, seq = entry.get("task"), entry.get("name"), entry.get("seq")
hours = int((now - created) // HOUR)
place = ranks[task] if isinstance(task, str) and task in ranks else len(ranks)
holder = order[name] if isinstance(name, str) and name in order else len(order)
return (not entry.get("hotfix"), place - hours, holder, seq if isinstance(seq, int) and not isinstance(seq, bool) else 0)
active = sorted((pair for pair in queue if pair[0].get("status") == "active"), key=lambda pair: epoch(pair[0].get("granted")) or pair[1])
waiting = sorted((pair for pair in queue if pair[0].get("status") == "waiting"), key=waiting_key)
return [(shown(entry.get("id"))[:TEXT_SHOWN], entry.get("status") == "waiting") for entry, _ in [*active, *waiting]]
def branch_of(row: dict) -> str:
return row["branch"] if row["branch"] != "-" else row["worktree_branch"]
def task_edges(rows: list[dict], chain: list[tuple[str, bool]]) -> list[dict]:
"""Args:
rows: the shown task rows of task_rows().
chain: queue_chain().
Returns:
One {"from", "to", "kind"} edge per predecessor among the shown
rows: kind after for an explicit `rasci.py set --after`, base for a
task whose base branch is another task's branch, queue for each
waiting queue job and the job ahead of it.
"""
shown_tasks = {row["task"] for row in rows}
edges = [{"from": other, "to": row["task"], "kind": "after"} for row in rows for other in row["after"] if other in shown_tasks and other != row["task"]]
branches: dict[str, list[str]] = {}
for row in rows:
if row["kind"] != "queue" and branch_of(row):
branches.setdefault(branch_of(row), []).append(row["task"])
edges += [{"from": other, "to": row["task"], "kind": "base"} for row in rows if row["kind"] != "queue" for other in branches.get(row["base"], []) if other != row["task"]]
jobs = [(f"{QUEUE}{job}", waits) for job, waits in chain]
edges += [{"from": ahead, "to": job, "kind": "queue"} for (ahead, _), (job, waits) in itertools.pairwise(jobs) if waits and {ahead, job} <= shown_tasks]
return edges
+7 -3
View File
@@ -36,7 +36,7 @@ from .reviewing import review_row
from .settings import media_origins, station_origins, valid_settings
from .signed import signing
from .skill_scripts import OUTPUT_LIMIT
from .tasks import task_rows
from .tasks import queue_chain, task_edges, task_rows
RADIO_WINDOW = 86400
JOBS_SHOWN = 20
@@ -103,6 +103,9 @@ class View:
people = {node["id"]: {"name": node["label"], "now": directory.now(node["id"]) or node["label"], "names": node["names"]} for node in drawn["nodes"] if node["kind"] != "subagent"}
settings = self.settings.get()
inbox = self.inbox(now, tasks, directory)
queue = queue_entries(self.council)
order = stored_order(self.council / AGENT_ORDER)
rows = task_rows(tasks, queue, self.tree.get())
return {
"settings": settings,
"media": media_origins(settings),
@@ -128,8 +131,9 @@ class View:
"messages": [message_row(message) for message in self.messages.listed() if begin <= message["created_ts"] <= end],
"operator": operator_rows(tasks),
"register": register_rows(tasks),
"tasks": task_rows(tasks, queue_entries(self.council), self.tree.get()),
"agent_order": agent_order(tasks, claims, stored_order(self.council / AGENT_ORDER)),
"tasks": rows,
"task_edges": task_edges(rows, queue_chain(queue, tasks, order, now)),
"agent_order": agent_order(tasks, claims, order),
"radio": radio,
"claims": claims,
"grants": grant_rows,