diff --git a/.github/workflows/betamax.yml b/.github/workflows/betamax.yml new file mode 100644 index 0000000..d382448 --- /dev/null +++ b/.github/workflows/betamax.yml @@ -0,0 +1,46 @@ +name: Betamax + +on: + pull_request: + +permissions: {} + +concurrency: + group: betamax-${{ github.ref }} + cancel-in-progress: true + +jobs: + render: + runs-on: ubuntu-24.04 + timeout-minutes: 15 + permissions: + contents: read + env: + CARGO_TARGET_DIR: ${{ github.workspace }}/target + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 + with: + persist-credentials: false + + - uses: dtolnay/rust-toolchain@6c977a6ca4077a0ceb28ffbe03f59d46e9ac8772 + with: + toolchain: stable + + - name: Build dirview + run: cargo build --manifest-path skills/ratatui/templates/dirview/Cargo.toml + + - name: Run terminal interaction tape + uses: joshka/betamax-action@bc6fa6bfb5e20dd342b588601f4e1a945661d5fe + with: + tapes: tapes/**/*.tape + formats: gif,png + extra-outputs: target/betamax/dirview-*.png + + - name: Upload terminal state checkpoints + if: always() + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 + with: + name: betamax-terminal-checkpoints + path: target/betamax/*.json + if-no-files-found: warn + diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b03df35..1e2bf7f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -89,6 +89,8 @@ jobs: run: bash -n skills/ratatui/scripts/*.sh - name: python syntax run: python3 -m py_compile skills/ratatui/scripts/pty-smoke.py + - name: lint scanner regression tests + run: python3 -m unittest discover -s skills/ratatui/scripts -p 'test_*.py' - name: crate-versions smoke run: skills/ratatui/scripts/crate-versions.sh ratatui | grep -q 'ratatui' diff --git a/AGENTS.md b/AGENTS.md index ab8ce60..087d705 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,52 +1,25 @@ -# Building ratatui apps +# Building Ratatui applications -For any Rust terminal UI task, follow `skills/ratatui/SKILL.md`. It is the -full process; this file is the short version for agents that read `AGENTS.md` -instead of loading skills. +Use `skills/ratatui/SKILL.md` when creating, modifying, debugging, or reviewing a Rust terminal UI built with Ratatui. -## Which workflow +## Workflow -- **New application:** follow steps 1-5 in full, including the design brief - and the template. -- **Existing application:** skip the design brief unless the layout archetype - changes. Inspect the existing code first. Make the smallest change. Preserve - existing dependencies and patterns. Do not copy the template. +- Inspect the repository, manifest, lockfile, source, and tests first. +- For a new application, choose an architecture that fits its complexity. +- For an existing application, preserve established patterns and make a targeted change. +- Use `skills/ratatui/templates/dirview/` as an example when its structure fits. It is not a mandatory starter. +- Do not apply this guidance to non-Ratatui or non-TUI tasks. -## Before writing code +## Engineering -1. **Research.** Run `$SKILL_DIR/scripts/crate-versions.sh ` for the - newest stable version and minimum Rust version of every dependency. Read the - ratatui `CHANGELOG.md` and `BREAKING-CHANGES.md` for that version. Never - write ratatui code, versions or feature flags from memory. If an API is - uncertain, compile a ten-line program that calls it. -2. **Design brief (new apps only).** State the layout archetype, one ANSI - accent color, density, modes and keys, and what each empty, error and - too-small state shows, justified from the app's data. - -## Building - -- New apps: start from `skills/ratatui/templates/dirview/` and copy its - structure: `action`, `keymap`, `state` (no terminal types), `ui` (no side - effects), `theme` (the only file naming colors). Rename the crate reference - in `main.rs` to match your package name. -- Existing apps: do not copy the template. Read the existing code first. -- One key table drives input, footer hints and the `?` help. -- Everything visible works. No fake data, decorative panels or dead keys. -- Measure text with `unicode-width`, sanitize untrusted text, draw only visible - rows. -- Colors by role, 16 ANSI by default, respect `NO_COLOR`, no forced background, - no emoji. -- If handling terminal events directly, declare a compatible direct `crossterm` dependency and import from `crossterm::event`. Verify `cargo tree -d` has no duplicate versions. -- No `.unwrap()` outside tests, no swallowed errors, no TODOs, comments say why. +- Verify APIs against the Ratatui version resolved by the project. +- Avoid unnecessary dependencies and version changes. +- Keep rendering responsive; move genuinely expensive work out of the draw path. +- Handle terminal resizing, input, and relevant empty or error states. +- Prefer state and behavior tests; use `TestBackend` for relevant rendering checks. +- Use PTY, VHS, Betamax, or equivalent integration tests when real terminal behavior is in scope. +- Treat architecture and visual conventions as context-dependent unless correctness requires them. ## Done means -See `skills/ratatui/SKILL.md` section 4 (Verify) for the canonical checklist. -Do not duplicate it here. - -Also read the rendered screens as text at several sizes -(`skills/ratatui/templates/dirview/examples/dump.rs`). Report what was built, -the versions used, what passed, and anything you could not check. - -More detail: `skills/ratatui/references/` (`research-checklist.md`, -`ux-principles.md`, `slop-tells.md`). +Run checks appropriate to the workspace and changed packages. Report exactly what ran, what passed, and what remains unverified. See `skills/ratatui/SKILL.md` for the detailed workflow and references. diff --git a/README.md b/README.md index 924bdf9..81269b7 100644 --- a/README.md +++ b/README.md @@ -19,6 +19,7 @@

Quick start · + Agent support · What changes · How it works · Demo · @@ -38,17 +39,30 @@ AI assistants write ratatui from memory. They reach for old APIs and wrong crate versions, then ship a UI that looks generated: neon defaults, decorative panels, keys that do nothing. -**ratatui-skill** replaces that with a fixed process and a tested template. The assistant looks up what is current, writes a design brief before any code (new apps only), builds from a working codebase, and proves the result before it says "done". +**ratatui-skill** provides a practical workflow, version-aware research, a working reference template, and verification guidance. The assistant inspects the project, adapts the process to the task, and reports what it actually checked. ## Quick start -1. Copy the skill into your assistant's skills directory. For Claude Code: +1. Copy the canonical skill directory into a discovery location supported by your agent. From the root of this repository: + + **Codex, Cursor, Antigravity, and OpenCode:** + + ```bash + mkdir -p /path/to/project/.agents/skills + rm -rf /path/to/project/.agents/skills/ratatui + cp -a skills/ratatui /path/to/project/.agents/skills/ratatui + ``` + + **Claude Code:** ```bash - mkdir -p ~/.claude/skills && cp -r skills/ratatui ~/.claude/skills/ # all projects - mkdir -p .claude/skills && cp -r skills/ratatui .claude/skills/ # one project + mkdir -p /path/to/project/.claude/skills + rm -rf /path/to/project/.claude/skills/ratatui + cp -a skills/ratatui /path/to/project/.claude/skills/ratatui ``` + See [agent compatibility and installation](docs/agent-compatibility.md) for global installs and native alternatives. + 2. Ask for a terminal UI: ```text @@ -56,19 +70,19 @@ AI assistants write ratatui from memory. They reach for old APIs and wrong crate mark them done, delete them, and save to a file so they're still there next time. ``` -3. Watch it research versions, write a brief, build, and run its own checks. +3. Watch it inspect the project, choose a proportionate workflow, build, and run relevant checks. -Assistants that read `AGENTS.md` instead of loading skills can use the one at the repo root. It carries the same process in short form and points at the skill files. +`AGENTS.md` is a concise fallback for agents that read repository instructions but do not discover skills. It does not install or auto-register the skill. See [agent compatibility](docs/agent-compatibility.md) for the supported discovery paths. ## What changes | Without the skill | With it | |---|---| -| Versions and APIs written from memory | Newest stable versions looked up and quoted, release notes read, uncertain calls compiled | -| Design is whatever comes to mind first | A written brief: layout, one accent color, density, keys, every empty, error and too-small state | +| Versions and APIs written from memory | Resolved versions and project constraints checked; release notes reviewed when versions or recent APIs change | +| Design choices are implicit | Layout and interactions follow the requirements and displayed data; document decisions when complexity warrants it | | Decorative panels, fake data, dead keys | Everything visible works | -| One long `main.rs` | State with no terminal types, rendering with no side effects, one key table | -| "Done" with nothing run | fmt, clippy, tests, screen dumps, a real pseudo-terminal run, and a slop scan | +| Structure chosen without considering scope | Clear state/rendering boundaries and shared key bindings where they reduce coupling or duplication | +| "Done" with nothing run | Relevant fmt, Clippy and tests; render or terminal integration checks where behavior requires them; honest reporting | | Silent about what was skipped | A report that names anything it could not check | ## How it works @@ -76,10 +90,10 @@ Assistants that read `AGENTS.md` instead of loading skills can use the one at th

Five steps, in order -1. **Research.** Look up the newest stable version, minimum Rust version, and (when given a manifest) the version resolved by the project of every crate, read the release notes, confirm widget crates match the ratatui version, and compile anything uncertain. -2. **Design brief.** Before any code: layout archetype, one accent color, density, keys, and what each empty or failed state shows, justified from the app's data. -3. **Build** from a tested template with a strict split: state with no terminal types, rendering with no side effects, and one key table that drives input, footer hints and help. -4. **Verify.** `cargo fmt --check`, clippy with warnings denied, tests, text dumps of the screen at several sizes, a run in a real pseudo-terminal, and a slop scan. +1. **Research.** Check the newest stable and minimum supported versions alongside versions resolved by the project. Preserve existing constraints; review release notes when changing versions or relying on recently changed APIs. Confirm widget crates match the resolved Ratatui version and compile uncertain APIs. +2. **Design.** For a non-trivial new interface, make the interaction model, layout, keyboard behavior, and relevant empty/error states explicit before implementation. Keep this lightweight for small tasks. +3. **Build** with the simplest architecture that fits. Use the dirview template as a reference when its structure is relevant; preserve existing project conventions. +4. **Verify.** Run relevant formatting, Clippy and test checks. Use TestBackend for rendering behavior and PTY or recording-based tests when real terminal interaction matters. Report anything not checked. 5. **Report honestly,** including anything it could not check.
@@ -88,10 +102,10 @@ Assistants that read `AGENTS.md` instead of loading skills can use the one at th The rules it enforces - Everything visible works. No fake data, decorative panels or dead keys. -- One key table drives input, footer hints and the `?` help, so a documented key always works. +- When input, footer hints, and help repeat the same bindings, keep them in sync through a shared source of truth. - Text is measured with `unicode-width`, untrusted text is sanitized, only visible rows are drawn. -- Colors by role in one file, 16 ANSI colors by default, `NO_COLOR` respected, no forced background, no emoji. -- No `.unwrap()` outside tests, no swallowed errors, no TODOs, comments say why. +- Choose colors and visual conventions for the product and terminal environment; support monochrome output when required. +- Handle errors deliberately and use compiler-visible Clippy lints where a project wants to prohibit specific patterns. - Destructive actions confirm. Slow work never blocks the draw loop. @@ -109,7 +123,7 @@ cd todo TODO_THEME=catppuccin cargo run --bin todo ``` -The default uses the 16 ANSI colors from your terminal palette. `NO_COLOR` renders monochrome. Source, keys and the file format are in [`todo/README.md`](todo/README.md). +The demo uses the terminal palette by default and supports `NO_COLOR` for monochrome output. Source, keys and the file format are in [`todo/README.md`](todo/README.md). ## What's inside @@ -117,7 +131,7 @@ The default uses the 16 ANSI colors from your terminal palette. `NO_COLOR` rende AGENTS.md the process in short form, for agents without skill support assets/ banner, demo, faq and sponsor images docs/ version-aware distribution proposal -evals/ 10 evaluation tasks, harness, scoring rubric, results +evals/ task suite, paired-run harness, scoring rubric, human-review records skills/ratatui/ SKILL.md the process references/ @@ -163,11 +177,12 @@ cargo run -- . Does it only work with Claude Code?
-**No. Any assistant that can run commands works.** +**No. The skill uses the open Agent Skills directory format.** -The skill format is read by assistants that support skills, and anything that -reads `AGENTS.md` can use the short version at the repo root. The scripts and -template are plain shell, Python and Rust. +Codex, Claude Code, Cursor, Antigravity, and OpenCode document compatible +skill discovery paths. Use the install location listed in +[`docs/agent-compatibility.md`](docs/agent-compatibility.md). The repository +has not yet been runtime-smoke-tested in every listed client. @@ -183,8 +198,8 @@ The versions in this repo are what the template was tested with, ratatui 0.30.2 on its minimum supported Rust version, 1.88. They are not a promise about what is newest when you read this. The skill tells the assistant to: -1. Run `crate-versions.sh` for each dependency. -2. Read the release notes for the version it returns. +1. Run `crate-versions.sh` for relevant dependencies. +2. Preserve project constraints and inspect release notes when changing versions or using recently changed APIs. 3. Compile any API it is unsure about before using it. @@ -195,11 +210,11 @@ tells the assistant to: Why a "slop scan"?
-**Generated UIs are recognizable, so the scanner fails CI on the mechanical tells.** +**The scanner is deliberately narrow. It is a guardrail, not an AI-slop detector.** -Emoji icons, neon gradients, placeholder rows and comments that narrate the code -are checked by [`lint-slop.sh`](skills/ratatui/scripts/lint-slop.sh). The rest are -judgment calls listed in +It checks a small set of mechanical source conventions. It cannot reliably +judge visual hierarchy, fake data, unnecessary abstractions, or whether a design +fits the product. Those require behavior tests and human review. See [`references/slop-tells.md`](skills/ratatui/references/slop-tells.md). diff --git a/docs/agent-compatibility.md b/docs/agent-compatibility.md new file mode 100644 index 0000000..59baf3a --- /dev/null +++ b/docs/agent-compatibility.md @@ -0,0 +1,92 @@ +# Agent compatibility + +`skills/ratatui/` is the canonical skill source in this repository. It follows the open Agent Skills directory format: one directory containing `SKILL.md` and optional `references/`, `scripts/`, and template assets. + +Do not maintain separate copies of the instructions for each agent. Install the same canonical directory at the discovery path for the client you use. + +## Project-level discovery paths + +| Agent | Project-level path | Notes | +|---|---|---| +| OpenAI Codex | `.agents/skills/ratatui/` | Codex also supports user-level `~/.agents/skills/ratatui/`. | +| Claude Code | `.claude/skills/ratatui/` | Claude Code also supports `~/.claude/skills/ratatui/`. | +| Cursor | `.agents/skills/ratatui/` or `.cursor/skills/ratatui/` | Cursor also recognizes Claude and Codex skill directories. | +| Google Antigravity | `.agents/skills/ratatui/` | Shared workspace path for Antigravity IDE and CLI. | +| OpenCode | `.opencode/skills/ratatui/` | OpenCode also discovers `.agents/skills/` and `.claude/skills/` as compatibility locations. | + +The shared `.agents/skills/ratatui/` path is the simplest project-level choice when using Codex, Cursor, Antigravity, and OpenCode together. Claude Code currently uses its own `.claude/skills/` project path, so install a copy there as well when Claude Code is part of the workflow. + +## Global discovery paths + +| Agent | User-level path | +|---|---| +| OpenAI Codex | `~/.agents/skills/ratatui/` | +| Claude Code | `~/.claude/skills/ratatui/` | +| Cursor | `~/.agents/skills/ratatui/` or `~/.cursor/skills/ratatui/` | +| Google Antigravity | `~/.gemini/config/skills/ratatui/` | +| OpenCode | `~/.config/opencode/skills/ratatui/` | + +OpenCode additionally accepts global compatibility directories `~/.agents/skills/` and `~/.claude/skills/`. + +## Install from this repository + +Run these commands from the root of the cloned `ratatui-skill` repository. Replace `/path/to/project` with the root of the project where you want the skill available. + +### Shared location + +For Codex, Cursor, Antigravity, and OpenCode: + +```bash +mkdir -p /path/to/project/.agents/skills +rm -rf /path/to/project/.agents/skills/ratatui +cp -a skills/ratatui /path/to/project/.agents/skills/ratatui +``` + +### Claude Code + +```bash +mkdir -p /path/to/project/.claude/skills +rm -rf /path/to/project/.claude/skills/ratatui +cp -a skills/ratatui /path/to/project/.claude/skills/ratatui +``` + +### OpenCode native location + +```bash +mkdir -p /path/to/project/.opencode/skills +rm -rf /path/to/project/.opencode/skills/ratatui +cp -a skills/ratatui /path/to/project/.opencode/skills/ratatui +``` + +### Global install + +For a user-level install, replace the project directory above with the global path from the tables. For example, Codex: + +```bash +mkdir -p ~/.agents/skills +rm -rf ~/.agents/skills/ratatui +cp -a skills/ratatui ~/.agents/skills/ratatui +``` + +Avoid maintaining multiple copies of the same skill in overlapping discovery directories for one agent unless you intentionally want to test precedence or overrides. Some clients load more than one source and resolve duplicate skill names using product-specific precedence rules. + +## What "compatible" means + +There are separate levels of compatibility: + +1. **Format-compatible:** the directory contains the standard `SKILL.md` frontmatter and supporting files. +2. **Discovery-documented:** the agent's official documentation lists the installation path. +3. **Runtime-tested:** the skill has been installed in that product and verified to appear, trigger, load references, and run its scripts. + +This repository uses the standard skill directory format and documents the official discovery paths linked below. The paths are not a claim that every listed client has been smoke-tested with this repository. Live discovery, trigger behavior, reference loading, and script execution still need product-by-product validation. + +The skill's portable content is shared. Product-specific features, invocation controls, and context-loading behavior may differ. + +## Official documentation + +- [OpenAI Codex skill locations and configuration](https://learn.chatgpt.com/docs/build-skills) and [OpenAI's skill-based OSS maintenance workflow](https://developers.openai.com/blog/skills-agents-sdk) +- [Claude Code skills](https://code.claude.com/docs/en/skills) +- [Cursor Agent Skills](https://cursor.com/docs/skills) +- [Google Antigravity agent skills](https://antigravity.google/docs/skills) +- [OpenCode skills](https://opencode.ai/docs/skills/) +- [Agent Skills specification](https://agentskills.io/specification) diff --git a/docs/ratatui-evidence.md b/docs/ratatui-evidence.md new file mode 100644 index 0000000..fde969f --- /dev/null +++ b/docs/ratatui-evidence.md @@ -0,0 +1,31 @@ +# Ratatui implementation evidence + +This catalogue links guidance in the skill to primary Ratatui project practice and maintainer discussions. A recommendation is scoped to the evidence shown; it is not a universal requirement for every TUI. + +Research checked: 27 November 2026. + +## Evidence map + +| Guidance | Primary evidence | What it supports | What it does not prove | +|---|---|---|---| +| Separate state/logic tests from rendered-buffer tests | [Ratatui discussion #1381](https://github.com/ratatui/ratatui/discussions/1381) and [discussion #1894](https://github.com/ratatui/ratatui/discussions/1894) | Test state transitions as ordinary logic where possible; use TestBackend when the rendered buffer is part of the behavior under test. | TestBackend does not test real input events, terminal restoration, or an actual terminal emulator. | +| Test interactive journeys with reproducible terminal sessions | [Ratatui Labs](https://github.com/ratatui/ratatui-labs), its [Betamax CI workflow](https://github.com/ratatui/ratatui-labs/blob/main/.github/workflows/ci.yml), and [command-palette tape](https://github.com/ratatui/ratatui-labs/blob/main/tapes/command-palette.tape) | A Ratatui-maintained project uses Betamax tapes to exercise and capture application interactions. | This is evidence that the approach is used, not that every application needs a tape. | +| Assert semantic terminal state, not screenshots alone | [Betamax terminal testing](https://www.joshka.net/betamax/testing/terminal-testing/) | Wait for expected visible content and inspect recorded terminal state; use image snapshots for supplementary review. | Pixel equality alone is not a reliable assertion of application behavior. | +| Keep terminal-session CI unprivileged | [Betamax GitHub Action](https://github.com/joshka/betamax-action) and [GitHub Actions guidance](https://www.joshka.net/betamax/testing/github-action/) | Tapes run shell commands. Use a fresh runner, read-only repository permission, no secrets, and checkout without persisted credentials. | A tape is not harmless arbitrary data; it executes commands with the permissions of the CI job. | +| Handle resize in the application event loop | [Ratatui application development guide](https://ratatui.rs/how-to/develop-apps/terminal-and-event-handler/) and [Terminal API](https://docs.rs/ratatui/latest/ratatui/struct.Terminal.html) | Redraw with the current terminal area after resize and test the application's own declared responsive policy. | Ratatui does not define universal breakpoints or guarantee a specific layout policy. | +| Check APIs against the resolved dependency version | [Ratatui releases](https://github.com/ratatui/ratatui/releases) and [versioned crate documentation](https://docs.rs/ratatui/) | Read the manifest and lockfile, then use API docs/source for the resolved version. | Latest-version docs do not prove an API exists in an older project. | + +## How this changes the skill + +- State transitions and domain logic can be unit-tested without a terminal. +- TestBackend is appropriate for layout, clipping, styles, and other visible-buffer behavior. +- PTY integration remains useful for actual key input, terminal lifecycle, restoration, and resize survival. +- Betamax is a useful additional tool for selected user journeys, especially when an interaction must be reproducible in CI. +- Resize policy is application-specific. Tests should match declared breakpoints and minimum dimensions. +- Dependency research starts with the project's resolved versions rather than an assumed latest release. + +## Evidence limitations + +This catalogue is a source map, not a systematic survey of Ratatui applications. It supports the scoped engineering guidance above; it does not prove that the ratatui-skill improves model-generated applications. + +This repository makes no measured effectiveness claim. Controlled paired trials are an optional research method for anyone who wants to investigate that question; they are not a prerequisite for using the skill or contributing code. \ No newline at end of file diff --git a/docs/skill-rule-audit.md b/docs/skill-rule-audit.md new file mode 100644 index 0000000..b38b6eb --- /dev/null +++ b/docs/skill-rule-audit.md @@ -0,0 +1,49 @@ +# Skill guidance classification + +Status: initial maintainer audit. This is a working decision record, not a claim that every recommendation has been empirically validated. + +The purpose is to prevent preferences from silently becoming universal requirements. Update this record when repository evidence, real usage, or evaluations change a decision. + +## Classification + +- **Required:** necessary for correctness, compatibility, an explicit user requirement, or a verified project constraint. +- **Recommended:** a useful default with known exceptions. +- **Optional:** a choice driven by product requirements or taste. +- **Experimental:** a hypothesis that needs additional evidence. + +## Initial rule inventory + +| Guidance | Classification | Reason and boundary | +|---|---|---| +| Inspect the manifest, lockfile, and existing code before changing an application | Required | Prevents incompatible APIs, accidental upgrades, and unnecessary rewrites. | +| Verify APIs against the version resolved by the project | Required | Ratatui and backend APIs vary by release. | +| Preserve existing dependencies unless there is a reason to change them | Recommended | Minimizes churn; a task may require a dependency change. | +| Keep the draw path free of avoidable blocking work | Required when work can block interaction | Responsiveness is a behavioral requirement; implementations may be synchronous, asynchronous, cached, bounded, or incremental. | +| Handle terminal restoration and errors correctly | Required | A TUI must not leave the user's terminal unusable after normal errors or exit. | +| Separate state from rendering | Recommended | Improves testability in many applications; very small applications may not need additional layers. | +| Centralize key bindings | Recommended when bindings are repeated across input and UI | A single source prevents drift; a small one-screen tool may not need a separate keymap module. | +| Use TestBackend | Recommended for rendering behavior | Useful for layout and visible-state tests, but not every behavior is a rendering concern. | +| Use PTY or recording-based integration tests | Required when terminal lifecycle or real input is in scope; otherwise optional | Unit tests cannot prove terminal interaction, but PTY tests are unnecessary for every local state change. | +| Use the dirview template | Optional | It is an example. Its architecture may not fit every product. | +| Write a design brief | Optional, scaled to complexity | A short plan helps complex interfaces; a tiny focused change does not need ceremony. | +| Use exactly one accent color or a fixed ANSI palette | Optional | Visual direction depends on the application, terminal support, and user requirements. | +| Keep all color constructors inside a theme module | Optional repository convention | Can help larger applications centralize semantic styles; should not be enforced as a universal Ratatui rule. | +| Require a fixed file/module layout | Optional | Modules should represent real boundaries, not satisfy a template. | +| Ban emoji or decorative styling universally | Optional style guidance | Taste is not correctness; apply only when it fits the product. | + +## Evidence policy + +For each substantial rule: + +1. Identify the concrete failure or user problem it addresses. +2. Find primary evidence: Ratatui documentation, source, examples, accepted changes, maintainer review, or a reproducible bug. +3. Record meaningful counterexamples and trade-offs. +4. Choose the narrowest classification justified by evidence. +5. Add a regression task when the rule addresses a repeatable failure. +6. Keep empirical claims separate from design rationale. + +Do not cite a project preference as a Ratatui requirement. An accepted implementation is not necessarily the only valid implementation. + +## Optional evaluation tooling + +The repository includes task specifications and a trial harness for maintainers who want to study skill effectiveness. These tools are optional and are not required for normal use, CI, or release readiness. The harness stages existing-project fixtures and distinguishes automated acceptance from ungraded trials. No measured effectiveness claim is made. diff --git a/evals/README.md b/evals/README.md index 39b2fa8..5918a43 100644 --- a/evals/README.md +++ b/evals/README.md @@ -1,33 +1,87 @@ -# Evaluation suite for ratatui-skill +# Evaluation suite -Measures whether the skill improves agent output. Each task is a self-contained -specification with acceptance criteria that can be checked by compilation, tests, -and PTY interaction. +This is an optional evaluation toolkit for maintainers who want to compare agent results. It is not part of normal skill installation, use, or CI, and running it is not required to use or merge routine skill improvements. The harness is a reproducible runner, not evidence of effectiveness by itself. -## Structure +## Current status -- `tasks/` - one Markdown file per evaluation task -- `harness/` - scripts to run trials and collect results +- Ten task specifications cover new projects, existing-project changes, compatibility, debugging, and a negative-trigger case. +- Existing-project tasks use explicit fixtures staged into isolated trial workspaces. +- Each trial records repository commit, task-spec SHA-256, skill content hash, condition, model/provider labels, timing, process exit status, tool-call telemetry, language checks, and acceptance status. +- Task-specific acceptance scripts provide objective checks where practical. Trials without one remain ungraded until human review. +- The committed report remains preliminary. It does not establish that the skill improves Rust task outcomes. + +See results/summary.md for the actual result state and limitations. + +## Optional: run a paired evaluation + +Only run this when you intentionally want a controlled model comparison. It requires OpenCode, a configured provider credential, and an explicit provider/model ID. EVAL_MODEL is passed to OpenCode as --model, not merely recorded as a label. + +~~~bash +EVAL_MODEL="provider/model-id" \ +EVAL_PROVIDER="provider-name" \ +EVAL_MODEL_SETTINGS="temperature=0;reasoning=high" \ +bash evals/harness/run-suite.sh 3 600 +~~~ + +Three repetitions across ten tasks create 60 model runs. This is an optional research exercise, not a release gate. A smaller smoke run checks mechanics only and cannot establish effectiveness. + +The optional third argument selects an output directory outside the repository: + +~~~bash +EVAL_MODEL="provider/model-id" bash evals/harness/run-suite.sh 3 600 /tmp/ratatui-skill-evals +~~~ + +EVAL_PROVIDER and EVAL_MODEL_SETTINGS are operator-supplied descriptive labels. They are not provider-side enforcement or automatic inspection. Keep the real settings identical between both conditions and document them. Never put credentials in task files, model labels, or result artifacts. + +The suite randomizes baseline/skill order within each task repetition. It writes schedule.tsv and suite.json with the seed, schedule hash, repository commit, model metadata, and task hashes. Set EVAL_ORDER_SEED to reproduce the schedule order. + +## Optional: one trial + +~~~bash +EVAL_MODEL="provider/model-id" bash evals/harness/run-trial.sh evals/tasks/02-add-widget.md 1 /tmp/widget-skill 600 +EVAL_MODEL="provider/model-id" bash evals/harness/run-trial.sh evals/tasks/02-add-widget.md 0 /tmp/widget-base 600 +~~~ + +Use identical model/provider/settings and environment values for both commands. Each trial directory contains the prompt, generated project, OpenCode event stream, text output, standard error, per-check logs, acceptance output, and result.json. + +## Isolation and telemetry + +Every trial gets a temporary HOME, XDG config/data/cache/state directories, OpenCode config directory, and OpenCode data store. The runner copies only the OpenCode authentication database or legacy auth file. It does not copy user skill directories or user OpenCode configuration, which could contaminate baseline runs. Provider API-key environment variables are inherited. + +The runner fails when it finds a machine-wide Ratatui skill in the known OpenCode system skill locations or a project-local skill in a baseline fixture. Trial directories and results directories must be new or empty. + +The agent's newline-delimited JSON events are retained. A direct root-session skill tool call naming ratatui is counted as activation. Baseline calls are counted as leakage. OpenCode does not expose all child-session tool events in its root event stream, so delegated activation is recorded as unverified, not guessed. If telemetry is unverified, the suite remains incomplete. + +## Optional human review + +Automated acceptance does not replace code and behavior review. Copy the template into each trial directory and complete it: + +~~~bash +cp evals/human-review-template.json /path/to/trial/human-review.json +python3 evals/harness/summarize-results.py /path/to/results +~~~ + +A review record requires a reviewer, ISO date, passed or failed status, all ten 0-2 rubric scores, critical failures, and explanatory notes. A passing status with critical failures is invalid. The rubric deliberately has no universal numeric pass threshold. + +The summarizer can be rerun after reviews are added. It exits 2 while acceptance or review is incomplete, and 1 when a trial fails. ## Method -1. For each task, run N trials with the skill enabled and N without. -2. Same task spec, same environment, same model. -3. Capture: generated code, compile result, test result, PTY output, token count. -4. Score each trial against the task's acceptance criteria. -5. Report: pass rate, failure modes, token overhead, workflow adherence. - -## Status - -All 10 tasks are **proposed**. Harness v2 is implemented with: -- Real skill injection (copy to isolated opencode config, verify presence) -- Honest exit status (no `|| true` suppression) -- Timeout classification (exit 124 = timeout) -- Separate stdout/stderr logs -- Skill content hash (not git HEAD) -- Language-aware (Rust vs Python) -- Configurable timeout - -Two partial trials have been run. Results in `evals/results/`. -Full trials require ~10 min each with a real model. Results will be -added to `evals/results/` once executed. +1. Keep model, model version, provider, actual settings, task text, permissions, environment, and fixture commit consistent across conditions. +2. Run baseline and skill conditions in separate workspaces. The baseline must not see the skill or project instructions. +3. Randomize execution order within each pair and retain the schedule. +4. Run multiple repetitions because model output is nondeterministic. Three paired trials per task is an initial floor, not proof of statistical power. +5. Use deterministic checks for objective behavior where practical. +6. Have a human review architecture, maintainability, usability, and visual quality using the rubric. +7. Inspect trajectories as well as final artifacts: repository inspection, API research, unnecessary edits, recovery, verification, and skill activation. +8. Report failed, timed-out, incomplete, ungraded, and telemetry-unknown trials. Explain any exclusions from denominators. + +## Metrics + +Report per task and condition: completion and timeout rate; format, build, Clippy, and test success; automated acceptance; human score distributions; API/version correctness; terminal interaction and resize behavior; unnecessary complexity; token usage, latency, and cost where provider measurements are reliable; and activation precision including negative cases. + +Keep objective checks and human judgments separate. Do not collapse every dimension into one unqualified score. + +## Limitations + +The optional harness currently supports OpenCode only. Other agent integrations require separate runners and runtime validation. A successful process exit is not proof of a successful task. Tasks without deterministic acceptance are ungraded until reviewed. Skill activation through child agents may remain unverified if the runtime does not expose those events. \ No newline at end of file diff --git a/evals/acceptance/10-no-trigger.sh b/evals/acceptance/10-no-trigger.sh index b98b8cc..5e8210e 100755 --- a/evals/acceptance/10-no-trigger.sh +++ b/evals/acceptance/10-no-trigger.sh @@ -1,16 +1,49 @@ #!/usr/bin/env bash -# Acceptance checks for Eval 10: Python task that should NOT trigger skill -set -uo pipefail +set -Eeuo pipefail PROJECT="${1:?project dir required}" -FAIL=0 -check() { - local label="$1" - shift - if "$@"; then echo "PASS: $label"; else echo "FAIL: $label"; FAIL=$((FAIL+1)); fi -} +TMP="$(mktemp -d)" +trap 'rm -rf "$TMP"' EXIT -if [[ ! -f "$PROJECT/Cargo.toml" ]] || ! grep -qi ratatui "$PROJECT/Cargo.toml"; then echo "PASS: no ratatui dependency"; else echo "FAIL: no ratatui dependency"; FAIL=$((FAIL+1)); fi -if ! grep -rl ratatui "$PROJECT" --include='*.rs' 2>/dev/null | grep -q .; then echo "PASS: no rust files with ratatui"; else echo "FAIL: no rust files with ratatui"; FAIL=$((FAIL+1)); fi -check "python files exist" find "$PROJECT" -name '*.py' -print -quit | grep -q . +test -f "$PROJECT/solution.py" +python3 -m py_compile "$PROJECT/solution.py" -exit "$FAIL" +cat > "$TMP/input.csv" <<'CSV' +A,B,C,Name,Empty +1,2,,alpha, +3,4,5,beta, +,6,7,gamma, +CSV + +python3 "$PROJECT/solution.py" "$TMP/input.csv" > "$TMP/output.json" +python3 - "$TMP/output.json" <<'PY' +import json +import math +import pathlib +import sys + +data = json.loads(pathlib.Path(sys.argv[1]).read_text(encoding="utf-8")) +assert set(data) == {"A", "B", "C"} +assert data["A"]["count"] == 2 +assert data["A"]["mean"] == 2 +assert data["A"]["median"] == 2 +assert math.isclose(data["A"]["std"], 1) +assert data["B"]["count"] == 3 +assert data["B"]["mean"] == 4 +assert data["B"]["median"] == 4 +assert math.isclose(data["B"]["std"], math.sqrt(8 / 3)) +assert data["C"]["count"] == 2 +assert data["C"]["mean"] == 6 +assert data["C"]["median"] == 6 +assert math.isclose(data["C"]["std"], 1) +PY + +if python3 "$PROJECT/solution.py" "$TMP/missing.csv" > "$TMP/missing.out" 2> "$TMP/missing.err"; then + echo "missing input unexpectedly succeeded" >&2 + exit 1 +fi +test -s "$TMP/missing.err" +if find "$PROJECT" -type f \( -name Cargo.toml -o -name '*.rs' \) -print -quit | grep -q .; then + echo "non-TUI Python task created a Rust project" >&2 + exit 1 +fi +echo "Python CSV acceptance passed." diff --git a/evals/fixtures/ratatui-028/Cargo.toml b/evals/fixtures/ratatui-028/Cargo.toml new file mode 100644 index 0000000..56e9b60 --- /dev/null +++ b/evals/fixtures/ratatui-028/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "ratatui-028-fixture" +version = "0.1.0" +edition = "2021" +rust-version = "1.75" +publish = false + +[dependencies] +ratatui = "=0.28.0" diff --git a/evals/fixtures/ratatui-028/src/main.rs b/evals/fixtures/ratatui-028/src/main.rs new file mode 100644 index 0000000..3d7987d --- /dev/null +++ b/evals/fixtures/ratatui-028/src/main.rs @@ -0,0 +1,16 @@ +use ratatui::backend::TestBackend; +use ratatui::layout::Rect; +use ratatui::widgets::{Block, Borders, Paragraph}; +use ratatui::Terminal; + +fn main() -> Result<(), Box> { + let backend = TestBackend::new(40, 8); + let mut terminal = Terminal::new(backend)?; + terminal.draw(|frame| { + let area: Rect = frame.area(); + let widget = Paragraph::new("Ratatui 0.28 fixture") + .block(Block::default().borders(Borders::ALL).title("Fixture")); + frame.render_widget(widget, area); + })?; + Ok(()) +} diff --git a/evals/harness/mock/mock-agent.sh b/evals/harness/mock/mock-agent.sh index f841539..39e3ab2 100755 --- a/evals/harness/mock/mock-agent.sh +++ b/evals/harness/mock/mock-agent.sh @@ -37,11 +37,41 @@ RS sleep 300 ;; python) - cat > main.py <<'PY' -import csv, statistics -print("done") + cat > solution.py <<'PY' +import csv +import json +import math +import statistics +import sys + +with open(sys.argv[1], newline="", encoding="utf-8") as stream: + rows = list(csv.DictReader(stream)) +result = {} +for key in rows[0] if rows else []: + values = [] + valid = True + for row in rows: + value = row[key].strip() + if not value: + continue + try: + number = float(value) + except ValueError: + valid = False + break + if not math.isfinite(number): + valid = False + break + values.append(number) + if valid and values: + result[key] = { + "count": len(values), + "mean": statistics.mean(values), + "median": statistics.median(values), + "std": statistics.pstdev(values), + } +print(json.dumps(result)) PY - echo "Generated Python script" ;; no-ratatui) mkdir -p src @@ -59,3 +89,12 @@ RS echo "Generated without ratatui" ;; esac + + +if [[ "${MOCK_SKILL_CALL:-0}" == 1 ]]; then + printf '%s\n' '{"type":"tool_use","part":{"tool":"skill","state":{"status":"completed","input":{"name":"ratatui"}}}}' +fi +if [[ "${MOCK_SUBAGENT_CALL:-0}" == 1 ]]; then + printf '%s\n' '{"type":"tool_use","part":{"tool":"task","state":{"status":"completed","input":{"description":"delegate implementation"}}}}' +fi +printf '%s\n' '{"type":"text","part":{"type":"text","text":"Mock agent completed"}}' diff --git a/evals/harness/run-suite.sh b/evals/harness/run-suite.sh index 64bab2b..343a41d 100755 --- a/evals/harness/run-suite.sh +++ b/evals/harness/run-suite.sh @@ -1,51 +1,80 @@ #!/usr/bin/env bash -# Run the full evaluation suite: N trials per task per condition. -# -# usage: run-suite.sh [TRIALS_PER_CONDITION] [TIMEOUT] -# -# Exit status: 0 if all required checks pass, 1 otherwise. set -Eeuo pipefail TRIALS="${1:-1}" -TIMEOUT="${2:-300}" +TIMEOUT="${2:-600}" REPO_ROOT="$(cd "$(dirname "$0")/../.." && pwd -P)" RESULTS="${3:-${TMPDIR:-/tmp}/ratatui-skill-evals-$(date +%Y%m%d-%H%M%S)}" [[ "$TRIALS" =~ ^[1-9][0-9]*$ ]] || { echo "TRIALS must be a positive integer" >&2; exit 2; } [[ "$TIMEOUT" =~ ^[1-9][0-9]*$ ]] || { echo "TIMEOUT must be a positive integer" >&2; exit 2; } +[[ -n "${EVAL_MODEL:-}" ]] || { echo "Set EVAL_MODEL to an explicit provider/model ID." >&2; exit 2; } mkdir -p "$RESULTS" RESULTS="$(cd "$RESULTS" && pwd -P)" case "$RESULTS/" in "$REPO_ROOT/"*) echo "results must be outside the repository" >&2; exit 2 ;; esac +if [[ -n "$(find "$RESULTS" -mindepth 1 -maxdepth 1 -print -quit)" ]]; then + printf 'results directory must be empty: %s\n' "$RESULTS" >&2 + exit 2 +fi + +ORDER_SEED="${EVAL_ORDER_SEED:-$(date +%s)}" +SCHEDULE="$RESULTS/schedule.tsv" +python3 - "$REPO_ROOT/evals/tasks" "$SCHEDULE" "$TRIALS" "$ORDER_SEED" <<'PYSCHEDULE' +import pathlib +import random +import sys + +task_root = pathlib.Path(sys.argv[1]) +schedule = pathlib.Path(sys.argv[2]) +rng = random.Random(int(sys.argv[4])) +rows = [] +for task in sorted(task_root.glob("*.md")): + for trial in range(1, int(sys.argv[3]) + 1): + conditions = [0, 1] + rng.shuffle(conditions) + for condition in conditions: + rows.append(f"{task.stem}\t{condition}\t{trial}") +schedule.write_text("\n".join(rows) + "\n", encoding="utf-8") +PYSCHEDULE -echo "Running $TRIALS trial(s) per task per condition, timeout=${TIMEOUT}s" +EXPECTED_TRIALS="$(wc -l < "$SCHEDULE" | tr -d ' ')" +python3 - "$REPO_ROOT" "$RESULTS" "$SCHEDULE" "$ORDER_SEED" "$EXPECTED_TRIALS" <<'PYSUITE' +import hashlib +import json +import os +import pathlib +import subprocess +import sys -SUITE_FAILED=0 -TRIAL_COUNT=0 -PASS_COUNT=0 -FAIL_COUNT=0 +repo, results, schedule = map(pathlib.Path, sys.argv[1:4]) +metadata = { + "repository_commit": subprocess.check_output(["git", "-C", str(repo), "rev-parse", "HEAD"], text=True).strip(), + "model": os.environ.get("EVAL_MODEL", "not recorded"), + "provider": os.environ.get("EVAL_PROVIDER", "not recorded"), + "model_settings": os.environ.get("EVAL_MODEL_SETTINGS", "not recorded"), + "order_seed": sys.argv[4], + "schedule_sha256": hashlib.sha256(schedule.read_bytes()).hexdigest(), + "expected_trials": int(sys.argv[5]), + "task_hashes": {p.name: hashlib.sha256(p.read_bytes()).hexdigest() for p in sorted((repo / "evals/tasks").glob("*.md"))}, +} +(results / "suite.json").write_text(json.dumps(metadata, indent=2) + "\n", encoding="utf-8") +PYSUITE -for task in "$REPO_ROOT"/evals/tasks/*.md; do - name=$(basename "$task" .md) - for skill in 0 1; do - for trial in $(seq 1 "$TRIALS"); do - dir="$RESULTS/$name-skill$skill-trial$trial" - echo "=== $name skill=$skill trial=$trial ===" - TRIAL_COUNT=$((TRIAL_COUNT + 1)) - if bash "$REPO_ROOT/evals/harness/run-trial.sh" "$task" "$skill" "$dir" "$TIMEOUT"; then - PASS_COUNT=$((PASS_COUNT + 1)) - else - FAIL_COUNT=$((FAIL_COUNT + 1)) - SUITE_FAILED=1 - fi - done - done -done +echo "Running $EXPECTED_TRIALS trials, $TRIALS repetitions per condition, timeout=${TIMEOUT}s, order_seed=$ORDER_SEED" +RUNNER_FAILURES=0 +while IFS=$'\t' read -r name skill trial; do + dir="$RESULTS/$name-skill$skill-trial$trial" + echo "=== $name skill=$skill trial=$trial ===" + mkdir "$dir" + if ! bash "$REPO_ROOT/evals/harness/run-trial.sh" "$REPO_ROOT/evals/tasks/$name.md" "$skill" "$dir" "$TIMEOUT"; then + RUNNER_FAILURES=$((RUNNER_FAILURES + 1)) + echo "Trial did not pass automated execution checks: $dir" >&2 + fi +done < "$SCHEDULE" -echo "" -echo "=== Suite summary ===" -echo "Trials: $TRIAL_COUNT Passed: $PASS_COUNT Failed: $FAIL_COUNT" -if [ "$SUITE_FAILED" -ne 0 ]; then - echo "SUITE FAILED: $FAIL_COUNT trial(s) did not pass" +SUMMARY_STATUS=0 +python3 "$REPO_ROOT/evals/harness/summarize-results.py" "$RESULTS" "$EXPECTED_TRIALS" || SUMMARY_STATUS=$? +if [[ "$RUNNER_FAILURES" -gt 0 ]]; then + printf 'SUITE FAILED: %s trial runner invocation(s) failed\n' "$RUNNER_FAILURES" >&2 exit 1 fi -echo "SUITE PASSED" -exit 0 +exit "$SUMMARY_STATUS" \ No newline at end of file diff --git a/evals/harness/run-trial.sh b/evals/harness/run-trial.sh old mode 100755 new mode 100644 index 0613779..dca204a --- a/evals/harness/run-trial.sh +++ b/evals/harness/run-trial.sh @@ -11,35 +11,83 @@ umask 077 TASK_FILE="${1:?task file required}" WITH_SKILL="${2:?0 or 1}" TRIAL_DIR="${3:?trial dir required}" -TIMEOUT="${4:-300}" +TIMEOUT="${4:-600}" +CHECK_TIMEOUT="${EVAL_CHECK_TIMEOUT:-300}" +EVAL_MODEL="${EVAL_MODEL:-}" REPO_ROOT="$(cd "$(dirname "$0")/../.." && pwd -P)" [[ "$WITH_SKILL" == 0 || "$WITH_SKILL" == 1 ]] || { echo "WITH_SKILL must be 0 or 1" >&2; exit 2; } [[ "$TIMEOUT" =~ ^[1-9][0-9]*$ ]] || { echo "TIMEOUT must be a positive integer" >&2; exit 2; } +[[ "$CHECK_TIMEOUT" =~ ^[1-9][0-9]*$ ]] || { echo "EVAL_CHECK_TIMEOUT must be a positive integer" >&2; exit 2; } +[[ -n "$EVAL_MODEL" ]] || { echo "Set EVAL_MODEL to an explicit provider/model ID." >&2; exit 2; } TASK_FILE="$(cd "$(dirname "$TASK_FILE")" && pwd -P)/$(basename "$TASK_FILE")" [[ -f "$TASK_FILE" ]] || { echo "task file not found" >&2; exit 2; } mkdir -p "$TRIAL_DIR" TRIAL_DIR="$(cd "$TRIAL_DIR" && pwd -P)" case "$TRIAL_DIR/" in "$REPO_ROOT/"*) echo "TRIAL_DIR must be outside the repository to prevent AGENTS.md leakage" >&2; exit 2 ;; esac +if [[ -n "$(find "$TRIAL_DIR" -mindepth 1 -maxdepth 1 -print -quit)" ]]; then + printf 'trial directory is not empty: %s\n' "$TRIAL_DIR" >&2 + exit 2 +fi TASK=$(cat "$TASK_FILE") PROJECT="$TRIAL_DIR/project" mkdir -p "$PROJECT" -# Isolated opencode config per trial (never touch user's real config). +ORIGINAL_HOME="$HOME" +ORIGINAL_XDG_CONFIG_HOME="${XDG_CONFIG_HOME:-$ORIGINAL_HOME/.config}" +ORIGINAL_XDG_DATA_HOME="${XDG_DATA_HOME:-$ORIGINAL_HOME/.local/share}" +ORIGINAL_DB="${OPENCODE_DB:-$ORIGINAL_XDG_DATA_HOME/opencode/opencode.db}" SCRATCH="$(mktemp -d "${TMPDIR:-/tmp}/ratatui-skill-trial.XXXXXX")" CONFIG_DIR="$SCRATCH/opencode-config" -mkdir -p "$CONFIG_DIR" -chmod 700 "$SCRATCH" "$CONFIG_DIR" +ISOLATED_HOME="$SCRATCH/home" +ISOLATED_XDG_CONFIG="$SCRATCH/xdg-config" +ISOLATED_XDG_DATA="$SCRATCH/xdg-data" +ISOLATED_XDG_CACHE="$SCRATCH/xdg-cache" +ISOLATED_XDG_STATE="$SCRATCH/xdg-state" +mkdir -p "$CONFIG_DIR" "$ISOLATED_HOME" "$ISOLATED_XDG_CONFIG" "$ISOLATED_XDG_DATA/opencode" "$ISOLATED_XDG_CACHE" "$ISOLATED_XDG_STATE" +chmod 700 "$SCRATCH" "$CONFIG_DIR" "$ISOLATED_HOME" cleanup() { rm -rf "$SCRATCH"; } trap cleanup EXIT INT TERM -if [ -f "$HOME/.config/opencode/auth.json" ]; then - install -m 600 "$HOME/.config/opencode/auth.json" "$CONFIG_DIR/auth.json" -fi -if [ -f "$HOME/.config/opencode/opencode.json" ]; then - install -m 600 "$HOME/.config/opencode/opencode.json" "$CONFIG_DIR/opencode.json" + +for system_skill in "/etc/opencode/skills/ratatui/SKILL.md" "/Library/Application Support/opencode/skills/ratatui/SKILL.md"; do + if [ -f "$system_skill" ]; then + echo "Machine-wide Ratatui skill found at $system_skill; trial isolation is not guaranteed." >&2 + exit 2 + fi +done + +for auth_file in "$ORIGINAL_XDG_DATA_HOME/opencode/auth.json" "$ORIGINAL_XDG_CONFIG_HOME/opencode/auth.json"; do + if [ -f "$auth_file" ]; then + install -m 600 "$auth_file" "$ISOLATED_XDG_DATA/opencode/auth.json" + fi +done +if [ -f "$ORIGINAL_DB" ]; then + python3 - "$ORIGINAL_DB" "$ISOLATED_XDG_DATA/opencode/opencode.db" <<'PYDB' +import pathlib +import sqlite3 +import sys + +source = sqlite3.connect(pathlib.Path(sys.argv[1]).resolve().as_uri() + "?mode=ro", uri=True) +target = sqlite3.connect(sys.argv[2]) +try: + source.backup(target) +finally: + target.close() + source.close() +PYDB fi +export RUSTUP_HOME="${RUSTUP_HOME:-$ORIGINAL_HOME/.rustup}" +export HOME="$ISOLATED_HOME" +export XDG_CONFIG_HOME="$ISOLATED_XDG_CONFIG" +export XDG_DATA_HOME="$ISOLATED_XDG_DATA" +export XDG_CACHE_HOME="$ISOLATED_XDG_CACHE" +export XDG_STATE_HOME="$ISOLATED_XDG_STATE" +export OPENCODE_CONFIG_DIR="$CONFIG_DIR" +export OPENCODE_DB="$ISOLATED_XDG_DATA/opencode/opencode.db" +unset OPENCODE_CONFIG OPENCODE_CONFIG_CONTENT + # Skill injection: copy skill only for skill-enabled trials. SKILL_HASH="none" SKILL_INJECTED=false @@ -53,13 +101,29 @@ if [ "$WITH_SKILL" = "1" ]; then rm -rf "$SKILL_DST" cp -r "$SKILL_SRC" "$SKILL_DST" # Hash actual skill contents (not git HEAD). - SKILL_HASH=$(python3 -c "import hashlib, pathlib, sys; h=hashlib.sha256(); [h.update(p.read_bytes()) for p in sorted(pathlib.Path(sys.argv[1]).rglob('*')) if p.is_file()]; print(h.hexdigest())" "$SKILL_SRC") + SKILL_HASH=$(python3 - "$SKILL_SRC" <<'PYHASH' +import hashlib +import pathlib +import sys + +root = pathlib.Path(sys.argv[1]) +digest = hashlib.sha256() +for path in sorted(item for item in root.rglob("*") if item.is_file()): + relative = path.relative_to(root).as_posix().encode("utf-8") + content = path.read_bytes() + digest.update(len(relative).to_bytes(8, "big")) + digest.update(relative) + digest.update(len(content).to_bytes(8, "big")) + digest.update(content) +print(digest.hexdigest()) +PYHASH +) SKILL_INJECTED=true if [ ! -f "$SKILL_DST/SKILL.md" ]; then echo "skill injection failed: SKILL.md not found" >&2 exit 2 fi - PROMPT="Use the ratatui skill. $TASK" + PROMPT="$TASK" else # Ensure no skill leaks into baseline. rm -rf "$CONFIG_DIR/skills" @@ -72,9 +136,13 @@ printf '%s\n' "$PROMPT" > "$TRIAL_DIR/prompt.txt" TASK_LANG=$(grep -m1 '^language:' "$TASK_FILE" 2>/dev/null | sed 's/^language: *//' | tr -d ' ' || true) [ -n "$TASK_LANG" ] || TASK_LANG="rust" -# Set up project based on language. -if [ "$TASK_LANG" = "rust" ]; then - cat > "$PROJECT/Cargo.toml" <<'TOML' +TASK_TRIGGER=$(sed -nE 's/^[#[:space:]]*Should trigger skill:[[:space:]]*(yes|no).*$/\1/ip' "$TASK_FILE" | head -1 | tr '[:upper:]' '[:lower:]') +TASK_FIXTURE=$(grep -m1 '^fixture:' "$TASK_FILE" 2>/dev/null | sed 's/^fixture: *//' | tr -d ' ' || true) + +case "$TASK_FIXTURE" in + "") + if [ "$TASK_LANG" = "rust" ]; then + cat > "$PROJECT/Cargo.toml" <<'TOML' [package] name = "eval-app" version = "0.1.0" @@ -82,57 +150,170 @@ edition = "2024" [dependencies] TOML -else - # Python task: no Cargo project. - : -fi + fi + ;; + dirview) + cp -a "$REPO_ROOT/skills/ratatui/templates/dirview/." "$PROJECT/" + ;; + dirview-filter-reset) + cp -a "$REPO_ROOT/skills/ratatui/templates/dirview/." "$PROJECT/" + python3 - "$PROJECT/src/state.rs" <<'PYFIXTURE' +import pathlib +import sys + +path = pathlib.Path(sys.argv[1]) +source = path.read_text(encoding="utf-8") +old = """ Action::FilterInput(c) => { + self.filter.push(c); + self.rebuild(self.selected_name()); + }""" +new = """ Action::FilterInput(c) => { + self.filter.push(c); + self.selected = 0; + self.rebuild(None); + }""" +if old not in source: + raise SystemExit("could not seed the task-specific filter-selection regression") +path.write_text(source.replace(old, new, 1), encoding="utf-8") +PYFIXTURE + ;; + todo) + cp -a "$REPO_ROOT/todo/." "$PROJECT/" + ;; + ratatui-028) + cp -a "$REPO_ROOT/evals/fixtures/ratatui-028/." "$PROJECT/" + ;; + *) + printf 'unknown fixture: %s\n' "$TASK_FIXTURE" >&2 + exit 2 + ;; +esac # Run opencode FROM the project directory (critical fix). START_TIME=$(date +%s) set +e ( cd "$PROJECT" - OPENCODE_CONFIG_DIR="$CONFIG_DIR" timeout "$TIMEOUT" "${OPENCODE_BIN:-opencode}" run "$(cat "$TRIAL_DIR/prompt.txt")" \ - > "$TRIAL_DIR/stdout.txt" 2> "$TRIAL_DIR/stderr.txt" + timeout "$TIMEOUT" "${OPENCODE_BIN:-opencode}" run --standalone --format json --model "$EVAL_MODEL" "$(cat "$TRIAL_DIR/prompt.txt")" \ + > "$TRIAL_DIR/events.ndjson" 2> "$TRIAL_DIR/stderr.txt" ) EXIT_STATUS=$? set -e END_TIME=$(date +%s) ELAPSED=$((END_TIME - START_TIME)) +TELEMETRY="$(python3 - "$TRIAL_DIR/events.ndjson" "$TRIAL_DIR/stdout.txt" "$WITH_SKILL" <<'PYEVENTS' +import json +import pathlib +import sys + +event_path = pathlib.Path(sys.argv[1]) +text_path = pathlib.Path(sys.argv[2]) +with_skill = sys.argv[3] == "1" +valid_events = 0 +skill_calls = 0 +subagent_calls = 0 +tool_names = set() +text_parts = [] + +for line in event_path.read_text(encoding="utf-8", errors="replace").splitlines(): + try: + event = json.loads(line) + except json.JSONDecodeError: + if line.strip(): + text_parts.append(line) + continue + if not isinstance(event, dict): + continue + valid_events += 1 + part = event.get("part") + if not isinstance(part, dict): + part = {} + if event.get("type") == "text" and isinstance(part.get("text"), str): + text_parts.append(part["text"]) + if event.get("type") != "tool_use": + continue + tool = part.get("tool") + if not isinstance(tool, str): + continue + tool_names.add(tool) + state = part.get("state") + if not isinstance(state, dict): + state = {} + inputs = state.get("input") + if not isinstance(inputs, dict): + inputs = {} + name = inputs.get("name", inputs.get("skill", inputs.get("skill_name"))) + if tool == "skill" and name == "ratatui": + skill_calls += 1 + if tool in {"task", "subagent"}: + subagent_calls += 1 + +text_path.write_text("\n".join(text_parts) + ("\n" if text_parts else ""), encoding="utf-8") +if skill_calls: + activated = "true" +elif subagent_calls or valid_events == 0: + activated = "unverified" +else: + activated = "false" +if with_skill: + leaked = "not_applicable" +elif skill_calls: + leaked = "true" +elif subagent_calls or valid_events == 0: + leaked = "unverified" +else: + leaked = "false" +print(json.dumps({ + "skill_activated": activated, + "skill_leaked": leaked, + "skill_tool_calls": skill_calls, + "subagent_tool_calls": subagent_calls, + "tool_names": sorted(tool_names), + "json_event_count": valid_events +}, separators=(",", ":"))) +PYEVENTS +)" +SKILL_ACTIVATED="$(python3 -c 'import json,sys; print(json.loads(sys.argv[1])["skill_activated"])' "$TELEMETRY")" +SKILL_LEAKED="$(python3 -c 'import json,sys; print(json.loads(sys.argv[1])["skill_leaked"])' "$TELEMETRY")" + TIMED_OUT=false if [ "$EXIT_STATUS" = "124" ]; then TIMED_OUT=true fi -# Skill activation cannot be verified from output text alone. -# Report as unverified; a future harness version can check agent tool calls. -SKILL_ACTIVATED="unverified" -# Skill leakage cannot be verified from output text alone. -SKILL_LEAKED="unverified" # Collect results based on language. COMPILE_OK=false +FMT_OK=false CLIPPY_OK=false TEST_OK=false HAS_RATATUI=false FILES_GENERATED=0 +mkdir -p "$TRIAL_DIR/checks" -if [ "$TASK_LANG" = "rust" ]; then - if cargo build --manifest-path "$PROJECT/Cargo.toml" >/dev/null 2>&1; then - COMPILE_OK=true - fi - if cargo clippy --manifest-path "$PROJECT/Cargo.toml" -- -D warnings >/dev/null 2>&1; then - CLIPPY_OK=true - fi - if cargo test --manifest-path "$PROJECT/Cargo.toml" >/dev/null 2>&1; then - TEST_OK=true +run_check() { + local name="$1" + shift + if timeout "$CHECK_TIMEOUT" "$@" > "$TRIAL_DIR/checks/$name.log" 2>&1; then + printf 'true' + else + printf 'false' fi +} + +if [ "$TASK_LANG" = "rust" ]; then + FMT_OK="$(run_check fmt cargo fmt --manifest-path "$PROJECT/Cargo.toml" --check)" + COMPILE_OK="$(run_check build cargo build --manifest-path "$PROJECT/Cargo.toml")" + CLIPPY_OK="$(run_check clippy cargo clippy --manifest-path "$PROJECT/Cargo.toml" --all-targets -- -D warnings)" + TEST_OK="$(run_check test cargo test --manifest-path "$PROJECT/Cargo.toml")" if grep -q ratatui "$PROJECT/Cargo.toml" 2>/dev/null; then HAS_RATATUI=true fi fi FILES_GENERATED=$(find "$PROJECT" -type f \( -name '*.rs' -o -name '*.py' \) ! -path '*/target/*' | wc -l | tr -d ' ') +REPO_COMMIT=$(git -C "$REPO_ROOT" rev-parse HEAD) +TASK_HASH=$(python3 -c "import hashlib, pathlib, sys; print(hashlib.sha256(pathlib.Path(sys.argv[1]).read_bytes()).hexdigest())" "$TASK_FILE") # Run task-specific acceptance checks if available. ACCEPTANCE_SCRIPT="$REPO_ROOT/evals/acceptance/$(basename "$TASK_FILE" .md).sh" @@ -140,7 +321,7 @@ ACCEPTANCE_PASS="unverified" ACCEPTANCE_DETAILS="" if [ -x "$ACCEPTANCE_SCRIPT" ]; then set +e - ACCEPTANCE_OUTPUT=$("$ACCEPTANCE_SCRIPT" "$PROJECT" 2>&1) + ACCEPTANCE_OUTPUT=$(timeout "$CHECK_TIMEOUT" "$ACCEPTANCE_SCRIPT" "$PROJECT" 2>&1) ACCEPTANCE_STATUS=$? set -e if [ "$ACCEPTANCE_STATUS" -eq 0 ]; then ACCEPTANCE_PASS="true"; else ACCEPTANCE_PASS="false"; fi @@ -148,12 +329,15 @@ if [ -x "$ACCEPTANCE_SCRIPT" ]; then fi # Write result using Python for valid JSON. -python3 - "$TRIAL_DIR" "$TASK_FILE" "$WITH_SKILL" "$EXIT_STATUS" "$TIMED_OUT" "$ELAPSED" "$SKILL_HASH" "$SKILL_INJECTED" "$SKILL_ACTIVATED" "$SKILL_LEAKED" "$COMPILE_OK" "$CLIPPY_OK" "$TEST_OK" "$HAS_RATATUI" "$FILES_GENERATED" "$TASK_LANG" "$ACCEPTANCE_PASS" "$ACCEPTANCE_DETAILS" <<'PY' +python3 - "$TRIAL_DIR" "$TASK_FILE" "$WITH_SKILL" "$REPO_COMMIT" "$TASK_HASH" "$EXIT_STATUS" "$TIMED_OUT" "$ELAPSED" "$SKILL_HASH" "$SKILL_INJECTED" "$SKILL_ACTIVATED" "$SKILL_LEAKED" "$FMT_OK" "$COMPILE_OK" "$CLIPPY_OK" "$TEST_OK" "$HAS_RATATUI" "$FILES_GENERATED" "$TASK_LANG" "$TASK_FIXTURE" "$TASK_TRIGGER" "$ACCEPTANCE_PASS" "$ACCEPTANCE_DETAILS" "$TELEMETRY" <<'PY' import json, sys, os -(trial_dir, task, with_skill, exit_status, timed_out, elapsed, skill_hash, injected, - activated, leaked, compile_ok, clippy_ok, test_ok, has_ratatui, files, lang, acceptance, details) = sys.argv[1:] +(trial_dir, task, with_skill, repository_commit, task_hash, exit_status, timed_out, elapsed, skill_hash, injected, + activated, leaked, fmt_ok, compile_ok, clippy_ok, test_ok, has_ratatui, files, lang, fixture, expected_trigger, acceptance, details, telemetry_json) = sys.argv[1:] +telemetry = json.loads(telemetry_json) result = { "task": os.path.basename(task), + "repository_commit": repository_commit, + "task_spec_sha256": task_hash, "with_skill": with_skill == "1", "exit_status": int(exit_status), "timed_out": timed_out == "true", @@ -162,21 +346,32 @@ result = { "skill_injected": injected == "true", "skill_activated": activated, "skill_leaked": leaked, + "skill_tool_calls": telemetry["skill_tool_calls"], + "subagent_tool_calls": telemetry["subagent_tool_calls"], + "tool_names": telemetry["tool_names"], + "agent_json_event_count": telemetry["json_event_count"], "task_language": lang, + "model": os.environ.get("EVAL_MODEL", "not recorded"), + "provider": os.environ.get("EVAL_PROVIDER", "not recorded"), + "model_settings": os.environ.get("EVAL_MODEL_SETTINGS", "not recorded"), + "task_fixture": fixture or None, + "expected_skill_trigger": expected_trigger or None, + "fmt_ok": fmt_ok == "true", "compile_ok": compile_ok == "true", "clippy_ok": clippy_ok == "true", "test_ok": test_ok == "true", "has_ratatui": has_ratatui == "true", - "files_generated": int(files), + "source_files_after_run": int(files), "acceptance_pass": acceptance, "acceptance_details": details, + "human_review": "required", } with open(os.path.join(trial_dir, "result.json"), "w") as f: json.dump(result, f, indent=2) print(json.dumps(result, indent=2)) # A trial is successful only when the agent, required language checks, and acceptance checks pass. failed = int(exit_status) != 0 or timed_out == "true" or acceptance == "false" -if lang == "rust" and (compile_ok != "true" or clippy_ok != "true" or test_ok != "true"): +if lang == "rust" and (fmt_ok != "true" or compile_ok != "true" or clippy_ok != "true" or test_ok != "true"): failed = True sys.exit(1 if failed else 0) PY diff --git a/evals/harness/summarize-results.py b/evals/harness/summarize-results.py new file mode 100644 index 0000000..5d61775 --- /dev/null +++ b/evals/harness/summarize-results.py @@ -0,0 +1,220 @@ +#!/usr/bin/env python3 +import datetime +import json +import pathlib +import sys + +SCORE_KEYS = { + "functional_acceptance", + "api_version_correctness", + "terminal_lifecycle", + "keyboard_interaction", + "resize_layout", + "state_error_handling", + "architecture", + "tests", + "scope_discipline", + "verification_quality", +} + + +def read_json(path): + try: + return json.loads(path.read_text(encoding="utf-8")) + except (OSError, UnicodeDecodeError, json.JSONDecodeError): + return None + + +def review_status(trial_dir): + review_path = trial_dir / "human-review.json" + if not review_path.exists(): + return "pending" + review = read_json(review_path) + if not isinstance(review, dict): + return "invalid" + + if not isinstance(review.get("reviewer"), str) or not review["reviewer"].strip(): + return "invalid" + try: + datetime.date.fromisoformat(review.get("reviewed_at", "")) + except (TypeError, ValueError): + return "invalid" + if not isinstance(review.get("status"), str) or review["status"] not in {"passed", "failed"}: + return "invalid" + if not isinstance(review.get("notes"), str) or not review["notes"].strip(): + return "invalid" + scores = review.get("scores") + if not isinstance(scores, dict) or set(scores) != SCORE_KEYS: + return "invalid" + if any( + type(score) is not int or score not in {0, 1, 2} + for score in scores.values() + ): + return "invalid" + failures = review.get("critical_failures") + if not isinstance(failures, list) or any(not isinstance(item, str) for item in failures): + return "invalid" + if review["status"] == "passed" and failures: + return "invalid" + return review["status"] + + +def main(): + if len(sys.argv) not in {2, 3}: + print("usage: summarize-results.py RESULTS_DIR [EXPECTED_TRIALS]", file=sys.stderr) + return 2 + + expected_trials = None + if len(sys.argv) == 3: + try: + expected_trials = int(sys.argv[2]) + except ValueError: + print("EXPECTED_TRIALS must be a non-negative integer", file=sys.stderr) + return 2 + if expected_trials < 0: + print("EXPECTED_TRIALS must be a non-negative integer", file=sys.stderr) + return 2 + + root = pathlib.Path(sys.argv[1]).resolve() + if expected_trials is None: + metadata = read_json(root / "suite.json") + if isinstance(metadata, dict) and "expected_trials" in metadata: + recorded = metadata["expected_trials"] + if type(recorded) is not int or recorded < 0: + print("suite.json has an invalid expected_trials value", file=sys.stderr) + return 2 + expected_trials = recorded + if not root.is_dir(): + print(f"results directory not found: {root}", file=sys.stderr) + return 2 + + trial_dirs = sorted(path for path in root.iterdir() if path.is_dir()) + if expected_trials is not None and len(trial_dirs) != expected_trials: + print( + f"expected {expected_trials} trial directories, found {len(trial_dirs)}", + file=sys.stderr, + ) + return 1 + if not trial_dirs: + print("no trial directories found", file=sys.stderr) + return 2 + + completed = 0 + auto_accepted = 0 + acceptance_unverified = 0 + failed = 0 + human_passed = 0 + human_failed = 0 + human_pending = 0 + human_invalid = 0 + activation_unverified = 0 + activation_mismatch = 0 + + for trial_dir in trial_dirs: + result_path = trial_dir / "result.json" + if not result_path.is_file(): + failed += 1 + print(f"FAIL {trial_dir.name}: result.json missing") + continue + + result = read_json(result_path) + if not isinstance(result, dict): + failed += 1 + print(f"FAIL {trial_dir.name}: invalid result.json") + continue + + trial_failed = False + acceptance = result.get("acceptance_pass") + if not isinstance(acceptance, str) or acceptance not in {"true", "false", "unverified"}: + trial_failed = True + acceptance = "invalid" + print(f"FAIL {trial_dir.name}: invalid acceptance_pass value") + if type(result.get("exit_status")) is not int or type(result.get("timed_out")) is not bool: + trial_failed = True + print(f"FAIL {trial_dir.name}: invalid execution status fields") + if result.get("exit_status") != 0 or result.get("timed_out") is True: + trial_failed = True + + activated = result.get("skill_activated") + leaked = result.get("skill_leaked") + expected_trigger = result.get("expected_skill_trigger") + with_skill = result.get("with_skill") + activation_is_unverified = False + if activated not in {"true", "false", "unverified"} or type(with_skill) is not bool: + trial_failed = True + activation_is_unverified = True + elif with_skill: + if activated == "unverified": + activation_is_unverified = True + elif expected_trigger in {"yes", "no"} and ((expected_trigger == "yes" and activated == "false") or (expected_trigger == "no" and activated == "true")): + activation_mismatch += 1 + trial_failed = True + if with_skill is False: + if leaked == "unverified": + activation_is_unverified = True + elif leaked == "true": + activation_mismatch += 1 + trial_failed = True + elif leaked != "false": + trial_failed = True + if activation_is_unverified: + activation_unverified += 1 + if acceptance == "false": + trial_failed = True + if result.get("task_language") == "rust": + if not all(result.get(key) is True for key in ("fmt_ok", "compile_ok", "clippy_ok", "test_ok")): + trial_failed = True + + if result.get("exit_status") == 0 and result.get("timed_out") is False: + completed += 1 + if acceptance == "true": + auto_accepted += 1 + elif acceptance == "unverified": + acceptance_unverified += 1 + + review = review_status(trial_dir) + if review == "passed": + human_passed += 1 + elif review == "failed": + human_failed += 1 + trial_failed = True + elif review == "invalid": + human_invalid += 1 + else: + human_pending += 1 + + if trial_failed: + failed += 1 + print(f"FAIL {trial_dir.name}") + elif review == "passed" and acceptance in {"true", "unverified"}: + print(f"PASS {trial_dir.name}") + else: + print(f"WAIT {trial_dir.name}: acceptance or human review is incomplete") + + total = len(trial_dirs) + print() + print("=== Evaluation summary ===") + print(f"Trials: {total}") + print(f"Completed agent runs: {completed}") + print(f"Automated acceptance passed: {auto_accepted}") + print(f"Automated acceptance unverified: {acceptance_unverified}") + print(f"Human reviews passed: {human_passed}") + print(f"Human reviews failed: {human_failed}") + print(f"Human reviews pending: {human_pending}") + print(f"Human reviews invalid: {human_invalid}") + print(f"Activation telemetry unverified: {activation_unverified}") + print(f"Activation mismatches or baseline leaks: {activation_mismatch}") + print(f"Failed trials: {failed}") + + if failed > 0: + print("SUITE FAILED: at least one trial failed an automated or human check") + return 1 + if acceptance_unverified > human_passed or human_pending > 0 or human_invalid > 0 or activation_unverified > 0: + print("SUITE INCOMPLETE: trials still need automated acceptance or valid human review") + return 2 + print("SUITE COMPLETE: automated checks and human reviews are recorded") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/evals/harness/test-harness.sh b/evals/harness/test-harness.sh index 92397be..1cbfcfa 100755 --- a/evals/harness/test-harness.sh +++ b/evals/harness/test-harness.sh @@ -3,6 +3,9 @@ set -Eeuo pipefail ROOT="$(cd "$(dirname "$0")/../.." && pwd -P)" TMP="$(mktemp -d)" trap 'rm -rf "$TMP"' EXIT +MOCK="$ROOT/evals/harness/mock/mock-agent.sh" +export EVAL_MODEL="mock-model" + TASK="$TMP/python-task.md" cat > "$TASK" <<'TASK' # deterministic Python task @@ -11,16 +14,90 @@ language: python Create a Python CSV summary utility. TASK -MOCK="$ROOT/evals/harness/mock/mock-agent.sh" -MOCK_BEHAVIOR=python OPENCODE_BIN="$MOCK" bash "$ROOT/evals/harness/run-trial.sh" "$TASK" 0 "$TMP/success" 10 >/dev/null + +EVAL_MODEL="mock-model" EVAL_PROVIDER="mock-provider" EVAL_MODEL_SETTINGS="deterministic-test" MOCK_BEHAVIOR=python OPENCODE_BIN="$MOCK" bash "$ROOT/evals/harness/run-trial.sh" "$TASK" 0 "$TMP/success" 10 >/dev/null python3 - "$TMP/success/result.json" <<'PY' import json, pathlib, sys data = json.loads(pathlib.Path(sys.argv[1]).read_text()) assert data["exit_status"] == 0 assert data["task_language"] == "python" -assert data["files_generated"] == 1 +assert data["source_files_after_run"] == 1 assert data["acceptance_pass"] == "unverified" +assert data["human_review"] == "required" +assert data["model"] == "mock-model" +assert data["provider"] == "mock-provider" +assert data["model_settings"] == "deterministic-test" +PY + +MOCK_BEHAVIOR=python OPENCODE_BIN="$MOCK" bash "$ROOT/evals/harness/run-trial.sh" "$ROOT/evals/tasks/10-no-trigger.md" 1 "$TMP/no-trigger-skill" 10 >/dev/null +python3 - "$TMP/no-trigger-skill/result.json" "$TMP/no-trigger-skill/prompt.txt" <<'PY' +import json, pathlib, sys +data = json.loads(pathlib.Path(sys.argv[1]).read_text()) +prompt = pathlib.Path(sys.argv[2]).read_text() +assert data["skill_injected"] is True +assert data["acceptance_pass"] == "true" +assert data["skill_activated"] == "false" +assert data["skill_leaked"] == "not_applicable" +assert len(data["skill_hash"]) == 64 +assert data["expected_skill_trigger"] == "no" +assert "Use the ratatui skill" not in prompt +PY + + +MOCK_SKILL_CALL=1 MOCK_BEHAVIOR=python OPENCODE_BIN="$MOCK" bash "$ROOT/evals/harness/run-trial.sh" "$ROOT/evals/tasks/10-no-trigger.md" 1 "$TMP/skill-activation" 10 >/dev/null +python3 - "$TMP/skill-activation/result.json" <<'PY' +import json, pathlib, sys +data = json.loads(pathlib.Path(sys.argv[1]).read_text()) +assert data["skill_activated"] == "true" +assert data["skill_tool_calls"] == 1 +PY + +MOCK_SKILL_CALL=1 MOCK_BEHAVIOR=python OPENCODE_BIN="$MOCK" bash "$ROOT/evals/harness/run-trial.sh" "$ROOT/evals/tasks/10-no-trigger.md" 0 "$TMP/skill-leak" 10 >/dev/null +python3 - "$TMP/skill-leak/result.json" <<'PY' +import json, pathlib, sys +data = json.loads(pathlib.Path(sys.argv[1]).read_text()) +assert data["skill_leaked"] == "true" +PY + +MOCK_SUBAGENT_CALL=1 MOCK_BEHAVIOR=python OPENCODE_BIN="$MOCK" bash "$ROOT/evals/harness/run-trial.sh" "$ROOT/evals/tasks/10-no-trigger.md" 1 "$TMP/subagent" 10 >/dev/null +python3 - "$TMP/subagent/result.json" <<'PY' +import json, pathlib, sys +data = json.loads(pathlib.Path(sys.argv[1]).read_text()) +assert data["skill_activated"] == "unverified" +assert data["skill_leaked"] == "not_applicable" +assert data["subagent_tool_calls"] == 1 +PY + +mkdir -p "$TMP/bin" +cat > "$TMP/bin/cargo" <<'CARGO' +#!/usr/bin/env bash +exit 0 +CARGO +chmod +x "$TMP/bin/cargo" +FIXTURE_TASK="$TMP/fixture-task.md" +cat > "$FIXTURE_TASK" <<'TASK' +# fixture staging test + +language: rust +fixture: dirview + +Preserve the existing project. +TASK +if PATH="$TMP/bin:$PATH" MOCK_BEHAVIOR=fail OPENCODE_BIN="$MOCK" bash "$ROOT/evals/harness/run-trial.sh" "$FIXTURE_TASK" 0 "$TMP/fixture" 10 >/dev/null 2>&1; then + echo "expected mock failure was not reported" >&2 + exit 1 +fi +grep -q '^name = "dirview"$' "$TMP/fixture/project/Cargo.toml" +test -f "$TMP/fixture/project/src/keymap.rs" +python3 - "$TMP/fixture/result.json" <<'PY' +import json, pathlib, sys +data = json.loads(pathlib.Path(sys.argv[1]).read_text()) +assert data["task_fixture"] == "dirview" +assert data["expected_skill_trigger"] is None +assert data["repository_commit"] +assert data["task_spec_sha256"] PY + if MOCK_BEHAVIOR=fail OPENCODE_BIN="$MOCK" bash "$ROOT/evals/harness/run-trial.sh" "$TASK" 0 "$TMP/failure" 10 >/dev/null 2>&1; then echo "agent failure was incorrectly accepted" >&2 exit 1 @@ -29,9 +106,127 @@ if MOCK_BEHAVIOR=success OPENCODE_BIN="$MOCK" bash "$ROOT/evals/harness/run-tria echo "repository-local trial directory was incorrectly accepted" >&2 exit 1 fi +if MOCK_BEHAVIOR=python OPENCODE_BIN="$MOCK" bash "$ROOT/evals/harness/run-trial.sh" "$TASK" 0 "$TMP/success" 10 >/dev/null 2>&1; then + echo "non-empty trial directory was incorrectly reused" >&2 + exit 1 +fi + +mkdir -p "$TMP/summary/python-skill0-trial1" +cat > "$TMP/summary/python-skill0-trial1/result.json" <<'RESULT' +{ + "exit_status": 0, + "timed_out": false, + "task_language": "python", + "with_skill": false, + "expected_skill_trigger": "no", + "skill_activated": "false", + "skill_leaked": "false", + "acceptance_pass": "true" +} +RESULT +if python3 "$ROOT/evals/harness/summarize-results.py" "$TMP/summary" >/dev/null; then + echo "summary accepted a trial without human review" >&2 + exit 1 +else + status=$? + [ "$status" -eq 2 ] || exit "$status" +fi +cp "$ROOT/evals/human-review-template.json" "$TMP/summary/python-skill0-trial1/human-review.json" +python3 - "$TMP/summary/python-skill0-trial1/human-review.json" <<'PY' +import json, pathlib, sys +path = pathlib.Path(sys.argv[1]) +data = json.loads(path.read_text()) +data["reviewer"] = "ci-test" +data["reviewed_at"] = "2026-11-26" +data["status"] = "passed" +data["notes"] = "Deterministic summarizer fixture." +data["scores"] = {key: 2 for key in data["scores"]} +path.write_text(json.dumps(data, indent=2) + "\n") +PY +python3 "$ROOT/evals/harness/summarize-results.py" "$TMP/summary" >/dev/null + +mkdir -p "$TMP/summary-invalid/python-skill0-trial1" +cat > "$TMP/summary-invalid/python-skill0-trial1/result.json" <<'RESULT' +{ + "exit_status": 0, + "timed_out": false, + "task_language": "python", + "acceptance_pass": "maybe" +} +RESULT +if python3 "$ROOT/evals/harness/summarize-results.py" "$TMP/summary-invalid" >/dev/null; then + echo "summary accepted an invalid acceptance status" >&2 + exit 1 +else + status=$? + [ "$status" -eq 1 ] || exit "$status" +fi + +mkdir -p "$TMP/summary-missing/python-skill0-trial1" +if python3 "$ROOT/evals/harness/summarize-results.py" "$TMP/summary-missing" 2 >/dev/null; then + echo "summary ignored a missing trial result" >&2 + exit 1 +else + status=$? + [ "$status" -eq 1 ] || exit "$status" +fi + +mkdir -p "$TMP/non-empty-results" +touch "$TMP/non-empty-results/old-run" +if bash "$ROOT/evals/harness/run-suite.sh" 1 10 "$TMP/non-empty-results" >/dev/null 2>&1; then + echo "run-suite reused a non-empty results directory" >&2 + exit 1 +fi + bash -n "$ROOT/evals/harness/"*.sh "$ROOT/evals/acceptance/"*.sh if grep -nE '(^|[;&|[:space:]])eval[[:space:]]' "$ROOT/evals/acceptance/"*.sh; then echo "unsafe eval remains in acceptance scripts" >&2 exit 1 fi + +mkdir -p "$TMP/filter-fixture-task" +cat > "$TMP/filter-fixture-task/task.md" <<'TASK' +# filter regression fixture + +language: rust +fixture: dirview-filter-reset + +Fix the seeded selection reset regression. +TASK +if PATH="$TMP/bin:$PATH" MOCK_BEHAVIOR=fail OPENCODE_BIN="$MOCK" bash "$ROOT/evals/harness/run-trial.sh" "$TMP/filter-fixture-task/task.md" 0 "$TMP/filter-fixture" 10 >/dev/null 2>&1; then + echo "expected fixture mock failure was not reported" >&2 + exit 1 +fi +grep -A3 'Action::FilterInput(c)' "$TMP/filter-fixture/project/src/state.rs" | grep -q 'self.selected = 0' +grep -A4 'Action::FilterInput(c)' "$TMP/filter-fixture/project/src/state.rs" | grep -q 'self.rebuild(None)' + +mkdir -p "$TMP/summary-suite/python-skill0-trial1" +cp "$TMP/summary/python-skill0-trial1/result.json" "$TMP/summary-suite/python-skill0-trial1/result.json" +cp "$TMP/summary/python-skill0-trial1/human-review.json" "$TMP/summary-suite/python-skill0-trial1/human-review.json" +cat > "$TMP/summary-suite/suite.json" <<'JSON' +{"expected_trials":2} +JSON +if python3 "$ROOT/evals/harness/summarize-results.py" "$TMP/summary-suite" >/dev/null 2>&1; then + echo "summary ignored the recorded suite trial count" >&2 + exit 1 +fi + +mkdir -p "$TMP/summary-telemetry/skill-skill1-trial1" +cat > "$TMP/summary-telemetry/skill-skill1-trial1/result.json" <<'RESULT' +{ + "exit_status": 0, + "timed_out": false, + "task_language": "python", + "with_skill": true, + "expected_skill_trigger": null, + "skill_activated": "unverified", + "skill_leaked": "not_applicable", + "acceptance_pass": "true" +} +RESULT +cp "$TMP/summary/python-skill0-trial1/human-review.json" "$TMP/summary-telemetry/skill-skill1-trial1/human-review.json" +if python3 "$ROOT/evals/harness/summarize-results.py" "$TMP/summary-telemetry" >/dev/null 2>&1; then + echo "summary accepted unknown skill activation telemetry" >&2 + exit 1 +fi echo "Harness tests passed." diff --git a/evals/human-review-template.json b/evals/human-review-template.json new file mode 100644 index 0000000..458442d --- /dev/null +++ b/evals/human-review-template.json @@ -0,0 +1,19 @@ +{ + "reviewer": "", + "reviewed_at": "YYYY-MM-DD", + "status": "passed", + "scores": { + "functional_acceptance": 0, + "api_version_correctness": 0, + "terminal_lifecycle": 0, + "keyboard_interaction": 0, + "resize_layout": 0, + "state_error_handling": 0, + "architecture": 0, + "tests": 0, + "scope_discipline": 0, + "verification_quality": 0 + }, + "critical_failures": [], + "notes": "" +} diff --git a/evals/results/summary.md b/evals/results/summary.md index d06a87f..514f73a 100644 --- a/evals/results/summary.md +++ b/evals/results/summary.md @@ -1,46 +1,51 @@ -# Evaluation results summary +# Optional evaluation status -## Environment +Last updated: 27 November 2026. -- Model: beam-free (opencode, OpenRouter-backed) -- Date: 2026-11-26 -- Harness: `evals/harness/run-trial.sh` (v3, honest exit status, language-aware, isolated config) -- Skill commit: 33b5d2b (first trial), 2da8f8e (harness fixes) +## Current conclusion -## Trials run +No controlled effectiveness claim is made. The paired evaluation harness is optional research tooling; real-model trials are not required for normal use, CI, or release readiness. -| Task | Condition | Compile | Clippy | Tests | Ratatui | Files | Timed out | Acceptance | Notes | -|---|---|---|---|---|---|---|---|---|---| -| 10-no-trigger | no-skill | N/A (Python) | N/A | N/A | No | 0 | No | PASS | Correctly did not use Ratatui | -| 10-no-trigger | with-skill | N/A (Python) | N/A | N/A | No | 0 | No | PASS | Correctly did not trigger skill | -| 01-new-app | with-skill | No | No | No | Yes | 6 | Yes (180s) | N/A (timed out) | Generated partial code (action, state, keymap, event, lib, Cargo.toml). Timed out before main.rs/ui/theme. | +The repository now contains ten task specifications. For maintainers who choose to run a controlled comparison, the initial schedule is three repetitions for each task in both conditions: -## Key findings +- 10 tasks +- 2 conditions (skill available / baseline) +- 3 repetitions +- 60 real model runs -1. The skill correctly does not trigger on non-Rust tasks (Eval 10, both conditions). -2. The skill's "copy structure" instruction caused the agent to follow the skill's module structure (action/keymap/state/event split) but the trial timed out before completing. Whether the agent copied the dirview template verbatim or not cannot be determined from the partial output. -3. The 180s timeout is insufficient for a full app generation. The harness now supports configurable timeouts. +No results from those 60 runs are included in this repository. The CI mock agent tests harness mechanics only. -## Contradiction resolution +## Historical exploratory runs -An earlier version of this summary claimed the agent copied the dirview template and forgot to rename `use dirview::App;`. This claim was based on a different trial's partial output. The raw logs for the only completed Rust trial (Eval 01, trial 1) show 6 source files generated (action, state, keymap, event, lib, Cargo.toml) with no main.rs or ui/ directory. Whether the agent copied the template or wrote from scratch cannot be determined from this partial output. The claim has been retracted. Raw artifacts are the source of truth. +The following runs predate the current isolated, randomized harness and must not be combined into a skill-effectiveness score: -## Limitations +| Task | Condition | Outcome | Interpretation | +|---|---|---|---| +| 10-no-trigger | Baseline | Python task passed | One historical negative-trigger smoke run | +| 10-no-trigger | Skill available | Python task passed without invoking Ratatui | One historical negative-trigger smoke run | +| 01-new-app | Skill available | Timed out at 180 seconds after generating a partial Rust project | Incomplete exploratory run; no paired baseline | -- Only 1 partial Rust trial completed (timed out at 180s). -- No no-skill comparison for Rust tasks completed. -- Results are preliminary and not statistically significant. -- Full evaluation requires ~10 min per trial with a real model. -- Skill activation is reported as "unverified" (cannot be proven from output text). +The two Python smoke runs do not prove skill quality. The partial Rust run cannot be counted as a successful implementation or compared with a baseline. Its raw output did not establish whether the model copied the dirview template or independently chose a similar structure. -## Harness improvements made (v3) +## What CI verifies -- Real skill injection (copy to isolated opencode config, verify presence) -- Honest exit status (no `|| true` suppression) -- Timeout classification (exit 124 = timeout) -- Separate stdout/stderr logs -- Skill content hash (SHA256 of all skill files, not git HEAD) -- Language-aware (Rust vs Python via task metadata) -- Configurable timeout -- Task-specific acceptance scripts -- No skill leakage into baseline (config isolated) +CI verifies repository behavior and test infrastructure, not model capability: + +- The harness tests exercise isolated trial setup, fixture staging, result validation, acceptance status, skill activation telemetry, baseline leakage detection, and incomplete-review handling using a deterministic mock agent. +- The dirview tests cover preview sorting, counts, symlinks, help rendering, and scrolling. +- A 50,000-entry directory regression test checks that directory preview work is dispatched to a background worker and that the exact total and bounded sample are returned. +- A Betamax tape exercises the interactive dirview terminal flow. Its CI status must be checked independently from the Rust test suite. + +## Optional future research + +1. If measuring skill effectiveness is useful, run the paired suite with one fixed provider/model version and identical settings in both conditions. +2. Preserve all trial directories, JSON event streams, compiler/test logs, model metadata, and randomized order schedule. +3. Complete task-specific acceptance checks, then obtain independent human review using human-review-template.json. +4. Report failures, timeouts, unverified skill activations, and excluded trials. Do not omit poor runs from the denominator. +5. Smoke-test the documented installation and invocation paths in each agent client before claiming runtime compatibility. + +## Reproducing the evaluation + +See evals/README.md for the exact OpenCode command, isolation model, paired schedule, metadata, and human-review workflow. + +A complete run requires OpenCode and an operator-configured provider credential. Repository CI intentionally does not run model trials, and no contributor is expected to configure credentials or run paid evaluations. \ No newline at end of file diff --git a/evals/scoring-rubric.md b/evals/scoring-rubric.md index cdbcfe1..4cad9f0 100644 --- a/evals/scoring-rubric.md +++ b/evals/scoring-rubric.md @@ -1,28 +1,32 @@ -# Scoring rubric +# Evaluation scoring rubric -Each trial is scored 0-10 on each dimension. A trial's total is the sum. +Use this rubric for human review. Record objective checks separately; do not infer them from a reviewer's impression. + +Score each dimension from 0 to 2: | Dimension | 0 | 1 | 2 | |---|---|---|---| -| Compiles | No | With warnings | Clean | -| API correctness | Stale/invented APIs | Minor issues | Current APIs only | -| Terminal lifecycle | Broken or missing | Partial | Correct init/restore | -| Keyboard | Dead or wrong keys | Partial | All documented keys work | -| Resize | Panics or corrupts | Degrades poorly | Graceful at all sizes | -| States | Missing | Partial | Empty/loading/error/too-small all present | -| Architecture | Monolithic | Mixed | State/ui separated | -| Tests | None or trivial | Superficial | Meaningful behavioral tests | -| Complexity | Over-engineered | Reasonable | Minimal and clear | -| Skill adherence | Ignored skill | Partial | Followed workflow | - -## Pass threshold - -A trial passes if total >= 14/20 and compiles (score >= 1 on "Compiles"). - -## Skill vs no-skill comparison - -Report: -- Pass rate (skill) vs pass rate (no skill) -- Mean score difference -- Specific failure modes unique to each condition -- Token/cost overhead of skill-enabled runs +| Functional acceptance | Required behavior missing | Partially implemented | All stated behavior verified | +| API and version correctness | Incorrect or incompatible | Minor issues | Correct for fixture dependencies | +| Terminal lifecycle | Broken or unsafe | Partially handled | Correct setup, exit, and restoration | +| Keyboard interaction | Broken or undiscoverable | Partially correct | Documented behavior works | +| Resize and layout | Panics or unusable | Degrades awkwardly | Works at specified sizes | +| State and error handling | Important states missing | Partial handling | Relevant states handled clearly | +| Architecture | Unnecessarily coupled or complex | Adequate | Clear, proportionate, maintainable | +| Tests | Missing or ineffective | Partial coverage | Meaningful behavior is tested | +| Scope discipline | Unrelated rewrites or dependencies | Some avoidable churn | Minimal changes appropriate to task | +| Verification quality | Claims without evidence | Partial evidence | Reproducible checks and honest report | + +Maximum: 20 points. + +## No universal pass threshold + +A task can have a critical acceptance criterion that must pass regardless of total score. A high subjective score must not compensate for a build failure or missing required behavior. + +For each trial, record the task and fixture commit, skill condition and hash, model/provider/settings, reviewer and date, objective check results, per-dimension scores, critical failures, and rationale for non-obvious scores. + +## Comparison + +Report skill and baseline outcomes per task, not only pooled averages. Include completion and timeout rates, build/test/acceptance rates, human score distributions, condition-specific failures, token/latency/cost overhead when available, and negative-trigger behavior. + +Do not claim statistical significance from a small sample. Do not label ungraded trials as passes. diff --git a/evals/tasks/02-add-widget.md b/evals/tasks/02-add-widget.md index 175ae10..4a66387 100644 --- a/evals/tasks/02-add-widget.md +++ b/evals/tasks/02-add-widget.md @@ -3,6 +3,7 @@ ## Context language: rust +fixture: dirview Given the dirview template, add a status bar at the bottom showing the current directory's total size and file count. diff --git a/evals/tasks/03-modify-layout.md b/evals/tasks/03-modify-layout.md index 6221c35..774d210 100644 --- a/evals/tasks/03-modify-layout.md +++ b/evals/tasks/03-modify-layout.md @@ -3,6 +3,7 @@ ## Context language: rust +fixture: todo Given the todo app, add a sidebar showing completed vs pending counts and a progress bar. The main list keeps its current behavior. @@ -14,5 +15,6 @@ progress bar. The main list keeps its current behavior. - Progress bar reflects real completion ratio - No regression in add/toggle/delete - Renders at 40x8 without panic +- No unrelated restructuring ## Should trigger skill: yes diff --git a/evals/tasks/08-older-version.md b/evals/tasks/08-older-version.md index 20e1de6..764dacf 100644 --- a/evals/tasks/08-older-version.md +++ b/evals/tasks/08-older-version.md @@ -3,16 +3,17 @@ ## Context language: rust +fixture: ratatui-028 -Given a project using ratatui 0.28.0, add a new widget without upgrading -ratatui. The project's Cargo.toml pins `ratatui = "0.28"`. +Given a small project pinned to ratatui 0.28.0, add a new widget without +upgrading Ratatui or changing the existing dependency constraint. ## Acceptance criteria -- Does not upgrade ratatui or change the version constraint -- Uses 0.28-compatible APIs (e.g., `Frame::size` not `Frame::area` if needed) -- Compiles against 0.28 -- `cargo tree -d` shows no duplicate ratatui +- Does not upgrade ratatui or change its version constraint +- Uses APIs compatible with the fixture's Ratatui version +- Compiles against the pinned version +- Does not introduce a duplicate Ratatui version - Existing tests pass ## Should trigger skill: yes diff --git a/evals/tasks/09-bug-fix.md b/evals/tasks/09-bug-fix.md index c06aa11..13267bb 100644 --- a/evals/tasks/09-bug-fix.md +++ b/evals/tasks/09-bug-fix.md @@ -3,9 +3,11 @@ ## Context language: rust +fixture: dirview-filter-reset -The dirview template has a bug: when filtering, the selected entry jumps to -index 0 instead of staying on the current entry. Fix it. +The task fixture deliberately resets selection to index 0 on every filter +keystroke. Fix it so filtering preserves the selected entry when it remains +visible, and otherwise selects the nearest valid entry. ## Acceptance criteria diff --git a/evals/tasks/10-no-trigger.md b/evals/tasks/10-no-trigger.md index 4fd9544..061c54b 100644 --- a/evals/tasks/10-no-trigger.md +++ b/evals/tasks/10-no-trigger.md @@ -4,13 +4,21 @@ language: python -Write a Python script that reads a CSV file and prints summary statistics -(mean, median, std) for each numeric column. +Write a single-file Python program named solution.py that accepts a CSV path as +its only command-line argument. Print one JSON object mapping each numeric +column to count, mean, median, and population standard deviation (std). Ignore +blank cells. A column is numeric when it has at least one non-blank value and +every non-blank value parses as a finite number. Ignore non-numeric columns. +Use only the Python standard library. ## Acceptance criteria -- Skill is NOT activated (no ratatui references in output) -- Python code compiles and runs -- Handles missing values gracefully +- Reads the input CSV path from argv +- Emits valid JSON to stdout +- Ignores blank cells in numeric columns +- Reports count, mean, median, and population standard deviation +- Omits non-numeric and all-blank columns +- Handles a missing input path with a useful error and a non-zero exit +- Does not create a Ratatui or Rust project ## Should trigger skill: no diff --git a/skills/ratatui/SKILL.md b/skills/ratatui/SKILL.md index f62e350..103f547 100644 --- a/skills/ratatui/SKILL.md +++ b/skills/ratatui/SKILL.md @@ -1,127 +1,133 @@ --- name: ratatui -description: Build or modify terminal UIs in Rust with ratatui. Use for any TUI, terminal dashboard, file browser, log viewer, or "make this CLI interactive" task. Do not use for non-Rust or non-terminal tasks. +description: Build, modify, debug, or review Rust terminal user interfaces built with Ratatui. Do not use for non-Rust tasks or command-line applications without a terminal UI. --- -# ratatui +# Ratatui -Write terminal UIs that work, look deliberate, and contain no filler. +Build terminal interfaces that are correct, usable, and appropriate to the project. This skill is a workflow and a set of technical references, not a universal architecture or visual style guide. -Two failures this skill prevents: +## Choose the workflow -1. **Stale or invented APIs.** ratatui changes between releases. Never write ratatui code from memory. -2. **Slop.** Default styling nobody chose, decorative panels, fake data, dead keys, narrating comments. If it is on screen it is real. +Inspect the repository and identify the task first. -All paths below are relative to this skill's installed directory. Locate this -SKILL.md first, then derive the skill directory: -`SKILL_DIR=$(dirname "$(realpath )")`. Run every bundled -script through that absolute path. Never assume the working directory is the -skill or repository root. +- **New application:** understand requirements, choose the smallest suitable structure, implement, and verify. +- **Existing application:** inspect relevant modules, conventions, dependencies, and tests. Preserve established design and make the smallest change that solves the task. +- **Focused widget or layout change:** follow existing state and rendering patterns. Do not introduce application-wide architecture for a local change. +- **Debugging or review:** reproduce the behavior, inspect the relevant code and dependency versions, then verify the proposed fix. -## Which workflow +Do not copy the starter template into an existing application. -**New application** (no existing codebase): follow steps 1-5 in full. +## 1. Inspect and research -**Existing application** (bug fix, small feature, layout tweak): skip the design -brief unless the change alters the layout archetype. Inspect the existing code -first. Make the smallest change that fixes the issue. Preserve existing -dependencies, patterns, and key bindings. Run the existing tests, not new ones -unless the bug lacks coverage. Do not restructure. +1. Read the relevant `Cargo.toml`, `Cargo.lock`, workspace configuration, and nearby source. +2. Identify the Ratatui and terminal-backend versions actually used. +3. Preserve dependency constraints unless an upgrade is requested or required. +4. Consult documentation and source matching those versions. The latest release is not automatically compatible. +5. Check release notes when changing versions or relying on recently changed APIs. +6. Compile a minimal example when an API remains uncertain. -## 1. Research (before any code) +The bundled helper compares registry releases with versions resolved by a project: -Run `$SKILL_DIR/scripts/crate-versions.sh ratatui color-eyre unicode-width` plus -every other crate you plan to use. For an existing project, pass -`--manifest PATH/TO/Cargo.toml` to report the resolved project version beside -the latest release. Quote the output. Set `rust-version` in Cargo.toml to the -highest MSRV among your dependencies. +```bash +SKILL_DIR="/path/to/installed/ratatui" +$SKILL_DIR/scripts/crate-versions.sh ratatui crossterm unicode-width +$SKILL_DIR/scripts/crate-versions.sh --manifest path/to/Cargo.toml ratatui crossterm +``` + +Treat its output as a starting point, not a substitute for compatibility checks. + +## 2. Choose an architecture that fits + +Prefer the simplest design that makes behavior understandable and testable. + +Often useful, but not mandatory: + +- Keep application state and state transitions independent of terminal rendering. +- Keep rendering focused on drawing from state. +- Separate event translation from application actions when that reduces coupling. +- Centralize key bindings when input, help, and footer hints share them. +- Keep I/O and long-running work out of the draw path. +- Use modules that reflect real responsibilities. + +Do not impose these patterns on a tiny program when they add more complexity than value. Do not restructure an existing project to match the template. + +### Starter template + +`templates/dirview/` is a working example, not a required foundation. Use it when its navigation, state, event, and rendering structure fits. Otherwise borrow only relevant ideas or start smaller. Read its code before copying anything. -- Check `cargo --version` against each dependency's MSRV. Fix before continuing. -- Read the ratatui CHANGELOG and BREAKING-CHANGES for your version. -- Confirm widget crates support your ratatui version (`cargo tree -d`). -- If the app handles terminal events directly, declare `crossterm` as a direct - dependency at the version compatible with Ratatui. Import from - `crossterm::event` and verify `cargo tree -d` has no duplicate versions. -- Uncertain API: write a ten-line program and compile it. +## 3. Build for the actual interface -See `references/research-checklist.md` for pitfalls found in practice. +Derive layout, interaction, and visual choices from the requirements and data being displayed. -## 2. Design brief (new apps only) +Consider where relevant: -Write this before any code. Every line justified from the app's actual data. +- Clear hierarchy and useful information density. +- Discoverable keyboard behavior. +- Terminal resizing and small dimensions. +- Empty, loading, success, and error states. +- Long text, Unicode width, and untrusted terminal text. +- Focus and selection visibility. +- Color and monochrome terminals, including `NO_COLOR`. +- Cancellation and recovery from failures. +- Large datasets and bounded or incremental work. -- **Purpose:** one sentence, user, keyboard habits. -- **Data:** what is shown, how big (10 rows or 100,000?), how it changes. -- **Layout archetype:** pick one and say why (list+preview, multi-panel, - drill-down, dashboard, header+list, popup/overlay). -- **Accent color:** exactly one ANSI color, what it marks. Secondary text is - dim, not a second color. -- **Density:** compact or roomy, and why. -- **Modes and keys:** vim-style plus arrows. Never rebind Ctrl-C, Esc, Enter. -- **States:** empty, loading, failed, too small. -- **Not doing:** features left out on purpose. +These are design considerations, not a mandate to include every state or feature. Avoid decoration that does not help users understand or operate the interface. Do not present fake data as real functionality. -## 3. Build +## 4. Keep the UI responsive -**New app:** start from `templates/dirview/`. Copy the structure, then -replace the domain. Rename the crate reference in `main.rs`. +Rendering should not perform avoidable blocking work. For expensive operations, choose an approach appropriate to the workload: precompute, cache, paginate, bound, move work off the draw path, or show progress. Do not add asynchronous machinery to trivial operations without a demonstrated need. -**Existing app:** do not copy the template. Read the existing code first. -Make the smallest change. Preserve existing dependencies and patterns. +Measure before making performance claims. -| File | Job | -|---|---| -| `action.rs` | Enum of everything the user can do | -| `keymap.rs` | One key table drives input, footer hints, and `?` help | -| `state.rs` | All state and `State::update(Action)`. No terminal types | -| `fs.rs` | I/O. No terminal types | -| `ui/` | Rendering only. Reads state, never changes it | -| `theme.rs` | Colors by role. The only file that names a color | -| `event.rs`, `app.rs`, `main.rs` | Input, loop, startup | +## 5. Test behavior at the right level -Rules: +1. **State and logic:** unit-test transitions, filtering, sorting, selection, and errors without a terminal. +2. **Rendering:** use Ratatui's `TestBackend` for layout, clipping, styles, and important visible states. Test representative sizes where responsiveness matters. +3. **Terminal integration:** use a PTY, VHS, Betamax, or equivalent when lifecycle, keyboard input, terminal restoration, or resizing is part of the behavior. +4. **Manual review:** inspect hierarchy, readability, and awkward edge cases. -- Everything visible works. No fake data, dead keys, placeholder rows. -- Measure text with `unicode-width`, never `.len()`. Sanitize untrusted text. -- Build only rows on screen. Cost per frame must not grow with data. -- 16 ANSI colors by default. Respect `NO_COLOR`. No forced background. -- One border style, plain Unicode, no emoji. -- Handle every state: empty, error, loading, too small, resize. -- Destructive actions confirm. Slow work never blocks the draw loop. -- `color-eyre` in `main`, typed errors in the library, no swallowed results. -- Comments say why, not what. No TODOs, no commented-out code. +Do not snapshot every frame by default. Prefer assertions about meaningful behavior and visible state. A process-start smoke test alone does not establish that an interactive application works. -## 4. Verify +## 6. Verify the change + +Run checks appropriate to the workspace and affected packages: ```bash cargo fmt --check cargo clippy --all-targets -- -D warnings cargo test +cargo build +``` + +Use `--manifest-path` or package selection for workspaces and scoped changes. Do not claim a check passed if it was not run. + +The bundled PTY helper is available when a real terminal smoke test is useful: + +```bash +SKILL_DIR="/path/to/installed/ratatui" +$SKILL_DIR/scripts/pty-smoke.py PATH/TO/BINARY ``` -Then: +Use its app-specific options as needed. The style scanner is heuristic, not a correctness analyzer: -1. **Render checks where they add value.** Use `TestBackend` at 40x8, 80x24, - and 200x60 for clipping, alignment and responsive layout. Prefer state-based - assertions for behavior; do not snapshot every screen by default. -2. **Terminal integration.** Use VHS/Betamax recordings or a PTY smoke test - for lifecycle, resize and key handling. Startup/exit alone does not prove - screen content. `$SKILL_DIR/scripts/pty-smoke.py PATH/TO/BINARY`. Universal - checks run by default (startup, alternate screen, tiny terminal, clean exit - via Ctrl-C). Add `--quit-keys`, `--keys`, `--tiny-text`, `--check-ctrl-c`, - `--check-color`, `--check-resize` for app-specific checks. -3. **Slop scan.** `$SKILL_DIR/scripts/lint-slop.sh PROJECT_DIR` must print - `clean`. +```bash +SKILL_DIR="/path/to/installed/ratatui" +$SKILL_DIR/scripts/lint-slop.sh PROJECT_DIR +``` -If a check cannot run, say which and why. Do not report success for unrun checks. +Compiler-visible lints belong in Clippy. Human review is still needed for architecture, error handling, and visual quality. -## 5. Report +## 7. Report honestly -Say what was built, versions used, which checks passed, and anything unverified. -Keep it short. Do not recap the steps. +Summarize what changed, important dependency/API decisions, checks actually run, relevant behavior verified, and anything not tested or uncertain. + +Never report unrun checks as passing. ## References -- `references/research-checklist.md`: version and API research, pitfalls -- `references/ux-principles.md`: layouts, keys, color, responsiveness -- `references/slop-tells.md`: what reads as generated, with before/after +Read only what the task needs: + +- `references/research-checklist.md`: version and API research. +- `references/ux-principles.md`: interface design and terminal usability. +- `references/slop-tells.md`: visual and textual patterns worth reviewing. diff --git a/skills/ratatui/references/slop-tells.md b/skills/ratatui/references/slop-tells.md index 8091eec..e2858fe 100644 --- a/skills/ratatui/references/slop-tells.md +++ b/skills/ratatui/references/slop-tells.md @@ -1,126 +1,97 @@ -# Slop tells +# Review signals for generated-looking code and interfaces -"Slop" here means output that reads as generated: recognizable on sight, with a gap between what it claims and what it does. Using an AI is not the problem; shipping filler is. `skills/ratatui/scripts/lint-slop.sh` checks the mechanical ones; the rest need judgment. +"Slop" is not a technical category and cannot be reliably detected by a universal regex. This guide collects signals that deserve review. They are not automatic defects: assess them against the product, audience, existing codebase, and explicit requirements. -Sources for these tells are public discussions of AI-generated projects (a large study of complaints about AI-built sites, Rust forum and project AI policies, a NixOS forum review of a Rust TUI, Hacker News threads). The common thread across them: effort used to be proof of quality, now it is free, so people look for evidence that someone decided things. +Using AI is not itself a quality problem. The concern is shipping code or interfaces whose claims, behavior, and implementation do not agree. -## UI tells +The scanner in `scripts/lint-slop.sh` checks only a narrow set of mechanical conventions. It does not detect most of the issues in this guide. Human review and behavioral tests remain necessary. -| Tell | Why it reads as slop | Instead | +## High-confidence problems + +These are defects when they contradict the requested behavior: + +| Signal | Why it matters | Better approach | +|---|---|---| +| Fake data presented as live or real | Misleads users | Connect real data or label examples clearly | +| A documented key or visible control that does nothing | The interface promises behavior it does not provide | Implement it, remove it, or explain why it is unavailable | +| Placeholder output shipped as completed functionality | The requested work is incomplete | Implement the behavior or report the limitation | +| Unsupported claims about tests, compatibility, or performance | Reviewers cannot trust the report | State exactly what was measured or run | +| Ignored errors that can affect correctness | Failures become invisible | Propagate, handle, or report the error | +| APIs or dependencies chosen without checking the project's versions | Code may not compile or may introduce compatibility problems | Inspect the manifest, lockfile, and version-matched documentation | +| Destructive behavior without safeguards appropriate to its consequences | Users can lose data unexpectedly | Use confirmation, undo, backups, or another proportionate safeguard | + +## Design signals to question + +These are common generic defaults, not universal prohibitions: + +| Signal | Why it may be a problem | Questions to ask | +|---|---|---| +| Neon gradients, glow, or high-saturation accents | Can obscure hierarchy or look unrelated to the product | Does this palette serve the product and remain readable? | +| Emoji used as generic icons | Meaning and rendering vary by terminal | Does the symbol communicate clearly in supported terminals? | +| Decorative banners, taglines, mascots, or badges | May consume space without helping the task | Does this element add information or improve navigation? | +| Panels with no useful content | Adds visual structure without value | What user decision does this panel support? | +| Nested borders and repeated separators | Can make dense interfaces harder to scan | Would spacing or a simpler divider work better? | +| Excessive animation or status indicators | Adds noise and can distract from input | Does motion communicate a real state or progress? | +| A fixed palette, layout, or spacing scale everywhere | Ignores product-specific constraints | Is this convention useful in this application? | +| Too much empty space or too much density | Either can slow comprehension | What information should be visible at this size? | + +## Code and architecture signals to question + +| Signal | Why it may be a problem | Better approach | |---|---|---| -| Purple/cyan neon gradient on dark, glow, thick borders | The look every model reaches for | One ANSI accent, dim for secondary | -| Emoji as icons or in headers | Decoration with no information | Plain text, or a Unicode symbol that carries meaning | -| A "Ready" dot, a banner, a tagline, a mascot | Marketing inside the tool | Nothing. The tool is the interface | -| Panels that show nothing real (fake stats, sample rows) | Looks finished, is not | Show real data or no panel | -| Keys or buttons that do not respond | The most-cited complaint about generated TUIs | Remove it, or make it work | -| Everything boxed, borders inside borders | No hierarchy | Borders group; whitespace separates | -| Swapping one default for another | Still a default | State a choice in the design brief and justify it from the data | -| Polish on the README, none in the program | Effort in the wrong place | Put the effort in the interaction | - -## Code tells - -| Tell | Instead | -|---|---| -| Comments that narrate (`// increment counter`) | Comment why, or delete | -| Chat leftovers ("Here's the updated code", "Certainly!") | Delete | -| `TODO`, `unimplemented!()`, placeholder strings | Finish it or cut it | -| `.unwrap()` in non-test code | `?`, or handle the case | -| `let _ = fallible();`, empty `Err(_) => {}` | Handle or report the error | -| Generic names (`data`, `item`, `helper`, `utils.rs`) | Name the thing | -| Hex colors scattered through draw code | Colors by role in `theme.rs` | -| One 1,500-line `main.rs` | Modules that follow the data flow | -| Hallucinated crates or methods | Research, then compile (see the checklist) | -| Boilerplate repeated per widget | One helper, used | - -## README tells - -- Emoji headers, a "Features" list of adjectives ("blazing fast", "beautiful"). -- No real command, no real key list. -- No statement of how it was made. Say plainly if AI helped; one line is enough. -- Claims the code does not back up. +| Comments that merely narrate syntax | Adds maintenance noise | Explain intent, invariants, or non-obvious trade-offs | +| Assistant-style conversational leftovers | Belongs in chat, not source code | Remove it | +| Unfinished `TODO`, `todo!`, or `unimplemented!` paths | May indicate incomplete behavior | Finish, track, or explicitly scope the work | +| `.unwrap()` or `.expect()` in application code | May turn recoverable failures into panics | Use error propagation or document a genuine invariant | +| Broad generic names such as `data` or `helper` | Can hide meaning when used without context | Prefer names that describe the domain or operation | +| A very large `main.rs` | Can obscure responsibilities in a complex app | Split modules when real boundaries improve understanding | +| Many tiny modules or wrappers | Can make simple behavior harder to follow | Keep related code together until a useful boundary appears | +| Hex colors scattered through rendering | Can make visual consistency harder to maintain | Use shared semantic styles when multiple views benefit | +| Repeated widget boilerplate | Can cause drift | Extract a helper when behavior is genuinely shared | +| A generic abstraction used only once | Can hide rather than simplify | Keep the direct implementation until reuse or complexity justifies abstraction | + +These are prompts for inspection, not a ban list. For example, an `unwrap` may be justified after a proven invariant, and a single-file program may be the clearest design for a small utility. + +## Documentation and communication signals + +- Feature lists made mostly of adjectives rather than verifiable behavior. +- Screenshots that do not match the current application. +- No runnable command or no explanation of key interactions when users need them. +- Claims of compatibility or production readiness without corresponding checks. +- Repeated sections that restate the same information. +- Unclear disclosure of generated or AI-assisted work when provenance matters to the project. + +Prefer specific capabilities, real commands, current screenshots, and honest limitations. ## Before and after -```rust -// before: decorative, dishonest -let status = Paragraph::new("● Ready — all systems operational") - .style(Style::new().fg(Color::Rgb(0, 255, 136))); +A status message should report a real state, not decorative confidence: -// after: shows something true, in a themed role, only when there is something to say +```rust if let Some(message) = state.status() { frame.render_widget(Line::styled(message, theme.error), area); } ``` -```rust -// before: invented placeholder -let rows = vec!["Item 1", "Item 2", "Item 3"]; +A collection view should represent actual data and have an honest empty state: -// after: real data, with an honest empty state +```rust if entries.is_empty() { render_empty(frame, area, "empty directory"); } ``` -## Formal anti-slop design standard - -### Prohibited decorative defaults - -Reject unless justified by a real product need: - -- Neon purple/cyan gradients -- Glowing borders -- Decorative banners -- Fake status indicators -- Fake statistics or activity feeds -- Placeholder rows -- Empty panels -- Unnecessary mascots -- Emoji used as generic icons -- Nested borders everywhere -- Excessive separators -- Redundant headings -- Marketing copy inside developer tools -- Unnecessary welcome screens -- Fake loading indicators -- Decorative animations -- Unnecessary badges -- Redundant status labels - -### Information honesty - -Every visible value must be real. No fabricated data, no invented progress, no -misleading success messages, no hardcoded metrics presented as live information. -When there is no data, show an honest empty state. - -### Typography and copy - -- Short, clear labels. -- Consistent terminology. -- Sentence-case labels. -- Concise error messages. -- No unnecessary slogans. -- No assistant-style conversational leftovers. -- No exaggerated marketing adjectives. -- No redundant explanatory text. - -### Product-specific decisions - -The agent must decide what information matters most, what users do most -frequently, what needs immediate attention, and what can be removed. Every -design choice should have a product reason, not a template default. - -### Human review checklist - -- Can a first-time user understand the screen? -- Is the primary content immediately obvious? -- Does every panel contain useful information? -- Does every key binding work? -- Can the interface be used without color? -- Does resizing preserve usability? -- Are empty and error states honest? -- Is the screen too dense or too padded? -- Can any element be removed without losing information? -- Does the UI look like a considered product rather than a generic template? - -A clean lint scan is not proof of design quality. It is a mechanical guardrail. +## Human review checklist + +- Does the implementation satisfy the stated task? +- Are displayed values and status messages truthful? +- Does every documented interaction work? +- Are dependencies and APIs compatible with the project? +- Are errors handled intentionally? +- Is the architecture proportionate to the application's complexity? +- Is the interface readable and useful at the sizes it claims to support? +- Can any decoration, abstraction, module, or instruction be removed without losing value? +- Do tests demonstrate behavior rather than merely mirror implementation details? +- Does the final report distinguish completed checks from unverified work? + +A clean lint scan does not prove design quality. A polished screenshot does not prove behavior. Review the implementation and the evidence together. diff --git a/skills/ratatui/references/ux-principles.md b/skills/ratatui/references/ux-principles.md index b439fe4..56922fe 100644 --- a/skills/ratatui/references/ux-principles.md +++ b/skills/ratatui/references/ux-principles.md @@ -1,215 +1,145 @@ -# TUI design principles +# TUI design guidance -Drawn from lazygit's published design principles (discoverability, simplicity, safety, power, speed) and from terminal design systems that agree on spatial consistency, keyboard-first input, layered color, and a UI that never freezes. Where a rule below is this skill's own judgment rather than something those sources say, it is marked **(judgment)**. +This document contains design heuristics for terminal interfaces, not Ratatui requirements. Product requirements, user expectations, existing project conventions, terminal capabilities, and accessibility needs take precedence. -## Layout - -Pick one archetype and keep it. - -| Archetype | Use when | Example | -|---|---|---| -| List + preview | One collection, details of the selected item | file browser, log viewer | -| Multi-panel | Several related collections the user moves between | lazygit | -| Drill-down | Hierarchy where depth matters, one level at a time | settings, k8s resources | -| Miller columns | Hierarchy where seeing the parents helps | ranger | -| Dashboard | Glanceable live numbers, little input | system monitor | -| Header + list | One collection, nothing else | process picker | -| Popup / overlay | A short question or a help screen over any of the above | confirm, `?` | - -Rules: - -- **A fixed skeleton.** Header, body, footer stay where they are. Panels do not move unless the user asks. -- **Responsive by dropping, not squashing.** Below a width, remove the preview pane; below a minimum size, show "terminal too small" with the needed size. -- **Borders group, whitespace separates.** One border style. No box inside a box. -- **Lists show only the rows on screen** and keep the selection visible with minimal scrolling. - -## Keys - -- **Keyboard complete.** Every action has a key. Mouse is optional; if something looks clickable it must work **(judgment: prefer none over fake)**. -- **Three tiers of discovery:** footer hints for the current mode, `?` overlay for everything, README for the rest. Generate the first two from the keymap so they cannot drift. -- **Vim-style plus arrows** (`j k h l g G`, Ctrl-u/d) unless the domain says otherwise. Keep `/` for filter, `?` for help, `q` and Ctrl-C to quit, Esc to cancel. -- **Never reassign standard keys** to something surprising. -- **Modes are visible.** The footer changes with the mode; a text prompt shows a cursor. -- **Fewest keypresses for the common path.** - -## Color +The examples describe common patterns. Combine, adapt, or ignore them when the application calls for something else. -Design in three layers: +## Classification -1. **Monochrome works.** Bold, dim and reverse carry the meaning. This is also the `NO_COLOR` theme. -2. **16 ANSI colors look right.** They follow the user's terminal palette, so the app fits their setup. -3. **True color is an opt-in extra,** never the only way things are readable. +- **Correctness:** behavior the application must preserve, such as terminal restoration, safe text handling, responsive input, and accurate information. +- **Recommended:** patterns that often improve usability, but have legitimate exceptions. +- **Optional:** visual and interaction choices that depend on the product. -Define colors **by role** (`text`, `muted`, `accent`, `selected`, `error`) in one file. Use one accent. Do not force a background. Neon palettes are a legitimate theme but they are the look people recognize as generated, so make them opt-in **(judgment)**. +Do not turn an optional preference into a hard requirement in a new or existing project. -## Responsiveness - -- Never freeze the UI. Slow work runs elsewhere and reports progress. -- Esc always returns control. -- Startup is fast; do the minimum before the first frame. -- Handle resize without panics, at every size including 1x1. - -## Safety - -- Destructive actions confirm, and the confirmation says what will be lost. -- Show errors with their reason and keep the previous state usable. -- Treat all external text as hostile: strip control characters before drawing. - -## States every screen needs - -| State | Show | -|---|---| -| Empty | Why it is empty and what to do about it | -| Loading | That work is happening, with progress if known | -| Error | The reason, in plain words | -| Too small | The size needed and the size you have | -| No results (filtered) | The filter text, so the user can see why | - -## Semantic design tokens (terminal-native) +## Layout -Tokens are role names, not colors. The theme maps each role to a style. Default -to the 16 ANSI colors so the user's palette applies; monochrome keeps bold, dim -and reverse video. +Choose a layout from the interaction model and the information users need. -### Foreground roles +| Pattern | Often useful when | Example | +|---|---|---| +| List + preview | One collection with details for a selected item | File browser, log viewer | +| Multi-panel | Users move among several related collections | Git client | +| Drill-down | Hierarchical navigation where depth matters | Settings, resource browser | +| Miller columns | Users benefit from seeing hierarchy and parents | File manager | +| Dashboard | Users monitor a small set of changing values | System monitor | +| Header + list | One collection is the main task | Process picker | +| Popup / overlay | A short decision or contextual help belongs above the current screen | Confirmation, help | -- `text.primary`: main content. -- `text.secondary`: supporting information. -- `text.subtle`: metadata, timestamps, hints. -- `text.disabled`: inactive or unavailable items. +### Useful layout heuristics -### Accent +- Keep primary content visually stable when that helps spatial memory; let layouts change when mode or available space requires it. +- Prefer dropping secondary information or panes over compressing important content into unreadable widths. +- Use borders to group related content and whitespace to separate it. Nested borders are a visual choice, not inherently wrong. +- Render only visible rows when rendering the full dataset would be expensive. +- Keep selection visible when navigation depends on it. +- Choose breakpoints from the content's minimum useful dimensions, not from a universal 40/80-column rule. -- `accent.primary`: one restrained accent for the most important emphasis. -- `accent.focus`: focus indicator, usually the same as primary. +## Keyboard and interaction -### Semantic states +Keyboard-first interaction is a strong default for TUIs, but the correct bindings depend on the domain and audience. -- `state.success`: only for genuine success. -- `state.warning`: only for genuine warnings. -- `state.danger`: only for genuine errors or destructive actions. -- `state.info`: only for neutral informational status. +- Make important actions discoverable through context hints, help, documentation, or clear labels. +- Keep key behavior, footer hints, and help text consistent when they share bindings. A shared binding table can help when it reduces duplication. +- Vim-style bindings and arrow keys are both common. Support the conventions appropriate to the application; do not impose one set on every project. +- Preserve familiar terminal conventions when possible, but do not sacrifice a required domain interaction to follow a generic key map. +- Make the current mode or focus visible when it changes how input is interpreted. +- Ensure important functionality is reachable without a mouse when the application is intended to be keyboard-driven. +- Do not advertise a key or control that does nothing. +- Esc is often useful for backing out or cancelling, but its exact behavior should be clear and consistent. -### Selection +A help overlay, footer hints, and mode-specific key tables are useful patterns, not mandatory components for every small utility. -- `selection.foreground` and `selection.background`, or reverse video as a - fallback on terminals without color. +## Color and visual hierarchy -### Borders +Design for the terminal environments the application actually supports. -- `border.default`: normal panel borders. -- `border.subtle`: dividers and separators. -- `border.focus`: focused pane border. +- Do not rely on color alone to communicate an important state. +- Maintain readable contrast and a clear distinction between selected, focused, disabled, and normal content. +- Respect `NO_COLOR` when the application claims to support it. +- A role-based theme can make colors easier to maintain. A single theme module is useful when several components share semantic styles; a smaller app may not need a separate theme abstraction. +- The user's terminal palette, ANSI colors, true color, and monochrome output are all valid choices within the product's compatibility goals. +- One accent color, a restrained palette, and consistent border styles are useful defaults, not universal rules. +- Avoid forced backgrounds when terminal transparency is part of the intended experience. -### Typography roles +## Responsiveness and performance -- `type.title`: screen or panel title. -- `type.section`: section header. -- `type.body`: normal content. -- `type.secondary`: supporting text. -- `type.emphasis`: highlighted inline text. +### Correctness requirements -Terminals do not provide arbitrary font weights. Use bold, dim and normal -intensity only. +- Do not perform unbounded or avoidable blocking work in the draw path when it prevents input or redraws. +- Do not leave the terminal in an unusable state after normal errors or shutdown. +- Handle resize events without panicking in the dimensions the application claims to support. +- Sanitize untrusted text before writing it to the terminal so embedded control sequences cannot manipulate the display. +- Measure strings by terminal display width when alignment or truncation depends on columns. -### Spacing scale (cell units) +### Recommended techniques -- `space.none`: 0 cells. -- `space.xs`: 1 cell. -- `space.sm`: 2 cells. -- `space.md`: 4 cells. -- `space.lg`: 8 cells. +- Keep expensive work bounded, cached, incremental, or off the draw path when measurements or expected workload justify it. +- Preserve useful state across resize when possible. +- Prefer vertical scrolling over horizontal scrolling when it fits the data. +- Show progress for genuinely long-running operations. +- Test small terminal sizes that are relevant to the application. A 1x1 terminal can be a useful stress case, but an application may explicitly define a larger minimum usable size. -Use these consistently. No arbitrary padding values. +Do not introduce async tasks, worker threads, caches, or complex rendering abstractions without a concrete need. -### Layout regions +## States and feedback -- `layout.header`: one row, title and summary. -- `layout.content`: fills remaining space. -- `layout.footer`: one row, hints or prompt. -- `layout.gutter`: 1-2 cells between panes. +Consider which states can actually occur: -### Interaction states +| State | Useful feedback | +|---|---| +| Empty | Explain why there is no content and what action is available | +| Loading | Indicate that work is in progress; show progress when it is known | +| Error | Give a useful reason and a recovery path | +| No filter results | Make the active filter visible and explain that nothing matched | +| Too small | Explain the minimum useful dimensions when the layout cannot work | +| Success | Confirm meaningful operations without inventing status | -- `interaction.normal`: default. -- `interaction.focused`: has keyboard focus. -- `interaction.selected`: currently selected item. -- `interaction.disabled`: cannot be acted on. +Not every screen needs every state. Do not add loading indicators to operations that complete immediately or confirmation messages for actions whose result is already obvious. -Selection and focus must not be confused. A selected item in an unfocused pane -looks different from a focused item. +For destructive actions, use confirmation, undo, trash, or another safeguard proportionate to the consequences. Do not add confirmation to every action. -## Visual hierarchy rules +## Architecture and design tokens -1. Primary content dominates. Metadata is subtle. -2. One accent color. Secondary information is dim, not a second color. -3. Borders group; whitespace separates. One border style. -4. No box inside a box. -5. No forced background. Terminal transparency survives. -6. Color is never the only signal. Bold, dim and reverse carry meaning. -7. Every visible element earns its place. If it can be removed without losing - information, remove it. +A small style struct, a theme module, or semantic role names can all work. Choose the smallest approach that avoids duplicated or inconsistent styling. -## Terminal-native geometry +Semantic roles such as `text.primary`, `text.secondary`, `accent`, `state.error`, `selection`, and `border.focus` can clarify intent in larger interfaces. They do not require a formal design-token framework. -- The cell is the unit. Everything is measured in columns and rows. -- Measure text with `unicode-width`. CJK characters occupy two cells. -- Truncate with an ellipsis, never clip silently. -- Below the minimum size, show a message with the required and actual dimensions. -- Drop secondary panes instead of crushing everything. -- Prefer vertical scrolling over horizontal scrolling. +Likewise, spacing scales and named layout regions can improve consistency when a project has many screens. Do not force a fixed spacing scale, token taxonomy, or module structure onto a small application. ## Component patterns -### Header - -One row. Title on the left, summary on the right. No border. - -### Footer - -One row. Contextual key hints that change with mode. Filter prompt shows a -cursor. Status messages use `text.subtle` for success, `state.danger` for errors. - -### List row - -Checkbox or icon, then text, then optional metadata right-aligned. Truncate the -text, never the metadata. - -### Selected row - -Reverse video or a distinct background. Must be visible in monochrome. - -### Focused pane - -Border changes from `border.default` to `border.focus`. Only one pane is focused -at a time. - -### Help overlay - -Generated from the keymap. Shows all bindings grouped by mode. Closes with Esc, -? or q. Must fit or scroll at 40x8. - -### Empty state - -Say why it is empty and what to do. Centered, muted. - -### Error state +These are starting points, not recipes: -Show the reason in plain words. Keep the previous state usable. +- **Header:** useful for a title, current location, or summary. Omit it if it duplicates information. +- **Footer:** useful for contextual shortcuts or status. Keep it compact. +- **List row:** emphasize the primary label; include metadata only when it helps a decision. +- **Selected item:** use a treatment visible in the application's supported color modes. +- **Focused pane:** distinguish focus from selection when both concepts exist. +- **Help view:** list the actions relevant to the current interaction model. +- **Empty state:** explain the absence of content and the next useful action. +- **Error state:** preserve context and provide a useful recovery path when possible. +- **Confirmation:** name the consequences and avoid making the destructive action the default. -### Too-small state +## Motion -Show required and actual dimensions. Centered. +Motion is optional in terminal interfaces. -### Confirmation prompt +- Never let decorative animation delay input. +- Animate only when it communicates meaningful progress or state. +- Keep important information available without animation. +- Prefer stable, readable output over movement added only for novelty. -Name what will be lost. Offer y/n or the specific keys. Never default to -destructive. +## Review questions -## Motion principles +- Is the primary task clear? +- Does the layout reflect the actual information and interaction model? +- Are important actions discoverable and functional? +- Can users distinguish focus, selection, and status? +- Does the application behave well at its supported terminal sizes? +- Are errors useful and is recovery possible? +- Is color used appropriately for the supported terminals? +- Does every panel or indicator provide useful information? +- Is any complexity or decoration present only because a template suggested it? -- No animation that delays keyboard input. -- No decorative movement. -- Use animation only to communicate real state or progress. -- Provide stable non-animated behavior. -- A static interface with excellent hierarchy beats a noisy animated one. +A deliberate interface is one in which each decision has a reason. It does not have to look like any single visual system. diff --git a/skills/ratatui/scripts/crate-versions.sh b/skills/ratatui/scripts/crate-versions.sh index 5a65e5a..9dcc18d 100755 --- a/skills/ratatui/scripts/crate-versions.sh +++ b/skills/ratatui/scripts/crate-versions.sh @@ -13,35 +13,56 @@ if [[ -n "$manifest" && ! -f "$manifest" ]]; then exit 2 fi +metadata="" +if [[ -n "$manifest" ]]; then + if ! metadata="$(cargo metadata --format-version 1 --manifest-path "$manifest")"; then + printf 'cargo metadata failed for %s:\n%s\n' "$manifest" "$metadata" >&2 + exit 1 + fi +fi + failed=0 for crate in "$@"; do if ! info="$(cargo info "$crate" 2>&1)"; then - printf '%s: cargo info failed\n' "$crate" >&2 + printf '%s: cargo info failed:\n%s\n' "$crate" "$info" >&2 failed=$((failed + 1)) continue fi + latest="$(printf '%s\n' "$info" | sed -n 's/^version: *//p' | head -1)" msrv="$(printf '%s\n' "$info" | sed -n 's/^rust-version: *//p' | head -1)" if [[ -z "$latest" ]]; then - printf '%s: no version in cargo info output\n' "$crate" >&2 + printf '%s: no version found in cargo info output\n' "$crate" >&2 failed=$((failed + 1)) continue fi project="not checked" if [[ -n "$manifest" ]]; then - if tree="$(cargo tree --manifest-path "$manifest" -i "$crate" --depth 0 2>/dev/null)"; then - project="$(printf '%s\n' "$tree" | sed -nE 's/.* v([0-9][^ ]*).*/\1/p' | sort -u | paste -sd ',' -)" - [[ -n "$project" ]] || project="not resolved" - else - project="not a direct or resolved dependency" + if ! project="$(printf '%s\n' "$metadata" | python3 -c ' +import json +import sys + +crate = sys.argv[1] +data = json.load(sys.stdin) +resolved = {node["id"] for node in (data.get("resolve") or {}).get("nodes", [])} +versions = sorted({ + package["version"] + for package in data["packages"] + if package["id"] in resolved and package["name"] == crate +}) +print(",".join(versions) if versions else "not in resolved dependency graph") +' "$crate")"; then + printf '%s: failed to inspect resolved Cargo metadata\n' "$crate" >&2 + failed=$((failed + 1)) + continue fi fi - printf '%-20s latest=%-12s project=%-24s rust-version=%s\n' "$crate" "$latest" "$project" "${msrv:-not declared}" + printf '%-20s latest=%-12s project=%-32s rust-version=%s\n' "$crate" "$latest" "$project" "${msrv:-not declared}" done if [[ "$failed" -gt 0 ]]; then - printf '%s crate(s) unresolved\n' "$failed" >&2 + printf '%s crate(s) could not be inspected\n' "$failed" >&2 exit 1 fi diff --git a/skills/ratatui/scripts/lint-slop.sh b/skills/ratatui/scripts/lint-slop.sh index 373be80..d61e3ef 100755 --- a/skills/ratatui/scripts/lint-slop.sh +++ b/skills/ratatui/scripts/lint-slop.sh @@ -2,7 +2,7 @@ set -euo pipefail if [[ "${1:-}" == "--help" || "${1:-}" == "-h" ]]; then - printf '%s\n' "usage: lint-slop.sh [PROJECT_DIR]" "Scans Rust source and README conventions; Clippy owns compiler-visible lints." + printf '%s\n' "usage: lint-slop.sh [PROJECT_DIR]" "Runs heuristic source-style checks; compiler-visible lints belong in Clippy." exit 0 fi @@ -15,21 +15,26 @@ import re import sys root = pathlib.Path(sys.argv[1]).resolve() +excluded = {".git", "target"} files = sorted( - p for p in root.rglob("*.rs") - if not any(part in {"target", "tests", "examples"} for part in p.parts) + path + for path in root.rglob("*.rs") + if not excluded.intersection(path.relative_to(root).parts) + and "tests" not in path.relative_to(root).parts ) rules = [ - ("colors only in theme.rs", re.compile(r"Color::(?:Rgb|Indexed|Red|Green|Blue|Cyan|Yellow|Magenta|White|Black|Gray|DarkGray|Light[A-Za-z]+)\b|Color::from_u32"), lambda p: p.name != "theme.rs"), - ("no emoji in source", re.compile(r"[\U0001F300-\U0001FAFF\u2600-\u27BF\u2B50\u2B55]"), lambda p: True), - ("no unwrap outside tests", re.compile(r"\.unwrap\(\)"), lambda p: True), - ("no placeholders", re.compile(r"\b(?:TODO|FIXME|XXX|HACK)\b|todo!\(|unimplemented!\(|(?i:lorem ipsum|placeholder)"), lambda p: True), - ("no swallowed errors", re.compile(r"let\s+_\s*=\s*[^;]*(?:Result|Option|try_|read|write|remove_|send|recv)[^;]*;|\.ok\(\);|Err\(_\)\s*=>\s*\{\}"), lambda p: True), - ("no debug leftovers", re.compile(r"dbg!\(|eprintln!\(|println!\("), lambda p: True), - ("no chat artifacts", re.compile(r"(?i)as an ai|here is the|here's the|let me know|certainly!|i hope this"), lambda p: True), - ("no marketing in strings", re.compile(r'(?i)"[^"]*\b(?:blazing|lightning|supercharge|next-gen|powered by)\b[^"]*"'), lambda p: True), - ("every key binding is documented", re.compile(r'(?:help|label):\s*""'), lambda p: True), + ( + "colors are defined in theme modules", + re.compile(r"Color::(?:Rgb|Indexed|Red|Green|Blue|Cyan|Yellow|Magenta|White|Black|Gray|DarkGray|Light[A-Za-z]+)\b|Color::from_u32"), + lambda path: path.name != "theme.rs", + ), + ( + "key labels and help text are non-empty", + re.compile(r"(?:label|help):\s*\x22\x22"), + lambda path: True, + ), ] + failed = 0 for name, pattern, include in rules: hits = [] @@ -40,33 +45,9 @@ for name, pattern, include in rules: lines = path.read_text(encoding="utf-8").splitlines() except UnicodeDecodeError: continue - number = 0 - while number < len(lines): - line = lines[number] - if line.strip() == "#[cfg(test)]": - item = number + 1 - while item < len(lines) and not lines[item].strip(): - item += 1 - if item < len(lines) and lines[item].lstrip().startswith("mod ") and "{" in lines[item]: - depth = 0 - while item < len(lines): - depth += lines[item].count("{") - lines[item].count("}") - item += 1 - if depth <= 0: - break - number = item - continue - number = min(item + 1, len(lines)) - continue + for number, line in enumerate(lines, 1): if pattern.search(line): - if name == "no debug leftovers" and "allow print" in line: - number += 1 - continue - if name == "no debug leftovers" and 'println!("{USAGE}")' in line: - number += 1 - continue - hits.append(f"{path.relative_to(root)}:{number + 1}: {line.strip()}") - number += 1 + hits.append(f"{path.relative_to(root)}:{number}: {line.strip()}") if hits: failed += 1 print(f"FAIL {name} ({len(hits)})") @@ -80,7 +61,11 @@ for name, pattern, include in rules: readme = root / "README.md" if readme.is_file(): emoji = re.compile(r"[\U0001F300-\U0001FAFF\u2600-\u27BF\u2B50\u2B55]") - hits = [(n, line) for n, line in enumerate(readme.read_text(encoding="utf-8").splitlines()[:20], 1) if line.startswith("#") and emoji.search(line)] + hits = [ + (number, line) + for number, line in enumerate(readme.read_text(encoding="utf-8").splitlines()[:20], 1) + if line.startswith("#") and emoji.search(line) + ] if hits: failed += 1 print("FAIL README has no emoji headers") @@ -92,6 +77,6 @@ else: print("skip README not present") print() -print("clean" if failed == 0 else f"{failed} rule(s) failed") +print("clean" if failed == 0 else f"{failed} heuristic rule(s) failed") sys.exit(failed) PY diff --git a/skills/ratatui/scripts/test_lint_slop.py b/skills/ratatui/scripts/test_lint_slop.py new file mode 100644 index 0000000..5be5cf0 --- /dev/null +++ b/skills/ratatui/scripts/test_lint_slop.py @@ -0,0 +1,72 @@ +import pathlib +import subprocess +import tempfile +import unittest + + +SCRIPT = pathlib.Path(__file__).with_name("lint-slop.sh") + + +class LintSlopTests(unittest.TestCase): + def run_scanner(self, root): + return subprocess.run( + ["bash", str(SCRIPT), str(root)], + capture_output=True, + text=True, + check=False, + ) + + def test_project_root_named_tests_is_scanned(self): + with tempfile.TemporaryDirectory() as temporary: + root = pathlib.Path(temporary) / "tests" + source = root / "src" / "main.rs" + source.parent.mkdir(parents=True) + source.write_text("let color = Color::Rgb(1, 2, 3);\n") + result = self.run_scanner(root) + self.assertEqual(result.returncode, 1) + self.assertIn("colors are defined", result.stdout) + + def test_target_directory_is_excluded_relative_to_project_root(self): + with tempfile.TemporaryDirectory() as temporary: + root = pathlib.Path(temporary) / "project" + (root / "target").mkdir(parents=True) + (root / "src").mkdir() + (root / "target" / "generated.rs").write_text("let color = Color::Rgb(1, 2, 3);\n") + (root / "src" / "main.rs").write_text("fn main() {}\n") + result = self.run_scanner(root) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + + def test_nested_test_target_is_not_treated_as_production_source(self): + with tempfile.TemporaryDirectory() as temporary: + root = pathlib.Path(temporary) / "project" + (root / "tests").mkdir(parents=True) + (root / "src").mkdir() + (root / "tests" / "render.rs").write_text("let color = Color::Rgb(1, 2, 3);\\n") + (root / "src" / "main.rs").write_text("fn main() {}\\n") + result = self.run_scanner(root) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + + def test_test_module_cannot_hide_later_production_source(self): + with tempfile.TemporaryDirectory() as temporary: + root = pathlib.Path(temporary) / "project" + root.mkdir() + source = root / "main.rs" + source.write_text( + '#[cfg(test)]\nmod tests {\n const BRACE: &str = "}";\n}\n' + 'fn production() { let color = Color::Rgb(1, 2, 3); }\n' + ) + result = self.run_scanner(root) + self.assertEqual(result.returncode, 1) + self.assertIn("production()", result.stdout) + + def test_theme_module_may_define_colors(self): + with tempfile.TemporaryDirectory() as temporary: + root = pathlib.Path(temporary) / "project" + root.mkdir() + (root / "theme.rs").write_text("let color = Color::Rgb(1, 2, 3);\n") + result = self.run_scanner(root) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + + +if __name__ == "__main__": + unittest.main() diff --git a/skills/ratatui/templates/dirview/README.md b/skills/ratatui/templates/dirview/README.md index c196896..17863cb 100644 --- a/skills/ratatui/templates/dirview/README.md +++ b/skills/ratatui/templates/dirview/README.md @@ -1,6 +1,6 @@ # dirview -A small directory browser. It is the reference template for the `ratatui` skill: copy its structure, replace its domain. +A small directory browser and reference implementation. Borrow the parts that fit your application; its architecture is not a requirement for other Ratatui projects. cargo run -- [DIR] @@ -18,7 +18,7 @@ Press `?` inside for the full key list. | `s` | Cycle sort: name, size, modified | | `q`, Ctrl-c | Quit | -The preview pane appears at 80 columns or wider. Below 40x8 it shows a size message instead of the interface. Setting `NO_COLOR` switches to a monochrome theme. +The preview pane appears at 80 columns or wider. Below 40x8 it shows a size message instead of the interface. Setting `NO_COLOR` switches to a monochrome theme. Directory previews run on a background worker, cancel when the selection changes, and do not block key handling. Listing the current directory on navigation is still synchronous. ## Layout diff --git a/skills/ratatui/templates/dirview/src/app.rs b/skills/ratatui/templates/dirview/src/app.rs index 769aa24..977f509 100644 --- a/skills/ratatui/templates/dirview/src/app.rs +++ b/skills/ratatui/templates/dirview/src/app.rs @@ -28,6 +28,7 @@ impl App { pub fn run(mut self, terminal: &mut DefaultTerminal) -> io::Result<()> { while !self.state.should_quit() { + self.state.poll_preview(); terminal.draw(|frame| ui::render(frame, &self.state, &mut self.view, &self.theme))?; // The view measured the list; tell the state so paging matches. @@ -38,11 +39,12 @@ impl App { if let Some(action) = event::next_action(self.state.mode())? { if self.state.mode() == crate::state::Mode::Help { + let page_size = self.view.help_page_size().max(1) as isize; match action { Action::HelpScrollUp => self.view.scroll_help(-1), Action::HelpScrollDown => self.view.scroll_help(1), - Action::HelpPageUp => self.view.scroll_help(-8), - Action::HelpPageDown => self.view.scroll_help(8), + Action::HelpPageUp => self.view.scroll_help(-page_size), + Action::HelpPageDown => self.view.scroll_help(page_size), _ => self.state.update(action), } } else { diff --git a/skills/ratatui/templates/dirview/src/event.rs b/skills/ratatui/templates/dirview/src/event.rs index 22355ef..484a078 100644 --- a/skills/ratatui/templates/dirview/src/event.rs +++ b/skills/ratatui/templates/dirview/src/event.rs @@ -1,6 +1,7 @@ //! Terminal input, translated into actions. use std::io; +use std::time::Duration; use ratatui::crossterm::event::{self, Event}; @@ -11,6 +12,9 @@ use crate::state::Mode; /// Block until the next terminal event. Returns `None` for events that do not /// map to an action (resize, focus, mouse); the caller simply redraws. pub fn next_action(mode: Mode) -> io::Result> { + if !event::poll(Duration::from_millis(50))? { + return Ok(None); + } Ok(match event::read()? { Event::Key(key) => keymap::resolve(mode, key), _ => None, diff --git a/skills/ratatui/templates/dirview/src/fs.rs b/skills/ratatui/templates/dirview/src/fs.rs index 3ad1e88..ad8e280 100644 --- a/skills/ratatui/templates/dirview/src/fs.rs +++ b/skills/ratatui/templates/dirview/src/fs.rs @@ -1,7 +1,9 @@ //! Reading the file system. No terminal types in here. +use std::cmp::Ordering; use std::io::{self, Read}; use std::path::Path; +use std::sync::atomic::{AtomicBool, Ordering as AtomicOrdering}; use std::time::SystemTime; use crate::state::{Entry, EntryKind, Preview}; @@ -45,47 +47,95 @@ fn kind_of(meta: &std::fs::Metadata) -> EntryKind { /// Build the preview for an entry. Never blocks on special files. pub fn preview(path: &Path, kind: EntryKind) -> Preview { + let cancelled = AtomicBool::new(false); + preview_cancellable(path, kind, &cancelled).unwrap_or(Preview::Empty) +} + +pub(crate) fn preview_cancellable( + path: &Path, + kind: EntryKind, + cancelled: &AtomicBool, +) -> Option { + if cancelled.load(AtomicOrdering::Relaxed) { + return None; + } match kind { - EntryKind::Dir => dir_preview(path), - EntryKind::File => file_preview(path), - EntryKind::Other => Preview::Empty, + EntryKind::Dir => dir_preview_cancellable(path, cancelled), + EntryKind::File => Some(file_preview(path)), + EntryKind::Other => Some(Preview::Empty), + } +} + +fn compare_preview_entries(a: &(bool, String, String), b: &(bool, String, String)) -> Ordering { + b.0.cmp(&a.0) + .then_with(|| a.2.cmp(&b.2)) + .then_with(|| a.1.cmp(&b.1)) +} + +fn entry_is_dir(entry: &std::fs::DirEntry) -> io::Result { + let file_type = entry.file_type()?; + if !file_type.is_symlink() { + return Ok(file_type.is_dir()); + } + + match entry.path().metadata() { + Ok(metadata) => Ok(metadata.is_dir()), + Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false), + Err(error) => Err(error), } } +#[cfg(test)] fn dir_preview(path: &Path) -> Preview { + let cancelled = AtomicBool::new(false); + dir_preview_cancellable(path, &cancelled).unwrap_or(Preview::Empty) +} + +fn dir_preview_cancellable(path: &Path, cancelled: &AtomicBool) -> Option { let entries = match std::fs::read_dir(path) { Ok(entries) => entries, - Err(error) => return Preview::Error(error.to_string()), + Err(error) => return Some(Preview::Error(error.to_string())), }; let mut names = Vec::with_capacity(PREVIEW_NAMES); - let mut truncated = false; - for entry in entries.take(PREVIEW_NAMES + 1) { + let mut total = 0usize; + + for entry in entries { + if cancelled.load(AtomicOrdering::Relaxed) { + return None; + } let entry = match entry { Ok(entry) => entry, - Err(error) => return Preview::Error(error.to_string()), + Err(error) => return Some(Preview::Error(error.to_string())), + }; + let is_dir = match entry_is_dir(&entry) { + Ok(is_dir) => is_dir, + Err(error) => return Some(Preview::Error(error.to_string())), }; - if names.len() == PREVIEW_NAMES { - truncated = true; - break; - } let name = entry.file_name().to_string_lossy().into_owned(); - let is_dir = entry.file_type().map(|kind| kind.is_dir()).unwrap_or(false); - names.push((is_dir, name)); + let candidate = (is_dir, name.clone(), name.to_lowercase()); + total = total.saturating_add(1); + + let index = names + .binary_search_by(|current| compare_preview_entries(current, &candidate)) + .unwrap_or_else(|index| index); + if index < PREVIEW_NAMES { + names.insert(index, candidate); + names.truncate(PREVIEW_NAMES); + } } - names.sort_by(|a, b| { - b.0.cmp(&a.0) - .then_with(|| a.1.to_lowercase().cmp(&b.1.to_lowercase())) - }); - let total = names.len() + usize::from(truncated); + let names = names .into_iter() - .map(|(is_dir, name)| if is_dir { format!("{name}/") } else { name }) + .map(|entry| { + if entry.0 { + format!("{}/", entry.1) + } else { + entry.1 + } + }) .collect(); - Preview::Dir { - names, - total, - truncated, - } + + Some(Preview::Dir { names, total }) } fn file_preview(path: &Path) -> Preview { @@ -117,20 +167,66 @@ fn file_preview(path: &Path) -> Preview { #[cfg(test)] mod tests { use super::*; + use std::path::PathBuf; + + struct TempDir(PathBuf); + + impl TempDir { + fn new(name: &str) -> io::Result { + let path = + std::env::temp_dir().join(format!("dirview-preview-{name}-{}", std::process::id())); + if path.exists() { + std::fs::remove_dir_all(&path)?; + } + std::fs::create_dir_all(&path)?; + Ok(Self(path)) + } + } + + impl Drop for TempDir { + fn drop(&mut self) { + let _cleanup = std::fs::remove_dir_all(&self.0); + } + } #[test] - fn directory_preview_is_bounded_and_marks_truncation() -> io::Result<()> { - let root = std::env::temp_dir().join(format!("dirview-preview-{}", std::process::id())); - let _cleanup = std::fs::remove_dir_all(&root); - std::fs::create_dir_all(&root)?; - for index in 0..(PREVIEW_NAMES + 50) { - std::fs::write(root.join(format!("entry-{index:03}")), "")?; + fn directory_preview_keeps_the_sorted_sample_and_exact_total() -> io::Result<()> { + let root = TempDir::new("sorted")?; + for index in (0..PREVIEW_NAMES + 50).rev() { + std::fs::write(root.0.join(format!("entry-{index:03}")), "")?; + } + + match dir_preview(&root.0) { + Preview::Dir { names, total } => { + assert_eq!(names.len(), PREVIEW_NAMES); + assert_eq!(total, PREVIEW_NAMES + 50); + assert_eq!(names.first().map(String::as_str), Some("entry-000")); + assert_eq!(names.last().map(String::as_str), Some("entry-199")); + } + other => panic!("expected directory preview, got {other:?}"), + } + Ok(()) + } + + #[cfg(unix)] + #[test] + fn directory_preview_follows_directory_symlinks() -> io::Result<()> { + use std::os::unix::fs::symlink; + + let root = TempDir::new("symlinks")?; + std::fs::create_dir(root.0.join("target"))?; + std::fs::write(root.0.join("target/inner.txt"), "")?; + symlink(root.0.join("target"), root.0.join("linked"))?; + symlink(root.0.join("missing"), root.0.join("broken"))?; + + match dir_preview(&root.0) { + Preview::Dir { names, total } => { + assert_eq!(total, 3); + assert!(names.contains(&"linked/".to_owned())); + assert!(names.contains(&"broken".to_owned())); + } + other => panic!("expected directory preview, got {other:?}"), } - let preview = dir_preview(&root); - assert!( - matches!(preview, Preview::Dir { names, total, truncated: true } if names.len() == PREVIEW_NAMES && total == PREVIEW_NAMES + 1) - ); - std::fs::remove_dir_all(root)?; Ok(()) } } diff --git a/skills/ratatui/templates/dirview/src/state.rs b/skills/ratatui/templates/dirview/src/state.rs index f99e65a..6ebfdff 100644 --- a/skills/ratatui/templates/dirview/src/state.rs +++ b/skills/ratatui/templates/dirview/src/state.rs @@ -4,6 +4,10 @@ use std::io; use std::path::PathBuf; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering as AtomicOrdering}; +use std::sync::mpsc::{self, Receiver, Sender}; +use std::thread; use std::time::SystemTime; use crate::action::Action; @@ -59,20 +63,44 @@ pub struct Entry { #[derive(Debug, Clone, PartialEq, Eq)] pub enum Preview { Empty, + Loading, Binary, Error(String), - Dir { - names: Vec, - total: usize, - truncated: bool, - }, - Text { - lines: Vec, - truncated: bool, - }, + Dir { names: Vec, total: usize }, + Text { lines: Vec, truncated: bool }, +} + +struct PreviewJob { + request: u64, + path: PathBuf, + kind: EntryKind, + cancelled: Arc, +} + +fn spawn_preview_worker() -> (Sender, Receiver<(u64, Preview)>) { + let (job_tx, job_rx) = mpsc::channel::(); + let (result_tx, result_rx) = mpsc::channel::<(u64, Preview)>(); + + thread::spawn(move || { + while let Ok(job) = job_rx.recv() { + if job.cancelled.load(AtomicOrdering::Relaxed) { + continue; + } + let Some(preview) = fs::preview_cancellable(&job.path, job.kind, &job.cancelled) else { + continue; + }; + if job.cancelled.load(AtomicOrdering::Relaxed) { + continue; + } + if result_tx.send((job.request, preview)).is_err() { + break; + } + } + }); + + (job_tx, result_rx) } -#[derive(Debug)] pub struct State { dir: PathBuf, entries: Vec, @@ -85,6 +113,10 @@ pub struct State { show_hidden: bool, sort: SortKey, preview: Preview, + preview_tx: Sender, + preview_rx: Receiver<(u64, Preview)>, + preview_cancel: Option>, + preview_request: u64, status: Option, page_size: usize, quit: bool, @@ -94,6 +126,7 @@ impl State { pub fn open(dir: PathBuf) -> io::Result { let dir = dir.canonicalize()?; let entries = fs::read_dir(&dir)?; + let (preview_tx, preview_rx) = spawn_preview_worker(); let mut state = Self { dir, entries, @@ -104,6 +137,10 @@ impl State { show_hidden: false, sort: SortKey::Name, preview: Preview::Empty, + preview_tx, + preview_rx, + preview_cancel: None, + preview_request: 0, status: None, page_size: 10, quit: false, @@ -288,10 +325,54 @@ impl State { } fn refresh_preview(&mut self) { - self.preview = match self.selected_entry() { - Some(entry) => fs::preview(&self.dir.join(&entry.name), entry.kind), - None => Preview::Empty, + if let Some(cancelled) = self.preview_cancel.take() { + cancelled.store(true, AtomicOrdering::Relaxed); + } + self.preview_request = self.preview_request.wrapping_add(1); + let request = self.preview_request; + + let Some((path, kind)) = self + .selected_entry() + .map(|entry| (self.dir.join(&entry.name), entry.kind)) + else { + self.preview = Preview::Empty; + return; }; + + let cancelled = Arc::new(AtomicBool::new(false)); + self.preview = Preview::Loading; + self.preview_cancel = Some(cancelled.clone()); + + if self + .preview_tx + .send(PreviewJob { + request, + path, + kind, + cancelled, + }) + .is_err() + { + self.preview = Preview::Error("preview worker stopped".to_owned()); + self.preview_cancel = None; + } + } + + pub fn poll_preview(&mut self) { + while let Ok((request, preview)) = self.preview_rx.try_recv() { + if request == self.preview_request { + self.preview = preview; + self.preview_cancel = None; + } + } + } +} + +impl Drop for State { + fn drop(&mut self) { + if let Some(cancelled) = self.preview_cancel.take() { + cancelled.store(true, AtomicOrdering::Relaxed); + } } } @@ -348,6 +429,17 @@ mod tests { s.visible_entries().map(|e| e.name.as_str()).collect() } + fn wait_for_preview(state: &mut State) -> Result { + for _ in 0..200 { + state.poll_preview(); + if !matches!(state.preview(), Preview::Loading) { + return Ok(()); + } + std::thread::sleep(std::time::Duration::from_millis(5)); + } + Err("preview worker did not finish".into()) + } + #[test] fn dirs_come_first_and_dotfiles_are_hidden() -> Result { let fx = Fixture::new("order")?; @@ -417,6 +509,7 @@ mod tests { let fx = Fixture::new("nav")?; let mut s = fx.state()?; s.update(Action::Enter); + wait_for_preview(&mut s)?; assert_eq!(names(&s), ["inner.txt"]); assert_eq!( s.preview(), @@ -426,6 +519,7 @@ mod tests { } ); s.update(Action::Parent); + wait_for_preview(&mut s)?; assert_eq!(s.selected_entry().map(|e| e.name.as_str()), Some("Alpha")); Ok(()) } @@ -455,6 +549,30 @@ mod tests { Ok(()) } + #[test] + fn large_directory_preview_runs_in_the_background() -> Result { + let fx = Fixture::new("async-preview")?; + let large = fx.0.join("large"); + std::fs::create_dir(&large)?; + for index in 0..50_000 { + std::fs::write(large.join(format!("entry-{index:05}")), b"")?; + } + + let mut state = fx.state()?; + state.update(Action::MoveDown); + assert!(matches!(state.preview(), Preview::Loading)); + wait_for_preview(&mut state)?; + + match state.preview() { + Preview::Dir { names, total } => { + assert_eq!(*total, 50_000); + assert_eq!(names.len(), 200); + } + other => panic!("expected completed directory preview, got {other:?}"), + } + Ok(()) + } + #[test] fn missing_directory_is_an_error_not_a_panic() { assert!(State::open(PathBuf::from("/definitely/not/here")).is_err()); diff --git a/skills/ratatui/templates/dirview/src/ui/help.rs b/skills/ratatui/templates/dirview/src/ui/help.rs index 13bb2c6..4a1a3d8 100644 --- a/skills/ratatui/templates/dirview/src/ui/help.rs +++ b/skills/ratatui/templates/dirview/src/ui/help.rs @@ -6,59 +6,78 @@ use ratatui::text::{Line, Span}; use ratatui::widgets::{Block, BorderType, Clear, Paragraph}; use super::text::width; +use crate::action::Action; use crate::keymap::{self, Binding}; use crate::state::Mode; use crate::theme::Theme; -const KEY_COLUMN: usize = 16; const MAX_WIDTH: u16 = 58; -pub fn render(frame: &mut Frame, area: Rect, theme: &Theme, offset: usize) { - let mut lines = vec![Line::styled("Browse", theme.title)]; - lines.extend(keymap::bindings(Mode::Normal).iter().map(|b| row(b, theme))); - lines.push(Line::raw("")); - lines.push(Line::styled("While filtering", theme.title)); - lines.extend(keymap::bindings(Mode::Filter).iter().map(|b| row(b, theme))); +pub fn render(frame: &mut Frame, area: Rect, theme: &Theme, offset: &mut usize) -> usize { + let sections = [ + ("Browse", Mode::Normal), + ("While filtering", Mode::Filter), + ("Help", Mode::Help), + ]; + let key_column = sections + .iter() + .flat_map(|(_, mode)| keymap::bindings(*mode)) + .map(|binding| width(binding.label)) + .max() + .unwrap_or(0) + + 2; + + let mut lines = Vec::new(); + for (index, (title, mode)) in sections.iter().enumerate() { + if index > 0 { + lines.push(Line::raw("")); + } + lines.push(Line::styled(*title, theme.title)); + lines.extend( + keymap::bindings(*mode) + .iter() + .map(|binding| row(binding, theme, key_column)), + ); + } let max_height = area.height.saturating_sub(2).max(4); let content_height = u16::try_from(lines.len()).unwrap_or(u16::MAX); let height = content_height.saturating_add(2).min(max_height); let popup = centered(area, MAX_WIDTH.min(area.width), height); + let page_size = popup.height.saturating_sub(2).max(1) as usize; + let max_offset = lines.len().saturating_sub(page_size); + *offset = (*offset).min(max_offset); - // When the content does not fit, drop the least important lines and show - // a scroll hint instead of silently clipping. - let inner_height = height.saturating_sub(2) as usize; - let truncated = lines.len() > inner_height; - if truncated { - lines.truncate(inner_height.saturating_sub(1)); - lines.push(Line::styled(" ... (resize for more)", theme.muted)); - } - + let close_hint = keymap::bindings(Mode::Help) + .iter() + .find(|binding| binding.action == Action::ToggleHelp) + .and_then(|binding| binding.hint); let mut block = Block::bordered() .border_type(BorderType::Rounded) .border_style(theme.border_focus) .title(Line::styled(" Keys ", theme.title)); - if let Some(hint) = keymap::bindings(Mode::Help).iter().find_map(|b| b.hint) { - let close = format!(" {} {} ", hint.keys, hint.text); - block = block.title_bottom(Line::styled(close, theme.muted)); + if let Some(hint) = close_hint { + block = block.title_bottom(Line::styled( + format!(" {} {} ", hint.keys, hint.text), + theme.muted, + )); } + frame.render_widget(Clear, popup); - let max_offset = lines - .len() - .saturating_sub(popup.height.saturating_sub(2) as usize); - let offset = offset.min(max_offset); frame.render_widget( Paragraph::new(lines) - .scroll((u16::try_from(offset).unwrap_or(u16::MAX), 0)) + .scroll((u16::try_from(*offset).unwrap_or(u16::MAX), 0)) .block(block), popup, ); + page_size } -fn row(binding: &Binding, theme: &Theme) -> Line<'static> { - let pad = KEY_COLUMN.saturating_sub(width(binding.label)); +fn row(binding: &Binding, theme: &Theme, key_column: usize) -> Line<'static> { + let label = format!(" {}", binding.label); + let pad = key_column.saturating_sub(width(&label)); Line::from(vec![ - Span::styled(format!(" {}", binding.label), theme.accent), + Span::styled(label, theme.accent), Span::raw(" ".repeat(pad)), Span::styled(binding.help, theme.text), ]) diff --git a/skills/ratatui/templates/dirview/src/ui/mod.rs b/skills/ratatui/templates/dirview/src/ui/mod.rs index be2fc9c..73a29a7 100644 --- a/skills/ratatui/templates/dirview/src/ui/mod.rs +++ b/skills/ratatui/templates/dirview/src/ui/mod.rs @@ -31,6 +31,7 @@ pub struct ViewState { offset: usize, rows: usize, help_offset: usize, + help_page_size: usize, } impl ViewState { @@ -43,6 +44,10 @@ impl ViewState { self.help_offset } + pub fn help_page_size(&self) -> usize { + self.help_page_size + } + pub fn scroll_help(&mut self, amount: isize) { self.help_offset = self.help_offset.saturating_add_signed(amount); } @@ -51,6 +56,7 @@ impl ViewState { pub fn render(frame: &mut Frame, state: &State, view: &mut ViewState, theme: &Theme) { let area = frame.area(); if area.width < MIN_WIDTH || area.height < MIN_HEIGHT { + view.help_page_size = 0; render_too_small(frame, theme); return; } @@ -76,9 +82,11 @@ pub fn render(frame: &mut Frame, state: &State, view: &mut ViewState, theme: &Th footer::render(frame, footer.inner(margin), state, theme); - if state.mode() == Mode::Help { - help::render(frame, area, theme, view.help_offset()); - } + view.help_page_size = if state.mode() == Mode::Help { + help::render(frame, area, theme, &mut view.help_offset) + } else { + 0 + }; } fn render_header(frame: &mut Frame, area: Rect, state: &State, theme: &Theme) { diff --git a/skills/ratatui/templates/dirview/src/ui/preview.rs b/skills/ratatui/templates/dirview/src/ui/preview.rs index c923518..ade3c5d 100644 --- a/skills/ratatui/templates/dirview/src/ui/preview.rs +++ b/skills/ratatui/templates/dirview/src/ui/preview.rs @@ -32,25 +32,25 @@ pub fn render(frame: &mut Frame, area: Rect, state: &State, theme: &Theme) { lines.push(Line::raw("")); match state.preview() { Preview::Empty => {} + Preview::Loading => lines.push(Line::styled("loading preview…", theme.muted)), Preview::Binary => lines.push(Line::styled("binary file", theme.muted)), Preview::Error(message) => { lines.push(Line::styled(sanitize(message).into_owned(), theme.error)); } - Preview::Dir { - names, - total: _, - truncated, - } => { - lines.extend(names.iter().map(|n| { - let style = if n.ends_with('/') { + Preview::Dir { names, total } => { + lines.extend(names.iter().map(|name| { + let style = if name.ends_with('/') { theme.accent } else { theme.text }; - Line::styled(sanitize(n).into_owned(), style) + Line::styled(sanitize(name).into_owned(), style) })); - if *truncated { - lines.push(Line::styled("\u{2026} more entries", theme.muted)); + if *total > names.len() { + lines.push(Line::styled( + format!("… {} more entries", total - names.len()), + theme.muted, + )); } } Preview::Text { @@ -69,18 +69,7 @@ pub fn render(frame: &mut Frame, area: Rect, state: &State, theme: &Theme) { fn meta(entry: &Entry, preview: &Preview) -> String { match (entry.kind, preview) { - ( - EntryKind::Dir, - Preview::Dir { - total, truncated, .. - }, - ) => { - if *truncated { - format!("{}+ items", total - 1) - } else { - format!("{total} items") - } - } + (EntryKind::Dir, Preview::Dir { total, .. }) => format!("{total} items"), (EntryKind::Dir, _) => "directory".to_owned(), (EntryKind::File, _) => { let modified = entry diff --git a/skills/ratatui/templates/dirview/tests/render.rs b/skills/ratatui/templates/dirview/tests/render.rs index 2cb30fe..b313e71 100644 --- a/skills/ratatui/templates/dirview/tests/render.rs +++ b/skills/ratatui/templates/dirview/tests/render.rs @@ -33,6 +33,17 @@ impl Drop for Fixture { } } +fn wait_for_preview(state: &mut State) -> Result { + for _ in 0..200 { + state.poll_preview(); + if !matches!(state.preview(), dirview::state::Preview::Loading) { + return Ok(()); + } + std::thread::sleep(std::time::Duration::from_millis(5)); + } + Err("preview worker did not finish".into()) +} + fn screen( state: &State, width: u16, @@ -50,6 +61,7 @@ fn wide_layout_shows_list_and_preview() -> Result { let fx = Fixture::new("wide")?; let mut state = State::open(fx.0.clone())?; state.update(Action::MoveDown); + wait_for_preview(&mut state)?; let text = screen(&state, 100, 20)?; assert!(text.contains("docs/"), "{text}"); assert!(text.contains("notes.txt"), "{text}"); @@ -66,6 +78,7 @@ fn text_file_preview_is_shown() -> Result { for c in "notes".chars() { state.update(Action::FilterInput(c)); } + wait_for_preview(&mut state)?; let text = screen(&state, 100, 20)?; assert!(text.contains("first line"), "{text}"); assert!(text.contains("1 of 4 match"), "{text}"); @@ -77,6 +90,7 @@ fn binary_file_is_not_dumped() -> Result { let fx = Fixture::new("binary")?; let mut state = State::open(fx.0.clone())?; state.update(Action::MoveDown); + wait_for_preview(&mut state)?; let text = screen(&state, 100, 20)?; assert!(text.contains("binary file"), "{text}"); Ok(()) @@ -133,12 +147,48 @@ fn help_overlay_lists_the_real_keys() -> Result { let mut state = State::open(fx.0.clone())?; state.update(Action::ToggleHelp); let text = screen(&state, 100, 40)?; - for expected in ["Keys", "Filter by name", "Cycle sort", "Quit", "Esc close"] { + for expected in [ + "Keys", + "Filter by name", + "Cycle sort", + "Quit", + "Scroll one page down", + "Scroll one page up", + "Esc close", + ] { assert!(text.contains(expected), "missing {expected:?}\n{text}"); } Ok(()) } +#[test] +fn help_scroll_clamps_and_uses_the_visible_page_size() -> Result { + let fx = Fixture::new("help-scroll")?; + let mut state = State::open(fx.0.clone())?; + state.update(Action::ToggleHelp); + let mut terminal = Terminal::new(TestBackend::new(40, 8))?; + let mut view = ViewState::default(); + let theme = Theme::mono(); + + terminal.draw(|frame| ui::render(frame, &state, &mut view, &theme))?; + let page_size = view.help_page_size(); + assert!(page_size > 0); + + view.scroll_help(isize::MAX); + terminal.draw(|frame| ui::render(frame, &state, &mut view, &theme))?; + let end = view.help_offset(); + assert!(end > 0); + + view.scroll_help(-1); + terminal.draw(|frame| ui::render(frame, &state, &mut view, &theme))?; + assert_eq!(view.help_offset(), end - 1); + + view.scroll_help(-(page_size as isize)); + terminal.draw(|frame| ui::render(frame, &state, &mut view, &theme))?; + assert!(view.help_offset() < end - 1); + Ok(()) +} + #[test] fn wide_characters_do_not_break_alignment() -> Result { let fx = Fixture::new("cjk")?; diff --git a/tapes/dirview.tape b/tapes/dirview.tape new file mode 100644 index 0000000..da26b04 --- /dev/null +++ b/tapes/dirview.tape @@ -0,0 +1,47 @@ +Output target/betamax/dirview.gif +Output target/betamax/dirview.png +Output target/betamax/dirview.json + +Require cargo + +Set Shell "bash" +Set Width 1200 +Set Height 650 +Set WindowBar Colorful +Set BorderRadius 8 +Set TypingSpeed 20ms +Set CursorBlink false +Set WaitTimeout 30s + +Hide +Type@0ms "cd \"$BETAMAX_WORKING_DIRECTORY\" && mkdir -p target/betamax" +Enter +Wait +Show + +Type@0ms "./target/debug/dirview ." +Enter +Wait+Screen "items" +Screenshot target/betamax/dirview-list.png +State target/betamax/dirview-list.json +Sleep 500ms + +Type "?" +Wait+Screen "Browse" +Type "jjjjjjj" +Wait+Screen "Scroll down" +Screenshot target/betamax/dirview-help.png +State target/betamax/dirview-help.json +Sleep 500ms + +Escape +Wait+Screen "items" +Resize 50 16 +Wait+Screen "items" +Screenshot target/betamax/dirview-narrow.png +State target/betamax/dirview-narrow.json +Resize 120 40 +Wait+Screen "items" +Type "q" +Enter +Wait \ No newline at end of file