From 690bc5e477387247b75004333a3ba5cb8ef214e5 Mon Sep 17 00:00:00 2001 From: archae0pteryx Date: Sat, 7 Nov 2026 11:33:19 -0800 Subject: [PATCH 1/2] bd init: initialize beads issue tracking --- .agents/skills/beads/SKILL.md | 80 +++++++++ .agents/skills/beads/agents/openai.yaml | 4 + .agents/skills/code-review/SKILL.md | 89 +++++++++ .agents/skills/code-review/agents/openai.yaml | 3 + .agents/skills/codebase-design/DEEPENING.md | 37 ++++ .../skills/codebase-design/DESIGN-IT-TWICE.md | 44 +++++ .agents/skills/codebase-design/SKILL.md | 114 ++++++++++++ .../skills/codebase-design/agents/openai.yaml | 3 + .agents/skills/domain-modeling/ADR-FORMAT.md | 47 +++++ .../skills/domain-modeling/GLOSSARY-FORMAT.md | 60 +++++++ .agents/skills/domain-modeling/SKILL.md | 74 ++++++++ .../skills/domain-modeling/agents/openai.yaml | 3 + .agents/skills/handoff/SKILL.md | 16 ++ .agents/skills/handoff/agents/openai.yaml | 5 + .../HTML-REPORT.md | 123 +++++++++++++ .../improve-codebase-architecture/SKILL.md | 71 ++++++++ .../agents/openai.yaml | 5 + .agents/skills/pr/CREDITS.md | 3 + .agents/skills/pr/SKILL.md | 170 ++++++++++++++++++ .agents/skills/pr/agents/openai.yaml | 3 + .agents/skills/tdd/SKILL.md | 38 ++++ .agents/skills/tdd/agents/openai.yaml | 3 + .agents/skills/tdd/mocking.md | 59 ++++++ .agents/skills/tdd/tests.md | 77 ++++++++ .beads/.gitignore | 82 +++++++++ .beads/README.md | 81 +++++++++ .beads/config.yaml | 77 ++++++++ .beads/hooks/post-checkout | 59 ++++++ .beads/hooks/post-merge | 59 ++++++ .beads/hooks/pre-commit | 59 ++++++ .beads/hooks/pre-push | 59 ++++++ .beads/hooks/prepare-commit-msg | 59 ++++++ .beads/metadata.json | 7 + .claude/settings.json | 15 ++ .codex/config.toml | 2 + .codex/hooks.json | 51 ++++++ .cursor/hooks.json | 20 +++ .cursor/rules/beads.mdc | 67 +++++++ .gitignore | 7 + AGENTS.md | 128 +++++++++++++ CLAUDE.md | 77 ++++++++ 41 files changed, 2040 insertions(+) create mode 100644 .agents/skills/beads/SKILL.md create mode 100644 .agents/skills/beads/agents/openai.yaml create mode 100644 .agents/skills/code-review/SKILL.md create mode 100644 .agents/skills/code-review/agents/openai.yaml create mode 100644 .agents/skills/codebase-design/DEEPENING.md create mode 100644 .agents/skills/codebase-design/DESIGN-IT-TWICE.md create mode 100644 .agents/skills/codebase-design/SKILL.md create mode 100644 .agents/skills/codebase-design/agents/openai.yaml create mode 100644 .agents/skills/domain-modeling/ADR-FORMAT.md create mode 100644 .agents/skills/domain-modeling/GLOSSARY-FORMAT.md create mode 100644 .agents/skills/domain-modeling/SKILL.md create mode 100644 .agents/skills/domain-modeling/agents/openai.yaml create mode 100644 .agents/skills/handoff/SKILL.md create mode 100644 .agents/skills/handoff/agents/openai.yaml create mode 100644 .agents/skills/improve-codebase-architecture/HTML-REPORT.md create mode 100644 .agents/skills/improve-codebase-architecture/SKILL.md create mode 100644 .agents/skills/improve-codebase-architecture/agents/openai.yaml create mode 100644 .agents/skills/pr/CREDITS.md create mode 100644 .agents/skills/pr/SKILL.md create mode 100644 .agents/skills/pr/agents/openai.yaml create mode 100644 .agents/skills/tdd/SKILL.md create mode 100644 .agents/skills/tdd/agents/openai.yaml create mode 100644 .agents/skills/tdd/mocking.md create mode 100644 .agents/skills/tdd/tests.md create mode 100644 .beads/.gitignore create mode 100644 .beads/README.md create mode 100644 .beads/config.yaml create mode 100755 .beads/hooks/post-checkout create mode 100755 .beads/hooks/post-merge create mode 100755 .beads/hooks/pre-commit create mode 100755 .beads/hooks/pre-push create mode 100755 .beads/hooks/prepare-commit-msg create mode 100644 .beads/metadata.json create mode 100644 .claude/settings.json create mode 100644 .codex/config.toml create mode 100644 .codex/hooks.json create mode 100644 .cursor/hooks.json create mode 100644 .cursor/rules/beads.mdc create mode 100644 AGENTS.md create mode 100644 CLAUDE.md diff --git a/.agents/skills/beads/SKILL.md b/.agents/skills/beads/SKILL.md new file mode 100644 index 0000000..a5a3344 --- /dev/null +++ b/.agents/skills/beads/SKILL.md @@ -0,0 +1,80 @@ +--- +name: beads +description: Use when working in a repository that uses bd or Beads for durable project task tracking, issue dependencies, blocker management, multi-session handoff, or shared work memory. Trigger when the user asks to find ready work, claim or close tasks, create follow-up work, inspect blockers, recover project context, or choose between local planning and persistent project tracking. +--- + +# Beads + +Use Beads as the shared project task system. Local plans, scratch files, and personal memories are useful, but they are not the durable source of truth for project work. + +## First Step + +Run: + +```bash +bd prime +``` + +If that prints nothing, check whether the repository has an active Beads workspace: + +```bash +bd where +``` + +## Preferred Route + +Use the `bd` CLI when shell access is available. It is the most compact and direct Beads interface. + +## Core CLI Workflow + +1. Find work: + +```bash +bd ready +bd list --status=open +bd list --status=in_progress +``` + +2. Inspect before editing: + +```bash +bd show +``` + +3. Claim work atomically: + +```bash +bd update --claim +``` + +4. Create durable follow-up work when implementation reveals new tasks: + +```bash +bd create "Short title" --description="Why this exists and what needs to be done" --type=task --priority=2 +``` + +5. Close completed work: + +```bash +bd close --reason="Completed" +``` + +## What Belongs In Beads + +Use Beads for: + +- shared project tasks +- blockers and dependencies +- discovered follow-up work +- work that must survive thread reset, compaction, or handoff +- status that another person or agent should be able to resume + +Use agent-local planning tools only for the current turn's execution checklist. Do not treat them as shared project state. + +## Rules + +- Do not create markdown TODO files as the source of truth when Beads is available. +- Do not use `bd edit`; it opens an interactive editor. Use `bd update` flags instead. +- Prefer `--json` when parsing `bd` output programmatically. +- If hooks are installed, `bd prime` may already be injected. Run it manually when context is missing. +- Do not auto-close or mutate tasks unless the work is actually complete. diff --git a/.agents/skills/beads/agents/openai.yaml b/.agents/skills/beads/agents/openai.yaml new file mode 100644 index 0000000..09c3b8f --- /dev/null +++ b/.agents/skills/beads/agents/openai.yaml @@ -0,0 +1,4 @@ +interface: + display_name: "Beads" + short_description: "Project task tracking with bd" + default_prompt: "Use $beads to inspect ready work and manage durable project tasks." diff --git a/.agents/skills/code-review/SKILL.md b/.agents/skills/code-review/SKILL.md new file mode 100644 index 0000000..83183e0 --- /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. Start every sub-agent with a fresh context window. + +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..aebdc9f --- /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 with a fresh context window. 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/handoff/SKILL.md b/.agents/skills/handoff/SKILL.md new file mode 100644 index 0000000..a224edc --- /dev/null +++ b/.agents/skills/handoff/SKILL.md @@ -0,0 +1,16 @@ +--- +name: handoff +description: Compact the current conversation into a handoff document for another agent to pick up. +argument-hint: "What will the next session be used for?" +disable-model-invocation: true +--- + +Write a handoff document summarising the current conversation so a fresh agent can continue the work. Save to the temporary directory of the user's OS (`$TMPDIR`, else `/tmp`; `%TEMP%` on Windows) - not the current workspace. + +Include a "suggested skills" section in the document, naming which skills the next agent should call the Skill tool for. + +Do not duplicate content already captured in other artifacts (specs, plans, ADRs, issues, commits, diffs). Reference them by path or URL instead. + +Redact any sensitive information, such as API keys, passwords, or personally identifiable information. + +If the user passed arguments, treat them as a description of what the next session will focus on and tailor the doc accordingly. diff --git a/.agents/skills/handoff/agents/openai.yaml b/.agents/skills/handoff/agents/openai.yaml new file mode 100644 index 0000000..6e1d8da --- /dev/null +++ b/.agents/skills/handoff/agents/openai.yaml @@ -0,0 +1,5 @@ +interface: + display_name: "Handoff" + short_description: "Compact a conversation into a handoff" +policy: + allow_implicit_invocation: false 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..f1eabb5 --- /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 with a fresh context window 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/pr/CREDITS.md b/.agents/skills/pr/CREDITS.md new file mode 100644 index 0000000..5314bda --- /dev/null +++ b/.agents/skills/pr/CREDITS.md @@ -0,0 +1,3 @@ +# Credits + +The **Summary** section's menu of visuals (pseudocode, call trees, component trees, file trees, Mermaid, diffs) and its placement guidance come from [Dex Horthy](https://github.com/dexhorthy)'s [`show-me`](https://github.com/humanlayer/humanlayer) skill, reproduced almost word for word and aimed at a diff instead of a live conversation. `pr` does not depend on `show-me` as a skill (it isn't part of this repo, and a hard dependency would break standalone installs), so the content is copied in rather than pointed at; this file is the attribution a dependency would otherwise have carried. diff --git a/.agents/skills/pr/SKILL.md b/.agents/skills/pr/SKILL.md new file mode 100644 index 0000000..84dd4fb --- /dev/null +++ b/.agents/skills/pr/SKILL.md @@ -0,0 +1,170 @@ +--- +name: pr +description: "Use when writing a PR body." +metadata: + credits: + skill: show-me + author: Dex Horthy + organisation: Humanlayer + url: "https://github.com/humanlayer/skills/blob/main/plugins/show-me/skills/show-me/SKILL.md" +--- + +Use this template for writing the PR body: + +```markdown +## Summary + + + +## Evidence + +- **Before:** + **After:** + +## Merge Danger + +**Door:** + + + +**Blast Radius:** + + +``` + +## Sections + +Skip all preambles and keep prose brief. Use the user's domain language from `GLOSSARY.md`. + +### Summary + +Pick the smallest view that makes the key point clear. + +- Show logic or an algorithm as pseudocode: + +```text +on(save) + if content is unchanged + return cached result + write new content + return fresh result +``` + +- Show runtime control flow as a call tree: + +```text +submitForm + createSession + persistPrompt + launchAgent + navigateToSession +``` + +- Show UI structure as a component tree, including state and module boundaries that matter: + +```text + (apps/example/src/routes/session.tsx) + useSessionEvents() + + (packages/ui) +``` + +- Show file responsibility or a broad refactor as a shallow file tree: + +```text +src/ +├── commands/ # parses user actions +├── sessions/ # owns session state +└── transport/ # sends API requests +``` + +- Show component interaction, control flow, or data flow with Mermaid: + +```mermaid +sequenceDiagram + participant User + participant UI + participant Daemon + User->>UI: choose command + UI->>Daemon: send expanded prompt + Daemon-->>UI: stream result +``` + +- Use `diff` when the point is what changes and the surrounding shape already exists. Match the diff shape to the topic. + +For a component change: + +```diff + + useSessionEvents() + ++ + ++ +``` + +For a file-layout change: + +```diff + src/ + ├── commands/ ++│ └── show-me.ts # expands the slash command + ├── sessions/ +-└── transport.ts ++└── transport/ ++ ├── client.ts ++ └── stream.ts +``` + +For a call-tree or call-stack change: + +```diff + submitForm + createSession + persistPrompt ++ expandSkillMention + launchAgent +- navigateToSession ++ navigateToSession ++ subscribeToEvents +``` + +For a state or control-flow change: + +```diff + on(save) +- write content ++ if content is unchanged ++ return cached result ++ write new content ++ invalidate cache +``` + +- Show the whole block when most of it is new, when omitted context would hide ownership or order, or when the user needs a copyable target shape: + +```ts +function expandSkill(command: string): string { + const skillName = command.slice(1); + return `use the ${skillName} skill`; +} +``` + +#### Guidance + +Place each visual next to the short text it supports. Keep only the calls, files, props, states, and boundaries needed to answer the user's current question or the options to resolve the current discussion point. + +You may use one of these, you may use several, it is unlikely you will use all of them. Use your judgement and don't overwhelm the user. + +### Evidence + +Concrete evidence that the change works. Show a before and after. + +Screenshots are S-tier - when the environment is set up for it and the change is visual. + +Execution-based evidence is A-tier. Test results, console output. Show the exact test that now fails and passes, using pseudocode. + +### Merge Danger + +Describe whether it's a one-way or two-way door. You can walk back through two-way doors, but not one-way doors. A PR that is cheap to roll back is lower risk. Changes that involve destructive actions or hard-to-reverse decisions are one-way doors. + +The blast radius is the potential impact or scope of the changes introduced by this PR. Consider all possibilities. Examples are layout shift, breakages for consumers, mobile responsiveness, etc. diff --git a/.agents/skills/pr/agents/openai.yaml b/.agents/skills/pr/agents/openai.yaml new file mode 100644 index 0000000..48286f4 --- /dev/null +++ b/.agents/skills/pr/agents/openai.yaml @@ -0,0 +1,3 @@ +interface: + display_name: "PR" + short_description: "Write a PR body that's fast to review" 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/.beads/.gitignore b/.beads/.gitignore new file mode 100644 index 0000000..1ce0e03 --- /dev/null +++ b/.beads/.gitignore @@ -0,0 +1,82 @@ +# Dolt database (managed by Dolt, not git) +dolt/ +embeddeddolt/ +proxieddb/ + +# Runtime files +bd.sock +bd.sock.startlock +sync-state.json +last-touched +.exclusive-lock + +# Daemon runtime (lock, log, pid) +daemon.* + +# Push state (runtime, per-machine) +push-state.json + +# Lock files (various runtime locks) +*.lock + +# Credential key (encryption key for federation peer auth — never commit) +.beads-credential-key + +# Local version tracking (prevents upgrade notification spam after git ops) +.local_version + +proxied_server_client_info.json + +# Worktree redirect file (contains relative path to main repo's .beads/) +# Must not be committed as paths would be wrong in other clones +redirect + +# Sync state (local-only, per-machine) +# These files are machine-specific and should not be shared across clones +.sync.lock + +# Workspace operation gate (internal/workspacegate): physical-root gate +# files live beside the guarded root inside .beads (e.g. dolt.gate.lock) +*.gate.lock* +export-state/ +export-state.json +last_pull + +# Ephemeral store (SQLite - wisps/molecules, intentionally not versioned) +ephemeral.sqlite3 +ephemeral.sqlite3-journal +ephemeral.sqlite3-wal +ephemeral.sqlite3-shm + +# Dolt server management (auto-started by bd) +dolt-server.pid +dolt-server.log +dolt-server.lock +dolt-server.port +dolt-server.activity +dolt-server-config.yaml + +# Debug-mode pprof artifacts (written when dolt.debug: true in config.yaml) +dolt-pprof/ + +# Corrupt backup directories (created by bd doctor --fix recovery) +*.corrupt.backup/ + +# Backup data (auto-exported JSONL, local-only) +backup/ + +# Per-project environment file (Dolt connection config, GH#2520) +.env + +# Legacy files (from pre-Dolt versions) +*.db +*.db?* +*.db-journal +*.db-wal +*.db-shm +db.sqlite +bd.db +# NOTE: Do NOT add negation patterns here. +# They would override fork protection in .git/info/exclude. +# Config files (metadata.json, config.yaml) are tracked by git by default +# since no pattern above ignores them. diff --git a/.beads/README.md b/.beads/README.md new file mode 100644 index 0000000..63e8f4c --- /dev/null +++ b/.beads/README.md @@ -0,0 +1,81 @@ +# Beads - AI-Native Issue Tracking + +Welcome to Beads! This repository uses **Beads** for issue tracking - a modern, AI-native tool designed to live directly in your codebase alongside your code. + +## What is Beads? + +Beads is issue tracking that lives in your repo, making it perfect for AI coding agents and developers who want their issues close to their code. No web UI required - everything works through the CLI and integrates seamlessly with git. + +**Learn more:** [github.com/steveyegge/beads](https://github.com/steveyegge/beads) + +## Quick Start + +### Essential Commands + +```bash +# Create new issues +bd create "Add user authentication" + +# View all issues +bd list + +# View issue details +bd show + +# Update issue status +bd update --claim +bd update --status done + +# Sync with Dolt remote +bd dolt push +``` + +### Working with Issues + +Issues in Beads are: +- **Git-native**: Stored in Dolt database with version control and branching +- **AI-friendly**: CLI-first design works perfectly with AI coding agents +- **Branch-aware**: Issues can follow your branch workflow +- **Sync-ready**: Uses Dolt remotes for backup and team sharing + +## Why Beads? + +✨ **AI-Native Design** +- Built specifically for AI-assisted development workflows +- CLI-first interface works seamlessly with AI coding agents +- No context switching to web UIs + +🚀 **Developer Focused** +- Issues live in your repo, right next to your code +- Works offline, syncs when you push +- Fast, lightweight, and stays out of your way + +🔧 **Git Integration** +- Dolt-native sync via bd dolt push / bd dolt pull +- Branch-aware issue tracking +- Dolt-native three-way merge resolution + +## Get Started with Beads + +Try Beads in your own projects: + +```bash +# Install Beads +curl -sSL https://raw.githubusercontent.com/steveyegge/beads/main/scripts/install.sh | bash + +# Initialize in your repo +bd init + +# Create your first issue +bd create "Try out Beads" +``` + +## Learn More + +- **Documentation**: [github.com/steveyegge/beads/docs](https://github.com/steveyegge/beads/tree/main/docs) +- **Quick Start Guide**: Run `bd quickstart` +- **Examples**: [github.com/steveyegge/beads/examples](https://github.com/steveyegge/beads/tree/main/examples) + +--- + +*Beads: Issue tracking that moves at the speed of thought* ⚡ diff --git a/.beads/config.yaml b/.beads/config.yaml new file mode 100644 index 0000000..689935e --- /dev/null +++ b/.beads/config.yaml @@ -0,0 +1,77 @@ +# Beads Configuration File +# This file configures default behavior for all bd commands in this repository +# All settings can also be set via environment variables (BD_* prefix) +# or overridden with command-line flags + +# Issue prefix for this repository (used by bd init) +# If not set, bd init will auto-detect from directory name +# Example: issue-prefix: "myproject" creates issues like "myproject-1", "myproject-2", etc. +# issue-prefix: "" + +# Use no-db mode: JSONL-only, no Dolt database +# When true, .beads/issues.jsonl is the only local store +# no-db: false + +# Enable JSON output by default +# json: false + +# Feedback title formatting for mutating commands (create/update/close/dep/edit) +# 0 = hide titles, N > 0 = truncate to N characters +# output: +# title-length: 255 + +# Default actor for audit trails (overridden by BEADS_ACTOR or --actor) +# actor: "" + +# Optional JSONL sidecar for explicit agent/tool interaction audit records. +# Issue history is always recorded in the database and is visible with +# bd history --events; this only controls .beads/interactions.jsonl. +# audit: +# enabled: false + +# Export events (audit trail) to .beads/events.jsonl on each flush/sync +# When enabled, new events are appended incrementally using a high-water mark. +# Use 'bd export --events' to trigger manually regardless of this setting. +# events-export: false + +# Multi-repo configuration (experimental - bd-307) +# Allows hydrating from multiple repositories and routing writes to the correct database +# repos: +# primary: "." # Primary repo (where this database lives) +# additional: # Additional repos to hydrate from (read-only) +# - ~/beads-planning # Personal planning repo +# - ~/work-planning # Work planning repo + +# Dolt-native backup (periodic backup for off-machine recovery) +# This is full database backup only. Cross-machine sync uses Dolt remotes. +# backup: +# enabled: false # Disable auto-backup entirely +# interval: 15m # Minimum time between auto-backups +# git-push: false # Disable git push (backup locally only) +# git-repo: "" # Separate git repo for backups (default: project repo) + +# Optional JSONL auto-export for viewers, interchange, and issue-level migration. +# Disabled by default; enable only when an integration needs fresh .beads/issues.jsonl. +# Use relative paths under .beads/ for JSONL import/export filenames. +# export: +# auto: false +# path: issues.jsonl +# interval: 60s +# git-add: false +# import: +# path: issues.jsonl + +# Integration settings (access with 'bd config get/set') +# Non-secret keys (stored in the database): +# - jira.url, jira.project +# - linear.team_id +# - github.org, github.repo +# +# Secret keys (stored in this file but prefer env vars to avoid git exposure): +# - linear.api_key → use LINEAR_API_KEY env var instead +# - github.token → use GITHUB_TOKEN env var instead + +sync: + remote: "git+ssh://git@github.com/killallgit/herdr-scope.git" +export: + auto: true diff --git a/.beads/hooks/post-checkout b/.beads/hooks/post-checkout new file mode 100755 index 0000000..9d53a6f --- /dev/null +++ b/.beads/hooks/post-checkout @@ -0,0 +1,59 @@ +#!/usr/bin/env sh +# --- BEGIN BEADS INTEGRATION v1.3.2 --- +# This section is managed by beads. Do not remove these markers. +if command -v bd >/dev/null 2>&1; then + export BD_GIT_HOOK=1 + _bd_timeout=${BEADS_HOOK_TIMEOUT:-300} + case "$_bd_timeout" in + *[!0-9]*|'') _bd_timeout_invalid=1 ;; + *[1-9]*) _bd_timeout_invalid=0 ;; + *) _bd_timeout_invalid=1 ;; + esac + if [ "$_bd_timeout_invalid" -eq 1 ]; then + echo >&2 "beads: invalid BEADS_HOOK_TIMEOUT; using 300 seconds" + _bd_timeout=300 + fi + _bd_timeout_backend=none + _bd_timeout_command= + for _bd_timeout_candidate in timeout gtimeout; do + if command -v "$_bd_timeout_candidate" >/dev/null 2>&1; then + if _bd_timeout_version="$("$_bd_timeout_candidate" --version 2>/dev/null)"; then + case "$_bd_timeout_version" in + "timeout (GNU coreutils) "*) _bd_timeout_command=$_bd_timeout_candidate; break ;; + esac + fi + fi + done + if [ -n "$_bd_timeout_command" ]; then + _bd_timeout_backend=coreutils + if "$_bd_timeout_command" -- "$_bd_timeout" bd hooks run post-checkout "$@"; then + _bd_exit=0 + else + _bd_exit=$? + fi + elif command -v perl >/dev/null 2>&1; then + _bd_timeout_backend=perl + if perl -e 'alarm shift; exec @ARGV' -- "$_bd_timeout" bd hooks run post-checkout "$@"; then + _bd_exit=0 + else + _bd_exit=$? + fi + else + echo >&2 "beads: hook 'post-checkout' running without timeout; install coreutils or perl to enable BEADS_HOOK_TIMEOUT" + if bd hooks run post-checkout "$@"; then + _bd_exit=0 + else + _bd_exit=$? + fi + fi + if { [ "$_bd_timeout_backend" = coreutils ] && [ "$_bd_exit" -eq 124 ]; } || { [ "$_bd_timeout_backend" = perl ] && [ "$_bd_exit" -eq 142 ]; }; then + echo >&2 "beads: hook 'post-checkout' timed out after ${_bd_timeout}s — continuing without beads" + _bd_exit=0 + fi + if [ "$_bd_exit" -eq 3 ]; then + echo >&2 "beads: database not initialized — skipping hook 'post-checkout'" + _bd_exit=0 + fi + if [ "$_bd_exit" -ne 0 ]; then exit "$_bd_exit"; fi +fi +# --- END BEADS INTEGRATION v1.3.2 --- diff --git a/.beads/hooks/post-merge b/.beads/hooks/post-merge new file mode 100755 index 0000000..63f2260 --- /dev/null +++ b/.beads/hooks/post-merge @@ -0,0 +1,59 @@ +#!/usr/bin/env sh +# --- BEGIN BEADS INTEGRATION v1.3.2 --- +# This section is managed by beads. Do not remove these markers. +if command -v bd >/dev/null 2>&1; then + export BD_GIT_HOOK=1 + _bd_timeout=${BEADS_HOOK_TIMEOUT:-300} + case "$_bd_timeout" in + *[!0-9]*|'') _bd_timeout_invalid=1 ;; + *[1-9]*) _bd_timeout_invalid=0 ;; + *) _bd_timeout_invalid=1 ;; + esac + if [ "$_bd_timeout_invalid" -eq 1 ]; then + echo >&2 "beads: invalid BEADS_HOOK_TIMEOUT; using 300 seconds" + _bd_timeout=300 + fi + _bd_timeout_backend=none + _bd_timeout_command= + for _bd_timeout_candidate in timeout gtimeout; do + if command -v "$_bd_timeout_candidate" >/dev/null 2>&1; then + if _bd_timeout_version="$("$_bd_timeout_candidate" --version 2>/dev/null)"; then + case "$_bd_timeout_version" in + "timeout (GNU coreutils) "*) _bd_timeout_command=$_bd_timeout_candidate; break ;; + esac + fi + fi + done + if [ -n "$_bd_timeout_command" ]; then + _bd_timeout_backend=coreutils + if "$_bd_timeout_command" -- "$_bd_timeout" bd hooks run post-merge "$@"; then + _bd_exit=0 + else + _bd_exit=$? + fi + elif command -v perl >/dev/null 2>&1; then + _bd_timeout_backend=perl + if perl -e 'alarm shift; exec @ARGV' -- "$_bd_timeout" bd hooks run post-merge "$@"; then + _bd_exit=0 + else + _bd_exit=$? + fi + else + echo >&2 "beads: hook 'post-merge' running without timeout; install coreutils or perl to enable BEADS_HOOK_TIMEOUT" + if bd hooks run post-merge "$@"; then + _bd_exit=0 + else + _bd_exit=$? + fi + fi + if { [ "$_bd_timeout_backend" = coreutils ] && [ "$_bd_exit" -eq 124 ]; } || { [ "$_bd_timeout_backend" = perl ] && [ "$_bd_exit" -eq 142 ]; }; then + echo >&2 "beads: hook 'post-merge' timed out after ${_bd_timeout}s — continuing without beads" + _bd_exit=0 + fi + if [ "$_bd_exit" -eq 3 ]; then + echo >&2 "beads: database not initialized — skipping hook 'post-merge'" + _bd_exit=0 + fi + if [ "$_bd_exit" -ne 0 ]; then exit "$_bd_exit"; fi +fi +# --- END BEADS INTEGRATION v1.3.2 --- diff --git a/.beads/hooks/pre-commit b/.beads/hooks/pre-commit new file mode 100755 index 0000000..0928485 --- /dev/null +++ b/.beads/hooks/pre-commit @@ -0,0 +1,59 @@ +#!/usr/bin/env sh +# --- BEGIN BEADS INTEGRATION v1.3.2 --- +# This section is managed by beads. Do not remove these markers. +if command -v bd >/dev/null 2>&1; then + export BD_GIT_HOOK=1 + _bd_timeout=${BEADS_HOOK_TIMEOUT:-300} + case "$_bd_timeout" in + *[!0-9]*|'') _bd_timeout_invalid=1 ;; + *[1-9]*) _bd_timeout_invalid=0 ;; + *) _bd_timeout_invalid=1 ;; + esac + if [ "$_bd_timeout_invalid" -eq 1 ]; then + echo >&2 "beads: invalid BEADS_HOOK_TIMEOUT; using 300 seconds" + _bd_timeout=300 + fi + _bd_timeout_backend=none + _bd_timeout_command= + for _bd_timeout_candidate in timeout gtimeout; do + if command -v "$_bd_timeout_candidate" >/dev/null 2>&1; then + if _bd_timeout_version="$("$_bd_timeout_candidate" --version 2>/dev/null)"; then + case "$_bd_timeout_version" in + "timeout (GNU coreutils) "*) _bd_timeout_command=$_bd_timeout_candidate; break ;; + esac + fi + fi + done + if [ -n "$_bd_timeout_command" ]; then + _bd_timeout_backend=coreutils + if "$_bd_timeout_command" -- "$_bd_timeout" bd hooks run pre-commit "$@"; then + _bd_exit=0 + else + _bd_exit=$? + fi + elif command -v perl >/dev/null 2>&1; then + _bd_timeout_backend=perl + if perl -e 'alarm shift; exec @ARGV' -- "$_bd_timeout" bd hooks run pre-commit "$@"; then + _bd_exit=0 + else + _bd_exit=$? + fi + else + echo >&2 "beads: hook 'pre-commit' running without timeout; install coreutils or perl to enable BEADS_HOOK_TIMEOUT" + if bd hooks run pre-commit "$@"; then + _bd_exit=0 + else + _bd_exit=$? + fi + fi + if { [ "$_bd_timeout_backend" = coreutils ] && [ "$_bd_exit" -eq 124 ]; } || { [ "$_bd_timeout_backend" = perl ] && [ "$_bd_exit" -eq 142 ]; }; then + echo >&2 "beads: hook 'pre-commit' timed out after ${_bd_timeout}s — continuing without beads" + _bd_exit=0 + fi + if [ "$_bd_exit" -eq 3 ]; then + echo >&2 "beads: database not initialized — skipping hook 'pre-commit'" + _bd_exit=0 + fi + if [ "$_bd_exit" -ne 0 ]; then exit "$_bd_exit"; fi +fi +# --- END BEADS INTEGRATION v1.3.2 --- diff --git a/.beads/hooks/pre-push b/.beads/hooks/pre-push new file mode 100755 index 0000000..24796d1 --- /dev/null +++ b/.beads/hooks/pre-push @@ -0,0 +1,59 @@ +#!/usr/bin/env sh +# --- BEGIN BEADS INTEGRATION v1.3.2 --- +# This section is managed by beads. Do not remove these markers. +if command -v bd >/dev/null 2>&1; then + export BD_GIT_HOOK=1 + _bd_timeout=${BEADS_HOOK_TIMEOUT:-300} + case "$_bd_timeout" in + *[!0-9]*|'') _bd_timeout_invalid=1 ;; + *[1-9]*) _bd_timeout_invalid=0 ;; + *) _bd_timeout_invalid=1 ;; + esac + if [ "$_bd_timeout_invalid" -eq 1 ]; then + echo >&2 "beads: invalid BEADS_HOOK_TIMEOUT; using 300 seconds" + _bd_timeout=300 + fi + _bd_timeout_backend=none + _bd_timeout_command= + for _bd_timeout_candidate in timeout gtimeout; do + if command -v "$_bd_timeout_candidate" >/dev/null 2>&1; then + if _bd_timeout_version="$("$_bd_timeout_candidate" --version 2>/dev/null)"; then + case "$_bd_timeout_version" in + "timeout (GNU coreutils) "*) _bd_timeout_command=$_bd_timeout_candidate; break ;; + esac + fi + fi + done + if [ -n "$_bd_timeout_command" ]; then + _bd_timeout_backend=coreutils + if "$_bd_timeout_command" -- "$_bd_timeout" bd hooks run pre-push "$@"; then + _bd_exit=0 + else + _bd_exit=$? + fi + elif command -v perl >/dev/null 2>&1; then + _bd_timeout_backend=perl + if perl -e 'alarm shift; exec @ARGV' -- "$_bd_timeout" bd hooks run pre-push "$@"; then + _bd_exit=0 + else + _bd_exit=$? + fi + else + echo >&2 "beads: hook 'pre-push' running without timeout; install coreutils or perl to enable BEADS_HOOK_TIMEOUT" + if bd hooks run pre-push "$@"; then + _bd_exit=0 + else + _bd_exit=$? + fi + fi + if { [ "$_bd_timeout_backend" = coreutils ] && [ "$_bd_exit" -eq 124 ]; } || { [ "$_bd_timeout_backend" = perl ] && [ "$_bd_exit" -eq 142 ]; }; then + echo >&2 "beads: hook 'pre-push' timed out after ${_bd_timeout}s — continuing without beads" + _bd_exit=0 + fi + if [ "$_bd_exit" -eq 3 ]; then + echo >&2 "beads: database not initialized — skipping hook 'pre-push'" + _bd_exit=0 + fi + if [ "$_bd_exit" -ne 0 ]; then exit "$_bd_exit"; fi +fi +# --- END BEADS INTEGRATION v1.3.2 --- diff --git a/.beads/hooks/prepare-commit-msg b/.beads/hooks/prepare-commit-msg new file mode 100755 index 0000000..6c9e95b --- /dev/null +++ b/.beads/hooks/prepare-commit-msg @@ -0,0 +1,59 @@ +#!/usr/bin/env sh +# --- BEGIN BEADS INTEGRATION v1.3.2 --- +# This section is managed by beads. Do not remove these markers. +if command -v bd >/dev/null 2>&1; then + export BD_GIT_HOOK=1 + _bd_timeout=${BEADS_HOOK_TIMEOUT:-300} + case "$_bd_timeout" in + *[!0-9]*|'') _bd_timeout_invalid=1 ;; + *[1-9]*) _bd_timeout_invalid=0 ;; + *) _bd_timeout_invalid=1 ;; + esac + if [ "$_bd_timeout_invalid" -eq 1 ]; then + echo >&2 "beads: invalid BEADS_HOOK_TIMEOUT; using 300 seconds" + _bd_timeout=300 + fi + _bd_timeout_backend=none + _bd_timeout_command= + for _bd_timeout_candidate in timeout gtimeout; do + if command -v "$_bd_timeout_candidate" >/dev/null 2>&1; then + if _bd_timeout_version="$("$_bd_timeout_candidate" --version 2>/dev/null)"; then + case "$_bd_timeout_version" in + "timeout (GNU coreutils) "*) _bd_timeout_command=$_bd_timeout_candidate; break ;; + esac + fi + fi + done + if [ -n "$_bd_timeout_command" ]; then + _bd_timeout_backend=coreutils + if "$_bd_timeout_command" -- "$_bd_timeout" bd hooks run prepare-commit-msg "$@"; then + _bd_exit=0 + else + _bd_exit=$? + fi + elif command -v perl >/dev/null 2>&1; then + _bd_timeout_backend=perl + if perl -e 'alarm shift; exec @ARGV' -- "$_bd_timeout" bd hooks run prepare-commit-msg "$@"; then + _bd_exit=0 + else + _bd_exit=$? + fi + else + echo >&2 "beads: hook 'prepare-commit-msg' running without timeout; install coreutils or perl to enable BEADS_HOOK_TIMEOUT" + if bd hooks run prepare-commit-msg "$@"; then + _bd_exit=0 + else + _bd_exit=$? + fi + fi + if { [ "$_bd_timeout_backend" = coreutils ] && [ "$_bd_exit" -eq 124 ]; } || { [ "$_bd_timeout_backend" = perl ] && [ "$_bd_exit" -eq 142 ]; }; then + echo >&2 "beads: hook 'prepare-commit-msg' timed out after ${_bd_timeout}s — continuing without beads" + _bd_exit=0 + fi + if [ "$_bd_exit" -eq 3 ]; then + echo >&2 "beads: database not initialized — skipping hook 'prepare-commit-msg'" + _bd_exit=0 + fi + if [ "$_bd_exit" -ne 0 ]; then exit "$_bd_exit"; fi +fi +# --- END BEADS INTEGRATION v1.3.2 --- diff --git a/.beads/metadata.json b/.beads/metadata.json new file mode 100644 index 0000000..db8a5b3 --- /dev/null +++ b/.beads/metadata.json @@ -0,0 +1,7 @@ +{ + "database": "dolt", + "backend": "dolt", + "dolt_mode": "embedded", + "dolt_database": "herdr_scope", + "project_id": "7699d563-883e-4a58-84f7-cf33e30d04ba" +} \ No newline at end of file diff --git a/.claude/settings.json b/.claude/settings.json new file mode 100644 index 0000000..8487f87 --- /dev/null +++ b/.claude/settings.json @@ -0,0 +1,15 @@ +{ + "hooks": { + "SessionStart": [ + { + "hooks": [ + { + "command": "bd prime --hook-json", + "type": "command" + } + ], + "matcher": "" + } + ] + } +} diff --git a/.codex/config.toml b/.codex/config.toml new file mode 100644 index 0000000..146af7e --- /dev/null +++ b/.codex/config.toml @@ -0,0 +1,2 @@ +[features] +hooks = true diff --git a/.codex/hooks.json b/.codex/hooks.json new file mode 100644 index 0000000..13c7229 --- /dev/null +++ b/.codex/hooks.json @@ -0,0 +1,51 @@ +{ + "hooks": { + "PostCompact": [ + { + "hooks": [ + { + "command": "bd codex-hook PostCompact", + "statusMessage": "Scheduling Beads context refresh", + "type": "command" + } + ], + "matcher": "manual|auto" + } + ], + "PreCompact": [ + { + "hooks": [ + { + "command": "bd codex-hook PreCompact", + "statusMessage": "Checking Beads context", + "type": "command" + } + ], + "matcher": "manual|auto" + } + ], + "SessionStart": [ + { + "hooks": [ + { + "command": "bd codex-hook SessionStart", + "statusMessage": "Loading Beads context", + "type": "command" + } + ], + "matcher": "startup|resume|clear" + } + ], + "UserPromptSubmit": [ + { + "hooks": [ + { + "command": "bd codex-hook UserPromptSubmit", + "statusMessage": "Refreshing Beads context", + "type": "command" + } + ] + } + ] + } +} diff --git a/.cursor/hooks.json b/.cursor/hooks.json new file mode 100644 index 0000000..9d731c8 --- /dev/null +++ b/.cursor/hooks.json @@ -0,0 +1,20 @@ +{ + "hooks": { + "postToolUse": [ + { + "command": "bd cursor-hook postToolUse" + } + ], + "preCompact": [ + { + "command": "bd cursor-hook preCompact" + } + ], + "sessionStart": [ + { + "command": "bd cursor-hook sessionStart" + } + ] + }, + "version": 1 +} diff --git a/.cursor/rules/beads.mdc b/.cursor/rules/beads.mdc new file mode 100644 index 0000000..7bfa5bb --- /dev/null +++ b/.cursor/rules/beads.mdc @@ -0,0 +1,67 @@ +--- +alwaysApply: true +--- + + + + +# Beads Issue Tracking + +This project uses [Beads (bd)](https://github.com/gastownhall/beads) for issue tracking. + +## Core Rules + +- Track ALL work in bd (never use markdown TODOs or comment-based task lists) +- Use `bd ready` to find available work +- Use `bd create` to track new issues/tasks/bugs +- Treat commit, push, and Dolt remote sync as policy-controlled handoff actions +- Run `bd prime` for complete workflow context (SSOT for operational commands) +- Default to conservative git authority: report status and proposed commands unless the user, orchestrator, or repository profile explicitly authorizes commit/sync/push + +## Quick Reference + +```bash +bd prime # Load complete workflow context (SSOT) +bd ready # Show issues ready to work (no blockers) +bd list --status=open # List all open issues +bd create "title" -t task -p 2 # Create new issue +bd update --claim # Claim work atomically +bd unclaim # Release stuck issue (agent crashed) +bd close # Mark complete +bd dep add # Add dependency +bd dolt push # Sync with remote when authorized +``` + +## Workflow + +1. Check for ready work: `bd ready` +2. Claim an issue atomically: `bd update --claim` +3. Do the work +4. Mark complete: `bd close ` +5. Handoff: report changed files, validation, issue status, and any proposed commit/sync/push commands + +## Issue Types + +- `bug` - Something broken +- `feature` - New functionality +- `task` - Work item (tests, docs, refactoring) +- `epic` - Large feature with subtasks +- `chore` - Maintenance (dependencies, tooling) + +## Priorities + +- `0` - Critical (security, data loss, broken builds) +- `1` - High (major features, important bugs) +- `2` - Medium (default, nice-to-have) +- `3` - Low (polish, optimization) +- `4` - Backlog (future ideas) + +## Context Loading + +Run `bd prime` to get complete workflow documentation in AI-optimized format. +`bd prime` is the single source of truth for operational commands and session workflow. + +For detailed docs: see AGENTS.md, the beads quickstart +(https://github.com/gastownhall/beads/blob/main/docs/getting-started/quickstart.md), or run `bd --help` + + diff --git a/.gitignore b/.gitignore index 65c5910..3f980aa 100644 --- a/.gitignore +++ b/.gitignore @@ -7,3 +7,10 @@ coverage.html /build/ /vendor/ /_article/ + +# Beads / Dolt files (added by bd init) +.dolt/ +*.db +.beads-credential-key +.beads/proxieddb/ +*.gate.lock* diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..cf2ac15 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,128 @@ +# Agent Instructions + +This project uses **bd** (beads) for issue tracking. Run `bd prime` for full workflow context. + +> **Architecture in one line:** Issues live in a local Dolt database +> (`.beads/dolt/`); cross-machine sync uses `bd dolt push/pull` (a +> git-compatible protocol), stored under `refs/dolt/data` on your git +> remote — separate from `refs/heads/*` where your code lives. +> `.beads/issues.jsonl` is a passive export, not the wire protocol. +> +> See [sync-concepts](https://github.com/gastownhall/beads/blob/main/docs/core-concepts/sync-concepts.md) +> for the one-screen overview and anti-patterns (don't treat JSONL as the +> source of truth; don't `bd import` during normal operation; don't +> reach for third-party Dolt hosting before trying the default). + +## Quick Reference + +```bash +bd ready # Find available work +bd show # View issue details +bd update --claim # Claim work atomically +bd close # Complete work +bd dolt push # Push beads data to remote +``` + +## Non-Interactive Shell Commands + +**ALWAYS use non-interactive flags** with file operations to avoid hanging on confirmation prompts. + +Shell commands like `cp`, `mv`, and `rm` may be aliased to include `-i` (interactive) mode on some systems, causing the agent to hang indefinitely waiting for y/n input. + +**Use these forms instead:** +```bash +# Force overwrite without prompting +cp -f source dest # NOT: cp source dest +mv -f source dest # NOT: mv source dest +rm -f file # NOT: rm file + +# For recursive operations +rm -rf directory # NOT: rm -r directory +cp -rf source dest # NOT: cp -r source dest +``` + +**Other commands that may prompt:** +- `scp` - use `-o BatchMode=yes` for non-interactive +- `ssh` - use `-o BatchMode=yes` to fail instead of prompting +- `apt-get` - use `-y` flag +- `brew` - use `HOMEBREW_NO_AUTO_UPDATE=1` env var + + +## Beads Issue Tracker + +This project uses **bd (beads)** for issue tracking. Run `bd prime` to see full workflow context and commands. + +### Quick Reference + +```bash +bd ready # Find available work +bd show # View issue details +bd update --claim # Claim work +bd close # Complete work +``` + +### Rules + +- Use `bd` for ALL task tracking — do NOT use TodoWrite, TaskCreate, or markdown TODO lists +- Run `bd prime` for detailed command reference and session close protocol +- Use `bd remember` for persistent knowledge — do NOT use MEMORY.md files + +**Architecture in one line:** issues live in a local Dolt DB; sync uses `refs/dolt/data` on your git remote; `.beads/issues.jsonl` is a passive export. See https://github.com/gastownhall/beads/blob/main/docs/core-concepts/sync-concepts.md for details and anti-patterns. + +## Agent Context Profiles + +The managed Beads block is task-tracking guidance, not permission to override repository, user, or orchestrator instructions. + +- **Conservative (default)**: Use `bd` for task tracking. Do not run git commits, git pushes, or Dolt remote sync unless explicitly asked. At handoff, report changed files, validation, and suggested next commands. +- **Minimal**: Keep tool instruction files as pointers to `bd prime`; use the same conservative git policy unless active instructions say otherwise. +- **Team-maintainer**: Only when the repository explicitly opts in, agents may close beads, run quality gates, commit, and push as part of session close. A current "do not commit" or "do not push" instruction still wins. + +## Session Completion + +This protocol applies when ending a Beads implementation workflow. It is subordinate to explicit user, repository, and orchestrator instructions. + +1. **File issues for remaining work** - Create beads for anything that needs follow-up +2. **Run quality gates** (if code changed) - Tests, linters, builds +3. **Update issue status** - Close finished work, update in-progress items +4. **Handle git/sync by active profile**: + ```bash + # Conservative/minimal/default: report status and proposed commands; wait for approval. + git status + + # Team-maintainer opt-in only, unless current instructions forbid it: + git pull --rebase + bd dolt push + git push + git status + ``` +5. **Hand off** - Summarize changes, validation, issue status, and any blocked sync/commit/push step + +**Critical rules:** +- Explicit user or orchestrator instructions override this Beads block. +- Do not commit or push without clear authority from the active profile or the current user request. +- If a required sync or push is blocked, stop and report the exact command and error. + + + +## Beads Issue Tracker + +Use Beads (`bd`) for durable task tracking in repositories that include it. Use the `beads` skill at `.agents/skills/beads/SKILL.md` (project install) or `~/.agents/skills/beads/SKILL.md` (global install) for Beads workflow guidance, then use the `bd` CLI for issue operations. + +### Quick Reference + +```bash +bd ready # Find available work +bd show # View issue details +bd update --claim # Claim work +bd close # Complete work +bd prime # Refresh Beads context +``` + +### Rules + +- Use `bd` for all task tracking; do not create markdown TODO lists. +- Run `bd prime` when Beads context is missing or stale. Codex 0.129.0+ can load Beads context automatically through native hooks; use `/hooks` to inspect or toggle them. +- Keep persistent project memory in Beads via `bd remember`; do not create ad hoc memory files. + +**Architecture in one line:** issues live in a local Dolt DB; sync uses `refs/dolt/data` on your git remote; `.beads/issues.jsonl` is a passive export. See https://github.com/gastownhall/beads/blob/main/docs/core-concepts/sync-concepts.md for details and anti-patterns. + diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..b6674ae --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,77 @@ +# Project Instructions for AI Agents + +This file provides instructions and context for AI coding agents working on this project. + + +## Beads Issue Tracker + +This project uses **bd (beads)** for issue tracking. Run `bd prime` to see full workflow context and commands. + +### Quick Reference + +```bash +bd ready # Find available work +bd show # View issue details +bd update --claim # Claim work +bd close # Complete work +``` + +### Rules + +- Use `bd` for ALL task tracking — do NOT use TodoWrite, TaskCreate, or markdown TODO lists +- Run `bd prime` for detailed command reference and session close protocol +- Use `bd remember` for persistent knowledge — do NOT use MEMORY.md files + +**Architecture in one line:** issues live in a local Dolt DB; sync uses `refs/dolt/data` on your git remote; `.beads/issues.jsonl` is a passive export. See https://github.com/gastownhall/beads/blob/main/docs/core-concepts/sync-concepts.md for details and anti-patterns. + +## Agent Context Profiles + +The managed Beads block is task-tracking guidance, not permission to override repository, user, or orchestrator instructions. + +- **Conservative (default)**: Use `bd` for task tracking. Do not run git commits, git pushes, or Dolt remote sync unless explicitly asked. At handoff, report changed files, validation, and suggested next commands. +- **Minimal**: Keep tool instruction files as pointers to `bd prime`; use the same conservative git policy unless active instructions say otherwise. +- **Team-maintainer**: Only when the repository explicitly opts in, agents may close beads, run quality gates, commit, and push as part of session close. A current "do not commit" or "do not push" instruction still wins. + +## Session Completion + +This protocol applies when ending a Beads implementation workflow. It is subordinate to explicit user, repository, and orchestrator instructions. + +1. **File issues for remaining work** - Create beads for anything that needs follow-up +2. **Run quality gates** (if code changed) - Tests, linters, builds +3. **Update issue status** - Close finished work, update in-progress items +4. **Handle git/sync by active profile**: + ```bash + # Conservative/minimal/default: report status and proposed commands; wait for approval. + git status + + # Team-maintainer opt-in only, unless current instructions forbid it: + git pull --rebase + git push + git status + ``` +5. **Hand off** - Summarize changes, validation, issue status, and any blocked sync/commit/push step + +**Critical rules:** +- Explicit user or orchestrator instructions override this Beads block. +- Do not commit or push without clear authority from the active profile or the current user request. +- If a required sync or push is blocked, stop and report the exact command and error. + + + +## Build & Test + +_Add your build and test commands here_ + +```bash +# Example: +# npm install +# npm test +``` + +## Architecture Overview + +_Add a brief overview of your project architecture_ + +## Conventions & Patterns + +_Add your project-specific conventions here_ From eec4a40e2749f7b2aaa09baef9e12c0eec69efcb Mon Sep 17 00:00:00 2001 From: archae0pteryx Date: Sat, 7 Nov 2026 15:07:55 -0800 Subject: [PATCH 2/2] refactor: deepen sidebar presentation and gate releases with CI --- .gitattributes | 2 + .github/dependabot.yml | 19 ++ .github/workflows/ci.yml | 186 ++++++++++++++---- .github/workflows/release.yml | 42 ++-- .golangci-lint-version | 1 + .golangci.yaml | 2 +- GLOSSARY.md | 23 +++ Makefile | 81 ++++++-- README.md | 16 +- docs/architecture.md | 12 ++ docs/ci.md | 109 ++++++++++ docs/design.md | 3 +- go.mod | 2 +- herdr-plugin.toml | 8 +- internal/adapters/appearance/probe.go | 3 +- internal/adapters/config/plugin.go | 2 +- internal/adapters/herdr/client.go | 3 +- internal/adapters/scenario/scenario.go | 24 ++- internal/adapters/scenario/scenario_test.go | 82 ++++++++ internal/adapters/sidebar/glyphs.go | 2 - internal/adapters/sidebar/palette.go | 2 - internal/adapters/sidebar/projection.go | 55 ++++++ internal/adapters/sidebar/projection_test.go | 74 +++++++ internal/adapters/sidebar/tokens.go | 2 +- internal/adapters/sidebar/writer.go | 47 ++--- internal/adapters/sidebar/writer_test.go | 31 +++ internal/domain/catalog.go | 2 - scripts/build.cmd | 8 +- scripts/build.sh | 8 +- tests/contract/herdr_test.go | 2 +- tests/fixtures/scenarios/scenario-10.json | 62 ++++++ tests/golden/golden_test.go | 14 ++ tests/golden/scenario-10.classic.tokens.txt | 12 ++ tests/golden/scenario-10.classic.txt | 12 ++ .../scenario-10.classic.visit.tokens.txt | 15 ++ tests/golden/scenario-10.classic.visit.txt | 15 ++ tests/golden/scenario-10.tokens.txt | 10 + tests/golden/scenario-10.txt | 10 + tests/golden/scenario-10.visit.tokens.txt | 13 ++ tests/golden/scenario-10.visit.txt | 13 ++ tests/integration/herdr_test.go | 42 ++-- tools/go.mod | 35 ++++ tools/go.sum | 61 ++++++ 43 files changed, 1010 insertions(+), 157 deletions(-) create mode 100644 .github/dependabot.yml create mode 100644 .golangci-lint-version create mode 100644 GLOSSARY.md create mode 100644 docs/ci.md create mode 100644 internal/adapters/scenario/scenario_test.go create mode 100644 internal/adapters/sidebar/projection.go create mode 100644 internal/adapters/sidebar/projection_test.go create mode 100644 tests/fixtures/scenarios/scenario-10.json create mode 100644 tests/golden/scenario-10.classic.tokens.txt create mode 100644 tests/golden/scenario-10.classic.txt create mode 100644 tests/golden/scenario-10.classic.visit.tokens.txt create mode 100644 tests/golden/scenario-10.classic.visit.txt create mode 100644 tests/golden/scenario-10.tokens.txt create mode 100644 tests/golden/scenario-10.txt create mode 100644 tests/golden/scenario-10.visit.tokens.txt create mode 100644 tests/golden/scenario-10.visit.txt create mode 100644 tools/go.mod create mode 100644 tools/go.sum diff --git a/.gitattributes b/.gitattributes index 26fc915..ff09e44 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,3 +1,5 @@ +* text=auto eol=lf + # cmd.exe parses batch files with LF line endings unreliably; check them out # with CRLF everywhere, and keep the POSIX build script LF. *.cmd text eol=crlf diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..f5d04af --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,19 @@ +version: 2 +updates: + - package-ecosystem: gomod + directories: + - / + - /tools + schedule: + interval: weekly + groups: + go-dependencies: + patterns: ['*'] + update-types: [minor, patch] + - package-ecosystem: github-actions + directory: / + schedule: + interval: weekly + groups: + github-actions: + patterns: ['*'] diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 29118a0..2c1b9c9 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -5,69 +5,150 @@ on: branches: [ master ] pull_request: branches: [ master ] + merge_group: + workflow_call: + workflow_dispatch: + schedule: + - cron: '23 6 * * 1' permissions: contents: read +env: + GOTOOLCHAIN: local + +concurrency: + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.run_id }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +defaults: + run: + shell: bash + jobs: test: - name: Test (race) + name: Test (Linux, ${{ matrix.go || 'module Go' }}) runs-on: ubuntu-latest + timeout-minutes: 20 + strategy: + fail-fast: false + matrix: + go: [ '', stable ] + env: + CGO_ENABLED: '1' steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false - - name: Set up Go - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 + - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 with: + go-version: ${{ matrix.go }} go-version-file: go.mod - - name: Run tests - run: go test -race -count=1 ./... + cache-dependency-path: | + go.sum + tools/go.sum + - name: Race tests and coverage + run: make coverage + - name: Coverage summary + run: tail -n 1 build/reports/coverage.txt >> "$GITHUB_STEP_SUMMARY" + - name: Save test reports + if: always() + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: tests-linux-${{ matrix.go || 'module' }} + path: build/reports + retention-days: 7 - lint: - # Like `make lint`: the code has unix and windows variants, so lint each - # platform the plugin ships for. - name: Lint (${{ matrix.goos }}) + analysis: + name: Analysis (${{ matrix.goos }}) runs-on: ubuntu-latest + timeout-minutes: 15 strategy: fail-fast: false matrix: - goos: [ linux, darwin, windows ] + goos: [ linux, darwin ] steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false - - name: Set up Go - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 + - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 with: go-version-file: go.mod - - name: Run golangci-lint + cache-dependency-path: | + go.sum + tools/go.sum + - name: Lint uses: golangci/golangci-lint-action@ba0d7d2ec06a0ea1cb5fa41b2e4a3ab91d21278a # v9.3.0 env: GOOS: ${{ matrix.goos }} with: - # Keep in step with the golangci-lint `make lint` runs locally. - version: v2.12.2 - args: --config .golangci.yaml + version-file: .golangci-lint-version + args: --config .golangci.yaml ./... + - name: Vulnerability analysis + env: + TARGET_GOOS: ${{ matrix.goos }} + run: make vuln + + verify: + name: Format, modules, workflows + runs-on: ubuntu-latest + timeout-minutes: 15 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 + with: + go-version-file: go.mod + cache-dependency-path: | + go.sum + tools/go.sum + - run: make fmt-check modules workflows + + integration: + name: Live integration (Herdr 0.9.5) + runs-on: ubuntu-latest + timeout-minutes: 15 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 + with: + go-version-file: go.mod + cache-dependency-path: | + go.sum + tools/go.sum + - name: Install the tested Herdr release + run: | + curl -fL --retry 3 https://github.com/herdrdev/herdr/releases/download/v0.9.5/herdr-linux-x86_64 -o "$RUNNER_TEMP/herdr" + echo "14d9e8bc8b4a9e0118d77c32266f76d461f09b40342eb23752960bd89f59929d $RUNNER_TEMP/herdr" | sha256sum --check + chmod 755 "$RUNNER_TEMP/herdr" + - name: Run isolated integration tests + env: + HERDR_SCOPE_HERDR: ${{ runner.temp }}/herdr + run: make integration + - name: Save integration reports + if: always() + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: integration + path: build/reports + retention-days: 7 dist: - # A broken cross-compile shows up here, not when a release tag is pushed. - name: Cross-compile + name: Cross-compile and install runs-on: ubuntu-latest + timeout-minutes: 15 steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false - - name: Set up Go - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 + - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 with: go-version-file: go.mod - name: Build the release binaries run: make dist - # Every path of the install build step: a release tree's prebuilt binary, - # a source tree with no binaries, and one whose Go fails (the runner has - # a system Go to hide), which downloads the release of its version once - # that release exists. - name: Check the install step run: | shellcheck scripts/build.sh @@ -85,24 +166,49 @@ jobs: mkdir -p "$RUNNER_TEMP/broken-go" printf '#!/bin/sh\nexit 1\n' > "$RUNNER_TEMP/broken-go/go" chmod 755 "$RUNNER_TEMP/broken-go/go" - if curl -fsIL -o /dev/null "https://github.com/$GITHUB_REPOSITORY/releases/download/v$version/SHA256SUMS"; then - env PATH="$RUNNER_TEMP/broken-go:$PATH" sh scripts/build.sh | tee build/install.log - grep -q "installed the v$version release binary" build/install.log - bin/herdr-scope version - else - echo "v$version is not released yet: the download path is checked once it is" - fi - # A Go-less install pairs this checkout's manifest with the binary of the - # release of its version, so a released version's manifest stays as - # released: change it, bump the version. Comments may change. + status=$(curl -sSIL --retry 3 --max-time 30 --retry-max-time 120 -o /dev/null -w '%{http_code}' \ + "https://github.com/$GITHUB_REPOSITORY/releases/download/v$version/SHA256SUMS") + case "$status" in + 200) + env PATH="$RUNNER_TEMP/broken-go:$PATH" sh scripts/build.sh | tee build/install.log + grep -q "installed the v$version release binary" build/install.log + bin/herdr-scope version + ;; + 404) echo "v$version is not released yet: the download path is checked once it is" ;; + *) echo "::error::Release lookup returned HTTP $status"; exit 1 ;; + esac - name: Check the manifest against its release run: | version=$(sed -n 's/^version = "\(.*\)"$/\1/p' herdr-plugin.toml | head -n 1) - if git ls-remote --exit-code --tags origin "refs/tags/v$version" >/dev/null; then - git fetch --quiet --depth=1 origin "refs/tags/v$version:refs/tags/v$version" - strip() { grep -v -E '^[[:space:]]*(#|$)'; } - if ! diff <(git show "v$version:herdr-plugin.toml" | strip) <(strip < herdr-plugin.toml); then - echo "::error file=herdr-plugin.toml::the manifest changed since v$version, whose binary a Go-less install downloads: bump the version" + status=0 + git ls-remote --exit-code --tags origin "refs/tags/v$version" >/dev/null || status=$? + case "$status" in + 0) + git fetch --quiet --depth=1 origin "refs/tags/v$version:refs/tags/v$version" + strip() { grep -v -E '^[[:space:]]*(#|$)'; } + if ! diff <(git show "v$version:herdr-plugin.toml" | strip) <(strip < herdr-plugin.toml); then + echo "::error file=herdr-plugin.toml::the manifest changed since v$version, whose binary a Go-less install downloads: bump the version" + exit 1 + fi + ;; + 2) echo "v$version has no release tag yet" ;; + *) echo "::error::Release tag lookup failed with status $status"; exit "$status" ;; + esac + + check: + name: CI passed + if: always() + needs: [ test, analysis, verify, integration, dist ] + runs-on: ubuntu-latest + timeout-minutes: 1 + steps: + - name: Require every gate to pass + env: + RESULTS: ${{ join(needs.*.result, ' ') }} + run: | + for result in $RESULTS; do + if [ "$result" != success ]; then + echo "::error::A required job ended with $result" exit 1 fi - fi + done diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index cbe5260..81e7366 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -4,7 +4,7 @@ name: Release # - a GitHub release with per-platform archives (binary, LICENSE, # THIRD_PARTY_NOTICES.md) and SHA256SUMS; # - the installable tree: one orphan commit holding the tagged source plus -# the prebuilt binaries at bin/herdr-scope--[.exe], force-pushed +# the prebuilt binaries at bin/herdr-scope--, force-pushed # to the `release` branch and tagged vX.Y.Z-bin, so that # `herdr plugin install --ref release` (or --ref vX.Y.Z-bin) needs # no Go toolchain. A pre-release tag (vX.Y.Z-rc.1) gets its -bin tag but @@ -22,10 +22,19 @@ on: permissions: contents: read +env: + GOTOOLCHAIN: local + jobs: + quality: + name: Quality gates + uses: ./.github/workflows/ci.yml + build: name: Build + needs: quality runs-on: ubuntu-latest + timeout-minutes: 15 outputs: version: ${{ steps.version.outputs.version }} prerelease: ${{ steps.version.outputs.prerelease }} @@ -33,6 +42,7 @@ jobs: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false + fetch-depth: 0 - name: Set up Go uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 with: @@ -70,15 +80,20 @@ jobs: echo "prerelease=$prerelease" >> "$GITHUB_OUTPUT" echo "Releasing $version (pre-release: $prerelease)" - - name: Test - run: go test -count=1 ./... + - name: Require stable release tags to come from master + if: github.event_name == 'push' && steps.version.outputs.prerelease == 'false' + run: | + if ! git merge-base --is-ancestor "$GITHUB_SHA" origin/master; then + echo "::error::Stable release tags must point to a commit on master" + exit 1 + fi - name: Build the binaries env: VERSION: ${{ steps.version.outputs.version }} run: | make dist VERSION="$VERSION" - test "$(find build/bin -type f | wc -l)" -eq 6 + test "$(find build/bin -type f | wc -l)" -eq 3 build/bin/herdr-scope-linux-amd64 version | grep -F "herdr-scope $VERSION " - name: Package the archives @@ -88,23 +103,15 @@ jobs: rm -rf build/pkg build/release mkdir -p build/pkg build/release for bin in build/bin/herdr-scope-*; do - platform=$(basename "$bin" .exe) + platform=$(basename "$bin") platform=${platform#herdr-scope-} dir=herdr-scope-$VERSION-$platform mkdir "build/pkg/$dir" cp LICENSE THIRD_PARTY_NOTICES.md "build/pkg/$dir/" - case "$platform" in - windows-*) - cp "$bin" "build/pkg/$dir/herdr-scope.exe" - (cd build/pkg && zip -qrX "../release/$dir.zip" "$dir") - ;; - *) - install -m 755 "$bin" "build/pkg/$dir/herdr-scope" - tar -C build/pkg -czf "build/release/$dir.tar.gz" "$dir" - ;; - esac + install -m 755 "$bin" "build/pkg/$dir/herdr-scope" + tar -C build/pkg -czf "build/release/$dir.tar.gz" "$dir" done - (cd build/release && sha256sum -- *.tar.gz *.zip > SHA256SUMS && cat SHA256SUMS) + (cd build/release && sha256sum -- *.tar.gz > SHA256SUMS && cat SHA256SUMS) - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: @@ -117,6 +124,7 @@ jobs: publish: name: Publish + timeout-minutes: 10 if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v') needs: build runs-on: ubuntu-latest @@ -180,7 +188,7 @@ jobs: herdr plugin install $GITHUB_REPOSITORY --ref $TAG-bin - Use --ref release instead to install the latest release. Without --ref, Herdr checks out the default branch: the install step builds it from source when Go 1.26 or newer is on PATH, and otherwise downloads this release's binary and checks it against SHA256SUMS. + Use --ref release instead to install the latest release. Without --ref, Herdr checks out the default branch: the install step builds it from source using the Go toolchain declared in go.mod, and otherwise downloads this release's binary and checks it against SHA256SUMS. The archives hold the same binaries with LICENSE and THIRD_PARTY_NOTICES.md; SHA256SUMS lists their checksums. EOF diff --git a/.golangci-lint-version b/.golangci-lint-version new file mode 100644 index 0000000..f855fc0 --- /dev/null +++ b/.golangci-lint-version @@ -0,0 +1 @@ +v2.15.0 diff --git a/.golangci.yaml b/.golangci.yaml index 95980dc..32f2ef9 100644 --- a/.golangci.yaml +++ b/.golangci.yaml @@ -223,7 +223,7 @@ linters: # Default: [ switch ] check: - switch - - map + - mapliteral exhaustruct: # List of regular expressions to match type names that should be excluded from processing. diff --git a/GLOSSARY.md b/GLOSSARY.md new file mode 100644 index 0000000..78c0b22 --- /dev/null +++ b/GLOSSARY.md @@ -0,0 +1,23 @@ +# Herdr Scope + +Scope presents agents in the Agents panel and workspaces in Spaces. + +## Language + +**Workspace**: +A Herdr workspace, shown as a Space, containing tabs and panes. + +**Family**: +A workspace and the workspaces nested beneath it by repository or folder. A family remains one group even when its parent runs no agent. + +**Fold**: +A remembered choice to condense a family's agents while keeping questions, unseen results, focused agents, agents in the focused workspace, and a lone agent visible. + +**Fold line**: +The condensed summary of a family: its name, hidden-agent count, and activity. + +**Carrier**: +The agent whose place in the Agents panel carries a fold line. When the line replaces that agent's own row, focusing the carrier opens the family for a visit. + +**Visit**: +A temporary opening of a folded family that lasts until focus leaves the family; the remembered fold remains. diff --git a/Makefile b/Makefile index 2828bf5..db688b4 100644 --- a/Makefile +++ b/Makefile @@ -1,12 +1,17 @@ -# make dist: the release binaries, cross-compiled into build/bin (not dist/, -# which holds the bundled fonts, and not bin/, which the install step reads). -# The release workflow passes VERSION=; a local build describes -# the checkout, or keeps internal/bootstrap's Version when there is no tag. +SHELL := bash + DIST_DIR := build/bin -DIST_PLATFORMS := darwin/amd64 darwin/arm64 linux/amd64 linux/arm64 windows/amd64 windows/arm64 +DIST_PLATFORMS := darwin/amd64 darwin/arm64 linux/amd64 VERSION ?= $(shell git describe --tags --dirty 2>/dev/null | sed 's/^v//') +TARGET_GOOS ?= $(shell go env GOOS) +GOEXE := $(shell go env GOEXE) +GOLANGCI_LINT := build/tools/golangci-lint$(GOEXE) +GOVULNCHECK := build/tools/govulncheck$(GOEXE) +GO_TOOL := go tool -modfile=tools/go.mod +TEST_PACKAGES := ./cmd/... ./internal/... ./tests/unit ./tests/contract ./tests/golden +TEST_REPORTS := --junitfile build/reports/tests.xml --jsonfile build/reports/tests.json -.PHONY: build dist test race lint golden tidy +.PHONY: build dist tools test race coverage integration lint fmt fmt-check modules workflows vuln check golden tidy build: go build -trimpath -o bin/herdr-scope ./cmd/herdr-scope @@ -15,27 +20,73 @@ dist: rm -rf $(DIST_DIR) mkdir -p $(DIST_DIR) for p in $(DIST_PLATFORMS); do \ - os=$${p%/*}; arch=$${p#*/}; ext=; \ - if [ $$os = windows ]; then ext=.exe; fi; \ - out=$(DIST_DIR)/herdr-scope-$$os-$$arch$$ext; \ + os=$${p%/*}; arch=$${p#*/}; \ + out=$(DIST_DIR)/herdr-scope-$$os-$$arch; \ echo "$$out"; \ CGO_ENABLED=0 GOOS=$$os GOARCH=$$arch go build -trimpath \ -ldflags "-s -w -X main.version=$(VERSION)" -o $$out ./cmd/herdr-scope || exit 1; \ done +tools: $(GOLANGCI_LINT) $(GOVULNCHECK) + $(GO_TOOL) gotestsum --version + $(GO_TOOL) actionlint -version + +$(GOLANGCI_LINT): .golangci-lint-version + mkdir -p build/tools + curl -fsSL --retry 3 https://raw.githubusercontent.com/golangci/golangci-lint/25c5369a93aacb8cccea0d46e1569ca4a194564d/install.sh -o build/tools/install-golangci-lint.sh + sh build/tools/install-golangci-lint.sh -b build/tools "$$(tr -d '\r\n' < .golangci-lint-version)" + +$(GOVULNCHECK): tools/go.mod tools/go.sum + mkdir -p build/tools + go -C tools build -o ../$(GOVULNCHECK) golang.org/x/vuln/cmd/govulncheck + test: - go test -count=1 ./... + mkdir -p build/reports + $(GO_TOOL) gotestsum $(TEST_REPORTS) -- -count=1 -timeout=5m $(TEST_PACKAGES) race: - go test -race -count=1 ./... + mkdir -p build/reports + $(GO_TOOL) gotestsum $(TEST_REPORTS) -- -race -count=1 -timeout=5m $(TEST_PACKAGES) + +coverage: + mkdir -p build/reports + $(GO_TOOL) gotestsum $(TEST_REPORTS) -- -race -count=1 -timeout=5m \ + -covermode=atomic -coverpkg=./... -coverprofile=build/reports/coverage.out $(TEST_PACKAGES) + go tool cover -func=build/reports/coverage.out > build/reports/coverage.txt + tail -n 1 build/reports/coverage.txt + +integration: + mkdir -p build/reports + HERDR_SCOPE_INTEGRATION=1 $(GO_TOOL) gotestsum \ + --junitfile build/reports/integration.xml --jsonfile build/reports/integration.json \ + -- -race -count=1 -timeout=5m ./tests/integration + +lint: $(GOLANGCI_LINT) + GOOS=$(TARGET_GOOS) $(GOLANGCI_LINT) run --config .golangci.yaml ./... + +fmt: $(GOLANGCI_LINT) + $(GOLANGCI_LINT) fmt --config .golangci.yaml + +fmt-check: $(GOLANGCI_LINT) + @diff=$$($(GOLANGCI_LINT) fmt --config .golangci.yaml --diff) && test -z "$$diff" || { printf '%s\n' "$$diff"; exit 1; } + +modules: + go mod tidy -diff + go mod verify + go -C tools mod tidy -diff + go -C tools mod verify + +workflows: + $(GO_TOOL) actionlint + +vuln: $(GOVULNCHECK) + GOOS=$(TARGET_GOOS) $(GOVULNCHECK) ./... -lint: - golangci-lint run --config .golangci.yaml ./... - GOOS=windows golangci-lint run --config .golangci.yaml ./... +check: fmt-check modules workflows lint vuln coverage -# Rewrite tests/golden after an intended change to the look. golden: go test ./tests/golden -update -count=1 tidy: go mod tidy + go -C tools mod tidy diff --git a/README.md b/README.md index c15d427..ad7c8e1 100644 --- a/README.md +++ b/README.md @@ -58,8 +58,8 @@ for this fork's development. The original MIT copyright and license remain in herdr plugin install killallgit/herdr-scope --ref release ``` -The `release` branch carries prebuilt binaries for macOS, Linux and Windows once -published for this fork. Without `--ref`, Herdr builds from source with Go 1.26+. Without Go, it downloads the release binary and checks its checksum. Setup +The `release` branch carries prebuilt binaries for macOS (amd64/arm64) and Linux (amd64) once +published for this fork. Without `--ref`, Herdr builds from source using the Go version declared in [`go.mod`](go.mod). Without Go, it downloads the release binary and checks its checksum. Setup adds Scope's blocks to Herdr's `config.toml` between `HERDR-SCOPE` markers and installs the icon font for your user. It requires Herdr 0.9+ (protocol 22). @@ -145,19 +145,21 @@ statuses, never prompts or titles. Like any Herdr plugin, Scope runs as you, uns ```sh make build # bin/herdr-scope; the next state-start restarts the daemon on it -make race # unit, contract and golden tests -make lint # golangci-lint for darwin and windows +make check # pinned formatting, modules, workflows, lint, security and race/coverage gates +make race # offline unit, architecture, contract and golden tests +make lint # pinned golangci-lint for the host platform make golden # rewrite tests/golden after an intended change to the look ``` From a checkout: `make build && herdr plugin link .` (`plugin link` runs no build step). [Architecture](docs/architecture.md), [Herdr protocol notes](docs/protocol.md), -[design decisions](docs/design.md). `docs/demo/record.sh` re-records the GIF. +[design decisions](docs/design.md), [CI and test tooling](docs/ci.md). +`docs/demo/record.sh` re-records the GIF. ### Release verification -Run a non-publishing release rehearsal on the branch to test and package all six -platform binaries: +Run a non-publishing release rehearsal on the branch to run the full CI suite +and package all three platform binaries: ```sh gh workflow run release.yml --ref diff --git a/docs/architecture.md b/docs/architecture.md index ba8f401..4b236d8 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -1,5 +1,7 @@ # Architecture +Domain terms are defined in [GLOSSARY.md](../GLOSSARY.md). + Scope observes Herdr and paints the sidebar. It writes only its own display tokens, the Agents panel's view, a waiting tab's mark, the workspace order (`reorder_workspaces`, `nest_folders`), its managed blocks in Herdr's `config.toml`, and files in its own @@ -75,6 +77,16 @@ socket disappears. | `tui` | the settings popup | | `scenario` | replays recorded Herdr payloads through the pipeline for the golden tests and `render` | +`Presentation.Project` is a pure transformation from a sidebar view to pane and Spaces +tokens, restoration titles, and the next visible repaint. The writer adapter owns delivery, +diffs, retries, and cleanup; it does not interpret folds. Hidden carrier titles contribute +no repaint deadline, while the fold line's spinner and visible Spaces pulses still do. + +Scenario replay supplies folded roots and each step's focused workspace, reusing +`FollowVisits` and `BuildSidebar` to exercise fold visits through the same domain rules. +Its short observation sequence remains separate from the observer's I/O recovery and +cached-frame scheduling. + `internal/bootstrap` builds every adapter once per process and injects functions where one adapter needs another's behaviour. diff --git a/docs/ci.md b/docs/ci.md new file mode 100644 index 0000000..6d4b774 --- /dev/null +++ b/docs/ci.md @@ -0,0 +1,109 @@ +# Quality gates + +## Tooling + +Tests use Go's native `testing` package and the existing Testify assertions. +[gotestsum](https://github.com/gotestyourself/gotestsum) runs those tests unchanged, +prints failures and skips, and writes JUnit XML and Go test JSON. Failed tests are +not automatically retried. + +[golangci-lint v2](https://golangci-lint.run/docs/welcome/install/) provides static +analysis, including govet, Staticcheck, gosec, and Testify checks. Its version is +pinned in `.golangci-lint-version`. Make installs the official release binary with +its checksum-verifying installer, pinned to an upstream commit. It does not use +a globally installed linter or build a potentially different dependency graph. +CI uses the official golangci-lint action for caching and annotations, reading +the same version file and configuration. + +[govulncheck](https://go.dev/doc/tutorial/govulncheck) checks reachable vulnerable +functions in the application and its dependencies, including the Go standard +library. Findings fail the gate; they are not suppressed for an old compiler. + +[actionlint](https://github.com/rhysd/actionlint) checks workflow syntax, +expressions, and embedded shell commands through ShellCheck when available. +CI's Ubuntu runner includes ShellCheck. + +The Go tools are pinned with native `tool` directives in `tools/go.mod`, isolated +from the application's dependency graph. `go.mod` selects the supported Go +patch version; the tools module follows it. Dependency and action updates are +proposed weekly by Dependabot. Update the linter's version file deliberately +and run the gates before accepting a new linter release. + +## Local commands + +Go, Make, Bash, and curl are required on Linux or macOS. Race tests also need +a C compiler. + +```sh +make tools # prepare pinned tools; no global installs +make test # offline unit, architecture, contract, and golden tests +make race # the same tests with the race detector +make coverage # race tests, JUnit/JSON reports, and atomic coverage +make lint # lint the host platform +make vuln # scan the host platform for reachable vulnerabilities +make check # formatting, module consistency, workflows, lint, security, coverage +make dist # Linux amd64 and macOS amd64/arm64 release binaries +``` + +`make check` needs network access for missing tools/modules and the vulnerability +database. Reports are written under `build/reports`, which is ignored by Git. +Coverage is reported rather than gated on an arbitrary percentage. + +Run platform-specific analysis without cross-compiling the analysis tools: + +```sh +make lint vuln TARGET_GOOS=linux +make lint vuln TARGET_GOOS=darwin +``` + +Live integration is separate from the offline suite. On Linux or macOS, with +Herdr 0.9.5 installed: + +```sh +HERDR_SCOPE_HERDR=/absolute/path/to/herdr make integration +``` + +The test uses a private short-lived HOME, XDG directories, socket, and server; +it never attaches to the user's session. Plugin processes are race-instrumented; +private race reports and shutdown failures fail the test, including cleanup. +An explicitly requested integration run fails if Herdr is unavailable. CI downloads the tested Linux release and +verifies its pinned SHA256 before running it. + +Use `make fmt` to apply the configured formatters, `make tidy` to update module +files, and `make golden` only for intended visual changes. The corresponding CI +checks do not rewrite source, module files, or expected output. + +## GitHub Actions + +`.github/workflows/ci.yml` runs on master pushes, pull requests, merge queues, +manual dispatch, and a weekly schedule. It is also reusable by the release +workflow. It provides: + +- Native race tests and coverage on Linux only, with the module's Go version + and the latest stable Go. CI disables automatic + toolchain switching so each run really uses its selected compiler. +- Lint and source vulnerability analysis for Linux and macOS. +- Formatting, module tidy/verification, and workflow validation. +- A real, isolated Herdr 0.9.5 integration run on Linux. +- Release cross-compilation for Linux amd64 and macOS amd64/arm64, plus the + existing installer checks. +- JUnit, JSON, and coverage artifacts, retained even when tests fail. + +`CI passed` depends on every gate and fails if any gate fails, is cancelled, or +is skipped. Configure the master branch ruleset to require this status; workflow +files alone cannot enforce merge protection. The repository had no active +branch protection or rulesets at the time of this audit. No repository settings +are changed by this checkout. + +Release builds and non-publishing release rehearsals call the same CI workflow +before packaging. Stable release tags must point to commits on master; +pre-release tags and non-publishing rehearsals may use a development branch. +Publishing still requires a version tag and happens in a separate write-enabled job. A test-only Ubuntu run can no longer bypass the +lint, race, security, and integration gates. + +CI tests run on Linux only; macOS is cross-built for releases without native +macOS test jobs. Linux arm64 is not a release target. + +Windows is excluded from automated platform testing, analysis, and releases. +Existing Windows source and legacy installer code are retained, but no Windows +binaries or ZIP archives are produced. diff --git a/docs/design.md b/docs/design.md index 8bf0cdf..da8874c 100644 --- a/docs/design.md +++ b/docs/design.md @@ -93,8 +93,7 @@ session. ## Not verified -- Windows builds and lints but has not been run. Whether Herdr's launcher resolves - `bin/herdr-scope` to `.exe` is unconfirmed. +- Windows source is retained, but Windows is excluded from platform CI and releases. - Linux is unit-tested by faking the OS, not run on a host. - The settings popup's raw-terminal handling is covered by its state-machine tests only. - Kilo activity needs `sqlite3` on PATH; without it, Kilo panes read as plain idle. diff --git a/go.mod b/go.mod index 88072c1..41b76fc 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module github.com/killallgit/herdr-scope -go 1.26.5 +go 1.26.10 require ( github.com/BurntSushi/toml v1.5.0 diff --git a/herdr-plugin.toml b/herdr-plugin.toml index 118afdf..ef7e362 100644 --- a/herdr-plugin.toml +++ b/herdr-plugin.toml @@ -12,11 +12,11 @@ platforms = ["linux", "macos", "windows"] # - Release install, no Go needed: `herdr plugin install # killallgit/herdr-scope --ref release` (or `--ref vX.Y.Z-bin` to pin a # version) checks out the tree the release workflow publishes: the tagged -# source plus prebuilt bin/herdr-scope--[.exe] for macOS, Linux -# and Windows on amd64 and arm64. The step copies this machine's binary. +# source plus prebuilt bin/herdr-scope-- for macOS (amd64/arm64) +# and Linux (amd64). The step copies this machine's binary. # - Source install (the default branch, as the plugin catalog installs it, -# or any source tag) with Go 1.26+ on PATH: the step runs `go build`, -# which fetches the modules. +# or any source tag) with a compatible Go toolchain on PATH: the step +# runs `go build` with the toolchain and modules declared in go.mod. # - Source install without Go, or when that build fails: the step downloads # the archive of this manifest's version from the GitHub release and # checks it against the release's SHA256SUMS. diff --git a/internal/adapters/appearance/probe.go b/internal/adapters/appearance/probe.go index dd28d9e..aa9892f 100644 --- a/internal/adapters/appearance/probe.go +++ b/internal/adapters/appearance/probe.go @@ -102,8 +102,7 @@ func (p *Probe) probe(ctx context.Context) ports.Appearance { // ExecRunner runs probes as real processes. func ExecRunner(ctx context.Context, name string, args ...string) (string, int, error) { out, err := exec.CommandContext(ctx, name, args...).Output() - var exit *exec.ExitError - if errors.As(err, &exit) { + if exit, ok := errors.AsType[*exec.ExitError](err); ok { return string(out), exit.ExitCode(), nil } if err != nil { diff --git a/internal/adapters/config/plugin.go b/internal/adapters/config/plugin.go index 3b31063..0f3ebf7 100644 --- a/internal/adapters/config/plugin.go +++ b/internal/adapters/config/plugin.go @@ -356,7 +356,7 @@ func (p *parser) presentation(pres *ports.PresentationSettings) { } } glyphs := table(p.raw, "glyphs") - pres.Glyphs = map[domain.DisplayState]string{} + pres.Glyphs = make(map[domain.DisplayState]string) for name, v := range glyphs { state, known := domain.ParseDisplayState(name) glyph, isString := v.(string) diff --git a/internal/adapters/herdr/client.go b/internal/adapters/herdr/client.go index 73374c3..b117421 100644 --- a/internal/adapters/herdr/client.go +++ b/internal/adapters/herdr/client.go @@ -79,8 +79,7 @@ func (c *Client) call(ctx context.Context, method string, params, out any) error // itself and wraps a decode failure with %w, so a result of the wrong shape // still reads as a decode error. func classify(method string, err error) error { - var apiErr *herdrapi.APIError - if errors.As(err, &apiErr) { + if apiErr, ok := errors.AsType[*herdrapi.APIError](err); ok { return &APIError{Method: method, Code: apiErr.Code, Message: apiErr.Message} } var syntax *json.SyntaxError diff --git a/internal/adapters/scenario/scenario.go b/internal/adapters/scenario/scenario.go index 7fae302..0f479d7 100644 --- a/internal/adapters/scenario/scenario.go +++ b/internal/adapters/scenario/scenario.go @@ -46,13 +46,16 @@ type Scenario struct { Panes []json.RawMessage `json:"panes,omitempty"` // Activity seeds when panes last worked, as offsets from Start ("-30m"). Activity map[string]string `json:"activity"` - Steps []Step `json:"steps"` + // Folded names family roots, not individual workspaces to hide. + Folded []domain.WorkspaceID `json:"folded,omitempty"` + Steps []Step `json:"steps"` } // Step is one frame: the agent list at a moment. type Step struct { - At string `json:"at"` - Agents []map[string]json.RawMessage `json:"agents"` + At string `json:"at"` + Focused domain.WorkspaceID `json:"focused_workspace_id,omitempty"` + Agents []map[string]json.RawMessage `json:"agents"` } // Load reads a scenario file. @@ -136,6 +139,9 @@ type replay struct { host *storeHost writer *sidebar.Writer memory *domain.Memory + folded map[domain.WorkspaceID]bool + opened map[domain.WorkspaceID]bool + focused domain.WorkspaceID now time.Time live []domain.PaneID result Result @@ -159,7 +165,10 @@ func Run(s Scenario) (Result, error) { r := &replay{ s: s, settings: settings, mode: mode, hostGrouped: s.HostGrouped == nil || *s.HostGrouped, mapper: herdr.Mapper{Home: Home, Showing: sidebar.ReadBack}, - memory: domain.NewMemory(nil), now: s.Start, + memory: domain.NewMemory(nil), now: s.Start, folded: map[domain.WorkspaceID]bool{}, + } + for _, root := range s.Folded { + r.folded[root] = true } r.host = &storeHost{panes: sidebar.Store{}, workspaces: sidebar.Store{}, paneIDs: func() []domain.PaneID { return r.live }} r.writer = sidebar.NewWriter(r.host, presentation, func() time.Time { return r.now }) @@ -196,6 +205,11 @@ func (r *replay) step(index int, step Step) error { for _, a := range session.Agents { r.live = append(r.live, a.Pane) } + if session.FocusedWorkspace != "" { + r.focused = session.FocusedWorkspace + } + tree := domain.ResolveTree(session.Workspaces, r.settings.Policy.NestFolders, session.Home) + r.opened = domain.FollowVisits(r.opened, r.result.View, session.Agents, r.focused, tree) r.memory.Track(session.Agents) if index == 0 { if err = seed(r.memory, r.s, session.Agents); err != nil { @@ -212,6 +226,7 @@ func (r *replay) step(index int, step Step) error { r.result.View = domain.BuildSidebar(domain.SidebarInput{ At: r.now, Mode: r.mode, HostGrouped: r.hostGrouped, Policy: r.settings.Policy, Workspaces: session.Workspaces, Tabs: session.Tabs, Home: session.Home, Agents: observed, + Folded: r.folded, Focused: r.focused, Opened: r.opened, Tree: &tree, }) _, err = r.writer.Apply(context.Background(), r.result.View) return err //nolint:wrapcheck // the caller names the step @@ -237,6 +252,7 @@ func decodeStep(mapper herdr.Mapper, s Scenario, step Step, store sidebar.Store) raw, err := json.Marshal(map[string]any{"snapshot": map[string]any{ "version": "scenario", "protocol": 22, "workspaces": s.Workspaces, "tabs": s.Tabs, "panes": s.Panes, "agents": agents, + "focused_workspace_id": step.Focused, }}) if err != nil { return domain.Session{}, fmt.Errorf("snapshot: %w", err) diff --git a/internal/adapters/scenario/scenario_test.go b/internal/adapters/scenario/scenario_test.go new file mode 100644 index 0000000..358c1d8 --- /dev/null +++ b/internal/adapters/scenario/scenario_test.go @@ -0,0 +1,82 @@ +package scenario_test + +import ( + "encoding/json" + "path/filepath" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/killallgit/herdr-scope/internal/adapters/scenario" + "github.com/killallgit/herdr-scope/internal/domain" + "github.com/killallgit/herdr-scope/internal/ports" +) + +func TestReplayKeepsFocusWhenAStepOmitsIt(t *testing.T) { + s, err := scenario.Load(filepath.Join("..", "..", "..", "tests", "fixtures", "scenarios", "scenario-10.json")) + require.NoError(t, err) + s.Steps = s.Steps[:3] + s.Steps[2].Focused = "" + for _, agent := range s.Steps[2].Agents { + agent["focused"] = json.RawMessage("false") + } + + result, err := scenario.Run(s) + + require.NoError(t, err) + assert.Empty(t, result.View.Folded, "the visit stays open at the last known focus") + assert.Contains(t, result.Panes["w1:p1"]["fold"], "▾ acme") +} + +func TestReplayFollowsFoldVisits(t *testing.T) { + for _, layout := range []ports.Layout{ports.LayoutClassic, ports.LayoutCompact} { + for _, tc := range []struct { + name string + steps int + open bool + hidden int + }{ + {name: "folded", steps: 1, hidden: 2}, + {name: "carrier focused", steps: 2, open: true}, + {name: "sibling focused", steps: 3, open: true}, + {name: "focus left", steps: 4, hidden: 2}, + } { + t.Run(string(layout)+"/"+tc.name, func(t *testing.T) { + s, err := scenario.Load(filepath.Join("..", "..", "..", "tests", "fixtures", "scenarios", "scenario-10.json")) + require.NoError(t, err) + s.Layout, s.Steps = layout, s.Steps[:tc.steps] + + result, err := scenario.Run(s) + + require.NoError(t, err) + var folds []*domain.Fold + for _, group := range result.View.Groups { + for _, row := range group.Rows { + if row.Fold != nil { + folds = append(folds, row.Fold) + } + } + } + require.Len(t, folds, 2) + assert.Equal(t, domain.WorkspaceID("w1"), folds[0].Root) + assert.Equal(t, tc.open, folds[0].Open) + assert.Equal(t, tc.hidden, folds[0].Hidden) + assert.Equal(t, !tc.open, folds[0].Alone) + assert.Equal(t, domain.WorkspaceID("w3"), folds[1].Root) + assert.False(t, folds[1].Alone, "a lone agent keeps its own row") + assert.NotEmpty(t, result.Panes["w3:p1"]["title_idle_fresh"]) + if tc.open { + assert.Empty(t, result.View.Folded) + assert.NotContains(t, result.Panes["w2:p1"], "folded") + assert.Contains(t, result.Panes["w1:p1"]["fold"], "▾ acme") + } else { + require.Len(t, result.View.Folded, 1) + assert.Equal(t, domain.PaneID("w2:p1"), result.View.Folded[0].Pane) + assert.Equal(t, "1", result.Panes["w2:p1"]["folded"]) + assert.NotContains(t, result.Panes["w1:p1"], "title_idle_fresh") + } + }) + } + } +} diff --git a/internal/adapters/sidebar/glyphs.go b/internal/adapters/sidebar/glyphs.go index 8a7e0e7..0031914 100644 --- a/internal/adapters/sidebar/glyphs.go +++ b/internal/adapters/sidebar/glyphs.go @@ -21,8 +21,6 @@ type vendorGlyphs struct { } // vendorTable is every vendor's mark: its icon-font codepoint and its text form. -// -//nolint:goconst // table data: one literal per cell func vendorTable() []vendorGlyphs { return []vendorGlyphs{ {"claude", "\uE1A0", "§"}, {"codex", "\uE1A1", "Λ"}, {"opencode", "\uE1A2", "◇"}, diff --git a/internal/adapters/sidebar/palette.go b/internal/adapters/sidebar/palette.go index 6f6e5de..ccaac47 100644 --- a/internal/adapters/sidebar/palette.go +++ b/internal/adapters/sidebar/palette.go @@ -12,8 +12,6 @@ import ( // brandColor is a vendor's own published hue. Green and red stay out — they // mean done and blocked. A vendor absent here has no hue and draws in ink. -// -//nolint:goconst // table data: one literal per cell func brandColors() []struct { Kind domain.AgentKind Color string diff --git a/internal/adapters/sidebar/projection.go b/internal/adapters/sidebar/projection.go new file mode 100644 index 0000000..86bdb7e --- /dev/null +++ b/internal/adapters/sidebar/projection.go @@ -0,0 +1,55 @@ +package sidebar + +import ( + "strings" + "time" + + "github.com/killallgit/herdr-scope/internal/domain" +) + +type Projection struct { + Panes map[domain.PaneID]PaneProjection + Spaces map[domain.WorkspaceID]Tokens + Next time.Time +} + +type PaneProjection struct { + Agent domain.AgentID + Tokens Tokens + // Restore keeps a carrier's title readable after a plain stop. + Restore Tokens +} + +func (p Presentation) Project(view domain.SidebarView) Projection { + projected := Projection{ + Panes: map[domain.PaneID]PaneProjection{}, + Spaces: map[domain.WorkspaceID]Tokens{}, + Next: p.NextRepaint(view), + } + for _, group := range view.Groups { + for i, row := range group.Rows { + pane := PaneProjection{Agent: row.Agent, Tokens: p.PaneTokens(view, group, i)} + if row.Fold != nil && row.Fold.Alone { + pane.Restore = titles(p.FoldedTokens(view, row)) + } + projected.Panes[row.Pane] = pane + } + } + for _, row := range view.Folded { + projected.Panes[row.Pane] = PaneProjection{Agent: row.Agent, Tokens: p.FoldedTokens(view, row)} + } + for _, space := range view.Spaces { + projected.Spaces[space.Workspace] = p.SpaceTokens(space, view.At) + } + return projected +} + +func titles(tokens Tokens) Tokens { + out := Tokens{} + for name, value := range tokens { + if value != nil && strings.HasPrefix(name, titlePrefix) { + out[name] = value + } + } + return out +} diff --git a/internal/adapters/sidebar/projection_test.go b/internal/adapters/sidebar/projection_test.go new file mode 100644 index 0000000..72d0be7 --- /dev/null +++ b/internal/adapters/sidebar/projection_test.go @@ -0,0 +1,74 @@ +package sidebar + +import ( + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/killallgit/herdr-scope/internal/domain" + "github.com/killallgit/herdr-scope/internal/ports" +) + +func TestProjectionSchedulesVisibleContent(t *testing.T) { + for _, layout := range []ports.Layout{ports.LayoutClassic, ports.LayoutCompact} { + for _, tc := range []struct { + name string + fold *domain.Fold + folded bool + blocked bool + want time.Time + }{ + {name: "hidden carrier age", fold: &domain.Fold{Label: "acme", Hidden: 2, Alone: true}}, + {name: "fold spinner", fold: &domain.Fold{Label: "acme", Hidden: 2, Alone: true, Working: true}, want: at0().Add(150 * time.Millisecond)}, + {name: "lone agent age", fold: &domain.Fold{Label: "acme"}, want: at0().Add(30 * time.Second)}, + {name: "hidden working row", folded: true}, + {name: "Spaces pulse", blocked: true, want: at0().Add(750 * time.Millisecond)}, + } { + t.Run(string(layout)+"/"+tc.name, func(t *testing.T) { + settings := ports.DefaultSettings() + settings.Presentation.Layout = layout + settings.Presentation.Variant = ports.VariantText + settings.Presentation.ShowAge = ports.AgeAll + p := NewPresentation(settings, nil) + row := domain.SidebarRow{ + Pane: "w1:p1", Kind: "claude", Display: domain.DisplayIdle, + Title: "Draft release notes", Since: at0().Add(-90 * time.Second), Fold: tc.fold, + } + view, _ := rowView(row, true) + if tc.folded { + row.Display = domain.DisplayWorking + view.Groups, view.Folded = nil, []domain.SidebarRow{row} + } + if tc.blocked { + view.Groups = nil + view.Spaces = []domain.SpaceView{{Workspace: "w1", Mark: domain.DisplayBlocked, MarkKind: "claude"}} + } + + projected := p.Project(view) + + assert.Equal(t, tc.want, projected.Next) + }) + } + } +} + +func TestPresentationProjectsFoldTokensAndRestoration(t *testing.T) { + p := textPresentation() + view, _, _ := foldedView(domain.Fold{Root: "w1", Label: "acme", Hidden: 2, Working: true, WorkingKind: "claude"}) + view.Spaces = []domain.SpaceView{{Workspace: "w1", Label: "acme", Mark: domain.DisplayWorking, MarkKind: "claude"}} + + projected := p.Project(view) + + require.Len(t, projected.Panes, 3) + assert.Equal(t, "▸ acme", val(t, projected.Panes["w1:p1"].Tokens, "fold")) + assert.Empty(t, val(t, projected.Panes["w1:p1"].Tokens, "title_working")) + assert.Equal(t, "1", val(t, projected.Panes["w3:p1"].Tokens, "folded")) + assert.Equal(t, "○", val(t, projected.Spaces["w1"], "space_working_claude")) + assert.Equal(t, view.At.Add(spinStep), projected.Next) + assert.Equal(t, "⣷ Draft release notes", val(t, projected.Panes["w1:p1"].Restore, "title_working")) + assert.Len(t, projected.Panes["w1:p1"].Restore, 1) + assert.Empty(t, projected.Panes["w2:p1"].Restore) + assert.Empty(t, projected.Panes["w3:p1"].Restore) +} diff --git a/internal/adapters/sidebar/tokens.go b/internal/adapters/sidebar/tokens.go index df12e64..18535b1 100644 --- a/internal/adapters/sidebar/tokens.go +++ b/internal/adapters/sidebar/tokens.go @@ -638,7 +638,7 @@ func (p Presentation) NextRepaint(view domain.SidebarView) time.Time { next := NextAnimation(view) for _, g := range view.Groups { for _, row := range g.Rows { - if row.Since.IsZero() || !p.showsAge(row.Display) { + if (row.Fold != nil && row.Fold.Alone) || row.Since.IsZero() || !p.showsAge(row.Display) { continue } if at := ageChange(view.At, row.Since); next.IsZero() || at.Before(next) { diff --git a/internal/adapters/sidebar/writer.go b/internal/adapters/sidebar/writer.go index a07b2ee..93f18a0 100644 --- a/internal/adapters/sidebar/writer.go +++ b/internal/adapters/sidebar/writer.go @@ -61,9 +61,7 @@ type Writer struct { failed map[string]failure // members fingerprints the row set; a change triggers an orphan sweep. members string - // alone are the titles of rows that show a fold line alone, which a - // plain clear puts back so a stopped daemon leaves them readable. - alone map[domain.PaneID]Tokens + restore map[domain.PaneID]Tokens // tabs are the renames sent that the session read may not show yet. tabs map[domain.TabID]renamed } @@ -85,7 +83,7 @@ func (w *Writer) reset() { w.agents = map[domain.PaneID]domain.AgentID{} w.failed = map[string]failure{} w.members = "" - w.alone = map[domain.PaneID]Tokens{} + w.restore = map[domain.PaneID]Tokens{} w.tabs = map[domain.TabID]renamed{} } @@ -124,28 +122,22 @@ func (w *Writer) Apply(ctx context.Context, view domain.SidebarView) (time.Time, w.mu.Lock() defer w.mu.Unlock() now := w.clock() + projected := w.presentation.Project(view) var jobs []job live := map[domain.PaneID]domain.AgentID{} - alone := map[domain.PaneID]Tokens{} - for _, group := range view.Groups { - for i, row := range group.Rows { - live[row.Pane] = row.Agent - jobs = append(jobs, job{key: paneKey(row.Pane), pane: row.Pane, tokens: w.presentation.PaneTokens(view, group, i)}) - if row.Fold != nil && row.Fold.Alone { - alone[row.Pane] = titles(w.presentation.FoldedTokens(view, row)) - } + w.restore = map[domain.PaneID]Tokens{} + for id, pane := range projected.Panes { + live[id] = pane.Agent + jobs = append(jobs, job{key: paneKey(id), pane: id, tokens: pane.Tokens}) + if len(pane.Restore) > 0 { + w.restore[id] = pane.Restore } } - for _, row := range view.Folded { - live[row.Pane] = row.Agent - jobs = append(jobs, job{key: paneKey(row.Pane), pane: row.Pane, tokens: w.presentation.FoldedTokens(view, row)}) - } - w.alone = alone jobs = append(jobs, w.gonePanes(live)...) liveSpaces := map[domain.WorkspaceID]bool{} - for _, space := range view.Spaces { - liveSpaces[space.Workspace] = true - jobs = append(jobs, job{key: spaceKey(space.Workspace), space: space.Workspace, tokens: w.presentation.SpaceTokens(space, view.At)}) + for id, tokens := range projected.Spaces { + liveSpaces[id] = true + jobs = append(jobs, job{key: spaceKey(id), space: id, tokens: tokens}) } jobs = append(jobs, w.goneSpaces(liveSpaces)...) @@ -158,7 +150,7 @@ func (w *Writer) Apply(ctx context.Context, view domain.SidebarView) (time.Time, w.members = fingerprint } } - next := w.presentation.NextRepaint(view) + next := projected.Next if retry := w.nextRetry(now, jobs, view.Tabs); !retry.IsZero() && (next.IsZero() || retry.Before(next)) { next = retry } @@ -376,7 +368,7 @@ func (w *Writer) Clear(ctx context.Context, purge bool) error { } errs := []error{w.sweep(ctx, nil, names)} if !purge { - for pane, tokens := range w.alone { + for pane, tokens := range w.restore { errs = append(errs, w.report(ctx, job{pane: pane}, tokens)) } } @@ -415,17 +407,6 @@ func delta(tokens Tokens, sent map[string]string) Tokens { return out } -// titles are the title tokens a patch sets. -func titles(tokens Tokens) Tokens { - out := Tokens{} - for name, value := range tokens { - if value != nil && strings.HasPrefix(name, titlePrefix) { - out[name] = value - } - } - return out -} - func values(tokens Tokens) map[string]string { out := map[string]string{} for name, value := range tokens { diff --git a/internal/adapters/sidebar/writer_test.go b/internal/adapters/sidebar/writer_test.go index 1112749..129080f 100644 --- a/internal/adapters/sidebar/writer_test.go +++ b/internal/adapters/sidebar/writer_test.go @@ -361,6 +361,37 @@ func TestWriterHidesFoldedRowsAndAStopShowsThemAgain(t *testing.T) { assert.Equal(t, "task", host.store["w1:p1"]["title_idle"], "the lone line's row reads again") } +func TestWriterRestoresFoldTitlesInBothLayouts(t *testing.T) { + for _, layout := range []ports.Layout{ports.LayoutClassic, ports.LayoutCompact} { + t.Run(string(layout), func(t *testing.T) { + host := newFakeHost() + settings := ports.DefaultSettings() + settings.Presentation.Layout = layout + settings.Presentation.Variant = ports.VariantText + settings.Presentation.ShowAge = ports.AgeAll + w := NewWriter(host, NewPresentation(settings, nil), (&clock{now: at0()}).Now) + carrier := idleRow("a1", "w1:p1") + carrier.Since = at0().Add(-90 * time.Second) + carrier.Fold = &domain.Fold{Root: "w1", Label: "dashboard", Hidden: 2, Alone: true} + v := view(carrier) + v.Folded = []domain.SidebarRow{idleRow("a2", "w1:p2")} + + next, err := w.Apply(context.Background(), v) + + require.NoError(t, err) + assert.True(t, next.IsZero()) + assert.NotContains(t, host.store["w1:p1"], "title_idle") + require.NoError(t, w.Clear(context.Background(), false)) + want := "1m task" + if layout == ports.LayoutCompact { + want = "§ " + want + } + assert.Equal(t, want, host.store["w1:p1"]["title_idle"]) + assert.NotContains(t, host.store["w1:p2"], "folded") + }) + } +} + // busyView is a full panel: fifteen workspaces of two agents each, every // state and a spread of vendors, grouped, with the Spaces column. func busyView() domain.SidebarView { diff --git a/internal/domain/catalog.go b/internal/domain/catalog.go index bd9abc6..00a1ee2 100644 --- a/internal/domain/catalog.go +++ b/internal/domain/catalog.go @@ -3,8 +3,6 @@ package domain // knownAgents lists the agent kinds Scope recognises, in the order the glyph // tables use, with the name a row shows when the agent never sets a title. // Kinds are the ids Herdr reports, which is why Antigravity is "agy". -// -//nolint:goconst // catalogue data: each literal is one table cell, not a repeated constant func knownAgents() []struct { Kind AgentKind Name string diff --git a/scripts/build.cmd b/scripts/build.cmd index a41c24f..3ad1da8 100644 --- a/scripts/build.cmd +++ b/scripts/build.cmd @@ -41,7 +41,7 @@ where go >nul 2>nul if not errorlevel 1 ( echo herdr-scope: no prebuilt binary for windows-%ARCH%, building from source with Go go build -trimpath -o bin\herdr-scope.exe .\cmd\herdr-scope && exit /b 0 - 1>&2 echo herdr-scope: go build failed, it needs Go 1.26 or newer; trying the release binary + 1>&2 echo herdr-scope: go build failed, it needs the Go toolchain declared in go.mod; trying the release binary ) rem The release download. The script reads the version from the manifest @@ -52,7 +52,7 @@ powershell -NoProfile -NonInteractive -Command "$ErrorActionPreference = 'Stop'; 1>&2 echo herdr-scope: cannot install: this checkout has no prebuilt binary for 1>&2 echo windows-%ARCH%, no Go toolchain built one, and the release binary could -1>&2 echo not be downloaded. Install a release, which ships prebuilt binaries for -1>&2 echo macOS, Linux and Windows on amd64 and arm64: herdr plugin install killallgit/herdr-scope --ref release -1>&2 echo -- or install Go 1.26 or newer from https://go.dev/dl/ and run the install again. +1>&2 echo not be downloaded. New prebuilt releases are available only for +1>&2 echo macOS and Linux. Building from source on Windows requires Go. +1>&2 echo -- or install the Go version declared in go.mod from https://go.dev/dl/ and run the install again. exit /b 1 diff --git a/scripts/build.sh b/scripts/build.sh index 0957730..f25f541 100755 --- a/scripts/build.sh +++ b/scripts/build.sh @@ -96,7 +96,7 @@ if command -v go >/dev/null 2>&1; then if go build -trimpath -o bin/herdr-scope ./cmd/herdr-scope; then exit 0 fi - echo "herdr-scope: go build failed (it needs Go 1.26 or newer); trying the release binary" >&2 + echo "herdr-scope: go build failed (it needs the Go toolchain declared in go.mod); trying the release binary" >&2 fi if download; then @@ -106,9 +106,9 @@ fi cat >&2 <>> HERDR-SCOPE-BEGIN sidebar", "with its blocks") t.Log("a rebuilt bin/ takes over at the next start, without a stop first") - rebuild := exec.Command("go", "build", "-ldflags", "-X main.version=0.0.0-rebuilt", + rebuild := exec.Command("go", "build", "-race", "-ldflags", "-X main.version=0.0.0-rebuilt", "-o", filepath.Join(e.plugin, "bin", "herdr-scope"), "./cmd/herdr-scope") rebuild.Dir = repoRoot(t) out, err := rebuild.CombinedOutput() diff --git a/tools/go.mod b/tools/go.mod new file mode 100644 index 0000000..cc5ace1 --- /dev/null +++ b/tools/go.mod @@ -0,0 +1,35 @@ +module github.com/killallgit/herdr-scope/tools + +go 1.26.10 + +tool ( + github.com/rhysd/actionlint/cmd/actionlint + golang.org/x/vuln/cmd/govulncheck + gotest.tools/gotestsum +) + +require ( + github.com/bitfield/gotestdox v0.2.2 // indirect + github.com/bmatcuk/doublestar/v4 v4.10.0 // indirect + github.com/clipperhouse/uax29/v2 v2.7.0 // indirect + github.com/dnephin/pflag v1.0.7 // indirect + github.com/fatih/color v1.19.0 // indirect + github.com/fsnotify/fsnotify v1.9.0 // indirect + github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 // indirect + github.com/mattn/go-colorable v0.1.14 // indirect + github.com/mattn/go-isatty v0.0.20 // indirect + github.com/mattn/go-runewidth v0.0.21 // indirect + github.com/mattn/go-shellwords v1.0.12 // indirect + github.com/rhysd/actionlint v1.7.12 // indirect + github.com/robfig/cron/v3 v3.0.1 // indirect + go.yaml.in/yaml/v4 v4.0.0-rc.3 // indirect + golang.org/x/mod v0.42.0 // indirect + golang.org/x/sync v0.24.0 // indirect + golang.org/x/sys v0.49.0 // indirect + golang.org/x/telemetry v0.0.0-20261010193011-f71dc92da45e // indirect + golang.org/x/term v0.35.0 // indirect + golang.org/x/text v0.17.0 // indirect + golang.org/x/tools v0.52.0 // indirect + golang.org/x/vuln v1.9.0 // indirect + gotest.tools/gotestsum v1.13.0 // indirect +) diff --git a/tools/go.sum b/tools/go.sum new file mode 100644 index 0000000..722b254 --- /dev/null +++ b/tools/go.sum @@ -0,0 +1,61 @@ +github.com/bitfield/gotestdox v0.2.2 h1:x6RcPAbBbErKLnapz1QeAlf3ospg8efBsedU93CDsnE= +github.com/bitfield/gotestdox v0.2.2/go.mod h1:D+gwtS0urjBrzguAkTM2wodsTQYFHdpx8eqRJ3N+9pY= +github.com/bmatcuk/doublestar/v4 v4.10.0 h1:zU9WiOla1YA122oLM6i4EXvGW62DvKZVxIe6TYWexEs= +github.com/bmatcuk/doublestar/v4 v4.10.0/go.mod h1:xBQ8jztBU6kakFMg+8WGxn0c6z1fTSPVIjEY1Wr7jzc= +github.com/clipperhouse/uax29/v2 v2.7.0 h1:+gs4oBZ2gPfVrKPthwbMzWZDaAFPGYK72F0NJv2v7Vk= +github.com/clipperhouse/uax29/v2 v2.7.0/go.mod h1:EFJ2TJMRUaplDxHKj1qAEhCtQPW2tJSwu5BF98AuoVM= +github.com/dnephin/pflag v1.0.7 h1:oxONGlWxhmUct0YzKTgrpQv9AUA1wtPBn7zuSjJqptk= +github.com/dnephin/pflag v1.0.7/go.mod h1:uxE91IoWURlOiTUIA8Mq5ZZkAv3dPUfZNaT80Zm7OQE= +github.com/fatih/color v1.19.0 h1:Zp3PiM21/9Ld6FzSKyL5c/BULoe/ONr9KlbYVOfG8+w= +github.com/fatih/color v1.19.0/go.mod h1:zNk67I0ZUT1bEGsSGyCZYZNrHuTkJJB+r6Q9VuMi0LE= +github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k= +github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0= +github.com/google/go-cmdtest v0.4.1-0.20220921163831-55ab3332a786 h1:rcv+Ippz6RAtvaGgKxc+8FQIpxHgsF+HBzPyYL2cyVU= +github.com/google/go-cmdtest v0.4.1-0.20220921163831-55ab3332a786/go.mod h1:apVn/GCasLZUVpAJ6oWAuyP7Ne7CEsQbTnc0plM3m+o= +github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= +github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= +github.com/google/renameio v0.1.0 h1:GOZbcHa3HfsPKPlmyPyN2KEohoMXOhdMbHrvbpl2QaA= +github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= +github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 h1:El6M4kTTCOh6aBiKaUGG7oYTSPP8MxqL4YI3kZKwcP4= +github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510/go.mod h1:pupxD2MaaD3pAXIBCelhxNneeOaAeabZDe5s4K6zSpQ= +github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE= +github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8= +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/mattn/go-runewidth v0.0.21 h1:jJKAZiQH+2mIinzCJIaIG9Be1+0NR+5sz/lYEEjdM8w= +github.com/mattn/go-runewidth v0.0.21/go.mod h1:XBkDxAl56ILZc9knddidhrOlY5R/pDhgLpndooCuJAs= +github.com/mattn/go-shellwords v1.0.12 h1:M2zGm7EW6UQJvDeQxo4T51eKPurbeFbe8WtebGE2xrk= +github.com/mattn/go-shellwords v1.0.12/go.mod h1:EZzvwXDESEeg03EKmM+RmDnNOPKG4lLtQsUlTZDWQ8Y= +github.com/rhysd/actionlint v1.7.12 h1:vQ4GeJN86C0QH+gTUQcs8McmK62OLT3kmakPMtEWYnY= +github.com/rhysd/actionlint v1.7.12/go.mod h1:krOUhujIsJusovkaYzQ/VNH8PFexjNKqU0q5XI/4w+g= +github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs= +github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro= +github.com/rogpeppe/go-internal v1.11.0 h1:cWPaGQEPrBb5/AsnsZesgZZ9yb1OQ+GOISoDNXVBh4M= +github.com/rogpeppe/go-internal v1.11.0/go.mod h1:ddIwULY96R17DhadqLgMfk9H9tvdUzkipdSkR5nkCZA= +go.yaml.in/yaml/v4 v4.0.0-rc.3 h1:3h1fjsh1CTAPjW7q/EMe+C8shx5d8ctzZTrLcs/j8Go= +go.yaml.in/yaml/v4 v4.0.0-rc.3/go.mod h1:aZqd9kCMsGL7AuUv/m/PvWLdg5sjJsZ4oHDEnfPPfY0= +golang.org/x/mod v0.42.0 h1:ICeL3t2L30ljSPHHxDnR4fqVcBt/zR2zJAb9juavmQg= +golang.org/x/mod v0.42.0/go.mod h1:u5fzIrRInkL8MaO1cbRkUHT64v303YIT5KEqpNr7jRs= +golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA= +golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA= +golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= +golang.org/x/telemetry v0.0.0-20261010193011-f71dc92da45e h1:P6NGsugec4oASJ+yKMNgTndeo0h2CbixZLvQIe9h5R4= +golang.org/x/telemetry v0.0.0-20261010193011-f71dc92da45e/go.mod h1:GNu+nb+E5axfGmP+Uu3ZVQu5lE/Xk42MjZOHWUD94/o= +golang.org/x/term v0.35.0 h1:bZBVKBudEyhRcajGcNc3jIfWPqV4y/Kt2XcoigOWtDQ= +golang.org/x/term v0.35.0/go.mod h1:TPGtkTLesOwf2DE8CgVYiZinHAOuy5AYUYT1lENIZnA= +golang.org/x/text v0.17.0 h1:XtiM5bkSOt+ewxlOE/aE/AKEHibwj/6gvWMl9Rsh0Qc= +golang.org/x/text v0.17.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY= +golang.org/x/tools v0.52.0 h1:ryxg4U63oaUYk7uOLTF37n43f4qgtGvqV4Ioit1BaEs= +golang.org/x/tools v0.52.0/go.mod h1:ItcP5UNaVGG+Yc4eIYmaFLNJ4soEopkx5Y2d4lcEurs= +golang.org/x/tools/go/expect v0.1.1-deprecated h1:jpBZDwmgPhXsKZC6WhL20P4b/wmnpsEAGHaNy0n/rJM= +golang.org/x/tools/go/expect v0.1.1-deprecated/go.mod h1:eihoPOH+FgIqa3FpoTwguz/bVUSGBlGQU67vpBeOrBY= +golang.org/x/tools/go/packages/packagestest v0.1.1-deprecated h1:1h2MnaIAIXISqTFKdENegdpAgUXz6NrPEsbIeWaBRvM= +golang.org/x/tools/go/packages/packagestest v0.1.1-deprecated/go.mod h1:RVAQXBGNv1ib0J382/DPCRS/BPnsGebyM1Gj5VSDpG8= +golang.org/x/vuln v1.9.0 h1:12VaqnI9kJfqwRoPptxoqsUhQtdfrSbdksT7X/KY/sc= +golang.org/x/vuln v1.9.0/go.mod h1:E/Frwm0xp49fTyBW+6CQHdkvobknbwUM49yEpMGUauw= +gotest.tools/gotestsum v1.13.0 h1:+Lh454O9mu9AMG1APV4o0y7oDYKyik/3kBOiCqiEpRo= +gotest.tools/gotestsum v1.13.0/go.mod h1:7f0NS5hFb0dWr4NtcsAsF0y1kzjEFfAil0HiBQJE03Q= +gotest.tools/v3 v3.5.2 h1:7koQfIKdy+I8UTetycgUqXWSDwpgv193Ka+qRsmBY8Q= +gotest.tools/v3 v3.5.2/go.mod h1:LtdLGcnqToBH83WByAAi/wiwSFCArdFIUV/xxN4pcjA=