From 78f2fec339d91603beffed9faf0dbe6f08c1a115 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Wed, 18 Nov 2026 20:05:57 +0000 Subject: [PATCH] feat(match): merge and commit-tree previews, Match motion and Home tile MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The host runner computes a merge preview for each operator row that merges or commits and posts it to the runner-only /api/runner/previews, and an ask of git commit ships the staged commit tree; Match cards show what the merge brings in onto HEAD, or why no preview exists. Cards fly off with their verdict stamp unless reduced motion is set, Match gets its own button in Tasks and a Home tile that keeps the live stack, and the 3D graph and the faces fix land with it. ๐ŸŽฏ Fix: 85 % ๐Ÿ’ฅ Break: 10 % ๐Ÿ’ธ Tokens: โ€“ โฑ๏ธ Velocity: โ€“ ๐Ÿ›ก๏ธ Security: 100 % ๐Ÿ† Score: 77 ๐Ÿšฆ Gate: โ›” fix 85 % < 90, break 10 % > 5 Created-with: https://s.veen.world/skills Co-Authored-By: Claude Opus 5.5 --- orchestrator/client/permission_hook.py | 35 ++++- orchestrator/client/runner.py | 80 ++++++++++- orchestrator/client/staged_diff.py | 137 +++++++++++++++++-- orchestrator/kvb_orchestrator/handler.py | 13 +- orchestrator/kvb_orchestrator/hub.py | 5 +- orchestrator/kvb_orchestrator/jobs.py | 13 +- orchestrator/kvb_orchestrator/matching.py | 36 +++-- orchestrator/kvb_orchestrator/previewing.py | 90 +++++++++++++ orchestrator/templates/faces.js | 2 +- orchestrator/templates/nav.js | 2 +- orchestrator/templates/page-graph3d.js | 4 +- orchestrator/templates/page-home.js | 1 + orchestrator/templates/page-match.js | 142 +++++++++++++++----- orchestrator/templates/page-tasks.js | 2 +- orchestrator/templates/style-match.css | 59 ++++++-- tests/e2e/test_001_gaps_e2e.py | 2 +- tests/test_hub_home.py | 2 +- tests/test_hub_match.py | 85 ++++++++++++ tests/test_hub_operator_tasks.py | 72 ++++++++++ 19 files changed, 692 insertions(+), 90 deletions(-) create mode 100644 orchestrator/kvb_orchestrator/previewing.py diff --git a/orchestrator/client/permission_hook.py b/orchestrator/client/permission_hook.py index 3677c4b..fbb2b7f 100755 --- a/orchestrator/client/permission_hook.py +++ b/orchestrator/client/permission_hook.py @@ -24,10 +24,13 @@ Returns: would pass DIFF_BODY_LIMIT. An allow of such an ask turns into a deny with CHANGED when what the commit records (staged_diff.binding) differs right before answering from the - preview's, and with UNBOUND when either cannot be read. Any other - Bash command that may run git commit (-a, --all, -i, -o, -p, a - pathspec, a chain, a wrapper) is not approvable: no ask reaches the - hub, stderr gets WORKTREE and Claude Code shows its own dialog. + preview's, and with UNBOUND when either cannot be read. An ask for + a Bash git commit-tree of full object ids (staged_diff.tree_of) + carries the diff of its tree against its first parent the same way. + Any other Bash command that may run git commit (-a, --all, -i, -o, + -p, a pathspec, a chain, a wrapper) is not approvable: no ask + reaches the hub, stderr gets WORKTREE and Claude Code shows its own + dialog. """ from __future__ import annotations @@ -82,8 +85,24 @@ def commit_target(ask: dict) -> Path | None: return staged_diff.commit_of(ask["command"], ask["cwd"]) if ask["tool"] == "Bash" and ask["cwd"] else None +def tree_target(ask: dict) -> tuple[Path, str, list[str]] | None: + return staged_diff.tree_of(ask["command"], ask["cwd"]) if ask["tool"] == "Bash" and ask["cwd"] else None + + def unapprovable(ask: dict) -> bool: - return ask["tool"] == "Bash" and staged_diff.names_commit(ask["command"]) and commit_target(ask) is None + return ask["tool"] == "Bash" and staged_diff.names_commit(ask["command"]) and commit_target(ask) is None and tree_target(ask) is None + + +def tree_preview(ask: dict, rules: Path | None) -> dict: + found = tree_target(ask) + if found is None: + return {} + try: + diff, sealed = staged_diff.commit_tree_diff(*found, rules) + return {"diff": diff, "sealed": sealed} + except FAILURES as error: + print(f"kvb-orchestrator: the ask goes without its diff: {error}", file=sys.stderr) + return {} def commit_diff(ask: dict, rules: Path | None) -> tuple[str | None, dict]: @@ -91,11 +110,13 @@ def commit_diff(ask: dict, rules: Path | None) -> tuple[str | None, dict]: For a commit ask, what the commit records (staged_diff.binding, None when it cannot be read) and {"diff": the preview of exactly that, "sealed": the clear patches of its masked files}, {} when it cannot - be built; None and {} for any other ask. + be built; for a commit-tree ask None and its tree_preview, which + needs no binding: its object ids name content no write can change; + None and {} for any other ask. """ target = commit_target(ask) if target is None: - return None, {} + return None, tree_preview(ask, rules) try: pinned = staged_diff.binding(target) except FAILURES as error: diff --git a/orchestrator/client/runner.py b/orchestrator/client/runner.py index 6cbb864..debfd05 100755 --- a/orchestrator/client/runner.py +++ b/orchestrator/client/runner.py @@ -30,7 +30,12 @@ Returns: changes without --rasci and --council or into a council that is a symlink or another uid's, gate changes without --gates, and every other job. Posts the last 200 output lines - back while it runs and the exit code at its end. The exit code is 0. + back while it runs and the exit code at its end. Before every poll it + posts, for each open operator row that is a git merge of a full commit + id (staged_diff.merge_of) whose HEAD differs from the preview the hub + holds, staged_diff.merge_preview, which its Match card shows; such a + merge whose job names the previewed HEAD is refused once HEAD moved. The + exit code is 0. """ from __future__ import annotations @@ -53,10 +58,15 @@ from pathlib import Path from typing import NamedTuple import hub_api +import hub_limits import signing +import staged_diff import verifier LINES = 200 +PREVIEWS = "/api/runner/previews" +ERROR_LIMIT = 500 +PREVIEW_FAILURES = (OSError, ValueError, staged_diff.DiffError) BEAT = 2.0 SAFE_PATH = "/usr/bin:/bin" TASK_JOB = "task" @@ -142,6 +152,64 @@ def gate_refusal(job: dict, trust: verifier.Trust, now: float) -> str | None: return None +def moved(job: dict) -> str | None: + """Args: + job: a claimed operator command; head, when set, is the HEAD its + Match card previewed the merge against. + + Returns: + Why a git merge (staged_diff.merge_of) must not run because HEAD is + no longer that commit or cannot be read; None otherwise. + """ + found = staged_diff.merge_of(job["command"], job["directory"]) if job.get("head") else None + if found is None: + return None + try: + head = staged_diff.head_of(found[0]) + except PREVIEW_FAILURES as error: + return f"refused: HEAD cannot be read, so the merge is not the one previewed: {error}" + return None if head == job["head"] else f"refused: HEAD moved from {job['head'][:12]} to {head[:12]} since the Match card previewed the merge" + + +def preview(row: dict, rules: Path | None) -> dict | None: + """Args: + row: an open operator row with task, command, directory and head, + the HEAD of the preview the hub holds, None for none. + rules: the MEDUSA rules directory. + + Returns: + The preview to post for a git merge row whose HEAD differs from the + hub's: staged_diff.merge_preview, or {head, error} when it cannot be + built; None for every other row. + """ + found = staged_diff.merge_of(row["command"], row["directory"]) + if found is None: + return None + try: + head = staged_diff.head_of(found[0]) + except PREVIEW_FAILURES as error: + head, shown = "", {"error": str(error)[:ERROR_LIMIT]} + else: + shown = None + if head == row["head"]: + return None + if shown is None: + try: + shown = staged_diff.merge_preview(found[0], found[1], rules) + except PREVIEW_FAILURES as error: + shown = {"error": str(error)[:ERROR_LIMIT]} + return {"task": row["task"], "command": row["command"], "head": head, **shown} + + +def previews(base: str, rules: Path | None) -> None: + for row in call(base, PREVIEWS, None)["rows"]: + shown = preview(row, rules) + if shown is not None and len(json.dumps(shown).encode()) > hub_limits.DIFF_BODY_LIMIT: + shown = {"task": row["task"], "command": row["command"], "head": shown["head"], "error": f"the preview passes the hub's {hub_limits.DIFF_BODY_LIMIT} bytes"} + if shown is not None: + call(base, PREVIEWS, shown) + + def council_refusal(council: Path) -> str | None: """Args: council: the directory rasci.py writes the register into. @@ -283,7 +351,7 @@ def cycle(base: str, trust: verifier.Trust, register: Register | None, gates: Pa elif kind == GATE_JOB: reason = UNGATED if gates is None else gate_refusal(claimed, trust, time.time()) else: - reason = refusal(claimed, trust, time.time()) + reason = refusal(claimed, trust, time.time()) or moved(claimed) if reason is not None: send({"output": reason, "code": None, "refused": True}) elif kind == TASK_JOB: @@ -308,7 +376,15 @@ def main() -> int: base = hub_api.base_url(args.port) trust = verifier.Trust(approvers=args.approvers, replay=args.replay, origin=signing.origin_of(args.port)) register = Register(rasci=args.rasci, council=args.council) if args.rasci and args.council else None + rules, told = staged_diff.rules_root(), "" while True: + try: + previews(base, rules) + told = "" + except (OSError, ValueError, KeyError, TypeError) as error: + if str(error) != told: + print(f"runner: no merge previews: {error}", file=sys.stderr) + told = str(error) try: cycle(base, trust, register, args.gates) except (OSError, ValueError, KeyError, TypeError): diff --git a/orchestrator/client/staged_diff.py b/orchestrator/client/staged_diff.py index 5b5a019..bd6bd5d 100644 --- a/orchestrator/client/staged_diff.py +++ b/orchestrator/client/staged_diff.py @@ -4,9 +4,13 @@ HEAD instead of the live index. rules: the MEDUSA rules directory, None when MEDUSA is not installed. pinned: for bound_diff, what binding returned for the same cwd. + parents: for commit_tree_diff, the parent commits git commit-tree + records; the tree is diffed against the first one's tree, against + nothing without one. Returns: - review_diff, tree_diff, bound_diff: (diff, sealed). diff is the review + review_diff, tree_diff, bound_diff, commit_tree_diff: (diff, sealed). + diff is the review diff of requirement 003 of the staged tree against HEAD (git diff --cached), one {path, status, mode, additions, deletions, patch, note} per changed path, sorted by path, status A, M, D or B @@ -27,23 +31,31 @@ Returns: than FILE_CAP paths changed or one is longer than PATH_LIMIT, a settings file sandbox_paths reads is unreadable, the working tree lies under a denied path, HEAD exists but its tree cannot be listed, - HEAD is neither a commit nor unborn, or for bound_diff, the index no - longer matches pinned. + HEAD is neither a commit nor unborn, for bound_diff, the index no + longer matches pinned, or for commit_tree_diff, the tree is no tree + or a parent no commit of the repository. binding: what a commit records, for the permission hook to bind an allow to: the sha256 of staged() (the mode, object id and name of every index entry git write-tree records, so no intent-to-add one; an index with unmerged paths fails). commit_of: the directory of a single git commit that records exactly the staged index, None for any other command. + tree_of: (directory, tree, parents) of a single git commit-tree whose + tree and parents are full object ids, which no later write can + change; None for any other command. + merge_of: (directory, target) of a single git merge of one full object + id; merge_preview: what that merge brings in; head_of: the commit + HEAD names. names_commit: whether a command may run git commit anywhere in it. Every git call runs GIT with core.fsmonitor, core.hooksPath, lazy fetching, the system and the global config off, and an environment of only PASSED_ENV -and FIXED_ENV (PATH set to TRUSTED_PATH). The permission hook path -(binding, bound_diff, commit_of) runs only plumbing that writes nothing -(rev-parse, symbolic-ref, ls-tree, ls-files, cat-file); only approval.py, run +and FIXED_ENV (PATH set to TRUSTED_PATH). The permission hook and runner path +(binding, bound_diff, commit_tree_diff, merge_preview, head_of, commit_of, +tree_of, merge_of) runs only plumbing that writes nothing (rev-parse, +merge-base, symbolic-ref, ls-tree, ls-files, cat-file); only approval.py, run inside the sandbox, adds git write-tree. The diff itself is computed here: -the permission hook calls this outside the sandbox in a directory the agent +the permission hook and the runner call this outside the sandbox in a directory the agent chose, where a planted repository config, hook, filter, diff driver, promisor remote or program on PATH must start nothing, and nothing in the working tree is read. @@ -90,6 +102,16 @@ FIXED_ENV = {"GIT_OPTIONAL_LOCKS": "0", "GIT_NO_LAZY_FETCH": "1", "GIT_CONFIG_NO INTENT_TO_ADD = 0x20000000 DEBUG_LINES = 5 NAMES_COMMIT = re.compile(r"(? tuple[list[dict], return built(cwd, sides(cwd, None, index), rules) -def sides(cwd: Path, tree: str | None, index: bytes | None) -> tuple[dict, dict, dict[str, bytes | None]]: +def sides(cwd: Path, tree: str | None, index: bytes | None, parents: list[str] | None = None) -> tuple[dict, dict, dict[str, bytes | None]]: top = toplevel(cwd) roots = denied_roots(top) - old = head_tree(top) + old = head_tree(top) if parents is None else parent_tree(top, parents) if tree is not None: new = listed(git(top, ["ls-tree", "-r", "-z", "--full-tree", tree], None), 2) else: @@ -259,6 +281,10 @@ def head_tree(top: Path) -> dict[str, tuple[str, str]]: return listed(git(top, ["ls-tree", "-r", "-z", "--full-tree", "HEAD"], None), 2) +def parent_tree(top: Path, parents: list[str]) -> dict[str, tuple[str, str]]: + return listed(git(top, ["ls-tree", "-r", "-z", "--full-tree", parents[0]], None), 2) if parents else {} + + def text_lines(text: str) -> list[str]: lines = text.split("\n") return lines[:-1] if lines[-1] == "" else lines @@ -462,6 +488,31 @@ def tree_diff(cwd: Path, tree: str, rules: Path | None) -> tuple[list[dict], dic return built(cwd, sides(cwd, tree, None), rules) +def commit_tree_diff(cwd: Path, tree: str, parents: list[str], rules: Path | None) -> tuple[list[dict], dict[str, str]]: + ids = [tree, *parents] + kinds = git(toplevel(cwd), ["cat-file", "--batch-check=%(objecttype)"], "".join(f"{oid}\n" for oid in ids).encode()).decode("ascii").split("\n")[:-1] + if kinds != ["tree", *["commit"] * len(parents)]: + raise DiffError("git commit-tree names a tree that is no tree or a parent that is no commit here") + return built(cwd, sides(cwd, tree, None, parents), rules) + + +def head_of(cwd: Path) -> str: + return git(toplevel(cwd), ["rev-parse", "--verify", "HEAD^{commit}"], None).decode("ascii").strip() + + +def merge_preview(cwd: Path, target: str, rules: Path | None) -> dict: + """Returns: + {head, base, target, diff}: what git merge of the commit target + brings into HEAD, the tree of target against its merge base with + HEAD, secrets masked; the sealed clear patches stay behind. + """ + top = toplevel(cwd) + head = head_of(top) + base = git(top, ["merge-base", head, target], None).decode("ascii").strip() + tree = git(top, ["rev-parse", "--verify", f"{target}^{{tree}}"], None).decode("ascii").strip() + return {"head": head, "base": base, "target": target, "diff": commit_tree_diff(top, tree, [base], rules)[0]} + + def fetched(cwd: Path, old: dict, new: dict, changed: list[str], contents: dict[str, bytes | None]) -> None: needed = {side[path][1] for side in (old, new) for path in changed if path in side and side[path][0] != GITLINK and side[path][1] not in contents} sizes = blob_sizes(cwd, needed) @@ -526,6 +577,46 @@ def commit_of(command: str, cwd: str) -> Path | None: match (-a, --all, --amend, a pathspec, -o, -i, -p, --no-all, an unknown or ambiguous long option, git -c, or a GIT_ variable outside KEPT_VARS). """ + found = git_words(command, cwd) + return found[0] if found and found[1][0] == "commit" and index_only(found[1][1:]) else None + + +def tree_of(command: str, cwd: str) -> tuple[Path, str, list[str]] | None: + found = git_words(command, cwd) + if not found or found[1][0] != "commit-tree": + return None + named = tree_words(found[1][1:]) + return None if named is None else (found[0], *named) + + +def merge_of(command: str, cwd: str) -> tuple[Path, str] | None: + """Returns: + The directory and target of one git merge, behind what commit_of + passes, of exactly one commit named by its full OBJECT_ID with no + option outside MERGE_FLAGS, MERGE_ARGS and MERGE_VALUED; None for any + other command. + """ + found = git_words(command, cwd) + if not found or found[1][0] != "merge": + return None + targets, rest = [], iter(found[1][1:]) + for word in rest: + if word[:2] in MERGE_ARGS: + if not word[2:] and next(rest, None) is None: + return None + elif word.startswith("-") and word not in MERGE_FLAGS and not word.startswith(MERGE_VALUED): + return None + elif not word.startswith("-"): + targets.append(word) + return (found[0], targets[0]) if len(targets) == 1 and OBJECT_ID.fullmatch(targets[0]) else None + + +def git_words(command: str, cwd: str) -> tuple[Path, list[str]] | None: + """Returns: + For a command that is one git VERBS call, optionally behind what + commit_of passes, the directory it runs in and its words from the + verb on; None for any other command. + """ try: words = shlex.split(command) except ValueError: @@ -536,7 +627,31 @@ def commit_of(command: str, cwd: str) -> Path | None: if not words or Path(words[0]).name != "git": return None place, rest = past_git_options(place, words[1:]) - return place if rest and index_only(rest[1:]) else None + return (place, rest) if rest else None + + +def tree_words(words: list[str]) -> tuple[str, list[str]] | None: + """Returns: + The tree and the parents of git commit-tree with these words; None + for an option outside TREE_ARGS, -S and SIGNING, a missing option + argument, not exactly one tree, or a tree or parent that is no + full OBJECT_ID. + """ + trees, parents, rest = [], [], iter(words) + for word in rest: + if word[:2] in TREE_ARGS: + value = word[2:] or next(rest, None) + if value is None: + return None + if word[:2] == "-p": + parents.append(value) + elif word.startswith("-") and not (word.startswith(("-S", "--gpg-sign=")) or word in SIGNING): + return None + elif not word.startswith("-"): + trees.append(word) + if len(trees) != 1 or not all(OBJECT_ID.fullmatch(oid) for oid in [*trees, *parents]): + return None + return trees[0], parents def launched(place: Path, words: list[str]) -> tuple[Path, list[str]]: @@ -573,7 +688,7 @@ def past_env_options(place: Path, words: list[str]) -> tuple[Path, list[str]]: def past_git_options(place: Path, rest: list[str]) -> tuple[Path, list[str]]: - while rest and rest[0] != "commit": + while rest and rest[0] not in VERBS: if rest[0] == "-C" and len(rest) > 1: place, rest = place / rest[1], rest[2:] elif rest[0] in ("--no-pager", "-P", "--no-optional-locks"): diff --git a/orchestrator/kvb_orchestrator/handler.py b/orchestrator/kvb_orchestrator/handler.py index ba0a82f..7655945 100644 --- a/orchestrator/kvb_orchestrator/handler.py +++ b/orchestrator/kvb_orchestrator/handler.py @@ -27,6 +27,7 @@ ENTRY = re.compile(r"/api/stream/([0-9]{1,12})") BOARD = re.compile(r"/api/board/([a-z-]{1,32})") UPLOADS = "/api/uploads" MATCH_ROUTE = "/api/match" +PREVIEWS_ROUTE = "/api/runner/previews" MATCH_POSTS = {"/api/match/stale": "match_stale", "/api/match/snapshot": "match_snapshot"} POSTS = ("/api/asks", UPLOADS, "/api/messages", *MATCH_POSTS) STORED = { @@ -147,9 +148,9 @@ class Handler(Exchange): self.answer(hub.view_store.get, HTTPStatus.OK) elif path == "/api/subagents": self.answer(lambda: hub.subagents(self.query()), HTTPStatus.OK) - elif path == "/api/runner/jobs": + elif path in ("/api/runner/jobs", PREVIEWS_ROUTE): if self.client(): - self.answer(hub.runner_jobs, HTTPStatus.OK) + self.answer(hub.runner_jobs if path == "/api/runner/jobs" else hub.preview_rows, HTTPStatus.OK) else: self.send_text(HTTPStatus.FORBIDDEN, "forbidden: the runner calls with the X-Kvb-Orchestrator header and no origin only") elif entry: @@ -266,7 +267,9 @@ class Handler(Exchange): def runner(self, path: str, body: bytes) -> None: hub = self.server.hub route = RUNNER_ROUTE.fullmatch(path) - if route.group(2) == "claim": + if route is None: + self.answer(lambda: hub.record_preview(body), HTTPStatus.OK) + elif route.group(2) == "claim": self.answer(lambda: hub.claim(route.group(1)), HTTPStatus.OK) else: self.answer(lambda: hub.report(route.group(1), body), HTTPStatus.OK) @@ -285,7 +288,7 @@ class Handler(Exchange): return lambda body: self.answer(lambda: receive(body), HTTPStatus.OK if path in MATCH_POSTS else HTTPStatus.CREATED) self.send_text(HTTPStatus.FORBIDDEN, "forbidden: local POST with the X-Kvb-Orchestrator header and no foreign origin only") return None - if RUNNER_ROUTE.fullmatch(path): + if RUNNER_ROUTE.fullmatch(path) or path == PREVIEWS_ROUTE: if self.client(): return lambda body: self.runner(path, body) self.send_text(HTTPStatus.FORBIDDEN, "forbidden: the runner calls with the X-Kvb-Orchestrator header and no origin only") @@ -303,7 +306,7 @@ class Handler(Exchange): def do_POST(self) -> None: path = urlsplit(self.path).path - length = self.body_length({UPLOADS: UPLOAD_LIMIT, STT_ROUTE: INPUT_LIMIT, VOICE_ROUTE: STT_LIMIT, "/mcp": DIFF_BODY_LIMIT, "/api/asks": DIFF_BODY_LIMIT}.get(path, BODY_LIMIT)) + length = self.body_length({UPLOADS: UPLOAD_LIMIT, STT_ROUTE: INPUT_LIMIT, VOICE_ROUTE: STT_LIMIT, "/mcp": DIFF_BODY_LIMIT, "/api/asks": DIFF_BODY_LIMIT, PREVIEWS_ROUTE: DIFF_BODY_LIMIT}.get(path, BODY_LIMIT)) if length is None: return host = self.host() diff --git a/orchestrator/kvb_orchestrator/hub.py b/orchestrator/kvb_orchestrator/hub.py index be98755..b9e7e0b 100644 --- a/orchestrator/kvb_orchestrator/hub.py +++ b/orchestrator/kvb_orchestrator/hub.py @@ -35,6 +35,7 @@ from .messaging import Messaging from .names import Names from .offices import Offices from .presence import SNAPSHOT +from .previewing import Previewing from .queue_order import QUEUE_SCRIPT, QueueOrder from .receipts import ( NAMES, @@ -88,7 +89,7 @@ def environment(templates: Path) -> jinja2.Environment: @dataclass(frozen=True) -class Hub(Mcp, Reviewing, Revealing, Asking, Messaging, Choosing, Approving, Denying, Requesting, Cleaning, Offices, Tasking, Gating, Firewall, Inbox, Matching, Rules, Jobs, Sources, Timeline, View, Language): +class Hub(Mcp, Reviewing, Revealing, Asking, Messaging, Choosing, Approving, Denying, Requesting, Cleaning, Offices, Tasking, Gating, Firewall, Inbox, Matching, Previewing, Rules, Jobs, Sources, Timeline, View, Language): council: Path pages: Path public_port: int @@ -136,6 +137,7 @@ class Hub(Mcp, Reviewing, Revealing, Asking, Messaging, Choosing, Approving, Den queue_order: QueueOrder view_store: ViewStore match_snapshots: Ledger + merge_previews: Ledger live_state: LiveState def hosts(self) -> tuple[str, str]: @@ -206,6 +208,7 @@ def open_hub(council: Path, pages: Path, public_port: int, state: Path, host_sta replay=state / "replay" / "messages.json", view_store=ViewStore(state / "view.json"), match_snapshots=Ledger(state / "match.json"), + merge_previews=Ledger(state / "previews.json"), live_state=LiveState(live_ttl), rules=Ledger(state / "rules.json"), offers=Offers(), diff --git a/orchestrator/kvb_orchestrator/jobs.py b/orchestrator/kvb_orchestrator/jobs.py index 8bd6a09..8ad17f1 100644 --- a/orchestrator/kvb_orchestrator/jobs.py +++ b/orchestrator/kvb_orchestrator/jobs.py @@ -19,12 +19,14 @@ USAGE = 2 def runner_job(job: dict) -> dict: """Returns: - What the runner claims: an operator command, or a task or gate change - with kind and argv; a runner that predates such changes verifies them - as an operator command and refuses them. + What the runner claims: an operator command, with head when a Match + release bound it to a merge preview of that HEAD, or a task or gate + change with kind and argv; a runner that predates such changes + verifies them as an operator command and refuses them. """ change = {"kind": job["kind"], "argv": job["argv"]} if job.get("kind") in CHANGES else {} - return {**{key: job[key] for key in ("id", "task", "command", "directory", "sha256")}, **change, "proof": job.get("proof")} + head = {"head": job["head"]} if job.get("head") else {} + return {**{key: job[key] for key in ("id", "task", "command", "directory", "sha256")}, **change, **head, "proof": job.get("proof")} def console_of(job: dict | None) -> dict | None: @@ -60,7 +62,8 @@ class Jobs: return "refused: the row changed since the grant" if item["id"] in self.open_jobs(): return "already running" - job = {"task": row["task"], "command": row["command"], "directory": row["directory"], "sha256": item["sha256"], "status": "queued", "proof": proof} + head = self.previewed_head(row["task"], row["command"]) if item.get("bound") else "" + job = {"task": row["task"], "command": row["command"], "directory": row["directory"], "sha256": item["sha256"], "status": "queued", "proof": proof, "head": head} self.jobs.add({**job, "code": None, "output": "", "created_ts": time.time(), "started": None, "finished": None, "dismissed": False}) return "handed to the runner" diff --git a/orchestrator/kvb_orchestrator/matching.py b/orchestrator/kvb_orchestrator/matching.py index e619eca..573ac5f 100644 --- a/orchestrator/kvb_orchestrator/matching.py +++ b/orchestrator/kvb_orchestrator/matching.py @@ -8,6 +8,7 @@ from .diffs import stored_diff from .errors import Conflict, Missing, ToolError from .fields import decode, expect, field from .payloads import denied_roots, payload_files, payload_hash +from .previewing import merge_hash from .records import digest, iso_epoch from .register import REGISTER, adder, operator_rows, read_register from .scores import metric_chips, score_labels @@ -58,9 +59,10 @@ class Matching: agent = adder(tasks[row["task"]]) cards.append({**self.command_card(row, agent, born_of(agent, names, claims), roots, scan), "to": requester_of(claims, agent)[0]}) listed = {card["id"] for card in cards} - for snapshot in self.match_snapshots.listed(): - if snapshot["id"] not in listed: - self.match_snapshots.remove(snapshot["id"]) + for store in (self.match_snapshots, self.merge_previews): + for snapshot in store.listed(): + if snapshot["id"] not in listed: + store.remove(snapshot["id"]) return {"now": now, "cards": cards} def commit_card(self, review: dict, reviews: list[dict], born: float | None, labels: dict | None) -> dict: @@ -79,26 +81,38 @@ class Matching: "stale": bool(reason), "stale_reason": reason, "files": files, "command": "", "directory": review["worktree"], "reason": "", } + def card_payload(self, row: dict, roots: list[str] | None) -> tuple[list[dict], str, dict | None]: + """Returns: + What a command card shows and is bound to: the runner's merge + preview diff and merge_hash() for a git merge it previewed, else + the named payload files and payload_hash(); and the preview. + """ + preview = self.preview_of(row) + if preview is not None: + return preview.get("diff", []), merge_hash(row, preview), preview + files = payload_files(row["command"], row["directory"], roots) + return files, payload_hash(row["command"], row["directory"], files), None + def command_card(self, row: dict, agent: str, born: float | None, roots: list[str] | None, scan: dict) -> dict: card_id = f"operator:{row['task']}" - files = payload_files(row["command"], row["directory"], roots) - live = payload_hash(row["command"], row["directory"], files) + files, live, preview = self.card_payload(row, roots) snapshot = self.match_snapshots.get(card_id) - if snapshot is None or snapshot["command_sha256"] != digest(row["command"]): + if snapshot is None or snapshot["command_sha256"] != digest(row["command"]) or (preview is not None and not snapshot.get("previewed")): self.match_snapshots.remove(card_id) - snapshot = self.match_snapshots.insert(card_id, {"command_sha256": digest(row["command"]), "hash": live, "files": files, "taken": time.time()}) + snapshot = self.match_snapshots.insert(card_id, {"command_sha256": digest(row["command"]), "hash": live, "files": files, "previewed": preview is not None, "taken": time.time()}) stale = snapshot["hash"] != live + moved = "HEAD or the merge base moved since it was added" if preview is not None else "a payload file changed since it was added" + merge = None if preview is None else {key: preview.get(key, "") for key in ("head", "base", "target", "error")} repo, branch, worktree = place_of(row["directory"], scan) return { "id": card_id, "kind": "command", "ref": row["task"], "agent": agent, "born": born, "created_ts": snapshot["taken"], "repo": repo, "branch": branch, "worktree": worktree, "title": row["command"], "score": "", "metrics": [], "gate": "", "hash": snapshot["hash"], "live_hash": live, "stale": stale, - "stale_reason": "a payload file changed since it was added" if stale else "", "files": snapshot["files"], "command": row["command"], "directory": row["directory"], - "reason": row["why"], "sha256": digest(row["command"]), + "stale_reason": moved if stale else "", "files": snapshot["files"], "command": row["command"], "directory": row["directory"], + "reason": row["why"], "sha256": digest(row["command"]), "merge": merge, } def live_payload(self, row: dict) -> str: - files = payload_files(row["command"], row["directory"], denied_roots(self.settings_files()[0])) - return payload_hash(row["command"], row["directory"], files) + return self.card_payload(row, denied_roots(self.settings_files()[0]))[1] def payload_bound(self, row: dict, shown: object) -> list[dict]: """Args: diff --git a/orchestrator/kvb_orchestrator/previewing.py b/orchestrator/kvb_orchestrator/previewing.py new file mode 100644 index 0000000..d3a7e9e --- /dev/null +++ b/orchestrator/kvb_orchestrator/previewing.py @@ -0,0 +1,90 @@ +from __future__ import annotations + +import json +import re +import time + +from .diffs import valid_diff +from .errors import Conflict, Missing, ToolError +from .fields import bounded, decode, expect +from .records import digest +from .register import OPERATOR, REGISTER, operator_rows, read_register +from .signed import signing + +OBJECT_ID = re.compile(r"[0-9a-f]{40}|[0-9a-f]{64}") +ERROR_LIMIT = 500 +SHOWN = ("task", "command", "head", "base", "target", "diff") +FAILED = ("task", "command", "head", "error") + + +def card_id(task: str) -> str: + return f"operator:{task}" + + +def object_id(payload: dict, name: str, empty: bool) -> str: + value = payload[name] + if not isinstance(value, str) or not (OBJECT_ID.fullmatch(value) or (empty and value == "")): + raise ToolError(f"{name} must be a full git object id") + return value + + +def merge_hash(row: dict, preview: dict) -> str: + """Returns: + The sha256 a merge card is bound to: its command, directory, the + HEAD, merge base and target the runner previewed and the digest of + the diff or the error it sent. + """ + shown = {key: preview.get(key, "") for key in ("head", "base", "target", "error")} + return signing.item_hash({"kind": "merge", "command": row["command"], "directory": row["directory"], **shown, "diff": digest(json.dumps(preview.get("diff", []), sort_keys=True))}) + + +class Previewing: + def open_rows(self) -> list[dict]: + held = self.open_jobs() + return [row for row in operator_rows(read_register(self.council / REGISTER)) if row["check"] != "decision" and row["task"] not in held] + + def preview_of(self, row: dict) -> dict | None: + """Returns: + The runner's merge preview of the row's command, None when it + sent none for this command. + """ + found = self.merge_previews.get(card_id(row["task"])) + return found if found is not None and found["command"] == row["command"] else None + + def preview_rows(self) -> dict: + """Returns: + {"rows"}: every open operator row in an absolute directory with + the HEAD of the preview the hub holds, None for none, for the + runner to preview the git merges among them. + """ + rows = [row for row in self.open_rows() if row["directory"].startswith("/")] + return {"rows": [{"task": row["task"], "command": row["command"], "directory": row["directory"], "head": (self.preview_of(row) or {}).get("head")} for row in rows]} + + def record_preview(self, body: bytes) -> dict: + """Args: + body: from the runner, {task, command, head, base, target, diff} + for a git merge row, or {task, command, head, error} when it + could not preview it; head is empty when HEAD is unreadable. + """ + payload = decode(body) + expect(payload, FAILED if "error" in payload else SHOWN) + task = payload["task"] + if not isinstance(task, str) or not task.startswith(OPERATOR) or not signing.TASK.fullmatch(task): + raise ToolError("task must be an operator row") + row = next((row for row in self.open_rows() if row["task"] == task), None) + if row is None: + raise Missing(task) + if payload["command"] != row["command"]: + raise Conflict({"id": task, "status": "changed"}) + record = {"command": row["command"], "head": object_id(payload, "head", "error" in payload), "taken": time.time()} + if "error" in payload: + record["error"] = bounded(payload, "error", ERROR_LIMIT) + else: + record.update(base=object_id(payload, "base", False), target=object_id(payload, "target", False), diff=valid_diff(payload["diff"])) + self.merge_previews.remove(card_id(task)) + self.merge_previews.insert(card_id(task), record) + return {"id": card_id(task), "head": record["head"]} + + def previewed_head(self, task: str, command: str) -> str: + found = self.merge_previews.get(card_id(task)) + return found["head"] if found is not None and found["command"] == command and "diff" in found else "" diff --git a/orchestrator/templates/faces.js b/orchestrator/templates/faces.js index 0914d2e..026d4ec 100644 --- a/orchestrator/templates/faces.js +++ b/orchestrator/templates/faces.js @@ -88,7 +88,7 @@ const Faces = (() => { return {pick, parts}; } - return {SIZE, COUNTS, COMBINATIONS, of}; + return {SIZE, COUNTS, COMBINATIONS, of, hash}; })(); if (typeof module === "object" && module.exports) { module.exports = Faces; diff --git a/orchestrator/templates/nav.js b/orchestrator/templates/nav.js index fb43fd2..ab8abd4 100644 --- a/orchestrator/templates/nav.js +++ b/orchestrator/templates/nav.js @@ -10,7 +10,7 @@ const Nav = (() => { home: "bi-house-door", stream: "bi-activity", inbox: "bi-inbox", rules: "bi-card-checklist", agents: "bi-people", artifacts: "bi-git", tasks: "bi-list-check", orbit: "bi-globe2", chord: "bi-bezier2", swimlane: "bi-bar-chart-steps", tree: "bi-diagram-3", "3d": "bi-badge-3d", hierarchy: "bi-diagram-2", list: "bi-list-task", board: "bi-kanban", rasci: "bi-grid-3x3", gantt: "bi-calendar-range", burn: "bi-graph-down-arrow", - resources: "bi-speedometer2", + resources: "bi-speedometer2", match: "bi-stack", }; const OLD = {graph: ["agents", "orbit"], tree: ["artifacts", "tree"]}; const viewsOf = (screen) => (screen === "tasks" ? TASK_VIEWS : [...VIEWS, ...(OWN[screen] || [])]); diff --git a/orchestrator/templates/page-graph3d.js b/orchestrator/templates/page-graph3d.js index e55af29..15a2eb1 100644 --- a/orchestrator/templates/page-graph3d.js +++ b/orchestrator/templates/page-graph3d.js @@ -424,10 +424,10 @@ place(data.nodes, layout); g3.badges = new Map(); g3.faces = new Set(); - g3.graph.width(box.clientWidth).height(box.clientHeight).graphData(data); - drawPlanes(layout, data.nodes); const words = `${data.nodes.length} nodes ยท ${data.links.length} edges ยท ${LAYOUTS.find(([id]) => id === layout)[1]}${calm.matches ? " ยท without motion (prefers-reduced-motion)" : ""}`; host.replaceChildren(box, h("div", {class: "space-note"}, words)); + g3.graph.width(box.clientWidth).height(box.clientHeight).graphData(data); + drawPlanes(layout, data.nodes); window.requestAnimationFrame(() => g3.host === host && g3.fit && fit3d(0)); } diff --git a/orchestrator/templates/page-home.js b/orchestrator/templates/page-home.js index 4b55258..6454706 100644 --- a/orchestrator/templates/page-home.js +++ b/orchestrator/templates/page-home.js @@ -180,6 +180,7 @@ Panels.panel("artifacts/tree", "Artifacts: tree", () => homeTree(() => h("div", {class: "repos"}, treeCards("", true).nodes))); Panels.panel("agents/order", "Agents: priority", homeOrder); Panels.panel("tasks/operator", "Tasks: Waits on Operator", homeInbox); + Panels.panel("tasks/match", "Tasks: Match", () => homeMatch(), "", [6, 8]); Panels.item("metric", (id, view) => metricTitle(view), (size, id, view) => homeMetric(id, view)); Panels.capture("resources-hardware", () => resourcePin("hardware")); Panels.capture("resources-tokens", () => resourcePin("tokens")); diff --git a/orchestrator/templates/page-match.js b/orchestrator/templates/page-match.js index 77bbddb..19095e1 100644 --- a/orchestrator/templates/page-match.js +++ b/orchestrator/templates/page-match.js @@ -7,7 +7,9 @@ const SWIPE_SHARE = 0.25; const SWIPE_UP = 80; const FEEDBACK_LIMIT = 2000; - const matchView = {cards: null, order: [], marks: new Map(), opened: new Map(), decisions: new Map(), overview: false, front: null, drag: null, dom: null, sig: "", fetched: 0, loading: false, press: null}; + const FLY_MS = 400; + const CONFETTI = 28; + const matchView = {cards: null, order: [], marks: new Map(), opened: new Map(), decisions: new Map(), overview: false, front: null, drag: null, dom: null, sig: "", fetched: 0, loading: false, press: null, flying: false, openBefore: 0}; async function fetchMatch() { if (matchView.loading) { @@ -68,10 +70,12 @@ return h("tr", {class: "match-mark", "data-line": mark.line}, h("td", {colspan: columns}, icon("bi-chat-square-text"), h("span", {class: "match-mark-text"}, revealed(mark.comment)))); } + const patched = (card) => card.kind === "commit" || Boolean(card.merge); + function matchFileRows(card, file) { - const commit = card.kind === "commit"; - const rows = commit ? (file.patch ? Diffs.rows(file.patch).map(patchRow) : []) : file.state === "read" ? contentRows(file.content) : []; - const columns = commit ? 4 : 2; + const diffed = patched(card); + const rows = diffed ? (file.patch ? Diffs.rows(file.patch).map(patchRow) : []) : file.state === "read" ? contentRows(file.content) : []; + const columns = diffed ? 4 : 2; const marks = marksOf(card).filter((mark) => mark.path === file.path); return rows.flatMap((row) => { const line = row.dataset.line; @@ -86,7 +90,7 @@ function fileHead(card, file) { const count = marksOf(card).filter((mark) => mark.path === file.path).length; const marks = count ? h("span", {class: "match-marks", title: `${count} marks`}, String(count)) : null; - if (card.kind === "commit") { + if (patched(card)) { const tone = DIFF_TONES[file.status] || "neutral"; const stat = file.status === "B" ? icon("bi-file-earmark-binary") : h("span", {class: "stat"}, h("span", {class: "add"}, `+${file.additions}`), h("span", {class: "del"}, `-${file.deletions}`)); return h("summary", {class: "diff-head"}, h("span", {class: "letter", "data-tone": tone}, file.status), h("code", {class: "path"}, revealed(file.path)), h("span", {class: "spacer"}), @@ -100,8 +104,8 @@ function fileBlock(card, file, index) { const opened = matchView.opened.has(card.id) ? matchView.opened.get(card.id).has(file.path) : index === 0; const rows = matchFileRows(card, file); - const table = rows.length ? h("div", {class: "diff-scroll"}, h("table", {class: "diff"}, h("tbody", {}, rows))) : h("p", {class: "muted"}, card.kind === "commit" ? "No patch shipped for this file." : "Not read."); - const block = h("details", {class: "match-file", "data-path": file.path, "data-state": card.kind === "command" ? file.state : null, open: opened}, fileHead(card, file), table); + const table = rows.length ? h("div", {class: "diff-scroll"}, h("table", {class: "diff"}, h("tbody", {}, rows))) : h("p", {class: "muted"}, patched(card) ? "No patch shipped for this file." : "Not read."); + const block = h("details", {class: "match-file", "data-path": file.path, "data-state": patched(card) ? null : file.state, open: opened}, fileHead(card, file), table); block.addEventListener("toggle", () => remember(card, block)); return h("li", {}, block); } @@ -202,19 +206,25 @@ if (card.kind !== "command") { return null; } + const merge = card.merge; + const short = (oid) => oid.slice(0, 12); + const preview = merge ? h("p", {class: "match-merge", "data-error": String(Boolean(merge.error))}, icon(merge.error ? "bi-exclamation-triangle" : "bi-sign-merge-left"), + merge.error ? `No merge preview: ${merge.error}` : `Brings in ${short(merge.base)} โ†’ ${short(merge.target)}, onto HEAD ${short(merge.head)}`) : null; return h("section", {class: "match-payload"}, h("pre", {class: "match-command"}, h("code", {}, revealed(card.command))), h("p", {class: "match-directory"}, revealed(card.directory)), - card.reason && card.reason !== "-" ? h("p", {class: "match-reason"}, revealed(card.reason)) : null); + card.reason && card.reason !== "-" ? h("p", {class: "match-reason"}, revealed(card.reason)) : null, preview); } function matchCard(card) { const files = card.files || []; - const list = files.length ? h("ol", {class: "match-files", "aria-label": `Files: ${files.length}`}, files.map((file, index) => fileBlock(card, file, index))) : h("p", {class: "muted"}, card.kind === "commit" ? "No diff shipped with this stage." : "Its command names no file."); + const none = card.kind === "commit" ? "No diff shipped with this stage." : card.merge ? (card.merge.error ? "No diff to show." : "The merge brings no change.") : "Its command names no file."; + const list = files.length ? h("ol", {class: "match-files", "aria-label": `Files: ${files.length}`}, files.map((file, index) => fileBlock(card, file, index))) : h("p", {class: "muted"}, none); const body = h("div", {class: "match-body"}, matchCommand(card), list); body.addEventListener("scroll", () => openOnScroll(body, ".match-file"), {passive: true}); const article = h("article", {class: "card match-card front", "data-card": card.id, "data-kind": card.kind, "data-stale": String(Boolean(card.stale)), "aria-label": `${card.kind} card of ${card.agent || "an agent"}`}, matchHead(card), body); + article.style.setProperty("--agent-hue", String(Faces.hash(card.agent) % 360)); markable(article, card); window.setTimeout(() => openOnScroll(body, ".match-file"), 0); return article; @@ -236,9 +246,51 @@ return marksOf(card).map((mark) => `${mark.path}:${mark.line}: ${mark.comment}`).join("\n"); } + /** + * @param {string} verdict accept, reject or later: the way the front card flies off, its stamp shown on the way. + * @param {Function} then runs once the card is gone; at once without a front card or under reduced motion, never + * while another card still flies. + */ + function flyOff(verdict, then) { + const front = matchView.dom && matchView.dom.stack.querySelector(".match-card.front"); + if (matchView.flying) { + return; + } + if (!front || window.matchMedia("(prefers-reduced-motion: reduce)").matches) { + then(); + return; + } + matchView.flying = true; + let landed = false; + const land = () => { + if (!landed) { + landed = true; + matchView.flying = false; + then(); + } + }; + front.dataset.leaning = verdict; + front.dataset.fly = verdict; + front.addEventListener("animationend", (event) => event.target === front && land()); + window.setTimeout(land, FLY_MS); + } + function decide(card, verdict, feedback) { - matchView.decisions.set(cardKey(card), {verdict, feedback}); - drawMatch(true); + flyOff(verdict, () => { + matchView.decisions.set(cardKey(card), {verdict, feedback}); + drawMatch(true); + }); + } + + function confetti() { + return h("div", {class: "match-confetti", "aria-hidden": "true"}, Array.from({length: CONFETTI}, (_, index) => { + const bit = h("i", {}); + bit.style.setProperty("--x", `${(index * 37) % 100}%`); + bit.style.setProperty("--c", String((index * 47) % 360)); + bit.style.setProperty("--r", `${(index % 2 ? 1 : -1) * (180 + index * 23)}deg`); + bit.style.setProperty("--d", `${(index % 7) * 0.06}s`); + return bit; + })); } function acceptCard(card) { @@ -264,8 +316,10 @@ } function laterCard(card) { - matchView.order = [...matchView.order.filter((id) => id !== card.id), card.id]; - drawMatch(true); + flyOff("later", () => { + matchView.order = [...matchView.order.filter((id) => id !== card.id), card.id]; + drawMatch(true); + }); } /** @@ -275,7 +329,7 @@ */ function matchKey(key) { const card = matchView.front; - if (!card || !matchView.dom || !matchView.dom.stack.isConnected) { + if (!card || ui.screen !== "match" || !matchView.dom || !matchView.dom.stack.isConnected) { return false; } const act = {ArrowRight: acceptCard, ArrowLeft: rejectCard, ArrowUp: laterCard}[key]; @@ -291,8 +345,10 @@ const drag = matchView.drag; if (drag && drag.id === event.pointerId) { const [dx, dy] = [event.clientX - drag.x, event.clientY - drag.y]; + const up = -dy > Math.abs(dx); article.style.transform = `translate(${dx}px, ${Math.min(0, dy)}px) rotate(${dx / 40}deg)`; - article.dataset.leaning = dx > 0 ? "accept" : dx < 0 ? "reject" : ""; + article.dataset.leaning = up ? "later" : dx > 0 ? "accept" : dx < 0 ? "reject" : ""; + article.style.setProperty("--lean", String(Math.min(1, up ? -dy / SWIPE_UP : Math.abs(dx) / (SWIPE_SHARE * article.getBoundingClientRect().width)))); } }; const release = (event) => { @@ -301,18 +357,18 @@ return; } drag.end(); - article.style.removeProperty("transform"); - delete article.dataset.leaning; const [dx, dy] = [event.clientX - drag.x, event.clientY - drag.y]; const far = SWIPE_SHARE * article.getBoundingClientRect().width; - if (event.type === "pointercancel" || !article.isConnected) { + const swiped = event.type === "pointercancel" ? "" : Math.abs(dx) >= far && Math.abs(dx) > Math.abs(dy) ? (dx > 0 ? "accept" : "reject") : -dy >= SWIPE_UP && -dy > Math.abs(dx) ? "later" : ""; + article.style.removeProperty("--lean"); + if (!((swiped === "accept" && !card.stale) || swiped === "later")) { + article.style.removeProperty("transform"); + delete article.dataset.leaning; + } + if (!article.isConnected) { return; } - if (Math.abs(dx) >= far && Math.abs(dx) > Math.abs(dy)) { - (dx > 0 ? acceptCard : rejectCard)(card); - } else if (-dy >= SWIPE_UP && -dy > Math.abs(dx)) { - laterCard(card); - } + ({accept: acceptCard, reject: rejectCard, later: laterCard}[swiped] || (() => null))(card); }; head.addEventListener("pointerdown", (event) => { if (event.button !== 0 || matchView.drag || (event.target instanceof Element && event.target.closest("button, a, input, textarea, select"))) { @@ -422,9 +478,26 @@ matchView.drag.end(); } const bar = h("div", {class: "card controls task-toolbar", role: "toolbar", "aria-label": "Match"}, h("strong", {}, icon("bi-stack"), "Match"), count, h("span", {class: "spacer"}), decisions, - iconBtn("bi-list-check", "Tasks", "btn small soft", () => go("tasks", null), "Tasks: back to the task list")); + iconBtn("bi-list-check", "Tasks", "btn small soft", () => go("tasks", null), "Tasks: back to the task list"), h("span", {"data-star-slot": ""})); fetchMatch(); - return h("div", {class: "graph tasks match"}, bar, stack); + return h("div", {class: "graph tasks match", "data-panel": "tasks/match"}, bar, stack); + } + + /** + * @returns {Element} the Match stack for a Home tile, kept while it still holds the live stack, without the + * data-panel and star slot of the screen. + */ + function homeMatch() { + const kept = homeView.hosts.get("tasks/match"); + if (kept && matchView.dom && kept.contains(matchView.dom.stack)) { + return kept; + } + const host = h("div", {class: "match-home"}, matchScreen()); + host.querySelectorAll("[data-panel]").forEach((node) => node.removeAttribute("data-panel")); + host.querySelectorAll("[data-star-slot]").forEach((node) => node.removeAttribute("data-star-slot")); + homeView.hosts.set("tasks/match", host); + window.setTimeout(() => drawMatch(true), 0); + return host; } function drawMatch(force) { @@ -454,6 +527,8 @@ return; } matchView.sig = sig; + const cleared = matchView.openBefore > 0 && !open.length; + matchView.openBefore = open.length; dom.count.textContent = open.length === 1 ? "1 card waits" : `${open.length} cards wait`; dom.tally.textContent = String(matchView.decisions.size); dom.decisions.hidden = !matchView.decisions.size || shownOverview; @@ -464,14 +539,20 @@ } if (shownOverview) { matchView.front = null; - dom.stack.replaceChildren(overview(cards, open.length)); + const shown = overview(cards, open.length); + if (cleared) { + shown.prepend(confetti()); + } + dom.stack.replaceChildren(shown); return; } const [front, ...rest] = open; matchView.front = front; - const accept = h("button", {type: "button", class: "btn match-accept", disabled: Boolean(front.stale), ...named("Accept", front.stale ? `Accept: refused while the card is stale (${front.stale_reason})` : "Accept (right arrow, swipe right)"), on: {click: () => acceptCard(front)}}, icon("bi-check-lg")); - const reject = h("button", {type: "button", class: "btn match-reject", ...named("Reject", "Reject with feedback (left arrow, swipe left)"), on: {click: () => rejectCard(front)}}, icon("bi-x-lg")); - const later = h("button", {type: "button", class: "btn match-later", disabled: !rest.length, ...named("Later", "Later: to the back of the stack (up arrow, swipe up)"), on: {click: () => laterCard(front)}}, icon("bi-arrow-up")); + const act = (cls, iconName, word, hint, disabled, run) => h("button", {type: "button", class: `match-act ${cls}`, disabled, ...named(word, hint), on: {click: run}}, + h("span", {class: "match-act-face", "aria-hidden": "true"}, icon(iconName)), h("span", {class: "match-act-label"}, word)); + const accept = act("match-accept", "bi-check-lg", "Accept", front.stale ? `Accept: refused while the card is stale (${front.stale_reason})` : "Accept (right arrow, swipe right)", Boolean(front.stale), () => acceptCard(front)); + const reject = act("match-reject", "bi-x-lg", "Reject", "Reject with feedback (left arrow, swipe left)", false, () => rejectCard(front)); + const later = act("match-later", "bi-arrow-up", "Later", "Later: to the back of the stack (up arrow, swipe up)", !rest.length, () => laterCard(front)); const peeks = rest.length ? h("div", {class: "match-peeks", role: "group", "aria-label": `${rest.length} more cards`}, rest.map(peekTab)) : null; const behind = rest.slice(0, MATCH_PEEKS).map((card, index) => { const sheet = h("div", {class: "match-behind", "aria-hidden": "true"}); @@ -481,7 +562,8 @@ const before = dom.stack.querySelector(".match-card.front"); const scrolled = before && before.dataset.card === front.id ? before.querySelector(".match-body").scrollTop : 0; const shown = matchCard(front); + shown.dataset.fresh = String(!before || before.dataset.card !== front.id); draggable(shown, front); - dom.stack.replaceChildren(peeks, h("div", {class: "match-deck"}, behind, shown), h("div", {class: "match-actions"}, reject, later, accept)); + dom.stack.replaceChildren(peeks || h("div", {class: "match-peeks"}), h("div", {class: "match-deck"}, behind, shown), h("div", {class: "match-actions"}, reject, later, accept)); shown.querySelector(".match-body").scrollTop = scrolled; } diff --git a/orchestrator/templates/page-tasks.js b/orchestrator/templates/page-tasks.js index b8fad5e..d9082f8 100644 --- a/orchestrator/templates/page-tasks.js +++ b/orchestrator/templates/page-tasks.js @@ -153,7 +153,7 @@ function taskViewSwitch(inbox) { return h("div", {class: "segmented", role: "group", "aria-label": "View"}, Nav.TASK_VIEWS.map(([id, name]) => h("button", { type: "button", class: "icon-only", ...named(name), "aria-pressed": String(!inbox && ui.views.tasks === id), on: {click: () => go("tasks", id)}, - }, icon(Nav.ICONS[id])))); + }, icon(Nav.ICONS[id]))), h("button", {type: "button", class: "icon-only", ...named("Match"), "aria-pressed": "false", on: {click: () => go("match", null)}}, icon(Nav.ICONS.match))); } function tasksScreen() { diff --git a/orchestrator/templates/style-match.css b/orchestrator/templates/style-match.css index 9f4bcfb..383795e 100644 --- a/orchestrator/templates/style-match.css +++ b/orchestrator/templates/style-match.css @@ -1,14 +1,31 @@ .graph.tasks.match > .match-stack { flex: 1; } +.match-home { display: grid; height: 100%; min-height: 0; } +.match-home > .graph.match { min-height: 0; } .match-stack { display: grid; grid-template-rows: auto minmax(0, 1fr) auto; gap: var(--sp-2); min-height: 0; width: min(100%, 960px); margin: 0 auto; } .match-peeks { display: flex; flex-wrap: wrap; gap: var(--sp-1); min-width: 0; } .match-peek { display: inline-flex; align-items: center; gap: 6px; max-width: 100%; min-width: 0; padding: 4px 10px 4px 4px; border: 1px solid var(--line); border-radius: 999px; background: var(--panel); color: inherit; font: inherit; font-size: var(--fs-sm); cursor: pointer; } .match-peek[data-stale="true"] { border-color: var(--bad); } .match-peek .match-peek-title { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; min-width: 0; } -.match-deck { position: relative; display: grid; grid-template-rows: minmax(0, 1fr); min-height: 0; padding-top: 14px; } -.match-behind { position: absolute; inset: calc(14px - var(--depth) * 7px) calc(var(--depth) * 12px) auto; height: 40px; border: 1px solid var(--line); border-radius: var(--radius-lg); background: var(--panel); opacity: calc(1 - var(--depth) * 0.3); } -.match-card.front { position: relative; display: grid; grid-template-rows: auto minmax(0, 1fr); min-height: 0; padding: 0; overflow: hidden; } -.match-card[data-stale="true"] { box-shadow: inset 0 3px 0 var(--bad); } -.match-head { display: grid; justify-items: center; gap: 6px; padding: var(--sp-3); border-bottom: 1px solid var(--line); text-align: center; } +.match-deck { position: relative; display: grid; grid-template-rows: minmax(0, 1fr); min-height: 0; padding-top: 14px; overflow-x: clip; } +.match-behind { position: absolute; inset: calc(14px - var(--depth) * 7px) calc(var(--depth) * 12px) auto; height: 40px; border: 1px solid var(--line); border-radius: 22px; background: var(--panel); opacity: calc(1 - var(--depth) * 0.3); transform: rotate(calc((var(--depth) * 2 - 3) * 1deg)); } +.match-card.front { position: relative; display: grid; grid-template-rows: auto minmax(0, 1fr); min-height: 0; padding: 0; overflow: hidden; border-radius: 22px; box-shadow: 0 14px 34px -16px rgb(0 0 0 / 0.45); } +.match-card.front::before { content: ""; position: absolute; inset: 0 0 auto; z-index: 1; height: 6px; background: linear-gradient(90deg, hsl(var(--agent-hue, 210) 75% 58%), hsl(calc(var(--agent-hue, 210) + 70) 75% 58%)); } +.match-card[data-stale="true"]::before { background: var(--bad); } +.match-card.front[data-fresh="true"] { animation: match-in 0.32s cubic-bezier(0.34, 1.56, 0.64, 1); } +.match-card.front[data-fresh="true"] .match-who .avatar { animation: match-pop 0.5s cubic-bezier(0.34, 1.56, 0.64, 1); } +.match-card.front[data-fly="accept"] { animation: match-fly-right 0.26s ease-in forwards; } +.match-card.front[data-fly="reject"] { animation: match-fly-left 0.26s ease-in forwards; } +.match-card.front[data-fly="later"] { animation: match-fly-up 0.26s ease-in forwards; } +.match-card.front[data-leaning]::after { position: absolute; top: 18%; z-index: 2; padding: 4px 14px; border: 4px solid currentColor; border-radius: 12px; background: color-mix(in srgb, var(--panel) 75%, transparent); font-size: 1.9rem; font-weight: 800; letter-spacing: 0.08em; opacity: var(--lean, 1); pointer-events: none; } +.match-card.front[data-leaning="accept"]::after { content: "ACCEPT"; left: 7%; color: var(--ok); transform: rotate(-14deg); } +.match-card.front[data-leaning="reject"]::after { content: "REJECT"; right: 7%; color: var(--bad); transform: rotate(14deg); } +.match-card.front[data-leaning="later"]::after { content: "LATER"; left: 50%; color: var(--muted); transform: translateX(-50%) rotate(-4deg); } +@keyframes match-in { from { transform: translateY(18px) scale(0.96); opacity: 0.3; } } +@keyframes match-pop { from { transform: scale(0.5) rotate(-12deg); opacity: 0; } } +@keyframes match-fly-right { to { transform: translate(120%, -4%) rotate(18deg); opacity: 0; } } +@keyframes match-fly-left { to { transform: translate(-120%, -4%) rotate(-18deg); opacity: 0; } } +@keyframes match-fly-up { to { transform: translateY(-110%) scale(0.9); opacity: 0; } } +.match-head { display: grid; justify-items: center; gap: 6px; padding: var(--sp-3); border-bottom: 1px solid var(--line); background: linear-gradient(180deg, hsl(var(--agent-hue, 210) 80% 60% / 0.16), transparent 75%); text-align: center; } .match-who { display: grid; justify-items: center; gap: 2px; } .match-who .avatar.big { width: 72px; height: 72px; } .match-name { font-size: var(--fs-lg); } @@ -25,6 +42,8 @@ .match-command { margin: 0; padding: 8px 10px; border-radius: 10px; background: var(--sunken); font-family: var(--mono); white-space: pre-wrap; overflow-wrap: anywhere; } .match-directory, .match-reason { margin: 0; color: var(--muted); font-size: var(--fs-sm); overflow-wrap: anywhere; } .match-directory::before { content: "in "; } +.match-merge { display: flex; align-items: center; gap: 6px; margin: 0; color: var(--info); font-size: var(--fs-sm); font-family: var(--mono); overflow-wrap: anywhere; } +.match-merge[data-error="true"] { color: var(--warn); } .match-files { display: grid; gap: var(--sp-2); margin: 0; padding: 0; list-style: none; } .match-file { min-width: 0; overflow: hidden; border: 1px solid var(--line); border-radius: 10px; background: var(--panel); } .match-file > summary.diff-head { padding: 6px 10px; cursor: pointer; list-style: none; } @@ -37,19 +56,34 @@ .match-mark-text { margin-left: 6px; } .match-comment-box { display: grid; gap: 6px; } .match-comment-box .actions { display: flex; justify-content: flex-end; gap: 6px; } -.match-actions { display: flex; justify-content: space-between; padding-bottom: var(--sp-1); } -.match-actions .btn { width: 56px; height: 56px; border-radius: 50%; } -.match-reject { color: var(--bad); } -.match-accept { color: var(--ok); } -.match-accept:disabled, .match-later:disabled { opacity: 0.4; cursor: not-allowed; } +.match-actions { display: flex; justify-content: space-between; align-items: end; padding: 0 var(--sp-2) var(--sp-1); } +.match-act { display: grid; justify-items: center; gap: 8px; padding: 0; border: 0; background: none; color: inherit; font: inherit; font-size: var(--fs-sm); font-weight: 700; cursor: pointer; } +.match-act-face { display: grid; place-items: center; width: 76px; height: 76px; border-radius: 50%; background: var(--tone); color: #fff; font-size: 2rem; box-shadow: 0 6px 0 color-mix(in srgb, var(--tone) 55%, #000), 0 14px 26px -12px var(--tone); transition: transform 0.12s ease, box-shadow 0.12s ease; } +.match-reject { --tone: var(--bad); } +.match-accept { --tone: var(--ok); } +.match-later { --tone: var(--muted); } +.match-later .match-act-face { width: 60px; height: 60px; font-size: 1.5rem; } +.match-act:hover:not(:disabled) .match-act-face { transform: translateY(-2px) scale(1.06); } +.match-act:active:not(:disabled) .match-act-face { transform: translateY(5px); box-shadow: 0 1px 0 color-mix(in srgb, var(--tone) 55%, #000), 0 4px 10px -6px var(--tone); } +.match-act:focus-visible { outline: none; } +.match-act:focus-visible .match-act-face { outline: 3px solid var(--accent); outline-offset: 4px; } +.match-act:disabled { opacity: 0.4; cursor: not-allowed; } .match-head { touch-action: pan-y; cursor: grab; } .match-card.front[data-leaning] { transition: none; } .match-card.front[data-leaning="accept"] { box-shadow: inset 0 0 0 3px var(--ok); } .match-card.front[data-leaning="reject"] { box-shadow: inset 0 0 0 3px var(--bad); } +.match-done { position: relative; display: grid; place-items: center; min-height: 0; overflow: hidden; } +.match-confetti { position: absolute; inset: 0; pointer-events: none; } +.match-confetti i { position: absolute; top: -12px; left: var(--x); width: 9px; height: 14px; border-radius: 2px; background: hsl(var(--c) 85% 60%); animation: match-confetti 1.4s ease-in var(--d) forwards; opacity: 0; } +@keyframes match-confetti { 0% { opacity: 1; transform: translateY(0) rotate(0); } 100% { opacity: 0; transform: translateY(70vh) rotate(var(--r)); } } +@media (prefers-reduced-motion: reduce) { + .match-card.front, .match-card.front .match-who .avatar, .match-confetti i { animation: none !important; } + .match-act-face { transition: none; } +} .match-open-overview { display: inline-flex; align-items: center; gap: 4px; } .match-tally { min-width: 18px; padding: 0 5px; border-radius: 999px; background: var(--accent); color: var(--on-accent); font-size: var(--fs-xs); text-align: center; } .match-feedback { width: 100%; font-family: var(--mono); resize: vertical; } -.match-overview { grid-row: 1 / -1; display: grid; align-content: start; gap: var(--sp-2); min-height: 0; overflow: auto; } +.match-overview { position: relative; grid-row: 1 / -1; display: grid; align-content: start; gap: var(--sp-2); min-height: 0; overflow: auto; } .match-overview .actions { display: flex; flex-wrap: wrap; align-items: center; gap: var(--sp-1); } .match-decisions { display: grid; gap: var(--sp-1); margin: 0; padding: 0; list-style: none; } .match-decision { display: grid; gap: 4px; min-width: 0; padding: 6px 10px; border: 1px solid var(--line); border-radius: 10px; } @@ -62,4 +96,7 @@ .match-head { padding: var(--sp-2); } .match-who .avatar.big { width: 56px; height: 56px; } .match-body { padding: var(--sp-1) var(--sp-2) var(--sp-2); } + .match-act-face { width: 64px; height: 64px; font-size: 1.7rem; } + .match-later .match-act-face { width: 52px; height: 52px; font-size: 1.3rem; } + .match-card.front[data-leaning]::after { font-size: 1.4rem; } } diff --git a/tests/e2e/test_001_gaps_e2e.py b/tests/e2e/test_001_gaps_e2e.py index e5d17d4..a00bfb4 100644 --- a/tests/e2e/test_001_gaps_e2e.py +++ b/tests/e2e/test_001_gaps_e2e.py @@ -273,7 +273,7 @@ class TestOrchestratorGaps(HubCase): self.assertNotIn("error", sweep[0], sweep[0]) self.assertEqual(sorted(sweep[0]["expected"]), sorted(f"#{screen}" for screen in base.SCREENS)) self.assertEqual([target for target in sweep[0]["nav"] if not any(f"#{screen}" == target or f"#{screen}".startswith(f"{target}/") for screen in base.SCREENS)], []) - self.assertEqual(sorted({view for found in sweep for view in found["views"]}), sorted(sweep[0]["viewNames"])) + self.assertEqual(sorted({view for found in sweep for view in found["views"]}), sorted([*sweep[0]["viewNames"], "Match"])) for found, screen, width in zip(sweep, screens, widths, strict=True): with self.subTest(screen=screen, width=width): self.assertNotIn("error", found, found) diff --git a/tests/test_hub_home.py b/tests/test_hub_home.py index 735fe73..5628d3c 100644 --- a/tests/test_hub_home.py +++ b/tests/test_hub_home.py @@ -765,7 +765,7 @@ class TestHomePage(unittest.TestCase): marked = set(re.findall(r"\['[^']+', \"([^\"]+)\"\]", home)) captured = set(re.findall(r'Panels\.capture\("([^"]+)"', home)) made = set(re.findall(r'\{kind: "(\w+)", id, view[,}]', sources)) - self.assertEqual((len(literal), marked), (11, {"radio-log"})) + self.assertEqual((len(literal), marked), (12, {"radio-log"})) literal |= marked self.assertEqual(len(dynamic), 13) self.assertEqual(sorted(literal | dynamic), sorted(registered)) diff --git a/tests/test_hub_match.py b/tests/test_hub_match.py index 8a59c8e..5935ae0 100644 --- a/tests/test_hub_match.py +++ b/tests/test_hub_match.py @@ -39,6 +39,28 @@ def staged_repo(root: Path) -> Path: return repo +def merge_repo(root: Path) -> tuple[Path, str]: + repo = root / "merge" + repo.mkdir() + git(repo, "init", "-q", "-b", "main") + (repo / "app.py").write_text("keep = 1\n", encoding="utf-8") + git(repo, "add", "-A") + git(repo, "commit", "-q", "-m", "base") + git(repo, "checkout", "-q", "-b", "feature") + (repo / "app.py").write_text("keep = 1\nadded = 2\n", encoding="utf-8") + git(repo, "commit", "-q", "-am", "feature") + target = git(repo, "rev-parse", "HEAD").strip() + git(repo, "checkout", "-q", "main") + return repo, target + + +def move_head(repo: Path) -> str: + (repo / "other.txt").write_text("moved\n", encoding="utf-8") + git(repo, "add", "other.txt") + git(repo, "commit", "-q", "-m", "moved") + return git(repo, "rev-parse", "HEAD").strip() + + class MatchCase(HubCase): def setUp(self): super().setUp() @@ -336,6 +358,69 @@ class TestCommandCards(MatchCase): self.assertIn(words, shown.stdout) +class TestMergeCards(MatchCase): + def merge_row(self) -> tuple[Path, str, str]: + repo, target = merge_repo(self.work) + command = f"git merge --ff-only {target}" + self.operator_row("operator/merge", command, str(repo)) + return repo, target, command + + def released(self) -> tuple[Path, str, dict]: + repo, target, _ = self.merge_row() + self.card("operator:operator/merge") + self.run_runner(register=False) + card = self.card("operator:operator/merge") + entry = {"kind": "operator", "id": "operator/merge", "verb": "approve", "label": "", "sha256": card["sha256"], "payload": card["hash"]} + with mock.patch.object(batches, "UNDO", 0.05): + self.assertEqual(self.approve([entry], self.signed([entry], self.pin()))[0], 202) + self.settle(lambda: self.httpd.hub.jobs.listed() != []) + self.assertEqual([job["head"] for job in self.runner_jobs()], [card["merge"]["head"]]) + return repo, target, card + + def test_the_runner_previews_a_merge_row_and_its_card_turns_stale_once_head_moves(self): + repo, target, command = self.merge_row() + self.assertIsNone(self.card("operator:operator/merge")["merge"]) + self.run_runner(register=False) + card = self.card("operator:operator/merge") + head = git(repo, "rev-parse", "HEAD").strip() + self.assertEqual((card["merge"], card["stale"]), ({"head": head, "base": head, "target": target, "error": ""}, False)) + shown = {"": "@@ -1 +1,2 @@\n keep = 1\n+added = 2", "content withheld": ""} + self.assertEqual([(entry["path"], entry["status"], entry["additions"], entry["patch"] == shown[entry["note"]]) for entry in card["files"]], [("app.py", "M", 1, True)]) + status, _, body = self.call("GET", "/api/runner/previews", None, self.client()) + self.assertEqual((status, json.loads(body)["rows"]), (200, [{"task": "operator/merge", "command": command, "directory": str(repo), "head": head}])) + taken = self.httpd.hub.merge_previews.get("operator:operator/merge")["taken"] + self.run_runner(register=False) + self.assertEqual(self.httpd.hub.merge_previews.get("operator:operator/merge")["taken"], taken) + moved = move_head(repo) + self.run_runner(register=False) + after = self.card("operator:operator/merge") + self.assertEqual((after["stale"], after["stale_reason"], after["merge"]["head"]), (True, "HEAD or the merge base moved since it was added", moved)) + + def test_only_the_runner_posts_a_preview_and_only_for_an_open_row_and_its_command(self): + _, target, command = self.merge_row() + shown = {"task": "operator/merge", "command": command, "head": "a" * 40, "base": "a" * 40, "target": target, "diff": []} + self.assertEqual(self.post_json("/api/runner/previews", shown, self.guard(self.host))[0], 403) + self.assertEqual(self.call("GET", "/api/runner/previews", None, self.guard(self.host))[0], 403) + for bad, code in (({**shown, "command": "git merge main"}, 409), ({**shown, "task": "operator/gone"}, 404), ({**shown, "head": "HEAD"}, 400), ({**shown, "diff": "x"}, 400)): + with self.subTest(bad=bad): + self.assertEqual(self.post_json("/api/runner/previews", bad, self.client())[0], code) + self.assertEqual(self.post_json("/api/runner/previews", shown, self.client())[0], 200) + + def test_a_released_merge_runs_while_head_stays_the_previewed_one(self): + repo, target, _ = self.released() + self.run_runner(register=False) + self.settle(lambda: self.httpd.hub.jobs.listed()[0]["status"] == "done") + self.assertEqual(git(repo, "rev-parse", "HEAD").strip(), target) + + def test_a_released_merge_is_refused_once_head_moved_after_the_preview(self): + repo, _, card = self.released() + moved = move_head(repo) + self.run_runner(register=False) + job = self.httpd.hub.jobs.listed()[0] + self.assertEqual((job["status"], git(repo, "rev-parse", "HEAD").strip()), ("refused", moved)) + self.assertIn(f"HEAD moved from {card['merge']['head'][:12]} to {moved[:12]}", job["output"]) + + class TestPayloadHash(unittest.TestCase): def test_the_hash_binds_command_directory_and_every_file_state(self): files = [{"path": "/tmp/a", "state": "read", "reason": "", "sha256": "1" * 64, "size": 3, "content": "abc"}] diff --git a/tests/test_hub_operator_tasks.py b/tests/test_hub_operator_tasks.py index 94fe8e7..e6940a6 100644 --- a/tests/test_hub_operator_tasks.py +++ b/tests/test_hub_operator_tasks.py @@ -720,6 +720,78 @@ class TestStagedDiff(unittest.TestCase): found = staged_diff.commit_of(command, "/w") self.assertEqual(None if found is None else str(found), expected) + def test_only_a_single_git_commit_tree_of_full_object_ids_names_its_tree_and_parents(self): + tree, parent, other = "a" * 40, "b" * 40, "c" * 64 + cases = { + f"git commit-tree {tree} -p {parent} -m 'feat: x' -m body": ("/w", tree, [parent]), + f"git -C sub commit-tree -p{parent} -p {other} -S -mx {tree}": ("/w/sub", tree, [parent, other]), + f"env --chdir=sub git commit-tree {tree} --gpg-sign=KEY -F msg.txt": ("/w/sub", tree, []), + f"git commit-tree {tree} --no-gpg-sign -m 'fix commit'": ("/w", tree, []), + f"git commit-tree HEAD^{{tree}} -p {parent} -m x": None, + f"git commit-tree {tree} -p HEAD -m x": None, + f"git commit-tree {tree[:12]} -m x": None, + f"git commit-tree {tree} {other} -m x": None, + f"git commit-tree {tree} -p": None, + f"git commit-tree {tree} --frobnicate -m x": None, + f"git commit-tree {tree} -- -m x": None, + "git commit-tree -m x": None, + f"GIT_DIR=/tmp/other git commit-tree {tree} -m x": None, + f"git commit-tree {tree} -m x && git push": None, + f"git commit {tree} -m x": None, + } + for command, expected in cases.items(): + with self.subTest(command=command): + found = staged_diff.tree_of(command, "/w") + self.assertEqual(None if found is None else (str(found[0]), found[1], found[2]), expected) + self.assertIsNone(staged_diff.commit_of(f"git commit-tree {tree} -m x", "/w")) + + def test_only_a_single_git_merge_of_a_full_object_id_names_its_directory_and_target(self): + target = "d" * 40 + cases = { + f"git merge --ff-only {target}": ("/w", target), + f"git -C sub merge --no-ff --no-edit -m 'merge it' -S {target}": ("/w/sub", target), + f"git merge --message=x --no-verify -mx {target}": ("/w", target), + "git merge --ff-only origin/main": None, + f"git merge {target} {'e' * 40}": None, + f"git merge -s ours {target}": None, + f"git merge -X theirs {target}": None, + f"git merge --allow-unrelated-histories {target}": None, + "git merge -m": None, + f"git merge {target} && git push": None, + f"GIT_DIR=/tmp/x git merge {target}": None, + f"git merge-base HEAD {target}": None, + } + for command, expected in cases.items(): + with self.subTest(command=command): + found = staged_diff.merge_of(command, "/w") + self.assertEqual(None if found is None else (str(found[0]), found[1]), expected) + + def test_a_merge_preview_shows_the_target_tree_against_its_merge_base_with_head(self): + base = git(self.repo, "rev-parse", "HEAD").strip() + git(self.repo, "commit", "-q", "-m", "next") + target = git(self.repo, "rev-parse", "HEAD").strip() + git(self.repo, "reset", "-q", "--hard", base) + found = staged_diff.merge_preview(self.repo, target, self.rules) + tree = git(self.repo, "rev-parse", f"{target}^{{tree}}").strip() + self.assertEqual(found, {"head": base, "base": base, "target": target, "diff": staged_diff.tree_diff(self.repo, tree, self.rules)[0]}) + self.assertEqual(staged_diff.head_of(self.repo), base) + with self.assertRaises(staged_diff.DiffError): + staged_diff.merge_preview(self.repo, "0" * 40, self.rules) + + def test_a_commit_tree_ask_ships_its_tree_against_the_first_parent_and_its_allow_needs_no_binding(self): + tree = git(self.repo, "write-tree").strip() + head = git(self.repo, "rev-parse", "HEAD").strip() + ask = {**ASK, "tool": "Bash", "command": f"git commit-tree {tree} -p {head} -m 'fix commit'", "cwd": str(self.repo)} + diff, sealed = staged_diff.tree_diff(self.repo, tree, self.rules) + self.assertEqual(permission_hook.commit_diff(ask, self.rules), (None, {"diff": diff, "sealed": sealed})) + self.assertFalse(permission_hook.unapprovable(ask)) + self.assertEqual(permission_hook.bound(ALLOW, ask, None), ALLOW) + root = permission_hook.commit_diff({**ask, "command": f"git commit-tree {tree} -m root"}, self.rules)[1]["diff"] + self.assertEqual([(entry["path"], entry["status"]) for entry in root], [("added.txt", "A"), ("app.py", "A"), ("logo.png", "B")]) + for command in (f"git commit-tree {head} -p {tree} -m x", f"git commit-tree {'0' * 40} -m x"): + with self.subTest(command=command): + self.assertEqual(permission_hook.commit_diff({**ask, "command": command}, self.rules), (None, {})) + class TestHubOperatorTasks(HubCase): def scratch(self) -> tuple[Path, Path, dict]: