Merge branch 'feature/hub-gate-chips-glossary' into unify/skills-20261114

This commit is contained in:
Kevin Veen-Birkenbach committed 2026-11-14 22:00:15 +00:00
commit 4496479e86
14 files changed
+400 -48

No files matched your search

+1 -2
View File
@@ -72,8 +72,7 @@ const Ancestry = (() => {
const level = LEVELS.includes(found.level) ? found.level : "none";
const source = typeof found.source === "string" ? found.source : "";
const own = source === branch;
const from = own ? "own rule" : source ? `from ${source}` : "no rule";
return {action, level, source, own, inherited: !own, icon: LEVEL_ICONS[level], title: `${action}: ${level} · ${from}`};
return {action, level, source, own, inherited: !own, icon: LEVEL_ICONS[level]};
});
}
+77
View File
@@ -0,0 +1,77 @@
const Glossary = (() => {
"use strict";
const RULE_HINTS = {
ask: "Grants matching asks in matching directories, never a command with a warning (rm -r, push, --force, sudo, pipes into a shell …). The passkey signs the rule and the agents it applies to once; the hook checks signature, pattern and agent itself.",
review: "Grants reviews of matching branches and worktrees, only when their gate is green, for every agent: a review names no session. The passkey signs the rule once; the commit skill checks signature and pattern itself.",
decision: "Takes the recommended option in decisions of matching agents. The passkey signs the rule once; the decisions themselves stay unsigned.",
};
const OFFICE_VERBS = {
appoint: ["Appoint", "bi-person-plus", "council.py claim --operator on the host: the chosen session gets the free office."],
takeover: ["Hand over", "bi-arrow-left-right", "council.py takeover --operator on the host: the office goes to the chosen session, even if the current holder is still alive."],
recall: ["Recall", "bi-person-x", "council.py release --operator on the host: the office becomes free, even if the holder is still alive."],
};
const GATE_ACTIONS = {
commit: "a commit on this branch needs a gate receipt for its tree that meets the level; the commit-msg and pre-merge-commit hooks check it.",
merge: "a merge into this branch needs a receipt that meets the level; the pre-merge-commit hook checks it, the pre-push hook checks fast-forward and squash merges.",
push: "pushing this branch needs a receipt that meets the level for the tree of every pushed commit; the pre-push hook checks it.",
pr: "a pull request from this branch needs the level; gates.py resolve reports it, no git hook checks it.",
};
const GATE_LEVELS = {
none: "no receipt needed.",
quick: "gates.py quick passed on the staged files: Python syntax, JSON, bash -n and git diff --check.",
test: "a green make test on the exact tree, GPU tests off.",
"quality-high": "a green make quality-high on the exact tree, GPU tests off.",
e2e: "a green make e2e on the exact tree, GPU tests off; the strictest level.",
};
const RECEIPT = ["receipt", "a green run records one for its tree; it meets its own level and every lower one for 30 days."];
const GATE_SOURCES = {
own: ["own rule", "the branch sets this level itself."],
inherited: ["inherited from", "the branch sets no level, so the strictest level of its parent branches applies; the chip names the branch that sets it."],
unset: ["no rule", "neither the branch nor a parent sets a level, so the action needs no receipt."],
staged: ["staged", "changed here, not applied yet: Apply signs every staged change with one passkey signature, Discard drops them."],
};
const GATE_CYCLE = ["click, Enter or Space", "cycles the own rule through none, quick, test, quality-high and e2e, then back to inherited."];
const BRANCH_MARKS = {
merged: ["merged", "pkgmgr branch gc found every tip of the branch in the default branch or a merge line."],
unmerged: ["not merged", "the branch holds commits the default branch does not have."],
protected: ["protected", "the default or a protected branch: gc never deletes it."],
stale: ["stale", "pkgmgr branch gc marks the entry stale; the Reason line says why."],
unpushed: ["commits unpushed", "local commits its upstream does not have yet."],
behind: ["commits behind", "upstream commits the local branch does not have yet."],
gone: ["upstream gone", "the remote branch it tracks was deleted."],
detached: ["no upstream", "the branch tracks no remote branch."],
skip: ["gc skips", "pkgmgr branch gc leaves the branch alone for the reason shown."],
reason: ["Reason", "pkgmgr's own words: merged by ancestor, by patch or by a pull request; unmerged with the commits not in the default branch; no own commits; dirty with the changed paths; default or protected branch."],
};
/**
* @param {Object} mark one Ancestry.gateMarks entry: action, level, source and own.
* @param {Object|null} staged the staged change of the chip, its level null when it drops the own rule.
* @returns {Object} text: the chip text, also its aria-label; hint: the tooltip that explains it.
*/
function gateChip(mark, staged) {
const kind = staged ? "staged" : mark.own ? "own" : mark.source ? "inherited" : "unset";
const level = staged ? staged.level || "inherited" : mark.level;
const from = kind === "inherited" ? `${GATE_SOURCES.inherited[0]} ${mark.source}` : GATE_SOURCES[kind][0];
const text = `${mark.action}: ${level} (${from})`;
const meaning = Object.hasOwn(GATE_LEVELS, level) ? GATE_LEVELS[level] : GATE_SOURCES.inherited[1];
return {text, hint: [text, `${mark.action}: ${GATE_ACTIONS[mark.action]}`, `${level}: ${meaning}`, `${from}: ${GATE_SOURCES[kind][1]}`, `${GATE_CYCLE[0]}: ${GATE_CYCLE[1]}`].join("\n")};
}
/**
* @returns {Array<[string, Array<[string, string]>]>} the sections the Explain action lists, each a heading and its [term, meaning] rows.
*/
function explain() {
return [
["Gate actions", Object.entries(GATE_ACTIONS)],
["Gate levels", [...Object.entries(GATE_LEVELS), RECEIPT]],
["Where a level comes from", [...Object.values(GATE_SOURCES), GATE_CYCLE]],
["Branch marks", Object.values(BRANCH_MARKS)],
];
}
return {RULE_HINTS, OFFICE_VERBS, GATE_ACTIONS, GATE_LEVELS, GATE_SOURCES, GATE_CYCLE, RECEIPT, BRANCH_MARKS, gateChip, explain};
})();
if (typeof module === "object" && module.exports) {
module.exports = Glossary;
}
+2
View File
@@ -495,6 +495,8 @@ pre.notes { margin: 0; padding: 8px 10px; background: var(--sunken); border-radi
{% include "panels.js" %}
{% include "glossary.js" %}
{% include "ancestry.js" %}
{% include "popup.js" %}
+23 -10
View File
@@ -20,30 +20,43 @@
return ((tree.data && tree.data.gates) || {})[repo] ? tree.data.gates[repo][name] || null : null;
}
function gateIcons(repo, name) {
function gateChips(repo, name) {
const found = gatesOf(repo, name);
const own = (found && found.rules) || {};
return h("span", {class: "gates", role: "group", "aria-label": `Gates of ${name}`}, Ancestry.gateMarks(name, found).map((mark) => {
return h("span", {class: "gates", role: "group", "aria-label": `Gates of ${name}`, "data-repo": repo, "data-branch": name}, Ancestry.gateMarks(name, found).map((mark) => {
const key = `rule\u0000${repo}\u0000${name}\u0000${mark.action}`;
const staged = gateStage.items.find((item) => item.key === key);
const staged = gateStage.items.find((item) => item.key === key) || null;
const current = Object.hasOwn(own, mark.action) ? own[mark.action] : null;
const level = staged ? staged.level || "none" : mark.level;
const title = staged ? `${mark.action}: ${staged.level || "inherited"} · staged` : mark.title;
const chip = Glossary.gateChip(mark, staged);
const cycle = (event) => {
const group = event.currentTarget.closest(".gates");
const button = event.currentTarget;
const group = button.closest(".gates");
const focused = document.activeElement === button;
const next = Ancestry.nextRule(staged ? staged.level : current);
stageGate(key, next === current ? null : {argv: Ancestry.ruleArgv(repo, name, mark.action, next), level: next});
if (group && group.isConnected) {
group.replaceWith(gateIcons(repo, name));
const fresh = group && group.isConnected ? gateChips(repo, name) : null;
if (fresh) {
group.replaceWith(fresh);
}
const holder = fresh || [...document.querySelectorAll("#main .gates")].find((node) => node.dataset.repo === repo && node.dataset.branch === name);
if (focused && holder) {
holder.querySelector(`.gate-mark[data-action="${mark.action}"]`).focus();
}
};
return h("button", {
type: "button", class: ["gate-mark", "icon-only", mark.inherited && !staged ? "inherited" : "", staged ? "pending" : ""].filter(Boolean).join(" "),
"data-action": mark.action, "data-level": level, "data-source": mark.source, ...named(`${mark.action} gate`, title), on: {click: cycle},
}, icon(Ancestry.LEVEL_ICONS[level]));
type: "button", class: ["gate-mark", mark.inherited && !staged ? "inherited" : "", staged ? "pending" : ""].filter(Boolean).join(" "),
"data-action": mark.action, "data-level": level, "data-source": mark.source, ...named(revealed(chip.text), revealedLines(chip.hint)), on: {click: cycle},
}, icon(Ancestry.LEVEL_ICONS[level]), h("span", {class: "gate-text"}, revealed(chip.text)));
}));
}
function gateExplain() {
return h("details", {class: "gate-explain"}, h("summary", {title: "Explain: what each mark of this branch means"}, icon("bi-question-circle"), "Explain"),
Glossary.explain().map(([heading, rows]) => h("section", {}, h("h4", {}, heading),
h("dl", {class: "glossary"}, rows.map(([term, meaning]) => h("div", {}, h("dt", {}, term), h("dd", {}, meaning)))))));
}
function gateApply() {
const count = gateStage.items.length;
if (!count) {
+1 -1
View File
@@ -239,7 +239,7 @@
body.push(meta([["Path", data.path], ["Remote", data.remote], ["Default", data.default], ["Forge", data.forge], ["As of", data.scanned_at]]),
h("p", {class: "muted"}, `${data.branches.length} Branches · ${data.branches.reduce((sum, entry) => sum + entry.worktrees.length, 0) + data.detached.length} Worktrees`));
} else if (node.kind === "branch") {
body.push(h("div", {class: "states"}, branchStates(data), gateIcons(node.repo, data.name)), meta([["Upstream", data.upstream], ["Head", data.head.slice(0, 12), data.head], ["Merged into", data.merged_into], ["Reason", data.reason]]),
body.push(h("div", {class: "states"}, branchStates(data), gateChips(node.repo, data.name)), gateExplain(), meta([["Upstream", data.upstream], ["Head", data.head.slice(0, 12), data.head], ["Merged into", data.merged_into], ["Reason", data.reason]]),
data.worktrees.map((wt) => flowDetails(wt.flow, data.name)),
h("h3", {}, "Dry run"), h("pre", {class: "notes"}, data.plan.join("\n")), glance ? null : h("div", {class: "actions"}, deleteButton(data)));
} else if (node.kind === "worktree") {
+1 -5
View File
@@ -1,9 +1,5 @@
const OFFICE_RESULTS = {done: ["done", "ok"], refused: ["refused", "bad"], failed: ["failed", "bad"]};
const OFFICE_VERBS = {
appoint: ["Appoint", "bi-person-plus", "council.py claim --operator on the host: the chosen session gets the free office."],
takeover: ["Hand over", "bi-arrow-left-right", "council.py takeover --operator on the host: the office goes to the chosen session, even if the current holder is still alive."],
recall: ["Recall", "bi-person-x", "council.py release --operator on the host: the office becomes free, even if the holder is still alive."],
};
const OFFICE_VERBS = Glossary.OFFICE_VERBS;
const OFFICE_HINT = "The host checks your passkey signature itself and refuses if the holder changed since the signature.";
function successors(office, holder) {
+1 -5
View File
@@ -1,9 +1,5 @@
const RULE_KINDS = {ask: "Ask: tool + command pattern", review: "Review: branch pattern + gate green", decision: "Decision: take the recommendation"};
const RULE_HINTS = {
ask: "Grants matching asks in matching directories, never a command with a warning (rm -r, push, --force, sudo, pipes into a shell …). The passkey signs the rule and the agents it applies to once; the hook checks signature, pattern and agent itself.",
review: "Grants reviews of matching branches and worktrees, only when their gate is green, for every agent: a review names no session. The passkey signs the rule once; the commit skill checks signature and pattern itself.",
decision: "Takes the recommended option in decisions of matching agents. The passkey signs the rule once; the decisions themselves stay unsigned.",
};
const RULE_HINTS = Glossary.RULE_HINTS;
/**
* @param {Object} rule the stored rule to turn on again, which widens what agents may do.
+1 -1
View File
@@ -110,7 +110,7 @@
const result = resultOf(repo, entry);
return h("div", {class: "branch-row", "data-item": `artifact:${artifactRef(`branch:${repo.path}\u0000${entry.name}`)}`},
h("div", {class: "branch-name", "data-star-slot": ""}, h("strong", {}, entry.name), h("span", {class: "states"}, branchStates(entry)), entry.upstream ? h("span", {class: "muted"}, `↔ ${entry.upstream}`) : null,
h("span", {class: "muted", title: entry.head}, entry.head.slice(0, 10)), result ? resultChip(result) : null, h("span", {class: "spacer"}), gateIcons(repo.path, entry.name), glance ? null : deleteButton(entry)),
h("span", {class: "muted", title: entry.head}, entry.head.slice(0, 10)), result ? resultChip(result) : null, h("span", {class: "spacer"}), gateChips(repo.path, entry.name), glance ? null : deleteButton(entry)),
entry.worktrees.map(worktreeRow));
}
+14 -4
View File
@@ -8,10 +8,20 @@ svg .ancestry-edge.dropping { stroke: var(--bad); opacity: .5; }
svg .ancestry-node { cursor: grab; }
svg .ancestry-node:active { cursor: grabbing; }
svg .ancestry-node .label { fill: var(--text); font-size: var(--fs-2xs); }
.gates { display: inline-flex; align-items: center; gap: 2px; }
.gate-mark { display: inline-grid; place-items: center; width: 24px; height: 24px; padding: 0; border: 0; border-radius: 6px; background: transparent; color: var(--text); cursor: pointer; }
.gates { display: inline-flex; flex-wrap: wrap; align-items: center; gap: 4px; min-width: 0; max-width: 100%; }
.gate-mark { display: inline-flex; align-items: center; gap: 5px; min-width: 0; max-width: 100%; padding: 1px 9px; border: 1px solid var(--line-strong); border-radius: 999px; background: var(--neutral-soft); color: var(--text); font: inherit; font-size: var(--fs-xs); font-weight: 650; line-height: 20px; text-align: start; cursor: pointer; }
.gate-mark .bi { flex: none; }
.gate-mark .gate-text { min-width: 0; overflow-wrap: anywhere; }
.gate-mark:hover { background: var(--hover); }
.gate-mark.inherited { opacity: .4; }
.gate-mark.pending { outline: 1px dashed var(--info); color: var(--info); }
.gate-mark:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; }
.gate-mark.inherited { border-style: dashed; background: transparent; color: var(--muted); }
.gate-mark.pending { border: 1px dashed var(--info); background: var(--info-soft); color: var(--info); }
.gate-explain { margin: 4px 0 8px; }
.gate-explain > summary { display: inline-flex; align-items: center; gap: 6px; padding: 2px 0; color: var(--accent); font-weight: 650; cursor: pointer; }
.gate-explain h4 { margin: 10px 0 4px; color: var(--muted); font-size: var(--fs-xs); font-weight: 650; letter-spacing: .04em; text-transform: uppercase; }
.glossary { display: grid; gap: 4px; margin: 0; }
.glossary > div { display: grid; grid-template-columns: minmax(0, 9em) minmax(0, 1fr); gap: 8px; }
.glossary dt { font-weight: 650; overflow-wrap: anywhere; }
.glossary dd { margin: 0; color: var(--muted); overflow-wrap: anywhere; }
.gate-apply, .gate-staged { display: inline-flex; align-items: center; gap: 4px; }
.dry-run.locked pre { opacity: .6; }
+82 -14
View File
@@ -21,6 +21,12 @@ GATES_SPEC = importlib.util.spec_from_file_location("kvb_gates_for_e2e", REPO_RO
gates = importlib.util.module_from_spec(GATES_SPEC)
GATES_SPEC.loader.exec_module(gates)
KEPT_TIP = "0c9d8e7f6a5b4c3d2e1f0a9b8c7d6e5f4a3b2c1d"
DONE_CHIPS = ["commit: test (inherited from main)", "merge: none (no rule)", "push: none (no rule)", "pr: e2e (own rule)"]
DONE_MARKS = [[action, level, inherited, words, inherited, True] for (action, level, inherited), words in zip([("commit", "test", True), ("merge", "none", True), ("push", "none", True), ("pr", "e2e", False)], DONE_CHIPS, strict=True)]
EXPLAINED = ["Gate actions", "Gate levels", "Where a level comes from", "Branch marks"]
CHIP_STATE = """
const chipState = (button) => [button.dataset.action, button.dataset.level, button.classList.contains("inherited"), button.getAttribute("aria-label"), getComputedStyle(button).borderTopStyle === "dashed", text(button) === button.getAttribute("aria-label") && button.title.split("\\n")[0] === text(button)];
"""
CLEAN_ALL = """(async () => {@HELPERS@@UNLABELLED@
const every = await until(() => document.querySelector('#main button[aria-label="Delete all merged"]'), 8000);
await until(() => document.querySelector("#main svg.ancestry"), 8000);
@@ -40,7 +46,7 @@ CLEAN_ALL = """(async () => {@HELPERS@@UNLABELLED@
return {before, token, store: store ? [store.title, store.getAttribute("aria-label")] : null, rows, outcome: outcome ? (outcome.dataset.cleanup ? "queued" : "unsigned") : null, tokenClick, labels,
wide: document.documentElement.scrollWidth > document.documentElement.clientWidth};
})()"""
ANCESTRY = """(async () => {@HELPERS@@UNLABELLED@
ANCESTRY = """(async () => {@HELPERS@@UNLABELLED@@CHIPS@
const svg = await until(() => document.querySelector('#main svg.ancestry[aria-label="Ancestry of github.com/me/demo"]'), 8000);
if (!svg) {
return {error: "no ancestry"};
@@ -49,9 +55,10 @@ ANCESTRY = """(async () => {@HELPERS@@UNLABELLED@
const edges = all("path.ancestry-edge", svg).map((edge) => [edge.dataset.parent, edge.dataset.child, edge.dataset.source, getComputedStyle(edge).strokeDasharray !== "none"]);
const marks = (branch) => {
const row = all("#main .branch-row").find((entry) => text(entry.querySelector(".branch-name strong")) === branch);
return row ? all(".gate-mark", row).map((button) => [button.dataset.action, button.dataset.level, button.classList.contains("inherited"), button.title, Number(getComputedStyle(button).opacity) < 1]) : null;
return row ? all(".gate-mark", row).map(chipState) : null;
};
return {nodes, edges, done: marks("feature/done"), main: marks("main"), unlabelled: unlabelled(document.getElementById("main")), wide: document.documentElement.scrollWidth > document.documentElement.clientWidth};
const inside = all("#main .gate-mark").every((chip) => chip.getBoundingClientRect().right <= document.documentElement.clientWidth + 1);
return {nodes, edges, done: marks("feature/done"), main: marks("main"), inside, unlabelled: unlabelled(document.getElementById("main")), wide: document.documentElement.scrollWidth > document.documentElement.clientWidth};
})()"""
STAGE = """(async () => {@HELPERS@
const svg = await until(() => document.querySelector("#main svg.ancestry"), 8000);
@@ -102,10 +109,10 @@ AGENTS = """(async () => {@HELPERS@@UNLABELLED@
const nodes = all("g.ancestry-node", fresh).map((node) => [node.dataset.kind, Number(node.dataset.generation), node.getBoundingClientRect().top]);
return {nodes, edges: all("path.ancestry-edge", fresh).length, list: all("#main .spawn-tree li").length, unlabelled: unlabelled(document.getElementById("main")), wide: document.documentElement.scrollWidth > document.documentElement.clientWidth};
})()"""
POPUP_GATES = """(async () => {@HELPERS@@UNLABELLED@
POPUP_GATES = """(async () => {@HELPERS@@UNLABELLED@@CHIPS@
const id = `branch:${@REPO@}\\u0000feature/done`;
const dialog = document.getElementById("popup");
const marks = (group) => all(".gate-mark", group).map((button) => [button.dataset.action, button.dataset.level, button.classList.contains("inherited"), button.title, Number(getComputedStyle(button).opacity) < 1]);
const marks = (group) => all(".gate-mark", group).map(chipState);
const shut = async () => {
(document.activeElement || document.body).dispatchEvent(new KeyboardEvent("keydown", {key: "Escape", bubbles: true}));
await until(() => !dialog.open, 4000);
@@ -152,10 +159,56 @@ POPUP_GATES = """(async () => {@HELPERS@@UNLABELLED@
}
return {shown, wide: document.documentElement.scrollWidth > document.documentElement.clientWidth};
})()"""
POPUP_EXPLAIN = """(async () => {@HELPERS@
const id = `branch:${@REPO@}\\u0000feature/done`;
const dialog = document.getElementById("popup");
await screenShown(8000);
const picker = await until(() => document.querySelector('#main select[aria-label="Repository"]'), 8000);
if (picker && picker.value !== @REPO@) {
picker.value = @REPO@;
picker.dispatchEvent(new Event("change", {bubbles: true}));
}
const target = await until(() => all("#main svg [data-pick]").find((node) => node.dataset.pick === id), 8000);
if (!target) {
return {error: text(document.getElementById("main"))};
}
target.dispatchEvent(new MouseEvent("click", {bubbles: true, cancelable: true}));
const group = await until(() => dialog.open && dialog.querySelector(".popup-box .gates"), 6000);
const explain = group ? dialog.querySelector(".popup-box details.gate-explain") : null;
if (!explain) {
return {error: "no gate chips or Explain in the popup", open: dialog.open};
}
explain.querySelector("summary").click();
await until(() => explain.open, 2000);
const box = dialog.querySelector(".popup-box");
const frame = box.getBoundingClientRect();
const inside = (node) => {
const rect = node.getBoundingClientRect();
return rect.left >= frame.left - 1 && rect.right <= frame.right + 1 && rect.right <= document.documentElement.clientWidth + 1;
};
const chips = all(".gate-mark", group);
const commit = group.querySelector('.gate-mark[data-action="commit"]');
commit.focus();
return {
chips: chips.map((chip) => [text(chip), chip.getAttribute("aria-label"), chip.title.split("\\n")[0], chip.tabIndex]),
inside: [...chips, explain].map(inside),
scrolls: [box, dialog.querySelector(".popup-body")].some((node) => node.scrollWidth > node.clientWidth + 1),
summary: [text(explain.querySelector("summary")), explain.open],
headings: all("h4", explain).map(text), terms: all("dt", explain).length,
focused: document.activeElement === commit,
wide: document.documentElement.scrollWidth > document.documentElement.clientWidth,
};
})()"""
KEYBOARD = """(async () => {@HELPERS@
const dialog = document.getElementById("popup");
const staged = await until(() => dialog.querySelector('.popup-box .gate-mark.pending[data-action="commit"]'), 4000);
const apply = document.querySelector('#main button[aria-label="Apply"]');
return {open: dialog.open, staged: staged ? [text(staged), staged.getAttribute("aria-label"), staged.dataset.level] : null, focused: Boolean(staged) && document.activeElement === staged, apply: apply ? apply.title : null};
})()"""
def probe(template: str) -> str:
return template.replace("@HELPERS@", base.HELPERS).replace("@UNLABELLED@", base.UNLABELLED)
return template.replace("@HELPERS@", base.HELPERS).replace("@UNLABELLED@", base.UNLABELLED).replace("@CHIPS@", CHIP_STATE)
@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium")
@@ -196,13 +249,31 @@ class TestWorkbenchArtifacts(HubCase):
{"width": width, "height": height, "url": f"{self.base}?{width}-clean#artifacts/tree", "wait": 1200, "probe": probe(CLEAN_ALL), "shot": f"{shot}-clean-all.png"},
{"width": width, "height": height, "url": f"{self.base}?{width}#agents/tree", "wait": 1200, "probe": probe(AGENTS), "shot": f"{shot}-agents-ancestry.png"},
{"width": width, "height": height, "url": f"{self.base}?{width}-popups#artifacts/orbit", "wait": 1200, "probe": probe(POPUP_GATES).replace("@REPO@", json.dumps(self.repo)).replace("@THREE@", "true" if width == 1366 else "false"), "shot": f"{shot}-popup-gates.png"},
{"width": width, "height": height, "url": f"{self.base}?{width}-explain#artifacts/orbit", "wait": 1200, "probe": probe(POPUP_EXPLAIN).replace("@REPO@", json.dumps(self.repo)), "shot": f"{shot}-popup-explain.png"},
]
if browser == "chromium":
steps.append({"width": width, "height": height, "url": None, "wait": 0, "keys": ["Enter"], "probe": probe(KEYBOARD), "shot": f"{shot}-popup-keyboard.png"})
return steps
def check_chips(self, explained: dict, typed: dict | None, browser: str, width: int) -> None:
with self.subTest(browser=browser, width=width, part="popup chips and Explain"):
self.assertNotIn("error", explained, explained)
self.assertEqual(explained["chips"], [[words, words, words, 0] for words in DONE_CHIPS])
self.assertEqual(explained["inside"], [True] * 5, "a gate chip or the Explain list overflows the popup")
self.assertEqual((explained["scrolls"], explained["wide"]), (False, False))
self.assertEqual(explained["summary"], ["Explain", True])
self.assertEqual((explained["headings"], explained["terms"]), (EXPLAINED, 25))
self.assertTrue(explained["focused"])
if typed is not None:
with self.subTest(browser=browser, width=width, part="keyboard cycles a chip"):
self.assertEqual(typed["staged"], ["commit: none (staged)", "commit: none (staged)", "none"], typed)
self.assertEqual((typed["open"], typed["focused"], typed["apply"]), (True, True, "Apply 1 gate changes with one passkey signature"), typed)
def check(self, data: dict, browser: str, signs: bool) -> None:
results = iter(data["results"])
for width, _ in base.WIDTHS:
ancestry, staged, clean, agents, popups = next(results), next(results), next(results), next(results), next(results)
ancestry, staged, clean, agents, popups, explained = next(results), next(results), next(results), next(results), next(results), next(results)
self.check_chips(explained, next(results) if browser == "chromium" else None, browser, width)
with self.subTest(browser=browser, width=width, part="popup gate marks"):
self.assertNotIn("error", popups, popups)
views = ["orbit", "chord", "swimlane", *(["3d"] if width == 1366 else [])]
@@ -210,9 +281,7 @@ class TestWorkbenchArtifacts(HubCase):
for found in popups["shown"]:
self.assertNotIn("error", found, found)
self.assertEqual((found["title"], found["group"], found["unlabelled"]), ("feature/done", "Gates of feature/done", []), found)
self.assertEqual([mark[:3] for mark in found["marks"]], [["commit", "test", True], ["merge", "none", True], ["push", "none", True], ["pr", "e2e", False]], found)
self.assertEqual(found["marks"][0][3], "commit: test · from main", found)
self.assertEqual([mark[4] for mark in found["marks"]], [True, True, True, False], found)
self.assertEqual(found["marks"], DONE_MARKS, found)
self.assertEqual(found["marks"], ancestry["done"], "a popup shows other gate levels than the Tree row")
self.assertFalse(popups["wide"])
with self.subTest(browser=browser, width=width, part="unlabelled controls"):
@@ -225,10 +294,9 @@ class TestWorkbenchArtifacts(HubCase):
self.assertEqual(nodes, {"main": 0, "feature": 1, "feature/kept": 1, "feature/done": 2})
self.assertEqual(sorted(ancestry["edges"]), [
["feature", "feature/done", "derived", True], ["feature/kept", "feature/done", "operator", False], ["main", "feature", "recorded", False], ["main", "feature/kept", "derived", True]])
self.assertEqual([mark[:3] for mark in ancestry["done"]], [["commit", "test", True], ["merge", "none", True], ["push", "none", True], ["pr", "e2e", False]])
self.assertEqual([mark[3] for mark in ancestry["done"]][:1], ["commit: test · from main"])
self.assertEqual([mark[4] for mark in ancestry["done"]], [True, True, True, False])
self.assertEqual(ancestry["main"][0][:3], ["commit", "test", False])
self.assertEqual(ancestry["done"], DONE_MARKS)
self.assertEqual(ancestry["main"][0], ["commit", "test", False, "commit: test (own rule)", False, True])
self.assertTrue(ancestry["inside"], "a gate chip of the Tree overflows the viewport")
self.assertEqual((staged["pending"], staged["staged"], staged["count"]), (True, True, "2"), staged)
self.assertEqual(staged["apply"], ["Apply 2 gate changes with one passkey signature", "Apply"])
self.assertEqual(staged["left"], 0 if signs else 2, staged)
+4 -3
View File
@@ -96,7 +96,8 @@ class TestGateMarks(unittest.TestCase):
marks = {mark["action"]: mark for mark in self.data["marks"]}
self.assertEqual(list(marks), ["commit", "merge", "push", "pr"])
self.assertEqual([(marks[a]["level"], marks[a]["own"], marks[a]["inherited"]) for a in marks], [("test", True, False), ("quality-high", False, True), ("none", False, True), ("e2e", True, False)])
self.assertEqual([marks[a]["title"] for a in marks], ["commit: test · own rule", "merge: quality-high · from main", "push: none · no rule", "pr: e2e · own rule"])
self.assertEqual([marks[a]["source"] for a in marks], ["feature/a", "main", "", "feature/a"])
self.assertNotIn("title", marks["commit"])
self.assertEqual([marks[a]["icon"] for a in marks], ["bi-check2-circle", "bi-shield-check", "bi-circle", "bi-browser-chrome"])
def test_a_branch_gates_py_does_not_know_shows_none_inherited_for_every_action(self):
@@ -120,14 +121,14 @@ class TestAncestryAssets(unittest.TestCase):
done = subprocess.run(["node", "--check", str(ANCESTRY)], capture_output=True, text=True, timeout=60, check=False)
self.assertEqual(done.returncode, 0, done.stderr)
self.assertIn("svg .ancestry-edge.derived { stroke-dasharray: 5 5; }", STYLE.read_text(encoding="utf-8"))
self.assertIn(".gate-mark.inherited { opacity: .4; }", STYLE.read_text(encoding="utf-8"))
self.assertIn(".gate-mark.inherited { border-style: dashed; background: transparent; color: var(--muted); }", STYLE.read_text(encoding="utf-8"))
def test_every_new_control_is_an_icon_with_title_and_aria_label(self):
page = PAGE.read_text(encoding="utf-8")
for control in re.findall(r'iconBtn\("(bi-[a-z0-9-]+)", "([^"]+)"', page):
with self.subTest(control=control):
self.assertTrue(control[1])
self.assertIn('...named(`${mark.action} gate`, title)', page)
self.assertIn("...named(revealed(chip.text), revealedLines(chip.hint))", page)
self.assertIn('role: "button", "aria-label": node.label', page)
+187
View File
@@ -0,0 +1,187 @@
from __future__ import annotations
import json
import re
import subprocess
import unittest
from hub_case import HubCase
from hub_support import HUB, signing
TEMPLATES = HUB / "templates"
GLOSSARY = TEMPLATES / "glossary.js"
ANCESTRY = TEMPLATES / "ancestry.js"
MODULES = ["page-constants.js", "glossary.js", "ancestry.js", "page-reveal.js", "page-dom.js", "page-ancestry.js"]
RESOLVED = {"commit": {"level": "test", "source": "feature/a"}, "merge": {"level": "quality-high", "source": "main"}, "push": {"level": "none", "source": None}, "pr": {"level": "e2e", "source": "feature/a"}}
CHIPS = ["commit: test (own rule)", "merge: quality-high (inherited from main)", "push: none (no rule)", "pr: e2e (own rule)"]
# Param: argv[1] is glossary.js, argv[2] ancestry.js, argv[3] the resolved gates; prints the glossary tables, chip texts and Explain sections.
PROBE = """
const G = require(process.argv[1]);
const A = require(process.argv[2]);
const marks = A.gateMarks("feature/a", {resolved: JSON.parse(process.argv[3])});
console.log(JSON.stringify({
actions: A.ACTIONS, levels: A.LEVELS, gateActions: G.GATE_ACTIONS, gateLevels: G.GATE_LEVELS, sources: G.GATE_SOURCES, cycle: G.GATE_CYCLE, receipt: G.RECEIPT,
ruleHints: G.RULE_HINTS, officeVerbs: G.OFFICE_VERBS, branchMarks: G.BRANCH_MARKS,
chips: marks.map((mark) => G.gateChip(mark, null)),
staged: [G.gateChip(marks[2], {level: "quality-high"}), G.gateChip(marks[0], {level: null})],
explain: G.explain(),
}));
"""
# Param: argv[1] is the templates folder, argv[2] the module list and tree as JSON; prints the gate chips and the Explain block the page builds.
RENDER = r"""
const fs = require("fs");
const [dir, given] = [process.argv[1], JSON.parse(process.argv[2])];
const source = given.files.map((name) => fs.readFileSync(`${dir}/${name}`, "utf8")).join("\n");
class FakeNode {
constructor(tag) { this.tag = tag; this.attrs = {}; this.children = []; this.on = []; }
setAttribute(key, value) { this.attrs[key] = value; }
append(...children) { this.children.push(...children); }
addEventListener(name) { this.on.push(name); }
}
const stub = new Proxy(function () {}, {get: (target, key) => (key === Symbol.toPrimitive ? () => "" : key === Symbol.iterator ? [][Symbol.iterator].bind([]) : stub), apply: () => stub});
const sheet = new FakeNode("div");
const provided = {document: {createElement: (tag) => new FakeNode(tag), createElementNS: (ns, tag) => new FakeNode(tag), getElementById: (id) => (id === "emoji-bases" ? {textContent: "[]"} : sheet), addEventListener() {}}, Node: FakeNode, tree: given.tree};
const scope = new Proxy({}, {has: (target, key) => typeof key === "string" && (key in provided || !(key in globalThis)), get: (target, key) => (key === Symbol.unscopables ? undefined : key in provided ? provided[key] : stub)});
const page = new Function("scope", `with (scope) {\n${source}\nreturn {gateChips, gateExplain};\n}`)(scope);
const dump = (node) => (node instanceof FakeNode ? {tag: node.tag, attrs: node.attrs, on: node.on, children: node.children.map(dump)} : String(node));
console.log(JSON.stringify({chips: dump(page.gateChips("/r", "feature/a")), explain: dump(page.gateExplain())}));
"""
def text_of(node: dict | str) -> str:
return node if isinstance(node, str) else "".join(text_of(child) for child in node["children"])
def find(node: dict | str, tag: str) -> list[dict]:
if isinstance(node, str):
return []
return ([node] if node["tag"] == tag else []) + [hit for child in node["children"] for hit in find(child, tag)]
class TestGlossaryTables(unittest.TestCase):
@classmethod
def setUpClass(cls):
done = subprocess.run(["node", "-e", PROBE, str(GLOSSARY), str(ANCESTRY), json.dumps(RESOLVED)], capture_output=True, text=True, timeout=60, check=True)
cls.data = json.loads(done.stdout)
def assertTexts(self, values: list[str]) -> None:
for value in values:
with self.subTest(value=value):
self.assertIsInstance(value, str)
self.assertGreater(len(value.strip()), 3)
self.assertNotIn(chr(0x2014), value)
def test_every_gate_action_and_level_of_gates_py_has_a_meaning(self):
self.assertEqual(list(self.data["gateActions"]), list(signing.GATE_ACTIONS))
self.assertEqual(list(self.data["gateLevels"]), list(signing.GATE_LEVELS))
self.assertEqual((self.data["actions"], self.data["levels"]), (list(signing.GATE_ACTIONS), list(signing.GATE_LEVELS)))
self.assertTexts([*self.data["gateActions"].values(), *self.data["gateLevels"].values()])
def test_every_rule_hint_and_office_verb_keeps_its_key_and_has_a_text(self):
kinds = re.search(r"const RULE_KINDS = \{([^}]*)\}", (TEMPLATES / "page-rules.js").read_text(encoding="utf-8")).group(1)
self.assertEqual(sorted(self.data["ruleHints"]), sorted(re.findall(r"(\w+): \"", kinds)))
self.assertEqual(sorted(self.data["ruleHints"]), ["ask", "decision", "review"])
self.assertEqual(sorted(self.data["officeVerbs"]), ["appoint", "recall", "takeover"])
self.assertTexts(list(self.data["ruleHints"].values()))
for action, (verb, glyph, words) in self.data["officeVerbs"].items():
with self.subTest(action=action):
self.assertRegex(glyph, r"^bi-[a-z0-9-]+$")
self.assertTexts([verb, words])
def test_every_source_branch_mark_receipt_and_the_click_have_a_term_and_a_meaning(self):
self.assertEqual(sorted(self.data["sources"]), ["inherited", "own", "staged", "unset"])
pairs = [*self.data["sources"].values(), *self.data["branchMarks"].values(), self.data["receipt"], self.data["cycle"]]
for pair in pairs:
with self.subTest(pair=pair):
self.assertEqual(len(pair), 2)
self.assertTexts(pair)
def test_a_chip_names_action_level_and_where_the_level_comes_from(self):
self.assertEqual([chip["text"] for chip in self.data["chips"]], CHIPS)
self.assertEqual([chip["text"] for chip in self.data["staged"]], ["push: quality-high (staged)", "commit: inherited (staged)"])
def test_the_chip_tooltip_starts_with_the_chip_text_and_explains_action_level_source_and_click(self):
tables = self.data
merge = tables["chips"][1]["hint"].split("\n")
self.assertEqual(merge, [
CHIPS[1],
f"merge: {tables['gateActions']['merge']}",
f"quality-high: {tables['gateLevels']['quality-high']}",
f"inherited from main: {tables['sources']['inherited'][1]}",
f"{tables['cycle'][0]}: {tables['cycle'][1]}",
])
dropped = tables["staged"][1]["hint"].split("\n")
self.assertEqual(dropped[2:4], [f"inherited: {tables['sources']['inherited'][1]}", f"staged: {tables['sources']['staged'][1]}"])
def test_explain_lists_every_term_of_the_glossary_once(self):
sections = dict(self.data["explain"])
self.assertEqual(list(sections), ["Gate actions", "Gate levels", "Where a level comes from", "Branch marks"])
terms = [term for rows in sections.values() for term, _ in rows]
self.assertEqual(len(terms), len(set(terms)))
expected = [*signing.GATE_ACTIONS, *signing.GATE_LEVELS, self.data["receipt"][0], *(pair[0] for pair in self.data["sources"].values()), self.data["cycle"][0], *(pair[0] for pair in self.data["branchMarks"].values())]
self.assertEqual(terms, expected)
class TestGlossarySource(unittest.TestCase):
def test_rule_hints_and_office_verbs_are_written_only_in_the_glossary_and_re_exported_under_their_old_names(self):
rules = (TEMPLATES / "page-rules.js").read_text(encoding="utf-8")
offices = (TEMPLATES / "page-offices.js").read_text(encoding="utf-8")
self.assertIn(" const RULE_HINTS = Glossary.RULE_HINTS;\n", rules)
self.assertIn(" const OFFICE_VERBS = Glossary.OFFICE_VERBS;\n", offices)
sources = {path.name: path.read_text(encoding="utf-8") for path in TEMPLATES.glob("*.js")}
for words in ("Grants matching asks in matching directories", "Takes the recommended option", "council.py claim --operator on the host", "council.py release --operator on the host"):
with self.subTest(words=words):
self.assertEqual([name for name, text in sources.items() if words in text], ["glossary.js"])
def test_the_glossary_module_parses_on_its_own(self):
done = subprocess.run(["node", "--check", str(GLOSSARY)], capture_output=True, text=True, timeout=60, check=False)
self.assertEqual(done.returncode, 0, done.stderr)
class TestGateChipsRender(unittest.TestCase):
@classmethod
def setUpClass(cls):
tree = {"data": {"gates": {"/r": {"feature/a": {"resolved": RESOLVED, "rules": {"commit": "test", "pr": "e2e"}, "parents": []}}}}}
done = subprocess.run(["node", "-e", RENDER, str(TEMPLATES), json.dumps({"files": MODULES, "tree": tree})], capture_output=True, text=True, timeout=60, check=False)
if done.returncode != 0:
raise AssertionError(done.stderr.strip()[:800])
cls.data = json.loads(done.stdout)
def test_each_gate_is_a_focusable_text_chip_whose_aria_label_is_its_visible_text(self):
group = self.data["chips"]
self.assertEqual((group["tag"], group["attrs"]["role"], group["attrs"]["aria-label"]), ("span", "group", "Gates of feature/a"))
buttons = [child for child in group["children"] if isinstance(child, dict)]
self.assertEqual([button["tag"] for button in buttons], ["button"] * 4)
for button, words in zip(buttons, CHIPS, strict=True):
with self.subTest(chip=words):
self.assertEqual(button["attrs"]["type"], "button")
self.assertNotIn("tabindex", button["attrs"])
self.assertNotIn("icon-only", button["attrs"]["class"].split())
self.assertEqual(button["on"], ["click"])
self.assertEqual(text_of(button), words)
self.assertEqual(button["attrs"]["aria-label"], words)
self.assertTrue(button["attrs"]["title"].startswith(f"{words}\n"))
self.assertEqual([("inherited" in button["attrs"]["class"].split()) for button in buttons], [False, True, True, False])
def test_the_explain_action_is_a_disclosure_listing_every_glossary_term(self):
block = self.data["explain"]
self.assertEqual((block["tag"], block["attrs"]["class"]), ("details", "gate-explain"))
summary = block["children"][0]
self.assertEqual((summary["tag"], text_of(summary)), ("summary", "Explain"))
self.assertEqual([text_of(head) for head in find(block, "h4")], ["Gate actions", "Gate levels", "Where a level comes from", "Branch marks"])
terms = [text_of(term) for term in find(block, "dt")]
self.assertLessEqual({*signing.GATE_ACTIONS, *signing.GATE_LEVELS, "own rule", "inherited from", "no rule", "staged", "merged", "not merged", "Reason"}, set(terms))
self.assertEqual(len(find(block, "dd")), len(terms))
class TestHubGlossary(HubCase):
def test_the_page_ships_the_glossary_before_the_page_scripts_and_the_explain_icon(self):
html = self.index()
module = GLOSSARY.read_text(encoding="utf-8").strip()
self.assertIn(module, html)
self.assertLess(html.index(module), html.index("const RULE_HINTS = Glossary.RULE_HINTS;"))
self.assertIn('<symbol id="bi-question-circle"', html)
if __name__ == "__main__":
unittest.main()
+1 -1
View File
@@ -540,7 +540,7 @@ TREE_PROBE = DOM_KIT + """
const [, artifactsFile, treeFile, homeFile, dataFile] = process.argv.slice(1);
Object.assign(context, {
h, icon: () => text(""), named: (label, hint) => ({title: hint || label, "aria-label": label}), iconBtn: (name, label, cls, run, hint) => h("button", {"aria-label": label, title: hint}),
counter: (value) => text(value), emptyState: (title, words) => h("div", {class: "empty", "data-title": title}, words), branchAncestry: () => null, gateIcons: () => h("span", {class: "gates"}),
counter: (value) => text(value), emptyState: (title, words) => h("div", {class: "empty", "data-title": title}, words), branchAncestry: () => null, gateChips: () => h("span", {class: "gates"}), gateExplain: () => null,
flowLine: () => null, flowDetails: () => null, flowEdges: () => [], copyButton: () => null, face: () => null, person: (name) => text(name), status: (value) => text(value), pill: (words) => text(words),
workChips: () => null, popupHead: (glyph, label) => h("h2", {class: "panel-title"}, label), meta: (rows) => h("dl", {}, rows.map(([key, value]) => h("div", {"data-key": key}, value === null || value === undefined ? "" : value))),
WORK_CHIPS: {}, clock: {format: () => "c"}, stampOf: (t) => t, nowSeconds: () => 1763000000, labelOf: (key) => key, toast: () => null,
+5 -2
View File
@@ -10,7 +10,7 @@ from pathlib import Path
from hub_support import signing
TEMPLATES = Path(__file__).resolve().parent.parent / "orchestrator" / "templates"
MODULES = ["page-constants.js", "ancestry.js", "page-reveal.js", "page-dom.js", "page-diff.js", "page-rule-request.js", "page-inbox.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-diff.js", "page-rule-request.js", "page-inbox.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)
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)
@@ -140,7 +140,7 @@ class TestPageReveal(unittest.TestCase):
page_state = {
"state": {"reviews": [review], "inbox": [], "jobs": [{"kind": "task", "task": "T1", "command": f"rasci.py set T1{RLO} --prio 3", "status": "done"}], "graph": {"nodes": []}, "claims": []},
"ui": {"review": None, "file": 0},
"tree": {"data": {"repos": [repo], "gates": {"/r": {"feature/a": {"parents": [{"parent": f"main{FILLER}", "source": "own"}], "rules": {}}}}}},
"tree": {"data": {"repos": [repo], "gates": {"/r": {"feature/a": {"parents": [{"parent": f"main{FILLER}", "source": "own"}], "rules": {}, "resolved": {"merge": {"level": "test", "source": f"main{FILLER}"}}}}}}},
}
calls = [
["reviewSheet", ["r1"]],
@@ -149,12 +149,15 @@ class TestPageReveal(unittest.TestCase):
["branchAncestry", [repo]],
["priorityForm", [{"task": f"T1{FILLER}", "estimates": {}, "prio": 3}]],
["taskJobs", [{"task": "T1"}]],
["gateChips", ["/r", "feature/a"]],
]
found = shown(TEMPLATES, calls, page_state)
self.assertRevealed(found[0], ["202E", "3164", "00A0", "034F", "FE0F"])
for drawn in found[1:5]:
self.assertRevealed(drawn, ["3164"])
self.assertRevealed(found[5], ["202E"])
self.assertRevealed(found[6], ["3164"])
self.assertIn("merge: test (inherited from main⟨U+3164⟩)", found[6])
def test_an_inbox_ask_operator_row_and_decision_show_every_hidden_character_as_a_marker(self):
ask = item("ask", command=f"git status{RLO} && rm -rf ~", directory=f"/repo{ZWSP}", agent=f"Skills{RLO}")