feat(orchestrator): release Match decisions with one passkey, bound to what each card showed
Phase C of 012: the Match overview lists every decided card with flip, edit and back, and one passkey signature releases them all through the inbox. An approved operator command is bound to the payload hash its card showed (match_item in the signed set): the hub refuses a stale snapshot or a changed payload file at release and again before it queues the job. A rejected commit review carries its feedback as a radio call to the card's agent, which the hub verifies and records as the review's rejection. Reject feedback shows line by line, an empty one as such; the arrow keys are in the help; 012 counts every waiting inbox entry in the Tasks badge. Accepted MEDUSA false positives (kvb-think-criticize 2026-11-17): MEDUSA-MM-SCAN-058 signing.py:335 and :337 (pla of plan), EXA010 page-match.js:409 (passkey in a title), EXA006 matching.py:49 (agent then requester_of), STG002 page-constants.js:79 (U+2212 minus as a label). 🎯 Fix: 92 % 💥 Break: 4 % 💸 Tokens: 100 % ⏱️ Velocity: 100 % 🛡️ Security: 100 % (style-match.css not covered by MEDUSA, reviewed by hand) 🏆 Score: 88 🚦 Gate: ✅ 90/5, tokens and velocity <= 100, security 100 % Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
e9cd1aeda5
commit
5e00a79fdc
11 files changed
+673
-28
No files matched your search
@@ -14,8 +14,10 @@ terminal prompts.
|
||||
every file the command reads (an issue body, a script, a list file).
|
||||
Rejected: staged commits only; decision rows as cards (they keep their own
|
||||
pick view).
|
||||
2. **Place**: a Match view under the Tasks tab; the Tasks tab carries a badge
|
||||
with the number of waiting cards.
|
||||
2. **Place**: a Match view under the Tasks tab; the Tasks tab badge counts
|
||||
every waiting entry as 001 defines it, the cards included (operator
|
||||
2026-11-17: asks and decisions stay visible in the badge). Rejected: a
|
||||
badge of the cards alone.
|
||||
3. **Card layout**: on top the agent's face, below it the agent's name and
|
||||
its age in days (since its first session), then repository, branch and
|
||||
worktree; below them the affected files, each collapsed, opening one
|
||||
@@ -132,7 +134,8 @@ flowchart TD
|
||||
- [ ] After a release, each accepted command runs once and its result is
|
||||
shown; each rejected card's agent receives a radio call whose text
|
||||
contains the feedback.
|
||||
- [ ] The Tasks tab badge equals the number of waiting cards.
|
||||
- [ ] The Tasks tab badge equals the number of waiting inbox entries, every
|
||||
waiting card among them.
|
||||
|
||||
### Tests
|
||||
|
||||
|
||||
@@ -107,6 +107,15 @@ def operator_item(task: str, command: str, directory: str) -> dict:
|
||||
return {"kind": "operator", "id": task, "command": command, "directory": directory}
|
||||
|
||||
|
||||
def match_item(card_id: str, payload: str) -> dict:
|
||||
"""Args:
|
||||
card_id: the Match card of an operator command, operator:<task>.
|
||||
payload: the payload hash the card showed: command, directory and
|
||||
the state of every file the command names.
|
||||
"""
|
||||
return {"kind": "match", "id": card_id, "hash": payload}
|
||||
|
||||
|
||||
def cleanup_item(repository: str, branch: str, worktree: str, tip: str) -> dict:
|
||||
return {"kind": "cleanup", "repository": repository, "branch": branch, "worktree": worktree, "tip": tip}
|
||||
|
||||
|
||||
@@ -6,7 +6,14 @@ 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 .denying import (
|
||||
DENIABLE,
|
||||
DENY_KEYS,
|
||||
NOTED,
|
||||
denial_note,
|
||||
request_status,
|
||||
request_words,
|
||||
)
|
||||
from .errors import Conflict, Missing, ToolError
|
||||
from .fields import decode, expect, field, visible
|
||||
from .firewall import settings_request
|
||||
@@ -46,12 +53,20 @@ def inbox_item(raw: dict, label: str, title: str, gate: str, subject: dict | Non
|
||||
The batch item. A denial of a deniable kind signs its own item and
|
||||
carries the note that tells the requesting agent.
|
||||
"""
|
||||
note = denial_note(raw, requester) if raw["verb"] == "reject" and raw["kind"] in DENIABLE else None
|
||||
note = denial_note(raw, requester) if raw["verb"] == "reject" and "channel" in raw else None
|
||||
signed = subject if raw["verb"] == "approve" else None if note is None else signing.denial_item(subject, note["channel"], note["reason"], note["to"])
|
||||
sha256 = raw["sha256"] if raw["kind"] == "operator" else ""
|
||||
return {"kind": raw["kind"], "id": raw["id"], "verb": raw["verb"], "label": label, "sha256": sha256, "title": shown(title)[:200], "gate": gate, "signed": signed, "note": note}
|
||||
|
||||
|
||||
def signed_of(items: list[dict]) -> list[dict]:
|
||||
"""Returns:
|
||||
Every item the approval of items must list: each item's own signed
|
||||
item and the payload bindings of operator commands.
|
||||
"""
|
||||
return [entry for item in items for entry in ([item["signed"]] if item["signed"] is not None else []) + item.get("bound", [])]
|
||||
|
||||
|
||||
class Approving:
|
||||
def keys(self) -> list[dict]:
|
||||
try:
|
||||
@@ -164,6 +179,8 @@ class Approving:
|
||||
if item["note"] is not None:
|
||||
return self.deny(item, proof)
|
||||
if item["kind"] == "operator":
|
||||
if not all(self.payload_holds(bound) for bound in item.get("bound", [])):
|
||||
return "refused: a payload file changed since the release"
|
||||
return self.queue_job(item, proof)
|
||||
if item["kind"] == "ask":
|
||||
record = self.asks.get(item["id"])
|
||||
@@ -188,7 +205,7 @@ class Approving:
|
||||
Conflict when it is no longer the one the inbox showed the
|
||||
operator, sent back as raw["to"].
|
||||
"""
|
||||
if raw["verb"] != "reject" or raw["kind"] not in DENIABLE:
|
||||
if raw["verb"] != "reject" or "channel" not in raw:
|
||||
return ""
|
||||
name = self.addressee(who)[0]
|
||||
if raw["to"] != name:
|
||||
@@ -214,13 +231,16 @@ class Approving:
|
||||
raise Conflict({"id": row["task"], "status": "changed"})
|
||||
if row["task"] in self.open_jobs():
|
||||
raise Conflict({"id": row["task"], "status": "queued"})
|
||||
return inbox_item(raw, "", row["command"], "", operator_signed(row), self.requester(raw, adder(tasks[row["task"]])))
|
||||
bound = self.payload_bound(row, raw["payload"]) if "payload" in raw else []
|
||||
return {**inbox_item(raw, "", row["command"], "", operator_signed(row), self.requester(raw, adder(tasks[row["task"]]))), "bound": bound}
|
||||
|
||||
def item_of(self, raw: object, tasks: dict[str, dict]) -> dict:
|
||||
if not isinstance(raw, dict):
|
||||
raise ToolError("every item must be an object with kind, id, verb, label and sha256, and a denial also channel, reason and to")
|
||||
kind_name, verb = raw.get("kind"), raw.get("verb")
|
||||
expect(raw, (*ITEM_KEYS, *DENY_KEYS) if verb == "reject" and kind_name in DENIABLE else ITEM_KEYS)
|
||||
noted = verb == "reject" and (kind_name in DENIABLE or kind_name in NOTED and "channel" in raw)
|
||||
shown = ("payload",) if kind_name == "operator" and verb == "approve" and "payload" in raw else ()
|
||||
expect(raw, (*ITEM_KEYS, *DENY_KEYS) if noted else (*ITEM_KEYS, *shown))
|
||||
if kind_name not in INBOX_KINDS or verb not in VERBS or not isinstance(raw["label"], str) or not isinstance(raw["sha256"], str):
|
||||
raise ToolError(f"kind must be one of {', '.join(INBOX_KINDS)}, verb approve or reject, label and sha256 text")
|
||||
if kind_name == "operator":
|
||||
@@ -243,7 +263,7 @@ class Approving:
|
||||
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 answer_signed(record, label)
|
||||
return inbox_item(raw, label, title, record.get("gate", ""), subject, self.requester(raw, record["session"] if kind_name == "ask" else ""))
|
||||
return inbox_item(raw, label, title, record.get("gate", ""), subject, self.requester(raw, record["session"] if kind_name == "ask" else record.get("agent", "")))
|
||||
|
||||
def checked(self, raw: object) -> list[dict]:
|
||||
if not isinstance(raw, list) or not 1 <= len(raw) <= BATCH_LIMIT:
|
||||
@@ -277,14 +297,14 @@ class Approving:
|
||||
signed = self.enable_items(raw)
|
||||
return {**self.challenge_for(signed), "enables": signed[0]["rule"]}
|
||||
else:
|
||||
signed = [item["signed"] for item in self.checked(raw) if item["signed"] is not None]
|
||||
signed = signed_of(self.checked(raw))
|
||||
return self.challenge_for(signed)
|
||||
|
||||
def approve(self, body: bytes) -> dict:
|
||||
payload = decode(body)
|
||||
expect(payload, ("items", "proof"))
|
||||
items = self.checked(payload["items"])
|
||||
proof = self.covered(payload["proof"], [item["signed"] for item in items if item["signed"] is not None], time.time())
|
||||
proof = self.covered(payload["proof"], signed_of(items), time.time())
|
||||
return self.batches.add(items, "operator", proof, self.apply)
|
||||
|
||||
def undo(self, batch_id: str) -> dict:
|
||||
|
||||
@@ -11,6 +11,7 @@ from .signed import operator_signed, signing
|
||||
from .skill_scripts import RASCI
|
||||
|
||||
DENIABLE = ("ask", "operator", "rule")
|
||||
NOTED = ("review",)
|
||||
DENY_KEYS = ("channel", "reason", "to")
|
||||
DENY_CHANNELS = {**DIRECT, **{name: words for name, words in TO_ALL.items() if name != "mayday"}}
|
||||
REASON_LIMIT = 2000
|
||||
@@ -84,6 +85,14 @@ class Denying:
|
||||
return f"failed: {run['command']} → {run['code']}"
|
||||
command, directory = row["command"][:200], row["directory"]
|
||||
return f"stopped · {self.tell(item, proof, adder(tasks[item['id']]), f'operator command {command} in {directory}')}"
|
||||
if item["kind"] == "review":
|
||||
record, changed = self.reviews.decide(item["id"], {"status": "rejected", "proof": proof, **note})
|
||||
if record is None:
|
||||
return "unknown"
|
||||
if not changed:
|
||||
return f"already {record['status']}"
|
||||
title, branch = record["title"][:200], record["branch"]
|
||||
return f"rejected · {self.tell(item, proof, record.get('agent', ''), f'commit {title} on {branch}')}"
|
||||
ledger = self.asks if item["kind"] == "ask" else self.rule_requests
|
||||
record = ledger.get(item["id"])
|
||||
if record is None:
|
||||
|
||||
@@ -3,8 +3,9 @@ from __future__ import annotations
|
||||
import time
|
||||
|
||||
from .council import read_claims
|
||||
from .denying import requester_of
|
||||
from .diffs import stored_diff
|
||||
from .errors import Missing, ToolError
|
||||
from .errors import Conflict, Missing, ToolError
|
||||
from .fields import decode, expect, field
|
||||
from .payloads import denied_roots, payload_files, payload_hash
|
||||
from .records import digest, iso_epoch
|
||||
@@ -45,7 +46,7 @@ class Matching:
|
||||
claims = read_claims(self.council)
|
||||
names = self.names.listed()
|
||||
reviews = self.reviews.pending()
|
||||
cards = [self.commit_card(review, reviews, born_of(review.get("agent", ""), names, claims)) for review in reviews]
|
||||
cards = [{**self.commit_card(review, reviews, born_of(review.get("agent", ""), names, claims)), "to": requester_of(claims, review.get("agent", ""))[0]} for review in reviews]
|
||||
tasks = read_register(self.council / REGISTER)
|
||||
held = self.open_jobs()
|
||||
rows = [row for row in operator_rows(tasks) if row["check"] != "decision" and row["task"] not in held]
|
||||
@@ -53,7 +54,7 @@ class Matching:
|
||||
scan = self.tree.get()
|
||||
for row in rows:
|
||||
agent = adder(tasks[row["task"]])
|
||||
cards.append(self.command_card(row, agent, born_of(agent, names, claims), roots, scan))
|
||||
cards.append({**self.command_card(row, agent, born_of(agent, names, claims), roots, scan), "to": requester_of(claims, agent)[0]})
|
||||
listed = {card["id"] for card in cards}
|
||||
for snapshot in self.match_snapshots.listed():
|
||||
if snapshot["id"] not in listed:
|
||||
@@ -92,6 +93,35 @@ class Matching:
|
||||
"reason": row["why"], "sha256": digest(row["command"]),
|
||||
}
|
||||
|
||||
def live_payload(self, row: dict) -> str:
|
||||
files = payload_files(row["command"], row["directory"], denied_roots(self.settings_files()[0]))
|
||||
return payload_hash(row["command"], row["directory"], files)
|
||||
|
||||
def payload_bound(self, row: dict, shown: object) -> list[dict]:
|
||||
"""Args:
|
||||
row: the open operator row a Match release approves.
|
||||
shown: the payload hash its card showed the operator.
|
||||
|
||||
Returns:
|
||||
The match item binding the approval to that hash.
|
||||
|
||||
Raises:
|
||||
ToolError for a hash that is no hex digest; Conflict when the
|
||||
card's snapshot is gone or retaken, or a payload file changed
|
||||
since the card showed it.
|
||||
"""
|
||||
if not isinstance(shown, str) or not signing.HASH.fullmatch(shown):
|
||||
raise ToolError("payload must be the hash the card showed")
|
||||
snapshot = self.match_snapshots.get(f"operator:{row['task']}")
|
||||
if snapshot is None or snapshot["command_sha256"] != digest(row["command"]) or snapshot["hash"] != shown or self.live_payload(row) != shown:
|
||||
raise Conflict({"id": row["task"], "status": "stale"})
|
||||
return [signing.match_item(f"operator:{row['task']}", shown)]
|
||||
|
||||
def payload_holds(self, bound: dict) -> bool:
|
||||
task = bound["id"].removeprefix("operator:")
|
||||
row = next((row for row in operator_rows(read_register(self.council / REGISTER)) if row["task"] == task), None)
|
||||
return row is not None and self.live_payload(row) == bound["hash"]
|
||||
|
||||
def match_stale(self, body: bytes) -> dict:
|
||||
"""Args:
|
||||
body: {"id", "tree"}: a pending review and the tree git
|
||||
|
||||
@@ -76,7 +76,7 @@
|
||||
direct: [[740, 0, 0.2]],
|
||||
radio: [[520, 0, 0.07]],
|
||||
};
|
||||
const KEYS = [["Ctrl+K", "Commands, views, agents and AI command"], ["Right-click", "Context menu: the element's commands, then the tab's, then the general ones"], ["Shift+right-click", "The browser's own context menu"], ["Menu key · Shift+F10", "Context menu of the focused element: ↑ / ↓ move, Enter runs, Esc closes"], ["1 · 2 · 3 · 4", "Stream · Agents · Artifacts · Tasks"], ["j / k", "Waits on Operator: next / previous entry"], ["x", "Waits on Operator: select entry"], ["a", "Waits on Operator: grant entry (3 s to undo)"], ["Enter", "Waits on Operator: open entry"], ["f", "Feedback on the selected lines of a diff or a command"], ["/", "Search the stream"], ["h", "Look at the sky: drag turns the view, wheel or two fingers zoom, Esc ends"], ["Arrows · + / − · 0", "Sky (focused): turn · zoom · reset"], ["Drag · wheel", "3D: turn, right drag pans, wheel zooms"],["🎙 hold", "Voice input into the agent field or the command line, never sent automatically"], ["?", "This help"], ["Esc", "Close"]];
|
||||
const KEYS = [["Ctrl+K", "Commands, views, agents and AI command"], ["Right-click", "Context menu: the element's commands, then the tab's, then the general ones"], ["Shift+right-click", "The browser's own context menu"], ["Menu key · Shift+F10", "Context menu of the focused element: ↑ / ↓ move, Enter runs, Esc closes"], ["1 · 2 · 3 · 4", "Stream · Agents · Artifacts · Tasks"], ["j / k", "Waits on Operator: next / previous entry"], ["x", "Waits on Operator: select entry"], ["a", "Waits on Operator: grant entry (3 s to undo)"], ["Enter", "Waits on Operator: open entry"], ["f", "Feedback on the selected lines of a diff or a command"], ["→ · ← · ↑", "Match: accept · reject with feedback · later"],["/", "Search the stream"], ["h", "Look at the sky: drag turns the view, wheel or two fingers zoom, Esc ends"], ["Arrows · + / − · 0", "Sky (focused): turn · zoom · reset"], ["Drag · wheel", "3D: turn, right drag pans, wheel zooms"],["🎙 hold", "Voice input into the agent field or the command line, never sent automatically"], ["?", "This help"], ["Esc", "Close"]];
|
||||
const calm = window.matchMedia("(prefers-reduced-motion: reduce)");
|
||||
const relative = new Intl.RelativeTimeFormat("en", {numeric: "auto"});
|
||||
const absolute = new Intl.DateTimeFormat("en-GB", {dateStyle: "medium", timeStyle: "short"});
|
||||
|
||||
@@ -70,6 +70,8 @@
|
||||
}
|
||||
} else if (event.key === "f" && feedbackKey()) {
|
||||
event.preventDefault();
|
||||
} else if (event.key.startsWith("Arrow") && (target === document.body || (target instanceof Element && target.closest(".match-stack"))) && matchKey(event.key)) {
|
||||
event.preventDefault();
|
||||
} else if (event.key === "Enter" && current && target === document.body) {
|
||||
event.preventDefault();
|
||||
openItem(current);
|
||||
|
||||
@@ -3,7 +3,11 @@
|
||||
const LONG_PRESS = 550;
|
||||
const PRESS_SLOP = 10;
|
||||
const MATCH_KINDS = {commit: ["Commit", "info", "bi-git"], command: ["Command", "warn", "bi-terminal"]};
|
||||
const matchView = {cards: null, order: [], marks: new Map(), opened: new Map(), dom: null, sig: "", fetched: 0, loading: false, press: null};
|
||||
const MATCH_VERDICTS = {accept: ["Accept", "ok", "bi-check-lg"], reject: ["Reject", "bad", "bi-x-lg"]};
|
||||
const SWIPE_SHARE = 0.25;
|
||||
const SWIPE_UP = 80;
|
||||
const FEEDBACK_LIMIT = 2000;
|
||||
const matchView = {cards: null, order: [], marks: new Map(), opened: new Map(), decisions: new Map(), overview: false, front: null, drag: null, dom: null, sig: "", fetched: 0, loading: false, press: null};
|
||||
|
||||
async function fetchMatch() {
|
||||
if (matchView.loading) {
|
||||
@@ -42,8 +46,10 @@
|
||||
return days === 1 ? "1 day" : `${days} days`;
|
||||
}
|
||||
|
||||
const cardKey = (card) => `${card.id}@${card.hash}`;
|
||||
|
||||
function marksOf(card) {
|
||||
const key = `${card.id}@${card.hash}`;
|
||||
const key = cardKey(card);
|
||||
if (!matchView.marks.has(key)) {
|
||||
matchView.marks.set(key, []);
|
||||
}
|
||||
@@ -235,12 +241,200 @@
|
||||
}}}, face(card.agent || "-", false), h("span", {class: "pill", "data-tone": kindTone}, kindName), card.stale ? h("span", {class: "pill", "data-tone": "bad"}, "stale") : null, h("span", {class: "match-peek-title"}, revealed(card.title)));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {object} card a match card.
|
||||
* @returns {string} every mark of the card as one line "path:line: comment", in the order they were set.
|
||||
*/
|
||||
function feedbackOf(card) {
|
||||
return marksOf(card).map((mark) => `${mark.path}:${mark.line}: ${mark.comment}`).join("\n");
|
||||
}
|
||||
|
||||
function decide(card, verdict, feedback) {
|
||||
matchView.decisions.set(cardKey(card), {verdict, feedback});
|
||||
drawMatch(true);
|
||||
}
|
||||
|
||||
function acceptCard(card) {
|
||||
if (card.stale) {
|
||||
toast("Accept: refused", [`The card is stale: ${card.stale_reason}. Add it again to decide it.`], false);
|
||||
return;
|
||||
}
|
||||
decide(card, "accept", "");
|
||||
}
|
||||
|
||||
function rejectCard(card) {
|
||||
const kept = matchView.decisions.get(cardKey(card));
|
||||
const words = h("textarea", {class: "field match-feedback", rows: 6, maxlength: FEEDBACK_LIMIT, "aria-label": "Feedback"});
|
||||
words.value = (kept && kept.verdict === "reject" ? kept.feedback : feedbackOf(card)).slice(0, FEEDBACK_LIMIT);
|
||||
const confirm = h("button", {type: "button", class: "btn danger match-feedback-reject"}, icon("bi-x-lg"), "Reject");
|
||||
confirm.addEventListener("click", () => {
|
||||
closeSheet();
|
||||
decide(card, "reject", words.value.trim());
|
||||
});
|
||||
const note = `${card.agent || "The agent"} gets this text by radio call at the release; nothing is sent before.`;
|
||||
openSheet(`Reject: ${card.title}`, [h("p", {class: "muted"}, note), words, h("div", {class: "actions"}, h("span", {class: "spacer"}), btn("Cancel", "btn ghost", closeSheet), confirm)], false);
|
||||
words.focus();
|
||||
}
|
||||
|
||||
function laterCard(card) {
|
||||
matchView.order = [...matchView.order.filter((id) => id !== card.id), card.id];
|
||||
drawMatch(true);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} key the key of a keydown the global handler did not take.
|
||||
* @returns {boolean} whether the Match stack took it: the right arrow accepts the front card, the left arrow
|
||||
* rejects it, the up arrow sends it to the back.
|
||||
*/
|
||||
function matchKey(key) {
|
||||
const card = matchView.front;
|
||||
if (!card || !matchView.dom || !matchView.dom.stack.isConnected) {
|
||||
return false;
|
||||
}
|
||||
const act = {ArrowRight: acceptCard, ArrowLeft: rejectCard, ArrowUp: laterCard}[key];
|
||||
if (act) {
|
||||
act(card);
|
||||
}
|
||||
return Boolean(act);
|
||||
}
|
||||
|
||||
function draggable(article, card) {
|
||||
const head = article.querySelector(".match-head");
|
||||
const move = (event) => {
|
||||
const drag = matchView.drag;
|
||||
if (drag && drag.id === event.pointerId) {
|
||||
const [dx, dy] = [event.clientX - drag.x, event.clientY - drag.y];
|
||||
article.style.transform = `translate(${dx}px, ${Math.min(0, dy)}px) rotate(${dx / 40}deg)`;
|
||||
article.dataset.leaning = dx > 0 ? "accept" : dx < 0 ? "reject" : "";
|
||||
}
|
||||
};
|
||||
const release = (event) => {
|
||||
const drag = matchView.drag;
|
||||
if (!drag || drag.id !== event.pointerId) {
|
||||
return;
|
||||
}
|
||||
drag.end();
|
||||
article.style.removeProperty("transform");
|
||||
delete article.dataset.leaning;
|
||||
const [dx, dy] = [event.clientX - drag.x, event.clientY - drag.y];
|
||||
const far = SWIPE_SHARE * article.getBoundingClientRect().width;
|
||||
if (event.type === "pointercancel" || !article.isConnected) {
|
||||
return;
|
||||
}
|
||||
if (Math.abs(dx) >= far && Math.abs(dx) > Math.abs(dy)) {
|
||||
(dx > 0 ? acceptCard : rejectCard)(card);
|
||||
} else if (-dy >= SWIPE_UP && -dy > Math.abs(dx)) {
|
||||
laterCard(card);
|
||||
}
|
||||
};
|
||||
head.addEventListener("pointerdown", (event) => {
|
||||
if (event.button !== 0 || matchView.drag || (event.target instanceof Element && event.target.closest("button, a, input, textarea, select"))) {
|
||||
return;
|
||||
}
|
||||
const end = () => {
|
||||
matchView.drag = null;
|
||||
window.removeEventListener("pointermove", move);
|
||||
window.removeEventListener("pointerup", release);
|
||||
window.removeEventListener("pointercancel", release);
|
||||
};
|
||||
matchView.drag = {x: event.clientX, y: event.clientY, id: event.pointerId, end};
|
||||
window.addEventListener("pointermove", move);
|
||||
window.addEventListener("pointerup", release);
|
||||
window.addEventListener("pointercancel", release);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {object} card a decided match card.
|
||||
* @param {object} decision its {verdict, feedback}.
|
||||
* @returns {object} the inbox entry the release signs: an approval of the review, or of the operator row bound to
|
||||
* the payload hash the card showed, or its rejection carrying the feedback as a radio call to the card's agent.
|
||||
*/
|
||||
function matchEntry(card, decision) {
|
||||
const kind = card.kind === "commit" ? "review" : "operator";
|
||||
const entry = {kind, id: card.ref, verb: decision.verdict === "accept" ? "approve" : "reject", label: "", sha256: kind === "operator" ? card.sha256 || "" : ""};
|
||||
if (decision.verdict === "reject") {
|
||||
return {...entry, channel: "call", reason: decision.feedback, to: card.to || ""};
|
||||
}
|
||||
return kind === "operator" ? {...entry, payload: card.hash} : entry;
|
||||
}
|
||||
|
||||
function decided(cards) {
|
||||
return cards.map((card) => [card, matchView.decisions.get(cardKey(card))]).filter(([, decision]) => decision);
|
||||
}
|
||||
|
||||
async function releaseMatch(cards) {
|
||||
const picked = decided(cards);
|
||||
const released = await submit(picked.map(([card, decision]) => matchEntry(card, decision)), `Release: ${picked.length === 1 ? "1 decision" : `${picked.length} decisions`}`);
|
||||
if (released) {
|
||||
picked.forEach(([card]) => matchView.decisions.delete(cardKey(card)));
|
||||
matchView.overview = false;
|
||||
await fetchMatch();
|
||||
}
|
||||
}
|
||||
|
||||
function overviewRow(card, decision) {
|
||||
const [kindName, kindTone, kindIcon] = MATCH_KINDS[card.kind] || [card.kind, "neutral", "bi-collection"];
|
||||
const [word, tone, mark] = MATCH_VERDICTS[decision.verdict];
|
||||
const other = decision.verdict === "accept" ? "reject" : "accept";
|
||||
const flip = iconBtn(MATCH_VERDICTS[other][2], MATCH_VERDICTS[other][0], "btn small ghost match-flip", () => (other === "accept" ? acceptCard(card) : rejectCard(card)), `${MATCH_VERDICTS[other][0]} instead`);
|
||||
const back = iconBtn("bi-arrow-counterclockwise", "Back to the stack", "btn small ghost match-undecide", () => {
|
||||
matchView.decisions.delete(cardKey(card));
|
||||
matchView.overview = false;
|
||||
drawMatch(true);
|
||||
});
|
||||
return h("li", {class: "match-decision", "data-card": card.id, "data-verdict": decision.verdict},
|
||||
h("div", {class: "row"}, face(card.agent || "-", false), h("span", {class: "pill", "data-tone": kindTone}, icon(kindIcon), kindName), h("strong", {class: "match-decision-title"}, revealed(card.title)), h("span", {class: "spacer"}),
|
||||
h("span", {class: "pill match-verdict", "data-tone": tone}, icon(mark), word), decision.verdict === "reject" ? iconBtn("bi-pencil", "Edit feedback", "btn small ghost match-edit", () => rejectCard(card)) : null, flip, back),
|
||||
decision.verdict === "reject" ? h("pre", {class: "match-decision-feedback"}, revealedLines(decision.feedback === "" ? "no feedback text" : decision.feedback)) : null);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Array<object>} cards the cards in stack order.
|
||||
* @returns {string} why the release waits, empty when it can go: a commit whose gate is not green is released
|
||||
* only on its own, as the inbox grants it.
|
||||
*/
|
||||
function releaseBlock(cards) {
|
||||
const picked = decided(cards);
|
||||
if (!picked.length) {
|
||||
return "Nothing decided yet.";
|
||||
}
|
||||
const lone = picked.find(([card, decision]) => card.kind === "commit" && decision.verdict === "accept" && card.gate !== "pass");
|
||||
return lone && picked.length > 1 ? `The commit "${lone[0].title}" has no green gate and is released only on its own: send it back to the stack or release it alone.` : "";
|
||||
}
|
||||
|
||||
function overview(cards, open) {
|
||||
const picked = decided(cards);
|
||||
const block = releaseBlock(cards);
|
||||
const release = h("button", {type: "button", class: "btn primary match-release", disabled: Boolean(block), title: block || "One passkey signature releases every decision; 3 s remain to undo."},
|
||||
icon("bi-key"), picked.length === 1 ? "Release 1 decision" : `Release ${picked.length} decisions`);
|
||||
release.addEventListener("click", () => releaseMatch(cards));
|
||||
const back = open ? iconBtn("bi-stack", `Back to the stack (${open})`, "btn ghost match-back", () => {
|
||||
matchView.overview = false;
|
||||
drawMatch(true);
|
||||
}) : null;
|
||||
return h("section", {class: "card match-overview", "aria-label": "Decisions"},
|
||||
h("h2", {class: "panel-title"}, "Decisions"),
|
||||
h("p", {class: "muted"}, "Nothing has run yet. Accepted commits get the operator's signature for their exact tree, accepted commands run once as jobs under Waits on Operator, every rejection goes to its agent by radio call."),
|
||||
picked.length ? h("ol", {class: "match-decisions"}, picked.map(([card, decision]) => overviewRow(card, decision))) : h("p", {class: "muted"}, "No decision yet."),
|
||||
block && picked.length ? h("p", {class: "match-release-block"}, icon("bi-exclamation-triangle"), block) : null,
|
||||
h("div", {class: "actions"}, back, h("span", {class: "spacer"}), release));
|
||||
}
|
||||
|
||||
function matchScreen() {
|
||||
const stack = h("div", {class: "match-stack"});
|
||||
const count = h("span", {class: "muted"});
|
||||
matchView.dom = {stack, count};
|
||||
const tally = h("span", {class: "match-tally"}, "0");
|
||||
const decisions = h("button", {type: "button", class: "btn small soft match-open-overview", ...named("Decisions", "Decisions: the list of every decision, to change and release them"), on: {click: () => {
|
||||
matchView.overview = true;
|
||||
drawMatch(true);
|
||||
}}}, icon("bi-card-checklist"), tally);
|
||||
matchView.dom = {stack, count, decisions, tally};
|
||||
matchView.sig = "";
|
||||
const bar = h("div", {class: "card controls task-toolbar", role: "toolbar", "aria-label": "Match"}, h("strong", {}, icon("bi-stack"), "Match"), count, h("span", {class: "spacer"}),
|
||||
if (matchView.drag) {
|
||||
matchView.drag.end();
|
||||
}
|
||||
const bar = h("div", {class: "card controls task-toolbar", role: "toolbar", "aria-label": "Match"}, h("strong", {}, icon("bi-stack"), "Match"), count, h("span", {class: "spacer"}), decisions,
|
||||
iconBtn("bi-list-check", "Tasks", "btn small soft", () => go("tasks", null), "Tasks: back to the task list"));
|
||||
fetchMatch();
|
||||
return h("div", {class: "graph tasks match"}, bar, stack);
|
||||
@@ -259,19 +453,38 @@
|
||||
return;
|
||||
}
|
||||
const cards = matchOrder(matchView.cards);
|
||||
const sig = JSON.stringify([cards.map((card) => [card.id, card.hash, card.live_hash, card.stale, card.born, card.files ? card.files.length : null]), Math.floor(state.now / DAY)]);
|
||||
const byKey = new Map(cards.map((card) => [cardKey(card), card]));
|
||||
[...matchView.decisions].forEach(([key, decision]) => {
|
||||
const card = byKey.get(key);
|
||||
if (!card || (decision.verdict === "accept" && card.stale)) {
|
||||
matchView.decisions.delete(key);
|
||||
}
|
||||
});
|
||||
const open = cards.filter((card) => !matchView.decisions.has(cardKey(card)));
|
||||
const shownOverview = matchView.overview || (!open.length && matchView.decisions.size > 0);
|
||||
const sig = JSON.stringify([cards.map((card) => [card.id, card.hash, card.live_hash, card.stale, card.born, card.gate, card.files ? card.files.length : null]), [...matchView.decisions], shownOverview, Math.floor(state.now / DAY)]);
|
||||
if (!force && sig === matchView.sig) {
|
||||
return;
|
||||
}
|
||||
matchView.sig = sig;
|
||||
dom.count.textContent = cards.length === 1 ? "1 card waits" : `${cards.length} cards wait`;
|
||||
dom.count.textContent = open.length === 1 ? "1 card waits" : `${open.length} cards wait`;
|
||||
dom.tally.textContent = String(matchView.decisions.size);
|
||||
dom.decisions.hidden = !matchView.decisions.size || shownOverview;
|
||||
if (!cards.length) {
|
||||
matchView.front = null;
|
||||
dom.stack.replaceChildren(emptyState("No card waits", "No staged commit and no operator command waits for a decision."));
|
||||
return;
|
||||
}
|
||||
const [front, ...rest] = cards;
|
||||
const accept = h("button", {type: "button", class: "btn match-accept", disabled: Boolean(front.stale), ...named("Accept", front.stale ? `Accept: refused while the card is stale (${front.stale_reason})` : "Accept")}, icon("bi-check-lg"));
|
||||
const reject = h("button", {type: "button", class: "btn match-reject", ...named("Reject")}, icon("bi-x-lg"));
|
||||
if (shownOverview) {
|
||||
matchView.front = null;
|
||||
dom.stack.replaceChildren(overview(cards, open.length));
|
||||
return;
|
||||
}
|
||||
const [front, ...rest] = open;
|
||||
matchView.front = front;
|
||||
const accept = h("button", {type: "button", class: "btn match-accept", disabled: Boolean(front.stale), ...named("Accept", front.stale ? `Accept: refused while the card is stale (${front.stale_reason})` : "Accept (right arrow, swipe right)"), on: {click: () => acceptCard(front)}}, icon("bi-check-lg"));
|
||||
const reject = h("button", {type: "button", class: "btn match-reject", ...named("Reject", "Reject with feedback (left arrow, swipe left)"), on: {click: () => rejectCard(front)}}, icon("bi-x-lg"));
|
||||
const later = h("button", {type: "button", class: "btn match-later", disabled: !rest.length, ...named("Later", "Later: to the back of the stack (up arrow, swipe up)"), on: {click: () => laterCard(front)}}, icon("bi-arrow-up"));
|
||||
const peeks = rest.length ? h("div", {class: "match-peeks", role: "group", "aria-label": `${rest.length} more cards`}, rest.map(peekTab)) : null;
|
||||
const behind = rest.slice(0, MATCH_PEEKS).map((card, index) => {
|
||||
const sheet = h("div", {class: "match-behind", "aria-hidden": "true"});
|
||||
@@ -281,6 +494,7 @@
|
||||
const before = dom.stack.querySelector(".match-card.front");
|
||||
const scrolled = before && before.dataset.card === front.id ? before.querySelector(".match-body").scrollTop : 0;
|
||||
const shown = matchCard(front);
|
||||
dom.stack.replaceChildren(peeks, h("div", {class: "match-deck"}, behind, shown), h("div", {class: "match-actions"}, reject, accept));
|
||||
draggable(shown, front);
|
||||
dom.stack.replaceChildren(peeks, h("div", {class: "match-deck"}, behind, shown), h("div", {class: "match-actions"}, reject, later, accept));
|
||||
shown.querySelector(".match-body").scrollTop = scrolled;
|
||||
}
|
||||
@@ -38,7 +38,22 @@
|
||||
.match-actions .btn { width: 56px; height: 56px; border-radius: 50%; }
|
||||
.match-reject { color: var(--bad); }
|
||||
.match-accept { color: var(--ok); }
|
||||
.match-accept:disabled { opacity: 0.4; cursor: not-allowed; }
|
||||
.match-accept:disabled, .match-later:disabled { opacity: 0.4; cursor: not-allowed; }
|
||||
.match-head { touch-action: pan-y; cursor: grab; }
|
||||
.match-card.front[data-leaning] { transition: none; }
|
||||
.match-card.front[data-leaning="accept"] { box-shadow: inset 0 0 0 3px var(--ok); }
|
||||
.match-card.front[data-leaning="reject"] { box-shadow: inset 0 0 0 3px var(--bad); }
|
||||
.match-open-overview { display: inline-flex; align-items: center; gap: 4px; }
|
||||
.match-tally { min-width: 18px; padding: 0 5px; border-radius: 999px; background: var(--accent); color: var(--on-accent); font-size: var(--fs-xs); text-align: center; }
|
||||
.match-feedback { width: 100%; font-family: var(--mono); resize: vertical; }
|
||||
.match-overview { grid-row: 1 / -1; display: grid; align-content: start; gap: var(--sp-2); min-height: 0; overflow: auto; }
|
||||
.match-overview .actions { display: flex; flex-wrap: wrap; align-items: center; gap: var(--sp-1); }
|
||||
.match-decisions { display: grid; gap: var(--sp-1); margin: 0; padding: 0; list-style: none; }
|
||||
.match-decision { display: grid; gap: 4px; min-width: 0; padding: 6px 10px; border: 1px solid var(--line); border-radius: 10px; }
|
||||
.match-decision > .row { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; min-width: 0; }
|
||||
.match-decision-title { flex: 1 1 12rem; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.match-decision-feedback { margin: 0; padding: 6px 8px; border-radius: 8px; background: var(--sunken); font-family: var(--mono); font-size: var(--fs-sm); white-space: pre-wrap; overflow-wrap: anywhere; }
|
||||
.match-release-block { display: flex; align-items: center; gap: 6px; margin: 0; color: var(--warn); font-size: var(--fs-sm); }
|
||||
@media (max-width: 640px) {
|
||||
.match-place { grid-template-columns: minmax(0, 1fr); }
|
||||
.match-head { padding: var(--sp-2); }
|
||||
|
||||
@@ -0,0 +1,202 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest import mock
|
||||
|
||||
HERE = Path(__file__).resolve().parent
|
||||
sys.path[:0] = [str(HERE.parent), str(HERE)]
|
||||
|
||||
import hub_e2e_kit as base
|
||||
from hub_case import HubCase
|
||||
from hub_support import iso
|
||||
from kvb_orchestrator import batches, ledger, skill_scripts
|
||||
|
||||
OUT = Path(os.environ.get("E2E_OUT", "/tmp/hub-012-release-shots"))
|
||||
FIRST = "src/app.py"
|
||||
RELEASE_AT = 1366
|
||||
FLOW = """(async () => {@HELPERS@
|
||||
if (!@SIGNS@) {
|
||||
navigator.credentials.get = () => Promise.reject(new DOMException("The operator canceled.", "NotAllowedError"));
|
||||
}
|
||||
const posted = [];
|
||||
const send = window.fetch.bind(window);
|
||||
window.fetch = (path, init) => {
|
||||
if (["/api/sign", "/api/inbox/approve"].includes(String(path))) {
|
||||
posted.push([String(path), JSON.parse(init.body).items.map((item) => [item.kind, item.id, item.verb, item.channel || null, item.reason || null, item.to || null])]);
|
||||
}
|
||||
return send(path, init);
|
||||
};
|
||||
const card = () => document.querySelector("#main .match-card.front");
|
||||
const front = () => (card() ? card().dataset.card : null);
|
||||
if (!(await until(card, 8000))) {
|
||||
return {error: text(document.getElementById("main"))};
|
||||
}
|
||||
const key = (name) => document.body.dispatchEvent(new KeyboardEvent("keydown", {key: name, bubbles: true, cancelable: true}));
|
||||
const swipe = async (dx, dy) => {
|
||||
const head = card().querySelector(".match-head");
|
||||
const box = head.getBoundingClientRect();
|
||||
const [x, y] = [box.left + box.width / 2, box.top + 20];
|
||||
const at = (cx, cy) => ({bubbles: true, cancelable: true, pointerId: 11, pointerType: "touch", isPrimary: true, button: 0, clientX: cx, clientY: cy});
|
||||
head.dispatchEvent(new PointerEvent("pointerdown", at(x, y)));
|
||||
window.dispatchEvent(new PointerEvent("pointermove", at(x + dx / 2, y + dy / 2)));
|
||||
const leaning = card().dataset.leaning || "";
|
||||
window.dispatchEvent(new PointerEvent("pointerup", at(x + dx, y + dy)));
|
||||
await sleep(250);
|
||||
return leaning;
|
||||
};
|
||||
const order = [front()];
|
||||
const row = card().querySelector('.match-file[data-path="@FIRST@"] tr[data-line="3"]');
|
||||
row.scrollIntoView({block: "center"});
|
||||
const spot = row.getBoundingClientRect();
|
||||
row.dispatchEvent(new MouseEvent("contextmenu", {bubbles: true, cancelable: true, clientX: spot.left + 40, clientY: spot.top + 4, button: 2}));
|
||||
const field = await until(() => card().querySelector(".match-comment textarea"), 3000);
|
||||
field.value = "rename it";
|
||||
card().querySelector(".match-comment .match-save").click();
|
||||
await sleep(200);
|
||||
key("ArrowLeft");
|
||||
const feedback = await until(() => document.querySelector(".sheet-box .match-feedback"), 3000);
|
||||
const prefill = feedback ? feedback.value : null;
|
||||
feedback.value = `${prefill}\\nalso add a test`;
|
||||
document.querySelector(".sheet-box .match-feedback-reject").click();
|
||||
await until(() => front() !== order[0], 3000);
|
||||
order.push(front());
|
||||
key("ArrowUp");
|
||||
await until(() => front() !== order[1], 3000);
|
||||
order.push(front());
|
||||
const width = card().getBoundingClientRect().width;
|
||||
const leaned = await swipe(width * 0.4, 0);
|
||||
await until(() => front() !== order[2], 3000);
|
||||
order.push(front());
|
||||
const short = await swipe(width * 0.1, 0);
|
||||
const stayed = front() === order[3];
|
||||
await swipe(width * 0.4, 4);
|
||||
const overview = await until(() => document.querySelector("#main .match-overview"), 3000);
|
||||
const rows = overview ? all("#main .match-decision").map((item) => [item.dataset.card, item.dataset.verdict, text(item.querySelector(".match-decision-feedback"))]) : [];
|
||||
const release = document.querySelector("#main .match-release");
|
||||
const found = {order, prefill, leaned, short, stayed, rows, label: text(release), disabled: release.disabled, wide: document.documentElement.scrollWidth > window.innerWidth + 1};
|
||||
if (@RELEASE@) {
|
||||
const shown = new Set(all("#toasts .toast"));
|
||||
release.click();
|
||||
found.toast = await until(() => all("#toasts .toast").filter((node) => !shown.has(node)).map(text).find((entry) => entry.startsWith("Release")), 15000);
|
||||
found.emptied = @SIGNS@ ? Boolean(await until(() => document.querySelector("#main .match-stack .empty"), 15000)) : false;
|
||||
found.posted = posted;
|
||||
}
|
||||
return found;
|
||||
})()"""
|
||||
|
||||
|
||||
def patch(lines: int) -> str:
|
||||
rows = [f"@@ -1,{lines} +1,{lines + 1} @@"] + [f" line {number}" for number in range(1, lines + 1)]
|
||||
rows.insert(4, "+added line")
|
||||
return "\n".join(rows)
|
||||
|
||||
|
||||
@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium")
|
||||
class TestMatchRelease(HubCase):
|
||||
drive = base.OrchestratorE2ECase.drive
|
||||
authenticator = base.OrchestratorE2ECase.authenticator
|
||||
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
work = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(work.cleanup)
|
||||
self.work = Path(work.name)
|
||||
now = time.time()
|
||||
self.write_council({
|
||||
"work/s1/claim.json": {"office": "work/s1", "session": "s1", "runtime": "claude", "name": "Skills session", "since": iso(now - 86400), "beat": now, "work": "match"},
|
||||
"work/s2/claim.json": {"office": "work/s2", "session": "s2", "runtime": "claude", "name": "Stage session", "since": iso(now - 86400), "beat": now, "work": "i18n"},
|
||||
})
|
||||
self.rejected = self.review("feat: rejected stage", "feature/one", "Skills", [(FIRST, 20), ("docs/notes.md", 8)], now - 120)
|
||||
self.accepted = self.review("feat: accepted stage", "feature/two", "Stage", [("src/two.py", 12)], now - 60)
|
||||
folder = self.state / "firewall"
|
||||
folder.mkdir(parents=True, exist_ok=True)
|
||||
files = [{"path": "/home/op/.claude/settings.json", "exists": True, "sha256": "", "settings": {"sandbox": {"filesystem": {"denyRead": []}}}}]
|
||||
(folder / "view.json").write_text(json.dumps({"written": "2026-11-14T12:00:00+00:00", "files": files}), encoding="utf-8")
|
||||
self.write_council({"rasci.json": {"operator/ship": {"title": "make ship", "workdir": str(self.work), "description": "ship it", "check": "done", "roles": {"Skills": "A", "Operator": "R"}}}})
|
||||
self.cards = [f"review:{self.rejected}", f"review:{self.accepted}", "operator:operator/ship"]
|
||||
|
||||
def review(self, title: str, branch: str, agent: str, files: list[tuple[str, int]], created: float) -> str:
|
||||
"""Args:
|
||||
created: when the review was requested; the stamp has second
|
||||
resolution, so reviews requested in one second tie and their
|
||||
random ids would decide the card order.
|
||||
"""
|
||||
diff = [{"path": path, "status": "M", "mode": "100644", "additions": 1, "deletions": 0, "patch": patch(lines), "note": ""} for path, lines in files]
|
||||
page = self.page(f"{branch.replace('/', '-')}.html", "<!doctype html><title>p</title>")
|
||||
arguments = {**self.arguments(title, "", page), "worktree": f"/repo/.worktrees/{branch}", "branch": branch, "agent": agent, "diff": diff}
|
||||
with mock.patch.object(ledger, "stamp", return_value=iso(created)):
|
||||
result = self.tool("review_request", arguments)
|
||||
self.assertFalse(result["isError"], result)
|
||||
return result["structuredContent"]["id"]
|
||||
|
||||
def radio(self) -> list[list[str]]:
|
||||
return [args for script, args in self.scripts.calls if script == skill_scripts.RADIO]
|
||||
|
||||
def steps(self, browser: str, signs: bool) -> list[dict]:
|
||||
OUT.mkdir(parents=True, exist_ok=True)
|
||||
widths = sorted(base.WIDTHS, key=lambda size: size[0] == RELEASE_AT)
|
||||
steps = []
|
||||
for width, height in widths:
|
||||
flow = FLOW.replace("@HELPERS@", base.HELPERS).replace("@FIRST@", FIRST).replace("@SIGNS@", "true" if signs else "false")
|
||||
flow = flow.replace("@RELEASE@", "true" if width == RELEASE_AT else "false")
|
||||
steps.append({"width": width, "height": height, "url": f"http://localhost:{self.port}/?{width}#tasks/match", "wait": 1500, "probe": flow, "shot": str(OUT / f"{browser}-{width}-overview.png")})
|
||||
return steps
|
||||
|
||||
def check_flow(self, found: dict) -> None:
|
||||
reason = f"{FIRST}:3: rename it"
|
||||
self.assertNotIn("error", found, found)
|
||||
self.assertEqual(found["order"], [self.cards[0], self.cards[1], self.cards[2], self.cards[1]], found)
|
||||
self.assertEqual((found["prefill"], found["leaned"], found["short"], found["stayed"]), (reason, "accept", "accept", True), found)
|
||||
expected = [[self.cards[0], "reject", f"{reason}\nalso add a test"], [self.cards[1], "accept", None], [self.cards[2], "accept", None]]
|
||||
self.assertEqual(sorted(found["rows"]), sorted(expected), found)
|
||||
self.assertEqual((found["label"], found["disabled"], found["wide"]), ("Release 3 decisions", False, False), found)
|
||||
|
||||
def run_flow(self, browser: str, driver: str, binary: str, signs: bool) -> dict:
|
||||
with mock.patch.object(batches, "UNDO", 0.3):
|
||||
data = self.drive(self.steps(browser, signs), self.authenticator() if signs else None, driver, binary)
|
||||
if signs:
|
||||
self.settle(lambda: self.status(self.rejected) == "rejected" and self.status(self.accepted) == "approved")
|
||||
(OUT / f"{browser}-release.json").write_text(json.dumps(data, indent=1), encoding="utf-8")
|
||||
self.assertEqual([error for error in data["errors"] if "(style-src-elem)" not in error and "/favicon.ico" not in error], [])
|
||||
self.assertEqual(len(data["results"]), len(base.WIDTHS), data)
|
||||
for found in data["results"]:
|
||||
with self.subTest(browser=browser, release="toast" in found):
|
||||
self.check_flow(found)
|
||||
return data["results"][-1]
|
||||
|
||||
def test_chromium_swipes_three_cards_rejects_with_feedback_and_releases_with_one_signature(self):
|
||||
released = self.run_flow("chromium", "cdp.mjs", os.environ.get("CHROMIUM", "chromium"), signs=True)
|
||||
self.assertTrue(released["toast"].startswith("Release: 3 decisions"), released)
|
||||
self.assertTrue(released["emptied"], released)
|
||||
posted = [path for path, _ in released["posted"]]
|
||||
self.assertEqual(posted, ["/api/sign", "/api/inbox/approve"])
|
||||
items = sorted(released["posted"][1][1])
|
||||
told = f"{FIRST}:3: rename it\nalso add a test"
|
||||
self.assertEqual(items, sorted([["review", self.rejected, "reject", "call", told, "Skills"], ["review", self.accepted, "approve", None, None, None], ["operator", "operator/ship", "approve", None, None, None]]))
|
||||
stored = self.httpd.hub.reviews.get(self.rejected)
|
||||
self.assertEqual((stored["channel"], stored["reason"], stored["to"]), ("call", f"{FIRST}:3: rename it also add a test", "Skills"))
|
||||
self.assertIsNotNone(self.httpd.hub.reviews.get(self.accepted)["proof"])
|
||||
self.assertEqual([(job["task"], job["status"]) for job in self.httpd.hub.jobs.listed()], [("operator/ship", "queued")])
|
||||
self.settle(lambda: self.radio() != [])
|
||||
self.assertEqual(self.radio()[-1][:4], ["send", "call", "--to", "Skills session"])
|
||||
self.assertTrue(self.radio()[-1][-1].endswith(f"Reason: {FIRST}:3: rename it also add a test"), self.radio()[-1])
|
||||
|
||||
@unittest.skipUnless(shutil.which(os.environ.get("FIREFOX", "firefox")), "no Firefox")
|
||||
def test_firefox_swipes_three_cards_and_releases_nothing_unsigned(self):
|
||||
refused = self.run_flow("firefox", "bidi.mjs", os.environ.get("FIREFOX", "firefox"), signs=False)
|
||||
self.assertIn("not signed", refused["toast"], refused)
|
||||
self.assertEqual([path for path, _ in refused["posted"]], ["/api/sign"])
|
||||
time.sleep(0.5)
|
||||
self.assertEqual((self.status(self.rejected), self.status(self.accepted)), ("pending", "pending"))
|
||||
self.assertEqual((self.httpd.hub.jobs.listed(), self.radio()), ([], []))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
+143
-2
@@ -2,18 +2,23 @@ from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import secrets
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest import mock
|
||||
|
||||
from hub_case import HubCase
|
||||
from hub_support import GIT_ENV, HUB, REPO_ROOT
|
||||
from kvb_orchestrator import payloads
|
||||
from hub_support import APPROVAL, GIT_ENV, HUB, REPO_ROOT, key, signing
|
||||
from kvb_orchestrator import batches, payloads, skill_scripts
|
||||
|
||||
MATCH = REPO_ROOT / "skills" / "kvb-match" / "scripts" / "match.py"
|
||||
CLIENT = HUB / "client"
|
||||
FEEDBACK = "app.py:2: name it after what it holds\nnotes.md:3: say why"
|
||||
TOLD = "app.py:2: name it after what it holds notes.md:3: say why"
|
||||
|
||||
|
||||
def git(cwd: Path, *args: str) -> str:
|
||||
@@ -131,6 +136,142 @@ class TestMatchSkill(MatchCase):
|
||||
self.assertEqual(self.cards(), [])
|
||||
|
||||
|
||||
class TestMatchRelease(MatchCase):
|
||||
def radio(self) -> list[list[str]]:
|
||||
return [args for script, args in self.scripts.calls if script == skill_scripts.RADIO]
|
||||
|
||||
def stack(self) -> tuple[Path, str]:
|
||||
self.claim("s1", "Skills session")
|
||||
repo = staged_repo(self.work)
|
||||
review = self.add(repo)
|
||||
self.operator_row("operator/ship", "make ship", str(self.work))
|
||||
return repo, review
|
||||
|
||||
def decisions(self, review: str, verdict: str) -> list[dict]:
|
||||
"""Args:
|
||||
review: the review id of the commit card.
|
||||
verdict: accept or reject for the commit card; the command card
|
||||
is always rejected with FEEDBACK.
|
||||
|
||||
Returns:
|
||||
The entries the Match page releases, built as matchEntry builds
|
||||
them from the cards.
|
||||
"""
|
||||
commit, command = self.card(f"review:{review}"), self.card("operator:operator/ship")
|
||||
rejected = {"verb": "reject", "channel": "call", "reason": FEEDBACK}
|
||||
first = {"kind": "review", "id": commit["ref"], "verb": "approve", "label": "", "sha256": ""}
|
||||
second = {"kind": "operator", "id": command["ref"], "label": "", "sha256": command["sha256"], **rejected, "to": command["to"]}
|
||||
return [first if verdict == "accept" else {**first, **rejected, "to": commit["to"]}, second]
|
||||
|
||||
def verify(self, repo: Path, review: str) -> subprocess.CompletedProcess:
|
||||
argv = ["verify", "--port", str(self.port), "--approvers", str(self.approvers), "--replay", str(self.replay / "commit.json"), "--review", review, "--gate", "pass"]
|
||||
return subprocess.run([sys.executable, str(APPROVAL), *argv], cwd=repo, env={**os.environ, **GIT_ENV}, capture_output=True, text=True, timeout=60, check=False)
|
||||
|
||||
def test_every_card_names_the_addressee_its_inbox_entry_shows(self):
|
||||
_, review = self.stack()
|
||||
shown = {item["id"]: item["to"] for item in self.snapshot()["inbox"]}
|
||||
self.assertEqual({card["ref"]: card["to"] for card in self.cards()}, {review: "Skills", "operator/ship": "Skills"})
|
||||
self.assertEqual((shown[review], shown["operator/ship"]), ("Skills", "Skills"))
|
||||
|
||||
def test_one_signature_releases_an_accepted_commit_the_commit_check_verifies_and_a_rejection_told_by_call(self):
|
||||
repo, review = self.stack()
|
||||
entries = self.decisions(review, "accept")
|
||||
signer = self.pin()
|
||||
proof = self.signed(entries, signer)
|
||||
status, _, body = self.approve([entries[0], {**entries[1], "reason": "push it anyway"}], proof)
|
||||
self.assertEqual(status, 400, body)
|
||||
self.assertIn("list every approved item", body.decode())
|
||||
status, _, body = self.approve(entries, key(-8, "stranger").proof(proof["payload"], self.origin))
|
||||
self.assertEqual(status, 400, body)
|
||||
self.assertIn("not signed", body.decode())
|
||||
with mock.patch.object(batches, "UNDO", 0.4):
|
||||
status, _, body = self.approve(entries, proof)
|
||||
self.assertEqual(status, 202, body)
|
||||
self.assertEqual(self.call("POST", f"/api/inbox/undo/{json.loads(body)['id']}", b"", self.guard(self.host))[0], 200)
|
||||
self.assertIn("already used", self.approve(entries, proof)[2].decode())
|
||||
self.assertEqual(self.approve(entries, self.signed(entries, signer))[0], 202)
|
||||
self.settle(lambda: self.status(review) == "approved")
|
||||
self.settle(lambda: (skill_scripts.RASCI, ["set", "operator/ship", "--status", "stopped"]) in self.scripts.calls)
|
||||
self.settle(lambda: self.radio() != [])
|
||||
self.assertEqual(len(self.radio()), 1, self.radio())
|
||||
sent = self.radio()[0]
|
||||
self.assertEqual(sent[:6], ["send", "call", "--to", "Skills session", "--session", "Operator"])
|
||||
self.assertTrue(sent[6].endswith(f"Denied by the operator: operator command make ship in {self.work} (from Skills). Reason: {TOLD}"), sent)
|
||||
done = self.verify(repo, review)
|
||||
self.assertEqual(done.returncode, 0, done.stderr)
|
||||
self.assertIn(f"tree {git(repo, 'write-tree').strip()} on feature/match", done.stdout)
|
||||
self.assertNotIn(f"review:{review}", [card["id"] for card in self.cards()])
|
||||
|
||||
def test_a_rejected_commit_carries_its_feedback_by_call_and_the_commit_check_refuses_it(self):
|
||||
repo, review = self.stack()
|
||||
entries = self.decisions(review, "reject")
|
||||
with mock.patch.object(batches, "UNDO", 0.05):
|
||||
self.assertEqual(self.approve(entries, self.signed(entries, self.pin()))[0], 202)
|
||||
self.settle(lambda: self.status(review) == "rejected")
|
||||
self.settle(lambda: len(self.radio()) == 2)
|
||||
told = sorted(sent[6].split("] ", 1)[1] for sent in self.radio())
|
||||
self.assertEqual(told[0], f"Denied by the operator: commit feat: match on feature/match (from Skills). Reason: {TOLD}")
|
||||
self.assertEqual({tuple(sent[:4]) for sent in self.radio()}, {("send", "call", "--to", "Skills session")})
|
||||
stored = self.httpd.hub.reviews.get(review)
|
||||
self.assertEqual((stored["channel"], stored["reason"], stored["to"]), ("call", TOLD, "Skills"))
|
||||
done = self.verify(repo, review)
|
||||
self.assertEqual(done.returncode, 1, done.stdout)
|
||||
self.assertIn("rejected", done.stderr)
|
||||
|
||||
def test_a_command_release_binds_the_payload_hash_its_card_showed(self):
|
||||
body = self.work / "body.md"
|
||||
body.write_text("# Release\n", encoding="utf-8")
|
||||
command = f"gh issue create --body-file {body}"
|
||||
self.operator_row("operator/ship", command, str(self.work))
|
||||
card = self.card("operator:operator/ship")
|
||||
inbox = {"kind": "operator", "id": "operator/ship", "verb": "approve", "label": "", "sha256": card["sha256"]}
|
||||
entry = {**inbox, "payload": card["hash"]}
|
||||
row = signing.item_hash(signing.operator_item("operator/ship", command, str(self.work)))
|
||||
bound = signing.match_item("operator:operator/ship", card["hash"])
|
||||
self.assertEqual(self.prepare([inbox])["payload"]["items"], [row])
|
||||
self.assertEqual(sorted(self.prepare([entry])["payload"]["items"]), sorted([row, signing.item_hash(bound)]))
|
||||
signer = self.pin()
|
||||
bare = signer.proof(signing.approval_payload([row], secrets.token_hex(16), int(time.time()) + 60), self.origin)
|
||||
status, _, answer = self.approve([entry], bare)
|
||||
self.assertEqual(status, 400, answer)
|
||||
self.assertIn("list every approved item", answer.decode())
|
||||
for bad, code in (({**entry, "payload": "x"}, 400), ({**entry, "payload": "0" * 64}, 409), ({**entry, "verb": "reject", "channel": "call", "reason": "", "to": "Skills"}, 400)):
|
||||
with self.subTest(bad=bad):
|
||||
self.assertEqual(self.post_json("/api/sign", {"items": [bad]}, self.guard(self.host))[0], code)
|
||||
body.write_text("# Release, changed\n", encoding="utf-8")
|
||||
status, _, answer = self.post_json("/api/sign", {"items": [entry]}, self.guard(self.host))
|
||||
self.assertEqual(status, 409, answer)
|
||||
self.assertIn("stale", answer.decode())
|
||||
status, _, answer = self.post_json("/api/match/snapshot", {"task": "operator/ship"}, self.local())
|
||||
self.assertEqual(status, 200, answer)
|
||||
self.assertNotEqual(json.loads(answer)["hash"], card["hash"])
|
||||
self.assertEqual(self.post_json("/api/sign", {"items": [entry]}, self.guard(self.host))[0], 409)
|
||||
body.write_text("# Release\n", encoding="utf-8")
|
||||
status, _, answer = self.post_json("/api/match/snapshot", {"task": "operator/ship"}, self.local())
|
||||
self.assertEqual(json.loads(answer)["hash"], card["hash"], answer)
|
||||
with mock.patch.object(batches, "UNDO", 0.4):
|
||||
self.assertEqual(self.approve([entry], self.signed([entry], signer))[0], 202)
|
||||
body.write_text("# Release, changed after the release\n", encoding="utf-8")
|
||||
self.settle(lambda: any("payload file changed" in row["text"] for row in self.events("kinds=approval")["events"]))
|
||||
self.assertEqual(self.httpd.hub.jobs.listed(), [])
|
||||
body.write_text("# Release\n", encoding="utf-8")
|
||||
with mock.patch.object(batches, "UNDO", 0.05):
|
||||
self.assertEqual(self.approve([entry], self.signed([entry], signer))[0], 202)
|
||||
self.settle(lambda: self.httpd.hub.jobs.listed() != [])
|
||||
self.assertEqual([(job["task"], job["status"]) for job in self.httpd.hub.jobs.listed()], [("operator/ship", "queued")])
|
||||
|
||||
def test_a_commit_rejected_without_feedback_stays_a_plain_rejection(self):
|
||||
_, review = self.stack()
|
||||
entry = {"kind": "review", "id": review, "verb": "reject", "label": "", "sha256": ""}
|
||||
for bad in ({**entry, "channel": "call", "reason": "x"}, {**entry, "channel": "mayday", "reason": "x", "to": "Skills"}, {**entry, "reason": "x", "to": "Skills"}):
|
||||
with self.subTest(bad=bad):
|
||||
self.assertEqual(self.post_json("/api/sign", {"items": [bad]}, self.guard(self.host))[0], 400)
|
||||
with mock.patch.object(batches, "UNDO", 0.05):
|
||||
self.assertEqual(self.approve([entry], None)[0], 202)
|
||||
self.settle(lambda: self.status(review) == "rejected")
|
||||
self.assertEqual(self.radio(), [])
|
||||
|
||||
|
||||
class TestCommandCards(MatchCase):
|
||||
def payload_command(self) -> str:
|
||||
body = self.work / "body.md"
|
||||
|
||||
Reference in new issue
Block a user