diff --git a/.agents/skills/code-review/SKILL.md b/.agents/skills/code-review/SKILL.md new file mode 100644 index 0000000..373a4f2 --- /dev/null +++ b/.agents/skills/code-review/SKILL.md @@ -0,0 +1,89 @@ +--- +name: code-review +description: "Review the changes since a fixed point (commit, branch, tag, or merge-base) along two axes: Standards (does the code follow this repo's documented coding standards?) and Spec (does the code match what the originating issue/spec asked for?). Runs both reviews in parallel sub-agents and reports them side by side. Use when the user wants to review a branch, a PR, work-in-progress changes, or asks to \"review since X\"." +--- + +Two-axis review of the diff between `HEAD` and a fixed point the user supplies: + +- **Standards**: does the code conform to this repo's documented coding standards? +- **Spec**: does the code faithfully implement the originating issue / spec? + +Both axes run as **parallel sub-agents** so they don't pollute each other's context, then this skill aggregates their findings. + +The issue tracker should have been provided to you. If not, tell the user to run `/setup-matt-pocock-skills`. + +## Process + +### 1. Pin the fixed point + +Whatever the user said is the fixed point (a commit SHA, branch name, tag, `main`, `HEAD~5`, etc.). If they didn't specify one, ask for it. + +Capture the diff command once: `git diff ...HEAD` (three-dot, so the comparison is against the merge-base). Also note the list of commits via `git log ..HEAD --oneline`. + +Before going further, confirm the fixed point resolves (`git rev-parse `) and the diff is non-empty. A bad ref or empty diff should fail here, not inside two parallel sub-agents. + +### 2. Identify the spec source + +Look for the originating spec, in this order: + +1. Issue references in the commit messages (`#123`, `Closes #45`, GitLab `!67`, etc.), fetched via the workflow in the tracker doc. +2. A path the user passed as an argument. +3. A spec file under `docs/`, `specs/`, or `.scratch/` matching the branch name or feature. +4. If nothing is found, ask the user where the spec is. If they say there isn't one, the **Spec** sub-agent will skip and report "no spec available". + +### 3. Identify the standards sources + +Search the repo for every file that documents how code should be written. When `CODING_STANDARDS.md` or `CONTRIBUTING.md` exists, it must be on the list. + +On top of whatever the repo documents, the Standards axis always carries the **smell baseline** below: a fixed set of Fowler code smells (_Refactoring_, ch.3) that applies even when a repo documents nothing. Two rules bind it: + +- **The repo overrides.** A documented repo standard always wins; where it endorses something the baseline would flag, suppress the smell. +- **Always a judgement call.** Each smell is a labelled heuristic ("possible Feature Envy"), never a hard violation. Like any standard here, skip anything tooling already enforces. + +Each smell reads *what it is* → *how to fix*; match it against the diff: + +- **Mysterious Name**: a function, variable, or type whose name doesn't reveal what it does or holds. → rename it; if no honest name comes, the design's murky. +- **Duplicated Code**: the same logic shape appears in more than one hunk or file in the change. → extract the shared shape, call it from both. +- **Feature Envy**: a method that reaches into another object's data more than its own. → move the method onto the data it envies. +- **Data Clumps**: the same few fields or params keep travelling together (a type wanting to be born). → bundle them into one type, pass that. +- **Primitive Obsession**: a primitive or string standing in for a domain concept that deserves its own type. → give the concept its own small type. +- **Repeated Switches**: the same `switch`/`if`-cascade on the same type recurs across the change. → replace with polymorphism, or one map both sites share. +- **Shotgun Surgery**: one logical change forces scattered edits across many files in the diff. → gather what changes together into one module. +- **Divergent Change**: one file or module is edited for several unrelated reasons. → split so each module changes for one reason. +- **Speculative Generality**: abstraction, parameters, or hooks added for needs the spec doesn't have. → delete it; inline back until a real need shows. +- **Message Chains**: long `a.b().c().d()` navigation the caller shouldn't depend on. → hide the walk behind one method on the first object. +- **Middle Man**: a class or function that mostly just delegates onward. → cut it, call the real target direct. +- **Refused Bequest**: a subclass or implementer that ignores or overrides most of what it inherits. → drop the inheritance, use composition. + +### 4. Spawn both sub-agents in parallel + +Issue both sub-agent calls together, in the foreground, and aggregate the reports they return. + +**Standards sub-agent prompt** should include: + +- The full diff command and commit list. +- The list of standards-source files you found in step 3, **plus the smell baseline from step 3** pasted in full (the sub-agent has no other access to it). +- The brief: "Report, per file/hunk where relevant, (a) every place the diff violates a documented standard: cite the standard (file + the rule); and (b) any baseline smell you spot: name it and quote the hunk. Distinguish hard violations from judgement calls: documented-standard breaches can be hard, but baseline smells are always judgement calls, and a documented repo standard overrides the baseline. Skip anything tooling enforces. Under 400 words." + +**Spec sub-agent prompt** should include: + +- The diff command and commit list. +- The path or fetched contents of the spec. +- The brief: "Report: (a) requirements the spec asked for that are missing or partial; (b) behaviour in the diff that wasn't asked for (scope creep); (c) requirements that look implemented but where the implementation looks wrong. Quote the spec line for each finding. Under 400 words." + +If the spec is missing, skip the Spec sub-agent and note this in the final report. + +### 5. Aggregate + +Present the two reports under `## Standards` and `## Spec` headings, verbatim or lightly cleaned. Do **not** merge or rerank findings, because the two axes are deliberately separate (see _Why two axes_). + +End with a one-line summary: total findings per axis, and the worst issue _within each axis_ (if any). Don't pick a single winner across axes: that's the reranking the separation exists to prevent. + +## Why two axes + +A change can pass one axis and fail the other: + +- Code that follows every standard but implements the wrong thing → **Standards pass, Spec fail.** +- Code that does exactly what the issue asked but breaks the project's conventions → **Spec pass, Standards fail.** + +Reporting them separately stops one axis from masking the other. diff --git a/.agents/skills/code-review/agents/openai.yaml b/.agents/skills/code-review/agents/openai.yaml new file mode 100644 index 0000000..9076774 --- /dev/null +++ b/.agents/skills/code-review/agents/openai.yaml @@ -0,0 +1,3 @@ +interface: + display_name: "Code Review" + short_description: "Review a diff on standards and spec" diff --git a/.agents/skills/codebase-design/DEEPENING.md b/.agents/skills/codebase-design/DEEPENING.md new file mode 100644 index 0000000..cd94075 --- /dev/null +++ b/.agents/skills/codebase-design/DEEPENING.md @@ -0,0 +1,37 @@ +# Deepening + +How to deepen a cluster of shallow modules safely, given its dependencies. Assumes the vocabulary in [SKILL.md](SKILL.md): **module**, **interface**, **seam**, **adapter**. + +## Dependency categories + +When assessing a candidate for deepening, classify its dependencies. The category determines how the deepened module is tested across its seam. + +### 1. In-process + +Pure computation, in-memory state, no I/O. Always deepenable: merge the modules and test through the new interface directly. No adapter needed. + +### 2. Local-substitutable + +Dependencies that have local test stand-ins (PGLite for Postgres, in-memory filesystem). Deepenable if the stand-in exists. The deepened module is tested with the stand-in running in the test suite. The seam is internal; no port at the module's external interface. + +### 3. Remote but owned (Ports & Adapters) + +Your own services across a network boundary (microservices, internal APIs). Define a **port** (interface) at the seam. The deep module owns the logic; the transport is injected as an **adapter**. Tests use an in-memory adapter. Production uses an HTTP/gRPC/queue adapter. + +Recommendation shape: *"Define a port at the seam, implement an HTTP adapter for production and an in-memory adapter for testing, so the logic sits in one deep module even though it's deployed across a network."* + +### 4. True external (Mock) + +Third-party services (Stripe, Twilio, etc.) you don't control. The deepened module takes the external dependency as an injected port; tests provide a mock adapter. + +## Seam discipline + +- **One adapter means a hypothetical seam. Two adapters means a real one.** Don't introduce a port unless at least two adapters are justified (typically production + test). A single-adapter seam is just indirection. +- **Internal seams vs external seams.** A deep module can have internal seams (private to its implementation, used by its own tests) as well as the external seam at its interface. Don't expose internal seams through the interface just because tests use them. + +## Testing strategy: replace, don't layer + +- Old unit tests on shallow modules become waste once tests at the deepened module's interface exist; delete them. +- Write new tests at the deepened module's interface. The **interface is the test surface**. +- Tests assert on observable outcomes through the interface, not internal state. +- Tests should survive internal refactors, since they describe behaviour, not implementation. If a test has to change when the implementation changes, it's testing past the interface. diff --git a/.agents/skills/codebase-design/DESIGN-IT-TWICE.md b/.agents/skills/codebase-design/DESIGN-IT-TWICE.md new file mode 100644 index 0000000..d099013 --- /dev/null +++ b/.agents/skills/codebase-design/DESIGN-IT-TWICE.md @@ -0,0 +1,44 @@ +# Design It Twice + +When the user wants to explore alternative interfaces for a chosen deepening candidate, use this parallel sub-agent pattern. Based on "Design It Twice" (Ousterhout): your first idea is unlikely to be the best. + +Uses the vocabulary in [SKILL.md](SKILL.md): **module**, **interface**, **seam**, **adapter**, **leverage**. + +## Process + +### 1. Frame the problem space + +Before spawning sub-agents, write a user-facing explanation of the problem space for the chosen candidate: + +- The constraints any new interface would need to satisfy +- The dependencies it would rely on, and which category they fall into (see [DEEPENING.md](DEEPENING.md)) +- A rough illustrative code sketch to ground the constraints, not a proposal, just a way to make the constraints concrete + +Show this to the user, then immediately proceed to Step 2. The user reads and thinks while the sub-agents work in parallel. + +### 2. Spawn sub-agents + +Spawn 3+ sub-agents in parallel. Each must produce a **radically different** interface for the deepened module. + +Prompt each sub-agent with a separate technical brief (file paths, coupling details, dependency category from [DEEPENING.md](DEEPENING.md), what sits behind the seam). The brief is independent of the user-facing problem-space explanation in Step 1. Give each agent a different design constraint: + +- Agent 1: "Minimize the interface: aim for 1–3 entry points max. Maximise leverage per entry point." +- Agent 2: "Maximise flexibility: support many use cases and extension." +- Agent 3: "Optimise for the most common caller: make the default case trivial." +- Agent 4 (if applicable): "Design around ports & adapters for cross-seam dependencies." + +Include both [SKILL.md](SKILL.md) vocabulary and GLOSSARY.md vocabulary in the brief so each sub-agent names things consistently with the architecture language and the project's domain language. + +Each sub-agent outputs: + +1. Interface (types, methods, params, plus invariants, ordering, error modes) +2. Usage example showing how callers use it +3. What the implementation hides behind the seam +4. Dependency strategy and adapters (see [DEEPENING.md](DEEPENING.md)) +5. Trade-offs: where leverage is high, where it's thin + +### 3. Present and compare + +Present designs sequentially so the user can absorb each one, then compare them in prose. Contrast by **depth** (leverage at the interface), **locality** (where change concentrates), and **seam placement**. + +After comparing, give your own recommendation: which design you think is strongest and why. If elements from different designs would combine well, propose a hybrid. Be opinionated: the user wants a strong read, not a menu. diff --git a/.agents/skills/codebase-design/SKILL.md b/.agents/skills/codebase-design/SKILL.md new file mode 100644 index 0000000..3f63c81 --- /dev/null +++ b/.agents/skills/codebase-design/SKILL.md @@ -0,0 +1,114 @@ +--- +name: codebase-design +description: Shared vocabulary for designing deep modules. Use when the user wants to design or improve a module's interface, find deepening opportunities, decide where a seam goes, make code more testable or AI-navigable, or when another skill needs the deep-module vocabulary. +--- + +# Codebase Design + +Design **deep modules**: a lot of behaviour behind a small interface, placed at a clean seam, testable through that interface. Use this language and these principles wherever code is being designed or restructured. The aim is leverage for callers, locality for maintainers, and testability for everyone. + +## Glossary + +Use these terms exactly: don't substitute "component," "service," "API," or "boundary." Consistent language is the whole point. + +**Module**: anything with an interface and an implementation. Deliberately scale-agnostic: a function, class, package, or tier-spanning slice. _Avoid_: unit, component, service. + +**Interface**: everything a caller must know to use the module correctly: the type signature, but also invariants, ordering constraints, error modes, required configuration, and performance characteristics. _Avoid_: API, signature (too narrow, they refer only to the type-level surface). + +**Implementation**: what's inside a module, its body of code. Distinct from **Adapter**: a thing can be a small adapter with a large implementation (a Postgres repo) or a large adapter with a small implementation (an in-memory fake). Reach for "adapter" when the seam is the topic; "implementation" otherwise. + +**Depth**: leverage at the interface. The amount of behaviour a caller (or test) can exercise per unit of interface they have to learn. A module is **deep** when a large amount of behaviour sits behind a small interface, **shallow** when the interface is nearly as complex as the implementation. + +**Seam** _(Michael Feathers)_: a place where you can alter behaviour without editing in that place; the *location* at which a module's interface lives. Where to put the seam is its own design decision, distinct from what goes behind it. _Avoid_: boundary (overloaded with DDD's bounded context). + +**Adapter**: a concrete thing that satisfies an interface at a seam. Describes *role* (what slot it fills), not substance (what's inside). + +**Leverage**: what callers get from depth. More capability per unit of interface they learn. One implementation pays back across N call sites and M tests. + +**Locality**: what maintainers get from depth. Change, bugs, knowledge, and verification concentrate in one place rather than spreading across callers. Fix once, fixed everywhere. + +## Deep vs shallow + +**Deep module** = small interface + lots of implementation: + +``` +┌─────────────────────┐ +│ Small Interface │ ← Few methods, simple params +├─────────────────────┤ +│ │ +│ Deep Implementation│ ← Complex logic hidden +│ │ +└─────────────────────┘ +``` + +**Shallow module** = large interface + little implementation (avoid): + +``` +┌─────────────────────────────────┐ +│ Large Interface │ ← Many methods, complex params +├─────────────────────────────────┤ +│ Thin Implementation │ ← Just passes through +└─────────────────────────────────┘ +``` + +When designing an interface, ask: + +- Can I reduce the number of methods? +- Can I simplify the parameters? +- Can I hide more complexity inside? + +## Principles + +- **Depth is a property of the interface, not the implementation.** A deep module can be internally composed of small, mockable, swappable parts; they just aren't part of the interface. A module can have **internal seams** (private to its implementation, used by its own tests) as well as the **external seam** at its interface. +- **The deletion test.** Imagine deleting the module. If complexity vanishes, it was a pass-through. If complexity reappears across N callers, it was earning its keep. +- **The interface is the test surface.** Callers and tests cross the same seam. If you want to test *past* the interface, the module is probably the wrong shape. +- **One adapter means a hypothetical seam. Two adapters means a real one.** Don't introduce a seam unless something actually varies across it. + +## Designing for testability + +Good interfaces make testing natural: + +1. **Accept dependencies, don't create them.** + + ```typescript + // Testable + function processOrder(order, paymentGateway) {} + + // Hard to test + function processOrder(order) { + const gateway = new StripeGateway(); + } + ``` + +2. **Return results, don't produce side effects.** + + ```typescript + // Testable + function calculateDiscount(cart): Discount {} + + // Hard to test + function applyDiscount(cart): void { + cart.total -= discount; + } + ``` + +3. **Small surface area.** Fewer methods = fewer tests needed. Fewer params = simpler test setup. + +## Relationships + +- A **Module** has exactly one **Interface** (the surface it presents to callers and tests). +- **Depth** is a property of a **Module**, measured against its **Interface**. +- A **Seam** is where a **Module**'s **Interface** lives. +- An **Adapter** sits at a **Seam** and satisfies the **Interface**. +- **Depth** produces **Leverage** for callers and **Locality** for maintainers. + +## Rejected framings + +- **Depth as ratio of implementation-lines to interface-lines** (Ousterhout): rewards padding the implementation. We use depth-as-leverage instead. +- **"Interface" as the TypeScript `interface` keyword or a class's public methods**: too narrow: interface here includes every fact a caller must know. +- **"Boundary"**: overloaded with DDD's bounded context. Say **seam** or **interface**. + +## Going deeper + +- **Deepening a cluster given its dependencies**, see [DEEPENING.md](DEEPENING.md): dependency categories, seam discipline, and replace-don't-layer testing. +- **Exploring alternative interfaces**, see [DESIGN-IT-TWICE.md](DESIGN-IT-TWICE.md): spin up parallel sub-agents to design the interface several radically different ways, then compare on depth, locality, and seam placement. diff --git a/.agents/skills/codebase-design/agents/openai.yaml b/.agents/skills/codebase-design/agents/openai.yaml new file mode 100644 index 0000000..3180715 --- /dev/null +++ b/.agents/skills/codebase-design/agents/openai.yaml @@ -0,0 +1,3 @@ +interface: + display_name: "Codebase Design" + short_description: "Vocabulary for deep-module design" diff --git a/.agents/skills/domain-modeling/ADR-FORMAT.md b/.agents/skills/domain-modeling/ADR-FORMAT.md new file mode 100644 index 0000000..d7e61f3 --- /dev/null +++ b/.agents/skills/domain-modeling/ADR-FORMAT.md @@ -0,0 +1,47 @@ +# ADR Format + +ADRs live in `docs/adr/` and use sequential numbering: `0001-slug.md`, `0002-slug.md`, etc. + +Create the `docs/adr/` directory lazily: only when the first ADR is needed. + +## Template + +```md +# {Short title of the decision} + +{1-3 sentences: what's the context, what did we decide, and why.} +``` + +That's it. An ADR can be a single paragraph. The value is in recording *that* a decision was made and *why*, not in filling out sections. + +## Optional sections + +Only include these when they add genuine value. Most ADRs won't need them. + +- **Status** frontmatter (`proposed | accepted | deprecated | superseded by ADR-NNNN`): useful when decisions are revisited +- **Considered Options**: only when the rejected alternatives are worth remembering +- **Consequences**: only when non-obvious downstream effects need to be called out + +## Numbering + +Scan `docs/adr/` for the highest existing number and increment by one. + +## When to offer an ADR + +All three of these must be true: + +1. **Hard to reverse**: the cost of changing your mind later is meaningful +2. **Surprising without context**: a future reader will look at the code and wonder "why on earth did they do it this way?" +3. **The result of a real trade-off**: there were genuine alternatives and you picked one for specific reasons + +If a decision is easy to reverse, skip it: you'll just reverse it. If it's not surprising, nobody will wonder why. If there was no real alternative, there's nothing to record beyond "we did the obvious thing." + +### What qualifies + +- **Architectural shape.** "We're using a monorepo." "The write model is event-sourced, the read model is projected into Postgres." +- **Integration patterns between contexts.** "Ordering and Billing communicate via domain events, not synchronous HTTP." +- **Technology choices that carry lock-in.** Database, message bus, auth provider, deployment target. Not every library: just the ones that would take a quarter to swap out. +- **Boundary and scope decisions.** "Customer data is owned by the Customer context; other contexts reference it by ID only." The explicit no-s are as valuable as the yes-s. +- **Deliberate deviations from the obvious path.** "We're using manual SQL instead of an ORM because X." Anything where a reasonable reader would assume the opposite. These stop the next engineer from "fixing" something that was deliberate. +- **Constraints not visible in the code.** "We can't use AWS because of compliance requirements." "Response times must be under 200ms because of the partner API contract." +- **Rejected alternatives when the rejection is non-obvious.** If you considered GraphQL and picked REST for subtle reasons, record it; otherwise someone will suggest GraphQL again in six months. diff --git a/.agents/skills/domain-modeling/GLOSSARY-FORMAT.md b/.agents/skills/domain-modeling/GLOSSARY-FORMAT.md new file mode 100644 index 0000000..9c0b4c7 --- /dev/null +++ b/.agents/skills/domain-modeling/GLOSSARY-FORMAT.md @@ -0,0 +1,60 @@ +# GLOSSARY.md Format + +## Structure + +```md +# {Context Name} + +{One or two sentence description of what this context is and why it exists.} + +## Language + +**Order**: +{A one or two sentence description of the term} +_Avoid_: Purchase, transaction + +**Invoice**: +A request for payment sent to a customer after delivery. +_Avoid_: Bill, payment request + +**Customer**: +A person or organization that places orders. +_Avoid_: Client, buyer, account +``` + +## Rules + +- **Be opinionated.** When multiple words exist for the same concept, pick the best one and list the others under `_Avoid_`. +- **Keep definitions tight.** One or two sentences max. Define what it IS, not what it does. +- **Only include terms specific to this project's context.** General programming concepts (timeouts, error types, utility patterns) don't belong even if the project uses them extensively. Before adding a term, ask: is this a concept unique to this context, or a general programming concept? Only the former belongs. +- **Group terms under subheadings** when natural clusters emerge. If all terms belong to a single cohesive area, a flat list is fine. + +## Single vs multi-context repos + +**Single context (most repos):** One `GLOSSARY.md` at the repo root. + +**Multiple contexts:** A `GLOSSARY-MAP.md` at the repo root lists the contexts, where they live, and how they relate to each other: + +```md +# Glossary Map + +## Contexts + +- [Ordering](./src/ordering/GLOSSARY.md): receives and tracks customer orders +- [Billing](./src/billing/GLOSSARY.md): generates invoices and processes payments +- [Fulfillment](./src/fulfillment/GLOSSARY.md): manages warehouse picking and shipping + +## Relationships + +- **Ordering → Fulfillment**: Ordering emits `OrderPlaced` events; Fulfillment consumes them to start picking +- **Fulfillment → Billing**: Fulfillment emits `ShipmentDispatched` events; Billing consumes them to generate invoices +- **Ordering ↔ Billing**: Shared types for `CustomerId` and `Money` +``` + +The skill infers which structure applies: + +- If `GLOSSARY-MAP.md` exists, read it to find contexts +- If only a root `GLOSSARY.md` exists, single context +- If neither exists, create a root `GLOSSARY.md` lazily when the first term is resolved + +When multiple contexts exist, infer which one the current topic relates to. If unclear, ask. diff --git a/.agents/skills/domain-modeling/SKILL.md b/.agents/skills/domain-modeling/SKILL.md new file mode 100644 index 0000000..a4438c6 --- /dev/null +++ b/.agents/skills/domain-modeling/SKILL.md @@ -0,0 +1,74 @@ +--- +name: domain-modeling +description: Build and sharpen a project's domain model. Use when discussing codebase terminology, writing or editing a GLOSSARY.md, or recording or editing an ADR. +--- + +# Domain Modeling + +Actively build and sharpen the project's domain model as you design. This is the *active* discipline: challenging terms, inventing edge-case scenarios, and writing the glossary and decisions down the moment they crystallise. (Merely *reading* `GLOSSARY.md` for vocabulary is not this skill: that's a one-line habit any skill can do. This skill is for when you're changing the model, not just consuming it.) + +## File structure + +Most repos have a single context: + +``` +/ +├── GLOSSARY.md +├── docs/ +│ └── adr/ +│ ├── 0001-event-sourced-orders.md +│ └── 0002-postgres-for-write-model.md +└── src/ +``` + +If a `GLOSSARY-MAP.md` exists at the root, the repo has multiple contexts. The map points to where each one lives: + +``` +/ +├── GLOSSARY-MAP.md +├── docs/ +│ └── adr/ ← system-wide decisions +├── src/ +│ ├── ordering/ +│ │ ├── GLOSSARY.md +│ │ └── docs/adr/ ← context-specific decisions +│ └── billing/ +│ ├── GLOSSARY.md +│ └── docs/adr/ +``` + +Create files lazily: only when you have something to write. If no `GLOSSARY.md` exists, create one when the first term is resolved. If no `docs/adr/` exists, create it when the first ADR is needed. + +## During the session + +### Challenge against the glossary + +When the user uses a term that conflicts with the existing language in `GLOSSARY.md`, call it out immediately. "Your glossary defines 'cancellation' as X, but you seem to mean Y. Which is it?" + +### Sharpen fuzzy language + +When the user uses vague or overloaded terms, propose a precise canonical term. "You're saying 'account': do you mean the Customer or the User? Those are different things." + +### Discuss concrete scenarios + +When domain relationships are being discussed, stress-test them with specific scenarios. Invent scenarios that probe edge cases and force the user to be precise about the boundaries between concepts. + +### Cross-reference with code + +When the user states how something works, check whether the code agrees. If you find a contradiction, surface it: "Your code cancels entire Orders, but you just said partial cancellation is possible. Which is right?" + +### Update GLOSSARY.md inline + +When a term is resolved, update `GLOSSARY.md` right there. Don't batch these up: capture them as they happen. Use the format in [GLOSSARY-FORMAT.md](./GLOSSARY-FORMAT.md). + +`GLOSSARY.md` should be totally devoid of implementation details. Do not treat `GLOSSARY.md` as a spec, a scratch pad, or a repository for implementation decisions. It is a glossary and nothing else. + +### Offer ADRs sparingly + +Only offer to create an ADR when all three are true: + +1. **Hard to reverse**: the cost of changing your mind later is meaningful +2. **Surprising without context**: a future reader will wonder "why did they do it this way?" +3. **The result of a real trade-off**: there were genuine alternatives and you picked one for specific reasons + +If any of the three is missing, skip the ADR. Use the format in [ADR-FORMAT.md](./ADR-FORMAT.md). diff --git a/.agents/skills/domain-modeling/agents/openai.yaml b/.agents/skills/domain-modeling/agents/openai.yaml new file mode 100644 index 0000000..7f1522d --- /dev/null +++ b/.agents/skills/domain-modeling/agents/openai.yaml @@ -0,0 +1,3 @@ +interface: + display_name: "Domain Modeling" + short_description: "Build and sharpen a domain model" diff --git a/.agents/skills/grilling/SKILL.md b/.agents/skills/grilling/SKILL.md new file mode 100644 index 0000000..df69d99 --- /dev/null +++ b/.agents/skills/grilling/SKILL.md @@ -0,0 +1,30 @@ +--- +name: grilling +description: Grill the user relentlessly about a plan, decision, or idea. Use when the user wants to stress-test their thinking, or uses any 'grill' trigger phrases. +--- + +Interview the user relentlessly until you reach a shared understanding. Map this as a **design tree**: every decision branches into the decisions that hang off it. + +Work the tree in **rounds**. The **frontier** is every decision whose prerequisites are already settled: the questions you can ask _now_ without guessing at answers you haven't heard yet. Ask the whole frontier in one round: number each question and give your recommended answer. Then wait for the user's answers before the next round. + +Format a round like so: + +``` +❓ **Q1** - ****: + +➡️ + +--- + +❓ **Q2** - ****: + +➡️ +``` + +Word each question so "yes" accepts your recommended answer. + +Each round the user answers reshapes the tree: settled decisions push the frontier outward and unblock questions that depended on them. Recompute the frontier and ask the next round. A question whose answer depends on another question still open in this round belongs to a _later_ round, not this one. + +Finding _facts_ is your job, never the user's. When a frontier question needs a fact from the environment (filesystem, tools, etc.), dispatch a sub-agent to find it; don't ask the user for anything you could look up yourself. Don't block on it: a running exploration is an unsettled prerequisite, so only the questions downstream of it wait for the sub-agent to report; ask the rest of the frontier now. The _decisions_ are the user's: put each to them and wait. + +The session is done when the frontier is empty: every branch of the design tree visited, nothing left silently assumed. Do not act on it until the user confirms you have reached a shared understanding. diff --git a/.agents/skills/grilling/agents/openai.yaml b/.agents/skills/grilling/agents/openai.yaml new file mode 100644 index 0000000..ddbdb96 --- /dev/null +++ b/.agents/skills/grilling/agents/openai.yaml @@ -0,0 +1,3 @@ +interface: + display_name: "Grilling" + short_description: "Stress-test thinking a round of questions at a time" diff --git a/.agents/skills/improve-codebase-architecture/HTML-REPORT.md b/.agents/skills/improve-codebase-architecture/HTML-REPORT.md new file mode 100644 index 0000000..e39e825 --- /dev/null +++ b/.agents/skills/improve-codebase-architecture/HTML-REPORT.md @@ -0,0 +1,123 @@ +# HTML Report Format + +The architectural review is rendered as a single self-contained HTML file in the OS temp directory. Tailwind and Mermaid both come from CDNs. Mermaid handles graph-shaped diagrams reliably; hand-built divs and inline SVG handle the more editorial visuals (mass diagrams, cross-sections). Mix the two: don't lean on Mermaid for everything, it'll start to look generic. + +## Scaffold + +```html + + + + + Architecture review for {{repo name}} + + + + + +
+
...
+
...
+
...
+
+ + +``` + +## Header + +Repo name, date, and a compact legend: solid box = module, dashed line = seam, red arrow = leakage, thick dark box = deep module. No introduction paragraph. Straight into the candidates. + +## Candidate card + +The diagrams carry the weight. Prose is sparse, plain, and uses the glossary terms (from the `/codebase-design` skill) without ceremony. + +Each candidate is one `
`: + +- **Title**: short, names the deepening (e.g. "Collapse the Order intake pipeline"). +- **Badge row**: recommendation strength (`Strong` = emerald, `Worth exploring` = amber, `Speculative` = slate), plus a tag for the dependency category (`in-process`, `local-substitutable`, `ports & adapters`, `mock`). +- **Files**: monospaced list, `font-mono text-sm`. +- **Before / After diagram**: the centrepiece. Two columns, side by side. See patterns below. +- **Problem**: one sentence. What hurts. +- **Solution**: one sentence. What changes. +- **Wins**: bullets, ≤6 words each. e.g. "Tests hit one interface", "Pricing logic stops leaking", "Delete 4 shallow wrappers". +- **ADR callout** (if applicable): one line in an amber-tinted box. + +No paragraphs of explanation. If the diagram needs a paragraph to be understood, redraw the diagram. + +## Diagram patterns + +Pick the pattern that fits the candidate. Mix them. Don't make every diagram look the same. Variety is part of the point. + +### Mermaid graph (the workhorse for dependencies / call flow) + +Use a Mermaid `flowchart` or `graph` when the point is "X calls Y calls Z, and look at the mess." Wrap it in a Tailwind-styled card so it doesn't feel parachuted in. Style with classDef to colour leakage edges red and the deep module dark. Sequence diagrams work well for "before: 6 round-trips; after: 1." + +```html +
+
+    flowchart LR
+      A[OrderHandler] --> B[OrderValidator]
+      B --> C[OrderRepo]
+      C -.leak.-> D[PricingClient]
+      classDef leak stroke:#dc2626,stroke-width:2px;
+      class C,D leak
+  
+
+``` + +### Hand-built boxes-and-arrows (when Mermaid's layout fights you) + +Modules as `
`s with borders and labels. Arrows as inline SVG `` or `` elements positioned absolutely over a relative container. Reach for this when you want the "after" diagram to feel like one thick-bordered deep module with greyed-out internals, since Mermaid won't render that with the right weight. + +### Cross-section (good for layered shallowness) + +Stack horizontal bands (`h-12 border-l-4`) to show layers a call passes through. Before: 6 thin layers each doing nothing. After: 1 thick band labelled with the consolidated responsibility. + +### Mass diagram (good for "interface as wide as implementation") + +Two rectangles per module: one for interface surface area, one for implementation. Before: interface rectangle is nearly as tall as the implementation rectangle (shallow). After: interface rectangle is short, implementation rectangle is tall (deep). + +### Call-graph collapse + +Before: a tree of function calls rendered as nested boxes. After: the same tree collapsed into one box, with the now-internal calls shown faded inside it. + +## Style guidance + +- Lean editorial, not corporate-dashboard. Generous whitespace. Serif optional for headings (`font-serif` works well with stone/slate). +- Colour sparingly: one accent (emerald or indigo) plus red for leakage and amber for warnings. +- Keep diagrams ~320px tall so before/after sits comfortably side by side without scrolling. +- Use `text-xs uppercase tracking-wider` for module labels inside diagrams, so they read as schematic, not as UI. +- The only scripts are the Tailwind CDN and the Mermaid ESM import. The report is otherwise static: no app code, no interactivity beyond Mermaid's own rendering. + +## Top recommendation section + +One larger card. Candidate name, one sentence on why, anchor link to its card. That's it. + +## Tone + +Plain English, concise, but the architectural nouns and verbs come straight from the `/codebase-design` skill. Concision is not an excuse to drift. + +**Use exactly:** module, interface, implementation, depth, deep, shallow, seam, adapter, leverage, locality. + +**Never substitute:** component, service, unit (for module) · API, signature (for interface) · boundary (for seam) · layer, wrapper (for module, when you mean module). + +**Phrasings that fit the style:** + +- "Order intake module is shallow: interface nearly matches the implementation." +- "Pricing leaks across the seam." +- "Deepen: one interface, one place to test." +- "Two adapters justify the seam: HTTP in prod, in-memory in tests." + +**Wins bullets** name the gain in glossary terms: *"locality: bugs concentrate in one module"*, *"leverage: one interface, N call sites"*, *"interface shrinks; implementation absorbs the wrappers"*. Don't write *"easier to maintain"* or *"cleaner code"*, because those terms aren't in the glossary and don't earn their place. + +No hedging, no throat-clearing, no "it's worth noting that…". If a sentence could be a bullet, make it a bullet. If a bullet could be cut, cut it. If a term isn't in the `/codebase-design` glossary, reach for one that is before inventing a new one. diff --git a/.agents/skills/improve-codebase-architecture/SKILL.md b/.agents/skills/improve-codebase-architecture/SKILL.md new file mode 100644 index 0000000..44cc7d3 --- /dev/null +++ b/.agents/skills/improve-codebase-architecture/SKILL.md @@ -0,0 +1,71 @@ +--- +name: improve-codebase-architecture +description: Scan a codebase for deepening opportunities, present them as a visual HTML report, then grill through whichever one you pick. +disable-model-invocation: true +--- + +# Improve Codebase Architecture + +Surface architectural friction and propose **deepening opportunities**: refactors that turn shallow modules into deep ones. The aim is testability and AI-navigability. + +This command is _informed_ by the project's domain model and built on a shared design vocabulary: + +- Call the Skill tool with "codebase-design" for the architecture vocabulary (**module**, **interface**, **depth**, **seam**, **adapter**, **leverage**, **locality**) and its principles (the deletion test, "the interface is the test surface", "one adapter = hypothetical seam, two = real"). Use these terms exactly in every suggestion, and don't drift into "component," "service," "API," or "boundary." +- The domain language in `GLOSSARY.md` gives names to good seams; ADRs in `docs/adr/` record decisions this command should not re-litigate. + +## Process + +### 1. Explore + +**Scope before you scan: YAGNI.** Deepening a module pays off by making future changes to it easier, so put extra weight on the parts of the codebase that have recently changed. Decide *where* to look before you look: + +- If the user named a direction (a module, a subsystem, a pain point), take it, and skip the inference below. +- Otherwise, walk back a good stretch of the commit history (`git log --oneline`) to find the codebase's hot spots, the files and areas that keep coming up, and let those paths pull your attention first. If the changes are scattered with no clear hot spot, widen the net. + +Read the project's domain glossary (`GLOSSARY.md`) and any ADRs in the area you're touching first. + +Then spawn a sub-agent to walk the codebase. Don't follow rigid heuristics; explore organically and note where you experience friction: + +- Where does understanding one concept require bouncing between many small modules? +- Where are modules **shallow**, with an interface nearly as complex as the implementation? +- Where have pure functions been extracted just for testability, but the real bugs hide in how they're called (no **locality**)? +- Where do tightly-coupled modules leak across their seams? +- Which parts of the codebase are untested, or hard to test through their current interface? + +Apply the **deletion test** to anything you suspect is shallow: would deleting it concentrate complexity, or just move it? A "yes, concentrates" is the signal you want. + +### 2. Present candidates as an HTML report + +Write a self-contained HTML file to the OS temp directory so nothing lands in the repo. Resolve the temp dir from `$TMPDIR`, falling back to `/tmp` (or `%TEMP%` on Windows), and write to `/architecture-review-.html` so each run gets a fresh file. Open it for the user (`xdg-open ` on Linux, `open ` on macOS, `start ` on Windows) and tell them the absolute path. + +The report uses **Tailwind via CDN** for layout and styling, and **Mermaid via CDN** for diagrams where a graph/flow/sequence reliably communicates the structure. Mix Mermaid with hand-crafted CSS/SVG visuals: use Mermaid when relationships are graph-shaped (call graphs, dependencies, sequences), and hand-built divs/SVG when you want something more editorial (mass diagrams, cross-sections, collapse animations). Each candidate gets a **before/after visualisation**. Be visual. + +For each candidate, render a card with: + +- **Files**: which files/modules are involved +- **Problem**: why the current architecture is causing friction +- **Solution**: plain English description of what would change +- **Benefits**: explained in terms of locality and leverage, and how tests would improve +- **Before / After diagram**: side-by-side, custom-drawn, illustrating the shallowness and the deepening +- **Recommendation strength**: one of `Strong`, `Worth exploring`, `Speculative`, rendered as a badge + +End the report with a **Top recommendation** section: which candidate you'd tackle first and why. + +**Use GLOSSARY.md vocabulary for the domain, and the `/codebase-design` vocabulary for the architecture.** If `GLOSSARY.md` defines "Order," talk about "the Order intake module," not "the FooBarHandler," and not "the Order service." + +**ADR conflicts**: if a candidate contradicts an existing ADR, only surface it when the friction is real enough to warrant revisiting the ADR. Mark it clearly in the card (e.g. a warning callout: _"contradicts ADR-0007, but worth reopening because…"_). Don't list every theoretical refactor an ADR forbids. + +See [HTML-REPORT.md](HTML-REPORT.md) for the full HTML scaffold, diagram patterns, and styling guidance. + +Do NOT propose interfaces yet. After the file is written, ask the user: "Which of these would you like to explore?" + +### 3. Grilling loop + +Once the user picks a candidate, call the Skill tool with "grilling" to walk the decision tree with them: constraints, dependencies, the shape of the deepened module, what sits behind the seam, what tests survive. + +Side effects happen inline as decisions crystallize; call the Skill tool with "domain-modeling" to keep the domain model current as you go: + +- **Naming a deepened module after a concept not in `GLOSSARY.md`?** Add the term to `GLOSSARY.md`. Create the file lazily if it doesn't exist. +- **Sharpening a fuzzy term during the conversation?** Update `GLOSSARY.md` right there. +- **User rejects the candidate with a load-bearing reason?** Offer an ADR, framed as: _"Want me to record this as an ADR so future architecture reviews don't re-suggest it?"_ Only offer when the reason would actually be needed by a future explorer to avoid re-suggesting the same thing; skip ephemeral reasons ("not worth it right now") and self-evident ones. +- **Want to explore alternative interfaces for the deepened module?** Call the Skill tool with "codebase-design" and use its design-it-twice parallel sub-agent pattern. diff --git a/.agents/skills/improve-codebase-architecture/agents/openai.yaml b/.agents/skills/improve-codebase-architecture/agents/openai.yaml new file mode 100644 index 0000000..706fdca --- /dev/null +++ b/.agents/skills/improve-codebase-architecture/agents/openai.yaml @@ -0,0 +1,5 @@ +interface: + display_name: "Improve Codebase Architecture" + short_description: "Find and grill architecture improvements" +policy: + allow_implicit_invocation: false diff --git a/.agents/skills/pre-merge-review/SKILL.md b/.agents/skills/pre-merge-review/SKILL.md new file mode 100644 index 0000000..76447b6 --- /dev/null +++ b/.agents/skills/pre-merge-review/SKILL.md @@ -0,0 +1,24 @@ +--- +name: pre-merge-review +description: Use after opening a PR that changes behavior, safety, or module boundaries and before merging it. +user-invocable: false +metadata: + internal: true +--- + +# Pre-merge review + +In step 2, “this file” means the repository's `AGENTS.md`. + +1. Prefer CodeRabbit. `.coderabbit.yaml` makes it review only PRs labelled `needs-review`, and + not again on later pushes, because the plan allows about one review an hour. Push first, then + add the label (`gh pr edit N --add-label needs-review`) once the PR is ready, and confirm it + reviewed the current HEAD commit (the `wait-for-action` skill with `--coderabbit`; without + the label its status reads `Review skipped`, which is not a review). After fixing findings, comment `@coderabbitai review` to + review the new commits, if the hour allows. +2. If CodeRabbit is unavailable or rate-limited, run a local review in a fresh + context: a reviewer agent that did not write the change, given the diff, this file, + `DESIGN.md`, `GLOSSARY.md`, and the originating bead. The author's own pass does not + count. + +Verify each finding against the code; fix what is valid and say why the rest were skipped. diff --git a/.agents/skills/research/SKILL.md b/.agents/skills/research/SKILL.md new file mode 100644 index 0000000..fecee97 --- /dev/null +++ b/.agents/skills/research/SKILL.md @@ -0,0 +1,12 @@ +--- +name: research +description: Investigate a question against high-trust primary sources and capture the findings as a Markdown file in the repo. Use when the user wants a topic researched, docs or API facts gathered, or reading legwork delegated to a background agent. +--- + +Spin up a **background agent** to do the research, so you keep working while it reads. + +Its job: + +1. Investigate the question against **primary sources** (official docs, source code, specs, first-party APIs), not a secondary write-up of them. Follow every claim back to the source that owns it. +2. Write the findings to a single Markdown file, citing each claim's source. +3. Save it where the repo already keeps such notes; match the existing convention, and if there is none, put it somewhere sensible and say where. diff --git a/.agents/skills/research/agents/openai.yaml b/.agents/skills/research/agents/openai.yaml new file mode 100644 index 0000000..e18b96c --- /dev/null +++ b/.agents/skills/research/agents/openai.yaml @@ -0,0 +1,3 @@ +interface: + display_name: "Research" + short_description: "Research from high-trust sources" diff --git a/.agents/skills/tdd/SKILL.md b/.agents/skills/tdd/SKILL.md new file mode 100644 index 0000000..01eadaa --- /dev/null +++ b/.agents/skills/tdd/SKILL.md @@ -0,0 +1,38 @@ +--- +name: tdd +description: Test-driven development. Use when the user wants to build features or fix bugs test-first, mentions "red-green-refactor", or wants integration tests. +--- + +# Test-Driven Development + +TDD is the red → green loop. This skill is the reference that makes that loop produce tests worth keeping: what a good test is, where tests go, the anti-patterns, and the rules of the loop. Every section applies on every cycle: consult them before and during the loop, not after. + +When exploring the codebase, read `GLOSSARY.md` (if it exists) so test names and interface vocabulary match the project's domain language, and respect ADRs in the area you're touching. + +## What a good test is + +Tests verify behavior through public interfaces, not implementation details. Code can change entirely; tests shouldn't. A good test reads like a specification: "user can checkout with valid cart" tells you exactly what capability exists, and it survives refactors because it doesn't care about internal structure. + +See [tests.md](tests.md) for examples and [mocking.md](mocking.md) for mocking guidelines. + +## Seams: where tests go + +A **seam** is the public boundary you test at: the interface where you observe behavior without reaching inside. Tests live at seams, never against internals. + +**Test only at pre-agreed seams.** Before writing any test, write down the seams under test and confirm them with the user. No test is written at an unconfirmed seam. You can't test everything, so agreeing the seams up front is how testing effort lands on the critical paths and complex logic instead of every edge case. + +Ask: "What's the public interface, and which seams should we test?" Give each proposed seam a one-line note on what it catches and what it misses. + +When the shape of that interface is itself in question (how deep the module is, where the seam belongs, what the interface should expose), call the Skill tool with "codebase-design" for the vocabulary. It is the shared source of the module, interface, depth, seam, adapter, leverage and locality terms, and it is a reference to consult, not a session to run. + +## Anti-patterns + +- **Implementation-coupled**: mocks internal collaborators, tests private methods, or verifies through a side channel (querying the database instead of using the interface). The tell: the test breaks when you refactor but behavior hasn't changed. +- **Tautological**: the assertion recomputes the expected value the way the code does (`expect(add(a, b)).toBe(a + b)`, a snapshot derived by hand the same way, a constant asserted equal to itself), so it passes by construction and can never disagree with the code. Expected values must come from an independent source of truth: a known-good literal, a worked example, the spec. +- **Horizontal slicing**: writing all tests first, then all implementation. Bulk tests verify _imagined_ behavior: you test the _shape_ of things rather than user-facing behavior, the tests go insensitive to real changes, and you commit to test structure before understanding the implementation. Work in **vertical slices** instead: one test → one implementation → repeat, each test a **tracer bullet** that responds to what the last cycle taught you. + +## Rules of the loop + +- **Red before green.** Write the failing test first, then only enough code to pass it. Don't anticipate future tests or add speculative features. +- **One slice at a time.** One seam, one test, one minimal implementation per cycle. +- **Refactoring is not part of the loop.** It belongs to the review stage (see the `code-review` skill), not the red → green implementation cycle. diff --git a/.agents/skills/tdd/agents/openai.yaml b/.agents/skills/tdd/agents/openai.yaml new file mode 100644 index 0000000..651b838 --- /dev/null +++ b/.agents/skills/tdd/agents/openai.yaml @@ -0,0 +1,3 @@ +interface: + display_name: "TDD" + short_description: "Test-driven red-green-refactor" diff --git a/.agents/skills/tdd/mocking.md b/.agents/skills/tdd/mocking.md new file mode 100644 index 0000000..71cbfee --- /dev/null +++ b/.agents/skills/tdd/mocking.md @@ -0,0 +1,59 @@ +# When to Mock + +Mock at **system boundaries** only: + +- External APIs (payment, email, etc.) +- Databases (sometimes - prefer test DB) +- Time/randomness +- File system (sometimes) + +Don't mock: + +- Your own classes/modules +- Internal collaborators +- Anything you control + +## Designing for Mockability + +At system boundaries, design interfaces that are easy to mock: + +**1. Use dependency injection** + +Pass external dependencies in rather than creating them internally: + +```typescript +// Easy to mock +function processPayment(order, paymentClient) { + return paymentClient.charge(order.total); +} + +// Hard to mock +function processPayment(order) { + const client = new StripeClient(process.env.STRIPE_KEY); + return client.charge(order.total); +} +``` + +**2. Prefer SDK-style interfaces over generic fetchers** + +Create specific functions for each external operation instead of one generic function with conditional logic: + +```typescript +// GOOD: Each function is independently mockable +const api = { + getUser: (id) => fetch(`/users/${id}`), + getOrders: (userId) => fetch(`/users/${userId}/orders`), + createOrder: (data) => fetch('/orders', { method: 'POST', body: data }), +}; + +// BAD: Mocking requires conditional logic inside the mock +const api = { + fetch: (endpoint, options) => fetch(endpoint, options), +}; +``` + +The SDK approach means: +- Each mock returns one specific shape +- No conditional logic in test setup +- Easier to see which endpoints a test exercises +- Type safety per endpoint diff --git a/.agents/skills/tdd/tests.md b/.agents/skills/tdd/tests.md new file mode 100644 index 0000000..7ab8647 --- /dev/null +++ b/.agents/skills/tdd/tests.md @@ -0,0 +1,77 @@ +# Good and Bad Tests + +## Good Tests + +**Integration-style**: Test through real interfaces, not mocks of internal parts. + +```typescript +// GOOD: Tests observable behavior +test("user can checkout with valid cart", async () => { + const cart = createCart(); + cart.add(product); + const result = await checkout(cart, paymentMethod); + expect(result.status).toBe("confirmed"); +}); +``` + +Characteristics: + +- Tests behavior users/callers care about +- Uses public API only +- Survives internal refactors +- Describes WHAT, not HOW +- One logical assertion per test + +## Bad Tests + +**Implementation-detail tests**: Coupled to internal structure. + +```typescript +// BAD: Tests implementation details +test("checkout calls paymentService.process", async () => { + const mockPayment = jest.mock(paymentService); + await checkout(cart, payment); + expect(mockPayment.process).toHaveBeenCalledWith(cart.total); +}); +``` + +Red flags: + +- Mocking internal collaborators +- Testing private methods +- Asserting on call counts/order +- Test breaks when refactoring without behavior change +- Test name describes HOW not WHAT +- Verifying through external means instead of interface + +```typescript +// BAD: Bypasses interface to verify +test("createUser saves to database", async () => { + await createUser({ name: "Alice" }); + const row = await db.query("SELECT * FROM users WHERE name = ?", ["Alice"]); + expect(row).toBeDefined(); +}); + +// GOOD: Verifies through interface +test("createUser makes user retrievable", async () => { + const user = await createUser({ name: "Alice" }); + const retrieved = await getUser(user.id); + expect(retrieved.name).toBe("Alice"); +}); +``` + +**Tautological tests**: Expected value restates the implementation, so the test passes by construction. + +```typescript +// BAD: Expected value is recomputed the way the code computes it +test("calculateTotal sums line items", () => { + const items = [{ price: 10 }, { price: 5 }]; + const expected = items.reduce((sum, i) => sum + i.price, 0); + expect(calculateTotal(items)).toBe(expected); +}); + +// GOOD: Expected value is an independent, known literal +test("calculateTotal sums line items", () => { + expect(calculateTotal([{ price: 10 }, { price: 5 }])).toBe(15); +}); +``` diff --git a/.agents/skills/writing-for-agents/SKILL-MECHANICS.md b/.agents/skills/writing-for-agents/SKILL-MECHANICS.md new file mode 100644 index 0000000..9cdbdb2 --- /dev/null +++ b/.agents/skills/writing-for-agents/SKILL-MECHANICS.md @@ -0,0 +1,22 @@ +# Skill mechanics + +The skill-specific branch of [`writing-for-agents`](SKILL.md): what changes when the document is a skill (frontmatter, the invocation choice, and router skills). Everything else about writing it is the universal reference in `SKILL.md`. + +## Invocation + +Two choices, trading the two loads: + +- A **model-invoked** skill keeps a `description`, so the agent can fire it autonomously, and other skills can reach it. You can still type its name: model-invocation always _includes_ user reach; a description only ever adds agent discovery, never removes the human's. The description is the skill's top-level context pointer, forced to stay loaded at all times: permanent context load in exchange for discoverability. A model-invoked skill whose content is all reference is also one home for shared reference: another skill can invoke it, so reference needed by several skills lives in one place. Mechanics: omit `disable-model-invocation`, and write a model-facing description carrying the trigger branches (the pointer-writing rules in `SKILL.md` apply in full). +- A **user-invoked** skill strips the description from the agent's reach: only the human typing its name can invoke it, and no other skill can. Zero context load, but it spends cognitive load: you are the index that must remember it exists. Mechanics: set `disable-model-invocation: true`; the `description` becomes human-facing: a one-line summary, trigger lists stripped. + +Pick model-invocation only when the agent must reach the skill on its own, or another skill must. If it only ever fires by hand, make it user-invoked and pay no context load. + +Shared reference that two user-invoked skills both need can live in neither: with no descriptions, neither can fire the other. Push it to a plain file outside the skill system: external reference any skill can point at. + +## Splitting by invocation + +The invocation cut of splitting (the sequence cut lives in `SKILL.md`): split off a model-invoked skill when you have a distinct leading word that should trigger it on its own (a trigger word you actually use in your prompts), or another skill must reach it. You pay context load for the new always-loaded description, so that independent reach has to be worth it. + +## Router skills + +When user-invoked skills multiply past what you can remember, that piled-up cognitive load is cured by a **router skill**: one user-invoked skill that names the others and when to reach for each, so the human has one skill to remember instead of many. It can only hint, never fire them: user-invoked skills have no description, so nothing but the human can reach them. diff --git a/.agents/skills/writing-for-agents/SKILL.md b/.agents/skills/writing-for-agents/SKILL.md new file mode 100644 index 0000000..a37608d --- /dev/null +++ b/.agents/skills/writing-for-agents/SKILL.md @@ -0,0 +1,81 @@ +--- +name: writing-for-agents +description: Writing documents for agents. Use when creating or editing skills, or modifying AGENTS.md or CLAUDE.md. +--- + +Reference for writing any document an agent consumes: a skill, an `AGENTS.md` / `CLAUDE.md`, a doc reached by a pointer. The packaging differs; the writing does not: the same levers make each one predictable, since the agent takes the same _process_ every run rather than producing the same output. + +When the document you're writing is a skill, read [`SKILL-MECHANICS.md`](SKILL-MECHANICS.md) for frontmatter, invocation choice, and router skills. + +## Context pointers + +A **context pointer** is a reference held in the agent's context that names some out-of-context material and encodes the condition for reaching it. A skill's description is one; a line in `AGENTS.md` naming a doc is the same object. The pointer's _wording_, not its target, decides when the agent reaches the material, and how reliably. A must-have target behind a weakly worded pointer is a variance bug: sharpen the wording first, and inline the material only if sharpening fails. + +A pointer does two jobs: state what the material is, and list the **branches** that should trigger reaching it (a branch is a distinct case the document handles, so different runs take different paths through it). Every word of an always-loaded pointer costs on every turn, so it earns even harder pruning than the body: + +- **Front-load the leading word**: the pointer is where it does its triggering work. +- **One trigger per branch.** Synonyms that rename a single branch are one branch written twice; collapse them and keep only genuinely distinct branches. +- **Cut identity the body already carries.** + +## The two loads + +Every document and pointer you add spends one of two budgets: + +- **Context load** is the cost of always-loaded material on the agent's window: an `AGENTS.md` line, a skill description, anything sitting in context every turn, spending tokens and attention whether or not it fires. +- **Cognitive load** is the cost on the human: which documents exist and when to reach for each. The human is the index. Not a cost to minimise: it is the price of human agency; spend it where human judgement matters, remove it where it does not. + +Material reached only through a pointer escapes context load at the price of the pointer's own line; material with no pointer at all rides entirely on cognitive load. + +## Information hierarchy + +A document is built from two content types: **steps** (the ordered actions the agent performs) and **reference** (definitions, rules, facts consulted on demand). The two mix freely: all steps (a recipe), all reference (a review's rules, this skill), or both. The core decision is where each piece sits on the **information hierarchy**, a ladder ranked by how immediately the agent needs the material: + +1. **In-file step** is the primary tier: what the agent does, in order. +2. **In-file reference** is consulted on demand. Often a legitimately flat peer-set (every rule of a review on one rung), which is a fine arrangement, not a smell. +3. **Disclosed reference** is pushed out into a separate file, reached by a context pointer, loaded only when the pointer fires. Spans a sibling file in the same folder through fully external reference that lives anywhere and any document can point at. + +Push too little down and the top bloats; push too much and you hide material the agent actually needs. That tension is the whole decision. + +**Progressive disclosure** is the move down the ladder (out of the main file and behind a pointer) so the top stays legible. Not primarily a token optimisation: it is how the hierarchy is protected. Branching is the cleanest disclosure test: inline what every branch needs, and push behind a pointer what only some branches reach. When a document has steps, in-file reference that should be disclosed buries them and turns attending to them into a coin-flip: a variance lever, not just a legibility one. + +**Co-location** is the within-file companion: where the ladder decides _how far down_ a piece sits, co-location decides _what sits beside it_ once there. Keep a concept's definition, rules, and caveats under one heading rather than scattered, so reading one part brings its neighbours with it. The test: the document should read like documentation written for the agent. Grouped material reads that way; scattered material does not. (Distinct from duplication: that repeats one meaning in two places; scattering fragments one meaning across many.) + +**Sprawl** is the failure mode here: a document simply too long, even when every line is live and unique. Attention thins across the excess, and every extra line is one more to keep relevant. The cure is the ladder: disclose reference behind pointers, and split by branch or sequence so each path carries only what it needs. + +## Steps and completion criteria + +Every step ends on a **completion criterion**, the condition that tells the agent the work is done. Two properties make it a lever: + +- **Clarity**: can the agent tell done from not-done? A vague bound ("understanding reached") invites **premature completion**: ending the step before it is genuinely done, attention slipping to _being done_. The visible steps still ahead (the **post-completion steps**) supply the pull; the criterion's clarity is the resistance. Defend in order: **sharpen the bound first** (local and cheap); only if it is irreducibly fuzzy _and_ you observe the rush, hide the later steps by splitting the sequence. Hiding only works across a real context boundary (a hand-off or a subagent dispatch; an inline call leaves the later steps in context and clears nothing). +- **Demand**: how much it requires. "Every modified model accounted for" forces thorough work where "produce a change list" does not. Demand drives **legwork** (the digging the agent does within the work, latent in the wording rather than written as its own step), and it is not step-bound: "every rule applied" binds a body of flat reference just as "every step done" binds a sequence, which is how an all-reference document still carries an exhaustiveness bar. + +The strongest criteria are both checkable and exhaustive. + +## When to split + +Splitting one document into two spends one of the two loads, so split only when the cut earns it: + +- **By sequence**: split a run of steps where the post-completion steps tempt the agent to rush the one in front of it. Keeping them out of view drives more legwork on the current task. Beware the reverse: merging sequences exposes each step's later steps to what follows, inviting premature completion. +- **By invocation**, skill-specific: see [`SKILL-MECHANICS.md`](SKILL-MECHANICS.md). + +## Leading words + +A **leading word** is a compact concept already living in the model's pretraining that the agent thinks with while running the document (_lesson_, _fog of war_, _tracer bullets_). Repeated as a token, never as a sentence, it accumulates a distributed definition and anchors a whole region of behaviour in the fewest tokens, by recruiting priors the model already holds. Coining your own works if you define it clearly, but a made-up word recruits no priors: you pay in definition tokens what a pretrained word gives free; reach for an existing word first. + +It anchors twice. In the body, _execution_: the agent reaches for the same behaviour every time the word appears, and inside flat reference it focuses attention on a class of thing to look for. In a pointer, _invocation_: when the same word lives in your prompts, your docs, and your codebase, the agent links that shared language to the material and reaches it more reliably. + +Hunt for opportunities to refactor with leading words. A triad spelled out at three sites, a pointer spending a sentence to gesture at one idea. Each is a passage begging to collapse into a single token: + +- "fast, deterministic, low-overhead" → _tight_ (a _tight_ loop). +- "a loop you believe in" → _red_, turning a fuzzy gate into a binary observable state (the loop goes _red_ on the bug, or it doesn't). + +You win twice: fewer tokens, and a sharper hook for the agent to hang its thinking on. Assume every document is carrying restatements that leading words retire. Go find them. + +**Negation** is the failure mode beside this lever: steering by prohibition drags the forbidden behaviour into context and makes it _more_ available, not less. _Don't think of an elephant_, and the elephant is all there is; the negation is a weak modifier the strongly-activated concept overruns, so the ban half-reads as an instruction to do the thing. Prompt the **positive**: state the target behaviour ("write one-line comments") so the banned one is never spoken. A prohibition earns its place only as a hard guardrail you cannot phrase positively; even then, pair it with the positive target so attention lands on what to do. + +## Pruning + +- Keep each meaning in a **single source of truth**: one authoritative place, so changing the behaviour is a one-place edit. **Duplication** (the same meaning in more than one place) costs maintenance and tokens, and inflates a meaning's prominence on the ladder past its real rank. (The accidental inverse of a leading word, which repeats a token on purpose, never the meaning.) +- The **environment** is a source of truth too (`package.json` scripts, config files, the directory layout, `--help` output), and a document that restates it is a **cache**: a copy of a lookup, earning its load only when the lookup is expensive. Cache what the agent cannot find by looking: the unwritten convention, the reason behind a choice, the gotcha no config confesses. Leave the one-file, one-command lookups to the environment, where they cannot go stale. +- Check every line for **relevance**: does it still bear on what the document does? A line loses relevance by never bearing on the task (mere exposition, or a branch that should be disclosed) or by going stale as the behaviour or world it describes changes. Shorter documents are easier to keep relevant. Without a pruning discipline the default fate is **sediment**: stale layers that settle because adding feels safe and removing feels risky, until you must core down through them to find what is still live. +- Hunt **no-ops** sentence by sentence: an instruction the model already obeys by default pays load to say nothing. The test (does it change behaviour versus the default?) is model-relative, not reader-relative: two people disagreeing about a no-op disagree about the default, and settle it by running the document, not by debate. When a sentence fails, delete the whole sentence rather than trim words from it. The test also grades leading words: a word too weak to beat the default (_be thorough_ when the agent is already thorough-ish) is a no-op, and the fix is a stronger word (_relentless_), not a different technique. diff --git a/.agents/skills/writing-for-agents/agents/openai.yaml b/.agents/skills/writing-for-agents/agents/openai.yaml new file mode 100644 index 0000000..079c933 --- /dev/null +++ b/.agents/skills/writing-for-agents/agents/openai.yaml @@ -0,0 +1,3 @@ +interface: + display_name: "Writing for Agents" + short_description: "Write documents agents consume" diff --git a/.claude/skills/code-review b/.claude/skills/code-review new file mode 120000 index 0000000..2d88efd --- /dev/null +++ b/.claude/skills/code-review @@ -0,0 +1 @@ +../../.agents/skills/code-review \ No newline at end of file diff --git a/.claude/skills/codebase-design b/.claude/skills/codebase-design new file mode 120000 index 0000000..08b466e --- /dev/null +++ b/.claude/skills/codebase-design @@ -0,0 +1 @@ +../../.agents/skills/codebase-design \ No newline at end of file diff --git a/.claude/skills/domain-modeling b/.claude/skills/domain-modeling new file mode 120000 index 0000000..e672a60 --- /dev/null +++ b/.claude/skills/domain-modeling @@ -0,0 +1 @@ +../../.agents/skills/domain-modeling \ No newline at end of file diff --git a/.claude/skills/grilling b/.claude/skills/grilling new file mode 120000 index 0000000..e712452 --- /dev/null +++ b/.claude/skills/grilling @@ -0,0 +1 @@ +../../.agents/skills/grilling \ No newline at end of file diff --git a/.claude/skills/improve-codebase-architecture b/.claude/skills/improve-codebase-architecture new file mode 120000 index 0000000..be3dac9 --- /dev/null +++ b/.claude/skills/improve-codebase-architecture @@ -0,0 +1 @@ +../../.agents/skills/improve-codebase-architecture \ No newline at end of file diff --git a/.claude/skills/research b/.claude/skills/research new file mode 120000 index 0000000..7a555b6 --- /dev/null +++ b/.claude/skills/research @@ -0,0 +1 @@ +../../.agents/skills/research \ No newline at end of file diff --git a/.claude/skills/tdd b/.claude/skills/tdd new file mode 120000 index 0000000..2178bb8 --- /dev/null +++ b/.claude/skills/tdd @@ -0,0 +1 @@ +../../.agents/skills/tdd \ No newline at end of file diff --git a/.claude/skills/writing-for-agents b/.claude/skills/writing-for-agents new file mode 120000 index 0000000..90df155 --- /dev/null +++ b/.claude/skills/writing-for-agents @@ -0,0 +1 @@ +../../.agents/skills/writing-for-agents \ No newline at end of file diff --git a/AGENTS.md b/AGENTS.md index 44043a3..99837cf 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -6,11 +6,12 @@ editing; close completed issues after validation. Store project memory with `bd remember`. Issues live in `.beads/dolt/`. The JSONL export is passive; normal sync uses -`bd dolt push/pull`. Run git operations and remote sync only when explicitly requested. +`bd dolt push/pull`. Run Git operations—including add, commit, push, and merge—or +remote sync only when explicitly requested. ## Working conventions -- Prefix shell commands with `rtk`. +- Prefix each shell command with `rtk`, including every command in a chain. - Use non-interactive file operations: `cp -f`, `mv -f`, `rm -f`, and their recursive forms. Use `ssh`/`scp -o BatchMode=yes` and `HOMEBREW_NO_AUTO_UPDATE=1` for brew. - Keep decisions pure and effects explicit. Inject `Env`, `CommandRunner`, @@ -28,6 +29,9 @@ Issues live in `.beads/dolt/`. The JSONL export is passive; normal sync uses ## Validation +Before reporting implementation complete, run and report the entire required suite; +scoped checks do not substitute: + ```sh rtk task dev rtk task test @@ -46,18 +50,5 @@ Documentation-only and small, mechanical changes do not. Anything that changes b safety, or module boundaries does, and it is not merged before one is done and its findings are resolved. -1. Prefer CodeRabbit. `.coderabbit.yaml` makes it review only PRs labelled `needs-review`, and - not again on later pushes, because the plan allows about one review an hour. Push first, then - add the label (`gh pr edit N --add-label needs-review`) once the PR is ready, and confirm it - reviewed the current HEAD commit (the `wait-for-action` skill with `--coderabbit`; without - the label its status reads `Review skipped`, which is not a review). After fixing findings, comment `@coderabbitai review` to - review the new commits, if the hour allows. -2. If CodeRabbit is unavailable or rate-limited, run a local review in a fresh - context: a reviewer agent that did not write the change, given the diff, this file, - `DESIGN.md`, `GLOSSARY.md`, and the originating bead. The author's own pass does not - count. - -Verify each finding against the code; fix what is valid and say why the rest were skipped. - See `DESIGN.md` for module ownership and execution rules; `README.md` documents commands and interaction. diff --git a/DESIGN.md b/DESIGN.md index 7a22a2f..8bd6fc7 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -41,7 +41,7 @@ reports item start/end events and action steps. asks which to install and returns its steps (`plan_add_source`); the remaining agents install the source's skills through `npx skills`. The steps are shown as one plan and run only once approved. The CLI and the workspace share `Session::install_source`, which also records what arrived in the library. -Library skill installs inspect their source through that flow too. Explicit skill selections +Explicit skill selections use the owning plugins when the marketplace supplies all selected skills; sources without a matching plugin use loose skills. Codex recognizes native and legacy Claude marketplaces. Its project plugin plans download Git marketplace metadata without registering it globally, @@ -113,7 +113,7 @@ crate, `crates/skillz-harness`, so cargo itself stops it importing anything abov | harness | `model`, `env` | Installed facts, identities, scopes, and filesystem roots | | harness | `agents` | The `Harness` trait; per-agent (Claude, Codex) discovery of plugins and marketplaces, planning, usage, and native command knowledge | | harness | `npx` | Every loose skill, where each agent reads skills from, the `npx skills` commands and lock file | -| harness | `agent_skills` | The Agent Skills open format: frontmatter (harness extensions kept), validation, layout | +| harness | `agent_skills` | The Agent Skills open format: frontmatter (harness extensions kept), validation, layout, and `doctor`: typed diagnostics of the skills on disk (collisions, stray files, invalid files, broken links), read-only | | harness | `hooks`, `hook_text`, `mcp`, `subagents`, `subagent_store` | Shared formats and typed installed facts | | harness | `provision`, `update`, `usage`, `cost` | Planning steps against a tool's commands and reading its usage and context cost | | harness | `action`, `runner`, `redact`, `read_optional`, `json_edit`, `fswalk`, `clone`, `Spec` | Pure edits, staged writes, owned deletion, command running, secret redaction, the desired-thing vocabulary | @@ -122,31 +122,30 @@ crate, `crates/skillz-harness`, so cargo itself stops it importing anything abov | app | `merge`, `package`, `location`, `info`, `matcher` | Logical copies, source-package grouping, display facts | | app | `install`, `remove`, `prune` | Source resolution, selection, and the install, removal and prune flows | | app | `review`, `prompt`, `workspace` | Typed plans, verdicts, outcomes, the `Prompter` and `Screen` interfaces, workspace acts and model | -| app | `tree`, `spinner` | Plain tables and progress text | +| app | `tree`, `spinner`, `rule`, `json` | Plain tables and progress text, the labelled rule, and the `Json` trait every printable item has | | tui | `tui` | Reusable list/outline widgets and interactive presentation | | cli | `cli` | Command parsing, scope selection, sessions, and real dependency wiring | ## Interaction -Project and Global share `InstalledTab`. Rows resolve into actionable items once, -so installing, removing, and updating a package do not depend on expansion state. -Plugin contents are display-only children of the owning plugin. The Project tab includes -global plugins and skills under a separate read-only branch; its actions and clear flow -exclude that branch. The Library groups agents by source within their own section. -Library and profile row values carry the facts their presentation needs. +The workspace is one list, `PluginsTab`, over the project or over the user's installs (`-g`). +Packages are grouped from installed items and library entries by `Package`; selecting flips a +pending state and `enter` submits all of it as one `Act::Change`. The project list shows global +packages below a read-only divider, and its changes exclude them. Hooks, MCP servers and +hand-made files are not in the list yet. Saving, applying and clearing profiles, updating and +library editing are commands, not screens. `Outline` owns navigation and filtering. Screens resolve actions through `keymap::BINDINGS`; the same bindings generate help and hints. Plan and result screens share a text modal that accounts for wrapped visual lines and viewport -height. `App` drives one screen; local popup enums describe dialogs within tabs. +height. `App` drives one screen; a local popup describes a dialog within the tab. Terminal ownership and restoration remain in the shell and its hold guards. Opening a group reveals one level. Closing it resets its descendants; reloads preserve open groups by their ancestor paths so matching labels in other branches stay independent. -Plain `list QUERY` prints matching items. Browsing is explicit with `list -i`. -Background checks examine each installed id once per workspace session, then -recheck updated items and newly discovered ids. The README owns key tables and -command examples. +Plain `list QUERY` prints matching items. Browsing is explicit with `list -i`. Whether an +installed item has a newer version is asked only by `update --check` and `list --check`; the +list does not mark updates yet. The README owns key tables and command examples. ## Extension and tests diff --git a/GLOSSARY.md b/GLOSSARY.md index 29f1410..169a088 100644 --- a/GLOSSARY.md +++ b/GLOSSARY.md @@ -26,6 +26,16 @@ _Avoid_: Level, context The `name@marketplace` identity of a plugin; a bare name has no marketplace. _Avoid_: Plugin key, qualified name +### Plugins list + +**Package**: +What the plugins list shows a line for: a marketplace, an `owner/repo`, or the installed items and library entries that share one source. Selecting it and submitting installs or removes all of it as one change. +_Avoid_: Plugin group, bundle + +**Plugins list**: +The one interactive screen: a checkbox per package, `space` to select, `enter` to submit one plan. It has no tabs. +_Avoid_: Workspace tabs, Project tab + ### Loose skills **Loose skill**: diff --git a/README.md b/README.md index d35e7b5..8732066 100644 --- a/README.md +++ b/README.md @@ -23,18 +23,18 @@ is also a command. | Command | Does | | --- | --- | -| `list` (`ls`) | show what is installed as a tree, or browse it with `-i`; `--json` adds each item's location (`--check` also whether a newer version exists); `--available` lists the library items the project (`-g`: the user) lacks | +| `list` (`ls`) | in a terminal, a plain `list` (or `list -g`) opens the plugins list (see Workspace); otherwise (a query, `--all`, a kind filter, no terminal) it shows what is installed as a tree, or browse it with `-i`; `--json` never opens the list and prints the items for scripts and agents, adding each item's location (`--check` also whether a newer version exists); `--available` lists the library items the project (`-g`: the user) lacks | | `uninstall` (`rm`, `delete`) | fuzzy match, pick, confirm, remove completely; several queries go in one plan | | `update` | update installed items with the tool that installed them (`-g`: the user's); `--check` lists the ones with a newer version (`--json` for scripts) | | `reset` | remove every skill, plugin and marketplace in scope | | `prune` | find duplicate and unused skills and plugins, remove the ones picked | +| `doctor` | check the skills on disk, read-only: names that collide (per tool, listing every copy), skill files nested or loose where a tool will not look (or looks too hard), files that break the format, and broken links; `-g` for the user's skills only, `--json` for scripts | | `sync` | add everything installed, in the project and at user level, to the library (`-p PATH`, `-g` for user level only, `--dry-run`, `--json`); never removes anything from it | | `install` (`add`) | `install OWNER/REPO` (or a git URL or path): offers each agent the plugins the repo has a marketplace for (Claude `.claude-plugin/`, Codex `.agents/plugins/`), installs skills for the rest with `npx skills`, and shows the plan before running it; `-g` installs for the user instead of the project | -| `library` (`lib`) | `list` (`ls`, `--json`, kind filters), `add "LINE"`, `remove` (`rm`) a label query or LINE, `install QUERY...` into the project or with `-g` for the user (each with `--dry-run`, `-y` where it asks) | +| `library` (`lib`) | `list` (`ls`, kind filters; groups the items under a `── package ──` rule per package or folder and writes your home directory as `~`, while `--json` keeps full paths), `add "LINE"`, `remove` (`rm`) a label query or LINE, `install QUERY...` into the project or with `-g` for the user (each with `--dry-run`, `-y` where it asks) | | `use` | add what a project lacks of a profile (`--exact` also removes the rest) | | `run` | run a command against one profile in config dirs of its own | | `profile` | `list` (`ls`, with how each compares with the project; `--json`), `status [NAME]` (present, missing, extra; `--json`), `show` (`export`), `import FILE`, `new`, `add NAME "LINE"` or `--from-library QUERY`, `remove NAME QUERY`, `save`, `delete` (`rm`) | -| `project` | `list` (`ls`), `add`, `remove` (`rm`) | Kind filters on `list`, `uninstall`, `reset` and `prune`: `--skills --hooks --plugins --marketplaces --mcp --subagents` (singular spellings work too; none given means all kinds). @@ -74,9 +74,9 @@ Source installs prefer each tool's native plugin installer when a marketplace is skills, and installs everything such a plugin ships. The plan names each plugin with how many skills it brings, and for `--all` lists the skills of the source that no plugin supplies, which are not installed (name them with `--skill`). Sources without a matching plugin use `npx -skills`. Library skill installs that name skills inspect the source again, so older loose-skill -entries can install through the native plugin too; a malformed marketplace or plugin manifest -in the source never fails the install, its skills install loose instead. +skills`. A malformed marketplace or plugin manifest in the source never fails the install, its +skills install loose instead. `library install` and profile applies still install a loose +skill entry with `npx skills`, not through the plugin its source may offer. A Codex project install writes the marketplace and plugin into `.codex/config.toml`, which a team usually commits, so skillz refuses a source with a user, password or token in its URL (use ssh or @@ -94,28 +94,26 @@ and asks before installing it into the project too (`-y` goes ahead). Scope for `list`, `uninstall`, `reset` and `prune`: a `PATH` (or `-p PATH`) means that project only, `-g` means global only, neither means both (project = cwd). `install` and `update` act on one -project, or with `-g` on the user's installs; `use`, `run` and `profile` always act on one project, -and the workspace has a tab for each. A project that is your home directory counts as global. A `list` PATH must +project, or with `-g` on the user's installs; `use`, `run` and `profile` always act on one project. A project that is your home directory counts as global. A `list` PATH must start with `.`, `..` or `/` (`./sub`, not `sub`); any other word is a query. -## From the workspace to the command line +## From the list to the command line -Everything the workspace does is a command, and both run the same code (a plan reviewed first, -then the same install and removal steps): +Everything the list does is a command, and both run the same code (a plan reviewed first, then +the same install and removal steps). What the list does not do is a command too: -| In the workspace | On the command line | +| In the list | On the command line | | --- | --- | -| Project / Global tabs: what is installed, the split, where each item lives | `list`, `list -g`, `list --json` (`location`) | -| Update markers | `list --json --check`, `update --check [--json]` | -| `space` picks, `enter` removes the picks as one plan | `uninstall QUERY...` (`-y`, `--dry-run`) | -| `r` remove / `u` update the highlighted item | `uninstall`, `update` | -| `A` add from a repo: type `owner/repo`, a git URL or a path | `install SOURCE` | -| The Project header: the applied profile, matches / N missing / N extra | `profile status [NAME] [--json]`, `profile list [--json]` | -| Project and Global: `a` apply a profile (adds what is missing; `m` switches to replace). Project also: `p` keep some of its entries, `c` clear | `use NAME`, `use NAME --exact`, `use NAME -g` (`-y`, `--dry-run`), `uninstall` | -| Library: `a` add a typed line, `x` remove, `i` install the highlighted item | `library add "skill o/r tdd"`, `library remove QUERY`, `library install QUERY [-g]`, `sync` | -| Library: origin, link, version, installed in project / global | `library list [--json]` | -| Profiles: `n` new, `enter` / `e` edit, `x` delete; Project: `s` save the project as a profile | `profile new`, `profile add` / `profile remove`, `profile save`, `profile delete` | -| `/` filter, `space` fold, `?` help, `tab`, movement keys | on screen only: `list QUERY` and `list --all` do the same for the command line | +| What is installed, the split, where each item lives | `list`, `list -g`, `list --json` (`location`) | +| `space` selects, `enter` submits installs and removals as one plan | `install SOURCE`, `uninstall QUERY...` (`-y`, `--dry-run`) | +| `i` info: provenance and locations | `list --json` (`location`), `library list --json` | +| Updating | `update [QUERY] [-g]`, `update --check [--json]` | +| Applying and comparing a profile | `use NAME [--exact] [-g]`, `profile status [NAME] [--json]`, `profile list` | +| Saving the project as a profile, editing profiles | `profile save`, `profile new`, `profile add` / `profile remove`, `profile delete` | +| Clearing the project | `reset` removes skills, plugins and marketplaces; add `--hooks`, `--mcp`, `--subagents` for those kinds | +| Keeping only some entries of an applied profile | no command yet (bead `skillz-obs`) | +| The library | `library add "skill o/r tdd"`, `library remove QUERY`, `library install QUERY [-g]` (each entry installs for the agents it names; there is no `-a`), `sync` | +| `/` filter, `?` help, movement keys | on screen only: `list QUERY` and `list --all` do the same for the command line | ## Profiles @@ -217,12 +215,12 @@ shared with a wanted entry, such as a skill for two agents of which the profile `use` acts on one level only. In a project it installs into that project (Claude plugins at `local` scope, so only that project has them) and counts only what the project holds; with `-g` it installs at user level (Claude `--scope user`, `npx skills -g`, the Codex user config) and -counts only the user's own installs. A profile applied at user level shows up in the Project tab -as inherited, read-only items, and does not make the project match it. Codex plugins can only be +counts only the user's own installs. A profile applied at user level shows up in the project list +below the divider, read-only, and does not make the project match it. Codex plugins can only be installed at user level, so a project apply skips them. Which profile a project has loaded is never stored. A project matches a profile when nothing the -profile wants is missing from the inventory; the Project tab compares the directory with the +profile wants is missing from the inventory; `profile status` compares the directory with the profile you choose. ## The store and the library @@ -230,7 +228,7 @@ profile you choose. `~/.config/skillz/store.json` is the only file skillz keeps for itself (apart from the scratch config dirs `run` makes). It holds `version`, `items` (the library) and `profiles`. The library is every skill, plugin, MCP server, hook and subagent you have installed or typed in, so that -anything installed once can be installed again from the Project or Global tab. Each item records its +anything installed once can be installed again with `library install`. Each item records its provenance: the `link` it was fetched from, the `engine` that installed it, the `version` (a plugin version, or the content hash `npx skills` locked) and when it was `recorded_at`. Every successful `install`, `use` and workspace change adds what it installed. @@ -239,18 +237,18 @@ The library is a master record, so it also learns what you installed some other workspace opens, a background scan reads everything installed in the project and at user level, for every agent (skills, plugins, MCP servers, hooks, subagents), and adds what the library does not have yet, marked as *detected* in its provenance. The workspace is shown at once; when the scan -ends the Library tab fills and a toast says how many were new (and how many MCP servers were left +ends the list gains them and a toast says how many were new (and how many MCP servers were left out for needing secrets). The same scan runs as `skillz sync`, after every install, update or change. It only ever adds: a second run adds nothing, labels you -gave are kept, and items that are no longer installed stay. The only way out of the library is its -remove key (`x`) or removing it by hand in `store.json`. `SKILLZ_NO_SYNC=1` turns the startup scan +gave are kept, and items that are no longer installed stay. The only way out of the library is +`skillz library remove` or removing it by hand in `store.json`. `SKILLZ_NO_SYNC=1` turns the startup scan off. A hand-made skill or subagent is recorded by the directory that holds it (engine `local`, marked detected), so it is reinstalled with `npx skills add --skill `. Items needing secrets, and items with nothing to reinstall them from, are not recorded. **Moving a folder.** skillz keeps no registry of projects, so moving a project is fine, but a hand-made skill or subagent is recorded by its absolute directory. When that directory is gone the -item is *stale*: the Library tab tags it `! missing source`, `library list` marks it and +item is *stale*: `library list` marks it as missing its source and `--json` has `"stale": true`, and `profile status` lists profile entries in that state as `unavailable` (apart from `missing`). The next sync (startup scan or `skillz sync`) re-points a stale item at the new directory in place when exactly one live local source holds a skill or @@ -289,100 +287,67 @@ never `~/.claude` or `~/.codex`. The variable is also set on every command skill ## Workspace -`skillz [PATH]` opens a workspace for one directory (default: the current one). It keeps nothing -per project: what is installed is read from the agents' own config each time. It needs a terminal -at least 40x10. Four tabs, switched with `tab` / `shift-tab` or `1` `2` `3` `4`: - -- **Project** and **Global**: the same tab over two scopes. Project is what this directory has - installed; Global is what you have installed at user level, outside any project. Each lists - only what is installed there, in sections by kind: `plugins`, `skills`, `agents`, - `MCP servers` and `hooks` (a section with nothing in it is left out). Every row is a whole - unit you can remove or update: a plugin is one row that says what it provides - (`3 skills, 2 hooks`), and what it provides is not listed again among the skills and hooks; - removing the plugin removes them. Skills hang under the package they came from, as - `npx skills list` does: an `owner/repo` or `local files`. `hooks` are only the hooks no plugin - declares. Every row shows its agents and where it lives on disk (the skill's directory, or the - config file). The header line is the directory, or `User-level, all projects`; on Project a - line above it names the profile last applied to the directory and how the directory compares - with it: matching, or `N missing` / `N extra` (`no profile applied` before the first apply). Picked rows get their own marker and a `to remove` note, and each - section or package shows its count of picks. `space`, `r` and `u` on a package row act on - everything in it (the plan shows what, and nothing happens until you confirm it); on an item - row they act on that item; on a section `space` folds it, `r` marks every item in it for removal - and `u` does nothing. A thing installed for - several agents (a subagent for Claude and Codex, say) is one row naming its agents, `claude, - codex`, or `claude, codex +2` when there are many; removing it removes every copy. A filter - keeps the section structure and hides rows with no match. Removals and updates on Global act on - the user's installs (`npx skills -g`, `claude ... --scope user`, the Codex user config). - Installed plugins expand with `→` (or `enter`, when nothing is picked) to show their skills, agents, commands and hooks. - These child rows are for inspection; removal and update apply to the whole plugin. - The Project tab also shows global plugins and skills below a dimmed `Global installs · read only` - separator. They can be expanded there; changes belong on the Global tab. Project clear and - removal picks exclude these global items. - `a` on Global applies a profile at user level, for every project, and the line above the list - compares the user's installs with the profile last applied there; Global has no `p`, `c` or - `s`. Adding is `A`, or the Library tab and profiles. - In the background the tabs check whether installed Claude marketplaces have a newer version - (a read-only `ls-remote`) and shows those in bold with a `*` after the name. Other kinds have - no reliable check and are never marked. `SKILLZ_NO_UPDATE_CHECK=1` turns the check off; - `skillz update --check` runs it from the command line. -- **Library**: the items skillz knows about, grouped by package like the other tabs, with where - each came from. Agents have a separate collapsible section, grouped by source repository or - directory; local agent directories stay separate. `space` or `enter` folds a section or source - group, and filtering an agent keeps its section and source visible. The line under the list - starts with how it got there (*detected*, *added by skillz* or *added by hand*), then shows the - link, how it was installed (`npx skills`, `claude plugin`, `codex plugin`, `manual`) and the - version or hash recorded. A `project` or `global` tag after a name says where the item is - installed right now; no tag means it is only in the library. `i` on an item opens a dialog - to install it: pick *This project* or *Global* and check the coding tools to install it for - (`space` chooses, `enter` installs, `esc` cancels). The tools the item names start checked. -- **Profiles**: your saved combinations, kept apart from any project: make, edit and delete - them here, and apply them from the Project tab. It is one list, each profile with its entries - under it. `n` opens a single modal: type the name, `tab` to the library items, `space` to - check them, and `s` (or `enter` in the name) saves. `enter` or `e` edits the profile under the - cursor in the same modal; `x` deletes it. - -Expanding a group reveals its immediate children. Nested groups stay closed until opened -individually, including after their parent is closed and reopened. In the profile editor, library -item names omit the kind their section already shows; source and marketplace details remain visible. +`skillz [PATH]` opens the plugins list for one directory (default: the current one). It keeps +nothing per project: what is installed is read from the agents' own config each time. It needs a +terminal at least 40x10. `skillz list` in a terminal (with no query, flag or kind filter) opens +the same list instead of printing, and `skillz list -g` (`--global`) opens it for the user's +installs alone, with no project rows and no global section; flipping a package there installs or +removes it at user level. + +The list has a line per package (a marketplace or an `owner/repo`), from the library and from +what the project has, by name, with no column header. A checkbox says whether the project has +it, and an installed one names its agents, `[claude, codex]`. Hooks, MCP servers and hand-made +files are not in it yet. + +- `space` selects or deselects the package under the cursor: its line turns bold and its box + shows what it will become, and nothing happens yet. `esc` drops the selection. +- `enter` submits everything selected as one change. The plan lists `installing` and `removing` + groups to confirm (an install is for every agent; an entry that names its own agents keeps to + them), each skill or plugin with its own box, all checked: `↑` `↓` move and `space` unchecks + one you want to leave out. +- `i` opens an info modal for the package under the cursor: where it comes from, how the library + came to know it (added by hand, found by a scan or installed by skillz, when, what it is + fetched from, with which tool and which version), what it offers and where each installed item + lives on disk. +- `/` filters. + +There are no tabs: updating, removing by query, profiles and library editing are commands (see +the table above). | Key | Does | | --- | --- | -| `space` | pick the item under the cursor for removal; again to unpick (on a package: everything in it; on a section: open or close it) | -| `enter` | remove all picks as one change, with one plan to review; with nothing picked, open or close the section | -| `r` | remove the item under the cursor from the tab's scope at once (after the plan); on a package row, removes everything in it; on a section, marks every item in it for removal. When the items are installed for more than one agent, the plan shows an Agents list above what will be removed; every agent starts checked and `space` unchecks one (`↑↓` moves) before `enter` applies | -| `esc` | clear the picks (with none, clear the filter) | -| `u` | update the installed item under the cursor, or every installed item of the package, after a plan to review; kinds with nothing to update (hooks, MCP servers, hand-made skills) are ignored | -| `a` | list the profiles and apply the one you choose, after a plan to review. It adds what is missing and removes nothing; `m` in the list switches to replacing everything (installs what is missing, removes the rest). The project (or, on Global, the user level) remembers it as its applied profile | -| `p` | list the applied profile's entries, those the project has checked; `space` checks or unchecks, `enter` installs the checked ones and removes the unchecked ones, after a plan (Project only) | -| `c` | clear: remove everything the project has, after a plan to review. The applied profile stays, so `p` or `a` can bring back all or part of it (Project only) | -| `s` | save what the project has installed as a new profile, after typing its name; the project then counts that profile as applied (Project only) | -| `←` `→`, `h` `l` | close / open a section (`←` on an item jumps to its section) | +| `space` | select the package under the cursor, or unselect it | +| `enter` | submit everything selected as one change, after a plan to review | +| `esc` | drop the selection (with none, clear the filter) | +| `i` | info: where the package comes from and where each installed item lives | +| `/` | filter; keeps matching rows, `esc` clears it | | `↑↓` `j` `k`, `PgUp` `PgDn`, `^u` `^d`, `g` `G` | move | -| `/` | filter; keeps matching rows and their section, `esc` clears it | | `?` | all keys for the screen | | `q`, `^c` | quit | -Marketplaces have their own selectable rows in the Project and Global tabs. `r` removes -that scope's marketplace declarations and installed plugins; `u` updates the marketplace. -Skills remain grouped by source, so a source row can remove or update its installed skills -together. Removing an installation keeps its saved Library entry for later reuse. - Project profile applies declare Claude marketplaces and install plugins in the project's `.claude/settings.local.json`. Claude keeps downloaded marketplaces and plugin caches under its user configuration directory; that shared storage does not make them global installs. Marketplace scope comes from `extraKnownMarketplaces` in settings, not from the shared -`known_marketplaces.json` download registry. Adding a plugin from the Project tab declares its +`known_marketplaces.json` download registry. Adding a plugin to the project declares its marketplace in the project's `.claude/settings.json`, the same scope the plugin is enabled in. Installing, removing, updating and applying show a plan first: `=` kept, `-` removed, `+` -installed, `^` updated, `~` skipped, framed in red when it removes something. `enter` or `y` goes ahead, `d` turns on dry run, -`s` shows the raw steps, `esc` cancels. A progress screen follows, then a result with counts and -any failures: `c` copies them (through the terminal, so it works over ssh), `r` retries, `enter` -closes. A toast says what happened. - -While a change runs, a modal over the tab lists every item it will change, each with a spinner +installed, `^` updated, `~` skipped, framed in red when it removes something. It ends in two +buttons, `[ Cancel ]` and `[ Delete ]` (`[ Apply ]` when nothing is removed), with no help text: +`←` `→` or `tab` change the button and `enter` answers it, `y` goes ahead and `n` or `esc` cancels. +`d` turns on dry run (the button then reads `Dry run`) and `s` shows the raw steps. A removal that +spans both agents lists them as checkboxes first; `space` unchecks one. Each plan line is the +item's name, its source when that adds something, and its kind. A plain confirm dialog is the +question with `[ No ]` and `[ Yes ]`, the cancelling one first. A progress screen follows, then a short result: a line for each item that changed and an +`[ OK ]` button, with no help text. If something failed, its reasons are listed and `[ Copy ]` +(through the terminal, so it works over ssh) and `[ Retry ]` come before OK; `←` `→` or `tab` +change the button, `enter` answers it, and `c` and `r` still work directly. A toast says what +happened. + +While a change runs, a modal over the list lists every item it will change, each with a spinner (`⠋`, or `|/-\` in ASCII mode) while it works, then a tick or a cross when it finishes; the -affected rows on the Project and Global tabs show the same marks until the next key. The result screen lists what was done (`Installed X`, `Removed Y`, `Updated Z`) and +affected rows in the list show the same marks until the next key. The result screen lists what was done (`Installed X`, `Removed Y`, `Updated Z`) and every failure with its reason. The browser (`list -i`) and every picker (`uninstall`, `prune`, `install`) diff --git a/crates/skillz-harness/src/agent_skills/doctor.rs b/crates/skillz-harness/src/agent_skills/doctor.rs new file mode 100644 index 0000000..271dff2 --- /dev/null +++ b/crates/skillz-harness/src/agent_skills/doctor.rs @@ -0,0 +1,352 @@ +//! What is wrong with the skills on disk, as typed diagnostics: names that collide, skill files +//! in places a tool will not look (or looks too hard), files that break the format and links that +//! lead nowhere. Reads the folders it is given and changes nothing. +//! +//! Which copy a tool keeps when names collide differs per tool and is not decided here: a +//! collision lists every copy, in the order the roots were given. + +use std::collections::{BTreeMap, HashSet}; +use std::fs; +use std::path::{Path, PathBuf}; + +use serde::Serialize; + +use super::{Frontmatter, SKILL_FILE, Violation, parse, validate}; +use crate::env::Env; +use crate::model::{Agent, Scope}; + +/// A folder skills live in, and the tools that read it. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Root { + pub dir: PathBuf, + pub scope: Scope, + pub agents: Vec, +} + +/// The folders each tool loads skills from, at user level and in the project; one that several +/// tools read is one root. +pub fn roots(env: &Env) -> Vec { + let mut roots: Vec = Vec::new(); + for scope in [Scope::Global, Scope::Project] { + for agent in [Agent::Claude, Agent::Codex] { + for dir in crate::npx::skill_dirs(env, agent, scope) { + // A project that is the home directory shares its folders with the user level. + match roots.iter_mut().find(|r| r.dir == dir) { + Some(root) => root.agents.push(agent), + None => roots.push(Root { + dir, + scope, + agents: vec![agent], + }), + } + } + } + } + roots +} + +/// Who would meet a collision. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum Readers { + /// These tools, each of which reads every copy as a skill. + Agents(Vec), + /// A tool that also loads nested and loose skill files (pi does), which sees every copy. + Recursive, +} + +/// Why a skill file sits where the tools do not expect one. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum Stray { + /// A `SKILL.md` below a folder that is not itself a skill: only tools that search deeper + /// find it. + Nested, + /// Skill-like frontmatter in a file that is not called `SKILL.md`. + WrongName, + /// A skill-like file directly in the skills folder, outside any skill folder. + Loose, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct Instance { + pub path: PathBuf, + pub scope: Scope, + pub stray: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +#[serde(tag = "kind", rename_all = "snake_case")] +pub enum Diagnostic { + /// Several skill files answer to `name`; `copies` lists them all. + Collision { + name: String, + readers: Readers, + copies: Vec, + }, + Stray { + path: PathBuf, + name: Option, + scope: Scope, + why: Stray, + }, + /// A skill that breaks the Agent Skills format. + Invalid { + path: PathBuf, + name: String, + scope: Scope, + violations: Vec, + }, + /// A link in a skills folder whose target is gone. + Dangling { + path: PathBuf, + target: Option, + scope: Scope, + }, +} + +/// A skill file found while scanning, real or stray. +struct Found { + name: String, + file: PathBuf, + /// The file with every link followed, so two links to one file are one skill. + real: PathBuf, + root: usize, + stray: Option, +} + +#[derive(Default)] +struct Scan { + found: Vec, + diagnostics: Vec, + /// Files already reported, by real path: a link must not report its target twice. + reported: HashSet, +} + +/// Every problem in the skills under `roots`: collisions first, then strays, format problems and +/// dangling links, each in the order found. +pub fn diagnose(roots: &[Root]) -> Vec { + let mut scan = Scan::default(); + for (index, root) in roots.iter().enumerate() { + scan.root(index, root); + } + let mut diagnostics = collisions(roots, &scan.found); + diagnostics.extend(scan.diagnostics); + diagnostics +} + +impl Scan { + fn root(&mut self, index: usize, root: &Root) { + for (name, path) in entries(&root.dir) { + if name.starts_with('.') { + continue; + } + let Ok(meta) = fs::metadata(&path) else { + self.dangling(&path, root.scope); + continue; + }; + if meta.is_dir() { + self.top_dir(index, root, (&name, &path)); + } else if is_markdown(&path) && skill_like(&path).is_some() { + self.stray(index, root, &path, Stray::Loose); + } + } + } + + fn dangling(&mut self, path: &Path, scope: Scope) { + if fs::symlink_metadata(path).is_ok_and(|m| m.file_type().is_symlink()) { + self.diagnostics.push(Diagnostic::Dangling { + path: path.to_path_buf(), + target: fs::read_link(path).ok(), + scope, + }); + } + } + + /// A folder directly in a skills folder: a skill when it holds `SKILL.md`, else searched for + /// skill files that ended up inside. + fn top_dir(&mut self, index: usize, root: &Root, (name, dir): (&str, &Path)) { + let Some(file) = exact_skill_file(dir) else { + return self.nested(index, root, dir); + }; + let text = fs::read_to_string(&file).unwrap_or_default(); + let front = parse(&text); + let skill = front + .as_ref() + .and_then(|f| f.name.clone()) + .unwrap_or_else(|| name.to_string()); + let real = fs::canonicalize(&file).unwrap_or_else(|_| file.clone()); + let first_time = self.reported.insert(real.clone()); + if first_time { + let violations = match &front { + Some(front) => validate(front, name), + None => vec![Violation::MissingName, Violation::MissingDescription], + }; + if !violations.is_empty() { + self.diagnostics.push(Diagnostic::Invalid { + path: file.clone(), + name: skill.clone(), + scope: root.scope, + violations, + }); + } + } + self.found.push(Found { + name: skill, + file, + real, + root: index, + stray: None, + }); + } + + /// Search below a folder that is not a skill, without following links, for skill files. + fn nested(&mut self, index: usize, root: &Root, dir: &Path) { + if let Some(file) = exact_skill_file(dir) { + return self.stray(index, root, &file, Stray::Nested); + } + for (name, path) in entries(dir) { + if name.starts_with('.') || name == "node_modules" { + continue; + } + let Ok(meta) = fs::symlink_metadata(&path) else { + continue; + }; + if meta.is_dir() { + self.nested(index, root, &path); + } else if meta.is_file() && is_markdown(&path) && skill_like(&path).is_some() { + self.stray(index, root, &path, Stray::WrongName); + } + } + } + + fn stray(&mut self, index: usize, root: &Root, file: &Path, why: Stray) { + let front = skill_like(file); + let name = front.as_ref().and_then(|f| f.name.clone()); + let real = fs::canonicalize(file).unwrap_or_else(|_| file.to_path_buf()); + if self.reported.insert(real.clone()) { + self.diagnostics.push(Diagnostic::Stray { + path: file.to_path_buf(), + name: name.clone(), + scope: root.scope, + why, + }); + } + // A file without a name of its own is called after the folder holding it. + let name = name + .or_else(|| parent_name(file)) + .unwrap_or_else(|| "?".into()); + self.found.push(Found { + name, + file: file.to_path_buf(), + real, + root: index, + stray: Some(why), + }); + } +} + +/// Names that more than one skill file answers to: for each tool that reads the copies as +/// skills, and for tools that also load the strays. +fn collisions(roots: &[Root], found: &[Found]) -> Vec { + type Key = (String, Vec); + let mut by_agents: BTreeMap, Vec)> = BTreeMap::new(); + for agent in [Agent::Claude, Agent::Codex] { + let readable = found + .iter() + .enumerate() + .filter(|(_, f)| f.stray.is_none() && roots[f.root].agents.contains(&agent)); + for (name, copies) in grouped(readable) { + let key = ( + name, + copies.iter().map(|&i| found[i].real.clone()).collect(), + ); + let entry = by_agents.entry(key).or_default(); + entry.0.push(agent); + entry.1 = copies; + } + } + let mut diagnostics: Vec = by_agents + .into_iter() + .map(|((name, _), (agents, copies))| Diagnostic::Collision { + name, + readers: Readers::Agents(agents), + copies: copies_of(roots, found, &copies), + }) + .collect(); + // Only the groups a stray takes part in are new: the others are said above. + for (name, copies) in grouped(found.iter().enumerate()) { + if copies.iter().any(|&i| found[i].stray.is_some()) { + diagnostics.push(Diagnostic::Collision { + name, + readers: Readers::Recursive, + copies: copies_of(roots, found, &copies), + }); + } + } + diagnostics +} + +/// The files by name that more than one distinct file answers to, as indexes in the order found. +fn grouped<'a>(files: impl Iterator) -> Vec<(String, Vec)> { + let mut seen: HashSet<&Path> = HashSet::new(); + let mut by_name: BTreeMap<&str, Vec> = BTreeMap::new(); + for (at, file) in files { + if seen.insert(&file.real) { + by_name.entry(&file.name).or_default().push(at); + } + } + by_name + .into_iter() + .filter(|(_, copies)| copies.len() > 1) + .map(|(name, copies)| (name.to_string(), copies)) + .collect() +} + +fn copies_of(roots: &[Root], found: &[Found], at: &[usize]) -> Vec { + at.iter() + .map(|&i| Instance { + path: found[i].file.clone(), + scope: roots[found[i].root].scope, + stray: found[i].stray, + }) + .collect() +} + +/// The children of `dir` by name, sorted so reports are the same every time. +fn entries(dir: &Path) -> Vec<(String, PathBuf)> { + let Ok(read) = fs::read_dir(dir) else { + return vec![]; + }; + let mut entries: Vec<(String, PathBuf)> = read + .flatten() + .map(|e| (e.file_name().to_string_lossy().into_owned(), e.path())) + .collect(); + entries.sort(); + entries +} + +/// `dir/SKILL.md`, exactly so: a case-insensitive disk would answer to `skill.md` as well. +fn exact_skill_file(dir: &Path) -> Option { + entries(dir) + .into_iter() + .find(|(name, path)| name == SKILL_FILE && path.is_file()) + .map(|(_, path)| path) +} + +fn is_markdown(path: &Path) -> bool { + path.extension().is_some_and(|ext| ext == "md") +} + +/// The frontmatter of a file that names itself and describes itself, as a skill does. +fn skill_like(file: &Path) -> Option { + let front = parse(&fs::read_to_string(file).ok()?)?; + (front.name.is_some() && front.description.is_some()).then_some(front) +} + +fn parent_name(file: &Path) -> Option { + Some(file.parent()?.file_name()?.to_string_lossy().into_owned()) +} + +#[cfg(test)] +mod tests; diff --git a/crates/skillz-harness/src/agent_skills/doctor/tests.rs b/crates/skillz-harness/src/agent_skills/doctor/tests.rs new file mode 100644 index 0000000..a8b16e4 --- /dev/null +++ b/crates/skillz-harness/src/agent_skills/doctor/tests.rs @@ -0,0 +1,322 @@ +use std::fs; +use std::path::Path; + +use super::*; + +fn skill_text(name: &str) -> String { + format!("---\nname: {name}\ndescription: does {name}\n---\nbody\n") +} + +fn write(path: impl AsRef, text: &str) { + let path = path.as_ref(); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, text).unwrap(); +} + +fn skill(root: &Path, dir: &str, name: &str) { + write(root.join(dir).join("SKILL.md"), &skill_text(name)); +} + +fn root(dir: &Path, scope: Scope, agents: &[Agent]) -> Root { + Root { + dir: dir.to_path_buf(), + scope, + agents: agents.to_vec(), + } +} + +fn collisions(found: &[Diagnostic]) -> Vec<(&str, &Readers, usize)> { + found + .iter() + .filter_map(|d| match d { + Diagnostic::Collision { + name, + readers, + copies, + } => Some((name.as_str(), readers, copies.len())), + _ => None, + }) + .collect() +} + +#[test] +fn two_skills_with_one_name_in_folders_one_tool_reads_collide_for_that_tool() { + let dir = tempfile::tempdir().unwrap(); + let (a, b) = (dir.path().join("a"), dir.path().join("b")); + skill(&a, "tdd", "tdd"); + skill(&b, "tdd", "tdd"); + + let found = diagnose(&[ + root(&a, Scope::Global, &[Agent::Codex]), + root(&b, Scope::Project, &[Agent::Codex]), + ]); + + assert_eq!( + collisions(&found), + [("tdd", &Readers::Agents(vec![Agent::Codex]), 2)] + ); +} + +#[test] +fn a_name_in_folders_no_single_tool_reads_together_is_not_a_collision() { + let dir = tempfile::tempdir().unwrap(); + let (claude, codex) = (dir.path().join("claude"), dir.path().join("codex")); + skill(&claude, "tdd", "tdd"); + skill(&codex, "tdd", "tdd"); + + let found = diagnose(&[ + root(&claude, Scope::Global, &[Agent::Claude]), + root(&codex, Scope::Global, &[Agent::Codex]), + ]); + + assert_eq!(collisions(&found), []); +} + +#[test] +fn a_collision_both_tools_meet_names_both_tools_once() { + let dir = tempfile::tempdir().unwrap(); + let (a, b) = (dir.path().join("a"), dir.path().join("b")); + skill(&a, "tdd", "tdd"); + skill(&b, "tdd", "tdd"); + let both = [Agent::Claude, Agent::Codex]; + + let found = diagnose(&[ + root(&a, Scope::Global, &both), + root(&b, Scope::Project, &both), + ]); + + assert_eq!( + collisions(&found), + [("tdd", &Readers::Agents(both.to_vec()), 2)] + ); +} + +#[cfg(unix)] +#[test] +fn a_link_to_the_same_skill_is_one_skill_not_a_collision() { + let dir = tempfile::tempdir().unwrap(); + let (store, linked) = (dir.path().join("store"), dir.path().join("linked")); + skill(&store, "tdd", "tdd"); + fs::create_dir_all(&linked).unwrap(); + std::os::unix::fs::symlink(store.join("tdd"), linked.join("tdd")).unwrap(); + + let found = diagnose(&[ + root(&store, Scope::Global, &[Agent::Codex]), + root(&linked, Scope::Global, &[Agent::Codex]), + ]); + + assert_eq!(found, []); +} + +#[cfg(unix)] +#[test] +fn a_link_whose_target_is_gone_is_dangling_and_a_plain_file_is_not() { + let dir = tempfile::tempdir().unwrap(); + let skills = dir.path().join("skills"); + fs::create_dir_all(&skills).unwrap(); + std::os::unix::fs::symlink(dir.path().join("missing"), skills.join("old")).unwrap(); + write(skills.join("README"), "not a skill"); + + let found = diagnose(&[root(&skills, Scope::Global, &[Agent::Claude])]); + + assert_eq!( + found, + [Diagnostic::Dangling { + path: skills.join("old"), + target: Some(dir.path().join("missing")), + scope: Scope::Global, + }] + ); +} + +/// The shape of your workspace: three files claiming one name below a folder that is no skill. +fn workspace(skills: &Path) { + let base = skills.join("git-janitor-workspace"); + write( + base.join("iteration-3/baseline-snapshot/skill.md"), + &skill_text("git-janitor"), + ); + write( + base.join("skill-snapshot/SKILL.original.md"), + &skill_text("git-janitor"), + ); + write( + base.join("skill-snapshot/git-janitor.md"), + &skill_text("git-janitor"), + ); +} + +#[test] +fn skill_files_below_a_folder_that_is_no_skill_are_strays_and_collide_for_deep_scanners() { + let dir = tempfile::tempdir().unwrap(); + let skills = dir.path().join("skills"); + workspace(&skills); + + let found = diagnose(&[root(&skills, Scope::Global, &[Agent::Codex])]); + + let strays = found + .iter() + .filter(|d| { + matches!( + d, + Diagnostic::Stray { + why: Stray::WrongName, + .. + } + ) + }) + .count(); + assert_eq!(strays, 3); + assert_eq!( + collisions(&found), + [("git-janitor", &Readers::Recursive, 3)] + ); +} + +#[test] +fn a_skill_md_below_a_non_skill_folder_is_nested_and_a_real_skill_beside_it_is_not() { + let dir = tempfile::tempdir().unwrap(); + let skills = dir.path().join("skills"); + skill(&skills, "tdd", "tdd"); + skill(&skills, "workspace/old/tdd", "tdd"); + + let found = diagnose(&[root(&skills, Scope::Global, &[Agent::Claude])]); + + let nested = skills.join("workspace/old/tdd/SKILL.md"); + assert!(found.contains(&Diagnostic::Stray { + path: nested, + name: Some("tdd".into()), + scope: Scope::Global, + why: Stray::Nested, + })); + // Claude never loads the nested one, so for Claude there is nothing to collide with. + assert_eq!(collisions(&found), [("tdd", &Readers::Recursive, 2)]); +} + +#[test] +fn a_skill_like_file_directly_in_the_folder_is_loose() { + let dir = tempfile::tempdir().unwrap(); + let skills = dir.path().join("skills"); + write(skills.join("notes.md"), "just notes, no frontmatter"); + write(skills.join("helper.md"), &skill_text("helper")); + + let found = diagnose(&[root(&skills, Scope::Global, &[Agent::Claude])]); + + assert_eq!( + found, + [Diagnostic::Stray { + path: skills.join("helper.md"), + name: Some("helper".into()), + scope: Scope::Global, + why: Stray::Loose, + }] + ); +} + +#[test] +fn hidden_folders_and_node_modules_are_not_searched() { + let dir = tempfile::tempdir().unwrap(); + let skills = dir.path().join("skills"); + skill(&skills, ".system/tdd", "tdd"); + skill(&skills, "work/node_modules/pkg", "pkg"); + + assert_eq!( + diagnose(&[root(&skills, Scope::Global, &[Agent::Claude])]), + [] + ); +} + +#[test] +fn a_skill_that_breaks_the_format_is_reported_with_each_rule_it_breaks() { + let dir = tempfile::tempdir().unwrap(); + let skills = dir.path().join("skills"); + write( + skills.join("Bad_Name/SKILL.md"), + "---\nname: Bad_Name\n---\n", + ); + write(skills.join("plain/SKILL.md"), "no frontmatter at all"); + skill(&skills, "fine", "fine"); + + let found = diagnose(&[root(&skills, Scope::Project, &[Agent::Claude])]); + + let invalid: Vec<(&str, &[Violation])> = found + .iter() + .filter_map(|d| match d { + Diagnostic::Invalid { + name, violations, .. + } => Some((name.as_str(), violations.as_slice())), + _ => None, + }) + .collect(); + assert_eq!( + invalid, + [ + ( + "Bad_Name", + &[Violation::NameCharacters, Violation::MissingDescription][..] + ), + ( + "plain", + &[Violation::MissingName, Violation::MissingDescription][..] + ), + ] + ); +} + +#[cfg(unix)] +#[test] +fn a_file_reachable_through_two_roots_is_reported_once() { + let dir = tempfile::tempdir().unwrap(); + let (store, linked) = (dir.path().join("store"), dir.path().join("linked")); + write(store.join("Bad/SKILL.md"), "---\nname: Bad\n---\n"); + fs::create_dir_all(&linked).unwrap(); + std::os::unix::fs::symlink(store.join("Bad"), linked.join("Bad")).unwrap(); + + let found = diagnose(&[ + root(&store, Scope::Global, &[Agent::Codex]), + root(&linked, Scope::Global, &[Agent::Claude]), + ]); + + assert_eq!(found.len(), 1); +} + +#[test] +fn the_roots_are_the_folders_each_tool_reads_with_shared_ones_merged() { + let env = Env::new("/h".into(), "/p".into()); + + let roots = roots(&env); + + let shared = roots + .iter() + .find(|r| r.dir == Path::new("/h/.agents/skills")) + .unwrap(); + assert_eq!(shared.agents, [Agent::Codex]); + let claude = roots + .iter() + .find(|r| r.dir == Path::new("/h/.claude/skills")) + .unwrap(); + assert_eq!( + (claude.scope, claude.agents.as_slice()), + (Scope::Global, &[Agent::Claude][..]) + ); + assert!( + roots + .iter() + .any(|r| r.dir == Path::new("/p/.claude/skills") && r.scope == Scope::Project) + ); +} + +#[test] +fn a_project_that_is_the_home_directory_does_not_repeat_the_user_level_roots() { + let dir = tempfile::tempdir().unwrap(); + let env = Env::new(dir.path().into(), dir.path().into()); + + let found = roots(&env); + + let mut dirs: Vec<_> = found.iter().map(|root| root.dir.clone()).collect(); + let all = dirs.len(); + dirs.sort(); + dirs.dedup(); + assert_eq!(dirs.len(), all); + assert!(found.iter().all(|root| root.scope == Scope::Global)); +} diff --git a/crates/skillz-harness/src/agent_skills/mod.rs b/crates/skillz-harness/src/agent_skills/mod.rs index 8f8c2fa..1af579a 100644 --- a/crates/skillz-harness/src/agent_skills/mod.rs +++ b/crates/skillz-harness/src/agent_skills/mod.rs @@ -3,10 +3,12 @@ //! `references/` and `assets/`. Harnesses extend the frontmatter with keys of their own; those //! are kept in `Frontmatter::extra` rather than dropped. +mod doctor; mod frontmatter; mod layout; mod validate; +pub use doctor::{Diagnostic, Instance, Readers, Root, Stray, diagnose, roots}; pub use frontmatter::{Frontmatter, parse, skill_name}; pub use layout::{Layout, layout}; pub use validate::{Violation, validate}; diff --git a/crates/skillz-harness/src/agent_skills/validate.rs b/crates/skillz-harness/src/agent_skills/validate.rs index cb1c51d..b6b3f95 100644 --- a/crates/skillz-harness/src/agent_skills/validate.rs +++ b/crates/skillz-harness/src/agent_skills/validate.rs @@ -5,7 +5,8 @@ const DESCRIPTION_MAX: usize = 1024; const COMPATIBILITY_MAX: usize = 500; /// A way a skill breaks the Agent Skills specification. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)] +#[serde(rename_all = "snake_case")] pub enum Violation { MissingName, NameTooLong, diff --git a/crates/skillz-harness/src/agents/claude/update.rs b/crates/skillz-harness/src/agents/claude/update.rs index 1129735..b5d67d5 100644 --- a/crates/skillz-harness/src/agents/claude/update.rs +++ b/crates/skillz-harness/src/agents/claude/update.rs @@ -69,10 +69,7 @@ mod tests { use crate::model::{Agent, Scope}; use crate::runner::CommandRunner; use crate::runner::Output; - use crate::update::check::spawn; use std::path::Path; - use std::sync::Arc; - use std::sync::mpsc; struct Heads { local: &'static str, @@ -144,15 +141,4 @@ mod tests { assert_eq!(results, [false; 3]); } - - #[test] - fn found_ids_arrive_on_the_channel() { - let dir = tempfile::tempdir().unwrap(); - let check: Arc = Arc::new(checker(dir.path(), "aaa", "bbb")); - let (tx, rx) = mpsc::channel(); - - spawn(check, vec![marketplace("mp")], tx); - - assert_eq!(rx.iter().collect::>(), ["marketplace:mp"]); - } } diff --git a/crates/skillz-harness/src/update/check.rs b/crates/skillz-harness/src/update/check.rs index b437552..62c7458 100644 --- a/crates/skillz-harness/src/update/check.rs +++ b/crates/skillz-harness/src/update/check.rs @@ -1,10 +1,6 @@ //! Finding out, without changing anything, whether an item has a newer version. Only what can //! be told reliably is checked; every other kind reads as having no update. -use std::sync::Arc; -use std::sync::mpsc::Sender; -use std::thread; - use crate::model::Installed; pub trait UpdateCheck: Send + Sync { @@ -24,15 +20,3 @@ impl UpdateCheck for NoCheck { pub fn any_available(checker: &dyn UpdateCheck, item: &Installed) -> bool { item.parts().iter().any(|part| checker.available(part)) } - -/// Check `items` on a thread of their own, sending the id of each that has an update as it is -/// found. Stops when the receiver is gone. -pub fn spawn(checker: Arc, items: Vec, found: Sender) { - thread::spawn(move || { - for item in items { - if any_available(checker.as_ref(), &item) && found.send(item.id).is_err() { - return; - } - } - }); -} diff --git a/crates/skillz-harness/src/update/mod.rs b/crates/skillz-harness/src/update/mod.rs index e958baf..8182252 100644 --- a/crates/skillz-harness/src/update/mod.rs +++ b/crates/skillz-harness/src/update/mod.rs @@ -39,10 +39,6 @@ fn part_steps(adapters: &[Box], item: &Installed, cwd: &Path) -> Ve } } -pub fn can_update(item: &Installed) -> bool { - !steps(&crate::agents::registry(), item, Path::new("")).is_empty() -} - /// A subagent copied from a source is copied again from it. fn recopy(item: &Installed, cwd: &Path) -> Vec { let Some(source) = item.source.clone() else { @@ -70,6 +66,11 @@ mod tests { use crate::model::Agent; use crate::model::Scope; + /// Whether any agent has a step to update `item`. + fn can_update(item: &Installed) -> bool { + !steps(&crate::agents::registry(), item, Path::new("")).is_empty() + } + fn item(name: &str, kind: Kind, installer: Installer) -> Installed { Installed { details: Default::default(), diff --git a/skills-lock.json b/skills-lock.json new file mode 100644 index 0000000..cd197a1 --- /dev/null +++ b/skills-lock.json @@ -0,0 +1,53 @@ +{ + "version": 1, + "skills": { + "code-review": { + "source": "mattpocock/skills", + "sourceType": "github", + "skillPath": "skills/engineering/code-review/SKILL.md", + "computedHash": "57cfd4ceb011f05e58a1a4f4cad3b2e03419d371f8990f4bcb32ff0d435a039f" + }, + "codebase-design": { + "source": "mattpocock/skills", + "sourceType": "github", + "skillPath": "skills/engineering/codebase-design/SKILL.md", + "computedHash": "b2888e4f4e8c0af3bfd557575a64b905c44e6248c3101d72077816882b3a92b9" + }, + "domain-modeling": { + "source": "mattpocock/skills", + "sourceType": "github", + "skillPath": "skills/engineering/domain-modeling/SKILL.md", + "computedHash": "b3eb40152b81f0c98fd2095a023c019452dbdce56f7540cc67fece2972db8369" + }, + "grilling": { + "source": "mattpocock/skills", + "sourceType": "github", + "skillPath": "skills/productivity/grilling/SKILL.md", + "computedHash": "ef1641a2047b71b60f1942cd35efb47d3afc9d584dff5a0b01f8c7db923aaa08" + }, + "improve-codebase-architecture": { + "source": "mattpocock/skills", + "sourceType": "github", + "skillPath": "skills/engineering/improve-codebase-architecture/SKILL.md", + "computedHash": "ac2c94885f34ff8492dc12aa4543182f661f32ea1722b8d6b6c2c7045af33ae3" + }, + "research": { + "source": "mattpocock/skills", + "sourceType": "github", + "skillPath": "skills/engineering/research/SKILL.md", + "computedHash": "c8c1cba327a6f824b554cd978079a3dadd7406d73174f8fb9bfef58824691970" + }, + "tdd": { + "source": "mattpocock/skills", + "sourceType": "github", + "skillPath": "skills/engineering/tdd/SKILL.md", + "computedHash": "daf55026f456af104a72fa43247f7bcec89e5127316dc5b1b8d675d6a9d8ce94" + }, + "writing-for-agents": { + "source": "mattpocock/skills", + "sourceType": "github", + "skillPath": "skills/productivity/writing-for-agents/SKILL.md", + "computedHash": "95da47fc97af998e85b7d7e6d57b3ac76727c1e290cfe9ea09005aacb826959f" + } + } +} diff --git a/src/app/app_paths.rs b/src/app/app_paths.rs index c9365d3..af695d7 100644 --- a/src/app/app_paths.rs +++ b/src/app/app_paths.rs @@ -13,6 +13,32 @@ pub fn store_path(env: &Env) -> PathBuf { skillz_dir(env).join("store.json") } +/// `text` with the home directory written `~`, wherever a path in it starts there. A path that +/// merely contains the home directory's name further along (`/srv/home/me/x`) is left alone. +pub fn tilde(text: &str, home: &Path) -> String { + let home = home.to_string_lossy(); + if home.is_empty() || home == "/" { + return text.to_string(); + } + let inside = format!("{home}/"); + let mut out = String::new(); + let mut rest = text; + while let Some(at) = rest.find(&inside) { + let starts_a_path = rest[..at] + .chars() + .next_back() + .is_none_or(|c| !(c.is_alphanumeric() || matches!(c, '/' | '.' | '-' | '_' | '~'))); + out.push_str(&rest[..at]); + out.push_str(if starts_a_path { "~/" } else { &inside }); + rest = &rest[at + inside.len()..]; + } + out.push_str(rest); + match out == *home { + true => "~".into(), + false => out, + } +} + /// Resolve local skill and subagent sources for this project. Repository references stay /// portable; explicit local paths stay local even after their directory disappears. pub fn resolve_source(env: &Env, source: &str) -> String { @@ -49,3 +75,23 @@ pub fn spec_in_env(env: &Env, mut spec: Spec) -> Spec { } spec } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_home_directory_is_written_as_tilde_wherever_a_path_starts_there() { + let home = Path::new("/home/me"); + + let inside = tilde("skills tdd [/home/me/code/skills]", home); + let exact = tilde("/home/me", home); + let other = tilde("/srv/home/mex/app", home); + let deeper = tilde("/srv/home/me/app", home); + + assert_eq!(inside, "skills tdd [~/code/skills]"); + assert_eq!(exact, "~"); + assert_eq!(other, "/srv/home/mex/app"); + assert_eq!(deeper, "/srv/home/me/app"); + } +} diff --git a/src/app/apply/mod.rs b/src/app/apply/mod.rs index 094633c..1e07b53 100644 --- a/src/app/apply/mod.rs +++ b/src/app/apply/mod.rs @@ -16,7 +16,7 @@ mod tests; pub use drift::{Drift, drift}; pub use run::{Report, Watch}; -pub use standing::{Standing, compare, holds, loaded, only_wanted_by}; +pub use standing::{Standing, compare, holds, loaded}; pub use switch::Switch; use crate::app::stale::Probe; diff --git a/src/app/apply/standing.rs b/src/app/apply/standing.rs index 4428d3a..a9249a6 100644 --- a/src/app/apply/standing.rs +++ b/src/app/apply/standing.rs @@ -85,24 +85,6 @@ pub fn holds(installed: &[Installed], entry: &Spec) -> bool { compare(&profile.resolved(), installed).missing.is_empty() } -/// The ids of installed items that `dropped` wants and `kept` does not: what is left over once -/// only the kept entries are to stay. -pub fn only_wanted_by(dropped: &[Spec], kept: &[Spec], installed: &[Installed]) -> Vec { - let unwanted_by = |entries: &[Spec]| -> HashSet { - compare(entries, installed) - .extras - .into_iter() - .map(|extra| extra.item.id) - .collect() - }; - let (not_dropped, not_kept) = (unwanted_by(dropped), unwanted_by(kept)); - installed - .iter() - .filter(|item| !not_dropped.contains(&item.id) && not_kept.contains(&item.id)) - .map(|item| item.id.clone()) - .collect() -} - fn distinct(entries: &[Spec]) -> Vec { let mut seen: Vec = Vec::new(); for entry in entries { @@ -243,24 +225,6 @@ mod tests { assert_eq!(not_wanting.extras.len(), 1); } - #[test] - fn dropping_an_entry_removes_only_what_no_kept_entry_wants() { - let live = [sourced_skill("a"), sourced_skill("b"), sourced_skill("c")]; - - let removable = only_wanted_by(&[skill_entry(&["a"])], &[skill_entry(&["b"])], &live); - - assert_eq!(removable, ["skill:a"]); - } - - #[test] - fn an_item_a_kept_entry_also_wants_stays() { - let live = [sourced_skill("a")]; - - let removable = only_wanted_by(&[skill_entry(&["a"])], &[skill_entry(&["a"])], &live); - - assert!(removable.is_empty()); - } - fn profile(name: &str, skills: &[&str]) -> Profile { let mut p = Profile::new(name); p.entries = vec![skill_entry(skills)]; diff --git a/src/app/info.rs b/src/app/info.rs index 722663c..efefee8 100644 --- a/src/app/info.rs +++ b/src/app/info.rs @@ -13,7 +13,7 @@ pub enum Used { At(u64), } -fn describe_installer(installer: Installer) -> &'static str { +pub(crate) fn describe_installer(installer: Installer) -> &'static str { match installer { Installer::Npx => "npx skills", Installer::ClaudeCli => "claude plugin", diff --git a/src/app/json.rs b/src/app/json.rs new file mode 100644 index 0000000..29eb750 --- /dev/null +++ b/src/app/json.rs @@ -0,0 +1,47 @@ +//! The JSON form of a data item, so any command can offer `--json` for scripts and agents by +//! calling `write_json`. Every type that derives `Serialize` has it; a new data type needs +//! nothing more than that derive. + +use std::io::Write; + +use serde::Serialize; + +pub trait Json { + /// The item as pretty-printed JSON and a newline. + fn write_json(&self, out: &mut dyn Write) -> anyhow::Result<()>; +} + +impl Json for T { + fn write_json(&self, out: &mut dyn Write) -> anyhow::Result<()> { + serde_json::to_writer_pretty(&mut *out, self)?; + writeln!(out)?; + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::{Value, json}; + + #[derive(Serialize)] + struct Thing { + name: &'static str, + } + + fn written(item: &(impl Json + ?Sized)) -> Value { + let mut out = Vec::new(); + item.write_json(&mut out).unwrap(); + assert_eq!(out.last(), Some(&b'\n')); + serde_json::from_slice(&out).unwrap() + } + + #[test] + fn a_data_item_and_a_list_of_them_write_the_json_they_serialize_to() { + let one = written(&Thing { name: "a" }); + let many = written(&vec![Thing { name: "a" }, Thing { name: "b" }]); + + assert_eq!(one, json!({"name": "a"})); + assert_eq!(many, json!([{"name": "a"}, {"name": "b"}])); + } +} diff --git a/src/app/library/item.rs b/src/app/library/item.rs index 99039fc..9fd24c4 100644 --- a/src/app/library/item.rs +++ b/src/app/library/item.rs @@ -26,17 +26,6 @@ impl ItemKind { } } - /// What several of this kind are called: `skills`, `MCP servers`. - pub fn plural(self) -> &'static str { - match self { - ItemKind::Skill => "skills", - ItemKind::Plugin => "plugins", - ItemKind::Mcp => "MCP servers", - ItemKind::Hook => "hooks", - ItemKind::Subagent => "agents", - } - } - pub fn of_entry(entry: &Spec) -> ItemKind { match entry { Spec::Skill { .. } => ItemKind::Skill, diff --git a/src/app/location.rs b/src/app/location.rs index 2086914..5c44bb1 100644 --- a/src/app/location.rs +++ b/src/app/location.rs @@ -1,6 +1,5 @@ //! Where an installed item lives on disk, so it is clear why it counts for its group. -use crate::app::merge::tag; use skillz_harness::model::Installed; /// The location discovery recorded for this installed item. @@ -11,22 +10,6 @@ pub fn location(item: &Installed) -> String { .unwrap_or_default() } -/// One `agents: location` per copy of an item seen through several agents; none for a lone item. -pub fn places(item: &Installed) -> Vec { - item.members - .iter() - .map(|m| format!("{}: {}", tag(&m.agents), location(m))) - .collect() -} - -/// What to show beside an item: its location, or every copy's with its agents. -pub fn detail(item: &Installed) -> String { - match places(item) { - places if places.is_empty() => location(item), - places => places.join("; "), - } -} - #[cfg(test)] mod tests { use super::*; diff --git a/src/app/mod.rs b/src/app/mod.rs index 792800c..6fc6a1d 100644 --- a/src/app/mod.rs +++ b/src/app/mod.rs @@ -6,6 +6,7 @@ pub mod app_paths; pub mod apply; pub(crate) mod info; pub mod install; +pub mod json; pub mod library; pub(crate) mod location; pub(crate) mod matcher; @@ -16,6 +17,7 @@ pub mod prompt; pub mod prune; pub(crate) mod remove; pub mod review; +pub mod rule; pub(crate) mod snapshot; pub(crate) mod spinner; pub mod stale; diff --git a/src/app/review.rs b/src/app/review.rs index 3842b44..54a5c89 100644 --- a/src/app/review.rs +++ b/src/app/review.rs @@ -25,6 +25,17 @@ impl Group { } } + /// How the plan modal titles the group: what is being done to its entries. + pub fn heading(self) -> &'static str { + match self { + Group::Keep => "keeping", + Group::Remove => "removing", + Group::Install => "installing", + Group::Update => "updating", + Group::Skip => "skipping", + } + } + pub const ALL: [Group; 5] = [ Group::Keep, Group::Remove, @@ -44,19 +55,53 @@ pub struct PlanView { pub steps: Vec, } -/// The agents a plan offers to act on, each checked or not, and the one under the cursor. +/// One item a plan installs or removes, which the user may leave out. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Pick { + pub group: Group, + /// What names it in this plan: the entry as text, or the installed item's id. + pub id: String, + /// The ids of the installed copies behind it. Narrowing the agents folds a shared item down to + /// the copies that remain and so renames it; these still say it is the same item. + pub copies: Vec, + pub label: String, + pub on: bool, +} + +/// An item a plan lists, before the user's checks are applied to it. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Listed { + pub group: Group, + pub id: String, + pub copies: Vec, + pub label: String, +} + +/// What a plan offers to narrow: the agents it reaches and the items it installs or removes, +/// each checked or not, and the one under the cursor (the agents first, then the items). #[derive(Debug, Clone, PartialEq, Eq, Default)] pub struct Targets { + /// Empty when the plan reaches no more than one agent: there is nothing to choose. pub agents: Vec<(Agent, bool)>, + pub items: Vec, pub cursor: usize, + /// Items the user unchecked that the plan stopped listing (narrowing the agents hid them): + /// they stay unchecked should they come back. + pub left_out: Vec, } impl Targets { - /// All of `agents`, checked. + /// All of `agents`, checked; none are offered for one agent or fewer. pub fn all(agents: Vec) -> Self { + let offered = match agents.len() > 1 { + true => agents, + false => vec![], + }; Targets { - agents: agents.into_iter().map(|agent| (agent, true)).collect(), + agents: offered.into_iter().map(|agent| (agent, true)).collect(), + items: vec![], cursor: 0, + left_out: vec![], } } @@ -68,15 +113,63 @@ impl Targets { .collect() } + /// The agents to plan for, when the user can choose among them. + pub fn narrowing(&self) -> Option> { + (!self.agents.is_empty()).then(|| self.checked()) + } + + /// How many lines the cursor can rest on. + pub fn rows(&self) -> usize { + self.agents.len() + self.items.len() + } + + /// Whether the item called `id` is left in the plan; one the plan does not list is. + pub fn includes(&self, id: &str) -> bool { + self.items.iter().find(|p| p.id == id).is_none_or(|p| p.on) + } + + /// The plan's items as they are now, keeping what the user already unchecked. + pub fn sync_items(&mut self, listed: Vec) { + let known: Vec = std::mem::take(&mut self.items) + .into_iter() + .chain(std::mem::take(&mut self.left_out)) + .collect(); + let same = |old: &Pick, new: &Listed| { + old.id == new.id || old.copies.iter().any(|copy| new.copies.contains(copy)) + }; + self.left_out = known + .iter() + .filter(|old| !old.on && !listed.iter().any(|new| same(old, new))) + .cloned() + .collect(); + self.items = listed + .into_iter() + .map(|new| Pick { + on: known + .iter() + .find(|old| same(old, &new)) + .is_none_or(|p| p.on), + group: new.group, + id: new.id, + copies: new.copies, + label: new.label, + }) + .collect(); + self.cursor = self.cursor.min(self.rows().saturating_sub(1)); + } + pub fn toggled(mut self) -> Self { + let agents = self.agents.len(); if let Some((_, on)) = self.agents.get_mut(self.cursor) { *on = !*on; + } else if let Some(pick) = self.items.get_mut(self.cursor - agents) { + pick.on = !pick.on; } self } pub fn moved(mut self, down: bool) -> Self { - let last = self.agents.len().saturating_sub(1); + let last = self.rows().saturating_sub(1); self.cursor = match down { true => (self.cursor + 1).min(last), false => self.cursor.saturating_sub(1), @@ -239,6 +332,95 @@ mod tests { ); } + fn item(group: Group, id: &str, copies: &[&str]) -> Listed { + Listed { + group, + id: id.into(), + copies: copies.iter().map(|copy| copy.to_string()).collect(), + label: id.into(), + } + } + + fn listed() -> Vec { + vec![ + item(Group::Install, "a", &[]), + item(Group::Remove, "b", &["b"]), + ] + } + + #[test] + fn syncing_items_keeps_what_was_unchecked_and_includes_new_ones() { + let mut targets = Targets::all(vec![]); + targets.sync_items(listed()); + targets.cursor = 1; + let targets = targets.toggled(); + + let mut again = targets.clone(); + again.sync_items(vec![ + item(Group::Remove, "b", &["b"]), + item(Group::Install, "c", &[]), + ]); + + assert!(!again.includes("b") && again.includes("c") && again.includes("unlisted")); + assert!(!targets.includes("b") && targets.includes("a")); + } + + #[test] + fn an_item_renamed_by_narrowing_the_agents_stays_unchecked() { + let mut targets = Targets::all(vec![Agent::Claude, Agent::Codex]); + targets.sync_items(vec![item( + Group::Remove, + "subagent:claude:reviewer", + &["subagent:claude:reviewer", "subagent:codex:reviewer"], + )]); + targets.cursor = 2; + let mut targets = targets.toggled(); + + targets.sync_items(vec![item( + Group::Remove, + "subagent:codex:reviewer", + &["subagent:codex:reviewer"], + )]); + + assert!(!targets.includes("subagent:codex:reviewer")); + } + + #[test] + fn an_unchecked_item_that_drops_out_of_the_plan_is_still_unchecked_when_it_returns() { + let mut targets = Targets::all(vec![Agent::Claude, Agent::Codex]); + targets.sync_items(vec![item(Group::Install, "a", &[])]); + targets.cursor = 2; + let mut targets = targets.toggled(); + + targets.sync_items(vec![]); + targets.sync_items(vec![item(Group::Install, "a", &[])]); + + assert!(!targets.includes("a")); + } + + #[test] + fn the_cursor_runs_over_the_agents_then_the_items() { + let mut targets = Targets::all(vec![Agent::Claude, Agent::Codex]); + targets.sync_items(listed()); + + let at_item = targets.clone().moved(true).moved(true); + let toggled = at_item.clone().toggled(); + + assert_eq!(targets.rows(), 4); + assert_eq!(toggled.checked(), [Agent::Claude, Agent::Codex]); + assert!(!toggled.includes("a")); + assert_eq!(toggled.moved(true).moved(true).moved(true).cursor, 3); + } + + #[test] + fn one_agent_or_none_offers_no_agent_choice() { + assert_eq!(Targets::all(vec![Agent::Claude]).narrowing(), None); + assert_eq!( + Targets::all(vec![Agent::Claude, Agent::Codex]).narrowing(), + Some(vec![Agent::Claude, Agent::Codex]) + ); + } + #[test] fn problems_list_failures_then_leftovers() { let outcome = Outcome { diff --git a/src/app/rule.rs b/src/app/rule.rs new file mode 100644 index 0000000..50727ba --- /dev/null +++ b/src/app/rule.rs @@ -0,0 +1,35 @@ +//! A horizontal rule with a label in the middle: `──────── global ────────`. The list's divider +//! and the command line's group headings are both drawn with it. + +/// How wide the command line draws a rule: the width of a terminal that is not asked. +pub const RULE_WIDTH: usize = 72; + +/// `label` between two runs of `rule`, `width` cells in all and the label centred. A label too +/// wide for that stands alone. +pub fn centered_rule(label: &str, width: usize, rule: &str) -> String { + let label = format!(" {label} "); + let room = width.saturating_sub(label.chars().count()); + let (left, right) = (room / 2, room - room / 2); + format!("{}{label}{}", rule.repeat(left), rule.repeat(right)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_label_sits_in_the_middle_and_the_whole_is_exactly_as_wide() { + let line = centered_rule("global", 20, "─"); + + let before = line.chars().take_while(|&c| c == '─').count(); + let after = line.chars().rev().take_while(|&c| c == '─').count(); + assert_eq!(line.chars().count(), 20); + assert!(before.abs_diff(after) <= 1); + assert!(line.contains(" global ")); + } + + #[test] + fn a_label_wider_than_the_width_is_kept_whole() { + assert_eq!(centered_rule("a-long-name", 4, "─"), " a-long-name "); + } +} diff --git a/src/app/workspace.rs b/src/app/workspace.rs index 58d0462..1705561 100644 --- a/src/app/workspace.rs +++ b/src/app/workspace.rs @@ -1,5 +1,5 @@ //! What the workspace screen exchanges with the flow that drives it: the `Act` the user asked -//! for, the `Model` the tabs show, the `Synced` outcomes of background syncs and the `Screen` +//! for, the `Model` the list shows, the `Synced` outcomes of background syncs and the `Screen` //! the flow feeds. Things are named by id, entry or profile name, so an act still means the //! same if the lists changed while it was in flight. @@ -7,75 +7,23 @@ use std::sync::mpsc::Receiver; use std::sync::{Arc, Mutex}; use crate::app::library::Catalog; -use crate::app::profile::Profile; use skillz_harness::Spec; use skillz_harness::model::{Agent, Installed, Scope}; #[derive(Debug, Clone, PartialEq, Eq)] pub enum Act { Quit, - /// Remove the installed items with these ids in `scope`, as one plan. - Remove { + /// Install these entries and remove the installed items with these ids, as one plan, in + /// `scope`. + Change { scope: Scope, - ids: Vec, - }, - /// Bring the installed items with these ids in `scope` to their latest version, as one plan. - Update { - scope: Scope, - ids: Vec, - }, - /// Install what the profile has that `scope` lacks. - Apply { - scope: Scope, - profile: String, - }, - /// Install what `source` (`owner/repo`, a git URL or a path) offers each agent in `scope`. - InstallSource { - scope: Scope, - source: String, - }, - /// Add the item a one-line entry describes to the library. - LibraryAdd { - spec: String, - }, - /// Install this library entry in `scope`, for the tools its agents name. - LibraryInstall { - scope: Scope, - entry: Spec, - }, - LibraryRemove(Spec), - /// Make `scope` hold exactly what the profile has, removing the rest. - ApplyExact { - scope: Scope, - profile: String, - }, - /// Make the project hold these entries of its profile and not the rest of it: install the - /// entries, remove the installed items with these ids. - Subset { install: Vec, remove: Vec, }, - /// Make a profile of this name holding these entries. - CreateProfile { - name: String, - entries: Vec, - }, - /// Store what the project has installed as a new profile. - SaveCurrent { - name: String, - }, - /// Replace the profile's entries. - SetEntries { - profile: String, - entries: Vec, - }, - DeleteProfile { - name: String, - }, } -/// What the tabs show: a snapshot of the project, the library and the profiles, read again -/// after every act. +/// What the list shows: a snapshot of the project, the user's installs and the library, read +/// again after every act. #[derive(Default)] pub struct Model { /// The project directory as shown, home abbreviated. @@ -87,12 +35,6 @@ pub struct Model { /// The coding tools an install can be made for. pub agents: Vec, pub library: Catalog, - /// The readable profiles, with what they extend already merged in. - pub profiles: Vec, - /// The profile last applied to the project. - pub applied: Option, - /// The profile last applied at user level. - pub applied_global: Option, /// Shown as a toast: what the last act did or why it failed. pub notice: Option, } @@ -109,12 +51,8 @@ pub struct Synced { pub trait Screen { /// Show the new snapshot and toast what the last act reported. fn load(&mut self, model: Model); - /// Mark the items whose ids arrive on `found` as having an update. - fn watch_updates(&mut self, found: Receiver); /// Show the outcome of each library sync that arrives on `done`. fn watch_syncs(&mut self, done: Receiver); - /// Drop the marks of items that were just updated. - fn forget_updates(&mut self, ids: &[String]); } /// A screen shared with whatever redraws it while a change runs. diff --git a/src/cli/args.rs b/src/cli/args.rs index 3f31f78..4191c25 100644 --- a/src/cli/args.rs +++ b/src/cli/args.rs @@ -4,7 +4,7 @@ use clap::{Args, Parser, Subcommand}; use super::library_args::LibraryCommand; use super::profile_args::ProfileCommand; -use skillz_harness::model::{Agent, Installed, Kind}; +use skillz_harness::model::{Agent, Installed, Kind, Scope}; #[derive(Debug, Parser)] #[command( @@ -35,6 +35,8 @@ pub enum Command { Reset(ResetArgs), /// Find duplicate skills and skills/plugins unused for 7+ days, then remove the ones picked Prune(PruneArgs), + /// Check the skills on disk for name collisions, stray skill files, format problems and broken links + Doctor(DoctorArgs), /// Install what a project lacks of a profile (with --exact, remove the rest) Use(UseArgs), /// Create, inspect and delete profiles @@ -89,6 +91,19 @@ pub struct ListArgs { pub interactive: bool, } +#[derive(Debug, Args)] +pub struct DoctorArgs { + /// Project directory (default: cwd) + #[arg(short = 'p', long)] + pub project: Option, + /// Only the user's skills, not the project's + #[arg(short, long, conflicts_with = "project")] + pub global: bool, + /// Print the diagnostics as JSON for scripts and agents + #[arg(long)] + pub json: bool, +} + #[derive(Debug, Args)] pub struct RunArgs { /// Profile to load into its own isolated Claude and Codex config dirs @@ -282,6 +297,41 @@ impl Filter { } } +/// The scope whose plugins list the command opens instead of printing: a plain `list` of the +/// project, or of the user's installs with `-g`. A query, a flag or a kind filter asks for the +/// printed listing. +pub(super) fn plugin_list(command: &Command) -> Option { + match command { + Command::List(args) => args.plugin_list(), + _ => None, + } +} + +impl ListArgs { + pub(super) fn plugin_list(&self) -> Option { + let plain = self.target.is_none() + && !(self.all || self.json || self.check || self.available || self.interactive) + && !self.filter.narrows(); + plain.then_some(match self.filter.global { + true => Scope::Global, + false => Scope::Project, + }) + } +} + +impl Filter { + /// Asks for some kinds or agents only. + fn narrows(&self) -> bool { + self.skills + || self.hooks + || self.plugins + || self.marketplaces + || self.mcp + || self.subagents + || !self.agents.is_empty() + } +} + /// `--yes` (prune: `--force`) swaps the interactive prompter for one that picks and confirms everything. pub(super) fn wants_auto_yes(command: &Command) -> bool { match command { @@ -316,6 +366,47 @@ pub(super) fn wants_auto_yes(command: &Command) -> bool { mod tests { use super::*; + fn opens(args: &[&str]) -> Option { + let cli = Cli::try_parse_from(std::iter::once("skillz").chain(args.iter().copied())); + cli.unwrap().command.as_ref().and_then(plugin_list) + } + + #[test] + fn a_plain_list_opens_the_projects_plugins_and_dash_g_the_users() { + let plain = opens(&["list"]); + let in_project = opens(&["ls", "-p", "."]); + let user = opens(&["list", "-g"]); + let long = opens(&["list", "--global"]); + + assert_eq!( + (plain, in_project, user, long), + ( + Some(Scope::Project), + Some(Scope::Project), + Some(Scope::Global), + Some(Scope::Global) + ) + ); + } + + #[test] + fn json_a_query_or_any_other_flag_prints_instead_of_opening_the_list() { + let printed = [ + &["list", "--json"][..], + &["list", "-g", "--json"], + &["list", "--json", "--check"], + &["list", "tdd"], + &["list", "--all"], + &["list", "-i"], + &["list", "-g", "--skills"], + &["list", "--skills"], + &["list", "--available"], + ] + .map(opens); + + assert_eq!(printed, [None; 9]); + } + #[test] fn the_command_tree_is_valid_and_profile_commands_parse() { use clap::CommandFactory; diff --git a/src/cli/doctor.rs b/src/cli/doctor.rs new file mode 100644 index 0000000..59534f2 --- /dev/null +++ b/src/cli/doctor.rs @@ -0,0 +1,213 @@ +//! `skillz doctor`: what is wrong with the skills on disk. Read-only. + +use std::io::Write; +use std::path::Path; + +use super::args::DoctorArgs; +use super::deps::Deps; +use super::scope::resolve_project; +use crate::app::app_paths::tilde; +use crate::app::json::Json; +use crate::app::rule::{RULE_WIDTH, centered_rule}; +use skillz_harness::agent_skills::{self, Diagnostic, Instance, Readers, Stray, Violation}; +use skillz_harness::model::{Agent, Scope}; + +pub(super) fn doctor(deps: &Deps, args: &DoctorArgs, out: &mut dyn Write) -> anyhow::Result<()> { + let env = resolve_project(deps, args.project.as_deref())?; + let mut roots = agent_skills::roots(&env); + if args.global { + roots.retain(|root| root.scope == Scope::Global); + } + let found = agent_skills::diagnose(&roots); + if args.json { + return found.write_json(out); + } + report(&found, &deps.home) + .iter() + .try_for_each(|line| writeln!(out, "{line}"))?; + Ok(()) +} + +/// The diagnostics a person reads: a rule per kind of problem, `~` for the home directory. +fn report(found: &[Diagnostic], home: &Path) -> Vec { + if found.is_empty() { + return vec!["No problems found with your skills.".into()]; + } + let sections: [(&str, Vec); 4] = [ + ("name collisions", collision_lines(found, home)), + ("stray skill files", stray_lines(found, home)), + ("format problems", invalid_lines(found, home)), + ("broken links", dangling_lines(found, home)), + ]; + let mut lines = Vec::new(); + for (title, body) in sections.into_iter().filter(|(_, body)| !body.is_empty()) { + if !lines.is_empty() { + lines.push(String::new()); + } + lines.push(centered_rule(title, RULE_WIDTH, "─")); + lines.extend(body); + } + lines +} + +fn collision_lines(found: &[Diagnostic], home: &Path) -> Vec { + let mut lines = Vec::new(); + for diagnostic in found { + let Diagnostic::Collision { + name, + readers, + copies, + } = diagnostic + else { + continue; + }; + lines.push(format!("{name} ({})", who(readers))); + lines.extend(copies.iter().map(|copy| copy_line(copy, home))); + } + lines +} + +fn who(readers: &Readers) -> String { + match readers { + Readers::Agents(agents) => { + let names: Vec = agents.iter().map(Agent::to_string).collect(); + format!("read as skills by {}", names.join(", ")) + } + Readers::Recursive => "seen by tools that also load nested and loose skill files".into(), + } +} + +/// A path as the user reads it: their home directory as `~`. +fn shown(path: &Path, home: &Path) -> String { + tilde(&path.display().to_string(), home) +} + +fn copy_line(copy: &Instance, home: &Path) -> String { + let path = shown(©.path, home); + match copy.stray { + None => format!(" {path}"), + Some(why) => format!(" {path} [{}]", stray_reason(why)), + } +} + +fn stray_lines(found: &[Diagnostic], home: &Path) -> Vec { + found + .iter() + .filter_map(|d| match d { + Diagnostic::Stray { + path, name, why, .. + } => Some(format!( + " {} {} [{}]", + shown(path, home), + name.as_deref().unwrap_or("(no name)"), + stray_reason(*why) + )), + _ => None, + }) + .collect() +} + +fn stray_reason(why: Stray) -> &'static str { + match why { + Stray::Nested => "SKILL.md below a folder that is not a skill", + Stray::WrongName => "skill frontmatter in a file not called SKILL.md", + Stray::Loose => "skill file outside any skill folder", + } +} + +fn invalid_lines(found: &[Diagnostic], home: &Path) -> Vec { + let mut lines = Vec::new(); + for diagnostic in found { + if let Diagnostic::Invalid { + path, + name, + violations, + .. + } = diagnostic + { + lines.push(format!("{name} {}", shown(path, home))); + lines.extend(violations.iter().map(|v| format!(" {}", violation(*v)))); + } + } + lines +} + +fn violation(violation: Violation) -> &'static str { + match violation { + Violation::MissingName => "has no name", + Violation::NameTooLong => "name is longer than 64 characters", + Violation::NameCharacters => "name uses characters other than a-z, 0-9 and hyphens", + Violation::NameHyphens => "name starts or ends with a hyphen or has two in a row", + Violation::NameIsNotTheDirectory => "name differs from its folder's name", + Violation::MissingDescription => "has no description", + Violation::DescriptionTooLong => "description is longer than 1024 characters", + Violation::CompatibilityTooLong => "compatibility is longer than 500 characters", + } +} + +fn dangling_lines(found: &[Diagnostic], home: &Path) -> Vec { + found + .iter() + .filter_map(|d| match d { + Diagnostic::Dangling { path, target, .. } => { + let shown = |p: &Path| shown(p, home); + Some(match target { + Some(target) => format!(" {} → {}", shown(path), shown(target)), + None => format!(" {}", shown(path)), + }) + } + _ => None, + }) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + use skillz_harness::agent_skills::Root; + use std::fs; + + fn skill(dir: &Path, name: &str) { + fs::create_dir_all(dir).unwrap(); + fs::write( + dir.join("SKILL.md"), + format!("---\nname: {name}\ndescription: d\n---\n"), + ) + .unwrap(); + } + + #[test] + fn a_clean_set_of_skills_says_so_with_one_line() { + assert_eq!(report(&[], Path::new("/h")).len(), 1); + } + + #[test] + fn problems_come_under_a_rule_per_kind_with_the_home_directory_as_tilde() { + let home = tempfile::tempdir().unwrap(); + let skills = home.path().join(".agents/skills"); + skill(&skills.join("tdd"), "tdd"); + skill(&skills.join("work/old"), "tdd"); + skill(&skills.join("bad"), "Bad"); + let roots = [Root { + dir: skills.clone(), + scope: Scope::Global, + agents: vec![Agent::Codex], + }]; + + let lines = report(&agent_skills::diagnose(&roots), home.path()); + + let rules: Vec<&String> = lines.iter().filter(|l| l.starts_with('─')).collect(); + assert_eq!(rules.len(), 3); + assert!(rules.iter().all(|r| r.chars().count() == RULE_WIDTH)); + assert!( + lines + .iter() + .any(|l| l.contains("~/.agents/skills/work/old")) + ); + assert!( + !lines + .iter() + .any(|l| l.contains(&home.path().display().to_string())) + ); + } +} diff --git a/src/cli/library/listing.rs b/src/cli/library/listing.rs index 3df4bab..46fa83b 100644 --- a/src/cli/library/listing.rs +++ b/src/cli/library/listing.rs @@ -5,13 +5,16 @@ use std::io::Write; use super::super::deps::Deps; use super::super::library_args::LibraryListArgs; use super::super::scope::installed; -use super::rows::{Row, rows}; +use super::rows::{Row, grouped, rows}; use crate::app::apply::holds; +use crate::app::json::Json; use crate::app::library::{Held, LibraryItem}; +use crate::app::rule::RULE_WIDTH; use crate::app::stale::Disk; use crate::app::store::Store; use skillz_harness::env::Env; use skillz_harness::model::Scope; +use std::path::Path; /// What the project and the user have installed, as the library tells it apart. fn held_by(deps: &Deps, env: &Env) -> Held { @@ -33,7 +36,8 @@ pub(super) fn list( .iter() .filter(|item| kinds.is_empty() || kinds.contains(&item.kind())) .collect(); - write_rows(rows(shown, (&held_by(deps, env), &Disk)), args.json, out) + let rows = rows(shown, (&held_by(deps, env), &Disk)); + write_rows(&rows, (args.json, &deps.home), out) } /// The library items the project, or with `Scope::Global` the user, does not have installed. @@ -50,16 +54,24 @@ pub(in crate::cli) fn available( .iter() .filter(|item| !holds(&here, &item.entry)) .collect(); - write_rows(rows(offered, (&held_by(deps, env), &Disk)), json, out) + let rows = rows(offered, (&held_by(deps, env), &Disk)); + write_rows(&rows, (json, &deps.home), out) } -fn write_rows(rows: Vec, json: bool, out: &mut dyn Write) -> anyhow::Result<()> { +/// JSON keeps every path as it is; the listing a person reads groups the items by package and +/// writes the home directory `~`. +fn write_rows( + rows: &[Row], + (json, home): (bool, &Path), + out: &mut dyn Write, +) -> anyhow::Result<()> { if json { let json: Vec<_> = rows.iter().map(Row::json).collect(); - writeln!(out, "{}", serde_json::to_string_pretty(&json)?)?; + json.write_json(out)?; } else { - rows.iter() - .try_for_each(|row| writeln!(out, "{}", row.line()))?; + grouped(rows, home, RULE_WIDTH) + .iter() + .try_for_each(|line| writeln!(out, "{line}"))?; } Ok(()) } diff --git a/src/cli/library/mod.rs b/src/cli/library/mod.rs index 3e36722..b95401f 100644 --- a/src/cli/library/mod.rs +++ b/src/cli/library/mod.rs @@ -1,4 +1,4 @@ -//! `skillz library`: the library the workspace's Library tab shows, from the command line. +//! `skillz library`: the library of everything skillz has seen or been given, from the command line. mod install; mod listing; diff --git a/src/cli/library/rows.rs b/src/cli/library/rows.rs index dc382b6..9e077bb 100644 --- a/src/cli/library/rows.rs +++ b/src/cli/library/rows.rs @@ -2,8 +2,15 @@ use serde_json::{Value, json}; +use std::collections::BTreeMap; +use std::path::Path; + +use crate::app::app_paths::tilde; use crate::app::library::{Cue, Held, LibraryItem, Presence}; +use crate::app::package::Package; +use crate::app::rule::centered_rule; use crate::app::stale::{Probe, missing_source}; +use skillz_harness::redact::redact; pub(in crate::cli) struct Row<'a> { item: &'a LibraryItem, @@ -26,7 +33,66 @@ pub(in crate::cli) fn rows<'a>( .collect() } +/// Named packages first by name, then the folders hand-made items live in, MCP servers and +/// hooks; the title is what the rule over the group says. +fn group_of(item: &LibraryItem) -> (u8, String) { + match Package::of_entry(&item.entry) { + Package::Source(name) | Package::Marketplace(name) => (0, name), + Package::Local => (1, item.source()), + Package::Mcp => (2, Package::Mcp.title()), + Package::Hooks => (3, Package::Hooks.title()), + } +} + +/// The rows under a rule per package or folder, `~` for the home directory, one line per item. +pub(in crate::cli) fn grouped(rows: &[Row], home: &Path, width: usize) -> Vec { + let mut groups: BTreeMap<(u8, String), Vec<&Row>> = BTreeMap::new(); + for row in rows { + let (rank, title) = group_of(row.item); + groups + .entry((rank, title.to_lowercase())) + .or_default() + .push(row); + } + let mut lines = Vec::new(); + for (_, mut members) in groups { + members.sort_by_key(|row| (row.item.kind(), row.item.short_label().to_lowercase())); + if !lines.is_empty() { + lines.push(String::new()); + } + let title = tilde(&redact(&group_of(members[0].item).1), home); + lines.push(centered_rule(&title, width, "─")); + lines.extend(members.iter().map(|row| row.entry_line(home))); + } + lines +} + impl Row<'_> { + /// `tdd skill project global (detected)`: the item inside its package, what it is and where + /// it is installed. + fn entry_line(&self, home: &Path) -> String { + let places = [ + (self.presence.project, "project"), + (self.presence.global, "global"), + ] + .into_iter() + .filter_map(|(here, name)| here.then_some(name)) + .collect::>() + .join(" "); + let origin = format!("{:?}", Cue::of(self.item.provenance.as_ref())).to_lowercase(); + let places = if places.is_empty() { + "-".into() + } else { + places + }; + let stale = if self.stale { " ! missing source" } else { "" }; + let name = tilde(&self.item.short_label(), home); + format!( + " {name:<30} {:<11} {places:<15} ({origin}){stale}", + self.item.kind().noun() + ) + } + pub fn json(&self) -> Value { let provenance = self.item.provenance.as_ref(); json!({ @@ -42,22 +108,6 @@ impl Row<'_> { "installed": {"project": self.presence.project, "global": self.presence.global}, }) } - - pub fn line(&self) -> String { - let places = [ - (self.presence.project, "project"), - (self.presence.global, "global"), - ] - .into_iter() - .filter_map(|(here, name)| here.then_some(name)) - .collect::>() - .join(" "); - let origin = format!("{:?}", Cue::of(self.item.provenance.as_ref())).to_lowercase(); - let stale = if self.stale { "! missing source" } else { "" }; - format!("{} ({origin}) {places} {stale}", self.item.label) - .trim_end() - .to_string() - } } #[cfg(test)] @@ -101,4 +151,43 @@ mod tests { assert_eq!(rows[0].json()["stale"], true); assert_eq!(rows[1].json()["stale"], false); } + + fn at(path: &str, name: &str) -> LibraryItem { + LibraryItem::from_entry(skill(path, name)) + } + + #[test] + fn items_are_grouped_under_a_rule_per_package_with_the_home_directory_as_tilde() { + let (a, b, c) = ( + at("/home/me/code/skills", "tdd"), + at("/home/me/code/skills", "grill"), + at("o/r", "other"), + ); + let held = Held::of(&[], &[]); + let rows = rows(vec![&a, &c, &b], (&held, &Disk)); + + let lines = grouped(&rows, Path::new("/home/me"), 40); + + let rules: Vec<&String> = lines.iter().filter(|l| l.starts_with('─')).collect(); + assert_eq!(rules.len(), 2); + assert!(rules.iter().all(|r| r.chars().count() == 40)); + assert!(rules.iter().any(|r| r.contains(" ~/code/skills "))); + assert!(!lines.iter().any(|l| l.contains("/home/me"))); + // The package's two items sit under its rule, `grill` before `tdd`. + let at_rule = lines + .iter() + .position(|l| l.contains("~/code/skills")) + .unwrap(); + assert!(lines[at_rule + 1].contains("grill") && lines[at_rule + 2].contains("tdd")); + } + + #[test] + fn json_keeps_the_paths_as_they_are() { + let item = at("/home/me/code/skills", "tdd"); + let held = Held::of(&[], &[]); + + let row = rows(vec![&item], (&held, &Disk)).remove(0).json(); + + assert_eq!(row["source"], "/home/me/code/skills"); + } } diff --git a/src/cli/list.rs b/src/cli/list.rs index 070409d..857d5fb 100644 --- a/src/cli/list.rs +++ b/src/cli/list.rs @@ -4,6 +4,7 @@ use std::io::Write; use super::deps::Deps; use super::removal::{Review, confirm_and_remove}; use super::scope::Scene; +use crate::app::json::Json; use crate::app::location::location; use crate::app::package::Package; use crate::app::prompt::Choice; @@ -135,9 +136,7 @@ fn print_json( anyhow::Ok(row) }) .collect::>()?; - serde_json::to_writer_pretty(&mut *out, &rows)?; - writeln!(out)?; - Ok(()) + rows.write_json(out) } /// The per-agent copies a merged item stands for, each with its own id, agents and location. diff --git a/src/cli/mod.rs b/src/cli/mod.rs index f7c3621..f96a0b8 100644 --- a/src/cli/mod.rs +++ b/src/cli/mod.rs @@ -2,6 +2,7 @@ mod args; mod deps; +mod doctor; mod isolate; mod library; mod library_args; @@ -28,11 +29,11 @@ use std::sync::Arc; use anyhow::Context; use clap::Parser; -use args::wants_auto_yes; pub use args::{ - Cli, Command, Filter, InstallArgs, ListArgs, PruneArgs, ResetArgs, SyncArgs, UninstallArgs, - UpdateArgs, UseArgs, + Cli, Command, DoctorArgs, Filter, InstallArgs, ListArgs, PruneArgs, ResetArgs, SyncArgs, + UninstallArgs, UpdateArgs, UseArgs, }; +use args::{plugin_list, wants_auto_yes}; pub use deps::Deps; pub use library_args::{ AddArgs, KindFlags, LibraryCommand, LibraryInstallArgs, LibraryListArgs, LibraryRemoveArgs, @@ -52,7 +53,19 @@ use skillz_harness::update::check::{NoCheck, UpdateCheck}; pub fn main() -> anyhow::Result { let cli = Cli::parse(); let theme = Theme::detect(&|name| std::env::var(name).ok()); - let tui = TuiPrompter::new(theme, std::env::var_os("SKILLZ_NO_MOUSE").is_none()); + // Pickers and the browser read keys from stdin and draw on stdout. + let interactive = std::io::stdin().is_terminal() && std::io::stdout().is_terminal(); + let plugins = cli + .command + .as_ref() + .filter(|_| interactive) + .and_then(plugin_list) + .unwrap_or(skillz_harness::model::Scope::Project); + let tui = TuiPrompter::new( + theme, + std::env::var_os("SKILLZ_NO_MOUSE").is_none(), + plugins, + ); let prompter: &dyn Prompter = if cli.command.as_ref().is_some_and(wants_auto_yes) { &AssumeYes } else { @@ -71,8 +84,7 @@ pub fn main() -> anyhow::Result { adapters: agents::registry().into(), runner: &runner, prompter, - // Pickers and the browser read keys from stdin and draw on stdout. - interactive: std::io::stdin().is_terminal() && std::io::stdout().is_terminal(), + interactive, checker, scanner: background_scanner(), }; diff --git a/src/cli/profile_status.rs b/src/cli/profile_status.rs index 0064ece..3f97cc4 100644 --- a/src/cli/profile_status.rs +++ b/src/cli/profile_status.rs @@ -7,6 +7,7 @@ use serde_json::{Value, json}; use super::deps::Deps; use super::scope::installed; use crate::app::apply::{Standing, compare, drift}; +use crate::app::json::Json; use crate::app::profile::{Profile, Store}; use crate::app::stale::{Disk, Probe, missing_source}; use skillz_harness::Spec; @@ -30,7 +31,7 @@ pub(super) fn list(deps: &Deps, env: &Env, json: bool, out: &mut dyn Write) -> a }) .collect(); if json { - return Ok(writeln!(out, "{}", serde_json::to_string_pretty(&rows)?)?); + return rows.write_json(out); } rows.iter() .try_for_each(|row| writeln!(out, "{}", line_of(row)))?; @@ -79,7 +80,7 @@ pub(super) fn status( .map(|p| standing_json(&p.name, &compare(&p.resolved(), &here), &Disk)) .collect(); if json { - return Ok(writeln!(out, "{}", serde_json::to_string_pretty(&rows)?)?); + return rows.write_json(out); } rows.iter().try_for_each(|row| write_standing(row, out)) } diff --git a/src/cli/run.rs b/src/cli/run.rs index bbfb954..4357e04 100644 --- a/src/cli/run.rs +++ b/src/cli/run.rs @@ -6,6 +6,7 @@ use super::args::{ UpdateArgs, UseArgs, }; use super::deps::Deps; +use super::doctor::doctor; use super::isolate::run_isolated; use super::library::{available, library_command}; use super::list::{ListView, list}; @@ -16,6 +17,7 @@ use super::scope::{Scene, resolve, resolve_project, split_target}; use super::session::{Change, Session, with_session}; use super::sync::{SyncRequest, sync}; use super::update::{UpdateRequest, check, update}; +use super::workspace::workspace; use crate::app::install::{InstallRequest, SkillSelection}; use skillz_harness::model::Scope; @@ -27,6 +29,7 @@ pub fn run(command: Command, deps: &Deps, out: &mut dyn Write) -> anyhow::Result Command::Uninstall(args) => succeeded(run_uninstall(deps, args, out)), Command::Update(args) => succeeded(run_update(deps, args, out)), Command::Prune(args) => succeeded(run_prune(deps, args, out)), + Command::Doctor(args) => succeeded(doctor(deps, &args, out)), Command::Reset(args) => succeeded(run_reset(deps, args, out)), Command::Use(args) => succeeded(run_use(deps, args, out)), Command::Sync(args) => succeeded(run_sync(deps, args, out)), @@ -45,6 +48,9 @@ fn succeeded(result: anyhow::Result<()>) -> anyhow::Result { } fn run_list(deps: &Deps, args: ListArgs, out: &mut dyn Write) -> anyhow::Result<()> { + if deps.interactive && args.plugin_list().is_some() { + return workspace(deps, args.project.as_deref()); + } if args.available { let scope = scope_of(args.filter.global); let env = resolve_project(deps, args.project.as_deref())?; diff --git a/src/cli/session/change.rs b/src/cli/session/change.rs index 25e1ca2..9858159 100644 --- a/src/cli/session/change.rs +++ b/src/cli/session/change.rs @@ -4,7 +4,7 @@ use super::Session; use super::notice::Notice; -use super::plan_view::{plan_view, step_label}; +use super::plan_view::{item_lines, plan_view, step_label}; use super::selection::{Selection, outcome_of, selection_plan}; use super::updates::update_plan; use crate::app::apply::{self, Switch, Watch}; @@ -91,16 +91,24 @@ pub(in crate::cli) fn change( let applier = job.applier(); let mut switch = job.plan(&applier, what, None)?; targets = targets.or_else(|| job.offered_targets(what, &switch)); - if let Some(chosen) = &targets { - switch = job.plan(&applier, what, Some(&chosen.checked()))?; + if let Some(only) = targets.as_ref().and_then(Targets::narrowing) { + switch = job.plan(&applier, what, Some(&only))?; } switch .updates .retain(|(item, _)| !completed_updates.contains(&item.id)); - if switch.is_empty() && targets.is_none() { + if switch.is_empty() && targets.as_ref().is_none_or(|t| t.agents.is_empty()) { return Ok(Some(Notice::UpToDate)); } let mut view = plan_view(&switch, job.scope); + if let Some(chosen) = &mut targets { + // The plan lists every item with a box; what is unchecked is not done. + chosen.sync_items(item_lines(&switch)); + switch + .installs + .retain(|(entry, _)| chosen.includes(&entry.to_string())); + switch.removals.retain(|item| chosen.includes(&item.id)); + } view.targets.clone_from(&targets); view.heading = what.heading(job.scope); match deps.prompter.plan(&view)? { @@ -137,7 +145,8 @@ impl Job<'_> { } } - /// The agents a removal could reach, when it spans more than one. + /// What the user may narrow in a change they picked: the agents it reaches, when more than + /// one, and each item it installs or removes. fn offered_targets(&self, what: &Change, switch: &Switch) -> Option { if !matches!(what, Change::Selection(_)) { return None; @@ -149,7 +158,7 @@ impl Job<'_> { .collect(); agents.sort(); agents.dedup(); - (agents.len() > 1).then(|| Targets::all(agents)) + Some(Targets::all(agents)) } fn plan( diff --git a/src/cli/session/change/selection_tests.rs b/src/cli/session/change/selection_tests.rs index 654ee8c..3d36b5b 100644 --- a/src/cli/session/change/selection_tests.rs +++ b/src/cli/session/change/selection_tests.rs @@ -194,3 +194,68 @@ fn a_failed_removal_is_not_counted_as_removed() { assert!(!values[0].is_clean()); assert!(dir.path().join(".agents/skills/tdd").exists()); } + +/// Unchecks the removal and one install in the first plan it is shown, then approves the second. +struct UnchecksFirst { + install: String, + plans: std::cell::Cell, +} + +impl crate::app::prompt::Prompter for UnchecksFirst { + fn multi_select(&self, _title: &str, _options: &[String]) -> anyhow::Result> { + Ok(vec![]) + } + + fn confirm(&self, _question: &str) -> anyhow::Result { + Ok(true) + } + + fn plan(&self, view: &crate::app::review::PlanView) -> anyhow::Result { + self.plans.set(self.plans.get() + 1); + if self.plans.get() > 1 { + return Ok(Verdict::Apply); + } + let mut targets = view.targets.clone().expect("a selection offers its items"); + for pick in &mut targets.items { + if pick.group == crate::app::review::Group::Remove || pick.id == self.install { + pick.on = false; + } + } + Ok(Verdict::Retarget(targets)) + } +} + +#[test] +fn an_item_the_user_unchecks_is_neither_installed_nor_removed() { + let dir = tempfile::tempdir().unwrap(); + project_with_skill(dir.path(), "tdd"); + let ids = [skill_id(dir.path())]; + let entries = [skill_entry("grill"), skill_entry("rust")]; + let runner = crate::app::install::test_support::FakeRunner::new(|_| {}); + let prompter = UnchecksFirst { + install: entries[0].to_string(), + plans: Default::default(), + }; + let deps = Deps::for_test(dir.path(), registry(), (&runner, &prompter)); + + let result = change( + &session(&deps, dir.path()), + Scope::Project, + &Change::Selection(&selection(&entries, &ids)), + ); + + let adds: Vec<_> = runner + .calls() + .into_iter() + .filter(|(_, args, _)| args.contains(&"add".to_string())) + .collect(); + assert!(matches!( + result.unwrap(), + Some(Notice::Changed { + installed: 1, + removed: 0 + }) + )); + assert_eq!(adds.len(), 1); + assert!(dir.path().join(".agents/skills/tdd").exists()); +} diff --git a/src/cli/session/notice.rs b/src/cli/session/notice.rs index e1a4543..c223436 100644 --- a/src/cli/session/notice.rs +++ b/src/cli/session/notice.rs @@ -28,11 +28,6 @@ pub(in crate::cli) enum Notice { secrets: usize, }, Created(String), - /// A profile saved from the project, with the installed items it could not hold. - Saved { - name: String, - skipped: Vec, - }, Updated(String), Deleted(String), } @@ -66,10 +61,6 @@ impl fmt::Display for Notice { Ok(()) } Notice::Created(name) => write!(f, "created {name}"), - Notice::Saved { name, skipped } if skipped.is_empty() => write!(f, "saved {name}"), - Notice::Saved { name, skipped } => { - write!(f, "saved {name}; not saved: {}", skipped.join(", ")) - } Notice::Updated(name) => write!(f, "updated {name}"), Notice::Deleted(name) => write!(f, "deleted {name}"), } diff --git a/src/cli/session/perform.rs b/src/cli/session/perform.rs index 65b57b9..1a09a93 100644 --- a/src/cli/session/perform.rs +++ b/src/cli/session/perform.rs @@ -4,9 +4,7 @@ use super::Session; use super::change::{Change, change}; use super::notice::Notice; use super::selection::Selection; -use crate::app::install::{InstallRequest, SkillSelection}; use crate::app::workspace::Act; -use skillz_harness::Spec; use skillz_harness::model::Scope; impl Session<'_, '_> { @@ -14,73 +12,19 @@ impl Session<'_, '_> { pub(in crate::cli) fn perform(&self, act: Act) -> anyhow::Result> { match &act { Act::Quit => Ok(None), - Act::Remove { scope, ids } => { - let picked = Selection { - install: &[], - remove: ids, - only: None, - }; - change(self, *scope, &Change::Selection(&picked)) - } - Act::Subset { install, remove } => { + Act::Change { + scope, + install, + remove, + } => { let picked = Selection { install, remove, only: None, }; - change(self, Scope::Project, &Change::Selection(&picked)) - } - Act::Update { scope, ids } => change(self, *scope, &Change::Update(ids)), - Act::Apply { scope, profile } => self.apply(*scope, profile, &Change::Apply(profile)), - Act::ApplyExact { scope, profile } => { - self.apply(*scope, profile, &Change::ApplyExact(profile)) - } - Act::InstallSource { scope, source } => self.install_source(&InstallRequest { - source: source.clone(), - cwd: self.deps.cwd.clone(), - agents: self.deps.agents_or_all(&[]), - scope: *scope, - selection: SkillSelection::Interactive, - }), - Act::LibraryAdd { spec } => self.library_add(spec), - Act::LibraryInstall { scope, entry } => self.library_install(*scope, entry), - Act::LibraryRemove(entry) => self.library_remove(entry), - Act::CreateProfile { name, entries } => self.create_profile(name, entries).map(Some), - Act::SaveCurrent { name } => { - let saved = self.save_current(name)?; - self.remember_applied(Scope::Project, name)?; - Ok(Some(saved)) + change(self, *scope, &Change::Selection(&picked)) } - Act::SetEntries { profile, entries } => self.set_entries(profile, entries).map(Some), - Act::DeleteProfile { name } => self.delete_profile(name).map(Some), - } - } - - /// Install a library entry. A skill that names its skills is installed from its source like - /// any other source, so a plugin the source offers is used; every other entry is a plain - /// change. - fn library_install(&self, scope: Scope, entry: &Spec) -> anyhow::Result> { - if let Spec::Skill { - source, - names, - agents, - } = entry - && !names.is_empty() - { - return self.install_source(&InstallRequest { - source: source.clone(), - cwd: self.deps.cwd.clone(), - agents: self.deps.agents_or_all(agents), - scope, - selection: SkillSelection::Patterns(names.clone()), - }); } - let picked = Selection { - install: std::slice::from_ref(entry), - remove: &[], - only: None, - }; - change(self, scope, &Change::Selection(&picked)) } /// Apply `profile` at `scope`, and remember it as that level's once the change went through. diff --git a/src/cli/session/plan_view.rs b/src/cli/session/plan_view.rs index e9b6601..9eb89ae 100644 --- a/src/cli/session/plan_view.rs +++ b/src/cli/session/plan_view.rs @@ -2,9 +2,10 @@ use crate::app::apply::Switch; use crate::app::remove::Plan; -use crate::app::review::{Group, PlanView}; +use crate::app::review::{Group, Listed, PlanView}; use skillz_harness::action::Action; -use skillz_harness::model::Scope; +use skillz_harness::model::{Installed, Scope, split_plugin_id}; +use skillz_harness::redact::redact; pub(super) fn plan_view(switch: &Switch, scope: Scope) -> PlanView { let kept = switch.present.iter().map(ToString::to_string).collect(); @@ -12,15 +13,15 @@ pub(super) fn plan_view(switch: &Switch, scope: Scope) -> PlanView { .removals .iter() .map(|item| match switch.is_unsourced(item) { - true => format!("{} (no known source)", item.label(true)), - false => item.label(true), + true => format!("{} (no known source)", plan_label(item)), + false => plan_label(item), }) .collect(); let install = switch.installs.iter().map(|(e, _)| e.to_string()).collect(); let update = switch .updates .iter() - .map(|(item, _)| item.label(true)) + .map(|(item, _)| plan_label(item)) .collect(); let skip = switch .unsupported @@ -51,6 +52,43 @@ pub(super) fn plan_view(switch: &Switch, scope: Scope) -> PlanView { } } +/// What a plan installs and removes, one entry per item, for the user to check or leave out. +pub(super) fn item_lines(switch: &Switch) -> Vec { + let removing = switch.removals.iter().map(|item| Listed { + group: Group::Remove, + id: item.id.clone(), + copies: item.parts().iter().map(|part| part.id.clone()).collect(), + label: plan_label(item), + }); + let installing = switch.installs.iter().map(|(entry, _)| { + let text = entry.to_string(); + Listed { + group: Group::Install, + id: text.clone(), + copies: vec![], + label: text, + } + }); + removing.chain(installing).collect() +} + +/// An installed item as a plan line: its name, where it comes from when that says something more +/// than the name, and its kind. The agents and the scope are left out: the plan's heading names the +/// scope and its agent boxes name the agents. +fn plan_label(item: &Installed) -> String { + let (name, marketplace) = split_plugin_id(&item.name); + let source = item + .source + .as_deref() + .filter(|_| marketplace.is_empty()) + .unwrap_or(marketplace); + let from = match source { + s if s.is_empty() || s == name => String::new(), + s => format!(" [{}]", redact(s)), + }; + format!("{name}{from} ({})", item.kind) +} + /// What `step` is for and what it does: `removing orca: rm ~/.claude/skills/orca`. pub(super) fn step_label(switch: &Switch, removal: &Plan, step: &Action) -> String { format!("{}: {}", purpose(switch, removal, step), step.describe()) @@ -120,6 +158,37 @@ mod tests { } } + fn plugin(name: &str, group: &str) -> Installed { + Installed { + kind: Kind::Plugin, + group: group.into(), + source: None, + agents: vec![Agent::Claude, Agent::Codex], + ..removable(name) + } + } + + #[test] + fn a_plugin_named_for_its_marketplace_says_so_once_and_leaves_out_agents_and_scope() { + let same = plan_label(&plugin("killall-skills@killall-skills", "killall-skills")); + let other = plan_label(&plugin("tdd@killall-skills", "killall-skills")); + + assert_eq!(same, "killall-skills (plugin)"); + assert_eq!(other, "tdd [killall-skills] (plugin)"); + } + + #[test] + fn a_skill_names_its_source_unless_that_is_its_name() { + let from_repo = Installed { + source: Some("o/r".into()), + ..removable("tdd") + }; + let local = removable("tdd"); + + assert_eq!(plan_label(&from_repo), "tdd [o/r] (skill)"); + assert_eq!(plan_label(&local), "tdd (skill)"); + } + #[test] fn only_groups_with_lines_are_listed_in_display_order() { let view = plan_view(&switch(), Scope::Project); diff --git a/src/cli/session/profiles.rs b/src/cli/session/profiles.rs index 2dc6cba..0e0f31a 100644 --- a/src/cli/session/profiles.rs +++ b/src/cli/session/profiles.rs @@ -1,10 +1,8 @@ -//! Changes to the stored profiles: creating, building, saving from the project and deleting. +//! Changes to the stored profiles: creating, building and deleting. use super::Session; use super::notice::Notice; use crate::app::profile::Profile; -use crate::cli::profile::save_profile; -use crate::cli::scope::{complete_installed, project_env}; use skillz_harness::Spec; use skillz_harness::model::Scope; @@ -25,17 +23,6 @@ impl Session<'_, '_> { Ok(Notice::Created(name.into())) } - /// A profile of what the project has installed; what cannot be reproduced is reported. - pub(in crate::cli) fn save_current(&self, name: &str) -> anyhow::Result { - let env = project_env(self.deps, &self.project); - let items = complete_installed(self.deps, &env, Scope::Project)?; - let saved = save_profile(&self.profiles, &items, name, false)?; - Ok(Notice::Saved { - name: name.into(), - skipped: saved.skipped.into_iter().map(|s| s.label).collect(), - }) - } - pub(in crate::cli) fn set_entries( &self, name: &str, @@ -48,7 +35,9 @@ impl Session<'_, '_> { } /// The profile last applied at `scope`: to this project, or at user level. Deleting a - /// profile forgets it. + /// profile forgets it. Only tests read the record back: nothing shows it since the profile + /// header went with the old tabs. + #[cfg(test)] pub(in crate::cli) fn applied(&self, scope: Scope) -> Option { self.store .read() diff --git a/src/cli/session/profiles/tests.rs b/src/cli/session/profiles/tests.rs index bdef78d..301cb09 100644 --- a/src/cli/session/profiles/tests.rs +++ b/src/cli/session/profiles/tests.rs @@ -6,8 +6,10 @@ use crate::app::install::test_support::{FakeRunner, ScriptedPrompter}; use crate::app::profile::{self, StillExtended}; use crate::app::store; use crate::cli::deps::Deps; +use crate::cli::profile::save_profile; +use crate::cli::scope::{complete_installed, project_env}; use skillz_harness::agents::registry; -use skillz_harness::model::Agent; +use skillz_harness::model::{Agent, Scope}; fn session<'a, 'd>(deps: &'a Deps<'d>, dir: &Path) -> Session<'a, 'd> { Session { @@ -26,6 +28,13 @@ fn with_session(check: impl FnOnce(&Session, &Path) -> T) -> T { check(&session(&deps, dir.path()), dir.path()) } +/// What `skillz profile save` does: snapshot the project's installs into a profile. +fn save_current(session: &Session, name: &str) -> anyhow::Result { + let env = project_env(session.deps, &session.project); + let items = complete_installed(session.deps, &env, Scope::Project)?; + save_profile(&session.profiles, &items, name, false) +} + fn skill(name: &str) -> Spec { Spec::Skill { source: "o/r".into(), @@ -93,12 +102,9 @@ fn saving_the_project_lists_what_could_not_be_saved() { fs::create_dir_all(&loose).unwrap(); fs::write(loose.join("SKILL.md"), "---\nname: mine\n---\n").unwrap(); - let notice = session.save_current("snap").unwrap(); + let saved = save_current(session, "snap").unwrap(); - let Notice::Saved { skipped, .. } = notice else { - panic!("expected a saved notice"); - }; - assert_eq!(skipped.len(), 1); + assert_eq!(saved.skipped.len(), 1); assert!(session.profiles.load("snap").unwrap().entries.is_empty()); }); } @@ -114,7 +120,7 @@ fn saving_the_project_keeps_a_hand_made_skill_by_the_dir_holding_it() { ) .unwrap(); - session.save_current("snap").unwrap(); + save_current(session, "snap").unwrap(); // Assert the profile reinstalls it from the skills dir, canonicalized as discovery does. let held_in = fs::canonicalize(dir.join(".claude/skills")).unwrap(); @@ -134,7 +140,7 @@ fn saving_over_an_existing_profile_is_refused() { with_session(|session, _| { session.create_profile("snap", &[]).unwrap(); - assert!(session.save_current("snap").is_err()); + assert!(save_current(session, "snap").is_err()); }); } diff --git a/src/cli/session/source_install.rs b/src/cli/session/source_install.rs index da4b54d..37f1e57 100644 --- a/src/cli/session/source_install.rs +++ b/src/cli/session/source_install.rs @@ -83,81 +83,4 @@ mod tests { assert!(notice.is_none()); assert_eq!(programs, ["git"]); } - - #[test] - fn library_skills_are_reinspected_and_install_the_native_package() { - use crate::app::install::test_support::mattpocock_fixture; - use crate::app::workspace::Act; - let home = tempfile::tempdir().unwrap(); - let project = tempfile::tempdir().unwrap(); - let runner = FakeRunner::new(mattpocock_fixture); - let prompter = ScriptedPrompter::new(&[], true); - let deps = Deps::for_test(home.path(), registry(), (&runner, &prompter)); - let env = skillz_harness::env::Env::new(home.path().into(), project.path().into()); - let session = Session::open(&deps, &env); - - session - .perform(Act::LibraryInstall { - scope: Scope::Project, - entry: skillz_harness::Spec::Skill { - source: "mattpocock/skills".into(), - names: vec!["tdd".into()], - agents: vec![Agent::Claude, Agent::Codex], - }, - }) - .unwrap(); - - let calls = runner.calls(); - assert_eq!( - calls.iter().map(|call| call.0.as_str()).collect::>(), - ["git", "claude", "claude", "codex"] - ); - assert_eq!( - calls[2].1, - vec![ - "plugin", - "install", - "mattpocock-skills@mattpocock", - "--scope", - "local" - ] - ); - assert!(!home.path().join(".codex/config.toml").exists()); - let doc: toml_edit::DocumentMut = - std::fs::read_to_string(project.path().join(".codex/config.toml")) - .unwrap() - .parse() - .unwrap(); - assert_eq!( - doc["plugins"]["mattpocock-skills@mattpocock"]["enabled"].as_bool(), - Some(true) - ); - } - - #[test] - fn a_library_skill_that_names_no_skills_installs_as_a_plain_change() { - use crate::app::workspace::Act; - let home = tempfile::tempdir().unwrap(); - let project = tempfile::tempdir().unwrap(); - let runner = FakeRunner::new(|_| {}); - let prompter = ScriptedPrompter::new(&[], true); - let deps = Deps::for_test(home.path(), registry(), (&runner, &prompter)); - let env = skillz_harness::env::Env::new(home.path().into(), project.path().into()); - let session = Session::open(&deps, &env); - - session - .perform(Act::LibraryInstall { - scope: Scope::Project, - entry: skillz_harness::Spec::Skill { - source: "o/r".into(), - names: vec![], - agents: vec![Agent::Claude], - }, - }) - .unwrap(); - - let programs: Vec = runner.calls().into_iter().map(|call| call.0).collect(); - assert!(!programs.contains(&"git".to_string())); - assert!(programs.contains(&"npx".to_string())); - } } diff --git a/src/cli/update.rs b/src/cli/update.rs index c7ebe3c..4c96faa 100644 --- a/src/cli/update.rs +++ b/src/cli/update.rs @@ -9,6 +9,7 @@ use serde_json::json; use super::removal::{Pick, choose}; use super::scope::Scene; use super::session::{Change, change, with_session}; +use crate::app::json::Json; use crate::app::remove; use skillz_harness::model::{Installed, Scope}; use skillz_harness::update; @@ -72,7 +73,7 @@ pub(super) fn check( .iter() .map(|i| json!({"id": i.id, "name": i.name, "kind": i.kind, "scope": i.scope})) .collect(); - writeln!(out, "{}", serde_json::to_string_pretty(&rows)?)?; + rows.write_json(out)?; } else if outdated.is_empty() { writeln!(out, "no updates found")?; } else { diff --git a/src/cli/workspace/mod.rs b/src/cli/workspace/mod.rs index 20eb7d1..13bf751 100644 --- a/src/cli/workspace/mod.rs +++ b/src/cli/workspace/mod.rs @@ -1,5 +1,5 @@ -//! The workspace for one directory: what it and the user have installed, the library and the -//! profiles, with installs, removals and profile applies shown as a plan first, as for `use`. +//! The workspace for one directory: the plugins list of what it and the user have installed, +//! with installs and removals shown as a plan first, as for `install`. mod model; mod sync; @@ -13,7 +13,6 @@ use super::scope::resolve_project; use super::session::{Notice, Session}; use crate::app::workspace::{Act, Screen, SharedScreen}; use model::snapshot; -use skillz_harness::update::check; /// Open the workspace on `path` (default: the current directory). An act that fails shows its /// error as a toast and the workspace stays open. The terminal is entered once and kept until @@ -25,34 +24,15 @@ pub fn workspace(deps: &Deps, path: Option<&Path>) -> anyhow::Result<()> { sync::start(deps, &env, synced); let session = Session::open(deps, &env); let screen = deps.prompter.screen()?; - let (found, results) = mpsc::channel(); - lock(&screen).watch_updates(results); lock(&screen).watch_syncs(syncs); let mut notice = None; - let mut checked = std::collections::HashSet::new(); loop { let model = snapshot(&session, notice.take())?; - let due = model - .installed - .iter() - .chain(&model.global) - .filter(|item| checked.insert(item.id.clone())) - .cloned() - .collect::>(); - if !due.is_empty() { - check::spawn(deps.checker.clone(), due, found.clone()); - } lock(&screen).load(model); let act = deps.prompter.workspace()?; if act == Act::Quit { return Ok(()); } - if let Act::Update { ids, .. } = &act { - lock(&screen).forget_updates(ids); - for id in ids { - checked.remove(id); - } - } notice = session .perform(act) .unwrap_or_else(|e| Some(Notice::Failed(format!("{e:#}")))); diff --git a/src/cli/workspace/model.rs b/src/cli/workspace/model.rs index 1a369b9..37d4887 100644 --- a/src/cli/workspace/model.rs +++ b/src/cli/workspace/model.rs @@ -1,4 +1,5 @@ -//! What the tabs show: the project read from its native config, the library and the profiles. +//! What the list shows: the project and the user's installs read from their native config, and +//! the library. use std::path::Path; @@ -9,7 +10,7 @@ use crate::cli::scope::{installed, project_env}; use skillz_harness::model::Scope; /// The snapshot to show next, with `notice` to toast; an unreadable library is shown empty and -/// reported in its place, along with the profiles kept beside it. +/// reported in its place. pub(super) fn snapshot(session: &Session, notice: Option) -> anyhow::Result { let deps = session.deps(); let env = project_env(deps, session.project()); @@ -27,15 +28,6 @@ pub(super) fn snapshot(session: &Session, notice: Option) -> anyhow::Res .map(|adapter| adapter.agent()) .collect(), library, - profiles: session - .profiles() - .readable() - .unwrap_or_default() - .into_iter() - .map(|profile| profile.in_env(&env)) - .collect(), - applied: session.applied(Scope::Project), - applied_global: session.applied(Scope::Global), notice: notice.or(problem).map(|n| n.to_string()), }) } @@ -61,9 +53,8 @@ mod tests { assert_eq!((inside.as_str(), outside.as_str()), ("~/app", "/srv/app")); } #[test] - fn local_sources_match_in_workspace_views_without_rewriting_stored_entries() { + fn local_sources_match_in_the_list_without_rewriting_stored_entries() { use crate::app::library::{Catalog, Held, LibraryItem}; - use crate::app::profile::Profile; use crate::app::store::Store; use crate::cli::deps::Deps; use skillz_harness::Spec; @@ -94,14 +85,11 @@ mod tests { names: vec![name.into()], agents: vec![Agent::Claude], }; - let mut profile = Profile::new("local"); - profile.entries = vec![entry("reviewer")]; let default = LibraryItem::from_entry(entry("reviewer")); let custom = LibraryItem::new("My helper", entry("helper")); let store = Store::in_env(&env); store .update(|document| { - document.profiles = vec![profile]; document.items = Catalog::from_items(vec![default.clone(), custom.clone()]); Ok(()) }) @@ -117,8 +105,6 @@ mod tests { let model = snapshot(&Session::open(&deps, &env), None).unwrap(); - assert!(crate::app::apply::drift(&model.profiles[0], &model.installed).matches()); - assert!(crate::app::apply::loaded(&model.profiles, &model.installed).is_some()); assert!( Held::of(&model.installed, &model.global) .presence(&model.library.items()[0].entry) @@ -141,54 +127,4 @@ mod tests { before ); } - - #[test] - fn explicit_missing_sources_stay_local_and_repository_references_stay_portable() { - use crate::app::profile::Profile; - use crate::app::stale::{Disk, missing_source}; - use crate::app::store::Store; - use crate::cli::deps::Deps; - use skillz_harness::Spec; - use skillz_harness::env::Env; - let dir = tempfile::tempdir().unwrap(); - let env = Env::new(dir.path().into(), dir.path().into()); - let mut profile = Profile::new("sources"); - profile.entries = [ - "./gone", - "../gone", - "org/repo", - "https://host/repo.git", - "git@host:org/repo.git", - ] - .into_iter() - .map(|source| Spec::Skill { - source: source.into(), - names: vec!["reviewer".into()], - agents: vec![], - }) - .collect(); - let original = profile.clone(); - Store::in_env(&env) - .update(|document| { - document.profiles.push(profile); - Ok(()) - }) - .unwrap(); - let prompter = crate::app::prompt::AssumeYes; - let deps = Deps::for_test( - dir.path(), - vec![], - (&skillz_harness::runner::NoCommands, &prompter), - ); - - let model = snapshot(&Session::open(&deps, &env), None).unwrap(); - let entries = &model.profiles[0].entries; - - assert!( - entries[..2] - .iter() - .all(|entry| missing_source(entry, &Disk).is_some()) - ); - assert_eq!(&entries[2..], &original.resolved()[2..]); - } } diff --git a/src/tui/filter.rs b/src/tui/filter.rs index 3518d4b..75354b4 100644 --- a/src/tui/filter.rs +++ b/src/tui/filter.rs @@ -2,21 +2,36 @@ //! counts matches, and match highlighting. use ratatui::Frame; -use ratatui::layout::{Constraint, Layout, Rect}; +use ratatui::layout::Rect; use ratatui::style::{Modifier, Style}; use ratatui::text::Span; use ratatui::widgets::Paragraph; use super::theme::Theme; +use super::widgets::container::{Container, Size}; use super::widgets::input::InputField; +use super::widgets::panel::Panel; /// The `/` prompt with its text field, drawn where the key bar usually is. pub fn draw_prompt(frame: &mut Frame, area: Rect, field: &InputField, theme: &Theme) { - let [slash, text] = Layout::horizontal([Constraint::Length(1), Constraint::Min(1)]).areas(area); + let [slash, text] = Container::row([Size::Fixed(1), Size::Fill(1)]).areas(area); frame.render_widget(Paragraph::new("/").style(theme.accent), slash); field.render(frame, text, theme); } +/// The area for a pane's rows. Unfiltered, that is all of `area`; a filter takes the top line to +/// name the query and the matches. +pub fn pane(frame: &mut Frame, area: Rect, query: &str, badge: String, theme: &Theme) -> Rect { + if query.is_empty() { + return area; + } + Panel::new(title("", query)) + .focused(true) + .bare() + .badge(badge) + .render(frame, area, theme) +} + /// `title` with the active query appended; just the title when nothing is filtered. pub fn title(title: &str, query: &str) -> String { match query { diff --git a/src/tui/glyphs.rs b/src/tui/glyphs.rs index 56bbe2e..83bd5fc 100644 --- a/src/tui/glyphs.rs +++ b/src/tui/glyphs.rs @@ -17,6 +17,11 @@ pub struct Glyphs { pub failed: &'static str, /// One cell of a horizontal rule. pub rule: &'static str, + /// Three cells each: a tree's connector to a child that has later siblings, to the last + /// child, and the line that carries on past a branch. + pub branch: &'static str, + pub last: &'static str, + pub trunk: &'static str, /// The frames of the in-flight spinner, one cell wide. pub spinner: &'static [&'static str], } @@ -36,6 +41,9 @@ impl Glyphs { closed: "▸", failed: "✗", rule: "─", + branch: "├─ ", + last: "└─ ", + trunk: "│ ", spinner: &["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"], }; @@ -53,6 +61,9 @@ impl Glyphs { closed: "+", failed: "x", rule: "-", + branch: "|- ", + last: "`- ", + trunk: "| ", spinner: &["|", "/", "-", "\\"], }; diff --git a/src/tui/help.rs b/src/tui/help.rs index 289dd2c..7db5b2a 100644 --- a/src/tui/help.rs +++ b/src/tui/help.rs @@ -100,13 +100,13 @@ mod tests { #[test] fn every_listed_binding_gets_a_row_under_a_section_per_group() { - let sections = keymap::help_sections(&[Scope::Project]); + let sections = keymap::help_sections(&[Scope::Plugins]); - let rows = rows(&[Scope::Project]); + let rows = rows(&[Scope::Plugins]); let listed: usize = sections.iter().map(|(_, b)| b.len()).sum(); assert_eq!(rows.len(), listed + sections.len()); - assert!(matches!(rows[0], Row::Section(Scope::Project))); + assert!(matches!(rows[0], Row::Section(Scope::Plugins))); } #[test] @@ -127,7 +127,7 @@ mod tests { #[test] fn escape_and_question_mark_close_while_navigation_keeps_it_open() { - let mut help = Help::new(&[Scope::Project]); + let mut help = Help::new(&[Scope::Plugins]); let moved = help.handle(key(KeyCode::Down)); let ignored = help.handle(key(KeyCode::Char('z'))); @@ -150,7 +150,7 @@ mod tests { #[test] fn a_short_screen_scrolls_the_overlay_instead_of_cutting_it() { let theme = Theme::dark(); - let mut help = Help::new(&[Scope::Project]); + let mut help = Help::new(&[Scope::Plugins]); let top = render_to_buffer(60, 10, |f| help.render(f, &theme)); for _ in 0..30 { help.handle(key(KeyCode::Down)); diff --git a/src/tui/keymap.rs b/src/tui/keymap.rs index 2e05af4..f99aff7 100644 --- a/src/tui/keymap.rs +++ b/src/tui/keymap.rs @@ -7,14 +7,8 @@ use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyModifiers}; pub enum Scope { /// Navigation and leaving, valid wherever a list has the keys. Common, - /// The tab bar and what works on every tab. - Workspace, - /// The Project and Global tabs: the installed items and what the library could add. - Installed, - /// What only the Project tab has: comparing and applying a profile. - Project, - Library, - Profiles, + /// The single list of plugins, each installed or not in the project. + Plugins, /// Choosing library items with checkboxes. Picker, Tree, @@ -23,26 +17,19 @@ pub enum Scope { Plan, Result, Confirm, - /// Choosing where and for which tools to install a library item. - Install, } impl Scope { pub fn title(self) -> &'static str { match self { Scope::Common => "Everywhere", - Scope::Workspace => "Tabs", - Scope::Installed => "Installed", - Scope::Project => "Profile", - Scope::Library => "Library", - Scope::Profiles => "Profiles", + Scope::Plugins => "Plugins", Scope::Picker => "Choose items", Scope::Tree => "List", Scope::Filter => "Filter", Scope::Plan => "Plan", Scope::Result => "Result", Scope::Confirm => "Confirm", - Scope::Install => "Install", } } } @@ -68,25 +55,6 @@ pub enum Action { Toggle, Mark, Info, - NextTab, - PrevTab, - GoTab(u8), - ApplyProfile, - /// Choose which entries of the applied profile the project keeps. - PickSubset, - /// Remove everything the project has. - Clear, - Add, - /// Install the highlighted library item. - Install, - Delete, - NewProfile, - SaveCurrent, - Build, - Update, - /// Install what a repo or path offers. - AddSource, - Remove, ToggleDryRun, ToggleSteps, Copy, @@ -142,10 +110,7 @@ const fn bind( } use Action as A; -use Scope::{ - Common, Confirm, Filter, Install, Installed, Library, Picker, Plan, Profiles, Project, Result, - Tree, Workspace, -}; +use Scope::{Common, Confirm, Filter, Picker, Plan, Plugins, Result, Tree}; #[rustfmt::skip] pub const BINDINGS: &[Binding] = &[ @@ -162,41 +127,11 @@ pub const BINDINGS: &[Binding] = &[ bind(Common, A::Quit, &[ch('q')], "q", "quit", 40), bind(Common, A::Interrupt, &[ctrl('c')], "^c", "quit anywhere", 0), bind(Common, A::Help, &[ch('?')], "?", "help", 0), - bind(Workspace, A::NextTab, &[plain(KeyCode::Tab)], "tab", "next tab", 20), - bind(Workspace, A::PrevTab, &[plain(KeyCode::BackTab)], "shift-tab", "previous tab", 0), - bind(Workspace, A::GoTab(0), &[ch('1')], "1 2 3 4", "go to tab", 0), - bind(Workspace, A::GoTab(1), &[ch('2')], "", "", 0), - bind(Workspace, A::GoTab(2), &[ch('3')], "", "", 0), - bind(Workspace, A::GoTab(3), &[ch('4')], "", "", 0), - bind(Installed, A::Toggle, &[ch(' ')], "space", "pick", 1), - bind(Installed, A::Select, &[plain(KeyCode::Enter)], "enter", "apply picks / fold", 2), - bind(Installed, A::AddSource, &[ch('A')], "A", "add from repo", 9), - bind(Installed, A::Remove, &[ch('r')], "r", "remove", 4), - bind(Installed, A::ApplyProfile, &[ch('a')], "a", "apply profile", 3), - bind(Project, A::PickSubset, &[ch('p')], "p", "keep from profile", 5), - bind(Project, A::Clear, &[ch('c')], "c", "clear", 6), - bind(Project, A::SaveCurrent, &[ch('s')], "s", "save as profile", 10), - bind(Installed, A::Update, &[ch('u')], "u", "update", 7), - bind(Installed, A::Filter, &[ch('/')], "/", "filter", 8), - bind(Installed, A::Left, &[plain(KeyCode::Left), ch('h')], "← →", "collapse / expand", 0), - bind(Installed, A::Right, &[plain(KeyCode::Right), ch('l')], "", "", 0), - bind(Library, A::Add, &[ch('a')], "a", "add", 1), - bind(Library, A::Install, &[ch('i')], "i", "install", 2), - bind(Library, A::Delete, &[ch('x')], "x", "remove", 3), - bind(Library, A::Filter, &[ch('/')], "/", "filter", 4), - bind(Library, A::Toggle, &[ch(' ')], "space", "expand", 0), - bind(Library, A::Select, &[plain(KeyCode::Enter)], "enter", "expand", 0), - bind(Library, A::Left, &[plain(KeyCode::Left), ch('h')], "← →", "collapse / expand", 0), - bind(Library, A::Right, &[plain(KeyCode::Right), ch('l')], "", "", 0), - bind(Profiles, A::Build, &[plain(KeyCode::Enter), ch('e')], "enter e", "edit", 1), - bind(Profiles, A::NewProfile, &[ch('n')], "n", "new", 2), - bind(Profiles, A::Delete, &[ch('x')], "x", "delete", 3), - bind(Profiles, A::Filter, &[ch('/')], "/", "filter", 4), - bind(Profiles, A::Toggle, &[ch(' ')], "space", "expand", 0), - bind(Profiles, A::Left, &[plain(KeyCode::Left), ch('h')], "", "", 0), - bind(Profiles, A::Right, &[plain(KeyCode::Right), ch('l')], "", "", 0), - bind(Install, A::Toggle, &[ch(' ')], "space", "choose", 1), - bind(Install, A::Select, &[plain(KeyCode::Enter)], "enter", "install", 2), + bind(Plugins, A::Toggle, &[ch(' ')], "space", "select", 0), + bind(Plugins, A::Select, &[plain(KeyCode::Enter)], "enter", "apply", 0), + bind(Plugins, A::Back, &[plain(KeyCode::Esc)], "esc", "clear selection", 0), + bind(Plugins, A::Info, &[ch('i')], "i", "info", 0), + bind(Plugins, A::Filter, &[ch('/')], "/", "filter", 0), bind(Picker, A::Toggle, &[ch(' ')], "space", "check", 0), bind(Picker, A::Select, &[plain(KeyCode::Enter)], "enter", "save selection", 0), bind(Picker, A::Left, &[plain(KeyCode::Left), ch('h')], "← →", "collapse / expand", 0), @@ -208,12 +143,18 @@ pub const BINDINGS: &[Binding] = &[ bind(Tree, A::Toggle, &[ch(' ')], "space", "expand", 5), bind(Tree, A::Left, &[plain(KeyCode::Left), ch('h')], "← →", "collapse / expand", 0), bind(Tree, A::Right, &[plain(KeyCode::Right), ch('l')], "", "", 0), - bind(Plan, A::Select, &[plain(KeyCode::Enter), ch('y'), ch('Y')], "enter y", "apply", 1), - bind(Plan, A::Back, &[plain(KeyCode::Esc), ch('n'), ch('N')], "esc n", "cancel", 4), - bind(Plan, A::ToggleDryRun, &[ch('d')], "d", "dry run", 2), - bind(Plan, A::Toggle, &[ch(' ')], "space", "check", 5), - bind(Plan, A::ToggleSteps, &[ch('s')], "s", "steps", 3), - bind(Result, A::Select, &[plain(KeyCode::Enter), ch(' ')], "enter", "close", 1), + bind(Plan, A::Select, &[plain(KeyCode::Enter)], "enter", "choose", 0), + bind(Plan, A::Yes, &[ch('y'), ch('Y')], "y", "apply", 0), + bind(Plan, A::Back, &[plain(KeyCode::Esc)], "esc", "cancel", 0), + bind(Plan, A::No, &[ch('n'), ch('N')], "n", "cancel", 0), + bind(Plan, A::Left, &[plain(KeyCode::Left), ch('h'), plain(KeyCode::BackTab)], "← →", "change button", 0), + bind(Plan, A::Right, &[plain(KeyCode::Right), ch('l'), plain(KeyCode::Tab)], "", "", 0), + bind(Plan, A::ToggleDryRun, &[ch('d')], "d", "dry run", 0), + bind(Plan, A::Toggle, &[ch(' ')], "space", "check", 0), + bind(Plan, A::ToggleSteps, &[ch('s')], "s", "steps", 0), + bind(Result, A::Select, &[plain(KeyCode::Enter), ch(' ')], "enter", "choose", 1), + bind(Result, A::Left, &[plain(KeyCode::Left), ch('h'), plain(KeyCode::BackTab)], "← →", "change button", 0), + bind(Result, A::Right, &[plain(KeyCode::Right), ch('l'), plain(KeyCode::Tab)], "", "", 0), bind(Result, A::Back, &[plain(KeyCode::Esc)], "esc", "close", 0), bind(Result, A::Copy, &[ch('c')], "c", "copy", 2), bind(Result, A::Retry, &[ch('r')], "r", "retry", 3), @@ -324,16 +265,20 @@ mod tests { #[test] fn the_same_letter_means_different_things_per_scope() { - let project = press(Project, 'p'); - let tree = press(Tree, 'p'); + let plugins = press(Plugins, 'i'); + let result = press(Result, 'i'); + let tree = press(Tree, 'x'); - assert_eq!((project, tree), (Some(Action::PickSubset), None)); + assert_eq!( + (plugins, result, tree), + (Some(Action::Info), None, Some(Action::Mark)) + ); } #[test] fn a_scope_falls_back_to_the_common_bindings() { assert_eq!(press(Tree, 'j'), Some(Action::Down)); - assert_eq!(press(Project, 'q'), Some(Action::Quit)); + assert_eq!(press(Plugins, 'q'), Some(Action::Quit)); } #[test] @@ -350,53 +295,8 @@ mod tests { let half = resolve(Common, ctrl_key('d')); assert_eq!(half, Some(Action::HalfPageDown)); - assert_eq!(press(Project, 'd'), None); - assert_eq!(resolve(Project, ctrl_key('c')), Some(Action::Interrupt)); - } - - #[test] - fn the_tab_keys_move_between_tabs_and_jump_by_number() { - let shift_tab = KeyEvent::new(KeyCode::BackTab, KeyModifiers::SHIFT); - - let keys = [ - resolve(Workspace, key(KeyCode::Tab)), - resolve(Workspace, shift_tab), - press(Workspace, '1'), - press(Workspace, '4'), - ]; - - assert_eq!( - keys, - [ - Some(Action::NextTab), - Some(Action::PrevTab), - Some(Action::GoTab(0)), - Some(Action::GoTab(3)) - ] - ); - } - - #[test] - fn a_tab_binds_the_keys_of_all_its_scopes_and_global_can_apply_but_not_keep_clear_or_save() { - let project = [Installed, Project]; - let keys = ['r', 'p', 'a', 'c']; - - let on_project = keys.map(|c| resolve_in(&project, key(KeyCode::Char(c)))); - let on_global = keys.map(|c| resolve_in(&[Installed], key(KeyCode::Char(c)))); - - assert_eq!( - on_project, - [ - Some(Action::Remove), - Some(Action::PickSubset), - Some(Action::ApplyProfile), - Some(Action::Clear) - ] - ); - assert_eq!( - on_global, - [Some(Action::Remove), None, Some(Action::ApplyProfile), None] - ); + assert_eq!(press(Plugins, 'd'), None); + assert_eq!(resolve(Plugins, ctrl_key('c')), Some(Action::Interrupt)); } #[test] @@ -413,17 +313,14 @@ mod tests { #[test] fn hints_come_out_most_important_first_and_without_duplicates() { - for scope in [Installed, Library, Tree] { - let hints = hints(&[scope]); - let mut sorted = hints.clone(); - sorted.dedup(); - - assert_eq!(hints, sorted); - assert!(!hints.is_empty()); - } + let hints = hints(&[Tree]); + let mut sorted = hints.clone(); + sorted.dedup(); + assert_eq!(hints, sorted); + assert!(!hints.is_empty()); let ranks: Vec = BINDINGS .iter() - .filter(|b| matches!(b.scope, Installed | Project | Workspace) && b.rank > 0) + .filter(|b| b.scope == Tree && b.rank > 0) .map(|b| b.rank) .collect(); let mut distinct = ranks.clone(); @@ -434,7 +331,7 @@ mod tests { #[test] fn the_scopes_own_enter_replaces_the_common_one_in_help() { - let selects = help_sections(&[Installed, Project]) + let selects = help_sections(&[Plugins]) .into_iter() .flat_map(|(_, bindings)| bindings) .filter(|b| b.action == Action::Select); @@ -442,22 +339,6 @@ mod tests { assert_eq!(selects.count(), 1); } - #[test] - fn each_profile_key_means_its_own_action() { - let keys = ['n', 'e', 'x', 'a', 's'].map(|c| press(Profiles, c)); - - assert_eq!( - keys, - [ - Some(Action::NewProfile), - Some(Action::Build), - Some(Action::Delete), - None, - None - ] - ); - } - #[test] fn every_listed_binding_names_its_keys() { let nameless = BINDINGS @@ -469,10 +350,10 @@ mod tests { #[test] fn help_lists_the_scope_first_then_the_common_bindings() { - let sections = help_sections(&[Installed]); + let sections = help_sections(&[Plugins]); let scopes: Vec = sections.iter().map(|(s, _)| *s).collect(); - assert_eq!(scopes, [Installed, Common]); + assert_eq!(scopes, [Plugins, Common]); assert!( sections .iter() @@ -482,13 +363,13 @@ mod tests { #[test] fn caller_scope_order_wins_over_table_order() { - let key = key(KeyCode::Enter); + let key = key(KeyCode::Tab); - let picker_first = resolve_in(&[Picker, Profiles], key); - let profiles_first = resolve_in(&[Profiles, Picker], key); + let plan_first = resolve_in(&[Plan, Confirm], key); + let confirm_first = resolve_in(&[Confirm, Plan], key); // Assert overlapping bindings follow the scope order supplied by the caller. - assert_eq!(picker_first, Some(Action::Select)); - assert_eq!(profiles_first, Some(Action::Build)); + assert_eq!(plan_first, Some(Action::Right)); + assert_eq!(confirm_first, Some(Action::Toggle)); } } diff --git a/src/tui/plan.rs b/src/tui/plan.rs index f9be612..08bcae1 100644 --- a/src/tui/plan.rs +++ b/src/tui/plan.rs @@ -1,5 +1,6 @@ -//! The plan to approve before a switch: what stays, goes and arrives, with the raw steps and a -//! dry run one key away. A plan that removes something is framed in the danger colour. +//! The plan to approve before a switch: what stays, goes and arrives, answered with Cancel and a +//! button named for the change. The raw steps and a dry run are a key away, unlisted. A plan that +//! removes something is framed in the danger colour. use ratatui::Frame; use ratatui::crossterm::event::{Event, KeyEvent}; @@ -9,20 +10,38 @@ use ratatui::text::{Line, Span}; use super::app::{Screen, Step}; use super::keymap::{self, Action, Scope}; use super::theme::Theme; +use super::widgets::buttons::Buttons; use super::widgets::panel::Panel; use super::widgets::text_modal::{Page, TextModal}; use crate::app::review::{Group, PlanView, Targets, Verdict}; +/// Marks the line the cursor is on. +const CURSOR: &str = "▌ "; + +/// Where the cancelling and the approving button sit in the row. +const CANCEL: usize = 0; +const APPROVE: usize = 1; + pub struct PlanScreen { view: PlanView, raw: bool, dry_run: bool, modal: TextModal, + buttons: Buttons, + /// The cursor moved, so the next draw scrolls it into view. + follow: bool, } impl PlanScreen { + /// Approving is focused, so Enter applies; cancelling is a key or a button away. pub fn new(view: PlanView) -> Self { + let approve = match view.destructive() { + true => "Delete", + false => "Apply", + }; PlanScreen { + buttons: Buttons::new(&["Cancel", approve], APPROVE), + follow: view.targets.is_some(), view, raw: false, dry_run: false, @@ -46,17 +65,27 @@ impl PlanScreen { fn on_key(&mut self, key: KeyEvent) -> Step { match keymap::resolve(Scope::Plan, key) { - Some(Action::Select) => Step::Act(self.accepted()), - Some(Action::Back | Action::Quit) => Step::Act(Verdict::Cancel), + Some(Action::Select) => Step::Act(self.focused()), + Some(Action::Yes) => Step::Act(self.accepted()), + Some(Action::Back | Action::No | Action::Quit) => Step::Act(Verdict::Cancel), + Some(Action::Left) => { + self.buttons.previous(); + Step::Stay + } + Some(Action::Right) => { + self.buttons.next(); + Step::Stay + } Some(Action::Interrupt) => Step::Quit, - Some(Action::Toggle) => match &self.view.targets { + Some(Action::Toggle) => match self.checkable() { Some(targets) => Step::Act(Verdict::Retarget(targets.clone().toggled())), None => Step::Stay, }, - Some(movement @ (Action::Up | Action::Down)) if self.view.targets.is_some() => { + Some(movement @ (Action::Up | Action::Down)) if self.checkable().is_some() => { if let Some(targets) = self.view.targets.take() { self.view.targets = Some(targets.moved(movement == Action::Down)); } + self.follow = true; Step::Stay } Some(Action::ToggleDryRun) => self.toggle(|s| &mut s.dry_run), @@ -73,9 +102,36 @@ impl PlanScreen { let flag = flag(self); *flag = !*flag; self.modal.reset(); + self.name_approval(); Step::Stay } + /// A dry run only previews, and the button says so. + fn name_approval(&mut self) { + let label = match (self.dry_run, self.view.destructive()) { + (true, _) => "Dry run", + (false, true) => "Delete", + (false, false) => "Apply", + }; + self.buttons.set_label(APPROVE, label); + } + + /// The boxes the user can check, when the plan has any. + fn checkable(&self) -> Option<&Targets> { + self.view + .targets + .as_ref() + .filter(|targets| targets.rows() > 0) + } + + /// What the focused button answers. + fn focused(&self) -> Verdict { + match self.buttons.focus() { + CANCEL => Verdict::Cancel, + _ => self.accepted(), + } + } + fn accepted(&self) -> Verdict { if self.dry_run { Verdict::DryRun @@ -97,42 +153,25 @@ impl Screen for PlanScreen { } fn draw(&mut self, frame: &mut Frame, theme: &Theme) { + let lines = self.text(theme); + let reveal = self.follow.then(|| cursor_line(&lines)).flatten(); + self.follow = false; let page = Page { panel: Panel::new(self.view.heading.clone()).danger(self.view.destructive()), - lines: self.text(theme), - footer: self.hints(theme), + lines, + reveal, + buttons: Some(self.buttons.line(theme)), + help: None, }; self.modal.render(frame, theme, page); } } -impl PlanScreen { - fn hints(&self, theme: &Theme) -> Line<'static> { - let spans = keymap::hint_bindings(&[Scope::Plan]) - .into_iter() - .filter_map(|binding| { - if binding.action == Action::Toggle && self.view.targets.is_none() { - return None; - } - let active = match binding.action { - Action::ToggleDryRun => self.dry_run, - Action::ToggleSteps => self.raw, - _ => false, - }; - let label = if binding.action == Action::Select && self.dry_run { - "dry run" - } else { - binding.label - }; - let style = if active { theme.warn } else { theme.muted }; - Some(Span::styled(format!("{} {label} ", binding.keys), style)) - }); - Line::from(spans.collect::>()) - } -} - /// The agents the plan may reach, each checked or not, the cursor on one. fn target_lines(targets: &Targets, theme: &Theme) -> Vec> { + if targets.agents.is_empty() { + return vec![]; + } let glyphs = &theme.glyphs; let mut lines = vec![Line::styled( "Agents", @@ -143,7 +182,7 @@ fn target_lines(targets: &Targets, theme: &Theme) -> Vec> { true => (glyphs.checked, theme.ok), false => (glyphs.unchecked, theme.muted), }; - let cursor = if at == targets.cursor { "▌ " } else { " " }; + let cursor = if at == targets.cursor { CURSOR } else { " " }; Line::from(vec![ Span::styled(cursor, theme.accent), Span::styled(format!("{glyph} {agent}"), style), @@ -167,24 +206,71 @@ fn group_style(group: Group, theme: &Theme) -> Style { fn group_lines(view: &PlanView, theme: &Theme) -> Vec> { let mut lines = Vec::new(); for group in Group::ALL { + let picks = view + .targets + .as_ref() + .map(|targets| check_lines(targets, group, theme)) + .unwrap_or_default(); let entries = view.lines(group); - if entries.is_empty() { + if picks.is_empty() && entries.is_empty() { continue; } let style = group_style(group, theme); if !lines.is_empty() { lines.push(Line::default()); } - let head = format!("{} ({})", group.name(), entries.len()); + let count = if picks.is_empty() { + entries.len() + } else { + picks.len() + }; + let head = format!("{} ({count})", group.heading()); lines.push(Line::styled( head, style.add_modifier(theme.title.add_modifier), )); - lines.extend(entries.iter().cloned().map(|e| Line::styled(e, style))); + if picks.is_empty() { + lines.extend(entries.iter().cloned().map(|e| Line::styled(e, style))); + } else { + lines.extend(picks); + } } lines } +/// The items of `group` the user may leave out, each with a box; the cursor marks one. +fn check_lines(targets: &Targets, group: Group, theme: &Theme) -> Vec> { + let glyphs = &theme.glyphs; + targets + .items + .iter() + .enumerate() + .filter(|(_, pick)| pick.group == group) + .map(|(at, pick)| { + let cursor = if targets.agents.len() + at == targets.cursor { + CURSOR + } else { + " " + }; + let (glyph, style) = match pick.on { + true => (glyphs.checked, group_style(group, theme)), + false => (glyphs.unchecked, theme.muted), + }; + Line::from(vec![ + Span::styled(cursor, theme.accent), + Span::styled(format!("{glyph} {}", pick.label), style), + ]) + }) + .collect() +} + +/// The line the cursor is on. +fn cursor_line(lines: &[Line<'static>]) -> Option { + lines + .iter() + .position(|line| line.spans.first().is_some_and(|s| s.content == CURSOR)) +} + fn step_lines(view: &PlanView, theme: &Theme) -> Vec> { let mut lines = vec![Line::styled( format!("{} steps, in order", view.steps.len()), @@ -264,6 +350,155 @@ mod tests { } } + fn drawn_text(screen: &mut PlanScreen) -> String { + let theme = Theme::dark(); + let buffer = render_to_buffer(100, 30, |f| screen.draw(f, &theme)); + (0..30) + .map(|y| crate::tui::widgets::testing::row_text(&buffer, y)) + .collect::>() + .join("\n") + } + + #[test] + fn the_modal_ends_in_cancel_and_delete_buttons_with_no_help_text() { + let mut screen = PlanScreen::new(view()); + + let text = drawn_text(&mut screen); + + assert!(text.find("[ Cancel ]").unwrap() < text.find("[ Delete ]").unwrap()); + // The old key hints: apply, dry run, steps. + assert!(!text.contains("dry run") && !text.contains("steps") && !text.contains("enter")); + } + + fn pick(group: Group, id: &str, on: bool) -> crate::app::review::Pick { + crate::app::review::Pick { + group, + id: id.into(), + copies: vec![], + label: id.into(), + on, + } + } + + fn with_items() -> PlanScreen { + PlanScreen::new(PlanView { + groups: vec![(Group::Install, vec!["a".into(), "b".into()])], + targets: Some(Targets { + agents: vec![], + items: vec![ + pick(Group::Install, "a", true), + pick(Group::Install, "b", true), + ], + cursor: 0, + left_out: vec![], + }), + ..view() + }) + } + + #[test] + fn each_item_to_install_has_a_box_and_space_unchecks_the_one_under_the_cursor() { + let mut screen = with_items(); + + answer(&mut screen, KeyCode::Down); + let verdict = answer(&mut screen, KeyCode::Char(' ')); + + let Some(Verdict::Retarget(targets)) = verdict else { + panic!("expected a new plan, got {verdict:?}"); + }; + let on: Vec = targets.items.iter().map(|p| p.on).collect(); + assert_eq!(on, [true, false]); + assert_eq!(targets.cursor, 1); + } + + #[test] + fn the_items_are_drawn_checked_or_not_under_their_heading() { + let mut screen = with_items(); + if let Some(targets) = screen.view.targets.as_mut() { + targets.items[1].on = false; + } + + let text = drawn_text(&mut screen); + + let theme = Theme::dark(); + assert!(text.contains(&format!("{} a", theme.glyphs.checked))); + assert!(text.contains(&format!("{} b", theme.glyphs.unchecked))); + } + + #[test] + fn a_plan_with_no_boxes_leaves_up_and_down_and_space_to_the_modal() { + let mut screen = PlanScreen::new(PlanView { + targets: Some(Targets::default()), + ..view() + }); + + assert_eq!(answer(&mut screen, KeyCode::Char(' ')), None); + } + + #[test] + fn installs_and_removals_are_listed_under_their_own_headings() { + let mut screen = PlanScreen::new(PlanView { + groups: vec![ + (Group::Remove, vec!["y".into()]), + (Group::Install, vec!["x".into(), "z".into()]), + ], + ..view() + }); + + let text = drawn_text(&mut screen); + + let (removing, installing) = ( + text.find("removing (1)").unwrap(), + text.find("installing (2)").unwrap(), + ); + assert!(removing < installing); + } + + #[test] + fn a_plan_that_removes_nothing_is_approved_with_apply() { + let mut screen = PlanScreen::new(PlanView { + groups: vec![(Group::Install, vec!["a".into()])], + ..view() + }); + + let text = drawn_text(&mut screen); + + assert!(text.contains("[ Apply ]") && !text.contains("Delete")); + } + + #[test] + fn arrows_or_tab_move_the_focus_and_enter_answers_the_focused_button() { + let mut screen = PlanScreen::new(view()); + + answer(&mut screen, KeyCode::Left); + let on_cancel = answer(&mut screen, KeyCode::Enter); + answer(&mut screen, KeyCode::Tab); + let on_delete = answer(&mut screen, KeyCode::Enter); + + assert_eq!(on_cancel, Some(Verdict::Cancel)); + assert_eq!(on_delete, Some(Verdict::Apply)); + } + + #[test] + fn y_approves_and_n_cancels_whichever_button_is_focused() { + let mut screen = PlanScreen::new(view()); + answer(&mut screen, KeyCode::Left); + + let yes = answer(&mut screen, KeyCode::Char('y')); + let no = answer(&mut screen, KeyCode::Char('n')); + + assert_eq!((yes, no), (Some(Verdict::Apply), Some(Verdict::Cancel))); + } + + #[test] + fn a_dry_run_renames_the_approving_button() { + let mut screen = PlanScreen::new(view()); + + answer(&mut screen, KeyCode::Char('d')); + + assert!(drawn_text(&mut screen).contains("[ Dry run ]")); + } + #[test] fn enter_applies_and_esc_cancels() { let verdicts = diff --git a/src/tui/prompter.rs b/src/tui/prompter.rs index a36d953..0e79678 100644 --- a/src/tui/prompter.rs +++ b/src/tui/prompter.rs @@ -19,6 +19,7 @@ use crate::app::prompt::{Choice, Hold, Picked, Prompter}; use crate::app::review::{ItemEvent, Next, Outcome, PlanView, Progress, Verdict}; use crate::app::tree::{self, Node}; use crate::app::workspace::{Act, SharedScreen}; +use skillz_harness::model::Scope; /// Terminal prompter. The theme is chosen once by the caller and handed to every screen; the /// terminal is entered by the first screen and left again once nothing holds it. @@ -32,11 +33,12 @@ pub struct TuiPrompter { } impl TuiPrompter { - pub fn new(theme: Theme, mouse: bool) -> Self { + /// The workspace is the plugins list of `scope`. + pub fn new(theme: Theme, mouse: bool, scope: Scope) -> Self { TuiPrompter { theme, shell: Shell::new(mouse), - screen: Arc::new(Mutex::new(Workspace::standard())), + screen: Arc::new(Mutex::new(Workspace::plugins(scope))), shown: RefCell::default(), } } diff --git a/src/tui/result.rs b/src/tui/result.rs index fc5a104..7cac23b 100644 --- a/src/tui/result.rs +++ b/src/tui/result.rs @@ -1,5 +1,5 @@ -//! How a switch ended: counts, then anything that went wrong with a key to copy it or run the -//! rest again, then the steps that ran. +//! How a switch ended: a line for each item that changed, then anything that went wrong and the +//! steps that ran. It is answered with an OK button, plus Copy and Retry when something failed. use ratatui::Frame; use ratatui::crossterm::event::{Event, KeyEvent}; @@ -10,26 +10,71 @@ use super::clipboard; use super::keymap::{self, Action, Scope}; use super::result_items::done_lines; use super::theme::Theme; +use super::widgets::buttons::Buttons; use super::widgets::panel::Panel; use super::widgets::text_modal::{Page, TextModal}; use crate::app::review::{Next, Outcome}; +/// What a button does. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Pressed { + Copy, + Retry, + Ok, +} + pub struct ResultScreen { title: String, outcome: Outcome, modal: TextModal, copied: bool, copy: fn(&str), + /// The buttons' meanings, in the order of `buttons`; OK is last and focused. + choices: Vec, + buttons: Buttons, } impl ResultScreen { pub fn new(title: &str, outcome: Outcome) -> Self { + let mut choices = Vec::new(); + if !outcome.is_clean() { + choices.push(Pressed::Copy); + } + if !outcome.failures.is_empty() { + choices.push(Pressed::Retry); + } + choices.push(Pressed::Ok); + let labels: Vec<&str> = choices + .iter() + .map(|choice| match choice { + Pressed::Copy => "Copy", + Pressed::Retry => "Retry", + Pressed::Ok => "OK", + }) + .collect(); ResultScreen { title: title.to_string(), outcome, modal: TextModal::default(), copied: false, copy: copy_to_terminal, + buttons: Buttons::new(&labels, choices.len() - 1), + choices, + } + } + + fn press(&mut self, choice: Pressed) -> Step { + match choice { + Pressed::Copy => { + (self.copy)(&self.clip()); + self.copied = true; + if let Some(at) = self.choices.iter().position(|c| *c == Pressed::Copy) { + self.buttons.set_label(at, "Copied"); + } + Step::Stay + } + Pressed::Retry => Step::Act(Next::Retry), + Pressed::Ok => Step::Act(Next::Done), } } @@ -48,14 +93,14 @@ impl ResultScreen { fn on_key(&mut self, key: KeyEvent) -> Step { match keymap::resolve(Scope::Result, key) { - Some(Action::Copy) => { - (self.copy)(&self.clip()); - self.copied = true; + Some(Action::Copy) if self.choices.contains(&Pressed::Copy) => { + return self.press(Pressed::Copy); } Some(Action::Retry) if self.can_retry() => return Step::Act(Next::Retry), - Some(Action::Back | Action::Select | Action::Quit) => { - return Step::Act(Next::Done); - } + Some(Action::Select) => return self.press(self.choices[self.buttons.focus()]), + Some(Action::Back | Action::Quit) => return Step::Act(Next::Done), + Some(Action::Left) => self.buttons.previous(), + Some(Action::Right) => self.buttons.next(), Some(Action::Interrupt) => return Step::Quit, Some(movement) => self.modal.navigate(movement), None => {} @@ -64,8 +109,10 @@ impl ResultScreen { } fn lines(&self, theme: &Theme) -> Vec> { - let mut lines = vec![counts(&self.outcome, theme)]; - lines.extend(done_lines(&self.outcome, theme)); + let mut lines = done_lines(&self.outcome, theme); + if lines.is_empty() && self.outcome.is_clean() { + lines.push(Line::styled("Nothing changed", theme.muted)); + } lines.extend(problem_lines(&self.outcome, theme)); let steps = collapse_repeats(&self.outcome.log); if !self.outcome.is_clean() && !steps.is_empty() { @@ -75,21 +122,6 @@ impl ResultScreen { } lines } - - fn hints(&self, theme: &Theme) -> Line<'static> { - let spans = keymap::hint_bindings(&[Scope::Result]) - .into_iter() - .filter(|binding| binding.action != Action::Retry || self.can_retry()) - .map(|binding| { - let label = if binding.action == Action::Copy && self.copied { - "copied" - } else { - binding.label - }; - Span::styled(format!("{} {label} ", binding.keys), theme.muted) - }); - Line::from(spans.collect::>()) - } } /// Consecutive identical steps as one line with a count: `removing orca ×8`. @@ -106,20 +138,6 @@ fn copy_to_terminal(text: &str) { let _ = clipboard::copy(text); } -fn counts(outcome: &Outcome, theme: &Theme) -> Line<'static> { - let count = |n: usize, what: &str, shown: ratatui::style::Style| { - let style = if n == 0 { theme.muted } else { shown }; - Span::styled(format!("{what} {n} "), style) - }; - Line::from(vec![ - count(outcome.removed, "removed", theme.text), - count(outcome.installed, "installed", theme.ok), - count(outcome.updated, "updated", theme.ok), - count(outcome.skipped, "skipped", theme.warn), - count(outcome.failures.len(), "failed", theme.danger), - ]) -} - fn problem_lines(outcome: &Outcome, theme: &Theme) -> Vec> { if outcome.is_clean() { return vec![]; @@ -162,7 +180,9 @@ impl Screen for ResultScreen { let page = Page { panel: Panel::new(self.title.clone()).danger(!self.outcome.is_clean()), lines: self.lines(theme), - footer: self.hints(theme), + buttons: Some(self.buttons.line(theme)), + help: None, + reveal: None, }; self.modal.render(frame, theme, page); } @@ -255,8 +275,70 @@ mod tests { let lines = screen.lines(&theme); - // Line 0 is the counts; the failure is the second problem block line. - assert_eq!(lines[2].spans[0].style, theme.danger); + // Line 0 is the blank that opens the problems; the failure follows it. + assert_eq!(lines[1].spans[0].style, theme.danger); + } + + fn drawn_text(screen: &mut ResultScreen) -> String { + use crate::tui::widgets::testing::{render_to_buffer, row_text}; + let theme = Theme::dark(); + let buffer = render_to_buffer(100, 30, |f| screen.draw(f, &theme)); + (0..30) + .map(|y| row_text(&buffer, y)) + .collect::>() + .join("\n") + } + + #[test] + fn a_clean_result_is_the_list_of_what_changed_and_one_ok_button() { + let outcome = Outcome { + items: vec![crate::app::review::ItemEvent { + target: crate::app::review::Target::Remove("a".into()), + label: "killall-skills".into(), + phase: crate::app::review::Phase::Succeeded, + }], + ..Outcome::default() + }; + let mut screen = ResultScreen::new("Change", outcome); + + let text = drawn_text(&mut screen); + + assert!(text.contains("Removed killall-skills") && text.contains("[ OK ]")); + assert!(!text.contains("Copy") && !text.contains("Retry")); + // No counts and no key hints. + assert!( + !text.contains("installed 0") && !text.contains("enter") && !text.contains("close") + ); + } + + #[test] + fn a_failed_result_offers_copy_and_retry_before_ok_and_enter_answers_ok() { + let mut screen = ResultScreen::new("Change", failed()); + + let text = drawn_text(&mut screen); + let enter = answer(&mut screen, KeyCode::Enter); + + let (copy, retry, ok) = ( + text.find("[ Copy ]").unwrap(), + text.find("[ Retry ]").unwrap(), + text.find("[ OK ]").unwrap(), + ); + assert!(copy < retry && retry < ok); + assert_eq!(enter, Some(Next::Done)); + } + + #[test] + fn moving_to_retry_and_pressing_enter_retries_and_copy_says_copied() { + let mut screen = ResultScreen::new("Change", failed()); + screen.copy = |_| {}; + + answer(&mut screen, KeyCode::Left); + let retry = answer(&mut screen, KeyCode::Enter); + answer(&mut screen, KeyCode::Left); + let copy = answer(&mut screen, KeyCode::Enter); + + assert_eq!((retry, copy), (Some(Next::Retry), None)); + assert!(drawn_text(&mut screen).contains("[ Copied ]")); } #[test] diff --git a/src/tui/result_items.rs b/src/tui/result_items.rs index 1d503e4..a9ee04d 100644 --- a/src/tui/result_items.rs +++ b/src/tui/result_items.rs @@ -1,4 +1,4 @@ -//! The result screen's list of what was done, item by item. +//! The result screen's list of what was done, one line per item. use ratatui::text::{Line, Span}; @@ -23,7 +23,7 @@ pub(super) fn done_lines(outcome: &Outcome, theme: &Theme) -> Vec> Span::raw(format!("{} {}", verb(&event.target), event.label)), ]) }); - std::iter::once(Line::default()).chain(lines).collect() + lines.collect() } fn verb(target: &Target) -> &'static str { @@ -59,8 +59,7 @@ mod tests { let lines = done_lines(&outcome, &Theme::dark()); - // A blank separator, then the two that worked. - assert_eq!(lines.len(), 3); + assert_eq!(lines.len(), 2); } #[test] diff --git a/src/tui/theme.rs b/src/tui/theme.rs index be03461..8dfa7f7 100644 --- a/src/tui/theme.rs +++ b/src/tui/theme.rs @@ -26,6 +26,12 @@ pub struct Theme { pub border: Style, pub title: Style, pub text: Style, + /// Text that matters more than the rest of its row. + pub strong: Style, + /// The option under the cursor in a dialog's list or a row of buttons. + pub choice: Style, + /// Rows shown for reference that no key acts on. + pub inactive: Style, pub kinds: Kinds, pub glyphs: Glyphs, } @@ -85,6 +91,9 @@ impl Theme { border: fg(Color::DarkGray), title: fg(Color::White).add_modifier(Modifier::BOLD), text: Style::new(), + strong: modifier(Modifier::BOLD), + choice: modifier(Modifier::REVERSED | Modifier::BOLD), + inactive: fg(Color::DarkGray).add_modifier(Modifier::DIM), kinds: Kinds::of([75, 177, 80, 180, 146]), glyphs: Glyphs::UNICODE, } @@ -102,6 +111,9 @@ impl Theme { border: fg(Color::Gray), title: fg(Color::Black).add_modifier(Modifier::BOLD), text: Style::new(), + strong: modifier(Modifier::BOLD), + choice: modifier(Modifier::REVERSED | Modifier::BOLD), + inactive: fg(Color::Gray).add_modifier(Modifier::DIM), kinds: Kinds::of([25, 127, 30, 94, 60]), glyphs: Glyphs::UNICODE, } @@ -120,6 +132,9 @@ impl Theme { border: modifier(Modifier::DIM), title: modifier(Modifier::BOLD), text: Style::new(), + strong: modifier(Modifier::BOLD), + choice: modifier(Modifier::REVERSED | Modifier::BOLD), + inactive: modifier(Modifier::DIM), kinds: Kinds::plain(), glyphs: Glyphs { cursor: "> ", @@ -181,6 +196,12 @@ impl Theme { } } + /// A section heading: its kind's colour when it has one, bold either way. + pub fn heading(&self, kind: Option) -> Style { + kind.map_or(self.title, |kind| self.kind_style(kind)) + .add_modifier(Modifier::BOLD) + } + pub fn border_for(&self, focused: bool) -> Style { if focused { self.focus_border diff --git a/src/tui/tree_view/draw.rs b/src/tui/tree_view/draw.rs index 999b996..306917b 100644 --- a/src/tui/tree_view/draw.rs +++ b/src/tui/tree_view/draw.rs @@ -13,6 +13,7 @@ use crate::tui::keymap::{self, Scope}; use crate::tui::theme::Theme; use crate::tui::widgets::empty; use crate::tui::widgets::keybar::KeyBar; +use crate::tui::widgets::margin; use crate::tui::widgets::modal::{self, ModalSize}; use crate::tui::widgets::panel::Panel; @@ -31,8 +32,8 @@ fn mark_span(mark: Mark, theme: &Theme) -> Span<'static> { impl TreeState { pub fn draw(&mut self, title: &str, frame: &mut Frame, theme: &Theme) { - let [body, foot] = - Layout::vertical([Constraint::Min(1), Constraint::Length(1)]).areas(frame.area()); + let [body, foot] = Layout::vertical([Constraint::Min(1), Constraint::Length(1)]) + .areas(margin::inset(frame.area())); self.draw_list(title, frame, body, theme); self.draw_footer(frame, foot, theme); self.draw_overlay(frame, theme); diff --git a/src/tui/tree_view/tests.rs b/src/tui/tree_view/tests.rs index 6765165..77aacd3 100644 --- a/src/tui/tree_view/tests.rs +++ b/src/tui/tree_view/tests.rs @@ -2,6 +2,7 @@ use super::marks::Mark; use super::model::Overlay; use super::*; use crate::tui::theme::Theme; +use crate::tui::widgets::margin::{MARGIN_X, MARGIN_Y}; use crate::tui::widgets::testing::{key, keys, render_to_buffer, row_text}; use ratatui::crossterm::event::{KeyCode, KeyEvent}; @@ -212,9 +213,11 @@ fn the_cursor_row_is_drawn_with_the_selection_style() { let buffer = render_to_buffer(40, 8, |f| s.draw("t", f, &theme)); - // Row 0 sits under the border and the column header; its cells carry the selection background. - assert_eq!(buffer[(6, 2)].bg, theme.selection.bg.unwrap()); - assert_ne!(buffer[(6, 3)].bg, theme.selection.bg.unwrap()); + // Row 0 sits under the margin, the border and the column header; its cells carry the + // selection background. + let (x, y) = (6 + MARGIN_X, 2 + MARGIN_Y); + assert_eq!(buffer[(x, y)].bg, theme.selection.bg.unwrap()); + assert_ne!(buffer[(x, y + 1)].bg, theme.selection.bg.unwrap()); } #[test] diff --git a/src/tui/widgets/buttons.rs b/src/tui/widgets/buttons.rs new file mode 100644 index 0000000..783ec1d --- /dev/null +++ b/src/tui/widgets/buttons.rs @@ -0,0 +1,98 @@ +//! A row of labelled buttons, one of them focused. Every confirm dialog draws its answers with +//! this, the cancelling one first. + +use ratatui::text::{Line, Span}; + +use crate::tui::theme::Theme; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Buttons { + labels: Vec, + focus: usize, +} + +impl Buttons { + /// `labels` left to right, with `focus` on the one at that position. + pub fn new(labels: &[&str], focus: usize) -> Self { + Buttons { + labels: labels.iter().map(|l| l.to_string()).collect(), + focus: focus.min(labels.len().saturating_sub(1)), + } + } + + pub fn focus(&self) -> usize { + self.focus + } + + pub fn set_label(&mut self, at: usize, label: &str) { + if let Some(slot) = self.labels.get_mut(at) { + *slot = label.to_string(); + } + } + + pub fn next(&mut self) { + self.focus = (self.focus + 1) % self.labels.len().max(1); + } + + pub fn previous(&mut self) { + let count = self.labels.len().max(1); + self.focus = (self.focus + count - 1) % count; + } + + /// `[ Cancel ] [ Delete ]`, the focused one reversed. + pub fn line(&self, theme: &Theme) -> Line<'static> { + let mut spans = Vec::new(); + for (at, label) in self.labels.iter().enumerate() { + if at > 0 { + spans.push(Span::raw(" ")); + } + let style = if at == self.focus { + theme.choice + } else { + theme.text + }; + spans.push(Span::styled(format!("[ {label} ]"), style)); + } + Line::from(spans) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn focus_wraps_both_ways() { + let mut buttons = Buttons::new(&["Cancel", "Delete"], 0); + + buttons.previous(); + let wrapped_back = buttons.focus(); + buttons.next(); + + assert_eq!((wrapped_back, buttons.focus()), (1, 0)); + } + + #[test] + fn only_the_focused_button_is_reversed() { + let theme = Theme::dark(); + let line = Buttons::new(&["Cancel", "Delete"], 1).line(&theme); + + let styles: Vec<_> = line + .spans + .iter() + .filter(|s| s.content.starts_with('[')) + .map(|s| s.style) + .collect(); + + assert_eq!(styles, [theme.text, theme.choice]); + } + + #[test] + fn a_label_can_be_replaced() { + let mut buttons = Buttons::new(&["Cancel", "Apply"], 1); + + buttons.set_label(1, "Dry run"); + + assert!(buttons.line(&Theme::dark()).to_string().contains("Dry run")); + } +} diff --git a/src/tui/widgets/confirm.rs b/src/tui/widgets/confirm.rs index ef408fb..5cc9391 100644 --- a/src/tui/widgets/confirm.rs +++ b/src/tui/widgets/confirm.rs @@ -1,12 +1,12 @@ -//! A yes/no dialog. Focus starts on No so a stray Enter never destroys anything. +//! A confirm dialog: a question and two answers as buttons, the cancelling one first. Focus starts +//! on the cancelling button so a stray Enter never destroys anything. use ratatui::Frame; use ratatui::crossterm::event::KeyEvent; -use ratatui::layout::{Constraint, Layout}; -use ratatui::style::{Modifier, Style}; -use ratatui::text::{Line, Span}; use ratatui::widgets::{Paragraph, Wrap}; +use super::buttons::Buttons; +use super::container::{Container, Size}; use super::modal::{self, ModalSize}; use super::panel::Panel; use crate::tui::keymap::{self, Action, Scope}; @@ -20,17 +20,15 @@ pub enum Outcome { No, } -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -enum Button { - Yes, - No, -} +/// Where the cancelling and the confirming button sit in the row. +const CANCEL: usize = 0; +const CONFIRM: usize = 1; #[derive(Debug, Clone, PartialEq, Eq)] pub struct ConfirmDialog { title: String, prompt: String, - focus: Button, + buttons: Buttons, } impl ConfirmDialog { @@ -38,13 +36,13 @@ impl ConfirmDialog { ConfirmDialog { title: title.into(), prompt: prompt.into(), - focus: Button::No, + buttons: Buttons::new(&["No", "Yes"], CANCEL), } } #[cfg(test)] pub fn yes_focused(&self) -> bool { - self.focus == Button::Yes + self.buttons.focus() == CONFIRM } pub fn handle(&mut self, key: KeyEvent) -> Outcome { @@ -53,7 +51,7 @@ impl ConfirmDialog { Some(Action::No | Action::Back | Action::Quit | Action::Interrupt) => Outcome::No, Some(Action::Select) => self.choice(), Some(Action::Toggle) => { - self.toggle_focus(); + self.buttons.next(); Outcome::Pending } _ => Outcome::Pending, @@ -61,53 +59,23 @@ impl ConfirmDialog { } fn choice(&self) -> Outcome { - match self.focus { - Button::Yes => Outcome::Yes, - Button::No => Outcome::No, + match self.buttons.focus() { + CONFIRM => Outcome::Yes, + _ => Outcome::No, } } - fn toggle_focus(&mut self) { - self.focus = match self.focus { - Button::Yes => Button::No, - Button::No => Button::Yes, - }; - } - pub fn render(&self, frame: &mut Frame, theme: &Theme) { let size = ModalSize { width: 52, height: 7, }; let inner = modal::open(frame, size, Panel::new(self.title.clone()), theme); - let [text, _, buttons] = Layout::vertical([ - Constraint::Min(1), - Constraint::Length(1), - Constraint::Length(1), - ]) - .areas(inner); + let [text, _, buttons] = + Container::column([Size::Fill(1), Size::Fixed(1), Size::Fixed(1)]).areas(inner); let prompt = Paragraph::new(self.prompt.clone()).wrap(Wrap { trim: true }); frame.render_widget(prompt, text); - let row = Paragraph::new(self.button_row(theme)).centered(); - frame.render_widget(row, buttons); - } - - fn button_row(&self, theme: &Theme) -> Line<'static> { - Line::from(vec![ - self.button("Yes", Button::Yes, theme), - Span::raw(" "), - self.button("No", Button::No, theme), - ]) - } - - fn button(&self, label: &str, which: Button, theme: &Theme) -> Span<'static> { - let base = theme.text; - let style = if self.focus == which { - base.patch(Style::new().add_modifier(Modifier::REVERSED | Modifier::BOLD)) - } else { - base - }; - Span::styled(format!("[ {label} ]"), style) + frame.render_widget(Paragraph::new(self.buttons.line(theme)).centered(), buttons); } } @@ -116,6 +84,7 @@ mod tests { use super::*; use crate::tui::widgets::testing::{key, render_to_buffer, row_text}; use ratatui::crossterm::event::KeyCode; + use ratatui::style::Modifier; fn dialog() -> ConfirmDialog { ConfirmDialog::new("Remove", "Sure?") @@ -163,9 +132,13 @@ mod tests { assert_eq!(dialog().handle(key(KeyCode::Char('z'))), Outcome::Pending); } + fn drawn(d: &ConfirmDialog, theme: &Theme) -> ratatui::buffer::Buffer { + render_to_buffer(60, 12, |f| d.render(f, theme)) + } + fn button_cell(d: &ConfirmDialog, theme: &Theme) -> ratatui::buffer::Cell { - let buffer = render_to_buffer(60, 11, |f| d.render(f, theme)); - let y = (0..11) + let buffer = drawn(d, theme); + let y = (0..12) .find(|y| row_text(&buffer, *y).contains('[')) .unwrap(); let x = row_text(&buffer, y).chars().position(|c| c == '[').unwrap(); @@ -176,8 +149,12 @@ mod tests { fn focused_button_is_reversed() { let theme = Theme::dark(); let mut d = dialog(); + // The cancelling button is first; moving on focuses the confirming one, so the first + // button is no longer the reversed one. + let before = button_cell(&d, &theme); d.handle(key(KeyCode::Tab)); - let cell = button_cell(&d, &theme); - assert!(cell.modifier.contains(Modifier::REVERSED)); + let after = button_cell(&d, &theme); + assert!(before.modifier.contains(Modifier::REVERSED)); + assert!(!after.modifier.contains(Modifier::REVERSED)); } } diff --git a/src/tui/widgets/container.rs b/src/tui/widgets/container.rs new file mode 100644 index 0000000..c97bb65 --- /dev/null +++ b/src/tui/widgets/container.rs @@ -0,0 +1,85 @@ +//! A flex container: splits an area along one axis into parts that are a fixed size or share +//! what is left. It draws nothing and has no margin, padding or gap, so parts sit edge to edge +//! and together cover the area. Whatever a part holds is the caller's to draw. + +use ratatui::layout::{Constraint, Direction, Layout, Rect}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Size { + /// This many cells along the axis; empty when it is 0. + Fixed(u16), + /// A share of what the fixed parts leave; `Fill(2)` takes twice what `Fill(1)` does. + Fill(u16), +} + +impl From for Constraint { + fn from(size: Size) -> Self { + match size { + Size::Fixed(cells) => Constraint::Length(cells), + Size::Fill(share) => Constraint::Fill(share), + } + } +} + +#[derive(Debug, Clone, Copy)] +pub struct Container { + axis: Direction, + sizes: [Size; N], +} + +impl Container { + /// Parts stacked top to bottom. + pub fn column(sizes: [Size; N]) -> Self { + Container { + axis: Direction::Vertical, + sizes, + } + } + + /// Parts side by side, left to right. + pub fn row(sizes: [Size; N]) -> Self { + Container { + axis: Direction::Horizontal, + sizes, + } + } + + /// The area of each part, in order. + pub fn areas(&self, area: Rect) -> [Rect; N] { + Layout::new(self.axis, self.sizes.map(Constraint::from)).areas(area) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_column_gives_fixed_parts_their_size_and_fill_the_rest_with_no_gaps() { + let [top, middle, bottom] = + Container::column([Size::Fixed(1), Size::Fill(1), Size::Fixed(2)]) + .areas(Rect::new(3, 4, 20, 10)); + + assert_eq!(top, Rect::new(3, 4, 20, 1)); + assert_eq!(middle, Rect::new(3, 5, 20, 7)); + assert_eq!(bottom, Rect::new(3, 12, 20, 2)); + } + + #[test] + fn a_row_splits_the_width_and_fill_parts_share_in_proportion() { + let [left, right] = + Container::row([Size::Fill(1), Size::Fill(2)]).areas(Rect::new(0, 0, 30, 5)); + + assert_eq!((left.width, right.width), (10, 20)); + assert_eq!(right.x, left.right()); + } + + #[test] + fn a_part_of_no_cells_is_empty_and_the_others_still_cover_the_area() { + let [none, rest] = + Container::column([Size::Fixed(0), Size::Fill(1)]).areas(Rect::new(0, 0, 8, 6)); + + assert!(none.is_empty()); + assert_eq!(rest, Rect::new(0, 0, 8, 6)); + } +} diff --git a/src/tui/widgets/margin.rs b/src/tui/widgets/margin.rs new file mode 100644 index 0000000..27afe4a --- /dev/null +++ b/src/tui/widgets/margin.rs @@ -0,0 +1,31 @@ +//! Breathing room between a full-screen layout and the terminal edge. + +use ratatui::layout::{Margin, Rect}; + +/// Terminal cells are about twice as tall as wide, so the sides get twice the rows' margin. +pub const MARGIN_X: u16 = 2; +pub const MARGIN_Y: u16 = 1; + +/// `screen` with the margin taken off every edge; empty when the screen is smaller than it. +pub fn inset(screen: Rect) -> Rect { + screen.inner(Margin::new(MARGIN_X, MARGIN_Y)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_edge_loses_the_margin() { + let inner = inset(Rect::new(0, 0, 80, 24)); + assert_eq!( + inner, + Rect::new(MARGIN_X, MARGIN_Y, 80 - 2 * MARGIN_X, 24 - 2 * MARGIN_Y) + ); + } + + #[test] + fn a_screen_smaller_than_the_margin_is_empty() { + assert!(inset(Rect::new(0, 0, 3, 1)).is_empty()); + } +} diff --git a/src/tui/widgets/mod.rs b/src/tui/widgets/mod.rs index d0e9279..7bc7dfe 100644 --- a/src/tui/widgets/mod.rs +++ b/src/tui/widgets/mod.rs @@ -1,14 +1,16 @@ //! Reusable widgets. Each is a pure state type plus a render fn that takes a `Theme`. +pub(crate) mod buttons; pub(crate) mod confirm; +pub(crate) mod container; pub(crate) mod empty; pub(crate) mod input; pub(crate) mod keybar; pub(crate) mod list; +pub(crate) mod margin; pub(crate) mod modal; pub(crate) mod outline; pub(crate) mod panel; -pub(crate) mod tabs; #[cfg(test)] pub(crate) mod testing; pub(crate) mod text_modal; diff --git a/src/tui/widgets/outline/mod.rs b/src/tui/widgets/outline/mod.rs index 0fd5f70..e4e168f 100644 --- a/src/tui/widgets/outline/mod.rs +++ b/src/tui/widgets/outline/mod.rs @@ -159,6 +159,7 @@ impl Outline { } /// How many rows sit directly under row `id`. + #[cfg(test)] pub fn child_count(&self, id: usize) -> usize { self.parents.iter().filter(|&&p| p == Some(id)).count() } diff --git a/src/tui/widgets/tabs.rs b/src/tui/widgets/tabs.rs deleted file mode 100644 index a62d195..0000000 --- a/src/tui/widgets/tabs.rs +++ /dev/null @@ -1,131 +0,0 @@ -//! A tab bar: which tab is selected, and stepping through them with wrap-around. - -use ratatui::Frame; -use ratatui::layout::Rect; -use ratatui::style::Modifier; -use ratatui::text::{Line, Span}; -use ratatui::widgets::Paragraph; - -use crate::tui::theme::Theme; - -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct Tabs { - titles: Vec, - selected: usize, -} - -impl Tabs { - pub fn new(titles: &[&str]) -> Self { - Tabs { - titles: titles.iter().map(|t| t.to_string()).collect(), - selected: 0, - } - } - - pub fn selected(&self) -> usize { - self.selected - } - - /// Jump to tab `index`; out of range is ignored. - pub fn select(&mut self, index: usize) { - if index < self.titles.len() { - self.selected = index; - } - } - - pub fn next(&mut self) { - self.selected = (self.selected + 1) % self.titles.len().max(1); - } - - pub fn previous(&mut self) { - let count = self.titles.len().max(1); - self.selected = (self.selected + count - 1) % count; - } - - pub fn render(&self, frame: &mut Frame, area: Rect, theme: &Theme) { - frame.render_widget(Paragraph::new(self.line(theme)), area); - } - - fn line(&self, theme: &Theme) -> Line<'static> { - let mut spans = Vec::new(); - for (i, title) in self.titles.iter().enumerate() { - if i > 0 { - spans.push(Span::styled(" │ ", theme.border)); - } - spans.push(self.tab(i, title, theme)); - } - Line::from(spans) - } - - fn tab(&self, index: usize, title: &str, theme: &Theme) -> Span<'static> { - let label = title.to_string(); - if index == self.selected { - Span::styled(label, theme.accent.add_modifier(Modifier::BOLD)) - } else { - Span::styled(label, theme.muted) - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::tui::widgets::testing::render_to_buffer; - - fn tabs() -> Tabs { - Tabs::new(&["alpha", "beta", "gamma"]) - } - - #[test] - fn select_jumps_and_ignores_out_of_range() { - let mut t = tabs(); - - t.select(2); - t.select(9); - - assert_eq!(t.selected(), 2); - } - - #[test] - fn next_steps_forward_and_wraps() { - let mut t = tabs(); - - let visited: Vec = (0..3) - .map(|_| { - t.next(); - t.selected() - }) - .collect(); - - assert_eq!(visited, [1, 2, 0]); - } - - #[test] - fn previous_wraps_backwards_from_the_first_tab() { - let mut t = tabs(); - - t.previous(); - - assert_eq!(t.selected(), 2); - } - - #[test] - fn stepping_with_one_tab_stays_put() { - let mut t = Tabs::new(&["only"]); - - t.next(); - t.previous(); - - assert_eq!(t.selected(), 0); - } - - #[test] - fn selected_tab_is_accented_and_others_muted() { - let theme = Theme::dark(); - let t = tabs(); - let buffer = render_to_buffer(40, 1, |f| t.render(f, f.area(), &theme)); - assert_eq!(buffer[(0, 0)].fg, theme.accent.fg.unwrap()); - let other = "1 alpha │ ".chars().count() as u16; - assert_eq!(buffer[(other, 0)].fg, theme.muted.fg.unwrap()); - } -} diff --git a/src/tui/widgets/text_modal.rs b/src/tui/widgets/text_modal.rs index 8d10075..f75963c 100644 --- a/src/tui/widgets/text_modal.rs +++ b/src/tui/widgets/text_modal.rs @@ -2,10 +2,10 @@ use ratatui::Frame; use ratatui::crossterm::event::{Event, MouseEventKind}; -use ratatui::layout::{Constraint, Layout}; use ratatui::text::Line; use ratatui::widgets::{Paragraph, Wrap}; +use super::container::{Container, Size}; use super::modal::{self, ModalSize, PAD_X}; use super::panel::Panel; use crate::tui::keymap::Action; @@ -13,10 +13,15 @@ use crate::tui::theme::Theme; const WIDTH: u16 = 76; +/// What a text modal shows: the body, then the answers as buttons and a line of help text, each +/// only when given. pub struct Page { pub panel: Panel, pub lines: Vec>, - pub footer: Line<'static>, + pub buttons: Option>, + pub help: Option>, + /// A line (of the body, before wrapping) to scroll into view, when it is not already. + pub reveal: Option, } #[derive(Default)] @@ -27,6 +32,16 @@ pub struct TextModal { } impl TextModal { + /// Scroll the least that brings `line` into the window. + fn reveal(&mut self, line: usize) { + let window = self.page.max(1); + if line < self.offset { + self.offset = line; + } else if line >= self.offset + window { + self.offset = line + 1 - window; + } + } + pub fn reset(&mut self) { self.offset = 0; } @@ -62,23 +77,38 @@ impl TextModal { let paragraph = Paragraph::new(page.lines).wrap(Wrap { trim: false }); let width = WIDTH.min(frame.area().width.saturating_sub(2 * PAD_X)); let lines = paragraph.line_count(width.saturating_sub(2)); + let (buttons, help) = (page.buttons.is_some(), page.help.is_some()); + let below = u16::from(buttons) + u16::from(help); + // The body, then a blank line and the rows below it, and the border's two rows. + let tail = if below > 0 { 1 + below } else { 0 }; let size = ModalSize { width, - height: u16::try_from(lines.saturating_add(4)).unwrap_or(u16::MAX), + height: u16::try_from(lines) + .unwrap_or(u16::MAX) + .saturating_add(tail + 2), }; let inner = modal::open(frame, size, page.panel, theme); - let [body, _, foot] = Layout::vertical([ - Constraint::Min(1), - Constraint::Length(1), - Constraint::Length(1), + let [body, _, buttons_row, help_row] = Container::column([ + Size::Fill(1), + Size::Fixed(u16::from(below > 0)), + Size::Fixed(u16::from(buttons)), + Size::Fixed(u16::from(help)), ]) .areas(inner); self.lines = paragraph.line_count(body.width); self.page = usize::from(body.height); + if let Some(line) = page.reveal { + self.reveal(line); + } self.clamp(); let offset = u16::try_from(self.offset).unwrap_or(u16::MAX); frame.render_widget(paragraph.scroll((offset, 0)), body); - frame.render_widget(Paragraph::new(page.footer), foot); + if let Some(line) = page.buttons { + frame.render_widget(Paragraph::new(line).centered(), buttons_row); + } + if let Some(line) = page.help { + frame.render_widget(Paragraph::new(line), help_row); + } } fn clamp(&mut self) { diff --git a/src/tui/workspace/checks.rs b/src/tui/workspace/checks.rs deleted file mode 100644 index 6727c71..0000000 --- a/src/tui/workspace/checks.rs +++ /dev/null @@ -1,49 +0,0 @@ -//! The ids of items the background update check has found newer versions of, kept for the -//! session. Results arrive on a channel and are taken whenever the screen is drawn. - -use std::collections::BTreeSet; -use std::sync::mpsc::Receiver; - -#[derive(Default)] -pub(super) struct Checks { - found: Option>, - outdated: BTreeSet, -} - -impl Checks { - pub fn watch(&mut self, found: Receiver) { - self.found = Some(found); - } - - /// Everything found so far. - pub fn outdated(&mut self) -> &BTreeSet { - if let Some(found) = &self.found { - self.outdated.extend(found.try_iter()); - } - &self.outdated - } - - pub fn forget(&mut self, ids: &[String]) { - self.outdated.retain(|id| !ids.contains(id)); - } -} - -#[cfg(test)] -mod tests { - use super::*; - use std::sync::mpsc; - - #[test] - fn found_ids_are_kept_until_forgotten() { - let (tx, rx) = mpsc::channel(); - let mut checks = Checks::default(); - checks.watch(rx); - - tx.send("a".to_string()).unwrap(); - tx.send("b".to_string()).unwrap(); - let found = checks.outdated().len(); - checks.forget(&["a".to_string()]); - - assert_eq!((found, checks.outdated().len()), (2, 1)); - } -} diff --git a/src/tui/workspace/installed/direct.rs b/src/tui/workspace/installed/direct.rs deleted file mode 100644 index 5fc0235..0000000 --- a/src/tui/workspace/installed/direct.rs +++ /dev/null @@ -1,23 +0,0 @@ -//! Removing the highlighted row at once. - -use super::InstalledTab; -use crate::app::workspace::Act; - -impl InstalledTab { - /// Remove the highlighted item, or everything its package provides; on a section, mark every - /// item in it for removal instead. - pub(super) fn remove_current(&mut self) -> Option { - if let Some(ids) = self.section_ids() { - self.pending.toggle_all(&ids); - return None; - } - let ids = self.acted_on(); - match ids.is_empty() { - true => None, - false => Some(Act::Remove { - scope: self.scope, - ids, - }), - } - } -} diff --git a/src/tui/workspace/installed/direct_tests.rs b/src/tui/workspace/installed/direct_tests.rs deleted file mode 100644 index bae430a..0000000 --- a/src/tui/workspace/installed/direct_tests.rs +++ /dev/null @@ -1,101 +0,0 @@ -use ratatui::crossterm::event::KeyCode; - -use super::rows::tests::installed; -use super::tests::{PLUGIN, PLUGINS, TDD, loaded, on_item, press}; -use super::*; -use skillz_harness::model::{Kind, Scope}; - -fn remove(ids: &[&str]) -> Option { - Some(Act::Remove { - scope: Scope::Project, - ids: ids.iter().map(|id| id.to_string()).collect(), - }) -} - -#[test] -fn r_removes_the_highlighted_item_at_once() { - let mut tab = loaded(); - on_item(&mut tab, TDD); - - assert_eq!(press(&mut tab, KeyCode::Char('r')), remove(&["skill:tdd"])); -} - -#[test] -fn r_on_a_plugin_removes_the_whole_plugin() { - let mut tab = loaded(); - on_item(&mut tab, PLUGIN); - - assert_eq!( - press(&mut tab, KeyCode::Char('r')), - remove(&["plugin:p@mp"]) - ); -} - -#[test] -fn a_plugin_expands_but_its_contents_cannot_be_removed_separately() { - let mut tab = loaded(); - on_item(&mut tab, PLUGIN); - let before = tab.outline.visible().len(); - press(&mut tab, KeyCode::Right); - assert_eq!(tab.outline.visible().len(), before + 2); - let child = tab - .rows - .iter() - .position(|row| matches!(row, Row::Detail(_))) - .unwrap(); - on_item(&mut tab, child); - assert_eq!(press(&mut tab, KeyCode::Char('r')), None); - assert_eq!(press(&mut tab, KeyCode::Char('u')), None); - press(&mut tab, KeyCode::Char(' ')); - assert!(tab.pending.is_empty()); - on_item(&mut tab, PLUGIN); - assert_eq!( - press(&mut tab, KeyCode::Char('r')), - remove(&["plugin:p@mp"]) - ); -} - -#[test] -fn r_on_a_package_removes_everything_installed_from_it() { - let mut tab = InstalledTab::project(); - tab.load_open(&Model { - installed: vec![ - installed("tdd", Kind::Skill, Some("o/r")), - installed("grill", Kind::Skill, Some("o/r")), - installed("other", Kind::Skill, Some("x/y")), - ], - ..Model::default() - }); - let package = tab - .rows - .iter() - .position(|row| matches!(row, Row::Package(_))) - .unwrap(); - on_item(&mut tab, package); - - let act = press(&mut tab, KeyCode::Char('r')); - - assert_eq!(act, remove(&["skill:grill", "skill:tdd"])); -} - -#[test] -fn r_on_a_section_marks_every_item_in_it_for_removal() { - let mut tab = loaded(); - on_item(&mut tab, PLUGINS); - - let act = press(&mut tab, KeyCode::Char('r')); - - assert_eq!(act, None); - assert_eq!(tab.pending.picks(), ["plugin:p@mp"]); -} - -#[test] -fn typing_r_into_the_filter_is_text_not_a_command() { - let mut tab = loaded(); - press(&mut tab, KeyCode::Char('/')); - - let act = press(&mut tab, KeyCode::Char('r')); - - assert_eq!(act, None); - assert_eq!(tab.outline.query(), "r"); -} diff --git a/src/tui/workspace/installed/draw.rs b/src/tui/workspace/installed/draw.rs deleted file mode 100644 index d0bec2b..0000000 --- a/src/tui/workspace/installed/draw.rs +++ /dev/null @@ -1,195 +0,0 @@ -//! Drawing the Project and Global tabs: the header line, then the outline in a panel. - -use ratatui::Frame; -use ratatui::layout::{Constraint, Layout, Margin, Rect}; -use ratatui::style::Modifier; -use ratatui::text::{Line, Span}; -use ratatui::widgets::Paragraph; - -use super::header::{self, Comparison}; -use super::rows::{Item, Row}; -use super::status::Status; -use super::{InstalledTab, Popup}; -use crate::app::apply::Drift; -use crate::tui::filter; -use crate::tui::theme::Theme; -use crate::tui::widgets::empty; -use crate::tui::widgets::modal::{self, ModalSize}; -use crate::tui::widgets::panel::Panel; -use skillz_harness::model::Scope; - -/// Room per level of depth before a row's caret or status mark. -pub(super) const INDENT: &str = " "; -const SOURCE_WIDTH: u16 = 56; - -impl InstalledTab { - pub(super) fn draw_body(&mut self, frame: &mut Frame, area: Rect, theme: &Theme) { - let drift = self.drift(); - let comparison = self.comparison(&drift); - let [head, body] = - Layout::vertical([Constraint::Length(1), Constraint::Min(1)]).areas(area); - let line = header::line(comparison, head.width, theme); - frame.render_widget(Paragraph::new(line), head); - self.draw_outline(frame, body, theme); - match &mut self.popup { - Popup::Apply(picker) => picker.render(frame, theme), - Popup::Subset(subset) => subset.render(frame, theme), - Popup::Save(field) => { - let size = ModalSize { - width: SOURCE_WIDTH.min(frame.area().width), - height: 3, - }; - let inner = modal::open(frame, size, Panel::new("Save as profile"), theme); - field.render(frame, inner, theme); - } - Popup::Source(field) => { - let size = ModalSize { - width: SOURCE_WIDTH.min(frame.area().width), - height: 3, - }; - let inner = modal::open(frame, size, Panel::new("Add from repo"), theme); - field.render(frame, inner, theme); - } - Popup::None | Popup::Filter => {} - } - } - - fn panel_title(&self) -> &str { - match self.scope { - Scope::Project => &self.dir, - Scope::Global => "User-level, all projects", - } - } - - fn comparison<'a>(&self, drift: &'a Option) -> Comparison<'a> { - match drift { - None => Comparison::Unchosen, - Some(drift) => Comparison::With(drift), - } - } - - fn draw_outline(&mut self, frame: &mut Frame, area: Rect, theme: &Theme) { - let panel = Panel::new(filter::title(self.panel_title(), self.outline.query())) - .focused(true) - .bare() - .badge(self.outline.badge()); - let inner = panel.render(frame, area, theme).inner(Margin::new(1, 0)); - if self.outline.visible().is_empty() { - return empty::render(frame, inner, self.empty_message(theme)); - } - let lines: Vec> = self - .outline - .visible() - .iter() - .map(|&id| self.row_line(id, theme)) - .collect(); - self.outline.render(frame, inner, &lines, theme); - } - - fn empty_message(&self, theme: &Theme) -> Vec> { - if self.outline.is_filtered() { - return vec![Line::styled("Nothing matches", theme.muted)]; - } - vec![ - Line::styled("Nothing installed here", theme.text), - Line::styled("A adds a plugin or skills from a repo", theme.muted), - ] - } - - fn row_line(&self, id: usize, theme: &Theme) -> Line<'static> { - let mut line = match &self.rows[id] { - Row::Inherited => { - let count = self.rows[id + 1..] - .iter() - .filter(|row| matches!(row, Row::Item(_))) - .count(); - let rule = theme.glyphs.rule.repeat(2); - Line::from(format!( - "{rule} {} Global installs · read only ({count}) {rule}", - self.outline.caret(id, &theme.glyphs) - )) - } - Row::Section(kind) => self.section_line(id, *kind, theme), - Row::Package(group) => self.group_line(id, group, theme), - Row::Item(item) => self.item_line(id, item, theme), - Row::Detail(label) => Line::styled( - format!("{}{label}", INDENT.repeat(self.outline.depth(id) + 2)), - theme.muted, - ), - }; - if self.read_only(id) { - let dim = theme.muted.add_modifier(Modifier::DIM); - line.style = dim; - for span in &mut line.spans { - span.style = dim; - } - } - line - } - - /// The spinner, tick or cross of a change under way on the row; a space otherwise. - fn status_mark(&self, id: &str, theme: &Theme) -> Span<'static> { - let glyphs = &theme.glyphs; - match self.statuses.of(id) { - Some(Status::Working) => { - Span::styled(glyphs.frame(self.statuses.ticks()), theme.accent) - } - Some(Status::Done) => Span::styled(glyphs.loaded, theme.ok), - Some(Status::Failed) => Span::styled(glyphs.failed, theme.danger), - None => Span::raw(" "), - } - } - - fn item_line(&self, row: usize, item: &Item, theme: &Theme) -> Line<'static> { - let glyphs = &theme.glyphs; - // Picks, change progress and update marks are keyed by id; a read-only row shows none - // of them, whatever id a project row shares with it. - let live = !self.read_only(row); - let picked = live && self.pending.contains(&item.id); - let (box_glyph, box_style, text_style) = match picked { - false => ( - glyphs.checked, - theme.ok, - theme.text.add_modifier(Modifier::BOLD), - ), - true => (glyphs.to_remove, theme.warn, theme.warn), - }; - let mut spans = vec![Span::raw(INDENT.repeat(self.outline.depth(row)))]; - if !item.children.is_empty() { - spans.push(Span::styled( - format!("{} ", self.outline.caret(row, glyphs)), - theme.muted, - )); - } - let status = match live { - true => self.status_mark(&item.id, theme), - false => Span::raw(" "), - }; - spans.extend([status, Span::styled(format!(" {box_glyph} "), box_style)]); - let outdated = live && self.is_outdated(&item.id); - let text_style = match outdated { - true => text_style.add_modifier(Modifier::BOLD), - false => text_style, - }; - spans.extend(filter::highlight( - &item.label, - &self.outline.matched(row), - 0, - text_style, - theme, - )); - if outdated { - spans.push(Span::styled("*", text_style)); - } - if !item.agents.is_empty() { - spans.push(Span::styled(format!(" ({})", item.agents), theme.muted)); - } - if !item.detail.is_empty() { - spans.push(Span::styled(format!(" {}", item.detail), theme.muted)); - } - if picked { - spans.push(Span::styled(" to remove", text_style)); - } - Line::from(spans) - } -} diff --git a/src/tui/workspace/installed/draw_group.rs b/src/tui/workspace/installed/draw_group.rs deleted file mode 100644 index 1cb5532..0000000 --- a/src/tui/workspace/installed/draw_group.rs +++ /dev/null @@ -1,57 +0,0 @@ -//! Drawing the rows that stand for a section and for a package. - -use ratatui::style::Modifier; -use ratatui::text::{Line, Span}; - -use super::InstalledTab; -use super::draw::INDENT; -use super::rows::{Group, items_of, plural}; -use crate::app::library::ItemKind; -use crate::tui::theme::Theme; -use skillz_harness::model::Kind; - -impl InstalledTab { - pub(super) fn section_line(&self, id: usize, kind: Kind, theme: &Theme) -> Line<'static> { - let caret = self.outline.caret(id, &theme.glyphs); - let indent = INDENT.repeat(self.outline.depth(id)); - let count = items_of(&self.rows, id).count(); - let mut spans = vec![ - Span::styled( - format!("{indent}{caret} {}", plural(kind)), - ItemKind::of(kind) - .map_or(theme.title, |kind| theme.kind_style(kind)) - .add_modifier(Modifier::BOLD), - ), - Span::styled(format!(" ({count})"), theme.muted), - ]; - spans.extend(self.pending_summary(id, theme)); - Line::from(spans) - } - - pub(super) fn group_line(&self, id: usize, group: &Group, theme: &Theme) -> Line<'static> { - let caret = self.outline.caret(id, &theme.glyphs); - let indent = INDENT.repeat(self.outline.depth(id)); - let mut spans = vec![ - Span::styled( - format!("{indent}{caret} {}", group.package.title()), - theme.title, - ), - Span::styled( - format!(" ({})", items_of(&self.rows, id).count()), - theme.muted, - ), - ]; - spans.extend(self.pending_summary(id, theme)); - Line::from(spans) - } - - fn pending_summary(&self, row: usize, theme: &Theme) -> Option> { - match self.pending.count(items_of(&self.rows, row)) { - 0 => None, - removing => Some(Span::styled( - format!(" {removing} to remove"), - theme.accent, - )), - } - } -} diff --git a/src/tui/workspace/installed/global_tests.rs b/src/tui/workspace/installed/global_tests.rs deleted file mode 100644 index 61f16e4..0000000 --- a/src/tui/workspace/installed/global_tests.rs +++ /dev/null @@ -1,322 +0,0 @@ -use ratatui::crossterm::event::KeyCode; - -use super::rows::tests::{global, installed}; -use super::tests::{on_item, press}; -use super::*; -use crate::tui::widgets::testing::open_all; -use crate::tui::widgets::testing::render_to_buffer; -use skillz_harness::Spec; -use skillz_harness::model::Kind; - -/// `tdd` installed in the project and `grill` globally. -fn model() -> Model { - Model { - dir: "~/app".into(), - installed: vec![installed("tdd", Kind::Skill, Some("o/r"))], - global: vec![global("grill", Kind::Skill, Some("o/r"))], - ..Model::default() - } -} - -/// The rows of a scope's one skill: its section, the package, the skill. -const SKILL: usize = 2; - -fn loaded(scope: Scope) -> InstalledTab { - let mut tab = InstalledTab::new(scope); - tab.load(&model()); - open_all(&mut tab.outline); - tab -} - -fn labels(tab: &InstalledTab) -> Vec { - tab.rows - .iter() - .filter_map(|row| match row { - Row::Item(item) => Some(item.label.clone()), - _ => None, - }) - .collect() -} - -#[test] -fn the_project_tab_also_lists_global_skills_for_inspection() { - assert_eq!(labels(&loaded(Scope::Project)), ["tdd", "grill"]); - assert_eq!(labels(&loaded(Scope::Global)), ["grill"]); -} - -#[test] -fn the_global_tab_has_no_keep_clear_or_save_keys() { - let mut tab = loaded(Scope::Global); - - let keys = ['p', 'c', 's'].map(|c| press(&mut tab, KeyCode::Char(c))); - - assert_eq!((keys, tab.captures_keys()), ([None, None, None], false)); -} - -/// A global tab holding `grill` globally, with a profile `web` that wants it, applied there. -fn global_tab_with_profile() -> InstalledTab { - let mut web = Profile::new("web"); - web.entries = vec![Spec::Skill { - source: "o/r".into(), - names: vec!["grill".into()], - agents: vec![], - }]; - let mut tab = InstalledTab::new(Scope::Global); - tab.load(&Model { - global: vec![global("grill", Kind::Skill, Some("o/r"))], - profiles: vec![web], - applied: Some("api".into()), - applied_global: Some("web".into()), - ..Model::default() - }); - tab -} - -#[test] -fn a_on_the_global_tab_applies_a_profile_at_user_level_and_adds_by_default() { - let mut tab = global_tab_with_profile(); - - press(&mut tab, KeyCode::Char('a')); - let added = press(&mut tab, KeyCode::Enter); - press(&mut tab, KeyCode::Char('a')); - press(&mut tab, KeyCode::Char('m')); - let replaced = press(&mut tab, KeyCode::Enter); - - assert_eq!( - (added, replaced), - ( - Some(Act::Apply { - scope: Scope::Global, - profile: "web".into() - }), - Some(Act::ApplyExact { - scope: Scope::Global, - profile: "web".into() - }) - ) - ); -} - -#[test] -fn the_global_tab_compares_with_the_profile_applied_at_user_level_not_the_projects() { - let tab = global_tab_with_profile(); - - let drift = tab.drift().unwrap(); - - assert_eq!((drift.profile.as_str(), drift.matches()), ("web", true)); -} - -#[test] -fn removing_and_updating_on_the_global_tab_name_the_global_scope() { - let mut tab = loaded(Scope::Global); - on_item(&mut tab, SKILL); - - let remove = press(&mut tab, KeyCode::Char('r')); - let update = press(&mut tab, KeyCode::Char('u')); - - assert_eq!( - remove, - Some(Act::Remove { - scope: Scope::Global, - ids: vec!["global-skill:grill".into()] - }) - ); - assert_eq!( - update, - Some(Act::Update { - scope: Scope::Global, - ids: vec!["global-skill:grill".into()] - }) - ); -} - -fn drawn_checkboxes(scope: Scope, width: u16, height: u16) -> usize { - let mut tab = loaded(scope); - let theme = Theme::dark(); - let buffer = render_to_buffer(width, height, |f| tab.draw(f, f.area(), &theme)); - buffer - .content() - .iter() - .filter(|cell| cell.symbol() == theme.glyphs.checked) - .count() -} - -#[test] -fn both_tabs_draw_their_rows_at_small_and_large_sizes() { - for scope in [Scope::Project, Scope::Global] { - let count = if scope == Scope::Project { 2 } else { 1 }; - assert_eq!(drawn_checkboxes(scope, 80, 24), count, "{scope:?}"); - assert_eq!(drawn_checkboxes(scope, 50, 15), count, "{scope:?}"); - } -} - -#[test] -fn marketplaces_can_be_removed_and_updated_from_either_scope() { - for scope in [Scope::Project, Scope::Global] { - let mut marketplace = installed("mp", Kind::Marketplace, Some("o/mp")); - marketplace.scope = scope; - marketplace.installer = skillz_harness::model::Installer::ClaudeCli; - let id = marketplace.id.clone(); - let model = match scope { - Scope::Project => Model { - installed: vec![marketplace], - ..Model::default() - }, - Scope::Global => Model { - global: vec![marketplace], - ..Model::default() - }, - }; - let mut tab = InstalledTab::new(scope); - tab.load_open(&model); - let at = tab - .rows - .iter() - .position(|row| matches!(row, Row::Item(item) if item.id == id)) - .unwrap(); - on_item(&mut tab, at); - assert_eq!( - press(&mut tab, KeyCode::Char('r')), - Some(Act::Remove { - scope, - ids: vec![id.clone()] - }) - ); - assert_eq!( - press(&mut tab, KeyCode::Char('u')), - Some(Act::Update { - scope, - ids: vec![id] - }) - ); - } -} - -#[test] -fn inherited_items_cannot_be_picked_removed_updated_or_cleared() { - let mut tab = loaded(Scope::Project); - let inherited = tab - .rows - .iter() - .position(|row| matches!(row, Row::Item(item) if item.id == "global-skill:grill")) - .unwrap(); - on_item(&mut tab, inherited); - - assert_eq!(press(&mut tab, KeyCode::Char(' ')), None); - assert!(tab.pending.is_empty()); - assert_eq!(press(&mut tab, KeyCode::Char('r')), None); - assert_eq!(press(&mut tab, KeyCode::Char('u')), None); - assert_eq!( - press(&mut tab, KeyCode::Char('c')), - Some(Act::Remove { - scope: Scope::Project, - ids: vec!["skill:tdd".into()], - }) - ); -} - -#[test] -fn inherited_installs_draw_dimmed_while_project_installs_do_not() { - use ratatui::style::Modifier; - let mut tab = loaded(Scope::Project); - let theme = Theme::dark(); - let buffer = render_to_buffer(100, 30, |frame| tab.draw(frame, frame.area(), &theme)); - let dimmed: Vec<_> = buffer - .content() - .iter() - .filter(|cell| cell.symbol() == theme.glyphs.checked) - .map(|cell| cell.modifier.contains(Modifier::DIM)) - .collect(); - assert_eq!(dimmed, [false, true]); -} - -#[test] -fn inherited_plugins_expand_one_level_at_a_time_without_becoming_actionable() { - let mut plugin = super::rows::tests::plugin_providing_a_skill_and_a_hook("global-plugin"); - plugin.scope = Scope::Global; - let mut tab = InstalledTab::project(); - tab.load(&Model { - global: vec![plugin], - ..Model::default() - }); - assert_eq!(tab.outline.visible(), [0]); - press(&mut tab, KeyCode::Right); - assert_eq!(tab.outline.visible(), [0, 1]); - tab.outline.select_row(1); - press(&mut tab, KeyCode::Right); - assert_eq!(tab.outline.visible(), [0, 1, 2]); - tab.outline.select_row(2); - press(&mut tab, KeyCode::Enter); - assert_eq!(tab.outline.visible(), [0, 1, 2, 3, 4]); - assert!(tab.pending.is_empty()); - assert_eq!(press(&mut tab, KeyCode::Char('r')), None); - tab.outline.select_row(3); - assert_eq!(press(&mut tab, KeyCode::Char('r')), None); - assert_eq!(press(&mut tab, KeyCode::Char('u')), None); - assert_eq!(press(&mut tab, KeyCode::Char('c')), None); -} - -#[test] -fn picking_a_project_item_marks_no_inherited_item_that_shares_its_id() { - let mut tab = InstalledTab::project(); - tab.load(&Model { - installed: vec![installed("tdd", Kind::Skill, Some("o/r"))], - global: vec![Installed { - id: "skill:tdd".into(), - ..global("tdd", Kind::Skill, Some("o/r")) - }], - ..Model::default() - }); - open_all(&mut tab.outline); - let project = tab - .rows - .iter() - .position(|row| matches!(row, Row::Item(item) if item.id == "skill:tdd")) - .unwrap(); - on_item(&mut tab, project); - press(&mut tab, KeyCode::Char(' ')); - - let theme = Theme::dark(); - let buffer = render_to_buffer(100, 30, |frame| tab.draw(frame, frame.area(), &theme)); - let marked = |glyph: &str| { - buffer - .content() - .iter() - .filter(|cell| cell.symbol() == glyph) - .count() - }; - - assert_eq!( - (marked(theme.glyphs.to_remove), marked(theme.glyphs.checked)), - (1, 1) - ); -} - -#[test] -fn a_pick_does_not_outlive_its_project_item_because_a_global_one_shares_the_id() { - let shared = |build: fn(&str, Kind, Option<&str>) -> Installed| Installed { - id: "skill:tdd".into(), - ..build("tdd", Kind::Skill, Some("o/r")) - }; - let mut tab = InstalledTab::project(); - tab.load(&Model { - installed: vec![shared(installed)], - global: vec![shared(global)], - ..Model::default() - }); - open_all(&mut tab.outline); - let project = tab - .rows - .iter() - .position(|row| matches!(row, Row::Item(item) if item.id == "skill:tdd")) - .unwrap(); - on_item(&mut tab, project); - press(&mut tab, KeyCode::Char(' ')); - - tab.load(&Model { - global: vec![shared(global)], - ..Model::default() - }); - - assert!(tab.pending.is_empty()); -} diff --git a/src/tui/workspace/installed/header.rs b/src/tui/workspace/installed/header.rs deleted file mode 100644 index 3fbd49e..0000000 --- a/src/tui/workspace/installed/header.rs +++ /dev/null @@ -1,131 +0,0 @@ -//! The line above the outline: where the items are and how they compare with the chosen profile. - -use ratatui::style::Style; -use ratatui::text::{Line, Span}; -use unicode_width::UnicodeWidthStr; - -use crate::app::apply::Drift; -use crate::tui::theme::Theme; - -const GAP: &str = " "; - -#[derive(Debug, Clone, PartialEq, Eq)] -pub(super) struct Segment { - pub text: String, - pub style: Style, -} - -fn seg(text: impl Into, style: Style) -> Segment { - Segment { - text: text.into(), - style, - } -} - -/// How the items stand against the profile applied at the tab's level. -#[derive(Debug, Clone, Copy)] -pub(super) enum Comparison<'a> { - Unchosen, - With(&'a Drift), -} - -/// The pieces of the header, most important first. -pub(super) fn segments(comparison: Comparison, theme: &Theme) -> Vec { - let mut shown = vec![]; - match comparison { - Comparison::Unchosen => shown.push(seg("no profile applied", theme.muted)), - Comparison::With(d) if d.matches() => shown.push(seg( - format!("{} matches {}", theme.glyphs.loaded, d.profile), - theme.ok, - )), - Comparison::With(d) => { - if d.missing > 0 { - shown.push(seg(format!("{} missing", d.missing), theme.danger)); - } - if d.extra > 0 { - shown.push(seg(format!("{} extra", d.extra), theme.warn)); - } - shown.push(seg(format!("vs {}", d.profile), theme.muted)); - } - } - shown -} - -/// The segments that fit `width`, in order; the first always stays. -fn fit(segments: Vec, width: usize) -> Vec { - let mut used = 0; - let mut kept = Vec::new(); - for (i, segment) in segments.into_iter().enumerate() { - used += segment.text.width() + if i > 0 { GAP.width() } else { 0 }; - if i > 0 && used > width { - break; - } - kept.push(segment); - } - kept -} - -pub(super) fn line(comparison: Comparison, width: u16, theme: &Theme) -> Line<'static> { - let mut spans = Vec::new(); - for (i, segment) in fit(segments(comparison, theme), width as usize) - .into_iter() - .enumerate() - { - if i > 0 { - spans.push(Span::raw(GAP)); - } - spans.push(Span::styled(segment.text, segment.style)); - } - Line::from(spans) -} - -#[cfg(test)] -mod tests { - use super::*; - - fn drift(missing: usize, extra: usize) -> Drift { - Drift { - profile: "web".into(), - missing, - extra, - } - } - - fn styles(comparison: Comparison, theme: &Theme) -> Vec