fix(hub): commit rows run only after their reviews, which now hold two hours
Stage 2.0's commit row failed because its approvals lived 15 minutes and the row ran before them (operator picks 2026-11-20). A review approval now holds two hours (signing.REVIEW_LIFETIME 7200 for all-review batches, signing.lifetime and checked_approval shared by the verifier and the hub). operator.py run reads the approval.py verify steps of a row's command (VERIFY_STEP, the same pattern signing uses), asks the hub through the client's hub_api for each review and skips the row with 'waits <name>: <why>; the row stays open' until every one is approved; a hub that does not answer, a missing client or a port above 65535 also skips it. The inbox lists each commit row's reviews (inbox.linked) with a reviews k/n approved pill; its Run button becomes 'Approve n and run', which brings the row's pending reviews into the selection, signs each rule and red-gate review alone first and then the rest once; approving.apply settles operator rows after the reviews they verify. kvb-git-diff and requirement 020 describe it.
Stacked on grantall (14bb4f3). Conflicts in page-inbox.js (grantNote and DENY_NOTE next to the ux reason chips) and kvb-git-diff/SKILL.md (the superseded line next to the two-hour paragraph) keep both sides. ruff and node --check pass.
Tests: tests/test_operator.py ran once before the commit (operator exception): 51 passed, 61 subtests. test_hub_approval, test_hub_console, test_hub_grant_mode and the fixture updates are written, not run: the full suite runs once on master after all bundles (operator order).
Security: MEDUSA over the staged tree on master: 100, no findings, all 16 files covered. WEB-SSRF at skills/kvb-org-operator/scripts/operator.py:996 (urllib.request to the local hub at base_url(port)) stays accepted as by design after kvb-think-criticize with 1 skeptic over 2 rounds and the operator's accept on 2026-11-21: the port is checked against 65535, the opener has no proxy and no redirects.
🎯 Fix: 92 %
💥 Break: 5 %
💸 Tokens: –
⏱️ Velocity: –
🛡️ Security: 100 %
🏆 Score: 87
🚦 Gate: ✅ 90/5, tokens and velocity <= 100, security 100 %
Created-with: https://s.veen.world/skills
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
14bb4f38df
commit
0fa05c54d5
16 files changed
+288
-33
No files matched your search
@@ -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<port>[0-9]+))(?=[^;&|]*--review (?P<review>[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
|
||||
|
||||
|
||||
|
||||
@@ -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"]:
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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"))
|
||||
|
||||
@@ -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),
|
||||
|
||||
Reference in new issue
Block a user