diff --git a/README.md b/README.md index 9d07d85..80d8b45 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ Compatible with Claude Code, Codex, Gemini CLI, Cursor, Copilot, Windsurf, Cline ## Naming ๐Ÿท๏ธ -Every first-party skill is named `kvb--` with one of these categories: `think`, `create`, `code`, `ci`, `git`, `release`, `check`, `org`, `agent`, `skill`, `coach`: `think` thinks without producing a file, `create` produces an artifact, `code` works on code, `ci` on pipelines, `git` on history and forges, `release` announces a release (changelog, article, posts), `check` analyses and reports findings, `org` coordinates agents, `agent` acts on one agent itself: its repository setup (code index, agent instructions) and its state (drain, suspend, resume), `skill` works on skills themselves, `coach` serves the operator's wellbeing. Only `kvb-cleanup`, `kvb-coach`, `kvb-help` and the collectors `kvb-dream`, `kvb-optimize`, `kvb-release` and `kvb-transcend` stand without a category. Names use `a-z`, `0-9` and single hyphens, at most 64 characters, and equal their directory name. `tests/test_naming.py` enforces all of it, including that the organigram below lists every skill under its category. +Every first-party skill is named `kvb--` with one of these categories: `think`, `create`, `code`, `ci`, `git`, `release`, `check`, `org`, `agent`, `skill`, `coach`: `think` thinks without producing a file, `create` produces an artifact, `code` works on code, `ci` on pipelines, `git` on history and forges, `release` announces a release (changelog, article, posts), `check` analyses and reports findings, `org` coordinates agents, `agent` acts on one agent itself: its repository setup (code index, agent instructions) and its state (drain, suspend, resume), `skill` works on skills themselves, `coach` serves the operator's wellbeing. Only `kvb-cleanup`, `kvb-coach`, `kvb-help`, `kvb-match` and the collectors `kvb-dream`, `kvb-optimize`, `kvb-release` and `kvb-transcend` stand without a category. Names use `a-z`, `0-9` and single hyphens, at most 64 characters, and equal their directory name. `tests/test_naming.py` enforces all of it, including that the organigram below lists every skill under its category. ## Organigram ๐Ÿ›๏ธ @@ -115,6 +115,7 @@ flowchart LR none --> optimize_all[kvb-optimize] none --> release_all[kvb-release] none --> coach_all[kvb-coach] + none --> match_all[kvb-match] coach --> coach_meditation[kvb-coach-meditation] ``` @@ -240,6 +241,7 @@ flowchart LR optimize[kvb-optimize] release_all[kvb-release] coach[kvb-coach] + match[kvb-match] end subgraph cat_coach [coach] meditation[kvb-coach-meditation] diff --git a/docs/requirements/012-match-review.md b/docs/requirements/012-match-review.md new file mode 100644 index 0000000..2922a25 --- /dev/null +++ b/docs/requirements/012-match-review.md @@ -0,0 +1,149 @@ +# 012 - Match Review + +## User Story + +As the operator, I want every waiting commit and operator command as a card +in one stack under Tasks, decide each with a swipe and release all decisions +with one passkey at the end, so that I review agent work fast without +terminal prompts. + +## Decisions (operator-confirmed 2026-11-14; do not re-litigate) + +1. **Cards**: staged commits (diff, score, gate) and operator commands with + their payload: the command, its directory, its reason and the content of + every file the command reads (an issue body, a script, a list file). + Rejected: staged commits only; decision rows as cards (they keep their own + pick view). +2. **Place**: a Match view under the Tasks tab; the Tasks tab carries a badge + with the number of waiting cards. +3. **Card layout**: on top the agent's face, below it the agent's name and + its age in days (since its first session), then repository, branch and + worktree; below them the affected files, each collapsed, opening one + after another while the card scrolls down and showing the diff (commits) + or the file content (command payloads) with line numbers. +4. **Marks**: a right-click on a code line (a long press on touch) opens a + short comment field; the mark stays on the card. +5. **Decide**: the green check at the bottom right, a swipe right or the + right arrow key accepts; the red cross at the bottom left, a swipe left or + the left arrow key rejects and opens a feedback popup prefilled with the + card's marks (file, line, comment), editable; a swipe up or the up arrow + key moves the card to the back of the stack. Nothing runs while the + operator swipes. +6. **Release**: after the last card, a list overview shows every decision + with a way to change it; one passkey signature over the list of card id, + tree or payload hash and decision releases them all. Accepted commits: + the agent checks the signature with `approval.py verify` against the + signed hash and commits. Accepted commands: the hub runs them as it runs + operator rows today. Rejections: a radio call with the feedback text goes + to the card's agent. Rejected: a passkey per card; a release button + without a passkey. +7. **Source**: the existing hub review queue (`approval.py`) and the operator + rows stay the source of truth. A thin `kvb-match` skill (`match.py add`, + `list`, `show`) lets an agent add a finished stage as a patch snapshot + (staged diff, tree hash, score) and shows the cards in a terminal. + Rejected: a second queue next to the reviews; a UI over the reviews only. +8. **Snapshot binding**: a card shows the patch or payload as it was when it + was added; when the agent's staged tree or a payload file changes + afterwards, the card shows `stale` and cannot be accepted until it is + added again. +9. **Gone rows**: a card whose review or operator row the server no longer + has leaves the stack on the next refresh; it never shows a 404. +10. **Responsive**: the view works at 390 px and on desktop, with touch + swipe and mouse drag. Reaching the hub from a phone is a separate + requirement. + +## Approach + +```mermaid +flowchart TD + subgraph P["๐Ÿงญ 0 ยท Preparation"] + P1["๐Ÿ“‹ Write requirement"] --> P2{"โœ… Operator approves?"} + P2 -- "โœ๏ธ corrections" --> P1 + end + P2 -- "๐Ÿค– yes" --> Q1 + subgraph Q["๐Ÿ—‚๏ธ A ยท Queue and skill"] + Q1["๐Ÿงฉ match.py add, list, show over the review queue"] --> Q2["๐Ÿ“ฆ Operator rows as cards with payload files"] + Q2 --> Q3["๐Ÿ”’ Snapshot hash, stale and gone detection"] + Q3 --> QT{"๐Ÿงช Unit tests green?"} + QT -- "๐Ÿ”ด no: fix" --> Q1 + end + QT -- "๐ŸŸข yes" --> C1 + subgraph C["๐Ÿƒ B ยท Card"] + C1["๐Ÿ™‚ Face, name, age, repository, branch, worktree"] --> C2["๐Ÿ“œ Files open on scroll, diff with line numbers"] + C2 --> C3["๐Ÿ–ฑ๏ธ Right-click and long-press marks"] + C3 --> CT{"๐Ÿงช E2E at 1920, 1366, 390 green?"} + CT -- "๐Ÿ”ด no: fix" --> C1 + CT -- "๐ŸŸข yes" --> CF{"๐Ÿ’ฌ Operator feedback on screenshots?"} + CF -- "โœ๏ธ changes" --> C1 + end + CF -- "๐Ÿ‘ fits" --> D1 + subgraph D["๐Ÿ‘‰ C ยท Decide and release"] + D1["โ†”๏ธ Swipe, buttons, arrow keys, later"] --> D2["๐Ÿ“ Feedback popup prefilled from marks"] + D2 --> D3["๐Ÿ“‹ List overview of all decisions"] + D3 --> D4["๐Ÿ”‘ One passkey signature over ids, hashes, decisions"] + D4 --> D5["๐Ÿš€ Commits verified and committed, commands run, calls sent"] + D5 --> DT{"๐Ÿงช Release and negative control green?"} + DT -- "๐Ÿ”ด no: fix" --> D1 + DT -- "๐ŸŸข yes" --> DF{"๐Ÿ’ฌ Operator feedback?"} + DF -- "โœ๏ธ changes" --> D1 + end + DF -- "๐Ÿ‘ fits" --> E1["๐Ÿ Review, commit with operator OK, hand-over"] +``` + +## Acceptance Criteria + +### Queue and skill + +- [ ] `match.py add --repo ` in a worktree with staged changes adds + one card whose patch equals `git diff --cached` and whose hash equals + `git write-tree`; `match.py list` shows it and `match.py show ` + prints its patch. +- [ ] Every open operator row appears as a card with its command, directory, + reason and the content of each regular file its command names; a + symlink or a file over the size limit is shown as refused, not read. +- [ ] A card whose staged tree or payload file changed after it was added + shows `stale` and its accept is disabled. +- [ ] A card whose review or operator row the server no longer returns is + gone from the stack after the next refresh, without a page reload. + +### Card + +- [ ] A card shows the agent's face, name, age in days, repository, branch + and worktree, and the file list. +- [ ] Scrolling down a card opens its files one after another; each shows + its diff or content with line numbers. +- [ ] A right-click or a long press on a code line adds a mark with a + comment; the mark is shown at its line. + +### Decide and release + +- [ ] Swipe right, the check button and the right arrow record accept; swipe + left, the cross button and the left arrow open the feedback popup + prefilled with every mark of the card; swipe up and the up arrow move + the card to the back; no commit and no command runs before the + release. +- [ ] The list overview shows every decision and lets each be changed + before the release. +- [ ] The server refuses a release whose passkey signature does not cover + exactly the listed card ids, hashes and decisions, and refuses a + replayed signature. +- [ ] After a release, `approval.py verify` accepts an accepted commit only + at its signed tree hash; a changed index is refused. +- [ ] After a release, each accepted command runs once and its result is + shown; each rejected card's agent receives a radio call whose text + contains the feedback. +- [ ] The Tasks tab badge equals the number of waiting cards. + +### Tests + +- [ ] Unit: `match.py add`, `list`, `show`; the snapshot hash; stale and gone + detection; release signature verification for a valid, a tampered and + a replayed list; the feedback prefill from marks. +- [ ] Integration: `approval.py verify` against a released list; payload + extraction from operator rows, including a symlink and an oversized + file that are refused. +- [ ] E2E: Chromium and Firefox at 1920, 1366 and 390 px swipe through three + cards (a commit, a command, a stale card), mark a line, reject with + feedback, open the list overview and release through a virtual WebAuthn + authenticator; negative control: a decision changed after signing is + refused. diff --git a/docs/requirements/README.md b/docs/requirements/README.md index fe46054..1147bc3 100644 --- a/docs/requirements/README.md +++ b/docs/requirements/README.md @@ -12,3 +12,4 @@ skill defines the format. - [006 - Score Metric Overlays](006-score-metric-overlays.md) - [007 - Resources View](007-resources-view.md) - [008 - Home Dashboard](008-home-dashboard.md) +- [012 - Match Review](012-match-review.md) diff --git a/orchestrator/kvb_orchestrator/handler.py b/orchestrator/kvb_orchestrator/handler.py index 7639f19..e0e8ba8 100644 --- a/orchestrator/kvb_orchestrator/handler.py +++ b/orchestrator/kvb_orchestrator/handler.py @@ -25,7 +25,9 @@ ITEM = re.compile(r"/api/(asks|decisions)/([0-9a-f]{16})(?:/(allow|deny))?") ENTRY = re.compile(r"/api/stream/([0-9]{1,12})") BOARD = re.compile(r"/api/board/([a-z-]{1,32})") UPLOADS = "/api/uploads" -POSTS = ("/api/asks", UPLOADS, "/api/messages") +MATCH_ROUTE = "/api/match" +MATCH_POSTS = {"/api/match/stale": "match_stale", "/api/match/snapshot": "match_snapshot"} +POSTS = ("/api/asks", UPLOADS, "/api/messages", *MATCH_POSTS) STORED = { "page": (".html", "text/html; charset=utf-8", PAGE_CSP), "files": (".json", "application/json", PLAIN_CSP), @@ -127,6 +129,8 @@ class Handler(Exchange): self.answer(lambda: hub.events(self.query()), HTTPStatus.OK) elif path == "/api/tree": self.answer(hub.repositories, HTTPStatus.OK) + elif path == MATCH_ROUTE: + self.answer(hub.match_cards, HTTPStatus.OK) elif path == "/api/resources": self.answer(lambda: sampled(hub.kept / RESOURCES, hub.span(self.query(), time.time())), HTTPStatus.OK) elif path == "/api/scores": @@ -262,9 +266,11 @@ class Handler(Exchange): """ if path == "/mcp": return self.mcp_receiver(host) - if path == "/api/asks": + if path == "/api/asks" or path in MATCH_POSTS: if self.local(host): - return lambda body: self.answer(lambda: self.server.hub.ask(body), HTTPStatus.CREATED) + hub = self.server.hub + receive = getattr(hub, MATCH_POSTS[path]) if path in MATCH_POSTS else hub.ask + 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): diff --git a/orchestrator/kvb_orchestrator/hub.py b/orchestrator/kvb_orchestrator/hub.py index 2eb787c..a49bdc6 100644 --- a/orchestrator/kvb_orchestrator/hub.py +++ b/orchestrator/kvb_orchestrator/hub.py @@ -26,6 +26,7 @@ from .inbox import Inbox from .jobs import Jobs from .language import Language, Model from .ledger import Ledger, Marks, Reviews +from .matching import Matching from .mcp import Mcp from .messaging import Messaging from .names import Names @@ -82,7 +83,7 @@ def environment(templates: Path) -> jinja2.Environment: @dataclass(frozen=True) -class Hub(Mcp, Reviewing, Asking, Messaging, Choosing, Approving, Denying, Requesting, Cleaning, Offices, Tasking, Gating, Firewall, Inbox, Rules, Jobs, Sources, Timeline, View, Language): +class Hub(Mcp, Reviewing, Asking, Messaging, Choosing, Approving, Denying, Requesting, Cleaning, Offices, Tasking, Gating, Firewall, Inbox, Matching, Rules, Jobs, Sources, Timeline, View, Language): council: Path pages: Path public_port: int @@ -128,6 +129,7 @@ class Hub(Mcp, Reviewing, Asking, Messaging, Choosing, Approving, Denying, Reque replay: Path history: History view_store: ViewStore + match_snapshots: Ledger def hosts(self) -> tuple[str, str]: return f"127.0.0.1:{self.public_port}", f"localhost:{self.public_port}" @@ -174,6 +176,7 @@ def open_hub(council: Path, pages: Path, public_port: int, state: Path, host_sta voice_notes=VoiceNotes(state / "voice", host_state / "voice", speech, lambda: {message["voice"] for message in messages.listed() if message.get("voice")}), replay=state / "replay" / "messages.json", view_store=ViewStore(state / "view.json"), + match_snapshots=Ledger(state / "match.json"), rules=Ledger(state / "rules.json"), offers=Offers(), jobs=Ledger(state / "jobs.json"), diff --git a/orchestrator/kvb_orchestrator/matching.py b/orchestrator/kvb_orchestrator/matching.py new file mode 100644 index 0000000..f7ff82d --- /dev/null +++ b/orchestrator/kvb_orchestrator/matching.py @@ -0,0 +1,124 @@ +from __future__ import annotations + +import time + +from .council import read_claims +from .diffs import stored_diff +from .errors import Missing, ToolError +from .fields import decode, expect, field +from .payloads import denied_roots, payload_files, payload_hash +from .records import digest, iso_epoch +from .register import REGISTER, adder, operator_rows, read_register +from .signed import signing +from .tree import inside + +OPERATOR = "operator/" + + +def repository_of(common_dir: str) -> str: + return common_dir.removesuffix("/.git") if common_dir.endswith("/.git") else common_dir + + +def born_of(agent: str, names: list[dict], claims: list[dict]) -> float | None: + """Returns: + When the agent was first seen: its earliest name sighting, else its + earliest claim; None when neither knows it. + """ + seen = [entry["first_seen"] for entry in names if entry["name"] == agent and isinstance(entry.get("first_seen"), int | float)] + claimed = [iso_epoch(claim["since"]) for claim in claims if agent and agent in (claim["agent"], claim["session"])] + found = seen or [moment for moment in claimed if moment is not None] + return min(found) if found else None + + +def place_of(directory: str, scan: dict) -> tuple[str, str, str]: + """Returns: + The repository, branch and worktree of the deepest worktree of the + branch tree that holds directory; empty texts outside every one. + """ + found = [(repo["path"], branch["name"], tree["path"]) for repo in scan.get("repos", []) for branch in repo["branches"] for tree in branch["worktrees"] if tree["path"] and inside(directory, tree["path"])] + return max(found, key=lambda place: len(place[2])) if found else ("", "", directory) + + +class Matching: + def match_cards(self) -> dict: + now = time.time() + claims = read_claims(self.council) + names = self.names.listed() + reviews = self.reviews.pending() + cards = [self.commit_card(review, reviews, born_of(review.get("agent", ""), names, claims)) for review in reviews] + tasks = read_register(self.council / REGISTER) + held = self.open_jobs() + rows = [row for row in operator_rows(tasks) if row["check"] != "decision" and row["task"] not in held] + roots = denied_roots(self.settings_files()[0]) + scan = self.tree.get() + for row in rows: + agent = adder(tasks[row["task"]]) + cards.append(self.command_card(row, agent, born_of(agent, names, claims), roots, scan)) + 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"]) + return {"now": now, "cards": cards} + + def commit_card(self, review: dict, reviews: list[dict], born: float | None) -> dict: + newer = [other["id"] for other in reviews if other["created"] > review["created"] and (other["worktree"], other["branch"]) == (review["worktree"], review["branch"])] + live = review.get("live_tree") + reason = f"added again as review:{newer[-1]}" if newer else "the staged tree changed since it was added" if live not in (None, review["tree"]) else "" + try: + files = stored_diff(self.reviews.pages, "review", review["id"])["diff"] + except Missing: + files = None + place = {"repo": repository_of(review.get("repo", "")), "branch": review["branch"], "worktree": review["worktree"]} + return { + "id": f"review:{review['id']}", "kind": "commit", "ref": review["id"], "agent": review.get("agent", ""), "born": born, "created_ts": iso_epoch(review["created"]), + **place, "title": review["title"], "score": review.get("score", ""), "gate": review.get("gate", ""), "hash": review["tree"], "live_hash": live or review["tree"], + "stale": bool(reason), "stale_reason": reason, "files": files, "command": "", "directory": review["worktree"], "reason": "", + } + + 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) + snapshot = self.match_snapshots.get(card_id) + if snapshot is None or snapshot["command_sha256"] != digest(row["command"]): + 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()}) + stale = snapshot["hash"] != live + 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": "", "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"]), + } + + def match_stale(self, body: bytes) -> dict: + """Args: + body: {"id", "tree"}: a pending review and the tree git + write-tree prints in its worktree now; a tree other than the + review's marks its card stale. + """ + payload = decode(body) + expect(payload, ("id", "tree")) + review_id, tree = field(payload, "id"), field(payload, "tree") + review = self.reviews.get(review_id) + if review is None or review["status"] != "pending": + raise Missing(review_id) + self.reviews.change(review_id, {"live_tree": tree}) + return {"id": review_id, "stale": tree != review["tree"]} + + def match_snapshot(self, body: bytes) -> dict: + """Args: + body: {"task"}: an open operator row whose card takes its payload + files as they are now. + """ + payload = decode(body) + expect(payload, ("task",)) + 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") + self.match_snapshots.remove(f"operator:{task}") + card = next((card for card in self.match_cards()["cards"] if card["id"] == f"operator:{task}"), None) + if card is None: + raise Missing(task) + return {"id": card["id"], "hash": card["hash"], "stale": card["stale"]} diff --git a/orchestrator/kvb_orchestrator/payloads.py b/orchestrator/kvb_orchestrator/payloads.py new file mode 100644 index 0000000..72c78ae --- /dev/null +++ b/orchestrator/kvb_orchestrator/payloads.py @@ -0,0 +1,121 @@ +from __future__ import annotations + +import hashlib +import os +import re +import shlex +import stat + +from .signed import client_module, signing + +sandbox_paths = client_module("sandbox_paths", {}) + +PAYLOAD_LIMIT = 64 << 10 +PAYLOAD_FILES = 8 +PAYLOAD_ROOT = "/tmp" +BINARY_PROBE = 8000 +EXTENSION = re.compile(r"[^/]+\.[A-Za-z0-9]{1,8}") +URL = re.compile(r"[A-Za-z][A-Za-z0-9+.-]*://") + + +def words_of(command: str) -> list[str]: + try: + return shlex.split(command) + except ValueError: + return command.split() + + +def named_paths(command: str, directory: str) -> list[str]: + """Returns: + Every word of the command, or value of a --name=value option, that + names a path: one holding a / or ending in a file extension, no + URL; relative ones joined to directory, each once, in order. + """ + found: list[str] = [] + for word in words_of(command): + value = word.split("=", 1)[1] if word.startswith("-") and "=" in word else word + if not value or value.startswith("-") or URL.match(value) or not ("/" in value or EXTENSION.fullmatch(value)): + continue + path = os.path.normpath(os.path.join(directory, os.path.expanduser(value))) + if path not in found: + found.append(path) + return found + + +def refused(path: str, reason: str, size: int) -> dict: + return {"path": path, "state": "refused", "reason": reason, "sha256": "", "size": size, "content": ""} + + +def read_payload(path: str, roots: list[str] | None) -> dict | None: + """Args: + path: an absolute, normalized path a command names. + roots: the sandbox denyRead roots, None when the hub knows none yet. + + Returns: + The file as shown on a card: read with its content and sha256, or + refused with the reason and no content; None when nothing lies at + the path or it is no file. + """ + try: + info = os.lstat(path) + except OSError: + return None + if stat.S_ISLNK(info.st_mode): + return refused(path, "a symlink, never followed", 0) + if not stat.S_ISREG(info.st_mode): + return None + if not path.startswith(f"{PAYLOAD_ROOT}/") or os.path.realpath(path) != path: + return refused(path, f"outside {PAYLOAD_ROOT} or behind a symlinked folder", info.st_size) + if roots is None: + return refused(path, "no sandbox view yet, so no file is read", info.st_size) + if sandbox_paths.denied(path, roots): + return refused(path, "the sandbox denies reading it", info.st_size) + if info.st_size > PAYLOAD_LIMIT: + return refused(path, f"{info.st_size} bytes, over the {PAYLOAD_LIMIT} bytes a card shows", info.st_size) + try: + descriptor = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK) + except OSError as error: + return refused(path, f"unreadable: {error.strerror}", info.st_size) + with os.fdopen(descriptor, "rb") as handle: + if not stat.S_ISREG(os.fstat(handle.fileno()).st_mode): + return refused(path, "no regular file", info.st_size) + data = handle.read(PAYLOAD_LIMIT + 1) + if len(data) > PAYLOAD_LIMIT: + return refused(path, f"over the {PAYLOAD_LIMIT} bytes a card shows", len(data)) + if b"\0" in data[:BINARY_PROBE]: + return refused(path, "a binary file", len(data)) + return {"path": path, "state": "read", "reason": "", "sha256": hashlib.sha256(data).hexdigest(), "size": len(data), "content": data.decode("utf-8", "replace")} + + +def payload_files(command: str, directory: str, roots: list[str] | None) -> list[dict]: + found = (read_payload(path, roots) for path in named_paths(command, directory) if directory.startswith("/")) + return [entry for entry in found if entry is not None][:PAYLOAD_FILES] + + +def payload_hash(command: str, directory: str, files: list[dict]) -> str: + """Returns: + The sha256 a command card is bound to: its command, directory and + each named file's path, state, reason and content digest. + """ + listed = [[entry["path"], entry["state"], entry["reason"], entry["sha256"]] for entry in files] + return signing.item_hash({"kind": "payload", "command": command, "directory": directory, "files": listed}) + + +def denied_roots(settings_files: list[dict]) -> list[str] | None: + """Args: + settings_files: the settings files of the hub's sandbox view, each + with its permissions and sandbox sections. + + Returns: + Every absolute sandbox.filesystem.denyRead entry of them, None when + the view lists no file. + """ + if not settings_files: + return None + roots: list[str] = [] + for entry in settings_files: + sandbox = entry["settings"].get("sandbox") + filesystem = sandbox.get("filesystem") if isinstance(sandbox, dict) else None + listed = filesystem.get("denyRead") if isinstance(filesystem, dict) else None + roots += [path.rstrip("/") or "/" for path in listed or [] if isinstance(path, str) and path.startswith("/")] + return roots diff --git a/orchestrator/templates/index.html.j2 b/orchestrator/templates/index.html.j2 index 39abc2e..7062ca0 100644 --- a/orchestrator/templates/index.html.j2 +++ b/orchestrator/templates/index.html.j2 @@ -434,6 +434,8 @@ pre.notes { margin: 0; padding: 8px 10px; background: var(--sunken); border-radi {% include "style-home.css" %} {% include "style-firewall.css" %} + +{% include "style-match.css" %} @@ -585,6 +587,8 @@ pre.notes { margin: 0; padding: 8px 10px; background: var(--sunken); border-radi {% include "page-kanban.js" %} +{% include "page-match.js" %} + {% include "page-choices.js" %} {% include "page-time.js" %} diff --git a/orchestrator/templates/nav.js b/orchestrator/templates/nav.js index 325055f..7168bf3 100644 --- a/orchestrator/templates/nav.js +++ b/orchestrator/templates/nav.js @@ -2,7 +2,7 @@ const Nav = (() => { "use strict"; const TABS = [["home", "Home"], ["stream", "Stream"], ["agents", "Agents"], ["artifacts", "Artifacts"], ["tasks", "Tasks"], ["resources", "Resources"]]; const SUBS = {stream: [["rules", "Firewall"]]}; - const PANES = {inbox: ["tasks", "operator"]}; + const PANES = {inbox: ["tasks", "operator"], match: ["tasks", "match"]}; const VIEWS = [["orbit", "Orbit"], ["chord", "Chord"], ["swimlane", "Swimlane"], ["tree", "Tree"], ["3d", "3D"]]; const TASK_VIEWS = [["list", "List"], ["board", "Board"], ["rasci", "RASCI"], ["gantt", "Gantt"], ["burn", "Burndown and burnup"], ["3d", "3D"]]; const OWN = {agents: [["hierarchy", "Hierarchy"]]}; diff --git a/orchestrator/templates/page-match.js b/orchestrator/templates/page-match.js new file mode 100644 index 0000000..16a2cb1 --- /dev/null +++ b/orchestrator/templates/page-match.js @@ -0,0 +1,286 @@ + const MATCH_REFRESH = 2000; + const MATCH_PEEKS = 2; + const LONG_PRESS = 550; + const PRESS_SLOP = 10; + const MATCH_KINDS = {commit: ["Commit", "info", "bi-git"], command: ["Command", "warn", "bi-terminal"]}; + const matchView = {cards: null, order: [], marks: new Map(), opened: new Map(), dom: null, sig: "", fetched: 0, loading: false, press: null}; + + async function fetchMatch() { + if (matchView.loading) { + return; + } + matchView.loading = true; + matchView.fetched = Date.now(); + try { + const response = await fetch("/api/match", {cache: "no-store"}); + if (response.ok) { + const data = await response.json(); + matchView.cards = Array.isArray(data.cards) ? data.cards : []; + } + } catch { + matchView.cards = matchView.cards || []; + } finally { + matchView.loading = false; + } + drawMatch(); + } + + function matchOrder(cards) { + const ids = new Set(cards.map((card) => card.id)); + const kept = matchView.order.filter((id) => ids.has(id)); + const fresh = cards.filter((card) => !kept.includes(card.id)).sort((a, b) => Number(a.stale) - Number(b.stale) || (a.created_ts || 0) - (b.created_ts || 0)); + matchView.order = [...kept, ...fresh.map((card) => card.id)]; + const byId = new Map(cards.map((card) => [card.id, card])); + return matchView.order.map((id) => byId.get(id)); + } + + function ageWords(born) { + if (typeof born !== "number") { + return "age unknown"; + } + const days = Math.max(0, Math.floor((state.now - born) / DAY)); + return days === 1 ? "1 day" : `${days} days`; + } + + function marksOf(card) { + const key = `${card.id}@${card.hash}`; + if (!matchView.marks.has(key)) { + matchView.marks.set(key, []); + } + return matchView.marks.get(key); + } + + function contentRows(text) { + const lines = String(text).split("\n"); + if (lines.length && lines[lines.length - 1] === "") { + lines.pop(); + } + return lines.map((line, index) => h("tr", {class: "ctx", "data-line": index + 1}, h("td", {class: "num"}, index + 1), h("td", {class: "code"}, revealed(line)))); + } + + function markRow(mark, columns) { + 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)))); + } + + function fileRows(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 marks = marksOf(card).filter((mark) => mark.path === file.path); + return rows.flatMap((row) => { + const line = row.dataset.line; + const here = marks.filter((mark) => String(mark.line) === line); + if (here.length) { + row.classList.add("marked"); + } + return [row, ...here.map((mark) => markRow(mark, columns))]; + }); + } + + 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") { + 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"}), + file.note ? h("span", {class: "note", title: file.note}, icon("bi-eye-slash"), file.note) : null, marks, stat); + } + const tone = file.state === "read" ? "ok" : "bad"; + return h("summary", {class: "diff-head"}, h("span", {class: "letter", "data-tone": tone}, icon("bi-file-earmark-text")), h("code", {class: "path"}, revealed(file.path)), h("span", {class: "spacer"}), + file.state === "read" ? null : h("span", {class: "note", title: file.reason}, icon("bi-exclamation-triangle"), `refused: ${file.reason}`), marks, h("span", {class: "muted"}, `${file.size} B`)); + } + + function fileBlock(card, file, index) { + const opened = matchView.opened.has(card.id) ? matchView.opened.get(card.id).has(file.path) : index === 0; + const rows = fileRows(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); + block.addEventListener("toggle", () => remember(card, block)); + return h("li", {}, block); + } + + function remember(card, block) { + if (!matchView.opened.has(card.id)) { + matchView.opened.set(card.id, new Set()); + } + const open = matchView.opened.get(card.id); + if (block.open) { + open.add(block.dataset.path); + } else { + open.delete(block.dataset.path); + } + } + + function openOnScroll(body) { + const files = [...body.querySelectorAll(".match-file")]; + const view = body.getBoundingClientRect(); + for (let index = 0; index < files.length - 1; index += 1) { + const file = files[index]; + if (!file.open) { + return; + } + const next = files[index + 1]; + if (!next.open && file.getBoundingClientRect().bottom <= view.bottom + 8) { + next.open = true; + return; + } + } + } + + function closeComment(card) { + const open = card.querySelector(".match-comment"); + if (open) { + open.remove(); + } + } + + function commentField(card, data, row) { + const article = row.closest(".match-card"); + closeComment(article); + const file = row.closest(".match-file"); + const words = h("textarea", {class: "field", rows: 2, "aria-label": "Comment", placeholder: "Comment on this line"}); + const save = h("button", {type: "button", class: "btn small primary match-save", ...named("Save mark"), on: {click: () => { + if (!words.value.trim()) { + words.focus(); + return; + } + marksOf(data).push({path: file.dataset.path, line: Number(row.dataset.line), comment: words.value.trim()}); + drawMatch(true); + }}}, icon("bi-bookmark-fill"), "Save"); + const cancel = h("button", {type: "button", class: "btn small ghost", ...named("Cancel"), on: {click: () => closeComment(article)}}, "Cancel"); + const columns = row.children.length; + const field = h("tr", {class: "match-comment"}, h("td", {colspan: columns}, h("div", {class: "match-comment-box"}, h("code", {}, `${file.dataset.path}:${row.dataset.line}`), words, h("div", {class: "actions"}, cancel, save)))); + row.after(field); + words.focus(); + } + + function codeRow(event) { + const row = event.target instanceof Element ? event.target.closest(".match-file tr[data-line]") : null; + return row && !row.classList.contains("match-mark") ? row : null; + } + + function markable(article, data) { + article.addEventListener("contextmenu", (event) => { + const row = codeRow(event); + if (row) { + event.preventDefault(); + commentField(article, data, row); + } + }); + article.addEventListener("pointerdown", (event) => { + const row = codeRow(event); + if (!row || event.pointerType !== "touch") { + return; + } + const press = {x: event.clientX, y: event.clientY, timer: window.setTimeout(() => { + matchView.press = null; + commentField(article, data, row); + }, LONG_PRESS)}; + matchView.press = press; + }); + const drop = () => { + if (matchView.press) { + window.clearTimeout(matchView.press.timer); + matchView.press = null; + } + }; + article.addEventListener("pointermove", (event) => { + if (matchView.press && Math.hypot(event.clientX - matchView.press.x, event.clientY - matchView.press.y) > PRESS_SLOP) { + drop(); + } + }); + article.addEventListener("pointerup", drop); + article.addEventListener("pointercancel", drop); + } + + function matchHead(card) { + const [kindName, kindTone, kindIcon] = MATCH_KINDS[card.kind] || [card.kind, "neutral", "bi-collection"]; + return h("header", {class: "match-head"}, + h("div", {class: "match-who"}, face(card.agent || "-", true), h("strong", {class: "match-name"}, revealed(card.agent || "unknown agent")), h("span", {class: "match-age"}, ageWords(card.born))), + h("div", {class: "states"}, h("span", {class: "pill", "data-tone": kindTone}, icon(kindIcon), kindName), card.gate ? pill(`gate ${card.gate}`, card.gate === "pass" ? "ok" : "bad") : null, + card.score ? h("span", {class: "pill", "data-tone": "neutral"}, revealed(card.score)) : null, card.stale ? h("span", {class: "pill match-stale-pill", "data-tone": "bad"}, icon("bi-hourglass-split"), "stale") : null), + h("dl", {class: "meta match-place"}, [["Repository", card.repo], ["Branch", card.branch], ["Worktree", card.worktree]].map(([label, value]) => h("div", {}, h("dt", {}, label), h("dd", {}, h("code", {title: value ? revealed(value) : null}, revealed(dash(value))))))), + h("h2", {class: "match-title"}, revealed(card.title)), + card.stale ? h("p", {class: "match-stale"}, icon("bi-exclamation-triangle"), revealed(card.stale_reason)) : null); + } + + function matchCommand(card) { + if (card.kind !== "command") { + return 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); + } + + 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 body = h("div", {class: "match-body"}, matchCommand(card), list); + body.addEventListener("scroll", () => openOnScroll(body), {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); + markable(article, card); + window.setTimeout(() => openOnScroll(body), 0); + return article; + } + + function peekTab(card) { + const [kindName, kindTone] = MATCH_KINDS[card.kind] || [card.kind, "neutral"]; + return h("button", {type: "button", class: "match-peek", "data-card": card.id, "data-stale": String(Boolean(card.stale)), ...named(`Show ${kindName.toLowerCase()} card: ${card.title}`), on: {click: () => { + matchView.order = [card.id, ...matchView.order.filter((id) => id !== card.id)]; + drawMatch(true); + }}}, face(card.agent || "-", false), h("span", {class: "pill", "data-tone": kindTone}, kindName), card.stale ? h("span", {class: "pill", "data-tone": "bad"}, "stale") : null, h("span", {class: "match-peek-title"}, revealed(card.title))); + } + + function matchScreen() { + const stack = h("div", {class: "match-stack"}); + const count = h("span", {class: "muted"}); + matchView.dom = {stack, count}; + matchView.sig = ""; + 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"}), + iconBtn("bi-list-check", "Tasks", "btn small soft", () => go("tasks", null), "Tasks: back to the task list")); + fetchMatch(); + return h("div", {class: "graph tasks match"}, bar, stack); + } + + function drawMatch(force) { + const dom = matchView.dom; + if (!dom || !dom.stack.isConnected) { + return; + } + if (!matchView.loading && Date.now() - matchView.fetched > MATCH_REFRESH) { + fetchMatch(); + } + if (matchView.cards === null) { + dom.stack.replaceChildren(h("p", {class: "muted"}, "Loading cards โ€ฆ")); + return; + } + const cards = matchOrder(matchView.cards); + const sig = JSON.stringify([cards.map((card) => [card.id, card.hash, card.live_hash, card.stale, card.born, card.files ? card.files.length : null]), Math.floor(state.now / DAY)]); + if (!force && sig === matchView.sig) { + return; + } + matchView.sig = sig; + dom.count.textContent = cards.length === 1 ? "1 card waits" : `${cards.length} cards wait`; + if (!cards.length) { + dom.stack.replaceChildren(emptyState("No card waits", "No staged commit and no operator command waits for a decision.")); + return; + } + const [front, ...rest] = cards; + 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")}, icon("bi-check-lg")); + const reject = h("button", {type: "button", class: "btn match-reject", ...named("Reject")}, icon("bi-x-lg")); + 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"}); + sheet.style.setProperty("--depth", String(index + 1)); + return sheet; + }); + 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); + dom.stack.replaceChildren(peeks, h("div", {class: "match-deck"}, behind, shown), h("div", {class: "match-actions"}, reject, accept)); + shown.querySelector(".match-body").scrollTop = scrolled; + } diff --git a/orchestrator/templates/page-screens.js b/orchestrator/templates/page-screens.js index 621d4fc..8c1131e 100644 --- a/orchestrator/templates/page-screens.js +++ b/orchestrator/templates/page-screens.js @@ -55,7 +55,7 @@ } function screenOf() { - return {home: homeScreen, stream: streamScreen, inbox: tasksScreen, rules: rulesScreen, agents: agentsScreen, artifacts: artifactsScreen, tasks: tasksScreen, resources: resourcesScreen}[ui.screen](); + return {home: homeScreen, stream: streamScreen, inbox: tasksScreen, match: matchScreen, rules: rulesScreen, agents: agentsScreen, artifacts: artifactsScreen, tasks: tasksScreen, resources: resourcesScreen}[ui.screen](); } function render(force) { @@ -70,10 +70,11 @@ inboxDom = null; inboxSig = ""; taskView.dom = null; + matchView.dom = null; const main = document.getElementById("main"); main.setAttribute("aria-labelledby", `tab-${ui.screen}`); main.replaceChildren(screenOf()); - const fit = ["tasks", "inbox", "resources"].includes(ui.screen) || (["agents", "artifacts"].includes(ui.screen) && !["tree", "hierarchy"].includes(ui.views[ui.screen])); + const fit = ["tasks", "inbox", "match", "resources"].includes(ui.screen) || (["agents", "artifacts"].includes(ui.screen) && !["tree", "hierarchy"].includes(ui.views[ui.screen])); document.body.classList.toggle("fit", fit); document.body.classList.toggle("pane", !fit); drawn.screen = ui.screen; @@ -90,6 +91,7 @@ drawInbox(); drawRadio(); drawTasks(); + drawMatch(false); drawChoices(); drawStatus(); tick(); diff --git a/orchestrator/templates/style-match.css b/orchestrator/templates/style-match.css new file mode 100644 index 0000000..2b9b592 --- /dev/null +++ b/orchestrator/templates/style-match.css @@ -0,0 +1,47 @@ +.graph.tasks.match > .match-stack { flex: 1; } +.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-who { display: grid; justify-items: center; gap: 2px; } +.match-who .avatar.big { width: 72px; height: 72px; } +.match-name { font-size: var(--fs-lg); } +.match-age { color: var(--muted); font-size: var(--fs-sm); } +.match-place { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: var(--sp-2); width: 100%; margin: 0; text-align: left; } +.match-place code { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.match-title { margin: 0; font-size: var(--fs-md); overflow-wrap: anywhere; } +.match-stale { display: flex; align-items: center; gap: 6px; margin: 0; color: var(--bad); font-size: var(--fs-sm); } +.match-body { min-height: 0; overflow: auto; padding: var(--sp-2) var(--sp-3) var(--sp-3); overscroll-behavior: contain; } +.match-payload { display: grid; gap: 4px; margin-bottom: var(--sp-2); } +.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-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; } +.match-file > summary.diff-head::-webkit-details-marker { display: none; } +.match-file .diff-scroll { max-height: none; overflow: auto hidden; } +.match-file .diff-head .note { display: inline-flex; align-items: center; gap: 4px; color: var(--warn); font-size: var(--fs-xs); } +.match-marks { min-width: 20px; padding: 0 6px; border-radius: 999px; background: var(--accent); color: var(--on-accent); font-size: var(--fs-xs); text-align: center; } +.match-file tr.marked td.code { box-shadow: inset 3px 0 0 var(--accent); } +.match-file tr.match-mark td, .match-file tr.match-comment td { padding: 4px 10px; background: var(--info-soft); font-family: var(--sans); white-space: normal; } +.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 { opacity: 0.4; cursor: not-allowed; } +@media (max-width: 640px) { + .match-place { grid-template-columns: minmax(0, 1fr); } + .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); } +} diff --git a/skills/kvb-code-test/SKILL.md b/skills/kvb-code-test/SKILL.md index 3c1f89f..c0520bb 100644 --- a/skills/kvb-code-test/SKILL.md +++ b/skills/kvb-code-test/SKILL.md @@ -2,7 +2,7 @@ name: kvb-code-test description: > Run the Makefile test targets the operator picks and report; fix mode loops - until green. Trigger when asked to run or fix the tests. + until green. Trigger when asked to run or fix tests. --- The Makefile is the source of truth for how this project runs tests. Never diff --git a/skills/kvb-code-tune/SKILL.md b/skills/kvb-code-tune/SKILL.md index bc957eb..3308024 100644 --- a/skills/kvb-code-tune/SKILL.md +++ b/skills/kvb-code-tune/SKILL.md @@ -2,7 +2,7 @@ name: kvb-code-tune description: > Speed up CI, deploys, builds and hot paths without losing logic or - coverage. Trigger on a job over its time budget or where time goes. + coverage. Trigger on a job over budget or where time goes. --- One rule outranks every optimization: **nothing that reduces logic, coverage or diff --git a/skills/kvb-git-diff/SKILL.md b/skills/kvb-git-diff/SKILL.md index d48eb4d..f554c39 100644 --- a/skills/kvb-git-diff/SKILL.md +++ b/skills/kvb-git-diff/SKILL.md @@ -1,7 +1,7 @@ --- name: kvb-git-diff description: > - Approve staged commits in the Agent Orchestrator; the commit skills run it. + Approve staged commits in the Agent Orchestrator; commit skills run it. --- The commit skills run this where they ask for the commit approval. A hub diff --git a/skills/kvb-match/SKILL.md b/skills/kvb-match/SKILL.md new file mode 100644 index 0000000..14ef175 --- /dev/null +++ b/skills/kvb-match/SKILL.md @@ -0,0 +1,28 @@ +--- +name: kvb-match +description: > + Add finished stages as hub Match cards. +--- + +The operator decides every waiting commit and operator command as a card in +the hub's Match view under Tasks. The cards come from the hub's review queue +and the operator rows; this skill only adds to them and shows them. +`${CLAUDE_SKILL_DIR}/scripts/match.py` holds the steps. + +1. Once a stage is finished, add it in the worktree. `` is `pass` + when every gate the calling skill ran is green, else `fail`: + + ```bash + python3 ${CLAUDE_SKILL_DIR}/scripts/match.py add --repo "$PWD" --title "" --score "" --gate --agent "" + ``` + + It prints the review `id`. The card shows the patch and tree of that + moment; change the stage afterwards and the card turns `stale`, so add it + again. +2. An operator row's card shows the files its command names as they were + when it appeared. After changing one, take it again: + `match.py add --task `. +3. `match.py list` prints every card and marks a commit card whose staged + tree changed as stale in the hub; `match.py show ` prints its patch + or its command with the payload files. +4. Wait for the decision as `kvb-git-diff` does, from its step 3 on. diff --git a/skills/kvb-match/scripts/match.py b/skills/kvb-match/scripts/match.py new file mode 100755 index 0000000..7ee3383 --- /dev/null +++ b/skills/kvb-match/scripts/match.py @@ -0,0 +1,195 @@ +#!/usr/bin/env python3 +"""Args: + add --repo --title --score --gate + --agent [--pages ] [--rules ]: adds the staged + change of the worktree as a commit card: a review of the hub queue + whose page holds the patch git diff --cached prints and whose tree is + the one git write-tree prints; is the hub's pages folder, + /tmp/kvb-git-diff by default, and --rules the MEDUSA rules the + masked card diff is built with, as approval.py request takes them. + add --task : takes the payload files of an open operator + row again, so its stale card turns fresh. + list: prints one line per card; a commit card whose worktree's staged + tree changed is reported to the hub, which marks it stale. + show : prints a commit card's patch, or a command card's command, + directory, reason and payload files. + --port : the hub's port, 8737 by default. + --client : the hub's client folder, by default + ~/.local/share/kvb-orchestrator/client. + +Returns: + Exit code 0 with the result on stdout; 1 with the reason on stderr. +""" + +from __future__ import annotations + +import argparse +import html +import importlib +import json +import os +import re +import sys +import tempfile +import urllib.request +from pathlib import Path + +PORT = 8737 +CLIENT = Path.home() / ".local" / "share" / "kvb-orchestrator" / "client" +PAGES = Path("/tmp/kvb-git-diff") +PATCH = re.compile(r'
(.*)
', re.DOTALL) +REVIEW = re.compile(r"[0-9a-f]{16}") +UNSAFE = re.compile(r"[^A-Za-z0-9._-]+") + + +class Refused(Exception): + pass + + +def client_modules(folder: Path) -> dict: + sys.path.insert(0, str(folder)) + return {name: importlib.import_module(name) for name in ("hub_api", "staged_diff", "approval")} + + +def git_text(client: dict, cwd: Path, args: list[str]) -> str: + try: + return client["staged_diff"].git(cwd, args, None).decode("utf-8", "surrogateescape") + except client["staged_diff"].DiffError as error: + raise Refused(str(error)) from error + + +def hub(client: dict, port: int, path: str, body: dict | None) -> object: + api = client["hub_api"] + data = None if body is None else json.dumps(body).encode("utf-8") + headers = {**api.GUARD, **({} if body is None else {"Content-Type": "application/json"})} + try: + return api.load(urllib.request.Request(f"{api.base_url(port)}{path}", data=data, headers=headers, method="GET" if body is None else "POST"), api.SLACK) + except (OSError, ValueError) as error: + raise Refused(f"the Agent Orchestrator did not answer {path}: {error}") from error + + +def page_text(client: dict, port: int, review_id: str) -> str: + api = client["hub_api"] + request = urllib.request.Request(f"{api.base_url(port)}/reviews/{review_id}/page", headers=api.GUARD) + try: + with api.OPENER.open(request, timeout=api.SLACK) as response: + return response.read().decode("utf-8", "replace") + except OSError as error: + raise Refused(f"the review page did not load: {error}") from error + + +def cards(client: dict, port: int) -> list[dict]: + data = hub(client, port, "/api/match", None) + if not isinstance(data, dict) or not isinstance(data.get("cards"), list): + raise Refused("the Agent Orchestrator answered no cards") + return data["cards"] + + +def add_commit(args: argparse.Namespace, client: dict) -> str: + repo = args.repo.resolve() + tree = git_text(client, repo, ["write-tree"]).strip() + branch = git_text(client, repo, ["symbolic-ref", "--short", "HEAD"]).strip() + patch = git_text(client, repo, ["diff", "--cached", "--no-ext-diff", "--no-textconv", "--no-color"]) + if not patch.strip(): + raise Refused(f"nothing staged in {repo}") + shown = patch.encode("utf-8", "surrogateescape").decode("utf-8", "replace") + page = args.pages / f"match-{UNSAFE.sub('-', branch)}-{tree[:12]}.html" + page.write_text(f'{html.escape(args.title)}
{html.escape(shown)}
\n', encoding="utf-8") + with tempfile.NamedTemporaryFile("w", encoding="utf-8", suffix=".txt", delete=False) as notes: + notes.write(f"{args.score}\n") + try: + os.chdir(repo) + request = argparse.Namespace(port=args.port, title=args.title, page=page, notes=Path(notes.name), gate=args.gate, score=args.score, agent=args.agent, rules=args.rules) + return client["approval"].request_review(request) + except client["approval"].Refused as error: + raise Refused(str(error)) from error + finally: + os.unlink(notes.name) + + +def add_task(args: argparse.Namespace, client: dict) -> str: + return json.dumps(hub(client, args.port, "/api/match/snapshot", {"task": args.task})) + + +def checked(client: dict, port: int, card: dict) -> dict: + worktree = Path(card["worktree"]) + if card["kind"] != "commit" or card["stale"] or not worktree.is_dir(): + return card + try: + live = git_text(client, worktree, ["write-tree"]).strip() + except Refused: + return card + if live == card["hash"]: + return card + hub(client, port, "/api/match/stale", {"id": card["ref"], "tree": live}) + return {**card, "stale": True, "stale_reason": "the staged tree changed since it was added"} + + +def list_cards(args: argparse.Namespace, client: dict) -> str: + lines = [] + for card in (checked(client, args.port, card) for card in cards(client, args.port)): + where = card["branch"] or card["directory"] + lines.append("\t".join([card["id"], card["kind"], "stale" if card["stale"] else "fresh", card["agent"] or "-", where or "-", card["title"]])) + return "\n".join(lines) if lines else "no cards" + + +def card_id(text: str) -> str: + return f"review:{text}" if REVIEW.fullmatch(text) else text + + +def show_card(args: argparse.Namespace, client: dict) -> str: + wanted = card_id(args.card) + card = next((card for card in cards(client, args.port) if card["id"] == wanted), None) + if card is None: + raise Refused(f"no card {wanted}") + if card["kind"] == "commit": + found = PATCH.search(page_text(client, args.port, card["ref"])) + if found: + return html.unescape(found.group(1)) + return "".join(f"--- {entry['path']}\n{entry['patch']}\n" for entry in card["files"] or []) + lines = [f"$ {card['command']}", f" in {card['directory']}", f" reason: {card['reason']}"] + for entry in card["files"]: + lines.append(f"--- {entry['path']} ({entry['state']}{': ' + entry['reason'] if entry['reason'] else ''})") + lines.append(entry["content"].rstrip("\n")) + return "\n".join(lines) + "\n" + + +def parser() -> argparse.ArgumentParser: + found = argparse.ArgumentParser(prog="match") + commands = found.add_subparsers(dest="command", required=True) + adding = commands.add_parser("add") + target = adding.add_mutually_exclusive_group(required=True) + target.add_argument("--repo", type=Path) + target.add_argument("--task") + for name in ("--title", "--score", "--agent"): + adding.add_argument(name) + adding.add_argument("--gate", choices=("pass", "fail")) + adding.add_argument("--pages", type=Path, default=PAGES) + adding.add_argument("--rules", type=Path) + commands.add_parser("list") + showing = commands.add_parser("show") + showing.add_argument("card") + for sub in (adding, commands.choices["list"], showing): + sub.add_argument("--port", type=int, default=PORT) + sub.add_argument("--client", type=Path, default=CLIENT) + return found + + +def main() -> int: + args = parser().parse_args() + if args.command == "add" and args.repo and not all((args.title, args.score, args.agent, args.gate)): + print("refused: add --repo needs --title, --score, --gate and --agent", file=sys.stderr) + return 1 + try: + client = client_modules(args.client) + run = {"list": list_cards, "show": show_card}.get(args.command) or (add_commit if args.repo else add_task) + output = run(args, client) + except (Refused, OSError) as error: + print(f"refused: {error}", file=sys.stderr) + return 1 + sys.stdout.write(output if output.endswith("\n") or args.command == "show" else f"{output}\n") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/skills/kvb-org-perform/SKILL.md b/skills/kvb-org-perform/SKILL.md index 3ae8e67..e95b334 100644 --- a/skills/kvb-org-perform/SKILL.md +++ b/skills/kvb-org-perform/SKILL.md @@ -2,7 +2,7 @@ name: kvb-org-perform description: > Pick `model` and `effort` per subagent from a fixed table, cheaper only at - 90 % confidence of equal results. Apply AUTOMATICALLY before every Agent + 90% confidence of equal results. Apply AUTOMATICALLY before every Agent call. --- diff --git a/skills/kvb-think-criticize/SKILL.md b/skills/kvb-think-criticize/SKILL.md index 640a135..b5abdfe 100644 --- a/skills/kvb-think-criticize/SKILL.md +++ b/skills/kvb-think-criticize/SKILL.md @@ -3,8 +3,8 @@ name: kvb-think-criticize description: > Constructive criticism of a plan, design, decision, text or code, hardened by dialectic. Trigger on "kritisiere", - "konstruktive Kritik", "was haeltst du davon", or requests for honest - feedback. + "konstruktive Kritik", "was haeltst du davon", or honest feedback + requests. --- Critical but constructive: the goal is a better result, not a verdict on its diff --git a/skills/kvb-think-listen/SKILL.md b/skills/kvb-think-listen/SKILL.md index 8a5858f..95bc6de 100644 --- a/skills/kvb-think-listen/SKILL.md +++ b/skills/kvb-think-listen/SKILL.md @@ -1,7 +1,7 @@ --- name: kvb-think-listen description: > - Pin down every requirement by focused questions, then reflect the task + Pin down requirements by focused questions, then reflect the task back. Trigger on unclear scope, constraints or success criteria, or a skill needing an operator-only fact. --- diff --git a/tests/e2e/test_match_review_e2e.py b/tests/e2e/test_match_review_e2e.py new file mode 100644 index 0000000..14cc423 --- /dev/null +++ b/tests/e2e/test_match_review_e2e.py @@ -0,0 +1,215 @@ +from __future__ import annotations + +import json +import os +import shutil +import sys +import tempfile +import time +import unittest +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path[:0] = [str(HERE.parent), str(HERE)] + +import test_orchestrator_e2e as base +from hub_case import HubCase +from hub_support import iso + +OUT = Path(os.environ.get("E2E_OUT", "/tmp/hub-012-shots")) +FILES = (("src/app.py", 60), ("src/view.js", 30), ("docs/notes.md", 12)) +CARD = """ + const card = () => document.querySelector("#main .match-card.front"); + const body = () => card() && card().querySelector(".match-body"); + const opened = () => all(".match-file", card()).filter((file) => file.open).map((file) => file.dataset.path); + const pick = async (id) => { + const tab = await until(() => document.querySelector(`#main .match-peek[data-card="${id}"]`), 8000); + if (tab) { + tab.click(); + } + return until(() => card() && card().dataset.card === id && card(), 8000); + }; + const head = () => ({ + card: card().dataset.card, kind: card().dataset.kind, stale: card().dataset.stale, face: Boolean(card().querySelector(".match-who .avatar svg")), + name: text(card().querySelector(".match-name")), age: text(card().querySelector(".match-age")), + place: all(".match-place dt", card()).map(text).map((label, index) => [label, text(all(".match-place dd", card())[index])]), + files: all(".match-file", card()).map((file) => file.dataset.path), accept: card().closest(".match-stack").querySelector(".match-accept").disabled, + reason: text(card().querySelector(".match-stale")), peeks: all("#main .match-peek").map((tab) => tab.dataset.card), + wide: document.documentElement.scrollWidth > window.innerWidth + 1, + }); +""" +STACK = """(async () => {@HELPERS@@CARD@ + await screenShown(8000); + await until(card, 8000); + await sleep(400); + return head(); +})()""" +SCROLL = """(async () => {@HELPERS@@CARD@ + await until(card, 8000); + const steps = [opened()]; + for (let step = 0; step < 6; step += 1) { + body().scrollTop = body().scrollHeight; + body().dispatchEvent(new Event("scroll")); + await sleep(350); + steps.push(opened()); + } + const numbered = all(".match-file[open]", card()).map((file) => [file.dataset.path, all("tr[data-line] td.num", file).filter((cell) => text(cell)).length > 0]); + body().scrollTop = 0; + return {steps, numbered}; +})()""" +MARK = """(async () => {@HELPERS@@CARD@ + await until(card, 8000); + const row = (path, line) => card().querySelector(`.match-file[data-path="${path}"] tr[data-line="${line}"]`); + const save = async (words) => { + const field = await until(() => card().querySelector(".match-comment textarea"), 3000); + if (!field) { + return false; + } + field.value = words; + card().querySelector(".match-comment .match-save").click(); + await sleep(200); + return true; + }; + const first = row("@FIRST@", 3); + first.scrollIntoView({block: "center"}); + const box = first.getBoundingClientRect(); + first.dispatchEvent(new MouseEvent("contextmenu", {bubbles: true, cancelable: true, clientX: box.left + 40, clientY: box.top + 4, button: 2})); + const clicked = await save("use the helper here"); + const second = row("@FIRST@", 6); + second.dispatchEvent(new PointerEvent("pointerdown", {bubbles: true, cancelable: true, pointerId: 7, pointerType: "touch", isPrimary: true, clientX: box.left + 40, clientY: box.top + 4})); + await sleep(800); + second.dispatchEvent(new PointerEvent("pointerup", {bubbles: true, cancelable: true, pointerId: 7, pointerType: "touch", isPrimary: true})); + const pressed = await save("long press note"); + const marks = all("tr.match-mark", card()).map((mark) => [mark.dataset.line, text(mark.querySelector(".match-mark-text"))]); + const marked = all("tr.marked", card()).map((mark) => mark.dataset.line); + return {clicked, pressed, marks, marked, count: text(card().querySelector('.match-file[data-path="@FIRST@"] .match-marks'))}; +})()""" +PICK = """(async () => {@HELPERS@@CARD@ + const found = await pick("@ID@"); + if (!found) { + return {missing: "@ID@"}; + } + await sleep(400); + const command = card().querySelector(".match-command"); + const payload = all(".match-file", card()).map((file) => [file.dataset.path.split("/").pop(), file.dataset.state || "", all("tr[data-line]", file).length]); + return {...head(), command: command ? text(command.querySelector("code")) : null, where: text(card().querySelector(".match-directory")), why: text(card().querySelector(".match-reason")), payload}; +})()""" + + +def probe(template: str, **values: str) -> str: + found = template.replace("@HELPERS@", base.HELPERS).replace("@CARD@", CARD) + for name, value in values.items(): + found = found.replace(f"@{name}@", value) + return found + + +def patch(lines: int) -> str: + rows = [f"@@ -1,{lines} +1,{lines + 1} @@"] + [f" line {number}" for number in range(1, lines + 1)] + rows.insert(4, "+added line") + return "\n".join(rows) + + +@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium") +class TestMatchReview(HubCase): + drive = base.TestOrchestratorE2E.drive + + def setUp(self): + super().setUp() + work = tempfile.TemporaryDirectory() + self.addCleanup(work.cleanup) + self.work = Path(work.name) + now = time.time() + self.write_council({ + "work/s1/claim.json": {"office": "work/s1", "session": "s1", "runtime": "claude", "name": "Skills", "since": iso(now - 3 * 86400 - 60), "beat": now, "work": "match"}, + "work/s2/claim.json": {"office": "work/s2", "session": "s2", "runtime": "claude", "name": "Stage", "since": iso(now - 9 * 86400 - 60), "beat": now, "work": "i18n"}, + }) + diff = [{"path": path, "status": "M", "mode": "100644", "additions": 1, "deletions": 0, "patch": patch(lines), "note": ""} for path, lines in FILES] + self.commit = self.review("feat: match review", "/repo/.worktrees/feature/match", "feature/match", "Skills", diff) + stale_diff = [{"path": "README.md", "status": "M", "mode": "100644", "additions": 1, "deletions": 0, "patch": patch(8), "note": ""}] + self.stale = self.review("docs: stale stage", "/repo/.worktrees/feature/old", "feature/old", "Stage", stale_diff) + status, _, body = self.post_json("/api/match/stale", {"id": self.stale, "tree": "f" * 40}, self.local()) + self.assertEqual(status, 200, body) + self.payload() + self.base = f"http://{self.host}/" + + def review(self, title: str, worktree: str, branch: str, agent: str, diff: list[dict]) -> str: + arguments = {**self.arguments(title, "", self.page(f"{branch.replace('/', '-')}.html", "p")), "worktree": worktree, "branch": branch, "agent": agent, "diff": diff} + result = self.tool("review_request", arguments) + self.assertFalse(result["isError"], result) + return result["structuredContent"]["id"] + + def payload(self) -> None: + body = self.work / "body.md" + body.write_text("".join(f"Release note line {number}\n" for number in range(1, 15)), encoding="utf-8") + (self.work / "link.md").symlink_to(body) + folder = self.state / "firewall" + folder.mkdir(parents=True, exist_ok=True) + files = [{"path": "/home/op/.claude/settings.json", "exists": True, "sha256": "", "settings": {"sandbox": {"filesystem": {"denyRead": []}}}}] + (folder / "view.json").write_text(json.dumps({"written": "2026-11-14T12:00:00+00:00", "files": files}), encoding="utf-8") + self.command = f"gh issue create --body-file {body} --list link.md" + self.write_council({"rasci.json": {"operator/issue": {"title": self.command, "workdir": str(self.work), "description": "file the release issue", "check": "done", "roles": {"Skills": "A", "Operator": "R"}}}}) + + def steps(self, browser: str, widths: tuple[tuple[int, int], ...]) -> list[dict]: + OUT.mkdir(parents=True, exist_ok=True) + steps = [] + for width, height in widths: + shot = str(OUT / f"{browser}-{width}") + steps += [ + {"width": width, "height": height, "url": f"{self.base}?{width}#tasks/match", "wait": 1500, "probe": probe(STACK), "shot": f"{shot}-stack.png"}, + {"width": width, "height": height, "url": None, "wait": 0, "probe": probe(SCROLL), "shot": None}, + {"width": width, "height": height, "url": None, "wait": 0, "probe": probe(MARK, FIRST=FILES[0][0]), "shot": f"{shot}-marked.png"}, + {"width": width, "height": height, "url": None, "wait": 0, "probe": probe(PICK, ID="operator:operator/issue"), "shot": f"{shot}-command.png"}, + {"width": width, "height": height, "url": None, "wait": 0, "probe": probe(PICK, ID=f"review:{self.stale}"), "shot": f"{shot}-stale.png"}, + ] + return steps + + def check(self, data: dict, widths: tuple[tuple[int, int], ...]) -> None: + results = iter(data["results"]) + order = [path for path, _ in FILES] + for width, _ in widths: + with self.subTest(width=width): + stack = next(results) + self.assertEqual((stack["card"], stack["kind"], stack["stale"], stack["face"]), (f"review:{self.commit}", "commit", "false", True), stack) + self.assertEqual((stack["name"], stack["age"]), ("Skills", "3 days"), stack) + self.assertEqual(stack["place"], [["Repository", "/repo"], ["Branch", "feature/match"], ["Worktree", "/repo/.worktrees/feature/match"]], stack) + self.assertEqual(stack["files"], order) + self.assertEqual(stack["peeks"], ["operator:operator/issue", f"review:{self.stale}"], stack) + self.assertFalse(stack["accept"], stack) + self.assertFalse(stack["wide"], stack) + scroll = next(results) + self.assertEqual(scroll["steps"][0], order[:1], scroll) + self.assertEqual(scroll["steps"][-1], order, scroll) + for step in scroll["steps"]: + self.assertEqual(step, order[: len(step)], scroll) + self.assertGreater(len({len(step) for step in scroll["steps"]}), 2, scroll) + self.assertEqual(scroll["numbered"], [[path, True] for path in order], scroll) + mark = next(results) + self.assertEqual((mark["clicked"], mark["pressed"]), (True, True), mark) + self.assertEqual(mark["marks"], [["3", "use the helper here"], ["6", "long press note"]], mark) + self.assertEqual(mark["marked"], ["3", "6"], mark) + self.assertEqual(mark["count"], "2", mark) + command = next(results) + self.assertEqual((command["kind"], command["stale"], command["command"], command["why"]), ("command", "false", self.command, "file the release issue"), command) + self.assertEqual(command["where"], str(self.work), command) + self.assertEqual(command["payload"], [["body.md", "read", 14], ["link.md", "refused", 0]], command) + self.assertEqual((command["name"], command["age"]), ("Skills", "3 days"), command) + stale = next(results) + self.assertEqual((stale["kind"], stale["stale"], stale["accept"], stale["name"], stale["age"]), ("commit", "true", True, "Stage", "9 days"), stale) + self.assertIn("changed", stale["reason"]) + + def test_chromium_shows_face_place_files_on_scroll_and_marks_at_three_widths(self): + data = self.drive(self.steps("chromium", base.WIDTHS), None) + (OUT / "chromium-match.json").write_text(json.dumps(data, indent=1), encoding="utf-8") + self.assertEqual(data["errors"], []) + self.check(data, base.WIDTHS) + + @unittest.skipUnless(shutil.which(os.environ.get("FIREFOX", "firefox")), "no Firefox") + def test_firefox_shows_face_place_files_on_scroll_and_marks_at_three_widths(self): + data = self.drive(self.steps("firefox", base.WIDTHS), None, "bidi.mjs", os.environ.get("FIREFOX", "firefox")) + (OUT / "firefox-match.json").write_text(json.dumps(data, indent=1), encoding="utf-8") + self.assertEqual([error for error in data["errors"] if "/favicon.ico" not in error], []) + self.check(data, base.WIDTHS) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_hub_match.py b/tests/test_hub_match.py new file mode 100644 index 0000000..626a41c --- /dev/null +++ b/tests/test_hub_match.py @@ -0,0 +1,208 @@ +from __future__ import annotations + +import json +import os +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + +from hub_case import HubCase +from hub_support import GIT_ENV, HUB, REPO_ROOT +from kvb_orchestrator import payloads + +MATCH = REPO_ROOT / "skills" / "kvb-match" / "scripts" / "match.py" +CLIENT = HUB / "client" + + +def git(cwd: Path, *args: str) -> str: + done = subprocess.run(["git", *args], cwd=cwd, env={**os.environ, **GIT_ENV}, check=True, capture_output=True, text=True) + return done.stdout + + +def staged_repo(root: Path) -> Path: + repo = root / "demo" + repo.mkdir() + git(repo, "init", "-q", "-b", "feature/match") + (repo / "app.py").write_text("keep = 1\nold = 2\n", encoding="utf-8") + git(repo, "add", "-A") + git(repo, "commit", "-q", "-m", "base") + (repo / "app.py").write_text("keep = 1\nnew = 3\nmore = 4\n", encoding="utf-8") + (repo / "notes.md").write_text("# Notes\n\nfresh\n", encoding="utf-8") + git(repo, "add", "-A") + return repo + + +class MatchCase(HubCase): + def setUp(self): + super().setUp() + work = tempfile.TemporaryDirectory() + self.addCleanup(work.cleanup) + self.work = Path(work.name) + self.sandbox_view([]) + + def sandbox_view(self, denied: list[str]) -> None: + folder = self.state / "firewall" + folder.mkdir(parents=True, exist_ok=True) + settings = {"sandbox": {"filesystem": {"denyRead": denied}}} + files = [{"path": "/home/op/.claude/settings.json", "exists": True, "sha256": "", "settings": settings}] + (folder / "view.json").write_text(json.dumps({"written": "2026-11-14T12:00:00+00:00", "files": files}), encoding="utf-8") + + def match(self, cwd: Path, *args: str) -> subprocess.CompletedProcess: + command = [sys.executable, str(MATCH), *args, "--port", str(self.port), "--client", str(CLIENT)] + return subprocess.run(command, cwd=cwd, env={**os.environ, **GIT_ENV}, capture_output=True, text=True, timeout=60, check=False) + + def add(self, repo: Path) -> str: + done = self.match(repo, "add", "--repo", str(repo), "--title", "feat: match", "--score", "๐ŸŽฏ 95 ๐Ÿ’ฅ 3", "--gate", "pass", "--agent", "Skills", "--pages", str(self.pages)) + self.assertEqual(done.returncode, 0, done.stderr) + return json.loads(done.stdout)["id"] + + def cards(self) -> list[dict]: + status, _, body = self.get("/api/match") + self.assertEqual(status, 200, body) + return json.loads(body)["cards"] + + def card(self, card_id: str) -> dict: + return next(card for card in self.cards() if card["id"] == card_id) + + def operator_row(self, task: str, command: str, directory: str) -> None: + register = {task: {"title": command, "workdir": directory, "description": "ship the release notes", "check": "done", "roles": {"Skills": "A", "Operator": "R"}}} + self.write_council({"rasci.json": register}) + + +class TestMatchSkill(MatchCase): + def test_add_takes_the_staged_patch_and_tree_and_list_and_show_print_them(self): + repo = staged_repo(self.work) + review = self.add(repo) + card = self.card(f"review:{review}") + self.assertEqual((card["kind"], card["hash"], card["stale"]), ("commit", git(repo, "write-tree").strip(), False)) + self.assertEqual((card["branch"], card["worktree"], card["agent"], card["title"]), ("feature/match", str(repo), "Skills", "feat: match")) + self.assertEqual([entry["path"] for entry in card["files"]], ["app.py", "notes.md"]) + shown = self.match(repo, "show", f"review:{review}") + self.assertEqual(shown.returncode, 0, shown.stderr) + self.assertEqual(shown.stdout, git(repo, "diff", "--cached")) + listed = self.match(repo, "list") + self.assertEqual(listed.returncode, 0, listed.stderr) + self.assertIn(f"review:{review}", listed.stdout) + self.assertIn("feat: match", listed.stdout) + + def test_add_refuses_an_empty_stage(self): + repo = staged_repo(self.work) + git(repo, "commit", "-q", "-m", "all") + done = self.match(repo, "add", "--repo", str(repo), "--title", "feat: none", "--score", "๐ŸŽฏ 1", "--gate", "pass", "--agent", "Skills", "--pages", str(self.pages)) + self.assertEqual(done.returncode, 1) + self.assertIn("nothing staged", done.stderr) + self.assertEqual(self.cards(), []) + + def test_a_changed_stage_turns_the_card_stale_and_adding_it_again_gives_a_fresh_card(self): + repo = staged_repo(self.work) + first = self.add(repo) + (repo / "notes.md").write_text("# Notes\n\nchanged\n", encoding="utf-8") + git(repo, "add", "-A") + listed = self.match(repo, "list") + self.assertEqual(listed.returncode, 0, listed.stderr) + self.assertIn("stale", listed.stdout) + old = self.card(f"review:{first}") + self.assertTrue(old["stale"], old) + self.assertIn("changed", old["stale_reason"]) + second = self.add(repo) + fresh = self.card(f"review:{second}") + self.assertEqual((fresh["stale"], fresh["hash"]), (False, git(repo, "write-tree").strip())) + self.assertTrue(self.card(f"review:{first}")["stale"]) + + def test_a_stale_report_needs_the_local_guard_and_a_tree(self): + repo = staged_repo(self.work) + review = self.add(repo) + status, _, _ = self.post_json("/api/match/stale", {"id": review, "tree": "f" * 40}, {"Host": self.host}) + self.assertEqual(status, 403) + status, _, _ = self.post_json("/api/match/stale", {"id": review, "tree": "nope"}, self.local()) + self.assertEqual(status, 400) + self.assertFalse(self.card(f"review:{review}")["stale"]) + + def test_a_gone_review_or_operator_row_leaves_the_cards(self): + repo = staged_repo(self.work) + review = self.add(repo) + self.operator_row("operator/ship", "make ship", str(self.work)) + self.assertEqual(sorted(card["id"] for card in self.cards()), sorted([f"review:{review}", "operator:operator/ship"])) + status, _, body = self.post_json(f"/reviews/{review}/reject", {}, self.guard(self.host)) + self.assertEqual(status, 200, body) + self.write_council({"rasci.json": {}}) + self.assertEqual(self.cards(), []) + + +class TestCommandCards(MatchCase): + def payload_command(self) -> str: + body = self.work / "body.md" + body.write_text("# Release\n\nline two\n", encoding="utf-8") + (self.work / "link.md").symlink_to(body) + (self.work / "big.txt").write_text("x" * (payloads.PAYLOAD_LIMIT + 1), encoding="utf-8") + (self.work / "secret.txt").write_text("hidden\n", encoding="utf-8") + return f"gh issue create --body-file {body} --list link.md --big=big.txt --key {self.work / 'secret.txt'} --base origin/main" + + def test_an_operator_row_is_a_card_with_command_directory_reason_and_payload_files(self): + self.sandbox_view([str(self.work / "secret.txt")]) + command = self.payload_command() + self.operator_row("operator/ship", command, str(self.work)) + card = self.card("operator:operator/ship") + self.assertEqual((card["kind"], card["command"], card["directory"], card["reason"], card["agent"], card["stale"]), ("command", command, str(self.work), "ship the release notes", "Skills", False)) + files = {Path(entry["path"]).name: entry for entry in card["files"]} + self.assertEqual(sorted(files), ["big.txt", "body.md", "link.md", "secret.txt"]) + self.assertEqual((files["body.md"]["state"], files["body.md"]["content"]), ("read", "# Release\n\nline two\n")) + for name, words in (("link.md", "symlink"), ("big.txt", "bytes"), ("secret.txt", "sandbox")): + with self.subTest(name=name): + self.assertEqual((files[name]["state"], files[name]["content"]), ("refused", "")) + self.assertIn(words, files[name]["reason"]) + + def test_without_a_sandbox_view_every_payload_file_is_refused(self): + (self.state / "firewall" / "view.json").unlink() + command = self.payload_command() + self.operator_row("operator/ship", command, str(self.work)) + states = {entry["state"] for entry in self.card("operator:operator/ship")["files"]} + self.assertEqual(states, {"refused"}) + + def test_a_changed_payload_file_turns_the_card_stale_until_it_is_added_again(self): + command = self.payload_command() + self.operator_row("operator/ship", command, str(self.work)) + before = self.card("operator:operator/ship") + (self.work / "body.md").write_text("# Release\n\nswapped\n", encoding="utf-8") + after = self.card("operator:operator/ship") + self.assertTrue(after["stale"], after) + self.assertEqual(after["files"], before["files"]) + self.assertNotEqual(after["live_hash"], after["hash"]) + done = self.match(self.work, "add", "--task", "operator/ship") + self.assertEqual(done.returncode, 0, done.stderr) + fresh = self.card("operator:operator/ship") + self.assertFalse(fresh["stale"], fresh) + self.assertIn("swapped", next(entry["content"] for entry in fresh["files"] if entry["path"].endswith("body.md"))) + + def test_decision_rows_and_rows_at_the_runner_are_no_cards(self): + self.write_council({"rasci.json": {"operator/pick": {"title": "-", "workdir": str(self.work), "check": "decision", "roles": {"Operator": "R"}}}}) + self.assertEqual(self.cards(), []) + + def test_show_prints_the_command_and_its_payload(self): + command = self.payload_command() + self.operator_row("operator/ship", command, str(self.work)) + shown = self.match(self.work, "show", "operator:operator/ship") + self.assertEqual(shown.returncode, 0, shown.stderr) + for words in (command, f"in {self.work}", "line two", "refused"): + with self.subTest(words=words): + self.assertIn(words, shown.stdout) + + +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"}] + base = payloads.payload_hash("make ship", "/repo", files) + self.assertEqual(base, payloads.payload_hash("make ship", "/repo", [dict(files[0])])) + self.assertRegex(base, "^[0-9a-f]{64}$") + for changed in (payloads.payload_hash("make ship ", "/repo", files), payloads.payload_hash("make ship", "/other", files), payloads.payload_hash("make ship", "/repo", [{**files[0], "sha256": "2" * 64}]), payloads.payload_hash("make ship", "/repo", [{**files[0], "state": "refused"}])): + self.assertNotEqual(changed, base) + + def test_named_paths_come_from_words_and_option_values_resolved_in_the_directory(self): + named = payloads.named_paths("gh issue create --body-file /tmp/x/body.md --list=list.txt scripts/run.sh 'quoted file.md' https://example.org/a.md", "/repo") + self.assertEqual(named, ["/tmp/x/body.md", "/repo/list.txt", "/repo/scripts/run.sh", "/repo/quoted file.md"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_naming.py b/tests/test_naming.py index e8734cd..794a112 100644 --- a/tests/test_naming.py +++ b/tests/test_naming.py @@ -16,6 +16,7 @@ UNCATEGORIZED = frozenset( "kvb-coach", "kvb-dream", "kvb-help", + "kvb-match", "kvb-optimize", "kvb-release", "kvb-transcend",