feat(hub): every choice is one numbered dialog with an Other answer

Decisions, decision rows and hook questions render through one page-dialog.js: numbered options, check boxes for multi picks, the recommended option tagged, and a one-line Other answer; page-inbox.js and page-match.js drop their own option code. choosing.picks accepts one line of other text for every decision and decision row, not only hook questions, and approving checks a decision row's label through it and visible(). operator.py add --check decision now needs 2 to 4 --option values, as an AskUserQuestion offers (OPTION_FLOOR 2, OPTION_LIMIT 4 instead of 12), and refuses --option or --recommended on any other check; kvb-agent-optimize's graph.py passes two answers for each row it adds, and checks.md names the instruction-step answers Done= and Blocked=.

Stacked on questions (a6eee78); applied cleanly. ruff and node --check pass.

Tests: test_hub_decision_rows, test_hub_questions, test_operator, test_code_graph, test_hub_match and the Match waiting and question e2e updated. 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 over 21 files; index.html.j2 is not covered and was read by hand (dialog style rules and the page-dialog.js include).

🎯 Fix: 90 %
💥 Break: 5 %
💸 Tokens: –
⏱️ Velocity: –
🛡️ Security: 100 %
🏆 Score: 86
🚦 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:
Kevin Veen-BirkenbachandClaude Opus 5.5 committed 2026-11-22 15:10:26 +00:00
1 parent a6eee78165
commit 88e53ac51f
22 files changed
+212 -181

No files matched your search

+6 -4
View File
@@ -248,10 +248,12 @@ class Approving:
def row_answer_entry(self, raw: dict, row: dict, tasks: dict[str, dict]) -> dict: def row_answer_entry(self, raw: dict, row: dict, tasks: dict[str, dict]) -> dict:
"""Returns: """Returns:
The signed item of a decision row answered with one of its option The signed item of a decision row answered with one of its option
labels: the post row_answer_signed() builds to the row's agent. labels or one line of other text: the post row_answer_signed()
builds to the row's agent.
""" """
if raw["label"] not in [option["label"] for option in row["options"]] or "payload" in raw: if not picks(row, raw["label"]) or "payload" in raw:
raise ToolError("a decision row is approved with one of its option labels and no payload") raise ToolError("a decision row is approved with one of its option labels or one line of other text, and no payload")
visible({"label": raw["label"]})
if digest(row["command"]) != raw["sha256"]: if digest(row["command"]) != raw["sha256"]:
raise Conflict({"id": row["task"], "status": "changed"}) raise Conflict({"id": row["task"], "status": "changed"})
if answered(self.answers.get(row["task"]), row): if answered(self.answers.get(row["task"]), row):
@@ -281,7 +283,7 @@ class Approving:
label = "" label = ""
if kind_name == "decision": if kind_name == "decision":
if verb != "approve" or not picks(record, raw["label"]): if verb != "approve" or not picks(record, raw["label"]):
raise ToolError("a decision is approved with one of its option labels, a multi decision with one or more of them in option order, a hook question also with one line of other text") raise ToolError("a decision is approved with one of its option labels, a multi decision with one or more of them in option order, or with one line of other text")
visible([{"label": part} for part in raw["label"].split(PICKED)]) visible([{"label": part} for part in raw["label"].split(PICKED)])
label = raw["label"] label = raw["label"]
if kind_name == "rule": if kind_name == "rule":
+7 -7
View File
@@ -21,17 +21,17 @@ OTHER_LIMIT = 1000
def picks(decision: dict, label: str) -> bool: def picks(decision: dict, label: str) -> bool:
"""Args: """Args:
label: the answer to a decision: one option label, or for a multi decision: a decision or a decision row, with its options.
decision one or more labels in option order, joined by PICKED, label: the answer to it: one option label, or for a multi decision
which no label holds; for a decision the permission hook asked one or more labels in option order, joined by PICKED, which no
also one line of free text up to OTHER_LIMIT characters, trimmed label holds; or one line of free text up to OTHER_LIMIT
and no option label. characters, trimmed and no option label.
Returns: Returns:
Whether label is a valid answer to the decision. Whether label is a valid answer to the decision.
""" """
labels = [option["label"] for option in decision["options"]] labels = [option["label"] for option in decision["options"]]
if decision.get("hooked") and PICKED not in label and label not in labels: if PICKED not in label and label not in labels:
return 0 < len(label) <= OTHER_LIMIT and label == label.strip() return 0 < len(label) <= OTHER_LIMIT and label == label.strip()
if not decision.get("multi"): if not decision.get("multi"):
return label in labels return label in labels
@@ -66,7 +66,7 @@ def row_answer_signed(row: dict, to: str, label: str) -> dict:
"""Args: """Args:
row: an open decision row of the register. row: an open decision row of the register.
to: the row's adding agent. to: the row's adding agent.
label: one of the row's option labels. label: the answer picks() accepts for the row.
Returns: Returns:
The post to that agent that a Match pick signs, in the words the The post to that agent that a Match pick signs, in the words the
+2 -2
View File
@@ -21,7 +21,7 @@ SNOOZE_LIMIT = 8 * 86400
class Inbox: class Inbox:
def inbox(self, now: float, tasks: dict[str, dict], directory: Directory) -> list[dict]: def inbox(self, now: float, tasks: dict[str, dict], directory: Directory) -> list[dict]:
claims = read_claims(self.council) claims = read_claims(self.council)
base = {"agent": "", "to": "", "detail": "", "green": False, "gate": "", "score": "", "warnings": [], "options": [], "recommended": "", "multi": False, "other": 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": ""}
items = [] items = []
for review in self.reviews.pending(): for review in self.reviews.pending():
created = iso_epoch(review["created"]) or now created = iso_epoch(review["created"]) or now
@@ -35,7 +35,7 @@ class Inbox:
items.append({**base, "kind": "ask", "id": ask["id"], "ts": ask["created_ts"], **fields, "command": ask["command"], "directory": ask["cwd"]}) items.append({**base, "kind": "ask", "id": ask["id"], "ts": ask["created_ts"], **fields, "command": ask["command"], "directory": ask["cwd"]})
for decision in (decision for decision in self.decisions.pending() if decision_status(decision, now) == "pending"): for decision in (decision for decision in self.decisions.pending() if decision_status(decision, now) == "pending"):
recommended = decision.get("recommended", "") recommended = decision.get("recommended", "")
fields = {"title": decision["question"][:300], "agent": decision["agent"], "green": recommended != "", "options": decision["options"], "recommended": recommended, "multi": bool(decision.get("multi")), "other": bool(decision.get("hooked"))} fields = {"title": decision["question"][:300], "agent": decision["agent"], "green": recommended != "", "options": decision["options"], "recommended": recommended, "multi": bool(decision.get("multi"))}
items.append({**base, "kind": "decision", "id": decision["id"], "ts": decision["created_ts"], **fields}) items.append({**base, "kind": "decision", "id": decision["id"], "ts": decision["created_ts"], **fields})
held = self.open_jobs() held = self.open_jobs()
consoles = self.consoles() consoles = self.consoles()
+1 -1
View File
@@ -147,7 +147,7 @@ class Matching:
"born": born, "created_ts": item["ts"], "repo": repo, "branch": branch, "worktree": worktree, "title": item["title"], "score": "", "born": born, "created_ts": item["ts"], "repo": repo, "branch": branch, "worktree": worktree, "title": item["title"], "score": "",
"metrics": metric_chips("\n".join((item["title"], item["command"], item["detail"])), labels, False), "gate": "", "hash": shown, "live_hash": shown, "stale": False, "stale_reason": "", "metrics": metric_chips("\n".join((item["title"], item["command"], item["detail"])), labels, False), "gate": "", "hash": shown, "live_hash": shown, "stale": False, "stale_reason": "",
"files": files, "command": item["command"], "directory": item["directory"], "reason": item["detail"], "sha256": item["sha256"], "options": item["options"], "files": files, "command": item["command"], "directory": item["directory"], "reason": item["detail"], "sha256": item["sha256"], "options": item["options"],
"recommended": item["recommended"], "multi": item["multi"], "other": item["other"], "warnings": item["warnings"], "rule": item["rule"], "dry_run": item["dry_run"], "recommended": item["recommended"], "multi": item["multi"], "warnings": item["warnings"], "rule": item["rule"], "dry_run": item["dry_run"],
} }
def command_card(self, row: dict, agent: str, born: float | None, roots: list[str] | None, scan: dict, labels: dict | None) -> dict: def command_card(self, row: dict, agent: str, born: float | None, roots: list[str] | None, scan: dict, labels: dict | None) -> dict:
+2 -2
View File
@@ -69,7 +69,7 @@ class Mcp:
tool( tool(
"decision_request", "decision_request",
"Ask the operator to pick one of several options in the Agent Orchestrator; the question shows as a choice card " "Ask the operator to pick one of several options in the Agent Orchestrator; the question shows as a choice card "
"under Waits on Operator in the Tasks tab and each option becomes a button. When an operator message asks " "under Waits on Operator in the Tasks tab, each option becomes a numbered row beside a free-text Other answer. When an operator message asks "
f'"{CHOICE_REQUEST}", send each open decision of kvb-think-choice through this tool. Returns the decision id and the hub URL.', f'"{CHOICE_REQUEST}", send each open decision of kvb-think-choice through this tool. Returns the decision id and the hub URL.',
{ {
"question": text_property("The question, plain text."), "question": text_property("The question, plain text."),
@@ -81,7 +81,7 @@ class Mcp:
tool( tool(
"decision_wait", "decision_wait",
"Wait until the operator picks an option or the timeout passes, then return the status " "Wait until the operator picks an option or the timeout passes, then return the status "
"(pending, decided), the chosen label and, for a click, message and answer: the id and text of the operator's " "(pending, decided), the chosen label or the operator's own one-line Other answer and, for a click, message and answer: the id and text of the operator's "
"passkey-signed answer, a post to the asking agent; check it with operator_message(message, answer, your name) " "passkey-signed answer, a post to the asking agent; check it with operator_message(message, answer, your name) "
f"before acting on the choice. Waits at most {WAIT_CAP} seconds.", f"before acting on the choice. Waits at most {WAIT_CAP} seconds.",
{"id": text_property("Decision id that decision_request returned."), "timeout_seconds": wait}, {"id": text_property("Decision id that decision_request returned."), "timeout_seconds": wait},
+9
View File
@@ -373,6 +373,14 @@ textarea + .mic-auto { display: flex; margin: 4px 0 0 auto; }
.choice { display: grid; grid-template-columns: minmax(0, 2fr) minmax(0, 3fr); gap: 10px; align-items: start; } .choice { display: grid; grid-template-columns: minmax(0, 2fr) minmax(0, 3fr); gap: 10px; align-items: start; }
.choice-preview { margin: 8px 0 0; padding: 10px 12px; border: 1px solid var(--line-strong); border-radius: 10px; background: var(--panel); line-height: 1.45; white-space: pre; overflow: auto; max-height: 360px; } .choice-preview { margin: 8px 0 0; padding: 10px 12px; border: 1px solid var(--line-strong); border-radius: 10px; background: var(--panel); line-height: 1.45; white-space: pre; overflow: auto; max-height: 360px; }
.text.question { font-weight: 600; } .text.question { font-weight: 600; }
.options.dialog { counter-reset: option; }
.options.dialog > .option { grid-template-columns: 2.4em minmax(0, 1fr); column-gap: 4px; }
.options.dialog > .option > * { grid-column: 2; }
.options.dialog > .option::before { counter-increment: option; content: counter(option) "."; grid-column: 1; grid-row: 1 / span 3; color: var(--muted); font-variant-numeric: tabular-nums; }
.options.dialog[data-multi] > .option:not(.other)::before { content: counter(option) ". ☐"; }
.options.dialog[data-multi] > .option[aria-pressed="true"]::before { content: counter(option) ". ☑"; color: var(--accent); }
.option-tag { justify-self: start; font-style: normal; font-size: var(--fs-xs); padding: 0 7px; border: 1px solid var(--ok); border-radius: 999px; color: var(--ok); }
.choice-send { justify-self: start; }
@media (max-width: 720px) { .choice { grid-template-columns: 1fr; } } @media (max-width: 720px) { .choice { grid-template-columns: 1fr; } }
.inbox-head { display: flex; align-items: center; gap: 8px; margin-bottom: 10px; } .inbox-head { display: flex; align-items: center; gap: 8px; margin-bottom: 10px; }
.inbox-list { display: grid; gap: 8px; margin: 0; padding: 0; list-style: none; } .inbox-list { display: grid; gap: 8px; margin: 0; padding: 0; list-style: none; }
@@ -575,6 +583,7 @@ pre.notes { margin: 0; padding: 8px 10px; background: var(--sunken); border-radi
{% include "page-reveal.js" %} {% include "page-reveal.js" %}
{% include "page-dom.js" %} {% include "page-dom.js" %}
{% include "page-dialog.js" %}
{% include "page-api.js" %} {% include "page-api.js" %}
+59
View File
@@ -0,0 +1,59 @@
/**
* @param {Object} item a decision, a decision row or a decision card: id, options [{label, description, preview}], recommended (labels joined by PICKED), multi.
* @param {Object} how pick: called with the answer, one label, the toggled labels in option order joined by PICKED, or the trimmed Other text; toggled: the Set of toggled labels of a multi decision, kept by the caller across redraws; chosen: the answer given so far, "" for none; locked: whether the dialog takes no answer; hint: what an answer does, shown in the titles; group: an extra class of the option list.
* @returns {HTMLElement} the dialog an AskUserQuestion shows: numbered options with their description, the recommended ones tagged, a free-text Other row, Send for a multi decision, and a preview pane beside them once an option has one. The keys 1 to n pick or toggle an option, n + 1 focuses Other.
*/
function choiceDialog(item, how) {
const recommended = item.recommended ? item.recommended.split(PICKED) : [];
const chosen = how.chosen ? how.chosen.split(PICKED) : [];
const pane = item.options.some((option) => option.preview) ? h("pre", {class: "choice-preview", "aria-label": "Preview"}) : null;
const show = (option) => {
if (pane) {
pane.textContent = revealedLines(option.preview || "");
}
};
const send = item.multi ? h("button", {type: "button", class: "btn small primary choice-send", disabled: how.locked || !how.toggled.size, ...named("Send", revealed(`Send the toggled options: ${how.hint}`))}, icon("bi-check2-square"), "Send") : null;
const buttons = item.options.map((option) => {
const marked = recommended.includes(option.label);
const button = h("button", {
type: "button", class: `option${marked ? " recommended" : ""}`, disabled: how.locked, "aria-pressed": String(item.multi ? how.toggled.has(option.label) : chosen.includes(option.label)),
title: revealed(`${option.label}: ${how.hint}`),
on: {click: () => {
if (!item.multi) {
how.pick(option.label);
return;
}
how.toggled.has(option.label) ? how.toggled.delete(option.label) : how.toggled.add(option.label);
button.setAttribute("aria-pressed", String(how.toggled.has(option.label)));
send.disabled = !how.toggled.size;
}, focus: () => show(option), mouseenter: () => show(option)},
}, h("strong", {}, revealed(option.label)), marked && !option.label.includes("(Recommended)") ? h("em", {class: "option-tag"}, "Recommended") : null,
option.description ? h("span", {}, revealed(option.description)) : null);
return button;
});
if (send) {
send.addEventListener("click", () => how.pick(item.options.filter((option) => how.toggled.has(option.label)).map((option) => option.label).join(PICKED)));
}
const typed = chosen.length === 1 && !item.options.some((option) => option.label === chosen[0]) ? chosen[0] : null;
const input = h("input", {class: "field", type: "text", maxlength: OTHER_LIMIT, placeholder: "Other: type your own answer …", "aria-label": `Other answer to ${item.id}`, value: typed, disabled: how.locked});
const other = h("form", {class: "option other"}, input,
h("button", {type: "submit", class: "btn small", disabled: how.locked, ...named("Send", revealed(`Send this text: ${how.hint}`))}, icon("bi-send"), "Send"));
other.addEventListener("submit", (event) => {
event.preventDefault();
if (input.value.trim()) {
how.pick(input.value.trim());
}
});
const list = h("div", {class: `options dialog${how.group ? ` ${how.group}` : ""}`, role: "group", "aria-label": "Options", "data-multi": item.multi ? "" : null}, buttons, other, send);
list.addEventListener("keydown", (event) => {
const index = Number(event.key) - 1;
if (event.target === input || event.altKey || event.ctrlKey || event.metaKey || !Number.isInteger(index) || index < 0 || index > buttons.length) {
return;
}
event.preventDefault();
event.stopPropagation();
index < buttons.length ? buttons[index].click() : input.focus();
});
show(item.options.find((option) => recommended.includes(option.label)) || item.options[0] || {});
return pane ? h("div", {class: "choice"}, list, pane) : list;
}
+7 -60
View File
@@ -120,72 +120,19 @@
} }
} }
/** const signsFor = (item) => `your passkey signs this answer, a post to ${item.agent}`;
* @param {Object} item a decision row, or a decision the permission hook asked.
* @param {Function} send called with the trimmed text once it is not empty.
* @returns {HTMLElement} the free-text answer form.
*/
function otherAnswer(item, send) {
const done = answers.has(keyOf(item));
const input = h("input", {class: "field", type: "text", placeholder: "Other answer …", "aria-label": `Other answer to ${item.id}`, maxlength: item.kind === "decision" ? OTHER_LIMIT : null, disabled: done});
const form = h("form", {class: "option other"}, input,
h("button", {type: "submit", class: "btn small", disabled: done, ...named("Send", revealed(`Send: your passkey signs this answer for ${item.agent}`))}, icon("bi-send"), "Send"));
form.addEventListener("submit", (event) => {
event.preventDefault();
if (input.value.trim()) {
send(input.value.trim());
}
});
return form;
}
/** /**
* @param {Object} item a decision or a decision row; a multi decision takes several options, toggled until Send. * @param {Object} item an inbox item.
* @param {Function} pick called with the answer: one label, or the toggled labels in option order joined by PICKED. * @param {Function} after called before a picked answer is sent.
* @param {HTMLElement} [other] a free-text answer form. * @returns {HTMLElement|Array|null} the choiceDialog() of a decision or a decision row, with its recipient line for a row; null for every other item.
* @returns {HTMLElement} the option buttons with their preview pane.
*/ */
function choicePanel(item, pick, other) {
const done = Boolean(answerOf(item));
const recommended = item.recommended.split(PICKED);
const toggled = new Set();
const pane = item.options.some((option) => option.preview) ? h("pre", {class: "choice-preview", "aria-label": "Preview"}) : null;
const show = (option) => {
if (pane) {
pane.textContent = revealedLines(option.preview || "");
}
};
const send = item.multi ? h("button", {type: "button", class: "btn small primary choice-send", disabled: true, ...named("Send", revealed(`Send the toggled options: your passkey signs this answer for ${item.agent}`))}, icon("bi-send"), "Send") : null;
const buttons = item.options.map((option) => {
const button = h("button", {
type: "button", class: `option${recommended.includes(option.label) ? " recommended" : ""}`, title: revealed(`${option.label}: your passkey signs this answer, a post to ${item.agent}`), disabled: item.held || done,
"aria-pressed": item.multi ? "false" : null,
on: {click: () => {
if (!item.multi) {
pick(option.label);
return;
}
toggled.has(option.label) ? toggled.delete(option.label) : toggled.add(option.label);
button.setAttribute("aria-pressed", String(toggled.has(option.label)));
send.disabled = !toggled.size;
}, focus: () => show(option), mouseenter: () => show(option)},
}, h("strong", {}, revealed(option.label)), option.description ? h("span", {}, revealed(option.description)) : null);
return button;
});
if (send) {
send.addEventListener("click", () => pick(item.options.filter((option) => toggled.has(option.label)).map((option) => option.label).join(PICKED)));
}
show(item.options.find((option) => recommended.includes(option.label)) || item.options[0] || {});
const list = h("div", {class: "options"}, buttons, other || null, send);
return pane ? h("div", {class: "choice"}, list, pane) : list;
}
const choiceOf = (item, after) => { const choiceOf = (item, after) => {
if (item.kind === "decision") { if (item.kind === "decision") {
const choose = (label) => { after(); chooseOne(item, label); }; return choiceDialog(item, {pick: (label) => { after(); chooseOne(item, label); }, toggled: new Set(), chosen: "", locked: item.held, hint: signsFor(item), group: ""});
return choicePanel(item, choose, item.other ? otherAnswer(item, choose) : null);
} }
return asked(item) ? [answerTo(item), choicePanel(item, (label) => { after(); answerRow(item, label); }, otherAnswer(item, (text) => answerRow(item, text)))] : null; const told = answerOf(item);
return asked(item) ? [answerTo(item), choiceDialog(item, {pick: (label) => { after(); answerRow(item, label); }, toggled: new Set(), chosen: told, locked: item.held || Boolean(told), hint: signsFor(item), group: ""})] : null;
}; };
/** /**
+11 -50
View File
@@ -275,58 +275,19 @@
} }
/** /**
* @param {Object} card a decision card; a multi one takes several options, toggled here and kept in matchView.toggles across redraws until Pick. * @param {Object} card a decision card; a multi one keeps its toggled options in matchView.toggles across redraws until Send.
* @returns {HTMLElement} its option buttons, and Pick for a multi card. * @returns {HTMLElement} its choiceDialog(); an answer is picked now and sent at the release.
*/ */
function matchOptions(card) { function matchOptions(card) {
const kept = matchView.decisions.get(cardKey(card)); const key = cardKey(card);
const recommended = card.recommended.split(PICKED); const kept = matchView.decisions.get(key);
const toggled = matchView.toggles.get(cardKey(card)) || new Set(kept ? kept.label.split(PICKED) : []); const toggled = matchView.toggles.get(key) || new Set(kept ? kept.label.split(PICKED) : []);
const pick = card.multi ? h("button", {type: "button", class: "btn small primary match-pick", disabled: !toggled.size, title: revealed(`Pick: the toggled options, sent to ${card.agent || "its agent"} at the release`)}, icon("bi-check2-square"), "Pick") : null; matchView.toggles.set(key, toggled);
const buttons = card.options.map((option) => { const pick = (label) => {
const button = h("button", { matchView.toggles.delete(key);
type: "button", class: `option${recommended.includes(option.label) ? " recommended" : ""}`, "aria-pressed": String(toggled.has(option.label)), decide(card, "accept", "", label);
title: revealed(`${option.label}: ${card.multi ? "toggled now" : "picked now"}, sent to ${card.agent || "its agent"} at the release`), };
on: {click: () => { return choiceDialog({...card, id: card.ref}, {pick, toggled, chosen: kept ? kept.label : "", locked: false, hint: `picked now, sent to ${card.agent || "its agent"} at the release`, group: "match-options"});
if (!card.multi) {
decide(card, "accept", "", option.label);
return;
}
toggled.has(option.label) ? toggled.delete(option.label) : toggled.add(option.label);
matchView.toggles.set(cardKey(card), toggled);
button.setAttribute("aria-pressed", String(toggled.has(option.label)));
pick.disabled = !toggled.size;
}},
}, h("strong", {}, revealed(option.label)), option.description ? h("span", {}, revealed(option.description)) : null);
return button;
});
if (pick) {
pick.addEventListener("click", () => {
matchView.toggles.delete(cardKey(card));
decide(card, "accept", "", card.options.filter((option) => toggled.has(option.label)).map((option) => option.label).join(PICKED));
});
}
return h("div", {class: "options match-options", role: "group", "aria-label": "Options"}, buttons, pick, card.other ? matchOther(card, kept) : null);
}
/**
* @param {Object} card a decision card of a question the permission hook asked.
* @param {Object} [kept] its decision so far; a free-text one fills the field.
* @returns {HTMLElement} the one-line free-text answer, picked like an option.
*/
function matchOther(card, kept) {
const free = kept && kept.label && !kept.label.split(PICKED).some((label) => card.options.some((option) => option.label === label));
const input = h("input", {class: "field", type: "text", maxlength: OTHER_LIMIT, placeholder: "Other answer …", "aria-label": "Other answer", value: free ? kept.label : null});
const form = h("form", {class: "option other match-other"}, input,
h("button", {type: "submit", class: "btn small", ...named("Pick", revealed(`Pick: this text, sent to ${card.agent || "its agent"} at the release`))}, icon("bi-send"), "Pick"));
form.addEventListener("submit", (event) => {
event.preventDefault();
if (input.value.trim()) {
matchView.toggles.delete(cardKey(card));
decide(card, "accept", "", input.value.trim());
}
});
return form;
} }
function matchPayload(card) { function matchPayload(card) {
+8 -1
View File
@@ -78,6 +78,9 @@
if (entry.kind === "transcript") { if (entry.kind === "transcript") {
return pill((PARTS.find(([id]) => id === entry.part) || [entry.part, entry.part])[1], PART_TONES[entry.part] || "neutral"); return pill((PARTS.find(([id]) => id === entry.part) || [entry.part, entry.part])[1], PART_TONES[entry.part] || "neutral");
} }
if (entry.kind === "operator" && entry.ref.check === "decision") {
return pill("Decision", KIND_TONES.decision);
}
return pill((KINDS.find(([id]) => id === entry.kind) || [entry.kind, entry.kind])[1], KIND_TONES[entry.kind] || "neutral"); return pill((KINDS.find(([id]) => id === entry.kind) || [entry.kind, entry.kind])[1], KIND_TONES[entry.kind] || "neutral");
} }
@@ -110,6 +113,9 @@
} }
return [text, more]; return [text, more];
} }
if (entry.kind === "operator" && entry.ref.check === "decision") {
return [h("p", {class: "text question"}, revealed(entry.title)), entry.text !== "-" ? h("p", {class: "text reason"}, revealed(entry.text)) : null];
}
if (entry.kind === "ask" || entry.kind === "operator") { if (entry.kind === "ask" || entry.kind === "operator") {
const where = entry.kind === "ask" ? entry.ref.cwd : entry.ref.directory; const where = entry.kind === "ask" ? entry.ref.cwd : entry.ref.directory;
return [h("div", {class: "command", "data-path": where || "-"}, h("code", {}, entry.kind === "ask" ? entry.text : entry.title), copyButton(entry.kind === "ask" ? entry.text : entry.title)), h("span", {class: "muted"}, `in ${dash(where)}`), entry.kind === "operator" && entry.text !== "-" ? h("p", {class: "text"}, entry.text) : null]; return [h("div", {class: "command", "data-path": where || "-"}, h("code", {}, entry.kind === "ask" ? entry.text : entry.title), copyButton(entry.kind === "ask" ? entry.text : entry.title)), h("span", {class: "muted"}, `in ${dash(where)}`), entry.kind === "operator" && entry.text !== "-" ? h("p", {class: "text"}, entry.text) : null];
@@ -130,6 +136,7 @@
function eventRow(entry) { function eventRow(entry) {
const item = entry.waiting ? inboxOf(entry) : null; const item = entry.waiting ? inboxOf(entry) : null;
const choice = item ? choiceOf(item, () => {}) : null;
const alarm = entry.kind === "radio" && (entry.part === "mayday" || entry.part === "pan-pan"); const alarm = entry.kind === "radio" && (entry.part === "mayday" || entry.part === "pan-pan");
const renamed = entry.now && entry.now !== entry.agent ? h("span", {title: `now: ${entry.now}`}, person(entry.agent)) : person(entry.agent); const renamed = entry.now && entry.now !== entry.agent ? h("span", {title: `now: ${entry.now}`}, person(entry.agent)) : person(entry.agent);
const who = entry.agent ? [face(entry.agent, false), renamed] : entry.session ? h("strong", {title: entry.session}, entry.session.slice(0, 8)) : null; const who = entry.agent ? [face(entry.agent, false), renamed] : entry.session ? h("strong", {title: entry.session}, entry.session.slice(0, 8)) : null;
@@ -138,7 +145,7 @@
h("div", {class: "msg-meta"}, when(entry.ts), kindPill(entry), extras(entry)), h("div", {class: "msg-meta"}, when(entry.ts), kindPill(entry), extras(entry)),
h("div", {}, h("div", {},
h("div", {class: "route", "data-star-slot": ""}, who, entry.sub ? h("button", {type: "button", class: "linkish muted", on: {click: () => focusSub(entry.session, entry.sub)}}, `› Subagent ${entry.sub.slice(0, 12)}`) : null, entry.kind === "ask" ? h("strong", {}, entry.title) : null, headline), h("div", {class: "route", "data-star-slot": ""}, who, entry.sub ? h("button", {type: "button", class: "linkish muted", on: {click: () => focusSub(entry.session, entry.sub)}}, `› Subagent ${entry.sub.slice(0, 12)}`) : null, entry.kind === "ask" ? h("strong", {}, entry.title) : null, headline),
body(entry), entry.kind === "decision" && choice ? choice : [body(entry), choice],
entry.kind === "radio" ? readerRow(entry.ref) : null, entry.kind === "radio" ? readerRow(entry.ref) : null,
item ? diffBlocks(item) : null, item ? diffBlocks(item) : null,
item ? feedbackList(keyOf(item)) : null, item ? feedbackList(keyOf(item)) : null,
+8 -3
View File
@@ -508,13 +508,15 @@ def unit_active() -> bool:
return unit is not None and unit.returncode == 0 return unit is not None and unit.returncode == 0
def add_row_once(slug: str, session: str, command: str, reason: str) -> None: def add_row_once(slug: str, session: str, command: str, reason: str, options: list[str]) -> None:
"""Args: """Args:
slug: the kvb-org-operator row; added at most once per host, so a row slug: the kvb-org-operator row; added at most once per host, so a row
the operator cancelled is never reopened. the operator cancelled is never reopened.
session: the hook payload's session id, forwarded as --session. session: the hook payload's session id, forwarded as --session.
command: the row's command, shown only (--check decision). command: the row's command, shown only (--check decision).
reason: why the row exists. reason: why the row exists.
options: the row's answers as "<label>=<consequence>", the
recommended one first.
""" """
rows = state_dir() / "rows.json" rows = state_dir() / "rows.json"
with locked_json(rows) as added: with locked_json(rows) as added:
@@ -526,6 +528,7 @@ def add_row_once(slug: str, session: str, command: str, reason: str) -> None:
result = run([ result = run([
sys.executable, "-I", str(script), "add", slug, "--session", session, sys.executable, "-I", str(script), "add", slug, "--session", session,
"--dir", str(Path.home()), "--command", command, "--reason", reason, "--check", "decision", "--dir", str(Path.home()), "--command", command, "--reason", reason, "--check", "decision",
*[part for option in options for part in ("--option", option)], "--recommended", options[0].partition("=")[0],
], timeout=ROW_TIMEOUT) ], timeout=ROW_TIMEOUT)
if result is not None and result.returncode == 0: if result is not None and result.returncode == 0:
with locked_json(rows) as added: with locked_json(rows) as added:
@@ -537,7 +540,8 @@ def notices(session: str, settings: dict | None) -> list[str]:
if settings is None: if settings is None:
path = config_path() path = config_path()
messages.append(f"kvb-code-graph: nothing is indexed until {path} sets queue_file_threshold and queue_task (operator row {CONFIG_ROW})") messages.append(f"kvb-code-graph: nothing is indexed until {path} sets queue_file_threshold and queue_task (operator row {CONFIG_ROW})")
add_row_once(CONFIG_ROW, session, f"code {path}", "set queue_file_threshold and queue_task; the code graph hook indexes nothing until both are set") add_row_once(CONFIG_ROW, session, f"code {path}", "set queue_file_threshold and queue_task; the code graph hook indexes nothing until both are set",
[f"Configure=set queue_file_threshold and queue_task in {path}; indexing starts", "Leave off=nothing is indexed"])
kind = daemon_kind(binary()) kind = daemon_kind(binary())
if kind == "permanent": if kind == "permanent":
return messages return messages
@@ -548,7 +552,8 @@ def notices(session: str, settings: dict | None) -> list[str]:
messages.append(NOTICE_PENDING if kind == "session-managed" else NOTICE_STUCK) messages.append(NOTICE_PENDING if kind == "session-managed" else NOTICE_STUCK)
elif unit_installed(): elif unit_installed():
messages.append(NOTICE) messages.append(NOTICE)
add_row_once(DAEMON_ROW, session, ENABLE, "no permanent codebase-memory-mcp daemon: graphs lose their watch when the last session ends") add_row_once(DAEMON_ROW, session, ENABLE, "no permanent codebase-memory-mcp daemon: graphs lose their watch when the last session ends",
["Enable=run the command; one permanent daemon keeps every graph watched", "Per session=graphs lose their watch when the last session ends"])
else: else:
messages.append(NOTICE_NO_UNIT) messages.append(NOTICE_NO_UNIT)
return messages return messages
+6 -5
View File
@@ -21,8 +21,9 @@ without a shell command takes `decision`, its question or instruction as
`--command`. Other kinds, relative paths and shell `--command`. Other kinds, relative paths and shell
metacharacters exit 2. metacharacters exit 2.
A `decision` row carries each answer as `--option "<label>=<what it A `decision` row carries two to four answers, as an `AskUserQuestion`
means>"` and your pick as `--recommended`; the hub shows them as buttons, offers, each as `--option "<label>=<what it means>"`, and your pick as
and the answer reaches the row's A as a passkey-signed post `--recommended`; an instruction step offers `Done=` and `Blocked=`. The hub
`Decision <task>` / `Answer: <answer>` to check with `operator_message` shows them as a numbered dialog with a one-line Other answer, and the answer
before acting. reaches the row's A as a passkey-signed post `Decision <task>` /
`Answer: <answer>` to check with `operator_message` before acting.
+19 -18
View File
@@ -18,11 +18,12 @@ Args:
--check <kind>[:<arg>] [--option "<label>=<description>" ...] --check <kind>[:<arg>] [--option "<label>=<description>" ...]
[--recommended <label>] [--session <id>]: record a command, or update [--recommended <label>] [--session <id>]: record a command, or update
the row of that slug, as queued with Operator R and the adder A, its the row of that slug, as queued with Operator R and the adder A, its
session id under `sessions`. --option, only with --check decision session id under `sessions`. --option, required with --check
and at most OPTION_LIMIT times, gives the answers the Agent decision OPTION_FLOOR to OPTION_LIMIT times and refused otherwise,
Orchestrator shows as buttons beside a free answer; the operator's gives the answers the Agent Orchestrator shows as numbered rows
pick arrives as a signed post to the adder. --recommended names one beside a free Other answer, as an AskUserQuestion does; the
of them. operator's pick arrives as a signed post to the adder. --recommended
names one of them.
Kinds, never a shell command: Kinds, never a shell command:
pushed:<repo dir> `git rev-list --count @{u}..HEAD` is 0 there; pushed:<repo dir> `git rev-list --count @{u}..HEAD` is 0 there;
no upstream counts as open. no upstream counts as open.
@@ -173,7 +174,8 @@ INTERRUPTED = 130
SUDO = re.compile(r"\bsudo\b") SUDO = re.compile(r"\bsudo\b")
PREFIX = "operator/" PREFIX = "operator/"
KINDS = ("pushed", "installed", "binary", "absent", "manual", "decision") KINDS = ("pushed", "installed", "binary", "absent", "manual", "decision")
OPTION_LIMIT = 12 OPTION_FLOOR = 2
OPTION_LIMIT = 4
LABEL_LIMIT = 80 LABEL_LIMIT = 80
OPEN = ("queued", "blocked") OPEN = ("queued", "blocked")
META = re.compile(r"[\s|&;()<>$`\\\"'*?\[\]{}~!#]") META = re.compile(r"[\s|&;()<>$`\\\"'*?\[\]{}~!#]")
@@ -313,19 +315,18 @@ def choices(raw: list[str] | None, recommended: str | None, check: str) -> list[
check: the row's --check kind. check: the row's --check kind.
Returns: Returns:
[{"label", "description"}] in the given order; [] without options. [{"label", "description"}] in the given order; [] for another check.
Exits 2 when options come with another check than decision, exceed Exits 2 when options or a pick come with another check than
OPTION_LIMIT, repeat a label, hold an empty, multi-line or longer decision, when a decision holds fewer than OPTION_FLOOR or more than
than LABEL_LIMIT label, or when --recommended names no option. OPTION_LIMIT options, repeats a label, holds an empty, multi-line or
longer than LABEL_LIMIT label, or when --recommended names no option.
""" """
if not raw:
if recommended:
fail("--recommended needs --option")
return []
if check != "decision": if check != "decision":
fail("--option is only for --check decision") if raw or recommended:
if len(raw) > OPTION_LIMIT: fail("--option and --recommended are only for --check decision")
fail(f"at most {OPTION_LIMIT} --option values") return []
if not OPTION_FLOOR <= len(raw or []) <= OPTION_LIMIT:
fail(f"--check decision needs {OPTION_FLOOR} to {OPTION_LIMIT} --option values, as an AskUserQuestion offers")
options = [] options = []
for text in raw: for text in raw:
label, _, description = text.partition("=") label, _, description = text.partition("=")
@@ -354,7 +355,7 @@ def cmd_add(rasci: ModuleType, args: argparse.Namespace) -> int:
fail(f"--command {visible(command, '')!r} holds a control character; record one line") fail(f"--command {visible(command, '')!r} holds a control character; record one line")
refused = None if args.check == "decision" else unrunnable(command, args.dir) refused = None if args.check == "decision" else unrunnable(command, args.dir)
if refused: if refused:
fail(f"--command {command!r} {refused}; write the real command, or record the step with --check decision") fail(f"--command {command!r} {refused}; write the real command, or ask the step as --check decision with {OPTION_FLOOR} to {OPTION_LIMIT} --option answers")
options = choices(args.option, args.recommended, args.check) options = choices(args.option, args.recommended, args.check)
council = module("council", rasci.COUNCIL) council = module("council", rasci.COUNCIL)
sid, _ = council.caller(args.session) sid, _ = council.caller(args.session)
+1 -1
View File
@@ -201,7 +201,7 @@ CHOICE_ANSWER = """(async () => {@HELPERS@@WATCH@
if (!card) { if (!card) {
return {error: text(document.getElementById("main"))}; return {error: text(document.getElementById("main"))};
} }
const option = all(".option", card).find((button) => text(button.querySelector("strong")) === "Wait"); const option = all("button.option", card).find((button) => text(button.querySelector("strong")) === "Wait");
const title = option.title; const title = option.title;
const shown = new Set(all("#toasts .toast")); const shown = new Set(all("#toasts .toast"));
option.click(); option.click();
+4 -4
View File
@@ -32,7 +32,7 @@ FRONT = """(async () => {@HELPERS@
peek.click(); peek.click();
} }
const node = await until(() => (card() && card().dataset.card === "@PICK@" ? card() : null), 3000); const node = await until(() => (card() && card().dataset.card === "@PICK@" ? card() : null), 3000);
return {front: node ? node.dataset.card : null, options: node ? all(".match-options .option", node).map((option) => [text(option.querySelector("strong")), option.classList.contains("recommended")]) : [], return {front: node ? node.dataset.card : null, options: node ? all(".match-options button.option", node).map((option) => [text(option.querySelector("strong")), option.classList.contains("recommended")]) : [],
wide: document.documentElement.scrollWidth > window.innerWidth + 1}; wide: document.documentElement.scrollWidth > window.innerWidth + 1};
})()""" })()"""
HOME = """(async () => {@HELPERS@@HOME_KIT@ HOME = """(async () => {@HELPERS@@HOME_KIT@
@@ -79,13 +79,13 @@ FLOW = """(async () => {@HELPERS@
const id = node.dataset.card; const id = node.dataset.card;
const acts = Object.fromEntries(all("#main .match-actions .match-act").map((button) => [text(button.querySelector(".match-act-label")), button.disabled])); const acts = Object.fromEntries(all("#main .match-actions .match-act").map((button) => [text(button.querySelector(".match-act-label")), button.disabled]));
seen[id] = {kind: node.dataset.kind, chips: all(".match-metric", node).map((chip) => `${chip.dataset.metric}=${text(chip.querySelector("strong"))}`), acts, seen[id] = {kind: node.dataset.kind, chips: all(".match-metric", node).map((chip) => `${chip.dataset.metric}=${text(chip.querySelector("strong"))}`), acts,
options: all(".match-options .option", node).map((option) => text(option.querySelector("strong"))), rule: Boolean(node.querySelector(".rule-request")), command: text(node.querySelector(".match-command"))}; options: all(".match-options button.option", node).map((option) => text(option.querySelector("strong"))), rule: Boolean(node.querySelector(".rule-request")), command: text(node.querySelector(".match-command"))};
if (id.startsWith("operator:")) { if (id.startsWith("operator:")) {
node.querySelector(".match-options .option:not(.recommended)").click(); node.querySelector(".match-options button.option:not(.recommended)").click();
} else if (id.startsWith("decision:")) { } else if (id.startsWith("decision:")) {
key("ArrowLeft"); key("ArrowLeft");
seen[id].refused = Boolean(await until(() => all("#toasts .toast").map(text).find((entry) => entry.startsWith("Reject: not possible")), 3000)); seen[id].refused = Boolean(await until(() => all("#toasts .toast").map(text).find((entry) => entry.startsWith("Reject: not possible")), 3000));
node.querySelector(".match-options .option").click(); node.querySelector(".match-options button.option").click();
} else if (id.startsWith("ask:")) { } else if (id.startsWith("ask:")) {
key("ArrowRight"); key("ArrowRight");
} else { } else {
+3 -3
View File
@@ -39,11 +39,11 @@ MATCH = """(async () => {@HELPERS@@CAPTURE@
if (!card) { if (!card) {
return {error: text(document.getElementById("main"))}; return {error: text(document.getElementById("main"))};
} }
const options = () => all(".match-options .option", card); const options = () => all(".match-options button.option", card);
const pick = card.querySelector(".match-pick"); const pick = card.querySelector(".choice-send");
const before = look(options(), pick); const before = look(options(), pick);
[0, 2, 1, 1].forEach((index) => options()[index].click()); [0, 2, 1, 1].forEach((index) => options()[index].click());
const toggled = {...look(options(), pick), front: document.querySelector("#main .match-card.front") === card, other: Boolean(card.querySelector(`.match-other input[maxlength="1000"]`))}; const toggled = {...look(options(), pick), front: document.querySelector("#main .match-card.front") === card, other: Boolean(card.querySelector(`.option.other input[maxlength="1000"]`))};
pick.click(); pick.click();
const overview = await until(() => document.querySelector("#main .match-overview"), 3000); const overview = await until(() => document.querySelector("#main .match-overview"), 3000);
const found = {before, toggled, rows: overview ? all("#main .match-decision").map((item) => [item.dataset.card, text(item.querySelector(".match-verdict"))]) : [], wide: wide()}; const found = {before, toggled, rows: overview ? all("#main .match-decision").map((item) => [item.dataset.card, text(item.querySelector(".match-verdict"))]) : [], wide: wide()};
+2
View File
@@ -455,6 +455,7 @@ class TestCodeGraphHook(CodeGraphCase):
rows = [json.loads(line) for line in lines(self.logs["operator"])] rows = [json.loads(line) for line in lines(self.logs["operator"])]
self.assertEqual([row[:2] for row in rows], [["add", "kvb-code-graph-config"]]) self.assertEqual([row[:2] for row in rows], [["add", "kvb-code-graph-config"]])
self.assertEqual(rows[0][rows[0].index("--check") + 1], "decision") self.assertEqual(rows[0][rows[0].index("--check") + 1], "decision")
self.assertEqual((rows[0].count("--option"), rows[0][rows[0].index("--recommended") + 1]), (2, "Configure"))
def test_failed_index_backs_off_across_sessions(self): def test_failed_index_backs_off_across_sessions(self):
repo = self._repo("main") repo = self._repo("main")
@@ -501,6 +502,7 @@ class TestCodeGraphHook(CodeGraphCase):
self.assertEqual(len(rows), 1) self.assertEqual(len(rows), 1)
self.assertEqual(rows[0][:2], ["add", "kvb-code-graph-daemon"]) self.assertEqual(rows[0][:2], ["add", "kvb-code-graph-daemon"])
self.assertEqual(rows[0][rows[0].index("--check") + 1], "decision") self.assertEqual(rows[0][rows[0].index("--check") + 1], "decision")
self.assertEqual((rows[0].count("--option"), rows[0][rows[0].index("--recommended") + 1]), (2, "Enable"))
self.assertEqual(rows[0][rows[0].index("--session") + 1], "s1") self.assertEqual(rows[0][rows[0].index("--session") + 1], "s1")
self.assertIn("systemctl --user enable --now kvb-code-graph.service", rows[0]) self.assertIn("systemctl --user enable --now kvb-code-graph.service", rows[0])
+18 -2
View File
@@ -8,7 +8,7 @@ from hub_case import HubCase
from hub_support import HUB from hub_support import HUB
TEMPLATES = HUB / "templates" TEMPLATES = HUB / "templates"
MODULES = ["page-constants.js", "page-reveal.js", "page-dom.js", "page-inbox.js", "page-grant.js"] MODULES = ["page-constants.js", "page-reveal.js", "page-dom.js", "page-dialog.js", "page-inbox.js", "page-grant.js"]
PROBE = r""" PROBE = r"""
const fs = require("fs"); const fs = require("fs");
const vm = require("vm"); const vm = require("vm");
@@ -21,6 +21,8 @@ class El {
replaceChildren(...nodes) { this.children = nodes; } replaceChildren(...nodes) { this.children = nodes; }
addEventListener(name, handler) { this.handlers[name] = handler; } addEventListener(name, handler) { this.handlers[name] = handler; }
fire(name) { return this.handlers[name]({stopPropagation() {}, preventDefault() {}}); } fire(name) { return this.handlers[name]({stopPropagation() {}, preventDefault() {}}); }
click() { return this.fire("click"); }
focus() { document.activeElement = this; }
remove() {} remove() {}
} }
const all = (node) => [node, ...(node.children || []).filter((child) => child instanceof El).flatMap(all)]; const all = (node) => [node, ...(node.children || []).filter((child) => child instanceof El).flatMap(all)];
@@ -98,6 +100,15 @@ const results = {};
await optionNamed(pick, "A").fire("click"); await optionNamed(pick, "A").fire("click");
results.pick.submits = submits.splice(0); results.pick.submits = submits.splice(0);
results.pick.sent = sent.splice(0); results.pick.sent = sent.splice(0);
const list = classed(inboxItem(items.pick, 5), "dialog")[0];
let stopped = 0;
const press = (key, target) => list.handlers.keydown({key, target: target || list, altKey: false, ctrlKey: false, metaKey: false, preventDefault() {}, stopPropagation() { stopped += 1; }});
["2", "0", "5", "x"].forEach((key) => press(key));
press("1", all(list).find((el) => el.tag === "input"));
await new Promise((resolve) => setTimeout(resolve, 0));
results.keys = {submits: submits.splice(0), stopped, focused: document.activeElement === null ? "" : document.activeElement.tag};
press("4");
results.keys.other = document.activeElement.tag;
console.log(JSON.stringify(results)); console.log(JSON.stringify(results));
})().catch((error) => { console.error(error && error.stack || error); process.exit(1); }); })().catch((error) => { console.error(error && error.stack || error); process.exit(1); });
`; `;
@@ -153,10 +164,15 @@ class TestDecisionRows(unittest.TestCase):
def test_a_choice_card_shows_the_preview_of_the_focused_option_beside_the_options(self): def test_a_choice_card_shows_the_preview_of_the_focused_option_beside_the_options(self):
pick = self.data["pick"] pick = self.data["pick"]
self.assertEqual((pick["shape"]["choice"], pick["shape"]["other"]), (1, 0)) self.assertEqual((pick["shape"]["choice"], pick["shape"]["other"]), (1, 1))
self.assertEqual((pick["first"], pick["hovered"], pick["empty"]), (["[B]"], ["[A]\nline"], [""])) self.assertEqual((pick["first"], pick["hovered"], pick["empty"]), (["[B]"], ["[A]\nline"], [""]))
self.assertEqual((pick["submits"], pick["sent"]), (["Choice: A"], [])) self.assertEqual((pick["submits"], pick["sent"]), (["Choice: A"], []))
def test_the_digit_keys_pick_an_option_or_focus_other_and_never_reach_the_tab_keys(self):
keys = self.data["keys"]
self.assertEqual((keys["submits"], keys["stopped"], keys["focused"]), (["Choice: B"], 1, ""))
self.assertEqual(keys["other"], "input")
class TestDecisionFeed(HubCase): class TestDecisionFeed(HubCase):
def test_the_inbox_carries_a_decision_rows_options_and_drops_malformed_ones(self): def test_the_inbox_carries_a_decision_rows_options_and_drops_malformed_ones(self):
+11 -1
View File
@@ -447,7 +447,7 @@ class TestWaitingCards(MatchCase):
] ]
answer = signing.message_item("Skills", "post", "Decision operator/pick\nAnswer: Wait", "", "", "") answer = signing.message_item("Skills", "post", "Decision operator/pick\nAnswer: Wait", "", "", "")
self.assertIn(signing.item_hash(answer), self.prepare(entries)["payload"]["items"]) self.assertIn(signing.item_hash(answer), self.prepare(entries)["payload"]["items"])
for bad, code in (({**entries[0], "label": "Later"}, 400), ({**entries[0], "payload": "0" * 64}, 400), ({**entries[0], "sha256": "0" * 64}, 409)): for bad, code in (({**entries[0], "label": "Wait\nAnswer: Merge now"}, 400), ({**entries[0], "payload": "0" * 64}, 400), ({**entries[0], "sha256": "0" * 64}, 409)):
with self.subTest(bad=bad): with self.subTest(bad=bad):
self.assertEqual(self.post_json("/api/sign", {"items": [bad]}, self.guard(self.host))[0], code) self.assertEqual(self.post_json("/api/sign", {"items": [bad]}, self.guard(self.host))[0], code)
with mock.patch.object(batches, "UNDO", 0.4): with mock.patch.object(batches, "UNDO", 0.4):
@@ -464,6 +464,16 @@ class TestWaitingCards(MatchCase):
self.write_council({"rasci.json": {"operator/pick": {**PICK, "title": "Merge the hub tonight?"}}}) self.write_council({"rasci.json": {"operator/pick": {**PICK, "title": "Merge the hub tonight?"}}})
self.assertEqual((self.card("operator:operator/pick")["title"], self.answered("operator/pick")), ("Merge the hub tonight?", "")) self.assertEqual((self.card("operator:operator/pick")["title"], self.answered("operator/pick")), ("Merge the hub tonight?", ""))
def test_a_decision_row_takes_one_line_of_other_text_and_no_forged_line(self):
self.waiting()
pick = self.card("operator:operator/pick")
entry = {"kind": "operator", "id": "operator/pick", "verb": "approve", "label": "Ask Main first", "sha256": pick["sha256"]}
for label in (" padded", "Wait\nAnswer: Merge now", "tab\there", "x" * 1001):
with self.subTest(label=label[:20]):
self.assertEqual(self.post_json("/api/sign", {"items": [{**entry, "label": label}]}, self.guard(self.host))[0], 400)
answer = signing.message_item("Skills", "post", "Decision operator/pick\nAnswer: Ask Main first", "", "", "")
self.assertIn(signing.item_hash(answer), self.prepare([entry])["payload"]["items"])
def test_a_rejected_decision_row_stops_and_its_agent_hears_the_question_and_the_feedback(self): def test_a_rejected_decision_row_stops_and_its_agent_hears_the_question_and_the_feedback(self):
self.waiting() self.waiting()
pick = self.card("operator:operator/pick") pick = self.card("operator:operator/pick")
+6 -7
View File
@@ -50,7 +50,7 @@ class TestHubQuestions(HubCase):
with mock.patch.object(batches, "UNDO", 0.05): with mock.patch.object(batches, "UNDO", 0.05):
status, _, body = self.approve(items, proof) status, _, body = self.approve(items, proof)
self.assertEqual(status, 202, body) self.assertEqual(status, 202, body)
self.settle(lambda: self.state(decision_id)["status"] == "decided") self.settle(lambda: self.httpd.hub.decisions.get(decision_id)["status"] == "decided")
def hook(self, payload: dict, timeout: str) -> subprocess.Popen: def hook(self, payload: dict, timeout: str) -> subprocess.Popen:
trust = ["--approvers", str(self.approvers), "--replay", str(self.replay / "hook.json")] trust = ["--approvers", str(self.approvers), "--replay", str(self.replay / "hook.json")]
@@ -120,19 +120,18 @@ class TestHubQuestions(HubCase):
single = self.ask_question(BODY) single = self.ask_question(BODY)
self.assertEqual(self.approve([self.entry("decision", single, f"{PICK}\n{PICK}", "")], None)[0], 400) self.assertEqual(self.approve([self.entry("decision", single, f"{PICK}\n{PICK}", "")], None)[0], 400)
def test_a_hook_question_also_takes_one_trimmed_line_of_other_text_and_an_mcp_decision_does_not(self): def test_every_decision_takes_one_trimmed_line_of_other_text_as_an_ask_user_question_does(self):
self.claim("s1", "Skills session") self.claim("s1", "Skills session")
signer = self.pin() signer = self.pin()
single, multi, mcp = self.ask_question(BODY), self.ask_question(MULTI_BODY), self.decision("") single, multi, mcp = self.ask_question(BODY), self.ask_question(MULTI_BODY), self.decision("")
item = next(item for item in self.snapshot()["inbox"] if item["id"] == mcp) for decision_id, label in ((single, " padded"), (single, "x" * 1001), (single, "tab\there"), (mcp, "two\nlines"), (mcp, "padded ")):
self.assertFalse(item["other"])
self.assertTrue(next(item for item in self.snapshot()["inbox"] if item["id"] == single)["other"])
for decision_id, label in ((single, " padded"), (single, "x" * 1001), (single, "tab\there"), (mcp, "free text")):
with self.subTest(label=label[:20]): with self.subTest(label=label[:20]):
self.assertEqual(self.approve([self.entry("decision", decision_id, label, "")], None)[0], 400) self.assertEqual(self.approve([self.entry("decision", decision_id, label, "")], None)[0], 400)
self.pick(single, "Keep the old one", signer) self.pick(single, "Keep the old one", signer)
self.pick(multi, "None of these", signer) self.pick(multi, "None of these", signer)
self.assertEqual((self.state(single)["choice"], self.state(multi)["choice"]), ("Keep the old one", "None of these")) self.pick(mcp, "Ask Main first", signer)
self.assertEqual([self.httpd.hub.decisions.get(found)["choice"] for found in (single, multi, mcp)], ["Keep the old one", "None of these", "Ask Main first"])
self.assertTrue(all("other" not in item for item in self.snapshot()["inbox"]))
def test_the_hook_passes_a_signed_other_text_on_as_the_answer(self): def test_the_hook_passes_a_signed_other_text_on_as_the_answer(self):
self.claim("s1", "Skills session") self.claim("s1", "Skills session")
+21 -9
View File
@@ -87,7 +87,7 @@ class TestOperator(unittest.TestCase):
def _add(self, slug: str, workdir: Path, command: str, reason: str, check: str) -> None: def _add(self, slug: str, workdir: Path, command: str, reason: str, check: str) -> None:
self.assertEqual( self.assertEqual(
self._out("add", slug, "--dir", str(workdir), "--command", command, "--reason", reason, self._out("add", slug, "--dir", str(workdir), "--command", command, "--reason", reason,
"--check", check), "--check", check, *(("--option", "Yes=go ahead", "--option", "No=leave it") if check == "decision" else ())),
[f"added operator/{slug}"], [f"added operator/{slug}"],
) )
@@ -184,25 +184,37 @@ class TestOperator(unittest.TestCase):
def _register(self) -> dict[str, dict]: def _register(self) -> dict[str, dict]:
return json.loads((self.root / "rasci.json").read_text(encoding="utf-8")) return json.loads((self.root / "rasci.json").read_text(encoding="utf-8"))
def test_a_decision_row_keeps_its_options_and_pick_and_a_re_add_without_them_drops_both(self): def test_a_decision_row_keeps_its_options_and_pick_and_a_re_add_without_them_is_refused(self):
question = ["add", "pick", "--dir", str(self.base), "--command", "decide: keep or remove it", "--reason", "only the operator may", "--check", "decision"] question = ["add", "pick", "--dir", str(self.base), "--command", "decide: keep or remove it", "--reason", "only the operator may", "--check", "decision"]
self._out(*question, "--option", "Keep=ships with the PR", "--option", "Remove = drop it first", "--recommended", "Remove") self._out(*question, "--option", "Keep=ships with the PR", "--option", "Remove = drop it first", "--recommended", "Remove")
kept = ([{"label": "Keep", "description": "ships with the PR"}, {"label": "Remove", "description": "drop it first"}], "Remove")
row = self._register()["operator/pick"] row = self._register()["operator/pick"]
self.assertEqual((row["options"], row["recommended"]), ([{"label": "Keep", "description": "ships with the PR"}, {"label": "Remove", "description": "drop it first"}], "Remove")) self.assertEqual((row["options"], row["recommended"]), kept)
self._out(*question) refused = self._run(*question)
self.assertEqual({"options", "recommended"} & set(self._register()["operator/pick"]), set()) self.assertEqual(refused.returncode, 2)
self.assertIn("--check decision needs 2 to 4 --option values", refused.stderr)
row = self._register()["operator/pick"]
self.assertEqual((row["options"], row["recommended"]), kept)
def test_options_need_a_decision_row_distinct_labels_and_a_known_pick(self): def test_options_need_a_decision_row_two_to_four_distinct_labels_and_a_known_pick(self):
add = ["add", "bad", "--dir", str(self.base), "--command", "decide: x", "--reason", "r"] add = ["add", "bad", "--dir", str(self.base), "--command", "decide: x", "--reason", "r"]
two = ("--option", "A=x", "--option", "C=z")
refused = { refused = {
"manual": self._run(*add[:-2], "--command", "echo hi", "--reason", "r", "--check", "manual", "--option", "A"), "manual": self._run(*add[:-2], "--command", "echo hi", "--reason", "r", "--check", "manual", "--option", "A"),
"manual pick": self._run(*add[:-2], "--command", "echo hi", "--reason", "r", "--check", "manual", "--recommended", "A"),
"none": self._run(*add, "--check", "decision"),
"one": self._run(*add, "--check", "decision", "--option", "A=x"),
"five": self._run(*add, "--check", "decision", *[part for label in "ABCDE" for part in ("--option", label)]),
"twice": self._run(*add, "--check", "decision", "--option", "A=x", "--option", "A=y"), "twice": self._run(*add, "--check", "decision", "--option", "A=x", "--option", "A=y"),
"unknown pick": self._run(*add, "--check", "decision", "--option", "A", "--recommended", "B"), "unknown pick": self._run(*add, "--check", "decision", *two, "--recommended", "B"),
"pick alone": self._run(*add, "--check", "decision", "--recommended", "A"), "pick alone": self._run(*add, "--check", "decision", "--recommended", "A"),
"empty label": self._run(*add, "--check", "decision", "--option", "=only text"), "empty label": self._run(*add, "--check", "decision", *two, "--option", "=only text"),
} }
self.assertEqual({name: result.returncode for name, result in refused.items()}, dict.fromkeys(refused, 2)) self.assertEqual({name: result.returncode for name, result in refused.items()}, dict.fromkeys(refused, 2))
self.assertTrue(all("needs 2 to 4" in refused[name].stderr for name in ("none", "one", "five", "pick alone")), {name: result.stderr for name, result in refused.items()})
self.assertNotIn("operator/bad", self._register() if (self.root / "rasci.json").exists() else {}) self.assertNotIn("operator/bad", self._register() if (self.root / "rasci.json").exists() else {})
self.assertEqual(self._run(*add, "--check", "decision", *two, "--option", "B=y", "--option", "D=w", "--recommended", "B").returncode, 0)
self.assertEqual([option["label"] for option in self._register()["operator/bad"]["options"]], ["A", "C", "B", "D"])
def _session(self, sid: str, name: str) -> None: def _session(self, sid: str, name: str) -> None:
(self.home / ".claude" / "sessions" / f"{sid}.json").write_text(json.dumps({"sessionId": sid, "name": name}), encoding="utf-8") (self.home / ".claude" / "sessions" / f"{sid}.json").write_text(json.dumps({"sessionId": sid, "name": name}), encoding="utf-8")
@@ -329,7 +341,7 @@ class TestOperator(unittest.TestCase):
result = self._run("add", "x", "--dir", str(self.base), "--command", command, "--reason", "r", result = self._run("add", "x", "--dir", str(self.base), "--command", command, "--reason", "r",
"--check", "manual") "--check", "manual")
self.assertEqual(result.returncode, 2, command) self.assertEqual(result.returncode, 2, command)
self.assertIn("record the step with --check decision", result.stderr) self.assertIn("ask the step as --check decision with 2 to 4 --option answers", result.stderr)
self._add("subshell", self.base, "(umask 077; touch secret)", "r", "manual") self._add("subshell", self.base, "(umask 077; touch secret)", "r", "manual")
self._add("env", self.base, "GIT_CONFIG_COUNT=1 git status", "r", "manual") self._add("env", self.base, "GIT_CONFIG_COUNT=1 git status", "r", "manual")
self._add("ask", self.base, "Edit pcs.yml: add the group", "r", "decision") self._add("ask", self.base, "Edit pcs.yml: add the group", "r", "decision")
+1 -1
View File
@@ -10,7 +10,7 @@ from pathlib import Path
from hub_support import signing from hub_support import signing
TEMPLATES = Path(__file__).resolve().parent.parent / "orchestrator" / "templates" TEMPLATES = Path(__file__).resolve().parent.parent / "orchestrator" / "templates"
MODULES = ["page-constants.js", "glossary.js", "ancestry.js", "page-reveal.js", "page-dom.js", "page-diff.js", "page-rule-request.js", "page-inbox.js", "page-grant.js", "page-firewall.js", "page-review.js", "page-cleanup.js", "page-offices.js", "page-ancestry.js", "page-tasks-prio.js"] MODULES = ["page-constants.js", "glossary.js", "ancestry.js", "page-reveal.js", "page-dom.js", "page-dialog.js", "page-diff.js", "page-rule-request.js", "page-inbox.js", "page-grant.js", "page-firewall.js", "page-review.js", "page-cleanup.js", "page-offices.js", "page-ancestry.js", "page-tasks-prio.js"]
RLO, ZWSP, LRI, SEPARATOR, CARRIAGE = chr(0x202E), chr(0x200B), chr(0x2066), chr(0x2028), chr(0x0D) RLO, ZWSP, LRI, SEPARATOR, CARRIAGE = chr(0x202E), chr(0x200B), chr(0x2066), chr(0x2028), chr(0x0D)
FILLER, NBSP, CGJ, VS15, VS16 = chr(0x3164), chr(0xA0), chr(0x34F), chr(0xFE0E), chr(0xFE0F) FILLER, NBSP, CGJ, VS15, VS16 = chr(0x3164), chr(0xA0), chr(0x34F), chr(0xFE0E), chr(0xFE0F)
HIDDEN = (RLO, ZWSP, LRI, SEPARATOR, CARRIAGE, FILLER, NBSP, CGJ, VS16) HIDDEN = (RLO, ZWSP, LRI, SEPARATOR, CARRIAGE, FILLER, NBSP, CGJ, VS16)