diff --git a/docs/requirements/020-bulk-grant-mode.md b/docs/requirements/020-bulk-grant-mode.md index 24f2c97..15a5b7d 100644 --- a/docs/requirements/020-bulk-grant-mode.md +++ b/docs/requirements/020-bulk-grant-mode.md @@ -23,10 +23,13 @@ pass. and every option pick toggles its item into one shared selection (pressed state): inbox rows, Home, stream rows, the review sheet and the key `a`. A decision or decision row keeps the option picked for it; - picking the same option again takes it out. Grant n signs every - batchable item under one passkey signature, then asks one more + picking the same option again takes it out. Grant n first asks one signature per rule request and per red-gate review, one after the - other, since the server accepts neither inside a batch. Deny always + other, since the server accepts neither inside a batch, then signs + every batchable item under one passkey signature. A commit row brings + the pending reviews its `approval.py verify` steps check along, and + the server settles it after them, so it runs only once they are + approved (operator 2026-11-20: approve-and-run). Deny always acts at once with its reason; the Match deck and the palette keep their own confirmed release. Rejected: a unified tray where denials collect too; rules, red-gate reviews and option picks acting directly in Select @@ -103,7 +106,8 @@ flowchart TD - [ ] Unit: view store validation of `approval.mode`; page vm: a grant in Select toggles `ui.selected` without a post, a grant in Direct posts, an option pick collects with its label, a rule and a red-gate review - collect and get their own signature after the batch, the tray counts. + collect and get their own signature before the batch, a commit row + grants the reviews it verifies first, the tray counts. - [ ] Integration: n/a: the server and the signing path stay unchanged (decision 6). - [ ] E2E: Chromium and Firefox at 1920, 1366 and 390: the continuous diff diff --git a/orchestrator/client/signing.py b/orchestrator/client/signing.py index 113c73b..7c4e5a6 100644 --- a/orchestrator/client/signing.py +++ b/orchestrator/client/signing.py @@ -12,11 +12,13 @@ from pathlib import Path RP_ID = "localhost" VERSION = 1 LIFETIME = 900 +REVIEW_LIFETIME = 7200 RULE_LIFETIME = 366 * 86400 ALGORITHMS = {-7: "ES256", -8: "EdDSA", -257: "RS256"} HASH = re.compile(r"[0-9a-f]{64}") NONCE = re.compile(r"[0-9a-f]{32}") ID = re.compile(r"[0-9a-f]{16}") +VERIFY_STEP = re.compile(r"approval\.py verify(?=[^;&|]*--port (?P[0-9]+))(?=[^;&|]*--review (?P[0-9a-f]{16}))") CHAINED = re.compile(r"[;&|`$<>()\n\r]") OFFICE = re.compile(r"chair|[a-z0-9][a-z0-9._-]{0,63}/[a-z0-9][a-z0-9._-]{0,63}") SESSION = re.compile(r"(?!-)[A-Za-z0-9_-]{1,128}") @@ -110,6 +112,15 @@ def review_item(review_id: str, repo: str, worktree: str, branch: str, tree: str return {"kind": "review", "id": review_id, "repo": repo, "worktree": worktree, "branch": branch, "tree": tree} +def verified_reviews(command: str) -> list[str]: + """Returns: + The review ids the approval.py verify steps of an operator command + check, in order and each once: a commit row whose run needs them + approved first. + """ + return list(dict.fromkeys(step["review"] for step in VERIFY_STEP.finditer(command))) + + def operator_item(task: str, command: str, directory: str) -> dict: return {"kind": "operator", "id": task, "command": command, "directory": directory} @@ -755,7 +766,17 @@ def expiry(value: object, now: float, cap: int) -> int: return value -def checked_approval(payload: object, now: float) -> dict: +def lifetime(items: list[dict]) -> int: + """Returns: + How long an approval of items may live: REVIEW_LIFETIME when every + item is a review, whose approval names one exact tree and is used + once at the commit, so a commit row may run well after the clicks; + LIFETIME for any other mix. + """ + return REVIEW_LIFETIME if items and all(item.get("kind") == "review" for item in items) else LIFETIME + + +def checked_approval(payload: object, now: float, cap: int) -> dict: if not isinstance(payload, dict) or set(payload) != APPROVAL_KEYS or payload["v"] != VERSION or payload["kind"] != "approve": raise Refused("the payload is no approval") items = payload["items"] @@ -763,7 +784,7 @@ def checked_approval(payload: object, now: float) -> dict: raise Refused("the approval lists no item hashes") if not isinstance(payload["nonce"], str) or not NONCE.fullmatch(payload["nonce"]): raise Refused("the approval holds no nonce") - expiry(payload["expires"], now, LIFETIME) + expiry(payload["expires"], now, cap) return payload diff --git a/orchestrator/client/verifier.py b/orchestrator/client/verifier.py index 62b2ab9..03436e7 100644 --- a/orchestrator/client/verifier.py +++ b/orchestrator/client/verifier.py @@ -20,6 +20,7 @@ from signing import ( checked_approval, checked_rule, item_hash, + lifetime, load_pinned, rule_allows, ) @@ -301,7 +302,7 @@ def check(proof: object, item: dict, gate: str, trust: Trust, now: float) -> Non if not rule_allows(payload, item, gate, now): raise Refused("the signed rule does not match this item") return - checked_approval(payload, now) + checked_approval(payload, now, lifetime([item])) count = verify_assertion(proof["assertion"], payload, pinned(trust.approvers), trust.origin) digest = item_hash(item) if digest not in payload["items"]: diff --git a/orchestrator/kvb_orchestrator/approving.py b/orchestrator/kvb_orchestrator/approving.py index 445d707..a910267 100644 --- a/orchestrator/kvb_orchestrator/approving.py +++ b/orchestrator/kvb_orchestrator/approving.py @@ -95,7 +95,7 @@ class Approving: credentials = [key["id"] for key in self.keys()] if not items: return {"payload": None, "challenge": None, "credentials": credentials} - request = signing.approval_payload([signing.item_hash(item) for item in items], secrets.token_hex(16), int(time.time()) + signing.LIFETIME) + request = signing.approval_payload([signing.item_hash(item) for item in items], secrets.token_hex(16), int(time.time()) + signing.lifetime(items)) return {"payload": request, "challenge": signing.challenge(request), "credentials": credentials} def operator_proven(self, proof: object, item: dict) -> dict: @@ -147,7 +147,7 @@ class Approving: 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) + payload = signing.checked_approval(proof["payload"], now, signing.lifetime(signed)) except signing.Refused as error: raise ToolError(f"proof: {error}") from None if not isinstance(proof["assertion"], dict) or any(signing.item_hash(item) not in payload["items"] for item in signed): @@ -171,7 +171,12 @@ class Approving: self.log.add({"kind": "rule", "title": f"Rule grants: {item['title']}", "text": words, "ref": {"rule": rule["id"], "batch": batch["id"], "item": item["id"]}}) def apply(self, batch: dict) -> None: - for item in batch["items"]: + """Args: + batch: settled item by item; operator rows after every other + item, so a commit row's job never starts before the reviews + its verify steps check are decided. + """ + for item in sorted(batch["items"], key=lambda item: item["kind"] == "operator"): try: outcome = self.settle_item(item, batch["proof"] if item["signed"] is not None else None) except (OSError, ToolError) as error: diff --git a/orchestrator/kvb_orchestrator/inbox.py b/orchestrator/kvb_orchestrator/inbox.py index 418796d..a79edbf 100644 --- a/orchestrator/kvb_orchestrator/inbox.py +++ b/orchestrator/kvb_orchestrator/inbox.py @@ -21,7 +21,7 @@ SNOOZE_LIMIT = 8 * 86400 class Inbox: def inbox(self, now: float, tasks: dict[str, dict], directory: Directory) -> list[dict]: claims = read_claims(self.council) - base = {"agent": "", "to": "", "detail": "", "green": False, "gate": "", "score": "", "warnings": [], "options": [], "recommended": "", "multi": False, "check": "", "command": "", "directory": "", "sha256": "", "runnable": False, "deniable": False, "job": None, "rule": None, "dry_run": None, "diff": None, "settled": False, "answered": ""} + base = {"agent": "", "to": "", "detail": "", "green": False, "gate": "", "score": "", "warnings": [], "options": [], "recommended": "", "multi": False, "check": "", "command": "", "directory": "", "sha256": "", "runnable": False, "deniable": False, "job": None, "rule": None, "dry_run": None, "diff": None, "settled": False, "answered": "", "reviews": []} items = [] for review in self.reviews.pending(): created = iso_epoch(review["created"]) or now @@ -45,7 +45,7 @@ class Inbox: busy = row["task"] in held answer = self.answers.get(row["task"]) fields = {"answered": answer["label"] if answered(answer, row) else "", "title": row["command"], "detail": row["why"], "agent": adder(tasks[row["task"]]), "to": requester_of(claims, adder(tasks[row["task"]]))[0], "command": row["command"], "directory": row["directory"], "sha256": digest(row["command"]), "check": row["check"], "options": row["options"], "recommended": row["recommended"]} - state = {"runnable": runnable(row) and not busy, "deniable": not busy, "job": console_of(consoles.get(row["task"]))} + state = {"runnable": runnable(row) and not busy, "deniable": not busy, "job": console_of(consoles.get(row["task"])), "reviews": self.linked(row["command"])} items.append({**base, "kind": "operator", "id": row["task"], "ts": self.watch.first(row["task"], now), **fields, **state}) listed = {row["task"] for row in rows} for task, job in consoles.items(): @@ -58,6 +58,14 @@ class Inbox: item.update(pinned=mark["pinned"], until=mark["until"] if mark["until"] > now else 0.0, held=self.batches.holds(item["kind"], item["id"])) return sorted(items, key=lambda item: (not item["pinned"], -item["ts"], item["id"])) + def linked(self, command: str) -> list[dict]: + """Returns: + {"id", "status", "gate"} of each review the approval.py verify + steps of command check; status unknown for one the hub lacks. + """ + records = {review_id: self.reviews.get(review_id) for review_id in signing.verified_reviews(command)} + return [{"id": review_id, "status": record["status"] if record else "unknown", "gate": record.get("gate", "") if record else ""} for review_id, record in records.items()] + def mark(self, body: bytes) -> dict: payload = decode(body) expect(payload, ("kind", "id", "until", "pinned")) diff --git a/orchestrator/templates/page-inbox.js b/orchestrator/templates/page-inbox.js index 88ad402..117c71e 100644 --- a/orchestrator/templates/page-inbox.js +++ b/orchestrator/templates/page-inbox.js @@ -158,6 +158,26 @@ const denialOf = (item, reason) => ({...entryOf(item, "reject", ""), channel: "post", reason, to: item.to}); const pickable = (item) => !item.held && (collectable(item) || deniable(item)); + const unsettled = (item) => item.reviews.filter((review) => review.status !== "approved"); + + /** + * @param {Object[]} items the entries to grant. + * @returns {Object[]} items after the pending reviews that their commit rows verify and that are not among them yet. + */ + function withReviews(items) { + const keys = new Set(items.map(keyOf)); + const linked = new Set(items.flatMap((item) => unsettled(item).map((review) => review.id))); + return [...state.inbox.filter((entry) => entry.kind === "review" && linked.has(entry.id) && !entry.held && !keys.has(keyOf(entry))), ...items]; + } + + const DENY_NOTE = "Every entry and every full command that gets denied; each requester gets its denial and the reason by post. After the click the passkey signs the whole selection once; then 3 s remain to undo."; + + function grantNote(alone, batched) { + const solos = alone ? ` Each rule and each red-gate review first asks its own signature, one after the other (${alone}).` : ""; + const rest = batched ? ` ${alone ? "Then the" : "The"} passkey signs the rest once, commit rows settling after the reviews they verify.` : ""; + return `Every entry and every full command that gets granted.${solos}${rest} Each signature leaves 3 s to undo.`; + } + function bulk(items, label, deny) { const usable = items.filter(deny ? deniable : batchable); const alone = deny ? [] : items.filter(solo); @@ -175,19 +195,16 @@ const reason = deny ? h("textarea", {class: "field", maxlength: DENY_REASON, rows: 3, placeholder: "e.g. make the gate green first"}) : null; confirm.addEventListener("click", async () => { closeSheet(); - if (usable.length && !(await submit(usable.map((item) => (deny ? denialOf(item, reason.value) : entryOf(item, "approve", labelOf(item)))), `${label}: ${usable.length} entries`))) { - return; - } for (const item of alone) { if (!(await grantSolo(item))) { return; } } + if (usable.length) { + await submit(usable.map((item) => (deny ? denialOf(item, reason.value) : entryOf(item, "approve", labelOf(item)))), `${label}: ${usable.length} entries`); + } }); - const note = deny - ? "Every entry and every full command that gets denied; each requester gets its denial and the reason by post. After the click the passkey signs the whole selection once; then 3 s remain to undo." - : `Every entry and every full command that gets granted. After the click the passkey signs the whole selection once; then 3 s remain to undo.${alone.length ? ` Each rule and each red-gate review then asks its own signature, one after the other (${alone.length}).` : ""}`; - openSheet(label, [h("p", {class: "muted"}, note), h("ul", {class: "mini"}, rows), ...(deny ? [reasonChips(reason), h("label", {class: "deny-reason"}, "Reason (optional, every requester reads it)", reason)] : []), + openSheet(label, [h("p", {class: "muted"}, deny ? DENY_NOTE : grantNote(alone.length, usable.length)), h("ul", {class: "mini"}, rows), ...(deny ? [reasonChips(reason), h("label", {class: "deny-reason"}, "Reason (optional, every requester reads it)", reason)] : []), h("div", {class: "actions"}, h("span", {class: "spacer"}), btn("Cancel", "btn ghost", closeSheet), confirm)], false); (reason || confirm).focus(); } @@ -202,7 +219,7 @@ const grantable = chosen.filter(collectable); return { chosen, - grant: h("button", {type: "button", class: "btn small primary", ...named(`Grant selection (${grantable.length})`), disabled: !grantable.length || ui.busy, on: {click: () => bulk(chosen, "Grant selection", false)}}, icon("bi-check2-square"), `Grant ${grantable.length}`), + grant: h("button", {type: "button", class: "btn small primary", ...named(`Grant selection (${grantable.length})`), disabled: !grantable.length || ui.busy, on: {click: () => bulk(withReviews(chosen), "Grant selection", false)}}, icon("bi-check2-square"), `Grant ${grantable.length}`), deny: h("button", {type: "button", class: "menu-item danger", ...named(`Deny selection (${denials.length})`, `Deny selection (${denials.length}): each requester gets its denial and an optional reason by post, one passkey signature, 3 s to undo`), disabled: !denials.length || ui.busy, on: {click: () => bulk(chosen, "Deny selection", true)}}, icon("bi-x-square"), `Deny ${denials.length}`), green: h("button", {type: "button", class: "menu-item", ...named(`Grant all green (${green.length})`), disabled: !green.length || ui.busy, on: {click: () => bulk(green, "Grant all green", false)}}, icon("bi-check2-all"), `Grant all green ${green.length}`), }; @@ -238,6 +255,26 @@ } } + function reviewsPill(item) { + if (!item.reviews.length) { + return null; + } + const waiting = unsettled(item).length; + return pill(`reviews ${item.reviews.length - waiting}/${item.reviews.length} approved`, waiting ? "neutral" : "ok"); + } + + function runButton(item) { + const waiting = unsettled(item); + if (!waiting.length) { + return iconBtn("bi-play-fill", "Run", "btn small primary", () => approveOne(item)); + } + const stuck = waiting.some((review) => review.status !== "pending"); + const why = stuck + ? "A review its commit verifies is rejected or unknown to this hub: the run would fail at its verify step" + : `Approve the ${waiting.length} reviews its commit verifies, then run it: each red-gate review asks its own signature, the rest goes with the row in one`; + return h("button", {type: "button", class: "btn small primary", ...named(`Approve ${waiting.length} and run`, why), disabled: stuck || ui.busy, on: {click: () => (collecting(item) ? collect(item) : bulk(withReviews([item]), "Approve and run", false))}}, icon("bi-play-fill"), `Approve ${waiting.length} and run`); + } + function actionsFor(item) { if (item.held) { return [h("span", {class: "muted"}, "takes effect …")]; @@ -250,7 +287,7 @@ } else if (item.kind === "decision" && item.recommended) { grant(h("button", {type: "button", class: "btn small primary", ...named(revealed(`Recommendation: ${shownPick(item.recommended)}`)), on: {click: () => approveOne(item)}}, icon("bi-check-lg"), revealed(shownPick(item.recommended)))); } else if (item.kind === "operator" && item.runnable) { - grant(iconBtn("bi-play-fill", "Run", "btn small primary", () => approveOne(item))); + grant(runButton(item)); } else if (item.kind === "rule") { grant(h("button", {type: "button", class: "btn small primary", ...named("Accept", "Accept: the passkey signs exactly this rule, then it applies"), on: {click: () => approveOne(item)}}, icon("bi-shield-check"), "Accept")); } @@ -279,6 +316,7 @@ asked(item) ? pill("Decision", KIND_TONES.decision) : pill(ITEM_LABELS[item.kind], KIND_TONES[item.kind]), answerOf(item) ? pill(revealed(`answered: ${answerOf(item)}`), "ok") : null, item.kind === "review" ? pill(item.gate === "pass" ? "Gate green" : "Gate red", item.gate === "pass" ? "ok" : "bad") : null, + reviewsPill(item), item.warnings.map((warning) => pill(warning, "bad")), item.pinned ? pill("pinned", "violet") : null, item.until ? pill(`until ${absolute.format(stampOf(item.until))}`, "neutral") : null), diff --git a/skills/kvb-git-diff/SKILL.md b/skills/kvb-git-diff/SKILL.md index 16f16ff..f4870b6 100644 --- a/skills/kvb-git-diff/SKILL.md +++ b/skills/kvb-git-diff/SKILL.md @@ -48,6 +48,10 @@ once the operator's pinned passkey signature over it verifies here. `rejected`, or the tree changed: no commit; report the printed reason. `superseded`: a newer request for the same worktree and branch replaced it; wait on the review its `superseded_by` names. + A review's approval holds two hours. A `kvb-org-operator` commit row + chaining these steps runs only once every review is approved: + `operator.py run` skips it until then, and its hub card offers + `Approve n and run`. No kvb-orchestrator tools, or the verify step refused: ask the calling skill's approval question in chat. diff --git a/skills/kvb-org-operator/scripts/operator.py b/skills/kvb-org-operator/scripts/operator.py index e066cd5..74ffdf5 100755 --- a/skills/kvb-org-operator/scripts/operator.py +++ b/skills/kvb-org-operator/scripts/operator.py @@ -47,8 +47,11 @@ Args: directory, command, reason and check in a label column (control characters made visible; on a terminal values wrap under their column, and unless NO_COLOR is set the separator is bold, labels dim, - the command bold cyan and preview commands yellow), then a preview - of what the command changes, its output indented, and asks [y]es / + the command bold cyan and preview commands yellow). A commit row + whose approval.py verify steps name a review the Agent Orchestrator + on their --port does not hold approved, or whose hub does not + answer, is skipped with the reason and stays open (unready()). + Otherwise a preview of what the command changes, its output indented, and asks [y]es / [s]kip / [c]ancel / [d]iff / [q]uit; d shows the full diff. A repo whose git config names filter commands gets no preview. c asks for a reason (empty: back to the question), sets the row as shown stopped @@ -152,6 +155,7 @@ import subprocess import termios import textwrap import time +import urllib.request from collections.abc import Callable from pathlib import Path from types import ModuleType @@ -162,6 +166,11 @@ WATCH = SKILLS / "kvb-org-organize" / "scripts" / "watch.py" QUEUE = SKILLS / "kvb-org-queue" / "scripts" / "queue.py" RADIO = SKILLS / "kvb-org-radio" / "scripts" / "radio.py" COUNCIL = SKILLS / "kvb-org-organize" / "scripts" / "council.py" +HUB_API = Path.home() / ".local" / "share" / "kvb-orchestrator" / "client" / "hub_api.py" +VERIFY_STEP = re.compile(r"approval\.py verify(?=[^;&|]*--port (?P[0-9]+))(?=[^;&|]*--review (?P[0-9a-f]{16}))") +HUB_SECONDS = 5 +PORT_LIMIT = 65535 +REVIEWS_SHOWN = 5 HOLD_KIND = "operator" HOLD_SESSION = "Operator" NOT_RUN = 75 @@ -961,6 +970,52 @@ def cmd_granted(rasci: ModuleType, args: argparse.Namespace) -> int: return subprocess.run(args.argv, cwd=row["directory"], check=False).returncode +def unapproved(command: str) -> list[str] | None: + """Returns: + The review ids the approval.py verify steps of command name whose + review the Agent Orchestrator on their --port does not hold approved, + in order; [] when every one is approved or command names none; None + when the hub does not answer, a --port lies above PORT_LIMIT (the + resolver would wrap it onto another port), or + the client's hub_api.py, whose + loopback opener sends no proxy and follows no redirect, is missing, + so the commit would fail at its verify. + """ + steps = list(VERIFY_STEP.finditer(command)) + if not steps: + return [] + if not HUB_API.is_file(): + return None + api = module("kvb_operator_hub_api", HUB_API) + waiting = [] + for step in steps: + port = int(step["port"]) + if port > PORT_LIMIT: + return None + try: + status = api.call(urllib.request.Request(f"{api.base_url(port)}/api/reviews/{step['review']}", headers=api.GUARD), HUB_SECONDS).get("status") + except (OSError, ValueError, TypeError): + return None + if status != "approved": + waiting.append(step["review"]) + return list(dict.fromkeys(waiting)) + + +def unready(row: dict) -> str | None: + """Returns: + Why run skips row for now: reviews its commit verifies that the + operator has not approved yet, or a hub that does not answer about + them; None when it may run. + """ + waiting = unapproved(row["command"]) + if waiting is None: + return f"the hub does not answer about the reviews its commit verifies, or {HUB_API} is missing; start or install it, then run again" + if not waiting: + return None + more = " …" if len(waiting) > REVIEWS_SHOWN else "" + return f"{len(waiting)} reviews its commit verifies are not approved yet ({', '.join(waiting[:REVIEWS_SHOWN])}{more}); approve them in the hub, then run again" + + def cmd_run(rasci: ModuleType, args: argparse.Namespace) -> int: shell = os.environ.get("SHELL") if not shell: @@ -982,6 +1037,10 @@ def cmd_run(rasci: ModuleType, args: argparse.Namespace) -> int: print(field("command", visible(row["command"], ""), "command")) print(field("why", visible(row["why"] or "-", ""))) print(field("check", visible(check, "")), flush=True) + why = unready(row) + if why: + print(f"waits {name}: {why}; the row stays open") + continue holdable = heavy_row(watch, cfg, row) answer, reason = decide(row, holdable, typed) if answer == "q" or (answer == "c" and reason is None): diff --git a/tests/test_hub_approval.py b/tests/test_hub_approval.py index 70d35dd..5a6e160 100644 --- a/tests/test_hub_approval.py +++ b/tests/test_hub_approval.py @@ -150,6 +150,23 @@ class TestApproval(unittest.TestCase): self.approvers.write_text('{"credentials": []}', encoding="utf-8") self.refused(signer.proof(self.payload([self.item], int(self.now) + 60), ORIGIN), self.item, "", "no key is pinned") + def test_a_review_approval_lives_two_hours_and_every_other_kind_fifteen_minutes(self): + signer = key(-7, "main") + signer.pin(self.approvers, ORIGIN) + tree = signing.review_item("0123456789abcdef", "/repo/.git", "/repo", "main", "a" * 40) + later = int(self.now) + signing.LIFETIME + 60 + verifier.check(signer.proof(self.payload([tree], later), ORIGIN), tree, "pass", self.trust, self.now) + self.refused(signer.proof(self.payload([tree], int(self.now) + signing.REVIEW_LIFETIME + 60), ORIGIN), tree, "pass", "too far") + self.refused(signer.proof(self.payload([self.item, tree], later), ORIGIN), self.item, "", "too far") + self.assertEqual((signing.lifetime([tree]), signing.lifetime([tree, self.item]), signing.lifetime([])), (signing.REVIEW_LIFETIME, signing.LIFETIME, signing.LIFETIME)) + + def test_the_operator_runner_reads_the_verify_steps_of_a_commit_row_as_the_hub_does(self): + runner = (HUB.parent / "skills" / "kvb-org-operator" / "scripts" / "operator.py").read_text(encoding="utf-8") + self.assertIn(f'VERIFY_STEP = re.compile(r"{signing.VERIFY_STEP.pattern}")', runner) + first, second = "a" * 16, "b" * 16 + command = f"approval.py verify --port 1 --review {first} && approval.py verify --review {second} --gate pass --port 2; approval.py verify --port 1 --review {first}; approval.py verify --review {'c' * 16}; echo --port 3" + self.assertEqual(signing.verified_reviews(command), [first, second]) + def test_one_bulk_signature_serves_each_listed_item_once(self): signer = key(-8, "main") signer.pin(self.approvers, ORIGIN) diff --git a/tests/test_hub_console.py b/tests/test_hub_console.py index b1eb3e7..4de2b6f 100644 --- a/tests/test_hub_console.py +++ b/tests/test_hub_console.py @@ -8,7 +8,7 @@ from unittest import mock from hub_case import HubCase from hub_support import HUB -from kvb_orchestrator import batches, skill_scripts +from kvb_orchestrator import batches, jobs, skill_scripts COMMAND = "echo hi" DIGEST = hashlib.sha256(COMMAND.encode()).hexdigest() @@ -29,6 +29,29 @@ class TestHubConsole(HubCase): def dismiss(self, payload: object, headers: dict[str, str]) -> int: return self.post_json("/api/inbox/dismiss", payload, headers)[0] + def test_a_commit_row_lists_the_reviews_it_verifies_and_queues_its_job_only_after_them(self): + self.claim("s1", "Skills session") + review = self.request("feat: x", "notes") + command = f"python3 approval.py verify --port 8737 --review {review} --gate pass && python3 approval.py verify --port 8737 --review {'f' * 16} --gate pass && git commit -m x" + row = {"title": command, "workdir": str(self.outside), "description": "commit", "check": "manual", "status": "queued", "roles": {"Operator": "R", "Skills session": "A"}} + self.write_council({"rasci.json": {"operator/commit": row}}) + self.assertEqual(self.item("operator/commit")["reviews"], [{"id": review, "status": "pending", "gate": "pass"}, {"id": "f" * 16, "status": "unknown", "gate": ""}]) + self.assertEqual(self.item(review)["reviews"], []) + seen = [] + queue = jobs.Jobs.queue_job + + def spy(hub, item, proof): + seen.append(hub.reviews.get(review)["status"]) + return queue(hub, item, proof) + + signer = self.pin() + entries = [self.entry("operator", "operator/commit", "", hashlib.sha256(command.encode()).hexdigest()), self.entry("review", review, "", "")] + with mock.patch.object(batches, "UNDO", 0.05), mock.patch.object(jobs.Jobs, "queue_job", spy): + self.assertEqual(self.approve(entries, self.signed(entries, signer))[0], 202) + self.settle(lambda: self.item("operator/commit")["job"] is not None) + self.assertEqual(seen, ["approved"]) + self.assertEqual(self.item("operator/commit")["reviews"][0]["status"], "approved") + def test_the_job_console_stays_under_the_command_until_the_row_is_dismissed(self): self.claim("s1", "Skills session") self.register("queued") diff --git a/tests/test_hub_decision_rows.py b/tests/test_hub_decision_rows.py index b557f6a..af55aa9 100644 --- a/tests/test_hub_decision_rows.py +++ b/tests/test_hub_decision_rows.py @@ -34,7 +34,7 @@ const document = { createElement: (tag) => new El(tag), createElementNS: (ns, tag) => new El(tag), }; const now = 1_800_000_000; -const base = {agent: "Stage 2.0", to: "Stage 2.0", detail: "", green: false, gate: "", score: "", warnings: [], options: [], recommended: "", check: "", command: "", directory: "/repo", sha256: "s", runnable: false, deniable: true, job: null, rule: null, dry_run: null, diff: null, pinned: false, until: 0, held: false, ts: now}; +const base = {agent: "Stage 2.0", to: "Stage 2.0", detail: "", green: false, gate: "", score: "", warnings: [], options: [], recommended: "", check: "", command: "", directory: "/repo", sha256: "s", runnable: false, deniable: true, job: null, rule: null, dry_run: null, diff: null, pinned: false, until: 0, held: false, ts: now, reviews: []}; const question = "decide: keep or remove the donation section"; const options = [{label: "Keep", description: "the section ships with the IAM PR"}, {label: "Remove", description: "drop it before the PR"}]; const items = { diff --git a/tests/test_hub_grant_mode.py b/tests/test_hub_grant_mode.py index d4f0a0c..23c65ff 100644 --- a/tests/test_hub_grant_mode.py +++ b/tests/test_hub_grant_mode.py @@ -37,7 +37,7 @@ const document = { createElement: (tag) => new El(tag), createElementNS: (ns, tag) => new El(tag), }; const now = 1_800_000_000; -const base = {agent: "Store", to: "Store", detail: "", green: false, gate: "", score: "", warnings: [], options: [], recommended: "", command: "", directory: "/repo", sha256: "s", runnable: false, deniable: false, job: null, rule: null, dry_run: null, diff: null, pinned: false, until: 0, held: false, ts: now}; +const base = {agent: "Store", to: "Store", detail: "", green: false, gate: "", score: "", warnings: [], options: [], recommended: "", command: "", directory: "/repo", sha256: "s", runnable: false, deniable: false, job: null, rule: null, dry_run: null, diff: null, pinned: false, until: 0, held: false, ts: now, reviews: []}; const items = { green: {...base, kind: "review", id: "r-green", title: "feat: green", gate: "pass", green: true}, red: {...base, kind: "review", id: "r-red", title: "feat: red", gate: "fail"}, @@ -156,6 +156,21 @@ const byName = (node, label) => buttons(node).find((button) => button.getAttribu signing = true; await buttons(sheet[2]).find((button) => text(button).startsWith("Grant ")).click(); results.all_granted = take(); + const commit = {...base, kind: "operator", id: "operator/commit", title: "git commit", command: "git commit", runnable: true, deniable: true, reviews: [{id: "r-green", status: "pending", gate: "pass"}, {id: "r-red", status: "pending", gate: "fail"}, {id: "r-old", status: "approved", gate: "pass"}]}; + state.inbox = [...Object.values(items).map((item) => ({...item})), commit]; + const runOf = (row) => actionsFor(row)[0]; + results.run_label = runOf(commit).getAttribute("aria-label"); + await runOf(commit).click(); + results.run_collected = {...take(), sheets: sheets.splice(0).length}; + ui.selected.clear(); + mode.value = "direct"; + await runOf(commit).click(); + const runSheet = sheets.splice(0)[0]; + results.run_note = text(runSheet[0]); + await buttons(runSheet[2]).find((button) => text(button).startsWith("Grant ")).click(); + results.run_granted = take(); + results.run_stuck = runOf({...commit, reviews: [{id: "r-gone", status: "rejected", gate: "pass"}]}).getAttribute("disabled"); + results.run_plain = runOf({...commit, reviews: [{id: "r-old", status: "approved", gate: "pass"}]}).getAttribute("aria-label"); console.log(JSON.stringify(results)); })().catch((error) => { console.error(error && error.stack || error); process.exit(1); }); `; @@ -214,16 +229,24 @@ class TestGrantMode(unittest.TestCase): self.assertEqual((self.data["option_removed"]["selected"], self.data["option_removed"]["pressed"]), ([], [])) self.assertEqual(self.data["option_row"], {"pressed": ["Yes"], "batchable": True}) - def test_grant_n_signs_the_batch_once_then_each_rule_and_red_gate_alone(self): + def test_grant_n_signs_each_rule_and_red_gate_alone_first_then_the_batch_once(self): self.assertEqual(self.data["all"]["selected"], ["decision:d-1", "decision:d-2", "operator:operator/ask", "review:r-green", "review:r-red", "rule:1123456789abcdef"]) self.assertEqual((self.data["all"]["proofs"], self.data["all"]["accepts"]), ([], [])) self.assertEqual(self.data["all_grant"], "Grant selection (6)") - self.assertTrue(self.data["all_note"].endswith("Each rule and each red-gate review then asks its own signature, one after the other (2)."), self.data["all_note"]) + self.assertIn("Each rule and each red-gate review first asks its own signature, one after the other (2). Then the passkey signs the rest once", self.data["all_note"]) granted = self.data["all_granted"] - self.assertEqual(granted["proofs"], [["review:r-green", "decision:d-1", "decision:d-2", "operator:operator/ask"], ["review:r-red"]]) - self.assertEqual(granted["labels"], [["", "B", "B", "Yes"], [""]]) + self.assertEqual(granted["proofs"], [["review:r-red"], ["review:r-green", "decision:d-1", "decision:d-2", "operator:operator/ask"]]) + self.assertEqual(granted["labels"], [[""], ["", "B", "B", "Yes"]]) self.assertEqual((granted["accepts"], granted["selected"]), (["1123456789abcdef"], [])) + def test_a_commit_row_approves_the_reviews_it_verifies_before_it_runs(self): + self.assertEqual(self.data["run_label"], "Approve 2 and run") + self.assertEqual(self.data["run_collected"]["selected"], ["operator:operator/commit"]) + self.assertEqual((self.data["run_collected"]["proofs"], self.data["run_collected"]["sheets"]), ([], 0)) + self.assertIn("first asks its own signature, one after the other (1). Then the passkey signs the rest once, commit rows settling after the reviews they verify.", self.data["run_note"]) + self.assertEqual(self.data["run_granted"]["proofs"], [["review:r-red"], ["review:r-green", "operator:operator/commit"]]) + self.assertEqual((self.data["run_stuck"], self.data["run_plain"]), ("", "Run")) + def test_one_split_grants_the_selection_and_its_menu_holds_the_rest(self): tray = self.data["tray"] self.assertEqual(tray["main"], "Grant selection (4)") diff --git a/tests/test_hub_inbox_gone.py b/tests/test_hub_inbox_gone.py index d299068..1e121fb 100644 --- a/tests/test_hub_inbox_gone.py +++ b/tests/test_hub_inbox_gone.py @@ -27,7 +27,7 @@ const document = { createElement: () => new El(), createElementNS: () => new El(), }; const now = 1_800_000_000; -const base = {agent: "Store", to: "Store", detail: "", green: false, gate: "", score: "", warnings: [], options: [], recommended: "", command: "", directory: "/repo", sha256: "s", runnable: true, deniable: true, job: null, rule: null, dry_run: null, diff: null, pinned: false, until: 0, held: false, ts: now}; +const base = {agent: "Store", to: "Store", detail: "", green: false, gate: "", score: "", warnings: [], options: [], recommended: "", command: "", directory: "/repo", sha256: "s", runnable: true, deniable: true, job: null, rule: null, dry_run: null, diff: null, pinned: false, until: 0, held: false, ts: now, reviews: []}; const row = (id, command, extra) => ({...base, kind: "operator", id, title: command, command, ...extra}); const items = { gone: row(GONE, "git merge --no-ff --no-verify -F msg"), diff --git a/tests/test_hub_operator_tasks.py b/tests/test_hub_operator_tasks.py index 63a9e53..2c290f4 100644 --- a/tests/test_hub_operator_tasks.py +++ b/tests/test_hub_operator_tasks.py @@ -106,7 +106,7 @@ const classes = (node) => String(node.className || node.attrs.class || "").split const labels = (node) => all(node).filter((el) => el.tag === "button").map((el) => el.getAttribute("aria-label") || el.textContent); const calls = {proofs: [], posts: [], sheets: [], radio: [], signs: []}; const now = 1_800_000_000; -const base = {agent: "Skills", to: "Skills", detail: "", green: true, gate: "", score: "", warnings: [], options: [], recommended: "", command: "", directory: "", sha256: "", runnable: false, deniable: false, job: null, rule: null, dry_run: null, diff: null, pinned: false, until: 0, held: false, ts: now - 60}; +const base = {agent: "Skills", to: "Skills", detail: "", green: true, gate: "", score: "", warnings: [], options: [], recommended: "", command: "", directory: "", sha256: "", runnable: false, deniable: false, job: null, rule: null, dry_run: null, diff: null, pinned: false, until: 0, held: false, ts: now - 60, reviews: []}; const operator = {...base, kind: "operator", id: "operator/ship", title: "make ship", command: "make ship", directory: "/repo", detail: "release the build", runnable: true, deniable: true, green: false, sha256: "abc"}; const review = {...base, kind: "review", id: "0123456789abcdef", title: "feat: x", detail: "feature/x", gate: "pass", score: "🎯 95", directory: "/repo", diff: 4}; const ask = {...base, kind: "ask", id: "1123456789abcdef", title: "Bash: git commit -m x", command: "git commit -m x", directory: "/repo", deniable: true}; diff --git a/tests/test_operator.py b/tests/test_operator.py index b7b444c..b3c48d1 100644 --- a/tests/test_operator.py +++ b/tests/test_operator.py @@ -2,16 +2,19 @@ from __future__ import annotations +import http.server import json import os import pty import select import shutil import signal +import socket import subprocess import sys import tempfile import termios +import threading import time import unittest from pathlib import Path @@ -381,6 +384,55 @@ class TestOperator(unittest.TestCase): self.assertNotIn("\x1b", out) self.assertEqual(self._open(), ["operator/second"]) + def test_run_skips_a_commit_row_while_a_review_it_verifies_is_unapproved_or_the_hub_is_silent(self): + statuses = {"a" * 16: "pending", "b" * 16: "approved"} + + class Hub(http.server.BaseHTTPRequestHandler): + def do_GET(self): + review = self.path.rsplit("/", 1)[-1] + if review == "c" * 16: + self.send_response(302) + self.send_header("Location", f"/api/reviews/{'b' * 16}") + self.end_headers() + return + guarded = self.headers.get("X-Kvb-Orchestrator") == "1" + body = json.dumps({"status": statuses.get(review) if guarded else "approved"}).encode() + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.end_headers() + self.wfile.write(body) + + def log_message(self, *_): + return + + hub = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Hub) + self.addCleanup(hub.server_close) + threading.Thread(target=hub.serve_forever, daemon=True).start() + self.addCleanup(hub.shutdown) + silent = socket.socket() + silent.bind(("127.0.0.1", 0)) + dead = silent.getsockname()[1] + silent.close() + port = hub.server_address[1] + work = self.base / "work" + work.mkdir() + rows = {"pending": (port, "a"), "huge": (65536 + port, "b"), "approved": (port, "b"), "offline": (dead, "b"), "redirect": (port, "c")} + for slug, (target, letter) in rows.items(): + self._add(slug, work, f"true approval.py verify --port {target} --review {letter * 16} && touch ran-{slug}", "commit", "manual") + missing = self._feed("") + self.assertIn("waits operator/approved: the hub does not answer about the reviews its commit verifies, or", missing.stdout) + client = self.home / ".local" / "share" / "kvb-orchestrator" / "client" + client.mkdir(parents=True) + shutil.copy(REPO_ROOT / "orchestrator" / "client" / "hub_api.py", client / "hub_api.py") + result = self._feed("y\n") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(sorted(path.name for path in work.iterdir()), ["ran-approved"]) + self.assertIn(f"waits operator/pending: 1 reviews its commit verifies are not approved yet ({'a' * 16})", result.stdout) + self.assertIn("waits operator/offline: the hub does not answer", result.stdout) + self.assertIn("waits operator/redirect: the hub does not answer", result.stdout) + self.assertIn("waits operator/huge: the hub does not answer", result.stdout) + self.assertEqual(sorted(self._open()), ["operator/huge", "operator/offline", "operator/pending", "operator/redirect"]) + def test_run_colors_only_on_a_terminal_without_no_color(self): self._add("go", self.base, "true", "runnable", "manual") piped = self._feed("q\n").stdout diff --git a/tests/test_page_reveal.py b/tests/test_page_reveal.py index eba47b9..ad7b043 100644 --- a/tests/test_page_reveal.py +++ b/tests/test_page_reveal.py @@ -85,7 +85,7 @@ def shown(templates: Path, calls: list[list[object]], globals_: dict | None = No def item(kind: str, **fields: object) -> dict: - base = {"kind": kind, "id": "0123456789abcdef", "title": "Bash: make test", "command": "", "directory": "", "agent": "Skills", "to": "Skills", "ts": 1_800_000_000, "warnings": [], "options": [], "recommended": "", "held": False, "until": 0, "pinned": False, "diff": None, "job": None, "rule": None, "detail": "", "green": False, "gate": "", "score": "", "runnable": True, "deniable": True, "sha256": ""} + base = {"kind": kind, "id": "0123456789abcdef", "title": "Bash: make test", "command": "", "directory": "", "agent": "Skills", "to": "Skills", "ts": 1_800_000_000, "warnings": [], "options": [], "recommended": "", "held": False, "until": 0, "pinned": False, "diff": None, "job": None, "rule": None, "detail": "", "green": False, "gate": "", "score": "", "runnable": True, "deniable": True, "sha256": "", "reviews": []} return {**base, **fields}