feat: hub and skills requirements 032 to 063

Hub: send in the field (032), coherent speak box (033), stream head band (034), Match at full width with its pile (035, 036), Home without the outer box (037), badge to Match (038), rejects that survive a changed or withdrawn card (039), the release card (040), code marks in the review diff (041), why Deny is off (042), the undo window clock (043), widgets without inner boxes (044), the Artifacts head on one line (045), accepting a red gate's risk (046), one code box (047), done rows greyed and folded (048), one control height (049), menus that stay open (050), radio settings in the Device card (051), bubbles beside the modes (052), agent settings on every face and name (053), pin only by menu (054), WASD in Match (055), the flowing card edge (056), Schedules in Controls (057) and the hub poll cost (059).

Skills: the coach leaves for its own repository kevinveenbirkenbach/coach (058; test_install pins its four skills in skills-lock.json and stays red until that repository is published and pinned), hooks and timers start fewer processes (060), council files on hot paths stay bounded and mirror by marker instead of mtime (061), scripts and hooks hand agents less output (062), and block.py builds the commit table and message block in one run (063). Requirement documents 032 to 063 with their implementation amendments.

MEDUSA false positives accepted after kvb-think-criticize (36 lines): MM-SCAN-058 (pla inside replace or plan), JB-SCAN-616/641 (the local clip helper), CODEGEN-SCAN-001 (drop-in paths), CGS-SCAN-029 (systemctl argv from constants), CGS-SCAN-040 (runner poll loop), FLA-SCAN-055 (feedback), WM-SCAN-354, AI-BACKDOOR-006, GENAI-SCAN-1270, B604 (runner shell path for passkey-verified commands), TC004, EXA002, EXA006, EXA010 and WEB-SSRF.

🎯 Fix: 92 %
💥 Break: 8 %
💸 Tokens: 89 %
⏱️ Velocity: –
🛡️ Security: ~100 %
🏆 Score: 95
🚦 Gate: ⛔ break 8 % > 5

Created-with: https://s.veen.world/skills
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Kevin Veen-BirkenbachandClaude Opus 5.5 committed 2026-11-26 08:44:15 +00:00
1 parent e5fd70e183
commit 0fad1bfae3
265 files changed
+10400 -2208

No files matched your search

+3 -21
View File
@@ -9,7 +9,7 @@ Compatible with Claude Code, Codex, Gemini CLI, Cursor, Copilot, Windsurf, Cline
## Naming 🏷️
Every first-party skill is named `kvb-<category>-<name>` 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.
Every first-party skill is named `kvb-<category>-<name>` with one of these categories: `think`, `create`, `code`, `ci`, `git`, `release`, `check`, `org`, `agent`, `skill`: `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. The coach skills (`kvb-coach`, `kvb-coach-on`, `kvb-coach-off`, `kvb-coach-meditation`) live in their own repository, [coach](https://github.com/kevinveenbirkenbach/coach), which `skills-lock.json` pins and `make install` installs. Only `kvb-cleanup`, `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 🏛️
@@ -28,7 +28,6 @@ flowchart LR
kvb --> org[org]
kvb --> agent[agent]
kvb --> skill[skill]
kvb --> coach[coach]
kvb --> none[no category]
think --> think_listen[kvb-think-listen]
think --> think_explain[kvb-think-explain]
@@ -74,7 +73,6 @@ flowchart LR
check --> check_break_risk[kvb-check-break-risk]
check --> check_gate[kvb-check-gate]
check --> check_efficiency[kvb-check-efficiency]
check --> check_speed[kvb-check-speed]
check --> check_ansible[kvb-check-ansible]
check --> check_score[kvb-check-score]
org --> org_organize[kvb-org-organize]
@@ -115,9 +113,7 @@ flowchart LR
none --> dream_all[kvb-dream]
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]
```
## Skill map 🗺️
@@ -130,9 +126,8 @@ flowchart LR
commit_req([commit request])
stage_req([staging or fix ready])
edit_hook([edit in a git worktree])
reminders([12 h agent hint, 17:00 GNOME popup])
reminders([agent hint and GNOME popup, off until switched on in Schedules])
noon_midnight([00:00 and 12:00 timer])
full_hour([full hour])
code_task([code task])
spawn([subagent spawn])
end
@@ -194,7 +189,6 @@ flowchart LR
break_risk[kvb-check-break-risk]
gate[kvb-check-gate]
efficiency[kvb-check-efficiency]
speed[kvb-check-speed]
check_ansible[kvb-check-ansible]
score[kvb-check-score]
end
@@ -242,12 +236,8 @@ flowchart LR
dream[kvb-dream]
optimize[kvb-optimize]
release_all[kvb-release]
coach[kvb-coach]
match[kvb-match]
end
subgraph cat_coach [coach]
meditation[kvb-coach-meditation]
end
commit_req -.-> commit_next
commit_req -.-> commit_no_verify
@@ -255,7 +245,6 @@ flowchart LR
edit_hook -. council gate .-> democracy
reminders -.-> dream
noon_midnight -.-> queue_cleanup
full_hour -.-> coach
code_task -.-> clean
code_task -.-> scope_guard
spawn -.-> subagent_model
@@ -289,8 +278,6 @@ flowchart LR
score --> confidence
score --> break_risk
score --> efficiency
score --> speed
speed --> efficiency
efficiency -. heavy commands .-> queue
gate --> democracy
gate --> hotfix
@@ -398,11 +385,6 @@ flowchart LR
org_suspend -. hold and accept .-> operator
org_resume -. hold and accept .-> operator
agent_suspend -. stops .-> robot
coach --> active_listening
coach --> operator
coach --> rasci
coach --> meditation
meditation --> active_listening
autoskill --> autotune
autotune --> essence
transcend --> skill_transcend
@@ -470,7 +452,7 @@ Copy the skills into a specific project (`<repo>/.agents/skills` and `<repo>/.cl
make project TARGET=/path/to/repo
```
Both commands also patch the target's `.claude/settings.local.json` — the machine-local, untracked file, so a project's reviewed `.claude/settings.json` is never rewritten by an install: the caveman and ponytail plugins are enabled so their modes auto-activate on session start, and two reminder hooks are registered — `kvb-dream` points each agent at `/kvb-dream` at most once every twelve hours (stamped per session in `~/.claude/.dream-stamps/`), and `kvb-coach` runs its short form at the first prompt of every full hour, once across all agents (stamped in `~/.claude/.coach-hours/`); the global install also enables the `kvb-dream-notify.timer` systemd user timer, which recommends `/kvb-dream` in a GNOME notification daily at 17:00 local time and catches up once after a missed run, and the `kvb-org-queue-cleanup.timer` and `kvb-org-queue-cleanup.path` user units, which start a `kvb-org-queue-cleanup` round at 00:00 and 12:00 local time without catch-up and whenever an agent runs `cleanup.py request`. A PreToolUse gate from the `kvb-org-organize` skill blocks edits to files in a git worktree until the session holds a claim (`skills/kvb-org-organize/scripts/council.py`), and its resource watch (`skills/kvb-org-organize/scripts/watch.py`) measures disk, Docker and caches, cleans up low-risk data and blocks new heavy jobs before the disk runs out; it stays inactive until `~/.claude/agents-council/config.json` exists, and because its hooks run that config's commands outside the sandbox, the install adds `Edit(~/.claude/agents-council/**)` to `permissions.deny`, which also covers Write in every permission mode; `Edit(~/.local/state/agents-council/**)` joins it, so the state the skills' scripts keep there changes only through those scripts. The global install writes both rules into `~/.claude/settings.json` too (`scripts/council-deny.js`), the only user-wide settings file, so they bind sessions in every repository. The `kvb-org-radio` skill registers five hooks: its prompt hook and a PostToolBatch hook deliver the immediate radio (`call`, `broadcast`, `security`, `pan-pan`, `mayday`) mid-turn, a Stop hook delivers the post (`post`, `newsletter` and call receipts) when the turn ends, an `asyncRewake` Stop hook wakes an idle session for the radio, and a PreToolUse hook refuses every writing action while a mayday holds, except those of its sender and of the agents that join it with `radio.py assist`. The PreToolUse hook of the `kvb-org-queue` skill sends heavy commands through `queue.py hold` once the config sets `queue_enforce`, and holds a held command to the settings' Bash deny and ask rules, which see only `queue.py hold`. The global install also installs the MEDUSA security scanner with pipx for `kvb-check-security`, unless `medusa` is already on the PATH. It clones microsoft/TokenEconomizer at the commit pinned in `plugins-lock.json` to `~/Repositories/github.com/microsoft/TokenEconomizer` and installs it for Claude Code and, when `codex` is on the PATH, for Codex, which runs its hooks once they are approved with `/hooks`; tool pruning only proposes deny lists and never drops `AskUserQuestion`, `Artifact`, `Skill`, `Agent`, `ToolSearch` or the hub and code graph MCP tools, micro-skills learn only from repeated failures, and the loop guard stays on (requirement 021). Two hooks of the `kvb-org-perform` skill (`skills/kvb-org-perform/scripts/log.py`) log every Agent spawn with its task class, model and effort, and store the quality feedback a sandboxed session prints, in `~/.local/state/agents-council/subagent-model.jsonl`. Every hook runs `/usr/bin/python3 -I`, so neither the `python3` of a sandbox-writable virtualenv on the `PATH` nor `PYTHONPATH` reaches the hooks, which run outside the sandbox; older bare `python3` hook entries are rewritten. The reminder hooks run `/usr/bin/bash` and pin `PATH=/usr/bin:/bin`, and the council scripts keep only the `PATH` directories this uid cannot write (`skills/kvb-org-organize/scripts/hookpath.py`), so no binary an agent plants on the inherited `PATH` runs outside the sandbox. Existing settings are preserved.
Both commands also patch the target's `.claude/settings.local.json` — the machine-local, untracked file, so a project's reviewed `.claude/settings.json` is never rewritten by an install: the caveman and ponytail plugins are enabled so their modes auto-activate on session start, and two reminder hooks are registered, both silent until switched on in the hub's Controls › Schedules tab (`<council>/schedules.json`) — `kvb-dream` points each agent at `/kvb-dream` once every N hours (default 12, stamped per session in `~/.claude/.dream-stamps/`), and `kvb-coach` from the coach repository runs its short form at the first prompt every N hours (default 1), once across all agents (stamped in `~/.claude/.coach-hours/`); the global install also copies the `kvb-dream-notify.timer` systemd user timer, which recommends `/kvb-dream` in a GNOME notification daily at the set times (default 17:00, off) and catches up once after a missed run, enables the `kvb-org-queue-cleanup.timer` and `kvb-org-queue-cleanup.path` user units, which start a `kvb-org-queue-cleanup` round at 00:00 and 12:00 local time without catch-up and whenever an agent runs `cleanup.py request`, and enables `kvb-schedules.path` and `kvb-schedules.timer`, which run `skills/kvb-org-organize/scripts/schedules.py run` on every change of `schedules.json` and every 5 minutes: it switches and retimes the first-party units to their rows and lists every other user timer and hook for the hub. A PreToolUse gate from the `kvb-org-organize` skill blocks edits to files in a git worktree until the session holds a claim (`skills/kvb-org-organize/scripts/council.py`), and its resource watch (`skills/kvb-org-organize/scripts/watch.py`) measures disk, Docker and caches, cleans up low-risk data and blocks new heavy jobs before the disk runs out; it stays inactive until `~/.claude/agents-council/config.json` exists, and because its hooks run that config's commands outside the sandbox, the install adds `Edit(~/.claude/agents-council/**)` to `permissions.deny`, which also covers Write in every permission mode; `Edit(~/.local/state/agents-council/**)` joins it, so the state the skills' scripts keep there changes only through those scripts. The global install writes both rules into `~/.claude/settings.json` too (`scripts/council-deny.js`), the only user-wide settings file, so they bind sessions in every repository. The `kvb-org-radio` skill registers five hooks: its prompt hook and a PostToolBatch hook deliver the immediate radio (`call`, `broadcast`, `security`, `pan-pan`, `mayday`) mid-turn, a Stop hook delivers the post (`post`, `newsletter` and call receipts) when the turn ends, an `asyncRewake` Stop hook wakes an idle session for the radio, and a PreToolUse hook refuses every writing action while a mayday holds, except those of its sender and of the agents that join it with `radio.py assist`. The PreToolUse hook of the `kvb-org-queue` skill sends heavy commands through `queue.py hold` once the config sets `queue_enforce`, and holds a held command to the settings' Bash deny and ask rules, which see only `queue.py hold`. The global install also installs the MEDUSA security scanner with pipx for `kvb-check-security`, unless `medusa` is already on the PATH. It clones microsoft/TokenEconomizer at the commit pinned in `plugins-lock.json` to `~/Repositories/github.com/microsoft/TokenEconomizer` and installs it for Claude Code and, when `codex` is on the PATH, for Codex, which runs its hooks once they are approved with `/hooks`; tool pruning only proposes deny lists and never drops `AskUserQuestion`, `Artifact`, `Skill`, `Agent`, `ToolSearch` or the hub and code graph MCP tools, micro-skills learn only from repeated failures, and the loop guard stays on (requirement 021). Two hooks of the `kvb-org-perform` skill (`skills/kvb-org-perform/scripts/log.py`) log every Agent spawn with its task class, model and effort, and store the quality feedback a sandboxed session prints, in `~/.local/state/agents-council/subagent-model.jsonl`. Every hook runs `/usr/bin/python3 -I`, so neither the `python3` of a sandbox-writable virtualenv on the `PATH` nor `PYTHONPATH` reaches the hooks, which run outside the sandbox; older bare `python3` hook entries are rewritten. On a Bash call the radio, watch, queue, code graph and log hooks run in one interpreter per event, `skills/kvb-org-organize/scripts/hooks.py pre-bash` and `post-bash`, each handler in its own `try`; an exit 2 of any handler still blocks with its text, and the six older separate Bash entries are rewritten to these two. The reminder hooks run `/usr/bin/bash` and pin `PATH=/usr/bin:/bin`, and the council scripts keep only the `PATH` directories this uid cannot write (`skills/kvb-org-organize/scripts/hookpath.py`), so no binary an agent plants on the inherited `PATH` runs outside the sandbox. Existing settings are preserved.
The council root is the one directory every `kvb-org` script, hook and the hub share: the register, radio, queue, claims, operator rows, score journal, gate receipts, security cache and night state, plus `pages/` (the `kvb-git-diff` review pages the hub reads), `approvals/` (the replay stores of `approval.py verify`) and `gates/` (gate logs). `skills/kvb-org-organize/scripts/councilroot.py` alone resolves it: `$AGENTS_COUNCIL_ROOT`, else `$XDG_STATE_HOME/agents-shared`, else `~/.local/state/agents-shared`, so it survives a reboot; `councilroot.py root` prints it and `councilroot.py dir <part>` creates and prints a part. It and `agents-release` below are the only state paths a sandbox's `allowWrite` may name. Its sibling `~/.local/state/agents-council` (`councilroot.py durable`) is host-only and never belongs in `allowWrite`: only hooks, the runner and the systemd units write it (`gates.db`, the watch hook's copies of the receipt, parent, acceptance and queue-history journals, `queue-cleanup.json`, `resources/`, `subagent-model.jsonl`), and the hub mounts it read-only; no directory is both agent-writable and host-written except the council root, where every host writer opens files through `nofollow.py`. The `kvb-release` drafts lie in `agents-release/<version>` beside both (`councilroot.py release <version>`). The global install first runs `councilroot.py preflight` and stops before it copies anything unless `~/.claude/settings.json` lists both `agents-shared` and `agents-release` in `sandbox.filesystem.allowWrite`, no `allowWrite` entry reaches `agents-council` in the managed file, its `managed-settings.d` drop-ins, the user or user-local file (the list `councilroot.py` shares with the queue's permission check), in a project `.claude/settings.json` or `.claude/settings.local.json` below the pkgmgr repositories and worktrees directories (directory and file links followed), or in the start directory of any session listed in `~/.claude/projects`, and the move below would succeed; it warns while the agents are not suspended. Fixing those entries is the operator's step. It then builds the skills, stops the hub, the runner, the offices, resources and queue-cleanup units, runs `councilroot.py migrate`, which moves an earlier council root in `/tmp/agents-council` into the council root, copies the skills, runs `migrate --catch-up` for what the old skills wrote meanwhile, and starts the units again; the hub image is built before the container is replaced, and a failed build leaves the hub down and fails the install until `bash scripts/orchestrator.sh install` succeeds. Migrate refuses while a lock there is held or a queue job waits, and, checked under those locks, moves nothing (exit 4) while a file cannot be moved or a whole file both roots hold differs; the install then stops with the earlier root intact. Each file is renamed to a `.migrating` name before it is copied, so a writer that opens the old name meanwhile makes a new file the catch-up moves. An identical file leaves one copy, a `.jsonl` journal gets the rows it lacks (by id, else each exact line as often as the earlier root holds it more often, in `ts` order), links are skipped, and a second run moves nothing and duplicates no row. The catch-up keeps a differing whole file beside its namesake as `<name>.legacy-<hash>` (exit 3); a file that fails after the check stays behind (exit 5). After exit 3 or 5 the install goes on so the new skills read the new root, names every such file and exits 1 at the end. `~/.local/state/agents-council/migrate.started` exists from the first move to the end of a run; when a crash leaves it, the install copies the new skills anyway, names it and exits 1, and the next completed migrate removes it. Because the council root survives reboots, each `kvb-org-queue-cleanup` round first runs `councilroot.py retire`, which moves gate logs and review pages older than 30 days into `archive/<date>/`, and the radio appends the rows it drops past its last 500 to `archive/news-<date>.jsonl`; no reader opens `archive/`, which `kvb-cleanup` offers for deletion. Run the install with every agent suspended (`kvb-org-suspend`) and the queue empty, so nothing writes either root during the move.
@@ -0,0 +1,69 @@
# 032 - Send in the Field
## User Story
As the operator, I want a one-line answer field, its microphone and its Send
button to read as one field, so that answering is one control instead of a
field with buttons beside it.
## Decisions (operator-confirmed 2026-11-25; do not re-litigate)
1. **Order and look**: field, then mic, then Send, all inside one frame with
one border and one radius; the parts are separated only by 1 px vertical
lines. This extends 031's one-line frame by a last segment.
2. **Scope**: every one-line field with a mic whose form has its own submit
button, among them the choice "Other" answers. A one-line field without a
submit button keeps 031's frame unchanged.
3. **One helper**: the mic component (`page-mic.js`) moves the form's submit
button into the frame as the segment after the mic; no form places it by
hand.
4. **Timing**: 032 to 038 are implemented in order; tests are written per
requirement and run once after 038, then screenshots go to the operator.
## Approach
```mermaid
flowchart TD
subgraph P["🧭 0 · Preparation"]
P1["📋 Write requirement"] --> P2{"✅ Operator approves?"}
P2 -- "✏️ corrections" --> P1
end
P2 -- "🤖 yes" --> A1
subgraph A["🎙️ A · Send segment"]
A1["🧩 Mic helper takes the submit button as last segment"] --> A2["✍️ Unit and E2E tests written"]
end
A2 --> C1
subgraph C["🧪 C · All of 032 to 038"]
C1["🧪 All tests once"] --> C2{"🟢 Green?"}
C2 -- "🔴 no: fix" --> C1
C2 -- "🟢 yes" --> CF{"💬 Operator feedback on screenshots?"}
CF -- "✏️ changes" --> A1
end
CF -- "👍 fits" --> D1["🏁 Review, commit with operator OK, hand-over"]
```
## Acceptance Criteria
### Frame
- [ ] A DOM scan finds, in every form that holds a one-line mic field and a
submit button, the field, the mic and the submit button as the
frame's children in this order.
- [ ] The mic and Send segments span the frame's inner height (within 1 px),
and a 1 px divider sits before each of them.
- [ ] The Send segment draws no border or radius of its own; the frame's
right corners round it.
### Behaviour
- [ ] Enter in the field and a click on Send submit the same answer as
before (choice "Other" answer reaches its agent once).
- [ ] A redraw of the stream keeps the typed text, focus and caret (026).
### Tests
- [ ] Unit: the helper moves the submit button behind the mic and keeps a
single copy across repeated sweeps.
- [ ] Integration: n/a: no server change.
- [ ] E2E: the "Other" field of a decision in the stream at 1366 and 390:
order and geometry probes; screenshots.
@@ -0,0 +1,82 @@
# 033 - Coherent Speak Box
## User Story
As the operator, I want the radio speak box to be one coherent control, so
that writing, recording and sending read as one piece in the Radio view and
as a Home widget.
## Decisions (operator-confirmed 2026-11-25; do not re-litigate)
1. **One frame** (operator pick 2026-11-25): Channel and To on top as one
segmented row, the message textarea, and a footer row with Record on the
left and the mic, the PTT split and the MAYDAY toggle on the right, all
in one border and separated only by 1 px lines. Rejected: a messenger
composer with recipient chips, a rounded pill and a round send button,
which adds a second visual language beside the frames of 031 and 032.
2. **No extra labels**: no inner "Speak" heading where a box or widget title
already names the box; no channel hint as a tooltip on the Channel select
or the textarea (025's "no hint text" covers tooltips too).
3. **Fit**: in widget mode the box fills the widget body; the textarea takes
the free height and the footer with PTT and MAYDAY stays fully visible at
every widget size the Home grid allows.
4. **Behaviour unchanged**: hold-to-talk, the PTT test menu and the inline
MAYDAY confirmation keep working as today.
5. **Timing**: as 032.
## Approach
```mermaid
flowchart TD
subgraph P["🧭 0 · Preparation"]
P1["📋 Write requirement"] --> P2{"✅ Operator approves?"}
P2 -- "✏️ corrections" --> P1
end
P2 -- "🤖 yes" --> A1
subgraph A["📻 A · Speak box"]
A1["🧩 One frame: channel row, textarea, footer"] --> A2["📐 Widget fit"]
A2 --> A3["✍️ Unit and E2E tests written"]
end
A3 --> C1
subgraph C["🧪 C · All of 032 to 038"]
C1["🧪 All tests once"] --> C2{"🟢 Green?"}
C2 -- "🔴 no: fix" --> C1
C2 -- "🟢 yes" --> CF{"💬 Operator feedback on screenshots?"}
CF -- "✏️ changes" --> A1
end
CF -- "👍 fits" --> D1["🏁 Review, commit with operator OK, hand-over"]
```
## Acceptance Criteria
### Frame
- [ ] One frame element holds the channel row, the textarea and the footer;
the footer's children are Record, a spacer, the mic, the PTT split and
the MAYDAY toggle in this order.
- [ ] Inside the frame the parts are divided by 1 px lines and draw no
borders of their own.
### Labels
- [ ] No visible "Speak" text in the box apart from the box or widget title.
- [ ] No text of `CHANNEL_HINTS` (page-composer.js) reaches a `title`
attribute inside the composer.
### Fit
- [ ] As a Home widget at every height from 3 to 8 rows and every width
from 4 to 12 columns, the PTT split and the MAYDAY toggle lie fully
inside the widget body.
### Behaviour
- [ ] Hold-to-talk, the test menu and the MAYDAY confirmation pass the
existing composer tests.
### Tests
- [ ] Unit: the composer's DOM order and the absence of hint titles.
- [ ] Integration: n/a: no server change.
- [ ] E2E: Radio view and Home widget at 1920, 1366 and 390; geometry
probes; screenshots.
+63
View File
@@ -0,0 +1,63 @@
# 034 - Stream Head Band
## User Story
As the operator, I want the stream's view buttons, search and filters in one
head band separated from the list, so that I see where the controls end and
the entries start.
## Decisions (operator-confirmed 2026-11-25; do not re-litigate)
1. **Head band** (operator pick 2026-11-25): the stream's top row (view
buttons, search, filter menu, entry count) is the box head band of 023:
flush under the box's top border, tinted like the other box heads, with a
1 px line below it. Rejected: a plain 1 px line, which scrolls away and
differs from the other box heads.
2. **Sticky**: the band stays at the top of the stream box while the list
scrolls.
3. **Timing**: as 032.
## Approach
```mermaid
flowchart TD
subgraph P["🧭 0 · Preparation"]
P1["📋 Write requirement"] --> P2{"✅ Operator approves?"}
P2 -- "✏️ corrections" --> P1
end
P2 -- "🤖 yes" --> A1
subgraph A["🧭 A · Head band"]
A1["🧩 Filter row becomes the box head band"] --> A2["📌 Sticky while the list scrolls"]
A2 --> A3["✍️ E2E test written"]
end
A3 --> C1
subgraph C["🧪 C · All of 032 to 038"]
C1["🧪 All tests once"] --> C2{"🟢 Green?"}
C2 -- "🔴 no: fix" --> C1
C2 -- "🟢 yes" --> CF{"💬 Operator feedback on screenshots?"}
CF -- "✏️ changes" --> A1
end
CF -- "👍 fits" --> D1["🏁 Review, commit with operator OK, hand-over"]
```
## Acceptance Criteria
### Band
- [ ] The band is the first child of the stream box; its top edge equals the
box's inner top edge (within 1 px).
- [ ] The band has a 1 px bottom border in `var(--line)` and the background
of a Home widget, under which its title bar sits, so the list never
shows through it.
### Sticky
- [ ] After the list scrolls by 600 px the band's top edge is unchanged
(within 1 px).
### Tests
- [ ] Unit: n/a: layout only.
- [ ] Integration: n/a: no server change.
- [ ] E2E: band geometry and the scroll probe at 1920, 1366 and 390;
screenshots.
+58
View File
@@ -0,0 +1,58 @@
# 035 - Match Full Width
## User Story
As the operator, I want to enlarge a Match card to the full width, so that I
can read long diffs and commands without scrolling sideways.
## Decisions (operator-confirmed 2026-11-25; do not re-litigate)
1. **Toggle**: a ⤢ button in the card head switches the card between its
normal width (at most 960 px) and the full width of the Match area; ⤡
switches back.
2. **Kept**: the choice is stored per browser, like the Next cards toggle,
and applies to the following cards too.
3. **Widget**: in a Home widget the full width is the widget's width.
4. **No gain, no button**: where the Match area is at most 960 px wide the
button is hidden.
5. **Timing**: as 032.
## Approach
```mermaid
flowchart TD
subgraph P["🧭 0 · Preparation"]
P1["📋 Write requirement"] --> P2{"✅ Operator approves?"}
P2 -- "✏️ corrections" --> P1
end
P2 -- "🤖 yes" --> A1
subgraph A["🔍 A · Full width"]
A1["🧩 Toggle in the card head"] --> A2["💾 Kept in ViewStore"]
A2 --> A3["✍️ E2E test written"]
end
A3 --> C1
subgraph C["🧪 C · All of 032 to 038"]
C1["🧪 All tests once"] --> C2{"🟢 Green?"}
C2 -- "🔴 no: fix" --> C1
C2 -- "🟢 yes" --> CF{"💬 Operator feedback on screenshots?"}
CF -- "✏️ changes" --> A1
end
CF -- "👍 fits" --> D1["🏁 Review, commit with operator OK, hand-over"]
```
## Acceptance Criteria
### Toggle
- [ ] After a click on ⤢ the card's width equals the Match area's inner
width (within 2 px); after a click on ⤡ it is at most 960 px.
- [ ] After a reload the chosen width is kept.
- [ ] → ← ↑ and swiping work unchanged at both widths.
- [ ] At 390 px viewport width the button is absent.
### Tests
- [ ] Unit: n/a: layout and a stored flag.
- [ ] Integration: n/a: no server change.
- [ ] E2E: toggle, reload and keys at 1920 and 1366, button absence at 390;
screenshots.
+63
View File
@@ -0,0 +1,63 @@
# 036 - Match Pile
## User Story
As the operator, I want the waiting Match cards to lie behind the top card
like a pile of playing cards, so that I see at a glance that more cards
wait.
## Decisions (operator-confirmed 2026-11-25; do not re-litigate)
1. **Pile** (operator pick 2026-11-25): the next two waiting cards lie
behind the top card at full card size, lifted by 8 and 16 px and drawn
2 % and 4 % smaller, tilted by −1.5° and +1°, dimmed; their colour band
(the gradient top bar) peeks out above the top card. Rejected: a fan like a hand of
cards, which needs room at the sides and covers neighbouring panels in
widget mode.
2. **Inert**: the layers behind show nothing beyond their band, take no
focus and no clicks.
3. **Count**: as many layers as further waiting cards, at most two; none
behind the last card.
4. **Replaces** the 40 px slivers (`.match-behind`) of today.
5. **Reduced motion**: no animation when the pile reorders.
6. **Timing**: as 032.
## Approach
```mermaid
flowchart TD
subgraph P["🧭 0 · Preparation"]
P1["📋 Write requirement"] --> P2{"✅ Operator approves?"}
P2 -- "✏️ corrections" --> P1
end
P2 -- "🤖 yes" --> A1
subgraph A["🃏 A · Pile"]
A1["🧩 Full-size layers behind the top card"] --> A2["🎨 Band of each layer peeks out"]
A2 --> A3["✍️ E2E test written"]
end
A3 --> C1
subgraph C["🧪 C · All of 032 to 038"]
C1["🧪 All tests once"] --> C2{"🟢 Green?"}
C2 -- "🔴 no: fix" --> C1
C2 -- "🟢 yes" --> CF{"💬 Operator feedback on screenshots?"}
CF -- "✏️ changes" --> A1
end
CF -- "👍 fits" --> D1["🏁 Review, commit with operator OK, hand-over"]
```
## Acceptance Criteria
### Layers
- [ ] With three or more waiting cards, two layers lie behind the top card,
each the top card's size (within 2 px) with a lower z-index.
- [ ] Each layer's band starts above the top card's top edge.
- [ ] The layers have `pointer-events: none` and `aria-hidden="true"`.
- [ ] With two waiting cards one layer shows; with one card none.
### Tests
- [ ] Unit: n/a: layout only.
- [ ] Integration: n/a: no server change.
- [ ] E2E: layer count, size and band position for 3, 2 and 1 waiting
cards at 1920, 1366 and 390; screenshots.
+59
View File
@@ -0,0 +1,59 @@
# 037 - Home without Box
## User Story
As the operator, I want the Home widgets to stand directly on the sky, so
that the page shows the widgets and no box around them.
## Decisions (operator-confirmed 2026-11-25; do not re-litigate)
1. **No outer box**: on Home the main container draws no background, border,
shadow or frame padding; the widgets sit on the page background with the
grid's gap between them.
2. **Other screens keep their box.**
3. **Empty state**: "Nothing pinned yet" stays readable as a card of its
own.
4. **Timing**: as 032.
## Approach
```mermaid
flowchart TD
subgraph P["🧭 0 · Preparation"]
P1["📋 Write requirement"] --> P2{"✅ Operator approves?"}
P2 -- "✏️ corrections" --> P1
end
P2 -- "🤖 yes" --> A1
subgraph A["🏠 A · Home"]
A1["🧩 Main container without box on Home"] --> A2["✍️ E2E test written"]
end
A2 --> C1
subgraph C["🧪 C · All of 032 to 038"]
C1["🧪 All tests once"] --> C2{"🟢 Green?"}
C2 -- "🔴 no: fix" --> C1
C2 -- "🟢 yes" --> CF{"💬 Operator feedback on screenshots?"}
CF -- "✏️ changes" --> A1
end
CF -- "👍 fits" --> D1["🏁 Review, commit with operator OK, hand-over"]
```
## Acceptance Criteria
### Home
- [ ] On Home the main container's computed background is transparent and
it has no border and no box-shadow.
- [ ] The widgets' left edge lines up with the navigation bar's left content
edge (within 2 px).
- [ ] With no pins the empty state shows on its own card.
### Other screens
- [ ] The stream screen's box keeps its background, border and shadow.
### Tests
- [ ] Unit: n/a: layout only.
- [ ] Integration: n/a: no server change.
- [ ] E2E: Home with pins, Home empty and the stream at 1920, 1366 and 390;
screenshots.
+54
View File
@@ -0,0 +1,54 @@
# 038 - Badge to Match
## User Story
As the operator, I want a click on the blue count of open operator tasks to
take me straight to the Match view, so that I start deciding with one click.
## Decisions (operator-confirmed 2026-11-25; do not re-litigate)
1. **Target**: a click on the count on the Tasks navigation button opens the
Match screen; a click on the rest of the button keeps opening Tasks.
2. **Own control**: the count becomes a focusable control of its own next to
the Tasks icon, not a button nested in the Tasks button, named "N open
operator tasks: open Match".
3. **Hidden at zero**: as today, no count shows when nothing waits.
4. **Timing**: as 032.
## Approach
```mermaid
flowchart TD
subgraph P["🧭 0 · Preparation"]
P1["📋 Write requirement"] --> P2{"✅ Operator approves?"}
P2 -- "✏️ corrections" --> P1
end
P2 -- "🤖 yes" --> A1
subgraph A["🔢 A · Badge"]
A1["🧩 Count as its own control opening Match"] --> A2["✍️ E2E test written"]
end
A2 --> C1
subgraph C["🧪 C · All of 032 to 038"]
C1["🧪 All tests once"] --> C2{"🟢 Green?"}
C2 -- "🔴 no: fix" --> C1
C2 -- "🟢 yes" --> CF{"💬 Operator feedback on screenshots?"}
CF -- "✏️ changes" --> A1
end
CF -- "👍 fits" --> D1["🏁 Review, commit with operator OK, hand-over"]
```
## Acceptance Criteria
### Navigation
- [ ] A click on the count sets the location hash to `#tasks/match`; a
click on the Tasks icon opens the Tasks screen.
- [ ] Enter on the focused count opens Match.
- [ ] The count's `aria-label` names the number and Match.
- [ ] The count and the Tasks icon keep their positions (within 1 px).
### Tests
- [ ] Unit: n/a: one navigation handler.
- [ ] Integration: n/a: no server change.
- [ ] E2E: click and keyboard on the count and the icon at 1366 and 390.
@@ -0,0 +1,62 @@
# 039 - Match Rejects Survive
## User Story
As the operator, I want a reject I swiped to stay until the release even
when the agent changes or withdraws the card, so that my feedback always
reaches the agent.
## Decisions (operator-confirmed 2026-11-25; do not re-litigate)
1. **Key**: a reject is kept by card id, not by `id@hash`; an accept stays
bound to the exact hash, because it signs that tree. Rejected: dropping
the reject visibly with a toast, which loses the feedback.
2. **Changed card**: the release card shows such a reject with the note
"card changed since your reject"; the feedback goes out unchanged.
3. **Withdrawn card**: a reject whose card is gone is still sent at the
release, by radio call to the card's agent with title and feedback; the
card data needed for that is kept when the reject is made.
4. **Accept on a changed card**: dropped as today, but a toast names the
card ("changed since your accept: decide it again").
## Approach
```mermaid
flowchart TD
subgraph P["🧭 0 · Preparation"]
P1["📋 Write requirement"] --> P2{"✅ Operator approves?"}
P2 -- "✏️ corrections" --> P1
end
P2 -- "🤖 yes" --> A1
subgraph A["🛠️ A · Rejects survive"]
A1["🔑 Reject keyed by id, accept by id@hash"] --> A2["🏷️ Changed note, withdrawn call"]
A2 --> A3["✍️ E2E test written"]
end
A3 --> C1
subgraph C["🧪 C · All of 039 to 046"]
C1["🧪 All tests once"] --> C2{"🟢 Green?"}
C2 -- "🔴 no: fix" --> C1
C2 -- "🟢 yes" --> CF{"💬 Operator feedback on screenshots?"}
CF -- "✏️ changes" --> A1
end
CF -- "👍 fits" --> D1["🏁 Review, commit with operator OK, hand-over"]
```
## Acceptance Criteria
### Rejects
- [ ] Reject card X, then serve X with a new hash: the release card still
lists X as rejected with the note "card changed since your reject".
- [ ] Reject card X, then serve a list without X: the release sends exactly
one radio call to X's agent containing X's title and the feedback.
- [ ] Accept card X, then serve X with a new hash: the decision is gone and
one toast names X.
### Tests
- [ ] Unit: n/a: the decision logic lives in page JS without a unit harness;
E2E covers it.
- [ ] Integration: n/a: no server change.
- [ ] E2E: the three cases above against a mocked `/api/match`, the radio
call captured on `/api/radio`.
+66
View File
@@ -0,0 +1,66 @@
# 040 - Release Card
## User Story
As the operator, I want the release to arrive as the front card of the
Match deck once I have decided everything, so that I release the same way
I decide.
## Decisions (operator-confirmed 2026-11-25; do not re-litigate)
1. **When**: once every card that can be decided now is decided, the release
card is the front card; greyed cards (stale or blocked) do not hold it
back.
2. **Content**: the list of today's overview (each decision changeable or
back to the stack), the release-block note and the Release button.
3. **Gestures** (operator: "1 und 2"): swiping right or the right arrow
starts the passkey release exactly like the button; swiping left or the
left arrow returns to the stack.
4. **Behind it**: cards that arrive meanwhile and the greyed cards lie behind
the release card as the pile layers of 036; they never jump in front.
5. **Early**: the Decisions button (tally) still opens the release card
before everything is decided.
6. **Replaces** the overview section that takes the deck's place today.
## Approach
```mermaid
flowchart TD
subgraph P["🧭 0 · Preparation"]
P1["📋 Write requirement"] --> P2{"✅ Operator approves?"}
P2 -- "✏️ corrections" --> P1
end
P2 -- "🤖 yes" --> A1
subgraph A["🃏 A · Release card"]
A1["🧩 Release as deck card"] --> A2["👉 Swipe and arrows"]
A2 --> A3["✍️ E2E test written"]
end
A3 --> C1
subgraph C["🧪 C · All of 039 to 046"]
C1["🧪 All tests once"] --> C2{"🟢 Green?"}
C2 -- "🔴 no: fix" --> C1
C2 -- "🟢 yes" --> CF{"💬 Operator feedback on screenshots?"}
CF -- "✏️ changes" --> A1
end
CF -- "👍 fits" --> D1["🏁 Review, commit with operator OK, hand-over"]
```
## Acceptance Criteria
### Card
- [ ] With all decidable cards decided, `.match-deck .match-card.front` is
the release card and contains `.match-release`.
- [ ] Swiping the release card right or the right arrow runs the same
release as the button: exactly one submit with every decision.
- [ ] Swiping it left or the left arrow shows the open stack again.
- [ ] A card arriving while the release card is front lies in
`.match-layer`; the release card stays front.
- [ ] A stale or blocked open card does not prevent the release card and
lies behind it as a layer.
### Tests
- [ ] Unit: n/a: page JS.
- [ ] Integration: n/a: no server change.
- [ ] E2E: the five checks above at 1920 and 390; screenshots.
@@ -0,0 +1,59 @@
# 041 - Code Marks in the Review Modal
## User Story
As the operator, I want to mark code lines in the review modal's diff as I
can in Match, so that I point the agent at exact lines when I deny or
approve.
## Decisions (operator-confirmed 2026-11-25; do not re-litigate)
1. **Scope**: the review modal only. Rejected: every diff view, more surface
than asked for.
2. **Mechanism**: Match's marking is reused, not rebuilt: select or click
lines, attach a comment.
3. **Flow**: Deny prefills its reason with the marks as `path:line` plus
comment; Approve sends them to the agent as notes by radio post, as
Match does after a release.
4. **Persistence**: marks are kept per review id until the review is
decided, like Match's marks.
## Approach
```mermaid
flowchart TD
subgraph P["🧭 0 · Preparation"]
P1["📋 Write requirement"] --> P2{"✅ Operator approves?"}
P2 -- "✏️ corrections" --> P1
end
P2 -- "🤖 yes" --> A1
subgraph A["🖍️ A · Review marks"]
A1["🧩 Match marking on the modal diff"] --> A2["📝 Marks into deny reason and approval notes"]
A2 --> A3["✍️ E2E test written"]
end
A3 --> C1
subgraph C["🧪 C · All of 039 to 046"]
C1["🧪 All tests once"] --> C2{"🟢 Green?"}
C2 -- "🔴 no: fix" --> C1
C2 -- "🟢 yes" --> CF{"💬 Operator feedback on screenshots?"}
CF -- "✏️ changes" --> A1
end
CF -- "👍 fits" --> D1["🏁 Review, commit with operator OK, hand-over"]
```
## Acceptance Criteria
### Marks
- [ ] In the review modal, marking a diff line and adding the comment "c"
shows the mark in the modal.
- [ ] Deny opens with a reason containing `<path>:<line>` and "c".
- [ ] Approve sends one radio post to the agent containing `<path>:<line>`
and "c".
- [ ] Closing and reopening the modal for the same review keeps the mark.
### Tests
- [ ] Unit: n/a: page JS.
- [ ] Integration: n/a: no server change.
- [ ] E2E: the four checks above; screenshot.
+54
View File
@@ -0,0 +1,54 @@
# 042 - Why Deny Is Off
## User Story
As the operator, I want a disabled Deny button to tell me on hover why it
is off, so that I do not guess what is missing.
## Decisions (operator-confirmed 2026-11-25; do not re-litigate)
1. **Hover and focus**: a wrapper around the button carries the reason as
tooltip, because a disabled button fires no hover in Chrome; the button's
`aria-describedby` gives keyboard users the same text.
2. **Reasons**: "Pick the agent to tell: a post or call needs a recipient"
(deny sheet) and "No agent to tell: the item names no recipient" (the
split Deny button, `page-deny.js` `denySplit`).
3. **Enabled again**: once the reason is gone the tooltip names the action.
## Approach
```mermaid
flowchart TD
subgraph P["🧭 0 · Preparation"]
P1["📋 Write requirement"] --> P2{"✅ Operator approves?"}
P2 -- "✏️ corrections" --> P1
end
P2 -- "🤖 yes" --> A1
subgraph A["💬 A · Deny reason"]
A1["🧩 Wrapper with title and aria-describedby"] --> A2["✍️ E2E test written"]
end
A2 --> C1
subgraph C["🧪 C · All of 039 to 046"]
C1["🧪 All tests once"] --> C2{"🟢 Green?"}
C2 -- "🔴 no: fix" --> C1
C2 -- "🟢 yes" --> CF{"💬 Operator feedback on screenshots?"}
CF -- "✏️ changes" --> A1
end
CF -- "👍 fits" --> D1["🏁 Review, commit with operator OK, hand-over"]
```
## Acceptance Criteria
### Tooltip
- [ ] In the deny sheet with channel Call and no recipient, the wrapper of
the disabled Deny button has a `title` naming the missing recipient.
- [ ] The button's `aria-describedby` points to an element with that text.
- [ ] After a recipient is picked, Deny is enabled and the title no longer
names a missing recipient.
### Tests
- [ ] Unit: n/a: page JS.
- [ ] Integration: n/a: no server change.
- [ ] E2E: the three checks above.
@@ -0,0 +1,71 @@
# 043 - Undo Window on a Clock
## User Story
As the operator, I want to set on a clock dial from 0 to 60 s how long a
grant, deny or release waits before it takes effect, so that the undo
window fits my pace.
## Decisions (operator-confirmed 2026-11-25; do not re-litigate)
1. **Range**: whole seconds from 0 to 60; 0 takes effect at once without an
undo toast; default 3 s, today's value. Rejected: 1 to 30 s and fixed
choices (operator pick: 0 to 60).
2. **Dial**: an analog clock face in Settings with 60 ticks and one hand;
dragging the hand, clicking a tick, the arrow keys (±1 s) and Page Up and
Down (±5 s) set it; a readout shows "N s"; ARIA `slider`.
3. **Server**: the value is stored with the hub settings; `batches.py` reads
it per new batch instead of the constant `UNDO = 3.0`; a running batch
keeps its due time.
4. **One source**: every text that says "3 s" today (deny note, release
title, inbox deny note) shows the set value.
## Approach
```mermaid
flowchart TD
subgraph P["🧭 0 · Preparation"]
P1["📋 Write requirement"] --> P2{"✅ Operator approves?"}
P2 -- "✏️ corrections" --> P1
end
P2 -- "🤖 yes" --> A1
subgraph A["⏱️ A · Undo clock"]
A1["🧩 Setting read per batch"] --> A2["🕰️ Clock dial"]
A2 --> A3["📝 Texts from the setting"]
A3 --> A4["✍️ Unit, integration and E2E tests written"]
end
A4 --> C1
subgraph C["🧪 C · All of 039 to 046"]
C1["🧪 All tests once"] --> C2{"🟢 Green?"}
C2 -- "🔴 no: fix" --> C1
C2 -- "🟢 yes" --> CF{"💬 Operator feedback on screenshots?"}
CF -- "✏️ changes" --> A1
end
CF -- "👍 fits" --> D1["🏁 Review, commit with operator OK, hand-over"]
```
## Acceptance Criteria
### Setting
- [ ] With 10 s saved, a new batch's `due` lies 10 s (±0.5) after its
creation.
- [ ] With 0 saved, a new batch applies at once and no undo toast appears.
- [ ] The server refuses −1, 61 and 2.5 with 400.
### Dial
- [ ] The dial has `role="slider"`, `aria-valuemin="0"`,
`aria-valuemax="60"` and `aria-valuenow` equal to the readout.
- [ ] The right arrow raises the value by 1, Page Up by 5, capped at 60.
### Texts
- [ ] With 10 s set, the deny sheet note and the release button title say
"10 s".
### Tests
- [ ] Unit: settings validation for 0, 60, −1, 61 and 2.5.
- [ ] Integration: batch due time for 0 and 10 through the HTTP API.
- [ ] E2E: the dial and text checks above; screenshot of the dial.
@@ -0,0 +1,68 @@
# 044 - Widgets without Inner Boxes
## User Story
As the operator, I want a widget's content to fill the widget instead of
sitting in a second box, so that the Home widgets look calm and use their
space.
## Decisions (operator-confirmed 2026-11-25; do not re-litigate)
1. **General rule**: when a widget's content root is itself a box (a card
with its own border, background or padding), it loses border,
background, radius and outer padding and fills the widget body; named
examples Radio log, Radio device, Radio speak and Tasks Gantt. Rejected:
rules per widget, which every new widget would need again; 033's
speak-only rule folds into the general one. Amended 2026-11-26 after the
e2e run: the walk also enters the one box of a wrapper that holds only
it and `.legend` rows, so a Gantt or RASCI box beside its legend is
flattened at any size; the legend stays under it, and the box with the rows
after it fill the body; a text field inside the flattened box (the
Radio speak input) keeps its frame.
2. **Titles**: an inner title that repeats the widget's title bar ("HISTORY"
under "Radio log", "DEVICE" under "Radio device") is hidden in widget
mode; section labels that add information stay.
3. **Full view unchanged**: outside widget mode the boxes stay as they are.
## Approach
```mermaid
flowchart TD
subgraph P["🧭 0 · Preparation"]
P1["📋 Write requirement"] --> P2{"✅ Operator approves?"}
P2 -- "✏️ corrections" --> P1
end
P2 -- "🤖 yes" --> A1
subgraph A["📦 A · Unboxed widgets"]
A1["🧩 One rule for the content root"] --> A2["🏷️ Repeated inner titles hidden"]
A2 --> A3["✍️ E2E test written"]
end
A3 --> C1
subgraph C["🧪 C · All of 039 to 046"]
C1["🧪 All tests once"] --> C2{"🟢 Green?"}
C2 -- "🔴 no: fix" --> C1
C2 -- "🟢 yes" --> CF{"💬 Operator feedback on screenshots?"}
CF -- "✏️ changes" --> A1
end
CF -- "👍 fits" --> D1["🏁 Review, commit with operator OK, hand-over"]
```
## Acceptance Criteria
### Widgets
- [ ] For every widget kind on Home, the first box element inside
`.home-tile` below the title bar has a computed `border-width` of 0
and a transparent background.
- [ ] Its bottom edge lies within 2 px of the widget body's content
bottom.
- [ ] Radio log and Radio device show no visible inner title repeating the
widget title.
- [ ] Outside widget mode the same panels keep a 1px border.
### Tests
- [ ] Unit: n/a: CSS.
- [ ] Integration: n/a: no server change.
- [ ] E2E: the checks above for all widget kinds at 1920 and 390;
screenshots of Radio log, Radio device, Radio speak and Gantt.
@@ -0,0 +1,58 @@
# 045 - Artifacts Head on One Line
## User Story
As the operator, I want the Artifacts head on one tidy line, so that the
controls and the status do not break apart.
## Decisions (operator-confirmed 2026-11-25; do not re-litigate)
1. **One line**: from 1024 px width, view switch, picker, toolbar and count
sit on one line; no word breaks.
2. **Count**: "97 repositories · as of 14:02" truncates with an ellipsis
when space runs short; the full text sits in `title`.
3. **Delete blocked**: leaves the count text and becomes a warning chip
beside the delete button; chip and disabled delete button (042's
wrapper) carry the reason as tooltip.
4. **Narrow**: below 1024 px at most two lines, still no word broken.
## Approach
```mermaid
flowchart TD
subgraph P["🧭 0 · Preparation"]
P1["📋 Write requirement"] --> P2{"✅ Operator approves?"}
P2 -- "✏️ corrections" --> P1
end
P2 -- "🤖 yes" --> A1
subgraph A["🧱 A · Artifacts head"]
A1["🧩 One-line head"] --> A2["⚠️ Delete-blocked chip"]
A2 --> A3["✍️ E2E test written"]
end
A3 --> C1
subgraph C["🧪 C · All of 039 to 046"]
C1["🧪 All tests once"] --> C2{"🟢 Green?"}
C2 -- "🔴 no: fix" --> C1
C2 -- "🟢 yes" --> CF{"💬 Operator feedback on screenshots?"}
CF -- "✏️ changes" --> A1
end
CF -- "👍 fits" --> D1["🏁 Review, commit with operator OK, hand-over"]
```
## Acceptance Criteria
### Head
- [ ] At 1920 and 1366 the Artifacts head is one line: its height equals a
single control row (±2 px).
- [ ] The count element has `text-overflow: ellipsis` and a `title` with
the full text.
- [ ] Without a GitHub token a warning chip beside the delete button names
the reason and the count text holds no "Delete blocked".
- [ ] At 390 the head takes at most two lines.
### Tests
- [ ] Unit: n/a: page JS and CSS.
- [ ] Integration: n/a: no server change.
- [ ] E2E: the four checks above; screenshots at 1920, 1366 and 390.
@@ -0,0 +1,66 @@
# 046 - Accept the Risk of a Red Gate
## User Story
As the operator, I want a button on a commit with a red gate that accepts
its risk explicitly, so that it is released with my other decisions instead
of blocking them.
## Decisions (operator-confirmed 2026-11-25; do not re-litigate)
1. **Button, not warning**: each accepted commit without a green gate shows
"Accept risk: gate not green" in the release card (040); the release-block
warning goes. Rejected: today's hard blocker ("release it alone").
2. **Until clicked**: the Release button stays usable for everything else; a
risky commit whose risk is not accepted is left out of the release and
stays in the stack; the release card names it.
3. **Signature** (operator pick): each risk-accepted red-gate commit gets
its own passkey signature, one after the other, then the rest one
signature, as the inbox bulk grant does; the server rule
(`approving.py`: a red-gate review is approved only on its own) stays, so
every red-gate approval keeps an individual signature as proof.
Rejected: one signature with a `risk: accepted` flag per item, which
would weaken that rule.
4. **Take back**: an accepted risk can be withdrawn until the release.
## Approach
```mermaid
flowchart TD
subgraph P["🧭 0 · Preparation"]
P1["📋 Write requirement"] --> P2{"✅ Operator approves?"}
P2 -- "✏️ corrections" --> P1
end
P2 -- "🤖 yes" --> A1
subgraph A["⚠️ A · Accept risk"]
A1["🧩 Risk button per red-gate accept"] --> A2["🔑 Own signature each, then the rest"]
A2 --> A3["✍️ E2E test written"]
end
A3 --> C1
subgraph C["🧪 C · All of 039 to 046"]
C1["🧪 All tests once"] --> C2{"🟢 Green?"}
C2 -- "🔴 no: fix" --> C1
C2 -- "🟢 yes" --> CF{"💬 Operator feedback on screenshots?"}
CF -- "✏️ changes" --> A1
end
CF -- "👍 fits" --> D1["🏁 Review, commit with operator OK, hand-over"]
```
## Acceptance Criteria
### Risk
- [ ] No `.match-release-block` exists; a red-gate accept shows a
`.match-accept-risk` button.
- [ ] Without the click the release submits every decision except the risky
commit, which stays in the stack.
- [ ] With the click the release sends the risky commit in its own submit
before one submit with the rest.
- [ ] Withdrawing the accepted risk before the release leaves the commit out
again.
### Tests
- [ ] Unit: n/a: page JS.
- [ ] Integration: n/a: the server rule is unchanged and keeps its tests.
- [ ] E2E: the four checks above with the submits captured on `/api/inbox`.
+79
View File
@@ -0,0 +1,79 @@
# 047 - One Code Box
## User Story
As the operator, I want every piece of code in the hub to sit in the same
box with an eye button and its actions at the bottom edge, so that Stream,
Waits on Operator, Match and Tasks feel like one tool.
## Decisions (operator-confirmed 2026-11-25; do not re-litigate)
1. **One component**: every command box and diff block in Stream, Waits on
Operator (`#tasks/operator`), Match cards and Tasks is one code box; an
item's command and its diff files form one box.
2. **Eye toggles in place** (operator pick 2): the eye grows the box to its
full height and shrinks it back to its preview. Rejected: a modal viewer
with zoom for every box; a second viewer button beside the inline toggle.
3. **Defaults per place** (operator): Stream and Waits on Operator show a
12-line preview; Match cards show the box open and scroll inside the card
body; Tasks show it closed, and the eye opens it in a modal above.
4. **Footer** (operator pick): copy, eye, then Grant ✓ and Deny ✗▾ sit in one
bar at the box's bottom edge; snooze and pin stay to the right of the
item's actions row. Match keeps Accept and Reject under the deck, its
footer holds copy and eye. Rejected: buttons attached below the box;
actions left where they are.
5. **Review entries**: the eye of a review entry in the Stream loads its diff
into the box on the first click instead of opening the View diff modal.
## Approach
```mermaid
flowchart TD
subgraph P["🧭 0 · Preparation"]
P1["📋 Write requirement"] --> P2{"✅ Operator approves?"}
P2 -- "✏️ corrections" --> P1
end
P2 -- "🤖 yes" --> A1
subgraph A["📦 A · Code box"]
A1["🧩 One code box component"] --> A2["👁️ Eye defaults per place"]
A2 --> A3["🦶 Footer with copy, eye, Grant, Deny"]
A3 --> A4["✍️ E2E test written"]
end
A4 --> C1
subgraph C["🧪 C · All of 039 to 050"]
C1["🧪 All tests once"] --> C2{"🟢 Green?"}
C2 -- "🔴 no: fix" --> C1
C2 -- "🟢 yes" --> CF{"💬 Operator feedback on screenshots?"}
CF -- "✏️ changes" --> A1
end
CF -- "👍 fits" --> D1["🏁 Review, commit with operator OK, hand-over"]
```
## Acceptance Criteria
### Box
- [ ] Every `.command` and every diff block in `#stream`,
`#tasks/operator`, `#tasks/match` and `#tasks/list` lies inside one
`.code-box` per item, whose last child is its `.code-foot`.
- [ ] `.code-foot` holds a copy button and a `.code-eye` button carrying
`aria-expanded`; in Stream and Waits on Operator it also holds the
item's Grant and Deny.
### Eye
- [ ] Stream and Waits on Operator: a box taller than 12 lines starts
clipped (`aria-expanded="false"`); the eye shows its full height, a
second click clips it again.
- [ ] Match: the box starts open; the card body scrolls, the page does not.
- [ ] Tasks: the box starts closed; the eye opens a sheet with the full code,
Esc closes it.
- [ ] Stream review entry: the eye loads its diff into the box; no sheet
opens.
### Tests
- [ ] Unit: n/a: page JS.
- [ ] Integration: `test_hub_operator_tasks` and `test_hub_grant_mode`
follow the footer.
- [ ] E2E: the Box and Eye checks at 1920 and 390 in Chromium; screenshots.
+65
View File
@@ -0,0 +1,65 @@
# 048 - Done Rows Greyed and Folded
## User Story
As the operator, I want finished rows in Waits on Operator clearly greyed
and out of the way, without a checkbox, so that I see at a glance what still
waits on me.
## Decisions (operator-confirmed 2026-11-25; do not re-litigate)
1. **Done** means signed and inside its undo window (`held`) or its job
ended. Such a row is greyed (opacity at most 0.5, grayscale), carries a
"done" pill and moves under a "Done (n)" fold at the bottom, closed by
default. Rejected: greyed in place; hidden at once, which leaves the undo
window only in the toast.
2. **No checkbox** (operator: the green check already does it): in Select
mode the selection shows as the highlighted row (`aria-selected="true"`)
and the pressed green check; `x` still selects. Rejected: keeping the
checkbox.
## Approach
```mermaid
flowchart TD
subgraph P["🧭 0 · Preparation"]
P1["📋 Write requirement"] --> P2{"✅ Operator approves?"}
P2 -- "✏️ corrections" --> P1
end
P2 -- "🤖 yes" --> A1
subgraph A["🗂️ A · Done fold"]
A1["🧩 Done rows greyed under a fold"] --> A2["☑️ Checkbox out, selection on the row"]
A2 --> A3["✍️ E2E test written"]
end
A3 --> C1
subgraph C["🧪 C · All of 039 to 050"]
C1["🧪 All tests once"] --> C2{"🟢 Green?"}
C2 -- "🔴 no: fix" --> C1
C2 -- "🟢 yes" --> CF{"💬 Operator feedback on screenshots?"}
CF -- "✏️ changes" --> A1
end
CF -- "👍 fits" --> D1["🏁 Review, commit with operator OK, hand-over"]
```
## Acceptance Criteria
### Done
- [ ] A held row and a row whose job ended lie in a closed
`details.inbox-done` at the end of `#tasks/operator`, each with
`data-done`, a "done" pill and a computed opacity of at most 0.5.
- [ ] Its summary reads "Done (n)" with n the number of such rows.
### Selection
- [ ] `.inbox-list .item` holds no `input[type="checkbox"]`.
- [ ] In Select mode the green check of a row sets `aria-selected="true"` on
the row and `aria-pressed="true"` on the check; a second click clears
both; `x` toggles the same.
### Tests
- [ ] Unit: n/a: page JS.
- [ ] Integration: the checkbox test in `test_hub_operator_tasks` becomes the
selection check; `test_hub_grant_mode` follows.
- [ ] E2E: the Done and Selection checks at 1920 and 390; screenshots.
@@ -0,0 +1,61 @@
# 049 - One Control Height
## User Story
As the operator, I want every control in every head bar at one height, so
that buttons, search field and filters line up on every page.
## Decisions (operator-confirmed 2026-11-25; do not re-litigate)
1. **36 px** (operator pick) for every control in a `.box-head`: icon
buttons, the search field with its mic, the filter button, chips and
selects, from one CSS token. Rejected: 32 px, which shrinks the search
field; 40 px, which grows every button.
2. **Design pass**: every view is screenshotted at 1920 and 390; each misfit
found (alignment, wrapping, spacing) is fixed under this requirement and
listed in the hand-over.
## Approach
```mermaid
flowchart TD
subgraph P["🧭 0 · Preparation"]
P1["📋 Write requirement"] --> P2{"✅ Operator approves?"}
P2 -- "✏️ corrections" --> P1
end
P2 -- "🤖 yes" --> A1
subgraph A["📏 A · Control height"]
A1["🧩 One height token"] --> A2["🔎 Design pass over every view"]
A2 --> A3["✍️ E2E test written"]
end
A3 --> C1
subgraph C["🧪 C · All of 039 to 050"]
C1["🧪 All tests once"] --> C2{"🟢 Green?"}
C2 -- "🔴 no: fix" --> C1
C2 -- "🟢 yes" --> CF{"💬 Operator feedback on screenshots?"}
CF -- "✏️ changes" --> A1
end
CF -- "👍 fits" --> D1["🏁 Review, commit with operator OK, hand-over"]
```
## Acceptance Criteria
### Height
- [ ] `style-ui.css` defines `--control-h: 36px`, and every head-bar control
rule uses it.
- [ ] In every view of `test_box_heads_e2e.py`, every visible control in
`.box-head` is 36 ± 1 px high at 1920 and 390.
- [ ] Stream head: icon buttons, search field, filter button and count text
share one vertical centre ± 1 px.
### Design pass
- [ ] The hand-over lists every misfit found with its fix and its
before/after screenshot.
### Tests
- [ ] Unit: n/a: CSS.
- [ ] Integration: n/a: no server change.
- [ ] E2E: `test_box_heads_e2e.py` extended by the Height checks.
+53
View File
@@ -0,0 +1,53 @@
# 050 - Menus Stay Open
## User Story
As the operator, I want the filter menu to stay open while I click its
chips, so that I set several filters in one go.
## Decisions (operator-confirmed 2026-11-25; do not re-litigate)
1. **Stay open**: clicks inside the Stream filter menu, and inside every hub
menu whose entries are toggle chips, never close it. A menu entry that
runs an action still closes its menu.
2. **Close** (operator): 3 s after the pointer leaves the menu, cancelled when
it comes back; at once on a click outside or Esc.
## Approach
```mermaid
flowchart TD
subgraph P["🧭 0 · Preparation"]
P1["📋 Write requirement"] --> P2{"✅ Operator approves?"}
P2 -- "✏️ corrections" --> P1
end
P2 -- "🤖 yes" --> A1
subgraph A["📂 A · Menus"]
A1["🧩 Chip clicks keep the menu"] --> A2["⏲️ Close 3 s after leave, outside click, Esc"]
A2 --> A3["✍️ E2E test written"]
end
A3 --> C1
subgraph C["🧪 C · All of 039 to 050"]
C1["🧪 All tests once"] --> C2{"🟢 Green?"}
C2 -- "🔴 no: fix" --> C1
C2 -- "🟢 yes" --> CF{"💬 Operator feedback on screenshots?"}
CF -- "✏️ changes" --> A1
end
CF -- "👍 fits" --> D1["🏁 Review, commit with operator OK, hand-over"]
```
## Acceptance Criteria
### Menu
- [ ] After clicks on three kind chips of the Stream filter menu, the menu is
open and all three chips show their new state.
- [ ] After the pointer leaves, the menu is open at 2.5 s and closed at
3.5 s; a return at 2 s keeps it open.
- [ ] A click outside or Esc closes it at once.
### Tests
- [ ] Unit: n/a: page JS.
- [ ] Integration: n/a: no server change.
- [ ] E2E: the Menu checks in Chromium; screenshots.
@@ -0,0 +1,79 @@
# 051 - Radio Settings in the Device Card
## User Story
As the operator, I want every notification and radio setting, including the
GNOME desktop popups, in the Device card of the radio, so that I switch how
the hub reaches me in one place.
## Decisions (operator-confirmed 2026-11-25; do not re-litigate)
1. **Device card** (operator): the notification channels, the GNOME popups
and the internet radio stations move out of the general Settings into the
Device card of the radio spot. The general Settings keep Ambience,
Location, Appearance, Music and Passkey. Rejected: a card of their own; a
gear sheet in the radio bar.
2. **GNOME popups per source** (operator picks 1 and 2): resources
(`watch.py`), MAYDAY (`radio.py`) and the dream reminder
(`kvb-dream/hooks/notify.sh`), each on or off and each snoozable for 1 h
or until 8 am tomorrow. Rejected: one switch for all three, which mutes
MAYDAY with the rest.
3. **Bridge**: every signed settings save writes `notify.json` into the
council directory; the three senders read it before `notify-send`. A
muted source still reaches the Stream and the radio, only the popup goes.
A missing or unreadable file means on, so a broken file never silences an
alarm.
4. **Signed**: the switches change through the passkey like every setting.
## Approach
```mermaid
flowchart TD
subgraph P["🧭 0 · Preparation"]
P1["📋 Write requirement"] --> P2{"✅ Operator approves?"}
P2 -- "✏️ corrections" --> P1
end
P2 -- "🤖 yes" --> A1
subgraph A["📻 A · Device card"]
A1["🧩 Settings move into the Device card"] --> A2["🔔 GNOME switch and snooze per source"]
A2 --> A3["🌉 notify.json read by the three senders"]
A3 --> A4["✍️ Unit, integration and E2E tests written"]
end
A4 --> C1
subgraph C["🧪 C · All of 039 to 053"]
C1["🧪 All tests once"] --> C2{"🟢 Green?"}
C2 -- "🔴 no: fix" --> C1
C2 -- "🟢 yes" --> CF{"💬 Operator feedback on screenshots?"}
CF -- "✏️ changes" --> A1
end
CF -- "👍 fits" --> D1["🏁 Review, commit with operator OK, hand-over"]
```
## Acceptance Criteria
### Device card
- [ ] The Settings sheet has no "Notifications" and no "Internet radio"
section.
- [ ] The Device card holds `.radio-settings` with the channel switches,
three `.notify-source` rows (resources, mayday, dream) and the
stations.
### Popups
- [ ] Saving resources off writes `notify.json` with
`{"resources": {"on": false, "until": 0}, ...}` into the council
directory.
- [ ] Snooze 1 h writes `until` = now + 3600; the source sends no popup
before it and sends again after it.
- [ ] `watch.py`, `radio.py` and `notify.sh` run `notify-send` only for a
source that is on and not snoozed; a missing or broken `notify.json`
counts as on.
### Tests
- [ ] Unit: each sender with `notify.json` on, off, snoozed, expired,
missing and broken, against a fake `notify-send`.
- [ ] Integration: a signed settings save writes `notify.json`; an unsigned
one is refused.
- [ ] E2E: the Device card switches and snooze in Chromium; screenshots.
@@ -0,0 +1,54 @@
# 052 - Bubbles Beside the Modes
## User Story
As the operator, I want the chat bubbles switch beside the radio modes, so
that I set how messages reach me in one row.
## Decisions (operator-confirmed 2026-11-25; do not re-litigate)
1. **Toggle beside the modes** (operator): the bubbles switch sits in the
mode row next to Auto, Quiet, Silence, Morse and Gibberlink, set apart as
an on/off toggle, while the modes stay a choice of one. Rejected: a
bubbles card in the radio spot; a bubbles spot of its own.
2. **One setting**: it switches the same `bubbles` setting as the header
toggle, which stays as the quick switch; both always show the same state.
## Approach
```mermaid
flowchart TD
subgraph P["🧭 0 · Preparation"]
P1["📋 Write requirement"] --> P2{"✅ Operator approves?"}
P2 -- "✏️ corrections" --> P1
end
P2 -- "🤖 yes" --> A1
subgraph A["💬 A · Bubbles toggle"]
A1["🧩 Toggle in the mode row"] --> A2["🔗 Same setting as the header toggle"]
A2 --> A3["✍️ E2E test written"]
end
A3 --> C1
subgraph C["🧪 C · All of 039 to 053"]
C1["🧪 All tests once"] --> C2{"🟢 Green?"}
C2 -- "🔴 no: fix" --> C1
C2 -- "🟢 yes" --> CF{"💬 Operator feedback on screenshots?"}
CF -- "✏️ changes" --> A1
end
CF -- "👍 fits" --> D1["🏁 Review, commit with operator OK, hand-over"]
```
## Acceptance Criteria
### Toggle
- [ ] The mode row holds a `.radio-bubbles` button with `aria-pressed`
equal to the `bubbles` setting, separated from the mode buttons by a
divider.
- [ ] Clicking it flips bubbles; the active mode stays the same and
`#bubbles-toggle` shows the new state.
### Tests
- [ ] Unit: n/a: page JS.
- [ ] Integration: n/a: the setting exists.
- [ ] E2E: the Toggle checks in Chromium; screenshots.
@@ -0,0 +1,61 @@
# 053 - Agent Settings on Every Face and Name
## User Story
As the operator, I want every agent's avatar and name to open that agent,
with settings of its own, so that I tune one noisy agent without touching
the rest.
## Decisions (operator-confirmed 2026-11-25; do not re-litigate)
1. **Always clickable** (operator): every agent avatar and every agent name
in the hub opens the agent popover (`openAgent`). Today names built by
`person()` do; avatars and names written as plain text do not.
2. **Per-agent settings** (operator): the popover gains the agent's own
switches for sound, read aloud and bubbles, each on or off for this agent
only, stored in the signed settings.
## Approach
```mermaid
flowchart TD
subgraph P["🧭 0 · Preparation"]
P1["📋 Write requirement"] --> P2{"✅ Operator approves?"}
P2 -- "✏️ corrections" --> P1
end
P2 -- "🤖 yes" --> A1
subgraph A["🧑 A · Agent settings"]
A1["🧩 Faces and names open the agent"] --> A2["🎚️ Sound, read aloud, bubbles per agent"]
A2 --> A3["✍️ Integration and E2E tests written"]
end
A3 --> C1
subgraph C["🧪 C · All of 039 to 053"]
C1["🧪 All tests once"] --> C2{"🟢 Green?"}
C2 -- "🔴 no: fix" --> C1
C2 -- "🟢 yes" --> CF{"💬 Operator feedback on screenshots?"}
CF -- "✏️ changes" --> A1
end
CF -- "👍 fits" --> D1["🏁 Review, commit with operator OK, hand-over"]
```
## Acceptance Criteria
### Clickable
- [ ] In Stream, Waits on Operator, Match, Tasks and the radio log, every
`.avatar[data-face]` and every agent name sits in a button that opens
the agent popover; dragging a Match card by its head still works.
### Settings
- [ ] The agent popover holds `.agent-settings` with three switches.
- [ ] Sound off: no tone for that agent's radio; read aloud off: its
messages are not spoken; bubbles off: no bubble for it. Other agents
stay as they were.
### Tests
- [ ] Unit: n/a: page JS.
- [ ] Integration: the settings schema accepts the per-agent map and refuses
unknown keys.
- [ ] E2E: the Clickable and Settings checks in Chromium; screenshots.
+61
View File
@@ -0,0 +1,61 @@
# 054 - Pin Only by Menu
## User Story
As the operator, I want no favourite stars on the boxes and pinning only
through the context menu, so that the heads stay calm and pinning still
works from everywhere.
## Decisions (operator-confirmed 2026-11-25; do not re-litigate)
1. **No stars** (operator): no `.star` button anywhere in the hub; the star
slots and star rows go. Rejected: hiding them by CSS, which leaves them
focusable.
2. **Menu only** (operator): "Pin to Home" and "Unpin from Home" stay in the
context menu: right-click, a touch long press, or the menu key of the
focused box. Existing pins stay.
## Approach
```mermaid
flowchart TD
subgraph P["🧭 0 · Preparation"]
P1["📋 Write requirement"] --> P2{"✅ Operator approves?"}
P2 -- "✏️ corrections" --> P1
end
P2 -- "🤖 yes" --> A1
subgraph A["📌 A · Pin by menu"]
A1["🧩 Stars out"] --> A2["📋 Pin through the context menu only"]
A2 --> A3["✍️ E2E tests moved to the menu"]
end
A3 --> C1
subgraph C["🧪 C · All of 039 to 055"]
C1["🧪 All tests once"] --> C2{"🟢 Green?"}
C2 -- "🔴 no: fix" --> C1
C2 -- "🟢 yes" --> CF{"💬 Operator feedback on screenshots?"}
CF -- "✏️ changes" --> A1
end
CF -- "👍 fits" --> D1["🏁 Review, commit with operator OK, hand-over"]
```
## Acceptance Criteria
### Stars
- [ ] Every view of `test_box_heads_e2e.py` and Home hold no `.star` and no
`.star-row` element.
### Menu
- [ ] Right-clicking a box head that a star used to pin shows "Pin to Home";
running it adds the box to Home, and the same menu then shows "Unpin
from Home".
- [ ] A pin made before the change is still on Home.
### Tests
- [ ] Unit: the panels tests drop the star button and keep `targetOf` and
`add`.
- [ ] Integration: n/a: no server change.
- [ ] E2E: the bookmark tests pin through the context menu; the Stars and
Menu checks in Chromium.
+72
View File
@@ -0,0 +1,72 @@
# 055 - WASD in Match
## User Story
As the operator, I want to swipe the Match deck with W, A, S and D in an
endless round with the release card coming up in between, so that I decide,
skip, undo and release without leaving the keyboard's home row.
## Decisions (operator-confirmed 2026-11-25; do not re-litigate)
1. **Keys** (operator): D accepts, A rejects, W skips to the next card, S goes
back to the last card and undoes what happened to it: a decision is taken
back, a skip is reversed. Each further S steps one action further back,
down to the last release. The arrows keep working. Rejected: S undoing a
single step only.
2. **Release card** (operator): the same keys work on the release card of
040: D releases, A goes back to the stack, W skips on, S brings back the
last card.
3. **Endless round** (operator): W cycles through every open card, greyed
ones included, without end; while at least one decision waits, the
release card is one place in that round and comes up once per lap.
4. **Precedence**: on the Match screen W, A, S and D go to the deck before
any global key; in a text field they type as usual. The help (`?`) lists
them.
## Approach
```mermaid
flowchart TD
subgraph P["🧭 0 · Preparation"]
P1["📋 Write requirement"] --> P2{"✅ Operator approves?"}
P2 -- "✏️ corrections" --> P1
end
P2 -- "🤖 yes" --> A1
subgraph A["⌨️ A · WASD"]
A1["🧩 Keys to accept, reject, skip"] --> A2["↩️ Undo stack for S"]
A2 --> A3["🔁 Release card in the endless round"]
A3 --> A4["✍️ E2E test written"]
end
A4 --> C1
subgraph C["🧪 C · All of 039 to 055"]
C1["🧪 All tests once"] --> C2{"🟢 Green?"}
C2 -- "🔴 no: fix" --> C1
C2 -- "🟢 yes" --> CF{"💬 Operator feedback on screenshots?"}
CF -- "✏️ changes" --> A1
end
CF -- "👍 fits" --> D1["🏁 Review, commit with operator OK, hand-over"]
```
## Acceptance Criteria
### Keys
- [ ] D on the front card decides it as accept, A opens its reject feedback,
W puts it at the back; the arrows still do the same.
- [ ] After D, W, D, three S bring back the cards in reverse order, the two
decisions undone and the skipped card in front again.
- [ ] Typing W, A, S or D in a text field of the Match screen types the
letter and moves no card.
### Round
- [ ] With one decision made and two open cards, pressing W cycles card,
card, release card, card, and so on.
- [ ] On the release card D releases, A shows the stack, W shows the next
card, S brings back the last card.
### Tests
- [ ] Unit: n/a: page JS.
- [ ] Integration: n/a: no server change.
- [ ] E2E: the Keys and Round checks in Chromium; screenshots.
@@ -0,0 +1,57 @@
# 056 - Flowing Card Edge
## User Story
As the operator, I want the colour bar on top of a Match card to flow into
the card instead of sitting on it as a strip, so that the card reads as one
piece.
## Decisions (operator-confirmed 2026-11-25; do not re-litigate)
1. **Flowing bar** (operator, screenshot): the bar is full colour at the very
top edge and fades into the card head within 22 px, following the card's
rounded corners; the head's pattern fades in under it instead of starting
at a hard line. Rejected: today's 6 px strip with a hard lower edge.
2. **No scrollbar through the edge**: the card itself no longer scrolls, only
its body does, as 047 sets for Match cards; no scrollbar runs through the
top corner.
## Approach
```mermaid
flowchart TD
subgraph P["🧭 0 · Preparation"]
P1["📋 Write requirement"] --> P2{"✅ Operator approves?"}
P2 -- "✏️ corrections" --> P1
end
P2 -- "🤖 yes" --> A1
subgraph A["🌈 A · Card edge"]
A1["🧩 Bar as a fading overlay"] --> A2["📜 Only the body scrolls"]
A2 --> A3["✍️ E2E edge check updated"]
end
A3 --> C1
subgraph C["🧪 C · All of 039 to 056"]
C1["🧪 All tests once"] --> C2{"🟢 Green?"}
C2 -- "🔴 no: fix" --> C1
C2 -- "🟢 yes" --> CF{"💬 Operator feedback on screenshots?"}
CF -- "✏️ changes" --> A1
end
CF -- "👍 fits" --> D1["🏁 Review, commit with operator OK, hand-over"]
```
## Acceptance Criteria
### Edge
- [ ] The front card's `::before` is 22 px high, painted with the card's
gradient and masked from opaque at 0 px to transparent at 22 px.
- [ ] The head pattern's mask starts transparent at 0 px.
- [ ] The front card computes `overflow-y: hidden`; its `.match-body`
scrolls.
### Tests
- [ ] Unit: n/a: CSS.
- [ ] Integration: n/a: no server change.
- [ ] E2E: the edge check of `test_box_heads_e2e.py` asserts the Edge
checks for every pattern in Chromium and Firefox; screenshots.
@@ -0,0 +1,130 @@
# 057 - Schedules in Controls
## User Story
As the operator, I want one list of every automatic hook and timer in
Controls, so that I switch each one off or retime it with one click and
nothing spends tokens or machine time behind my back.
## Decisions (operator-confirmed 2026-11-25; do not re-litigate)
1. **Placement** (operator): a fourth Controls tab, Schedules, right of
Groups (`#stream/schedules`), also pinnable on Home. Rejected: a panel in
Resources; a section of the Settings sheet.
2. **Flag file** (operator): `<council>/schedules.json` is the one store of
the rows; the Schedules tab writes one row per change through
`POST /api/schedules`, and `schedules.py set` writes the same file on the
host. Every first-party hook and timer script reads it on each run. A
missing, linked or malformed file means the defaults. Rejected: adding and
removing hook entries in `~/.claude/settings.json` per toggle, which needs
a passkey-signed host writer. Amended during implementation (2026-11-25):
the first draft kept the rows in the hub settings and mirrored them to the
file, as `notify.json`; `/kvb-coach-on` (058) runs in an agent sandbox that
cannot reach the hub, and the next settings save would have overwritten
its change, so the file became the store. Amended 2026-11-25 after a
timing run: the hub keeps the store as `schedule_settings`, since a field
`schedules` shadowed `Sources.schedules(claims, now)`, the cron rows of
the event stream, and made every `/api/events` call fail.
3. **Rows** (operator): coach reminder (hook, every N hours, default 1, off),
dream reminder (hook, every N hours, default 12, off), dream popup (timer,
daily at HH:MM, default 17:00, off), queue cleanup (timer, list of HH:MM,
default 00:00 and 12:00, on), code graph (service, on or off, on), and
every other relevant entry found automatically: each further user timer
and each further hook command in `~/.claude/settings.json`. The hub's own
`kvb-orchestrator-*` units show read-only, because the hub needs them.
A foreign row shows its schedule and next run and offers its exact off
command to copy; the hub never switches a foreign unit.
4. **Host reconciler**: `kvb-org-organize/scripts/schedules.py`, started by
`kvb-schedules.path` (on a change of `schedules.json`) and
`kvb-schedules.timer` (every 5 minutes), writes
`<council>/schedules-view.json` (timers from `systemctl --user
list-timers --all --output=json`, hooks from `~/.claude/settings.json`)
and applies the first-party rows: `systemctl --user enable --now` or
`disable --now`, and a retime as the drop-in
`~/.config/systemd/user/<timer>.d/schedule.conf` with the validated
`OnCalendar`. Rejected: each script polling hourly, which cannot stop a
daemon and finds no foreign timer.
5. **Dream off by default** (operator): the dream reminder and the dream
popup start off, to save tokens; the installer copies the units and the
reconciler enables them only when switched on.
6. **No passkey**: a schedule switches an automation, not an alarm; the
MAYDAY and resource popups stay under 051. Residual: an agent that can
write the council directory can switch a first-party row, as with
`notify.json`.
## Approach
```mermaid
flowchart TD
subgraph P["🧭 0 · Preparation"]
P1["📋 Write requirement"] --> P2{"✅ Operator approves?"}
P2 -- "✏️ corrections" --> P1
end
P2 -- "🤖 yes" --> A1
subgraph A["🗓️ A · Schedules"]
A1["🧩 schedules setting + schedules.json"] --> A2["🛰️ schedules.py view + reconcile"]
A2 --> A3["🔌 coach, dream and cleanup scripts read the flags"]
A3 --> A4["🖥️ Controls tab Schedules"]
A4 --> A5["✍️ Tests written, not run"]
end
A5 --> C1
subgraph C["🧪 C · All of 057 and 058"]
C1["🧪 Unit, then e2e once"] --> C2{"🟢 Green?"}
C2 -- "🔴 no: fix" --> C1
C2 -- "🟢 yes" --> CF{"💬 Operator feedback on screenshots?"}
CF -- "✏️ changes" --> A1
end
CF -- "👍 fits" --> D1["🏁 Review, commit with operator OK, hand-over"]
```
## Acceptance Criteria
### Setting and file
- [ ] `schedules.ROWS` (hub) and `schedules.py` `ROWS` (host) hold the five
first-party rows with the defaults of decision 3; both `valid_row`
refuse an unknown row, an hour count outside 1 to 24, a time that is
not `HH:MM`, more than 6 cleanup times and a non-bool `on`.
- [ ] `POST /api/schedules` writes `<council>/schedules.json` with the changed
row and every other row as stored, and needs no passkey;
`schedules.py set` does the same on the host.
### Scripts
- [ ] The coach and dream `reminder.sh` print nothing while their row is off
or the file is missing, and use the row's hour count while on.
- [ ] `kvb-dream/hooks/notify.sh` sends no popup while the dream popup row is
off.
### Reconciler
- [ ] `schedules.py view` turns a fixture of `list-timers` JSON and a
settings file into rows: name, unit file, `OnCalendar`, next and last
run, owner `skills`, `hub` or `other`, and for hooks the event and
command.
- [ ] `schedules.py apply` calls exactly `enable --now` or `disable --now`
per first-party timer and service and writes the drop-in for a retime;
it never names a foreign or `kvb-orchestrator-*` unit.
- [ ] `scripts/install.sh` installs `kvb-schedules.path` and
`kvb-schedules.timer` and no longer enables `kvb-dream-notify.timer`.
### Controls tab
- [ ] Controls shows Tools, Rules, Groups, Schedules in that order;
`#stream/schedules` opens it.
- [ ] Each first-party row switches on or off and retimes; the change reaches
`schedules.json` after one click.
- [ ] Foreign and hub rows show their schedule and next run, have no switch,
and a foreign row offers its off command to copy.
- [ ] The Schedules panel pins on Home through the context menu (054).
### Tests
- [ ] Unit: row validation on both sides; `schedules.py view` and `apply`
against fixtures and a fake runner; both reminders and `notify.sh` with
the flag on, off and missing.
- [ ] Integration: a `HubCase` `POST /api/schedules` writes `schedules.json`
and the state carries the rows and the host view.
- [ ] E2E: Chromium at three widths: the tab order, a coach switch on and
off reaching the file, a dream popup retime reaching the file, a
foreign row without a switch, the pin on Home.
+96
View File
@@ -0,0 +1,96 @@
# 058 - Coach Repository
## User Story
As the operator, I want the coach in a repository of its own with commands
to switch it on and off, so that the skills repository stays lean and the
coach costs no tokens until I switch it on.
## Decisions (operator-confirmed 2026-11-25; do not re-litigate)
1. **Own repository** (operator): `github.com/kevinveenbirkenbach/coach`,
public, cloned at `~/Repositories/github.com/kevinveenbirkenbach/coach`.
`kvb-coach` (with `scripts/coach.py` and `hooks/reminder.sh`),
`kvb-coach-meditation` (with `scripts/meditation.py` and
`assets/meditation.html`) and their tests move there with their code. The
first commit names the skills commit they came from. Rejected: a private
repository, which needs `gh auth` on every host. Until the operator
creates the GitHub repository the clone is built in the gitignored
`.state/coach` of the skills repository, which the agent sandbox may
write; the lock entries follow the push, written by `npx skills add`,
which computes each `computedHash`.
2. **Commands** (operator): `/kvb-coach` coaches on demand as today;
`/kvb-coach-on` switches the hourly reminder on, `/kvb-coach-off` off;
`/kvb-coach-meditation` stays.
3. **Flag, not hook edits** (operator): on and off set the `coach` row of
`<council>/schedules.json` (057), the same row the Schedules tab switches.
The reminder hook stays registered and prints nothing while off. When the
hook is missing, `/kvb-coach-on` hands the operator the install command
instead of editing `~/.claude/settings.json`.
4. **Installed by default, off** (operator): `skills-lock.json` pins the four
coach skills at a commit of the coach repository; the installer registers
the reminder hook; the row starts off.
5. **Removed from skills**: `skills/kvb-coach*`, `tests/test_coach.py` and
`tests/test_meditation.py` leave the skills repository; every reference
in other skills, the README and the tests points to the coach repository.
## Approach
```mermaid
flowchart TD
subgraph P["🧭 0 · Preparation"]
P1["📋 Write requirement"] --> P2{"✅ Operator approves?"}
P2 -- "✏️ corrections" --> P1
end
P2 -- "🤖 yes" --> O1
subgraph O["🧑 O · Operator"]
O1["🌐 Create the public repo coach"] --> O2["🔓 Sandbox write for its clone"]
end
O2 --> A1
subgraph A["🧘 A · Coach repository"]
A1["📦 Move skills, code and tests"] --> A2["🔛 kvb-coach-on and kvb-coach-off"]
A2 --> A3["🔒 Lock entry in skills"] --> A4["🧹 Remove from skills"]
A4 --> A5["✍️ Tests written, not run"]
end
A5 --> C1
subgraph C["🧪 C · All of 057 and 058"]
C1["🧪 Unit, then e2e once"] --> C2{"🟢 Green?"}
C2 -- "🔴 no: fix" --> C1
C2 -- "🟢 yes" --> CF{"💬 Operator feedback?"}
CF -- "✏️ changes" --> A1
end
CF -- "👍 fits" --> D1["🏁 Review, commit and push with operator OK, hand-over"]
```
## Acceptance Criteria
### Coach repository
- [ ] The repository holds `skills/kvb-coach`, `skills/kvb-coach-on`,
`skills/kvb-coach-off`, `skills/kvb-coach-meditation`, `tests/`, a
README, the licence of the skills repository and a `make test` target.
- [ ] `coach.py schedule on` and `schedule off` write only the `coach` row
of `schedules.json` and keep every other row byte for byte.
- [ ] `reminder.sh` prints nothing while the row is off or the file is
missing.
### Skills repository
- [ ] `skills-lock.json` lists the four coach skills with `source`
`kevinveenbirkenbach/coach` and one commit; `make install` installs
them into `~/.claude/skills`.
- [ ] `git grep -n kvb-coach` in skills finds only the lock, the installer's
reminder list, the README pointer to the coach repository, the
`coach` row's hook path in `schedules.py` (057), the tests of those and
the CHANGELOG history. Amended during implementation (2026-11-25): the
first draft forgot the 057 row and the history.
- [ ] `skills/kvb-coach*`, `tests/test_coach.py` and `tests/test_meditation.py`
are gone.
### Tests
- [ ] Unit (coach repository): `test_coach.py` and `test_meditation.py`
moved; a test for `schedule on` and `off` and for the silent reminder.
- [ ] Integration: skills `test_install.py` checks the lock entries and the
registered reminder.
- [ ] E2E: n/a: no page change beyond the Schedules row of 057.
+91
View File
@@ -0,0 +1,91 @@
# 059 - Hub Poll Cost
## User Story
As the operator, I want the hub to rebuild and send only what changed, so
that an open page costs little CPU, memory and bandwidth.
## Decisions (operator-confirmed 2026-11-25; do not re-litigate)
1. **Register cache** (operator): `read_register` keeps the parsed
`rasci.json` keyed by its (inode, size, mtime_ns), as `History.rows`
does; one shared, read-only dict serves the state, the events, the rates
and the runner's previews.
2. **Unused fields go** (operator): the state drops `register`, which no
page module reads, and the radio rows' `speech`, which `word` and `rest`
already carry.
3. **Cached polls** (operator): `/api/state` without `to` shares
`live_state` by `from` rounded to the cache TTL and caches the encoded
bytes with the dict; `/api/events` answers 304 to an `If-None-Match`
that matches the window's digest; `drawStream` keeps its rows when the
shown ids are unchanged. Amended 2026-11-25 in the implementation: the
kept rows also need unchanged content and inbox items, since a review or
decision changes its status under the same id; only the polls skip, every
other redraw (a diff, a grant, a filter) still draws.
4. **Hidden tab** (operator): the sky, relayout and radio-sync intervals
skip while `document.hidden` and run once on `visibilitychange`; the
music graph stops while `musicLevel()` is 0 and restarts when it rises.
Amended 2026-11-25 in the implementation: the radio sync keeps switching
a playing station on its schedule in a hidden tab and skips only the
station drawing, since a station is mostly heard with the tab in the
background; the sky draws once on `visibilitychange` through the state
load the event already starts.
5. **Measured**: one state build and one events build are timed before and
after on the same council (`kvb-check-efficiency` velocity); the numbers go into the
hand-over. The skeptic's figures were estimates from file sizes.
Measured 2026-11-25 on a copy of the live council (3.4 MB `rasci.json`,
185 KB `news.jsonl`), HubCase with TTL 0, median of 10 polls:
`/api/state` 155.0 → 72.9 ms and 1,248,250 → 828,740 bytes,
`/api/events` 65.7 → 10.7 ms at 201,454 bytes. The run also found a
057 field shadowing the cron rows of `/api/events` (057 decision 2).
## Approach
```mermaid
flowchart TD
subgraph P["🧭 0 · Preparation"]
P1["📋 Write requirement"] --> P2{"✅ Operator approves?"}
P2 -- "✏️ corrections" --> P1
end
P2 -- "🤖 yes" --> A1
subgraph A["🖥️ A · Server"]
A1["⏱️ Time state and events builds"] --> A2["🗃️ Register cache"]
A2 --> A3["✂️ Drop register and speech"] --> A4["♻️ Shared builds and 304"]
end
A4 --> B1
subgraph B["🌙 B · Page"]
B1["🙈 Hidden-tab intervals"] --> B2["🔇 Music off at level 0"]
B2 --> B3["📜 Stream keeps unchanged rows"] --> B4["✍️ Tests written, not run"]
end
B4 --> C1
subgraph C["🧪 C · Verification"]
C1["🧪 Unit, then e2e once"] --> C2{"🟢 Green?"}
C2 -- "🔴 no: fix" --> C1
C2 -- "🟢 yes" --> CF{"💬 Operator feedback on screenshots?"}
CF -- "✏️ changes" --> A1
end
CF -- "👍 fits" --> D1["🏁 Review, commit with operator OK, hand-over"]
```
## Acceptance Criteria
### Server
- [ ] Two `/api/state` calls on an unchanged `rasci.json` parse it once.
- [ ] The state holds no `register` key and no radio row holds `speech`.
- [ ] Two polls within the TTL share one build and one encoding.
- [ ] `/api/events` with the current ETag answers 304 without a body.
### Page
- [ ] A hidden tab draws no sky for 60 s; `visibilitychange` draws once.
- [ ] Music level 0 stops the audio graph; a rise restarts it.
- [ ] `drawStream` replaces no row when the shown ids are unchanged.
### Tests
- [ ] Unit: the parse counter, the absent fields, the ETag and fake-timer
page probes.
- [ ] Integration: a `HubCase` state and events with and without changes.
- [ ] E2E: Chromium at three widths: Stream keeps its rows across polls,
a hidden tab stops the sky, the music stops at level 0.
@@ -0,0 +1,84 @@
# 060 - Host Hook and Timer Load
## User Story
As the operator, I want the skills' hooks and timers to start as few
processes as they need, so that agents and the machine stay fast.
## Decisions (operator-confirmed 2026-11-25; do not re-litigate)
1. **One dispatcher** (operator): `kvb-org-organize/scripts/hooks.py
pre-bash` and `post-bash` import radio, watch, queue, graph and log once
and run each handler in its own `try`; the first exit 2 wins;
`enable-plugins.js` registers it instead of the six Bash entries and
rewrites old ones. Each handler keeps its own script for direct calls.
Amended 2026-11-25 in the implementation: the radio block keeps its
entry for `Edit|Write|MultiEdit|NotebookEdit` and the code graph hook its
entry for `Read|Edit|Write|MultiEdit|NotebookEdit|Grep|Glob`, the tools
whose input names a path; a crash counts as exit 0 so the other handlers'
JSON answers survive.
2. **Runner ledger** (operator): a running job's output stays in memory or
in one file per job; `jobs.json` is written on a status change only;
finished and dismissed jobs are pruned; git toplevels are cached per
directory until HEAD, a ref or `packed-refs` moves; the previews poll
every 10 s, the jobs stay at 2 s.
3. **Token scan** (operator): resources `tokens` gets its own timer every
10 minutes; `sample` stays at 60 s and starts `queue.py` only while the
queue holds a waiting or active entry.
4. **Timers** (operator): the firewall view gets the tree heartbeat
`ExecCondition` and writes only on a change; the sessions snapshot runs
every 30 s and skips an unchanged write; the graph supervisor checks
every 120 s. Amended 2026-11-25 in the implementation: the firewall also
runs while a signed job waits; an unchanged sessions snapshot is still
rewritten every 120 s, since the hub drops one older than five minutes.
## Approach
```mermaid
flowchart TD
subgraph P["🧭 0 · Preparation"]
P1["📋 Write requirement"] --> P2{"✅ Operator approves?"}
P2 -- "✏️ corrections" --> P1
end
P2 -- "🤖 yes" --> A1
subgraph A["🪝 A · Hooks"]
A1["🔀 hooks.py dispatcher"] --> A2["🧩 enable-plugins.js rewrites the entries"]
end
A2 --> B1
subgraph B["⏲️ B · Runner and units"]
B1["📒 Ledger on status change"] --> B2["🌳 Cached git toplevels"]
B2 --> B3["🔟 Token timer, lean sample"] --> B4["🧭 Firewall, sessions, graph intervals"]
B4 --> B5["✍️ Tests written, not run"]
end
B5 --> C1
subgraph C["🧪 C · Verification"]
C1["🧪 Unit and integration"] --> C2{"🟢 Green?"}
C2 -- "🔴 no: fix" --> C1
C2 -- "🟢 yes" --> CF{"💬 Operator feedback?"}
CF -- "✏️ changes" --> A1
end
CF -- "👍 fits" --> D1["🏁 Review, commit with operator OK, hand-over"]
```
## Acceptance Criteria
### Hooks
- [ ] One Bash call starts one Python per hook event, counted by a fake
interpreter; every handler's exit 2 and output stay as before.
- [ ] A crash in one handler leaves the other handlers running.
### Runner and units
- [ ] A running job with output writes `jobs.json` 0 times until it ends.
- [ ] The unit files hold the intervals and conditions of decisions 3
and 4.
- [ ] `sample` with an empty queue starts no `queue.py`.
### Tests
- [ ] Unit: dispatcher order, exit codes and crash isolation; ledger
writes; `sample` without a queue; the unit file pins.
- [ ] Integration: `enable-plugins.js` rewrites the six Bash entries to
two.
- [ ] E2E: n/a: no page change.
@@ -0,0 +1,81 @@
# 061 - Bounded Council Files
## User Story
As the operator, I want the council files on hot paths to stay small and be
read only when they changed, so that every prompt and Bash call stays cheap
as the weeks pass.
## Decisions (operator-confirmed 2026-11-25; do not re-litigate)
1. **Queue histories** (operator): `kvb-org-queue-cleanup` trims both queue
histories to 30 days (`WINDOW_SECONDS`); `learned()` is memoized per
process on both files' (mtime_ns, size). Amended 2026-11-25 in the
implementation: the trim opens every round, before the chair check; a
line that is no history row stays, and rows appended during the rewrite
follow into the new file; the memo also keys on the inode and the
config's learning keys.
2. **Alerts** (operator): the `alerts.jsonl` read is skipped while its size
and mtime match the seen marker; rows past `ALERT_TTL` are dropped on
append; a memory stage is entered at once and left only after 2 samples
below it; "recovered" lines go to the chair only. Amended 2026-11-25 in
the implementation: the marker also holds the inode; an alert row carries
`chair`, and the disk "recovered" line is chair-only too.
3. **Mirror tail** (operator): the mirror stores the source's (inode, size)
and appends only the grown tail; a shrunk file or a new inode takes the
full merge. Amended 2026-11-25 in the implementation: the marker is
`.<name>.mirrored` beside the kept copy, and the stored size ends at the
last complete line, so a row still being written waits for the next
mirror. Amended 2026-11-25 after `make test`: an unchanged source is
skipped by the marker (same inode, marked size equal to its size), not
by an equal mtime; a copy created or a row appended in the source's
timestamp tick shared its mtime and lost those rows.
4. **Queue hold** (operator): the signal handler sets a `threading.Event`,
and a waiting hold waits on it for `POLL_SECONDS` instead of 0.2 s
ticks. Amended 2026-11-25 in the implementation: `Event.set()` inside a
signal handler can deadlock when the signal lands while the main thread
holds the event's lock in `Event.wait()`; the hold uses
`signal.set_wakeup_fd` on a pipe and `select` for `POLL_SECONDS`
instead, which wakes at once on a signal the same way.
## Approach
```mermaid
flowchart TD
subgraph P["🧭 0 · Preparation"]
P1["📋 Write requirement"] --> P2{"✅ Operator approves?"}
P2 -- "✏️ corrections" --> P1
end
P2 -- "🤖 yes" --> A1
subgraph A["🗄️ A · Files"]
A1["✂️ Trim queue histories"] --> A2["🧠 Memoized learned()"]
A2 --> A3["🚨 Alerts skip, TTL, hysteresis"] --> A4["🪞 Mirror tail"]
A4 --> A5["⏳ Event wait in the hold"] --> A6["✍️ Tests written, not run"]
end
A6 --> C1
subgraph C["🧪 C · Verification"]
C1["🧪 Unit and integration"] --> C2{"🟢 Green?"}
C2 -- "🔴 no: fix" --> C1
C2 -- "🟢 yes" --> CF{"💬 Operator feedback?"}
CF -- "✏️ changes" --> A1
end
CF -- "👍 fits" --> D1["🏁 Review, commit with operator OK, hand-over"]
```
## Acceptance Criteria
- [ ] A cleanup round leaves no history row older than 30 days and keeps
every newer row byte for byte.
- [ ] Ten prompts with an unchanged `alerts.jsonl` read it once.
- [ ] A memory value flapping around its threshold sends one alert per
stage change, not per sample; a non-chair gets no "recovered" line.
- [ ] A grown source mirrors only its new rows; a rewritten one merges.
- [ ] A waiting hold wakes at most once per `POLL_SECONDS` without a
signal, and at once on one.
### Tests
- [ ] Unit: trim, memo, alert skip and hysteresis, mirror tail and merge,
event wait.
- [ ] Integration: a cleanup round on a fixture council.
- [ ] E2E: n/a: no page change.
@@ -0,0 +1,98 @@
# 062 - Lean Agent Output
## User Story
As the operator, I want scripts and hooks to hand agents only what they
use, so that sessions spend fewer tokens and fewer turns.
## Decisions (operator-confirmed 2026-11-25; do not re-litigate)
1. **Short dumps** (operator): `rasci.py show` lists the top 30 by rank
plus "N more (show --all)", and the rasci skill summarizes instead of
reprinting; `radio.py show --since <duration> --summary` prints the
counts per class and peer and the last row of each; `kvb-org-matrix`
and the radio hint use it. Amended 2026-11-25 in the implementation: the
table keeps its two head lines and the gaps line, which names the shown
rows only, so 30 rows print at most 34 lines, 33 without a gap; the
radio hint reads `radio.py show --all --since 1d --summary`.
2. **Quieter hooks and tools** (operator): call receipts alone never exit 2
and ride the next context as "read by X HH:MM" without the text;
`enable-plugins.js` narrows the codebase-memory-mcp PreToolUse matcher to
`Grep|Glob` and drops its PostToolUse `Read` entry after the install;
`operator.py list` shows each command once and `add` dedupes by
directory and command; `security.py` prints `critical <n>` by default and
the skill drops `--json`. Amended 2026-11-25 in the implementation:
- Receipts alone wait at the Stop hook and ride the next prompt hook as
`MAIL CALL read by X HH:MM (your call of HH:MM)`; with a letter pending
the Stop mailbox takes them along, oldest first.
- `scripts/graph-hooks.js` narrows the graph hooks in
`~/.claude/settings.json` right after the codebase-memory-mcp installer
in `install.sh`: `enable-plugins.js` runs earlier and writes
`settings.local.json`, which never holds the installer's hooks. It also
drops the duplicate entries every reinstall adds; an entry mixing the
graph binary with another hook stays as it is.
- A second `add` of an open command in the same directory by another
session joins that row as one more A and keeps its session; the same
session may record one command for two steps on purpose, as the
existing operator tests do. `list` prints `step N` in the table and the
command once in its bash block.
- The line reads `🛡️ security <n> % critical <c> (medusa: ...)`.
3. **Trims** (operator): `budget.py` fails a `MEMORY.md` over 400 words; the
Capacity section of `kvb-org-organize` moves to `capacity.md`;
`kvb-check-speed` folds into `kvb-check-efficiency`; `kvb-skill-silence`
names the compact window `enable-plugins.js` writes (300000). Amended
2026-11-25 in the implementation: `budget.py --memory <path>` takes the
index, repeatable, a missing file counting as empty; `kvb-org-organize`
keeps a two-line Capacity pointer to `capacity.md`, and its schedules
moved into their own `## Schedules` section.
## Approach
```mermaid
flowchart TD
subgraph P["🧭 0 · Preparation"]
P1["📋 Write requirement"] --> P2{"✅ Operator approves?"}
P2 -- "✏️ corrections" --> P1
end
P2 -- "🤖 yes" --> A1
subgraph A["🤫 A · Output"]
A1["📋 Short rasci and radio dumps"] --> A2["📨 Receipts without a turn"]
A2 --> A3["🕸️ Narrow graph hooks"] --> A4["🧾 operator.py and security.py lines"]
end
A4 --> B1
subgraph B["✂️ B · Trims"]
B1["🧮 MEMORY.md cap"] --> B2["📦 Capacity to capacity.md"]
B2 --> B3["🔗 speed into efficiency"] --> B4["✍️ Tests written, not run"]
end
B4 --> C1
subgraph C["🧪 C · Verification"]
C1["🧪 Unit and integration"] --> C2{"🟢 Green?"}
C2 -- "🔴 no: fix" --> C1
C2 -- "🟢 yes" --> CF{"💬 Operator feedback?"}
CF -- "✏️ changes" --> A1
end
CF -- "👍 fits" --> D1["🏁 Review, commit with operator OK, hand-over"]
```
## Acceptance Criteria
- [ ] `rasci.py show` on 600 open rows without gaps prints at most 33
lines, the last `570 more (show --all)`.
- [ ] `radio.py show --summary` prints one line per class and peer.
- [ ] A batch of receipts alone exits 0 and prints nothing.
- [ ] After the install the graph hooks match `Grep|Glob` only and no
`Read` entry is left.
- [ ] `operator.py list` prints each command once; `add` twice keeps one
row.
- [ ] The default `security.py` output names the critical count in one
line.
- [ ] `budget.py` exits 1 on a 401-word `MEMORY.md`; `kvb-check-speed` is
gone and every reference points to `kvb-check-efficiency`.
### Tests
- [ ] Unit: each script output above; the `budget.py` memory cap.
- [ ] Integration: `graph-hooks.js` on a settings fixture with the graph
hooks (`tests/test_lean_output.py`); the naming test without
`kvb-check-speed`.
- [ ] E2E: n/a: no page change.
+83
View File
@@ -0,0 +1,83 @@
# 063 - One Commit Block
## User Story
As the operator, I want one script to build a commit's score table and
message block, so that a commit loads three skills instead of eleven.
## Decisions (operator-confirmed 2026-11-25; do not re-litigate)
1. **One script** (operator): `kvb-check-score/scripts/block.py --repo
<tree> --fix <n> --break <n>` runs `tokens.py`, `measure.py`, the speed
check, `security.py` (the critical count) and `gate.py status`, then
prints the commit table and the `--message-block` paragraph; its exit
codes are `score.py`'s (4 critical, 1 below 90/5, 3 ask again, 0 pass).
Amended 2026-11-25 in the implementation:
- `--base <ref>` is required as for every script it runs; `tokens.py`
runs on `--transcripts <dir>` (skill text changed, with `--saves` and
`--evidence` passed on as its `--value`), `measure.py` on
`-- <command...>` (runnable code changed), the higher tokens figure
counting when both ran; without either, tokens and velocity are `-`.
The speed check is `measure.py`'s velocity since 062 folded
`kvb-check-speed` into `kvb-check-efficiency`.
- Figures are read by their shape (`<n> %`, `new`, `<n> % critical <c>`,
`value <n:n>`), never by a label, so `labels.json` stays the one place
for labels.
- The output adds the `gate.py status` verdict between table and block,
and an `after the commit:` line with the `score.py --commit-table
--commit <hash>` call, so the table after the commit reuses the
measured figures instead of measuring again.
- A script that exits outside its result codes or prints no figure
stops the run with exit 2 and `block: <script> exited <code>: <last
line>` before anything is printed.
2. **Shorter chain**: `kvb-git-commit-no-verify` calls `block.py`;
`kvb-check-confidence` keeps the calibration rules; the score,
efficiency and security skills keep their scripts for direct use.
Amended 2026-11-25 in the implementation: `kvb-git-commit-next` and
`kvb-check-confidence` point to step 2 of `kvb-git-commit-no-verify`
instead of restating the chain, and `kvb-check-score` names `block.py`
in one sentence. The three skills count the scoring chain; the clean,
legal and hub-approval passes of step 1 and 3 stay their own concerns.
3. **Judgement stays**: fix confidence and break risk stay the agent's
inputs (`kvb-check-break-risk`); `block.py` never estimates them.
## Approach
```mermaid
flowchart TD
subgraph P["🧭 0 · Preparation"]
P1["📋 Write requirement"] --> P2{"✅ Operator approves?"}
P2 -- "✏️ corrections" --> P1
end
P2 -- "🤖 yes" --> A1
subgraph A["🧾 A · Commit block"]
A1["🧪 Golden output of today's chain"] --> A2["🧩 block.py"]
A2 --> A3["🔗 commit-no-verify calls it"] --> A4["✂️ confidence keeps calibration"]
A4 --> A5["✍️ Tests written, not run"]
end
A5 --> C1
subgraph C["🧪 C · Verification"]
C1["🧪 Unit and integration"] --> C2{"🟢 Green?"}
C2 -- "🔴 no: fix" --> C1
C2 -- "🟢 yes" --> CF{"💬 Operator feedback?"}
CF -- "✏️ changes" --> A1
end
CF -- "👍 fits" --> D1["🏁 Review, commit with operator OK, hand-over"]
```
## Acceptance Criteria
- [ ] `block.py` on a fixture repository prints the same table and block as
today's chain of single scripts (golden test).
- [ ] Its exit codes match `score.py`'s for a critical finding, a 90/5
miss, an over-budget ask and a pass.
- [ ] The commit path names `block.py` and loads at most three SKILL.md
files: commit-no-verify, confidence and break-risk.
### Tests
- [ ] Unit: the golden output, the exit codes, a failing sub-script named
(`tests/test_block.py`).
- [ ] Integration: `block.py` with fake tokens, measure, security and gate
scripts beside the real `score.py`.
- [ ] E2E: n/a: no page change.
+32
View File
@@ -35,3 +35,35 @@ skill defines the format.
- [029 - Controls Layout](029-controls-layout.md)
- [030 - Yes/No Answers as Buttons](030-yes-no-answers.md)
- [031 - Mic in Fields](031-mic-in-fields.md)
- [032 - Send in the Field](032-send-in-the-field.md)
- [033 - Coherent Speak Box](033-coherent-speak-box.md)
- [034 - Stream Head Band](034-stream-head-band.md)
- [035 - Match Full Width](035-match-full-width.md)
- [036 - Match Pile](036-match-pile.md)
- [037 - Home without Box](037-home-without-box.md)
- [038 - Badge to Match](038-badge-to-match.md)
- [039 - Match Rejects Survive](039-match-rejects-survive.md)
- [040 - Release Card](040-release-card.md)
- [041 - Code Marks in the Review Modal](041-review-code-marks.md)
- [042 - Why Deny Is Off](042-why-deny-is-off.md)
- [043 - Undo Window on a Clock](043-undo-window-clock.md)
- [044 - Widgets without Inner Boxes](044-widgets-without-inner-boxes.md)
- [045 - Artifacts Head on One Line](045-artifacts-head-one-line.md)
- [046 - Accept the Risk of a Red Gate](046-accept-red-gate-risk.md)
- [047 - One Code Box](047-one-code-box.md)
- [048 - Done Rows Greyed and Folded](048-done-rows-folded.md)
- [049 - One Control Height](049-one-control-height.md)
- [050 - Menus Stay Open](050-menus-stay-open.md)
- [051 - Radio Settings in the Device Card](051-radio-settings-in-device.md)
- [052 - Bubbles Beside the Modes](052-bubbles-beside-modes.md)
- [053 - Agent Settings on Every Face and Name](053-agent-settings-on-faces.md)
- [054 - Pin Only by Menu](054-pin-only-by-menu.md)
- [055 - WASD in Match](055-wasd-in-match.md)
- [056 - Flowing Card Edge](056-flowing-card-edge.md)
- [057 - Schedules in Controls](057-schedules-in-controls.md)
- [058 - Coach Repository](058-coach-repository.md)
- [059 - Hub Poll Cost](059-hub-poll-cost.md)
- [060 - Host Hook and Timer Load](060-host-hook-timer-load.md)
- [061 - Bounded Council Files](061-bounded-council-files.md)
- [062 - Lean Agent Output](062-lean-agent-output.md)
- [063 - One Commit Block](063-one-commit-block.md)
+10 -3
View File
@@ -45,12 +45,14 @@
~/.local/state/agents-council/resources.
--council: the council directory with queue.json and the claims.
--queue (sample): the installed kvb-org-queue queue.py, run with
AGENTS_COUNCIL_ROOT set to --council.
AGENTS_COUNCIL_ROOT set to --council while an entry waits or runs.
--transcripts (tokens): Claude Code's projects directory.
--proc, --sys (sample): where /proc and /sys are mounted.
Returns:
Runs on the host every minute through kvb-orchestrator-resources.timer,
Runs on the host, sample every minute through
kvb-orchestrator-resources.timer and tokens every 10 minutes through
kvb-orchestrator-tokens.timer,
because the hub's container sees neither the host's disks, memory and
GPUs nor its transcripts' offsets; nothing here calls a language model.
The exit code is 0.
@@ -331,7 +333,12 @@ def queue_view(council: Path, script: Path, run: Callable[[list[str]], str | Non
def queue_state(council: Path, script: Path, run: Callable[[list[str]], str | None]) -> dict:
return {**queue(council), **queue_view(council, script, run)}
"""Returns:
queue() with queue_view() added, which starts queue.py only while
an entry waits or runs.
"""
counts = queue(council)
return {**counts, **(queue_view(council, script, run) if counts["waiting"] or counts["active"] else {})}
def integers(value: object, size: int) -> bool:
+6 -3
View File
@@ -40,8 +40,8 @@ Returns:
changes without --rasci and --council or into a council that is a
symlink or another uid's, gate changes without --gates, and every other
job. Posts the last 200 output lines
back while it runs and the exit code at its end. Before every poll it
posts, for each open operator row that is a git merge of a full commit
back while it runs and the exit code at its end. Before a poll, at most
every PREVIEW_SECONDS, it posts, for each open operator row that is a git merge of a full commit
id (staged_diff.merge_of) whose HEAD differs from the preview the hub
holds, staged_diff.merge_preview, which its Match card shows; such a
merge whose job names the previewed HEAD is refused once HEAD moved. The
@@ -80,6 +80,7 @@ PREVIEWS = "/api/runner/previews"
ERROR_LIMIT = 500
PREVIEW_FAILURES = (OSError, ValueError, staged_diff.DiffError)
BEAT = 2.0
PREVIEW_SECONDS = 10.0
SAFE_PATH = "/usr/bin:/bin"
TASK_JOB = "task"
TASK_LIMIT = 30.0
@@ -461,8 +462,10 @@ def main() -> int:
trust = verifier.Trust(approvers=args.approvers, replay=args.replay, origin=signing.origin_of(args.port))
register = Register(rasci=args.rasci, council=args.council) if args.rasci and args.council else None
host = Host(shell=os.environ.get("SHELL") or pwd.getpwuid(os.geteuid()).pw_shell, operator=args.operator, council=args.council)
rules, told = staged_diff.rules_root(), ""
rules, told, previewed = staged_diff.rules_root(), "", None
while True:
if previewed is None or time.monotonic() - previewed >= PREVIEW_SECONDS:
previewed = time.monotonic()
try:
previews(base, rules)
told = ""
+20 -1
View File
@@ -10,7 +10,8 @@ Returns:
nor the host's processes: replaces --output with {"written": <epoch>,
"sessions": {<session id>: {"name", "status", "statusUpdatedAt",
"running"}}}, running being whether the record's pid still runs the
process it started. The exit code is 0.
process it started, unless it holds the same sessions written less than
REFRESH seconds ago. The exit code is 0.
"""
from __future__ import annotations
@@ -27,6 +28,7 @@ PROC = Path("/proc")
KEPT = ("name", "status", "statusUpdatedAt")
RECORD_BYTES = 65536
VALUE_CHARS = 200
REFRESH = 120
def read_record(path: Path) -> object:
@@ -96,7 +98,24 @@ def snapshot(folder: Path, proc: Path, now: float) -> dict:
}
def unchanged(output: Path, data: dict) -> bool:
"""Returns:
Whether output already holds data's sessions, written less than
REFRESH seconds before it; the hub counts a snapshot older than five
minutes as gone.
"""
try:
stored = json.loads(output.read_bytes())
except (OSError, ValueError, RecursionError):
return False
written = stored.get("written") if isinstance(stored, dict) else None
fresh = isinstance(written, int | float) and not isinstance(written, bool) and 0 <= data["written"] - written < REFRESH
return fresh and stored.get("sessions") == data["sessions"]
def write(output: Path, data: dict) -> None:
if unchanged(output, data):
return
with tempfile.NamedTemporaryFile("w", encoding="utf-8", dir=output.parent, prefix=f".{output.name}.", delete=False) as handle:
try:
json.dump(data, handle)
+11 -1
View File
@@ -408,14 +408,24 @@ def write_view(path: Path, view: dict) -> None:
verifier.private_dir(); a linked or foreign spool, or a write
that fails, prints one line and raises nothing, so an error of
the cycle before it still surfaces.
view: Writer.view().
view: Writer.view(); a stored view that differs only in "written"
stays.
"""
try:
with verifier.private_dir(path.parent, True) as folder:
if not same_view(folder, path.name, view):
verifier.write_at(folder, path.name, view)
except (signing.Refused, OSError) as error:
print(f"view not written: {error}", file=sys.stderr)
def same_view(folder: int, name: str, view: dict) -> bool:
try:
stored = json.loads(verifier.read_regular(name, folder))
except (OSError, ValueError, RecursionError):
return False
return isinstance(stored, dict) and {**stored, "written": None} == {**view, "written": None}
if __name__ == "__main__":
raise SystemExit(main())
+4
View File
@@ -230,6 +230,10 @@ def threshold_item(threshold: int) -> dict:
return {"kind": "speech-threshold", "threshold": threshold}
def popups_item(popups: dict) -> dict:
return {"kind": "popups", "popups": popups}
def task_item(task: str, argv: list[str]) -> dict:
return {"kind": "task", "id": task, "argv": argv}
+39 -1
View File
@@ -100,6 +100,8 @@ SAFE = (GIT, "--no-pager", "--no-lazy-fetch", "-c", "core.fsmonitor=false", "-c"
PASSED_ENV = ("HOME", "LANG", "LC_ALL", "LC_CTYPE")
FIXED_ENV = {"GIT_OPTIONAL_LOCKS": "0", "GIT_NO_LAZY_FETCH": "1", "GIT_CONFIG_NOSYSTEM": "1", "GIT_CONFIG_GLOBAL": os.devnull, "PATH": TRUSTED_PATH}
INTENT_TO_ADD = 0x20000000
TOPLEVELS: dict[str, tuple[Path, tuple]] = {}
TOPLEVELS_KEPT = 64
DEBUG_LINES = 5
NAMES_COMMIT = re.compile(r"(?<![\w.-])git(?![\w.-]).*(?<![\w-])commit(?![\w-])", re.DOTALL)
VERBS = ("commit", "commit-tree", "merge")
@@ -188,8 +190,44 @@ def blobs(cwd: Path, oids: set[str]) -> dict[str, bytes]:
return found
def stat_mark(path: Path) -> tuple[int, int] | None:
try:
found = os.stat(path)
except OSError:
return None
return found.st_ino, found.st_mtime_ns
def git_marks(top: Path) -> tuple:
"""Returns:
The (inode, mtime) of top's .git, its HEAD, packed-refs and
refs/heads, which change when the worktree, HEAD, a branch or
packed-refs moves; () when the .git file cannot be read.
"""
marker, gitdir = top / ".git", top / ".git"
try:
if marker.is_file():
gitdir = Path(os.path.realpath(top / marker.read_text(encoding="utf-8").strip().removeprefix("gitdir:").strip()))
common = Path(os.path.realpath(gitdir / (gitdir / "commondir").read_text(encoding="utf-8").strip())) if (gitdir / "commondir").is_file() else gitdir
except OSError:
return ()
return tuple(stat_mark(path) for path in (marker, gitdir / "HEAD", common / "packed-refs", common / "refs" / "heads"))
def toplevel(cwd: Path) -> Path:
return Path(os.path.realpath(git(cwd, ["rev-parse", "--show-toplevel"], None).decode("utf-8", "surrogateescape").strip()))
"""Returns:
The real path of cwd's worktree root, from git once per directory
until git_marks() of that root changes.
"""
key = os.path.realpath(cwd)
held = TOPLEVELS.get(key)
if held is not None and held[1] and held[1] == git_marks(held[0]):
return held[0]
top = Path(os.path.realpath(git(cwd, ["rev-parse", "--show-toplevel"], None).decode("utf-8", "surrogateescape").strip()))
if len(TOPLEVELS) >= TOPLEVELS_KEPT:
TOPLEVELS.clear()
TOPLEVELS[key] = (top, git_marks(top))
return top
def flagged(raw: bytes) -> list[tuple[bytes, int]]:
+10 -4
View File
@@ -7,11 +7,16 @@ from collections.abc import Callable
from .errors import Conflict, Missing
UNDO = 3.0
UNDO = 3
class Pending:
def __init__(self) -> None:
def __init__(self, window: Callable[[], float]) -> None:
"""Args:
window: returns the undo window in seconds the operator set, read
anew for every batch; a running batch keeps its due time.
"""
self.window = window
self.lock = threading.Lock()
self.batches: dict[str, dict] = {}
self.applied: set[str] = set()
@@ -28,9 +33,10 @@ class Pending:
The batch without its proof and timer.
"""
batch_id = secrets.token_hex(8)
timer = threading.Timer(UNDO, self.fire, args=(batch_id, apply))
window = self.window()
timer = threading.Timer(window, self.fire, args=(batch_id, apply))
timer.daemon = True
batch = {"id": batch_id, "items": items, "source": source, "due": time.time() + UNDO}
batch = {"id": batch_id, "items": items, "source": source, "due": time.time() + window}
with self.lock:
self.batches[batch_id] = {**batch, "proof": proof, "timer": timer}
timer.start()
+1 -1
View File
@@ -153,7 +153,7 @@ class Watch:
self.seen.setdefault(task, now)
if self.last is not None and self.last != tasks:
self.changes.extend(register_changes(self.last, tasks, now))
self.last = json.loads(json.dumps(tasks))
self.last = tasks
def first(self, task: str, now: float) -> float:
with self.lock:
+21 -1
View File
@@ -1,5 +1,6 @@
from __future__ import annotations
import hashlib
import json
import re
from collections.abc import Callable
@@ -15,6 +16,7 @@ GUARD = "X-Kvb-Orchestrator"
PLAIN_CSP = "default-src 'none'; frame-ancestors 'none'"
LENGTH = re.compile(r"[0-9]{1,9}")
QUERY_FIELDS = 32
TAG_LENGTH = 32
class HubServer(ThreadingHTTPServer):
@@ -46,7 +48,25 @@ class Exchange(BaseHTTPRequestHandler):
self.send(status, "text/plain; charset=utf-8", f"{message}\n".encode(), {"Content-Security-Policy": PLAIN_CSP})
def send_json(self, status: HTTPStatus, payload: dict) -> None:
self.send(status, "application/json", json.dumps(payload).encode(), {"Content-Security-Policy": PLAIN_CSP})
self.send_body(status, json.dumps(payload).encode())
def send_body(self, status: HTTPStatus, body: bytes) -> None:
self.send(status, "application/json", body, {"Content-Security-Policy": PLAIN_CSP})
def send_tagged(self, payload: dict) -> None:
"""Args:
payload: the answer; its digest is the ETag, and a request whose
If-None-Match names it gets 304 without a body.
"""
body = json.dumps(payload).encode()
tag = f'"{hashlib.sha256(body).hexdigest()[:TAG_LENGTH]}"'
if self.headers.get_all("If-None-Match") == [tag]:
self.send_response(HTTPStatus.NOT_MODIFIED)
self.send_header("ETag", tag)
self.send_header("Cache-Control", "no-store")
self.end_headers()
return
self.send(HTTPStatus.OK, "application/json", body, {"Content-Security-Policy": PLAIN_CSP, "ETag": tag})
def not_allowed(self) -> None:
self.send_response(HTTPStatus.METHOD_NOT_ALLOWED)
+6 -3
View File
@@ -81,7 +81,8 @@ FIREWALL_STATUS = {"settings_preview": HTTPStatus.OK, "change_settings": HTTPSta
WAV_POSTS = (STT_ROUTE, VOICE_ROUTE)
ACCOUNTS_ROUTE = "/api/accounts"
ACCOUNT_DROP = re.compile(r"/api/accounts/([0-9a-f]{16})/delete")
ACTION_POSTS = (ACCOUNTS_ROUTE, "/api/rules", "/api/nl", SETTINGS_ROUTE, TTS_ROUTE, STT_ROUTE, SIGN_ROUTE, RULE_SIGN_ROUTE, CLEANUP_ROUTE, OFFICES_ROUTE, TASKS_ROUTE, VOICE_ROUTE, MESSAGE_SIGN_ROUTE, SETTINGS_SIGN_ROUTE, CHOICES_ROUTE, CHOICES_SIGN_ROUTE, GATES_ROUTE, TOKEN_ROUTE, *FIREWALL_POSTS)
SCHEDULES_ROUTE = "/api/schedules"
ACTION_POSTS = (ACCOUNTS_ROUTE, SCHEDULES_ROUTE,"/api/rules", "/api/nl", SETTINGS_ROUTE, TTS_ROUTE, STT_ROUTE, SIGN_ROUTE, RULE_SIGN_ROUTE, CLEANUP_ROUTE, OFFICES_ROUTE, TASKS_ROUTE, VOICE_ROUTE, MESSAGE_SIGN_ROUTE, SETTINGS_SIGN_ROUTE, CHOICES_ROUTE, CHOICES_SIGN_ROUTE, GATES_ROUTE, TOKEN_ROUTE, *FIREWALL_POSTS)
class Handler(Exchange):
@@ -133,11 +134,11 @@ class Handler(Exchange):
elif proof:
self.answer(lambda: hub.review_proof(proof.group(1)), HTTPStatus.OK)
elif path == "/api/state":
self.answer(lambda: hub.window(self.query()), HTTPStatus.OK)
self.attempt(lambda: hub.window(self.query()), lambda body: self.send_body(HTTPStatus.OK, body))
elif path == "/api/stream":
self.answer(lambda: hub.stream(self.query()), HTTPStatus.OK)
elif path == "/api/events":
self.answer(lambda: hub.events(self.query()), HTTPStatus.OK)
self.attempt(lambda: hub.events(self.query()), self.send_tagged)
elif path == "/api/tree":
self.answer(hub.repositories, HTTPStatus.OK)
elif path == "/api/skills":
@@ -194,6 +195,8 @@ class Handler(Exchange):
return lambda body: self.answer(lambda: hub.accounts.save(body), HTTPStatus.OK)
if drop:
return lambda _body: self.answer(lambda: hub.accounts.drop(drop.group(1)), HTTPStatus.OK)
if path == SCHEDULES_ROUTE:
return lambda body: self.answer(lambda: hub.schedule_settings.save(body), HTTPStatus.OK)
reveal = REVEAL_ROUTE.fullmatch(path)
if reveal:
method = hub.sign_reveal if reveal.group(3) else hub.reveal
+4 -1
View File
@@ -53,6 +53,7 @@ from .resources import RESOURCES, SAMPLES
from .revealing import Revealing
from .reviewing import Reviewing
from .rules import Offers, Rules
from .schedules import Schedules
from .settings import Settings
from .signed import signing
from .skill_scripts import Runner
@@ -142,6 +143,7 @@ class Hub(Mcp, Reviewing, Revealing, Asking, Messaging, Choosing, Approving, Den
merge_previews: Ledger
live_state: LiveState
accounts: Accounts
schedule_settings: Schedules
def hosts(self) -> tuple[str, str]:
return f"127.0.0.1:{self.public_port}", f"localhost:{self.public_port}"
@@ -211,6 +213,7 @@ def open_hub(council: Path, pages: Path, public_port: int, state: Path, host_sta
replay=state / "replay" / "messages.json",
view_store=ViewStore(state / "view.json"),
accounts=Accounts(state, places.kept, council),
schedule_settings=Schedules(council),
match_snapshots=Ledger(state / "match.json"),
merge_previews=Ledger(state / "previews.json"),
live_state=LiveState(live_ttl),
@@ -219,7 +222,7 @@ def open_hub(council: Path, pages: Path, public_port: int, state: Path, host_sta
jobs=Ledger(state / "jobs.json"),
marks=Marks(state / "marks.json"),
log=Log(state / "log.jsonl"),
batches=Pending(),
batches=Pending(lambda: settings.undo()),
names=Names(state / "names.json"),
receipt_names=ReceiptNames(state / NAMES),
receipt_reads=ReceiptReads(state / READS),
+4 -1
View File
@@ -94,7 +94,10 @@ class Jobs:
raise Missing(job_id)
if record["status"] in JOB_OPEN:
raise Conflict({"id": job_id, "status": record["status"]})
if record.get("kind") in CHANGES:
self.jobs.change(job_id, {"dismissed": True})
else:
self.jobs.keep(lambda job: job.get("kind") in CHANGES or job["status"] in JOB_OPEN or (job["task"] != record["task"] and job.get("dismissed") is not True))
return {"id": job_id, "dismissed": True}
def queue_job(self, item: dict, proof: dict | None) -> str:
@@ -139,7 +142,7 @@ class Jobs:
if record["status"] != "running":
raise Conflict({"id": job_id, "status": record["status"]})
if code is None and not refused:
self.jobs.change(job_id, {"output": output})
self.jobs.note(job_id, {"output": output})
return {"id": job_id, "status": "running", "code": None}
status = "refused" if refused else "done" if code == 0 else "failed"
job, changed = self.jobs.transition(job_id, "running", {"status": status, "code": code, "output": output, "finished": time.time()})
+18
View File
@@ -87,6 +87,24 @@ class Ledger:
self.write({**self.items, item_id: updated})
return dict(updated)
def note(self, item_id: str, changes: dict) -> dict | None:
"""Returns:
The record with changes applied in memory only; the next write of
any record stores them, a restart before it loses them.
"""
with self.changed:
record = self.items.get(item_id)
if record is None:
return None
self.items = {**self.items, item_id: {**record, **changes}}
return dict(self.items[item_id])
def keep(self, wanted: Callable[[dict], bool]) -> None:
with self.changed:
kept = {key: record for key, record in self.items.items() if wanted(record)}
if len(kept) != len(self.items):
self.write(kept)
def remove(self, item_id: str) -> bool:
with self.changed:
if item_id not in self.items:
+25 -4
View File
@@ -1,5 +1,6 @@
from __future__ import annotations
import json
import threading
import time
from collections.abc import Callable
@@ -16,19 +17,35 @@ class LiveState:
self.ttl = ttl
self.guard = threading.Lock()
self.locks: dict[object, threading.Lock] = {}
self.built: dict[object, tuple[int, float, dict]] = {}
self.built: dict[object, tuple[int, float, dict, bytes]] = {}
self.generation = 0
def invalidate(self) -> None:
with self.guard:
self.generation += 1
def slot(self, moment: float) -> float:
"""Returns:
moment rounded down to a multiple of ttl, so polls whose window
starts within one ttl share a key; moment itself for a zero ttl.
"""
return moment - moment % self.ttl if self.ttl > 0 else moment
def shared(self, key: object, build: Callable[[], dict]) -> dict:
"""Returns:
build()'s result; callers arriving while it runs wait for it and
share it, and so do callers within ttl after it, until
invalidate() is called.
"""
return self.entry(key, build)[0]
def encoded(self, key: object, build: Callable[[], dict]) -> bytes:
"""Returns:
The JSON bytes of shared(key, build), encoded once per build.
"""
return self.entry(key, build)[1]
def entry(self, key: object, build: Callable[[], dict]) -> tuple[dict, bytes]:
with self.guard:
lock = self.locks.setdefault(key, threading.Lock())
with lock:
@@ -36,8 +53,12 @@ class LiveState:
generation = self.generation
hit = self.built.get(key)
if hit is not None and hit[0] == generation and time.monotonic() - hit[1] < self.ttl:
return hit[2]
return hit[2], hit[3]
value = build()
body = json.dumps(value).encode()
with self.guard:
self.built[key] = (generation, time.monotonic(), value)
return value
at = time.monotonic()
self.built = {old: found for old, found in self.built.items() if at - found[1] < self.ttl}
self.built[key] = (generation, at, value, body)
self.locks = {old: held for old, held in self.locks.items() if old in self.built}
return value, body
+26 -7
View File
@@ -1,5 +1,7 @@
from __future__ import annotations
import os
import threading
from pathlib import Path
from .council import HUMAN, agent, ordered
@@ -12,13 +14,34 @@ REGISTER = "rasci.json"
AGENT_ORDER = "agent-order.json"
OPERATOR = "operator/"
ENDED = ("done", "stopped")
PARSED_KEPT = 8
parsed: dict[Path, tuple[tuple[int, int, int], dict[str, dict]]] = {}
parsed_lock = threading.Lock()
def read_register(path: Path) -> dict[str, dict]:
data = read_json(path)
if not isinstance(data, dict):
"""Returns:
The task rows of the register, parsed again only when its inode, size
or mtime changed; a fresh top-level dict per call whose rows are
shared between callers and read only.
"""
try:
info = os.lstat(path)
except OSError:
return {}
return {task: row for task, row in data.items() if isinstance(row, dict)}
stamp = (info.st_ino, info.st_size, info.st_mtime_ns)
with parsed_lock:
found = parsed.get(path)
if found is not None and found[0] == stamp:
return dict(found[1])
data = read_json(path)
rows = {task: row for task, row in data.items() if isinstance(row, dict)} if isinstance(data, dict) else {}
with parsed_lock:
parsed.pop(path, None)
parsed[path] = (stamp, rows)
while len(parsed) > PARSED_KEPT:
parsed.pop(next(iter(parsed)))
return dict(rows)
def status_of(row: dict) -> str:
@@ -128,10 +151,6 @@ def register_row(task: str, row: dict) -> dict:
}
def register_rows(tasks: dict[str, dict]) -> list[dict]:
return [register_row(task, row) for task, row in sorted(tasks.items(), key=pinned) if is_open(task, row, False)]
def stored_order(path: Path) -> list[str]:
data = read_json(path)
names = data.get("agents") if isinstance(data, dict) else None
+112
View File
@@ -0,0 +1,112 @@
from __future__ import annotations
import json
from pathlib import Path
from .errors import ToolError
from .fields import decode
from .records import read_json, write_atomic
from .settings import CLOCK, flag, section
SCHEDULES = "schedules.json"
SCHEDULES_VIEW = "schedules-view.json"
ROWS = {
"coach": {"on": False, "every": 1},
"dream": {"on": False, "every": 12},
"dream-popup": {"on": False, "at": ["17:00"]},
"queue-cleanup": {"on": True, "at": ["00:00", "12:00"]},
"code-graph": {"on": True},
}
HOURS = (1, 24)
TIMES_LIMIT = 6
VIEW_LIMIT = 200
VIEW_TEXT = 2000
VIEW_KEYS = ("name", "kind", "owner", "unit", "file", "schedule", "next", "last", "event", "command", "off")
def valid_row(name: object, value: object) -> dict:
"""Args:
name: one of ROWS.
value: the row: on, plus every (hours from 1 to 24) for a reminder
hook or at (1 to TIMES_LIMIT distinct HH:MM) for a timer.
Returns:
The row, times sorted.
"""
if not isinstance(name, str) or name not in ROWS:
raise ToolError(f"no such schedule: {name}")
row = section(value, str(name), tuple(ROWS[name]))
found = {"on": flag(row["on"], f"{name}.on")}
if "every" in row:
every = row["every"]
if isinstance(every, bool) or not isinstance(every, int) or not HOURS[0] <= every <= HOURS[1]:
raise ToolError(f"{name}.every must be a whole number of hours from {HOURS[0]} to {HOURS[1]}")
found["every"] = every
if "at" in row:
times = row["at"]
if not isinstance(times, list) or not 1 <= len(times) <= TIMES_LIMIT or not all(isinstance(time, str) and CLOCK.fullmatch(time) for time in times):
raise ToolError(f"{name}.at must hold 1 to {TIMES_LIMIT} times like 17:00")
if len(set(times)) != len(times):
raise ToolError(f"{name}.at names a time twice")
found["at"] = sorted(times)
return found
def stored_rows(council: Path) -> dict:
"""Returns:
Every row of ROWS from schedules.json; a missing, linked or malformed
file, or a malformed row, gives that row's default.
"""
data = read_json(council / SCHEDULES)
rows = {}
for name, default in ROWS.items():
try:
rows[name] = valid_row(name, data[name])
except (ToolError, KeyError, TypeError):
rows[name] = default
return rows
def view_rows(council: Path) -> dict:
"""Returns:
{at, rows}: what the host reconciler last saw, each row with the
VIEW_KEYS as strings or numbers; {at: None, rows: []} before its first
run or for a malformed file.
"""
data = read_json(council / SCHEDULES_VIEW)
rows = data.get("rows") if isinstance(data, dict) else None
at = data.get("at") if isinstance(data, dict) else None
if not isinstance(rows, list) or isinstance(at, bool) or not isinstance(at, int | float):
return {"at": None, "rows": []}
kept = []
for row in rows[:VIEW_LIMIT]:
if isinstance(row, dict) and isinstance(row.get("name"), str):
kept.append({key: shown(row.get(key)) for key in VIEW_KEYS})
return {"at": at, "rows": kept}
def shown(value: object) -> str | float | None:
if isinstance(value, str):
return value[:VIEW_TEXT]
if isinstance(value, int | float) and not isinstance(value, bool):
return value
return None
class Schedules:
def __init__(self, council: Path) -> None:
self.council = council
def view(self) -> dict:
return {"rows": stored_rows(self.council), "host": view_rows(self.council)}
def save(self, body: bytes) -> dict:
"""Args:
body: {row, value}: one row of ROWS and its new value; every
other row keeps its stored value.
"""
data = section(decode(body), "body", ("row", "value"))
rows = {**stored_rows(self.council), data["row"]: valid_row(data["row"], data["value"])}
self.council.mkdir(parents=True, exist_ok=True)
write_atomic(self.council / SCHEDULES, json.dumps(rows, sort_keys=True).encode())
return self.view()
+55 -1
View File
@@ -7,6 +7,7 @@ import threading
from pathlib import Path
from urllib.parse import urlsplit
from .batches import UNDO
from .errors import ToolError
from .fields import FIELDS, NAME_LIMIT, expect
from .rates import METRICS, PERIOD_NAMES
@@ -19,7 +20,13 @@ TRENDS = ("off", "regression", "velocity")
TREND_DAYS = (1, 365)
THRESHOLDS = tuple(range(0, ALWAYS + 1, 10))
WPM = (5, 40)
LATE = ("rates", "morse")
LATE = ("rates", "morse", "undo", "popups", "agents")
AGENT_SWITCHES = ("sound", "aloud", "bubbles")
AGENTS_LIMIT = 200
UNDO_RANGE = (0, 60)
POPUP_SOURCES = ("resources", "mayday", "dream")
POPUP_UNTIL = 4102444800
NOTIFY = "notify.json"
RADIO_MOVED = ("sounds", "squelch")
SPEECH_MOVED = ("on", "classes", "muted")
COLOR = re.compile(r"#[0-9a-f]{6}")
@@ -49,6 +56,9 @@ SETTINGS = {
"trend": {"mode": "off", "days": 7},
"bubbles": False,
"rates": {"period": "hour", "metrics": ["tasks", "tokens", "cpu"]},
"undo": UNDO,
"popups": {source: {"on": True, "until": 0} for source in POPUP_SOURCES},
"agents": {},
}
RATE_CHIP = (2, 9)
SPACE_AXES = ("none", "time", "spawn")
@@ -188,6 +198,43 @@ def trend_setting(raw: object) -> dict:
return {"mode": entry["mode"], "days": entry["days"]}
def undo_setting(raw: object) -> int:
low, high = UNDO_RANGE
if isinstance(raw, bool) or not isinstance(raw, int) or not low <= raw <= high:
raise ToolError(f"undo must be whole seconds from {low} to {high}")
return raw
def popups_setting(raw: object) -> dict:
data = section(raw, "popups", POPUP_SOURCES)
popups = {}
for source in POPUP_SOURCES:
entry = section(data[source], f"popups.{source}", ("on", "until"))
until = entry["until"]
if isinstance(until, bool) or not isinstance(until, int) or not 0 <= until <= POPUP_UNTIL:
raise ToolError(f"popups.{source}.until must be whole epoch seconds from 0 to {POPUP_UNTIL}")
popups[source] = {"on": flag(entry["on"], f"popups.{source}.on"), "until": until}
return popups
def agents_setting(raw: object) -> dict:
"""Returns:
Each agent key with its sound, aloud and bubbles switches; an entry
with all three on is dropped, since on is what an absent agent gets.
"""
if not isinstance(raw, dict) or len(raw) > AGENTS_LIMIT:
raise ToolError(f"agents must be an object of at most {AGENTS_LIMIT} agents")
agents = {}
for key, entry in raw.items():
if not 0 < len(key) <= NAME_LIMIT:
raise ToolError(f"agents keys must be 1 to {NAME_LIMIT} characters")
switches = section(entry, f"agents.{key}", AGENT_SWITCHES)
kept = {name: flag(switches[name], f"agents.{key}.{name}") for name in AGENT_SWITCHES}
if not all(kept.values()):
agents[key] = kept
return agents
def rates_setting(raw: object) -> dict:
entry = section(raw, "rates", tuple(SETTINGS["rates"]))
low, high = RATE_CHIP
@@ -224,6 +271,9 @@ def valid_settings(raw: object) -> dict:
"trend": trend_setting(data["trend"]),
"bubbles": flag(data["bubbles"], "bubbles"),
"rates": rates_setting(data["rates"]),
"undo": undo_setting(data["undo"]),
"popups": popups_setting(data["popups"]),
"agents": agents_setting(data["agents"]),
}
@@ -306,6 +356,10 @@ class Settings:
with self.lock:
return copy.deepcopy(self.current)
def undo(self) -> float:
with self.lock:
return float(self.current["undo"])
def put(self, raw: object, expected: dict) -> dict:
"""Args:
raw: the settings to save.
+27 -15
View File
@@ -1,5 +1,6 @@
from __future__ import annotations
import json
import time
from .asking import ask_row, decision_row
@@ -25,22 +26,21 @@ from .graph import graph
from .jobs import JOB_OPEN
from .messaging import message_row
from .orbits import TRACK_STEPS, track
from .phrasing import joined, phrase_parts
from .phrasing import phrase_parts
from .presence import presence, read_snapshot
from .queue_order import grant_order, live_ids
from .receipts import inline, read_of
from .records import epoch, iso_epoch, read_jsonl
from .records import epoch, iso_epoch, read_jsonl, write_atomic
from .register import (
AGENT_ORDER,
REGISTER,
agent_order,
operator_rows,
read_register,
register_rows,
stored_order,
)
from .reviewing import review_row
from .settings import completed, media_origins, station_origins, valid_settings
from .settings import NOTIFY, completed, media_origins, station_origins, valid_settings
from .signed import signing
from .skill_scripts import OUTPUT_LIMIT
from .tasks import queue_chain, queue_line, task_edges, task_rows
@@ -76,14 +76,21 @@ class View:
raise ToolError("from must not lie after to")
return begin, end
def window(self, query: dict[str, list[str]]) -> dict:
def window(self, query: dict[str, list[str]]) -> bytes:
"""Returns:
The encoded state of the window; a live window, one without
`to`, is shared with every poll whose `from` falls into the same
live_state slot.
"""
sampled = single(query, "track")
if sampled not in (None, "1"):
raise ToolError("track must be 1 or left out")
self.tree.beat()
if "from" in query or "to" in query:
return self.built(query, sampled)
return self.live_state.shared(sampled, lambda: self.built(query, sampled))
if "to" in query:
return json.dumps(self.built(query, sampled)).encode()
begin, _ = self.span(query, time.time())
key = (sampled, None if "from" not in query else self.live_state.slot(begin))
return self.live_state.encoded(key, lambda: self.built(query, sampled))
def built(self, query: dict[str, list[str]], sampled: str | None) -> dict:
now = time.time()
@@ -122,7 +129,7 @@ class View:
called = [directory.at(key, row["ts"]) or name for key, name in zip(targets, row["to"], strict=True)]
speaker = directory.at(source, row["ts"]) or row["from"]
word, rest = phrase_parts(row["class"], speaker, called, row["text"])
spoken = {"speech": joined((word, rest)), "word": word, "rest": rest, "voice": self.speech.voice_of(source), "pitch": pitch_of(source), **sound_of(source), "speaker": speaker, "called": called}
spoken = {"word": word, "rest": rest, "voice": self.speech.voice_of(source), "pitch": pitch_of(source), **sound_of(source), "speaker": speaker, "called": called}
read = read_of(inlined, row["ts"])
radio.append({**row, "source": source, "targets": targets, "now": directory.now(source), **spoken, **read})
grant_rows = [{**grant, "target": directory.key(grant["to"], grant["ts"])} for grant in grants(history, (begin, end), claims, tasks)]
@@ -142,6 +149,7 @@ class View:
stored = self.messages.listed()
return {
"settings": settings,
"schedules": self.schedule_settings.view(),
"media": media_origins(settings),
"speech": {**self.speech.describe(), "gate": self.speech_gate.state()},
"people": people,
@@ -165,7 +173,6 @@ class View:
"messages": [{**message_row(message), **read_of(inlined, epoch(message.get("relay_ts")))} for message in stored if begin <= message["created_ts"] <= end],
"reasons": recent_reasons(stored),
"operator": operator_rows(tasks),
"register": register_rows(tasks),
"tasks": rows,
"task_edges": task_edges(rows, chain),
"queue_line": queue_line(chain, queue),
@@ -190,14 +197,16 @@ class View:
The items the operator's passkey signs for this save: the station
origins and the new urls when the settings name a stream url the
saved ones do not, and the speech threshold when it differs from
the saved one, since the hub's speech gate enforces it. The hub
dials no url before it is signed, and resolves its redirect
targets only after the signature.
the saved one, since the hub's speech gate enforces it, and the
desktop popups when they differ, since muting one silences an
alarm outside the page. The hub dials no url before it is signed,
and resolves its redirect targets only after the signature.
"""
urls = sorted({stream["url"] for stream in settings["streams"]} - {stream["url"] for stream in saved["streams"]})
threshold = settings["speech"]["threshold"]
streams = [signing.stream_item(station_origins(settings), urls)] if urls else []
return streams + ([signing.threshold_item(threshold)] if threshold != saved["speech"]["threshold"] else [])
speech = [signing.threshold_item(threshold)] if threshold != saved["speech"]["threshold"] else []
return streams + speech + ([signing.popups_item(settings["popups"])] if settings["popups"] != saved["popups"] else [])
def resolved(self, settings: dict, saved: dict) -> tuple[dict, list[str]]:
"""Args:
@@ -258,7 +267,10 @@ class View:
for change in self.signed_changes(settings, saved):
self.operator_proven(proof, change)
resolved, problems = self.resolved(settings, saved)
return {"settings": self.settings.put(resolved, saved), "problems": problems}
stored = self.settings.put(resolved, saved)
self.council.mkdir(parents=True, exist_ok=True)
write_atomic(self.council / NOTIFY, json.dumps(stored["popups"], sort_keys=True).encode())
return {"settings": stored, "problems": problems}
def render(self, nonce: str) -> tuple[str, str]:
now = time.time()
@@ -5,5 +5,6 @@ Description=Agent Orchestrator firewall: verify the operator signature, then wri
Type=oneshot
Environment=PATH=/usr/bin:/bin
EnvironmentFile=%h/.local/share/kvb-orchestrator/.env
ExecCondition=/bin/sh -c 'test -n "$(find %h/.local/state/kvb-orchestrator/tree-heartbeat -mmin -5 2>/dev/null)" || test -n "$(ls -A %h/.local/state/kvb-orchestrator/firewall/jobs 2>/dev/null)"'
ExecStart=/usr/bin/env python3 %h/.local/share/kvb-orchestrator/client/settings_writer.py --port ${KVB_ORCHESTRATOR_PORT} --jobs %h/.local/state/kvb-orchestrator/firewall/jobs --results %h/.local/state/kvb-orchestrator/firewall/results --view %h/.local/state/kvb-orchestrator/firewall/view.json --approvers %h/.config/kvb-orchestrator/approvers.json --replay %h/.local/state/kvb-orchestrator-approvals/firewall.json --tree %h/.local/state/pkgmgr/tree/branch-tree.json
TimeoutStartSec=120
@@ -1,12 +1,11 @@
[Unit]
Description=Agent Orchestrator resources: disks, CPU, RAM, swap, load, GPU, the queue and the transcripts' tokens, into the files the orchestrator reads
Description=Agent Orchestrator resources: disks, CPU, RAM, swap, load, GPU and the queue, into the files the orchestrator reads
[Service]
Type=oneshot
Environment=PATH=/usr/bin:/bin
EnvironmentFile=%h/.local/share/kvb-orchestrator/.env
ExecStart=/usr/bin/env python3 %h/.local/share/kvb-orchestrator/client/resources.py sample --state ${KVB_ORCHESTRATOR_KEPT}/resources --council ${KVB_ORCHESTRATOR_COUNCIL} --proc /proc --sys /sys --queue ${KVB_ORCHESTRATOR_SKILLS}/kvb-org-queue/scripts/queue.py
ExecStart=/usr/bin/env python3 %h/.local/share/kvb-orchestrator/client/resources.py tokens --state ${KVB_ORCHESTRATOR_KEPT}/resources --council ${KVB_ORCHESTRATOR_COUNCIL} --transcripts ${KVB_ORCHESTRATOR_PROJECTS}
Nice=10
IOSchedulingClass=idle
TimeoutStartSec=300
@@ -1,9 +1,9 @@
[Unit]
Description=Agent Orchestrator sessions 15 seconds after its last run
Description=Agent Orchestrator sessions 30 seconds after its last run
[Timer]
OnActiveSec=5s
OnUnitInactiveSec=15s
OnUnitInactiveSec=30s
AccuracySec=1s
[Install]
@@ -0,0 +1,11 @@
[Unit]
Description=Agent Orchestrator tokens: the transcripts' token counts, into the file the orchestrator reads
[Service]
Type=oneshot
Environment=PATH=/usr/bin:/bin
EnvironmentFile=%h/.local/share/kvb-orchestrator/.env
ExecStart=/usr/bin/env python3 %h/.local/share/kvb-orchestrator/client/resources.py tokens --state ${KVB_ORCHESTRATOR_KEPT}/resources --council ${KVB_ORCHESTRATOR_COUNCIL} --transcripts ${KVB_ORCHESTRATOR_PROJECTS}
Nice=10
IOSchedulingClass=idle
TimeoutStartSec=300
@@ -0,0 +1,9 @@
[Unit]
Description=Agent Orchestrator tokens every 10 minutes
[Timer]
OnCalendar=*-*-* *:00/10:00
AccuracySec=1s
[Install]
WantedBy=timers.target
+17 -1
View File
@@ -58,6 +58,7 @@ h1 { margin: 0; font-size: var(--fs-lg); font-weight: 680; letter-spacing: -.01e
.badge { min-width: 22px; padding: 0 7px; border-radius: 999px; background: var(--neutral-soft); color: var(--muted); font-size: var(--fs-xs); font-weight: 650; line-height: 20px; text-align: center; font-variant-numeric: tabular-nums; }
.badge[hidden] { display: none; }
.badge.urgent { background: var(--accent); color: var(--on-accent); }
.tab-group > a.badge { margin-inline: calc(var(--sp-2) - var(--sp-3) - 2px) var(--sp-3); text-decoration: none; }
.badge.alarm { background: var(--alarm); color: #fff; }
.tools { display: flex; flex-wrap: wrap; align-items: center; justify-content: flex-end; gap: 6px; }
.grant-bar, .grant-tray { display: flex; flex-wrap: wrap; align-items: center; justify-content: flex-end; gap: 6px; }
@@ -204,6 +205,7 @@ table.diff tr.more td { padding: 8px 16px; color: var(--muted); font-style: ital
.entry { grid-template-columns: minmax(0, 1fr); padding: 10px 12px; }
.msg-meta { display: flex; flex-wrap: wrap; align-items: center; }
.tabs button { padding: 6px 8px; }
.tab-group > a.badge { margin-inline: calc(var(--sp-2) - 8px - 2px) 8px; }
}
.entry:last-child { border-bottom: 0; }
.entry:hover { background: var(--hover); }
@@ -223,6 +225,8 @@ table.diff tr.more td { padding: 8px 16px; color: var(--muted); font-style: ital
.box-head > .box-title { display: inline-flex; align-items: center; gap: 6px; margin: 0; font-size: var(--fs-sm); font-weight: 650; }
.box-head .field { padding-block: 3px; }
.box-head > .box-slot { display: contents; }
.stream-head { position: sticky; top: calc(-1 * var(--main-top)); z-index: 3; margin-bottom: 10px; background: var(--glass-card); -webkit-backdrop-filter: var(--blur); backdrop-filter: var(--blur); }
.stream-head input[type="search"] { padding-block: 3px; }
.segmented { display: inline-flex; padding: 3px; gap: 2px; border-radius: 10px; background: var(--sunken); border: 1px solid var(--line); }
.segmented button { padding: 4px 11px; border: 0; border-radius: 8px; background: transparent; color: var(--muted); font-size: var(--fs-sm); font-weight: 580; cursor: pointer; }
.segmented button[aria-selected="true"], .segmented button[aria-pressed="true"] { background: var(--panel); color: var(--text); box-shadow: var(--shadow); }
@@ -307,12 +311,14 @@ input[type="datetime-local"] { padding: 3px 6px; border: 1px solid var(--line-st
.avatar { display: inline-grid; place-items: center; flex: none; width: 26px; height: 26px; overflow: hidden; border-radius: 50%; background: var(--sunken); border: 1px solid var(--line); }
.avatar.big { width: 52px; height: 52px; }
.readers { display: flex; flex-wrap: wrap; align-items: center; gap: 4px; margin-top: 6px; }
.reader { position: relative; display: inline-flex; }
.reader { position: relative; display: inline-flex; padding: 0; border: 0; border-radius: 50%; background: none; color: inherit; font: inherit; cursor: pointer; }
.reader .avatar { width: 22px; height: 22px; }
.reader .ack { position: absolute; right: -4px; bottom: -3px; display: inline-grid; place-items: center; width: 13px; height: 13px; border-radius: 50%; background: var(--ok); color: #fff; font-size: 9px; box-shadow: 0 0 0 1.5px var(--panel); }
.readers-more { padding: 0 7px; border-radius: 999px; background: var(--neutral-soft); color: var(--muted); font-size: var(--fs-xs); font-weight: 650; line-height: 20px; cursor: default; }
.avatar svg { display: block; width: 100%; height: 100%; }
.linkish { padding: 0; border: 0; background: none; color: inherit; font-weight: 650; text-align: left; cursor: pointer; overflow-wrap: anywhere; }
.agent-link { display: inline-flex; align-items: center; gap: 8px; min-width: 0; }
.agent-face { display: inline-flex; flex: none; padding: 0; border: 0; border-radius: 50%; background: none; cursor: pointer; }
.linkish:hover { color: var(--accent); text-decoration: underline; }
.popup { position: fixed; inset: 0; z-index: 25; width: auto; height: auto; max-width: none; max-height: none; margin: 0; padding: 0; overflow: hidden; border: 0; background: transparent; color: var(--text); }
.fade { animation: fade .2s var(--ease); }
@@ -357,6 +363,8 @@ textarea { width: 100%; min-height: 84px; padding: 8px 10px; border: 1px solid v
.mic:hover:not(:disabled) { background: var(--hover); color: var(--text); }
.mic:disabled { cursor: not-allowed; opacity: .55; }
.mic-line > .mic { border-left: 1px solid var(--line); border-radius: 0 9px 9px 0; }
.mic-line > .mic:not(:last-child) { border-radius: 0; }
.mic-line > button[type="submit"] { flex: none; border: 0; border-left: 1px solid var(--line); border-radius: 0 9px 9px 0; background: transparent; box-shadow: none; }
.mic-foot > .mic { min-height: 28px; border-radius: 8px; }
.palette-row > .mic-line { border: 0; border-radius: 0; }
.mic[aria-pressed="true"] { background: var(--bad-soft); color: var(--bad); animation: mic-pulse 1.2s ease-in-out infinite; }
@@ -628,6 +636,8 @@ pre.notes { margin: 0; padding: 8px 10px; background: var(--sunken); border-radi
{% include "page-diff.js" %}
{% include "page-codebox.js" %}
{% include "page-filters.js" %}
{% include "page-stream.js" %}
@@ -681,11 +691,14 @@ pre.notes { margin: 0; padding: 8px 10px; background: var(--sunken); border-radi
{% include "page-radio.js" %}
{% include "page-radioview.js" %}
{% include "page-notify.js" %}
{% include "page-agentset.js" %}
{% include "page-radiolog.js" %}
{% include "page-composer.js" %}
{% include "page-dial.js" %}
{% include "page-settings.js" %}
{% include "page-speech.js" %}
@@ -704,6 +717,7 @@ pre.notes { margin: 0; padding: 8px 10px; background: var(--sunken); border-radi
{% include "page-resources.js" %}
{% include "page-accounts.js" %}
{% include "page-schedules.js" %}
{% include "page-rates.js" %}
@@ -727,6 +741,8 @@ pre.notes { margin: 0; padding: 8px 10px; background: var(--sunken); border-radi
{% include "page-load.js" %}
{% include "page-timers.js" %}
{% include "page-boot.js" %}
})();
+7
View File
@@ -13,6 +13,7 @@ const Nav = (() => {
resources: "bi-speedometer2", match: "bi-stack",
};
const OLD = {graph: ["agents", "orbit"], tree: ["artifacts", "tree"]};
const SCHEDULES = "schedules";
const viewsOf = (screen) => (screen === "tasks" ? TASK_VIEWS : [...VIEWS, ...(OWN[screen] || [])]);
const known = (screen, view) => viewsOf(screen).some(([id]) => id === view);
@@ -21,6 +22,9 @@ const Nav = (() => {
}
function hashOf(screen, view) {
if (screen === "rules" && view === SCHEDULES) {
return `#stream/${SCHEDULES}`;
}
if (Object.hasOwn(PANES, screen)) {
return `#${PANES[screen].join("/")}`;
}
@@ -45,6 +49,9 @@ const Nav = (() => {
if (!head && pinned > 0) {
return {screen: "home", view: null, redirect: "#home"};
}
if (head === "stream" && sub === SCHEDULES) {
return {screen: "rules", view: SCHEDULES, redirect: null};
}
if (head === "stream" && sub === "radio") {
return {screen: "stream", view: null, redirect: "#stream", spot: true};
}
+1 -1
View File
@@ -8,7 +8,7 @@
accountsView.body = body;
const add = iconBtn("bi-plus-lg", "Add account", "btn small soft", () => accountSheet(null), "Add account: provider, email, renewal and weekly reset; kept on this host only");
const panel = h("section", {class: "card res-panel res-accounts", "data-panel": "resources-accounts", "aria-label": "Accounts"},
h("div", {class: "res-head", "data-star-slot": ""}, h("span", {class: "res-title", title: "Accounts", "aria-label": "Accounts"}, icon("bi-person-badge")), h("span", {class: "acc-title"}, "Accounts"), h("span", {class: "spacer"}), add), body);
h("div", {class: "res-head", "data-legend-slot": ""}, h("span", {class: "res-title", title: "Accounts", "aria-label": "Accounts"}, icon("bi-person-badge")), h("span", {class: "acc-title"}, "Accounts"), h("span", {class: "spacer"}), add), body);
return {panel, body};
}
+4 -4
View File
@@ -46,7 +46,7 @@
const down = officeBtn("bi-arrow-down", `Move ${name} down`, `Move ${name} down: lower priority`, () => moveAgent(name, 1), `down:${name}`);
up.disabled = index === 0;
down.disabled = index === ui.order.length - 1;
const item = h("li", {draggable: "true", "data-name": name}, icon("bi-grip-vertical", "grip"), h("span", {class: "rank"}, `${index + 1}.`), face(name, false), person(name), h("span", {class: "spacer"}), up, down);
const item = h("li", {draggable: "true", "data-name": name}, icon("bi-grip-vertical", "grip"), h("span", {class: "rank"}, `${index + 1}.`), agentLink(name), h("span", {class: "spacer"}), up, down);
item.addEventListener("dragstart", (event) => {
orderDom.dragged = name;
item.classList.add("dragging");
@@ -79,15 +79,15 @@
const key = orderDom.focus || focusKey(box);
orderDom.focus = null;
const changed = JSON.stringify(ui.order) !== JSON.stringify(state.agent_order);
Panels.keepFocus(orderDom.slot, () => box.replaceChildren(
h("div", {class: "inbox-head"}, h("h2", {class: "group-title", id: "agent-order-title", tabindex: "-1", "data-focus": "order:title"}, "Agent priority", counter(ui.order.length)), h("span", {class: "spacer"}), orderDom.slot),
box.replaceChildren(
h("div", {class: "inbox-head"}, h("h2", {class: "group-title", id: "agent-order-title", tabindex: "-1", "data-focus": "order:title"}, "Agent priority", counter(ui.order.length))),
h("p", {class: "muted"}, "Orders the chair's grants and decides only between equal task priorities; the tasks' --prio pins stay unchanged."),
ui.order.length ? h("ol", {class: "order-list", "aria-label": "Agent order"}, ui.order.map(orderItem)) : h("p", {class: "muted"}, "No agent with an office or an open task."),
h("div", {class: "actions"},
h("span", {class: "muted"}, "Drag or use the arrows to reorder"),
h("span", {class: "spacer"}),
h("button", {type: "button", class: "btn ghost", "data-focus": "order:reset", disabled: !changed, on: {click: () => placeAgent([...state.agent_order], "order:reset")}}, "Reset"),
h("button", {type: "button", class: "btn primary", "data-focus": "order:save", disabled: !changed, on: {click: saveAgentOrder}}, "Save order"))));
h("button", {type: "button", class: "btn primary", "data-focus": "order:save", disabled: !changed, on: {click: saveAgentOrder}}, "Save order")));
const target = key && [...box.querySelectorAll("[data-focus]")].find((element) => element.dataset.focus === key);
if (target && target.disabled) {
refocus(box, key.startsWith("up:") ? `down:${key.slice(3)}` : key.startsWith("down:") ? `up:${key.slice(5)}` : "order:title");
+4 -18
View File
@@ -113,12 +113,13 @@
const life = h("span", {class: "muted"});
const night = h("span", {});
const claimed = nightAgents().some(([sid]) => sid === key);
const nightRow = h("div", {class: "actions agent-night", role: "group", "aria-label": "Day/Night"}, night, h("span", {class: "spacer"}), radioMute(key, name),
const nightRow = h("div", {class: "actions agent-night", role: "group", "aria-label": "Day/Night"}, night, h("span", {class: "spacer"}),
claimed ? ACTIONS.slice(1).map(([id]) => actionButton(id, "btn small", null, () => [key])) : null);
const switches = agentSettings(key);
const former = (people()[key] || {names: []}).names.filter((entry) => entry !== name);
openPopup(name, [
popupHead(face(name, true), name, h("span", {class: "muted"}, former.length ? `Agent · formerly ${former.join(", ")}` : "Agent"), " ", life),
h("div", {class: "popup-body", "data-item": `agent:${key}`}, nightRow, info, h("h3", {}, "Subagents"), subs, h("h3", {}, "History"), log),
h("div", {class: "popup-body", "data-item": `agent:${key}`}, nightRow, switches, info, h("h3", {}, "Subagents"), subs, h("h3", {}, "History"), log),
form,
], anchor, () => {
agentDom = null;
@@ -129,27 +130,12 @@
});
ui.agent = key;
agentDom = {info, history: log, night};
paintAgentSettings(switches);
drawAgent();
loadSubagents(key, subs, life);
text.focus();
}
function radioMute(key, name) {
const button = h("button", {type: "button", class: "btn small agent-mute", "aria-label": `Mute ${name}`});
const show = () => {
const muted = radioSet.muted.includes(key);
button.title = muted ? `Muted: the radio reads ${name} aloud again on a press` : `Mute ${name}: the radio stops reading this agent aloud`;
button.setAttribute("aria-pressed", String(muted));
button.replaceChildren(icon(muted ? "bi-volume-mute" : "bi-volume-up"), muted ? "Muted" : "Radio on");
};
button.addEventListener("click", () => {
keepRadio(RadioSet.muting(radioSet, key));
show();
});
show();
return button;
}
function agentNames() {
const names = new Set([...state.graph.nodes.filter((node) => node.kind === "session" || node.kind === "chair").map((node) => nameOf(node.id)), ...state.agent_order]);
return [...names].sort((a, b) => a.localeCompare(b));
+38
View File
@@ -0,0 +1,38 @@
const AGENT_SWITCHES = [
["sound", "bi-bell", "Sound", "its tones, Morse and Gibberlink on the radio"],
["aloud", "bi-megaphone", "Read aloud", "the radio speaks its rows"],
["bubbles", "bi-chat-quote", "Bubbles", "a speech bubble beside its face"],
];
let agentSaves = Promise.resolve();
const agentOn = (key, what) => RadioSet.heard({class: "", source: key}, settings.agents, what);
function setAgent(key, what) {
agentSaves = agentSaves.then(async () => {
const entry = {...Object.fromEntries(AGENT_SWITCHES.map(([name]) => [name, agentOn(key, name)])), [what]: !agentOn(key, what)};
if (!await saveSettings({...settings, space: savedSpace(), agents: {...settings.agents, [key]: entry}})) {
drawAgentSettings();
}
});
}
function agentSettings(key) {
return h("div", {class: "agent-settings", role: "group", "aria-label": `${nameOf(key)}: radio and bubbles`, "data-agent": key},
AGENT_SWITCHES.map(([what, glyph, label]) => h("button", {type: "button", class: "btn small agent-switch", "data-switch": what, on: {click: () => setAgent(key, what)}}, icon(glyph), label)),
h("p", {class: "muted"}, "For this agent only; a MAYDAY always sounds, speaks and shows."));
}
function paintAgentSettings(group) {
const key = group.dataset.agent;
const name = nameOf(key);
for (const button of group.querySelectorAll("[data-switch]")) {
const [what, , label, hint] = AGENT_SWITCHES.find(([id]) => id === button.dataset.switch);
const on = agentOn(key, what);
button.setAttribute("aria-pressed", String(on));
button.title = `${label} for ${name}: ${on ? "on" : "off"}, ${hint}; a press turns it ${on ? "off" : "on"}`;
}
}
function drawAgentSettings() {
document.querySelectorAll(".agent-settings[data-agent]").forEach(paintAgentSettings);
}
+2 -1
View File
@@ -74,7 +74,8 @@
const newAlarms = [...alarms].filter(([key]) => !known.alarms.has(key)).map(([, row]) => row);
const newRadio = state.radio.filter((row) => !known.radio.has(`${row.ts}|${row.from}|${row.text.slice(0, 40)}`));
const direct = newRadio.filter((row) => row.to.includes(HUMAN));
const present = {mayday: newAlarms.length > 0, review: fresh.some((item) => item.kind !== "operator"), direct: direct.length > 0, radio: newRadio.length > 0};
const sounding = newRadio.filter((row) => RadioSet.heard(row, settings.agents, "sound"));
const present = {mayday: newAlarms.length > 0, review: fresh.some((item) => item.kind !== "operator"), direct: sounding.some((row) => row.to.includes(HUMAN)), radio: sounding.length > 0};
const kind = radioSet.mode === "silence" || !settings.channels.sounds ? null : Voice.beep(present, tones(), SOUND_KINDS.map(([id]) => id));
if (kind) {
play(kind, loudness(kind));
+9 -4
View File
@@ -245,7 +245,7 @@
} else if (node.kind === "worktree") {
body.push(h("div", {class: "states"}, worktreeStates(data)), workChips(data.open_work), meta([["Path", data.path], ["Branch", data.branch], ["HEAD", data.head.slice(0, 12), data.head]]),
flowDetails(data.flow, data.branch),
data.workers.length ? h("div", {class: "who"}, data.workers.map((name) => [face(name, false), person(name)])) : h("p", {class: "muted"}, "No agent works here."),
data.workers.length ? h("div", {class: "who"}, data.workers.map((name) => agentLink(name))) : h("p", {class: "muted"}, "No agent works here."),
data.review ? h("div", {class: "who"}, status(data.review.status), h("span", {}, data.review.title)) : null, h("div", {class: "actions"}, copyButton(data.path)));
} else if (node.kind === "artefact") {
body.push(meta([["Ref", data.ref], ["Kind", data.kind], ["Task", data.task], ["Since", data.added]]), data.ended ? pill("Task ended: clean up", "warn") : null);
@@ -255,13 +255,18 @@
return [popupHead(icon(kindIcon), node.label, h("span", {class: "muted"}, kindName)), h("div", {class: "popup-body", "data-item": `artifact:${artifactRef(node.id)}`}, body)];
}
function treeCount(words) {
tree.dom.count.textContent = words;
tree.dom.count.title = words;
}
function artifactsScreen() {
const view = ui.views.artifacts;
const picker = h("select", {class: "field", "aria-label": "Repository", title: "Repository", on: {change: (event) => {
art.repo = event.target.value;
drawArtifacts();
}}});
const count = h("span", {class: "muted"});
const count = h("span", {class: "muted art-count"});
const reload = iconBtn("bi-arrow-clockwise", "Reload", "btn small soft", fetchTree, "Reload: read the tree state from pkgmgr");
const stageBox = h("div", {class: "stage"});
const legendBox = h("div", {});
@@ -277,7 +282,7 @@
drawArtifacts();
fetchTree();
}, 0);
const controls = boxHead("Artifacts", "", viewSwitch("artifacts"), view === "3d" ? layoutTools("artifacts") : view === "tree" ? null : picker,
const controls = boxHead("Artifacts", "art-head", viewSwitch("artifacts"), view === "3d" ? layoutTools("artifacts") : view === "tree" ? null : picker,
h("div", {class: "toolbar"}, search, reload, removeAll, apply), count);
const body = view === "tree" ? h("div", {class: "tree-panel", "data-panel": "artifacts/tree"}, list) : h("div", {class: "card stage-card", "data-panel": `artifacts/${view}`}, stageBox, legendBox);
return h("div", {class: "graph"}, controls, body);
@@ -314,7 +319,7 @@
}
tree.dom.apply.replaceChildren(gateApply() || "");
const empty = !tree.data || tree.data.error;
tree.dom.count.textContent = empty ? "" : `${tree.data.repos.length} repositories · as of ${clock.format(stampOf(tree.data.scanned))}`;
treeCount(empty ? "" : `${tree.data.repos.length} repositories · as of ${clock.format(stampOf(tree.data.scanned))}`);
if (empty) {
tree.dom.stage.replaceChildren(emptyState(tree.busy || !tree.data ? "Reading repositories …" : "No tree", tree.data ? tree.data.error : "pkgmgr writes the tree every minute while this page is open."));
return;
+3 -11
View File
@@ -16,7 +16,8 @@
document.getElementById("palette-open").addEventListener("click", openPalette);
document.getElementById("settings-open").addEventListener("click", settingsSheet);
document.getElementById("bubbles-toggle").addEventListener("click", toggleBubbles);
document.addEventListener("click", (event) => closeMenus(event.target instanceof Element ? event.target.closest(MENUS) : null));
document.addEventListener("click", menuClick);
document.addEventListener("toggle", menuLinger, true);
document.addEventListener("scroll", placeStations, {capture: true, passive: true});
document.addEventListener("fullscreenchange", () => {
if (!document.fullscreenElement) {
@@ -60,13 +61,4 @@
drawTime();
motion.asOf = ui.asOf;
relayout(0);
window.setInterval(poll, 10000);
window.setInterval(follow, 3000);
window.setInterval(() => relayout(MOVE), RELAYOUT);
window.setInterval(() => live() && drawSky(), 30000);
window.setInterval(syncRadio, 20000);
window.setInterval(() => {
if (tree.dom && !document.hidden) {
fetchTree();
}
}, 60000);
startTimers();
+2 -1
View File
@@ -145,7 +145,7 @@
}
const head = speech.current || speech.loading || speech.item;
startQuiet(Bubbles.plan(head, speech.pending));
const planned = Bubbles.plan(head, speech.pending, bubbles.quiet);
const planned = Bubbles.plan(head, speech.pending, bubbles.quiet).filter((entry) => entry.item.bubble !== false);
const kept = new Set(planned.map((entry) => entry.item));
for (const [item, view] of bubbles.shown) {
if (!kept.has(item)) {
@@ -182,6 +182,7 @@
function syncBubbles() {
document.getElementById("bubbles-toggle").setAttribute("aria-pressed", String(settings.bubbles));
document.querySelectorAll(".radio-bubbles").forEach((button) => button.setAttribute("aria-pressed", String(settings.bubbles)));
bubbleLayer().hidden = !settings.bubbles;
if (settings.bubbles) {
bubbleFont();
+43
View File
@@ -0,0 +1,43 @@
const CODE_OPEN = {preview: false, open: true, closed: false};
const codeView = {open: new Map()};
/**
* @param {string} key what the box shows, such as an item key; its open state survives every redraw.
* @param {string} place preview (Stream, Waits on Operator: 12 lines until the eye shows all), open (Match: the whole
* code, the card body scrolls) or closed (Tasks: one line, the eye opens the whole code in a sheet).
* @param {Array} parts the command and diff nodes the box holds; null entries are skipped.
* @param {string} copy the text the copy button copies, "" for no copy button.
* @param {Array} actions the Grant and Deny nodes for the right end of the foot, [] for none.
* @param {Function|null} load runs after the eye opened the box, such as a redraw that fetches a review's diff; null
* when the box already holds everything.
* @returns {HTMLElement} the .code-box: its .code-body, then its .code-foot.
*/
function codeBox(key, place, parts, copy, actions, load) {
const id = `${place}:${key}`;
const body = h("div", {class: "code-body"}, parts.filter(Boolean));
const eye = h("button", {type: "button", class: "btn small ghost icon-only code-eye", on: {click: () => {
if (place === "closed") {
openSheet("Code", [h("div", {class: "code-box", "data-place": "sheet"}, body.cloneNode(true))], true);
return;
}
codeView.open.set(id, eye.getAttribute("aria-expanded") !== "true");
paintEye();
if (load) {
load();
}
}}}, icon("bi-eye"));
const root = h("div", {class: "code-box", "data-place": place}, body,
h("div", {class: "code-foot"}, copy ? copyButton(copy) : null, eye, h("span", {class: "spacer"}), actions));
const paintEye = () => {
const open = place !== "closed" && (codeView.open.has(id) ? codeView.open.get(id) : CODE_OPEN[place]);
const words = place === "closed" ? "Show all: the whole code in a sheet" : open ? "Show less: back to the preview" : "Show all: the whole code in place";
root.dataset.open = String(open);
eye.setAttribute("aria-expanded", String(open));
eye.setAttribute("aria-label", open ? "Show less" : "Show all");
eye.title = words;
};
paintEye();
return root;
}
const codeOpened = (key, place) => codeView.open.get(`${place}:${key}`) === true;
+7 -6
View File
@@ -29,7 +29,7 @@
}
/**
* @param {Element} form the composer the question shows in, above its footer, its last child.
* @param {Element} form the composer the question shows in, inside its frame above the footer.
* @param {string} question what the operator confirms.
* @param {string} yes the confirming button's label.
* @returns {Promise<boolean>} true on yes, false on Cancel or Escape; nothing leaves the page before.
@@ -49,7 +49,7 @@
done(false);
}
});
form.lastElementChild.before(box);
form.querySelector(".mic-foot").before(box);
accept.focus();
});
}
@@ -207,7 +207,7 @@
}
function composerForm() {
const channel = h("select", {class: "field"}, CHANNELS.map(([id, label]) => h("option", {value: id, title: CHANNEL_HINTS[id]}, label)));
const channel = h("select", {class: "field"}, CHANNELS.map(([id, label]) => h("option", {value: id}, label)));
const recipient = h("select", {class: "field"});
const toField = h("label", {}, "To", recipient);
const text = h("textarea", {"aria-label": "Message", placeholder: "Message to the agents …", maxlength: 20000, "data-skills": ""});
@@ -240,12 +240,13 @@
drawMayday(mayday);
const sync = () => {
toField.hidden = !TO_ONE.some(([id]) => id === channel.value);
channel.title = CHANNEL_HINTS[channel.value];
};
channel.addEventListener("change", sync);
sync();
const form = h("form", {class: "composer"}, h("div", {class: "composer-grid"}, h("label", {}, "Channel", channel), toField), micFrame(text, [record]), replay,
h("div", {class: "actions"}, status, h("div", {class: "ptt-split", role: "group", "aria-label": "Send"}, submit, testMenu(text, channel)), mayday));
const frame = micFrame(text, [record, status]);
frame.prepend(h("div", {class: "composer-grid"}, h("label", {}, "Channel", channel), toField));
frame.querySelector(".mic-foot").append(h("div", {class: "ptt-split", role: "group", "aria-label": "Send"}, submit, testMenu(text, channel)), mayday);
const form = h("form", {class: "composer"}, frame, replay);
const empty = () => {
if (!text.value.trim()) {
toast("Nothing to send", ["Write a text or record one; the transcript lands in the field for checking."], false);
+2 -2
View File
@@ -37,7 +37,7 @@
const MOVE = 2000;
const RELAYOUT = 60000;
const SESSION_ID = /^[A-Za-z0-9_-]{1,128}$/;
const STORE = {views: "kvb-orchestrator.views", status: "kvb-orchestrator.status", comments: "kvb-orchestrator.match-comments", peeks: "kvb-orchestrator.match-peeks"};
const STORE = {views: "kvb-orchestrator.views", status: "kvb-orchestrator.status", comments: "kvb-orchestrator.match-comments", peeks: "kvb-orchestrator.match-peeks", wide: "kvb-orchestrator.match-wide"};
const PRESENCE = {
working: ["Working", "bi-gear-fill", "info"],
alive: ["Alive", "bi-heart-pulse-fill", "ok"],
@@ -75,7 +75,7 @@
direct: [[740, 0, 0.2]],
radio: [[520, 0, 0.07]],
};
const KEYS = [["Ctrl+K", "Commands, views, agents and AI command"], ["Right-click", "Context menu: the element's commands, then the tab's, then the general ones"], ["Shift+right-click", "The browser's own context menu"], ["Menu key · Shift+F10", "Context menu of the focused element: ↑ / ↓ move, Enter runs, Esc closes"], ["1 · 2 · 3 · 4", "Stream · Agents · Artifacts · Tasks"], ["j / k", "Waits on Operator: next / previous entry"], ["x", "Waits on Operator: select entry"], ["a", "Waits on Operator: grant entry (3 s to undo)"], ["Enter", "Waits on Operator: open entry"], ["f", "Comment on the selected lines of a diff or a command; Deny or Grant sends the comments"], ["→ · ← · ↑", "Match: accept · reject with feedback · later"],["/", "Search the stream"], ["h", "Look at the sky: drag turns the view, wheel or two fingers zoom, Esc ends"], ["Arrows · + / - · 0", "Sky (focused): turn · zoom · reset"], ["Drag · wheel", "3D: turn, right drag pans, wheel zooms"], ["+ / - · 0 · Ctrl+wheel", "Home tile (focused): zoom its content in · out · reset"],["🎙 hold", "Voice input into the agent field or the command line, never sent automatically"], ["?", "This help"], ["Esc", "Close"]];
const KEYS = [["Ctrl+K", "Commands, views, agents and AI command"], ["Right-click", "Context menu: the element's commands, then the tab's, then the general ones"], ["Shift+right-click", "The browser's own context menu"], ["Menu key · Shift+F10", "Context menu of the focused element: ↑ / ↓ move, Enter runs, Esc closes"], ["1 · 2 · 3 · 4", "Stream · Agents · Artifacts · Tasks"], ["j / k", "Waits on Operator: next / previous entry"], ["x", "Waits on Operator: select entry"], ["a", "Waits on Operator: grant entry (undo window as set in Settings)"], ["Enter", "Waits on Operator: open entry"], ["f", "Comment on the selected lines of a diff or a command; Deny or Grant sends the comments"], ["d · a · w · s", "Match (also → · ← · ↑): accept · reject with feedback · next card · undo the last step; on the release card d releases"],["/", "Search the stream"], ["h", "Look at the sky: drag turns the view, wheel or two fingers zoom, Esc ends"], ["Arrows · + / - · 0", "Sky (focused): turn · zoom · reset"], ["Drag · wheel", "3D: turn, right drag pans, wheel zooms"], ["+ / - · 0 · Ctrl+wheel", "Home tile (focused): zoom its content in · out · reset"],["🎙 hold", "Voice input into the agent field or the command line, never sent automatically"], ["?", "This help"], ["Esc", "Close"]];
const calm = window.matchMedia("(prefers-reduced-motion: reduce)");
const relative = new Intl.RelativeTimeFormat("en", {numeric: "auto"});
const absolute = new Intl.DateTimeFormat("en-GB", {dateStyle: "medium", timeStyle: "short"});
+4 -1
View File
@@ -60,6 +60,9 @@
}
function ctxPinItems(node, target) {
if (target.refused) {
return [{label: "Pin to Home", hint: `not possible, ${target.refused}`, run: () => toast("Not pinned", [`Pin to Home is not possible: ${target.refused}.`], false)}];
}
const entry = ctxPinEntry(target);
if (!entry) {
return [];
@@ -86,7 +89,7 @@
{kind: "entry", id: ctxAttr("data-ref"), title: (ref) => ctxEntryOf(ref).title, items: ctxEntryItems},
{kind: "rule", id: ctxAttr("data-rule", "data-entry"), title: (id) => `Rule ${id}`, items: (node, id) => [ctxCopyItem("Copy rule", id)]},
{kind: "pick", id: ctxAttr("data-pick"), title: ctxPickTitle, items: ctxPickItems},
{kind: "pin", id: ctxPinOf, title: (target) => ctxPinEntry(target).title, items: ctxPinItems},
{kind: "pin", id: ctxPinOf, title: (target) => (ctxPinEntry(target) || {title: "Home pin"}).title, items: ctxPinItems},
{kind: "tile", id: (node) => (node.matches(".home-tile[data-pin]") ? node.dataset.pin : null), title: (key) => `Tile ${key}`, items: ctxTileItems},
];
+31 -6
View File
@@ -39,19 +39,42 @@
}
const reasonChips = (field) => presetChips(field, state.reasons, "Recent reasons");
const NO_RECIPIENT = "Pick the agent to tell: a post or call needs a recipient";
const NO_AGENT = "No agent to tell: the item names no recipient; pick one under Deny via …";
let whyOffCount = 0;
/**
* @param {HTMLButtonElement} button a button that may be disabled.
* @returns {root, set}: root wraps the button and carries its tooltip, because a disabled
* button fires no hover in Chrome; set(why, hint) disables the button and names why while why is not empty, else
* enables it and names the action hint; aria-describedby gives keyboard users the same text.
*/
function whyOff(button) {
whyOffCount += 1;
const note = h("span", {id: `why-off-${whyOffCount}`, hidden: true});
const root = h("span", {class: "why-off"}, button, note);
button.setAttribute("aria-describedby", note.id);
const set = (why, hint) => {
button.disabled = Boolean(why);
root.title = why || hint;
note.textContent = why || hint;
};
return {root, set};
}
function denySheet(item) {
const name = `deny-${keyOf(item)}`;
const recipient = h("select", {class: "field"}, h("option", {value: ""}, "Pick the agent to tell"),
denyRecipients(item).map((agent) => h("option", {value: agent, selected: agent === item.to}, revealed(agent))));
const confirm = h("button", {type: "button", class: "btn danger"}, icon("bi-x-lg"), "Deny");
const gate = whyOff(confirm);
const hints = [];
const picked = () => choices.map((label) => label.querySelector("input")).find((input) => input.checked);
const paintDeny = () => {
hints.forEach(([small, direct, hint]) => {
small.textContent = `to ${direct ? revealed(recipient.value) || "nobody yet: pick a recipient" : "all"}, ${hint}`;
});
confirm.disabled = DIRECT_DENY.has(picked().value) && !recipient.value;
gate.set(DIRECT_DENY.has(picked().value) && !recipient.value ? NO_RECIPIENT : "", `Deny: ${CLASSES[picked().value]} ${DIRECT_DENY.has(picked().value) ? `to ${revealed(recipient.value)}` : "to all"}, signed by your passkey`);
};
const choices = DENY_CHANNELS.map(([id, direct, hint]) => {
const small = h("small", {});
@@ -76,21 +99,23 @@
h("label", {class: "deny-recipient"}, "Recipient of a post or call", recipient),
reasonChips(reason),
h("label", {class: "deny-reason"}, "Reason (optional, the agent reads it too)", reason),
h("p", {class: "muted"}, "The passkey signs the denial with channel, recipient and reason; then 3 s remain to undo it.",
h("p", {class: "muted"}, `The passkey signs the denial with channel, recipient and reason; then ${undoWords()}.`,
" Mayday stays reserved for the operator."),
h("div", {class: "actions"}, h("span", {class: "spacer"}), btn("Cancel", "btn ghost", closeSheet), confirm)], false);
h("div", {class: "actions"}, h("span", {class: "spacer"}), btn("Cancel", "btn ghost", closeSheet), gate.root)], false);
reason.focus();
}
function denySplit(item) {
const main = iconBtn("bi-x-lg", "Deny", "btn small danger", () => (lineNotes(keyOf(item)) ? denySheet(item) : denyNow(item, "post", "", item.to)), item.to ? `Deny: by post to ${revealed(item.to)}, 3 s to undo; with line comments it opens Deny via … with them as the reason` : "Deny: the card names no agent; pick one under Deny via …");
main.disabled = !item.to;
const hint = `Deny: by post to ${revealed(item.to)}, then ${undoWords()}; with line comments it opens Deny via … with them as the reason`;
const main = iconBtn("bi-x-lg", "Deny", "btn small danger", () => (lineNotes(keyOf(item)) ? denySheet(item) : denyNow(item, "post", "", item.to)), item.to ? hint : NO_AGENT);
const gate = whyOff(main);
gate.set(item.to ? "" : NO_AGENT, hint);
const more = h("button", {type: "button", class: "btn small danger icon-only", "aria-haspopup": "dialog", ...named("Deny via …", "Deny via another channel or with a reason")}, caret());
more.addEventListener("click", (event) => {
event.stopPropagation();
denySheet(item);
});
return h("div", {class: "deny-split", role: "group", "aria-label": "Deny"}, main, more);
return h("div", {class: "deny-split", role: "group", "aria-label": "Deny"}, gate.root, more);
}
/**
+75
View File
@@ -0,0 +1,75 @@
const DIAL_MAX = 60;
const DIAL_PAGE = 5;
const DIAL_SIZE = 140;
const DIAL_RADIUS = 58;
/**
* @param {number} second a value on the dial, 0 to DIAL_MAX.
* @param {number} radius how far from the centre.
* @returns {number[]} the point [x, y] for that second, 0 and 60 at the top, clockwise.
*/
function dialPoint(second, radius) {
const angle = (second / DIAL_MAX) * 2 * Math.PI;
const centre = DIAL_SIZE / 2;
return [centre + Math.sin(angle) * radius, centre - Math.cos(angle) * radius];
}
/**
* @param {number} value the undo window in whole seconds the dial starts at.
* @param {string} label the slider's accessible name.
* @returns {root, value}: an analog clock face with 60 ticks and one hand, an ARIA slider:
* dragging the hand or clicking a tick sets it, the arrows step 1 s, Page Up and Down 5 s, Home and End the ends.
*/
function undoDial(value, label) {
let seconds = value;
const ticks = Array.from({length: DIAL_MAX}, (_, second) => {
const long = second % DIAL_PAGE === 0;
const [x1, y1] = dialPoint(second, DIAL_RADIUS - (long ? 10 : 5));
const [x2, y2] = dialPoint(second, DIAL_RADIUS);
return s("line", {class: `dial-tick${long ? " long" : ""}`, x1: fixed(x1), y1: fixed(y1), x2: fixed(x2), y2: fixed(y2)});
});
const centre = DIAL_SIZE / 2;
const hand = s("line", {class: "dial-hand", x1: centre, y1: centre});
const face = s("svg", {class: "dial-face", viewBox: `0 0 ${DIAL_SIZE} ${DIAL_SIZE}`, "aria-hidden": "true", focusable: "false"},
s("circle", {class: "dial-rim", cx: centre, cy: centre, r: DIAL_RADIUS + 4}), ticks, hand, s("circle", {class: "dial-pin", cx: centre, cy: centre, r: 4}));
const readout = h("output", {class: "dial-readout"});
const root = h("div", {class: "undo-dial", role: "slider", tabindex: "0", "aria-label": label, "aria-valuemin": "0", "aria-valuemax": String(DIAL_MAX)}, face, readout);
const set = (next) => {
seconds = Math.max(0, Math.min(DIAL_MAX, Math.round(next)));
const [x2, y2] = dialPoint(seconds, DIAL_RADIUS - 14);
hand.setAttribute("x2", fixed(x2));
hand.setAttribute("y2", fixed(y2));
readout.textContent = `${seconds} s`;
root.setAttribute("aria-valuenow", String(seconds));
root.setAttribute("aria-valuetext", seconds ? `${seconds} seconds to undo` : "0 seconds: takes effect at once");
};
const pointed = (event) => {
const box = face.getBoundingClientRect();
const degrees = (Math.atan2(event.clientX - box.left - box.width / 2, box.top + box.height / 2 - event.clientY) * 180) / Math.PI;
set(((degrees + 360) % 360) / (360 / DIAL_MAX));
};
root.addEventListener("keydown", (event) => {
const steps = {ArrowRight: 1, ArrowUp: 1, ArrowLeft: -1, ArrowDown: -1, PageUp: DIAL_PAGE, PageDown: -DIAL_PAGE};
if (event.key in steps) {
set(seconds + steps[event.key]);
} else if (event.key === "Home" || event.key === "End") {
set(event.key === "Home" ? 0 : DIAL_MAX);
} else {
return;
}
event.preventDefault();
event.stopPropagation();
});
face.addEventListener("pointerdown", (event) => {
face.setPointerCapture(event.pointerId);
pointed(event);
root.focus({preventScroll: true});
});
face.addEventListener("pointermove", (event) => {
if (face.hasPointerCapture(event.pointerId)) {
pointed(event);
}
});
set(seconds);
return {root, value: () => seconds};
}
+6 -5
View File
@@ -183,16 +183,17 @@
/**
* @param {HTMLElement} row a code row with data-line, as a right-click hits it.
* @returns {Object|null} the row as the lines a comment covers, like selectionFeedback(); null outside a [data-path] region of an item with a requester.
* @returns {Object|null} the row as the lines a comment covers, like selectionFeedback(); null outside a [data-path]
* region of an inbox item. An item without a requester takes marks too: Deny via … picks whom they go to.
*/
function rowPick(row) {
const region = row.closest("[data-path]");
const card = region && region.closest("[data-ref]");
if (!card || !card.dataset.to || !row.dataset.line || row.classList.contains("match-mark") || row.closest(".match-card")) {
if (!card || !card.dataset.ref || !row.dataset.line || row.classList.contains("match-mark") || row.closest(".match-card")) {
return null;
}
const line = Number(row.dataset.line);
return {ref: card.dataset.ref, to: card.dataset.to, path: region.dataset.path, from: line, until: line, anchor: row, inline: Boolean(region.closest("#sheet"))};
return {ref: card.dataset.ref, to: card.dataset.to || "", path: region.dataset.path, from: line, until: line, anchor: row, inline: Boolean(region.closest("#sheet"))};
}
/**
@@ -237,7 +238,7 @@
const elementOf = (node) => (node instanceof Element ? node : node.parentElement);
const region = elementOf(range.startContainer) && elementOf(range.startContainer).closest("[data-path]");
const card = region && region.closest("[data-ref]");
if (!card || !card.dataset.to || !elementOf(range.endContainer) || elementOf(range.endContainer).closest("[data-path]") !== region) {
if (!card || !card.dataset.ref || !elementOf(range.endContainer) || elementOf(range.endContainer).closest("[data-path]") !== region) {
return null;
}
const quote = selection.toString();
@@ -247,7 +248,7 @@
if (!lines) {
return null;
}
return {ref: card.dataset.ref, to: card.dataset.to, path: region.dataset.path, from: lines[0], until: lines[1], anchor: rows.length ? rows[rows.length - 1] : region, inline: Boolean(region.closest("#sheet")), rect: range.getBoundingClientRect()};
return {ref: card.dataset.ref, to: card.dataset.to || "", path: region.dataset.path, from: lines[0], until: lines[1], anchor: rows.length ? rows[rows.length - 1] : region, inline: Boolean(region.closest("#sheet")), rect: range.getBoundingClientRect()};
}
function hideFeedback() {
+58 -4
View File
@@ -99,7 +99,17 @@
s("title", {}, PRESENCE[value][0]), s("rect", {class: "presence-dot", x: fixed(-size * 0.65), y: fixed(-size * 0.65), width: fixed(size * 1.3), height: fixed(size * 1.3), rx: fixed(size * 0.65)}),
s("g", {class: "glyph"}, s("use", {href: `#${PRESENCE[value][1]}`, x: fixed(-size / 2), y: fixed(-size / 2), width: fixed(size), height: fixed(size)}))) : null;
};
const person = (name) => (name && name !== "-" && name !== "all" && name !== HUMAN ? h("button", {type: "button", class: "linkish", title: revealed(`Open ${name}`), on: {click: () => openAgent(name)}}, revealed(name)) : dash(name));
const isAgent = (name) => Boolean(name) && name !== "-" && name !== "all" && name !== HUMAN;
const person = (name) => (isAgent(name) ? h("button", {type: "button", class: "linkish", title: revealed(`Open ${name}`), on: {click: () => openAgent(name)}}, revealed(name)) : dash(name));
const openFrom = (name) => (event) => {
event.stopPropagation();
const self = event.currentTarget;
openAgent(name, () => (self.isConnected ? self : null));
};
const agentLink = (name, big, cls) => (isAgent(name)
? h("button", {type: "button", class: "linkish agent-link", title: revealed(`Open ${name}`), on: {click: openFrom(name)}}, face(name, big), h("span", {class: cls || "agent-name"}, revealed(people()[name] ? nameOf(name) : name)))
: h("span", {class: "agent-link"}, face(name || "-", big), h("span", {class: cls || "agent-name"}, dash(name))));
const agentFace = (name, big) => (isAgent(name) ? h("button", {type: "button", class: "agent-face", ...named(revealed(`Open ${people()[name] ? nameOf(name) : name}`)), on: {click: openFrom(name)}}, face(name, big)) : face(name || "-", big));
const people = () => state.people || {};
const labelOf = (key) => (people()[key] || {name: String(key).replace(/^name:/, "")}).name;
const nameOf = (key) => (people()[key] || {now: String(key).replace(/^name:/, "")}).now;
@@ -108,8 +118,10 @@
const readLabel = (reader) => Receipts.label(reader, (ts) => absolute.format(stampOf(ts)));
const readerRow = (row) => {
const {shown, hidden} = Receipts.strip(row);
const avatar = (reader) => h("span", {class: "reader", "data-session": reader.session, "data-acked": String(reader.acked), role: "img", ...named(readLabel(reader))},
face(people()[reader.session] ? reader.session : reader.name, false), reader.acked ? h("span", {class: "ack", "aria-hidden": "true"}, icon("bi-check2-all")) : null);
const avatar = (reader) => {
const who = people()[reader.session] ? reader.session : reader.name;
return h("button", {type: "button", class: "reader", "data-session": reader.session, "data-acked": String(reader.acked), ...named(readLabel(reader)), on: {click: openFrom(who)}}, face(who, false), reader.acked ? h("span", {class: "ack", "aria-hidden": "true"}, icon("bi-check2-all")) : null);
};
const more = hidden.length ? h("span", {class: "readers-more", role: "img", ...named(`${hidden.length} more readers`, [...shown, ...hidden].map(readLabel).join("\n"))}, `+${hidden.length}`) : null;
return shown.length ? h("div", {class: "readers", role: "group", "aria-label": `Read by ${shown.length + hidden.length}`}, shown.map(avatar), more) : null;
};
@@ -147,7 +159,49 @@
return button;
}
const MENUS = "details.menu, details.radio-station, .ctx-menu";
const MENUS = "details.menu, details.radio-station, details.radio-notify, .ctx-menu";
const MENU_LINGER = 3000;
const ACTIONS_IN_MENU = "button, a[href], [role='button']";
/**
* @param {MouseEvent} event a click anywhere on the page.
* The menu the click landed in stays open, read from the event path because a toggle chip may redraw itself away
* before the click reaches the document; an action entry of a details.menu (a button without aria-pressed) closes it.
*/
function menuClick(event) {
const path = event.composedPath().filter((node) => node instanceof Element);
const menu = path.find((node) => node.matches(MENUS)) || null;
const control = path.find((node) => node.matches(`${ACTIONS_IN_MENU}, summary, label, input, select, textarea`));
const action = Boolean(menu && menu.matches("details.menu") && control && control.matches(ACTIONS_IN_MENU) && !control.hasAttribute("aria-pressed"));
closeMenus(action ? null : menu);
}
/**
* @param {Event} event a toggle of any details element, caught on the way down.
* An opened details.menu closes MENU_LINGER ms after a mouse or pen leaves it; coming back in time keeps it open.
*/
function menuLinger(event) {
const menu = event.target;
if (!(menu instanceof HTMLDetailsElement) || !menu.matches("details.menu") || menu.dataset.linger) {
return;
}
menu.dataset.linger = "on";
let timer = 0;
menu.addEventListener("pointerleave", (left) => {
if (left.pointerType !== "touch" && menu.open) {
window.clearTimeout(timer);
timer = window.setTimeout(() => {
menu.open = false;
}, MENU_LINGER);
}
});
menu.addEventListener("pointerenter", () => window.clearTimeout(timer));
menu.addEventListener("toggle", () => {
if (!menu.open) {
window.clearTimeout(timer);
}
});
}
function closeMenus(keep) {
for (const menu of document.querySelectorAll(MENUS)) {
+6 -1
View File
@@ -14,7 +14,7 @@
const TARGET_GONE = "gone";
const TARGET_PICK = "";
const SESSION_KEY = /^(?!-)[A-Za-z0-9_-]{1,128}$/;
const CONTROL_TABS = [["tools", "Tools", "bi-plug"], ["rules", "Rules", "bi-shield-lock"], ["groups", "Groups", "bi-people"]];
const CONTROL_TABS = [["tools", "Tools", "bi-plug"], ["rules", "Rules", "bi-shield-lock"], ["groups", "Groups", "bi-people"], ["schedules", "Schedules", "bi-clock"]];
const CAPABILITY_WORDS = {deniedMcpServers: ["Unblock server", "Block server"], enabledPlugins: ["Enable plugin", "Disable plugin"], switches: ["Turn on", "Turn off"]};
const TOOL_HINTS = {
deniedMcpServers: "Off blocks the server before it loads, in every session and project.",
@@ -201,10 +201,15 @@
* @returns {HTMLElement} the Controls screen: title, tab list, one panel per tab, only the chosen one shown, and the bar.
*/
function controlsPage(panels, bar) {
if (ui.views.rules === "schedules") {
firewall.tab = "schedules";
ui.views.rules = null;
}
const views = {};
const tabs = {};
const pick = (id) => {
firewall.tab = id;
window.history.replaceState(null, "", Nav.hashOf("rules", id === "schedules" ? id : null));
for (const [key, tab] of Object.entries(tabs)) {
tab.setAttribute("aria-selected", String(key === id));
views[key].hidden = key !== id;
+8 -6
View File
@@ -4,6 +4,7 @@
[GRANT_SELECT]: ["Select", "bi-check2-square", "Select mode", "Select: every grant button and option adds its item to the selection; Grant grants the selection under one passkey signature, each rule and red-gate review under its own"],
};
const PICKED_HINT = "In the selection: take it out with ✕ in the Grant menu";
const UNPICK_HINT = "Selected: press again to take it out of the selection";
const SOLO_HINT = "Select: press to add it to the selection; Grant asks its own passkey signature for it";
const grantView = {tray: null, sig: "", open: false};
const choices = new Map();
@@ -73,16 +74,17 @@
}
const picked = ui.selected.has(keyOf(item));
if (picked) {
button.disabled = true;
button.setAttribute("class", `${button.getAttribute("class")} picked`);
}
if (grantMode() !== GRANT_SELECT) {
button.disabled = picked;
if (picked) {
button.setAttribute("title", PICKED_HINT);
}
if (grantMode() === GRANT_SELECT) {
return button;
}
button.setAttribute("aria-pressed", String(picked));
if (!picked) {
button.setAttribute("title", solo(item) ? SOLO_HINT : "Select: press to add it to the selection; Grant grants it");
}
}
button.setAttribute("title", picked ? UNPICK_HINT : solo(item) ? SOLO_HINT : "Select: press to add it to the selection; Grant grants it");
return button;
}
+1 -1
View File
@@ -158,7 +158,7 @@
}
function legend() {
return h("div", {class: "legend", "data-star-slot": ""}, LEGEND.map(([name, label]) => h("span", {}, h("i", {class: `swatch t-${name}`}), label)),
return h("div", {class: "legend", "data-legend-slot": ""}, LEGEND.map(([name, label]) => h("span", {}, h("i", {class: `swatch t-${name}`}), label)),
h("span", {class: "muted"}, "Line width = count · closeness = recent collaboration"));
}
+1 -2
View File
@@ -6,7 +6,6 @@
function hierarchyScreen() {
hier.chart = h("section", {class: "card org-chart", "data-panel": "agents/hierarchy", "aria-labelledby": "org-title"});
orderDom.box = h("section", {class: "card agent-order", id: "agent-order", "aria-labelledby": "agent-order-title", "data-panel": "agents/order"});
orderDom.slot = h("span", {"data-star-slot": ""});
hier.sig = "";
return h("div", {class: "hierarchy-body"}, hier.chart, orderDom.box);
}
@@ -190,7 +189,7 @@
const count = state.claims.length;
const chart = organigram();
hier.chart.replaceChildren(
h("div", {class: "inbox-head", "data-star-slot": ""}, h("h2", {class: "group-title", id: "org-title"}, "Organigram", counter(count)),
h("div", {class: "inbox-head"}, h("h2", {class: "group-title", id: "org-title"}, "Organigram", counter(count)),
h("span", {class: "muted"}, "Formal offices from the council: Operator, Chair, line and staff positions"),
h("span", {class: "spacer"}),
h("button", {type: "button", class: "btn small soft", "data-focus": "appoint:new", ...named("New office", "New office: give a free office to a session, with a passkey signature"), on: {click: () => officeSheet("appoint", null)}}, icon("bi-person-plus"), "New office")),
+36 -4
View File
@@ -137,7 +137,7 @@
const tasks = node ? node.tasks : [];
const claims = node ? node.claims : [];
return h("div", {class: "home-agent"},
h("div", {class: "who"}, face(key, true), person(nameOf(key)), presenceMark(key, true)),
h("div", {class: "who"}, agentLink(key, true), presenceMark(key, true)),
h("p", {class: "muted"}, claims.length ? `Offices: ${claims.map((claim) => claim.office).join(", ")}` : "No office"),
tasks.length ? h("ul", {class: "mini"}, tasks.map((task) => h("li", {}, h("div", {class: "row"}, h("code", {}, task.task), status(task.status)), h("span", {}, dash(task.title)))))
: h("p", {class: "muted"}, "No open tasks."));
@@ -190,6 +190,7 @@
Panels.panel("tasks/operator", "Tasks: Waits on Operator", homeInbox);
Panels.panel("tasks/match", "Tasks: Match", () => homeMatch(), "", [6, 8]);
Panels.panel("resources-accounts", "Resources: accounts", () => homeAccounts(), "", [12, 5]);
Panels.panel("stream/schedules", "Controls: schedules", () => schedulesContent(), "", [12, 6]);
Panels.item("metric", (id, view) => metricTitle(view), (size, id, view) => homeMetric(id, view));
Panels.capture("resources-hardware", () => resourcePin("hardware"));
Panels.capture("resources-tokens", () => resourcePin("tokens"));
@@ -202,14 +203,14 @@
function homeOrder() {
const order = state.agent_order;
return order.length ? h("ol", {class: "order-list home-order"}, order.map((name, index) => h("li", {"data-name": name}, h("span", {class: "rank"}, `${index + 1}.`), face(name, false), person(name))))
return order.length ? h("ol", {class: "order-list home-order"}, order.map((name, index) => h("li", {"data-name": name}, h("span", {class: "rank"}, `${index + 1}.`), agentLink(name))))
: h("p", {class: "muted"}, "No agent with an office or an open task.");
}
function homeInbox() {
const items = visibleInbox();
return items.length ? h("ol", {class: "home-inbox"}, items.map((item) => h("li", {class: `k-${item.kind}`, "data-wait": keyOf(item)},
h("div", {class: "msg-meta"}, when(item.ts), pill(ITEM_LABELS[item.kind], KIND_TONES[item.kind]), item.agent ? [face(item.agent, false), person(item.agent)] : null),
h("div", {class: "msg-meta"}, when(item.ts), pill(ITEM_LABELS[item.kind], KIND_TONES[item.kind]), item.agent ? agentLink(item.agent) : null),
inboxHeadline(item),
h("div", {class: "item-actions line-actions"}, actionsFor(item))))) : emptyState("All done", "Nothing is waiting for you right now.");
}
@@ -573,6 +574,36 @@
}
}
const HOME_DOMINANT = 0.75;
const boxed = (look) => parseFloat(look.borderTopWidth) > 0 || look.backgroundColor !== "rgba(0, 0, 0, 0)" || look.backgroundImage !== "none";
const areaOf = (node) => node.offsetWidth * node.offsetHeight;
/**
* @param {Element} body a tile's .home-body.
* Walks down from the body's content through the child that covers at least HOME_DOMINANT of its parent's area, or
* into the one box of a wrapper that holds only it and .legend rows (Gantt, RASCI); the first box on that path
* (border, background) becomes .home-flat and fills the body, the wrappers above it .home-chain.
*/
function homeFlatten(body) {
if (!body.isConnected) {
return;
}
body.querySelectorAll(".home-flat, .home-chain").forEach((node) => node.classList.remove("home-flat", "home-chain"));
const chain = [];
for (let node = body.firstElementChild; node;) {
if (boxed(getComputedStyle(node))) {
chain.forEach((wrapper) => wrapper.classList.add("home-chain"));
node.classList.add("home-flat");
return;
}
chain.push(node);
const biggest = [...node.children].reduce((best, child) => (!best || areaOf(child) > areaOf(best) ? child : best), null);
const boxes = [...node.children].filter((child) => boxed(getComputedStyle(child)));
const legended = boxes.length === 1 && [...node.children].every((child) => child === boxes[0] || child.matches(".legend"));
node = legended ? boxes[0] : biggest && areaOf(biggest) >= HOME_DOMINANT * areaOf(node) ? biggest : null;
}
}
function homeContent(entry, pin) {
try {
return entry.render({w: pin.w, h: pin.h});
@@ -598,6 +629,7 @@
const shown = content || homeGone(pin, key);
if (body.childNodes.length !== 1 || body.firstChild !== shown) {
body.replaceChildren(shown);
window.requestAnimationFrame(() => homeFlatten(body));
}
paintZoom(tile);
}
@@ -655,7 +687,7 @@
homeView.mark();
});
ViewStore.on(ZOOM_PATH, () => drawHome());
homeView.mark = Panels.decorate(document.body, {pinned: (kind, id) => Panels.has(homePins(), kind, id), press: homePress, marks: HOME_MARKS});
homeView.mark = Panels.decorate(document.body, HOME_MARKS);
window.addEventListener("pointermove", homeDragMove);
window.addEventListener("pointerup", homeDragEnd);
window.addEventListener("pointercancel", homeDragEnd);
+60 -24
View File
@@ -1,5 +1,6 @@
let inboxSlot = null;
let inboxDoneOpen = false;
const GONE_NOTICE = "already done or removed elsewhere";
const doneItem = (item) => Boolean(item.held || (item.job && !jobOpen(item.job)));
function closeGone(result, keys, label) {
if (result.status !== 404 || !keys.length) {
@@ -71,7 +72,18 @@
return true;
}
/**
* @returns {string} what happens after a signature with the undo window the operator set: "3 s remain to undo",
* or "it takes effect at once" for 0.
*/
const undoWords = () => (settings.undo > 0 ? `${settings.undo} s remain to undo` : "it takes effect at once");
function undoToast(batch, label) {
if (!(batch.due > nowSeconds())) {
toast(label, ["Done: no undo window is set."], true);
load();
return;
}
const left = h("span", {class: "muted"});
const button = h("button", {type: "button", class: "btn small", ...named("Undo")}, icon("bi-arrow-counterclockwise"), "Undo");
const box = h("div", {class: "toast wait", role: "status"}, h("strong", {}, label), h("div", {class: "undo-row"}, left, h("span", {class: "spacer"}), button));
@@ -195,12 +207,12 @@
return [...state.inbox.filter((entry) => entry.kind === "review" && linked.has(entry.id) && !entry.held && !keys.has(keyOf(entry))), ...items];
}
const DENY_NOTE = "Every entry and every full command that gets denied; each requester gets its denial and the reason by post. After the click 3 s remain for undo, and one passkey signature covers the whole selection.";
const denyNote = () => `Every entry and every full command that gets denied; each requester gets its denial and the reason by post. After the click ${undoWords()}, and one passkey signature covers the whole selection.`;
function grantNote(alone, batched) {
const solos = alone ? ` Each rule and each red-gate review first asks its own signature, one after the other (${alone}).` : "";
const rest = batched ? ` ${alone ? "Then the" : "The"} passkey signs the rest once, commit rows settling after the reviews they verify.` : "";
return `Every entry and every full command that gets granted.${solos}${rest} Each signature leaves 3 s to undo.`;
return `Every entry and every full command that gets granted.${solos}${rest} After each signature ${undoWords()}.`;
}
function bulk(items, label, deny) {
@@ -236,7 +248,7 @@
}
}
});
openSheet(label, [h("p", {class: "muted"}, deny ? DENY_NOTE : grantNote(alone.length, usable.length)), h("ul", {class: "mini"}, rows), ...(deny ? [reasonChips(reason), h("label", {class: "deny-reason"}, "Reason (optional, every requester reads it)", reason)] : []),
openSheet(label, [h("p", {class: "muted"}, deny ? denyNote() : grantNote(alone.length, usable.length)), h("ul", {class: "mini"}, rows), ...(deny ? [reasonChips(reason), h("label", {class: "deny-reason"}, "Reason (optional, every requester reads it)", reason)] : []),
h("div", {class: "actions"}, h("span", {class: "spacer"}), btn("Cancel", "btn ghost", closeSheet), confirm)], false);
(reason || confirm).focus();
}
@@ -252,7 +264,7 @@
return {
chosen,
grant: h("button", {type: "button", class: "btn small primary", ...named(`Grant selection (${grantable.length})`), disabled: !grantable.length || ui.busy, on: {click: () => bulk(withReviews(chosen), "Grant selection", false)}}, icon("bi-check2-square"), `Grant ${grantable.length}`),
deny: h("button", {type: "button", class: "menu-item danger", ...named(`Deny selection (${denials.length})`, `Deny selection (${denials.length}): each requester gets its denial and an optional reason by post, 3 s to undo, one passkey signature`), disabled: !denials.length || ui.busy, on: {click: () => bulk(chosen, "Deny selection", true)}}, icon("bi-x-square"), `Deny ${denials.length}`),
deny: h("button", {type: "button", class: "menu-item danger", ...named(`Deny selection (${denials.length})`, `Deny selection (${denials.length}): each requester gets its denial and an optional reason by post, one passkey signature, then ${undoWords()}`), disabled: !denials.length || ui.busy, on: {click: () => bulk(chosen, "Deny selection", true)}}, icon("bi-x-square"), `Deny ${denials.length}`),
green: h("button", {type: "button", class: "menu-item", ...named(`Grant all green (${green.length})`), disabled: !green.length || ui.busy, on: {click: () => bulk(green, "Grant all green", false)}}, icon("bi-check2-all"), `Grant all green ${green.length}`),
};
}
@@ -272,7 +284,7 @@
return date.getTime() / 1000;
}
function toggle(item, refocus) {
function toggle(item) {
if (!item || !pickable(item)) {
return;
}
@@ -281,10 +293,6 @@
ui.cursor = Math.max(visibleInbox().findIndex((entry) => keyOf(entry) === key), 0);
drawInbox();
drawGrant();
const box = inboxDom.querySelector(`.item[data-index="${ui.cursor}"] > input[type="checkbox"]`);
if (refocus && box) {
box.focus({preventScroll: true});
}
}
function reviewsPill(item) {
@@ -366,17 +374,33 @@
return "";
}
/**
* @param {Object} item an inbox item.
* @param {Array} actions its Grant and Deny nodes.
* @returns {HTMLElement|null} one code box with the item's command and diff and the actions in its foot, or null for an
* item with neither.
*/
function itemCode(item, actions) {
const commanded = item.kind === "ask" || (item.kind === "operator" && !asked(item));
const command = commanded ? h("div", {class: "command", "data-path": item.directory || "-"}, h("code", {}, revealed(item.command))) : null;
const where = commanded ? h("span", {class: "muted code-where"}, revealed(`in ${dash(item.directory)}`)) : null;
const diff = diffBlocks(item);
return command || diff ? codeBox(keyOf(item), "preview", [command, where, diff], commanded ? item.command : "", actions, null) : null;
}
function inboxItem(item, index) {
const red = item.kind === "review" && item.gate !== "pass";
const commanded = item.kind === "ask" || (item.kind === "operator" && !asked(item));
const wait = waitOf(item);
const actions = actionsFor(item);
const code = itemCode(item, actions);
const classes = ["item", "entry", `k-${item.kind}`, "waiting", isGreen(item) ? "green" : "", red ? "red" : "", item.held ? "held" : "", wait ? "pending" : "", index === ui.cursor ? "cursor" : ""].filter(Boolean).join(" ");
const box = h("input", {type: "checkbox", "aria-label": `Select ${item.title}`, checked: ui.selected.has(keyOf(item)), disabled: !pickable(item), on: {change: () => toggle(item, true)}});
return h("li", {class: classes, "data-index": index, "data-ref": keyOf(item), "data-to": item.to || null, "data-blocked": item.blocked ? "" : null, "aria-busy": wait ? "true" : null, title: item.blocked || wait || null},
box,
const done = doneItem(item);
const selected = grantMode() === GRANT_SELECT ? String(ui.selected.has(keyOf(item))) : null;
return h("li", {class: classes, "data-index": index, "data-ref": keyOf(item), "data-to": item.to || null, "data-blocked": item.blocked ? "" : null, "data-done": done ? "" : null, "aria-selected": selected, "aria-busy": wait ? "true" : null, title: item.blocked || wait || null},
h("div", {class: "msg-meta"},
when(item.ts),
wait ? h("span", {class: "wait-spin", role: "status", "aria-label": wait, title: wait}) : null,
done ? pill("done", "ok") : null,
asked(item) ? pill("Decision", KIND_TONES.decision) : pill(ITEM_LABELS[item.kind], KIND_TONES[item.kind]),
item.kind === "review" ? pill(item.gate === "pass" ? "Gate green" : "Gate red", item.gate === "pass" ? "ok" : "bad") : null,
reviewsPill(item),
@@ -386,20 +410,18 @@
h("div", {class: "entry-body"},
h("div", {class: "route"},
inboxHeadline(item),
item.agent ? [face(item.agent, false), person(item.agent)] : null),
item.agent ? agentLink(item.agent) : null),
item.kind === "review" ? h("div", {class: "muted"}, revealed(item.detail), item.score ? revealed(` · ${item.score}`) : "") : null,
commanded ? h("div", {class: "command", "data-path": item.directory || "-"}, h("code", {}, revealed(item.command)), copyButton(item.command)) : null,
commanded ? h("span", {class: "muted"}, revealed(`in ${dash(item.directory)}`)) : null,
asked(item) ? h("p", {class: "text question"}, revealed(item.title)) : null,
item.kind === "operator" && item.detail && item.detail !== "-" ? h("p", {class: "text reason"}, revealed(item.detail)) : null,
item.blocked ? h("p", {class: "item-blocked"}, icon("bi-slash-circle"), item.blocked) : null,
diffBlocks(item),
code,
item.job ? consoleOf(item.job) : null,
item.kind === "rule" ? ruleRequestBody(item) : null,
choiceOf(item, () => {}),
feedbackList(keyOf(item))),
h("div", {class: "item-actions line-actions"},
actionsFor(item),
code ? null : actions,
h("span", {class: "spacer"}),
iconBtn("bi-hourglass-split", "1 h", "btn small ghost", () => mark(item, nowSeconds() + 3600, item.pinned), "1 h: snooze for one hour"),
iconBtn("bi-sunrise", "tomorrow", "btn small ghost", () => mark(item, tomorrow(), item.pinned), "tomorrow: snooze until 8 am tomorrow"),
@@ -409,7 +431,6 @@
function inboxScreen() {
inboxDom = h("div", {class: "inbox", "data-panel": "tasks/operator"});
inboxSlot = h("span", {"data-star-slot": ""});
return inboxDom;
}
@@ -437,14 +458,29 @@
ui.snoozed = event.target.checked;
drawInbox();
}}});
keepTyping(inboxDom, () => Panels.keepFocus(inboxSlot, () => inboxDom.replaceChildren(
keepTyping(inboxDom, () => inboxDom.replaceChildren(
h("div", {class: "inbox-head"}, h("h2", {class: "group-title"}, "Waits on Operator", counter(waitingCount())), h("span", {class: "spacer"}),
hidden ? h("label", {class: "check"}, snoozed, `${hidden} snoozed`) : null, inboxSlot),
hidden ? h("label", {class: "check"}, snoozed, `${hidden} snoozed`) : null),
onLocalhost() ? "" : h("p", {class: "muted"}, "The passkey signs grants only under ", localLink()),
items.length ? h("ol", {class: "inbox-list"}, items.map(inboxItem)) : emptyState("All done", "Nothing is waiting for you right now."))));
...inboxRows(items)));
settleConsoles(items);
}
/**
* @param {Object[]} items the visible inbox items in cursor order.
* @returns {Array} the open rows, then the done rows (signed within their undo window, or their job ended) under a
* Done (n) fold at the end, closed until the operator opens it.
*/
function inboxRows(items) {
const rows = items.map((item, index) => [item, index]);
const live = rows.filter(([item]) => !doneItem(item));
const done = rows.filter(([item]) => doneItem(item));
const fold = done.length ? h("details", {class: "inbox-done", open: inboxDoneOpen, on: {toggle: (event) => {
inboxDoneOpen = event.currentTarget.open;
}}}, h("summary", {}, `Done (${done.length})`), h("ol", {class: "inbox-list"}, done.map(([item, index]) => inboxItem(item, index)))) : null;
return [live.length ? h("ol", {class: "inbox-list"}, live.map(([item, index]) => inboxItem(item, index))) : emptyState("All done", "Nothing is waiting for you right now."), fold].filter(Boolean);
}
function openItem(item) {
if (!item) {
return;
@@ -454,7 +490,7 @@
return;
}
const body = [
h("div", {class: "who"}, pill(ITEM_LABELS[item.kind], KIND_TONES[item.kind]), item.agent ? face(item.agent, false) : null, item.agent ? person(item.agent) : null, when(item.ts)),
h("div", {class: "who"}, pill(ITEM_LABELS[item.kind], KIND_TONES[item.kind]), item.agent ? agentLink(item.agent) : null, when(item.ts)),
h("p", {class: "text"}, revealed(item.title)),
item.command && !asked(item) ? h("div", {class: "command"}, h("code", {}, revealed(item.command)), copyButton(item.command)) : null,
asked(item) && item.detail && item.detail !== "-" ? h("p", {class: "text reason"}, revealed(item.detail)) : null,
+1 -1
View File
@@ -173,7 +173,7 @@
},
},
},
h("div", {class: "head-row", "data-star-slot": ""}, queuePlace(row), h("code", {class: "task-id"}, row.task), cardLabels(row), h("span", {class: "spacer"}),
h("div", {class: "head-row"}, queuePlace(row), h("code", {class: "task-id"}, row.task), cardLabels(row), h("span", {class: "spacer"}),
row.pending ? h("span", {class: "kanban-pending", role: "img", ...named("Staged", row.pending.map(shownArgv).join("\n"))}, icon("bi-pencil")) : null,
openJobs(row.task).length ? h("span", {class: "kanban-wait", role: "img", ...named("At the runner", `${row.task}: a signed change waits for the runner`)}, icon("bi-hourglass-split")) : null,
row.editable ? h("span", {class: "kanban-handle", role: "img", draggable: "true", ...named("Follows", `Drag onto the card that waits for ${row.task}`), on: {dragstart: dragFrom(row.task, "after"), dragend: () => {
+2 -2
View File
@@ -62,7 +62,7 @@
moveCursor(event.key === "j" ? 1 : -1);
} else if (inInbox && event.key === "x") {
event.preventDefault();
toggle(current, false);
toggle(current);
} else if (inInbox && event.key === "a") {
event.preventDefault();
if (current && !current.held) {
@@ -70,7 +70,7 @@
}
} else if (event.key === "f" && feedbackKey()) {
event.preventDefault();
} else if (event.key.startsWith("Arrow") && (target === document.body || (target instanceof Element && target.closest(".match-stack"))) && matchKey(event.key)) {
} else if ((event.key.startsWith("Arrow") || /^[wasd]$/i.test(event.key)) && (target === document.body || (target instanceof Element && target.closest(".match-stack"))) && matchKey(event.key)) {
event.preventDefault();
} else if (event.key === "Enter" && current && target === document.body) {
event.preventDefault();
+12 -2
View File
@@ -60,13 +60,23 @@
const ownOf = (host, selector) => [...host.querySelectorAll(selector)].find((node) => node.closest(Panels.HOSTS) === host) || null;
function legendSlot(host) {
const own = ownOf(host, "[data-legend-slot]") || [...host.children].find((child) => child.classList.contains("legend-row"));
if (own) {
return own;
}
const row = h("div", {class: "legend-row"});
host.prepend(row);
return row;
}
function markLegends() {
for (const host of document.querySelectorAll("#main [data-panel]")) {
if (host.closest(".home-tile")) {
continue;
}
const star = ownOf(host, ".star");
legendFor(host, LEGEND_PATHS.view, host.dataset.panel, star && ownOf(host, LEGEND_PARTS) ? (button) => star.nextElementSibling !== button && star.after(button) : null);
const slot = ownOf(host, LEGEND_PARTS) ? legendSlot(host) : null;
legendFor(host, LEGEND_PATHS.view, host.dataset.panel, slot ? (button) => slot.lastElementChild !== button && slot.append(button) : null);
}
for (const tile of document.querySelectorAll(".home-tile[data-pin]")) {
const open = tile.querySelector(".home-open");
+1 -1
View File
@@ -32,7 +32,7 @@
render(false);
drawTime();
drawAgent();
drawStream();
drawStream(true);
if (motion.current.size === 0 || ui.asOf !== motion.asOf) {
const first = motion.current.size === 0;
motion.asOf = ui.asOf;
+291 -110
View File
@@ -11,7 +11,9 @@
const CONFETTI = 28;
const COMMENTS_KEPT = 5;
const PATTERNS = ["dots", "stripes", "waves", "grid", "rings"];
const matchView = {cards: null, order: [], marks: new Map(), opened: new Map(), decisions: new Map(), toggles: new Map(), overview: false, front: null, drag: null, dom: null, sig: "", fetched: 0, loading: false, press: null, flying: false, openBefore: 0, epoch: 0};
const RELEASE = "release";
const MOVES = {ArrowRight: "accept", d: "accept", ArrowLeft: "reject", a: "reject", ArrowUp: "later", w: "later", s: "undo"};
const matchView = {cards: null, order: [], marks: new Map(), opened: new Map(), decisions: new Map(), toggles: new Map(), history: [], release: null, releasing: false, front: null, drag: null, dom: null, sig: "", fetched: 0, loading: false, press: null, flying: false, openBefore: 0, epoch: 0};
/**
* @returns {Promise<void>} settled when this read ends, at once while another runs; a response requested before
@@ -44,13 +46,43 @@
drawMatch();
}
const toFront = (id) => {
matchView.order = [id, ...matchView.order.filter((one) => one !== id)];
};
const toBack = (id) => {
matchView.order = [...matchView.order.filter((one) => one !== id), id];
};
/**
* @param {string} id the card the step acts on, or RELEASE.
* Keeps the order and the card's decision from before the step, so S can put both back.
*/
function logStep(id) {
matchView.history.push({id, order: [...matchView.order], decision: matchView.decisions.get(id)});
}
function undoStep() {
const step = matchView.history.pop();
if (!step) {
toast("Nothing to undo", ["Every step back to the last release is undone."], false);
return;
}
matchView.order = step.order;
if (step.decision) {
matchView.decisions.set(step.id, step.decision);
} else {
matchView.decisions.delete(step.id);
}
drawMatch(true);
}
function matchOrder(cards) {
const ids = new Set(cards.map((card) => card.id));
const kept = matchView.order.filter((id) => ids.has(id));
const kept = matchView.order.filter((id) => ids.has(id) || id === RELEASE);
const fresh = cards.filter((card) => !kept.includes(card.id)).sort((a, b) => Number(Boolean(a.blocked)) - Number(Boolean(b.blocked)) || 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));
return matchView.order.filter((id) => id !== RELEASE).map((id) => byId.get(id));
}
function ageWords(born) {
@@ -63,6 +95,16 @@
const cardKey = (card) => `${card.id}@${card.hash}`;
/**
* @param {object} card a card as /api/match serves it now.
* @returns {object|undefined} its decision: a reject by card id whatever the card's hash, an accept only for the
* exact hash it was made on.
*/
function decisionOf(card) {
const decision = matchView.decisions.get(card.id);
return decision && (decision.verdict === "reject" || decision.hash === card.hash) ? decision : undefined;
}
/**
* @returns {string[]} this browser's last COMMENTS_KEPT distinct saved line comments, newest first.
*/
@@ -72,6 +114,15 @@
}
const peeksShown = () => stored(STORE.peeks, true) !== false;
const matchWide = () => stored(STORE.wide, false) === true;
function widenToggle() {
const wide = matchWide();
return iconBtn(wide ? "bi-arrows-angle-contract" : "bi-arrows-angle-expand", wide ? "Normal width" : "Full width", "btn small ghost match-widen", () => {
keep(STORE.wide, !matchWide());
drawMatch(true);
}, wide ? "Normal width: the card back to at most 960 px" : "Full width: the card over the whole Match area");
}
function rememberComment(text) {
keep(STORE.comments, [text, ...savedComments().filter((old) => old !== text)].slice(0, COMMENTS_KEPT));
@@ -182,27 +233,34 @@
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 codeRow(event, selector) {
const row = event.target instanceof Element ? event.target.closest(selector) : null;
return row && !row.classList.contains("match-mark") && !row.classList.contains("match-comment") ? row : null;
}
function markable(article, data) {
article.addEventListener("contextmenu", (event) => {
const row = codeRow(event);
/**
* @param {HTMLElement} root the element whose code rows take marks: a Match card or the review modal's diff.
* @param {string} selector the code rows inside root.
* @param {Function} open takes the row a right-click or a touch long press hit and opens its comment field;
* Shift+right-click keeps the browser's own menu.
*/
function markable(root, selector, open) {
root.addEventListener("contextmenu", (event) => {
const row = event.shiftKey ? null : codeRow(event, selector);
if (row) {
event.preventDefault();
commentField(article, data, row);
event.stopPropagation();
open(row);
}
});
article.addEventListener("pointerdown", (event) => {
const row = codeRow(event);
root.addEventListener("pointerdown", (event) => {
const row = codeRow(event, selector);
if (!row || event.pointerType !== "touch") {
return;
}
const press = {x: event.clientX, y: event.clientY, timer: window.setTimeout(() => {
matchView.press = null;
commentField(article, data, row);
open(row);
}, LONG_PRESS)};
matchView.press = press;
});
@@ -212,13 +270,13 @@
matchView.press = null;
}
};
article.addEventListener("pointermove", (event) => {
root.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);
root.addEventListener("pointerup", drop);
root.addEventListener("pointercancel", drop);
}
/**
@@ -265,8 +323,8 @@
function matchHead(card) {
const [kindName, kindTone, kindIcon] = MATCH_KINDS[card.kind] || [card.kind, "neutral", "bi-collection"];
const metrics = card.metrics || [];
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))),
return h("header", {class: "match-head"}, widenToggle(),
h("div", {class: "match-who"}, agentLink(card.agent || "-", true, "match-name"), h("span", {class: "match-age"}, ageWords(card.born))),
metrics.length ? h("ul", {class: "match-metrics", "aria-label": "Scores"}, metrics.map((metric) => h("li", {class: "match-metric", "data-metric": metric.id, title: revealed(`${metric.label}: ${metric.value}`)},
h("span", {"aria-hidden": "true"}, metric.emoji), h("span", {class: "match-metric-label"}, metric.label), h("strong", {}, revealed(metric.value))))) : null,
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,
@@ -282,7 +340,7 @@
*/
function matchOptions(card) {
const key = cardKey(card);
const kept = matchView.decisions.get(key);
const kept = decisionOf(card);
const toggled = matchView.toggles.get(key) || new Set(kept ? kept.label.split(PICKED) : []);
matchView.toggles.set(key, toggled);
const pick = (label) => {
@@ -300,7 +358,7 @@
return h("section", {class: "match-payload"}, ruleRequestBody({...card, detail: card.reason}));
}
if (card.kind === "ask") {
return h("section", {class: "match-payload"}, h("pre", {class: "match-command"}, h("code", {}, revealed(card.command))), h("p", {class: "match-directory"}, revealed(card.directory)),
return h("section", {class: "match-payload"}, h("p", {class: "match-directory"}, revealed(card.directory)),
card.warnings.length ? h("p", {class: "match-warnings"}, card.warnings.map((warning) => pill(warning, "bad"))) : null);
}
if (card.kind !== "command") {
@@ -311,7 +369,6 @@
const preview = merge ? h("p", {class: "match-merge", "data-error": String(Boolean(merge.error))}, icon(merge.error ? "bi-exclamation-triangle" : "bi-sign-merge-left"),
merge.error ? `No merge preview: ${merge.error}` : `Brings in ${short(merge.base)} → ${short(merge.target)}, onto HEAD ${short(merge.head)}`) : null;
return h("section", {class: "match-payload"},
h("pre", {class: "match-command"}, h("code", {}, revealed(card.command))),
h("p", {class: "match-directory"}, revealed(card.directory)),
card.reason && card.reason !== "-" ? h("p", {class: "match-reason"}, revealed(card.reason)) : null, preview);
}
@@ -332,13 +389,16 @@
const files = card.files || [];
const none = card.kind === "commit" ? (card.diff_error ? `No diff shipped with this stage. ${card.diff_error}` : "No diff shipped with this stage.") : card.kind === "ask" ? "Its tool call changes no file." : card.merge ? (card.merge.error ? "No diff to show." : "The merge brings no change.") : "Its command names no file.";
const list = files.length ? h("ol", {class: "match-files", "aria-label": `Files: ${files.length}`}, files.map((file, index) => fileBlock(card, file, index))) : card.kind === "decision" || card.kind === "rule" ? null : h("p", {class: "muted"}, none);
const body = h("div", {class: "match-body"}, card.blocked ? h("p", {class: "match-blocked"}, icon("bi-hourglass-split"), revealed(card.blocked)) : null, matchPayload(card), list);
const commanded = card.kind === "ask" || card.kind === "command";
const command = commanded ? h("pre", {class: "match-command"}, h("code", {}, revealed(card.command))) : null;
const code = command || files.length ? codeBox(card.id, "open", [command, list], commanded ? card.command : "", [], null) : list;
const body = h("div", {class: "match-body"}, card.blocked ? h("p", {class: "match-blocked"}, icon("bi-hourglass-split"), revealed(card.blocked)) : null, matchPayload(card), code);
body.addEventListener("scroll", () => openOnScroll(body, ".match-file"), {passive: true});
const article = h("article", {class: "card match-card front", "data-card": card.id, "data-kind": card.kind, "data-stale": String(Boolean(card.stale)), ...(card.blocked ? {"data-blocked": "", title: card.blocked} : {}), "aria-label": `${card.kind} card of ${card.agent || "an agent"}`},
matchHead(card), body);
article.style.setProperty("--agent-hue", String(Faces.hash(card.agent) % 360));
paint(article, card.id);
markable(article, card);
markable(article, ".match-file tr[data-line]", (row) => commentField(article, card, row));
window.setTimeout(() => openOnScroll(body, ".match-file"), 0);
return article;
}
@@ -346,7 +406,7 @@
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)), ...(card.blocked ? {"data-blocked": ""} : {}), ...named(`Show ${kindName.toLowerCase()} card: ${card.title}`, card.blocked ? `${card.title}: ${card.blocked}` : undefined), on: {click: () => {
matchView.order = [card.id, ...matchView.order.filter((id) => id !== card.id)];
toFront(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)));
}
@@ -369,7 +429,7 @@
if (matchView.flying) {
return;
}
if (!front || window.matchMedia("(prefers-reduced-motion: reduce)").matches) {
if (!front || front.classList.contains("match-release-card") || window.matchMedia("(prefers-reduced-motion: reduce)").matches) {
then();
return;
}
@@ -396,7 +456,8 @@
*/
function decide(card, verdict, feedback, label) {
flyOff(verdict, () => {
matchView.decisions.set(cardKey(card), {verdict, feedback, label});
logStep(card.id);
matchView.decisions.set(card.id, {verdict, feedback, label, hash: card.hash, card, risk: false});
drawMatch(true);
});
}
@@ -454,7 +515,7 @@
toast("Reject: not possible", ["A choice is answered with one of its options."], false);
return;
}
const kept = matchView.decisions.get(cardKey(card));
const kept = decisionOf(card);
const words = h("textarea", {class: "field match-feedback", rows: 6, maxlength: FEEDBACK_LIMIT, "aria-label": "Feedback", "data-skills": card.repo || ""});
words.value = (kept && kept.verdict === "reject" ? kept.feedback : feedbackOf(card)).slice(0, FEEDBACK_LIMIT);
const confirm = h("button", {type: "button", class: "btn danger match-feedback-reject"}, icon("bi-x-lg"), "Reject");
@@ -470,29 +531,47 @@
function laterCard(card) {
flyOff("later", () => {
matchView.order = [...matchView.order.filter((id) => id !== card.id), card.id];
logStep(card.id);
toBack(card.id);
drawMatch(true);
});
}
/**
* @param {string} key the key of a keydown the global handler did not take.
* @returns {boolean} whether the Match stack took it: the right arrow accepts the front card, the left arrow
* rejects it, the up arrow sends it to the back.
* @returns {boolean} whether the Match stack took it: D or the right arrow accepts the front card, A or the left
* arrow rejects it, W or the up arrow skips to the next card, S undoes the last step; on the release card D
* releases, A and W go on to the next card.
*/
function matchKey(key) {
const card = matchView.front;
if (!card || ui.screen !== "match" || !matchView.dom || !matchView.dom.stack.isConnected) {
const move = MOVES[key.length === 1 ? key.toLowerCase() : key];
if (!move || ui.screen !== "match" || !matchView.dom || !matchView.dom.stack.isConnected) {
return false;
}
const act = {ArrowRight: acceptCard, ArrowLeft: rejectCard, ArrowUp: laterCard}[key];
if (act) {
act(card);
if (move === "undo") {
undoStep();
return true;
}
return Boolean(act);
if (matchView.release) {
const run = matchView.release[move];
if (run) {
run();
}
return Boolean(run);
}
const card = matchView.front;
if (card) {
({accept: acceptCard, reject: rejectCard, later: laterCard})[move](card);
}
return Boolean(card);
}
function draggable(article, card) {
/**
* @param {HTMLElement} article the front card, dragged by its head.
* @param {object} acts what a swipe runs: accept (right), reject (left), later (up); a missing one leaves the card.
* @param {Function} stays takes the swipe and tells whether the card keeps its offset while it flies off.
*/
function draggable(article, acts, stays) {
const head = article.querySelector(".match-head");
const move = (event) => {
const drag = matchView.drag;
@@ -514,14 +593,14 @@
const far = SWIPE_SHARE * article.getBoundingClientRect().width;
const swiped = event.type === "pointercancel" ? "" : Math.abs(dx) >= far && Math.abs(dx) > Math.abs(dy) ? (dx > 0 ? "accept" : "reject") : -dy >= SWIPE_UP && -dy > Math.abs(dx) ? "later" : "";
article.style.removeProperty("--lean");
if (!((swiped === "accept" && flies(card)) || swiped === "later")) {
if (!(acts[swiped] && stays(swiped))) {
article.style.removeProperty("transform");
delete article.dataset.leaning;
}
if (!article.isConnected) {
if (!article.isConnected || !acts[swiped]) {
return;
}
({accept: acceptCard, reject: rejectCard, later: laterCard}[swiped] || (() => null))(card);
acts[swiped]();
};
head.addEventListener("pointerdown", (event) => {
if (event.button !== 0 || matchView.drag || (event.target instanceof Element && event.target.closest("button, a, input, textarea, select"))) {
@@ -559,22 +638,81 @@
return card.kind === "command" ? {...entry, payload: card.hash} : entry;
}
/**
* @param {Array<object>} cards the cards /api/match serves now, in stack order.
* @returns {Array<Array>} [card, decision] pairs: the decided cards in stack order, then each reject whose card is
* gone, as its card from the time of the reject marked withdrawn.
*/
function decided(cards) {
return cards.map((card) => [card, matchView.decisions.get(cardKey(card))]).filter(([, decision]) => decision);
const here = new Set(cards.map((card) => card.id));
const shown = cards.map((card) => [card, decisionOf(card)]).filter(([, decision]) => decision);
const gone = [...matchView.decisions.values()].filter((decision) => !here.has(decision.card.id)).map((decision) => [{...decision.card, withdrawn: true}, decision]);
return [...shown, ...gone];
}
const risky = (card, decision) => card.kind === "commit" && decision.verdict === "accept" && card.gate !== "pass";
const decisionWords = (count) => (count === 1 ? "1 decision" : `${count} decisions`);
/**
* @param {Array<Array>} picked [card, decision] pairs from decided().
* @returns {object} lone: risk-accepted red-gate commits, each signed on its own first; rest: every other decision
* signed together; gone: withdrawn rejects, sent by radio only; held: red-gate commits whose risk is not accepted,
* left out of the release and back to the stack once it ran.
*/
function releasePlan(picked) {
const signed = picked.filter(([card]) => !card.withdrawn);
return {
lone: signed.filter(([card, decision]) => risky(card, decision) && decision.risk),
rest: signed.filter(([card, decision]) => !risky(card, decision)),
gone: picked.filter(([card]) => card.withdrawn),
held: signed.filter(([card, decision]) => risky(card, decision) && !decision.risk),
};
}
async function releaseMatch(cards) {
const picked = decided(cards);
const released = await submit(picked.map(([card, decision]) => matchEntry(card, decision)), `Release: ${picked.length === 1 ? "1 decision" : `${picked.length} decisions`}`);
if (released) {
const gone = new Set(picked.map(([card]) => card.id));
const plan = releasePlan(decided(cards));
if (matchView.releasing || !(plan.lone.length + plan.rest.length + plan.gone.length)) {
return;
}
matchView.releasing = true;
const done = [];
try {
for (const pair of plan.lone) {
if (!(await submit([matchEntry(...pair)], `Release: ${pair[0].title}`))) {
return;
}
done.push(pair);
}
if (plan.rest.length && !(await submit(plan.rest.map((pair) => matchEntry(...pair)), `Release: ${decisionWords(plan.rest.length)}`))) {
return;
}
done.push(...plan.rest, ...plan.gone);
plan.held.forEach(([card]) => matchView.decisions.delete(card.id));
} finally {
matchView.releasing = false;
if (done.length) {
await settleRelease(done);
}
}
}
/**
* @param {Array<Array>} done the released [card, decision] pairs: their cards leave the stack, a withdrawn reject
* goes to its agent by radio call, the line notes of an accepted card by post.
*/
async function settleRelease(done) {
const gone = new Set(done.map(([card]) => card.id));
matchView.epoch += 1;
matchView.cards = matchView.cards.filter((card) => !gone.has(card.id));
picked.forEach(([card]) => matchView.decisions.delete(cardKey(card)));
matchView.overview = false;
done.forEach(([card]) => matchView.decisions.delete(card.id));
matchView.history = [];
drawMatch(true);
await fetchMatch();
for (const [card, decision] of picked) {
for (const [card, decision] of done) {
if (card.withdrawn) {
await radioSend({to: card.to || card.agent, text: `Rejected: ${card.title}. The card was withdrawn before the release. Feedback:\n${decision.feedback}`, upload: "", cls: "call", voice: ""});
continue;
}
const notes = decision.verdict === "accept" ? feedbackOf(card) : "";
if (notes && card.to) {
await radioSend({to: card.to, text: `Granted: ${card.title}. Notes:\n${notes}`, upload: "", cls: "post", voice: ""});
@@ -582,62 +720,87 @@
matchView.marks.delete(cardKey(card));
}
}
function riskButton(decision) {
const taken = Boolean(decision.risk);
const words = taken ? "Risk accepted" : "Accept risk: gate not green";
const hint = taken ? "Risk accepted: the commit gets its own passkey signature at the release; click to take it back" : "Accept risk: the gate is not green; until you click, the release leaves this commit out and it goes back to the stack";
return h("button", {type: "button", class: "btn small match-accept-risk", "aria-pressed": String(taken), "data-tone": taken ? "warn" : "bad", title: hint, on: {click: () => {
decision.risk = !taken;
drawMatch(true);
}}}, icon(taken ? "bi-shield-fill-exclamation" : "bi-shield-exclamation"), words);
}
function overviewRow(card, decision) {
const [kindName, kindTone, kindIcon] = MATCH_KINDS[card.kind] || [card.kind, "neutral", "bi-collection"];
const [word, tone, mark] = MATCH_VERDICTS[decision.verdict];
const other = decision.verdict === "accept" ? "reject" : "accept";
const flip = (other === "reject" && pickOnly(card)) || (other === "accept" && !flies(card)) ? null : iconBtn(MATCH_VERDICTS[other][2], MATCH_VERDICTS[other][0], "btn small ghost match-flip", () => (other === "accept" ? acceptCard(card) : rejectCard(card)), `${MATCH_VERDICTS[other][0]} instead`);
const back = iconBtn("bi-arrow-counterclockwise", "Back to the stack", "btn small ghost match-undecide", () => {
matchView.decisions.delete(cardKey(card));
matchView.overview = false;
const flip = card.withdrawn || (other === "reject" && pickOnly(card)) || (other === "accept" && !flies(card)) ? null : iconBtn(MATCH_VERDICTS[other][2], MATCH_VERDICTS[other][0], "btn small ghost match-flip", () => (other === "accept" ? acceptCard(card) : rejectCard(card)), `${MATCH_VERDICTS[other][0]} instead`);
const back = iconBtn("bi-arrow-counterclockwise", card.withdrawn ? "Drop the reject" : "Back to the stack", "btn small ghost match-undecide", () => {
matchView.decisions.delete(card.id);
toFront(card.id);
drawMatch(true);
});
return h("li", {class: "match-decision", "data-card": card.id, "data-verdict": decision.verdict},
h("div", {class: "row"}, face(card.agent || "-", false), h("span", {class: "pill", "data-tone": kindTone}, icon(kindIcon), kindName), h("strong", {class: "match-decision-title"}, revealed(card.title)), h("span", {class: "spacer"}),
h("span", {class: "pill match-verdict", "data-tone": tone}, icon(mark), decision.label ? revealed(`${word}: ${shownPick(decision.label)}`) : word), decision.verdict === "reject" ? iconBtn("bi-pencil", "Edit feedback", "btn small ghost match-edit", () => rejectCard(card)) : null, flip, back),
const held = risky(card, decision) && !decision.risk;
const note = card.withdrawn ? "Card withdrawn: the feedback goes to its agent by radio call at the release." : decision.verdict === "reject" && decision.hash !== card.hash ? "Card changed since your reject." : held ? "Left out of the release until you accept its risk: it goes back to the stack." : "";
return h("li", {class: "match-decision", "data-card": card.id, "data-verdict": decision.verdict, "data-withdrawn": String(Boolean(card.withdrawn)), "data-held": String(held)},
h("div", {class: "row"}, agentFace(card.agent || "-", false), h("span", {class: "pill", "data-tone": kindTone}, icon(kindIcon), kindName), h("strong", {class: "match-decision-title"}, revealed(card.title)), h("span", {class: "spacer"}),
h("span", {class: "pill match-verdict", "data-tone": tone}, icon(mark), decision.label ? revealed(`${word}: ${shownPick(decision.label)}`) : word), risky(card, decision) ? riskButton(decision) : null, decision.verdict === "reject" ? iconBtn("bi-pencil", "Edit feedback", "btn small ghost match-edit", () => rejectCard(card)) : null, flip, back),
note ? h("p", {class: "muted match-decision-note"}, icon("bi-info-circle"), note) : null,
decision.verdict === "reject" ? h("pre", {class: "match-decision-feedback"}, revealedLines(decision.feedback === "" ? "no feedback text" : decision.feedback)) : null);
}
/**
* @param {Array<object>} cards the cards in stack order.
* @returns {string} why the release waits, empty when it can go: a commit whose gate is not green is released
* only on its own, as the inbox grants it.
* @param {number} open how many cards wait undecided behind it.
* @returns {HTMLElement} the release card: front card of the deck with every decision, its own moves (D or a
* right swipe releases, A, W or a left swipe goes on to the next card) mirrored in matchView.release for the keys.
*/
function releaseBlock(cards) {
function releaseCard(cards, open) {
const picked = decided(cards);
if (!picked.length) {
return "Nothing decided yet.";
}
const lone = picked.find(([card, decision]) => card.kind === "commit" && decision.verdict === "accept" && card.gate !== "pass");
return lone && picked.length > 1 ? `The commit "${lone[0].title}" has no green gate and is released only on its own: send it back to the stack or release it alone.` : "";
}
function overview(cards, open) {
const picked = decided(cards);
const block = releaseBlock(cards);
const release = h("button", {type: "button", class: "btn primary match-release", disabled: Boolean(block), title: block || "One passkey signature releases every decision; 3 s remain to undo."},
icon("bi-key"), picked.length === 1 ? "Release 1 decision" : `Release ${picked.length} decisions`);
release.addEventListener("click", () => releaseMatch(cards));
const back = open ? iconBtn("bi-stack", `Back to the stack (${open})`, "btn ghost match-back", () => {
matchView.overview = false;
const plan = releasePlan(picked);
const count = plan.lone.length + plan.rest.length + plan.gone.length;
const signatures = plan.lone.length ? `${plan.lone.length === 1 ? "The risk-accepted commit gets its own" : `Each of the ${plan.lone.length} risk-accepted commits gets its own`} passkey signature first, then one signature releases the rest` : "One passkey signature releases every decision";
const run = () => releaseMatch(cards);
const back = open ? () => {
logStep(RELEASE);
toBack(RELEASE);
drawMatch(true);
}) : null;
return h("section", {class: "card match-overview", "aria-label": "Decisions"},
h("h2", {class: "panel-title"}, "Decisions"),
} : null;
const release = h("button", {type: "button", class: "btn primary match-release", disabled: !count, title: count ? `${signatures}; after each signature ${undoWords()}.` : "Nothing to release yet."},
icon("bi-key"), `Release ${decisionWords(count)}`);
release.addEventListener("click", run);
const article = h("article", {class: "card match-card front match-release-card match-overview", "data-card": "release", "aria-label": "Release card: the decisions"},
h("header", {class: "match-head"}, widenToggle(), h("h2", {class: "match-title"}, icon("bi-key"), "Release"),
h("p", {class: "muted match-release-hint"}, open ? "D, → or a right swipe releases; A, W, ← or a left swipe goes on to the next card; S undoes the last step." : "D, → or a right swipe releases; S undoes the last step.")),
h("div", {class: "match-body"},
h("p", {class: "muted"}, "Nothing has run yet. Accepted commits get the operator's signature for their exact tree, accepted commands run once as jobs under Waits on Operator, accepted asks are granted, every picked option and every rejection goes to its agent by radio call."),
picked.length ? h("ol", {class: "match-decisions"}, picked.map(([card, decision]) => overviewRow(card, decision))) : h("p", {class: "muted"}, "No decision yet."),
block && picked.length ? h("p", {class: "match-release-block"}, icon("bi-exclamation-triangle"), block) : null,
h("div", {class: "actions"}, back, h("span", {class: "spacer"}), release));
h("div", {class: "actions"}, back ? iconBtn("bi-stack", `Back to the stack (${open})`, "btn ghost match-back", back) : null, h("span", {class: "spacer"}), release)));
paint(article, "release");
matchView.release = {accept: count ? run : null, reject: back, later: back};
draggable(article, matchView.release, () => false);
return article;
}
/**
* @param {Array<object>} rest the cards lying behind the front card.
* @returns {Array<HTMLElement>} at most MATCH_PEEKS pile layers, deepest first.
*/
function layersOf(rest) {
return rest.slice(0, MATCH_PEEKS).map((card, index) => {
const layer = h("div", {class: "match-layer", "data-card": card.id, "data-depth": String(index + 1), "data-stale": String(Boolean(card.stale)), "aria-hidden": "true", inert: ""});
paint(layer, card.id);
return layer;
}).reverse();
}
function matchScreen() {
const stack = h("div", {class: "match-stack"});
const count = h("span", {class: "muted"});
const tally = h("span", {class: "match-tally"}, "0");
const decisions = h("button", {type: "button", class: "btn small soft match-open-overview", ...named("Decisions", "Decisions: the list of every decision, to change and release them"), on: {click: () => {
matchView.overview = true;
const decisions = h("button", {type: "button", class: "btn small soft match-open-overview", ...named("Decisions", "Decisions: the release card with every decision, to change and release them"), on: {click: () => {
toFront(RELEASE);
drawMatch(true);
}}}, icon("bi-card-checklist"), tally);
const peeks = h("button", {type: "button", class: "btn small soft match-peeks-toggle", "aria-pressed": String(peeksShown()), ...named("Next cards", "Next cards: show or hide the row of waiting cards below the buttons"), on: {click: () => {
@@ -650,7 +813,7 @@
matchView.drag.end();
}
const bar = boxHead("Match", "task-toolbar", h("strong", {class: "box-title"}, icon("bi-stack"), "Match"), count, h("span", {class: "spacer"}), decisions, peeks,
iconBtn("bi-list-check", "Tasks", "btn small soft", () => go("tasks", null), "Tasks: back to the task list"), h("span", {"data-star-slot": ""}));
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", "data-panel": "tasks/match"}, bar, stack);
}
@@ -686,61 +849,79 @@
return;
}
const cards = matchOrder(matchView.cards);
const byKey = new Map(cards.map((card) => [cardKey(card), card]));
[...matchView.decisions].forEach(([key, decision]) => {
const card = byKey.get(key);
if (!card || (decision.verdict === "accept" && card.stale)) {
matchView.decisions.delete(key);
const byId = new Map(cards.map((card) => [card.id, card]));
[...matchView.decisions].forEach(([id, decision]) => {
const card = byId.get(id);
if (decision.verdict === "accept" && (!card || card.stale || card.hash !== decision.hash)) {
matchView.decisions.delete(id);
if (card && card.hash !== decision.hash) {
toast(`Accept dropped: ${card.title}`, ["The card changed since your accept: decide it again."], false);
}
}
});
const open = cards.filter((card) => !matchView.decisions.has(cardKey(card)));
const shownOverview = matchView.overview || (!open.length && matchView.decisions.size > 0);
const sig = JSON.stringify([cards.map((card) => [card.id, card.hash, card.live_hash, card.stale, card.born, card.gate, card.files ? card.files.length : null]), [...matchView.decisions], shownOverview, Math.floor(state.now / DAY)]);
if (!force && sig === matchView.sig) {
const open = cards.filter((card) => !decisionOf(card));
const waiting = open.filter((card) => !card.stale && !card.blocked);
if (!matchView.decisions.size) {
matchView.order = matchView.order.filter((id) => id !== RELEASE);
} else if (!matchView.order.includes(RELEASE)) {
matchView.order.push(RELEASE);
}
const cleared = matchView.openBefore > 0 && !waiting.length && matchView.decisions.size > 0;
matchView.openBefore = waiting.length;
if (cleared) {
toFront(RELEASE);
}
const byOpen = new Map(open.map((card) => [card.id, card]));
const rotation = matchView.order.filter((id) => id === RELEASE || byOpen.has(id));
const releasing = rotation[0] === RELEASE;
const sig = JSON.stringify([cards.map((card) => [card.id, card.hash, card.live_hash, card.stale, card.born, card.gate, card.files ? card.files.length : null]), [...matchView.decisions].map(([id, decision]) => [id, decision.verdict, decision.feedback, decision.label, decision.hash, decision.risk]), rotation, Math.floor(state.now / DAY)]);
if (!force && sig === matchView.sig && !cleared) {
return;
}
matchView.sig = sig;
const cleared = matchView.openBefore > 0 && !open.length;
matchView.openBefore = open.length;
dom.count.textContent = open.length === 1 ? "1 card waits" : `${open.length} cards wait`;
dom.tally.textContent = String(matchView.decisions.size);
dom.peeks.setAttribute("aria-pressed", String(peeksShown()));
dom.decisions.hidden = !matchView.decisions.size || shownOverview;
if (!cards.length) {
dom.decisions.hidden = !matchView.decisions.size || releasing;
matchView.release = null;
if (!rotation.length) {
matchView.front = null;
dom.stack.replaceChildren(emptyState("No card waits", "Nothing waits on the operator."));
return;
}
if (shownOverview) {
const behind = rotation.slice(1).filter((id) => id !== RELEASE).map((id) => byOpen.get(id));
dom.stack.dataset.wide = String(matchWide());
const before = dom.stack.querySelector(".match-card.front");
const peekRow = (rest) => (rest.length && peeksShown() ? h("div", {class: "match-peeks", role: "group", "aria-label": `${rest.length} more cards`}, rest.map(peekTab)) : null);
if (releasing) {
matchView.front = null;
const shown = overview(cards, open.length);
const scrolledRelease = before && before.dataset.card === "release" ? before.querySelector(".match-body").scrollTop : 0;
const shown = releaseCard(cards, behind.length);
shown.dataset.fresh = String(!before || before.dataset.card !== "release");
if (cleared) {
shown.prepend(confetti());
}
dom.stack.replaceChildren(shown);
const peeksBelow = peekRow(behind);
dom.stack.replaceChildren(h("div", {class: "match-deck"}, layersOf(behind), shown), ...(peeksBelow ? [peeksBelow] : []));
shown.querySelector(".match-body").scrollTop = scrolledRelease;
return;
}
const [front, ...rest] = open;
const front = byOpen.get(rotation[0]);
const rest = behind;
matchView.front = front;
const act = (cls, iconName, word, hint, disabled, run) => h("button", {type: "button", class: `match-act ${cls}`, disabled, ...named(word, hint), on: {click: run}},
h("span", {class: "match-act-face", "aria-hidden": "true"}, icon(iconName)), h("span", {class: "match-act-label"}, word));
const hint = front.blocked ? `Accept: not possible now. ${front.blocked}` : front.stale ? `Accept: refused while the card is stale (${front.stale_reason})` : front.kind === "rule" ? "Accept: opens its row, where the passkey signs exactly this rule" : front.kind === "decision" ? (needsPick(front) ? "Accept: pick one of its options" : `Accept: ${shownPick(acceptLabel(front))} (right arrow, swipe right)`) : "Accept (right arrow, swipe right)";
const hint = front.blocked ? `Accept: not possible now. ${front.blocked}` : front.stale ? `Accept: refused while the card is stale (${front.stale_reason})` : front.kind === "rule" ? "Accept: opens its row, where the passkey signs exactly this rule" : front.kind === "decision" ? (needsPick(front) ? "Accept: pick one of its options" : `Accept: ${shownPick(acceptLabel(front))} (D, right arrow, swipe right)`) : "Accept (D, right arrow, swipe right)";
const accept = act("match-accept", "bi-check-lg", "Accept", revealed(hint), Boolean(front.blocked || front.stale) || needsPick(front), () => acceptCard(front));
const declining = front.kind === "decision" && Answers.pair(front) ? `Reject: ${shownPick(Answers.pair(front).no)}, with an optional comment on what to do instead (left arrow, swipe left)` : "Reject with feedback (left arrow, swipe left)";
const declining = front.kind === "decision" && Answers.pair(front) ? `Reject: ${shownPick(Answers.pair(front).no)}, with an optional comment on what to do instead (A, left arrow, swipe left)` : "Reject with feedback (A, left arrow, swipe left)";
const rejectHint = front.blocked ? `Reject: not possible now. ${front.blocked}` : pickOnly(front) ? "Reject: a choice is answered with one of its options" : declining;
const reject = act("match-reject", "bi-x-lg", "Reject", revealed(rejectHint), Boolean(front.blocked) || pickOnly(front), () => rejectCard(front));
const later = act("match-later", "bi-arrow-up", "Later", "Later: to the back of the stack (up arrow, swipe up)", !rest.length, () => laterCard(front));
const peeks = rest.length && peeksShown() ? 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 later = act("match-later", "bi-arrow-up", "Later", "Later: on to the next card, this one to the back (W, up arrow, swipe up); S undoes the last step", rotation.length < 2, () => laterCard(front));
const peeks = peekRow(rest);
const scrolled = before && before.dataset.card === front.id ? before.querySelector(".match-body").scrollTop : 0;
const shown = matchCard(front);
shown.dataset.fresh = String(!before || before.dataset.card !== front.id);
draggable(shown, front);
keepTyping(dom.stack, () => dom.stack.replaceChildren(h("div", {class: "match-deck"}, behind, shown), h("div", {class: "match-actions"}, reject, later, accept), ...(peeks ? [peeks] : [])));
draggable(shown, {accept: () => acceptCard(front), reject: () => rejectCard(front), later: () => laterCard(front)}, (swiped) => (swiped === "accept" && flies(front)) || swiped === "later");
keepTyping(dom.stack, () => dom.stack.replaceChildren(h("div", {class: "match-deck"}, layersOf(rest), shown), h("div", {class: "match-actions"}, reject, later, accept), ...(peeks ? [peeks] : [])));
shown.querySelector(".match-body").scrollTop = scrolled;
}
+17 -6
View File
@@ -58,23 +58,34 @@
/**
* @param {HTMLInputElement|HTMLTextAreaElement} field the text field; it moves into the frame.
* @param {Node[]} extras what belongs to a textarea besides its mic, on the footer's left (Record, a count); [] for none.
* @returns {HTMLElement} one frame around field and mic: for a one-line field the mic as the field's last segment, for a
* textarea a footer row below it whose last child is the mic.
* @param {Node[]} extras for a textarea what belongs to it besides its mic, on the footer's left (Record, a count); for a
* one-line field the segments after the mic (its form's submit button); [] for none.
* @returns {HTMLElement} one frame around field and mic: for a one-line field the mic and then the extras as its last
* segments, for a textarea a footer row below it whose last child is the mic.
*/
function micFrame(field, extras) {
const button = micButton(field);
if (field.tagName === "TEXTAREA") {
return h("div", {class: "mic-frame mic-area"}, field, h("div", {class: "mic-foot"}, extras, h("span", {class: "spacer"}), button));
}
return h("span", {class: "mic-frame mic-line"}, field, button);
return h("span", {class: "mic-frame mic-line"}, field, button, extras);
}
/**
* @param {HTMLInputElement|HTMLTextAreaElement} field a text field the sweep frames.
* @returns {HTMLButtonElement[]} the submit button right after a one-line field, which joins its frame behind the mic; [] otherwise.
*/
function micSend(field) {
const next = field.nextElementSibling;
return field.tagName !== "TEXTAREA" && next && next.matches("button[type=submit]") ? [next] : [];
}
function micWrap(field) {
const focused = document.activeElement === field;
const [start, end] = [field.selectionStart, field.selectionEnd];
const [parent, next] = [field.parentNode, field.nextSibling];
parent.insertBefore(micFrame(field, []), next);
const send = micSend(field);
const [parent, next] = [field.parentNode, (send[0] || field).nextSibling];
parent.insertBefore(micFrame(field, send), next);
if (focused) {
field.focus({preventScroll: true});
field.setSelectionRange(start, end);
+10 -9
View File
@@ -120,19 +120,20 @@
function tuneMusic(seconds) {
music.tension = Math.min(waitingCount() / 4, 1);
if (music.gain) {
glide(music.filter.frequency, 700 + 900 * music.tension, 4);
glide(music.drone[1].oscillator.detune, 8 * music.tension, 6);
glide(music.gain.gain, musicLevel(), seconds);
}
}
function syncMusic() {
if (settings.music.on) {
const level = musicLevel();
if (level > 0) {
startMusic();
} else {
stopMusic();
}
if (music.gain) {
glide(music.filter.frequency, 700 + 900 * music.tension, 4);
glide(music.drone[1].oscillator.detune, 8 * music.tension, 6);
glide(music.gain.gain, level, seconds);
}
}
function syncMusic() {
tuneMusic(FADE / 1000);
}
+77
View File
@@ -0,0 +1,77 @@
const POPUP_CHOICES = [
["resources", "Resource warnings", "watch.py: RAM, disk and queue warnings"],
["mayday", "MAYDAY calls", "radio.py: a MAYDAY on the radio"],
["dream", "Dream reminder", "kvb-dream: the daily dream reminder"],
];
const SNOOZE_HOUR = 3600;
let notifySaves = Promise.resolve();
function notifyFold(part) {
part.notify = h("div", {class: "notify-sets"});
part.notifySig = "";
return h("details", {class: "radio-notify", on: {toggle: (event) => placeStation(event.currentTarget)}},
h("summary", {title: "Notifications: the hub's channels and the GNOME desktop popups"}, caret(), h("h3", {class: "group-title"}, "Notifications")),
h("div", {class: "station-body"}, part.notify));
}
/**
* @param {function(object): object} change the keys to save, built from the
* settings current when the save runs, so quick clicks queue and none
* overwrites the one before it.
*/
function saveNotify(change) {
notifySaves = notifySaves.then(async () => {
if (!await saveSettings({...settings, space: savedSpace(), ...change(settings)})) {
liveParts("devices").forEach((part) => {
part.notifySig = "";
});
drawNotify();
}
});
}
function channelBox(id, label) {
const box = h("input", {type: "checkbox", name: `channel-${id}`, "data-focus": `channel-${id}`, checked: settings.channels[id]});
box.addEventListener("change", () => {
const on = box.checked;
saveNotify((now) => ({channels: {...now.channels, [id]: on}}));
});
return h("label", {class: "check"}, box, label);
}
function popupRow([id, label, hint], now) {
const entry = settings.popups[id];
const put = (next) => saveNotify((current) => ({popups: {...current.popups, [id]: next}}));
const snoozed = entry.on && entry.until > now;
const state = entry.on ? (snoozed ? "snoozed" : "on") : "off";
const box = h("input", {type: "checkbox", name: `popup-${id}`, "data-focus": `popup-${id}`, checked: entry.on});
box.addEventListener("change", () => put({on: box.checked, until: 0}));
const act = (key, text, title, next) => h("button", {type: "button", class: "btn small ghost", "data-focus": `${key}-${id}`, title: `${label}: ${title}`, on: {click: () => put(next())}}, text);
return h("div", {class: "notify-source", "data-source": id, "data-state": state},
h("label", {class: "check", title: hint}, box, label),
h("span", {class: "muted notify-state"}, snoozed ? `snoozed until ${clock.format(stampOf(entry.until))}` : state),
snoozed ? act("resume", "Resume", "popups again from now", () => ({on: true, until: 0})) : null,
entry.on ? act("hour", "1 h", "no popup for 1 hour", () => ({on: true, until: Math.floor(nowSeconds()) + SNOOZE_HOUR})) : null,
entry.on ? act("morning", "8:00", "no popup until 8 am tomorrow", () => ({on: true, until: tomorrow()})) : null);
}
function drawNotify() {
const now = nowSeconds();
const sig = JSON.stringify([settings.channels, settings.popups, Math.floor(now / 60)]);
for (const part of liveParts("devices")) {
if (sig === part.notifySig) {
continue;
}
part.notifySig = sig;
const focused = part.notify.contains(document.activeElement) ? document.activeElement.dataset.focus : "";
part.notify.replaceChildren(
h("fieldset", {class: "channels"}, h("legend", {}, "Notification channels"), CHANNEL_CHOICES.map(([id, label]) => channelBox(id, label))),
h("fieldset", {class: "popups"}, h("legend", {}, "GNOME popups"),
h("p", {class: "muted"}, "A muted source still reaches the Stream and the radio; only its desktop popup stays away. Your passkey signs every change."),
POPUP_CHOICES.map((choice) => popupRow(choice, now))));
const again = focused ? part.notify.querySelector(`[data-focus="${focused}"]`) : null;
if (again) {
again.focus();
}
}
}
+2 -1
View File
@@ -12,7 +12,8 @@
{label: "Radio …", hint: "Post, Call, Newsletter, Broadcast, Pan-Pan, Security, Mayday; the gear holds tones and read aloud", scope: "general", run: openRadio},
...ACTIONS.map(([id, label]) => ({label, hint: id === "clear-mayday" ? "Mayday" : "Day/Night", scope: "general", run: () => confirmAct(id, [])})),
{label: "Priority …", hint: "agent order in the hierarchy", scope: "agents", run: openAgentOrder},
{label: "Controls …", hint: "tools, rules and groups", scope: "stream", run: () => go("rules", null)},
{label: "Controls …", hint: "tools, rules, groups and schedules", scope: "stream", run: () => go("rules", null)},
{label: "Schedules …", hint: "switch off or retime the reminders, timers and hooks", scope: "stream", run: () => go("rules", "schedules")},
{label: "Settings …", hint: "Ambience, location, colors, music, notifications, internet radio", scope: "general", run: settingsSheet},
{label: settings.music.on ? "Music off" : "Music on", hint: "Ambience", scope: "general", run: toggleMusic},
{label: space.look ? "Leave the sky" : "Look at the sky", hint: "h", scope: "general", run: () => skyLook(!space.look)},
+2
View File
@@ -94,7 +94,9 @@
const stream = index < 0 ? null : settings.streams[index];
const url = stream ? stream.url : "";
if (url === radio.url && !radio.waiting) {
if (!document.hidden) {
drawStations();
}
return;
}
const missing = stream ? Ambience.stationOrigins(stream).filter((origin) => !pageMedia.has(origin)) : [];
+7 -11
View File
@@ -48,7 +48,7 @@
const [name, label] = sent ? ["bi-arrow-up-right", "Sent"] : ["bi-arrow-down-left", "Received"];
const first = firstLine(row.text);
const line = h("li", {class: "radio-row", "data-key": row.key, "data-dir": sent ? "sent" : "received", "data-class": row.class, "data-ts": row.ts, on: {click: (event) => openRadioRow(event.currentTarget.row, event.currentTarget)}},
row.source && !sent && row.from !== HUMAN ? muteFace(row.source, row.from) : null,
row.source && !sent && row.from !== HUMAN ? senderFace(row.source, row.from) : null,
h("button", {type: "button", class: "radio-pick", "aria-haspopup": "dialog", title: first},
when(row.ts),
h("span", {class: "radio-dir", role: "img", ...named(label)}, icon(name)),
@@ -84,14 +84,11 @@
/**
* @param {string} key the sender's session key.
* @param {string} name the sender's name.
* @returns {Element} the sender's avatar as a button that mutes or unmutes the sender on the radio, without opening the row.
* @returns {Element} the sender's avatar as a button that opens the agent with its own radio switches, without opening the row; greyed while its sound and read aloud are both off.
*/
function muteFace(key, name) {
const muted = radioSet.muted.includes(key);
return h("button", {type: "button", class: "radio-mute", "aria-pressed": String(muted), ...named(`Mute ${name}`, muted ? `Muted: a press lets the radio read ${name} aloud again` : `Mute ${name}: the radio stops reading this agent aloud`), on: {click: (event) => {
event.stopPropagation();
keepRadio(RadioSet.muting(radioSet, key));
}}}, face(key, false));
function senderFace(key, name) {
const quiet = !agentOn(key, "sound") && !agentOn(key, "aloud");
return h("button", {type: "button", class: "radio-sender", "data-quiet": String(quiet), ...named(`Open ${name}`, `Open ${name}${quiet ? ": its sound and read aloud are off" : ""}; its own switches sit in the agent card`), on: {click: openFrom(key)}}, face(key, false));
}
function patchList(list, lines) {
@@ -132,8 +129,7 @@
function readerLine(reader) {
const known = reader.read !== null && reader.read !== undefined;
return h("li", {class: "popup-reader", "data-session": reader.session, "data-acked": String(reader.acked)},
face(people()[reader.session] ? reader.session : reader.name, false),
h("strong", {}, reader.name),
h("strong", {}, agentLink(people()[reader.session] ? reader.session : reader.name)),
h("span", {class: "muted"}, known ? `read ${reader.approximate ? "about " : ""}${absolute.format(stampOf(reader.read))}` : "read, time unknown"),
reader.acked ? pill("acknowledged", "ok") : null);
}
@@ -205,7 +201,7 @@
function drawLog() {
const entry = radioSet.log;
const sig = JSON.stringify([state.radio.length, state.radio.length ? state.radio[state.radio.length - 1].ts : 0, state.messages.length, Receipts.signature(state.radio), Receipts.signature(state.messages), entry, radioSet.muted, Math.floor(Date.now() / 60000)]);
const sig = JSON.stringify([state.radio.length, state.radio.length ? state.radio[state.radio.length - 1].ts : 0, state.messages.length, Receipts.signature(state.radio), Receipts.signature(state.messages), entry, settings.agents, Math.floor(Date.now() / 60000)]);
for (const dom of liveParts("logs")) {
if (sig !== dom.sig) {
dom.sig = sig;
+16 -9
View File
@@ -110,7 +110,7 @@
const {caption} = part.face;
caption.hidden = !now;
caption.replaceChildren(...(now ? [
h("span", {class: "speaker-face"}, face(now.who, false)),
h("span", {class: "speaker-face"}, agentFace(now.who, false)),
h("strong", {}, nameOf(now.who), h("span", {class: "caption-verb"}, " speaking")),
h("span", {class: "caption-line", title: now.line}, now.line),
iconBtn("bi-stop-fill", "Stop speaking", "btn small ghost", cancelSpeech),
@@ -235,7 +235,10 @@
const menu = h("div", {class: "radio-mode-menu", hidden: true});
Object.assign(part, {face: {lamp, cls, mode, cpu, caption, modes, menu}, menuFor: "", menuSig: "", knobs: knobs()});
const display = h("div", {class: "radio-display", role: "group", "aria-label": "Display"}, lamp, cls, mode, cpu);
return h("div", {class: "radio-face", role: "group", "aria-label": "Radio set"}, display, caption, modes, menu,
const bubbles = h("button", {type: "button", class: "btn small ghost icon-only radio-bubbles", "aria-pressed": String(settings.bubbles), "aria-controls": "bubbles",
...named("Speech bubbles", "Speech bubbles: show each message as a bubble beside its speaker, on or off"), on: {click: toggleBubbles}}, icon("bi-chat-quote"));
const row = h("div", {class: "radio-mode-row"}, modes, h("span", {class: "mode-divider", "aria-hidden": "true"}), bubbles);
return h("div", {class: "radio-face", role: "group", "aria-label": "Radio set"}, display, caption, row, menu,
h("div", {class: "radio-knobs", role: "group", "aria-label": "Knobs"}, part.knobs.rows));
}
@@ -244,11 +247,11 @@
* @returns {object} the bar part with its root.
*/
function radioBar(spot) {
return {root: h("div", {class: "spot-bar", "data-star-slot": ""}, h("div", {class: "spot-head"}, spot ? h("h3", {class: "group-title"}, "Radio") : null, h("span", {class: "spacer"})))};
return {root: h("div", {class: "spot-bar"}, h("div", {class: "spot-head"}, spot ? h("h3", {class: "group-title"}, "Radio") : null, h("span", {class: "spacer"})))};
}
function cardHead(title, ...tools) {
return h("div", {class: "radio-card-head", "data-star-slot": ""}, h("h3", {class: "group-title"}, title), tools);
return h("div", {class: "radio-card-head"}, h("h3", {class: "group-title"}, title), tools);
}
function stationFold(part) {
@@ -263,7 +266,10 @@
if (!fold.open) {
return;
}
const edge = fold.getBoundingClientRect();
const layer = fold.querySelector(".station-body");
const frame = layer.offsetParent || fold;
const outer = frame.getBoundingClientRect();
const edge = {top: outer.top + frame.clientTop, bottom: outer.top + frame.clientTop + frame.clientHeight};
let [top, bottom] = [0, window.innerHeight];
for (let node = fold.parentElement; node && node !== document.documentElement; node = node.parentElement) {
const look = getComputedStyle(node);
@@ -274,13 +280,13 @@
}
const [above, below] = [Math.floor(edge.top - top), Math.floor(bottom - edge.bottom)];
fold.style.removeProperty("--room");
const up = above >= fold.querySelector(".station-body").offsetHeight || above >= below;
const up = above >= layer.offsetHeight || above >= below;
fold.dataset.side = up ? "up" : "down";
fold.style.setProperty("--room", `${Math.max(0, up ? above : below)}px`);
}
function placeStations(event) {
for (const fold of document.querySelectorAll("details.radio-station[open]")) {
for (const fold of document.querySelectorAll("details:is(.radio-station, .radio-notify)[open]")) {
if (!(event && event.target instanceof Node && fold.contains(event.target))) {
placeStation(fold);
}
@@ -290,7 +296,8 @@
function deviceCard() {
const part = {stationsSig: ""};
const face = faceplate(part);
part.root = h("section", {class: "radio-card radio-device", "data-panel": "radio-device", "aria-label": "Device"}, cardHead("Device"), face, stationFold(part));
part.root = h("section", {class: "radio-card radio-device", "data-panel": "radio-device", "aria-label": "Device"}, cardHead("Device"), face,
h("div", {class: "radio-settings"}, notifyFold(part), stationFold(part)));
radioParts.devices.push(part);
return part;
}
@@ -345,6 +352,7 @@
function drawRadio() {
drawRadioSet();
drawStations();
drawNotify();
drawSpeak();
}
@@ -370,7 +378,6 @@
const made = body ? [body.bar.root, body.grid] : {"radio-device": deviceCard, "radio-speak": speakCard, "radio-log": historyCard}[id]().root;
const root = h("div", {class: `radio-home radio-home-${id}`}, made);
root.querySelectorAll("[data-panel]").forEach((node) => node.removeAttribute("data-panel"));
root.querySelectorAll("[data-star-slot]").forEach((node) => node.removeAttribute("data-star-slot"));
window.setTimeout(drawRadio, 0);
return root;
}
+1 -1
View File
@@ -42,7 +42,7 @@
const legend = h("div", {class: "res-legend"});
const plot = h("div", {class: "res-plot"});
const panel = h("section", {class: `card res-panel res-${kind}`, "data-panel": `resources-${kind}`, "aria-label": label, hidden: kind === "combined"},
h("div", {class: "res-head", "data-star-slot": ""}, h("span", {class: "res-title", title: label, "aria-label": label}, icon(name)), legend), plot);
h("div", {class: "res-head", "data-legend-slot": ""}, h("span", {class: "res-title", title: label, "aria-label": label}, icon(name)), legend), plot);
return {kind, label, legend, plot, panel};
});
const accounts = accountsPanel();
+10 -1
View File
@@ -57,7 +57,16 @@
node.addEventListener("click", closeSheet);
return node;
}) : null));
openSheet(review.title, [head, h("div", {class: "split", "data-ref": ref, "data-to": item && item.to ? item.to : null}, treeNav, diff)], true);
const split = h("div", {class: "split", "data-ref": ref, "data-to": item && item.to ? item.to : null}, treeNav, diff);
if (ref) {
markable(split, ".review-file tr[data-line]", (row) => {
const picked = rowPick(row);
if (picked) {
markLines(picked);
}
});
}
openSheet(review.title, [head, split], true);
ui.review = id;
reviewDom = {tree: treeNav, diff, notes, ref};
}
+1 -1
View File
@@ -73,5 +73,5 @@
});
const dom = firewallSections();
const ruleCard = h("div", {class: "card"}, h("h3", {}, "New hub rule for automatic grants"), hint, form);
return controlsPage({tools: [dom.tools], rules: [dom.settings, ruleCard, dom.patterns], groups: [dom.groups, dom.sets]}, dom.bar);
return controlsPage({tools: [dom.tools], rules: [dom.settings, ruleCard, dom.patterns], groups: [dom.groups, dom.sets], schedules: [schedulesPanel()]}, dom.bar);
}
+88
View File
@@ -0,0 +1,88 @@
const SCHEDULE_ROWS = {
coach: ["Coach reminder", "bi-heart-pulse", "A one-line health tip at the top of an agent's answer, once across all agents."],
dream: ["Dream reminder", "bi-moon-stars", "A /kvb-dream hint, once per agent session."],
"dream-popup": ["Dream popup", "bi-bell", "A GNOME notification to run /kvb-dream."],
"queue-cleanup": ["Queue cleanup", "bi-trash3", "Deletes the queue jobs no living process holds."],
"code-graph": ["Code graph", "bi-diagram-3", "Keeps the codebase-memory-mcp daemon watching every graph."],
};
const SCHEDULE_UNITS = {"dream-popup": "kvb-dream-notify.timer", "queue-cleanup": "kvb-org-queue-cleanup.timer", "code-graph": "kvb-code-graph.service"};
const SCHEDULE_HOURS = [1, 24];
const SCHEDULE_START = "systemctl --user start kvb-schedules.service";
async function saveSchedule(name, value) {
const result = await sendJson("/api/schedules", {row: name, value});
if (result.ok && result.data) {
state.schedules = result.data;
} else {
toast("Schedule not changed", fail(result), false);
}
await load();
}
const scheduleHost = (unit) => state.schedules.host.rows.find((row) => row.unit === unit) || null;
const scheduleTimes = (text) => text.split(",").map((part) => part.trim()).filter(Boolean);
/**
* @param {Object} host a row of the host view, or null.
* @returns {HTMLElement} its next and last run, or why there is none yet.
*/
function scheduleRuns(host) {
if (!host || (host.next === null && host.last === null)) {
return h("span", {class: "muted"}, "no run known");
}
return h("span", {class: "muted sched-runs"}, host.next === null ? null : ["next ", when(host.next)], host.next !== null && host.last !== null ? " · " : null, host.last === null ? null : ["last ", when(host.last)]);
}
/**
* @param {string} name a key of SCHEDULE_ROWS.
* @param {Object} row its stored row: on, plus every or at.
* @returns {HTMLElement} the row: switch, its timing field and its runs.
*/
function scheduleRow(name, row) {
const [label, glyph, hint] = SCHEDULE_ROWS[name];
const change = (key, value) => saveSchedule(name, {...state.schedules.rows[name], [key]: value});
const toggle = h("input", {type: "checkbox", role: "switch", checked: row.on, "aria-label": `${label}: on`, on: {change: (event) => change("on", event.target.checked)}});
const timing = [];
if (Object.hasOwn(row, "every")) {
timing.push(h("label", {class: "sched-field"}, "every", h("input", {class: "field sched-hours", type: "number", min: SCHEDULE_HOURS[0], max: SCHEDULE_HOURS[1], step: 1, value: row.every, "aria-label": `${label}: every hours`,
on: {change: (event) => change("every", Number(event.target.value))}}), "h"));
}
if (Object.hasOwn(row, "at")) {
timing.push(h("label", {class: "sched-field"}, "at", h("input", {class: "field sched-times", type: "text", value: row.at.join(", "), placeholder: "17:00, 21:30", "aria-label": `${label}: at times`,
on: {change: (event) => change("at", scheduleTimes(event.target.value))}})));
}
const unit = SCHEDULE_UNITS[name];
return h("li", {class: `sched-row${row.on ? "" : " off"}`, "data-schedule": name},
h("label", {class: "sched-switch"}, toggle, icon(glyph), h("span", {class: "sched-name"}, label)),
h("span", {class: "sched-hint muted"}, hint), ...timing, unit ? scheduleRuns(scheduleHost(unit)) : null);
}
/**
* @param {Object} host a host view row the hub must not switch: a hub unit or a foreign timer or hook.
* @returns {HTMLElement} its schedule, runs and, for a foreign row, its off command to copy.
*/
function scheduleForeign(host) {
return h("li", {class: "sched-row foreign", "data-schedule-foreign": host.name},
h("span", {class: "sched-name"}, host.name), h("span", {class: `chip ${host.owner === "hub" ? "ok" : ""}`}, host.owner),
h("code", {class: "sched-hint"}, host.kind === "hook" ? host.command : dash(host.schedule)), host.kind === "hook" ? null : scheduleRuns(host),
host.off ? h("span", {class: "sched-off"}, h("code", {}, host.off), host.kind === "hook" ? null : copyButton(host.off)) : null);
}
/**
* @returns {HTMLElement} the Schedules panel: the first-party rows, then every other timer and hook the host
* reconciler last saw; a hint with its start command before its first run.
*/
function schedulesContent() {
const {rows, host} = state.schedules;
const others = host.rows.filter((row) => row.owner !== "skills");
return h("div", {class: "stack sched"},
h("ul", {class: "sched-list", "aria-label": "Switchable"}, Object.keys(SCHEDULE_ROWS).map((name) => scheduleRow(name, rows[name]))),
host.at === null
? h("p", {class: "muted"}, "The host has not listed its timers and hooks yet: ", h("code", {}, SCHEDULE_START), copyButton(SCHEDULE_START))
: h("div", {}, h("h3", {}, "Other timers and hooks"), h("p", {class: "muted"}, "Seen ", when(host.at), "; the hub never switches these."),
h("ul", {class: "sched-list", "aria-label": "Read only"}, others.map(scheduleForeign))));
}
function schedulesPanel() {
return h("section", {class: "card", "data-panel": "stream/schedules", "aria-label": "Schedules"}, schedulesContent());
}
+8 -4
View File
@@ -1,10 +1,11 @@
const navButtons = new Map();
function tabButton(id, label, hint) {
const badge = Object.hasOwn(state.badges, id) ? h("span", {class: "badge", hidden: true}) : null;
const button = h("button", {type: "button", id: `tab-${id}`, class: "icon-only", "aria-controls": "main", ...named(label, hint ? `${label} (${hint})` : label), on: {click: () => go(id, null)}}, icon(Nav.ICONS[id]), badge);
const own = id === "tasks";
const badge = Object.hasOwn(state.badges, id) ? h(own ? "a" : "span", {class: "badge", hidden: true, href: own ? Nav.hashOf("match", null) : null}) : null;
const button = h("button", {type: "button", id: `tab-${id}`, class: "icon-only", "aria-controls": "main", ...named(label, hint ? `${label} (${hint})` : label), on: {click: () => go(id, null)}}, icon(Nav.ICONS[id]), own ? null : badge);
navButtons.set(id, {button, badge});
return button;
return own ? [button, badge] : button;
}
document.getElementById("tabs").append(...Nav.TABS.map(([id, label], index) => h("div", {class: "tab-group"},
@@ -57,7 +58,7 @@
if (ui.screen === "agents") {
return JSON.stringify([ui.views.agents]);
}
return JSON.stringify(ui.screen === "artifacts" || ui.screen === "tasks" ? [ui.views[ui.screen]] : ui.screen === "rules" ? state.rules : []);
return JSON.stringify(ui.screen === "artifacts" || ui.screen === "tasks" ? [ui.views[ui.screen]] : ui.screen === "rules" ? [state.rules, state.schedules] : []);
}
function screenOf() {
@@ -111,6 +112,9 @@
badge.textContent = String(count);
badge.hidden = count === 0;
badge.className = `badge${id === "tasks" && count ? " urgent" : ""}`;
if (badge.tagName === "A") {
badge.setAttribute("aria-label", `${count} open operator ${count === 1 ? "task" : "tasks"}: open Match`);
}
}
const banner = document.getElementById("mayday");
const silence = state.silence;
+9 -4
View File
@@ -13,6 +13,9 @@
drawSky();
syncMusic();
syncRadio();
drawNotify();
drawAgentSettings();
drawLog();
musicButton();
syncBubbles();
syncChannels(before);
@@ -128,7 +131,7 @@
judge();
const musicOn = h("input", {type: "checkbox", checked: settings.music.on});
const volume = h("input", {type: "range", min: 0, max: 1, step: 0.05, value: settings.music.volume, "aria-label": "Overall volume"});
const channels = Object.fromEntries(CHANNEL_CHOICES.map(([id]) => [id, h("input", {type: "checkbox", name: `channel-${id}`, checked: settings.channels[id]})]));
const undo = undoDial(settings.undo, "Undo window in seconds");
const form = h("form", {class: "settings"},
ambience(),
h("section", {}, h("h3", {}, "Location"), h("p", {class: "muted"}, "Sun, moon and stars stand where you see them from here, looking south; under 🔭 Sky (key h) you turn the view. Decimal degrees, north and east positive."),
@@ -136,8 +139,7 @@
h("section", {}, h("h3", {}, "Appearance"), h("label", {}, "Colors", theme), custom, verdict),
h("section", {}, h("h3", {}, "Music"), h("p", {class: "muted"}, "Generative ambient music, made offline: calm with an empty inbox, a little tenser when something waits, quieter under messages."),
h("div", {class: "grid"}, h("label", {class: "check"}, musicOn, "Music on"), h("label", {}, "Overall volume (music and radio)", volume))),
h("section", {}, h("h3", {}, "Notifications"), h("p", {class: "muted"}, "Each channel switches one way the hub tells you about something new. Which kinds sound and which classes are read aloud, the mode, squelch, speech threshold and stations sit in the radio panel behind the radio button in the header."),
h("fieldset", {class: "grid channels"}, h("legend", {}, "Notification channels"), CHANNEL_CHOICES.map(([id, label]) => h("label", {class: "check"}, channels[id], label)))),
h("section", {class: "undo-window"}, h("h3", {}, "Undo window"), h("p", {class: "muted"}, "Seconds between a passkey signature and the moment it takes effect, to undo it; 0 takes effect at once. Drag the hand, click a tick, or use the arrows (1 s) and Page Up / Down (5 s)."), undo.root),
passkeySection(),
h("div", {class: "sheet-foot"}, h("span", {class: "spacer"}), btn("Cancel", "btn ghost", closeSheet), h("button", {type: "submit", class: "btn primary"}, "Save")));
form.addEventListener("submit", async (event) => {
@@ -149,7 +151,9 @@
theme: theme.value,
colors: Object.fromEntries(COLOR_FIELDS.map(([id]) => [id, colors[id].value])),
music: {on: musicOn.checked, volume: Number(volume.value)},
channels: Object.fromEntries(CHANNEL_CHOICES.map(([id]) => [id, channels[id].checked])),
channels: settings.channels,
popups: settings.popups,
agents: settings.agents,
streams: settings.streams,
speech: settings.speech,
morse: settings.morse,
@@ -158,6 +162,7 @@
trend: settings.trend,
bubbles: settings.bubbles,
rates: settings.rates,
undo: undo.value(),
};
if (await saveSettings(next)) {
closeSheet();
+1 -1
View File
@@ -116,7 +116,7 @@
const all = spawnFlat(root).map(({entry}) => entry).filter((entry) => entry.running !== null);
const running = all.filter((entry) => entry.running).length;
spawn.dom.list.replaceChildren(
h("div", {class: "inbox-head", "data-star-slot": ""}, h("h2", {class: "group-title"}, "Spawn tree", counter(all.length)), h("span", {class: "muted"}, `${running} running · ${all.length - running} finished · Operator → Chair → Sessions → Subagents`)),
h("div", {class: "inbox-head"}, h("h2", {class: "group-title"}, "Spawn tree", counter(all.length)), h("span", {class: "muted"}, `${running} running · ${all.length - running} finished · Operator → Chair → Sessions → Subagents`)),
agentAncestry(root),
h("ul", {class: "spawn-tree root"}, spawnItem(root)));
}
Loaded 100 of 265 files, more files were not shown because too many files have changed in this diff. Show more