diff --git a/README.md b/README.md index 56f2094..51f0ad5 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ Compatible with Claude Code, Codex, Gemini CLI, Cursor, Copilot, Windsurf, Cline ## Naming 🏷️ -Every first-party skill is named `kvb--` with one of these categories: `think`, `create`, `code`, `ci`, `git`, `release`, `check`, `org`, `agent`, `skill`, `coach`: `think` thinks without producing a file, `create` produces an artifact, `code` works on code, `ci` on pipelines, `git` on history and forges, `release` announces a release (changelog, article, posts), `check` analyses and reports findings, `org` coordinates agents, `agent` acts on one agent itself: its repository setup (code index, agent instructions) and its state (drain, suspend, resume), `skill` works on skills themselves, `coach` serves the operator's wellbeing. Only `kvb-cleanup`, `kvb-coach`, `kvb-help`, `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--` 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 (`/.agents/skills` and `/.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 (`/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 ` 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/` beside both (`councilroot.py release `). 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 `.legacy-` (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//`, and the radio appends the rows it drops past its last 500 to `archive/news-.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. diff --git a/docs/requirements/032-send-in-the-field.md b/docs/requirements/032-send-in-the-field.md new file mode 100644 index 0000000..2fb8c93 --- /dev/null +++ b/docs/requirements/032-send-in-the-field.md @@ -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. diff --git a/docs/requirements/033-coherent-speak-box.md b/docs/requirements/033-coherent-speak-box.md new file mode 100644 index 0000000..b3f1b02 --- /dev/null +++ b/docs/requirements/033-coherent-speak-box.md @@ -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. diff --git a/docs/requirements/034-stream-head-band.md b/docs/requirements/034-stream-head-band.md new file mode 100644 index 0000000..52684c5 --- /dev/null +++ b/docs/requirements/034-stream-head-band.md @@ -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. diff --git a/docs/requirements/035-match-full-width.md b/docs/requirements/035-match-full-width.md new file mode 100644 index 0000000..da58479 --- /dev/null +++ b/docs/requirements/035-match-full-width.md @@ -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. diff --git a/docs/requirements/036-match-pile.md b/docs/requirements/036-match-pile.md new file mode 100644 index 0000000..f8376f0 --- /dev/null +++ b/docs/requirements/036-match-pile.md @@ -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. diff --git a/docs/requirements/037-home-without-box.md b/docs/requirements/037-home-without-box.md new file mode 100644 index 0000000..452a264 --- /dev/null +++ b/docs/requirements/037-home-without-box.md @@ -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. diff --git a/docs/requirements/038-badge-to-match.md b/docs/requirements/038-badge-to-match.md new file mode 100644 index 0000000..2578f57 --- /dev/null +++ b/docs/requirements/038-badge-to-match.md @@ -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. diff --git a/docs/requirements/039-match-rejects-survive.md b/docs/requirements/039-match-rejects-survive.md new file mode 100644 index 0000000..047e5c0 --- /dev/null +++ b/docs/requirements/039-match-rejects-survive.md @@ -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`. diff --git a/docs/requirements/040-release-card.md b/docs/requirements/040-release-card.md new file mode 100644 index 0000000..86e652e --- /dev/null +++ b/docs/requirements/040-release-card.md @@ -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. diff --git a/docs/requirements/041-review-code-marks.md b/docs/requirements/041-review-code-marks.md new file mode 100644 index 0000000..aac797a --- /dev/null +++ b/docs/requirements/041-review-code-marks.md @@ -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 `:` and "c". +- [ ] Approve sends one radio post to the agent containing `:` + 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. diff --git a/docs/requirements/042-why-deny-is-off.md b/docs/requirements/042-why-deny-is-off.md new file mode 100644 index 0000000..b243f3a --- /dev/null +++ b/docs/requirements/042-why-deny-is-off.md @@ -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. diff --git a/docs/requirements/043-undo-window-clock.md b/docs/requirements/043-undo-window-clock.md new file mode 100644 index 0000000..be2572a --- /dev/null +++ b/docs/requirements/043-undo-window-clock.md @@ -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. diff --git a/docs/requirements/044-widgets-without-inner-boxes.md b/docs/requirements/044-widgets-without-inner-boxes.md new file mode 100644 index 0000000..915a8ec --- /dev/null +++ b/docs/requirements/044-widgets-without-inner-boxes.md @@ -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. diff --git a/docs/requirements/045-artifacts-head-one-line.md b/docs/requirements/045-artifacts-head-one-line.md new file mode 100644 index 0000000..4d7579d --- /dev/null +++ b/docs/requirements/045-artifacts-head-one-line.md @@ -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. diff --git a/docs/requirements/046-accept-red-gate-risk.md b/docs/requirements/046-accept-red-gate-risk.md new file mode 100644 index 0000000..987a8df --- /dev/null +++ b/docs/requirements/046-accept-red-gate-risk.md @@ -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`. diff --git a/docs/requirements/047-one-code-box.md b/docs/requirements/047-one-code-box.md new file mode 100644 index 0000000..0fb9d9e --- /dev/null +++ b/docs/requirements/047-one-code-box.md @@ -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. diff --git a/docs/requirements/048-done-rows-folded.md b/docs/requirements/048-done-rows-folded.md new file mode 100644 index 0000000..acdea58 --- /dev/null +++ b/docs/requirements/048-done-rows-folded.md @@ -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. diff --git a/docs/requirements/049-one-control-height.md b/docs/requirements/049-one-control-height.md new file mode 100644 index 0000000..ef4742b --- /dev/null +++ b/docs/requirements/049-one-control-height.md @@ -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. diff --git a/docs/requirements/050-menus-stay-open.md b/docs/requirements/050-menus-stay-open.md new file mode 100644 index 0000000..241c1f1 --- /dev/null +++ b/docs/requirements/050-menus-stay-open.md @@ -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. diff --git a/docs/requirements/051-radio-settings-in-device.md b/docs/requirements/051-radio-settings-in-device.md new file mode 100644 index 0000000..d60e782 --- /dev/null +++ b/docs/requirements/051-radio-settings-in-device.md @@ -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. diff --git a/docs/requirements/052-bubbles-beside-modes.md b/docs/requirements/052-bubbles-beside-modes.md new file mode 100644 index 0000000..de976ba --- /dev/null +++ b/docs/requirements/052-bubbles-beside-modes.md @@ -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. diff --git a/docs/requirements/053-agent-settings-on-faces.md b/docs/requirements/053-agent-settings-on-faces.md new file mode 100644 index 0000000..780f916 --- /dev/null +++ b/docs/requirements/053-agent-settings-on-faces.md @@ -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. diff --git a/docs/requirements/054-pin-only-by-menu.md b/docs/requirements/054-pin-only-by-menu.md new file mode 100644 index 0000000..e620f8c --- /dev/null +++ b/docs/requirements/054-pin-only-by-menu.md @@ -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. diff --git a/docs/requirements/055-wasd-in-match.md b/docs/requirements/055-wasd-in-match.md new file mode 100644 index 0000000..97aa62d --- /dev/null +++ b/docs/requirements/055-wasd-in-match.md @@ -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. diff --git a/docs/requirements/056-flowing-card-edge.md b/docs/requirements/056-flowing-card-edge.md new file mode 100644 index 0000000..c637e34 --- /dev/null +++ b/docs/requirements/056-flowing-card-edge.md @@ -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. diff --git a/docs/requirements/057-schedules-in-controls.md b/docs/requirements/057-schedules-in-controls.md new file mode 100644 index 0000000..5dbd526 --- /dev/null +++ b/docs/requirements/057-schedules-in-controls.md @@ -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): `/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 + `/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/.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 `/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. diff --git a/docs/requirements/058-coach-repository.md b/docs/requirements/058-coach-repository.md new file mode 100644 index 0000000..afee644 --- /dev/null +++ b/docs/requirements/058-coach-repository.md @@ -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 + `/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. diff --git a/docs/requirements/059-hub-poll-cost.md b/docs/requirements/059-hub-poll-cost.md new file mode 100644 index 0000000..65e7913 --- /dev/null +++ b/docs/requirements/059-hub-poll-cost.md @@ -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. diff --git a/docs/requirements/060-host-hook-timer-load.md b/docs/requirements/060-host-hook-timer-load.md new file mode 100644 index 0000000..90ca552 --- /dev/null +++ b/docs/requirements/060-host-hook-timer-load.md @@ -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. diff --git a/docs/requirements/061-bounded-council-files.md b/docs/requirements/061-bounded-council-files.md new file mode 100644 index 0000000..ddeed3a --- /dev/null +++ b/docs/requirements/061-bounded-council-files.md @@ -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 + `..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. diff --git a/docs/requirements/062-lean-agent-output.md b/docs/requirements/062-lean-agent-output.md new file mode 100644 index 0000000..4297b9d --- /dev/null +++ b/docs/requirements/062-lean-agent-output.md @@ -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 --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 ` 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 % critical (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 ` 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. diff --git a/docs/requirements/063-one-commit-block.md b/docs/requirements/063-one-commit-block.md new file mode 100644 index 0000000..0714b61 --- /dev/null +++ b/docs/requirements/063-one-commit-block.md @@ -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 + --fix --break ` 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 ` is required as for every script it runs; `tokens.py` + runs on `--transcripts ` (skill text changed, with `--saves` and + `--evidence` passed on as its `--value`), `measure.py` on + `-- ` (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 (` %`, `new`, ` % critical `, + `value `), 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 ` 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: - - diff --git a/skills/kvb-coach-meditation/scripts/meditation.py b/skills/kvb-coach-meditation/scripts/meditation.py deleted file mode 100755 index 4bf02b9..0000000 --- a/skills/kvb-coach-meditation/scripts/meditation.py +++ /dev/null @@ -1,110 +0,0 @@ -#!/usr/bin/env python3 -"""Keep the kvb-coach-meditation settings and write the session page. - -Args: - --state: path of the settings JSON file. - set = ...: change settings; every value is validated. - show: print the settings. - session --page --out : write the page with the - settings embedded and print its path; fails while a setting is missing. - -Exit codes: - 0 done, 2 usage error. -""" - -from __future__ import annotations - -import argparse -import json -import sys -from pathlib import Path - -PLACEHOLDER = "const SETTINGS = null;" -RANGES = { - "minutes": (int, 1, 30), - "beat": (float, 8.0, 13.0), - "base": (float, 100.0, 400.0), - "volume": (float, 0.05, 1.0), -} -CHOICES = { - "mode": ("binaural", "isochronic"), - "palette": ("aurora", "ocean", "ember", "forest"), - "breathing": ("box", "478", "none"), -} -KEYS = (*RANGES, *CHOICES) - - -def fail(message: str) -> None: - print(f"meditation: {message}", file=sys.stderr) - sys.exit(2) - - -def parse(pair: str) -> tuple[str, int | float | str]: - key, sep, raw = pair.partition("=") - if not sep or key not in KEYS: - fail(f"{pair}: expected = with key in {', '.join(KEYS)}") - if key in CHOICES: - if raw not in CHOICES[key]: - fail(f"{key} must be one of {', '.join(CHOICES[key])}") - return key, raw - kind, low, high = RANGES[key] - try: - value = kind(raw) - except ValueError: - fail(f"{key} must be a number") - if not low <= value <= high: - fail(f"{key} must lie between {low} and {high}") - return key, value - - -def load(path: Path) -> dict: - try: - return json.loads(path.read_text(encoding="utf-8")) - except FileNotFoundError: - return {} - except ValueError: - fail(f"{path} is not valid JSON") - - -def main() -> int: - parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) - parser.add_argument("--state", required=True) - sub = parser.add_subparsers(dest="cmd", required=True) - sub.add_parser("set").add_argument("pairs", nargs="+") - sub.add_parser("show") - p = sub.add_parser("session") - p.add_argument("--page", required=True) - p.add_argument("--out", required=True) - args = parser.parse_args() - - path = Path(args.state) - settings = load(path) - if args.cmd == "set": - settings.update(parse(pair) for pair in args.pairs) - path.parent.mkdir(parents=True, exist_ok=True) - tmp = path.with_suffix(".tmp") - tmp.write_text(json.dumps(settings, indent=1, sort_keys=True), encoding="utf-8") - tmp.replace(path) - if args.cmd in ("set", "show"): - for key in KEYS: - print(f"{key}={settings.get(key, '-')}") - return 0 - missing = [key for key in KEYS if key not in settings] - if missing: - fail(f"missing settings: {', '.join(missing)}") - page = Path(args.page) - if not page.is_file(): - fail(f"{page} does not exist") - template = page.read_text(encoding="utf-8") - if template.count(PLACEHOLDER) != 1: - fail(f"{page} lacks the line {PLACEHOLDER}") - embedded = json.dumps({key: settings[key] for key in KEYS}) - out = Path(args.out) - out.parent.mkdir(parents=True, exist_ok=True) - out.write_text(template.replace(PLACEHOLDER, f"const SETTINGS = {embedded};"), encoding="utf-8") - print(out.resolve()) - return 0 - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/skills/kvb-coach/SKILL.md b/skills/kvb-coach/SKILL.md deleted file mode 100644 index 9897619..0000000 --- a/skills/kvb-coach/SKILL.md +++ /dev/null @@ -1,80 +0,0 @@ ---- -name: kvb-coach -description: > - Coach the operator's next step: psyche, body, sleep, food, own and - delegable tasks. Trigger on "was soll ich tun". ---- - -Be the operator's coach: short, warm, concrete, with emojis, in the -operator's language. Their health comes first; work is one area of six, not -the default. Suggestions, never pressure. - -The profile keeps what the operator enjoys, dislikes and last did, host-local -in the gitignored `.state/` of the skills repository: - -```bash -coach.py --profile /.state/coach.json like|dislike|forget "" -coach.py --profile done "" [--at ] -coach.py --profile show [--json] -``` - -Areas: `psyche`, `body`, `sleep`, `food`, `tasks`, `delegate`. Every coaching -skill beyond this one is named `kvb-coach-`. - -`hooks/reminder.sh` prints one fixed tip at the first prompt of every full -hour, once across all agents (stamped in `~/.claude/.coach-hours/`), chosen -by the hour: sleep late, food at meal times, else moving. The agent passes -it on in one line without loading this skill. - -## Step 1: read the situation - -- **Time**: local time and weekday, and how long the operator has been at it - today (their first message of the day in the session transcripts). -- **Profile**: `coach.py show`: likes, dislikes, hours since the last sleep, - meal, workout or break. -- **Own tasks**: the open commands of the `kvb-org-operator` skill and the - decisions agents wait on. -- **Delegable**: what the operator did by hand that an agent could do, and - queued `kvb-org-rasci` register tasks without a worker. - -## Step 2: suggest - -At most one line per area, the most urgent first, the whole answer on one -screen: - -- 🧠 **Psyche**: a short break, a walk outside, five minutes with the - `kvb-coach-meditation` skill or box breathing, a call with a friend, - something just for fun. -- 💪 **Body**: a workout from the operator's likes (a 20-minute run, a - bodyweight circuit, cycling, yoga), stretching neck, hips and back after - long sitting, standing up every hour. -- 😴 **Sleep**: wind down, screens off, seven to nine hours; a 20-minute nap - in the early afternoon. -- 🥗 **Food**: water, a real meal with vegetables and protein, a healthy - snack instead of sugar, no caffeine late in the day. -- ✅ **Your tasks**: the one step only the operator can take that unblocks - the most. -- 🤖 **Delegate**: what an agent can take over, with the skill or command - that does it. - -The situation sets the order: late evening puts sleep first, hours without -a break put moving first, a meal more than five hours ago puts food first. -Prefer what the operator likes, never offer a dislike, and do not repeat the -last tip of an area. Close with one encouraging line. - -## Step 3: listen and remember - -Often, not every time: when the profile is empty, after a declined -suggestion, and every few runs, run the `kvb-think-listen` skill with one -short `AskUserQuestion` (what they enjoy, what fits right now, what to -avoid). Record the answers with `like` and `dislike`, and what the operator -reports having done with `done`. - -## Rules - -- The operator decides: no guilt, no nagging, a declined tip stays off for - the day. -- General wellbeing, no medical advice: pain, illness or lasting exhaustion - get one kind pointer to a doctor. -- The profile never leaves the host: not into commits, memory files or peer - messages. diff --git a/skills/kvb-coach/hooks/reminder.sh b/skills/kvb-coach/hooks/reminder.sh deleted file mode 100755 index 6129dc7..0000000 --- a/skills/kvb-coach/hooks/reminder.sh +++ /dev/null @@ -1,18 +0,0 @@ -#!/usr/bin/env bash -set -euo pipefail -export PATH=/usr/bin:/bin - -hours="${COACH_STAMP_DIR:-${HOME}/.claude/.coach-hours}" -hour="${COACH_HOUR:-$(date +%Y-%m-%dT%H)}" - -mkdir -p "${hours}" -mkdir "${hours}/${hour}" 2>/dev/null || exit 0 -find "${hours}" -mindepth 1 -maxdepth 1 -type d ! -name "${hour}" -exec rmdir {} + - -case "${hour##*T}" in - 22 | 23 | 0[0-5]) tip="😴 Late: wind down, screens off soon, seven to nine hours of sleep." ;; - 1[2-3] | 1[8-9]) tip="🥗 Meal time: a real meal with vegetables and protein, and a glass of water." ;; - *) tip="🚶 Stand up, stretch neck, hips and back for two minutes, and drink a glass of water." ;; -esac - -printf 'COACH HOUR: open your answer with this one line for the operator, word for word, then continue with the request; load no skill for it:\n%s (More: /kvb-coach)\n' "${tip}" diff --git a/skills/kvb-coach/scripts/coach.py b/skills/kvb-coach/scripts/coach.py deleted file mode 100755 index 981752c..0000000 --- a/skills/kvb-coach/scripts/coach.py +++ /dev/null @@ -1,135 +0,0 @@ -#!/usr/bin/env python3 -"""Keep the operator's coaching profile: likes, dislikes and when what was done. - -Args: - --profile: path of the profile JSON file. - like|dislike : record a preference; one replaces the other. - forget : drop a preference. - done [--at ]: log that the operator did it. - show [--now ] [--json]: likes, dislikes and the last logged activity - per area with the hours since. - -Exit codes: - 0 done, 2 usage error. -""" - -from __future__ import annotations - -import argparse -import datetime -import json -import sys -from pathlib import Path - -AREAS = ("psyche", "body", "sleep", "food", "tasks", "delegate") -LOG_LIMIT = 500 - - -def fail(message: str) -> None: - print(f"coach: {message}", file=sys.stderr) - sys.exit(2) - - -def moment(value: str | None) -> datetime.datetime: - if value is None: - return datetime.datetime.now(datetime.UTC) - try: - parsed = datetime.datetime.fromisoformat(value) - except ValueError: - fail(f"{value} is not an ISO timestamp") - return parsed if parsed.tzinfo else parsed.replace(tzinfo=datetime.UTC) - - -def load(path: Path) -> dict: - try: - data = json.loads(path.read_text(encoding="utf-8")) - except FileNotFoundError: - return {"likes": {}, "dislikes": {}, "log": []} - except ValueError: - fail(f"{path} is not valid JSON") - return data - - -def save(path: Path, data: dict) -> None: - path.parent.mkdir(parents=True, exist_ok=True) - tmp = path.with_suffix(".tmp") - tmp.write_text( - json.dumps(data, indent=1, sort_keys=True, ensure_ascii=False), encoding="utf-8" - ) - tmp.replace(path) - - -def prefer(data: dict, keep: str, area: str, thing: str) -> None: - for key in ("likes", "dislikes"): - items = data[key].setdefault(area, []) - if thing in items: - items.remove(thing) - if keep: - data[keep][area].append(thing) - - -def summary(data: dict, now: datetime.datetime) -> list[dict]: - rows = [] - for area in AREAS: - last = next((e for e in reversed(data["log"]) if e["area"] == area), None) - hours = None - if last: - hours = round((now - moment(last["at"])).total_seconds() / 3600, 1) - rows.append( - { - "area": area, - "likes": data["likes"].get(area, []), - "dislikes": data["dislikes"].get(area, []), - "last": last["thing"] if last else None, - "hours_ago": hours, - } - ) - return rows - - -def main() -> int: - parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) - parser.add_argument("--profile", required=True) - sub = parser.add_subparsers(dest="cmd", required=True) - for name in ("like", "dislike", "forget"): - p = sub.add_parser(name) - p.add_argument("area", choices=AREAS) - p.add_argument("thing") - p = sub.add_parser("done") - p.add_argument("area", choices=AREAS) - p.add_argument("thing") - p.add_argument("--at") - p = sub.add_parser("show") - p.add_argument("--now") - p.add_argument("--json", action="store_true") - args = parser.parse_args() - - path = Path(args.profile) - data = load(path) - if args.cmd == "show": - rows = summary(data, moment(args.now)) - if args.json: - print(json.dumps(rows, indent=1, ensure_ascii=False)) - return 0 - for row in rows: - last = f"{row['last']} {row['hours_ago']}h ago" if row["last"] else "-" - print( - f"{row['area']}\tlast: {last}\tlikes: {', '.join(row['likes']) or '-'}" - f"\tdislikes: {', '.join(row['dislikes']) or '-'}" - ) - return 0 - if args.cmd == "done": - data["log"].append( - {"area": args.area, "thing": args.thing, "at": moment(args.at).isoformat()} - ) - data["log"] = data["log"][-LOG_LIMIT:] - else: - keep = {"like": "likes", "dislike": "dislikes"}.get(args.cmd, "") - prefer(data, keep, args.area, args.thing) - save(path, data) - print(f"{args.cmd} {args.area} {args.thing}") - return 0 - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/skills/kvb-dream/SKILL.md b/skills/kvb-dream/SKILL.md index fde3619..351fe65 100644 --- a/skills/kvb-dream/SKILL.md +++ b/skills/kvb-dream/SKILL.md @@ -78,7 +78,7 @@ window filled, with the finished tasks' artifacts (`rasci.py artifacts repository, which hands merged-clean rows to `kvb-git-gc`. Each keeps its own confirmations; the dream never writes, deletes or commits for them. Close with `date +%s > ~/.claude/.dream-stamps/"$CLAUDE_CODE_SESSION_ID"`, so the -next hint is twelve hours out. +next hint is a full interval out. ## Rules diff --git a/skills/kvb-dream/hints.md b/skills/kvb-dream/hints.md index 73e15d1..431ea55 100644 --- a/skills/kvb-dream/hints.md +++ b/skills/kvb-dream/hints.md @@ -1,10 +1,15 @@ # Dream hints -Two hints point at the dream; neither is a trigger: +Two hints point at the dream; neither is a trigger, and both start off to +save tokens: -- `hooks/reminder.sh` tells each agent at most once every twelve hours, +- `hooks/reminder.sh` tells each agent once every N hours (default 12), stamped per session in `~/.claude/.dream-stamps/`. - The `kvb-dream-notify.timer` user timer shows a GNOME notification daily at - 17:00 local time, catching up once after a missed run. + the set times (default 17:00), catching up once after a missed run. + +The operator switches and retimes both in the hub's Controls › Schedules tab, +or with `kvb-org-organize/scripts/schedules.py set dream|dream-popup`; the +`kvb-schedules` units apply a change within seconds. On a hint, print it and continue with the actual request. diff --git a/skills/kvb-dream/hooks/notify.sh b/skills/kvb-dream/hooks/notify.sh index 13fecd9..0967181 100755 --- a/skills/kvb-dream/hooks/notify.sh +++ b/skills/kvb-dream/hooks/notify.sh @@ -4,5 +4,17 @@ set -euo pipefail [[ "${XDG_CURRENT_DESKTOP:-}" == *GNOME* ]] || exit 0 command -v notify-send >/dev/null || exit 0 +schedules="$(dirname "$0")/../../kvb-org-organize/scripts/schedules.py" +[[ -f "$schedules" ]] && command -v python3 >/dev/null || exit 0 +python3 -I "$schedules" check dream-popup >/dev/null 2>&1 || exit 0 + +popups="$(dirname "$0")/../../kvb-org-organize/scripts/popups.py" +muted=3 +status=0 +if [[ -f "$popups" ]] && command -v python3 >/dev/null; then + python3 -I "$popups" allowed dream >/dev/null 2>&1 || status=$? +fi +[[ "$status" -ne "$muted" ]] || exit 0 + notify-send --app-name=kvb-dream "kvb-dream" \ "Time to dream: run /kvb-dream in your agent sessions to process the day." diff --git a/skills/kvb-dream/hooks/reminder.sh b/skills/kvb-dream/hooks/reminder.sh index b2c5095..bf6a241 100755 --- a/skills/kvb-dream/hooks/reminder.sh +++ b/skills/kvb-dream/hooks/reminder.sh @@ -2,7 +2,11 @@ set -euo pipefail export PATH=/usr/bin:/bin -interval="${DREAM_INTERVAL_SECONDS:-43200}" +schedules="$(dirname "$0")/../../kvb-org-organize/scripts/schedules.py" +[[ -f "${schedules}" ]] || exit 0 +hours="$(/usr/bin/python3 -I "${schedules}" check dream /dev/null)" || exit 0 +[[ "${hours}" =~ ^[0-9]+$ ]] || exit 0 +interval="$((hours * 3600))" stamps="${DREAM_STAMP_DIR:-${HOME}/.claude/.dream-stamps}" session="$(/usr/bin/python3 -I -c'import json, sys; print(json.load(sys.stdin).get("session_id", ""))' 2>/dev/null)" || exit 0 @@ -24,7 +28,7 @@ mkdir -p "${stamps}" printf '%s\n' "${now}" >"${stamp}" cat <<'HINT' -DREAM HINT: over twelve hours since this agent's last hint. Show the operator +DREAM HINT: the dream reminder is on in the hub's Schedules tab. Show the operator this notice verbatim as a short block, then continue with their request. Do NOT run kvb-dream, do not start replaying the history, do not ask questions about it. diff --git a/skills/kvb-git-commit-next/SKILL.md b/skills/kvb-git-commit-next/SKILL.md index fa62a5a..bb6f948 100644 --- a/skills/kvb-git-commit-next/SKILL.md +++ b/skills/kvb-git-commit-next/SKILL.md @@ -16,19 +16,10 @@ description: > verdict and the recommended move (keep staged / take theirs / combine). Wait for the operator's decision; do not commit. 3. Nothing similar found, or the operator picked the staged version: run the - kvb-git-commit-no-verify skill on the currently staged changes - (kvb-code-clean pass and kvb-check-legal check first, then the - kvb-check-score commit table of 📁 worktree, - 🌿 branch, 📊 diff stat, scores with 🛡️ security and gate, then - `git commit --no-verify`, exact staging index only, its message carrying - the `score.py --message-block` paragraph as one `-m` argument, then its - trailers, then the table again with the - hash). Its approval-prompt duty is binding: the commit call's approval - prompt names worktree, branch, diff stat and the score values with - 🛡️ security, and the message holds the block, or the call is not sent. - Gate exit 4 (critical security finding): no commit, the call is never - sent. Exit 1 is shown and the operator's word decides; exit 3 asks the - operator again first, naming each cause. + kvb-git-commit-no-verify skill on the currently staged changes. Its + steps bind unchanged: clean and legal passes, the `block.py` table and + message block, the approval-prompt duty and the gate exits (4: never + sent; 1: the operator's word; 3: ask again, naming each cause). 4. Group the remaining uncommitted changes into logical bundles (one concern per bundle: same failure class, mechanism or role) and stage the next one; never mix concerns to save a commit. Staging happens here and nowhere @@ -40,12 +31,11 @@ description: > --file --match `, first with `--dry-run`. 5. For the newly staged bundle run the kvb-code-clean pass, then the kvb-think-explain skill (what the changes do and how the pieces - interact, file:line-anchored), then the kvb-check-confidence skill (its - kvb-check-score block with 🛡️ security from `security.py` of - kvb-check-security, evidence, residuals). -6. Close with the staged bundle's commit table (`score.py ... - --commit-table `: 📁 worktree, 🌿 branch, 📊 diff stat, scores, - gate), what remains unstaged, the `push` targets of `pkgmgr worktree + interact, file:line-anchored), then the kvb-check-confidence skill (fix, + break, evidence, residuals) and `block.py` as step 2 of + kvb-git-commit-no-verify runs it. +6. Close with the staged bundle's `block.py` table and gate verdict, what + remains unstaged, the `push` targets of `pkgmgr worktree flow --json` the branch flows into, and wait for the operator's commit decision; never auto-commit the newly staged bundle. Ask through the kvb-git-diff skill: a hub approval is the operator's commit decision for diff --git a/skills/kvb-git-commit-no-verify/SKILL.md b/skills/kvb-git-commit-no-verify/SKILL.md index 85279f7..ac5f3e2 100644 --- a/skills/kvb-git-commit-no-verify/SKILL.md +++ b/skills/kvb-git-commit-no-verify/SKILL.md @@ -8,13 +8,27 @@ description: > 1. Run the kvb-code-clean pass (comments, defaults, principles) over the staged and unstaged changes first, then the kvb-check-legal check over the staging index. A legal blocker stops here. -2. Show in the message right before the `git commit` call, never only after - it, the commit table of the kvb-check-score skill (`score.py ... - --commit-table `): 📁 worktree, 🌿 branch, 📊 staged diff stat, - then fix, break, tokens, velocity, security, score and gate of the staged - bundle, as the kvb-check-confidence skill produces them: break risk - derived through the kvb-check-break-risk skill, never estimated. Never - print a diff in the chat, only its stat. +2. Score the staged bundle in one run, in the background with its output in + a `/tmp` log: + + ```bash + python3 ${CLAUDE_SKILL_DIR}/../kvb-check-score/scripts/block.py --repo --base HEAD --fix --break [--transcripts ~/.claude/projects [--saves --evidence ""]] [-- ] + ``` + + Fix confidence comes from the kvb-check-confidence skill, break risk + derived through the kvb-check-break-risk skill, never estimated. + `--transcripts` when skill text changed; `-- ` (the targeted + tests or a CLI call of the changed code) when runnable code changed, and + then the whole call runs inside + `${CLAUDE_SKILL_DIR}/../kvb-org-queue/scripts/queue.py hold --kind test + --task --`. It prints the commit table (📁 worktree, 🌿 branch, + 📊 staged diff stat, fix, break, tokens, velocity, security, score, + gate), the `gate.py status` verdict that 90/5 also needs, the message + block and the call for step 5. Show the table and the verdict right + before the `git commit` call, never only after it. Exit 2 names the + failing script; `security.py exited 4` sends you to + `${CLAUDE_SKILL_DIR}/../kvb-check-security/coverage.md`. Never print a + diff in the chat, only its stat. 3. Approval-prompt duty: the commit call's approval prompt (Claude Code: the Bash `description`; other runtimes: their prompt text) names the worktree path, the branch, the diff stat and the score values of step 2. Missing @@ -30,12 +44,12 @@ description: > 4. Commit exactly the staging index with `git commit --no-verify` and a Conventional-Commits message derived from the staged diff; never add unstaged files, never push. Message: `-m "" -m "" -m - "" --trailer "Created-with: + "" --trailer "Created-with: https://s.veen.world/skills" --trailer "Co-Authored-By: ..."`. A commit-creating call without block or `Created-with`, upstream commits included, is not sent; a merge is `git merge --no-ff --no-commit`, then this commit. Every commit and PR skill takes both from here; a PR body ends with `Created with https://s.veen.world/skills`. -5. Report the created commit hash, the commit table again with - `--commit ` (the committed diff stat and a 🔖 Commit column), and - what remains uncommitted. +5. Report the created commit hash, the commit table again by the `after the + commit:` call of step 2 with the hash filled in (the committed diff stat + and a 🔖 Commit column), and what remains uncommitted. diff --git a/skills/kvb-org-matrix/SKILL.md b/skills/kvb-org-matrix/SKILL.md index 0f52398..2a3c8ae 100644 --- a/skills/kvb-org-matrix/SKILL.md +++ b/skills/kvb-org-matrix/SKILL.md @@ -18,7 +18,8 @@ you could not read: list, the operator's goals this session, and the requirement or plan documents the work follows. 2. **Peers**: `council.py list` (the `kvb-org-organize` skill) and the radio - store, `radio.py show --all` (the `kvb-org-radio` skill); never message a + store, `radio.py show --all --since 1d --summary` (the `kvb-org-radio` + skill); never message a peer for status. 3. **Working tree**: `git status --short` and `git log --oneline -10`: uncommitted and untracked files are open work, commits since the branch diff --git a/skills/kvb-org-operator/SKILL.md b/skills/kvb-org-operator/SKILL.md index cdc141c..e9f501a 100644 --- a/skills/kvb-org-operator/SKILL.md +++ b/skills/kvb-org-operator/SKILL.md @@ -7,8 +7,8 @@ description: > Every step that waits on a human, across all agents, is a task `operator/` of the `kvb-org-rasci` register with a test for when it is -done. `${CLAUDE_SKILL_DIR}/scripts/operator.py` writes and reads those rows, -so collecting them needs no messages. +done. `${CLAUDE_SKILL_DIR}/scripts/operator.py` writes and reads those rows; +no messages needed. ```bash operator.py add --dir --command "" --reason "" --check [:] @@ -69,8 +69,8 @@ Never poll peers; a sweep runs only when the operator asks for one, as with `add` first, so `run` holds them. - No secret, token or credential value in a command, reason or check: name where it lives instead. -- Merge duplicates: one row per step across all agents. Read `list --json` - before adding; re-add a known step under its existing slug. +- One row per step: `add` of another agent's open command in its directory + joins that row as an A; re-add your steps under their slug. - Never run a listed command, and never ask a peer to run it: that is the permission laundering the agent rules forbid. - A command that fails the "What counts" test is not the operator's; run it diff --git a/skills/kvb-org-operator/scripts/operator.py b/skills/kvb-org-operator/scripts/operator.py index e38bf4b..509b93b 100755 --- a/skills/kvb-org-operator/scripts/operator.py +++ b/skills/kvb-org-operator/scripts/operator.py @@ -372,6 +372,34 @@ def choices(raw: list[str] | None, recommended: str | None, check: str) -> list[ return options +def twin_of(tasks: dict, task: str, directory: str, command: str, sid: str) -> str | None: + """Args: + sid: the adding session; its own rows never count, since one agent + may record the same command for two steps on purpose. + + Returns: + The first other open operator row of another session holding the + same directory and command, None without one. + """ + return next(( + other for other, entry in sorted(tasks.items()) + if other != task and other.startswith(PREFIX) and entry.get("status") in OPEN + and (entry.get("workdir"), entry.get("title")) == (directory, command) + and sid not in sessions_of(entry).values() + ), None) + + +def sessions_of(entry: dict) -> dict: + sessions = entry.get("sessions") + return sessions if isinstance(sessions, dict) else {} + + +def join(rasci: ModuleType, entry: dict, party: str, sid: str) -> None: + roles = entry.get("roles", {}) + entry["roles"] = {**roles, party: rasci.letters_of(roles.get(party, ""), "A")} + entry["sessions"] = {**sessions_of(entry), party: sid} + + def cmd_add(rasci: ModuleType, args: argparse.Namespace) -> int: task = task_of(rasci, args.slug) for error in (path_problem(args.dir, "--dir"), problem(args.check)): @@ -394,6 +422,11 @@ def cmd_add(rasci: ModuleType, args: argparse.Namespace) -> int: sid, _ = council.caller(args.session) party = council.live_sessions().get(sid) or sid with rasci.database() as tasks: + twin = twin_of(tasks, task, args.dir, command, sid) + if twin is not None: + join(rasci, tasks[twin], party, sid) + print(f"joined {twin}: it holds the same command in the same directory") + return 0 # Trip-wire: the register is dumped with sort_keys, so insertion order needs its own field. seq = max((e.get("seq", 0) for t, e in tasks.items() if t.startswith(PREFIX)), default=0) + 1 entry = tasks.setdefault(task, {}) @@ -468,12 +501,18 @@ def cmd_list(rasci: ModuleType, args: argparse.Namespace) -> int: if not listed: print("operator: nothing open") return 0 + first: dict[tuple, dict] = {} + for row in listed: + first.setdefault((row["directory"], row["command"]), row) + listed = list(first.values()) + steps = [(number, row) for number, row in enumerate(listed, 1) if runnable(row)] + numbered = {number for number, _ in steps} print(HEADER) print("|---|---|---|---|---|") for number, row in enumerate(listed, 1): - values = (number, row["directory"] or "-", row["command"] or "-", row["why"] or "-", row["check"]) + command = f"step {number}" if number in numbered else row["command"] or "-" + values = (number, row["directory"] or "-", command, row["why"] or "-", row["check"]) print("| " + " | ".join(cell(v) for v in values) + " |") - steps = [(number, row) for number, row in enumerate(listed, 1) if runnable(row)] for number, row in steps: print() print(f"{number}. {visible(row['task'], '')}") diff --git a/skills/kvb-org-organize/SKILL.md b/skills/kvb-org-organize/SKILL.md index 91833bd..2ebeba4 100644 --- a/skills/kvb-org-organize/SKILL.md +++ b/skills/kvb-org-organize/SKILL.md @@ -37,24 +37,15 @@ after a restart. ## Capacity -- Light runs self-admit: `watch.py admit --kind test-nostack -- `, - start on `grant`. Light is only ruff, shellcheck, markdownlint, lizard, jq, - py_compile, cargo fmt, `env CARGO_BUILD_JOBS=4 cargo build|check|clippy|test`, - or one test file or module outside `e2e/` that reaches no Playwright; - anything else: `queue.py hold --kind test`. -- Memory stop (also PSI or swap-out) blocks every admit and grant; running - jobs go on. -- `make test`, `make test-lint`, quality gates, deploys, - iteration loops, swarm, image builds, cloud, shared-data cleanup, anything - with Docker or over a few minutes: run through `queue.py hold` - (`kvb-org-queue`), which grants by rule and releases on exit; the chair only - handles exceptions. In a worktree wrap `gate.py run` or `gate.py hold` - (`kvb-check-gate`). -- No running job is cut short for capacity; only the operator orders one - down. Exception: void by a missing merged hotfix (`kvb-git-hotfix`). - `RESOURCE` hook lines address the chair; others adjust plans. -- Read `capacity.md` when you hold the chair, a job seems - hung, or the resource watch fires. +Read `capacity.md` before any run beyond one lint or one test file, when you +hold the chair, a job seems hung, or a `RESOURCE` line fires. + +## Schedules + +Reminders and timers follow `/schedules.json`, which the hub's +Controls › Schedules tab writes: `scripts/schedules.py check|set|view`; +`kvb-schedules.path` and `.timer` run `schedules.py run`, which switches the +first-party units and lists every other timer and hook for the hub. ## Peer protocol diff --git a/skills/kvb-org-organize/capacity.md b/skills/kvb-org-organize/capacity.md index fd5f97e..84740d9 100644 --- a/skills/kvb-org-organize/capacity.md +++ b/skills/kvb-org-organize/capacity.md @@ -1,4 +1,23 @@ -# Chair, allocation and resource watch +# Capacity: admission, allocation and resource watch + +## Admission + +- Light runs self-admit: `watch.py admit --kind test-nostack -- `, + start on `grant`. Light is only ruff, shellcheck, markdownlint, lizard, jq, + py_compile, cargo fmt, `env CARGO_BUILD_JOBS=4 cargo build|check|clippy|test`, + or one test file or module outside `e2e/` that reaches no Playwright; + anything else: `queue.py hold --kind test`. +- Memory stop (also PSI or swap-out) blocks every admit and grant; running + jobs go on. +- `make test`, `make test-lint`, quality gates, deploys, + iteration loops, swarm, image builds, cloud, shared-data cleanup, anything + with Docker or over a few minutes: run through `queue.py hold` + (`kvb-org-queue`), which grants by rule and releases on exit; the chair only + handles exceptions. In a worktree wrap `gate.py run` or `gate.py hold` + (`kvb-check-gate`). +- No running job is cut short for capacity; only the operator orders one + down. Exception: void by a missing merged hotfix (`kvb-git-hotfix`). + `RESOURCE` hook lines address the chair; others adjust plans. ## Allocation diff --git a/skills/kvb-org-organize/scripts/hooks.py b/skills/kvb-org-organize/scripts/hooks.py new file mode 100755 index 0000000..f9d0a94 --- /dev/null +++ b/skills/kvb-org-organize/scripts/hooks.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Run the skills' Bash hooks in one interpreter. + +pre-bash radio.py block, watch.py block, queue.py block, graph.py hook +post-bash watch.py watch, log.py persist + +Every handler reads the same hook event; exit 2 of any handler blocks with the +stderr of each handler that exited 2, otherwise their JSON answers merge. +""" + +from __future__ import annotations + +import contextlib +import importlib.util +import io +import json +import sys +import traceback +from pathlib import Path + +SKILLS = Path(__file__).resolve().parents[2] +BLOCK = 2 +HANDLERS = { + "pre-bash": ( + ("kvb-org-radio/scripts/radio.py", "block"), + ("kvb-org-organize/scripts/watch.py", "block"), + ("kvb-org-queue/scripts/queue.py", "block"), + ("kvb-agent-optimize/scripts/graph.py", "hook"), + ), + "post-bash": ( + ("kvb-org-organize/scripts/watch.py", "watch"), + ("kvb-org-perform/scripts/log.py", "persist"), + ), +} +RANK = {"allow": 0, "ask": 1, "deny": 2} +JOINED = ("additionalContext", "systemMessage") + + +def exit_code(stop: SystemExit) -> int: + if stop.code is None or isinstance(stop.code, int): + return stop.code or 0 + print(stop.code, file=sys.stderr) + return 1 + + +def handle(script: str, sub: str, raw: str) -> tuple[int, str, str]: + """Args: + script: the handler's path below SKILLS. + sub: the subcommand its main() parses. + raw: the hook event, given to the handler as its stdin. + + Returns: + The handler's exit code, stdout and stderr; a missing script answers + 0 without output, a crash 1 with its traceback. + """ + path = SKILLS / script + if not path.is_file(): + return 0, "", "" + out, err = io.StringIO(), io.StringIO() + sys.argv, sys.stdin = [str(path), sub], io.StringIO(raw) + with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): + try: + name = f"kvb_hook_{path.parent.parent.name.replace('-', '_')}_{path.stem}" + spec = importlib.util.spec_from_file_location(name, path) + module = importlib.util.module_from_spec(spec) + sys.modules[name] = module + spec.loader.exec_module(module) + code = module.main() + except SystemExit as stop: + code = exit_code(stop) + except Exception: # noqa: BLE001 + traceback.print_exc() + code = 1 + return code if isinstance(code, int) else 1, out.getvalue(), err.getvalue() + + +def merge_specific(into: dict, given: dict) -> None: + decision = given.get("permissionDecision") + held = into.get("permissionDecision") + if decision in RANK and (held not in RANK or RANK[decision] > RANK[held]): + into["permissionDecision"], into["permissionDecisionReason"] = decision, given.get("permissionDecisionReason", "") + elif decision in RANK and decision == held and given.get("permissionDecisionReason"): + into["permissionDecisionReason"] = "\n".join(filter(None, (into.get("permissionDecisionReason"), given["permissionDecisionReason"]))) + for key, value in given.items(): + if key in ("permissionDecision", "permissionDecisionReason"): + continue + if key in JOINED and isinstance(value, str) and isinstance(into.get(key), str): + into[key] = f"{into[key]}\n{value}" + else: + into.setdefault(key, value) + + +def merged(outputs: list[str]) -> tuple[dict, list[str]]: + """Returns: + One hook answer from the handlers' JSON objects, and every other + non-empty stdout text, which a hook answer cannot carry. + """ + answer: dict = {} + loose = [] + for text in filter(None, (output.strip() for output in outputs)): + try: + given = json.loads(text) + except ValueError: + given = None + if not isinstance(given, dict): + loose.append(text) + continue + for key, value in given.items(): + if key == "hookSpecificOutput" and isinstance(value, dict) and isinstance(answer.get(key, {}), dict): + merge_specific(answer.setdefault(key, {}), value) + elif key in JOINED and isinstance(value, str) and isinstance(answer.get(key), str): + answer[key] = f"{answer[key]}\n{value}" + else: + answer.setdefault(key, value) + return answer, loose + + +def main() -> int: + if len(sys.argv) != 2 or sys.argv[1] not in HANDLERS: + print(f"usage: hooks.py {'|'.join(HANDLERS)}", file=sys.stderr) + return 1 + stdin, stdout, stderr = sys.stdin, sys.stdout, sys.stderr + raw = stdin.read() + results = [handle(script, sub, raw) for script, sub in HANDLERS[sys.argv[1]]] + sys.stdin = stdin + blocked = [err for code, _, err in results if code == BLOCK] + if blocked: + stderr.write("".join(blocked)) + return BLOCK + answer, loose = merged([out for _, out, _ in results]) + stderr.write("".join(err for _, _, err in results) + "".join(f"{text}\n" for text in loose)) + if answer: + stdout.write(json.dumps(answer) + "\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/skills/kvb-org-organize/scripts/popups.py b/skills/kvb-org-organize/scripts/popups.py new file mode 100755 index 0000000..ded6d1f --- /dev/null +++ b/skills/kvb-org-organize/scripts/popups.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Usage: + popups.py allowed SOURCE + +Args: + allowed: exit 0 when SOURCE may show a desktop popup now, MUTED (3) when + the operator switched it off or snoozed it in the hub's radio Device + card. A missing, linked, unreadable or malformed notify.json, or one + that names SOURCE wrongly, allows it, so a broken file never silences + an alarm; a caller treats every status but MUTED, a crash included, + as allowed. + SOURCE: resources (watch.py), mayday (radio.py) or dream + (kvb-dream/hooks/notify.sh). + +Environment: + AGENTS_COUNCIL_ROOT, XDG_STATE_HOME, HOME: the council directory + councilroot.py resolves; the hub writes notify.json into it on every + signed settings save. +""" + +from __future__ import annotations + +import importlib.util +import json +import sys +import time +from pathlib import Path +from types import ModuleType + +SOURCES = ("resources", "mayday", "dream") +NOTIFY = "notify.json" +MUTED = 3 + + +def sibling(name: str) -> ModuleType: + spec = importlib.util.spec_from_file_location(f"kvb_popups_{name}", Path(__file__).resolve().parent / f"{name}.py") + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def allowed(root: Path, source: str, now: float) -> bool: + """Args: + root: the council directory holding notify.json. + source: one of SOURCES. + now: the current time in epoch seconds. + + Returns: + False only while notify.json names source off, or snoozed until a + time after now; True for every unreadable or malformed state. + """ + try: + entry = json.loads(sibling("nofollow").read_text(root, root / NOTIFY))[source] + on, until = entry["on"], entry["until"] + except (OSError, ValueError, KeyError, TypeError): + return True + if not isinstance(on, bool) or isinstance(until, bool) or not isinstance(until, int | float): + return True + return on and until <= now + + +def main(argv: list[str]) -> int: + if len(argv) != 2 or argv[0] != "allowed" or argv[1] not in SOURCES: + print(__doc__, file=sys.stderr) + return 2 + return 0 if allowed(sibling("councilroot").root(), argv[1], time.time()) else MUTED + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/skills/kvb-org-organize/scripts/schedules.py b/skills/kvb-org-organize/scripts/schedules.py new file mode 100755 index 0000000..7baf68d --- /dev/null +++ b/skills/kvb-org-organize/scripts/schedules.py @@ -0,0 +1,335 @@ +#!/usr/bin/env python3 +"""Usage: + schedules.py check ROW + schedules.py set ROW [--on | --off] [--every HOURS] [--at HH:MM ...] + schedules.py view [--timers FILE] [--settings FILE] [--units DIR] + schedules.py apply [--units DIR] + schedules.py run + +Args: + check: exit 0 while ROW is on, printing its hours for a reminder hook; + OFF (3) while it is off. A missing, linked or malformed schedules.json + or row gives the row's default. + set: change ROW in schedules.json, keep every other row, print ROW. + view: print every user timer and every hook command of the settings file + as JSON rows: name, kind, owner (skills for the rows of ROWS, hub for + kvb-orchestrator-* units, other), unit, file, schedule, next and last + run in epoch seconds, event, command and off, the command that + switches a foreign row off. + apply: switch the units of ROWS to their rows: the drop-in + DIR/.d/schedule.conf for a retime, then enable --now or + disable --now where the unit's state differs. A foreign or hub unit + is never named. + run: view into schedules-view.json, then apply; kvb-schedules.path and + kvb-schedules.timer start it. + ROW: one of ROWS. + --timers: a systemctl --user list-timers --all --output=json answer; + systemctl is asked when left out. + --settings: the Claude Code settings file, ~/.claude/settings.json unless + given. + --units: the systemd user unit directory, ~/.config/systemd/user unless + given. + +Environment: + AGENTS_COUNCIL_ROOT, XDG_STATE_HOME, HOME: the council directory + councilroot.py resolves; the hub's Schedules tab writes + schedules.json into it. +""" + +from __future__ import annotations + +import argparse +import importlib.util +import json +import os +import re +import subprocess +import sys +import time +from collections.abc import Callable +from pathlib import Path +from types import ModuleType + +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}, +} +UNITS = {"dream-popup": "kvb-dream-notify.timer", "queue-cleanup": "kvb-org-queue-cleanup.timer", "code-graph": "kvb-code-graph.service"} +HOOKS = {"coach": "/kvb-coach/hooks/reminder.sh", "dream": "/kvb-dream/hooks/reminder.sh"} +HUB_PREFIX = "kvb-orchestrator-" +HOURS = (1, 24) +TIMES_LIMIT = 6 +CLOCK = re.compile(r"(?:[01][0-9]|2[0-3]):[0-5][0-9]") +TIMER_KEYS = ("OnCalendar", "OnActiveSec", "OnBootSec", "OnStartupSec", "OnUnitActiveSec", "OnUnitInactiveSec") +SEARCHED = (Path("/etc/systemd/user"), Path("/usr/lib/systemd/user")) +DROP_IN = "schedule.conf" +SWITCHED = ("enabled", "disabled") +SYSTEMCTL = ("systemctl", "--user") +RUN_TIMEOUT = 60 +MICRO = 1_000_000 +FILE_MODE = 0o600 +OFF = 3 + +Runner = Callable[[list[str]], tuple[int, str]] + + +def sibling(name: str) -> ModuleType: + spec = importlib.util.spec_from_file_location(f"kvb_schedules_{name}", Path(__file__).resolve().parent / f"{name}.py") + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def valid_row(name: str, value: object) -> dict: + """Args: + name: one of ROWS. + value: the row, with exactly the keys of its ROWS default. + + Returns: + The row, times sorted; ValueError when malformed. + """ + default = ROWS[name] + if not isinstance(value, dict) or set(value) != set(default) or not isinstance(value["on"], bool): + raise ValueError(f"{name} must hold exactly {', '.join(sorted(default))}") + found = {"on": value["on"]} + if "every" in default: + every = value["every"] + if isinstance(every, bool) or not isinstance(every, int) or not HOURS[0] <= every <= HOURS[1]: + raise ValueError(f"{name}.every must be a whole number of hours from {HOURS[0]} to {HOURS[1]}") + found["every"] = every + if "at" in default: + times = value["at"] + if not isinstance(times, list) or not 1 <= len(times) <= TIMES_LIMIT or not all(isinstance(item, str) and CLOCK.fullmatch(item) for item in times): + raise ValueError(f"{name}.at must hold 1 to {TIMES_LIMIT} times like 17:00") + if len(set(times)) != len(times): + raise ValueError(f"{name}.at names a time twice") + found["at"] = sorted(times) + return found + + +def stored(root: Path) -> dict: + try: + data = json.loads(sibling("nofollow").read_text(root, root / SCHEDULES)) + except (OSError, ValueError): + data = {} + rows = {} + for name, default in ROWS.items(): + try: + rows[name] = valid_row(name, data[name]) + except (ValueError, KeyError, TypeError): + rows[name] = default + return rows + + +def write(root: Path, name: str, data: object) -> None: + sibling("nofollow").replace(root, root / name, json.dumps(data, sort_keys=True), FILE_MODE) + + +def changed(row: dict, on: bool | None, every: int | None, at: list[str] | None) -> dict: + found = dict(row) + for key, value in (("on", on), ("every", every), ("at", at)): + if value is not None: + if key not in found: + raise ValueError(f"this row takes no --{key}") + found[key] = value + return found + + +def unit_file(units: Path, unit: str) -> Path | None: + return next((folder / unit for folder in (units, *SEARCHED) if (folder / unit).is_file()), None) + + +def schedule_of(path: Path | None) -> str: + """Returns: + The timer settings of the unit file and its drop-ins in order; an + empty assignment resets the ones before it, as systemd reads them. + """ + if path is None: + return "" + found: list[str] = [] + drop_ins = sorted(path.with_name(f"{path.name}.d").glob("*.conf")) + for file in (path, *drop_ins): + try: + lines = file.read_text(encoding="utf-8", errors="replace").splitlines() + except OSError: + continue + for line in lines: + key, sign, value = line.strip().partition("=") + if sign and key.strip() in TIMER_KEYS: + value = value.strip() + found = [item for item in found if not item.startswith(f"{key.strip()}=")] if not value else [*found, f"{key.strip()}={value}"] + return "; ".join(found) + + +def epoch(value: object) -> float | None: + if isinstance(value, bool) or not isinstance(value, int | float) or value <= 0: + return None + return value / MICRO + + +def owner_of(unit: str) -> str: + if unit in UNITS.values(): + return "skills" + return "hub" if unit.startswith(HUB_PREFIX) else "other" + + +def timer_rows(timers: object, units: Path) -> list[dict]: + rows = [] + for entry in timers if isinstance(timers, list) else []: + unit = entry.get("unit") if isinstance(entry, dict) else None + if not isinstance(unit, str) or not unit: + continue + path = unit_file(units, unit) + owner = owner_of(unit) + rows.append({ + "name": unit, "kind": "timer", "owner": owner, "unit": unit, "file": str(path or ""), "schedule": schedule_of(path), + "next": epoch(entry.get("next")), "last": epoch(entry.get("last")), "event": "", "command": "", + "off": f"systemctl --user disable --now {unit}" if owner == "other" else "", + }) + return rows + + +def hook_rows(settings: Path) -> list[dict]: + try: + hooks = json.loads(settings.read_text(encoding="utf-8")).get("hooks") + except (OSError, ValueError, AttributeError): + return [] + rows = [] + for event, groups in hooks.items() if isinstance(hooks, dict) else []: + for group in groups if isinstance(groups, list) else []: + for hook in group.get("hooks", []) if isinstance(group, dict) else []: + command = hook.get("command") if isinstance(hook, dict) else None + if not isinstance(command, str): + continue + mine = next((name for name, script in HOOKS.items() if script in command), None) + rows.append({ + "name": mine or f"{event} hook", "kind": "hook", "owner": "skills" if mine else "other", "unit": "", "file": str(settings), + "schedule": event, "next": None, "last": None, "event": event, "command": command, + "off": "" if mine else f"remove it from hooks.{event} in {settings}", + }) + return rows + + +def run_command(argv: list[str]) -> tuple[int, str]: + try: + done = subprocess.run(argv, capture_output=True, text=True, timeout=RUN_TIMEOUT, check=False) + except (OSError, subprocess.TimeoutExpired): + return 1, "" + return done.returncode, done.stdout + + +def listed_timers(run: Runner) -> object: + code, out = run([*SYSTEMCTL, "list-timers", "--all", "--output=json"]) + try: + return json.loads(out) if code == 0 else [] + except ValueError: + return [] + + +def view(timers: object, settings: Path, units: Path) -> list[dict]: + return timer_rows(timers, units) + hook_rows(settings) + + +def drop_in(units: Path, unit: str, times: list[str]) -> bool: + """Returns: + True when DIR/.d/schedule.conf changed: OnCalendar reset, then + one daily OnCalendar per time. + """ + path = units / f"{unit}.d" / DROP_IN + text = "[Timer]\nOnCalendar=\n" + "".join(f"OnCalendar=*-*-* {item}:00\n" for item in times) + try: + if path.read_text(encoding="utf-8") == text: + return False + except OSError: + pass + path.parent.mkdir(parents=True, exist_ok=True) + temp = path.with_name(f".{DROP_IN}.{os.getpid()}") + temp.write_text(text, encoding="utf-8") + temp.replace(path) + return True + + +def apply(rows: dict, run: Runner, units: Path) -> list[str]: + """Returns: + The systemctl calls made, without the state queries. + """ + calls = [] + retimed = [unit for name, unit in UNITS.items() if "at" in rows[name] and unit_file(units, unit) and drop_in(units, unit, rows[name]["at"])] + if retimed: + calls.append([*SYSTEMCTL, "daemon-reload"]) + calls += [[*SYSTEMCTL, "try-restart", unit] for unit in retimed] + for call in calls: + run(call) + for name, unit in UNITS.items(): + state = run([*SYSTEMCTL, "is-enabled", unit])[1].strip() + if state in SWITCHED and rows[name]["on"] != (state == "enabled"): + call = [*SYSTEMCTL, "enable" if rows[name]["on"] else "disable", "--now", unit] + run(call) + calls.append(call) + return [" ".join(call[2:]) for call in calls] + + +def parsed(argv: list[str]) -> argparse.Namespace: + parser = argparse.ArgumentParser(prog="schedules.py", add_help=False) + commands = parser.add_subparsers(dest="command", required=True) + commands.add_parser("check").add_argument("row", choices=ROWS) + setter = commands.add_parser("set") + setter.add_argument("row", choices=ROWS) + switch = setter.add_mutually_exclusive_group() + switch.add_argument("--on", dest="on", action="store_const", const=True) + switch.add_argument("--off", dest="on", action="store_const", const=False) + setter.add_argument("--every", type=int) + setter.add_argument("--at", nargs="+") + viewer = commands.add_parser("view") + viewer.add_argument("--timers", type=Path) + viewer.add_argument("--settings", type=Path, default=Path.home() / ".claude" / "settings.json") + viewer.add_argument("--units", type=Path, default=Path.home() / ".config" / "systemd" / "user") + commands.add_parser("apply").add_argument("--units", type=Path, default=Path.home() / ".config" / "systemd" / "user") + commands.add_parser("run") + return parser.parse_args(argv) + + +def main(argv: list[str]) -> int: + try: + args = parsed(argv) + except SystemExit: + print(__doc__, file=sys.stderr) + return 2 + root = sibling("councilroot").root() + if args.command == "check": + row = stored(root)[args.row] + if not row["on"]: + return OFF + if "every" in row: + print(row["every"]) + return 0 + if args.command == "set": + rows = stored(root) + try: + rows[args.row] = valid_row(args.row, changed(rows[args.row], args.on, args.every, args.at)) + except ValueError as error: + print(f"schedules.py: {error}", file=sys.stderr) + return 2 + write(root, SCHEDULES, rows) + print(json.dumps(rows[args.row], sort_keys=True)) + return 0 + settings = Path.home() / ".claude" / "settings.json" + units = getattr(args, "units", Path.home() / ".config" / "systemd" / "user") + if args.command == "view": + timers = json.loads(args.timers.read_text(encoding="utf-8")) if args.timers else listed_timers(run_command) + print(json.dumps(view(timers, args.settings, units), indent=2)) + return 0 + if args.command == "run": + write(root, SCHEDULES_VIEW, {"at": time.time(), "rows": view(listed_timers(run_command), settings, units)}) + for call in apply(stored(root), run_command, units): + print(call) + return 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/skills/kvb-org-organize/scripts/watch.py b/skills/kvb-org-organize/scripts/watch.py index bf460ec..95bc24d 100755 --- a/skills/kvb-org-organize/scripts/watch.py +++ b/skills/kvb-org-organize/scripts/watch.py @@ -2,7 +2,8 @@ """Watch disk, Docker and caches for the kvb-org-organize resource chair. Usage: - watch.py watch hook (UserPromptSubmit, PostToolUse): measure at most once + watch.py watch hook (UserPromptSubmit; PostToolUse on Bash through + hooks.py post-bash): measure at most once per interval machine-wide, act on the stage, show alerts, and append the rows of /queue-history.jsonl (kvb-org-queue), /security-accepted.jsonl @@ -10,7 +11,8 @@ Usage: /gate-parents.jsonl (kvb-check-gate) whose id it lacks to the same name in the host-only root (councilroot.py durable), never through a link - watch.py block hook (PreToolUse on Bash): exit 2 for a heavy job while the + watch.py block hook (PreToolUse on Bash through hooks.py pre-bash): exit 2 + for a heavy job while the disk stage is stop or critical, the memory stage is stop or cannot be judged without memory_limits, or a kvb-org-radio mayday holds radio silence @@ -118,6 +120,7 @@ import tomllib from collections.abc import Iterable from pathlib import Path from types import ModuleType +from typing import TextIO def loaded(name: str, path: Path) -> ModuleType: @@ -134,6 +137,7 @@ def sibling(name: str) -> ModuleType: nofollow = sibling("nofollow") hookpath = sibling("hookpath") councilroot = sibling("councilroot") +popups = sibling("popups") QUEUE = Path(__file__).resolve().parents[2] / "kvb-org-queue" / "scripts" / "queue.py" ROOT = councilroot.root() CONFIG = Path( @@ -160,6 +164,8 @@ MIRRORED = ( (HISTORY, KEPT_HISTORY), (ACCEPTED, KEPT_ACCEPTED), (RECEIPTS, KEPT_RECEIPTS), (PARENTS, KEPT_PARENTS), ) ALERT_TTL = 3600 +CHAIR = ROOT / "chair" / "claim.json" +MEMORY_SETTLE = 2 CLIP = 1000 CLEANUP_LOCK = "cleanup.lock" LOCK_TTL = 1800 @@ -548,33 +554,91 @@ def stage_for(free: float, samples: list[list[float]], cfg: dict, now: float) -> return STAGES[level] -def alert(stage: str, text: str) -> None: +def alert(stage: str, text: str, chair_only: bool) -> None: + """Args: + stage: the stage the alert reports. + text: what each session sees. + chair_only: whether only the session holding the office chair sees it. + """ + now = time.time_ns() + cutoff = now - ALERT_TTL * 10**9 + row = json.dumps({"id": now, "stage": stage, "text": text, "chair": chair_only}) + "\n" try: ROOT.mkdir(parents=True, exist_ok=True) - nofollow.append(ROOT, ALERTS, json.dumps({"id": time.time_ns(), "stage": stage, "text": text}) + "\n", 0o600) + with open(nofollow.open_below(ROOT, ALERTS, os.O_RDWR | os.O_CREAT, 0o600), "r+", encoding="utf-8") as handle: + fcntl.flock(handle, fcntl.LOCK_EX) + kept = [line + "\n" for row_id, line in history_rows(handle.read()) if isinstance(row_id, int) and row_id > cutoff] + handle.seek(0) + handle.truncate() + handle.write("".join(kept) + row) except OSError: pass +def seen_mark(path: Path) -> tuple[int, list[int] | None]: + """Args: + path: a session's seen marker: the id of the newest alert it saw and + the [inode, size, mtime_ns] of alerts.jsonl at that read, or a + bare id as older hooks wrote it. + + Returns: + (id, file); 0 and None for a missing or unreadable marker. + """ + try: + mark = json.loads(nofollow.read_text(ROOT, path)) + except (OSError, ValueError, RecursionError): + return 0, None + if isinstance(mark, int): + return mark, None + if isinstance(mark, dict) and isinstance(mark.get("id"), int): + return mark["id"], mark.get("file") + return 0, None + + +def chairs(session: str) -> bool: + try: + claim = json.loads(nofollow.read_text(ROOT, CHAIR)) + except (OSError, ValueError, RecursionError): + return False + return isinstance(claim, dict) and claim.get("session") == session + + +def changed_alerts(marked: list[int] | None) -> tuple[list[int], str] | None: + """Args: + marked: the [inode, size, mtime_ns] of alerts.jsonl at the session's + last read, or None. + + Returns: + (its [inode, size, mtime_ns] now, its text), None while it is + unreadable or still as marked. + """ + try: + with open(nofollow.open_below(ROOT, ALERTS, os.O_RDONLY, 0), "rb") as handle: + info = os.fstat(handle.fileno()) + file = [info.st_ino, info.st_size, info.st_mtime_ns] + if file == marked: + return None + return file, handle.read(nofollow.READ_LIMIT).decode("utf-8", errors="replace") + except OSError: + return None + + def unseen_alerts(session: str) -> list[str]: seen_path = ROOT / "seen" / session - try: - seen = int(nofollow.read_text(ROOT, seen_path)) - except (OSError, ValueError): - seen = 0 - try: - text = nofollow.read_text(ROOT, ALERTS) - except OSError: + seen, marked = seen_mark(seen_path) + changed = changed_alerts(marked) + if changed is None: return [] - cutoff = time.time_ns() - ALERT_TTL * 10**9 - fresh = [json.loads(line) for _, line in history_rows(text)] - fresh = [ - a for a in fresh - if isinstance(a["id"], int) and isinstance(a.get("text"), str) and a["id"] > max(seen, cutoff) - ] - if fresh: - write_text(seen_path, str(fresh[-1]["id"])) - return [clip(a["text"]) for a in fresh] + file, text = changed + fresh = fresh_alerts(text, max(seen, time.time_ns() - ALERT_TTL * 10**9)) + write_text(seen_path, json.dumps({"id": fresh[-1]["id"] if fresh else seen, "file": file})) + shown = [a for a in fresh if a.get("chair") is not True or chairs(session)] + return [clip(a["text"]) for a in shown] + + +def fresh_alerts(text: str, after: int) -> list[dict]: + rows = [json.loads(line) for _, line in history_rows(text)] + return [a for a in rows if isinstance(a["id"], int) and isinstance(a.get("text"), str) and a["id"] > after] def write_text(path: Path, text: str) -> None: @@ -596,10 +660,12 @@ def consumers() -> str: def notify(cfg: dict, text: str) -> None: + if not popups.allowed(ROOT, "resources", time.time()): + return try: subprocess.run([*cfg["notify"], text], capture_output=True, timeout=10, check=False) except (OSError, subprocess.TimeoutExpired): - alert("critical", f"RESOURCE: desktop notification failed: {cfg['notify'][0]}") + alert("critical", f"RESOURCE: desktop notification failed: {cfg['notify'][0]}", False) def spawn_cleanup(mode: str) -> None: @@ -614,12 +680,12 @@ def act(cfg: dict, stage: str, previous: str, free: float) -> None: limits = cfg["thresholds_gb"] head = f"/ has {free:.1f} GB free (warn < {limits['warn']}, stop < {limits['stop']}, critical < {limits['critical']} GB)" if STAGES.index(stage) < STAGES.index(previous): - alert(stage, f"RESOURCE {stage.upper()}: recovered, {head}.") + alert(stage, f"RESOURCE {stage.upper()}: recovered, {head}.", True) return if stage == "warn": - alert(stage, f"RESOURCE WARN: {head}. Biggest consumers: {consumers()}. Chair: plan a cleanup; peers: request no large slot.") + alert(stage, f"RESOURCE WARN: {head}. Biggest consumers: {consumers()}. Chair: plan a cleanup; peers: request no large slot.", False) elif stage in ("stop", "critical"): - alert(stage, f"RESOURCE {stage.upper()}: {head}. New heavy jobs are blocked; low-risk cleanup is running. {consumers()}") + alert(stage, f"RESOURCE {stage.upper()}: {head}. New heavy jobs are blocked; low-risk cleanup is running. {consumers()}", False) spawn_cleanup("--full") if stage == "critical": notify(cfg, f"Agents council: {head}. Heavy jobs blocked; a running stack needs the operator's OK to go.") @@ -628,13 +694,13 @@ def act(cfg: dict, stage: str, previous: str, free: float) -> None: def act_memory(cfg: dict, stage: str, previous: str, sample: dict[str, float | None]) -> None: head = memory_text(sample) if MEMORY_STAGES.index(stage) < MEMORY_STAGES.index(previous): - alert(stage, f"RESOURCE MEMORY {stage.upper()}: recovered, {head}.") + alert(stage, f"RESOURCE MEMORY {stage.upper()}: recovered, {head}.", True) return holders = "; ".join(swap_holders(CGROUPS, container_names())) or "no container holds swap" if stage == "warn": - alert(stage, f"RESOURCE MEMORY WARN: {head}. Top swap holders: {holders}. Chair: find the holder; peers: start nothing heavy.") + alert(stage, f"RESOURCE MEMORY WARN: {head}. Top swap holders: {holders}. Chair: find the holder; peers: start nothing heavy.", False) else: - alert(stage, f"RESOURCE MEMORY STOP: {head}. New heavy jobs are blocked. Top swap holders: {holders}.") + alert(stage, f"RESOURCE MEMORY STOP: {head}. New heavy jobs are blocked. Top swap holders: {holders}.", False) notify(cfg, f"Agents council: memory nearly exhausted ({head}). Heavy jobs blocked; top swap holders: {holders}.") @@ -650,27 +716,80 @@ def history_rows(text: str) -> list[tuple[str, str]]: return rows +def mirror_mark(target: Path) -> Path: + return target.with_name(f".{target.name}.mirrored") + + +def whole_lines(data: bytes) -> tuple[str, int]: + """Returns: + The complete lines of data as text and their byte length; a line still + being written stays for the next mirror. + """ + end = data.rfind(b"\n") + 1 + return data[:end].decode("utf-8", errors="replace"), end + + def keep_rows(origin: Path, target: Path) -> None: - # The kept file takes the source's mtime: an unchanged source is skipped without parsing. + """Mirror the rows of origin into target. + + Args: + origin: the agents' file below ROOT. + target: its kept copy below KEPT. Its marker holds the source's + [inode, offset] of the last mirror: the same inode at its marked + size is skipped without reading the source, past that offset only + the rows after it are appended, any other source merges every row + whose id the copy lacks. An mtime match is no skip: a copy created + or a row appended in the source's timestamp tick shares its mtime. + """ try: - source = origin.stat().st_mtime_ns - if target.exists() and target.stat().st_mtime_ns == source: - return - KEPT.mkdir(mode=0o700, parents=True, exist_ok=True) - with open(nofollow.open_below(KEPT, target, os.O_RDWR | os.O_CREAT | os.O_APPEND, 0o600), "a+", encoding="utf-8") as kept: - fcntl.flock(kept, fcntl.LOCK_EX | fcntl.LOCK_NB) - kept.seek(0) - known = {row_id for row_id, _ in history_rows(kept.read())} - for row_id, line in history_rows(nofollow.read_text(ROOT, origin)): - if row_id not in known: - known.add(row_id) - kept.write(line + "\n") - kept.flush() - os.utime(kept.fileno(), ns=(source, source)) + with open(nofollow.open_below(ROOT, origin, os.O_RDONLY, 0), "rb") as source: + info = os.fstat(source.fileno()) + KEPT.mkdir(mode=0o700, parents=True, exist_ok=True) + with open(nofollow.open_below(KEPT, target, os.O_RDWR | os.O_CREAT | os.O_APPEND, 0o600), "a+", encoding="utf-8") as kept: + own = os.fstat(kept.fileno()) + if (own.st_dev, own.st_ino) == (info.st_dev, info.st_ino): + return + fcntl.flock(kept, fcntl.LOCK_EX | fcntl.LOCK_NB) + offset = mirror_offset(target, info) + if offset == info.st_size: + return + source.seek(offset or 0) + text, length = whole_lines(source.read(nofollow.READ_LIMIT)) + if offset is None: + merge_rows(kept, text) + else: + kept.write("".join(line + "\n" for _, line in history_rows(text))) + kept.flush() + nofollow.replace(KEPT, mirror_mark(target), json.dumps([info.st_ino, (offset or 0) + length]), 0o600) except (OSError, ValueError, TypeError): pass +def mirror_offset(target: Path, info: os.stat_result) -> int | None: + """Args: + target: the kept copy. + info: the source's stat. + + Returns: + The source offset its tail starts at, None when the source has + another inode or is shorter than marked and takes the full merge. + """ + try: + inode, offset = json.loads(nofollow.read_text(KEPT, mirror_mark(target))) + except (OSError, ValueError, TypeError, RecursionError): + return None + return offset if inode == info.st_ino and isinstance(offset, int) and 0 <= offset <= info.st_size else None + + +def merge_rows(kept: TextIO, text: str) -> None: + kept.seek(0) + known = {row_id for row_id, _ in history_rows(kept.read())} + for row_id, line in history_rows(text): + if row_id not in known: + known.add(row_id) + kept.write(line + "\n") + + def keep_history() -> None: for origin, target in MIRRORED: keep_rows(origin, target) @@ -680,6 +799,23 @@ def stale(state: dict, cfg: dict, now: float) -> bool: return now - state.get("checked", 0) >= cfg["interval_seconds"] +def settled_memory(held: str, measured: str, below: int) -> tuple[str, int]: + """Args: + held: the memory stage the alerts last reported. + measured: the stage of this sample. + below: samples in a row so far that measured below held. + + Returns: + (the stage to report, the new below count): a higher stage at once, a + lower one only on the MEMORY_SETTLE-th sample in a row below held. + """ + rank = MEMORY_STAGES.index + if rank(measured) >= rank(held): + return (measured, 0) + below += 1 + return (measured, 0) if below >= MEMORY_SETTLE else (held, below) + + def measure_and_act(cfg: dict, state: dict, now: float, problem: str | None) -> None: free, _ = disk(cfg) samples = [s for s in state.get("samples", []) if now - s[0] <= cfg["projection_minutes"] * 60] @@ -690,8 +826,10 @@ def measure_and_act(cfg: dict, state: dict, now: float, problem: str | None) -> sample = None if problem else memory() was_short = state.get("memory_stage", "ok") if sample is not None: - state["memory_stage"] = memory_stage(sample, cfg) - due = now - state.get("caches_checked", 0) >= cfg["cache_interval_seconds"] + state["memory_stage"], state["memory_below"] = settled_memory( + was_short, memory_stage(sample, cfg), state.get("memory_below", 0) + ) + due =now - state.get("caches_checked", 0) >= cfg["cache_interval_seconds"] if due: state["caches_checked"] = now write_json(STATE, state) @@ -2769,6 +2907,7 @@ def cmd_cleanup(cfg: dict, args: argparse.Namespace) -> int: f"RESOURCE CLEANUP: freed {after - before:.1f} GB ({cache_gb:.1f} GB caches), " f"/ now {after:.1f} GB free; {len(results) - len(failed)} commands ok" + (f", failed: {' | '.join(failed)}" if failed else "."), + False, ) finally: os.rmdir(CLEANUP_LOCK, dir_fd=root) diff --git a/skills/kvb-org-organize/systemd/kvb-schedules.path b/skills/kvb-org-organize/systemd/kvb-schedules.path new file mode 100644 index 0000000..ad1aec4 --- /dev/null +++ b/skills/kvb-org-organize/systemd/kvb-schedules.path @@ -0,0 +1,8 @@ +[Unit] +Description=Schedules: apply a change of schedules.json at once + +[Path] +PathModified=%S/agents-shared/schedules.json + +[Install] +WantedBy=paths.target diff --git a/skills/kvb-org-organize/systemd/kvb-schedules.service b/skills/kvb-org-organize/systemd/kvb-schedules.service new file mode 100644 index 0000000..bc67c28 --- /dev/null +++ b/skills/kvb-org-organize/systemd/kvb-schedules.service @@ -0,0 +1,9 @@ +[Unit] +Description=Schedules: list the user timers and hooks for the hub, switch the first-party ones to schedules.json + +[Service] +Type=oneshot +Environment=PATH=/usr/bin:/bin +ExecStart=/usr/bin/python3 -I %h/.claude/skills/kvb-org-organize/scripts/schedules.py run +Nice=10 +TimeoutStartSec=120 diff --git a/skills/kvb-org-organize/systemd/kvb-schedules.timer b/skills/kvb-org-organize/systemd/kvb-schedules.timer new file mode 100644 index 0000000..27f33e5 --- /dev/null +++ b/skills/kvb-org-organize/systemd/kvb-schedules.timer @@ -0,0 +1,10 @@ +[Unit] +Description=Schedules: refresh the hub's timer and hook view every 5 minutes + +[Timer] +OnStartupSec=30s +OnUnitActiveSec=5min +AccuracySec=30s + +[Install] +WantedBy=timers.target diff --git a/skills/kvb-org-perform/scripts/log.py b/skills/kvb-org-perform/scripts/log.py index 013bf38..784b7e5 100755 --- a/skills/kvb-org-perform/scripts/log.py +++ b/skills/kvb-org-perform/scripts/log.py @@ -7,7 +7,8 @@ Usage: rate the latest spawn with this Agent description log.py followup --description D --text T record an operator follow-up question or correction on it - log.py persist hook (PostToolUse on Bash): append the one line a sandboxed + log.py persist hook (PostToolUse on Bash through hooks.py post-bash): + append the one line a sandboxed feedback or followup printed as `pending: `, only when the command was that bare call and the line is well-formed and from the hook's own session diff --git a/skills/kvb-org-queue-cleanup/scripts/cleanup.py b/skills/kvb-org-queue-cleanup/scripts/cleanup.py index 25692a0..e77b186 100755 --- a/skills/kvb-org-queue-cleanup/scripts/cleanup.py +++ b/skills/kvb-org-queue-cleanup/scripts/cleanup.py @@ -17,8 +17,10 @@ Environment: CLAUDE_CODE_SESSION_ID: run refuses to start while it is set. Args: - run: one round, accountable to the live holder of the council office - chair; without one it deletes nothing. --window: seconds of each + run: one round. It first drops the rows of both queue histories (the + agents' and the host-only copy) that ended over the kvb-org-queue + history.py WINDOW_SECONDS ago, then is accountable to the live holder + of the council office chair; without one it deletes no job. --window: seconds of each window, at least WINDOW_FLOOR (the service passes 900). It refuses unless it can write the host state. A job is a waiting or active entry with a string id, status, kind and lock; every other entry @@ -475,6 +477,48 @@ def claim(state: dict) -> bool: return True +def ended_before(line: str, cutoff: float) -> bool: + try: + row = json.loads(line) + except (ValueError, RecursionError): + return False + return isinstance(row, dict) and isinstance(row.get("end"), (int, float)) and row["end"] < cutoff + + +def trim_history(base: Path, path: Path, cutoff: float) -> int: + """Args: + base: the trusted directory holding path. + path: a queue history; every line but a row that ended before cutoff + stays byte for byte, and lines appended while it is rewritten + follow into the new file. + cutoff: epoch seconds. + + Returns: + The rows dropped; 0 for a missing or unreadable file. + """ + try: + with open(nofollow.open_below(base, path, os.O_RDONLY, 0), "rb") as old: + lines = old.read(nofollow.READ_LIMIT).decode("utf-8", errors="replace").splitlines() + kept = [line for line in lines if not ended_before(line, cutoff)] + if len(kept) == len(lines): + return 0 + nofollow.replace(base, path, "".join(f"{line}\n" for line in kept), 0o600) + late = old.read(nofollow.READ_LIMIT) + if late: + nofollow.append(base, path, late.decode("utf-8", errors="replace"), 0o600) + except OSError: + return 0 + return len(lines) - len(kept) + + +def trim_histories(now: float) -> None: + cutoff = now - queue.history.WINDOW_SECONDS + dropped = trim_history(watch.ROOT, watch.HISTORY, cutoff) + trim_history(watch.KEPT, watch.KEPT_HISTORY, cutoff) + if dropped: + print(f"queue-cleanup: dropped {dropped} queue history rows that ended over " + f"{queue.history.WINDOW_SECONDS // 86400} days ago") + + def run_round(window: float, clock: Clock) -> int: """Args: window: seconds each of the two windows lasts. @@ -483,6 +527,7 @@ def run_round(window: float, clock: Clock) -> int: Returns: The exit code. """ + trim_histories(clock.time()) session, chair = top_chair() if session is None: print(f"queue-cleanup: {chair}; no one is accountable, nothing is deleted") diff --git a/skills/kvb-org-queue/scripts/queue.py b/skills/kvb-org-queue/scripts/queue.py index 1ca5f1b..cee8bfa 100755 --- a/skills/kvb-org-queue/scripts/queue.py +++ b/skills/kvb-org-queue/scripts/queue.py @@ -7,7 +7,7 @@ Usage: queue.py list [--json] queue.py history queue.py cancel ID [--session ID] - queue.py block hook (PreToolUse on Bash) + queue.py block hook (PreToolUse on Bash through hooks.py pre-bash) Environment: AGENTS_COUNCIL_ROOT, XDG_STATE_HOME, HOME: the shared state directory the @@ -140,6 +140,7 @@ import importlib.util import json import os import re +import select import shlex import signal import stat @@ -168,7 +169,6 @@ EXE = os.path.realpath(sys.executable) CODE_FILES = tuple(path.relative_to(SKILLS) for path in (Path(__file__).resolve(), *SIBLINGS.values())) POLL_SECONDS = 20 CLAIM_SECONDS = 3 * POLL_SECONDS -TICK_SECONDS = 0.2 HOUR = 3600 CANCELLED = 3 NOT_RUN = 75 @@ -241,6 +241,7 @@ HOLDS = watch.ROOT / "holds" TAG = re.compile(r"\d+-\d+") SILENCE = watch.ROOT / "radio-silence.json" HISTORIES = (watch.HISTORY, watch.KEPT_HISTORY) +LEARNED: dict[str, tuple[dict, dict]] = {} def code_of(root: Path) -> str | None: @@ -312,8 +313,29 @@ def caps(cfg: dict) -> dict[str, int]: return cfg.get("slot_limits", {}) +def marks(paths: tuple[Path, ...]) -> tuple[tuple[int, int, int] | None, ...]: + found = [] + for path in paths: + try: + info = path.stat() + except OSError: + found.append(None) + else: + found.append((info.st_ino, info.st_mtime_ns, info.st_size)) + return tuple(found) + + def learned(cfg: dict, now: float) -> tuple[dict[str, dict], dict[str, dict]]: - return history.learn(history.read(HISTORIES), now, cfg) + """Returns: + history.learn over HISTORIES, computed once per process while both + files keep their inode, mtime and size and cfg its learning keys; a + row that leaves the window meanwhile counts until the next change. + """ + key = json.dumps([marks(HISTORIES), cfg.get("light_kinds"), cfg.get(history.RAM_CAP), cfg.get("load_limits")], sort_keys=True) + if key not in LEARNED: + LEARNED.clear() + LEARNED[key] = history.learn(history.read(HISTORIES), now, cfg) + return LEARNED[key] def limits(cfg: dict, kinds: dict[str, dict], entries: list[dict]) -> dict[str, tuple[int, str]]: @@ -1396,19 +1418,19 @@ def leave(entry_id: str) -> None: data["entries"] = [e for e in data["entries"] if e["id"] != entry_id] -def pause(caught: list[int]) -> None: - deadline = time.monotonic() + POLL_SECONDS - while not caught and time.monotonic() < deadline: - time.sleep(TICK_SECONDS) +def pause(wake: int) -> None: + select.select([wake], [], [], POLL_SECONDS) -def wait(cfg: dict, entry_id: str, caught: list[int]) -> tuple[int | None, int]: +def wait(cfg: dict, entry_id: str, caught: list[int], wake: int) -> tuple[int | None, int]: """Poll until the grant. Args: cfg: the config at the hold's start; every poll reads it anew. entry_id: this hold's entry. caught: signals the caller caught; the first ends the wait. + wake: the read end of the signal wakeup pipe; a caught signal makes it + readable, so a pause between polls ends at once. Returns: (None, other active jobs at the grant) once granted, else (the exit @@ -1458,7 +1480,7 @@ def wait(cfg: dict, entry_id: str, caught: list[int]) -> tuple[int | None, int]: if (position, reason) != shown: print(f"queue: {entry_id} waits at position {position}: {reason}", file=sys.stderr, flush=True) shown = (position, reason) - pause(caught) + pause(wake) return 128 + caught[0], 0 @@ -1610,6 +1632,9 @@ def cmd_hold(args: argparse.Namespace) -> int: else: send(child, signum) + wake, alarm = os.pipe() + os.set_blocking(alarm, False) + signal.set_wakeup_fd(alarm, warn_on_full_buffer=False) for signum in FORWARDED: signal.signal(signum, forward) with holding() as (tag, lock_fd): @@ -1622,7 +1647,7 @@ def cmd_hold(args: argparse.Namespace) -> int: }) try: try: - code, concurrent = wait(cfg, entry["id"], caught) + code, concurrent = wait(cfg, entry["id"], caught, wake) except Stale: hand_over(entry["id"]) raise diff --git a/skills/kvb-org-radio/SKILL.md b/skills/kvb-org-radio/SKILL.md index 142e223..fcefb22 100644 --- a/skills/kvb-org-radio/SKILL.md +++ b/skills/kvb-org-radio/SKILL.md @@ -13,7 +13,7 @@ reach other agents, on every runtime. Both channels share one store, ```bash radio.py post "" [--to ...] [--session ] radio.py send "" [--to ...] [--session ] -radio.py show [--all] [--session ] +radio.py show [--all] [--since s|m|h|d] [--summary] [--session ] radio.py clear [--force] [--session ] radio.py assist [--session ] ``` @@ -32,7 +32,7 @@ a full turn per receiver, costly. | Class | Addressee | Use | | --- | --- | --- | -| call | `--to` names | one peer must act or answer now; the caller gets a read receipt in its post and never waits | +| call | `--to` names | one peer must act or answer now; the caller never waits, a read receipt follows | | broadcast | all | every agent must know now, nothing is in danger | | security | all | a hazard peers must know before their next step (main red, a moved path) | | pan-pan | all | urgent trouble that blocks others and needs help soon | @@ -42,8 +42,8 @@ A mayday holds radio silence two hours, except `--no-silence` or under another's silence, which notify the operator instead: a hook refuses every Edit, Write and Bash command except those the config's `never_block` and `mayday_allow` start with and bare `radio.py` calls (text in single quotes, -no shell operators), until its sender runs `radio.py clear` once resolved. The sender keeps working; an agent -able to help joins with `radio.py assist` and keeps working too. Never +no shell operators), until its sender runs `radio.py clear` once resolved. +The sender keeps working; a helper joins with `radio.py assist`. Never clear another agent's mayday; `--force` only on the operator's order. ## Rules @@ -59,6 +59,8 @@ clear another agent's mayday; `--force` only on the operator's order. merged; never post them yourself. - One event, one row: no greeting, no acknowledgement, nothing the board or `kvb-org-rasci` register already shows; read them before asking. +- Overview: `radio.py show --all --since 1d --summary`, never the whole + store. - No secret, token or credential value in a text: name where it lives. - No sender proves operator approval, except an `Operator` row with `[kvb-orchestrator msg ]` whose `operator_message(id, text, to)`, with @@ -73,6 +75,6 @@ the post, `listen` (Stop, `asyncRewake`) wakes an idle session for the radio, `block` (PreToolUse) holds the mayday. Subagents get nothing; their parent session reads the radio. -Other runtimes (Codex, Gemini CLI, Hermes, OpenClaw) use the same store and +Other runtimes use the same store and scripts with `--session ` and read with `radio.py show` at session start, before every heavy job and at the end of every turn; nothing wakes them. diff --git a/skills/kvb-org-radio/scripts/radio.py b/skills/kvb-org-radio/scripts/radio.py index effe0b2..d1d8403 100755 --- a/skills/kvb-org-radio/scripts/radio.py +++ b/skills/kvb-org-radio/scripts/radio.py @@ -38,12 +38,15 @@ Args: assist [--session ]: join the active mayday as a helper, whom the block lets through like its sender. hook: UserPromptSubmit hook; prints the active silence and the - undelivered radio rows, mayday first, at most 10. Never fails. + undelivered radio rows, mayday first, at most 10, then the call + receipts while no other mail waits. Never fails. tool: PostToolBatch hook; adds the undelivered radio rows as additionalContext. Never fails. mailbox: Stop hook; prints the undelivered post, newsletters and call receipts to stderr, at most 10, and exits 2 so the agent reads them - before it idles. Never fails. + before it idles; receipts alone exit 0 and wait for the next prompt. + A receipt reads "read by HH:MM" without the call's text. + Never fails. listen: Stop hook with asyncRewake; polls every POLL_SECONDS until a radio row reaches this session, prints it to stderr and exits 2; exits 0 once a newer listener of the session took over. @@ -53,8 +56,11 @@ Args: mayday_allow regex matches from its start; a shell operator, double quote or backslash outside single quotes, or any parse error, blocks. The mayday's sender and its helpers pass. Never fails. - show [--all] [--session ]: print the active silence and the - undelivered rows, or every kept row, without delivering them. + show [--all] [--since s|m|h|d] [--summary] [--session ]: print + the active silence and the undelivered rows, or every kept row, + without delivering them; --since keeps the rows of that last span, + --summary prints one line per class and sender with the count and + the newest row. feedback set post|call [--session ]: store the channel feedback send uses for the session, in /feedback.json; post unless set. operator.py does not use it: it always calls. @@ -88,7 +94,7 @@ import shlex import subprocess import sys import time -from collections.abc import Iterator +from collections.abc import Callable, Iterator from pathlib import Path from types import ModuleType @@ -120,6 +126,9 @@ SILENCE_SECONDS = 7200 NOTIFY_SECONDS = 10 POLL_SECONDS = 15 NEVER = 0.0 +DURATION = re.compile(r"(\d+)([smhd])") +UNITS = {"s": 1, "m": 60, "h": 3600, "d": 86400} +HINT = "radio.py show --all --since 1d --summary" def fail(message: str) -> None: @@ -204,7 +213,9 @@ def clip(value: object) -> str: def line(row: dict) -> str: if kind(row) == "receipt": - return f"MAIL CALL {clip(row.get('from'))} read {clock(row['ts'])}: {clip(row.get('text'))}" + call = row.get("call") + sent = f" (your call of {clock(call)})" if isinstance(call, int | float) else "" + return f"MAIL CALL read by {clip(row.get('from'))} {clock(row['ts'])}{sent}" target = f" to {', '.join(clip(name) for name in targets(row))}" if targets(row) else "" return ( f"{channel(row).upper()} {kind(row).upper()} {clock(row['ts'])} " @@ -215,7 +226,7 @@ def line(row: dict) -> str: def capped(rows: list[dict]) -> list[str]: picked = sorted(rows, key=lambda row: (rank(row), -row["ts"]))[:SHOWN] more = ( - [f"{channel(rows[0]).upper()} {len(rows) - SHOWN} more items: radio.py show --all"] + [f"{channel(rows[0]).upper()} {len(rows) - SHOWN} more items: {HINT}"] if len(rows) > SHOWN else [] ) @@ -314,7 +325,7 @@ def silence_line(active: dict) -> str: def notify_once(active: dict | None) -> None: - if active is None: + if active is None or not organize("popups").allowed(ROOT, "mayday", time.time()): return try: argv = config()["notify"] @@ -489,16 +500,34 @@ def pending(sid: str, name: str, state: dict, family: str) -> list[dict]: return [row for row in items() if channel(row) == family and for_me(row, name, sid) and not seen(row, name, sid, prompt, state, since)] -def take(sid: str, family: str) -> list[dict]: +def take(sid: str, family: str, wanted: Callable[[list[dict]], bool]) -> list[dict]: + """Args: + sid: the session. + family: radio or mail. + wanted: whether the pending rows of the family are taken now; one + mark covers the whole family, so they are taken all or none. + + Returns: + The rows taken. + """ name = name_of(sid) with session(sid) as state: rows = pending(sid, name, state, family) - if rows: - state[family] = max(row["ts"] for row in rows) - save(sid, state) + if not wanted(rows): + return [] + state[family] = max(row["ts"] for row in rows) + save(sid, state) return rows +def letters(rows: list[dict]) -> bool: + return any(kind(row) != "receipt" for row in rows) + + +def receipts_only(rows: list[dict]) -> bool: + return bool(rows) and not letters(rows) + + def acknowledge(sid: str, rows: list[dict]) -> None: calls = [ row @@ -525,8 +554,9 @@ def cmd_hook(_: argparse.Namespace) -> int: if not sid: return 0 active = silence() - rows = take(sid, "radio") - out = ([silence_line(active)] if active else []) + capped(rows) + rows = take(sid, "radio", bool) + receipts = take(sid, "mail", receipts_only) + out = ([silence_line(active)] if active else []) + capped(rows) + capped(receipts) if out: print("\n".join(out)) notify_once(active) @@ -564,7 +594,7 @@ def cmd_tool(_: argparse.Namespace) -> int: def cmd_mailbox(_: argparse.Namespace) -> int: try: sid = hook_session() - rows = take(sid, "mail") if sid else [] + rows = take(sid, "mail", letters) if sid else [] except Exception: # noqa: BLE001 return 0 if not rows: @@ -588,7 +618,7 @@ def cmd_listen(_: argparse.Namespace) -> int: mtime = news_mtime() if mtime != known: known = mtime - rows = take(sid, "radio") + rows = take(sid, "radio", bool) if rows: print("\n".join(capped(rows)), file=sys.stderr) notify_once(silence()) @@ -643,6 +673,29 @@ def cmd_block(_: argparse.Namespace) -> int: return 2 +def duration(text: str) -> int: + match = DURATION.fullmatch(text) + if match is None: + raise argparse.ArgumentTypeError(f"{text!r} is no duration like 30m, 2h or 1d") + return int(match[1]) * UNITS[match[2]] + + +def summary(rows: list[dict]) -> list[str]: + """Returns: + One line per class and sender: the count and the newest row's time + and text, receipts without the text; radio classes first. + """ + groups: dict[tuple[str, str], list[dict]] = {} + for row in rows: + groups.setdefault((kind(row), clip(row.get("from"))), []).append(row) + lines = [] + for (cls, peer), group in sorted(groups.items(), key=lambda item: ((RADIO + MAIL).index(item[0][0]), item[0][1])): + last = max(group, key=lambda row: row["ts"]) + text = "" if cls == "receipt" else f": {clip(last.get('text'))}" + lines.append(f"{cls.upper()} {peer}: {len(group)}, last {clock(last['ts'])}{text}") + return lines + + def cmd_show(args: argparse.Namespace) -> int: active = silence() if active: @@ -654,8 +707,11 @@ def cmd_show(args: argparse.Namespace) -> int: name = name_of(sid) with session(sid) as state: rows = ordered(pending(sid, name, state, "radio") + pending(sid, name, state, "mail")) - for row in rows: - print(line(row)) + if args.since is not None: + cutoff = time.time() - args.since + rows = [row for row in rows if row["ts"] >= cutoff] + for text in summary(rows) if args.summary else [line(row) for row in rows]: + print(text) return 0 @@ -723,6 +779,8 @@ def main() -> int: sub.add_parser(name).set_defaults(func=func) p = sub.add_parser("show") p.add_argument("--all", action="store_true") + p.add_argument("--since", type=duration) + p.add_argument("--summary", action="store_true") p.add_argument("--session") p.set_defaults(func=cmd_show) feedback = sub.add_parser("feedback").add_subparsers(dest="action", required=True) diff --git a/skills/kvb-org-rasci/SKILL.md b/skills/kvb-org-rasci/SKILL.md index e7c5c55..9905d69 100644 --- a/skills/kvb-org-rasci/SKILL.md +++ b/skills/kvb-org-rasci/SKILL.md @@ -5,9 +5,8 @@ description: > Trigger on "rasci", "raci", "zuständigkeiten". --- -The register is the single point of truth of the organisation: every agent -records here what it works on, and claims, queue, handover and reports run -over it. `${CLAUDE_SKILL_DIR}/scripts/rasci.py` keeps it in +The register is the organisation's single point of truth: every agent +records what it works on; claims, queue, handover and reports run over it. `${CLAUDE_SKILL_DIR}/scripts/rasci.py` keeps it in `/rasci.json`. A `kvb-org-organize` claim enters its task by itself (holder as R and A, `running`, start, workdir, branch); its release sets `done` and the end, or `stopped` while a key result is still open. @@ -18,8 +17,7 @@ rasci.py kr add "" | met | open | rm rasci.py role "" rasci.py get rasci.py rm -rasci.py show [--all] -rasci.py show --wide [--all] +rasci.py show [--wide] [--all] rasci.py artifacts [--ended] [--task ] [--worker ] rasci.py estimate "" --value --complexity rasci.py estimate Operator --value @@ -40,22 +38,22 @@ published). `done` is refused while one is open; a task ended short of them is ## Roles - **R Responsible**: does the task: the claim holder, or the subagent it runs. -- **A Accountable**: exactly one; takes the final decision and carries the - overall responsibility. The claim holder, unless the operator decides. +- **A Accountable**: exactly one; takes the final decision. The claim + holder, unless the operator decides. - **S Supportive**: actively helps carry it out: a peer's fix, the chair's grant, a stack or runner. - **C Consulted**: asked for input before acting: line representatives, lineage owners, the operator on a pending decision. -- **I Informed**: kept up to date on progress or result, without a say. +- **I Informed**: kept informed of progress, without a say. `-` clears a party; the operator is the party `Operator`. ## Rules - On start, `set` title, objective, description, priority and worker, `kr - add` every key result, and `role` every party beyond R and A; on each - change, update the status. The worker is the one session or subagent - executing the task right now. + add` every key result, and `role` every party beyond R and A; update the + status on each change. The worker is the session or subagent executing + it now. - Artifacts share this table and follow the `kvb-org-artefacts` skill: record each one when it appears, drop it once deleted. Add every script or tool the task ran (`--tool`): `tools` ranks them for `kvb-dream`. @@ -69,8 +67,9 @@ published). `done` is refused while one is open; a task ended short of them is - Write only your own rows; another session's task belongs to that session. - Read `show` (Prio, WSJF, Task, Status, Worker, A; cells cut short) or `get` instead of asking a peer what it works on. `show --wide` adds OKR, - Artifacts, Start, End and every RASCI letter. -- When invoked, print `show --wide` unchanged; its `gaps:` line names tasks - without exactly one A, without R, or open without a key result. `hotfix/` - and `operator/` rows are records, not work tasks: `gaps:`, `wsjf` and + Artifacts, Start, End and every RASCI letter. Both cap at the top 30 open + tasks; `--all` lists every task. +- When invoked, summarize `show --wide` (counts per status, top tasks, the + `gaps:` line: shown tasks without exactly one A, without R, or open + without a key result), never reprint it. `hotfix/` and `operator/` rows are records, not work tasks: `gaps:`, `wsjf` and `artifacts` skip them. `get` prints one task in full, key results numbered. diff --git a/skills/kvb-org-rasci/scripts/rasci.py b/skills/kvb-org-rasci/scripts/rasci.py index 98fa4dc..28b7467 100755 --- a/skills/kvb-org-rasci/scripts/rasci.py +++ b/skills/kvb-org-rasci/scripts/rasci.py @@ -35,6 +35,7 @@ LETTERS = re.compile(r"^(?!.*(.).*\1)[RASCI]+$") ORDER = "RASCI" WIDE = ("Prio", "WSJF", "Task", "OKR", "Status", "Worker", "Artifacts", "Start", "End", *ORDER) COMPACT = ("Prio", "WSJF", "Task", "Status", "Worker", "A") +SHOWN = 30 STATUSES = ("queued", "running", "blocked", "done", "stopped") ENDED = ("done", "stopped") FIELDS = ( @@ -601,12 +602,16 @@ def cmd_show(args: argparse.Namespace) -> int: print("| " + " | ".join(header) + " |") print("|" + "---|" * len(header)) problems = [] - for rank, task in enumerate(ranked(rows), 1): + order = ranked(rows) + shown = order if args.all else order[:SHOWN] + for rank, task in enumerate(shown, 1): row = rows[task] score = wsjf(row) values = [rank, f"{score[2]:g}" if score else "-", *columns(task, row)] print("| " + " | ".join(str(v) for v in values) + " |") problems += gaps(task, row) + if len(order) > len(shown): + print(f"{len(order) - len(shown)} more (show --all)") if problems: print("gaps: " + "; ".join(problems)) return 0 diff --git a/skills/kvb-skill-silence/SKILL.md b/skills/kvb-skill-silence/SKILL.md index 257e996..3546304 100644 --- a/skills/kvb-skill-silence/SKILL.md +++ b/skills/kvb-skill-silence/SKILL.md @@ -15,12 +15,14 @@ duplicates; this skill cuts what still costs. The skills the current repository owns (`skills/`, its own `.claude/skills/`, not installed copies) and the skills repository. Measure before changing: -- `scripts/budget.py --repo --top 10`: listing words, the - longest descriptions, every SKILL.md over the cap. +- `scripts/budget.py --repo --top 10 --memory /MEMORY.md`: listing words, the longest descriptions, every SKILL.md + over the cap, and a `MEMORY.md` over 400 words. - Each own SKILL.md's word count, and what each registered hook prints per turn (settings files, read-only). -- The window's traffic: the radio store (`radio.py show --all` of the - `kvb-org-radio` skill; wakes carry `"wake": true` in its `news.jsonl`), +- The window's traffic: the radio store (`radio.py show --all --since 7d + --summary` of the `kvb-org-radio` skill; wakes carry `"wake": true` in its + `news.jsonl`), this session's `SendMessage` calls, and subagent runs (`log.py report` of the `kvb-org-perform` skill). - Context re-read per turn, from the transcripts Claude Code keeps: @@ -48,8 +50,8 @@ not installed copies) and the skills repository. Measure before changing: `kvb-agent-optimize` skill), grep and reading after. 6. **Hooks**: a hook prints nothing when nothing changed; a reminder fires once per window, not per turn. -7. **Context window**: `make install` sets `CLAUDE_CODE_AUTO_COMPACT_WINDOW` - to 500000 where it is unset. Propose a new value only with the +7. **Context window**: `make install` (`scripts/enable-plugins.js`) sets + `CLAUDE_CODE_AUTO_COMPACT_WINDOW` to 300000 where it is unset. Propose a new value only with the `context.py` series as evidence (tokens saved, compactions, and the operator's corrections of agents that lost a detail after one); the operator picks and changes it, because the settings are the operator's. diff --git a/tests/e2e/bidi.mjs b/tests/e2e/bidi.mjs index 1b174a7..083687e 100644 --- a/tests/e2e/bidi.mjs +++ b/tests/e2e/bidi.mjs @@ -10,7 +10,7 @@ import {join} from "node:path"; const [binary, planFile] = process.argv.slice(2); const plan = JSON.parse(readFileSync(planFile, "utf8")); const profile = mkdtempSync(join(tmpdir(), "bidi-")); -writeFileSync(join(profile, "user.js"), ['user_pref("media.navigator.streams.fake", true);', 'user_pref("media.navigator.permission.disabled", true);', ""].join("\n")); +writeFileSync(join(profile, "user.js"), ['user_pref("media.navigator.streams.fake", true);', 'user_pref("media.navigator.permission.disabled", true);', 'user_pref("media.volume_scale", "0.0");', ""].join("\n")); const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); const KEYS = {Enter: "", Tab: "", ArrowLeft: "", ArrowRight: ""}; const port = await new Promise((resolve) => { diff --git a/tests/e2e/cdp.mjs b/tests/e2e/cdp.mjs index 2d676f8..35717d1 100644 --- a/tests/e2e/cdp.mjs +++ b/tests/e2e/cdp.mjs @@ -15,7 +15,7 @@ const profile = mkdtempSync(join(tmpdir(), "cdp-")); // --no-sandbox: the agent sandbox already forbids the user namespaces Chromium's own sandbox needs. // --enable-unsafe-swiftshader: without a GPU, headless Chromium gives WebGL only through SwiftShader, which it no longer enables by itself. // --ignore-certificate-errors: the https station fixtures use a throwaway self-signed certificate. -const flags = ["--headless", "--no-sandbox", "--disable-gpu", "--use-angle=swiftshader", "--enable-unsafe-swiftshader", "--ignore-certificate-errors", "--use-fake-device-for-media-stream", "--use-fake-ui-for-media-stream", "--no-first-run", "--no-default-browser-check", "--hide-scrollbars", `--user-data-dir=${profile}`, "--remote-debugging-port=0", "about:blank"]; +const flags = ["--headless", "--no-sandbox", "--disable-gpu", "--use-angle=swiftshader", "--enable-unsafe-swiftshader", "--ignore-certificate-errors", "--use-fake-device-for-media-stream", "--use-fake-ui-for-media-stream", "--mute-audio", "--no-first-run", "--no-default-browser-check", "--hide-scrollbars", `--user-data-dir=${profile}`, "--remote-debugging-port=0", "about:blank"]; const browser = spawn(binary, flags, {stdio: ["ignore", "ignore", "pipe"]}); const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); const KEYS = {Enter: [13, "\r"], Tab: [9, ""], ArrowLeft: [37, ""], ArrowRight: [39, ""]}; diff --git a/tests/e2e/hub_e2e_inbox.py b/tests/e2e/hub_e2e_inbox.py index eee7b2f..7cdc3bd 100644 --- a/tests/e2e/hub_e2e_inbox.py +++ b/tests/e2e/hub_e2e_inbox.py @@ -25,7 +25,7 @@ RUN_DONE = """(async () => {@HELPERS@@LABELS@ await until(() => document.querySelector("#main .console").dataset.status === "done", 20000); await sleep(500); const lines = out().textContent.trim().split("\\n"); - return {done: line(), last: lines[lines.length - 1], lines: lines.length, followed: atEnd(), actions: all(".item-actions button", out().closest("li")).map(name)}; + return {done: line(), last: lines[lines.length - 1], lines: lines.length, followed: atEnd(), actions: all(":is(.item-actions, .code-foot) button", out().closest("li")).map(name)}; })()""".replace("@HELPERS@", HELPERS).replace("@LABELS@", LABELS) INBOX_PICK = """(async () => {@HELPERS@ navigator.credentials.get = @SIGNS@ ? navigator.credentials.get.bind(navigator.credentials) : () => Promise.reject(new DOMException("The operator canceled.", "NotAllowedError")); @@ -50,14 +50,15 @@ INBOX_PICK = """(async () => {@HELPERS@ last.scrollIntoView({block: "center"}); await sleep(300); const title = text(last.querySelector(".command code")); + const ref = last.dataset.ref; + await cursorTo(ref); + await sleep(300); const before = scroller.scrollTop; - last.querySelector("input").click(); + await pressKey("x"); await sleep(300); const after = scroller.scrollTop; - const holder = document.activeElement && document.activeElement.closest("li"); - const focused = Boolean(holder && text(holder.querySelector(".command code")) === title && document.activeElement.checked); - all("#main .inbox-list > li").find((li) => li.textContent.includes("pick a name")).querySelector("input").click(); - await sleep(300); + const focused = Boolean(document.querySelector(`#main .inbox-list > li.cursor[data-ref="${ref}"]`)); + await selectRow(all("#main .inbox-list > li").find((li) => li.textContent.includes("pick a name")).dataset.ref); const buttons = all("#grant-bar .grant-split button").map(name); document.querySelector("#grant-bar details.grant-menu > summary").click(); await until(() => document.querySelector("#grant-bar details.grant-menu[open]"), 2000); @@ -78,7 +79,8 @@ LAYOUT = """(async () => {@HELPERS@@LABELS@ await until(() => document.querySelector("#main .console") && rowOf("Rule request"), 8000); const rule = rowOf("Rule request"); return { - kinds: all("#main .inbox-list > li").map((li) => text(li.querySelector(".pill"))), + kinds: all("#main .inbox-list > li").map((li) => all(".msg-meta .pill", li).map(text).find((label) => label !== "done")), + done: all("#main .inbox-list > li[data-done]").length, splits: all("#main .deny-split").map((group) => all("button", group).map(name)), console: line(), followed: atEnd(), @@ -210,8 +212,6 @@ CHOICE_SEND = """(async () => {@HELPERS@@WATCH@ return {picked, counted, opened, runs, fields: all("textarea, input:not([type=checkbox])", bar()).length, ...fits()}; })()""".replace("@HELPERS@", HELPERS).replace("@WATCH@", WATCH) CHOICE_ANSWER = """(async () => {@HELPERS@@WATCH@ - bar().querySelector("summary").click(); - await sleep(200); const closed = [bar().open, all("button[data-channel]", bar()).filter((button) => button.checkVisibility()).length]; const card = await until(() => all("#main .inbox-list > li").find((li) => li.textContent.includes("@QUESTION@")), 8000); if (!card) { diff --git a/tests/e2e/hub_e2e_kit.py b/tests/e2e/hub_e2e_kit.py index 012c989..5a5ecc0 100644 --- a/tests/e2e/hub_e2e_kit.py +++ b/tests/e2e/hub_e2e_kit.py @@ -44,6 +44,13 @@ HELPERS = """ const all = (selector, root) => [...(root || document).querySelectorAll(selector)]; const text = (node) => (node ? node.textContent.trim() : null); const name = (node) => (node ? node.getAttribute("aria-label") || text(node) : null); + const streamShowsAll = async () => { + const chip = await until(() => all("#main .chip").find((node) => text(node) === "only waiting"), 8000); + if (chip && chip.getAttribute("aria-pressed") === "true") { + chip.click(); + await sleep(1500); + } + }; const toolbarRows = () => { const bar = document.querySelector('#main [role="toolbar"][aria-label="Tasks"]'); const boxes = bar ? [...bar.children].filter((node) => node.getClientRects().length).map((node) => node.getBoundingClientRect()).sort((a, b) => a.top - b.top) : []; @@ -58,6 +65,23 @@ HELPERS = """ } return rows; }; + const pressKey = async (key) => { + document.body.dispatchEvent(new KeyboardEvent("keydown", {key, bubbles: true, cancelable: true})); + await sleep(60); + }; + const cursorTo = async (ref) => { + const row = () => document.querySelector(`#main .inbox-list > li[data-ref="${ref}"]`); + const cursor = () => document.querySelector("#main .inbox-list > li.cursor"); + for (let steps = 0; steps < 50 && row() && cursor() !== row(); steps += 1) { + await pressKey(Number(row().dataset.index) > Number(cursor() ? cursor().dataset.index : -1) ? "j" : "k"); + } + return Boolean(row() && cursor() === row()); + }; + const selectRow = async (ref) => { + await cursorTo(ref); + await pressKey("x"); + await sleep(200); + }; const taskLayout = () => all("#main .graph.tasks > *").map((node) => (node.matches('[role="toolbar"]') ? "toolbar" : node.matches('[aria-label="Task filters"]') ? "chips" : "body")); const screenShown = async (ms) => { const shown = await until(() => { diff --git a/tests/e2e/hub_e2e_views.py b/tests/e2e/hub_e2e_views.py index abd6cf0..9307cfd 100644 --- a/tests/e2e/hub_e2e_views.py +++ b/tests/e2e/hub_e2e_views.py @@ -6,7 +6,8 @@ PROBE = """(async () => {@HELPERS@ await screenShown(8000); await until(() => !(text(document.querySelector("#main .space-note")) || "").startsWith("Loading") && !all("#main .empty h2").some((title) => text(title).endsWith("…")), 8000); const badge = (button) => { - const found = button.querySelector(".badge"); + const next = button.nextElementSibling; + const found = button.querySelector(".badge") || (next && next.matches("a.badge") ? next : null); return found && !found.hidden ? text(found) : null; }; const icons = all("svg.bi").filter((svg) => !svg.closest(".sprite")); @@ -95,7 +96,7 @@ ACTIONS = """(async () => {@HELPERS@ await sleep(500); found.popup = all("#popup input[type=radio]").map((input) => [input.value, input.checked]); found.popupUnlabelled = all("#popup svg.bi").map((svg) => svg.parentElement).filter((owner) => !text(owner) && !(owner.getAttribute("title") && owner.getAttribute("aria-label"))).length; - found.centred = [document.getElementById("popup").open, document.querySelector("#popup .leader line").getAttribute("display")]; + found.leader = [document.getElementById("popup").open, document.querySelector("#popup .leader line").getAttribute("display")]; return found; })()""".replace("@HELPERS@", HELPERS) POPUPS = """ @@ -140,7 +141,7 @@ POPUP_ORBIT = """(async () => {@HELPERS@@POPUPS@ await sleep(400); const art = box.querySelector(".popup-head .avatar.big"); const face = art ? {key: art.dataset.face, svg: Boolean(art.querySelector("svg.face-art .mouth")), text: art.textContent} : null; - const shown = {...opened(), ...look(pick()), sections: all("h3", box).map((head) => head.firstChild.textContent), composer: Boolean(box.querySelector("form textarea")), offices: text(box.querySelector(".popup-body p")), face}; + const shown = {...opened(), ...look(pick()), sections: all("h3", box).map((head) => head.firstChild.textContent), composer: Boolean(box.querySelector("form textarea")), offices: text(box.querySelector(".popup-body > div:not(.agent-settings) > p")), face}; const gone = await away(pick); click(pick()); await sleep(300); diff --git a/tests/e2e/radio_layout_focus_probes.py b/tests/e2e/radio_layout_focus_probes.py index ca25bcd..19cd585 100644 --- a/tests/e2e/radio_layout_focus_probes.py +++ b/tests/e2e/radio_layout_focus_probes.py @@ -47,7 +47,8 @@ POP = """(async () => {@HELPERS@@PROBES@ [top, bottom] = [Math.max(top, box(node).top), Math.min(bottom, box(node).bottom)]; } } - const room = {above: Math.floor(box(fold).top - top), below: Math.floor(bottom - box(fold).bottom), need: Math.floor(Math.min(layer.scrollHeight + layer.offsetHeight - layer.clientHeight, cap))}; + const frame = box(layer.offsetParent || fold); + const room = {above: Math.floor(frame.top - top), below: Math.floor(bottom - frame.bottom), need: Math.floor(Math.min(layer.scrollHeight + layer.offsetHeight - layer.clientHeight, cap))}; const opened = {open: fold.open, side: fold.dataset.side, height: Math.round(box(layer).height), cap: Math.ceil(cap), ...room, outside: outside(layer), whole}; layer.querySelector(".station button").focus(); document.activeElement.dispatchEvent(new KeyboardEvent("keydown", {key: "Escape", bubbles: true})); diff --git a/tests/e2e/radio_layout_kit.py b/tests/e2e/radio_layout_kit.py index ce1e67f..432cf07 100644 --- a/tests/e2e/radio_layout_kit.py +++ b/tests/e2e/radio_layout_kit.py @@ -70,7 +70,20 @@ PROBES = """ node.click(); }; const box = (node) => node.getBoundingClientRect(); - const ownStar = (owner) => all(".star", owner).find((node) => node.closest("[data-panel], [data-item]") === owner) || null; + const pinByMenu = async (owner) => { + const edge = box(owner); + owner.dispatchEvent(new MouseEvent("contextmenu", {bubbles: true, cancelable: true, button: 2, clientX: Math.round(edge.left + 4), clientY: Math.round(edge.top + 4)})); + const menu = await until(() => document.querySelector(".ctx-menu:not([hidden])"), 3000); + const item = menu ? all('[role="group"][data-scope="element"] [role="menuitem"]', menu).find((node) => text(node.querySelector(".ctx-label")) === "Pin to Home") : null; + if (item) { + item.click(); + } else if (menu) { + menu.dispatchEvent(new KeyboardEvent("keydown", {key: "Escape", bubbles: true, cancelable: true})); + } + await sleep(250); + const target = Panels.targetOf(owner); + return String((ViewStore.get("home.pins") || []).some((pin) => pin.kind === target.kind && pin.id === target.id)); + }; const openSpot = async () => { await until(() => typeof Nav === "object" && document.getElementById("radio-spot"), 8000); const toggle = document.getElementById("radio-open"); diff --git a/tests/e2e/radio_layout_probes.py b/tests/e2e/radio_layout_probes.py index 610516f..f10704b 100644 --- a/tests/e2e/radio_layout_probes.py +++ b/tests/e2e/radio_layout_probes.py @@ -39,9 +39,6 @@ LAYOUT = """(async () => {@HELPERS@@PROBES@ }); const [device, speak, history] = ["radio-device", "radio-speak", "radio-log"].map((id) => box(spot.querySelector(`[data-panel="${id}"]`))); const owners = [spot, ...all("[data-panel]", spot)]; - const controls = all('button, input, select, textarea, summary, [role="tab"]', spot).filter((node) => shown(node) && !node.classList.contains("star")); - const overlap = (a, b) => Math.max(0, Math.min(a.right, b.right) - Math.max(a.left, b.left)) * Math.max(0, Math.min(a.bottom, b.bottom) - Math.max(a.top, b.top)); - const covered = owners.map(ownStar).filter(Boolean).flatMap((star) => controls.filter((node) => !node.contains(star) && overlap(box(star), box(node)) > 1).map((node) => `${star.title} over ${node.getAttribute("aria-label") || text(node)}`)); const knobs = all(".radio-knobs .knob-row", spot).map((row) => Math.round(box(row.querySelector(".knob-label")).left)); return { page: [document.documentElement.scrollWidth, innerWidth], tall: [document.documentElement.scrollHeight, innerHeight, Math.round(box(spot).height)], @@ -57,7 +54,7 @@ LAYOUT = """(async () => {@HELPERS@@PROBES@ sliver: Math.min(...avatars.map((row) => row.sliver)), order: {stacked: device.bottom <= speak.top + 1 && speak.bottom <= history.top + 1 && Math.abs(device.left - speak.left) < 2, beside: device.right <= speak.left && speak.bottom <= history.top + 1 && Math.abs(speak.left - history.left) < 2}, labels: [...new Set(knobs)].length, - stars: owners.map((owner) => [owner.dataset.panel, Boolean(ownStar(owner))]), covered, + pinnable: owners.map((owner) => [owner.dataset.panel, Boolean(Panels.targetOf(owner))]), stars: all(".star, .star-row", spot).length, stations: [Boolean(spot.querySelector("details.radio-station")), spot.querySelector("details.radio-station").open], }; })()""" @@ -124,12 +121,7 @@ HOME = """(async () => {@HELPERS@@PROBES@ const owners = Object.fromEntries(@PARTS@.map((id) => [id, id === "radio" ? spot : spot.querySelector(`[data-panel="${id}"]`)])); const pressed = {}; for (const [id, owner] of Object.entries(owners)) { - const star = ownStar(owner); - if (star.getAttribute("aria-pressed") !== "true") { - star.click(); - await sleep(250); - } - pressed[id] = star.getAttribute("aria-pressed"); + pressed[id] = await pinByMenu(owner); } await until(() => (ViewStore.get("home.pins") || []).length === 4, 5000); const stored = (ViewStore.get("home.pins") || []).map((pin) => [`${pin.kind}:${pin.id}`, pin.w, pin.h]); @@ -169,7 +161,7 @@ HOME = """(async () => {@HELPERS@@PROBES@ speak: [Boolean(tile("radio-speak").querySelector("form.composer textarea")), tile("radio-speak").querySelectorAll("form.composer select option").length > 0], log: [tile("radio-log").querySelectorAll(".radio-row").length, tile("radio").querySelectorAll(".radio-row").length, document.querySelectorAll("#radio-spot .radio-row").length], gone: all("#main .home-tile.gone").length, - stars: all("#main .home-tile .home-body .star").length, + stars: all("#main .star, #main .star-row").length, ids: all("#main .home-tile .home-body [id]").map((node) => node.id).filter((id) => !id.startsWith("mic-field-")), }; const count = (id) => tile(id).querySelectorAll(".radio-row").length; @@ -332,7 +324,7 @@ SPOT = """(async () => {@HELPERS@@PROBES@@SPEAKING@ const found = await cue("@CUE@"); await sleep(300); states.speech = {...measure(), who: found && !found.error ? found.who : found}; - const stop = display.querySelector("button"); + const stop = display.querySelector('button[aria-label="Stop speaking"]'); if (stop) { stop.click(); } diff --git a/tests/e2e/radio_set_kit.py b/tests/e2e/radio_set_kit.py index ed8bac0..0e7bece 100644 --- a/tests/e2e/radio_set_kit.py +++ b/tests/e2e/radio_set_kit.py @@ -193,15 +193,26 @@ LOG = """(async () => {@HELPERS@@RADIO@ all(".radio-filters button", spot).find((button) => name(button) === "Clear filters").click(); await sleep(150); const clearedChips = [chips(), search().value, rows().length]; - const muteOf = () => spot.querySelector(".radio-row .radio-mute"); - const sender = name(muteOf()); - muteOf().click(); + const faceOf = () => spot.querySelector(".radio-row .radio-sender"); + const sender = name(faceOf()); + faceOf().click(); + const switches = await until(() => document.getElementById("popup").open && document.querySelector("#popup .agent-settings"), 4000); + const key = switches ? switches.dataset.agent : ""; + const stored = async () => ((await (await fetch("/api/state", {cache: "no-store"})).json()).settings.agents || {})[key] || null; + const flip = async (what, want) => { + switches.querySelector(`[data-switch="${what}"]`).click(); + await until(() => switches.querySelector(`[data-switch="${what}"]`).getAttribute("aria-pressed") === want, 4000); + }; + await flip("sound", "false"); + await flip("aloud", "false"); + await until(() => faceOf().dataset.quiet === "true", 4000); + const muted = [sender, faceOf().dataset.quiet, await stored(), Boolean(switches)]; + await flip("sound", "true"); + await flip("aloud", "true"); + await until(() => faceOf().dataset.quiet === "false", 4000); + const unmuted = [faceOf().dataset.quiet, await stored()]; + all("#popup .popup-head button").find((button) => name(button) === "Close").click(); await sleep(150); - const stored = () => JSON.parse(localStorage.getItem("kvb-orchestrator.radio") || "{}").muted || []; - const muted = [sender, muteOf().getAttribute("aria-pressed"), stored().length, document.getElementById("popup").open]; - muteOf().click(); - await sleep(150); - const unmuted = [muteOf().getAttribute("aria-pressed"), stored().length]; spot.querySelector(".radio-row .radio-pick").click(); const full = await until(() => document.getElementById("popup").open && document.querySelector("#popup .radio-full"), 4000); const opened = [document.getElementById("popup").open, text(full)]; diff --git a/tests/e2e/test_001_gaps_e2e.py b/tests/e2e/test_001_gaps_e2e.py index d230bf1..ac3a040 100644 --- a/tests/e2e/test_001_gaps_e2e.py +++ b/tests/e2e/test_001_gaps_e2e.py @@ -83,7 +83,7 @@ SWEEP = """(async () => {@HELPERS@ } return top < -1 || bottom > innerHeight + 1 || left < -1 || right > innerWidth + 1 ? "outside the window" : null; }; - const nodes = all("#main *").filter((node) => !node.ownerSVGElement && !node.closest("canvas") && shown(node)); + const nodes = all("#main *").filter((node) => !node.ownerSVGElement && !node.closest("canvas, [inert]") && shown(node)); const cut = nodes.map((node) => [path(node), clipped(node)]).filter(([, why]) => why); const owner = (node) => { for (let up = node.parentElement; up && up !== main; up = up.parentElement) { diff --git a/tests/e2e/test_agent_settings_e2e.py b/tests/e2e/test_agent_settings_e2e.py new file mode 100644 index 0000000..259782a --- /dev/null +++ b/tests/e2e/test_agent_settings_e2e.py @@ -0,0 +1,202 @@ +from __future__ import annotations + +import json +import os +import shutil +import sys +import time +import unittest +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path[:0] = [str(HERE.parent), str(HERE)] + +import hub_e2e_kit as base +import test_radio_receipts_e2e as rr +from kvb_orchestrator import settings +from kvb_orchestrator.presence import SNAPSHOT + +OUT = Path(os.environ.get("E2E_OUT", "/tmp/agent-settings-shots")) +WIDTH, HEIGHT = 1366, 900 +SILENT = """() => { + try { + localStorage.setItem("kvb-orchestrator.radio", JSON.stringify({mode: "silence", classes: ["mayday", "security"]})); + } catch (error) { + return; + } +}""" +KIT = """ + const SKIP = ".match-peek, .popup-head, .ctx-menu, .palette, #popup, .chip-check"; + const OPENERS = "button.agent-link, button.agent-face, button.reader, button.radio-sender, button.org-holder"; + const fresh = async () => (await (await fetch("/api/state", {cache: "no-store"})).json()); + const audit = async (root) => { + const keys = (await fresh()).people || {}; + const faces = all(".avatar[data-face]", root).filter((node) => node.getClientRects().length && keys[node.dataset.face] && !node.closest(SKIP)); + return {count: faces.length, loose: faces.filter((node) => !node.closest(OPENERS)).map((node) => `${node.dataset.face} in ${node.parentElement.className}`)}; + }; + const closePopup = async () => { + const close = all("#popup .popup-head button").find((node) => node.getAttribute("aria-label") === "Close"); + if (close) { + close.click(); + } + await until(() => !document.getElementById("popup").open, 4000); + }; + const opens = async (button) => { + if (!button) { + return null; + } + button.click(); + const group = await until(() => document.getElementById("popup").open && document.querySelector("#popup .agent-settings[data-agent]"), 4000); + const found = group ? {agent: group.dataset.agent, switches: all("[data-switch]", group).map((node) => [node.dataset.switch, node.getAttribute("aria-pressed"), text(node)])} : null; + await closePopup(); + return found; + }; + const shown = (selector) => all(selector).find((node) => node.getClientRects().length) || null; +""" +STREAM = """(async () => {@HELPERS@@KIT@ + await screenShown(8000); + location.hash = "#stream"; + await streamShowsAll(); + await until(() => shown("#main .entry button.agent-link") && shown("#main .entry button.reader"), 10000); + await sleep(400); + const found = { + audit: await audit(document.getElementById("main")), + entry: await opens(shown("#main .entry button.agent-link")), + reader: await opens(shown("#main .entry button.reader")), + }; + location.hash = "#stream/inbox"; + await until(() => shown("#main .inbox-list button.agent-link"), 10000); + return {...found, waiting: await opens(shown("#main .inbox-list button.agent-link"))}; +})()""" +TASKS = """(async () => {@HELPERS@@KIT@ + location.hash = "#tasks"; + await until(() => shown("#main .who button.agent-link"), 10000); + await sleep(400); + return {audit: await audit(document.getElementById("main")), worker: await opens(shown("#main .who button.agent-link"))}; +})()""" +RADIO = """(async () => {@HELPERS@@KIT@ + location.hash = "#stream/radio"; + const spot = await until(() => document.getElementById("radio-spot") && shown("#radio-spot .radio-row .radio-sender") && document.getElementById("radio-spot"), 10000); + await sleep(400); + return {audit: spot ? await audit(spot.querySelector(".radio-log")) : null, sender: await opens(shown("#radio-spot .radio-row .radio-sender"))}; +})()""" +BUBBLES = """(async () => {@HELPERS@@KIT@ + const everything = document.querySelector('#radio-spot .radio-tabs [data-tab="all"]'); + if (everything && everything.getAttribute("aria-selected") !== "true") { + everything.click(); + await sleep(400); + } + const row = await until(() => all("#radio-spot .radio-row").find((node) => node.querySelector(".radio-sender") && node.querySelector(".radio-route") && text(node.querySelector(".radio-route")).startsWith("Stage ")), 10000); + if (!row) { + return {error: "no radio row from Stage"}; + } + row.querySelector(".radio-sender").click(); + const group = await until(() => document.getElementById("popup").open && document.querySelector("#popup .agent-settings[data-agent]"), 4000); + if (!group) { + return {error: "no agent settings for Stage"}; + } + const agent = group.dataset.agent; + const toggle = () => group.querySelector('[data-switch="bubbles"]'); + toggle().click(); + const pressed = Boolean(await until(() => toggle().getAttribute("aria-pressed") === "false", 6000)); + const end = Date.now() + 6000; + let stored = null; + while (Date.now() < end) { + stored = ((await fresh()).settings.agents || {})[agent] || null; + if (stored && stored.bubbles === false) { + break; + } + await sleep(200); + } + await closePopup(); + const other = await until(() => document.querySelector('.speech-bubble:not([data-who="' + agent + '"])'), 15000); + const seen = new Set(); + const watchUntil = Date.now() + 3000; + while (Date.now() < watchUntil) { + all(".speech-bubble").forEach((node) => seen.add(node.dataset.who)); + await sleep(100); + } + const quiet = await until(() => all("#radio-spot .radio-row").find((node) => text(node.querySelector(".radio-route") || node).startsWith("Stage ") && node.querySelector(".radio-sender")), 4000); + quiet.querySelector(".radio-sender").click(); + const again = await until(() => document.getElementById("popup").open && document.querySelector("#popup .agent-settings[data-agent]"), 4000); + again.querySelector('[data-switch="bubbles"]').click(); + await until(() => again.querySelector('[data-switch="bubbles"]').getAttribute("aria-pressed") === "true", 6000); + await sleep(600); + const back = ((await fresh()).settings.agents || {})[agent] || null; + await closePopup(); + return {agent, pressed, stored, other: other ? other.dataset.who : null, seen: [...seen], back}; +})()""" + + +def fill(probe: str) -> str: + return probe.replace("@HELPERS@", base.HELPERS).replace("@KIT@", KIT) + + +@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium") +class TestAgentSettings(base.OrchestratorE2ECase): + mark = rr.TestRadioReceipts.mark + sight = rr.TestRadioReceipts.sight + + def setUp(self): + super().setUp() + OUT.mkdir(parents=True, exist_ok=True) + file =self.state / "settings.json" + file.write_text(json.dumps({**settings.SETTINGS, "bubbles": True}), encoding="utf-8") + held = self.httpd.hub.settings + with held.lock: + held.current = settings.Settings(file).get() + self.sent = False + self.present() + self.mark("s2", time.time()) + self.sight() + self.beside(self.live_rows) + + def present(self) -> None: + payload = {"written": time.time(), "sessions": {"s1": {"name": "Skills session", "running": True}, "s2": {"name": "Stage", "running": True}}} + written = self.state / f".{SNAPSHOT}.e2e" + written.write_text(json.dumps(payload), encoding="utf-8") + os.replace(written, self.state / SNAPSHOT) + + def live_rows(self) -> None: + self.present() + if self.sent or self.httpd.hub.settings.get()["agents"].get("s2", {}).get("bubbles") is not False: + return + self.sent = True + now = time.time() + rows = [ + {"ts": now, "from": "Stage", "to": [], "text": "stage rotates the keys quietly", "class": "security", "v": 2}, + {"ts": now + 0.001, "from": "Skills session", "to": [], "text": "skills rotates the keys aloud", "class": "security", "v": 2}, + ] + with (self.council / "news.jsonl").open("a", encoding="utf-8") as handle: + handle.write(self.jsonl(rows)) + + def test_chromium_opens_every_agent_from_its_face_or_name_and_switches_its_own_bubbles(self): + steps = [ + {"width": WIDTH, "height": HEIGHT, "url": f"{self.base}?agents#stream", "wait": 1200, "probe": fill(STREAM), "shot": str(OUT / "chromium-stream.png")}, + {"width": WIDTH, "height": HEIGHT, "url": None, "wait": 0, "probe": fill(TASKS), "shot": str(OUT / "chromium-tasks.png")}, + {"width": WIDTH, "height": HEIGHT, "url": None, "wait": 0, "probe": fill(RADIO), "shot": str(OUT / "chromium-radio.png")}, + {"width": WIDTH, "height": HEIGHT, "url": None, "wait": 0, "probe": fill(BUBBLES), "shot": str(OUT / "chromium-bubbles.png")}, + ] + data = self.drive(steps, self.authenticator(), init=SILENT) + (OUT / "chromium-agent-settings.json").write_text(json.dumps(data, indent=1), encoding="utf-8") + self.assertEqual(data["errors"], []) + stream, tasks, radio, bubbles = data["results"] + switches = [["sound", "true", "Sound"], ["aloud", "true", "Read aloud"], ["bubbles", "true", "Bubbles"]] + for name, found in (("stream", stream), ("tasks", tasks), ("radio", radio)): + with self.subTest(screen=name): + self.assertNotIn("error", found, found) + self.assertGreater(found["audit"]["count"], 0, found) + self.assertEqual(found["audit"]["loose"], [], found) + for found in (stream["entry"], stream["waiting"], stream["reader"], tasks["worker"], radio["sender"]): + self.assertIsNotNone(found, data["results"]) + self.assertEqual(found["switches"], switches, found) + self.assertNotIn("error", bubbles, bubbles) + self.assertEqual((bubbles["agent"], bubbles["pressed"], bubbles["stored"]), ("s2", True, {"sound": True, "aloud": True, "bubbles": False}), bubbles) + self.assertEqual(bubbles["other"], "s1", bubbles) + self.assertNotIn("s2", bubbles["seen"], bubbles) + self.assertIsNone(bubbles["back"], bubbles) + self.assertEqual(self.httpd.hub.settings.get()["agents"], {}) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/e2e/test_artifacts_head_e2e.py b/tests/e2e/test_artifacts_head_e2e.py new file mode 100644 index 0000000..044c9cd --- /dev/null +++ b/tests/e2e/test_artifacts_head_e2e.py @@ -0,0 +1,87 @@ +from __future__ import annotations + +import json +import os +import shutil +import sys +import unittest +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path[:0] = [str(HERE.parent), str(HERE)] + +import hub_e2e_kit as base +from hub_case import HubCase + +OUT = Path(os.environ.get("E2E_OUT", "/tmp/hub-045-shots")) +WIDTHS = ((1920, 1080), (1366, 768), (390, 844)) +HEAD = """(async () => {@HELPERS@ + const head = await until(() => { + const found = document.querySelector("#main .art-head"); + return found && found.querySelector(".art-count").textContent && found.querySelector(".delete-blocked") ? found : null; + }, 10000); + if (!head) { + return {error: text(document.getElementById("main")).slice(0, 300)}; + } + await sleep(300); + const items = (node) => (getComputedStyle(node).display === "contents" ? [...node.children].flatMap(items) : [node]); + const shown = [...head.children].flatMap(items).filter((child) => child.getClientRects().length); + const boxes = shown.map((child) => child.getBoundingClientRect()).sort((a, b) => a.top - b.top); + let [lines, bottom] = [0, -Infinity]; + for (const box of boxes) { + if (box.top >= bottom - 1) { + lines += 1; + bottom = box.bottom; + } else { + bottom = Math.max(bottom, box.bottom); + } + } + const look = getComputedStyle(head); + const inner = head.clientHeight - parseFloat(look.paddingTop) - parseFloat(look.paddingBottom); + const row = Math.max(...shown.map((child) => child.getBoundingClientRect().height)); + const count = head.querySelector(".art-count"); + const chip = head.querySelector(".delete-blocked"); + const every = head.querySelector('button[aria-label="Delete all merged"]'); + return { + lines, inner: Math.round(inner), row: Math.round(row), overflow: head.scrollWidth > head.clientWidth + 1, + count: {text: text(count), title: count.title, ellipsis: getComputedStyle(count).textOverflow, nowrap: getComputedStyle(count).whiteSpace}, + chip: {title: chip.title, beside: chip.parentElement === every.closest(".why-off").parentElement}, + every: {disabled: every.disabled, wrapper: every.closest(".why-off").title}, + wide: document.documentElement.scrollWidth > innerWidth + 1, + }; +})()""" + + +@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium") +class TestArtifactsHead(HubCase): + drive = base.OrchestratorE2ECase.drive + + def setUp(self): + super().setUp() + OUT.mkdir(parents=True, exist_ok=True) + self.write_fixture("branch-tree-tokenless.json") + data = json.loads(self.tree_file.read_text(encoding="utf-8")) + data["repos"] = [repo for repo in data["repos"] if repo["forge"] != "none"] + self.tree_file.write_text(json.dumps(data), encoding="utf-8") + + def test_chromium_keeps_the_artifacts_head_on_one_line_from_1024_px_and_moves_delete_blocked_into_a_chip(self): + steps = [{"width": width, "height": height, "url": f"http://localhost:{self.port}/?{width}#artifacts/tree", "wait": 1500, "probe": HEAD.replace("@HELPERS@", base.HELPERS), "shot": str(OUT / f"chromium-{width}-artifacts-head.png")} for width, height in WIDTHS] + data = self.drive(steps, None) + (OUT / "chromium-artifacts-head.json").write_text(json.dumps(data, indent=1), encoding="utf-8") + self.assertEqual([error for error in data["errors"] if "/favicon.ico" not in error], []) + reason = "no GitHub token in the Secret Service" + for (width, _), found in zip(WIDTHS, data["results"], strict=True): + with self.subTest(width=width): + self.assertNotIn("error", found, found) + self.assertEqual((found["overflow"], found["wide"]), (False, False), found) + self.assertLessEqual(found["lines"], 1 if width >= 1024 else 2, found) + if width >= 1024: + self.assertLessEqual(abs(found["inner"] - found["row"]), 2, found) + self.assertRegex(found["count"]["text"], r"^\d+ repositories · as of \d\d:\d\d$") + self.assertEqual((found["count"]["title"], found["count"]["ellipsis"], found["count"]["nowrap"]), (found["count"]["text"], "ellipsis", "nowrap"), found) + self.assertEqual(found["chip"], {"title": f"Delete blocked: {reason}", "beside": True}, found) + self.assertEqual(found["every"], {"disabled": True, "wrapper": f"Delete all merged blocked: {reason}"}, found) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/e2e/test_badge_match_e2e.py b/tests/e2e/test_badge_match_e2e.py new file mode 100644 index 0000000..fd5821b --- /dev/null +++ b/tests/e2e/test_badge_match_e2e.py @@ -0,0 +1,103 @@ +from __future__ import annotations + +import json +import os +import shutil +import sys +import unittest +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path[:0] = [str(HERE.parent), str(HERE)] + +import hub_e2e_kit as base +import hub_support +from hub_case import HubCase + +OUT = Path(os.environ.get("E2E_OUT", "/tmp/hub-038-shots")) +WIDTHS = tuple(size for size in base.WIDTHS if size[0] in (1366, 390)) +BADGE = """ + const tasks = () => document.getElementById("tab-tasks"); + const badge = () => { + const next = tasks().nextElementSibling; + return next && next.matches("a.badge") && !next.hidden ? next : null; + }; +""" +CLICK = """(async () => {@HELPERS@@BADGE@ + await screenShown(8000); + const count = await until(badge, 8000); + if (!count) { + return {error: "no count"}; + } + const [icon, edge, own] = [tasks().querySelector("svg").getBoundingClientRect(), count.getBoundingClientRect(), tasks().getBoundingClientRect()]; + const pad = parseFloat(getComputedStyle(tasks()).paddingLeft); + const gap = parseFloat(getComputedStyle(tasks()).columnGap); + const found = { + text: text(count), label: count.getAttribute("aria-label"), nested: Boolean(tasks().querySelector(".badge")), + icon: Math.round((icon.left - own.left - pad) * 10) / 10, count: Math.round((edge.left - icon.right - gap) * 10) / 10, + }; + count.click(); + found.hash = await until(() => location.hash === "#tasks/match" && location.hash, 4000); + location.hash = "stream"; + await screenShown(8000); + tasks().click(); + await sleep(400); + found.icon_hash = location.hash; + return found; +})()""" +FOCUS = """(async () => {@HELPERS@@BADGE@ + await screenShown(8000); + const count = await until(badge, 8000); + count.focus(); + return {focused: document.activeElement === count}; +})()""" +READ = """(async () => {@HELPERS@ + await sleep(400); + return {hash: location.hash}; +})()""" + + +def probe(template: str) -> str: + return template.replace("@HELPERS@", base.HELPERS).replace("@BADGE@", BADGE) + + +@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium") +class TestBadgeToMatch(HubCase): + drive = base.OrchestratorE2ECase.drive + + def setUp(self): + super().setUp() + OUT.mkdir(parents=True, exist_ok=True) + self.claim("s1", "Skills") + decided = self.tool("decision_request", {"question": "Open the Match view?", "options": hub_support.OPTIONS, "agent": "Skills", "recommended": ""}) + self.assertFalse(decided["isError"], decided) + self.snapshot() + self.page_url = f"http://localhost:{self.port}/" + + def test_chromium_opens_match_from_the_count_by_click_and_enter_and_tasks_from_the_icon(self): + steps = [] + for width, height in WIDTHS: + at = {"width": width, "height": height} + steps += [ + {**at, "url": f"{self.page_url}?{width}-click#stream", "wait": 1200, "probe": probe(CLICK), "shot": str(OUT / f"chromium-{width}-badge-match.png")}, + {**at, "url": f"{self.page_url}?{width}-key#stream", "wait": 1200, "probe": probe(FOCUS), "shot": None}, + {**at, "url": None, "wait": 0, "keys": ["Enter"], "probe": probe(READ), "shot": None}, + ] + data = self.drive(steps, None) + (OUT / "chromium-badge-match.json").write_text(json.dumps(data, indent=1), encoding="utf-8") + self.assertEqual(data["errors"], []) + results = iter(data["results"]) + for width, _ in WIDTHS: + click, focus, read = next(results), next(results), next(results) + with self.subTest(width=width): + self.assertNotIn("error", click, click) + self.assertEqual((click["text"], click["label"], click["nested"]), ("1", "1 open operator task: open Match", False), click) + self.assertLessEqual(abs(click["icon"]), 1, click) + self.assertLessEqual(abs(click["count"]), 1, click) + self.assertEqual(click["hash"], "#tasks/match", click) + self.assertTrue(click["icon_hash"].startswith("#tasks") and not click["icon_hash"].startswith("#tasks/match"), click) + self.assertEqual((focus["focused"], read["hash"]), (True, "#tasks/match"), (focus, read)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/e2e/test_box_heads_e2e.py b/tests/e2e/test_box_heads_e2e.py index adba850..b94404c 100644 --- a/tests/e2e/test_box_heads_e2e.py +++ b/tests/e2e/test_box_heads_e2e.py @@ -19,6 +19,7 @@ from hub_case import HubCase OUT = Path(os.environ.get("E2E_OUT", "/tmp/box-heads-shots")) VIEWS = { + "stream": "Stream", "tasks/match": "Match", "tasks/list": "Tasks", "tasks/board": "Tasks", @@ -52,10 +53,19 @@ BAND = """(async () => {@HELPERS@@BUTTON@ const style = getComputedStyle(main); const outer = main.getBoundingClientRect(); const box = head.getBoundingClientRect(); - const tops = [...head.querySelectorAll(":scope > *, :scope > .box-slot > *")].filter((node) => node.getClientRects().length).map((node) => Math.round(node.getBoundingClientRect().top)); + const shown = [...head.querySelectorAll(":scope > *, :scope > .box-slot > *")].filter((node) => node.getClientRects().length); + const tops = shown.map((node) => Math.round(node.getBoundingClientRect().top)); + const control = ':is(.btn, .field, select, input[type="search"], input[type="text"], .segmented, .chip, .menu > summary, .mic-line)'; + const controls = all(control, head).filter((node) => node.getClientRects().length && !node.closest(".menu-box") && !node.parentElement.closest(".mic-line, .segmented")) + .map((node) => [node.getAttribute("aria-label") || node.className || node.tagName, Math.round(node.getBoundingClientRect().height * 10) / 10]); + const centers = shown.map((node) => { + const box = node.getBoundingClientRect(); + return Math.round((box.top + box.height / 2) * 10) / 10; + }); return { + controls, centers, token: getComputedStyle(document.documentElement).getPropertyValue("--control-h").trim(), label: head.getAttribute("aria-label"), count: all(".box-head", main).length, cards: all(".card.controls", main).length, first, - edges: [box.top - outer.top - parseFloat(style.borderTopWidth), box.left - outer.left - parseFloat(style.borderLeftWidth), outer.right - parseFloat(style.borderRightWidth) - box.right].map((value) => Math.round(value * 10) / 10), + edges: [box.top - outer.top - parseFloat(style.borderTopWidth), box.left - outer.left - parseFloat(style.borderLeftWidth), outer.left + main.clientLeft + main.clientWidth - box.right].map((value) => Math.round(value * 10) / 10), height: Math.round(box.height), rows: new Set(tops).size, button: buttonHeight(head, "button.btn.small, button.btn"), wide: document.documentElement.scrollWidth > innerWidth + 1, violations: window.e2eViolations || null, }; @@ -92,9 +102,11 @@ EDGE = """(async () => {@HELPERS@ card.dataset.pattern = pattern; await sleep(60); const shown = getComputedStyle(card); + const edge = getComputedStyle(card, "::before"); const after = getComputedStyle(head, "::before"); found[pattern] = { - border: shown.borderTopWidth, bar: shown.backgroundImage.startsWith("linear-gradient"), size: shown.backgroundSize.split(",")[0].trim(), + border: shown.borderTopWidth, bar: edge.backgroundImage.startsWith("linear-gradient"), size: edge.height, scroll: shown.overflowY, + fade: (edge.maskImage || edge.webkitMaskImage || "").replace(/\\s+/g, " "), flush: Math.round(head.getBoundingClientRect().top - card.getBoundingClientRect().top), top: after.top, mask: (after.maskImage || after.webkitMaskImage || "").replace(/\\s+/g, " "), hatch: after.backgroundImage !== "none", }; @@ -146,6 +158,11 @@ class TestBoxHeads(HubCase): self.assertEqual((row["label"], row["count"], row["cards"], row["first"]), (VIEWS[view], 1, 0, True), row) self.assertEqual(row["edges"], [0, 0, 0], row) self.assertEqual((row["wide"], w4.quiet(row["violations"])), (False, []), row) + self.assertEqual(row["token"], "36px", row) + self.assertTrue(row["controls"], row) + self.assertEqual([control for control in row["controls"] if abs(control[1] - 36) > 1], [], row) + if view == "stream" and row["rows"] == 1: + self.assertLessEqual(max(row["centers"]) - min(row["centers"]), 2, row) if width == 1920 and row["rows"] == 1: self.assertLessEqual(abs(row["height"] - home["head"]), 1, (row, home["head"])) self.assertLessEqual(abs(row["button"] - home["button"]), 1, (row, home["button"])) @@ -172,8 +189,9 @@ class TestBoxHeads(HubCase): with self.subTest(browser=browser, width=width, step="edge"): self.assertNotIn("error", edge, edge) for pattern, found in edge["found"].items(): - self.assertEqual((found["border"], found["bar"], found["size"], found["flush"], found["top"], found["hatch"]), ("0px", True, "100% 6px", 0, "0px", True), (pattern, found)) - self.assertTrue(found["mask"].startswith("linear-gradient(rgba(0, 0, 0, 0) 6px"), (pattern, found)) + self.assertEqual((found["border"], found["bar"], found["size"], found["scroll"], found["flush"], found["top"], found["hatch"]), ("0px", True, "22px", "hidden", 0, "0px", True), (pattern, found)) + self.assertTrue(found["fade"].startswith("linear-gradient(rgb(0, 0, 0) 0px"), (pattern, found)) + self.assertTrue(found["mask"].startswith("linear-gradient(rgba(0, 0, 0, 0) 0px"), (pattern, found)) def test_chromium_puts_one_flush_band_on_every_box_and_keeps_the_card_bar_on_the_edge(self): data = self.drive(self.steps("chromium"), None, init=w4.GUARD) diff --git a/tests/e2e/test_bubbles_mode_row_e2e.py b/tests/e2e/test_bubbles_mode_row_e2e.py new file mode 100644 index 0000000..a01dad9 --- /dev/null +++ b/tests/e2e/test_bubbles_mode_row_e2e.py @@ -0,0 +1,96 @@ +from __future__ import annotations + +import json +import os +import shutil +import sys +import unittest +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path[:0] = [str(HERE.parent), str(HERE)] + +import hub_e2e_kit as base +from hub_case import HubCase +from hub_support import ASK + +OUT = Path(os.environ.get("E2E_OUT", "/tmp/bubbles-mode-row-shots")) +PROBE = """(async () => {@HELPERS@ + await screenShown(8000); + location.hash = "#stream/radio"; + const toggle = await until(() => document.querySelector("#radio-spot:not([hidden]) .radio-bubbles"), 8000); + if (!toggle) { + return {error: "no bubbles toggle in the mode row"}; + } + const header = document.getElementById("bubbles-toggle"); + const row = toggle.closest(".radio-mode-row"); + const modes = row.querySelector(".radio-modes"); + const stored = async () => (await (await fetch("/api/state", {cache: "no-store"})).json()).settings.bubbles; + const mode = () => all("#radio-spot .radio-modes button[aria-pressed='true']").map((button) => button.dataset.mode); + const look = async () => ({radio: toggle.getAttribute("aria-pressed"), header: header.getAttribute("aria-pressed"), stored: await stored(), mode: mode()}); + const flip = async (button, want) => { + button.click(); + await until(() => toggle.getAttribute("aria-pressed") === want && header.getAttribute("aria-pressed") === want, 8000); + const end = Date.now() + 8000; + while (Date.now() < end && String(await stored()) !== want) { + await sleep(200); + } + return look(); + }; + const divider = row.querySelector(".mode-divider"); + const [lane, bar, switcher] = [modes, divider, toggle].map((node) => node.getBoundingClientRect()); + const layout = { + order: [...row.children].map((node) => node.className), + divider: [Math.round(bar.width), bar.height > 0, getComputedStyle(divider).backgroundColor !== "rgba(0, 0, 0, 0)"], + sameLine: switcher.top < lane.bottom && switcher.bottom > lane.top, + after: bar.left >= lane.right - 1 || bar.top >= lane.bottom - 1, + named: [toggle.getAttribute("aria-label"), Boolean(toggle.title), toggle.getAttribute("aria-controls")], + inModes: Boolean(modes.querySelector(".radio-bubbles")), + }; + const before = await look(); + const want = before.radio === "true" ? "false" : "true"; + const flipped = await flip(toggle, want); + const back = await flip(header, before.radio); + return {layout, before, flipped, back, wide: document.documentElement.scrollWidth > innerWidth + 1}; +})()""" + + +@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium") +class TestBubblesModeRow(HubCase): + drive = base.OrchestratorE2ECase.drive + authenticator = base.OrchestratorE2ECase.authenticator + + def setUp(self): + super().setUp() + OUT.mkdir(parents=True, exist_ok=True) + self.claim("s1", "Skills session") + self.create_ask({**ASK, "timeout": 3600}) + + def test_chromium_switches_bubbles_from_the_mode_row_and_the_header_toggle_follows_at_three_widths(self): + authenticator = self.authenticator() + for width, height in base.WIDTHS: + with self.subTest(width=width): + probe = PROBE.replace("@HELPERS@", base.HELPERS) + data = self.drive([{"width": width, "height": height, "url": f"http://{self.host}/?{width}#stream", "wait": 1200, "probe": probe, "shot": str(OUT / f"chromium-{width}-bubbles-row.png")}], authenticator) + (OUT / f"chromium-{width}-bubbles-row.json").write_text(json.dumps(data, indent=1), encoding="utf-8") + self.assertEqual(data["errors"], []) + found = data["results"][0] + self.assertNotIn("error", found, found) + layout = found["layout"] + self.assertEqual(layout["order"][1:], ["mode-divider", "btn small ghost icon-only radio-bubbles"]) + self.assertIn("radio-modes", layout["order"][0]) + self.assertEqual((layout["divider"], layout["after"], layout["inModes"]), ([1, True, True], True, False), layout) + self.assertEqual(layout["named"], ["Speech bubbles", True, "bubbles"]) + if width >= 1024: + self.assertTrue(layout["sameLine"], layout) + before, flipped, back = found["before"], found["flipped"], found["back"] + self.assertEqual((before["radio"], before["stored"]), (before["header"], before["radio"] == "true"), before) + self.assertEqual((flipped["radio"], flipped["header"], flipped["stored"]), (str(not before["stored"]).lower(), str(not before["stored"]).lower(), not before["stored"]), flipped) + self.assertEqual((back["radio"], back["header"], back["stored"]), (before["radio"], before["radio"], before["stored"]), back) + self.assertEqual((flipped["mode"], back["mode"]), (before["mode"], before["mode"])) + self.assertEqual(len(before["mode"]), 1) + self.assertFalse(found["wide"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/e2e/test_bulk_grant_e2e.py b/tests/e2e/test_bulk_grant_e2e.py index 6bba6b2..3158ba0 100644 --- a/tests/e2e/test_bulk_grant_e2e.py +++ b/tests/e2e/test_bulk_grant_e2e.py @@ -33,7 +33,7 @@ COMMON = """ await until(() => menu().open, 2000); await sleep(100); }; - const grantOf = (ref) => row(ref) && (row(ref).querySelector(".item-actions button.primary") || all(".options.dialog > button.option", row(ref)).find((button) => text(button.querySelector("strong")) === "Yes")); + const grantOf = (ref) => row(ref) && (row(ref).querySelector(":is(.item-actions, .code-foot) button.primary") || all(".options.dialog > button.option", row(ref)).find((button) => text(button.querySelector("strong")) === "Yes")); const wide = () => document.documentElement.scrollWidth > innerWidth + 1; const switchState = () => [name(main()), count(), document.querySelector("#grant-bar #grant-direct") ? "select" : "direct"]; const storedMode = async (mode) => { @@ -248,9 +248,9 @@ class TestBulkGrant(base.OrchestratorE2ECase): self.assertEqual((mode["before"], mode["kept"], mode["after"]), (["Select", "0 selected", "direct"], True, selecting), mode) self.assertNotIn("error", collect, collect) self.assertEqual(collect["restored"], selecting, collect) - self.assertEqual(collect["pale"], [True, True], collect) + self.assertEqual(collect["pale"], [False, True], collect) self.assertEqual(collect["counts"], ["1 selected", "2 selected", "1 selected", "2 selected", "3 selected"], collect) - self.assertEqual((collect["pressed"], collect["posted"]), ([["true", True], ["true", True], ["true", True]], []), collect) + self.assertEqual((collect["pressed"], collect["posted"]), ([["true", False], ["true", False], ["true", False]], []), collect) self.assertEqual((collect["labels"][0], collect["labels"][-1]), ("Grant selection (3)", "Direct"), collect) self.assertEqual(sum(label.startswith("Remove ") for label in collect["labels"]), 3, collect) self.assertEqual((sheet["label"], len(sheet["listed"])), ("Grant 3", 3), sheet) diff --git a/tests/e2e/test_deny_reason_chips_e2e.py b/tests/e2e/test_deny_reason_chips_e2e.py index e51bc40..0f8928b 100644 --- a/tests/e2e/test_deny_reason_chips_e2e.py +++ b/tests/e2e/test_deny_reason_chips_e2e.py @@ -46,10 +46,7 @@ INBOX = """(async () => {@HELPERS@@COMMON@ } const single = await pick(1, sheet().querySelector(".deny-reason textarea")); const menu = () => document.querySelector("#grant-bar details.grant-menu"); - const checkbox = row("@ASK@").querySelector('input[type="checkbox"]'); - if (checkbox && !checkbox.checked) { - checkbox.click(); - } + await selectRow(row("@ASK@").dataset.ref); if (!(await until(() => menu(), 3000))) { return {single, error: "no selection menu"}; } diff --git a/tests/e2e/test_done_rows_e2e.py b/tests/e2e/test_done_rows_e2e.py new file mode 100644 index 0000000..10106bf --- /dev/null +++ b/tests/e2e/test_done_rows_e2e.py @@ -0,0 +1,88 @@ +from __future__ import annotations + +import json +import os +import shutil +import sys +import time +import unittest +from pathlib import Path +from unittest import mock + +HERE = Path(__file__).resolve().parent +sys.path[:0] = [str(HERE.parent), str(HERE)] + +import hub_e2e_kit as base +from hub_support import ASK +from kvb_orchestrator import batches + +OUT = Path(os.environ.get("E2E_OUT", "/tmp/hub-048-shots")) +DONE = """(async () => {@HELPERS@ + const row = (ref) => document.querySelector(`#main .inbox-list > li[data-ref="${ref}"]`); + if (!(await until(() => row("@OPEN@") && document.querySelector("#main details.inbox-done"), 8000))) { + return {error: text(document.getElementById("main")).slice(0, 300)}; + } + const fold = document.querySelector("#main details.inbox-done"); + const done = all(".inbox-list > li", fold).map((li) => ({ref: li.dataset.ref, done: li.hasAttribute("data-done"), pill: all(".msg-meta .pill", li).map(text).includes("done"), opacity: Number(getComputedStyle(li).opacity)})); + const shown = {open: fold.open, summary: text(fold.querySelector("summary")), last: fold === document.querySelector("#main .inbox").lastElementChild, done, + boxes: all('#main .inbox-list .item input[type="checkbox"]').length}; + await ViewStore.set("approval.mode", "select"); + await until(() => row("@OPEN@") && row("@OPEN@").hasAttribute("aria-selected"), 10000); + const check = () => row("@OPEN@").querySelector("[aria-pressed]"); + const state = () => [row("@OPEN@").getAttribute("aria-selected"), check() ? check().getAttribute("aria-pressed") : null]; + const before = state(); + check().click(); + await until(() => state()[0] === "true", 3000); + const picked = state(); + check().click(); + await until(() => state()[0] === "false", 3000); + const cleared = state(); + await cursorTo("@OPEN@"); + await pressKey("x"); + await until(() => state()[0] === "true", 3000); + const keyed = state(); + await pressKey("x"); + await until(() => state()[0] === "false", 3000); + await ViewStore.set("approval.mode", "direct"); + fold.scrollIntoView({block: "center"}); + return {...shown, before, picked, cleared, keyed, wide: document.documentElement.scrollWidth > innerWidth + 1}; +})()""" + + +@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium") +class TestDoneRows(base.OrchestratorE2ECase): + def setUp(self): + super().setUp() + OUT.mkdir(parents=True, exist_ok=True) + now = time.time() + greet = {"title": "echo greet", "workdir": str(self.outside), "description": "greets", "check": "manual", "status": "queued", "roles": {"Operator": "R", "Skills session": "A"}} + self.write_council({"rasci.json": {"operator/greet": greet}}) + fields = {"task": "operator/greet", "command": "echo greet", "directory": str(self.outside), "sha256": "", "status": "done", "proof": None} + self.httpd.hub.jobs.add({**fields, "code": 0, "output": "greet\n", "created_ts": now - 20, "started": now - 19, "finished": now - 10, "dismissed": False}) + self.open = f"ask:{self.create_ask({**ASK, 'command': 'make open', 'timeout': 3600})}" + held = self.create_ask({**ASK, "command": "make held", "timeout": 3600}) + self.held = f"ask:{held}" + entries = [self.entry("ask", held, "", "")] + with mock.patch.object(batches, "UNDO", 120): + self.assertEqual(self.approve(entries, self.signed(entries, self.pin()))[0], 202) + self.base = f"http://{self.host}/" + + def test_chromium_folds_held_and_ended_rows_under_done_and_selects_by_the_green_check_without_a_checkbox_at_1920_and_390(self): + probe = DONE.replace("@HELPERS@", base.HELPERS).replace("@OPEN@", self.open) + steps = [{"width": width, "height": height, "url": f"{self.base}?{width}#tasks/operator", "wait": 1500, "probe": probe, "shot": str(OUT / f"chromium-{width}-done-rows.png")} for width, height in ((1920, 1080), (390, 844))] + data = self.drive(steps, None) + (OUT / "chromium-done-rows.json").write_text(json.dumps(data, indent=1), encoding="utf-8") + self.assertEqual([error for error in data["errors"] if "/favicon.ico" not in error], []) + for (width, _), found in zip(((1920, 1080), (390, 844)), data["results"], strict=True): + with self.subTest(width=width): + self.assertNotIn("error", found, found) + self.assertEqual((found["open"], found["summary"], found["last"], found["boxes"], found["wide"]), (False, "Done (2)", True, 0, False), found) + self.assertEqual(sorted(row["ref"] for row in found["done"]), sorted([self.held, "operator:operator/greet"]), found) + for row in found["done"]: + self.assertTrue(row["done"] and row["pill"], row) + self.assertLessEqual(row["opacity"], 0.5, row) + self.assertEqual((found["before"], found["picked"], found["cleared"], found["keyed"]), (["false", "false"], ["true", "true"], ["false", "false"], ["true", "true"]), found) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/e2e/test_firewall_e2e.py b/tests/e2e/test_firewall_e2e.py index a294624..2a8f684 100644 --- a/tests/e2e/test_firewall_e2e.py +++ b/tests/e2e/test_firewall_e2e.py @@ -30,7 +30,7 @@ SHOW = """(async () => {@HELPERS@ if (!ready) { return {error: text(document.getElementById("main"))}; } - const owned = (svg) => svg.closest("button, a, [title]"); + const owned = (svg) => svg.closest("button, a, label, [title]"); const rows = () => all("#main table.fw-table tr[data-filter]"); const chip = (id) => document.querySelector(`#main [aria-label="Show rules"] button[data-filter="${id}"]`); const sources = all("#main tbody[data-source]").map((node) => node.dataset.source); @@ -290,7 +290,7 @@ class TestFirewallE2E(HubCase): with self.subTest(width=width): self.assertNotIn("error", shown, shown) self.assertEqual((shown["title"], shown["subs"]), ("Controls", base.SUBS)) - self.assertEqual(shown["tabs"], {"first": [["tools", "true", False], ["rules", "false", True], ["groups", "false", True]], "picked": [["tools", "false", True], ["rules", "true", False], ["groups", "false", True]]}) + self.assertEqual(shown["tabs"], {"first": [["tools", "true", False], ["rules", "false", True], ["groups", "false", True], ["schedules", "false", True]], "picked": [["tools", "false", True], ["rules", "true", False], ["groups", "false", True], ["schedules", "false", True]]}) self.assertEqual(shown["sources"], ["hub", str(self.settings)]) self.assertEqual(shown["folded"], {"expanded": ["false"] * 2, "rows": 0}) self.assertEqual(shown["opened"], ["true"] * 2) diff --git a/tests/e2e/test_home_bookmarks_e2e.py b/tests/e2e/test_home_bookmarks_e2e.py index 663989e..8ff0a75 100644 --- a/tests/e2e/test_home_bookmarks_e2e.py +++ b/tests/e2e/test_home_bookmarks_e2e.py @@ -40,7 +40,7 @@ LONG_NAME = "/".join(Path(LONG_REPO).parts[-3:]) LONG_ROWS = ("repo", "worktree", "core", "leaf") READ = res.READ.replace("const stored = async", "const storedResources = async").replace("await stored()", "await storedResources()") KIT = """ - const stars = (selector) => all(selector).map((owner) => Boolean(ownStar(owner))); + const pinnable = (selector) => all(selector).map((owner) => Boolean(Panels.targetOf(owner))); const panel = (kind) => `#main [data-panel="resources-${kind}"]`; const lineIds = (root) => [...new Set(all("path.res-line", root).map((path) => path.dataset.id))]; const tileOf = (kind) => all("#main .home-tile").find((node) => node.dataset.pin.startsWith(`metric:${kind}/`)) || null; @@ -73,21 +73,20 @@ LOADED = """(async () => {@HELPERS@@READ@ FOUND = """(async () => {@HELPERS@@HOME@@KIT@ const found = {}; await go("resources"); - found.charts = stars('#main section.res-panel[data-panel^="resources-"]'); - found.chips = all("#main .legend-chip .star").length; - found.inHead = all("#main .res-panel .star").every((star) => star.parentElement.classList.contains("res-head")); + found.charts = pinnable('#main section.res-panel[data-panel^="resources-"]'); + found.stars = all(".star, .star-row").length; await go("artifacts/tree"); await until(() => kept(), 8000); - found.tree = stars('#main [data-panel="artifacts/tree"]'); - found.rows = Object.fromEntries(["repo", "branch", "wt"].map((kind) => [kind, stars(`#main [data-item^="artifact:${kind}:"]`)])); + found.tree = pinnable('#main [data-panel="artifacts/tree"]'); + found.rows = Object.fromEntries(["repo", "branch", "wt"].map((kind) => [kind, pinnable(`#main [data-item^="artifact:${kind}:"]`)])); await until(() => Object.values(longRows).every((find) => find()), 8000); found.long = Object.fromEntries(Object.entries(longRows).map(([key, find]) => [key, find() ? find().dataset.item.length : null])); - found.disabled = all('#main [data-item^="artifact:"]').filter((node) => !ownStar(node) || ownStar(node).disabled).map((node) => node.dataset.item.slice(0, 80)); + found.disabled = all('#main [data-item^="artifact:"]').filter((node) => !Panels.targetOf(node) || Panels.targetOf(node).refused).map((node) => node.dataset.item.slice(0, 80)); found.deletes = all('#main button[aria-label="Delete"]').length; await go("agents/hierarchy"); - found.order = stars('#main [data-panel="agents/order"]'); + found.order = pinnable('#main [data-panel="agents/order"]'); await go("tasks/operator"); - found.operator = stars('#main [data-panel="tasks/operator"]'); + found.operator = pinnable('#main [data-panel="tasks/operator"]'); return found; })()""" METRIC = """(async () => {@HELPERS@@HOME@@READ@@KIT@ @@ -103,7 +102,7 @@ METRIC = """(async () => {@HELPERS@@HOME@@READ@@KIT@ } const cpuOnly = Boolean(await until(() => lineIds(document.querySelector(panel("hardware"))).join() === "@CPU@", 5000)); const hardware = await press(panel("hardware")); - const cpuTitle = starOf(panel("hardware")).getAttribute("title"); + const cpuTitle = (await pinState(panel("hardware")))[1]; const tokens = await press(panel("tokens")); for (const id of others) { chip(id).click(); @@ -111,7 +110,7 @@ METRIC = """(async () => {@HELPERS@@HOME@@READ@@KIT@ } const back = Boolean(await until(() => lineIds(document.querySelector(panel("hardware"))).length === @COUNT@, 5000)); await sleep(200); - const allState = [starOf(panel("hardware")).getAttribute("aria-pressed"), starOf(panel("hardware")).getAttribute("title")]; + const allState = await pinState(panel("hardware")); await pickPanel("combined", true); await pickPanel("hardware", false); await pickPanel("tokens", false); @@ -127,7 +126,7 @@ COMBINED_OFF = """(async () => {@HELPERS@@HOME@@READ@@KIT@ await pickPanel("combined", false); const off = Boolean(await until(() => charts().length === 2 && lines().length === @COUNT@, 8000)); await sleep(300); - return {off, hardware: [starOf(panel("hardware")).getAttribute("aria-pressed"), starOf(panel("hardware")).getAttribute("title")]}; + return {off, hardware: await pinState(panel("hardware"))}; })()""" HOME_METRICS = """(async () => {@HELPERS@@HOME@@KIT@ await go("home"); @@ -166,12 +165,7 @@ PM = """(async () => {@HELPERS@@HOME@@KIT@ const row = await until(() => kept(), 8000); row.closest("details").open = true; const tree = await press('#main [data-panel="artifacts/tree"]'); - const rowStar = row ? ownStar(row) : null; - if (rowStar) { - rowStar.click(); - await sleep(200); - } - const branch = rowStar ? (ownStar(kept()) || rowStar).getAttribute("aria-pressed") : null; + const branch = row ? await pinOwner(kept() || row) : null; await go("agents/hierarchy"); const order = await press('#main [data-panel="agents/order"]'); await go("tasks/operator"); @@ -210,14 +204,9 @@ LONG = """(async () => {@HELPERS@@HOME@@KIT@ const pressed = {}; const keys = {}; for (const [key, find] of Object.entries(longRows)) { - const star = ownStar(find()); keys[key] = pinKey(find()); - pressed[key] = star ? [star.disabled, star.title.startsWith("Pin to Home: Artifact ")] : null; - if (star && !star.disabled) { - star.click(); - await sleep(200); - } - pressed[key].push(ownStar(longRows[key]()).getAttribute("aria-pressed")); + const before = await menuPinOf(find()); + pressed[key] = before ? [before[1].startsWith("Pin to Home: Artifact "), await pinOwner(find())] : null; } await go("home"); await settled(); @@ -365,10 +354,10 @@ class TestHomeBookmarks(HubCase): {"width": width, "height": height, "url": f"{page}-clear#stream", "wait": 600, "probe": CLEAR, "shot": None}, {"width": width, "height": height, "url": f"{page}-loaded#resources", "wait": 1200, "probe": probe(LOADED), "shot": None}, {"width": width, "height": height, "url": None, "wait": 0, "probe": probe(FOUND), "shot": None}, - {"width": width, "height": height, "url": None, "wait": 0, "probe": probe(dash.STARS), "shot": None}, - {"width": width, "height": height, "url": None, "wait": 0, "probe": probe(METRIC), "shot": f"{shot}-combined-star.png"}, - {"width": width, "height": height, "url": None, "wait": 0, "probe": probe(dash.STARS, ["resources"]), "shot": None}, - {"width": width, "height": height, "url": None, "wait": 0, "probe": probe(COMBINED_OFF), "shot": f"{shot}-metric-star.png"}, + {"width": width, "height": height, "url": None, "wait": 0, "probe": probe(dash.OWNERS), "shot": None}, + {"width": width, "height": height, "url": None, "wait": 0, "probe": probe(METRIC), "shot": f"{shot}-combined-pin.png"}, + {"width": width, "height": height, "url": None, "wait": 0, "probe": probe(dash.OWNERS, ["resources"]), "shot": None}, + {"width": width, "height": height, "url": None, "wait": 0, "probe": probe(COMBINED_OFF), "shot": f"{shot}-metric-pin.png"}, {"width": width, "height": height, "url": None, "wait": 0, "probe": probe(HOME_METRICS), "shot": f"{shot}-home-metrics.png"}, {"width": width, "height": height, "url": f"{page}-reloaded#home", "wait": 1500, "probe": probe(RELOADED), "shot": None}, {"width": width, "height": height, "url": None, "wait": 0, "probe": probe(PM), "shot": f"{shot}-home-bookmarks.png"}, @@ -388,7 +377,7 @@ class TestHomeBookmarks(HubCase): loaded = next(results) self.assertTrue(loaded["drawn"], loaded) found = next(results) - self.assertEqual((found["charts"], found["chips"], found["inHead"]), ([True] * 4, 0, True), found) + self.assertEqual((found["charts"], found["stars"]), ([True] * 4, 0), found) self.assertEqual(found["tree"], [True], found) self.assertTrue(found["rows"]["repo"] and all(found["rows"]["repo"]), found) self.assertTrue(found["rows"]["branch"] and all(found["rows"]["branch"]), found) @@ -399,7 +388,7 @@ class TestHomeBookmarks(HubCase): self.assertEqual(found["disabled"], [], found) self.assertGreaterEqual(found["deletes"], 1, found) walked = next(results) - self.assertEqual((walked["missing"], walked["covered"]), ([], []), walked) + self.assertEqual((walked["missing"], walked["stars"]), ([], []), walked) metric = next(results) self.assertNotIn("error", metric, metric) self.assertEqual((metric["cpuOnly"], metric["hardware"], metric["tokens"], metric["back"], metric["combinedOn"], metric["combined"]), (True, "true", "true", True, True, "true"), metric) @@ -415,7 +404,7 @@ class TestHomeBookmarks(HubCase): self.assertRegex(metric["stored"][0][1], r"^hardware/[0-9a-f]{16}$") self.assertEqual([key for _, key, _ in metric["stored"][1:]], ["tokens/interval/all", "combined/interval/all"]) combined_walk = next(results) - self.assertEqual((combined_walk["missing"], combined_walk["covered"]), ([], []), combined_walk) + self.assertEqual((combined_walk["missing"], combined_walk["stars"]), ([], []), combined_walk) self.assertEqual(next(results), {"off": True, "hardware": ["false", "Pin to Home: Hardware: all series"]}) home = next(results) self.assertEqual(home["errors"], [], home) @@ -453,7 +442,7 @@ class TestHomeBookmarks(HubCase): def check_long(self, long: dict) -> None: self.assertEqual(long["errors"], [], long) - self.assertEqual(long["pressed"], {key: [False, True, "true"] for key in LONG_ROWS}, long) + self.assertEqual(long["pressed"], {key: [True, "true"] for key in LONG_ROWS}, long) self.assertEqual([key for key in long["stored"] if key in long["keys"].values()], list(long["keys"].values()), long) for key in ("core", "leaf"): self.assertRegex(long["keys"][key], r"^artifact:(wt|artefact)_23_[0-9a-f]{16}$", long) diff --git a/tests/e2e/test_home_dashboard_e2e.py b/tests/e2e/test_home_dashboard_e2e.py index 98e169c..14ead29 100644 --- a/tests/e2e/test_home_dashboard_e2e.py +++ b/tests/e2e/test_home_dashboard_e2e.py @@ -20,6 +20,7 @@ from hub_support import HUB, iso OUT = Path(os.environ.get("E2E_OUT", "/tmp/hub-008-shots")) REAL_STORE = (HUB / "templates" / "view-store.js").exists() CUE = "e2e-home-change" +PIN_LABELS = ("Pin to Home", "Unpin from Home") SCREENS = [ "stream", "agents/orbit", "agents/chord", "agents/swimlane", "agents/3d", "agents/tree", "agents/hierarchy", "artifacts/orbit", "artifacts/chord", "artifacts/swimlane", "artifacts/tree", "artifacts/3d", @@ -52,19 +53,48 @@ HOME = """ await screenShown(8000); await sleep(500); }; - const ownStar = (owner) => [...owner.querySelectorAll(".star")].find((node) => node.closest("[data-panel], [data-item]") === owner) || null; - const starOf = (selector) => { - const owner = document.querySelector(selector); - return owner ? ownStar(owner) : null; + const PIN_LABELS = ["Pin to Home", "Unpin from Home"]; + const shownMenu = () => document.querySelector(".ctx-menu:not([hidden])"); + const menuLabel = (node) => text(node.querySelector(".ctx-label")); + const closeMenu = async () => { + const menu = shownMenu(); + if (menu) { + menu.dispatchEvent(new KeyboardEvent("keydown", {key: "Escape", bubbles: true, cancelable: true})); + await sleep(100); + } }; - const press = async (selector) => { - const button = await until(() => starOf(selector), 8000); - if (!button) { + const pinItem = async (owner) => { + await closeMenu(); + owner.scrollIntoView({block: "center"}); + const box = owner.getBoundingClientRect(); + owner.dispatchEvent(new MouseEvent("contextmenu", {bubbles: true, cancelable: true, button: 2, clientX: Math.round(box.left + 4), clientY: Math.round(box.top + 4)})); + const menu = await until(shownMenu, 3000); + return menu ? all('[role="group"][data-scope="element"] [role="menuitem"]', menu).find((node) => PIN_LABELS.includes(menuLabel(node))) || null : null; + }; + const menuPinOf = async (owner) => { + const item = await pinItem(owner); + const state = item ? [String(menuLabel(item) === PIN_LABELS[1]), `${menuLabel(item)}: ${item.title}`] : null; + await closeMenu(); + return state; + }; + const pinState = async (selector) => { + const owner = await until(() => document.querySelector(selector), 8000); + return owner ? menuPinOf(owner) : null; + }; + const pinOwner = async (owner) => { + const target = Panels.targetOf(owner); + const item = await pinItem(owner); + if (!item) { + await closeMenu(); return null; } - button.click(); + item.click(); await sleep(200); - return button.getAttribute("aria-pressed"); + return String((ViewStore.get("home.pins") || []).some((pin) => pin.kind === target.kind && pin.id === target.id)); + }; + const press = async (selector) => { + const owner = await until(() => document.querySelector(selector), 8000); + return owner ? pinOwner(owner) : null; }; const tiles = () => all("#main .home-tile").map((tile) => tile.dataset.pin); const tile = (key) => document.querySelector(`#main .home-tile[data-pin="${key}"]`); @@ -103,71 +133,41 @@ START_EMPTY = """(async () => {@HELPERS@ await screenShown(8000); return {hash: location.hash, screen: document.getElementById("main").getAttribute("aria-labelledby"), first: name(document.querySelector("#tabs > .tab-group > button"))}; })()""" -STARS = """(async () => {@HELPERS@@HOME@ +OWNERS = """(async () => {@HELPERS@@HOME@ const seen = []; const missing = []; - const covered = []; - const CONTROLS = 'button, a[href], input, select, textarea, summary, [role="button"], [role="tab"], [tabindex]:not([tabindex="-1"])'; - const shown = (node) => node.getClientRects().length > 0 && getComputedStyle(node).visibility !== "hidden" && !node.closest("details:not([open]) > :not(summary)"); - const overlap = (a, b) => Math.max(0, Math.min(a.right, b.right) - Math.max(a.left, b.left)) * Math.max(0, Math.min(a.bottom, b.bottom) - Math.max(a.top, b.top)); + const stars = []; + const menus = []; const XHTML = "http://www.w3.org/1999/xhtml"; - const clipped = (node) => { - const box = node.getBoundingClientRect(); - const drawn = {left: box.left, top: box.top, right: box.right, bottom: box.bottom}; - let position = getComputedStyle(node).position; - for (let at = node.parentElement; at && at !== document.body && position !== "fixed"; at = at.parentElement) { - const look = getComputedStyle(at); - if (at.namespaceURI !== XHTML || ["inline", "contents"].includes(look.display) || (position === "absolute" && look.position === "static")) { - continue; - } - position = look.position; - const edge = at.getBoundingClientRect(); - const left = edge.left + at.clientLeft; - const top = edge.top + at.clientTop; - if (look.overflowX !== "visible") { - drawn.left = Math.max(drawn.left, left); - drawn.right = Math.min(drawn.right, left + at.clientWidth); - } - if (look.overflowY !== "visible") { - drawn.top = Math.max(drawn.top, top); - drawn.bottom = Math.min(drawn.bottom, top + at.clientHeight); - } - } - return drawn; - }; - const layer = (node) => node.closest("dialog[open]"); - const count = (where) => { + const shown = (node) => node.getClientRects().length > 0 && getComputedStyle(node).visibility !== "hidden" && !node.closest("details:not([open]) > :not(summary)"); + const count = async (where) => { const owners = all("[data-panel], [data-item]").filter((node) => node.namespaceURI === XHTML); seen.push([where, owners.length]); - missing.push(...owners.filter((node) => !ownStar(node)).map((node) => `${where}: ${node.outerHTML.slice(0, 120)}`)); - const controls = all(CONTROLS).filter(shown); - for (const star of all(".star").filter(shown)) { - const box = clipped(star); - for (const other of controls) { - if (other !== star && !other.contains(star) && !star.contains(other) && layer(other) === layer(star) && overlap(box, clipped(other)) > 1) { - covered.push(`${where}: ${star.title} over ${other.outerHTML.slice(0, 100)}`); - } - } - } + missing.push(...owners.filter((node) => !Panels.targetOf(node)).map((node) => `${where}: ${node.outerHTML.slice(0, 120)}`)); + stars.push(...all(".star, .star-row").map((node) => `${where}: ${node.outerHTML.slice(0, 120)}`)); + const first = owners.filter(shown).find((node) => node.closest("dialog[open]")) || owners.find(shown) || owners[0]; + const item = first ? await pinItem(first) : null; + menus.push([where, item ? menuLabel(item) : null]); + await closeMenu(); }; for (const hash of @SCREENS@) { await go(hash); await sleep(hash.endsWith("3d") || hash.startsWith("artifacts") ? 1500 : 300); - count(hash); + await count(hash); } await go("agents/orbit"); const agent = document.querySelector('#main svg .node.k-session[data-pick]'); if (agent) { agent.dispatchEvent(new MouseEvent("click", {bubbles: true})); await until(() => document.querySelector('#popup[open] [data-item^="agent:"]'), 5000); - count("agent card"); + await count("agent card"); document.getElementById("popup").close(); } document.getElementById("radio-open").click(); await until(() => document.querySelector('[data-panel="radio-log"]'), 5000); - count("radio spot"); + await count("radio spot"); document.getElementById("radio-open").click(); - return {seen, missing, covered, total: seen.reduce((sum, [, size]) => sum + size, 0)}; + return {seen, missing, stars, menus, total: seen.reduce((sum, [, size]) => sum + size, 0)}; })()""" PIN = """(async () => {@HELPERS@@HOME@ await go("tasks/gantt"); @@ -322,7 +322,7 @@ class TestHomeDashboard(HubCase): steps += [ {"width": width, "height": height, "url": f"{page}-clear#stream", "wait": 600, "probe": CLEAR, "shot": None}, {"width": width, "height": height, "url": f"{page}-empty", "wait": 1500, "probe": probe(START_EMPTY), "shot": f"{shot}-start-empty.png"}, - {"width": width, "height": height, "url": None, "wait": 0, "probe": probe(STARS), "shot": f"{shot}-stars.png"}, + {"width": width, "height": height, "url": None, "wait": 0, "probe": probe(OWNERS), "shot": f"{shot}-owners.png"}, {"width": width, "height": height, "url": f"{page}-pin#stream", "wait": 1200, "probe": probe(PIN), "shot": f"{shot}-pinned.png"}, {"width": width, "height": height, "url": None, "wait": 0, "probe": probe(RESIZE), "shot": f"{shot}-resized.png"}, {"width": width, "height": height, "url": None, "wait": 0, "probe": probe(REORDER), "shot": f"{shot}-reordered.png"}, @@ -347,10 +347,10 @@ class TestHomeDashboard(HubCase): next(results) empty = next(results) self.assertEqual((empty["hash"], empty["screen"], empty["first"]), ("", "tab-stream", "Home"), empty) - stars = next(results) - self.assertEqual(stars["missing"], [], stars) - self.assertEqual(stars["covered"], [], stars) - self.assertGreater(stars["total"], 20, stars) + owners = next(results) + self.assertEqual((owners["missing"], owners["stars"]), ([], []), owners) + self.assertEqual([where for where, label in owners["menus"] if label not in PIN_LABELS], [where for where, size in owners["seen"] if not size], owners) + self.assertGreater(owners["total"], 20, owners) pinned = next(results) self.assertEqual((pinned["gantt"], pinned["feature"], pinned["docs"], pinned["streamed"], pinned["chart"], pinned["off"], pinned["again"]), ("true", "true", "true", "true", True, "false", "true"), pinned) self.assertEqual(pinned["pinned"], ["panel:tasks/gantt", "task:work/feature", "task:work/docs", "panel:stream"]) @@ -397,14 +397,14 @@ class TestHomeDashboard(HubCase): def init(self) -> str | None: return None if REAL_STORE else STUB - def test_chromium_stars_pins_resizes_reorders_and_marks_gone_tiles_at_three_widths(self): + def test_chromium_pins_by_menu_resizes_reorders_and_marks_gone_tiles_at_three_widths(self): data = self.drive(self.steps("chromium"), None, init=self.init()) (OUT / "chromium-home.json").write_text(json.dumps(data, indent=1), encoding="utf-8") self.assertEqual(data["errors"], []) self.check(data) @unittest.skipUnless(shutil.which(os.environ.get("FIREFOX", "firefox")), "no Firefox") - def test_firefox_stars_pins_resizes_reorders_and_marks_gone_tiles_at_three_widths(self): + def test_firefox_pins_by_menu_resizes_reorders_and_marks_gone_tiles_at_three_widths(self): data = self.drive(self.steps("firefox"), None, "bidi.mjs", os.environ.get("FIREFOX", "firefox"), init=self.init()) (OUT / "firefox-home.json").write_text(json.dumps(data, indent=1), encoding="utf-8") self.assertEqual([error for error in data["errors"] if "/favicon.ico" not in error], []) @@ -412,7 +412,7 @@ class TestHomeDashboard(HubCase): @unittest.skipUnless(REAL_STORE, "waits on 007: view-store.js and /api/view are not on this branch yet") def test_a_second_browser_shows_the_same_layout(self): - first = self.drive([step for step in self.steps("chromium")[:6] if step["probe"] != probe(STARS)], None) + first = self.drive([step for step in self.steps("chromium")[:6] if step["probe"] != probe(OWNERS)], None) second = self.drive([{"width": 1366, "height": 768, "url": f"{self.base}?second", "wait": 2000, "probe": probe(RELOADED), "shot": str(OUT / "chromium-second.png")}], None) self.assertEqual(second["results"][0]["tiles"], first["results"][-1]["down"]) self.assertEqual((second["results"][0]["hash"], second["results"][0]["screen"]), ("#home", "tab-home")) diff --git a/tests/e2e/test_home_flat_widgets_e2e.py b/tests/e2e/test_home_flat_widgets_e2e.py new file mode 100644 index 0000000..ff96e1c --- /dev/null +++ b/tests/e2e/test_home_flat_widgets_e2e.py @@ -0,0 +1,147 @@ +from __future__ import annotations + +import json +import os +import shutil +import sys +import time +import unittest +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path[:0] = [str(HERE.parent), str(HERE)] + +import hub_e2e_kit as base +import test_home_bookmarks_e2e as bm +import test_home_tile_open_e2e as opened +import test_workbench_w4_e2e as w4 +from hub_case import HubCase + +OUT = Path(os.environ.get("E2E_OUT", "/tmp/hub-044-shots")) +PANELS = [ + "stream", "radio-log", "radio", "radio-device", "radio-speak", "agents/orbit", "agents/chord", "agents/swimlane", "agents/3d", "agents/tree", "agents/hierarchy", + "artifacts/orbit", "artifacts/chord", "artifacts/swimlane", "artifacts/3d", "artifacts/tree", "tasks/list", "tasks/board", "tasks/rasci", "tasks/gantt", "tasks/burn", + "tasks/3d", "tasks/operator", "tasks/match", "agents/order", "resources-accounts", +] +NAMED = {"panel:radio-log": "radio-card", "panel:radio-device": "radio-card", "panel:radio-speak": "radio-card", "panel:tasks/gantt": "gantt-scroll"} +FLAT = """(async () => {@HELPERS@@HOME@@KIT@ + await go("home"); + await until(() => !all("#main .home-tile .empty h2").some((title) => text(title).endsWith("…")), 8000); + await sleep(1200); + const boxed = (node) => { + const look = getComputedStyle(node); + return parseFloat(look.borderTopWidth) > 0 || look.backgroundColor !== "rgba(0, 0, 0, 0)" || look.backgroundImage !== "none"; + }; + const area = (node) => node.offsetWidth * node.offsetHeight; + const left = (body) => { + for (let node = body.firstElementChild; node;) { + if (node.classList.contains("home-flat")) { + return null; + } + if (boxed(node)) { + return node.className; + } + const biggest = [...node.children].reduce((best, child) => (!best || area(child) > area(best) ? child : best), null); + node = biggest && area(biggest) >= 0.75 * area(node) ? biggest : null; + } + return null; + }; + const found = all("#main .home-tile").map((node) => { + const body = node.querySelector(".home-body"); + const flat = body.querySelector(".home-flat"); + const look = flat ? getComputedStyle(flat) : null; + const pad = parseFloat(getComputedStyle(body).paddingBottom); + const tail = []; + for (let node = flat; node; node = node.nextElementSibling) { + tail.push(node.getBoundingClientRect().bottom); + } + const gap = flat ? body.getBoundingClientRect().top + body.clientTop + body.clientHeight - pad - Math.max(...tail) : null; + const heading = flat ? flat.querySelector(":scope > .radio-card-head > .group-title") : null; + return { + key: node.dataset.pin, flat: flat ? [...flat.classList].filter((name) => name !== "home-flat") : null, boxLeft: left(body), + border: look ? look.borderTopWidth : null, background: look ? look.backgroundColor : null, gap: gap === null ? null : Math.round(gap * 10) / 10, + heading: heading ? heading.getClientRects().length > 0 : null, + }; + }); + return {tiles: found, wide: document.documentElement.scrollWidth > innerWidth + 1}; +})()""" +FULL = """(async () => {@HELPERS@@HOME@ + await go("tasks/gantt"); + const gantt = await until(() => document.querySelector("#main .gantt-scroll"), 8000); + const ganttBorder = gantt ? getComputedStyle(gantt).borderTopWidth : null; + document.getElementById("radio-open").click(); + const log = await until(() => document.querySelector('#radio-spot:not([hidden]) [data-panel="radio-log"]'), 8000); + const device = document.querySelector('#radio-spot:not([hidden]) [data-panel="radio-device"]'); + const out = {gantt: ganttBorder, log: log ? getComputedStyle(log).borderTopWidth : null, device: device ? getComputedStyle(device).borderTopWidth : null}; + document.getElementById("radio-open").click(); + return out; +})()""" +SHOW = """(async () => {@HELPERS@@HOME@ + await go("home"); + const found = await until(() => tile("@KEY@"), 8000); + found.scrollIntoView({block: "center"}); + await sleep(400); + return {key: found.dataset.pin}; +})()""" + + +def probe(template: str, **names: str) -> str: + return opened.probe(template.replace("@PANELS@", json.dumps(PANELS)), **names) + + +@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium") +class TestHomeFlatWidgets(HubCase): + seed = base.OrchestratorE2ECase.seed + subagents = base.OrchestratorE2ECase.subagents + drive = base.OrchestratorE2ECase.drive + sample = w4.TestWorkbenchResources.sample + + def setUp(self): + super().setUp() + OUT.mkdir(parents=True, exist_ok=True) + self.seed() + now = int(time.time()) + self.start = now - now % 60 - w4.ROWS * 60 + folder = self.kept / "resources" + folder.mkdir() + (folder / "samples.jsonl").write_text(self.jsonl([self.sample(index) for index in range(w4.ROWS)]), encoding="utf-8") + + def steps(self) -> list[dict]: + steps = [] + for width, height in ((1920, 1080), (390, 844)): + page = f"{self.base}?{width}" + steps += [ + {"width": width, "height": height, "url": f"{page}-clear#stream", "wait": 600, "probe": bm.CLEAR, "shot": None}, + {"width": width, "height": height, "url": f"{page}-seed#stream", "wait": 1200, "probe": probe(opened.SEED), "shot": None}, + {"width": width, "height": height, "url": f"{page}-flat#home", "wait": 1500, "probe": probe(FLAT), "shot": str(OUT / f"chromium-{width}-home.png")}, + {"width": width, "height": height, "url": f"{page}-full#stream", "wait": 1200, "probe": probe(FULL), "shot": None}, + ] + steps += [{"width": width, "height": height, "url": None, "wait": 0, "probe": probe(SHOW, key=key), "shot": str(OUT / f"chromium-{width}-{key.split(':')[1].replace('/', '-')}.png")} for key in NAMED] + return steps + + def test_chromium_flattens_every_widget_whose_content_is_a_box_and_keeps_the_box_in_full_view_at_1920_and_390(self): + data = self.drive(self.steps(), None) + (OUT / "chromium-flat.json").write_text(json.dumps(data, indent=1), encoding="utf-8") + self.assertEqual([error for error in data["errors"] if "/favicon.ico" not in error], []) + per_width = len(data["results"]) // 2 + for index, width in enumerate((1920, 390)): + flat, full = data["results"][index * per_width + 2], data["results"][index * per_width + 3] + self.assertFalse(flat["wide"], flat) + tiles = {tile["key"]: tile for tile in flat["tiles"]} + self.assertEqual(len(tiles), len(PANELS) + 7, sorted(tiles)) + for key, tile in tiles.items(): + with self.subTest(width=width, key=key): + self.assertIsNone(tile["boxLeft"], tile) + if tile["flat"] is not None: + self.assertEqual((tile["border"], tile["background"]), ("0px", "rgba(0, 0, 0, 0)"), tile) + self.assertLessEqual(abs(tile["gap"]), 2, tile) + for key, box in NAMED.items(): + with self.subTest(width=width, named=key): + self.assertIn(box, tiles[key]["flat"] or [], tiles[key]) + for key in ("panel:radio-log", "panel:radio-device"): + self.assertFalse(tiles[key]["heading"], tiles[key]) + self.assertEqual(full, {"gantt": "1px", "log": "1px", "device": "1px"}, full) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/e2e/test_home_frame_e2e.py b/tests/e2e/test_home_frame_e2e.py new file mode 100644 index 0000000..e64336e --- /dev/null +++ b/tests/e2e/test_home_frame_e2e.py @@ -0,0 +1,95 @@ +from __future__ import annotations + +import json +import os +import shutil +import sys +import unittest +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path[:0] = [str(HERE.parent), str(HERE)] + +import hub_e2e_kit as base +from hub_case import HubCase + +OUT = Path(os.environ.get("E2E_OUT", "/tmp/hub-037-shots")) +FRAME = """ + const frame = () => { + const look = getComputedStyle(document.getElementById("main")); + return {background: look.backgroundColor, image: look.backgroundImage, border: look.borderLeftWidth, shadow: look.boxShadow}; + }; +""" +PINS = """(async () => {@HELPERS@@FRAME@ + await ViewStore.update("home.pins", () => [{kind: "panel", id: "stream", w: 6, h: 4}, {kind: "panel", id: "radio-log", w: 6, h: 4}]); + location.hash = "home"; + await screenShown(8000); + const tile = await until(() => document.querySelector("#main .home-tile"), 8000); + await sleep(600); + const nav = document.querySelector(".navbar"); + const edge = nav.getBoundingClientRect().left + parseFloat(getComputedStyle(nav).paddingLeft); + return {frame: frame(), offset: Math.round((tile.getBoundingClientRect().left - edge) * 10) / 10, wide: document.documentElement.scrollWidth > innerWidth + 1}; +})()""" +EMPTY = """(async () => {@HELPERS@@FRAME@ + await ViewStore.update("home.pins", () => []); + location.hash = "home"; + await screenShown(8000); + const empty = await until(() => document.querySelector("#main .home > .empty:not([hidden])"), 8000); + await sleep(300); + const look = empty ? getComputedStyle(empty) : null; + return {frame: frame(), card: look ? [look.backgroundColor !== "rgba(0, 0, 0, 0)", look.borderTopStyle, text(empty.querySelector("h2"))] : null}; +})()""" +STREAM = """(async () => {@HELPERS@@FRAME@ + location.hash = "stream"; + await screenShown(8000); + await sleep(300); + return {frame: frame()}; +})()""" +CLEAR = "rgba(0, 0, 0, 0)" + + +def probe(template: str) -> str: + return template.replace("@HELPERS@", base.HELPERS).replace("@FRAME@", FRAME) + + +@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium") +class TestHomeFrame(HubCase): + drive = base.OrchestratorE2ECase.drive + + def setUp(self): + super().setUp() + OUT.mkdir(parents=True, exist_ok=True) + self.claim("s1", "Skills") + self.snapshot() + self.page_url = f"http://localhost:{self.port}/" + + def test_chromium_draws_home_without_a_box_and_keeps_the_box_on_the_stream(self): + steps = [] + for width, height in base.WIDTHS: + shot = OUT / f"chromium-{width}" + steps += [ + {"width": width, "height": height, "url": f"{self.page_url}?{width}-pins#home", "wait": 1200, "probe": probe(PINS), "shot": f"{shot}-home-pins.png"}, + {"width": width, "height": height, "url": f"{self.page_url}?{width}-empty#home", "wait": 1200, "probe": probe(EMPTY), "shot": f"{shot}-home-empty.png"}, + {"width": width, "height": height, "url": f"{self.page_url}?{width}-stream#stream", "wait": 1200, "probe": probe(STREAM), "shot": None}, + ] + data = self.drive(steps, None) + (OUT / "chromium-home-frame.json").write_text(json.dumps(data, indent=1), encoding="utf-8") + self.assertEqual(data["errors"], []) + results = iter(data["results"]) + for width, _ in base.WIDTHS: + pins, empty, stream = next(results), next(results), next(results) + with self.subTest(width=width): + for found in (pins, empty, stream): + self.assertNotIn("error", found, found) + for bare in (pins["frame"], empty["frame"]): + self.assertEqual(bare, {"background": CLEAR, "image": "none", "border": "0px", "shadow": "none"}, bare) + self.assertLessEqual(abs(pins["offset"]), 2, pins) + self.assertFalse(pins["wide"]) + self.assertEqual(empty["card"], [True, "dashed", "Nothing pinned yet"], empty) + self.assertNotEqual(stream["frame"]["background"], CLEAR, stream) + self.assertEqual(stream["frame"]["border"], "1px", stream) + self.assertNotEqual(stream["frame"]["shadow"], "none", stream) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/e2e/test_hub_board_e2e.py b/tests/e2e/test_hub_board_e2e.py index 4af3ee8..dbeab48 100644 --- a/tests/e2e/test_hub_board_e2e.py +++ b/tests/e2e/test_hub_board_e2e.py @@ -103,7 +103,7 @@ class TestHubBoard(base.OrchestratorE2ECase): self.assertNotIn("error", found) self.assertEqual((found["badge"], found["start"], found["wide"]), (["Day", "1 alone"], everyone, False)) self.assertEqual((found["one"], found["kept"], found["none"], found["all"]), ([one, [True] * 3], one, [nobody, [False] * 3], [everyone, [True] * 3])) - self.assertEqual(found["popup"], {"badge": ["Draining"], "buttons": ["Mute Stage", "Drain", "Suspend", "Resume"]}) + self.assertEqual(found["popup"], {"badge": ["Draining"], "buttons": ["Drain", "Suspend", "Resume"]}) self.assertEqual([question.split(":")[0] for question in found["questions"]], ["Drain Stage", "Suspend Stage"]) sent = [["/api/board/sign", ["action", "agents"], "drain", ["s2"]], ["/api/board/drain", ["proof", "agents"], None, ["s2"]], ["/api/board/sign", ["action", "agents"], "suspend", ["s2"]], ["/api/board/suspend", ["proof", "agents"], None, ["s2"]]] self.assertEqual(found["posted"], sent if signs else sent[::2]) diff --git a/tests/e2e/test_hub_inbox_e2e.py b/tests/e2e/test_hub_inbox_e2e.py index 858bc70..c4fa72e 100644 --- a/tests/e2e/test_hub_inbox_e2e.py +++ b/tests/e2e/test_hub_inbox_e2e.py @@ -49,7 +49,7 @@ class TestHubInbox(base.OrchestratorE2ECase): def layout(self, probe: dict) -> None: self.assertNotIn("error", probe) - self.assertEqual(sorted(probe["kinds"]), ["Ask", "Operator", "Operator", "Review", "Rule request"]) + self.assertEqual((sorted(probe["kinds"]), probe["done"]), (["Ask", "Operator", "Operator", "Review", "Rule request"], 1)) self.assertEqual(probe["splits"], [["Deny", "Deny via …"]] * 5) self.assertEqual(probe["fields"], ["Kind", "Tool (glob)", "Pattern (glob)", "Directory (glob)", "Expires on"]) self.assertEqual(probe["dry"], "Dry run: the rule would have granted 1 of 1 asks from the last 7 days.") diff --git a/tests/e2e/test_hub_radio_e2e.py b/tests/e2e/test_hub_radio_e2e.py index 64edef4..cfe475d 100644 --- a/tests/e2e/test_hub_radio_e2e.py +++ b/tests/e2e/test_hub_radio_e2e.py @@ -310,7 +310,7 @@ class TestHubRadio(base.OrchestratorE2ECase): self.assertEqual(saved["tones"], ["MAYDAY / PAN-PAN", "Reviews, asks, decisions", "Post and calls to you", "All radio", "Squelch", "speak while CPU < 50 %"]) self.assertEqual(saved["bells"], ["MAYDAY / PAN-PAN tone", "Reviews, asks, decisions tone", "Post and calls to you tone", "All radio tone"]) self.assertEqual((saved["kept"], saved["after"]), ([float(squelch), radio_bell != "off", post == "speak"], [radio_bell, post])) - self.assertEqual(saved["general"], {"sections": ["Ambience", "Location", "Appearance", "Music", "Notifications", "Passkey"], "radio": 0}) + self.assertEqual(saved["general"], {"sections": ["Ambience", "Location", "Appearance", "Music", "Undo window", "Passkey"], "radio": 0}) self.assertEqual((saved["tall"], saved["wide"]), (width == 390, False)) self.assertEqual(read, {"squelch": float(squelch), "radio": radio_bell, "post": post, "tall": width == 390, "wide": False}) heads = {"post": ["post", "--to", "Stage"], "call": ["send", "call", "--to", "Stage"], "newsletter": ["post"]} diff --git a/tests/e2e/test_legend_toggle_e2e.py b/tests/e2e/test_legend_toggle_e2e.py index 96c949f..7b1343d 100644 --- a/tests/e2e/test_legend_toggle_e2e.py +++ b/tests/e2e/test_legend_toggle_e2e.py @@ -30,7 +30,7 @@ EXPECTED = { "resources": ["resources-hardware", "resources-tokens"], } READ = """ - const PARTS = ".legend > :not(.star, .legend-toggle), .res-legend, .home-metric > .legend-chips"; + const PARTS = ".legend > :not(.legend-toggle), .res-legend, .home-metric > .legend-chips"; const owners = () => [...all("#main [data-panel]").filter((host) => !host.closest(".home-tile")), ...all(".home-tile[data-pin]")]; const keyOf = (owner) => owner.dataset.pin || owner.dataset.panel; const ownerOf = (key) => owners().find((node) => keyOf(node) === key) || null; @@ -63,7 +63,7 @@ SCAN = """(async () => {@HELPERS@@READ@ const flip = async (key) => { const path = ownerOf(key).dataset.pin ? "tiles" : "views"; const button = () => toggleOf(ownerOf(key)); - const placed = path === "tiles" ? button().nextElementSibling.classList.contains("home-open") : button().previousElementSibling.classList.contains("star"); + const placed = path === "tiles" ? button().nextElementSibling.classList.contains("home-open") : button().parentElement.matches("[data-legend-slot], .legend-row") && button().parentElement.lastElementChild === button(); const before = shownParts(ownerOf(key)); button().click(); const hidden = Boolean(await until(() => ownerOf(key) && ownerOf(key).dataset.legend === "hidden" && shownParts(ownerOf(key)) === 0 && button().getAttribute("aria-pressed") === "false", 4000)); diff --git a/tests/e2e/test_line_comments_e2e.py b/tests/e2e/test_line_comments_e2e.py index bdf3328..907c3e9 100644 --- a/tests/e2e/test_line_comments_e2e.py +++ b/tests/e2e/test_line_comments_e2e.py @@ -91,7 +91,7 @@ OVERLAY = """(async () => {@HELPERS@@UNLABELLED@@CAPTURE@ document.body.dispatchEvent(new KeyboardEvent("keydown", {key: "Escape", bubbles: true})); await until(() => document.getElementById("sheet").hidden, 4000); const card = listed(row()); - row().querySelector(".item-actions button.primary").click(); + row().querySelector(":is(.item-actions, .code-foot) button.primary").click(); await until(() => posted.some(([path]) => path === (@SIGNS@ ? "/api/messages" : "/api/sign")), 10000); await sleep(1200); return {item, inline, marked, card, posted, kept: listed(row()), wide: document.documentElement.scrollWidth > innerWidth + 1}; @@ -140,7 +140,7 @@ class TestLineComments(base.OrchestratorE2ECase): denial = [["ask", "reject", "call", "a.txt:2: stream note"]] self.assertEqual(stream["posted"], [["/api/sign", None, denial], *([["/api/inbox/approve", None, denial]] if signs else [])]) self.assertNotIn("error", overlay, overlay) - self.assertEqual((overlay["item"], overlay["inline"]), ("Comment", {"after": True, "unlabelled": []})) + self.assertEqual((overlay["item"], overlay["inline"]), (None, {"after": True, "unlabelled": []})) self.assertEqual(overlay["marked"], {"rows": ["3"], "notes": ["overlay note"], "list": ["src/app.py:3overlay note"], "field": False, "open": True}) self.assertEqual(overlay["card"], ["src/app.py:3overlay note"]) grant = [["review", "approve", "", ""]] diff --git a/tests/e2e/test_match_pile_e2e.py b/tests/e2e/test_match_pile_e2e.py new file mode 100644 index 0000000..e4dbc73 --- /dev/null +++ b/tests/e2e/test_match_pile_e2e.py @@ -0,0 +1,167 @@ +from __future__ import annotations + +import json +import os +import shutil +import sys +import unittest +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path[:0] = [str(HERE.parent), str(HERE)] + +import hub_e2e_kit as base +import test_match_review_e2e as matched +import test_workbench_w4_e2e as w4 +from hub_case import HubCase + +OUT = Path(os.environ.get("E2E_OUT", "/tmp/hub-035-036-shots")) +DECK = """ + const widen = () => card() && card().querySelector(".match-widen"); + const shown = (node) => Boolean(node && node.getClientRects().length); + const area = () => { + const box = document.querySelector("#main .graph.match"); + const look = getComputedStyle(box); + return box.clientWidth - parseFloat(look.paddingLeft) - parseFloat(look.paddingRight); + }; + const width = () => card().offsetWidth; + const later = async () => { + const before = card().dataset.card; + document.body.dispatchEvent(new KeyboardEvent("keydown", {key: "ArrowUp", bubbles: true})); + return Boolean(await until(() => card() && card().dataset.card !== before, 4000)); + }; + const flip = async (wide) => { + widen().click(); + await until(() => document.querySelector("#main .match-stack").dataset.wide === String(wide), 4000); + await sleep(200); + }; +""" +WIDE = """(async () => {@HELPERS@@CARD@@DECK@ + await screenShown(8000); + if (!(await until(card, 8000))) { + return {error: text(document.getElementById("main")).slice(0, 300)}; + } + await sleep(300); + if (document.querySelector("#main .match-stack").dataset.wide === "true") { + await flip(false); + } + const before = {button: shown(widen()), width: width(), area: Math.round(area())}; + if (!before.button) { + return {before}; + } + await flip(true); + const wide = {width: width(), area: Math.round(area()), label: widen().getAttribute("aria-label"), keys: await later()}; + wide.after = width(); + return {before, wide}; +})()""" +KEPT = """(async () => {@HELPERS@@CARD@@DECK@ + await screenShown(8000); + if (!(await until(card, 8000))) { + return {error: text(document.getElementById("main")).slice(0, 300)}; + } + await sleep(300); + const kept = {wide: document.querySelector("#main .match-stack").dataset.wide, width: width(), area: Math.round(area())}; + await flip(false); + const narrow = {width: width(), label: widen().getAttribute("aria-label"), keys: await later()}; + narrow.after = width(); + return {kept, narrow}; +})()""" +PILE = """(async () => {@HELPERS@@CARD@@DECK@ + await screenShown(8000); + if (!(await until(card, 8000))) { + return {error: text(document.getElementById("main")).slice(0, 300)}; + } + await sleep(300); + const open = () => Number((text(document.querySelector("#main .task-toolbar .muted")) || "").split(" ")[0]); + const pile = () => { + const front = card(); + const edge = front.getBoundingClientRect(); + return {open: open(), release: front.classList.contains("match-release-card"), layers: all("#main .match-layer").map((layer) => ({ + size: Math.abs(layer.offsetWidth - front.offsetWidth) <= 2 && Math.abs(layer.offsetHeight - front.offsetHeight) <= 2, + above: layer.getBoundingClientRect().top < edge.top - 1, + lower: Number(getComputedStyle(layer).zIndex) < Number(getComputedStyle(front).zIndex), + inert: getComputedStyle(layer).pointerEvents === "none" && layer.getAttribute("aria-hidden") === "true", + }))}; + }; + const seen = [pile()]; + for (let tries = 0; open() > 1 && tries < 8; tries += 1) { + const count = open(); + document.body.dispatchEvent(new KeyboardEvent("keydown", {key: "ArrowLeft", bubbles: true})); + const confirm = await until(() => document.querySelector(".match-feedback-reject"), 2000); + if (!confirm) { + await later(); + continue; + } + confirm.click(); + if (await until(() => open() === count - 1 && card(), 4000)) { + await sleep(500); + seen.push(pile()); + } + } + return {seen}; +})()""" + + +def probe(template: str) -> str: + return template.replace("@HELPERS@", base.HELPERS).replace("@CARD@", matched.CARD).replace("@DECK@", DECK) + + +@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium") +class TestMatchPile(HubCase): + drive = base.OrchestratorE2ECase.drive + cards = matched.TestMatchReview.cards + review = matched.TestMatchReview.review + payload = matched.TestMatchReview.payload + + def setUp(self): + super().setUp() + OUT.mkdir(parents=True, exist_ok=True) + self.cards() + + def steps(self) -> list[dict]: + steps = [] + for width, height in base.WIDTHS: + at = {"width": width, "height": height} + shot = OUT / f"chromium-{width}" + steps.append({**at, "url": f"{self.base}?{width}-wide#tasks/match", "wait": 1500, "probe": probe(WIDE), "shot": f"{shot}-match-wide.png"}) + if width > 640: + steps.append({**at, "url": f"{self.base}?{width}-kept#tasks/match", "wait": 1500, "probe": probe(KEPT), "shot": f"{shot}-match-narrow.png"}) + steps.append({**at, "url": f"{self.base}?{width}-pile#tasks/match", "wait": 1500, "probe": probe(PILE), "shot": f"{shot}-match-pile.png"}) + return steps + + def test_chromium_widens_a_match_card_keeps_the_choice_and_piles_the_waiting_cards_behind_it(self): + data = self.drive(self.steps(), None, init=w4.GUARD) + (OUT / "chromium-match-pile.json").write_text(json.dumps(data, indent=1), encoding="utf-8") + self.assertEqual([error for error in data["errors"] if "/favicon.ico" not in error], []) + results = iter(data["results"]) + for width, _ in base.WIDTHS: + wide = next(results) + kept = next(results) if width > 640 else None + pile = next(results) + with self.subTest(width=width, step="wide"): + self.assertNotIn("error", wide, wide) + self.assertEqual(wide["before"]["button"], width > 640, wide) + self.assertLessEqual(wide["before"]["width"], 960, wide) + if width > 640: + self.assertLessEqual(abs(wide["wide"]["width"] - wide["wide"]["area"]), 2, wide) + self.assertEqual((wide["wide"]["label"], wide["wide"]["keys"], wide["wide"]["after"]), ("Normal width", True, wide["wide"]["width"]), wide) + if kept: + with self.subTest(width=width, step="kept"): + self.assertNotIn("error", kept, kept) + self.assertEqual(kept["kept"]["wide"], "true", kept) + self.assertLessEqual(abs(kept["kept"]["width"] - kept["kept"]["area"]), 2, kept) + self.assertLessEqual(kept["narrow"]["width"], 960, kept) + self.assertEqual((kept["narrow"]["label"], kept["narrow"]["keys"], kept["narrow"]["after"]), ("Full width", True, kept["narrow"]["width"]), kept) + with self.subTest(width=width, step="pile"): + self.assertNotIn("error", pile, pile) + seen = pile["seen"] + self.assertGreaterEqual(seen[0]["open"], 3, seen) + self.assertEqual(seen[-1]["open"], 1, seen) + for state in seen: + self.assertEqual(len(state["layers"]), min(2, state["open"] - (0 if state["release"] else 1)), state) + for layer in state["layers"]: + self.assertEqual(layer, {"size": True, "above": True, "lower": True, "inert": True}, state) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/e2e/test_match_rejects_e2e.py b/tests/e2e/test_match_rejects_e2e.py new file mode 100644 index 0000000..216d569 --- /dev/null +++ b/tests/e2e/test_match_rejects_e2e.py @@ -0,0 +1,170 @@ +from __future__ import annotations + +import json +import os +import shutil +import sys +import unittest +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path[:0] = [str(HERE.parent), str(HERE)] + +import hub_e2e_kit as base +import test_match_review_e2e as matched +from hub_case import HubCase + +OUT = Path(os.environ.get("E2E_OUT", "/tmp/hub-039-shots")) +INIT = """() => { + window.e2eViolations = []; + document.addEventListener("securitypolicyviolation", (event) => window.e2eViolations.push(`${event.violatedDirective} ${event.blockedURI}`)); + const real = window.fetch.bind(window); + window.e2eSent = []; + window.fetch = (input, options) => { + const url = String(input && input.url ? input.url : input); + if (url.startsWith("/api/match") && window.e2eMatch) { + return Promise.resolve(new Response(JSON.stringify({cards: window.e2eMatch}), {headers: {"Content-Type": "application/json"}})); + } + if (url === "/api/messages" && options && options.method === "POST") { + window.e2eSent.push(JSON.parse(options.body)); + } + return real(input, options); + }; +}""" +STEPS = """ + const served = async () => (await (await fetch("/api/match", {cache: "no-store"})).json()).cards; + const key = (name) => document.body.dispatchEvent(new KeyboardEvent("keydown", {key: name, bubbles: true})); + const actionable = async () => { + for (let tries = 0; tries < 6 && card() && card().querySelector(".match-stale-note, [data-stale='true']"); tries += 1) { + key("ArrowUp"); + await sleep(600); + } + return card() && card().dataset.card; + }; + const reject = async (words) => { + const id = await actionable(); + key("ArrowLeft"); + const field = await until(() => document.querySelector(".match-feedback"), 4000); + if (!field) { + return null; + } + field.value = words; + document.querySelector(".match-feedback-reject").click(); + await until(() => !card() || card().dataset.card !== id, 4000); + return id; + }; + const release = async () => { + const open = document.querySelector("#main .match-open-overview"); + if (open && !open.hidden) { + open.click(); + } + return until(() => document.querySelector("#main .match-overview"), 8000); + }; + const serve = async (cards) => { + window.e2eMatch = cards; + await sleep(2600); + window.dispatchEvent(new Event("focus")); + }; +""" +CHANGED = """(async () => {@HELPERS@@CARD@@STEPS@ + await screenShown(8000); + if (!(await until(card, 8000))) { + return {error: text(document.getElementById("main")).slice(0, 300)}; + } + await sleep(300); + const cards = await served(); + const id = await reject("fix the probe"); + await serve(cards.map((one) => (one.id === id ? {...one, hash: `${one.hash}0`} : one))); + await release(); + const note = await until(() => document.querySelector(`#main .match-decision[data-card="${id}"] .match-decision-note`), 8000); + const row = document.querySelector(`#main .match-decision[data-card="${id}"]`); + return {id, verdict: row && row.dataset.verdict, note: note ? text(note) : null}; +})()""" +ACCEPTED = """(async () => {@HELPERS@@CARD@@STEPS@ + await screenShown(8000); + if (!(await until(card, 8000))) { + return {error: text(document.getElementById("main")).slice(0, 300)}; + } + await sleep(300); + const cards = await served(); + const id = await actionable(); + const title = (cards.find((one) => one.id === id) || {}).title; + key("ArrowRight"); + await until(() => !card() || card().dataset.card !== id, 4000); + const tally = () => text(document.querySelector("#main .match-tally")); + const before = tally(); + const shown = new Set(all("#toasts .toast")); + await serve(cards.map((one) => (one.id === id ? {...one, hash: `${one.hash}0`} : one))); + const toast = await until(() => all("#toasts .toast").filter((node) => !shown.has(node)).map(text).find((entry) => entry.startsWith("Accept dropped")), 8000); + return {id, title, before, after: tally(), toast: toast || null}; +})()""" +WITHDRAWN = """(async () => {@HELPERS@@CARD@@STEPS@ + await screenShown(8000); + if (!(await until(card, 8000))) { + return {error: text(document.getElementById("main")).slice(0, 300)}; + } + await sleep(300); + const cards = await served(); + const id = await reject("withdrawn probe"); + const title = (cards.find((one) => one.id === id) || {}).title; + await serve(cards.filter((one) => one.id !== id)); + await release(); + const row = await until(() => document.querySelector(`#main .match-decision[data-card="${id}"][data-withdrawn="true"]`), 8000); + const button = document.querySelector("#main .match-release"); + if (!row || !button) { + return {id, row: Boolean(row), button: Boolean(button)}; + } + button.click(); + await until(() => window.e2eSent.length, 15000); + return {id, title, row: true, sent: window.e2eSent.map((message) => ({cls: message.class, text: message.text}))}; +})()""" + + +def probe(template: str) -> str: + return template.replace("@HELPERS@", base.HELPERS).replace("@CARD@", matched.CARD).replace("@STEPS@", STEPS) + + +@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium") +class TestMatchRejects(HubCase): + drive = base.OrchestratorE2ECase.drive + authenticator = base.OrchestratorE2ECase.authenticator + cards = matched.TestMatchReview.cards + review = matched.TestMatchReview.review + payload = matched.TestMatchReview.payload + + def setUp(self): + super().setUp() + OUT.mkdir(parents=True, exist_ok=True) + self.cards() + self.base = f"http://localhost:{self.port}/" + + def test_chromium_keeps_a_reject_across_a_changed_or_withdrawn_card_and_drops_a_changed_accept_with_a_toast(self): + at = {"width": 1366, "height": 900} + steps = [ + {**at, "url": f"{self.base}?changed#tasks/match", "wait": 1500, "probe": probe(CHANGED), "shot": str(OUT / "chromium-changed.png")}, + {**at, "url": f"{self.base}?accepted#tasks/match", "wait": 1500, "probe": probe(ACCEPTED), "shot": str(OUT / "chromium-accepted.png")}, + {**at, "url": f"{self.base}?withdrawn#tasks/match", "wait": 1500, "probe": probe(WITHDRAWN), "shot": str(OUT / "chromium-withdrawn.png")}, + ] + data = self.drive(steps, self.authenticator(), init=INIT) + (OUT / "chromium-match-rejects.json").write_text(json.dumps(data, indent=1), encoding="utf-8") + self.assertEqual([error for error in data["errors"] if "/favicon.ico" not in error], []) + changed, accepted, withdrawn = data["results"] + with self.subTest(case="changed reject"): + self.assertNotIn("error", changed, changed) + self.assertEqual(changed["verdict"], "reject", changed) + self.assertIn("changed since your reject", changed["note"], changed) + with self.subTest(case="changed accept"): + self.assertNotIn("error", accepted, accepted) + self.assertEqual((accepted["before"], accepted["after"]), ("1", "0"), accepted) + self.assertIn(accepted["title"], accepted["toast"] or "", accepted) + with self.subTest(case="withdrawn reject"): + self.assertNotIn("error", withdrawn, withdrawn) + self.assertTrue(withdrawn["row"], withdrawn) + calls = [message for message in withdrawn["sent"] if message["cls"] == "call"] + self.assertEqual(len(calls), 1, withdrawn) + self.assertIn(withdrawn["title"], calls[0]["text"], withdrawn) + self.assertIn("withdrawn probe", calls[0]["text"], withdrawn) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/e2e/test_match_release_card_e2e.py b/tests/e2e/test_match_release_card_e2e.py new file mode 100644 index 0000000..e2dac4f --- /dev/null +++ b/tests/e2e/test_match_release_card_e2e.py @@ -0,0 +1,193 @@ +from __future__ import annotations + +import json +import os +import shutil +import sys +import unittest +from pathlib import Path +from unittest import mock + +HERE = Path(__file__).resolve().parent +sys.path[:0] = [str(HERE.parent), str(HERE)] + +import hub_e2e_kit as base +import test_match_review_e2e as matched +from hub_case import HubCase +from kvb_orchestrator import batches + +OUT = Path(os.environ.get("E2E_OUT", "/tmp/hub-040-shots")) +INIT = """() => { + window.e2eViolations = []; + document.addEventListener("securitypolicyviolation", (event) => window.e2eViolations.push(`${event.violatedDirective} ${event.blockedURI}`)); + const real = window.fetch.bind(window); + window.e2eSubmits = []; + window.e2eMatch = null; + window.fetch = (input, options) => { + const url = String(input && input.url ? input.url : input); + if (url.startsWith("/api/match") && window.e2eMatch) { + return Promise.resolve(new Response(JSON.stringify({cards: window.e2eMatch}), {headers: {"Content-Type": "application/json"}})); + } + if (url === "/api/inbox/approve" && options && typeof options.body === "string") { + window.e2eSubmits.push(JSON.parse(options.body).items.map((item) => [item.kind, item.id, item.verb])); + } + return real(input, options); + }; +}""" +STEPS = """ + const served = async () => (await (await fetch("/api/match", {cache: "no-store"})).json()).cards; + const key = (name) => document.body.dispatchEvent(new KeyboardEvent("keydown", {key: name, bubbles: true, cancelable: true})); + const releasing = () => Boolean(card() && card().classList.contains("match-release-card")); + const decideAll = async () => { + for (let tries = 0; tries < 10 && card() && !releasing(); tries += 1) { + const front = card(); + const id = front.dataset.card; + key(front.dataset.stale === "true" || front.hasAttribute("data-blocked") ? "ArrowUp" : "ArrowRight"); + await until(() => !card() || card().dataset.card !== id, 4000); + await sleep(200); + } + return releasing(); + }; + const swipeRight = async () => { + const head = card().querySelector(".match-head"); + const box = head.getBoundingClientRect(); + const [x, y] = [box.left + box.width / 2, box.top + 20]; + const dx = card().getBoundingClientRect().width * 0.4; + const at = (cx) => ({bubbles: true, cancelable: true, pointerId: 12, pointerType: "touch", isPrimary: true, button: 0, clientX: cx, clientY: y}); + head.dispatchEvent(new PointerEvent("pointerdown", at(x))); + window.dispatchEvent(new PointerEvent("pointermove", at(x + dx / 2))); + const leaning = card().dataset.leaning || ""; + window.dispatchEvent(new PointerEvent("pointerup", at(x + dx))); + return leaning; + }; +""" +CARD040 = """(async () => {@HELPERS@@CARD@@STEPS@ + await screenShown(8000); + if (!(await until(card, 8000))) { + return {error: text(document.getElementById("main")).slice(0, 300)}; + } + await sleep(300); + const found = {ready: await decideAll()}; + const front = card(); + found.release = Boolean(front && front.closest(".match-deck") && front.querySelector(".match-release")); + found.layers = all("#main .match-layer").map((node) => node.dataset.card); + found.block = Boolean(document.querySelector("#main .match-release-block")); + found.risk = all("#main .match-accept-risk").map((node) => [node.closest(".match-decision").dataset.card, node.getAttribute("aria-pressed")]); + found.label = text(document.querySelector("#main .match-release")); + key("ArrowLeft"); + found.back = await until(() => !releasing() && card() && card().dataset.card, 4000); + document.querySelector("#main .match-open-overview").click(); + found.again = Boolean(await until(releasing, 4000)); + const cards = await served(); + window.e2eMatch = [...cards, {...cards.find((one) => one.id === "@COMMIT@"), id: "review:e2e-new", ref: "e2e-new", hash: "e2e", title: "e2e: arrived meanwhile"}]; + found.arrived = Boolean(await until(() => document.querySelector('#main .match-layer[data-card="review:e2e-new"]'), 10000)); + found.stays = releasing(); + window.e2eMatch = null; + found.wide = document.documentElement.scrollWidth > innerWidth + 1; + return found; +})()""" +RELEASE = """(async () => {@HELPERS@@CARD@@STEPS@ + await screenShown(8000); + if (!(await until(card, 8000))) { + return {error: text(document.getElementById("main")).slice(0, 300)}; + } + await sleep(300); + if (!(await decideAll())) { + return {error: text(document.getElementById("main")).slice(0, 300)}; + } + const risk = () => document.querySelector('#main .match-decision[data-card="@RED@"] .match-accept-risk'); + const pressed = []; + for (let clicks = 0; clicks < @CLICKS@; clicks += 1) { + risk().click(); + await sleep(200); + pressed.push(risk().getAttribute("aria-pressed")); + } + const label = text(document.querySelector("#main .match-release")); + window.e2eSubmits.length = 0; + const leaning = @SWIPE@ ? await swipeRight() : (key("ArrowRight"), ""); + await until(() => window.e2eSubmits.length >= @SUBMITS@, 20000); + await sleep(1500); + await until(() => card() && !releasing(), 8000); + return {pressed, label, leaning, submits: window.e2eSubmits, front: card() ? card().dataset.card : null, peeks: all("#main .match-peek").map((node) => node.dataset.card)}; +})()""" + + +def probe(template: str, **names: str) -> str: + fills = {"@HELPERS@": base.HELPERS, "@CARD@": matched.CARD, "@STEPS@": STEPS, **{f"@{key.upper()}@": value for key, value in names.items()}} + for key, value in fills.items(): + template = template.replace(key, value) + return template + + +class ReleaseDeck(HubCase): + drive = base.OrchestratorE2ECase.drive + authenticator = base.OrchestratorE2ECase.authenticator + cards = matched.TestMatchReview.cards + review = matched.TestMatchReview.review + payload = matched.TestMatchReview.payload + + def setUp(self): + super().setUp() + OUT.mkdir(parents=True, exist_ok=True) + self.cards() + diff = [{"path": "src/red.py", "status": "M", "mode": "100644", "additions": 1, "deletions": 0, "patch": "@@ -1,1 +1,2 @@\n line 1\n+red line", "note": ""}] + arguments = {**self.arguments("feat: red gate", "", self.page("feature-red.html", "p")), "worktree": "/repo/.worktrees/feature/red", "branch": "feature/red", "agent": "Stage", "diff": diff, "gate": "fail"} + result = self.tool("review_request", arguments) + self.assertFalse(result["isError"], result) + self.red = result["structuredContent"]["id"] + self.base = f"http://localhost:{self.port}/" + + +@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium") +class TestMatchReleaseCard(ReleaseDeck): + def release(self, name: str, clicks: int, swipe: bool, submits: int) -> dict: + step = {"width": 1920, "height": 1080, "url": f"{self.base}?{name}#tasks/match", "wait": 1500, "shot": str(OUT / f"chromium-{name}.png"), + "probe": probe(RELEASE, red=f"review:{self.red}", clicks=str(clicks), swipe="true" if swipe else "false", submits=str(submits))} + with mock.patch.object(batches, "UNDO", 0.3): + data = self.drive([step], self.authenticator(), init=INIT) + (OUT / f"chromium-{name}.json").write_text(json.dumps(data, indent=1), encoding="utf-8") + self.assertEqual([error for error in data["errors"] if "/favicon.ico" not in error], []) + found = data["results"][0] + self.assertNotIn("error", found, found) + return found + + def sorted_submits(self, found: dict) -> list[list[list[str]]]: + return [sorted(batch) for batch in found["submits"]] + + def test_chromium_puts_the_release_card_in_front_of_greyed_and_new_cards_and_left_returns_to_the_stack(self): + steps = [{"width": width, "height": height, "url": f"{self.base}?{width}-card#tasks/match", "wait": 1500, "shot": str(OUT / f"chromium-{width}-release-card.png"), + "probe": probe(CARD040, commit=f"review:{self.commit}")} for width, height in ((390, 844), (1920, 1080))] + data = self.drive(steps, None, init=INIT) + (OUT / "chromium-release-card.json").write_text(json.dumps(data, indent=1), encoding="utf-8") + self.assertEqual([error for error in data["errors"] if "/favicon.ico" not in error], []) + for (width, _), found in zip(((390, 844), (1920, 1080)), data["results"], strict=True): + with self.subTest(width=width): + self.assertNotIn("error", found, found) + self.assertEqual((found["ready"], found["release"], found["block"], found["wide"]), (True, True, False, False), found) + self.assertIn(f"review:{self.stale}", found["layers"], found) + self.assertEqual(found["risk"], [[f"review:{self.red}", "false"]], found) + self.assertEqual(found["label"], "Release 2 decisions", found) + self.assertEqual(found["back"], f"review:{self.stale}", found) + self.assertEqual((found["again"], found["arrived"], found["stays"]), (True, True, True), found) + + def test_chromium_release_by_arrow_leaves_the_red_gate_commit_in_the_stack_until_its_risk_is_accepted(self): + found = self.release("no-risk", 0, False, 1) + self.assertEqual(self.sorted_submits(found), [sorted([["review", self.commit, "approve"], ["operator", "operator/issue", "approve"]])], found) + self.assertEqual(found["label"], "Release 2 decisions", found) + self.assertIn(f"review:{self.red}", [found["front"], *found["peeks"]], found) + + def test_chromium_release_by_swipe_signs_a_risk_accepted_red_gate_commit_on_its_own_first(self): + found = self.release("risk", 1, True, 2) + self.assertEqual((found["pressed"], found["leaning"], found["label"]), (["true"], "accept", "Release 3 decisions"), found) + self.assertEqual(self.sorted_submits(found), [[["review", self.red, "approve"]], sorted([["review", self.commit, "approve"], ["operator", "operator/issue", "approve"]])], found) + self.settle(lambda: self.status(self.red) == "approved" and self.status(self.commit) == "approved") + + def test_chromium_a_withdrawn_risk_leaves_the_red_gate_commit_out_again(self): + found = self.release("withdrawn", 2, False, 1) + self.assertEqual((found["pressed"], found["label"]), (["true", "false"], "Release 2 decisions"), found) + self.assertEqual(self.sorted_submits(found), [sorted([["review", self.commit, "approve"], ["operator", "operator/issue", "approve"]])], found) + self.assertIn(f"review:{self.red}", [found["front"], *found["peeks"]], found) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/e2e/test_match_release_e2e.py b/tests/e2e/test_match_release_e2e.py index 3a6918d..0062a6c 100644 --- a/tests/e2e/test_match_release_e2e.py +++ b/tests/e2e/test_match_release_e2e.py @@ -84,8 +84,11 @@ FLOW = """(async () => {@HELPERS@ const leaned = await swipe(width * 0.4, 0); await until(() => front() !== order[2], 3000); order.push(front()); + key("w"); + await until(() => front() !== order[3], 3000); + order.push(front()); const short = await swipe(width * 0.1, 0); - const stayed = front() === order[3]; + const stayed = front() === order[4]; await swipe(width * 0.4, 4); const overview = await until(() => document.querySelector("#main .match-overview"), 3000); const rows = overview ? all("#main .match-decision").map((item) => [item.dataset.card, item.dataset.verdict, text(item.querySelector(".match-decision-feedback"))]) : []; @@ -175,7 +178,7 @@ class TestMatchRelease(HubCase): def check_flow(self, found: dict) -> None: reason = f"{FIRST}:3: rename it" self.assertNotIn("error", found, found) - self.assertEqual(found["order"], [self.cards[0], self.cards[1], self.cards[2], self.cards[1]], found) + self.assertEqual(found["order"], [self.cards[0], self.cards[1], self.cards[2], "release", self.cards[1]], found) self.assertEqual((found["prefill"], found["leaned"], found["short"], found["stayed"]), (reason, "accept", "accept", True), found) expected = [[self.cards[0], "reject", f"{reason}\nalso add a test"], [self.cards[1], "accept", None], [self.cards[2], "accept", None]] self.assertEqual(sorted(found["rows"]), sorted(expected), found) diff --git a/tests/e2e/test_match_review_e2e.py b/tests/e2e/test_match_review_e2e.py index 928eb02..ca53064 100644 --- a/tests/e2e/test_match_review_e2e.py +++ b/tests/e2e/test_match_review_e2e.py @@ -32,6 +32,7 @@ CARD = """ }; const head = () => ({ card: card().dataset.card, kind: card().dataset.kind, stale: card().dataset.stale, face: Boolean(card().querySelector(".match-who .avatar svg")), + opens: Boolean(card().querySelector(".match-who .avatar").closest("button.agent-link")), name: text(card().querySelector(".match-name")), age: text(card().querySelector(".match-age")), metrics: all(".match-metric", card()).map((chip) => [chip.dataset.metric, text(chip.querySelector("strong"))]), under: Boolean(card().querySelector(".match-metrics")) && card().querySelector(".match-metrics").getBoundingClientRect().top >= card().querySelector(".match-name").getBoundingClientRect().bottom - 1, @@ -182,9 +183,9 @@ class TestMatchReview(HubCase): order = [path for path, _ in FILES] paints = set() for width, _ in widths: + stack, scroll, mark, command, stale = (next(results) for _ in range(5)) with self.subTest(width=width): - stack = next(results) - self.assertEqual((stack["card"], stack["kind"], stack["stale"], stack["face"]), (f"review:{self.commit}", "commit", "false", True), stack) + self.assertEqual((stack["card"], stack["kind"], stack["stale"], stack["face"], stack["opens"]), (f"review:{self.commit}", "commit", "false", True, True), stack) self.assertEqual((stack["name"], stack["age"]), ("Skills", "3 days"), stack) self.assertEqual((stack["metrics"], stack["under"]), ([["fix", "95"], ["break", "3"]], True), stack) place = [["branch", "feature/match", "Branch: feature/match (click copies)"], ["repo", "repo", "Repository: /repo (click copies)"], @@ -197,25 +198,21 @@ class TestMatchReview(HubCase): self.assertEqual(stack["peeks"], ["operator:operator/issue", f"review:{self.stale}"], stack) self.assertFalse(stack["accept"], stack) self.assertFalse(stack["wide"], stack) - scroll = next(results) self.assertEqual(scroll["steps"][0], order[:1], scroll) self.assertEqual(scroll["steps"][-1], order, scroll) for step in scroll["steps"]: self.assertEqual(step, order[: len(step)], scroll) self.assertGreater(len({len(step) for step in scroll["steps"]}), 2, scroll) self.assertEqual(scroll["numbered"], [[path, True] for path in order], scroll) - mark = next(results) self.assertEqual((mark["clicked"], mark["pressed"]), (True, True), mark) self.assertEqual(mark["marks"], [["3", "use the helper here"], ["6", "long press note"]], mark) self.assertEqual(mark["marked"], ["3", "6"], mark) self.assertEqual((mark["presets"], mark["preset"]), (["long press note", "use the helper here"], ["use the helper here", True]), mark) self.assertEqual(mark["count"], "2", mark) - command = next(results) self.assertEqual((command["kind"], command["stale"], command["command"], command["why"]), ("command", "false", self.command, "file the release issue"), command) self.assertEqual(command["where"], str(self.work), command) self.assertEqual(command["payload"], [["body.md", "read", 14], ["link.md", "refused", 0]], command) self.assertEqual((command["name"], command["age"]), ("Skills", "3 days"), command) - stale = next(results) self.assertEqual((stale["kind"], stale["stale"], stale["accept"], stale["name"], stale["age"]), ("commit", "true", True, "Stage", "9 days"), stale) self.assertIn("changed", stale["reason"]) self.assertEqual(len(paints), 1, paints) diff --git a/tests/e2e/test_match_swipe_e2e.py b/tests/e2e/test_match_swipe_e2e.py index d0abba5..5c106d0 100644 --- a/tests/e2e/test_match_swipe_e2e.py +++ b/tests/e2e/test_match_swipe_e2e.py @@ -22,7 +22,7 @@ SIDE = """ const front = () => (card() ? card().dataset.card : null); const tally = () => text(document.querySelector("#main .match-tally")); const point = () => { - const name = card().querySelector(".match-name").getBoundingClientRect(); + const name = card().querySelector(".match-age").getBoundingClientRect(); return {front: front(), x: Math.round(name.left + name.width / 2), y: Math.round(name.top + name.height / 2), width: card().getBoundingClientRect().width}; }; const aim = (x, y) => { diff --git a/tests/e2e/test_match_waiting_e2e.py b/tests/e2e/test_match_waiting_e2e.py index 4dfe5e4..c3a8a68 100644 --- a/tests/e2e/test_match_waiting_e2e.py +++ b/tests/e2e/test_match_waiting_e2e.py @@ -68,7 +68,7 @@ FLOW = """(async () => {@HELPERS@ } return send(path, init); }; - const card = () => document.querySelector("#main .match-card.front"); + const card = () => document.querySelector("#main .match-card.front:not(.match-release-card)"); if (!(await until(card, 8000))) { return {error: text(document.getElementById("main"))}; } diff --git a/tests/e2e/test_match_wasd_e2e.py b/tests/e2e/test_match_wasd_e2e.py new file mode 100644 index 0000000..3adcc51 --- /dev/null +++ b/tests/e2e/test_match_wasd_e2e.py @@ -0,0 +1,111 @@ +from __future__ import annotations + +import json +import os +import shutil +import sys +import unittest +from pathlib import Path +from unittest import mock + +HERE = Path(__file__).resolve().parent +sys.path[:0] = [str(HERE.parent), str(HERE)] + +import test_match_release_card_e2e as deck +from kvb_orchestrator import batches + +OUT = Path(os.environ.get("E2E_OUT", "/tmp/hub-055-shots")) +WASD = """(async () => {@HELPERS@@CARD@@STEPS@ + await screenShown(8000); + if (!(await until(card, 8000))) { + return {error: text(document.getElementById("main")).slice(0, 300)}; + } + await sleep(300); + const front = () => (card() ? card().dataset.card : null); + const tally = () => text(document.querySelector("#main .match-tally")); + const press = async (name) => { + const was = front(); + key(name); + await until(() => front() !== was, 3000); + await sleep(250); + return front(); + }; + const seen = [front()]; + seen.push(await press("d")); + seen.push(await press("w")); + seen.push(await press("d")); + const decided = tally(); + const undone = [await press("s"), await press("s"), await press("s")]; + const cleared = tally(); + for (let tries = 0; tries < 4 && !card().querySelector(".match-file tr[data-line]"); tries += 1) { + await press("w"); + } + const row = card().querySelector(".match-file tr[data-line]"); + let typed = null; + if (row) { + const spot = row.getBoundingClientRect(); + row.dispatchEvent(new MouseEvent("contextmenu", {bubbles: true, cancelable: true, clientX: spot.left + 40, clientY: spot.top + 4, button: 2})); + const field = await until(() => card().querySelector(".match-comment textarea"), 3000); + const was = front(); + field.focus(); + field.dispatchEvent(new KeyboardEvent("keydown", {key: "d", bubbles: true, cancelable: true})); + await sleep(500); + typed = {front: front() === was, tally: tally()}; + card().querySelector(".match-comment .btn.ghost").click(); + } + key("a"); + const sheet = Boolean(await until(() => document.querySelector(".sheet-box .match-feedback"), 3000)); + document.querySelector(".sheet-box .btn.ghost").click(); + await sleep(300); + for (let tries = 0; tries < 4 && (front() === "@RED@" || card().dataset.stale === "true"); tries += 1) { + await press("w"); + } + await press("d"); + const lap = [front()]; + for (let step = 0; step < 8; step += 1) { + lap.push(await press("w")); + } + while (front() !== "release") { + await press("w"); + } + const onRelease = {a: await press("a")}; + document.querySelector("#main .match-open-overview").click(); + await until(releasing, 3000); + onRelease.w = await press("w"); + onRelease.s = await press("s"); + window.e2eSubmits.length = 0; + key("d"); + await until(() => window.e2eSubmits.length, 20000); + onRelease.d = window.e2eSubmits; + return {seen, decided, undone, cleared, typed, sheet, lap, onRelease}; +})()""" + + +@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium") +class TestMatchWasd(deck.ReleaseDeck): + def test_chromium_runs_the_deck_with_wasd_undoes_step_by_step_and_brings_the_release_card_once_a_lap(self): + OUT.mkdir(parents=True, exist_ok=True) + step = {"width": 1920, "height": 1080, "url": f"{self.base}?wasd#tasks/match", "wait": 1500, "shot": str(OUT / "chromium-wasd.png"), "probe": deck.probe(WASD, red=f"review:{self.red}")} + with mock.patch.object(batches, "UNDO", 0.3): + data = self.drive([step], self.authenticator(), init=deck.INIT) + (OUT / "chromium-wasd.json").write_text(json.dumps(data, indent=1), encoding="utf-8") + self.assertEqual([error for error in data["errors"] if "/favicon.ico" not in error], []) + found = data["results"][0] + self.assertNotIn("error", found, found) + first, second, third, _ = found["seen"] + self.assertEqual(found["decided"], "2", found) + self.assertEqual(found["undone"], [third, second, first], found) + self.assertEqual(found["cleared"], "0", found) + self.assertEqual(found["typed"], {"front": True, "tally": "0"}, found) + self.assertTrue(found["sheet"], found) + lap = found["lap"] + period = lap.index(lap[0], 1) + self.assertEqual(lap[period:], lap[: len(lap) - period], found) + self.assertEqual(lap[:period].count("release"), 1, found) + self.assertNotIn("release", [found["onRelease"]["a"], found["onRelease"]["w"]], found) + self.assertEqual(found["onRelease"]["s"], "release", found) + self.assertEqual(len(found["onRelease"]["d"]), 1, found) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/e2e/test_menus_stay_open_e2e.py b/tests/e2e/test_menus_stay_open_e2e.py new file mode 100644 index 0000000..987d79d --- /dev/null +++ b/tests/e2e/test_menus_stay_open_e2e.py @@ -0,0 +1,82 @@ +from __future__ import annotations + +import json +import os +import shutil +import sys +import unittest +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path[:0] = [str(HERE.parent), str(HERE)] + +import hub_e2e_kit as base + +OUT = Path(os.environ.get("E2E_OUT", "/tmp/hub-050-shots")) +MENU = """(async () => {@HELPERS@ + const menu = await until(() => document.querySelector("#main .stream-head details.menu"), 8000); + if (!menu) { + return {error: text(document.getElementById("main")).slice(0, 300)}; + } + const open = async () => { + if (!menu.open) { + menu.querySelector("summary").click(); + } + await until(() => menu.open, 2000); + }; + const chips = () => all('.menu-box [aria-label="Kinds"] .chip', menu); + const states = () => chips().map((chip) => chip.getAttribute("aria-pressed")); + const leave = () => menu.dispatchEvent(new PointerEvent("pointerleave", {pointerType: "mouse"})); + const enter = () => menu.dispatchEvent(new PointerEvent("pointerenter", {pointerType: "mouse"})); + await open(); + const before = states(); + for (const index of [0, 1, 2]) { + chips()[index].click(); + await sleep(300); + } + const after = states(); + const kept = menu.open; + leave(); + await sleep(2500); + const at25 = menu.open; + await sleep(1000); + const at35 = menu.open; + await open(); + leave(); + await sleep(2000); + enter(); + await sleep(1500); + const back = menu.open; + document.getElementById("main").click(); + await sleep(50); + const outside = menu.open; + await open(); + document.body.dispatchEvent(new KeyboardEvent("keydown", {key: "Escape", bubbles: true, cancelable: true})); + await sleep(50); + const escaped = menu.open; + await open(); + return {before, after, kept, at25, at35, back, outside, escaped}; +})()""" + + +@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium") +class TestMenusStayOpen(base.OrchestratorE2ECase): + def setUp(self): + super().setUp() + OUT.mkdir(parents=True, exist_ok=True) + + def test_chromium_keeps_the_stream_filter_open_through_chip_clicks_and_closes_it_3_s_after_the_pointer_left(self): + step = {"width": 1920, "height": 1080, "url": f"{self.base}?menu#stream", "wait": 1500, "probe": MENU.replace("@HELPERS@", base.HELPERS), "shot": str(OUT / "chromium-1920-filter-menu.png")} + data = self.drive([step], None) + (OUT / "chromium-menu.json").write_text(json.dumps(data, indent=1), encoding="utf-8") + self.assertEqual([error for error in data["errors"] if "/favicon.ico" not in error], []) + found = data["results"][0] + self.assertNotIn("error", found, found) + self.assertEqual(len(found["before"]), len(found["after"]), found) + self.assertEqual([found["before"][index] != found["after"][index] for index in range(3)], [True, True, True], found) + self.assertEqual((found["kept"], found["at25"], found["at35"], found["back"]), (True, True, False, True), found) + self.assertEqual((found["outside"], found["escaped"]), (False, False), found) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/e2e/test_mic_frames_e2e.py b/tests/e2e/test_mic_frames_e2e.py index fd77681..8dc485b 100644 --- a/tests/e2e/test_mic_frames_e2e.py +++ b/tests/e2e/test_mic_frames_e2e.py @@ -28,12 +28,16 @@ SCAN = """ const line = frame.classList.contains("mic-line"); const [outer, mic, text] = [frame.getBoundingClientRect(), button.getBoundingClientRect(), field.getBoundingClientRect()]; const foot = line ? null : frame.querySelector(":scope > .mic-foot"); + const tail = line ? [...frame.children].slice([...frame.children].indexOf(button) + 1) : []; + const end = line ? frame.lastElementChild.getBoundingClientRect() : null; + const spans = (box) => Math.abs(box.top - outer.top - 1) <= 1 && Math.abs(outer.bottom - 1 - box.bottom) <= 1; return { - id: field.id, framed: true, line, - last: line ? frame.lastElementChild === button : Boolean(foot) && foot.lastElementChild === button && field.nextElementSibling === foot, - fits: line ? Math.abs(mic.top - outer.top - 1) <= 1 && Math.abs(outer.bottom - 1 - mic.bottom) <= 1 && Math.abs(outer.right - 1 - mic.right) <= 1 : mic.bottom <= outer.bottom && mic.top >= text.bottom - 1, + id: field.id, label: field.getAttribute("aria-label") || "", framed: true, line, + last: line ? field.nextElementSibling === button && tail.every((node) => node.matches("button[type=submit]")) : Boolean(foot) && button.parentElement === foot && field.nextElementSibling === foot && [...foot.children].slice([...foot.children].indexOf(button) + 1).every((node) => node.matches(".ptt-split, .mayday-toggle")), + fits: line ? spans(mic) && Math.abs(outer.right - 1 - end.right) <= 1 : mic.bottom <= outer.bottom && mic.top >= text.bottom - 1, divider: line ? getComputedStyle(button).borderLeftWidth : getComputedStyle(foot).borderTopWidth, clear: line ? text.right <= mic.left + 0.5 : true, + send: tail.map((node) => ({fits: spans(node.getBoundingClientRect()), divider: getComputedStyle(node).borderLeftWidth, own: getComputedStyle(node).borderTopWidth})), }; }); const ring = (field) => { @@ -46,7 +50,13 @@ SCAN = """ STREAM = """(async () => {@HELPERS@@SCAN@ const field = await until(() => document.querySelector('#main input[type="search"]'), 15000); await until(() => field.closest(".mic-frame"), 4000); - return {mics: scan(), ring: ring(field), wide: wide()}; + const other = await until(() => document.querySelector("#main .option.other .mic-frame"), 8000); + const extra = document.body.appendChild(document.createElement("textarea")); + await sleep(100); + extra.remove(); + await sleep(100); + const sends = other.closest("form").querySelectorAll("button[type=submit]").length; + return {mics: scan(), sends, ring: ring(field), wide: wide()}; })()""" RULES = """(async () => {@HELPERS@@SCAN@ (await until(() => document.getElementById("controls-tab-rules"), 15000)).click(); @@ -58,10 +68,11 @@ RADIO = """(async () => {@HELPERS@@SCAN@ await until(() => area.closest(".mic-frame"), 4000); const foot = area.closest(".mic-frame").querySelector(".mic-foot"); const first = foot.firstElementChild; - const idle = getComputedStyle(foot.lastElementChild).backgroundColor; - foot.lastElementChild.setAttribute("aria-pressed", "true"); - const recording = getComputedStyle(foot.lastElementChild).backgroundColor; - foot.lastElementChild.setAttribute("aria-pressed", "false"); + const mic = foot.querySelector(":scope > button.mic"); + const idle = getComputedStyle(mic).backgroundColor; + mic.setAttribute("aria-pressed", "true"); + const recording = getComputedStyle(mic).backgroundColor; + mic.setAttribute("aria-pressed", "false"); area.style.height = "260px"; await sleep(100); const after = scan().find((entry) => entry.id === area.id); @@ -87,6 +98,8 @@ class TestMicFrames(HubCase): super().setUp() OUT.mkdir(parents=True, exist_ok=True) self.claim("s1", "Skills") + decided = self.tool("decision_request", {"question": "Merge the mic frames?", "options": hub_support.OPTIONS, "agent": "Skills", "recommended": ""}) + self.assertFalse(decided["isError"], decided) self.snapshot() self.page_url = f"http://localhost:{self.port}/" @@ -117,6 +130,9 @@ class TestMicFrames(HubCase): self.assertNotIn("error", found, found) self.check_mics(found["mics"]) self.assertFalse(found["wide"]) + other = [entry for entry in stream["mics"] if entry["label"].startswith("Other answer to ")] + self.assertEqual([entry["send"] for entry in other], [[{"fits": True, "divider": "1px", "own": "0px"}]], other) + self.assertEqual(stream["sends"], 1) self.assertEqual(stream["ring"], ["solid", "none"]) self.assertEqual(radio["ring"], ["solid", "none"]) self.assertEqual(radio["record"], "Record") diff --git a/tests/e2e/test_notification_channels_e2e.py b/tests/e2e/test_notification_channels_e2e.py index 062f1e8..214b0da 100644 --- a/tests/e2e/test_notification_channels_e2e.py +++ b/tests/e2e/test_notification_channels_e2e.py @@ -1,9 +1,11 @@ from __future__ import annotations +import datetime import json import os import shutil import sys +import time import unittest from pathlib import Path @@ -24,64 +26,103 @@ LABELS = [ ("channel-aloud", "Read radio aloud"), ("channel-title", "Waiting count in the tab title"), ] +SOURCES = [("resources", "Resource warnings"), ("mayday", "MAYDAY calls"), ("dream", "Dream reminder")] ON = {"browser": True, "sounds": True, "aloud": True, "title": True} +SECTIONS = ["Ambience", "Location", "Appearance", "Music", "Undo window", "Passkey"] KIT = """ const boxes = (group) => all("input[type=checkbox]", group).map((box) => [box.name, box.checked, words(box.closest("label"))]); + const rows = (fold) => all(".notify-source", fold).map((row) => [row.dataset.source, row.dataset.state, words(row.querySelector("label")), text(row.querySelector(".notify-state")), all("button", row).map(text)]); + const stored = async () => (await (await fetch("/api/state", {cache: "no-store"})).json()).settings; + const fold = async () => { + location.hash = "#stream/radio"; + const notify = await until(() => document.querySelector("#radio-spot details.radio-notify"), 8000); + if (notify && !notify.open) { + notify.querySelector("summary").click(); + await sleep(400); + } + const group = notify ? await until(() => notify.querySelector("fieldset.channels"), 8000) : null; + return {notify, group}; + }; const sheet = async () => { document.getElementById("settings-open").click(); const form = await until(() => document.querySelector(".sheet-box form.settings"), 8000); - const group = form ? form.querySelector("fieldset.channels") : null; - if (group) { - group.scrollIntoView({block: "center"}); - await sleep(300); + const found = form ? {sections: all("section > h3", form).map(text), channels: all("fieldset.channels, .notify-source", form).length} : null; + if (form) { + all("button", form).find((button) => text(button) === "Cancel").click(); + await until(() => !document.querySelector(".sheet-box form.settings"), 8000); } - return {form, group}; + return found; }; - const look = (form, group) => { - const box = group.getBoundingClientRect(); + const look = (notify, group) => { + const layer = notify.querySelector(".station-body").getBoundingClientRect(); return { - legend: text(group.querySelector("legend")), boxes: boxes(group), sections: all("section > h3", form).map(text), clashes: clashes(form), - inside: box.left >= -1 && box.right <= innerWidth + 1, wide: document.documentElement.scrollWidth > innerWidth + 1, + legend: text(group.querySelector("legend")), boxes: boxes(group), sources: rows(notify), clashes: clashes(notify.querySelector(".station-body")), + inDevice: Boolean(notify.closest(".radio-device > .radio-settings")), stations: Boolean(notify.closest(".radio-settings").querySelector("details.radio-station")), + inside: layer.left >= -1 && layer.right <= innerWidth + 1, wide: document.documentElement.scrollWidth > innerWidth + 1, }; }; - const save = async (group, on) => { - for (const box of all("input[type=checkbox]", group)) { + const save = async (on) => { + for (const name of @NAMES@) { + const {group} = await fold(); + const box = group.querySelector(`input[name="${name}"]`); if (box.checked !== on) { box.click(); } + const key = name.replace("channel-", ""); + const end = Date.now() + 8000; + while (Date.now() < end && (await stored()).channels[key] !== on) { + await sleep(200); + } } - const shown = boxes(group); - group.closest("form").querySelector('button[type="submit"]').click(); - const closed = Boolean(await until(() => !document.querySelector(".sheet-box form.settings"), 8000)); + const {group} = await fold(); const titled = Boolean(await until(() => (on ? /@TITLED@/.test(document.title) : document.title === "@PLAIN@"), 8000)); - const stored = (await (await fetch("/api/state", {cache: "no-store"})).json()).settings.channels; - return {shown, closed, titled, title: document.title, stored}; + return {shown: boxes(group), titled, title: document.title, stored: (await stored()).channels}; }; """ OPENED = """(async () => {@HELPERS@@OVERLAP@@KIT@ await screenShown(8000); await until(() => /@TITLED@/.test(document.title), 8000); const title = document.title; - const {form, group} = await sheet(); - return group ? {title, ...look(form, group)} : {error: text(document.querySelector(".sheet-box")), title}; + const general = await sheet(); + const {notify, group} = await fold(); + return group ? {title, general, ...look(notify, group)} : {error: "no channel group in the Device card", title}; })()""" SWITCHED = """(async () => {@HELPERS@@OVERLAP@@KIT@ - const group = document.querySelector(".sheet-box fieldset.channels"); - return group ? save(group, @ON@) : {error: "no channel group"}; + return save(@ON@); })()""" SAVED_ON = """(async () => {@HELPERS@@OVERLAP@@KIT@ - const group = document.querySelector(".sheet-box fieldset.channels"); - if (!group) { - return {error: "no channel group"}; - } - const saved = await save(group, true); - const again = await sheet(); + const saved = await save(true); + document.querySelector("#radio-spot details.radio-notify").open = false; + await sleep(300); + const again = await fold(); return {...saved, reopened: again.group ? boxes(again.group) : null}; })()""" +SNOOZED = """(async () => {@HELPERS@@OVERLAP@@KIT@ + await screenShown(8000); + const {notify} = await fold(); + const row = (id) => notify.querySelector(`.notify-source[data-source="${id}"]`); + const button = (id, label) => all("button", row(id)).find((item) => text(item) === label); + const wait = async (id, state) => Boolean(await until(() => row(id) && row(id).dataset.state === state, 8000)); + const before = rows(notify); + const titles = all(".notify-source button", notify).map((item) => item.getAttribute("title")); + button("resources", "1 h").click(); + const hour = await wait("resources", "snoozed"); + const snoozed = rows(notify); + row("mayday").querySelector('input[type="checkbox"]').click(); + const off = await wait("mayday", "off"); + button("dream", "8:00").click(); + const morning = await wait("dream", "snoozed"); + const after = rows(notify); + const dream = (await stored()).popups.dream; + button("dream", "Resume").click(); + const resumed = await wait("dream", "on"); + return {before, titles, hour, snoozed, off, morning, after, dream, resumed, last: rows(notify), popups: (await stored()).popups, toasts: all("#toasts .toast").map(text)}; +})()""" def fill(probe: str) -> str: - return probe.replace("@HELPERS@", base.HELPERS).replace("@OVERLAP@", base.OVERLAP).replace("@KIT@", KIT).replace("@TITLED@", TITLED).replace("@PLAIN@", PLAIN) + names = json.dumps([name for name, _ in LABELS]) + return probe.replace("@HELPERS@", base.HELPERS).replace("@OVERLAP@", base.OVERLAP).replace("@KIT@", KIT).replace("@NAMES@", names).replace("@TITLED@", TITLED).replace("@PLAIN@", PLAIN) @unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium") @@ -97,7 +138,7 @@ class TestNotificationChannels(HubCase): def legacy(self) -> None: file = self.state / "settings.json" - older = {key: value for key, value in settings.SETTINGS.items() if key != "channels"} + older = {key: value for key, value in settings.SETTINGS.items() if key not in ("channels", "popups")} file.write_text(json.dumps({**older, "notify": False}), encoding="utf-8") held = self.httpd.hub.settings with held.lock: @@ -118,17 +159,18 @@ class TestNotificationChannels(HubCase): self.assertNotIn("error", found, found) self.assertEqual(data["errors"], []) self.assertRegex(opened["title"], TITLED) + self.assertEqual(opened["general"], {"sections": SECTIONS, "channels": 0}) self.assertEqual((opened["legend"], opened["boxes"]), ("Notification channels", [[name, name != "channel-browser", label] for name, label in LABELS])) - self.assertEqual(opened["sections"], ["Ambience", "Location", "Appearance", "Music", "Notifications", "Passkey"]) - self.assertEqual((opened["clashes"], opened["inside"], opened["wide"]), ({"found": [], "outside": []}, True, False), opened) - self.assertEqual((off["shown"], off["closed"], off["titled"], off["title"], off["stored"]), ([[name, False, label] for name, label in LABELS], True, True, PLAIN, dict.fromkeys(ON, False)), off) + self.assertEqual([row[:3] for row in opened["sources"]], [[source, "on", label] for source, label in SOURCES]) + self.assertEqual((opened["inDevice"], opened["stations"], opened["clashes"], opened["inside"], opened["wide"]), (True, True, {"found": [], "outside": []}, True, False), opened) + self.assertEqual((off["shown"], off["titled"], off["title"], off["stored"]), ([[name, False, label] for name, label in LABELS], True, PLAIN, dict.fromkeys(ON, False)), off) self.assertEqual((reloaded["title"], reloaded["boxes"], reloaded["clashes"]), (PLAIN, [[name, False, label] for name, label in LABELS], {"found": [], "outside": []}), reloaded) - self.assertEqual((back["closed"], back["titled"], back["stored"], back["reopened"]), (True, True, ON, [[name, True, label] for name, label in LABELS]), back) + self.assertEqual((back["titled"], back["stored"], back["reopened"]), (True, ON, [[name, True, label] for name, label in LABELS]), back) self.assertRegex(back["title"], TITLED) written = json.loads((self.state / "settings.json").read_text(encoding="utf-8")) self.assertEqual((written["channels"], "notify" in written), (ON, False)) - def test_chromium_migrates_the_old_notify_flag_and_switches_every_channel_off_and_on_through_a_reload_at_three_widths(self): + def test_chromium_migrates_the_old_notify_flag_and_switches_every_channel_off_and_on_in_the_device_card_through_a_reload_at_three_widths(self): authenticator = self.authenticator() for width, height in base.WIDTHS: with self.subTest(width=width): @@ -137,6 +179,34 @@ class TestNotificationChannels(HubCase): (OUT / f"chromium-{width}-channels.json").write_text(json.dumps(data, indent=1), encoding="utf-8") self.check(data) + def test_chromium_snoozes_mutes_and_resumes_each_gnome_popup_source_and_writes_notify_json(self): + page = f"http://localhost:{self.port}/?popups" + started = time.time() + data = self.drive([{"width": 1366, "height": 900, "url": f"{page}#stream", "wait": 1200, "probe": fill(SNOOZED), "shot": str(OUT / "chromium-popups.png")}], self.authenticator()) + (OUT / "chromium-popups.json").write_text(json.dumps(data, indent=1), encoding="utf-8") + self.assertEqual(data["errors"], []) + found = data["results"][0] + self.assertNotIn("error", found, found) + self.assertEqual([row[:3] for row in found["before"]], [[source, "on", label] for source, label in SOURCES]) + self.assertEqual([row[4] for row in found["before"]], [["1 h", "8:00"]] * 3) + self.assertTrue(all(title.split(": ")[0] in dict(SOURCES).values() for title in found["titles"]), found["titles"]) + self.assertEqual((found["hour"], found["off"], found["morning"], found["resumed"]), (True, True, True, True), found) + resources = found["snoozed"][0] + self.assertEqual((resources[1], resources[4]), ("snoozed", ["Resume", "1 h", "8:00"])) + self.assertRegex(resources[3], r"^snoozed until \d\d:\d\d$") + self.assertEqual(found["after"][1][1:], ["off", "MAYDAY calls", "off", []]) + self.assertEqual(found["last"][2][1], "on") + popups = found["popups"] + self.assertEqual((popups["mayday"], popups["dream"]), ({"on": False, "until": 0}, {"on": True, "until": 0})) + self.assertTrue(popups["resources"]["on"]) + self.assertLessEqual(abs(popups["resources"]["until"] - (started + 3600)), 120, popups) + written = json.loads((self.council / settings.NOTIFY).read_text(encoding="utf-8")) + self.assertEqual(written, popups) + morning = datetime.datetime.fromtimestamp(found["dream"]["until"]) + self.assertEqual((found["dream"]["on"], morning.hour, morning.minute, morning.second), (True, 8, 0, 0), found["dream"]) + self.assertLess(started, found["dream"]["until"]) + self.assertLessEqual(found["dream"]["until"] - started, 33 * 3600) + if __name__ == "__main__": unittest.main() diff --git a/tests/e2e/test_one_code_box_e2e.py b/tests/e2e/test_one_code_box_e2e.py new file mode 100644 index 0000000..f5ca6cd --- /dev/null +++ b/tests/e2e/test_one_code_box_e2e.py @@ -0,0 +1,157 @@ +from __future__ import annotations + +import json +import os +import shutil +import sys +import unittest +from pathlib import Path +from unittest import mock + +HERE = Path(__file__).resolve().parent +sys.path[:0] = [str(HERE.parent), str(HERE)] + +import hub_e2e_kit as base +from hub_support import ASK +from kvb_orchestrator import batches + +OUT = Path(os.environ.get("E2E_OUT", "/tmp/hub-047-shots")) +LONG = "\n".join(f"echo line {number}" for number in range(1, 201)) +SHIP = "make ship " + " ".join(f"ARG{number}=value" for number in range(40)) +KIT = """ + const press = async (button) => { + button.click(); + await sleep(250); + return button.getAttribute("aria-expanded"); + }; + const look = (box) => { + const body = box.querySelector(".code-body"); + const foot = box.querySelector(".code-foot"); + return { + last: box.lastElementChild === foot, foot: all("button", foot).map(name), expanded: foot.querySelector(".code-eye").getAttribute("aria-expanded"), + clipped: body.scrollHeight > body.clientHeight + 1, + }; + }; + const toggle = async (box) => { + const eye = box.querySelector(".code-eye"); + const first = {...look(box)}; + const opened = await press(eye); + const full = {expanded: opened, clipped: look(box).clipped}; + const closed = await press(eye); + return {first, full, closed: {expanded: closed, clipped: look(box).clipped}}; + }; + const loose = (selector) => all(selector).filter((node) => !node.closest(".code-box")).length; +""" +STREAM = """(async () => {@HELPERS@@KIT@ + await streamShowsAll(); + const rowOf = () => document.querySelector('#main .feed > li[data-ref="@ASK@"]'); + const reviewOf = () => all("#main .feed > li.k-review").find((li) => !li.classList.contains("waiting") && text(li).includes("@REVIEW_TITLE@")); + await until(() => rowOf() && reviewOf(), 8000); + await sleep(1500); + const [row, review] = [rowOf(), reviewOf()]; + if (!row || !review) { + return {error: text(document.getElementById("main")).slice(0, 300)}; + } + const ask = await toggle(row.querySelector(".code-box")); + const box = review.querySelector(".code-box"); + const before = box ? box.querySelectorAll(".diff-file").length : null; + box.querySelector(".code-eye").click(); + const loaded = Boolean(await until(() => all("#main .feed > li.k-review").find((li) => text(li).includes("@REVIEW_TITLE@") && li.querySelector(".code-box .diff-file")), 8000)); + return {ask, before, loaded, sheet: Boolean(document.querySelector("#sheet:not([hidden])")), loose: loose("#main .command, #main .diff-file"), wide: document.documentElement.scrollWidth > innerWidth + 1}; +})()""" +OPERATOR = """(async () => {@HELPERS@@KIT@ + const row = await until(() => document.querySelector('#main .inbox-list > li[data-ref="@ASK@"]'), 8000); + if (!row) { + return {error: text(document.getElementById("main")).slice(0, 300)}; + } + return {ask: await toggle(row.querySelector(".code-box")), loose: loose("#main .command, #main .diff-file"), wide: document.documentElement.scrollWidth > innerWidth + 1}; +})()""" +MATCH = """(async () => {@HELPERS@@KIT@ + const front = () => document.querySelector("#main .match-card.front"); + await until(front, 8000); + for (let tries = 0; tries < 12 && front() && front().dataset.card !== "@ASK@"; tries += 1) { + const id = front().dataset.card; + document.body.dispatchEvent(new KeyboardEvent("keydown", {key: "w", bubbles: true, cancelable: true})); + await until(() => front() && front().dataset.card !== id, 3000); + await sleep(200); + } + const card = front(); + if (!card || card.dataset.card !== "@ASK@") { + return {error: card ? card.dataset.card : "no card"}; + } + const box = card.querySelector(".code-box"); + const body = card.querySelector(".match-body"); + return {box: look(box), place: box.dataset.place, scrolls: body.scrollHeight > body.clientHeight + 1, overflowY: getComputedStyle(body).overflowY, + page: document.documentElement.scrollHeight > innerHeight + 1, loose: loose("#main .match-command, #main .match-file")}; +})()""" +TASKS = """(async () => {@HELPERS@@KIT@ + const row = await until(() => document.querySelector('#main li[data-task="operator/ship"]'), 8000); + if (!row) { + return {error: text(document.getElementById("main")).slice(0, 300)}; + } + const box = row.querySelector(".code-box"); + const first = look(box); + box.querySelector(".code-eye").click(); + const sheet = await until(() => document.querySelector('#sheet:not([hidden]) .code-box[data-place="sheet"]'), 4000); + const full = sheet ? text(sheet) : null; + document.dispatchEvent(new KeyboardEvent("keydown", {key: "Escape", bubbles: true})); + const closed = Boolean(await until(() => !document.querySelector("#sheet:not([hidden])"), 4000)); + return {place: box.dataset.place, first, full, closed, loose: loose("#main .command, #main .diff-file")}; +})()""" + + +@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium") +class TestOneCodeBox(base.OrchestratorE2ECase): + def setUp(self): + super().setUp() + OUT.mkdir(parents=True, exist_ok=True) + self.ask =f"ask:{self.create_ask({**ASK, 'command': LONG, 'timeout': 3600})}" + register = json.loads((self.council / "rasci.json").read_text(encoding="utf-8")) + register["operator/ship"] = {"title": SHIP, "workdir": "/repo", "status": "running", "roles": {"Operator": "R"}} + self.write_council({"rasci.json": register}) + diff = [{"path": "src/box.py", "status": "M", "mode": "100644", "additions": 1, "deletions": 0, "patch": "@@ -1,1 +1,2 @@\n line 1\n+box line", "note": ""}] + self.review_title = "feat: decided box" + arguments = {**self.arguments(self.review_title, "", self.page("box.html", "p")), "worktree": "/repo/.worktrees/feature/box", "branch": "feature/box", "agent": "Stage", "diff": diff} + review = self.tool("review_request", arguments)["structuredContent"]["id"] + entries = [self.entry("review", review, "", "")] + with mock.patch.object(batches, "UNDO", 0.05): + self.assertEqual(self.approve(entries, self.signed(entries, self.pin()))[0], 202) + self.settle(lambda: self.status(review) == "approved") + + def fill(self, probe: str) -> str: + return probe.replace("@HELPERS@", base.HELPERS).replace("@KIT@", KIT).replace("@ASK@", self.ask).replace("@REVIEW_TITLE@", self.review_title) + + def test_chromium_puts_every_command_and_diff_in_one_code_box_whose_eye_toggles_in_place_at_1920_and_390(self): + steps = [] + for width, height in ((1920, 1080), (390, 844)): + page = f"{self.base}?{width}" + steps += [ + {"width": width, "height": height, "url": f"{page}-stream#stream", "wait": 1500, "probe": self.fill(STREAM), "shot": str(OUT / f"chromium-{width}-stream.png")}, + {"width": width, "height": height, "url": f"{page}-operator#tasks/operator", "wait": 1500, "probe": self.fill(OPERATOR), "shot": str(OUT / f"chromium-{width}-operator.png")}, + {"width": width, "height": height, "url": f"{page}-match#tasks/match", "wait": 1500, "probe": self.fill(MATCH), "shot": str(OUT / f"chromium-{width}-match.png")}, + {"width": width, "height": height, "url": f"{page}-tasks#tasks/list", "wait": 1500, "probe": self.fill(TASKS), "shot": str(OUT / f"chromium-{width}-tasks.png")}, + ] + data = self.drive(steps, None) + (OUT / "chromium-code-box.json").write_text(json.dumps(data, indent=1), encoding="utf-8") + self.assertEqual([error for error in data["errors"] if "/favicon.ico" not in error], []) + for index, width in enumerate((1920, 390)): + stream, operator, match, tasks = data["results"][index * 4:index * 4 + 4] + with self.subTest(width=width): + for found in (stream, operator, match, tasks): + self.assertNotIn("error", found, found) + self.assertEqual(found["loose"], 0, found) + for found in (stream["ask"], operator["ask"]): + self.assertEqual((found["first"]["last"], found["first"]["expanded"], found["first"]["clipped"]), (True, "false", True), found) + self.assertEqual(found["first"]["foot"][:2], ["Copy", "Show all"], found) + self.assertTrue({"Grant", "Deny"} <= set(found["first"]["foot"]), found) + self.assertEqual(found["full"], {"expanded": "true", "clipped": False}, found) + self.assertEqual(found["closed"], {"expanded": "false", "clipped": True}, found) + self.assertEqual((stream["before"], stream["loaded"], stream["sheet"], stream["wide"], operator["wide"]), (0, True, False, False, False), stream) + self.assertEqual((match["place"], match["box"]["expanded"], match["box"]["last"], match["box"]["foot"]), ("open", "true", True, ["Copy", "Show less"]), match) + self.assertEqual((match["scrolls"], match["overflowY"], match["page"]), (True, "auto", False), match) + self.assertEqual((tasks["place"], tasks["first"]["expanded"], tasks["closed"]), ("closed", "false", True), tasks) + self.assertIn(SHIP, tasks["full"], tasks) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/e2e/test_orchestrator_e2e.py b/tests/e2e/test_orchestrator_e2e.py index 1b07192..a549dff 100644 --- a/tests/e2e/test_orchestrator_e2e.py +++ b/tests/e2e/test_orchestrator_e2e.py @@ -205,12 +205,12 @@ class TestOrchestratorE2E(base.OrchestratorE2ECase): self.assertEqual(actions["keys"], ["#agents/chord", "#artifacts/tree", "#tasks/3d", "#home", "#stream"]) self.assertEqual(actions["ambience"], ["sky-look", "music-toggle", "leitstand", "notify"]) self.assertEqual((actions["settingsUnlabelled"], actions["popupUnlabelled"]), (0, 0)) - self.assertEqual((actions["sections"], actions["radioFields"]), (["Ambience", "Location", "Appearance", "Music", "Notifications", "Passkey"], 0)) + self.assertEqual((actions["sections"], actions["radioFields"]), (["Ambience", "Location", "Appearance", "Music", "Undo window", "Passkey"], 0)) for tool in ("Radio …", "Cancel mayday", "Priority …", "Drain", "Suspend", "Resume", "Controls …", "Settings …", "Look at the sky", "Toggle control room", "Enable notifications"): with self.subTest(tool=tool): self.assertTrue(any(tool in entry for entry in actions["palette"]), actions["palette"]) self.assertEqual(actions["popup"], [["post", True], ["call", False]]) - self.assertEqual(actions["centred"], [True, "none"]) + self.assertEqual(actions["leader"], [True, "inline"]) calm, chips = extra[4:] self.assertRegex(calm["note"], r"Force · without motion \(prefers-reduced-motion\)$") self.assertEqual({key: value for key, value in chips["inbox"].items() if key != "counted"}, {"hash": "#tasks/operator", "items": chips["inbox"]["counted"], "pressed": "true", "current": ["Tasks"]}) diff --git a/tests/e2e/test_pin_by_menu_e2e.py b/tests/e2e/test_pin_by_menu_e2e.py new file mode 100644 index 0000000..beee8e8 --- /dev/null +++ b/tests/e2e/test_pin_by_menu_e2e.py @@ -0,0 +1,124 @@ +from __future__ import annotations + +import json +import os +import shutil +import sys +import unittest +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path[:0] = [str(HERE.parent), str(HERE)] + +import hub_e2e_kit as base +import test_box_heads_e2e as heads +import test_home_bookmarks_e2e as bm +import test_home_dashboard_e2e as dash +import test_match_review_e2e as matched +import test_workbench_w4_e2e as w4 +from hub_case import HubCase + +OUT = Path(os.environ.get("E2E_OUT", "/tmp/pin-by-menu-shots")) +OLD = {"kind": "panel", "id": "tasks/list", "w": 6, "h": 4} +SEED = f"""(async () => {{ + await ViewStore.update("home.pins", () => [{json.dumps(OLD)}]); + return true; +}})()""" +VIEW = """(async () => {@HELPERS@ + await screenShown(8000); + await sleep(600); + return {owners: all("#main [data-panel], #main [data-item]").length, stars: all(".star, .star-row").length, slots: all("[data-star-slot]").length}; +})()""" +MENU = """(async () => {@HELPERS@@HOME@ + const read = async (hash, selector) => { + await go(hash); + const owner = await until(() => document.querySelector(selector), 8000); + if (!owner) { + return {error: hash}; + } + const spotOf = (node) => [...node.children].find((child) => child.closest("[data-panel], [data-item]") === node) || node; + const label = async () => { + const live = document.querySelector(selector); + const item = live ? await pinItem(spotOf(live)) : null; + return [item ? menuLabel(item) : null, item]; + }; + const [before, item] = await label(); + if (item) { + item.click(); + await sleep(800); + } + const target = Panels.targetOf(owner); + const added = stored().includes(`${target.kind}:${target.id}`); + const [after] = await label(); + await closeMenu(); + return {before, added, after}; + }; + return {gantt: await read("tasks/gantt", '#main [data-panel="tasks/gantt"]'), stream: await read("stream", '#main [data-panel="stream"]')}; +})()""" +TILES = """(async () => {@HELPERS@@HOME@ + await go("home"); + await until(() => tile("panel:tasks/list") && tile("panel:tasks/gantt") && tile("panel:stream"), 8000); + await sleep(400); + return {tiles: tiles(), stars: all(".star, .star-row").length, slots: all("[data-star-slot]").length}; +})()""" + + +def probe(template: str) -> str: + return template.replace("@HELPERS@", base.HELPERS).replace("@HOME@", dash.HOME) + + +@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium") +class TestPinByMenu(HubCase): + seed = base.OrchestratorE2ECase.seed + subagents = base.OrchestratorE2ECase.subagents + drive = base.OrchestratorE2ECase.drive + cards = matched.TestMatchReview.cards + review = matched.TestMatchReview.review + payload = matched.TestMatchReview.payload + + def setUp(self): + super().setUp() + OUT.mkdir(parents=True, exist_ok=True) + self.seed() + self.cards() + + def steps(self) -> list[dict]: + steps = [] + for width, height in base.WIDTHS: + at = {"width": width, "height": height} + shot = OUT / f"chromium-{width}" + steps += [ + {**at, "url": f"{self.base}?{width}-clear#stream", "wait": 600, "probe": bm.CLEAR, "shot": None}, + {**at, "url": f"{self.base}?{width}-seed#stream", "wait": 800, "probe": SEED, "shot": None}, + ] + steps += [{**at, "url": f"{self.base}?{width}-{view.replace('/', '-')}#{view}", "wait": 1500, "probe": probe(VIEW), "shot": f"{shot}-{view.replace('/', '-')}.png"} for view in heads.VIEWS] + steps += [ + {**at, "url": None, "wait": 0, "probe": probe(MENU), "shot": f"{shot}-menu.png"}, + {**at, "url": None, "wait": 0, "probe": probe(TILES), "shot": f"{shot}-home.png"}, + ] + return steps + + def test_chromium_shows_no_star_and_pins_and_unpins_through_the_context_menu_keeping_an_old_pin(self): + data = self.drive(self.steps(), None, init=w4.GUARD) + (OUT / "chromium-pin-by-menu.json").write_text(json.dumps(data, indent=1), encoding="utf-8") + self.assertEqual([error for error in data["errors"] if "/favicon.ico" not in error], []) + results = iter(data["results"]) + for width, _ in base.WIDTHS: + next(results) + next(results) + views = {view: next(results) for view in heads.VIEWS} + menu = next(results) + home = next(results) + with self.subTest(width=width, step="views"): + self.assertEqual({view: (row["stars"], row["slots"]) for view, row in views.items()}, dict.fromkeys(heads.VIEWS, (0, 0)), views) + self.assertGreater(sum(row["owners"] for row in views.values()), 0, views) + with self.subTest(width=width, step="menu"): + pinned = {"before": "Pin to Home", "added": True, "after": "Unpin from Home"} + self.assertEqual((menu["gantt"], menu["stream"]), (pinned, pinned), menu) + with self.subTest(width=width, step="home"): + self.assertEqual(home["tiles"], ["panel:tasks/list", "panel:tasks/gantt", "panel:stream"], home) + self.assertEqual((home["stars"], home["slots"]), (0, 0), home) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/e2e/test_poll_cost_e2e.py b/tests/e2e/test_poll_cost_e2e.py new file mode 100644 index 0000000..e68feb2 --- /dev/null +++ b/tests/e2e/test_poll_cost_e2e.py @@ -0,0 +1,131 @@ +from __future__ import annotations + +import json +import os +import shutil +import sys +import time +import unittest +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path[:0] = [str(HERE.parent), str(HERE)] + +import hub_e2e_kit as base +import test_home_bookmarks_e2e as bm +from hub_case import HubCase + +OUT = Path(os.environ.get("E2E_OUT", "/tmp/hub-059-shots")) +INIT = """() => { + window.e2eViolations = []; + document.addEventListener("securitypolicyviolation", (event) => window.e2eViolations.push(`${event.violatedDirective} ${event.blockedURI}`)); + window.e2eHidden = false; + Object.defineProperty(Document.prototype, "hidden", {configurable: true, get: () => window.e2eHidden}); + window.e2eAudio = {starts: 0, stops: 0}; + const start = OscillatorNode.prototype.start; + const stop = OscillatorNode.prototype.stop; + OscillatorNode.prototype.start = function (...args) { window.e2eAudio.starts += 1; return start.apply(this, args); }; + OscillatorNode.prototype.stop = function (...args) { window.e2eAudio.stops += 1; return stop.apply(this, args); }; +}""" +POLLS = """(async () => {@HELPERS@ + await streamShowsAll(); + const list = await until(() => document.querySelector('#main [data-panel="stream"]') && document.querySelector('#main [data-panel="stream"] li.entry') ? document.querySelector('#main [data-panel="stream"]') : null, 10000); + if (!list) { + return {error: text(document.getElementById("main"))}; + } + await sleep(1500); + const first = list.querySelector("li.entry"); + let replaced = 0; + new MutationObserver((records) => { replaced += records.length; }).observe(list, {childList: true}); + await sleep(11500); + const kept = {connected: first.isConnected, replaced, rows: list.querySelectorAll("li.entry").length}; + const note = document.getElementById("sky-note"); + let sky = 0; + new MutationObserver((records) => { sky += records.length; }).observe(note, {childList: true, characterData: true, subtree: true}); + window.e2eHidden = true; + document.dispatchEvent(new Event("visibilitychange")); + await sleep(11500); + const hidden = sky; + window.e2eHidden = false; + document.dispatchEvent(new Event("visibilitychange")); + await sleep(3000); + return {kept, hidden, shown: sky - hidden, violations: window.e2eViolations}; +})()""" +MUSIC = """(async () => {@HELPERS@ + const audio = () => ({...window.e2eAudio}); + const save = async (on, volume) => { + document.getElementById("settings-open").click(); + const form = await until(() => document.querySelector("#sheet form.settings"), 5000); + if (!form) { + return false; + } + const box = [...form.querySelectorAll("label.check")].find((label) => label.textContent.includes("Music on")).querySelector("input"); + box.checked = on; + form.querySelector('input[aria-label="Overall volume"]').value = String(volume); + form.requestSubmit(); + return Boolean(await until(() => !document.querySelector("#sheet form.settings"), 8000)); + }; + const before = audio(); + const on = await save(true, 0.5); + const started = await until(() => window.e2eAudio.starts >= before.starts + 4, 8000); + const loud = audio(); + const quiet = await save(true, 0); + await sleep(3500); + const stopped = audio(); + await sleep(6000); + const later = audio(); + const rose = await save(true, 0.5); + const restarted = await until(() => window.e2eAudio.starts >= later.starts + 4, 8000); + const off = await save(false, 0.5); + return {saved: [on, quiet, rose, off], started: Boolean(started), restarted: Boolean(restarted), before, loud, stopped, later, violations: window.e2eViolations}; +})()""" + + +def probe(template: str) -> str: + return template.replace("@HELPERS@", base.HELPERS) + + +@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium") +class TestPollCost(HubCase): + drive = base.OrchestratorE2ECase.drive + + def setUp(self): + super().setUp() + OUT.mkdir(parents=True, exist_ok=True) + now = time.time() + self.write_council({"news.jsonl": self.jsonl([{"ts": now - 60 * n, "from": "One", "to": [], "text": f"row {n}"} for n in range(1, 6)])}) + self.page_url = f"http://localhost:{self.port}/" + + def test_chromium_keeps_stream_rows_across_polls_stops_the_sky_hidden_and_the_music_at_level_zero_at_three_widths(self): + steps = [] + for width, height in base.WIDTHS: + at = {"width": width, "height": height} + shot = OUT / f"chromium-{width}" + steps += [ + {**at, "url": f"{self.page_url}?{width}-clear#stream", "wait": 600, "probe": bm.CLEAR, "shot": None}, + {**at, "url": f"{self.page_url}?{width}#stream", "wait": 1500, "probe": probe(POLLS), "shot": f"{shot}-stream.png"}, + {**at, "url": None, "wait": 0, "probe": probe(MUSIC), "shot": None}, + ] + data = self.drive(steps, None, init=INIT) + (OUT / "chromium-poll-cost.json").write_text(json.dumps(data, indent=1), encoding="utf-8") + self.assertEqual(data["errors"], []) + results = iter(data["results"]) + for width, _ in base.WIDTHS: + _, polls, music = next(results), next(results), next(results) + with self.subTest(width=width): + self.assertNotIn("error", polls, polls) + self.assertEqual((polls["kept"]["connected"], polls["kept"]["replaced"]), (True, 0), polls) + self.assertGreaterEqual(polls["kept"]["rows"], 5, polls) + self.assertEqual(polls["hidden"], 0, polls) + self.assertGreaterEqual(polls["shown"], 1, polls) + self.assertEqual(polls["violations"], []) + self.assertEqual(music["saved"], [True, True, True, True], music) + self.assertTrue(music["started"], music) + self.assertGreaterEqual(music["stopped"]["stops"] - music["loud"]["stops"], 4, music) + self.assertEqual(music["later"]["starts"], music["stopped"]["starts"], music) + self.assertTrue(music["restarted"], music) + self.assertEqual(music["violations"], []) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/e2e/test_radio_layout_e2e.py b/tests/e2e/test_radio_layout_e2e.py index 2049739..fc3f6ad 100644 --- a/tests/e2e/test_radio_layout_e2e.py +++ b/tests/e2e/test_radio_layout_e2e.py @@ -74,8 +74,7 @@ class TestRadioLayout(kit.RadioLayoutCase): self.assertGreaterEqual(layout["sliver"], 10, layout) self.assertTrue(layout["order"]["stacked" if width == 390 else "beside"], layout) self.assertEqual(layout["labels"], 1, layout) - self.assertEqual(layout["stars"], [[part, True] for part in PARTS], layout) - self.assertEqual(layout["covered"], [], layout) + self.assertEqual((layout["pinnable"], layout["stars"]), ([[part, True] for part in PARTS], 0), layout) self.assertEqual(layout["stations"], [True, False], layout) def check_popup(self, popup: dict) -> None: @@ -231,14 +230,14 @@ class TestRadioLayout(kit.RadioLayoutCase): with self.subTest(browser=browser, width=width, part="fit view"): self.check_fit(fit, (width, height)) - def test_chromium_lays_the_radio_out_without_overflow_one_line_rows_popup_and_four_home_stars_at_four_widths(self): + def test_chromium_lays_the_radio_out_without_overflow_one_line_rows_popup_and_four_home_pins_at_four_widths(self): data = self.drive(self.steps("chromium"), None) (OUT / "chromium-radio-layout.json").write_text(json.dumps(data, indent=1), encoding="utf-8") self.assertEqual(data["errors"], []) self.check(data, "chromium") @unittest.skipUnless(shutil.which(os.environ.get("FIREFOX", "firefox")), "no Firefox") - def test_firefox_lays_the_radio_out_without_overflow_one_line_rows_popup_and_four_home_stars_at_four_widths(self): + def test_firefox_lays_the_radio_out_without_overflow_one_line_rows_popup_and_four_home_pins_at_four_widths(self): data = self.drive(self.steps("firefox"), None, "bidi.mjs", os.environ.get("FIREFOX", "firefox")) (OUT / "firefox-radio-layout.json").write_text(json.dumps(data, indent=1), encoding="utf-8") self.assertEqual([error for error in data["errors"] if "/favicon.ico" not in error], []) diff --git a/tests/e2e/test_radio_set_e2e.py b/tests/e2e/test_radio_set_e2e.py index 46a49a0..f70593a 100644 --- a/tests/e2e/test_radio_set_e2e.py +++ b/tests/e2e/test_radio_set_e2e.py @@ -170,8 +170,8 @@ class TestRadioSet(HubCase): self.assertEqual([row["line"] for row in log["narrowed"]], ["rebase done"]) self.assertEqual(log["none"][0], 0) self.assertEqual(log["clearedChips"], [{"class": "", "from": "", "to": "", "agent": ""}, "", len(every)]) - self.assertTrue(log["muted"][0].startswith("Mute "), log["muted"]) - self.assertEqual((log["muted"][1:], log["unmuted"]), (["true", 1, False], ["false", 0]), log) + self.assertTrue(log["muted"][0].startswith("Open "), log["muted"]) + self.assertEqual((log["muted"][1:], log["unmuted"]), (["true", {"sound": False, "aloud": False, "bubbles": True}, True], ["false", None]), log) self.assertEqual(log["opened"][0], True) self.assertTrue(log["opened"][1], log) self.assertEqual(log["fits"], {"page": True, "panel": True}) diff --git a/tests/e2e/test_review_marks_e2e.py b/tests/e2e/test_review_marks_e2e.py new file mode 100644 index 0000000..eb5e219 --- /dev/null +++ b/tests/e2e/test_review_marks_e2e.py @@ -0,0 +1,77 @@ +from __future__ import annotations + +import json +import os +import shutil +import sys +import unittest +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path[:0] = [str(HERE.parent), str(HERE)] + +import hub_e2e_kit as base +import test_line_comments_e2e as comments + +MARKS = """(async () => {@HELPERS@@UNLABELLED@ + const row = () => document.querySelector('#main .inbox-list > li[data-ref="@REVIEW@"]'); + if (!(await until(row, 8000))) { + return {error: text(document.getElementById("main"))}; + } + const to = row().dataset.to || null; + const lines = () => all("#sheet .review-file[data-path='src/app.py'] tr[data-line]"); + const open = async () => { + row().querySelector(".headline").click(); + return until(() => lines().length, 8000); + }; + if (!(await open())) { + return {error: text(document.getElementById("sheet")), to}; + } + const cell = lines()[2].querySelector("td.code"); + const box = cell.getBoundingClientRect(); + cell.dispatchEvent(new MouseEvent("contextmenu", {bubbles: true, cancelable: true, clientX: box.left + 4, clientY: box.top + 4})); + const field = await until(() => document.querySelector("#sheet tr.match-comment textarea"), 4000); + if (!field) { + return {error: "no inline comment field", to, menu: Boolean(document.querySelector(".ctx-menu:not([hidden])"))}; + } + field.value = "c"; + all("#sheet tr.match-comment button").find((button) => name(button) === "Save comment").click(); + await until(() => document.querySelector("#sheet tr.match-mark"), 4000); + const shown = all("#sheet tr.match-mark").map(text); + document.body.dispatchEvent(new KeyboardEvent("keydown", {key: "Escape", bubbles: true})); + await until(() => document.getElementById("sheet").hidden, 4000); + await open(); + const kept = all("#sheet tr.match-mark").map(text); + const via = all("#sheet .deny-split button").find((button) => name(button).startsWith("Deny via")); + if (via) { + via.click(); + } + const reason = await until(() => document.querySelector(".sheet-box .deny-reason textarea"), 4000); + return {to, shown, kept, via: Boolean(via), reason: reason ? reason.value : null, wide: document.documentElement.scrollWidth > innerWidth + 1}; +})()""" + + +@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium") +class TestReviewMarks(base.OrchestratorE2ECase): + def setUp(self): + super().setUp() + arguments = {**self.arguments(comments.TITLE, "", self.page("marks.html", comments.review_page())), "worktree": "/repo/.worktrees/feature/marks", "branch": "feature/marks"} + result = self.tool("review_request", arguments) + self.assertFalse(result["isError"], result) + self.review = result["structuredContent"]["id"] + + def test_chromium_marks_a_line_in_the_review_modal_of_a_card_without_requester_and_keeps_it_for_the_deny_reason(self): + probe = MARKS.replace("@HELPERS@", base.HELPERS).replace("@UNLABELLED@", base.UNLABELLED).replace("@REVIEW@", f"review:{self.review}") + step = {"width": 1366, "height": 768, "url": f"http://localhost:{self.port}/?marks#stream/inbox", "wait": 1200, "probe": probe, "shot": self.shot("1366-review-marks")} + data = self.drive([step], None) + (Path(self.shot("1366-review-marks")).with_suffix(".json")).write_text(json.dumps(data, indent=1), encoding="utf-8") + self.assertEqual([error for error in data["errors"] if "(style-src-elem)" not in error and "/favicon.ico" not in error], []) + found = data["results"][0] + self.assertNotIn("error", found, found) + self.assertIsNone(found["to"], found) + self.assertEqual((found["shown"], found["kept"], found["via"], found["wide"]), (["c"], ["c"], True, False), found) + self.assertIn("src/app.py:3: c", found["reason"] or "", found) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/e2e/test_schedules_e2e.py b/tests/e2e/test_schedules_e2e.py new file mode 100644 index 0000000..10d4392 --- /dev/null +++ b/tests/e2e/test_schedules_e2e.py @@ -0,0 +1,117 @@ +from __future__ import annotations + +import json +import os +import shutil +import sys +import unittest +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path[:0] = [str(HERE.parent), str(HERE)] + +import hub_e2e_kit as base +import test_home_bookmarks_e2e as bm +import test_home_dashboard_e2e as dash +from hub_case import HubCase +from kvb_orchestrator import schedules + +OUT = Path(os.environ.get("E2E_OUT", "/tmp/hub-057-shots")) +FOREIGN = {"name": "backup.timer", "kind": "timer", "owner": "other", "unit": "backup.timer", "file": "/u/backup.timer", "schedule": "OnCalendar=daily", "next": 1_900_000_000, "last": None, "event": "", "command": "", "off": "systemctl --user disable --now backup.timer"} +HUB_UNIT = {**FOREIGN, "name": "kvb-orchestrator-tree.timer", "owner": "hub", "unit": "kvb-orchestrator-tree.timer", "off": ""} +PROBE = """(async () => {@HELPERS@@HOME@ + const row = (name) => document.querySelector(`#main [data-schedule="${name}"]`); + const rows = async () => (await (await fetch("/api/state")).json()).schedules.rows; + const settle = async (check, ms) => { + const end = Date.now() + ms; + while (Date.now() < end) { + if (await check()) { + return true; + } + await sleep(200); + } + return false; + }; + const owner = await until(() => document.querySelector('#main [data-panel="stream/schedules"]') && row("coach"), 8000); + if (!owner) { + return {error: text(document.getElementById("main"))}; + } + const tabs = all('#main [role="tab"]').map((tab) => [tab.dataset.tab, tab.getAttribute("aria-selected")]); + const foreign = all("#main [data-schedule-foreign]").map((node) => ({name: node.dataset.scheduleForeign, switches: node.querySelectorAll('input[role="switch"]').length, copy: Boolean(node.querySelector('button[aria-label="Copy"]')), off: text(node.querySelector(".sched-off code"))})); + const flip = async (wanted) => { + row("coach").querySelector('input[role="switch"]').click(); + return settle(async () => (await rows()).coach.on === wanted && row("coach") && row("coach").querySelector('input[role="switch"]').checked === wanted, 8000); + }; + const on = await flip(true); + const off = await flip(false); + const times = row("dream-popup").querySelector("input.sched-times"); + times.value = "21:30, 06:00"; + times.dispatchEvent(new Event("change", {bubbles: true})); + const retimed = await settle(async () => JSON.stringify((await rows())["dream-popup"].at) === '["06:00","21:30"]', 8000); + const wide = document.documentElement.scrollWidth > innerWidth + 1; + const panel = document.querySelector('#main [data-panel="stream/schedules"]'); + const spot = [...panel.children].find((node) => node.closest("[data-panel], [data-item]") === panel) || panel; + const item = await pinItem(spot); + const label = item ? menuLabel(item) : null; + if (item) { + item.click(); + await sleep(300); + } + await closeMenu(); + return {hash: location.hash, tabs, foreign, on, off, retimed, wide, label, pinned: stored().includes("panel:stream/schedules")}; +})()""" +TILE = """(async () => {@HELPERS@@HOME@ + await go("home"); + const shown = await until(() => tile("panel:stream/schedules") && tile("panel:stream/schedules").querySelector('[data-schedule="coach"]'), 8000); + return {tile: Boolean(shown), switches: shown ? tile("panel:stream/schedules").querySelectorAll('input[role="switch"]').length : 0}; +})()""" + + +def probe(template: str) -> str: + return template.replace("@HELPERS@", base.HELPERS).replace("@HOME@", dash.HOME) + + +@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium") +class TestSchedules(HubCase): + drive = base.OrchestratorE2ECase.drive + + def setUp(self): + super().setUp() + OUT.mkdir(parents=True, exist_ok=True) + self.council.mkdir(parents=True, exist_ok=True) + (self.council / schedules.SCHEDULES_VIEW).write_text(json.dumps({"at": 1_800_000_000, "rows": [FOREIGN, HUB_UNIT]}), encoding="utf-8") + self.page_url = f"http://localhost:{self.port}/" + + def test_chromium_opens_schedules_switches_coach_retimes_the_popup_shows_foreign_rows_read_only_and_pins_it_at_three_widths(self): + steps = [] + for width, height in base.WIDTHS: + at = {"width": width, "height": height} + shot = OUT / f"chromium-{width}" + steps += [ + {**at, "url": f"{self.page_url}?{width}-clear#stream", "wait": 600, "probe": bm.CLEAR, "shot": None}, + {**at, "url": f"{self.page_url}?{width}#stream/schedules", "wait": 1500, "probe": probe(PROBE), "shot": f"{shot}-schedules.png"}, + {**at, "url": None, "wait": 0, "probe": probe(TILE), "shot": f"{shot}-home.png"}, + ] + data = self.drive(steps, None) + (OUT / "chromium-schedules.json").write_text(json.dumps(data, indent=1), encoding="utf-8") + self.assertEqual(data["errors"], []) + results = iter(data["results"]) + for width, _ in base.WIDTHS: + _, found, home = next(results), next(results), next(results) + with self.subTest(width=width): + self.assertNotIn("error", found, found) + self.assertEqual(found["tabs"], [["tools", "false"], ["rules", "false"], ["groups", "false"], ["schedules", "true"]]) + self.assertEqual(found["hash"], "#stream/schedules") + self.assertEqual((found["on"], found["off"], found["retimed"], found["wide"]), (True, True, True, False)) + self.assertEqual(found["foreign"], [ + {"name": "backup.timer", "switches": 0, "copy": True, "off": "systemctl --user disable --now backup.timer"}, + {"name": "kvb-orchestrator-tree.timer", "switches": 0, "copy": False, "off": None}, + ]) + self.assertEqual((found["label"], found["pinned"]), ("Pin to Home", True)) + self.assertEqual(home, {"tile": True, "switches": 5}) + stored = json.loads((self.council / schedules.SCHEDULES).read_text(encoding="utf-8")) + self.assertEqual((stored["coach"], stored["dream-popup"]), ({"on": False, "every": 1}, {"on": False, "at": ["06:00", "21:30"]})) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/e2e/test_speak_box_e2e.py b/tests/e2e/test_speak_box_e2e.py new file mode 100644 index 0000000..21e85af --- /dev/null +++ b/tests/e2e/test_speak_box_e2e.py @@ -0,0 +1,127 @@ +from __future__ import annotations + +import json +import os +import re +import shutil +import sys +import unittest +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path[:0] = [str(HERE.parent), str(HERE)] + +import hub_e2e_kit as base +import hub_support +from hub_case import HubCase + +OUT = Path(os.environ.get("E2E_OUT", "/tmp/hub-033-shots")) +COMPOSER = (hub_support.HUB / "templates" / "page-composer.js").read_text(encoding="utf-8") +HINTS = re.findall(r'^\s+"?[\w-]+"?: "([^"]+)",$', COMPOSER.split("const MAYDAY_ASK")[0], re.MULTILINE) +SHAPE = """ + const hints = @HINTS@; + const role = (node) => [["channel", ".composer-grid"], ["text", "textarea"], ["foot", ".mic-foot"], ["mic", "button.mic"], ["ptt", ".ptt-split"], ["mayday", ".mayday-toggle"], + ["spacer", ".spacer"], ["status", ".composer-status"], ["record", "button[aria-pressed]"]].find(([, selector]) => node.matches(selector))?.[0] || node.tagName.toLowerCase(); + const edges = (node) => ["Top", "Right", "Bottom", "Left"].map((side) => getComputedStyle(node)[`border${side}Width`]); + const shape = (form) => { + const frame = form.querySelector(":scope > .mic-frame"); + const foot = frame.querySelector(":scope > .mic-foot"); + return { + frame: [...frame.children].map(role), foot: [...foot.children].map(role), + lines: {channel: edges(frame.querySelector(".composer-grid")), text: edges(frame.querySelector("textarea")), foot: getComputedStyle(foot).borderTopWidth}, + titles: all("[title]", form).map((node) => node.title).filter((title) => hints.some((hint) => title.includes(hint))), + }; + }; +""" +RADIO = """(async () => {@HELPERS@@SHAPE@ + const form = await until(() => document.querySelector("#radio-spot .radio-speak form.composer"), 15000); + await sleep(300); + return {shape: shape(form), wide: document.documentElement.scrollWidth > innerWidth + 1}; +})()""" +HOME = """(async () => {@HELPERS@@SHAPE@ + const misfits = []; + let first = null; + for (let rows = 3; rows <= 8; rows += 1) { + for (let cols = 4; cols <= 12; cols += 1) { + await ViewStore.update("home.pins", () => [{kind: "panel", id: "radio-speak", w: cols, h: rows}]); + const tile = await until(() => { + const node = document.querySelector('#main .home-tile[data-pin="panel:radio-speak"]'); + return node && node.dataset.w === String(cols) && node.dataset.h === String(rows) && node.querySelector("form.composer .mayday-toggle") ? node : null; + }, 4000); + if (!tile) { + misfits.push({cols, rows, missing: true}); + continue; + } + await sleep(40); + const body = tile.querySelector(".home-body").getBoundingClientRect(); + const out = [".ptt-split", ".mayday-toggle"].filter((selector) => { + const edge = tile.querySelector(selector).getBoundingClientRect(); + return !(edge.width > 0 && edge.left >= body.left - 0.5 && edge.right <= body.right + 0.5 && edge.top >= body.top - 0.5 && edge.bottom <= body.bottom + 0.5); + }); + if (out.length) { + misfits.push({cols, rows, out}); + } + if (!first) { + first = {shape: shape(tile.querySelector("form.composer")), speak: tile.querySelector(".home-body").innerText.includes("Speak")}; + } + } + } + await ViewStore.update("home.pins", () => [{kind: "panel", id: "radio-speak", w: 6, h: 5}]); + await sleep(400); + return {misfits, first, wide: document.documentElement.scrollWidth > innerWidth + 1}; +})()""" +FRAME = ["channel", "text", "foot"] +FOOT = ["record", "status", "spacer", "mic", "ptt", "mayday"] +LINES = {"channel": ["0px", "0px", "1px", "0px"], "text": ["0px", "0px", "0px", "0px"], "foot": "1px"} + + +def probe(template: str) -> str: + return template.replace("@HELPERS@", base.HELPERS).replace("@SHAPE@", SHAPE).replace("@HINTS@", json.dumps(HINTS)) + + +@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium") +class TestSpeakBox(HubCase): + drive = base.OrchestratorE2ECase.drive + + def setUp(self): + super().setUp() + OUT.mkdir(parents=True, exist_ok=True) + self.claim("s1", "Skills") + self.snapshot() + self.page_url = f"http://localhost:{self.port}/" + + def check_shape(self, shape: dict) -> None: + self.assertEqual((shape["frame"], shape["foot"]), (FRAME, FOOT), shape) + self.assertEqual((shape["lines"], shape["titles"]), (LINES, []), shape) + + def test_the_hint_list_is_read_from_the_composer(self): + self.assertEqual(len(HINTS), 6, HINTS) + + def test_chromium_draws_one_speak_frame_in_the_radio_view_and_keeps_ptt_and_mayday_inside_every_home_widget_size(self): + steps = [] + for width, height in base.WIDTHS: + shot = OUT / f"chromium-{width}" + steps += [ + {"width": width, "height": height, "url": f"{self.page_url}?{width}-radio#stream/radio", "wait": 1200, "probe": probe(RADIO), "shot": f"{shot}-radio-speak.png"}, + {"width": width, "height": height, "url": f"{self.page_url}?{width}-home#home", "wait": 1200, "probe": probe(HOME), "shot": f"{shot}-home-speak.png"}, + ] + data = self.drive(steps, None) + (OUT / "chromium-speak-box.json").write_text(json.dumps(data, indent=1), encoding="utf-8") + self.assertEqual(data["errors"], []) + results = iter(data["results"]) + for width, _ in base.WIDTHS: + radio, home = next(results), next(results) + with self.subTest(width=width, view="radio"): + self.assertNotIn("error", radio, radio) + self.check_shape(radio["shape"]) + self.assertFalse(radio["wide"]) + with self.subTest(width=width, view="home"): + self.assertNotIn("error", home, home) + self.assertEqual(home["misfits"], [], home["misfits"][:5]) + self.check_shape(home["first"]["shape"]) + self.assertFalse(home["first"]["speak"]) + self.assertFalse(home["wide"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/e2e/test_speak_card_e2e.py b/tests/e2e/test_speak_card_e2e.py index 00ee523..b423d87 100644 --- a/tests/e2e/test_speak_card_e2e.py +++ b/tests/e2e/test_speak_card_e2e.py @@ -116,8 +116,8 @@ class TestSpeakCard(base.OrchestratorE2ECase): layout = result["layout"] self.assertEqual((layout["hints"], layout["mayday"], layout["next"], layout["face"], layout["cards"]), ([], False, True, ["MAYDAY", "false"], 0), layout) self.assertEqual([value for value, _ in layout["channels"]], ["post", "call", "newsletter", "broadcast", "pan-pan", "security"], layout) - self.assertTrue(all(titled for _, titled in layout["channels"]), layout) - self.assertEqual(layout["radius"], ["14px", "10px", "10px"], layout) + self.assertFalse(any(titled for _, titled in layout["channels"]), layout) + self.assertEqual(layout["radius"], ["14px", "0px", "10px"], layout) self.assertEqual((layout["fits"], layout["wide"]), (True, False), layout) self.assertEqual((result["declined"], result["quiet"], result["asked"]), (ask, [], ask), result) self.assertTrue((result["toast"] or "").startswith("Mayday to all: sent$ radio.py send mayday"), result) diff --git a/tests/e2e/test_stream_band_e2e.py b/tests/e2e/test_stream_band_e2e.py new file mode 100644 index 0000000..99b7bc7 --- /dev/null +++ b/tests/e2e/test_stream_band_e2e.py @@ -0,0 +1,74 @@ +from __future__ import annotations + +import json +import os +import shutil +import sys +import unittest +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path[:0] = [str(HERE.parent), str(HERE)] + +import hub_e2e_kit as base +from hub_case import HubCase + +OUT = Path(os.environ.get("E2E_OUT", "/tmp/hub-034-shots")) +BAND = """(async () => {@HELPERS@ + if (!(await screenShown(8000))) { + return {error: "no screen"}; + } + const main = document.getElementById("main"); + const band = await until(() => main.querySelector(".stream-head"), 8000); + if (!band) { + return {error: text(main).slice(0, 300)}; + } + await sleep(400); + const look = getComputedStyle(band); + const tile = document.body.appendChild(Object.assign(document.createElement("div"), {className: "home-tile"})); + const tint = getComputedStyle(tile).backgroundColor; + tile.remove(); + const inner = () => main.getBoundingClientRect().top + parseFloat(getComputedStyle(main).borderTopWidth); + const before = band.getBoundingClientRect().top - inner(); + band.parentElement.append(Object.assign(document.createElement("div"), {style: "height: 3000px"})); + main.scrollTop = 600; + await sleep(200); + const after = band.getBoundingClientRect().top - inner(); + return { + first: band.parentElement.firstElementChild === band && main.firstElementChild === band.parentElement, + line: [look.borderBottomWidth, look.borderBottomStyle], lineColor: look.borderBottomColor === getComputedStyle(main.appendChild(Object.assign(document.createElement("i"), {style: "color: var(--line)"}))).color, + background: look.backgroundColor === tint, before: Math.round(before * 10) / 10, after: Math.round(after * 10) / 10, scrolled: main.scrollTop, + }; +})()""" + + +@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium") +class TestStreamBand(HubCase): + drive = base.OrchestratorE2ECase.drive + + def setUp(self): + super().setUp() + OUT.mkdir(parents=True, exist_ok=True) + self.claim("s1", "Skills") + self.snapshot() + self.page_url = f"http://localhost:{self.port}/" + + def test_chromium_keeps_the_stream_controls_in_a_flush_sticky_head_band(self): + steps = [ + {"width": width, "height": height, "url": f"{self.page_url}?{width}#stream", "wait": 1200, "probe": BAND.replace("@HELPERS@", base.HELPERS), "shot": str(OUT / f"chromium-{width}-stream-band.png")} + for width, height in base.WIDTHS + ] + data = self.drive(steps, None) + (OUT / "chromium-stream-band.json").write_text(json.dumps(data, indent=1), encoding="utf-8") + self.assertEqual(data["errors"], []) + for result, (width, _) in zip(data["results"], base.WIDTHS, strict=True): + with self.subTest(width=width): + self.assertNotIn("error", result, result) + self.assertEqual((result["first"], result["line"], result["lineColor"], result["background"]), (True, ["1px", "solid"], True, True), result) + self.assertLessEqual(abs(result["before"]), 1, result) + self.assertGreaterEqual(result["scrolled"], 600, result) + self.assertLessEqual(abs(result["after"] - result["before"]), 1, result) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/e2e/test_stream_keeps_typing_e2e.py b/tests/e2e/test_stream_keeps_typing_e2e.py index 516b3cc..4124cbd 100644 --- a/tests/e2e/test_stream_keeps_typing_e2e.py +++ b/tests/e2e/test_stream_keeps_typing_e2e.py @@ -39,6 +39,7 @@ PROBE = """(async () => {@HELPERS@ field.dispatchEvent(new Event("input", {bubbles: true})); field.setSelectionRange(6, 6); const top = scroller.scrollTop; + all("#main .chip").find((chip) => text(chip) === "Transcripts").click(); const redrawn = await until(() => { const [now, typed] = [askOf(), choiceOf()]; return now && typed && now.dataset.probe !== "old" && typed.dataset.probe !== "old" ? [now, typed] : null; diff --git a/tests/e2e/test_undo_dial_e2e.py b/tests/e2e/test_undo_dial_e2e.py new file mode 100644 index 0000000..c97e58b --- /dev/null +++ b/tests/e2e/test_undo_dial_e2e.py @@ -0,0 +1,83 @@ +from __future__ import annotations + +import json +import os +import shutil +import sys +import unittest +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path[:0] = [str(HERE.parent), str(HERE)] + +import test_match_release_card_e2e as deck + +OUT = Path(os.environ.get("E2E_OUT", "/tmp/hub-043-shots")) +WORDS = "10 s remain to undo" +TEXTS = """(async () => {@HELPERS@@CARD@@STEPS@ + const row = () => document.querySelector('#main .inbox-list > li[data-ref="@RED@"]'); + if (!(await until(row, 8000))) { + return {error: text(document.getElementById("main")).slice(0, 300)}; + } + all(".deny-split button", row()).find((button) => name(button).startsWith("Deny via")).click(); + const sheet = await until(() => document.querySelector(".sheet-box .deny-channels"), 4000); + const deny = sheet ? all(".sheet-box p.muted").map(text).find((line) => line.startsWith("The passkey signs the denial")) : null; + document.dispatchEvent(new KeyboardEvent("keydown", {key: "Escape", bubbles: true})); + await until(() => !document.querySelector(".sheet-box .deny-channels"), 4000); + document.getElementById("settings-open").click(); + const dial = await until(() => document.querySelector(".sheet-box form.settings .undo-dial"), 8000); + if (!dial) { + return {deny, error: "no dial"}; + } + dial.scrollIntoView({block: "center"}); + await sleep(300); + const attrs = () => ["role", "aria-valuemin", "aria-valuemax", "aria-valuenow", "aria-valuetext"].map((attr) => dial.getAttribute(attr)); + const dialed = {attrs: attrs(), label: dial.getAttribute("aria-label"), readout: text(dial.querySelector(".dial-readout")), ticks: all(".dial-tick", dial).length, long: all(".dial-tick.long", dial).length}; + const press = (key) => { + dial.dispatchEvent(new KeyboardEvent("keydown", {key, bubbles: true, cancelable: true})); + return dial.getAttribute("aria-valuenow"); + }; + dial.focus(); + const keys = [["ArrowRight", press("ArrowRight")], ["PageUp", press("PageUp")], ["End", press("End")], ["ArrowRight", press("ArrowRight")], ["PageDown", press("PageDown")], ["Home", press("Home")], ["ArrowLeft", press("ArrowLeft")]]; + const zero = {text: dial.getAttribute("aria-valuetext"), readout: text(dial.querySelector(".dial-readout"))}; + const box = dial.getBoundingClientRect(); + return {deny, opened: dialed, keys, zero, focused: document.activeElement === dial, inside: box.left >= 0 && box.right <= innerWidth, wide: document.documentElement.scrollWidth > innerWidth + 1}; +})()""" +RELEASED = """(async () => {@HELPERS@@CARD@@STEPS@ + await screenShown(8000); + if (!(await until(card, 8000)) || !(await decideAll())) { + return {error: text(document.getElementById("main")).slice(0, 300)}; + } + return {title: document.querySelector("#main .match-release").title}; +})()""" + + +@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium") +class TestUndoDial(deck.ReleaseDeck): + def setUp(self): + super().setUp() + OUT.mkdir(parents=True, exist_ok=True) + payload = {**self.snapshot()["settings"], "undo": 10, "proof": None} + self.assertEqual(self.post_json("/api/settings", payload, self.guard(self.host))[0], 200) + + def test_chromium_sets_the_undo_window_on_a_dial_and_every_undo_text_names_the_saved_seconds(self): + steps = [ + {"width": 1366, "height": 768, "url": f"{self.base}?dial#stream/inbox", "wait": 1500, "shot": str(OUT / "chromium-1366-undo-dial.png"), "probe": deck.probe(TEXTS, red=f"review:{self.red}")}, + {"width": 1920, "height": 1080, "url": f"{self.base}?dial-release#tasks/match", "wait": 1500, "shot": str(OUT / "chromium-1920-undo-release.png"), "probe": deck.probe(RELEASED)}, + ] + data = self.drive(steps, None, init=deck.INIT) + (OUT / "chromium-undo-dial.json").write_text(json.dumps(data, indent=1), encoding="utf-8") + self.assertEqual([error for error in data["errors"] if "/favicon.ico" not in error], []) + texts, released = data["results"] + for found in (texts, released): + self.assertNotIn("error", found, found) + self.assertIn(f"then {WORDS}.", texts["deny"], texts) + self.assertEqual(texts["opened"], {"attrs": ["slider", "0", "60", "10", "10 seconds to undo"], "label": "Undo window in seconds", "readout": "10 s", "ticks": 60, "long": 12}, texts) + self.assertEqual(texts["keys"], [["ArrowRight", "11"], ["PageUp", "16"], ["End", "60"], ["ArrowRight", "60"], ["PageDown", "55"], ["Home", "0"], ["ArrowLeft", "0"]], texts) + self.assertEqual(texts["zero"], {"text": "0 seconds: takes effect at once", "readout": "0 s"}, texts) + self.assertEqual((texts["focused"], texts["inside"], texts["wide"]), (True, True, False), texts) + self.assertTrue(released["title"].endswith(f"after each signature {WORDS}."), released) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/e2e/test_why_deny_e2e.py b/tests/e2e/test_why_deny_e2e.py new file mode 100644 index 0000000..fefb29c --- /dev/null +++ b/tests/e2e/test_why_deny_e2e.py @@ -0,0 +1,74 @@ +from __future__ import annotations + +import json +import os +import shutil +import sys +import time +import unittest +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path[:0] = [str(HERE.parent), str(HERE)] + +import hub_e2e_kit as base +import test_line_comments_e2e as comments +from hub_support import iso + +WHY = """(async () => {@HELPERS@@UNLABELLED@ + const row = () => document.querySelector('#main .inbox-list > li[data-ref="@REVIEW@"]'); + if (!(await until(row, 8000))) { + return {error: text(document.getElementById("main"))}; + } + const described = (button) => { + const note = document.getElementById(button.getAttribute("aria-describedby") || ""); + return note ? note.textContent : null; + }; + const main = all(".deny-split button", row()).find((button) => name(button) === "Deny"); + const split = {disabled: main.disabled, title: main.closest(".why-off").title, described: described(main)}; + all(".deny-split button", row()).find((button) => name(button).startsWith("Deny via")).click(); + const confirm = await until(() => all(".sheet-box .actions button").find((button) => text(button) === "Deny"), 4000); + const call = document.querySelector('.sheet-box .deny-channels input[value="call"]'); + const look = () => ({disabled: confirm.disabled, title: confirm.closest(".why-off").title, described: described(confirm)}); + const off = {checked: call.checked, ...look()}; + const select = document.querySelector(".sheet-box .deny-recipient select"); + select.value = "Skills"; + select.dispatchEvent(new Event("change", {bubbles: true})); + await sleep(100); + return {split, off, on: look(), wide: document.documentElement.scrollWidth > innerWidth + 1}; +})()""" + + +@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium") +class TestWhyDeny(base.OrchestratorE2ECase): + def setUp(self): + super().setUp() + now = time.time() + self.write_council({"work/s1/claim.json": {"office": "work/s1", "session": "s1", "runtime": "claude", "name": "Skills", "since": iso(now - 3600), "beat": now, "work": "hub"}}) + arguments = {**self.arguments(comments.TITLE, "", self.page("why.html", comments.review_page())), "worktree": "/repo/.worktrees/feature/why", "branch": "feature/why"} + result = self.tool("review_request", arguments) + self.assertFalse(result["isError"], result) + self.review = result["structuredContent"]["id"] + + def test_chromium_names_why_deny_is_off_on_hover_and_for_keyboard_users_until_a_recipient_is_picked(self): + probe = WHY.replace("@HELPERS@", base.HELPERS).replace("@UNLABELLED@", base.UNLABELLED).replace("@REVIEW@", f"review:{self.review}") + step = {"width": 1366, "height": 768, "url": f"http://localhost:{self.port}/?why#stream/inbox", "wait": 1200, "probe": probe, "shot": self.shot("1366-why-deny")} + data = self.drive([step], None) + Path(self.shot("1366-why-deny")).with_suffix(".json").write_text(json.dumps(data, indent=1), encoding="utf-8") + self.assertEqual([error for error in data["errors"] if "(style-src-elem)" not in error and "/favicon.ico" not in error], []) + found = data["results"][0] + self.assertNotIn("error", found, found) + missing = "No agent to tell: the item names no recipient" + self.assertTrue(found["split"]["disabled"], found) + self.assertTrue(found["split"]["title"].startswith(missing) and found["split"]["described"].startswith(missing), found) + needs = "Pick the agent to tell: a post or call needs a recipient" + self.assertEqual(found["off"], {"checked": True, "disabled": True, "title": needs, "described": needs}, found) + self.assertFalse(found["on"]["disabled"], found) + self.assertNotIn("needs a recipient", found["on"]["title"], found) + self.assertEqual(found["on"]["title"], found["on"]["described"], found) + self.assertIn("Skills", found["on"]["title"], found) + self.assertFalse(found["wide"], found) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/e2e/test_workbench_w1_e2e.py b/tests/e2e/test_workbench_w1_e2e.py index 8675590..caa92a6 100644 --- a/tests/e2e/test_workbench_w1_e2e.py +++ b/tests/e2e/test_workbench_w1_e2e.py @@ -41,7 +41,7 @@ OPERATOR = """(async () => {@HELPERS@@UNLABELLED@ const mine = (words) => all("#main .inbox-list > li").find((li) => li.textContent.includes(words)); const cards = ["@TAG@ review", "@TAG@ ship", "@TAG@ commit"].map(mine); const tasks = document.getElementById("tab-tasks"); - const badge = tasks.querySelector(".badge"); + const badge = tasks.nextElementSibling; const review = cards[0]; const files = all(".diff-file", review).map((file) => ({ path: file.dataset.path, status: file.dataset.status, open: file.querySelector("details") ? file.querySelector("details").open : null, @@ -57,7 +57,9 @@ OPERATOR = """(async () => {@HELPERS@@UNLABELLED@ operator: operator ? {command: text(operator.querySelector(".command code")), place: operator.querySelector(".command").dataset.path, text: text(operator), buttons: all("button", operator).map(name)} : null, files, wide: document.documentElement.scrollWidth > window.innerWidth + 1, }; - ["@TAG@ review", "@TAG@ ship", "@TAG@ commit"].forEach((words) => mine(words).querySelector('input[type="checkbox"]').click()); + for (const words of ["@TAG@ review", "@TAG@ ship", "@TAG@ commit"]) { + await selectRow(mine(words).dataset.ref); + } await sleep(300); found.unlabelled = {main: unlabelled(document.getElementById("main"))}; const grant = all("#grant-bar .grant-split button").find((button) => name(button).startsWith("Grant selection")); @@ -144,7 +146,7 @@ FEEDBACK = """(async () => {@HELPERS@@UNLABELLED@ all(".sheet-box .actions button").find((button) => text(button) === "Deny").click(); await until(() => window.e2eFeedback.length > before && (!@SIGNS@ || window.e2eFeedback.some(([path]) => path === "/api/inbox/approve")), 8000); await sleep(1200); - all(".item-actions button", fresh()).find((button) => name(button) === "Grant").click(); + all(":is(.item-actions, .code-foot) button", fresh()).find((button) => name(button) === "Grant").click(); await until(() => window.e2eFeedback.some(([path]) => path === (@SIGNS@ ? "/api/messages" : "/api/sign")) && window.e2eFeedback.filter(([path]) => path === "/api/sign").length >= 2, 10000); await sleep(1500); const kept = {review: fresh() ? all(".feedback-list li.line-mark", fresh()).map(text) : null, ask: ask() ? all(".feedback-list li.line-mark", ask()).map(text) : null}; @@ -204,7 +206,7 @@ class TestWorkbenchOperatorTasks(HubCase): self.assertNotIn("error", tasks, tasks) self.assertEqual((tasks["hash"], tasks["tabs"], tasks["subs"], tasks["streamInbox"], tasks["current"]), ("#tasks/operator", base.TABS, ["Controls"], False, ["Tasks"])) self.assertRegex(tasks["badge"] or "", r"^[1-9][0-9]*$") - self.assertEqual((tasks["kinds"], tasks["boxes"]), (["k-review", "k-operator", "k-ask"], [True, True, True])) + self.assertEqual((tasks["kinds"], tasks["boxes"]), (["k-review", "k-operator", "k-ask"], [False, False, False])) operator = tasks["operator"] self.assertEqual((operator["command"], operator["place"]), (f"make {tag} ship", "/repo")) self.assertIn(f"{tag} ship the build", operator["text"]) diff --git a/tests/e2e/test_yes_no_answers_e2e.py b/tests/e2e/test_yes_no_answers_e2e.py index e4123cc..3211f11 100644 --- a/tests/e2e/test_yes_no_answers_e2e.py +++ b/tests/e2e/test_yes_no_answers_e2e.py @@ -44,7 +44,7 @@ STREAM = """(async () => {@HELPERS@@READ@ return {error: text(document.getElementById("main")), rows: rows().length}; } const pick = rows().find((row) => row.dataset.ref === "operator:operator/pick"); - const buttons = (row) => all(".line-actions button", row).map((button) => [name(button), button.disabled]); + const buttons = (row) => all(":is(.line-actions, .code-foot) button", row).map((button) => [name(button), button.disabled]); const runs = rows().find((row) => row.dataset.ref === "operator:operator/runs"); return {refs: rows().map((row) => row.dataset.ref).sort(), blocked: blockedTitles("#main .feed > li.k-operator"), pickForms: pick ? all(".choice", pick).length : null, pickButtons: pick ? buttons(pick) : null, runsButtons: runs ? buttons(runs) : null, wide: wide()}; })()""" diff --git a/tests/hub_case.py b/tests/hub_case.py index 6131adb..27e8585 100644 --- a/tests/hub_case.py +++ b/tests/hub_case.py @@ -35,11 +35,18 @@ from hub_support import ( server, signing, ) -from kvb_orchestrator import engines +from kvb_orchestrator import batches, engines +from kvb_orchestrator.settings import Settings class HubCase(unittest.TestCase): + real_undo = False + def setUp(self): + if not self.real_undo: + undo = mock.patch.object(Settings, "undo", lambda _settings: batches.UNDO) + undo.start() + self.addCleanup(undo.stop) tmp = tempfile.TemporaryDirectory() self.addCleanup(tmp.cleanup) base = Path(tmp.name) diff --git a/tests/test_block.py b/tests/test_block.py new file mode 100644 index 0000000..35c4f0e --- /dev/null +++ b/tests/test_block.py @@ -0,0 +1,164 @@ +"""Requirement 063: block.py builds the commit table and message block from one run of every scoring script.""" + +from __future__ import annotations + +import os +import re +import shlex +import shutil +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + +from score_fixture import git_env + +REPO_ROOT = Path(__file__).resolve().parents[1] +SKILLS = REPO_ROOT / "skills" +ORGANIZE = SKILLS / "kvb-org-organize" / "scripts" +FAKES = { + "tokens": "kvb-check-efficiency", + "measure": "kvb-check-efficiency", + "security": "kvb-check-security", + "gate": "kvb-check-gate", +} +FAKE = """import os, pathlib, sys +stem = pathlib.Path(sys.argv[0]).stem.upper() +with open(os.environ["FAKE_LOG"], "a", encoding="utf-8") as log: + log.write(stem + " " + " ".join(sys.argv[1:]) + "\\n") +sys.stdout.write(os.environ.get("FAKE_" + stem, "")) +sys.stderr.write(os.environ.get("FAKE_" + stem + "_ERR", "")) +sys.exit(int(os.environ.get("FAKE_" + stem + "_CODE", "0"))) +""" +OUTPUTS = { + "TOKENS": "💸 tokens 98 % (skills 100→98 tokens; listing 10→10 words)\n💰 value ?:? (cost 1/day; pass --value with evidence)\n", + "MEASURE": "💸 tokens 104 % (cpu 1→1.04 s, ram 10→10 MB) · ⏱️ velocity 97 % (wall 2→1.94 s)\n", + "MEASURE_CODE": "3", + "SECURITY": "🛡️ security 100 % critical 0 (medusa: 0 findings in 2 files)\n", + "GATE": "green\ttest\t/tmp/gate-test.log\t2026-11-25T10:00\t-\ngate: green\n", +} +FIGURES = ["--fix", "95", "--break", "2"] +SKILL_NAME = re.compile(r"kvb-[a-z-]+[a-z]") +CHAIN = {"kvb-check-score", "kvb-check-efficiency", "kvb-check-security", "kvb-check-gate", "kvb-check-speed"} + + +class BlockCase(unittest.TestCase): + def setUp(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.tmp = Path(tmp.name) + skills = self.tmp / "skills" + shutil.copytree(SKILLS / "kvb-check-score", skills / "kvb-check-score", + ignore=shutil.ignore_patterns("__pycache__")) + (skills / "kvb-org-organize" / "scripts").mkdir(parents=True) + for name in ("nofollow.py", "councilroot.py"): + shutil.copy(ORGANIZE / name, skills / "kvb-org-organize" / "scripts" / name) + for stem, skill in FAKES.items(): + (skills / skill / "scripts").mkdir(parents=True, exist_ok=True) + (skills / skill / "scripts" / f"{stem}.py").write_text(FAKE, encoding="utf-8") + self.block = skills / "kvb-check-score" / "scripts" / "block.py" + self.score = skills / "kvb-check-score" / "scripts" / "score.py" + self.log = self.tmp / "calls.log" + self.repo = self.tmp / "repo" + self.repo.mkdir() + env = git_env(self.tmp) + for args in (("init", "-q", "-b", "feature/block"), ("commit", "-q", "--allow-empty", "-m", "base")): + subprocess.run(["git", *args], cwd=self.repo, env=env, capture_output=True, check=True) + (self.repo / "a.py").write_text("x = 1\n", encoding="utf-8") + subprocess.run(["git", "add", "a.py"], cwd=self.repo, env=env, capture_output=True, check=True) + self.env = {"PATH": os.environ["PATH"], "HOME": str(self.tmp), "AGENTS_COUNCIL_ROOT": str(self.tmp / "council"), + "FAKE_LOG": str(self.log), **{f"FAKE_{key}": value for key, value in OUTPUTS.items()}} + + def run_block(self, *args: str, **outputs: str) -> subprocess.CompletedProcess: + env = {**self.env, **{f"FAKE_{key}": value for key, value in outputs.items()}} + return subprocess.run([sys.executable, "-B", str(self.block), "--repo", str(self.repo), "--base", "HEAD", *args], + cwd=self.repo, env=env, capture_output=True, text=True, check=False) + + def run_score(self, *args: str) -> subprocess.CompletedProcess: + return subprocess.run([sys.executable, "-B", str(self.score), *args], cwd=self.repo, env=self.env, + capture_output=True, text=True, check=False) + + def calls(self) -> list[str]: + return self.log.read_text(encoding="utf-8").splitlines() if self.log.exists() else [] + + +class TestGolden(BlockCase): + def test_block_prints_what_the_single_scripts_print(self): + done = self.run_block(*FIGURES, "--transcripts", "/t", "--", "true") + values = [*FIGURES, "--efficiency", "104", "--speed", "97", "--security", "100", "--critical", "0", "--value", "?"] + table = self.run_score(*values, "--commit-table", str(self.repo)) + block = self.run_score(*values, "--message-block") + after = shlex.join(["python3", str(self.score.resolve()), *values, "--commit-table", str(self.repo)]) + self.assertEqual(done.stdout, f"{table.stdout}\ngate: green\n\n{block.stdout}\nafter the commit: {after} --commit \n") + self.assertEqual((done.returncode, table.returncode, block.returncode), (3, 3, 3)) + + def test_every_script_gets_the_tree_and_the_base(self): + self.run_block(*FIGURES, "--transcripts", "/t", "--saves", "500", "--evidence", "e", "--", "make", "test") + self.assertEqual(self.calls(), [ + f"TOKENS --repo {self.repo} --base HEAD --transcripts /t --value 500 --evidence e", + "MEASURE --base HEAD -- make test", + f"SECURITY --repo {self.repo} --base HEAD", + f"GATE status --repo {self.repo}", + ]) + + def test_a_new_skill_and_a_priced_value_reach_the_block(self): + done = self.run_block(*FIGURES, "--transcripts", "/t", + TOKENS="💸 tokens new (+40 tokens; listing 10→12 words)\n💰 value 1:20 (cost 1/day, value 20/day; e)\n") + self.assertIn("💸 Tokens: new\n⏱️ Velocity: –\n", done.stdout) + self.assertIn("💰 Value: 1:20\n", done.stdout) + self.assertEqual(done.returncode, 3) + + +class TestExitCodes(BlockCase): + def test_exit_codes_are_score_py_s(self): + cases = { + "pass": ((), {}, 0), + "below 90/5": (("--fix", "80"), {}, 1), + "ask again": (("--", "true"), {}, 3), + "critical": ((), {"SECURITY": "🛡️ security 50 % critical 1 (medusa: 1 finding)\n", "SECURITY_CODE": "1"}, 4), + } + for name, (extra, outputs, code) in cases.items(): + with self.subTest(name): + done = self.run_block(*FIGURES, *extra, **outputs) + self.assertEqual(done.returncode, code, done.stderr) + + +class TestFailures(BlockCase): + def test_a_failing_script_is_named_and_nothing_is_printed(self): + cases = { + "security.py exited 4: 🛡️ security – (not covered: a.py: review by hand)": { + "SECURITY": "🛡️ security – (not covered: a.py: review by hand)\n", "SECURITY_CODE": "4"}, + "gate.py exited 2: gate: kvb-gate.json cannot be trusted": { + "GATE_ERR": "gate: kvb-gate.json cannot be trusted\n", "GATE_CODE": "2"}, + "tokens.py printed no figure: nothing changed": {"TOKENS": "nothing changed\n"}, + "measure.py exited 2: base: make exited 2": {"MEASURE_ERR": "base: make exited 2\n", "MEASURE_CODE": "2"}, + } + for message, outputs in cases.items(): + with self.subTest(message): + done = self.run_block(*FIGURES, "--transcripts", "/t", "--", "make", **outputs) + self.assertEqual((done.returncode, done.stdout, done.stderr), (2, "", f"block: {message}\n")) + + def test_saves_without_evidence_is_a_usage_error_before_any_script(self): + done = self.run_block(*FIGURES, "--transcripts", "/t", "--saves", "500") + self.assertEqual(done.returncode, 2) + self.assertIn("--saves needs --evidence and --transcripts", done.stderr) + self.assertEqual(self.calls(), []) + + def test_an_out_of_range_fix_is_a_usage_error_before_any_script(self): + done = self.run_block("--fix", "120", "--break", "2") + self.assertEqual(done.returncode, 2) + self.assertEqual(self.calls(), []) + + +class TestCommitPath(unittest.TestCase): + def test_the_commit_skill_runs_block_py_and_loads_no_scoring_skill(self): + text = (SKILLS / "kvb-git-commit-no-verify" / "SKILL.md").read_text(encoding="utf-8") + self.assertIn("kvb-check-score/scripts/block.py", text) + loaded = set(SKILL_NAME.findall(re.sub(r"kvb-[a-z-]+/\S+", "", text))) + self.assertEqual(loaded & CHAIN, set()) + self.assertLessEqual({"kvb-check-confidence", "kvb-check-break-risk"}, loaded) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_bounded_files.py b/tests/test_bounded_files.py new file mode 100644 index 0000000..c0d5cd9 --- /dev/null +++ b/tests/test_bounded_files.py @@ -0,0 +1,252 @@ +"""Exercise requirement 061: the council files on hot paths stay small and are read only when they changed.""" + +from __future__ import annotations + +import contextlib +import io +import json +import os +import signal +import tempfile +import threading +import time +import unittest +from pathlib import Path +from unittest import mock + +from test_council_root import QUEUE, WATCH, load, rows +from test_queue_cleanup import CLEANUP, FakeClock + +DAY = 86400 +CFG = {"load_limits": {"cpu_percent": 90, "mem_percent": 90}} + + +def clock(wall: float) -> FakeClock: + return FakeClock(wall, lambda _seconds: None) + + +class Council(unittest.TestCase): + def setUp(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.base = Path(tmp.name).resolve() + self.root = self.base / "council" + self.root.mkdir(mode=0o700) + self.kept = self.base / "state" / "agents-council" + self.home = self.base / "home" + (self.home / ".claude" / "sessions").mkdir(parents=True) + env = mock.patch.dict(os.environ, { + "AGENTS_COUNCIL_ROOT": str(self.root), "XDG_STATE_HOME": str(self.base / "state"), "HOME": str(self.home), + "AGENTS_COUNCIL_CONFIG": str(self.base / "config.json"), + }) + env.start() + self.addCleanup(env.stop) + os.environ.pop("CLAUDE_CODE_SESSION_ID", None) + + def watch(self): + return load(WATCH, f"bounded_watch_{id(self)}") + + +class TestAlerts(Council): + def test_ten_prompts_with_an_unchanged_alerts_file_read_it_once(self): + watch = self.watch() + watch.alert("warn", "RESOURCE WARN: low", False) + with mock.patch.object(watch, "history_rows", wraps=watch.history_rows) as parsed: + shown = [watch.unseen_alerts("s1") for _ in range(10)] + self.assertEqual(shown, [["RESOURCE WARN: low"]] + [[]] * 9) + self.assertEqual(parsed.call_count, 1) + watch.alert("stop", "RESOURCE STOP: lower", False) + self.assertEqual(watch.unseen_alerts("s1"), ["RESOURCE STOP: lower"]) + + def test_an_older_bare_seen_mark_still_counts(self): + watch = self.watch() + watch.alert("warn", "seen before", False) + newest = json.loads(watch.ALERTS.read_text(encoding="utf-8").splitlines()[-1])["id"] + (self.root / "seen").mkdir() + (self.root / "seen" / "s1").write_text(str(newest), encoding="utf-8") + self.assertEqual(watch.unseen_alerts("s1"), []) + + def test_an_append_drops_the_rows_past_the_ttl(self): + watch = self.watch() + now = time.time_ns() + old = {"id": now - (watch.ALERT_TTL + 1) * 10**9, "stage": "warn", "text": "old", "chair": False} + young = {"id": now - 10**9, "stage": "warn", "text": "young", "chair": False} + watch.ALERTS.write_text(f"{json.dumps(old)}\nnot json\n{json.dumps(young)}\n", encoding="utf-8") + watch.alert("stop", "new", False) + texts = [json.loads(line)["text"] for line in watch.ALERTS.read_text(encoding="utf-8").splitlines()] + self.assertEqual(texts, ["young", "new"]) + + def test_a_recovered_line_reaches_only_the_chair(self): + watch = self.watch() + (self.root / "chair").mkdir() + (self.root / "chair" / "claim.json").write_text(json.dumps({"office": "chair", "session": "s0"}), encoding="utf-8") + watch.alert("ok", "RESOURCE OK: recovered", True) + watch.alert("warn", "RESOURCE WARN: low", False) + self.assertEqual(watch.unseen_alerts("s1"), ["RESOURCE WARN: low"]) + self.assertEqual(watch.unseen_alerts("s0"), ["RESOURCE OK: recovered", "RESOURCE WARN: low"]) + self.assertEqual(watch.unseen_alerts("s1"), []) + + def test_a_memory_value_flapping_around_its_threshold_alerts_once_per_stage_change(self): + watch = self.watch() + cfg = {"thresholds_gb": {"warn": -1, "stop": -2, "critical": -3}, "projection_minutes": 30, "cache_interval_seconds": DAY} + measured = ["warn", "ok", "warn", "ok", "warn", "ok", "ok", "ok"] + state = {"caches_checked": time.time()} + with ( + mock.patch.object(watch, "disk", return_value=(100.0, 200.0)), + mock.patch.object(watch, "memory", return_value={}), + mock.patch.object(watch, "memory_stage", side_effect=measured), + mock.patch.object(watch, "act_memory") as acted, + ): + for step in range(len(measured)): + watch.measure_and_act(cfg, state, time.time() + step, None) + self.assertEqual([(call.args[1], call.args[2]) for call in acted.call_args_list], [("warn", "ok"), ("ok", "warn")]) + self.assertEqual(state["memory_stage"], "ok") + + def test_a_higher_stage_is_entered_at_once_and_a_lower_one_after_two_samples(self): + settle = self.watch().settled_memory + self.assertEqual(settle("ok", "stop", 0), ("stop", 0)) + self.assertEqual(settle("stop", "warn", 0), ("stop", 1)) + self.assertEqual(settle("stop", "stop", 1), ("stop", 0)) + self.assertEqual(settle("stop", "ok", 1), ("ok", 0)) + + +class TestMirror(Council): + def setUp(self): + super().setUp() + self.mirror = self.watch() + self.source = self.mirror.ACCEPTED + self.target = self.mirror.KEPT_ACCEPTED + self.stamp = time.time_ns() + + def keep(self) -> list[str]: + self.mirror.keep_rows(self.source, self.target) + return rows(self.target) + + def touch(self) -> None: + self.stamp += 10**6 + os.utime(self.source, ns=(self.stamp, self.stamp)) + + def write(self, text: str) -> None: + with self.source.open("a", encoding="utf-8") as source: + source.write(text) + self.touch() + + def add(self, *ids: str) -> None: + self.write("".join(json.dumps({"id": row_id}) + "\n" for row_id in ids)) + + def test_a_grown_source_mirrors_only_its_new_rows(self): + self.add("r1", "r2") + self.assertEqual(self.keep(), ["r1", "r2"]) + self.target.write_text(json.dumps({"id": "r2"}) + "\n", encoding="utf-8") + self.add("r3") + self.assertEqual(self.keep(), ["r2", "r3"]) + + def test_a_rewritten_or_shrunk_source_merges_every_missing_row(self): + self.add("r1", "r2") + self.keep() + fresh = self.base / "fresh.jsonl" + fresh.write_text(json.dumps({"id": "r1"}) + "\n" + json.dumps({"id": "r4"}) + "\n", encoding="utf-8") + fresh.replace(self.source) + self.touch() + self.assertEqual(self.keep(), ["r1", "r2", "r4"]) + self.source.write_text(json.dumps({"id": "r5"}) + "\n", encoding="utf-8") + self.touch() + self.assertEqual(self.keep(), ["r1", "r2", "r4", "r5"]) + + def test_a_fresh_copy_sharing_the_source_mtime_still_mirrors_every_row(self): + self.add("r1", "r2") + self.target.parent.mkdir(parents=True, exist_ok=True) + self.target.write_text("", encoding="utf-8") + os.utime(self.target, ns=(self.stamp, self.stamp)) + self.assertEqual(self.keep(), ["r1", "r2"]) + + def test_a_row_appended_within_the_same_mtime_tick_mirrors_next_round(self): + self.add("r1") + self.assertEqual(self.keep(), ["r1"]) + with self.source.open("a", encoding="utf-8") as source: + source.write(json.dumps({"id": "r2"}) + "\n") + os.utime(self.source, ns=(self.stamp, self.stamp)) + self.assertEqual(self.keep(), ["r1", "r2"]) + + def test_a_line_still_being_written_waits_for_the_next_mirror(self): + self.add("r1") + self.write('{"id": "r2"') + self.assertEqual(self.keep(), ["r1"]) + self.write("}\n") + self.assertEqual(self.keep(), ["r1", "r2"]) + + +class TestTrim(Council): + def test_a_cleanup_round_drops_the_history_rows_over_30_days_old_and_keeps_the_rest_byte_for_byte(self): + cleanup = load(CLEANUP, f"bounded_cleanup_{id(self)}") + now = float(int(time.time())) + old = json.dumps({"id": "old", "end": now - 31 * DAY}) + "\n" + young = '{"end": %s, "id": "young"}\n' % (now - DAY) + kept = young + "not json\n" + self.kept.mkdir(parents=True, mode=0o700) + for path in (cleanup.watch.HISTORY, cleanup.watch.KEPT_HISTORY): + path.write_text(old + young + "not json\n" + old, encoding="utf-8") + out = io.StringIO() + with contextlib.redirect_stdout(out), contextlib.redirect_stderr(io.StringIO()): + code = cleanup.run_round(900, clock(now)) + self.assertEqual(code, 0) + self.assertIn("dropped 4 queue history rows that ended over 30 days ago", out.getvalue()) + for path in (cleanup.watch.HISTORY, cleanup.watch.KEPT_HISTORY): + with self.subTest(path=path.parent.name): + self.assertEqual(path.read_text(encoding="utf-8"), kept) + out = io.StringIO() + with contextlib.redirect_stdout(out), contextlib.redirect_stderr(io.StringIO()): + cleanup.run_round(900, clock(now)) + self.assertNotIn("dropped", out.getvalue()) + + +class TestQueue(Council): + def setUp(self): + super().setUp() + self.queue = load(QUEUE, f"bounded_queue_{id(self)}") + + def test_learned_reads_the_histories_once_until_one_changes(self): + queue = self.queue + now = time.time() + row = {"id": "j1", "kind": "test", "signature": "make test", "workdir": "/w", "start": now - 60, "end": now, + "minutes": 1, "disk_gb": 0, "mem_before": 10, "mem_max": 20, "cpu_before": 10, "cpu_max": 20} + queue.watch.HISTORY.write_text(json.dumps(row) + "\n", encoding="utf-8") + with mock.patch.object(queue.history, "read", wraps=queue.history.read) as reads: + first = queue.learned(CFG, now) + self.assertIs(queue.learned(CFG, now + 20), first) + self.assertEqual(reads.call_count, 1) + with queue.watch.HISTORY.open("a", encoding="utf-8") as history: + history.write(json.dumps({**row, "id": "j2"}) + "\n") + self.assertEqual(queue.learned(CFG, now)[0][("test", "make test")]["runs"], 2) + queue.learned({**CFG, "light_kinds": ["test"]}, now) + self.assertEqual(reads.call_count, 3) + + def test_a_waiting_hold_pauses_a_whole_poll_and_wakes_at_once_on_a_signal(self): + queue = self.queue + wake, alarm = os.pipe() + self.addCleanup(os.close, wake) + self.addCleanup(os.close, alarm) + os.set_blocking(alarm, False) + previous = signal.set_wakeup_fd(alarm, warn_on_full_buffer=False) + self.addCleanup(signal.set_wakeup_fd, previous) + caught: list[int] = [] + handler = signal.signal(signal.SIGUSR1, lambda signum, _frame: caught.append(signum)) + self.addCleanup(signal.signal, signal.SIGUSR1, handler) + with mock.patch.object(queue, "POLL_SECONDS", 0.5): + start = time.monotonic() + queue.pause(wake) + quiet = time.monotonic() - start + with mock.patch.object(queue, "POLL_SECONDS", 30): + timer = threading.Timer(0.1, os.kill, (os.getpid(), signal.SIGUSR1)) + timer.start() + self.addCleanup(timer.cancel) + start = time.monotonic() + queue.pause(wake) + woken = time.monotonic() - start + self.assertGreaterEqual(quiet, 0.5) + self.assertLess(woken, 5) + self.assertEqual(caught, [signal.SIGUSR1]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_coach.py b/tests/test_coach.py deleted file mode 100644 index 11d1576..0000000 --- a/tests/test_coach.py +++ /dev/null @@ -1,122 +0,0 @@ -"""Exercise coach.py: preferences flip between like and dislike, the log feeds hours since.""" - -from __future__ import annotations - -import json -import subprocess -import sys -import tempfile -import unittest -from pathlib import Path - -REPO_ROOT = Path(__file__).resolve().parents[1] -SCRIPT = REPO_ROOT / "skills" / "kvb-coach" / "scripts" / "coach.py" -HOOK = REPO_ROOT / "skills" / "kvb-coach" / "hooks" / "reminder.sh" - - -class TestCoach(unittest.TestCase): - def setUp(self): - self.tmp = tempfile.TemporaryDirectory() - self.addCleanup(self.tmp.cleanup) - self.profile = Path(self.tmp.name) / "state" / "coach.json" - - def _run(self, *args: str) -> subprocess.CompletedProcess: - return subprocess.run( - [sys.executable, str(SCRIPT), "--profile", str(self.profile), *args], - check=False, - capture_output=True, - text=True, - ) - - def _show(self, now: str) -> dict: - result = self._run("show", "--now", now, "--json") - self.assertEqual(result.returncode, 0, result.stderr) - return {row["area"]: row for row in json.loads(result.stdout)} - - def test_a_dislike_replaces_a_like_and_forget_drops_it(self): - self._run("like", "body", "Running") - self._run("like", "body", "Running") - self._run("like", "body", "Yoga") - self._run("dislike", "body", "Running") - body = self._show("2026-11-03T18:00:00+00:00")["body"] - self.assertEqual(body["likes"], ["Yoga"]) - self.assertEqual(body["dislikes"], ["Running"]) - self._run("forget", "body", "Running") - self.assertEqual(self._show("2026-11-03T18:00:00+00:00")["body"]["dislikes"], []) - - def test_the_latest_done_per_area_gives_the_hours_since(self): - self._run("done", "food", "Breakfast", "--at", "2026-11-03T08:00:00+00:00") - self._run("done", "food", "Lunch", "--at", "2026-11-03T12:30:00+00:00") - self._run("done", "sleep", "Night", "--at", "2026-11-02T23:00:00+00:00") - rows = self._show("2026-11-03T18:00:00+00:00") - self.assertEqual((rows["food"]["last"], rows["food"]["hours_ago"]), ("Lunch", 5.5)) - self.assertEqual(rows["sleep"]["hours_ago"], 19.0) - self.assertIsNone(rows["psyche"]["last"]) - - def test_invalid_input_exits_2_and_keeps_the_profile(self): - self.assertEqual(self._run("like", "work", "x").returncode, 2) - self.assertEqual(self._run("done", "body", "x", "--at", "yesterday").returncode, 2) - self.assertFalse(self.profile.exists()) - self.profile.parent.mkdir(parents=True) - self.profile.write_text("{broken", encoding="utf-8") - self.assertEqual(self._run("show").returncode, 2) - self.assertEqual(self.profile.read_text(encoding="utf-8"), "{broken") - - -class TestCoachHour(unittest.TestCase): - def setUp(self): - self.tmp = tempfile.TemporaryDirectory() - self.addCleanup(self.tmp.cleanup) - self.hours = Path(self.tmp.name) / "hours" - - def _run(self, hour: str) -> str: - return subprocess.run( - ["bash", str(HOOK)], - check=True, - capture_output=True, - text=True, - env={ - "PATH": "/usr/bin:/bin", - "HOME": self.tmp.name, - "COACH_STAMP_DIR": str(self.hours), - "COACH_HOUR": hour, - }, - ).stdout - - def test_first_prompt_of_each_hour_triggers_the_coach_once(self): - self.assertIn("kvb-coach", self._run("2026-11-03T14")) - self.assertEqual(self._run("2026-11-03T14"), "") - self.assertIn("kvb-coach", self._run("2026-11-03T15")) - self.assertEqual(sorted(p.name for p in self.hours.iterdir()), ["2026-11-03T15"]) - - def test_the_hour_picks_one_fixed_tip_and_loads_no_skill(self): - tips = {hour: self._run(f"2026-11-03T{hour}").splitlines() for hour in ("23", "04", "12", "19", "09", "16")} - firsts = {hour: lines[1].split(" ", 1)[0] for hour, lines in tips.items()} - self.assertEqual(firsts, {"23": "😴", "04": "😴", "12": "🥗", "19": "🥗", "09": "🚶", "16": "🚶"}) - self.assertTrue(all(len(lines) == 2 and "load no skill" in lines[0] for lines in tips.values())) - - def test_a_binary_planted_on_the_inherited_path_never_runs(self): - planted = Path(self.tmp.name) / "planted" - planted.mkdir() - marker = Path(self.tmp.name) / "ran" - for name in ("mkdir", "find", "cat", "date"): - fake = planted / name - fake.write_text(f"#!/bin/sh\n/usr/bin/touch '{marker}'\n", encoding="utf-8") - fake.chmod(0o755) - subprocess.run( - ["bash", str(HOOK)], - check=True, - capture_output=True, - text=True, - env={ - "PATH": f"{planted}:/usr/bin:/bin", - "HOME": self.tmp.name, - "COACH_STAMP_DIR": str(self.hours), - "COACH_HOUR": "2026-11-03T14", - }, - ) - self.assertFalse(marker.exists()) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_code_graph.py b/tests/test_code_graph.py index c27995b..9b2c70e 100644 --- a/tests/test_code_graph.py +++ b/tests/test_code_graph.py @@ -19,7 +19,7 @@ SCRIPT = REPO_ROOT / "skills" / "kvb-agent-optimize" / "scripts" / "graph.py" GIT = shutil.which("git") TASK = "work/code-graph-index" NOTICE = "codebase-memory-mcp: no permanent daemon; run: systemctl --user enable --now kvb-code-graph.service" -PENDING = "codebase-memory-mcp: kvb-code-graph.service starts the permanent daemon within 30 s after the last session ends; nothing to do" +PENDING = "codebase-memory-mcp: kvb-code-graph.service starts the permanent daemon within 120 s after the last session ends; nothing to do" STUCK = "codebase-memory-mcp: no daemon although kvb-code-graph.service is active; check: journalctl --user -u kvb-code-graph.service" FAKE_BINARY = """import json, os, sys, time refused = {"refuse": "async", "vanish": "status"} diff --git a/tests/test_council_root.py b/tests/test_council_root.py index 4fb33d1..970e44e 100644 --- a/tests/test_council_root.py +++ b/tests/test_council_root.py @@ -352,7 +352,7 @@ class TestMigrate(Home): units = (REPO_ROOT / "scripts" / "orchestrator.sh").read_text(encoding="utf-8") body = units[units.index("stop_all() {"):] body = body[:body.index("\n}\n")] - for unit in ("${RUNNER}", "${OFFICES_UNIT}.path", "${RESOURCES_UNIT}.timer", "${RESOURCES_UNIT}.service", "compose"): + for unit in ("${RUNNER}", "${OFFICES_UNIT}.path", "${RESOURCES_UNIT}.timer", "${RESOURCES_UNIT}.service", "${TOKENS_UNIT}.timer", "${TOKENS_UNIT}.service", "compose"): with self.subTest(unit=unit): self.assertIn(unit, body) self.assertIn("stop) stop_all ;;", units) diff --git a/tests/test_dream.py b/tests/test_dream.py index 2063a1b..0f47b0d 100644 --- a/tests/test_dream.py +++ b/tests/test_dream.py @@ -48,25 +48,41 @@ class TestDreamSkill(unittest.TestCase): self.assertIn(f"`{skill}`", text) +def council_with(root: Path, rows: dict | None) -> dict: + """Args: + root: the council directory to create. + rows: the schedules.json content, None for no file. + + Returns: + The environment entry that points the hooks at root. + """ + root.mkdir(parents=True, exist_ok=True) + if rows is not None: + (root / "schedules.json").write_text(json.dumps(rows), encoding="utf-8") + return {"AGENTS_COUNCIL_ROOT": str(root)} + + class TestDreamHook(unittest.TestCase): def setUp(self): self.tmp = tempfile.TemporaryDirectory() self.addCleanup(self.tmp.cleanup) self.stamps = Path(self.tmp.name) / "stamps" + self.council = Path(self.tmp.name) / "council" + self.schedule({"on": True, "every": 12}) - def _run(self, payload: str, interval: str = "43200") -> str: + def schedule(self, row: dict | None) -> None: + self.env = council_with(self.council, None if row is None else {"dream": row}) + if row is None: + (self.council / "schedules.json").unlink(missing_ok=True) + + def _run(self, payload: str, path: str = "/usr/bin:/bin") -> str: return subprocess.run( ["bash", str(HOOK)], input=payload, capture_output=True, text=True, check=True, - env={ - "PATH": "/usr/bin:/bin", - "HOME": self.tmp.name, - "DREAM_STAMP_DIR": str(self.stamps), - "DREAM_INTERVAL_SECONDS": interval, - }, + env={"PATH": path, "HOME": self.tmp.name, "DREAM_STAMP_DIR": str(self.stamps), **self.env}, ).stdout @staticmethod @@ -85,9 +101,22 @@ class TestDreamHook(unittest.TestCase): self._run(self._session("a1")) self.assertIn("/kvb-dream", self._run(self._session("b2"))) - def test_hint_returns_after_the_interval(self): - self._run(self._session("a1")) - self.assertIn("/kvb-dream", self._run(self._session("a1"), interval="0")) + def test_hint_returns_after_the_rows_hours(self): + self.schedule({"on": True, "every": 2}) + self.stamps.mkdir() + stamp = self.stamps / "a1" + now = int(subprocess.run(["date", "+%s"], capture_output=True, text=True, check=True).stdout) + stamp.write_text(f"{now - 3600}\n", encoding="utf-8") + self.assertEqual(self._run(self._session("a1")), "") + stamp.write_text(f"{now - 7300}\n", encoding="utf-8") + self.assertIn("/kvb-dream", self._run(self._session("a1"))) + + def test_the_row_off_or_no_schedules_file_keeps_it_silent_and_stamps_nothing(self): + for row in ({"on": False, "every": 12}, None): + with self.subTest(row=row): + self.schedule(row) + self.assertEqual(self._run(self._session("a1")), "") + self.assertFalse(self.stamps.exists()) def test_corrupt_stamp_does_not_crash(self): self.stamps.mkdir() @@ -108,19 +137,7 @@ class TestDreamHook(unittest.TestCase): fake = planted / name fake.write_text(f"#!/bin/sh\n/usr/bin/touch '{marker}'\n", encoding="utf-8") fake.chmod(0o755) - subprocess.run( - ["bash", str(HOOK)], - input=self._session("a1"), - capture_output=True, - text=True, - check=True, - env={ - "PATH": f"{planted}:/usr/bin:/bin", - "HOME": self.tmp.name, - "DREAM_STAMP_DIR": str(self.stamps), - "DREAM_INTERVAL_SECONDS": "43200", - }, - ) + self._run(self._session("a1"), path=f"{planted}:/usr/bin:/bin") self.assertFalse(marker.exists()) @@ -134,13 +151,15 @@ class TestDreamNotification(unittest.TestCase): fake = self.bin / "notify-send" fake.write_text(f'#!/bin/sh\nprintf "%s\\n" "$@" >> "{self.calls}"\n', encoding="utf-8") fake.chmod(0o755) + self.council = Path(self.tmp.name) / "council" - def _run(self, desktop: str) -> None: + def _run(self, desktop: str, row: dict | None = None) -> None: + rows = {"dream-popup": row or {"on": True, "at": ["17:00"]}} subprocess.run( ["bash", str(NOTIFY)], capture_output=True, check=True, - env={"PATH": f"{self.bin}:/usr/bin:/bin", "XDG_CURRENT_DESKTOP": desktop}, + env={"PATH": f"{self.bin}:/usr/bin:/bin", "XDG_CURRENT_DESKTOP": desktop, "HOME": self.tmp.name, **council_with(self.council, rows)}, ) def test_gnome_session_gets_the_popup(self): @@ -151,6 +170,18 @@ class TestDreamNotification(unittest.TestCase): self._run("KDE") self.assertFalse(self.calls.exists()) + def test_the_popup_row_off_or_a_missing_schedules_file_sends_nothing(self): + self._run("ubuntu:GNOME", {"on": False, "at": ["17:00"]}) + self.assertFalse(self.calls.exists()) + (self.council / "schedules.json").unlink() + subprocess.run( + ["bash", str(NOTIFY)], + capture_output=True, + check=True, + env={"PATH": f"{self.bin}:/usr/bin:/bin", "XDG_CURRENT_DESKTOP": "ubuntu:GNOME", "HOME": self.tmp.name, "AGENTS_COUNCIL_ROOT": str(self.council)}, + ) + self.assertFalse(self.calls.exists()) + def test_timer_fires_daily_at_five_pm_and_catches_up(self): timer = TIMER.read_text(encoding="utf-8") self.assertIn("OnCalendar=*-*-* 17:00:00", timer) @@ -194,12 +225,14 @@ class TestSettingsRegistration(unittest.TestCase): ("Stop", "kvb-org-radio/scripts/radio.py"): 2, ("PreToolUse", "kvb-org-radio/scripts/radio.py"): 1, ("PreToolUse", "kvb-org-organize/scripts/council.py"): 1, - ("PreToolUse", "kvb-org-organize/scripts/watch.py"): 1, - ("PreToolUse", "kvb-org-queue/scripts/queue.py"): 1, + ("PreToolUse", "kvb-org-organize/scripts/watch.py"): 0, + ("PreToolUse", "kvb-org-queue/scripts/queue.py"): 0, ("PreToolUse", "kvb-org-perform/scripts/log.py"): 1, ("PreToolUse", "kvb-agent-optimize/scripts/graph.py"): 1, - ("PostToolUse", "kvb-org-organize/scripts/watch.py"): 1, - ("PostToolUse", "kvb-org-perform/scripts/log.py"): 1, + ("PreToolUse", "kvb-org-organize/scripts/hooks.py"): 1, + ("PostToolUse", "kvb-org-organize/scripts/watch.py"): 0, + ("PostToolUse", "kvb-org-perform/scripts/log.py"): 0, + ("PostToolUse", "kvb-org-organize/scripts/hooks.py"): 1, } for (event, script), count in expected.items(): with self.subTest(event=event, script=script): @@ -218,39 +251,86 @@ class TestSettingsRegistration(unittest.TestCase): for entry in data["hooks"]["PreToolUse"] if any(hook["command"].endswith("radio.py\" block") for hook in entry["hooks"]) ] - self.assertEqual(block["matcher"], "Edit|Write|MultiEdit|NotebookEdit|Bash") - (gate,) = self._hooks(data, "PreToolUse", "kvb-org-queue/scripts/queue.py") + self.assertEqual(block["matcher"], "Edit|Write|MultiEdit|NotebookEdit") + (gate,) = self._hooks(data, "PreToolUse", "kvb-org-organize/scripts/hooks.py") result = subprocess.run(["sh", "-c", gate["command"]], capture_output=True, check=False) self.assertEqual(result.returncode, 1) def test_a_hook_runs_its_script_as_main_from_cached_bytecode_and_keeps_its_exit_code(self): - (gate,) = self._hooks(self._patch(), "PreToolUse", "kvb-org-queue/scripts/queue.py") - script = Path(self.tmp.name) / "skills" / "kvb-org-queue" / "scripts" / "queue.py" + (gate,) = self._hooks(self._patch(), "PreToolUse", "kvb-org-organize/scripts/hooks.py") + script = Path(self.tmp.name) / "skills" / "kvb-org-organize" / "scripts" / "hooks.py" script.parent.mkdir(parents=True) script.write_text("import sys\nprint(__name__, sys.argv[1:], sys.argv[0] == __file__)\nsys.exit(3)\n", encoding="utf-8") runs = [subprocess.run(["sh", "-c", gate["command"]], capture_output=True, text=True, check=False) for _ in range(2)] - self.assertEqual([(run.returncode, run.stdout) for run in runs], [(3, "__main__ ['block'] True\n")] * 2) - self.assertEqual([path.name.split(".")[0] for path in (script.parent / "__pycache__").iterdir()], ["queue"]) + self.assertEqual([(run.returncode, run.stdout) for run in runs], [(3, "__main__ ['pre-bash'] True\n")] * 2) + self.assertEqual([path.name.split(".")[0] for path in (script.parent / "__pycache__").iterdir()], ["hooks"]) - def test_every_bash_gate_answers_under_the_cached_loader_as_it_does_started_directly(self): + def bash_entries(self, data: dict, event: str) -> list[dict]: + return [entry for entry in data["hooks"].get(event, []) if not entry.get("matcher") or entry["matcher"] == "*" or re.fullmatch(entry["matcher"], "Bash")] + + def answer(self, command: str, home: Path, event: str) -> tuple: + home.mkdir() + env = {"PATH": "/usr/bin:/bin", "HOME": str(home), "AGENTS_COUNCIL_ROOT": str(home / "council"), "XDG_STATE_HOME": str(home / "state")} + payload = json.dumps({"session_id": "s", "hook_event_name": event, "tool_name": "Bash", "tool_input": {"command": "ls"}, "tool_response": {"stdout": ""}, "cwd": "/"}) + done = subprocess.run(["sh", "-c", command], input=payload, cwd="/", env=env, capture_output=True, text=True, timeout=60, check=False) + return done.returncode, done.stdout.replace(str(home), "~"), done.stderr.replace(str(home), "~") + + def test_the_bash_dispatcher_answers_as_its_handlers_started_directly(self): + data = self._patch() + skills = Path(self.tmp.name) / "skills" + skills.symlink_to(REPO_ROOT / "skills") + handlers = { + ("PreToolUse", "pre-bash"): [("kvb-org-radio/scripts/radio.py", "block"), ("kvb-org-organize/scripts/watch.py", "block"), ("kvb-org-queue/scripts/queue.py", "block"), ("kvb-agent-optimize/scripts/graph.py", "hook")], + ("PostToolUse", "post-bash"): [("kvb-org-organize/scripts/watch.py", "watch"), ("kvb-org-perform/scripts/log.py", "persist")], + } + for (event, sub), scripts in handlers.items(): + with self.subTest(event=event): + (gate,) = [hook for entry in self.bash_entries(data, event) for hook in entry["hooks"] if "importlib" in hook["command"]] + self.assertTrue(gate["command"].endswith(f'hooks.py" {sub}')) + direct = [self.answer(f'/usr/bin/python3 -I "{skills / script}" {name}', Path(self.tmp.name) / f"direct-{sub}-{n}", event) for n, (script, name) in enumerate(scripts)] + self.assertEqual([code for code, _, _ in direct], [0] * len(scripts), direct) + self.assertEqual(self.answer(gate["command"], Path(self.tmp.name) / f"dispatched-{sub}", event), (0, "".join(out for _, out, _ in direct), "".join(err for _, _, err in direct))) + + def test_one_bash_call_starts_one_python_per_hook_event(self): data = self._patch() (Path(self.tmp.name) / "skills").symlink_to(REPO_ROOT / "skills") + counter = Path(self.tmp.name) / "started" + fake = Path(self.tmp.name) / "python3" + fake.write_text(f'#!/bin/sh\necho started >> "{counter}"\nexec /usr/bin/python3 "$@"\n', encoding="utf-8") + fake.chmod(0o755) + for event in ("PreToolUse", "PostToolUse"): + with self.subTest(event=event): + counter.unlink(missing_ok=True) + commands = [hook["command"] for entry in self.bash_entries(data, event) for hook in entry["hooks"]] + for n, command in enumerate(commands): + self.answer(command.replace("/usr/bin/python3", str(fake)), Path(self.tmp.name) / f"count-{event}-{n}", event) + self.assertEqual(counter.read_text(encoding="utf-8").count("started"), 1) - def answer(command: str, home: Path) -> tuple: - home.mkdir() - env = {"PATH": "/usr/bin:/bin", "HOME": str(home), "AGENTS_COUNCIL_ROOT": str(home / "council"), "XDG_STATE_HOME": str(home / "state")} - payload = json.dumps({"session_id": "s", "hook_event_name": "PreToolUse", "tool_name": "Bash", "tool_input": {"command": "ls"}, "cwd": "/"}) - done = subprocess.run(["sh", "-c", command], input=payload, cwd="/", env=env, capture_output=True, text=True, timeout=60, check=False) - return done.returncode, done.stdout.replace(str(home), "~"), done.stderr.replace(str(home), "~") + def test_the_six_separate_bash_entries_are_rewritten_to_two(self): + base = Path(self.tmp.name) / "skills" - bash = [entry for entry in data["hooks"]["PreToolUse"] if "matcher" not in entry or "Bash" in entry["matcher"].split("|")] - gates = [re.search(r' ("[^"]+\.py") (\w+)$', hook["command"]) for entry in bash for hook in entry["hooks"] if "importlib" in hook["command"]] - self.assertEqual(len(gates), 4) - for n, gate in enumerate(gates): - with self.subTest(script=gate[1]): - cached = answer(gate.string, Path(self.tmp.name) / f"cached-{n}") - direct = answer(f"/usr/bin/python3 -I {gate[1]} {gate[2]}", Path(self.tmp.name) / f"direct-{n}") - self.assertEqual(cached, direct) + def entry(matcher: str | None, script: str, sub: str) -> dict: + hook = {"type": "command", "command": f'[ -f "{base}/{script}" ] && /usr/bin/python3 -I "{base}/{script}" {sub}'} + return {"matcher": matcher, "hooks": [hook]} if matcher else {"hooks": [hook]} + + self.settings.write_text(json.dumps({"hooks": { + "PreToolUse": [ + entry("Edit|Write|MultiEdit|NotebookEdit|Bash", "kvb-org-radio/scripts/radio.py", "block"), + entry("Bash", "kvb-org-organize/scripts/watch.py", "block"), + entry("Bash", "kvb-org-queue/scripts/queue.py", "block"), + entry(None, "kvb-agent-optimize/scripts/graph.py", "hook"), + ], + "PostToolUse": [entry("Bash", "kvb-org-organize/scripts/watch.py", "watch"), entry("Bash", "kvb-org-perform/scripts/log.py", "persist")], + }}), encoding="utf-8") + data = self._patch() + for event, sub in (("PreToolUse", "pre-bash"), ("PostToolUse", "post-bash")): + with self.subTest(event=event): + commands = [hook["command"] for entry in self.bash_entries(data, event) for hook in entry["hooks"]] + self.assertEqual(len(commands), 1, commands) + self.assertTrue(commands[0].endswith(f'kvb-org-organize/scripts/hooks.py" {sub}')) + (graph,) = [entry for entry in data["hooks"]["PreToolUse"] if any("graph.py" in hook["command"] for hook in entry["hooks"])] + self.assertEqual(graph["matcher"], "Read|Edit|Write|MultiEdit|NotebookEdit|Grep|Glob") + self.assertEqual(len(self._hooks(data, "PreToolUse", "kvb-org-radio/scripts/radio.py")), 1) def test_news_hook_moves_to_radio(self): base = Path(self.tmp.name) / "skills" @@ -298,7 +378,8 @@ class TestSettingsRegistration(unittest.TestCase): with self.subTest(command=command): self.assertIn("/usr/bin/python3 -I ", command) self.assertNotRegex(command, r"(^|&& )python3 ") - (gate,) = self._hooks(data, "PreToolUse", "kvb-org-queue/scripts/queue.py") + self.assertEqual(self._hooks(data, "PreToolUse", "kvb-org-queue/scripts/queue.py"), []) + (gate,) = self._hooks(data, "PreToolUse", "kvb-org-organize/scripts/hooks.py") self.assertIn("spec_from_file_location", gate["command"]) def test_reminders_run_the_system_bash_and_old_entries_move_to_it(self): diff --git a/tests/test_hook_exec_hardening.py b/tests/test_hook_exec_hardening.py index 9db907e..4e4b0eb 100644 --- a/tests/test_hook_exec_hardening.py +++ b/tests/test_hook_exec_hardening.py @@ -13,6 +13,8 @@ from collections.abc import Callable from pathlib import Path from unittest import mock +from test_dream import council_with + ROOT = Path(__file__).resolve().parents[1] CLIENT = ROOT / "orchestrator" / "client" REMINDER = ROOT / "skills" / "kvb-dream" / "hooks" / "reminder.sh" @@ -467,7 +469,8 @@ class TestReminderHook(Scratch): self.work.mkdir() def run_reminder(self, path: str) -> subprocess.CompletedProcess: - env = {**os.environ, "HOME": str(self.root), "DREAM_STAMP_DIR": str(self.root / "stamps"), "PATH": path} + council = council_with(self.root / "council", {"dream": {"on": True, "every": 12}}) + env = {**os.environ, **council, "HOME": str(self.root), "DREAM_STAMP_DIR": str(self.root / "stamps"), "PATH": path} return subprocess.run(["/usr/bin/bash", str(REMINDER)], cwd=self.work, input='{"session_id": "abc"}', env=env, capture_output=True, text=True, timeout=30, check=False) def test_a_planted_json_module_in_the_cwd_is_never_imported(self): diff --git a/tests/test_hooks.py b/tests/test_hooks.py new file mode 100644 index 0000000..61e0323 --- /dev/null +++ b/tests/test_hooks.py @@ -0,0 +1,102 @@ +from __future__ import annotations + +import json +import os +import shutil +import subprocess +import tempfile +import unittest +from pathlib import Path + +REPO_ROOT = Path(__file__).resolve().parents[1] +DISPATCHER = REPO_ROOT / "skills" / "kvb-org-organize" / "scripts" / "hooks.py" +SCRIPTS = { + "radio": "kvb-org-radio/scripts/radio.py", + "watch": "kvb-org-organize/scripts/watch.py", + "queue": "kvb-org-queue/scripts/queue.py", + "graph": "kvb-agent-optimize/scripts/graph.py", + "log": "kvb-org-perform/scripts/log.py", +} +FAKE = """import json, os, sys +NAME = {name!r} + + +def main(): + event = json.load(sys.stdin) + with open(os.environ["HOOK_LOG"], "a", encoding="utf-8") as log: + log.write(json.dumps([NAME, sys.argv[1:], event["tool_input"]["command"]]) + "\\n") + plan = json.loads(os.environ.get("HOOK_PLAN", "{{}}")).get(NAME, {{}}) + if plan.get("crash"): + raise RuntimeError(NAME + " broke") + if plan.get("out"): + print(plan["out"]) + if plan.get("err"): + print(plan["err"], file=sys.stderr) + if "exit" in plan: + sys.exit(plan["exit"]) + return plan.get("code", 0) +""" +ASK = {"hookSpecificOutput": {"hookEventName": "PreToolUse", "permissionDecision": "ask", "permissionDecisionReason": "held command meets an ask rule"}} + + +class TestHooks(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.root = Path(self.tmp.name) + target = self.root / "kvb-org-organize" / "scripts" / "hooks.py" + target.parent.mkdir(parents=True) + shutil.copy(DISPATCHER, target) + for name, script in SCRIPTS.items(): + path = self.root / script + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(FAKE.format(name=name), encoding="utf-8") + self.log = self.root / "log.jsonl" + + def dispatch(self, sub: str, plan: dict) -> subprocess.CompletedProcess: + self.log.unlink(missing_ok=True) + event = json.dumps({"session_id": "s", "hook_event_name": "PreToolUse", "tool_name": "Bash", "tool_input": {"command": "make test"}}) + env = {**os.environ, "HOOK_LOG": str(self.log), "HOOK_PLAN": json.dumps(plan)} + return subprocess.run(["/usr/bin/python3", "-I", str(self.root / "kvb-org-organize" / "scripts" / "hooks.py"), sub], input=event, env=env, capture_output=True, text=True, timeout=60, check=False) + + def ran(self) -> list[list]: + return [json.loads(line) for line in self.log.read_text(encoding="utf-8").splitlines()] + + def test_each_event_runs_its_handlers_in_order_with_the_same_event_and_their_own_subcommand(self): + self.assertEqual(self.dispatch("pre-bash", {}).returncode, 0) + self.assertEqual(self.ran(), [["radio", ["block"], "make test"], ["watch", ["block"], "make test"], ["queue", ["block"], "make test"], ["graph", ["hook"], "make test"]]) + self.assertEqual(self.dispatch("post-bash", {}).returncode, 0) + self.assertEqual(self.ran(), [["watch", ["watch"], "make test"], ["log", ["persist"], "make test"]]) + + def test_exit_two_blocks_with_the_text_of_every_blocking_handler_after_all_ran(self): + done = self.dispatch("pre-bash", {"watch": {"code": 2, "err": "watch: disk full"}, "queue": {"exit": 2, "err": "queue: through the queue"}, "graph": {"out": json.dumps({"systemMessage": "graph"})}}) + self.assertEqual((done.returncode, done.stdout, done.stderr), (2, "", "watch: disk full\nqueue: through the queue\n")) + self.assertEqual([name for name, _, _ in self.ran()], ["radio", "watch", "queue", "graph"]) + + def test_a_crash_leaves_the_other_handlers_running_and_their_answers_merged(self): + context = {"hookSpecificOutput": {"hookEventName": "PreToolUse", "additionalContext": "watch: alert"}} + done = self.dispatch("pre-bash", {"radio": {"crash": True}, "watch": {"out": json.dumps(context)}, "queue": {"out": json.dumps(ASK)}, "graph": {"out": json.dumps({"systemMessage": "graph: notice"})}}) + self.assertEqual(done.returncode, 0, done.stderr) + self.assertIn("RuntimeError: radio broke", done.stderr) + self.assertEqual([name for name, _, _ in self.ran()], ["radio", "watch", "queue", "graph"]) + self.assertEqual(json.loads(done.stdout), { + "hookSpecificOutput": {"hookEventName": "PreToolUse", "additionalContext": "watch: alert", "permissionDecision": "ask", "permissionDecisionReason": "held command meets an ask rule"}, + "systemMessage": "graph: notice", + }) + + def test_a_single_answer_passes_through_unchanged_and_plain_text_goes_to_stderr(self): + done = self.dispatch("pre-bash", {"queue": {"out": json.dumps(ASK)}, "graph": {"out": "plain words"}}) + self.assertEqual((done.returncode, json.loads(done.stdout)), (0, ASK)) + self.assertEqual(done.stderr, "plain words\n") + + def test_a_missing_handler_is_skipped_and_an_unknown_event_is_refused(self): + (self.root / SCRIPTS["queue"]).unlink() + self.assertEqual(self.dispatch("pre-bash", {}).returncode, 0) + self.assertEqual([name for name, _, _ in self.ran()], ["radio", "watch", "graph"]) + refused = self.dispatch("stop", {}) + self.assertEqual(refused.returncode, 1) + self.assertIn("usage: hooks.py pre-bash|post-bash", refused.stderr) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_host_writes.py b/tests/test_host_writes.py new file mode 100644 index 0000000..fa282f4 --- /dev/null +++ b/tests/test_host_writes.py @@ -0,0 +1,65 @@ +from __future__ import annotations + +import json +import os +import subprocess +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +import hub_support # noqa: F401 +import sessions +import settings_writer +import staged_diff + +ENV = {"PATH": "/usr/bin:/bin", "HOME": "/nonexistent", "GIT_CONFIG_NOSYSTEM": "1", "GIT_CONFIG_GLOBAL": os.devnull} + + +class TestHostWrites(unittest.TestCase): + def setUp(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.base = Path(tmp.name) + + def test_an_unchanged_sessions_snapshot_is_rewritten_only_after_the_refresh(self): + output = self.base / "agent-sessions.json" + data = {"written": 1000.0, "sessions": {"s1": {"name": "One", "running": True}}} + sessions.write(output, data) + first = output.stat().st_ino + sessions.write(output, {**data, "written": 1000.0 + sessions.REFRESH - 1}) + self.assertEqual((output.stat().st_ino, json.loads(output.read_text(encoding="utf-8"))["written"]), (first, 1000.0)) + sessions.write(output, {**data, "written": 1000.0 + sessions.REFRESH}) + self.assertEqual(json.loads(output.read_text(encoding="utf-8"))["written"], 1000.0 + sessions.REFRESH) + changed = {"written": 1000.0 + sessions.REFRESH + 1, "sessions": {}} + sessions.write(output, changed) + self.assertEqual(json.loads(output.read_text(encoding="utf-8")), changed) + + def test_a_settings_view_that_differs_only_in_its_stamp_stays(self): + folder = self.base / "firewall" + folder.mkdir(mode=0o700) + path = folder / "view.json" + view = {"written": 1.0, "files": [{"path": "/x", "exists": True}], "known": []} + settings_writer.write_view(path, view) + first = path.stat().st_ino + settings_writer.write_view(path, {**view, "written": 2.0}) + self.assertEqual((path.stat().st_ino, json.loads(path.read_text(encoding="utf-8"))["written"]), (first, 1.0)) + settings_writer.write_view(path, {**view, "written": 3.0, "known": ["server"]}) + self.assertEqual(json.loads(path.read_text(encoding="utf-8"))["known"], ["server"]) + + def test_a_toplevel_comes_from_git_once_until_head_moves(self): + repo = self.base / "repo" + sub = repo / "a" / "b" + sub.mkdir(parents=True) + subprocess.run(["git", "init", "-q", "-b", "main", str(repo)], env=ENV, check=True) + staged_diff.TOPLEVELS.clear() + with mock.patch.object(staged_diff, "git", wraps=staged_diff.git) as calls: + self.assertEqual((staged_diff.toplevel(sub), staged_diff.toplevel(sub)), (repo.resolve(), repo.resolve())) + self.assertEqual(calls.call_count, 1) + subprocess.run(["git", "symbolic-ref", "HEAD", "refs/heads/other"], cwd=repo, env=ENV, check=True) + self.assertEqual(staged_diff.toplevel(sub), repo.resolve()) + self.assertEqual(calls.call_count, 2) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_hub_agent_settings.py b/tests/test_hub_agent_settings.py new file mode 100644 index 0000000..c103678 --- /dev/null +++ b/tests/test_hub_agent_settings.py @@ -0,0 +1,62 @@ +from __future__ import annotations + +import json +import unittest + +from hub_case import HubCase +from kvb_orchestrator import fields, settings +from kvb_orchestrator.errors import ToolError + +QUIET = {"sound": False, "aloud": False, "bubbles": True} +LOUD = {"sound": True, "aloud": True, "bubbles": True} + + +class TestAgentsSetting(unittest.TestCase): + def test_each_agent_keeps_three_switches_and_an_all_on_entry_is_dropped(self): + self.assertEqual(settings.agents_setting({"s1": QUIET, "s2": LOUD, "name:Docs": {**LOUD, "bubbles": False}}), {"s1": QUIET, "name:Docs": {**LOUD, "bubbles": False}}) + self.assertEqual(settings.agents_setting({}), {}) + + def test_unknown_or_missing_switches_wrong_values_and_oversized_maps_are_refused(self): + wrongs = [ + [], + "s1", + {"s1": {**QUIET, "volume": 1}}, + {"s1": {"sound": False, "aloud": False}}, + {"s1": {**QUIET, "sound": "off"}}, + {"s1": {**QUIET, "sound": 0}}, + {"s1": True}, + {"": QUIET}, + {"x" * (fields.NAME_LIMIT + 1): QUIET}, + {f"s{index}": QUIET for index in range(settings.AGENTS_LIMIT + 1)}, + ] + for wrong in wrongs: + with self.subTest(wrong=str(wrong)[:80]), self.assertRaises(ToolError): + settings.agents_setting(wrong) + + +class TestHubAgentSettings(HubCase): + def test_the_agent_switches_save_without_a_passkey_and_a_page_without_them_keeps_them(self): + good = self.guard(self.host) + current = self.snapshot()["settings"] + self.assertEqual(current["agents"], {}) + quiet = {**current, "agents": {"s1": QUIET, "s2": LOUD}} + status, _, body = self.post_json("/api/settings/sign", quiet, good) + self.assertEqual((status, json.loads(body)["payload"]), (200, None), body) + status, _, body = self.post_json("/api/settings", {**quiet, "proof": None}, good) + self.assertEqual((status, json.loads(body)["settings"]["agents"]), (200, {"s1": QUIET}), body) + older = {key: value for key, value in current.items() if key != "agents"} + status, _, body = self.post_json("/api/settings", {**older, "bubbles": not current["bubbles"], "proof": None}, good) + self.assertEqual((status, json.loads(body)["settings"]["agents"]), (200, {"s1": QUIET}), body) + self.assertEqual(settings.Settings(self.state / "settings.json").get()["agents"], {"s1": QUIET}) + + def test_a_save_with_an_unknown_switch_is_refused_and_changes_nothing(self): + good = self.guard(self.host) + current = self.snapshot()["settings"] + for wrong in ({"s1": {**QUIET, "volume": 1}}, {"s1": {**QUIET, "aloud": "no"}}, ["s1"]): + with self.subTest(wrong=wrong): + self.assertEqual(self.post_json("/api/settings", {**current, "agents": wrong, "proof": None}, good)[0], 400) + self.assertEqual(self.snapshot()["settings"]["agents"], {}) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_hub_box_heads.py b/tests/test_hub_box_heads.py index fe5315d..243dcda 100644 --- a/tests/test_hub_box_heads.py +++ b/tests/test_hub_box_heads.py @@ -84,11 +84,10 @@ class TestBoxHeads(unittest.TestCase): self.assertRegex(page, r"\.box-head \{[^}]*margin: calc\(-1 \* var\(--main-top\)\) calc\(-1 \* var\(--main-pad\)\) 0;") self.assertIn("--main-top: var(--sp-3)", (TEMPLATES / "style-ui.css").read_text(encoding="utf-8")) - def test_the_match_card_bar_is_its_own_background_on_the_outer_edge(self): + def test_the_match_card_bar_flows_from_the_outer_edge_into_the_card(self): css = (TEMPLATES / "style-match.css").read_text(encoding="utf-8") - self.assertNotIn(".match-card.front::before", css) - self.assertRegex(css, r"\.match-card\.front \{[^}]*border-top-width: 0;[^}]*background: var\(--bar\) top / 100% 6px no-repeat") - self.assertIn("mask-image: linear-gradient(180deg, transparent 6px, #000 6px", css) + self.assertRegex(css, r"\.match-card\.front \{[^}]*border-top-width: 0;") + self.assertRegex(css, r"\.match-card\.front::before \{[^}]*inset: 0 0 auto;[^}]*height: 22px; background: var\(--bar\); mask-image: linear-gradient\(180deg, #000 0px 4px, transparent 22px\);") if __name__ == "__main__": diff --git a/tests/test_hub_bubbles.py b/tests/test_hub_bubbles.py index 6d56f00..eb5230a 100644 --- a/tests/test_hub_bubbles.py +++ b/tests/test_hub_bubbles.py @@ -72,8 +72,8 @@ function page(fault) { }, }, Voice: {...Voice, beep: () => null}, - RadioSet: {plan: (row) => (["mayday", "security"].includes(row.class) ? [{kind: "burst"}] : []), ledgerOf: () => null}, - settings: {bubbles: true, channels: {browser: false, sounds: true, aloud: true, title: true}, music: {}}, + RadioSet: {plan: (row) => (["mayday", "security"].includes(row.class) ? [{kind: "burst"}] : []), voiced: (steps) => steps, heard: () => true, ledgerOf: () => null}, + settings: {bubbles: true, channels: {browser: false, sounds: true, aloud: true, title: true}, music: {}, agents: {}}, radioSet: {mode: "auto", classes: ["mayday", "pan-pan", "security"], sounds: {}, squelch: 1}, state: {now: 1000, radio: [], inbox: [], pending: [], messages: [], speech: {tts: false, gate: {open: false}}}, known: {inbox: null, alarms: null, radio: null, batches: new Set(), now: null}, diff --git a/tests/test_hub_channels.py b/tests/test_hub_channels.py index 3965a44..788ceda 100644 --- a/tests/test_hub_channels.py +++ b/tests/test_hub_channels.py @@ -28,7 +28,7 @@ function announced(change) { const mayday = {ts: 10, from: "Docs", to: [], class: "mayday", text: "disk full"}; const direct = {ts: 11, from: "Stage", to: ["Operator"], class: "call", text: "gate red"}; const sandbox = { - Notification, window: {Notification, setTimeout: (run) => run()}, settings: {channels: {...ON, ...change}}, radioSet: {mode: "auto"}, + Notification, window: {Notification, setTimeout: (run) => run()}, settings: {channels: {...ON, ...change}, agents: {}}, RadioSet, radioSet: {mode: "auto"}, state: {inbox: [{id: "r1", kind: "review", title: "feat: x"}], radio: [mayday, direct], pending: []}, known: {inbox: new Set(), alarms: new Set(), radio: new Set(), batches: new Set(), now: null}, live: () => true, alarmRows: () => [mayday], keyOf: (item) => item.id, HUMAN: "Operator", Voice: {beep: () => "mayday"}, tones: () => ({}), loudness: () => 0.5, SOUND_KINDS: [["mayday", "MAYDAY"]], TONES: {mayday: [[880, 0, 0.2]]}, @@ -48,17 +48,29 @@ function synced(before, after) { sandbox.syncChannels({...ON, ...before}); return calls; } -function spoken(aloud, bubbles) { +function spoken(aloud, bubbles, agents = {}, cls = "security") { const said = []; const sandbox = { RadioSet, Bubbles, Voice, radioSet: RadioSet.valid({mode: "auto"}), HUMAN: "Operator", SPEECH_FRESH: 300, short: (value) => value, quietBubbles: () => null, - state: {now: 1000, messages: [], speech: {tts: true, gate: {open: true}}}, settings: {bubbles, channels: {...ON, aloud}}, + state: {now: 1000, messages: [], speech: {tts: true, gate: {open: true}}}, settings: {bubbles, channels: {...ON, aloud}, agents}, }; vm.runInNewContext(speechCode, sandbox); - sandbox.say = (...items) => said.push(...items.map((item) => item.silent)); - sandbox.speakRows([{ts: 1000, from: "Stage", to: [], class: "security", source: "s2", voice: "v2", word: "W", rest: "R", text: "rotate keys now"}]); + sandbox.say = (...items) => said.push(...items.map((item) => [item.silent, item.bubble])); + sandbox.speakRows([{ts: 1000, from: "Stage", to: [], class: cls, source: "s2", voice: "v2", word: "W", rest: "R", text: "rotate keys now"}]); + return said.map(([silent]) => silent); +} +function perAgent(agents, cls = "security") { + const said = []; + const sandbox = { + RadioSet, Bubbles, Voice, radioSet: RadioSet.valid({mode: "quiet"}), HUMAN: "Operator", SPEECH_FRESH: 300, short: (value) => value, quietBubbles: () => null, + state: {now: 1000, messages: [], speech: {tts: true, gate: {open: true}}}, settings: {bubbles: true, channels: ON, agents}, + }; + vm.runInNewContext(speechCode, sandbox); + sandbox.say = (...items) => said.push(...items.map((item) => [item.silent, item.bubble])); + sandbox.speakRows([{ts: 1000, from: "Stage", to: [], class: cls, source: "s2", voice: "v2", word: "W", rest: "R", text: "rotate keys now"}]); return said; } +const OFF = (change) => ({s2: {sound: true, aloud: true, bubbles: true, ...change}}); console.log(JSON.stringify({ announced: {on: announced({}), browser: announced({browser: false}), sounds: announced({sounds: false}), quiet: announced({browser: false, sounds: false, aloud: false, title: false})}, synced: { @@ -66,6 +78,11 @@ console.log(JSON.stringify({ stays: synced({sounds: false, aloud: false}, {sounds: false, aloud: false}), back: synced({sounds: false, aloud: false}, {}), title: synced({}, {title: false}), }, spoken: {on: spoken(true, false), off: spoken(false, false), bubbles: spoken(false, true), both: spoken(true, true)}, + agents: { + all: perAgent({}), aloud: perAgent(OFF({aloud: false})), sound: perAgent(OFF({sound: false})), bubbles: perAgent(OFF({bubbles: false})), + mute: perAgent(OFF({sound: false, aloud: false})), none: perAgent(OFF({sound: false, aloud: false, bubbles: false})), other: perAgent({s9: {sound: false, aloud: false, bubbles: false}}), + mayday: perAgent(OFF({sound: false, aloud: false, bubbles: false}), "mayday"), + }, })); """ @@ -150,6 +167,12 @@ class TestChannelGates(unittest.TestCase): def test_the_read_aloud_channel_plans_no_audible_step_and_keeps_the_silent_bubble(self): self.assertEqual(self.data["spoken"], {"on": [False], "off": [], "bubbles": [True], "both": [False]}) + def test_an_agents_own_switches_silence_its_speech_its_sounds_or_its_bubble_and_spare_other_agents_and_a_mayday(self): + agents = self.data["agents"] + self.assertEqual((agents["all"], agents["other"], agents["mayday"]), ([[False, True]], [[False, True]], [[False, True]])) + self.assertEqual((agents["aloud"], agents["sound"], agents["bubbles"]), ([[False, True]], [[False, True]], [[False, False]])) + self.assertEqual((agents["mute"], agents["none"]), ([[True, True]], [])) + def test_switching_a_channel_off_stops_what_it_already_queued_and_every_switch_redraws_the_title(self): synced = self.data["synced"] self.assertEqual(synced["sounds"], ["silence", "title"]) diff --git a/tests/test_hub_console.py b/tests/test_hub_console.py index 1c767d2..c360dc9 100644 --- a/tests/test_hub_console.py +++ b/tests/test_hub_console.py @@ -90,7 +90,41 @@ class TestHubConsole(HubCase): self.assertEqual(self.get("/api/inbox/dismiss")[0], 405) self.assertEqual(self.dismiss({"id": job["id"]}, self.guard(self.host)), 200) self.assertIsNone(self.item("operator/greet")) - self.assertEqual(self.snapshot()["jobs"][-1]["dismissed"], True) + self.assertEqual(self.snapshot()["jobs"], []) + self.assertEqual(json.loads((self.state / "jobs.json").read_text(encoding="utf-8")), {}) + + def test_a_running_job_keeps_its_output_in_memory_and_writes_the_ledger_only_on_its_end(self): + self.register("queued") + fields = {"task": "operator/greet", "command": COMMAND, "directory": str(self.outside), "sha256": DIGEST, "status": "queued", "proof": None} + job = self.httpd.hub.jobs.add({**fields, "code": None, "output": "", "created_ts": time.time(), "started": None, "finished": None, "dismissed": False}) + self.assertEqual(self.runner(f"/api/runner/{job['id']}/claim", {})[0], 200) + ledger = self.state / "jobs.json" + claimed = ledger.read_bytes() + for lines in range(1, 4): + output = "".join(f"line {n}\n" for n in range(lines)) + self.assertEqual(self.runner(f"/api/runner/{job['id']}/report", {"output": output, "code": None, "refused": False})[0], 200) + self.assertEqual(self.item("operator/greet")["job"]["output"], output) + self.assertEqual(ledger.read_bytes(), claimed) + self.assertEqual(self.runner(f"/api/runner/{job['id']}/report", {"output": "done\n", "code": 0, "refused": False})[0], 200) + stored = json.loads(ledger.read_text(encoding="utf-8"))[job["id"]] + self.assertEqual((stored["status"], stored["output"]), ("done", "done\n")) + + def test_dismissing_a_console_prunes_the_finished_command_jobs_of_its_task_and_keeps_task_changes(self): + self.register("queued") + now = time.time() + base = {"command": COMMAND, "directory": str(self.outside), "sha256": DIGEST, "proof": None, "code": 0, "output": "", "started": now, "finished": now, "dismissed": False} + older = self.httpd.hub.jobs.add({**base, "task": "operator/greet", "status": "failed", "created_ts": now - 20}) + newer = self.httpd.hub.jobs.add({**base, "task": "operator/greet", "status": "done", "created_ts": now - 10}) + gone = self.httpd.hub.jobs.add({**base, "task": "operator/other", "status": "done", "created_ts": now - 30, "dismissed": True}) + other = self.httpd.hub.jobs.add({**base, "task": "operator/other", "status": "done", "created_ts": now - 5}) + change = self.httpd.hub.jobs.add({**base, "task": "operator/greet", "status": "done", "created_ts": now - 15, "kind": "task", "argv": []}) + self.assertEqual(self.dismiss({"id": newer["id"]}, self.guard(self.host)), 200) + left = {job["id"] for job in self.httpd.hub.jobs.listed()} + self.assertEqual(left, {other["id"], change["id"]}) + self.assertNotIn(older["id"], left) + self.assertNotIn(gone["id"], left) + self.assertEqual(self.dismiss({"id": change["id"]}, self.guard(self.host)), 200) + self.assertIs(self.httpd.hub.jobs.get(change["id"])["dismissed"], True) def test_the_console_carries_only_the_tail_the_job_list_shows(self): self.register("queued") diff --git a/tests/test_hub_context_menu.py b/tests/test_hub_context_menu.py index 8faea6b..f05ea7f 100644 --- a/tests/test_hub_context_menu.py +++ b/tests/test_hub_context_menu.py @@ -39,7 +39,7 @@ class Element { Panels.item("task", (id) => `Task ${id}`, () => null); const KEYS_OF = {Stage: "s2", Docs: "s3"}; const NAMES = {s2: "Stage", s3: "Docs"}; -const calls = {tasks: [], pins: [], feedback: [], shown: [], closed: 0}; +const calls = {tasks: [], pins: [], feedback: [], shown: [], toasts: [], closed: 0}; const context = { console, Nav, Panels, Element, JSON, Math, Object, Array, String, Number, Boolean, Promise, Map, Set, Intl, document: {activeElement: null, currentScript: null}, window: {innerWidth: 1366, innerHeight: 768, matchMedia: () => ({matches: false})}, navigator: {}, @@ -50,7 +50,7 @@ const context = { agentNames: () => ["Docs", "Stage"], agentKey: (who) => KEYS_OF[who] || who, nameOf: (key) => NAMES[key] || key, labelOf: (key) => NAMES[key] || key, keyOf: (item) => `${item.kind}:${item.id}`, go: () => {}, useView: () => {}, useSaved: () => {}, openAgent: () => {}, openRadio: () => {}, confirmAct: () => {}, openAgentOrder: () => {}, settingsSheet: () => {}, toggleMusic: () => {}, skyLook: () => {}, toggleLeitstand: () => {}, askNotify: () => {}, helpSheet: () => {}, micFrame: (field) => field, - taskSheet: (id) => calls.tasks.push(id), artSelect: () => {}, select: () => {}, openItem: () => {}, openSheet: () => {}, glossarySections: () => [], toast: () => {}, + taskSheet: (id) => calls.tasks.push(id), artSelect: () => {}, select: () => {}, openItem: () => {}, openSheet: () => {}, glossarySections: () => [], toast: (...args) => calls.toasts.push(args), homePins: () => [], homePress: (kind, id) => calls.pins.push(`${kind}:${id}`), HOME_OPENERS: {task: (id) => calls.tasks.push(`home ${id}`)}, closeMenus: () => { calls.closed += 1; }, calls, }; @@ -67,6 +67,10 @@ const taskSections = ctxSections(inside); out.task = labels(taskSections); taskSections[0].items.forEach((item) => item.label !== "Copy task id" && item.run()); out.ran = {tasks: calls.tasks, pins: calls.pins}; +const refused = ctxSections(new Element("li", {"data-item": "artifact:wt:/" + "p".repeat(300)}))[0]; +out.refused = [refused.title, refused.items.map((item) => [item.label, item.hint])]; +refused.items[0].run(); +out.toasts = calls.toasts; ui.screen = "agents"; out.agent = labels(ctxSections(new Element("g", {"data-face": "s2", "data-pick": "s2"}))); out.operator = labels(ctxSections(new Element("span", {"data-face": "Operator"})))[0][0]; @@ -137,12 +141,18 @@ class TestHubContextMenu(unittest.TestCase): def test_the_element_items_act_on_the_clicked_element(self): self.assertEqual(self.data["ran"], {"tasks": ["work/feature"], "pins": ["task:work/feature"]}) + def test_a_refused_pin_keeps_its_menu_item_names_why_and_pins_nothing(self): + why = "the id runs past 200 characters" + self.assertEqual(self.data["refused"], ["Home pin", [["Pin to Home", f"not possible, {why}"]]]) + self.assertEqual(self.data["toasts"], [["Not pinned", [f"Pin to Home is not possible: {why}."], False]]) + self.assertEqual(self.data["ran"]["pins"], ["task:work/feature"]) + def test_an_agent_scoped_palette_item_shows_only_on_its_own_agent(self): self.assertEqual(self.data["agent"], [["element", "Stage", ["Stage", "Copy name"]], ["agents", "Agents", AGENTS_TAB], ["general", "General", GENERAL]]) self.assertEqual(self.data["operator"], "agents") def test_a_sub_screen_takes_the_items_of_its_tab(self): - self.assertEqual(self.data["rules"], [["stream", "Stream", ["View: Stream › Controls", "Stream: For you", "Stream: Mine", "Controls …"]], ["general", "General", GENERAL]]) + self.assertEqual(self.data["rules"], [["stream", "Stream", ["View: Stream › Controls", "Stream: For you", "Stream: Mine", "Controls …", "Schedules …"]], ["general", "General", GENERAL]]) def test_every_palette_item_has_a_scope_and_the_palette_still_lists_them_all(self): palette = self.data["palette"] diff --git a/tests/test_hub_decision_rows.py b/tests/test_hub_decision_rows.py index 8371b88..31eabb2 100644 --- a/tests/test_hub_decision_rows.py +++ b/tests/test_hub_decision_rows.py @@ -8,7 +8,7 @@ from hub_case import HubCase from hub_support import HUB TEMPLATES = HUB / "templates" -MODULES = ["page-constants.js", "answers.js", "page-reveal.js", "page-dom.js", "page-dialog.js", "page-inbox.js", "page-grant.js"] +MODULES = ["page-constants.js", "answers.js", "page-reveal.js", "page-dom.js", "page-dialog.js", "page-codebox.js", "page-inbox.js", "page-grant.js"] PROBE = r""" const fs = require("fs"); const vm = require("vm"); diff --git a/tests/test_hub_grant_mode.py b/tests/test_hub_grant_mode.py index 165a7de..9141b41 100644 --- a/tests/test_hub_grant_mode.py +++ b/tests/test_hub_grant_mode.py @@ -7,7 +7,7 @@ import unittest from hub_support import HUB TEMPLATES = HUB / "templates" -MODULES = ["page-constants.js", "answers.js", "page-reveal.js", "page-dom.js", "page-dialog.js", "page-diff.js", "page-inbox.js", "page-grant.js"] +MODULES = ["page-constants.js", "answers.js", "page-reveal.js", "page-dom.js", "page-dialog.js", "page-diff.js", "page-codebox.js", "page-inbox.js", "page-grant.js"] PROBE = r""" const fs = require("fs"); const vm = require("vm"); @@ -55,7 +55,7 @@ const context = { console, document, JSON, Math, Date, Intl, Promise, Set, Map, Number, String, Array, Object, RegExp, Boolean, Error, setTimeout, Node: El, Element: El, HTMLElement: El, window: {location: {hash: "", hostname: "localhost", port: "8737", pathname: "/"}, setTimeout: () => 0, clearTimeout: () => {}, setInterval: () => 0, clearInterval: () => {}, getSelection: () => "", matchMedia: () => ({matches: false})}, - state: {inbox: [], radio: [], messages: [], settings: {}, now}, inboxDom: null, + state: {inbox: [], radio: [], messages: [], settings: {}, now}, inboxDom: null, settings: {undo: 3}, ui: {screen: "inbox", busy: false, selected: new Set(), cursor: 0, snoozed: false, asOf: null}, known: {batches: new Set()}, ViewStore: {get: (path) => (path === "approval.mode" ? mode.value : null), set: (path, value) => { sets.push([path, value]); mode.value = value; }, on: (path, callback) => listeners.push([path, callback])}, @@ -197,15 +197,15 @@ class TestGrantMode(unittest.TestCase): self.assertEqual(self.data["collected"]["selected"], ["ask:a-1", "decision:d-1", "operator:operator/run", "review:r-green"]) self.assertEqual(self.data["collected"]["proofs"], []) - def test_a_picked_item_shows_a_pale_green_disabled_grant_button(self): + def test_a_picked_item_shows_a_pressed_pale_green_grant_button_that_a_second_press_takes_out(self): self.assertEqual(self.data["unpressed"]["pressed"], "false") self.assertTrue(self.data["unpressed"]["title"].startswith("Select: "), self.data["unpressed"]) self.assertEqual((self.data["unpressed"]["disabled"], self.data["unpressed"]["picked"]), (False, False)) pressed = self.data["pressed"] - self.assertEqual((pressed["pressed"], pressed["disabled"], pressed["picked"]), ("true", True, True)) - self.assertEqual(pressed["title"], "In the selection: take it out with ✕ in the Grant menu") + self.assertEqual((pressed["pressed"], pressed["disabled"], pressed["picked"]), ("true", False, True)) + self.assertEqual(pressed["title"], "Selected: press again to take it out of the selection") - def test_a_checkbox_pick_in_direct_also_turns_the_button_pale_and_opens_the_grant_split(self): + def test_a_pick_in_direct_also_turns_the_button_pale_and_opens_the_grant_split(self): picked = self.data["direct_picked"] self.assertEqual((picked["pressed"], picked["disabled"], picked["picked"]), (None, True, True)) self.assertEqual(self.data["direct_selection"]["main"], "Grant selection (1)") diff --git a/tests/test_hub_graph.py b/tests/test_hub_graph.py index dc4027b..b492b7b 100644 --- a/tests/test_hub_graph.py +++ b/tests/test_hub_graph.py @@ -9,7 +9,7 @@ from unittest import mock from hub_case import HubCase from hub_support import iso -from kvb_orchestrator import lifetimes, names, orbits +from kvb_orchestrator import lifetimes, names, orbits, phrasing class TestHubGraph(HubCase): @@ -87,7 +87,8 @@ class TestHubGraph(HubCase): with self.subTest(name=name): self.assertEqual([row["text"] for row in self.events(f"kinds=radio&agent={name}")["events"]], ["before", "after"]) snapshot = self.snapshot() - self.assertEqual([row["speech"] for row in snapshot["radio"]], ["Docs, Docs, this is Skills, before, over", "Docs, Docs, this is IAM, after, over"]) + self.assertEqual([phrasing.joined((row["word"], row["rest"])) for row in snapshot["radio"]], ["Docs, Docs, this is Skills, before, over", "Docs, Docs, this is IAM, after, over"]) + self.assertFalse([row for row in snapshot["radio"] if "speech" in row]) self.assertEqual({row["voice"] for row in snapshot["radio"]}, {self.httpd.hub.speech.voice_of("s1")}) live = {node["id"]: node for node in snapshot["graph"]["nodes"]} self.assertEqual((live["s1"]["label"], live["s1"]["names"]), ("IAM", ["Skills", "IAM"])) diff --git a/tests/test_hub_home.py b/tests/test_hub_home.py index d01bccb..0aa0d4f 100644 --- a/tests/test_hub_home.py +++ b/tests/test_hub_home.py @@ -339,42 +339,17 @@ const context = vm.createContext({document, MutationObserver: class { observe() vm.runInContext(fs.readFileSync(process.argv[1], "utf8"), context); const P = vm.runInContext("Panels", context); """ -STAR_PROBE = DOM_KIT + """ -P.panel("tasks/list", "Tasks: list", () => null); -P.panel("radio-log", "Radio log", () => null); -P.item("task", (id) => `Task ${id}`, () => null); -const slot = el("div", {class: "head-row", "data-star-slot": ""}, el("code", {}), el("button", {class: "priority"})); -const task = el("li", {"data-item": "task:work/a"}, slot, el("span", {})); -const bare = el("li", {"data-item": "task:work/b"}, el("span", {})); -const list = el("div", {"data-panel": "tasks/list"}, el("ol", {}, task, bare)); -const svg = new El("g", "http://www.w3.org/2000/svg"); -svg.setAttribute("data-item", "task:work/c"); -const radio = el("section", {"aria-label": "Radio log"}, el("ul", {"aria-label": "Radio log"})); -const root = el("main", {}, list, el("div", {}, svg), radio, el("div", {"data-panel": "nope"})); -const clicked = []; -const stars = () => root.querySelectorAll("[class]").filter((node) => node.classList.contains("star")); -const own = (host) => stars().filter((node) => node.closest("[data-panel], [data-item]") === host); -const mark = P.decorate(root, {pinned: (kind, id) => kind === "task" && id === "work/a", press: (...args) => clicked.push(args), marks: [['section[aria-label="Radio log"]', "radio-log"]]}); -const before = stars().length; +MARK_PROBE = DOM_KIT + """ +const radio = el("section", {"aria-label": "Radio log"}); +const kept = el("section", {"aria-label": "Radio log", "data-panel": "kept"}); +const root = el("main", {}, radio, kept); +const mark = P.decorate(root, [['section[aria-label="Radio log"]', "radio-log"]]); +const first = [radio.getAttribute("data-panel"), kept.getAttribute("data-panel"), root.all().length]; +const fresh = el("section", {"aria-label": "Radio log"}); +root.append(fresh); mark(); -const [panelStar] = own(list); -const [taskStar] = own(task); -const out = { - panel: {first: list.children[0].getAttribute("class"), stars: own(list).length, pressed: panelStar.getAttribute("aria-pressed"), title: panelStar.getAttribute("title")}, - task: {inSlot: taskStar.parentNode === slot, slotLast: slot.children.at(-1) === taskStar, rows: task.children.filter((child) => child.classList.contains("star-row")).length, - pressed: taskStar.getAttribute("aria-pressed"), label: taskStar.getAttribute("aria-label")}, - bare: {first: bare.children[0].getAttribute("class"), stars: own(bare).length}, - svg: svg.children.length, - radio: [radio.getAttribute("data-panel"), radio.children[0].getAttribute("class")], - again: [before, stars().length], -}; -taskStar.listeners.click[0]({preventDefault: () => null, stopPropagation: () => null}); -const fresh = el("div", {"data-star-slot": ""}); -task.replaceChildren(fresh, el("span", {})); -mark(); -out.redrawn = [own(task)[0].parentNode === fresh, stars().length]; -out.clicked = clicked; -console.log(JSON.stringify(out)); +console.log(JSON.stringify({first, fresh: [fresh.getAttribute("data-panel"), root.all().length], + targets: [P.targetOf(el("li", {"data-item": "task:work/a"})), P.targetOf(el("li", {"data-item": "nokind"})), P.targetOf(el("div", {"data-panel": "tasks/list"}))]})); """ MESSAGE_PROBE = """ const fs = require("fs"); @@ -428,22 +403,12 @@ console.log(JSON.stringify({ })); """ CAPTURE_PROBE = DOM_KIT + """ -P.item("metric", (id, view) => `Metric ${view.shown === null ? "all" : view.shown.join()}`, () => null); let selection = null; P.capture("resources-hardware", () => ({kind: "metric", id: selection === null ? "hardware/all" : "hardware/cpu", view: {chart: "hardware", tokens: "interval", shown: selection}})); -const head = el("div", {class: "res-head", "data-star-slot": ""}, el("span", {class: "res-title"})); -const chart = el("section", {"data-panel": "resources-hardware"}, head, el("div", {class: "res-plot"})); -const loose = el("section", {"data-panel": "resources-unknown"}); -const root = el("main", {}, chart, loose); -const clicked = []; -const mark = P.decorate(root, {pinned: (kind, id) => `${kind}:${id}` === "metric:hardware/cpu", press: (...args) => clicked.push(args)}); -const star = () => head.children.find((child) => child.classList.contains("star")); -const before = [star().getAttribute("aria-pressed"), star().getAttribute("title"), loose.children.length, chart.children[0] === head]; +const chart = el("section", {"data-panel": "resources-hardware"}); +const before = P.targetOf(chart); selection = ["host:CPU"]; -mark(); -const after = [star().getAttribute("aria-pressed"), star().getAttribute("title"), head.children.filter((child) => child.classList.contains("star")).length]; -star().listeners.click[0]({preventDefault: () => null, stopPropagation: () => null}); -console.log(JSON.stringify({before, after, clicked, target: P.targetOf(chart)})); +console.log(JSON.stringify({before, target: P.targetOf(chart), loose: P.targetOf(el("section", {"data-panel": "resources-unknown"}))})); """ METRIC_PROBE = """ const fs = require("fs"); @@ -488,61 +453,19 @@ const view = {chart: "hardware", tokens: "interval", shown: ["host:CPU"]}; })(); """ REFUSED_PROBE = DOM_KIT + """ -P.item("metric", (id) => `Metric ${id}`, () => null); -P.item("artifact", (id) => `Artifact ${id}`, () => null); let over = true; P.capture("resources-tokens", () => (over ? {kind: "metric", id: "tokens/interval/x", view: {chart: "tokens"}, refused: "too many series"} : {kind: "metric", id: "tokens/interval/y", view: {chart: "tokens"}})); -const chart = el("section", {"data-panel": "resources-tokens"}, el("div", {"data-star-slot": ""})); -const long = el("li", {"data-item": `artifact:wt:/${"p".repeat(300)}`}); -const root = el("main", {}, chart, long); -const clicked = []; -const mark = P.decorate(root, {pinned: () => false, press: (...args) => clicked.push(args)}); -const star = (host) => host.all().find((node) => node.classList.contains("star")); -const read = (host) => [star(host).hasAttribute("disabled"), star(host).getAttribute("title"), star(host).getAttribute("aria-pressed")]; -const fire = (host) => (star(host).listeners.click || []).forEach((listen) => listen({preventDefault: () => null, stopPropagation: () => null})); -const refused = read(chart); -const first = star(chart); -fire(chart); +const chart = el("section", {"data-panel": "resources-tokens"}); +const refused = P.targetOf(chart); over = false; -mark(); -const freed = [...read(chart), star(chart) === first]; -fire(chart); -over = true; -mark(); -const again = read(chart); -fire(chart); -fire(long); -console.log(JSON.stringify({refused, freed, again, long: read(long), clicked})); -""" -ORDER_PROBE = DOM_KIT + """ -Object.assign(context, {h, state: {agent_order: ["Skills", "Stage"]}, ui: {order: null}, counter: (value) => text(value), face: () => text("face"), person: (name) => text(name), - icon: () => text("icon"), officeBtn: (name, label) => h("button", {"aria-label": label}), focusKey: () => null, refocus: () => null, act: async () => true, go: () => null}); -vm.runInContext(`${fs.readFileSync(process.argv[2], "utf8")}\\nglobalThis.probe = {orderDom, drawAgentOrder};`, context); -const {orderDom, drawAgentOrder} = context.probe; -P.panel("agents/order", "Agents: priority", () => null); -orderDom.box = el("section", {"data-panel": "agents/order"}); -orderDom.slot = el("span", {"data-star-slot": ""}); -document.body.append(orderDom.box); -const mark = P.decorate(document.body, {pinned: () => false, press: () => null}); -const stars = () => orderDom.box.all().filter((node) => node.classList.contains("star")); -drawAgentOrder(); -mark(); -const first = stars()[0]; -first.focus(); -drawAgentOrder(); -mark(); -context.state.agent_order = ["Stage", "Skills", "Docs"]; -drawAgentOrder(); -mark(); -console.log(JSON.stringify({count: stars().length, same: stars()[0] === first, focused: document.activeElement === first, head: first.parentNode.parentNode === orderDom.box.children[0], - ranks: orderDom.box.all().filter((node) => node.tagName === "LI").map((node) => node.getAttribute("data-name"))})); +console.log(JSON.stringify({refused, freed: P.targetOf(chart), long: P.targetOf(el("li", {"data-item": `artifact:wt:/${"p".repeat(300)}`})), pins: P.add([], "metric", "tokens/interval/y", {chart: "tokens"}).pins})); """ TREE_PROBE = DOM_KIT + """ const [, artifactsFile, treeFile, homeFile, dataFile] = process.argv.slice(1); Object.assign(context, { h, icon: () => text(""), named: (label, hint) => ({title: hint || label, "aria-label": label}), iconBtn: (name, label, cls, run, hint) => h("button", {"aria-label": label, title: hint}), counter: (value) => text(value), emptyState: (title, words) => h("div", {class: "empty", "data-title": title}, words), branchAncestry: () => null, gateChips: () => h("span", {class: "gates"}), gateExplain: () => null, - flowLine: () => null, flowDetails: () => null, flowEdges: () => [], copyButton: () => null, face: () => null, person: (name) => text(name), status: (value) => text(value), pill: (words) => text(words), + flowLine: () => null, flowDetails: () => null, flowEdges: () => [], copyButton: () => null, face: () => null, person: (name) => text(name), agentLink: (name) => text(name), status: (value) => text(value), pill: (words) => text(words), workChips: () => null, popupHead: (glyph, label) => h("h2", {class: "panel-title"}, label), meta: (rows) => h("dl", {}, rows.map(([key, value]) => h("div", {"data-key": key}, value === null || value === undefined ? "" : value))), WORK_CHIPS: {}, clock: {format: () => "c"}, stampOf: (t) => t, nowSeconds: () => 1763000000, labelOf: (key) => key, toast: () => null, tree: {data: JSON.parse(fs.readFileSync(dataFile, "utf8")), model: null, busy: false, q: "", open: new Set(), dom: null}, @@ -767,7 +690,7 @@ class TestHomePage(unittest.TestCase): marked = set(re.findall(r"\['[^']+', \"([^\"]+)\"\]", home)) captured = set(re.findall(r'Panels\.capture\("([^"]+)"', home)) made = set(re.findall(r'\{kind: "(\w+)", id, view[,}]', sources)) - self.assertEqual((len(literal), marked), (13, {"radio-log"})) + self.assertEqual((len(literal), marked), (14, {"radio-log"})) literal |= marked self.assertEqual(len(dynamic), 13) self.assertEqual(sorted(literal | dynamic), sorted(registered)) @@ -777,20 +700,17 @@ class TestHomePage(unittest.TestCase): self.assertEqual((made, sorted(used | made)), ({"metric"}, sorted(kinds))) -class TestHomeStars(unittest.TestCase): - def test_a_star_sits_in_flow_in_its_own_hosts_slot_or_a_star_row_and_never_twice(self): - data = node(STAR_PROBE, str(PANELS)) - self.assertEqual(data["panel"], {"first": "star-row", "stars": 1, "pressed": "false", "title": "Pin to Home: Tasks: list"}) - self.assertEqual(data["task"], {"inSlot": True, "slotLast": True, "rows": 0, "pressed": "true", "label": "Unpin from Home"}) - self.assertEqual(data["bare"], {"first": "star-row", "stars": 1}) - self.assertEqual((data["svg"], data["radio"], data["again"], data["redrawn"]), (0, ["radio-log", "star-row"], [4, 4], [True, 4])) - self.assertEqual(data["clicked"], [["task", "work/a", "Task work/a", None]]) +class TestHomeMarks(unittest.TestCase): + def test_decorate_tags_only_untagged_marks_adds_no_element_and_tags_a_redrawn_one(self): + data = node(MARK_PROBE, str(PANELS)) + self.assertEqual((data["first"], data["fresh"]), (["radio-log", "kept", 2], ["radio-log", 3])) + self.assertEqual(data["targets"], [{"kind": "task", "id": "work/a"}, None, {"kind": "panel", "id": "tasks/list"}]) - def test_the_star_css_positions_nothing_and_leaves_the_starred_elements_alone(self): + def test_no_template_or_stylesheet_holds_a_star_a_star_row_or_a_star_slot(self): + star = re.compile(r"\.star\b|star-row|data-star-slot|keepFocus|\"star\"") + found = [path.name for path in sorted(TEMPLATES.iterdir()) if path.suffix in {".js", ".css", ".j2"} and star.search(path.read_text(encoding="utf-8"))] + self.assertEqual(found, []) css = (TEMPLATES / "style-home.css").read_text(encoding="utf-8") - star = re.findall(r"^\.star(?:-row)?(?:\[[^\]]+\])? \{([^}]*)\}", css, re.MULTILINE) - self.assertEqual(len(star), 3) - self.assertFalse(any("position" in rule for rule in star), star) self.assertNotIn("[data-panel]", css) self.assertNotIn("[data-item]", css) @@ -808,14 +728,13 @@ class TestHomeBookmarks(unittest.TestCase): self.assertEqual(data["lookup"], ["Metric hardware/x host:CPU", "hardware/x 4 hardware", "Metric hardware/x none", None]) self.assertEqual(data["digest"], [True, False, True, True]) - def test_a_captured_panel_stars_the_pin_its_capture_makes_now_and_presses_it_with_its_view(self): + def test_a_captured_panel_targets_the_pin_its_capture_makes_now_with_its_view(self): data = node(CAPTURE_PROBE, str(PANELS)) - self.assertEqual(data["before"], ["false", "Pin to Home: Metric all", 0, True]) - self.assertEqual(data["after"], ["true", "Unpin from Home: Metric host:CPU", 1]) - self.assertEqual(data["clicked"], [["metric", "hardware/cpu", "Metric host:CPU", self.VIEW]]) + self.assertEqual(data["before"], {"kind": "metric", "id": "hardware/all", "view": {**self.VIEW, "shown": None}}) self.assertEqual(data["target"], {"kind": "metric", "id": "hardware/cpu", "view": self.VIEW}) + self.assertEqual(data["loose"], {"kind": "panel", "id": "resources-unknown"}) - def test_a_chart_star_pins_the_series_switched_on_now_so_another_selection_is_another_pin(self): + def test_a_chart_pin_takes_the_series_switched_on_now_so_another_selection_is_another_pin(self): data = node(METRIC_PROBE, str(PANELS), str(TEMPLATES / "page-resources.js"), str(HOME)) cpu, mixed = data["digests"] self.assertEqual(data["empty"], {"kind": "metric", "id": "tokens/accumulated/all", "view": {"chart": "tokens", "tokens": "accumulated", "shown": None}}) @@ -828,27 +747,22 @@ class TestHomeBookmarks(unittest.TestCase): self.assertEqual(data["titles"], ["Hardware: CPU", "Tokens (accumulated): all series", "Combined: done, CPU", "Hardware: all series", "Tokens (accumulated): all series"]) self.assertEqual((data["four"], data["broken"]), ("Tokens: 4 series", ["Metric", None])) - def test_pressing_a_metric_star_stores_its_view_with_the_pin_and_pressing_again_unpins_it(self): + def test_pinning_a_metric_stores_its_view_with_the_pin_and_pinning_again_unpins_it(self): data = node(PRESS_PROBE, str(PANELS), str(HOME)) pin = {"kind": "metric", "id": "hardware/abc", "w": 4, "h": 3, "view": self.VIEW} self.assertEqual((data["stored"], data["after"], data["pins"]), ([pin], [], [])) - def test_a_chart_star_refuses_a_selection_past_the_view_stores_series_limit_and_names_why(self): + def test_a_chart_pin_refuses_a_selection_past_the_view_stores_series_limit_and_names_why(self): data = node(METRIC_PROBE, str(PANELS), str(TEMPLATES / "page-resources.js"), str(HOME), str(SHOWN_LIMIT)) why = f"more than {SHOWN_LIMIT} series are switched on: switch some off, or all of them on" self.assertEqual(data["limits"], [[SHOWN_LIMIT, None, 3], [SHOWN_LIMIT + 1, why, 3], [None, None, 3], [0, None, 3]]) - def test_a_refused_capture_or_an_overlong_id_disables_the_star_with_its_reason_and_a_press_pins_nothing(self): + def test_a_refused_capture_or_an_overlong_id_names_its_reason_and_a_freed_one_adds_its_pin(self): data = node(REFUSED_PROBE, str(PANELS)) - refused = [True, "Pin to Home: not possible, too many series", "false"] - self.assertEqual((data["refused"], data["again"]), (refused, refused)) - self.assertEqual(data["freed"], [False, "Pin to Home: Metric tokens/interval/y", "false", True]) - self.assertEqual(data["long"], [True, "Pin to Home: not possible, the id runs past 200 characters", "false"]) - self.assertEqual(data["clicked"], [["metric", "tokens/interval/y", "Metric tokens/interval/y", {"chart": "tokens"}]]) - - def test_the_agent_priority_star_stays_the_same_button_and_keeps_its_focus_through_a_redraw(self): - data = node(ORDER_PROBE, str(PANELS), str(TEMPLATES / "page-agent-order.js")) - self.assertEqual(data, {"count": 1, "same": True, "focused": True, "head": True, "ranks": ["Stage", "Skills", "Docs"]}) + self.assertEqual(data["refused"], {"kind": "metric", "id": "tokens/interval/x", "view": {"chart": "tokens"}, "refused": "too many series"}) + self.assertEqual(data["freed"], {"kind": "metric", "id": "tokens/interval/y", "view": {"chart": "tokens"}}) + self.assertEqual(data["long"], {"kind": "artifact", "id": None, "refused": "the id runs past 200 characters"}) + self.assertEqual(data["pins"], [{"kind": "metric", "id": "tokens/interval/y", "w": 4, "h": 3, "view": {"chart": "tokens"}}]) def test_the_client_pin_id_grammar_is_the_hubs(self): done = subprocess.run(["node", "-e", "console.log(JSON.stringify(require(process.argv[1]).ID.source))", str(PANELS)], capture_output=True, text=True, timeout=60, check=True) @@ -911,7 +825,7 @@ class TestHomeOpen(unittest.TestCase): PANEL_IDS = ( "stream", "radio-log", "agents/orbit", "agents/chord", "agents/swimlane", "agents/3d", "agents/tree", "agents/hierarchy", "agents/order", "artifacts/orbit", "artifacts/chord", "artifacts/swimlane", "artifacts/tree", "artifacts/3d", - "tasks/list", "tasks/board", "tasks/rasci", "tasks/gantt", "tasks/burn", "tasks/3d", "tasks/operator", + "tasks/list", "tasks/board", "tasks/rasci", "tasks/gantt", "tasks/burn", "tasks/3d", "tasks/operator", "stream/schedules", ) ITEMS: ClassVar[dict] = { "task": ("#tasks/list", "task:work/a", "tasks", "list"), @@ -937,7 +851,7 @@ class TestHomeOpen(unittest.TestCase): def test_every_panel_and_item_kind_links_to_its_own_tab_and_view_and_an_item_names_itself_to_open(self): data = node(LINK_PROBE, str(NAV), str(PANELS), str(HOME), json.dumps(self.PANEL_IDS)) - special = {"stream": ("stream", None), "radio-log": ("stream", None), "agents/order": ("agents", "hierarchy"), "tasks/operator": ("inbox", None)} + special = {"stream": ("stream", None), "radio-log": ("stream", None), "agents/order": ("agents", "hierarchy"), "tasks/operator": ("inbox", None), "stream/schedules": ("rules", "schedules")} for panel in self.PANEL_IDS: with self.subTest(panel=panel): found = data["panels"][panel] @@ -966,9 +880,10 @@ class TestHomeIndex(HubCase): for name in ("panels.js", "page-home.js", "style-home.css"): with self.subTest(name=name): self.assertIn((TEMPLATES / name).read_text(encoding="utf-8").strip(), html) - for glyph in ("bi-star", "bi-star-fill", "bi-house-door", "bi-grip-vertical", "bi-arrow-down-right", "bi-arrows-angle-expand"): + for glyph in ("bi-house-door", "bi-grip-vertical", "bi-arrow-down-right", "bi-arrows-angle-expand"): with self.subTest(glyph=glyph): self.assertIn(f' None: applying.set() finish.wait(10) - with mock.patch.object(batches, "UNDO", 0.05): - batch = pending.add([{"kind": "review", "id": "r1"}], "operator", None, apply) + batch = pending.add([{"kind": "review", "id": "r1"}], "operator", None, apply) self.assertTrue(applying.wait(10)) self.assertEqual((pending.holds("review", "r1"), pending.listed()), (True, [])) with self.assertRaises(Conflict): diff --git a/tests/test_hub_morse.py b/tests/test_hub_morse.py index f003dbb..33ffdd1 100644 --- a/tests/test_hub_morse.py +++ b/tests/test_hub_morse.py @@ -173,20 +173,21 @@ def radio_row(cls: str, text: str) -> dict: return {"class": cls, "source": "s1", "from": "Docs", "to": ["Skills session"], "called": ["Skills session"], "speaker": "Docs", "pitch": 612, "voice": "", "word": "", "rest": "", "text": text} -def radio_set(mode: str, muted: list[str]) -> dict: - return {"mode": mode, "classes": list(council.CLASSES), "muted": muted, "sounds": {}, "squelch": 1, "log": {}} +def radio_set(mode: str, classes: list[str]) -> dict: + return {"mode": mode, "classes": classes, "sounds": {}, "squelch": 1, "log": {}} class TestMorseCode(unittest.TestCase): @classmethod def setUpClass(cls): offline, online = {"tts": False, "open": False}, {"tts": True, "open": True} - plans = [[radio_row(name, TEXT), radio_set("morse", []), offline] for name in council.CLASSES] + every = list(council.CLASSES) + plans = [[radio_row(name, TEXT), radio_set("morse", every), offline] for name in council.CLASSES] plans += [ - [radio_row("security", TEXT), radio_set("morse", []), online], - [radio_row("security", TEXT), radio_set("morse", ["s1"]), offline], - [radio_row("mayday", TEXT), radio_set("morse", ["s1"]), offline], - [radio_row("broadcast", "word " * 600), radio_set("morse", []), offline], + [radio_row("security", TEXT), radio_set("morse", every), online], + [radio_row("security", TEXT), radio_set("morse", ["post"]), offline], + [radio_row("mayday", TEXT), radio_set("morse", ["post"]), offline], + [radio_row("broadcast", "word " * 600), radio_set("morse", every), offline], ] words = ["PARIS", "paris", "Gr\u00fc\u00dfe, Ëva! 😀 ~ À ÿ"] cls.data = node(CODES_PROBE, str(MORSE), str(RADIOSET), json.dumps({"words": words, "plans": plans})) diff --git a/tests/test_hub_operator_tasks.py b/tests/test_hub_operator_tasks.py index 545b691..697e596 100644 --- a/tests/test_hub_operator_tasks.py +++ b/tests/test_hub_operator_tasks.py @@ -24,7 +24,7 @@ hub_limits = importlib.import_module("hub_limits") approval = importlib.import_module("approval") TEMPLATES = HUB / "templates" DIFFS = TEMPLATES / "diffs.js" -PAGE_MODULES = ["page-constants.js", "answers.js", "page-reveal.js", "page-dom.js", "page-dialog.js", "page-diff.js", "page-inbox.js", "page-grant.js", "page-stream.js", "page-screens.js", "page-keyboard.js"] +PAGE_MODULES = ["page-constants.js", "answers.js", "page-reveal.js", "page-dom.js", "page-dialog.js", "page-diff.js", "page-codebox.js", "page-inbox.js", "page-grant.js", "page-stream.js", "page-screens.js", "page-keyboard.js"] SECRET = 'api_key = "plain-example-words"' ARMOURED = "before\n-----BEGIN EXAMPLE-----\nplain words only\n-----END EXAMPLE-----\nafter\n" WITHHELD = "content withheld" @@ -144,6 +144,17 @@ openSheet = (title, body) => calls.sheets.push({title, body}); const operatorCard = inboxItem(operator, 0); const streamCard = eventRow({id: "e1", kind: "operator", waiting: true, ts: now, agent: "Skills", title: "make ship", text: "release the build", ref: {task: "operator/ship", directory: "/repo", status: "queued"}}); const plainCard = eventRow({id: "e2", kind: "operator", waiting: false, ts: now, agent: "Skills", title: "make other", text: "-", ref: {task: "operator/other", directory: "/repo", status: "done"}}); +const pressedOf = (card) => { + const check = all(card).find((el) => el.tag === "button" && el.attrs["aria-pressed"] !== undefined); + return check ? check.attrs["aria-pressed"] : null; +}; +ViewStore = {get: () => GRANT_SELECT}; +ui.selected.add(keyOf(operator)); +const pickedCard = inboxItem(operator, 0); +ui.selected.delete(keyOf(operator)); +const freeCard = inboxItem(operator, 0); +ViewStore = null; +const selection = {picked: [pickedCard.attrs["aria-selected"], pressedOf(pickedCard)], free: [freeCard.attrs["aria-selected"], pressedOf(freeCard)], direct: [operatorCard.attrs["aria-selected"] || null, pressedOf(operatorCard)]}; diffView.cache.set("review:0123456789abcdef", [ {path: "src/app.py", status: "M", mode: "100644", additions: 2, deletions: 1, patch: "@@ -1,2 +1,3 @@\\n keep\\n-old\\n+new\\n+more", note: ""}, {path: "logo.png", status: "B", mode: "100644", additions: 0, deletions: 0, patch: "", note: ""}, @@ -178,9 +189,10 @@ const results = { operator: {classes: classes(operatorCard), checkbox: all(operatorCard).filter((el) => el.tag === "input" && el.attrs.type === "checkbox").length, ref: operatorCard.dataset.ref, to: operatorCard.dataset.to, command: all(operatorCard).filter((el) => classes(el).includes("command")).map((el) => [el.dataset.path, all(el).find((inner) => inner.tag === "code").textContent]), text: operatorCard.textContent, buttons: labels(operatorCard)}, - stream: {buttons: labels(streamCard), actions: all(streamCard).filter((el) => classes(el).includes("line-actions")).length, ref: streamCard.dataset.ref || null, plain: [labels(plainCard), plainCard.dataset.ref || null]}, + stream: {buttons: labels(streamCard), actions: all(streamCard).filter((el) => classes(el).includes("line-actions")).length, foot: all(streamCard).filter((el) => classes(el).includes("code-foot")).map(labels), ref: streamCard.dataset.ref || null, plain: [labels(plainCard), plainCard.dataset.ref || null]}, review: {ref: reviewCard.dataset.ref, files: sections.map(read), feedback: all(reviewCard).filter((el) => classes(el).includes("feedback-list")).map((el) => el.textContent)}, status: badgeState, + selection, ask: {ref: askCard.dataset.ref, to: askCard.dataset.to, files: all(askCard).filter((el) => classes(el).includes("diff-file")).map((el) => [el.dataset.path, all(el).filter((inner) => inner.tag === "tr").length]), regions: all(askCard).filter((el) => el.dataset.path !== undefined).map((el) => el.dataset.path)}, }; @@ -338,10 +350,10 @@ class TestOperatorPage(unittest.TestCase): self.assertEqual(status["zero"], [True, "Agent Orchestrator"]) self.assertEqual(status["untitled"], ["2", False, "Agent Orchestrator"]) - def test_an_operator_task_is_a_stream_card_with_a_checkbox_and_every_action(self): + def test_an_operator_task_is_a_stream_card_without_a_checkbox_and_with_every_action(self): card = self.data["operator"] self.assertTrue({"item", "entry", "k-operator", "waiting"} <= set(card["classes"]), card["classes"]) - self.assertEqual((card["checkbox"], card["ref"], card["to"]), (1, "operator:operator/ship", "Skills")) + self.assertEqual((card["checkbox"], card["ref"], card["to"]), (0, "operator:operator/ship", "Skills")) self.assertEqual(card["command"], [["/repo", "make ship"]]) for text in ("in /repo", "release the build"): with self.subTest(text=text): @@ -350,12 +362,17 @@ class TestOperatorPage(unittest.TestCase): with self.subTest(label=label): self.assertIn(label, card["buttons"]) - def test_the_stream_keeps_its_operator_card_with_its_actions(self): + def test_select_mode_shows_the_pick_as_the_selected_row_and_the_pressed_green_check(self): + self.assertEqual(self.data["selection"], {"picked": ["true", "true"], "free": ["false", "false"], "direct": [None, None]}) + + def test_the_stream_keeps_its_operator_card_with_its_actions_in_the_code_foot(self): stream = self.data["stream"] - self.assertEqual((stream["actions"], stream["ref"]), (1, "operator:operator/ship")) - self.assertIn("Run", stream["buttons"]) - self.assertIn("Deny", stream["buttons"]) - self.assertEqual(stream["plain"], [["Skills", "Copy"], None]) + self.assertEqual((stream["actions"], stream["ref"]), (0, "operator:operator/ship")) + self.assertEqual(len(stream["foot"]), 1, stream) + self.assertEqual(stream["foot"][0][:2], ["Copy", "Show all"], stream) + self.assertIn("Run", stream["foot"][0]) + self.assertIn("Deny", stream["foot"][0]) + self.assertEqual(stream["plain"], [["Skills", "Copy", "Show all"], None]) def test_a_review_card_shows_one_unified_block_per_file_expanded_collapsed_past_400_lines_and_binary_named_only(self): files = self.data["review"]["files"] diff --git a/tests/test_hub_page.py b/tests/test_hub_page.py index 3e15a03..31eeb0e 100644 --- a/tests/test_hub_page.py +++ b/tests/test_hub_page.py @@ -61,7 +61,7 @@ class TestHubPage(HubCase): embedded = re.search(r'', html, re.DOTALL).group(1) state = json.loads(embedded) self.assertEqual((state["reviews"][0]["title"], state["reviews"][0]["notes"]), ("", "")) - self.assertEqual((state["register"][0]["title"], state["radio"][0]["from"]), ("", "")) + self.assertEqual((state["tasks"][0]["title"], state["radio"][0]["from"]), ("", "")) def test_the_index_scripts_parse_and_embed_the_ambience_voice_nav_popup_faces_plan_and_space_modules(self): html = self.index() diff --git a/tests/test_hub_poll_cost.py b/tests/test_hub_poll_cost.py new file mode 100644 index 0000000..9d895c1 --- /dev/null +++ b/tests/test_hub_poll_cost.py @@ -0,0 +1,260 @@ +from __future__ import annotations + +import http.client +import json +import subprocess +import time +import unittest +from unittest import mock + +from hub_case import HubCase +from hub_support import HUB +from kvb_orchestrator import register +from kvb_orchestrator.livestate import LiveState + +TEMPLATES = HUB / "templates" +REGISTER = {"work/hub": {"title": "Build the hub", "status": "running", "roles": {"One": "RA"}}} +PROBE = r""" +const fs = require("fs"); +const vm = require("vm"); +const dir = process.argv[1]; +const read = (name) => fs.readFileSync(`${dir}/${name}`, "utf8"); +class El { + constructor() { Object.assign(this, {children: [], textContent: "", replaced: 0}); } + replaceChildren(...nodes) { this.replaced += 1; this.children = nodes; } +} +const results = {}; + +const timers = () => { + const intervals = []; + const listeners = {}; + const calls = {sky: 0, relayout: 0, radio: 0}; + const document = {hidden: true, addEventListener: (type, fn) => { (listeners[type] = listeners[type] || []).push(fn); }}; + const context = { + document, window: {setInterval: (fn, ms) => intervals.push([fn, ms])}, MOVE: 1, RELAYOUT: 15000, tree: {dom: null}, + poll: () => {}, follow: () => {}, fetchTree: () => {}, live: () => true, + drawSky: () => { calls.sky += 1; }, relayout: () => { calls.relayout += 1; }, syncRadio: () => { calls.radio += 1; }, + }; + vm.runInNewContext(`${read("page-timers.js")}\nstartTimers();`, context); + const run = (ms) => intervals.forEach(([fn, every]) => { for (let n = 0; n < Math.floor(ms / every); n += 1) fn(); }); + run(60000); + const hidden = {...calls}; + document.hidden = false; + listeners.visibilitychange.forEach((fn) => fn()); + const shown = {...calls}; + document.hidden = true; + listeners.visibilitychange.forEach((fn) => fn()); + run(30000); + return {hidden, shown, after: {...calls}}; +}; + +const music = () => { + const counts = {starts: 0, stops: 0}; + const param = () => ({value: 0, cancelScheduledValues() {}, setValueAtTime() {}, linearRampToValueAtTime(value) { this.value = value; }}); + const node = (extra) => ({connect: (next) => next, disconnect() {}, ...extra}); + class Audio { + constructor() { Object.assign(this, {state: "running", currentTime: 0, sampleRate: 10, destination: node({})}); } + createGain() { return node({gain: param()}); } + createConvolver() { return node({buffer: null}); } + createBiquadFilter() { return node({frequency: param(), Q: param(), type: ""}); } + createOscillator() { return node({frequency: param(), detune: param(), type: "", start: () => { counts.starts += 1; }, stop: () => { counts.stops += 1; }}); } + createBuffer(channels, length) { return {getChannelData: () => new Float32Array(length)}; } + } + const later = []; + const context = { + Math, Float32Array, audio: null, settings: {music: {on: true, volume: 1}}, radio: {playing: false}, + music: {gain: null, filter: null, drone: [], timer: 0, tension: 0, ducked: 0}, DUCK: 0.2, FADE: 3000, BASE: 110, CALM: [1], TENSE: [1], + waitingCount: () => 0, relabel: () => {}, saveSettings: () => {}, + window: {AudioContext: Audio, setTimeout: (fn) => { later.push(fn); return later.length; }, clearTimeout: () => {}}, + }; + vm.runInNewContext(read("page-music.js"), context); + const step = (name) => ({name, running: Boolean(context.music.gain), ...counts}); + const seen = []; + context.syncMusic(); + seen.push(step("on")); + context.radio.playing = true; + context.tuneMusic(1); + later.splice(0).forEach((fn) => fn()); + seen.push(step("radio")); + context.radio.playing = false; + context.tuneMusic(1); + seen.push(step("rise")); + context.settings.music.volume = 0; + context.tuneMusic(1); + seen.push(step("silent")); + return seen; +}; + +const streamDraws = async () => { + const list = new El(); + const requests = []; + let answer = null; + const entry = (id, text) => ({id, ts: 100, kind: "radio", waiting: false, text}); + const context = { + El, STREAM_KEEP: 2000, + stream: {key: null, events: [entry("radio:1", "a")], entries: [], last: 0, sessions: {}, busy: false, again: false, dom: {count: new El(), list}, error: "", tag: ""}, + state: {inbox: []}, ui: {screen: "stream", preset: 0, offline: false}, FEED_LIMIT: 400, + live: () => true, nowSeconds: () => 200, activeWaiting: () => false, emptyState: () => new El(), + keepTyping: (_, fn) => fn(), keepScroll: (_, fn) => fn(), h: () => new El(), + windowKey: () => "w", windowQuery: () => "from=0", filterQuery: () => "kinds=radio", + fetch: async (url, options) => { requests.push(options.headers["If-None-Match"] || ""); return answer; }, + }; + vm.runInNewContext(`${read("page-stream.js")}\neventRow = () => new El();`, context); + const draws = []; + const note = (name) => draws.push([name, list.replaced]); + context.drawStream(true); + note("first"); + context.drawStream(true); + note("same"); + context.drawStream(); + note("forced"); + context.stream.events = [entry("radio:1", "changed")]; + context.drawStream(true); + note("content"); + const body = {events: [entry("radio:1", "changed")], entries: [], last: 0, sessions: {}}; + answer = {status: 200, ok: true, headers: {get: () => '"t1"'}, json: async () => body}; + await context.fetchEvents(); + note("fetched"); + answer = {status: 304, ok: false, headers: {get: () => '"t1"'}, json: async () => { throw new Error("no body"); }}; + await context.fetchEvents(); + note("not modified"); + return {draws, requests, events: context.stream.events.length, tag: context.stream.tag, offline: context.ui.offline}; +}; + +(async () => { + results.timers = timers(); + results.music = music(); + results.stream = await streamDraws(); + console.log(JSON.stringify(results)); +})().catch((error) => { console.error(error && error.stack || error); process.exit(1); }); +""" + + +class TestRegisterCache(HubCase): + def parses(self, calls: list) -> int: + return sum(1 for call in calls if call.args[0].name == register.REGISTER) + + def test_two_states_on_an_unchanged_register_parse_it_once(self): + self.write_council({"rasci.json": REGISTER}) + with mock.patch.object(register, "read_json", wraps=register.read_json) as reader: + self.snapshot() + self.snapshot() + self.assertEqual(self.parses(reader.call_args_list), 1) + self.write_council({"rasci.json": {**REGISTER, "work/next": {"title": "Next", "status": "queued", "roles": {}}}}) + self.assertIn("work/next", {row["task"] for row in self.snapshot()["tasks"]}) + self.assertEqual(self.parses(reader.call_args_list), 2) + + def test_each_call_gets_its_own_top_level_dict_over_shared_rows(self): + self.write_council({"rasci.json": REGISTER}) + path = self.council / register.REGISTER + first, second = register.read_register(path), register.read_register(path) + self.assertIsNot(first, second) + self.assertIs(first["work/hub"], second["work/hub"]) + self.assertEqual(register.read_register(self.council / "missing.json"), {}) + + +class TestLiveStateSlots(unittest.TestCase): + def test_polls_within_the_ttl_share_one_build_and_one_encoding(self): + live = LiveState(60.0) + calls: list[int] = [] + + def build() -> dict: + calls.append(1) + return {"build": len(calls)} + + first = live.encoded("live", build) + self.assertIs(live.encoded("live", build), first) + self.assertEqual((len(calls), json.loads(first)), (1, {"build": 1})) + self.assertEqual(live.shared("live", build), {"build": 1}) + + def test_a_slot_rounds_the_window_start_down_to_the_ttl(self): + self.assertEqual([LiveState(2.0).slot(moment) for moment in (100.0, 101.9, 102.0)], [100.0, 100.0, 102.0]) + self.assertEqual(LiveState(0.0).slot(101.5), 101.5) + + def test_stale_slots_leave_the_cache(self): + live = LiveState(0.05) + live.shared(1, dict) + time.sleep(0.1) + live.shared(2, dict) + self.assertEqual((set(live.built), set(live.locks)), ({2}, {2})) + + +class TestLivePollsRoute(HubCase): + def live_ttl(self) -> float: + return 60.0 + + def test_polls_whose_start_shares_a_slot_share_one_state(self): + start = int(time.time()) // 60 * 60 - 3600 + first = self.state_at(f"from={start}") + self.assertEqual(self.state_at(f"from={start + 30}")["now"], first["now"]) + self.assertGreater(self.state_at(f"from={start - 60}")["now"], first["now"]) + self.assertGreater(self.state_at(f"from={start}&to={int(first['now'])}")["now"], first["now"]) + + def test_a_window_start_after_now_is_refused(self): + self.assertEqual(self.get(f"/api/state?from={int(time.time()) + 3600}")[0], 400) + + def state_at(self, query: str) -> dict: + status, headers, body = self.get(f"/api/state?{query}") + self.assertEqual((status, headers["content-type"]), (200, "application/json"), body) + return json.loads(body) + + +class TestEventsTag(HubCase): + def tagged(self, tag: str) -> tuple[int, dict, bytes]: + connection = http.client.HTTPConnection("127.0.0.1", self.port, timeout=30) + try: + connection.request("GET", "/api/events?kinds=radio", headers={"Host": self.host, "If-None-Match": tag}) + response = connection.getresponse() + return response.status, {name.lower(): value for name, value in response.getheaders()}, response.read() + finally: + connection.close() + + def test_the_current_tag_answers_304_without_a_body_and_a_change_answers_200(self): + now = time.time() + self.write_council({"news.jsonl": self.jsonl([{"ts": now - 10, "from": "One", "to": [], "text": "first"}])}) + status, headers, body = self.get("/api/events?kinds=radio") + self.assertEqual(status, 200, body) + tag = headers["etag"] + self.assertRegex(tag, r'^"[0-9a-f]{32}"$') + status, headers, body = self.tagged(tag) + self.assertEqual((status, body, headers["etag"]), (304, b"", tag)) + self.assertEqual(self.tagged('"other"')[0], 200) + self.write_council({"news.jsonl": self.jsonl([{"ts": now - 10, "from": "One", "to": [], "text": "first"}, {"ts": now - 5, "from": "Two", "to": [], "text": "second"}])}) + status, headers, body = self.tagged(tag) + self.assertEqual(status, 200, body) + self.assertNotEqual(headers["etag"], tag) + self.assertEqual([row["text"] for row in json.loads(body)["events"]], ["first", "second"]) + + +class TestPagePolls(unittest.TestCase): + @classmethod + def setUpClass(cls): + done = subprocess.run(["node", "-e", PROBE, str(TEMPLATES)], capture_output=True, text=True, timeout=60, check=False) + if done.returncode != 0: + raise AssertionError(done.stderr[-4000:]) + cls.data = json.loads(done.stdout) + + def test_a_hidden_tab_draws_no_sky_and_no_relayout_and_showing_it_lays_out_once(self): + found = self.data["timers"] + self.assertEqual((found["hidden"]["sky"], found["hidden"]["relayout"]), (0, 0), found) + self.assertEqual(found["hidden"]["radio"], 3, found) + self.assertEqual((found["shown"]["sky"], found["shown"]["relayout"], found["shown"]["radio"]), (0, 1, 4), found) + self.assertEqual((found["after"]["sky"], found["after"]["relayout"], found["after"]["radio"]), (0, 1, 5), found) + + def test_music_level_zero_stops_the_graph_and_a_rise_restarts_it(self): + steps = {step["name"]: step for step in self.data["music"]} + self.assertTrue(steps["on"]["running"], steps) + self.assertEqual((steps["radio"]["running"], steps["radio"]["stops"]), (False, steps["on"]["starts"]), steps) + self.assertTrue(steps["rise"]["running"], steps) + self.assertGreater(steps["rise"]["starts"], steps["on"]["starts"], steps) + self.assertFalse(steps["silent"]["running"], steps) + + def test_a_poll_with_unchanged_rows_replaces_none(self): + found = self.data["stream"] + self.assertEqual(found["draws"], [["first", 1], ["same", 1], ["forced", 2], ["content", 3], ["fetched", 3], ["not modified", 3]], found) + self.assertEqual(found["requests"], ["", '"t1"'], found) + self.assertEqual((found["events"], found["tag"], found["offline"]), (1, '"t1"', False), found) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_hub_popups.py b/tests/test_hub_popups.py new file mode 100644 index 0000000..740c54a --- /dev/null +++ b/tests/test_hub_popups.py @@ -0,0 +1,67 @@ +from __future__ import annotations + +import json +import time +import unittest + +from hub_case import HubCase +from hub_support import key, signing +from kvb_orchestrator import settings + +ALL_ON = {source: {"on": True, "until": 0} for source in settings.POPUP_SOURCES} + + +class TestHubPopups(HubCase): + def notified(self) -> dict | None: + file = self.council / settings.NOTIFY + return json.loads(file.read_text(encoding="utf-8")) if file.exists() else None + + def request(self, payload: dict) -> dict | None: + status, _, body = self.post_json("/api/settings/sign", payload, self.guard(self.host)) + self.assertEqual(status, 200, body) + return json.loads(body)["payload"] + + def test_every_save_writes_notify_json_and_a_popup_change_needs_the_passkey(self): + good = self.guard(self.host) + current = self.snapshot()["settings"] + self.assertEqual(current["popups"], ALL_ON) + quiet = {**current, "channels": {**current["channels"], "sounds": False}} + self.assertIsNone(self.request(quiet)) + self.assertEqual(self.post_json("/api/settings", {**quiet, "proof": None}, good)[0], 200) + self.assertEqual(self.notified(), ALL_ON) + muted = {**quiet, "popups": {**ALL_ON, "resources": {"on": False, "until": 0}}} + self.assertEqual(self.post_json("/api/settings", {**muted, "proof": None}, good)[:3:2], (400, b"not signed: no signature\n")) + self.assertEqual(self.notified(), ALL_ON) + signer = self.pin() + request = self.request(muted) + self.assertEqual(request["items"], [signing.item_hash(signing.popups_item(muted["popups"]))]) + stranger = self.post_json("/api/settings", {**muted, "proof": key(-7, "stranger").proof(request, self.origin)}, good) + self.assertEqual(stranger[:3:2], (400, b"not signed: the signing key is not pinned\n")) + snoozed = {**quiet, "popups": {**ALL_ON, "mayday": {"on": True, "until": int(time.time()) + 3600}}} + self.assertEqual(self.post_json("/api/settings", {**snoozed, "proof": signer.proof(request, self.origin)}, good)[:3:2], (400, b"not signed: the signature does not list this item\n")) + self.assertEqual(self.notified(), ALL_ON) + status, _, body = self.post_json("/api/settings", {**muted, "proof": signer.proof(request, self.origin)}, good) + self.assertEqual((status, json.loads(body)["settings"]["popups"]), (200, muted["popups"]), body) + self.assertEqual(self.notified(), muted["popups"]) + self.assertEqual(settings.Settings(self.state / "settings.json").get()["popups"], muted["popups"]) + + def test_a_popup_entry_must_name_every_source_with_a_bool_and_a_whole_second(self): + current = self.snapshot()["settings"] + wrongs = [ + {**ALL_ON, "dream": {"on": "yes", "until": 0}}, + {**ALL_ON, "dream": {"on": True, "until": -1}}, + {**ALL_ON, "dream": {"on": True, "until": 2.5}}, + {**ALL_ON, "dream": {"on": True, "until": True}}, + {**ALL_ON, "dream": {"on": True, "until": settings.POPUP_UNTIL + 1}}, + {**ALL_ON, "dream": {"on": True}}, + {**ALL_ON, "dream": {"on": True, "until": 0, "extra": 1}}, + {source: entry for source, entry in ALL_ON.items() if source != "dream"}, + {**ALL_ON, "email": {"on": True, "until": 0}}, + ] + for wrong in wrongs: + with self.subTest(wrong=wrong): + self.assertEqual(self.post_json("/api/settings/sign", {**current, "popups": wrong}, self.guard(self.host))[0], 400) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_hub_radioset.py b/tests/test_hub_radioset.py index 88a3d10..4b8be4f 100644 --- a/tests/test_hub_radioset.py +++ b/tests/test_hub_radioset.py @@ -177,7 +177,7 @@ function element(tag, attrs, ...children) { } function faced(mode) { const calls = []; - const sandbox = {RadioSet, radioSet: RadioSet.valid({mode, fallback: "morse"}), settings: {morse: {wpm: 18}}, h: element, icon: (name) => name, named: (label, hint) => ({"aria-label": label, title: hint})}; + const sandbox = {RadioSet, radioSet: RadioSet.valid({mode, fallback: "morse"}), settings: {morse: {wpm: 18}, bubbles: false}, toggleBubbles: () => null, h: element, icon: (name) => name, named: (label, hint) => ({"aria-label": label, title: hint})}; vm.runInNewContext(viewCode, sandbox); sandbox.knobs = () => []; sandbox.morseSpeed = () => element("label", {class: "morse-speed"}); @@ -185,7 +185,7 @@ function faced(mode) { sandbox.keepRadio = (change) => calls.push(change); const part = {}; const face = sandbox.faceplate(part); - const modes = face.children.find((child) => child.attrs["aria-label"] === "Mode"); + const modes = face.children.flatMap((child) => [child, ...(child.children || [])]).find((child) => child.attrs && child.attrs["aria-label"] === "Mode"); const button = (id) => modes.children.find((child) => child.dataset.mode === id); return {calls, part, modes, button, carets: modes.children.filter((child) => child.children.some((node) => node.attrs && node.attrs.class === "mode-caret")).map((child) => child.dataset.mode)}; } @@ -449,7 +449,6 @@ ROWS = { "mayday": {"class": "mayday", "source": "s1", "voice": "v1", "word": WORD, "rest": "this is Docs Docs Docs, disk full, over"}, "security": {"class": "security", "source": "s2", "voice": "v2", "word": "say-cure-ee-tay say-cure-ee-tay say-cure-ee-tay", "rest": "all stations, this is Stage, rotate, over"}, "post": {"class": "post", "source": "s2", "voice": "v2", "word": "", "rest": "Operator, Operator, this is Stage, ready, over"}, - "muted": {"class": "security", "source": "s9", "voice": "v9", "word": "say-cure-ee-tay say-cure-ee-tay say-cure-ee-tay", "rest": "all stations, this is Muted, x, over"}, "voiceless": {"class": "post", "source": "s3", "voice": "", "word": "", "rest": "x"}, } LOG = [ @@ -473,8 +472,14 @@ TONES = ("mayday", "review", "direct", "radio") BELL_SET = { "sounds": {"mayday": {"on": True, "volume": 0.9}, "review": {"on": True, "volume": 0.6}, "direct": {"on": True, "volume": 0.5}, "radio": {"on": False, "volume": 0.25}}, "classes": ["mayday", "pan-pan", "security", "newsletter"], - "muted": ["s1"], } +AGENTS = { + "s1": {"sound": False, "aloud": False, "bubbles": False}, + "s2": {"sound": False, "aloud": True, "bubbles": True}, + "s3": {"sound": True, "aloud": False, "bubbles": False}, +} +STEPS = [{"kind": "word", "text": "W"}, {"kind": "speech", "text": "R"}, {"kind": "burst"}, {"kind": "morse"}, {"kind": "gibberlink"}] +SENDERS = [("security", "s2"), ("post", "s3"), ("mayday", "s1"), ("security", "s1"), ("post", "s4")] def run(calls: dict[str, list[list]]) -> dict: @@ -485,7 +490,7 @@ def run(calls: dict[str, list[list]]) -> dict: class TestRadioSetModule(unittest.TestCase): @classmethod def setUpClass(cls): - defaults = {"mode": "auto", "fallback": "burst", "classes": ["mayday", "pan-pan", "security"], "muted": ["s9"], "sounds": {}, "squelch": 1, "log": {}} + defaults = {"mode": "auto", "fallback": "burst", "classes": ["mayday", "pan-pan", "security"],"sounds": {}, "squelch": 1, "log": {}} modes = ("auto", "quiet", "silence") lives = ({"tts": True, "open": True}, {"tts": True, "open": False}, {"tts": False, "open": True}) plans = [["plan", ROWS[name], {**defaults, "mode": mode}, live] for mode in modes for live in lives for name in ROWS] @@ -518,7 +523,8 @@ class TestRadioSetModule(unittest.TestCase): "bursts": [["burst", 0.45], ["burst", 0]], "bells": [["bell", BELL_SET, tone] for tone in TONES] + [["bell", {**BELL_SET, "classes": ["mayday", "post"]}, "direct"]], "rings": [["ring", BELL_SET, tone] for tone in TONES], - "mutes": [["muting", BELL_SET, "s1"], ["muting", BELL_SET, "s2"]], + "voiced": [["voiced", STEPS, {"class": cls, "source": source}, AGENTS] for cls, source in SENDERS], + "heard": [["heard", {"class": cls, "source": source}, AGENTS, "bubbles"] for cls, source in SENDERS], }) cls.modes, cls.lives = modes, lives @@ -549,12 +555,11 @@ class TestRadioSetModule(unittest.TestCase): self.assertEqual(self.plan("silence", live, "mayday"), [{"kind": "word", "text": WORD}] if self.lives[live]["tts"] else []) self.assertEqual(self.plan("silence", live, "post"), []) - def test_the_read_aloud_filters_skip_classes_and_muted_agents_but_never_a_mayday(self): + def test_the_read_aloud_filters_skip_classes_but_never_a_mayday(self): for mode in self.modes: for live in range(len(self.lives)): with self.subTest(mode=mode, live=live): self.assertEqual(self.plan(mode, live, "post"), []) - self.assertEqual(self.plan(mode, live, "muted"), []) self.assertEqual(self.plan(mode, live, "voiceless"), []) self.assertNotEqual(self.plan("auto", 0, "security"), []) @@ -570,8 +575,10 @@ class TestRadioSetModule(unittest.TestCase): self.assertEqual((radio["sounds"]["radio"], radio["classes"]), ({**sounds["radio"], "on": True}, ["mayday", "pan-pan", "security"])) self.assertEqual(mayday["sounds"]["review"], sounds["review"]) - def test_muting_toggles_one_agent_and_keeps_the_others(self): - self.assertEqual(self.data["mutes"], [{"muted": []}, {"muted": ["s1", "s2"]}]) + def test_an_agents_own_switches_drop_its_spoken_steps_sounds_or_bubble_but_never_a_mayday(self): + word, speech, burst, morse, gibberlink = STEPS + self.assertEqual(self.data["voiced"], [[word, speech], [burst, morse, gibberlink], STEPS, [], STEPS]) + self.assertEqual(self.data["heard"], [True, False, True, False, True]) def test_the_burst_is_band_passed_noise_of_about_0_6_seconds_at_the_given_loudness(self): loud, silent = self.data["bursts"] @@ -585,7 +592,7 @@ class TestRadioSetModule(unittest.TestCase): self.assertEqual((empty, broken, listed), (defaults, defaults, defaults)) self.assertEqual(defaults["mode"], "auto") self.assertEqual(self.data["constants"]["key"], "kvb-orchestrator.radio") - self.assertEqual((wrong["mode"], wrong["squelch"], wrong["classes"], wrong["muted"]), ("auto", 1, ["post", "mayday"], ["s1", "s2"])) + self.assertEqual((wrong["mode"], wrong["squelch"], wrong["classes"], "muted" in wrong), ("auto", 1, ["post", "mayday"], False)) self.assertEqual(wrong["sounds"]["radio"], {"on": False, "volume": 0.4}) self.assertEqual(wrong["sounds"]["review"], {"on": False, "volume": 0.6}) self.assertEqual((chosen["mode"], chosen["squelch"], chosen["classes"]), ("quiet", 0, list(council.CLASSES))) diff --git a/tests/test_hub_receipts.py b/tests/test_hub_receipts.py index 5f3d443..6a9ac12 100644 --- a/tests/test_hub_receipts.py +++ b/tests/test_hub_receipts.py @@ -41,11 +41,11 @@ const fs = require("fs"); const vm = require("vm"); const Receipts = require(process.argv[1]); const RadioSet = require(process.argv[2]); -const code = ["page-dom.js", "page-stream.js", "page-radioview.js", "page-radiolog.js", "page-agent.js"].map((name) => fs.readFileSync(`${process.argv[3]}/${name}`, "utf8")).join("\\n"); +const code = ["page-dom.js", "page-codebox.js", "page-stream.js", "page-radioview.js", "page-radiolog.js", "page-agent.js", "page-agentset.js"].map((name) => fs.readFileSync(`${process.argv[3]}/${name}`, "utf8")).join("\\n"); const input = JSON.parse(process.argv[4]); class Node { constructor(tag) { - Object.assign(this, {tag, attrs: {}, children: []}); + Object.assign(this, {tag, attrs: {}, children: [], dataset: {}}); } setAttribute(key, value) { this.attrs[key] = value; @@ -66,7 +66,7 @@ const find = (node, test, out = []) => { return out; }; const sandbox = { - Receipts, RadioSet, radioSet: RadioSet.valid({muted: ["s2"]}), Node, NS: "svg", HUMAN: "Operator", DAY: 86400, WEEKDAYS: [], revealed: String, + Receipts, RadioSet, radioSet: RadioSet.valid({}), settings: {agents: {s2: {sound: false, aloud: false, bubbles: true}}}, Node, NS: "svg", HUMAN: "Operator", DAY: 86400, WEEKDAYS: [], revealed: String, document: {createElement: (tag) => new Node(tag), createElementNS: (ns, tag) => new Node(tag)}, relative: {format: () => "ago"}, absolute: {format: (date) => `at ${date.getTime() / 1000}`}, Faces: {of: () => ({parts: []}), SIZE: 10}, speech: {current: null}, look: {hidden: new Set()}, PRESENCE: {}, STATUS: {}, @@ -82,7 +82,7 @@ const shape = (node) => ({ })), more: find(node, (item) => item.attrs.class === "readers-more").map((item) => ({text: text(item), title: item.attrs.title})), groups: find(node, (item) => item.attrs.class === "readers").map((item) => item.attrs["aria-label"]), - mutes: find(node, (item) => item.attrs.class === "radio-mute").map((item) => [item.attrs["aria-label"], item.attrs["aria-pressed"], find(item, (part) => part.attrs["data-face"] !== undefined).map((part) => part.attrs["data-face"])]), + senders: find(node, (item) => item.attrs.class === "radio-sender").map((item) => [item.attrs["aria-label"], item.attrs["data-quiet"], find(item, (part) => part.attrs["data-face"] !== undefined).map((part) => part.attrs["data-face"])]), }); console.log(JSON.stringify({ events: input.events.map((entry) => shape(sandbox.probe.eventRow(entry))), @@ -919,8 +919,8 @@ class TestReceiptsPage(unittest.TestCase): self.assertEqual((silent["readers"], silent["groups"]), ([], [])) self.assertEqual(self.data["events"][2]["readers"], []) - def test_a_log_row_from_an_agent_leads_with_its_avatar_that_mutes_it(self): - self.assertEqual([row["mutes"] for row in self.data["logs"]], [[], [], [], [["Mute Two", "true", ["s2"]]], [["Mute Skills", "false", ["s5"]]]]) + def test_a_log_row_from_an_agent_leads_with_its_avatar_that_opens_it_greyed_while_its_sound_and_read_aloud_are_off(self): + self.assertEqual([row["senders"] for row in self.data["logs"]], [[], [], [], [["Open Two", "true", ["s2"]]], [["Open Skills", "false", ["s5"]]]]) def test_more_than_eight_readers_collapse_into_plus_n_with_the_full_list_on_hover(self): crowd = self.data["events"][1] diff --git a/tests/test_hub_settings.py b/tests/test_hub_settings.py index 112afbd..ab1f48c 100644 --- a/tests/test_hub_settings.py +++ b/tests/test_hub_settings.py @@ -194,6 +194,21 @@ class TestHubSettings(HubCase): (self.state / "settings.json").write_text(json.dumps(older), encoding="utf-8") self.assertEqual(settings.Settings(self.state / "settings.json").get()["trend"], {"mode": "off", "days": 7}) + def test_the_undo_window_takes_whole_seconds_from_0_to_60_and_a_sheet_without_it_keeps_it(self): + self.assertEqual((settings.SETTINGS["undo"], self.snapshot()["settings"]["undo"]), (3, 3)) + good = self.guard(self.host) + for wrong in (-1, 61, 2.5, True, "10", None): + with self.subTest(wrong=wrong): + self.assertEqual(self.post_json("/api/settings", {**settings.SETTINGS, "undo": wrong}, good)[0], 400) + for chosen in (0, 60, 10): + with self.subTest(chosen=chosen): + status, _, body = self.post_json("/api/settings", {**self.snapshot()["settings"], "undo": chosen, "proof": None}, good) + self.assertEqual((status, json.loads(body)["settings"]["undo"]), (200, chosen)) + self.assertEqual(settings.Settings(self.state / "settings.json").get()["undo"], 10) + sheet = {key: value for key, value in self.snapshot()["settings"].items() if key != "undo"} + self.assertEqual(self.post_json("/api/settings", {**sheet, "proof": None}, good)[0], 200) + self.assertEqual(self.snapshot()["settings"]["undo"], 10) + def test_the_rates_chip_defaults_to_tasks_tokens_and_cpu_per_hour_is_validated_stored_without_a_passkey_survives_a_reload_and_a_sheet_without_it_keeps_it(self): default = {"period": "hour", "metrics": ["tasks", "tokens", "cpu"]} self.assertEqual((settings.SETTINGS["rates"], self.snapshot()["settings"]["rates"]), (default, default)) diff --git a/tests/test_hub_speak_card.py b/tests/test_hub_speak_card.py index 3e07482..3b4d2aa 100644 --- a/tests/test_hub_speak_card.py +++ b/tests/test_hub_speak_card.py @@ -59,23 +59,30 @@ class TestSpeakCard(unittest.TestCase): self.assertTrue(out["idle"][2].startswith("MAYDAY: "), out) self.assertEqual(out["active"], ["true", "Cancel mayday", "Cancel mayday: lift the radio silence so the agents write again; your passkey signs it"]) - def test_the_channel_select_holds_no_mayday_and_every_option_has_a_title(self): + def test_the_channel_select_holds_no_mayday_and_every_channel_keeps_its_hint_for_the_choice_buttons(self): out = self.probe() self.assertEqual(out["channels"], ["post", "call", "newsletter", "broadcast", "pan-pan", "security"]) self.assertTrue(out["titled"], out) - def test_the_card_has_no_hint_sentence_and_no_browser_confirm(self): + def test_the_card_has_no_hint_sentence_no_hint_tooltip_and_no_browser_confirm(self): composer = (TEMPLATES / "page-composer.js").read_text(encoding="utf-8") self.assertNotIn("window.confirm", composer) self.assertNotIn("Your passkey signs every message", composer) self.assertNotIn("composer-hint", composer) - self.assertRegex(composer, r"status, h\(\"div\", \{class: \"ptt-split\".*\), mayday\)\);") + self.assertNotIn("CHANNEL_HINTS[", composer) + + def test_channel_row_textarea_and_footer_share_one_frame_with_ptt_and_mayday_after_the_mic(self): + composer = (TEMPLATES / "page-composer.js").read_text(encoding="utf-8") + self.assertIn("const frame = micFrame(text, [record, status]);", composer) + self.assertIn('frame.prepend(h("div", {class: "composer-grid"}', composer) + self.assertRegex(composer, r'frame\.querySelector\("\.mic-foot"\)\.append\(h\("div", \{class: "ptt-split".*\), mayday\);') + self.assertIn('h("form", {class: "composer"}, frame, replay)', composer) def test_the_card_is_one_rounded_surface(self): css = (TEMPLATES / "style-ui.css").read_text(encoding="utf-8") self.assertRegex(css, r"\.radio-card\.radio-speak \{ border-radius: 14px; \}") - self.assertRegex(css, r"\.composer-grid \{[^}]*border-radius: 10px;") - self.assertRegex(css, r"\.composer textarea \{[^}]*border-radius: 10px;") + self.assertRegex(css, r"\.composer-grid \{ display: flex; min-width: 0; border-bottom: 1px solid var\(--line\); \}") + self.assertNotRegex(css, r"\.composer textarea \{[^}]*border-radius") self.assertNotIn(".radio-cancel", css) self.assertIsNone(re.search(r'class: "[^"]*\bcard\b', (TEMPLATES / "page-composer.js").read_text(encoding="utf-8"))) diff --git a/tests/test_hub_speech_gate.py b/tests/test_hub_speech_gate.py index d213020..0aeb463 100644 --- a/tests/test_hub_speech_gate.py +++ b/tests/test_hub_speech_gate.py @@ -271,7 +271,7 @@ class TestSpeechGateHttp(HubCase): self.host_cpu(50.0, 5) state = self.snapshot() self.assertEqual(state["speech"]["gate"], {"threshold": 50, "cpu": 50.0, "open": False}) - rows = [(row["word"], row["rest"], row["speech"]) for row in state["radio"]] + rows = [(row["word"], row["rest"], phrasing.joined((row["word"], row["rest"]))) for row in state["radio"]] self.assertEqual(rows, [ (WORDS["mayday"], "this is Docs Docs Docs, disk full, over", f"{WORDS['mayday']}, this is Docs Docs Docs, disk full, over"), ("", "Skills, Skills, this is Docs, ready, over", "Skills, Skills, this is Docs, ready, over"), diff --git a/tests/test_hub_state.py b/tests/test_hub_state.py index ac3ddea..68dc49e 100644 --- a/tests/test_hub_state.py +++ b/tests/test_hub_state.py @@ -68,7 +68,7 @@ class TestHubState(HubCase): self.assertEqual(self.status(review_id), "pending") def test_state_is_empty_without_council_files(self): - empty = {"reviews": [], "operator": [], "register": [], "radio": [], "claims": [], "grants": [], "agent_order": []} + empty = {"reviews": [], "operator": [], "tasks": [], "radio": [], "claims": [], "grants": [], "agent_order": []} state = self.snapshot() self.assertEqual({key: state[key] for key in empty}, empty) self.assertEqual([(node["id"], node["kind"]) for node in state["graph"]["nodes"]], [("Operator", "operator")]) @@ -101,10 +101,12 @@ class TestHubState(HubCase): state = self.snapshot() operator = state["operator"] self.assertEqual([(row["task"], row["command"], row["why"], row["status"]) for row in operator], [("operator/push-skills", "git-sign-push", "needs the key", "queued")]) - self.assertEqual([row["task"] for row in state["register"]], ["work/bare", "work/hub"]) - hub = state["register"][1] + self.assertNotIn("register", state) + shown = {row["task"]: row for row in state["tasks"]} + self.assertEqual({task for task, row in shown.items() if not row["ended"] and not task.startswith("operator/")}, {"work/bare", "work/hub"}) + hub = shown["work/hub"] self.assertEqual((hub["title"], hub["responsible"], hub["accountable"], hub["met"], hub["total"]), ("Build the hub", "One", "One", 1, 2)) - self.assertEqual(state["register"][0]["status"], "queued") + self.assertEqual(shown["work/bare"]["status"], "queued") texts = [row["text"] for row in state["radio"]] self.assertEqual(len(texts), 30) self.assertEqual((texts[0], texts[-2], texts[-1]), ("item 05", "item 33", "disk full")) @@ -151,12 +153,12 @@ class TestHubState(HubCase): set(state), { "now", "since", "until", "first", "alarm_since", "reviews", "asks", "decisions", "messages", "reasons", "operator", - "register", "tasks", "task_edges", "queue_line", "queue_jobs", "agent_order", "radio", "claims", "grants", "night", "night_parts", "presence", "silence", "graph", + "schedules", "tasks", "task_edges", "queue_line", "queue_jobs", "agent_order", "radio", "claims", "grants", "night", "night_parts", "presence", "silence", "graph", "inbox", "pending", "rules", "approvers", "jobs", "views", "llm", "people", "settings", "media", "speech", "badges", "kinds", }, ) - self.assertEqual([row["speech"] for row in state["radio"]], [ + self.assertEqual([phrasing.joined((row["word"], row["rest"])) for row in state["radio"]], [ "Maintainer, Maintainer, this is Skills, ready, over", "Maintainer, Maintainer, this is Skills, again, over", "all stations, this is Maintainer, board, out", diff --git a/tests/test_hub_undo_window.py b/tests/test_hub_undo_window.py new file mode 100644 index 0000000..def3ea1 --- /dev/null +++ b/tests/test_hub_undo_window.py @@ -0,0 +1,41 @@ +from __future__ import annotations + +import json +import time +import unittest + +from hub_case import HubCase +from kvb_orchestrator import settings + + +class TestHubUndoWindow(HubCase): + real_undo = True + + def window(self, seconds: int) -> None: + payload = {**self.snapshot()["settings"], "undo": seconds, "proof": None} + self.assertEqual(self.post_json("/api/settings", payload, self.guard(self.host))[0], 200) + + def granted(self, title: str, signer) -> tuple[str, float, dict]: + review = self.request(title, "") + entries = [self.entry("review", review, "", "")] + sent = time.time() + status, _, body = self.approve(entries, self.signed(entries, signer)) + self.assertEqual(status, 202, body) + return review, sent, json.loads(body) + + def test_a_new_batch_takes_the_saved_window_and_0_applies_at_once(self): + self.assertEqual(settings.SETTINGS["undo"], 3) + signer = self.pin() + self.window(10) + review, sent, batch = self.granted("feat: ten", signer) + self.assertAlmostEqual(batch["due"] - sent, 10, delta=0.5) + self.assertEqual(self.status(review), "pending") + self.assertEqual(self.call("POST", f"/api/inbox/undo/{batch['id']}", b"", self.guard(self.host))[0], 200) + self.window(0) + review, sent, batch = self.granted("feat: zero", signer) + self.assertLessEqual(batch["due"] - sent, 0.5) + self.settle(lambda: self.status(review) == "approved") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_install.py b/tests/test_install.py index f026edc..d13ecc1 100644 --- a/tests/test_install.py +++ b/tests/test_install.py @@ -27,6 +27,7 @@ HOME_TOOLS = ("bash", "cp", "dirname", "find", "install", "ln", "mkdir", "python COUNCIL_PARTS = ( "scripts/orchestrator.sh", "scripts/tokeneconomizer.sh", "plugins-lock.json", "skills/kvb-org-organize/scripts/councilroot.py", "skills/kvb-org-organize/scripts/nofollow.py", + "skills/kvb-org-organize/scripts/schedules.py", ) AGENT_ROOTS = {"sandbox": {"filesystem": {"allowWrite": ["~/.local/state/agents-shared", "~/.local/state/agents-release/**"]}}} CGROUP_KILL = """ @@ -40,6 +41,9 @@ HOME_UNITS = ( "kvb-org-queue-cleanup/systemd/kvb-org-queue-cleanup.service", "kvb-org-queue-cleanup/systemd/kvb-org-queue-cleanup.timer", "kvb-org-queue-cleanup/systemd/kvb-org-queue-cleanup.path", + "kvb-org-organize/systemd/kvb-schedules.service", + "kvb-org-organize/systemd/kvb-schedules.timer", + "kvb-org-organize/systemd/kvb-schedules.path", ) @@ -118,7 +122,7 @@ class TestInstall(unittest.TestCase): self.assertEqual(json.loads(config.read_text(encoding="utf-8")), {"mine": True}) self.assertIn(str(config), done.stderr) - def home_install(self, root: Path, binary: bool, config: bool = True, fail_now: bool = False) -> tuple[subprocess.CompletedProcess, list[str], list[str]]: + def home_install(self, root: Path, binary: bool, config: bool = True, fail_now: bool = False, schedules: dict | None = None) -> tuple[subprocess.CompletedProcess, list[str], list[str]]: repo, stubs, home = root / "repo", root / "bin", root / "home" (repo / "scripts").mkdir(parents=True) shutil.copy(INSTALL, repo / "scripts" / "install.sh") @@ -154,6 +158,10 @@ class TestInstall(unittest.TestCase): (home / ".config" / "kvb-code-graph" / "config.json").write_text( '{"queue_file_threshold": 2000, "queue_task": "work/code-graph-index"}\n', encoding="utf-8" ) + if schedules is not None: + council = home / ".local" / "state" / "agents-shared" + council.mkdir(parents=True, mode=0o700) + (council / "schedules.json").write_text(json.dumps(schedules), encoding="utf-8") env = {"PATH": str(stubs), "TARGET": str(home), "HOME": str(home), "AGENTS_COUNCIL_LEGACY": str(root / "legacy")} done = subprocess.run(["/bin/bash", str(repo / "scripts" / "install.sh")], env=env, capture_output=True, text=True, check=False) return done, read_lines(log), read_lines(cbm) @@ -168,6 +176,25 @@ class TestInstall(unittest.TestCase): self.assertEqual(installed.read_text(encoding="utf-8"), UNIT.read_text(encoding="utf-8")) self.assertNotIn("kvb-code-graph: no config", done.stderr) + def test_the_home_install_starts_the_schedules_reconciler_and_leaves_the_dream_timer_to_it(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + done, calls, _ = self.home_install(root, binary=True) + self.assertEqual(done.returncode, 0, done.stderr) + self.assertIn("--user enable --now kvb-org-queue-cleanup.timer kvb-org-queue-cleanup.path kvb-schedules.path kvb-schedules.timer", calls) + self.assertIn("--user start kvb-schedules.service", calls) + self.assertFalse([call for call in calls if "enable" in call and "kvb-dream-notify" in call]) + units = root / "home" / ".config" / "systemd" / "user" + for name in ("kvb-schedules.service", "kvb-schedules.timer", "kvb-schedules.path", "kvb-dream-notify.timer"): + self.assertTrue((units / name).is_file(), name) + + def test_a_code_graph_row_switched_off_keeps_the_service_off_on_a_reinstall(self): + with tempfile.TemporaryDirectory() as tmp: + done, calls, _ = self.home_install(Path(tmp), binary=True, schedules={"code-graph": {"on": False}}) + self.assertEqual(done.returncode, 0, done.stderr) + self.assertFalse([call for call in calls if "kvb-code-graph" in call]) + self.assertIn("kvb-code-graph.service stays off", done.stdout + done.stderr) + def test_the_home_install_turns_the_daemon_auto_index_off(self): with tempfile.TemporaryDirectory() as tmp: done, _, cbm = self.home_install(Path(tmp), binary=True) @@ -267,5 +294,21 @@ class TestInstall(unittest.TestCase): self.assertTrue((installed / "locked" / "SKILL.md").is_file()) +class TestCoachLock(unittest.TestCase): + COACH = ("kvb-coach", "kvb-coach-meditation", "kvb-coach-off", "kvb-coach-on") + + def test_the_lock_pins_the_four_coach_skills_at_one_commit_of_the_coach_repository(self): + lock = json.loads((REPO_ROOT / "skills-lock.json").read_text(encoding="utf-8"))["skills"] + coach = {name: entry for name, entry in lock.items() if entry["source"] == "kevinveenbirkenbach/coach"} + self.assertEqual(sorted(coach), list(self.COACH)) + self.assertEqual(len({entry["commit"] for entry in coach.values()}), 1) + self.assertEqual({name: (entry["sourceType"], entry["skillPath"]) for name, entry in coach.items()}, {name: ("github", f"skills/{name}/SKILL.md") for name in self.COACH}) + self.assertFalse([name for name in self.COACH if (REPO_ROOT / "skills" / name).exists()]) + + def test_the_installer_registers_the_coach_reminder_it_does_not_ship(self): + text = (REPO_ROOT / "scripts" / "enable-plugins.js").read_text(encoding="utf-8") + self.assertIn('const REMINDERS = ["kvb-dream", "kvb-coach"];', text) + + if __name__ == "__main__": unittest.main() diff --git a/tests/test_lean_output.py b/tests/test_lean_output.py new file mode 100644 index 0000000..790c27d --- /dev/null +++ b/tests/test_lean_output.py @@ -0,0 +1,147 @@ +"""Requirement 062: capped register table, MEMORY.md budget, narrowed graph hooks, velocity in kvb-check-efficiency.""" + +from __future__ import annotations + +import json +import shutil +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + +REPO_ROOT = Path(__file__).resolve().parents[1] +RASCI = REPO_ROOT / "skills" / "kvb-org-rasci" / "scripts" / "rasci.py" +BUDGET = REPO_ROOT / "scripts" / "budget.py" +GRAPH_HOOKS = REPO_ROOT / "scripts" / "graph-hooks.js" +GRAPH = "/home/op/.local/bin/codebase-memory-mcp" +OPEN_ROWS = 600 + + +class Scratch(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.base = Path(self.tmp.name) + + def run_script(self, command: list[str], env: dict[str, str] | None = None) -> subprocess.CompletedProcess: + return subprocess.run( + command, capture_output=True, text=True, env=env, cwd=self.base, check=False, timeout=120 + ) + + +class TestRegisterTable(Scratch): + def show(self, roles: dict[str, str], results: list[dict], *args: str) -> list[str]: + root = self.base / "council" + root.mkdir() + rows = { + f"work/t{n:03d}": {"title": f"T{n}", "prio": n, "roles": roles, "key_results": results} + for n in range(1, OPEN_ROWS + 1) + } + (root / "rasci.json").write_text(json.dumps(rows), encoding="utf-8") + env = {"PATH": "/usr/bin:/bin", "HOME": str(self.base / "home"), + "AGENTS_COUNCIL_ROOT": str(root), "CLAUDE_CODE_SESSION_ID": "s1"} + done = self.run_script([sys.executable, str(RASCI), "show", *args], env) + self.assertEqual(done.returncode, 0, done.stderr) + return done.stdout.splitlines() + + def test_show_prints_the_top_30_rows_and_counts_the_rest(self): + lines = self.show({"One": "AR"}, [{"text": "k", "met": False}]) + self.assertLessEqual(len(lines), 33) + self.assertTrue(lines[31].startswith("| 30 | - | work/t030: T30 |"), lines[31]) + self.assertEqual(lines[-1], f"{OPEN_ROWS - 30} more (show --all)") + + def test_show_all_lists_every_row_without_the_more_line(self): + lines = self.show({"One": "AR"}, [{"text": "k", "met": False}], "--all") + self.assertEqual(len(lines), OPEN_ROWS + 2) + self.assertNotIn("more (show --all)", lines[-1]) + + def test_gaps_name_only_the_shown_rows(self): + lines = self.show({}, []) + self.assertEqual(lines[-2], f"{OPEN_ROWS - 30} more (show --all)") + self.assertIn("work/t030 has 0 A", lines[-1]) + self.assertNotIn("work/t031", lines[-1]) + + +class TestMemoryBudget(Scratch): + def budget(self, memory: Path, memory_words: int | None) -> subprocess.CompletedProcess: + skill = self.base / "skills" / "x" / "SKILL.md" + skill.parent.mkdir(parents=True) + skill.write_text("---\nname: x\ndescription: short\n---\nbody\n", encoding="utf-8") + if memory_words is not None: + memory.write_text(" ".join(["word"] * memory_words) + "\n", encoding="utf-8") + return self.run_script([sys.executable, str(BUDGET), "--repo", str(self.base), "--top", "1", + "--memory", str(memory)]) + + def test_a_memory_index_of_400_words_passes(self): + done = self.budget(self.base / "MEMORY.md", 400) + self.assertEqual(done.returncode, 0, done.stdout) + self.assertIn(f"400/400 words in {self.base / 'MEMORY.md'}", done.stdout) + + def test_a_memory_index_of_401_words_fails(self): + done = self.budget(self.base / "MEMORY.md", 401) + self.assertEqual(done.returncode, 1, done.stdout) + self.assertIn(f"MEMORY.md over 400: {self.base / 'MEMORY.md'} (401)", done.stdout) + + def test_a_missing_memory_index_counts_as_empty(self): + done = self.budget(self.base / "absent.md", None) + self.assertEqual(done.returncode, 0, done.stdout) + self.assertIn(f"0/400 words in {self.base / 'absent.md'}", done.stdout) + + +def graph_entry(matcher: str) -> dict: + return {"matcher": matcher, "hooks": [{"type": "command", "command": GRAPH}]} + + +@unittest.skipUnless(shutil.which("node"), "node not installed") +class TestGraphHooks(Scratch): + def test_graph_hooks_run_on_grep_and_glob_only_and_never_after_read(self): + other = {"matcher": "Bash", "hooks": [{"type": "command", "command": "/usr/bin/guard"}]} + mixed = {"matcher": "Read", "hooks": [{"type": "command", "command": GRAPH}, + {"type": "command", "command": "/usr/bin/audit"}]} + settings = self.base / "settings.json" + settings.write_text(json.dumps({"model": "x", "hooks": { + "PreToolUse": [graph_entry("Grep|Glob|Bash"), other, graph_entry("Grep|Glob|Bash")], + "PostToolUse": [graph_entry("Read"), mixed], + }}), encoding="utf-8") + settings.chmod(0o640) + done = self.run_script(["node", str(GRAPH_HOOKS), str(settings)]) + self.assertEqual(done.returncode, 0, done.stderr) + data = json.loads(settings.read_text(encoding="utf-8")) + self.assertEqual(data["model"], "x") + self.assertEqual(data["hooks"]["PreToolUse"], [graph_entry("Grep|Glob"), other]) + self.assertEqual(data["hooks"]["PostToolUse"], [mixed]) + self.assertEqual(settings.stat().st_mode & 0o777, 0o640) + + def test_a_second_run_changes_nothing(self): + settings = self.base / "settings.json" + settings.write_text(json.dumps({"hooks": {"PreToolUse": [graph_entry("Grep|Glob|Bash")]}}), encoding="utf-8") + self.run_script(["node", str(GRAPH_HOOKS), str(settings)]) + first = settings.read_text(encoding="utf-8") + done = self.run_script(["node", str(GRAPH_HOOKS), str(settings)]) + self.assertEqual(done.returncode, 0, done.stderr) + self.assertEqual(settings.read_text(encoding="utf-8"), first) + + def test_a_settings_file_without_json_stays_untouched(self): + settings = self.base / "settings.json" + settings.write_text("not json", encoding="utf-8") + done = self.run_script(["node", str(GRAPH_HOOKS), str(settings)]) + self.assertEqual(done.returncode, 1) + self.assertEqual(settings.read_text(encoding="utf-8"), "not json") + + +class TestVelocityFold(unittest.TestCase): + def test_no_skill_or_readme_names_the_folded_speed_skill(self): + texts = [REPO_ROOT / "README.md", *sorted((REPO_ROOT / "skills").glob("*/SKILL.md"))] + named = [str(path.relative_to(REPO_ROOT)) for path in texts + if "kvb-check-speed" in path.read_text(encoding="utf-8")] + self.assertEqual(named, []) + self.assertFalse((REPO_ROOT / "skills" / "kvb-check-speed").exists()) + + def test_the_efficiency_skill_measures_velocity(self): + text = (REPO_ROOT / "skills" / "kvb-check-efficiency" / "SKILL.md").read_text(encoding="utf-8") + self.assertIn("## Code: velocity", text) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_meditation.py b/tests/test_meditation.py deleted file mode 100644 index afd6060..0000000 --- a/tests/test_meditation.py +++ /dev/null @@ -1,108 +0,0 @@ -"""Exercise meditation.py and keep it in step with the keys and choices of meditation.html.""" - -from __future__ import annotations - -import importlib.util -import json -import re -import subprocess -import sys -import tempfile -import unittest -from pathlib import Path - -REPO_ROOT = Path(__file__).resolve().parents[1] -SKILL = REPO_ROOT / "skills" / "kvb-coach-meditation" -SCRIPT = SKILL / "scripts" / "meditation.py" -PAGE = SKILL / "assets" / "meditation.html" -FULL = [ - "minutes=5", - "beat=10", - "base=196", - "volume=0.4", - "mode=isochronic", - "palette=aurora", - "breathing=box", -] - - -class TestMeditation(unittest.TestCase): - def setUp(self): - self.tmp = tempfile.TemporaryDirectory() - self.addCleanup(self.tmp.cleanup) - self.state = Path(self.tmp.name) / "state" / "meditation.json" - - def _run(self, *args: str) -> subprocess.CompletedProcess: - return subprocess.run( - [sys.executable, str(SCRIPT), "--state", str(self.state), *args], - check=False, - capture_output=True, - text=True, - ) - - def _session(self) -> subprocess.CompletedProcess: - out = Path(self.tmp.name) / "session.html" - return self._run("session", "--page", str(PAGE), "--out", str(out)) - - def test_session_page_embeds_every_setting(self): - self.assertEqual(self._run("set", *FULL).returncode, 0) - result = self._session() - self.assertEqual(result.returncode, 0, result.stderr) - page = Path(result.stdout.strip()).read_text(encoding="utf-8") - self.assertNotIn("const SETTINGS = null;", page) - embedded = json.loads(re.search(r"const SETTINGS = (\{.*?\});", page).group(1)) - self.assertEqual(embedded["beat"], 10.0) - self.assertEqual(embedded["minutes"], 5) - self.assertEqual(set(embedded), {pair.split("=")[0] for pair in FULL}) - - def test_session_refuses_missing_settings(self): - self._run("set", "minutes=5") - self.assertEqual(self._session().returncode, 2) - self.assertFalse((Path(self.tmp.name) / "session.html").exists()) - - def test_invalid_values_exit_2_and_keep_the_state(self): - self._run("set", *FULL) - before = json.loads(self.state.read_text(encoding="utf-8")) - for pair in ("beat=20", "mode=loud", "minutes=five", "tempo=3", "volume"): - with self.subTest(pair=pair): - self.assertEqual(self._run("set", "minutes=7", pair).returncode, 2) - self.assertEqual(json.loads(self.state.read_text(encoding="utf-8")), before) - - -class TestPageMatchesScript(unittest.TestCase): - def test_keys_and_choices_agree(self): - spec = importlib.util.spec_from_file_location("meditation", SCRIPT) - module = importlib.util.module_from_spec(spec) - spec.loader.exec_module(module) - page = PAGE.read_text(encoding="utf-8") - self.assertEqual(page.count(module.PLACEHOLDER), 1) - keys = re.search(r"const KEYS = \[(.*?)\];", page).group(1) - self.assertEqual(re.findall(r'"(\w+)"', keys), list(module.KEYS)) - for name, choices in (("PALETTES", "palette"), ("PATTERNS", "breathing")): - block = re.search(rf"const {name} = \{{(.*?)\n\}};", page, re.DOTALL).group(1) - found = re.findall(r'^\s*"?(\w+)"?:', block, re.MULTILINE) - self.assertEqual(sorted(found), sorted(module.CHOICES[choices])) - - def test_buttons_show_vendored_icons_with_their_former_text(self): - page = PAGE.read_text(encoding="utf-8") - sprite = (REPO_ROOT / "orchestrator" / "vendor" / "bootstrap-icons" / "bootstrap-icons.svg").read_text(encoding="utf-8") - vendored = dict(re.findall(r'(.*?)', sprite, re.DOTALL)) - embedded = dict(re.findall(r'(.*?)', page, re.DOTALL)) - used = re.findall(r'', page) - self.assertTrue(used) - self.assertEqual(sorted(embedded), sorted(set(used))) - for name in used: - with self.subTest(icon=name): - self.assertEqual(embedded[name], vendored[name]) - buttons = re.findall(r"]*)>(.*?)", page, re.DOTALL) - self.assertEqual([re.sub(r"<[^>]+>", "", inner).strip() for _, inner in buttons], [""]) - for attributes, inner in buttons: - self.assertIn('', inner) - self.assertIn('title="Start"', attributes) - self.assertIn('aria-label="Start"', attributes) - self.assertNotIn("☀", page) - self.assertIsNone(re.search(r'(?:src|href)="(?:https?:)?//', page)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_naming.py b/tests/test_naming.py index 794a112..597b24d 100644 --- a/tests/test_naming.py +++ b/tests/test_naming.py @@ -9,11 +9,10 @@ from pathlib import Path REPO_ROOT = Path(__file__).resolve().parents[1] SKILLS = REPO_ROOT / "skills" README = REPO_ROOT / "README.md" -CATEGORIES = ("think", "create", "code", "ci", "git", "release", "check", "org", "agent", "skill", "coach") +CATEGORIES = ("think", "create", "code", "ci", "git", "release", "check", "org", "agent", "skill") UNCATEGORIZED = frozenset( { "kvb-cleanup", - "kvb-coach", "kvb-dream", "kvb-help", "kvb-match", diff --git a/tests/test_operator.py b/tests/test_operator.py index 099068b..57194b1 100644 --- a/tests/test_operator.py +++ b/tests/test_operator.py @@ -264,13 +264,13 @@ class TestOperator(unittest.TestCase): [ HEADER, "|---|---|---|---|---|", - f"| 1 | {repo} | git commit -m wip | work uncommitted | manual |", - f"| 2 | {repo} | git-sign-push | branch ahead | pushed:{repo} |", - f"| 3 | {src} | make install | copy \\| stale | installed:{src}={dst} |", - f"| 4 | {base} | pipx install kvb-fake-tool | tool missing | binary:kvb-fake-tool |", - f"| 5 | {base} | sudo rm {stale} | root owned | absent:{stale} |", - f"| 6 | {base} | sudo reboot | new kernel | manual |", - f"| 7 | {base} | sudo systemctl restart docker | daemon config | manual |", + f"| 1 | {repo} | step 1 | work uncommitted | manual |", + f"| 2 | {repo} | step 2 | branch ahead | pushed:{repo} |", + f"| 3 | {src} | step 3 | copy \\| stale | installed:{src}={dst} |", + f"| 4 | {base} | step 4 | tool missing | binary:kvb-fake-tool |", + f"| 5 | {base} | step 5 | root owned | absent:{stale} |", + f"| 6 | {base} | step 6 | new kernel | manual |", + f"| 7 | {base} | step 7 | daemon config | manual |", *self._block(1, "commit-row", repo, "git commit -m wip"), *self._block(2, "push-row", repo, "git-sign-push"), *self._block(3, "installed-row", src, "make install"), @@ -335,6 +335,30 @@ class TestOperator(unittest.TestCase): self.assertEqual((row["title"], row["description"]), ("sudo reboot now", "kernel 7.2.9")) self.assertNotIn("end", self._register()["operator/second"]) + def test_a_second_add_of_the_same_command_in_the_same_directory_joins_the_open_row(self): + self._add("first", self.base, "sudo reboot", "kernel", "manual") + joined = self._as("s2", "add", "again", "--dir", str(self.base), "--command", "sudo reboot", "--reason", "too", + "--check", "manual") + self.assertEqual((joined.returncode, joined.stdout), (0, "joined operator/first: it holds the same command in the same directory\n")) + self.assertEqual(self._open(), ["operator/first"]) + row = self._register()["operator/first"] + self.assertEqual((row["roles"]["One"], row["roles"]["s2"], row["sessions"]["s2"]), ("A", "A", "s2")) + (self.base / "sub").mkdir() + self._add("elsewhere", self.base / "sub", "sudo reboot", "other host", "manual") + self.assertEqual(self._open(), ["operator/first", "operator/elsewhere"]) + self._add("mine", self.base, "sudo reboot", "a second step of its own", "manual") + self.assertEqual(self._open(), ["operator/first", "operator/elsewhere", "operator/mine"]) + + def test_list_prints_each_command_once(self): + self._add("first", self.base, "sudo reboot", "kernel", "manual") + twin = self._run("set", "operator/twin", "--title", "sudo reboot", "--workdir", str(self.base), "--status", "queued", + script=RASCI) + self.assertEqual(twin.returncode, 0, twin.stderr) + listed = self._out("list") + self.assertEqual(listed[:2], [HEADER, "|---|---|---|---|---|"]) + self.assertEqual([line.split(" | ")[2] for line in listed[2:] if line.startswith("| ")], ["step 1"]) + self.assertEqual(sum(line == "sudo reboot" for line in listed), 1) + def test_legacy_row_without_check_counts_as_manual(self): result = self._run("set", "operator/legacy", "--title", "sudo reboot", "--status", "queued", script=RASCI) self.assertEqual(result.returncode, 0, result.stderr) diff --git a/tests/test_orchestrator_migration.py b/tests/test_orchestrator_migration.py index 02da632..8f527b7 100644 --- a/tests/test_orchestrator_migration.py +++ b/tests/test_orchestrator_migration.py @@ -139,7 +139,7 @@ class TestOrchestratorMigration(unittest.TestCase): self.assertIn(f"{share / NEW}/client/permission_hook.py", hooks[1]["hooks"][0]["command"]) self.assertEqual(settings.stat().st_mode & 0o777, 0o640) self.assertIn(f"{OLD}/client", (self.home / ".claude" / f"settings.json.before-{NEW}-migration").read_text(encoding="utf-8")) - self.assertEqual((first["images"], first["mcp"], first["enabled"]), ([f"{NEW}:local"], {NEW: "http://127.0.0.1:8737/mcp"}, [f"{NEW}-firewall.path", f"{NEW}-firewall.timer", f"{NEW}-offices.path", f"{NEW}-resources.timer", f"{NEW}-runner.service", f"{NEW}-sessions.timer"])) + self.assertEqual((first["images"], first["mcp"], first["enabled"]), ([f"{NEW}:local"], {NEW: "http://127.0.0.1:8737/mcp"}, [f"{NEW}-firewall.path", f"{NEW}-firewall.timer", f"{NEW}-offices.path", f"{NEW}-resources.timer", f"{NEW}-runner.service", f"{NEW}-sessions.timer", f"{NEW}-tokens.timer"])) self.assertIn(["docker", "compose", "--file", str(share / OLD / "compose.yml"), "down", "--remove-orphans"], first["calls"]) before = snapshot(self.home) diff --git a/tests/test_page_reveal.py b/tests/test_page_reveal.py index 27124da..916458e 100644 --- a/tests/test_page_reveal.py +++ b/tests/test_page_reveal.py @@ -10,7 +10,7 @@ from pathlib import Path from hub_support import signing TEMPLATES = Path(__file__).resolve().parent.parent / "orchestrator" / "templates" -MODULES = ["page-constants.js", "glossary.js", "answers.js", "ancestry.js", "page-reveal.js", "page-dom.js", "page-dialog.js", "page-diff.js", "page-rule-request.js", "page-inbox.js", "page-grant.js", "page-firewall.js", "page-review.js", "page-cleanup.js", "page-offices.js", "page-ancestry.js", "page-tasks-prio.js"] +MODULES = ["page-constants.js", "glossary.js", "answers.js", "ancestry.js", "page-reveal.js", "page-dom.js", "page-dialog.js", "page-diff.js", "page-codebox.js", "page-rule-request.js", "page-inbox.js", "page-grant.js", "page-firewall.js", "page-review.js", "page-cleanup.js", "page-offices.js", "page-ancestry.js", "page-tasks-prio.js"] RLO, ZWSP, LRI, SEPARATOR, CARRIAGE = chr(0x202E), chr(0x200B), chr(0x2066), chr(0x2028), chr(0x0D) FILLER, NBSP, CGJ, VS15, VS16 = chr(0x3164), chr(0xA0), chr(0x34F), chr(0xFE0E), chr(0xFE0F) HIDDEN = (RLO, ZWSP, LRI, SEPARATOR, CARRIAGE, FILLER, NBSP, CGJ, VS16) @@ -36,7 +36,7 @@ HARNESS = r"""const fs = require("fs"); const [dir, given] = [process.argv[2], JSON.parse(fs.readFileSync(process.argv[3], "utf8"))]; const source = given.files.map((name) => fs.readFileSync(`${dir}/${name}`, "utf8")).join("\n"); class FakeNode { - constructor(tag) { this.tag = tag; this.attrs = {}; this.children = []; } + constructor(tag) { this.tag = tag; this.attrs = {}; this.children = []; this.dataset = {}; } setAttribute(key, value) { this.attrs[key] = value; } getAttribute(key) { return key in this.attrs ? this.attrs[key] : null; } append(...children) { this.children.push(...children); } diff --git a/tests/test_popups.py b/tests/test_popups.py new file mode 100644 index 0000000..8c178c6 --- /dev/null +++ b/tests/test_popups.py @@ -0,0 +1,132 @@ +from __future__ import annotations + +import importlib.util +import json +import subprocess +import sys +import tempfile +import time +import unittest +from pathlib import Path + +REPO_ROOT = Path(__file__).resolve().parents[1] +SCRIPTS = REPO_ROOT / "skills" / "kvb-org-organize" / "scripts" +POPUPS = SCRIPTS / "popups.py" +WATCH = SCRIPTS / "watch.py" +DREAM = REPO_ROOT / "skills" / "kvb-dream" / "hooks" / "notify.sh" +HOUR = 3600 +RECORD = "import sys; open(sys.argv[1], 'a').write(sys.argv[2] + '\\n')" +SHOWN = {"on": True, "expired": True, "missing": True, "broken": True, "list": True, "wrong on": True, "bool until": True, "linked": True, "off": False, "snoozed": False} + + +def load(name: str, path: Path): + spec = importlib.util.spec_from_file_location(name, path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +class PopupCase(unittest.TestCase): + source = "resources" + + def setUp(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.base = Path(tmp.name) + self.root = self.base / "council" + self.root.mkdir(mode=0o700) + self.file = self.root / "notify.json" + + def put(self, case: str, now: float) -> None: + self.file.unlink(missing_ok=True) + entries = { + "on": {"on": True, "until": 0}, + "off": {"on": False, "until": 0}, + "snoozed": {"on": True, "until": int(now) + HOUR}, + "expired": {"on": True, "until": int(now) - 1}, + "wrong on": {"on": "no", "until": 0}, + "bool until": {"on": False, "until": True}, + } + if case in entries: + self.file.write_text(json.dumps({self.source: entries[case]}), encoding="utf-8") + elif case == "broken": + self.file.write_text("{not json", encoding="utf-8") + elif case == "list": + self.file.write_text("[]", encoding="utf-8") + elif case == "linked": + target = self.base / "elsewhere.json" + target.write_text(json.dumps({self.source: {"on": False, "until": 0}}), encoding="utf-8") + self.file.symlink_to(target) + + +class TestAllowed(PopupCase): + def test_only_a_source_switched_off_or_snoozed_past_now_is_muted_and_every_unreadable_state_allows_it(self): + popups = load("popups_allowed", POPUPS) + now = time.time() + for case, shown in SHOWN.items(): + with self.subTest(case=case): + self.put(case, now) + self.assertIs(popups.allowed(self.root, self.source, now), shown) + + def test_a_snooze_ends_at_its_until_second(self): + popups = load("popups_until", POPUPS) + self.file.write_text(json.dumps({"resources": {"on": True, "until": 1000}}), encoding="utf-8") + self.assertEqual([popups.allowed(self.root, "resources", now) for now in (999.5, 1000, 1000.5)], [False, True, True]) + self.assertTrue(popups.allowed(self.root, "mayday", 999)) + + +class TestCli(PopupCase): + def run_cli(self, *args: str) -> int: + env = {"PATH": "/usr/bin:/bin", "HOME": str(self.base), "AGENTS_COUNCIL_ROOT": str(self.root)} + return subprocess.run([sys.executable, "-I", str(POPUPS), *args], capture_output=True, text=True, timeout=30, check=False, env=env).returncode + + def test_the_exit_status_is_0_when_allowed_3_when_muted_and_2_on_a_wrong_call(self): + now = time.time() + for case, shown in SHOWN.items(): + with self.subTest(case=case): + self.put(case, now) + self.assertEqual(self.run_cli("allowed", self.source), 0 if shown else 3) + for wrong in ((), ("allowed",), ("allowed", "email"), ("muted", "resources"), ("allowed", "resources", "extra")): + with self.subTest(wrong=wrong): + self.assertEqual(self.run_cli(*wrong), 2) + + +class TestWatchPopup(PopupCase): + def test_watch_runs_its_notify_command_only_for_resources_on_and_not_snoozed(self): + watch = load("watch_popups", WATCH) + watch.ROOT = self.root + log = self.base / "notified.log" + cfg = {"notify": [sys.executable, "-c", RECORD, str(log)]} + now = time.time() + for case, shown in SHOWN.items(): + with self.subTest(case=case): + log.unlink(missing_ok=True) + self.put(case, now) + watch.notify(cfg, f"RESOURCE {case}") + self.assertEqual(log.read_text(encoding="utf-8") if log.exists() else "", f"RESOURCE {case}\n" if shown else "") + + +class TestDreamPopup(PopupCase): + source = "dream" + + def test_the_dream_reminder_reaches_notify_send_only_while_dream_is_on_and_not_snoozed(self): + bin_dir = self.base / "bin" + bin_dir.mkdir() + calls = self.base / "calls" + fake = bin_dir / "notify-send" + fake.write_text(f'#!/bin/sh\nprintf "%s\\n" "$@" >> "{calls}"\n', encoding="utf-8") + fake.chmod(0o755) + env = {"PATH": f"{bin_dir}:/usr/bin:/bin", "XDG_CURRENT_DESKTOP": "ubuntu:GNOME", "AGENTS_COUNCIL_ROOT": str(self.root)} + (self.root / "schedules.json").write_text(json.dumps({"dream-popup": {"on": True, "at": ["17:00"]}}), encoding="utf-8") + now = time.time() + for case, shown in SHOWN.items(): + with self.subTest(case=case): + calls.unlink(missing_ok=True) + self.put(case, now) + done = subprocess.run(["bash", str(DREAM)], capture_output=True, text=True, timeout=30, check=False, env=env) + self.assertEqual(done.returncode, 0, done.stderr) + self.assertEqual(calls.exists() and "/kvb-dream" in calls.read_text(encoding="utf-8"), shown) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_radio.py b/tests/test_radio.py index f9c15b1..63cb649 100644 --- a/tests/test_radio.py +++ b/tests/test_radio.py @@ -17,6 +17,7 @@ REPO_ROOT = Path(__file__).resolve().parents[1] RADIO = REPO_ROOT / "skills" / "kvb-org-radio" / "scripts" / "radio.py" LINE = re.compile(r"^(?:RADIO|MAIL) (CALL|BROADCAST|SECURITY|PAN-PAN|MAYDAY|POST|NEWSLETTER) \d\d:\d\d (.*)$", re.DOTALL) STORED = "ts: " +RECEIPT = r"^MAIL CALL read by Two \d\d:\d\d \(your call of \d\d:\d\d\)$" LISTENER = ( "import importlib.util, sys\n" "spec = importlib.util.spec_from_file_location('radio', sys.argv[1])\n" @@ -298,7 +299,9 @@ class TestRadio(unittest.TestCase): ) self.assertEqual(len(self._prompt("s2")), 1) self.assertNotIn("CALL One to Two: ring", self._prompt("s3")) - self.assertEqual(len(self._prompt("s1")), 1) + caller = self._prompt("s1") + self.assertEqual(len(caller), 2) + self.assertRegex(caller[1], RECEIPT) def test_prompt_hook_shows_ten_and_counts_the_rest(self): self._send("s1", "send", "security", "early warning") @@ -307,7 +310,7 @@ class TestRadio(unittest.TestCase): lines = self._prompt("s2") self.assertEqual(lines[0], "SECURITY One: early warning") self.assertEqual(lines[1:-1], [f"BROADCAST One: item {n}" for n in range(3, 12)]) - self.assertEqual(lines[-1], "RADIO 3 more items: radio.py show --all") + self.assertEqual(lines[-1], "RADIO 3 more items: radio.py show --all --since 1d --summary") self.assertEqual(self._prompt("s2"), []) def test_the_mailbox_delivers_post_and_newsletters_once_when_the_turn_ends(self): @@ -326,7 +329,7 @@ class TestRadio(unittest.TestCase): code, lines = self._mailbox("s2") self.assertEqual(code, 2) self.assertEqual(lines[:-1], [f"NEWSLETTER One: item {n}" for n in range(2, 12)]) - self.assertEqual(lines[-1], "MAIL 2 more items: radio.py show --all") + self.assertEqual(lines[-1], "MAIL 2 more items: radio.py show --all --since 1d --summary") self.assertEqual(self._mailbox("s2"), (0, [])) def test_a_read_call_puts_one_receipt_in_the_callers_mailbox_without_waking_it(self): @@ -340,13 +343,37 @@ class TestRadio(unittest.TestCase): self.assertEqual([(r["from"], r["to"], r["text"], r["v"], r["call"]) for r in receipts], [("Two", ["One"], "ring", 2, rows[0]["ts"])]) time.sleep(0.5) self.assertIsNone(caller.poll()) - code, lines = self._mailbox("s1") - self.assertEqual(code, 2) + self.assertEqual(self._mailbox("s1"), (0, [])) + lines = self._prompt("s1") self.assertEqual(len(lines), 1) - self.assertRegex(lines[0], r"^MAIL CALL Two read \d\d:\d\d: ring$") + self.assertRegex(lines[0], RECEIPT) + self.assertEqual(self._prompt("s1"), []) self.assertEqual(self._mailbox("s1"), (0, [])) self.assertEqual(self._mailbox("s2"), (0, [])) + def test_receipts_ride_with_other_mail_at_the_stop(self): + self._send("s1", "send", "call", "ring", "--to", "Two") + self.assertEqual(self._tool("s2"), ["CALL One to Two: ring"]) + self._send("s3", "post", "for one", "--to", "One") + code, lines = self._mailbox("s1") + self.assertEqual(code, 2) + self.assertRegex(lines[0], RECEIPT) + self.assertEqual(lines[1:], ["POST Three to One: for one"]) + self.assertEqual(self._prompt("s1"), []) + + def test_show_summary_prints_one_line_per_class_and_sender_since_a_span(self): + self._send("s1", "send", "broadcast", "first") + self._send("s1", "send", "broadcast", "second") + self._send("s2", "post", "board") + old = {"ts": time.time() - 7200, "class": "security", "from": "Old", "to": [], "text": "stale", "v": 2} + with (self.root / "news.jsonl").open("a", encoding="utf-8") as news: + news.write(json.dumps(old) + "\n") + shown = self._cli("s3", "show", "--all", "--since", "1h", "--summary") + self.assertEqual(shown.returncode, 0, shown.stderr) + lines = [re.sub(r"\d\d:\d\d", "HH:MM", line) for line in shown.stdout.splitlines()] + self.assertEqual(lines, ["BROADCAST One: 2, last HH:MM: second", "NEWSLETTER Two: 1, last HH:MM: board"]) + self.assertEqual(self._cli("s3", "show", "--since", "soon").returncode, 2) + def test_tool_hook_delivers_radio_rows_once_and_leaves_the_mail_for_the_stop(self): self._send("s1", "post", "board") self.assertEqual(self._tool("s2"), []) @@ -400,6 +427,24 @@ class TestRadio(unittest.TestCase): self._prompt("s3") self.assertEqual(log.read_text(encoding="utf-8"), "Agents radio MAYDAY by One: smoke\n") + def test_a_mayday_popup_muted_or_snoozed_in_notify_json_stays_away_and_comes_once_it_is_on_again(self): + log = self.root.parent / "notified.log" + script = "import sys; open(sys.argv[1], 'a').write(sys.argv[2] + '\\n')" + self.config.write_text(json.dumps({"notify": [sys.executable, "-c", script, str(log)]}), encoding="utf-8") + self.root.mkdir(mode=0o700, parents=True, exist_ok=True) + popups = self.root / "notify.json" + popups.write_text(json.dumps({"mayday": {"on": False, "until": 0}}), encoding="utf-8") + self._send("s1", "send", "mayday", "smoke") + self._prompt("s2") + self.assertFalse(log.exists()) + popups.write_text(json.dumps({"mayday": {"on": True, "until": int(time.time()) + 3600}}), encoding="utf-8") + self._prompt("s3") + self.assertFalse(log.exists()) + popups.write_text(json.dumps({"mayday": {"on": True, "until": int(time.time()) - 1}}), encoding="utf-8") + self._prompt("s2") + self._prompt("s3") + self.assertEqual(log.read_text(encoding="utf-8"), "Agents radio MAYDAY by One: smoke\n") + def test_a_mayday_that_sets_no_silence_notifies_at_once_and_none_replaces_another_senders_silence(self): log = self.root.parent / "notified.log" script = "import sys; open(sys.argv[1], 'a').write(sys.argv[2] + '\\n')" @@ -544,7 +589,7 @@ class TestRadio(unittest.TestCase): (self.root / "news.jsonl").write_text("".join(json.dumps(r) + "\n" for r in rows), encoding="utf-8") shown = self._tool("s2") self.assertEqual(len(shown), 11) - self.assertEqual(shown[-1], "RADIO 2 more items: radio.py show --all") + self.assertEqual(shown[-1], "RADIO 2 more items: radio.py show --all --since 1d --summary") def test_long_fields_are_clipped_and_a_planted_silence_stays_on_one_line(self): self.root.mkdir() @@ -742,7 +787,10 @@ class TestRadio(unittest.TestCase): self._pidfile("s3").write_text(str(os.getpid()), encoding="utf-8") self.assertEqual(self._send("s1", "feedback", "send", "ran y", "--to", "Two", "--sid", "s2"), ["sent call to Two"]) self.assertEqual(self._prompt("s3"), ["CALL One to Two: ran x", "CALL One to Two: ran y"]) - self.assertEqual(self._prompt("s1"), []) + receipts = self._prompt("s1") + self.assertEqual(len(receipts), 2) + for line in receipts: + self.assertRegex(line, RECEIPT) def test_a_row_pinned_to_a_codex_session_reaches_it_by_its_id(self): self._send(None, "feedback", "set", "call", "--session", "codex-1") diff --git a/tests/test_resources_sample.py b/tests/test_resources_sample.py index 4eefd1e..9a523af 100644 --- a/tests/test_resources_sample.py +++ b/tests/test_resources_sample.py @@ -437,30 +437,50 @@ class TestSamplerInScratchHome(unittest.TestCase): self.assertTrue(all(ASLEEP not in " ".join(call) for call in calls), calls) self.assertEqual(sorted(path.name for path in samples.parent.iterdir()), ["cpu.json", "samples.jsonl"]) + def test_an_empty_queue_starts_no_queue_script(self): + (self.council / "queue.json").write_text(json.dumps({"entries": []}), encoding="utf-8") + self.sample() + (found,) = [json.loads(line) for line in (self.resources / "samples.jsonl").read_text(encoding="utf-8").splitlines()] + self.assertEqual(found["queue"], {"waiting": 0, "active": 0}) + self.assertEqual([json.loads(line)[0] for line in self.log.read_text(encoding="utf-8").splitlines()], ["df", "nvidia-smi"]) + class TestTimer(unittest.TestCase): - def test_a_user_timer_runs_sample_and_tokens_every_minute_without_a_page_condition(self): - timer = (UNITS / "kvb-orchestrator-resources.timer").read_text(encoding="utf-8").splitlines() - service = (UNITS / "kvb-orchestrator-resources.service").read_text(encoding="utf-8").splitlines() - self.assertIn("OnCalendar=*-*-* *:*:00", timer) - self.assertIn("WantedBy=timers.target", timer) + def test_a_user_timer_runs_sample_every_minute_and_tokens_every_ten_without_a_page_condition(self): script = "/usr/bin/env python3 %h/.local/share/kvb-orchestrator/client/resources.py" shared = "--state ${KVB_ORCHESTRATOR_KEPT}/resources --council ${KVB_ORCHESTRATOR_COUNCIL}" - self.assertEqual([line for line in service if line.startswith("ExecStart=")], [ - f"ExecStart={script} sample {shared} --proc /proc --sys /sys --queue ${{KVB_ORCHESTRATOR_SKILLS}}/kvb-org-queue/scripts/queue.py", - f"ExecStart={script} tokens {shared} --transcripts ${{KVB_ORCHESTRATOR_PROJECTS}}", - ]) - self.assertIn("EnvironmentFile=%h/.local/share/kvb-orchestrator/.env", service) - self.assertIn("Type=oneshot", service) - self.assertFalse(any(line.startswith("ExecCondition=") for line in service)) + for unit, calendar, starts in ( + ("resources", "OnCalendar=*-*-* *:*:00", [f"ExecStart={script} sample {shared} --proc /proc --sys /sys --queue ${{KVB_ORCHESTRATOR_SKILLS}}/kvb-org-queue/scripts/queue.py"]), + ("tokens", "OnCalendar=*-*-* *:00/10:00", [f"ExecStart={script} tokens {shared} --transcripts ${{KVB_ORCHESTRATOR_PROJECTS}}"]), + ): + with self.subTest(unit=unit): + timer = (UNITS / f"kvb-orchestrator-{unit}.timer").read_text(encoding="utf-8").splitlines() + service = (UNITS / f"kvb-orchestrator-{unit}.service").read_text(encoding="utf-8").splitlines() + self.assertIn(calendar, timer) + self.assertIn("WantedBy=timers.target", timer) + self.assertEqual([line for line in service if line.startswith("ExecStart=")], starts) + self.assertIn("EnvironmentFile=%h/.local/share/kvb-orchestrator/.env", service) + self.assertIn("Type=oneshot", service) + self.assertFalse(any(line.startswith("ExecCondition=") for line in service)) - def test_orchestrator_install_enables_the_resources_timer(self): + def test_orchestrator_install_enables_the_resources_and_tokens_timers(self): script = (hub_support.REPO_ROOT / "scripts" / "orchestrator.sh").read_text(encoding="utf-8") self.assertIn('RESOURCES_UNIT="${NAME}-resources"', script) - self.assertIn('systemctl --user enable --now "${RESOURCES_UNIT}.timer"', script) + self.assertIn('TOKENS_UNIT="${NAME}-tokens"', script) + self.assertIn('systemctl --user enable --now "${RESOURCES_UNIT}.timer"\n\tsystemctl --user enable --now "${TOKENS_UNIT}.timer"', script) self.assertIn('"${HUB}/client/resources.py"', script) self.assertIn("KVB_ORCHESTRATOR_SKILLS=%s", script) +class TestHostUnitPins(unittest.TestCase): + def test_the_firewall_sessions_and_graph_units_hold_their_intervals_and_conditions(self): + firewall = (UNITS / "kvb-orchestrator-firewall.service").read_text(encoding="utf-8") + self.assertIn("tree-heartbeat -mmin -5", firewall) + self.assertIn("firewall/jobs", firewall.split("ExecCondition=", 1)[1].splitlines()[0]) + self.assertIn("OnUnitInactiveSec=30s", (UNITS / "kvb-orchestrator-sessions.timer").read_text(encoding="utf-8").splitlines()) + graph = (hub_support.REPO_ROOT / "skills" / "kvb-agent-optimize" / "scripts" / "graph.py").read_text(encoding="utf-8") + self.assertIn("SUPERVISE_SECONDS = 120\n", graph) + + if __name__ == "__main__": unittest.main() diff --git a/tests/test_schedules.py b/tests/test_schedules.py new file mode 100644 index 0000000..93256f0 --- /dev/null +++ b/tests/test_schedules.py @@ -0,0 +1,287 @@ +"""Pin requirement 057: schedules.json as the one store of the Schedules rows, the host reconciler and the hub's tab.""" + +from __future__ import annotations + +import importlib.util +import json +import shutil +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + +from hub_case import HubCase +from kvb_orchestrator import schedules as hub_schedules + +REPO_ROOT = Path(__file__).resolve().parents[1] +ORGANIZE = REPO_ROOT / "skills" / "kvb-org-organize" +HELPER = ORGANIZE / "scripts" / "schedules.py" +SYSTEMD = ORGANIZE / "systemd" +TEMPLATES = REPO_ROOT / "orchestrator" / "templates" +MICRO = 1_000_000 +TIMERS = [ + {"next": 1_800_000_000 * MICRO, "left": 1, "last": 1_799_990_000 * MICRO, "passed": 1, "unit": "kvb-dream-notify.timer", "activates": "kvb-dream-notify.service"}, + {"next": 1_800_000_500 * MICRO, "left": 1, "last": None, "passed": None, "unit": "kvb-orchestrator-tree.timer", "activates": "kvb-orchestrator-tree.service"}, + {"next": 0, "left": 0, "last": 0, "passed": 0, "unit": "backup.timer", "activates": "backup.service"}, +] +SETTINGS = { + "hooks": { + "UserPromptSubmit": [{"hooks": [ + {"type": "command", "command": "/usr/bin/bash /home/u/.claude/skills/kvb-dream/hooks/reminder.sh"}, + {"type": "command", "command": "/usr/bin/bash /home/u/.claude/skills/kvb-coach/hooks/reminder.sh"}, + ]}], + "PreToolUse": [{"matcher": "Bash", "hooks": [{"type": "command", "command": "python3 /opt/guard.py"}]}], + }, +} + + +def load(name: str, path: Path): + spec = importlib.util.spec_from_file_location(name, path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +helper = load("kvb_schedules_helper", HELPER) + + +class Runner: + def __init__(self, states: dict[str, str]) -> None: + self.states = states + self.calls: list[list[str]] = [] + + def __call__(self, argv: list[str]) -> tuple[int, str]: + self.calls.append(argv) + if argv[2] == "is-enabled": + states = [self.states.get(unit, "not-found") for unit in argv[3:]] + return (0 if "enabled" in states else 1), "".join(f"{state}\n" for state in states) + return 0, "" + + +class TestRows(unittest.TestCase): + def test_host_and_hub_share_the_rows_the_limits_and_the_file_names(self): + self.assertEqual(helper.ROWS, hub_schedules.ROWS) + self.assertEqual((helper.HOURS, helper.TIMES_LIMIT, helper.SCHEDULES, helper.SCHEDULES_VIEW), (hub_schedules.HOURS, hub_schedules.TIMES_LIMIT, hub_schedules.SCHEDULES, hub_schedules.SCHEDULES_VIEW)) + self.assertEqual(set(helper.UNITS) | set(helper.HOOKS), set(helper.ROWS)) + + def test_coach_and_dream_start_off_cleanup_and_code_graph_on(self): + self.assertEqual({name: row["on"] for name, row in helper.ROWS.items()}, {"coach": False, "dream": False, "dream-popup": False, "queue-cleanup": True, "code-graph": True}) + self.assertEqual((helper.ROWS["coach"]["every"], helper.ROWS["dream"]["every"], helper.ROWS["dream-popup"]["at"], helper.ROWS["queue-cleanup"]["at"]), (1, 12, ["17:00"], ["00:00", "12:00"])) + + def test_both_sides_refuse_the_same_bad_rows(self): + bad = [ + ("nope", {"on": True}), ("coach", {"on": "yes", "every": 1}), ("coach", {"on": True, "every": 0}), ("coach", {"on": True, "every": 25}), + ("coach", {"on": True, "every": True}), ("coach", {"on": True, "every": 1.5}), ("coach", {"on": True}), ("coach", {"on": True, "every": 1, "at": ["17:00"]}), + ("dream-popup", {"on": True, "at": []}), ("dream-popup", {"on": True, "at": ["24:00"]}), ("dream-popup", {"on": True, "at": ["7:00"]}), + ("queue-cleanup", {"on": True, "at": ["00:00", "00:00"]}), ("queue-cleanup", {"on": True, "at": [f"0{hour}:00" for hour in range(7)]}), + ("code-graph", {"on": True, "every": 1}), + ] + for name, row in bad: + with self.subTest(name=name, row=row): + with self.assertRaises(hub_schedules.ToolError): + hub_schedules.valid_row(name, row) + if name in helper.ROWS: + with self.assertRaises(ValueError): + helper.valid_row(name, row) + good = {"on": True, "at": ["21:30", "06:00"]} + self.assertEqual(hub_schedules.valid_row("queue-cleanup", good), helper.valid_row("queue-cleanup", good)) + self.assertEqual(helper.valid_row("queue-cleanup", good)["at"], ["06:00", "21:30"]) + + +class HelperCase(unittest.TestCase): + def setUp(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.base = Path(tmp.name) + self.root = self.base / "council" + self.root.mkdir(mode=0o700) + self.file = self.root / helper.SCHEDULES + + def cli(self, *args: str) -> subprocess.CompletedProcess: + env = {"PATH": "/usr/bin:/bin", "HOME": str(self.base), "AGENTS_COUNCIL_ROOT": str(self.root)} + return subprocess.run([sys.executable, "-I", str(HELPER), *args], capture_output=True, text=True, timeout=30, check=False, env=env) + + +class TestCheckAndSet(HelperCase): + def test_check_answers_the_defaults_for_a_missing_linked_or_malformed_file(self): + target = self.base / "elsewhere.json" + target.write_text(json.dumps({"dream": {"on": True, "every": 3}}), encoding="utf-8") + for case in ("missing", "linked", "broken", "list"): + with self.subTest(case=case): + self.file.unlink(missing_ok=True) + if case == "linked": + self.file.symlink_to(target) + elif case == "broken": + self.file.write_text("{", encoding="utf-8") + elif case == "list": + self.file.write_text("[]", encoding="utf-8") + self.assertEqual(self.cli("check", "dream").returncode, helper.OFF) + self.assertEqual(self.cli("check", "queue-cleanup").returncode, 0) + + def test_check_prints_the_hours_of_a_reminder_that_is_on(self): + self.file.write_text(json.dumps({"coach": {"on": True, "every": 3}}), encoding="utf-8") + done = self.cli("check", "coach") + self.assertEqual((done.returncode, done.stdout), (0, "3\n")) + + def test_set_writes_only_its_row_and_keeps_every_other_row_byte_for_byte(self): + rows = {**helper.ROWS, "dream": {"on": True, "every": 6}, "queue-cleanup": {"on": True, "at": ["03:00"]}} + self.file.write_text(json.dumps(rows, sort_keys=True), encoding="utf-8") + before = json.loads(self.file.read_text(encoding="utf-8")) + done = self.cli("set", "coach", "--on", "--every", "2") + self.assertEqual(done.returncode, 0, done.stderr) + self.assertEqual(json.loads(done.stdout), {"on": True, "every": 2}) + after = json.loads(self.file.read_text(encoding="utf-8")) + self.assertEqual({name: row for name, row in after.items() if name != "coach"}, {name: row for name, row in before.items() if name != "coach"}) + self.assertEqual(after["coach"], {"on": True, "every": 2}) + self.assertEqual(self.file.read_text(encoding="utf-8"), json.dumps(after, sort_keys=True)) + self.assertEqual(self.file.stat().st_mode & 0o777, 0o600) + + def test_set_refuses_a_bad_value_and_a_key_the_row_does_not_take(self): + for args in (("coach", "--every", "30"), ("coach", "--at", "17:00"), ("dream-popup", "--at", "25:00"), ("code-graph", "--every", "1")): + with self.subTest(args=args): + self.assertEqual(self.cli("set", *args).returncode, 2) + self.assertFalse(self.file.exists()) + + +class TestView(HelperCase): + def test_view_rows_name_owner_unit_file_schedule_runs_and_hooks(self): + units = self.base / "units" + units.mkdir() + (units / "kvb-dream-notify.timer").write_text("[Timer]\nOnCalendar=*-*-* 17:00:00\nPersistent=true\n", encoding="utf-8") + (units / "kvb-dream-notify.timer.d").mkdir() + (units / "kvb-dream-notify.timer.d" / "schedule.conf").write_text("[Timer]\nOnCalendar=\nOnCalendar=*-*-* 21:30:00\n", encoding="utf-8") + (units / "backup.timer").write_text("[Timer]\nOnBootSec=5min\nOnUnitActiveSec=1d\n", encoding="utf-8") + settings = self.base / "settings.json" + settings.write_text(json.dumps(SETTINGS), encoding="utf-8") + rows = {row["name"]: row for row in helper.view(TIMERS, settings, units)} + dream = rows["kvb-dream-notify.timer"] + self.assertEqual((dream["owner"], dream["schedule"], dream["next"], dream["last"], dream["off"]), ("skills", "OnCalendar=*-*-* 21:30:00", 1_800_000_000, 1_799_990_000, "")) + self.assertEqual(dream["file"], str(units / "kvb-dream-notify.timer")) + hub = rows["kvb-orchestrator-tree.timer"] + self.assertEqual((hub["owner"], hub["last"], hub["off"]), ("hub", None, "")) + backup = rows["backup.timer"] + self.assertEqual((backup["owner"], backup["schedule"], backup["next"], backup["off"]), ("other", "OnBootSec=5min; OnUnitActiveSec=1d", None, "systemctl --user disable --now backup.timer")) + self.assertEqual((rows["dream"]["owner"], rows["coach"]["owner"], rows["dream"]["event"]), ("skills", "skills", "UserPromptSubmit")) + guard = rows["PreToolUse hook"] + self.assertEqual((guard["owner"], guard["command"], guard["kind"]), ("other", "python3 /opt/guard.py", "hook")) + self.assertIn(str(settings), guard["off"]) + + def test_view_survives_a_broken_timer_answer_and_a_missing_settings_file(self): + self.assertEqual(helper.view({"not": "a list"}, self.base / "missing.json", self.base), []) + self.assertEqual(helper.view([{"unit": 5}, "x"], self.base / "missing.json", self.base), []) + + def test_view_through_the_cli_reads_a_timer_fixture(self): + fixture = self.base / "timers.json" + fixture.write_text(json.dumps(TIMERS), encoding="utf-8") + done = self.cli("view", "--timers", str(fixture), "--settings", str(self.base / "none.json"), "--units", str(self.base)) + self.assertEqual(done.returncode, 0, done.stderr) + self.assertEqual([row["name"] for row in json.loads(done.stdout)], [entry["unit"] for entry in TIMERS]) + + +class TestApply(HelperCase): + def setUp(self): + super().setUp() + self.units = self.base / "units" + self.units.mkdir() + for unit in helper.UNITS.values(): + (self.units / unit).write_text("[Unit]\n", encoding="utf-8") + + def test_apply_switches_only_first_party_units_whose_state_differs(self): + rows = {**helper.ROWS, "dream-popup": {"on": True, "at": ["17:00"]}, "code-graph": {"on": False}} + runner = Runner({"kvb-dream-notify.timer": "disabled", "kvb-org-queue-cleanup.timer": "enabled", "kvb-code-graph.service": "enabled"}) + calls = helper.apply(rows, runner, self.units) + self.assertIn("enable --now kvb-dream-notify.timer", calls) + self.assertIn("disable --now kvb-code-graph.service", calls) + self.assertFalse([call for call in calls if "queue-cleanup" in call and "able" in call]) + named = {unit for argv in runner.calls if argv[2] != "daemon-reload" for unit in argv[3:] if unit != "--now"} + self.assertLessEqual(named, set(helper.UNITS.values())) + self.assertFalse([argv for argv in runner.calls if any(part.startswith("kvb-orchestrator-") for part in argv)]) + + def test_a_retime_writes_the_drop_in_reloads_once_and_a_second_apply_changes_nothing(self): + rows = {**helper.ROWS, "queue-cleanup": {"on": True, "at": ["03:00", "15:30"]}} + runner = Runner({unit: "enabled" for unit in helper.UNITS.values()} | {"kvb-dream-notify.timer": "disabled"}) + calls = helper.apply(rows, runner, self.units) + drop_in = self.units / "kvb-org-queue-cleanup.timer.d" / "schedule.conf" + self.assertEqual(drop_in.read_text(encoding="utf-8"), "[Timer]\nOnCalendar=\nOnCalendar=*-*-* 03:00:00\nOnCalendar=*-*-* 15:30:00\n") + self.assertEqual(calls.count("daemon-reload"), 1) + self.assertIn("try-restart kvb-org-queue-cleanup.timer", calls) + self.assertEqual(helper.apply(rows, Runner(runner.states), self.units), []) + + def test_a_missing_masked_or_static_unit_is_never_switched(self): + rows = {name: {**row, "on": not row["on"]} for name, row in helper.ROWS.items()} + runner = Runner({"kvb-dream-notify.timer": "masked", "kvb-org-queue-cleanup.timer": "static"}) + self.assertEqual([call for call in helper.apply(rows, runner, self.units) if "able" in call], []) + + +class TestUnits(unittest.TestCase): + def test_the_path_unit_watches_schedules_json_and_the_timer_refreshes_every_five_minutes(self): + self.assertIn("PathModified=%S/agents-shared/schedules.json", (SYSTEMD / "kvb-schedules.path").read_text(encoding="utf-8")) + self.assertIn("OnUnitActiveSec=5min", (SYSTEMD / "kvb-schedules.timer").read_text(encoding="utf-8")) + self.assertIn("kvb-org-organize/scripts/schedules.py run", (SYSTEMD / "kvb-schedules.service").read_text(encoding="utf-8")) + + def test_the_installer_no_longer_enables_the_dream_timer(self): + text = (REPO_ROOT / "scripts" / "install.sh").read_text(encoding="utf-8") + enables = [line for line in text.splitlines() if "enable --now" in line] + self.assertTrue(enables) + self.assertFalse([line for line in enables if "kvb-dream-notify" in line]) + self.assertTrue([line for line in enables if "kvb-schedules.path kvb-schedules.timer" in line]) + + +class TestSchedulesApi(HubCase): + def post(self, payload: object) -> tuple[int, bytes]: + status, _, body = self.post_json("/api/schedules", payload, self.guard(self.host)) + return status, body + + def test_a_row_change_reaches_schedules_json_and_the_state_and_keeps_the_other_rows(self): + status, body = self.post({"row": "coach", "value": {"on": True, "every": 2}}) + self.assertEqual(status, 200, body) + stored = json.loads((self.council / hub_schedules.SCHEDULES).read_text(encoding="utf-8")) + self.assertEqual(stored, {**hub_schedules.ROWS, "coach": {"on": True, "every": 2}}) + status, body = self.post({"row": "dream-popup", "value": {"on": True, "at": ["21:30"]}}) + self.assertEqual(status, 200, body) + rows = self.snapshot()["schedules"]["rows"] + self.assertEqual((rows["coach"], rows["dream-popup"]), ({"on": True, "every": 2}, {"on": True, "at": ["21:30"]})) + self.assertEqual(helper.stored(self.council), rows) + + def test_bad_rows_answer_400_and_leave_the_file_alone(self): + for payload in ({"row": "nope", "value": {"on": True}}, {"row": "coach", "value": {"on": True, "every": 0}}, {"row": ["coach"], "value": {}}, {"row": "coach"}, [1]): + with self.subTest(payload=payload): + self.assertEqual(self.post(payload)[0], 400) + self.assertFalse((self.council / hub_schedules.SCHEDULES).exists()) + + def test_the_state_carries_the_host_view_and_drops_a_malformed_one(self): + self.council.mkdir(parents=True, exist_ok=True) + view = self.council / hub_schedules.SCHEDULES_VIEW + self.assertEqual(self.snapshot()["schedules"]["host"], {"at": None, "rows": []}) + row = {"name": "backup.timer", "kind": "timer", "owner": "other", "unit": "backup.timer", "file": "/u/backup.timer", "schedule": "OnBootSec=5min", "next": 1.5, "last": None, "event": "", "command": "", "off": "systemctl --user disable --now backup.timer"} + view.write_text(json.dumps({"at": 100, "rows": [row, {"name": 3}, "x"]}), encoding="utf-8") + self.assertEqual(self.snapshot()["schedules"]["host"], {"at": 100, "rows": [row]}) + view.write_text(json.dumps({"at": True, "rows": [row]}), encoding="utf-8") + self.assertEqual(self.snapshot()["schedules"]["host"], {"at": None, "rows": []}) + + def test_a_get_of_the_route_is_not_allowed(self): + self.assertEqual(self.get("/api/schedules")[0], 405) + + +@unittest.skipUnless(shutil.which("node"), "node not installed") +class TestRoute(unittest.TestCase): + def test_stream_schedules_opens_the_controls_screen_on_its_tab_and_back(self): + probe = ( + "const Nav = require(process.argv[1]);" + "console.log(JSON.stringify([Nav.route('#stream/schedules', 0), Nav.hashOf('rules', 'schedules'), Nav.hashOf('rules', null)]));" + ) + done = subprocess.run(["node", "-e", probe, str(TEMPLATES / "nav.js")], capture_output=True, text=True, timeout=30, check=True) + self.assertEqual(json.loads(done.stdout), [{"screen": "rules", "view": "schedules", "redirect": None}, "#stream/schedules", "#stream/rules"]) + + def test_the_controls_tabs_end_with_schedules_and_the_home_panel_is_registered(self): + firewall = (TEMPLATES / "page-firewall.js").read_text(encoding="utf-8") + self.assertIn('["groups", "Groups", "bi-people"], ["schedules", "Schedules", "bi-clock"]];', firewall) + self.assertIn('Panels.panel("stream/schedules",', (TEMPLATES / "page-home.js").read_text(encoding="utf-8")) + self.assertIn('"data-panel": "stream/schedules"', (TEMPLATES / "page-schedules.js").read_text(encoding="utf-8")) + index = (TEMPLATES / "index.html.j2").read_text(encoding="utf-8") + self.assertLess(index.index('"page-schedules.js"'), index.index('"page-home.js"')) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_security.py b/tests/test_security.py index 31bfdd2..0753939 100644 --- a/tests/test_security.py +++ b/tests/test_security.py @@ -215,7 +215,7 @@ class TestSecurity(unittest.TestCase): result = self.scan(env=self.env) self.assertEqual( result.stdout, - "🛡️ security 63 % (medusa: 4 findings in 2 files: high app.py:2, medium new.py:3, low new.py:1, " + "🛡️ security 63 % critical 0 (medusa: 4 findings in 2 files: high app.py:2, medium new.py:3, low new.py:1, " "info new.py:4)\n", ) self.assertEqual(result.returncode, 3, result.stderr) @@ -266,7 +266,7 @@ class TestSecurity(unittest.TestCase): result = self.scan(env=self.env) self.assertEqual( (result.stdout, result.returncode), - ("🛡️ security 100 % (medusa: 0 findings, 1 accepted in 1 file)\n", 0), + ("🛡️ security 100 % critical 0 (medusa: 0 findings, 1 accepted in 1 file)\n", 0), ) accepted = json.loads(self.scan("--json", env=self.env).stdout)["accepted"] self.assertEqual([(a["rule"], a["path"], a["line"]) for a in accepted], [("FAKE-CRITICAL", "app.py", 2)]) @@ -274,14 +274,14 @@ class TestSecurity(unittest.TestCase): result = self.scan(env=self.env) self.assertEqual( (result.stdout, result.returncode), - ("🛡️ security 50 % (medusa: 1 finding in 1 file: critical app.py:2)\n", 1), + ("🛡️ security 50 % critical 1 (medusa: 1 finding in 1 file: critical app.py:2)\n", 1), ) def test_one_acceptance_never_hides_an_identical_line_elsewhere(self): twin = "x = fetch(url) # MARK-HIGH" self.write("app.py", f"print(1)\n{twin}\ny = 2\n{twin}\n") sha1 = hashlib.sha1(twin.encode()).hexdigest() - both = ("🛡️ security 50 % (medusa: 2 findings in 1 file: high app.py:2, high app.py:4)\n", 3) + both = ("🛡️ security 50 % critical 0 (medusa: 2 findings in 1 file: high app.py:2, high app.py:4)\n", 3) listing = self.base / "council" / "security-accepted.jsonl" listing.parent.mkdir(parents=True) listing.write_text(json.dumps({"rule": "FAKE-HIGH", "path": "app.py", "sha1": sha1}) + "\n", encoding="utf-8") @@ -300,7 +300,7 @@ class TestSecurity(unittest.TestCase): result = self.scan(env=self.env) self.assertEqual( (result.stdout, result.returncode), - ("🛡️ security 75 % (medusa: 1 finding, 1 accepted in 1 file: high app.py:2)\n", 3), + ("🛡️ security 75 % critical 0 (medusa: 1 finding, 1 accepted in 1 file: high app.py:2)\n", 3), ) self.write("app.py", f"print(1)\n{twin}\ny = 3\n{twin}\n") result = self.scan(env=self.env) @@ -314,7 +314,7 @@ class TestSecurity(unittest.TestCase): sha1 = hashlib.sha1(line.encode()).hexdigest() kept.write_text(json.dumps({"rule": "FAKE-HIGH", "path": "app.py", "sha1": sha1}) + "\n", encoding="utf-8") result = self.scan(env=self.env) - self.assertEqual(result.stdout, "🛡️ security 100 % (medusa: 0 findings, 1 accepted in 1 file)\n") + self.assertEqual(result.stdout, "🛡️ security 100 % critical 0 (medusa: 0 findings, 1 accepted in 1 file)\n") kept.write_text('{"rule": "FAKE-HIGH"}\n', encoding="utf-8") result = self.scan(env=self.env) self.assertEqual(result.returncode, 2) @@ -331,7 +331,7 @@ class TestSecurity(unittest.TestCase): result = self.accept("--rule", "FAKE-FILE", "--path", "Dockerfile", "--sha1", sha1, "--reason", "fixture") self.assertEqual(result.returncode, 0, result.stderr) result = self.scan(env=self.env) - self.assertEqual(result.stdout, "🛡️ security 100 % (medusa: 0 findings, 1 accepted in 1 file)\n") + self.assertEqual(result.stdout, "🛡️ security 100 % critical 0 (medusa: 0 findings, 1 accepted in 1 file)\n") self.write("Dockerfile", text + "USER app\n") self.assertEqual(self.scan(env=self.env).returncode, 3) @@ -345,7 +345,7 @@ class TestSecurity(unittest.TestCase): self.assertEqual(result.returncode, 0, result.stderr) self.assertIn("accepted FAKE-HIGH, FAKE-LOW app.py", result.stdout) result = self.scan(env=self.env) - self.assertEqual(result.stdout, "🛡️ security 100 % (medusa: 0 findings, 2 accepted in 1 file)\n") + self.assertEqual(result.stdout, "🛡️ security 100 % critical 0 (medusa: 0 findings, 2 accepted in 1 file)\n") def test_mjs_and_cjs_files_medusa_skips_are_scanned_and_reported_at_their_repository_path(self): line = "run(request.query) // MARK-HIGH" @@ -353,7 +353,7 @@ class TestSecurity(unittest.TestCase): result = self.scan(env=self.env) self.assertEqual( (result.stdout, result.returncode), - ("🛡️ security 75 % (medusa: 1 finding in 1 file: high tool.mjs:2)\n", 3), + ("🛡️ security 75 % critical 0 (medusa: 1 finding in 1 file: high tool.mjs:2)\n", 3), ) sha1 = hashlib.sha1(line.encode()).hexdigest() result = self.accept( @@ -365,7 +365,7 @@ class TestSecurity(unittest.TestCase): result = self.scan(env=self.env) self.assertEqual( (result.stdout, result.returncode), - ("🛡️ security 88 % (medusa: 2 findings, 1 accepted in 3 files: medium tool.mjs.js:1, low lib.CJS:1)\n", 3), + ("🛡️ security 88 % critical 0 (medusa: 2 findings, 1 accepted in 3 files: medium tool.mjs.js:1, low lib.CJS:1)\n", 3), ) def test_a_folder_named_like_the_alias_keeps_both_paths_apart(self): @@ -374,7 +374,7 @@ class TestSecurity(unittest.TestCase): result = self.scan(env=self.env) self.assertEqual( (result.stdout, result.returncode), - ("🛡️ security 73 % (medusa: 2 findings in 2 files: high tool.mjs:1, low tool.mjs.js/inner.py:1)\n", 3), + ("🛡️ security 73 % critical 0 (medusa: 2 findings in 2 files: high tool.mjs:1, low tool.mjs.js/inner.py:1)\n", 3), ) def test_the_cache_keeps_the_repository_path_of_an_aliased_file(self): @@ -391,7 +391,7 @@ class TestSecurity(unittest.TestCase): result = self.scan(env=self.env) self.assertEqual( (result.stdout, result.returncode), - ("🛡️ security 90 % (medusa: 1 finding in 1 file: medium a/b/tool.mjs:1)\n", 3), + ("🛡️ security 90 % critical 0 (medusa: 1 finding in 1 file: medium a/b/tool.mjs:1)\n", 3), ) def test_an_mjs_file_name_without_room_for_the_alias_is_scanned_under_a_short_one(self): @@ -417,7 +417,7 @@ class TestSecurity(unittest.TestCase): self.assertEqual((result.stdout, result.returncode), (f"🛡️ security – ({problem}: {HAND})\n", 4)) self.assertTrue(argv.exists()) self.assertEqual(list(folder.glob("*.json")), []) - scored = ("🛡️ security 75 % (medusa: 1 finding in 1 file: high tool.mjs:1)\n", 3) + scored = ("🛡️ security 75 % critical 0 (medusa: 1 finding in 1 file: high tool.mjs:1)\n", 3) argv.unlink() result = self.scan(env=self.env) self.assertEqual((result.stdout, result.returncode), scored) @@ -431,7 +431,7 @@ class TestSecurity(unittest.TestCase): def test_critical_exits_1_and_floors_at_0(self): self.write("app.py", "a # MARK-CRITICAL\nb # MARK-CRITICAL\nc # MARK-CRITICAL\n") result = self.scan(env=self.env) - self.assertTrue(result.stdout.startswith("🛡️ security 0 % (medusa: 3 findings in 1 file: critical app.py:1, ")) + self.assertTrue(result.stdout.startswith("🛡️ security 0 % critical 3 (medusa: 3 findings in 1 file: critical app.py:1, ")) self.assertEqual(result.returncode, 1) def test_more_than_five_locations_are_cut(self): @@ -439,18 +439,18 @@ class TestSecurity(unittest.TestCase): result = self.scan(env=self.env) self.assertEqual( result.stdout, - "🛡️ security 86 % (medusa: 7 findings in 1 file: low app.py:1, low app.py:2, low app.py:3, " + "🛡️ security 86 % critical 0 (medusa: 7 findings in 1 file: low app.py:1, low app.py:2, low app.py:3, " "low app.py:4, low app.py:5, +2 more)\n", ) self.assertEqual(result.returncode, 3) def test_clean_and_empty_changes_are_100(self): result = self.scan(env=self.env) - self.assertEqual((result.stdout, result.returncode), ("🛡️ security 100 % (medusa: 0 findings in 0 files)\n", 0)) + self.assertEqual((result.stdout, result.returncode), ("🛡️ security 100 % critical 0 (medusa: 0 findings in 0 files)\n", 0)) self.assertFalse((self.bin / "argv.json").exists()) self.write("app.py", "print(2)\n") result = self.scan(env=self.env) - self.assertEqual((result.stdout, result.returncode), ("🛡️ security 100 % (medusa: 0 findings in 1 file)\n", 0)) + self.assertEqual((result.stdout, result.returncode), ("🛡️ security 100 % critical 0 (medusa: 0 findings in 1 file)\n", 0)) def test_missing_medusa_asks_for_a_review_by_hand(self): if shutil.which("medusa", path=GIT_DIR): @@ -510,7 +510,7 @@ class TestSecurity(unittest.TestCase): argv.unlink() result = self.scan(env=self.env) self.assertTrue(argv.exists()) - self.assertEqual(result.stdout, "🛡️ security 100 % (medusa: 0 findings in 1 file)\n") + self.assertEqual(result.stdout, "🛡️ security 100 % critical 0 (medusa: 0 findings in 1 file)\n") folder.chmod(0o777) entry.unlink() argv.unlink() @@ -544,7 +544,7 @@ class TestSecurity(unittest.TestCase): self.assertEqual(json.loads(result.stdout), {"security": None, "problem": f"{rerun}: medusa exit 3"}) argv.unlink() complete = self.scan(env=self.env) - self.assertEqual((complete.stdout, complete.returncode), ("🛡️ security 100 % (medusa: 0 findings in 1 file)\n", 0)) + self.assertEqual((complete.stdout, complete.returncode), ("🛡️ security 100 % critical 0 (medusa: 0 findings in 1 file)\n", 0)) self.assertTrue(argv.exists()) self.assertEqual(len(list(folder.glob("*.json"))), 1) argv.unlink() @@ -591,7 +591,7 @@ class TestSecurity(unittest.TestCase): )) self.assertFalse(argv.exists()) self.write("app.py", "print(1)\nx = 1 # MARK-HIGH\n") - scored = ("🛡️ security 75 % (medusa: 1 finding in 1 file: high app.py:2; not covered: tpl.conf.j2)\n", 3) + scored = ("🛡️ security 75 % critical 0 (medusa: 1 finding in 1 file: high app.py:2; not covered: tpl.conf.j2)\n", 3) result = self.scan(env=self.env) self.assertEqual((result.stdout, result.returncode), scored) argv.unlink() @@ -759,7 +759,7 @@ class TestSecurity(unittest.TestCase): for number in ignored: os.killpg(security.pid, number) out, _ = security.communicate(timeout=20) - self.assertEqual((out, security.returncode), ("🛡️ security 100 % (medusa: 0 findings in 1 file)\n", 0)) + self.assertEqual((out, security.returncode), ("🛡️ security 100 % critical 0 (medusa: 0 findings in 1 file)\n", 0)) def test_the_first_stop_signal_ignores_the_others_and_kills_the_group(self): spec = importlib.util.spec_from_file_location("kvb_check_security_halt", SECURITY) @@ -784,7 +784,7 @@ class TestSecurity(unittest.TestCase): cwd=self.base, env=self.env, capture_output=True, text=True, check=False, ) self.assertEqual( - (result.stdout, result.returncode), ("🛡️ security 100 % (medusa: 0 findings in 1 file)\n", 0), result.stderr, + (result.stdout, result.returncode), ("🛡️ security 100 % critical 0 (medusa: 0 findings in 1 file)\n", 0), result.stderr, ) def test_usage_errors_exit_2(self):