Merge branch 'feature/hub-match-review' into unify/skills-20261114
# Conflicts: # docs/requirements/README.md
This commit is contained in:
commit
7241e53a98
23 files changed
+1407
-15
No files matched your search
@@ -26,7 +26,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),
|
||||
@@ -128,6 +130,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":
|
||||
@@ -265,9 +269,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):
|
||||
|
||||
@@ -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
|
||||
@@ -83,7 +84,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
|
||||
@@ -130,6 +131,7 @@ class Hub(Mcp, Reviewing, Asking, Messaging, Choosing, Approving, Denying, Reque
|
||||
history: History
|
||||
queue_order: QueueOrder
|
||||
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}"
|
||||
@@ -176,6 +178,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"),
|
||||
|
||||
@@ -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"]}
|
||||
@@ -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
|
||||
@@ -437,6 +437,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" %}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
@@ -593,6 +595,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" %}
|
||||
|
||||
@@ -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"]]};
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -61,7 +61,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) {
|
||||
@@ -76,10 +76,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;
|
||||
@@ -96,6 +97,7 @@
|
||||
drawInbox();
|
||||
drawRadio();
|
||||
drawTasks();
|
||||
drawMatch(false);
|
||||
drawChoices();
|
||||
drawStatus();
|
||||
tick();
|
||||
|
||||
@@ -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); }
|
||||
}
|
||||
Reference in new issue
Block a user