From 28f0cf48c5aefa2f1b9835aa723653fafafbe945 Mon Sep 17 00:00:00 2001 From: archae0pteryx Date: Tue, 27 Oct 2026 19:54:31 -0700 Subject: [PATCH 1/3] 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/grilling/SKILL.md | 30 ++++ .agents/skills/grilling/agents/openai.yaml | 3 + .../HTML-REPORT.md | 123 +++++++++++++++++ .../improve-codebase-architecture/SKILL.md | 71 ++++++++++ .../agents/openai.yaml | 5 + .agents/skills/research/SKILL.md | 12 ++ .agents/skills/research/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 +++++++++++ .../writing-for-agents/SKILL-MECHANICS.md | 22 +++ .agents/skills/writing-for-agents/SKILL.md | 81 +++++++++++ .../writing-for-agents/agents/openai.yaml | 3 + .beads/.gitignore | 82 +++++++++++ .beads/README.md | 81 +++++++++++ .beads/config.yaml | 75 ++++++++++ .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 | 11 ++ .codex/hooks.json | 51 +++++++ .cursor/hooks.json | 20 +++ .cursor/rules/beads.mdc | 67 +++++++++ .gitignore | 9 +- AGENTS.md | 128 ++++++++++++++++++ CLAUDE.md | 77 +++++++++++ 43 files changed, 2005 insertions(+), 1 deletion(-) 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/grilling/SKILL.md create mode 100644 .agents/skills/grilling/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/research/SKILL.md create mode 100644 .agents/skills/research/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 .agents/skills/writing-for-agents/SKILL-MECHANICS.md create mode 100644 .agents/skills/writing-for-agents/SKILL.md create mode 100644 .agents/skills/writing-for-agents/agents/openai.yaml 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..373a4f2 --- /dev/null +++ b/.agents/skills/code-review/SKILL.md @@ -0,0 +1,89 @@ +--- +name: code-review +description: "Review the changes since a fixed point (commit, branch, tag, or merge-base) along two axes: Standards (does the code follow this repo's documented coding standards?) and Spec (does the code match what the originating issue/spec asked for?). Runs both reviews in parallel sub-agents and reports them side by side. Use when the user wants to review a branch, a PR, work-in-progress changes, or asks to \"review since X\"." +--- + +Two-axis review of the diff between `HEAD` and a fixed point the user supplies: + +- **Standards**: does the code conform to this repo's documented coding standards? +- **Spec**: does the code faithfully implement the originating issue / spec? + +Both axes run as **parallel sub-agents** so they don't pollute each other's context, then this skill aggregates their findings. + +The issue tracker should have been provided to you. If not, tell the user to run `/setup-matt-pocock-skills`. + +## Process + +### 1. Pin the fixed point + +Whatever the user said is the fixed point (a commit SHA, branch name, tag, `main`, `HEAD~5`, etc.). If they didn't specify one, ask for it. + +Capture the diff command once: `git diff ...HEAD` (three-dot, so the comparison is against the merge-base). Also note the list of commits via `git log ..HEAD --oneline`. + +Before going further, confirm the fixed point resolves (`git rev-parse `) and the diff is non-empty. A bad ref or empty diff should fail here, not inside two parallel sub-agents. + +### 2. Identify the spec source + +Look for the originating spec, in this order: + +1. Issue references in the commit messages (`#123`, `Closes #45`, GitLab `!67`, etc.), fetched via the workflow in the tracker doc. +2. A path the user passed as an argument. +3. A spec file under `docs/`, `specs/`, or `.scratch/` matching the branch name or feature. +4. If nothing is found, ask the user where the spec is. If they say there isn't one, the **Spec** sub-agent will skip and report "no spec available". + +### 3. Identify the standards sources + +Search the repo for every file that documents how code should be written. When `CODING_STANDARDS.md` or `CONTRIBUTING.md` exists, it must be on the list. + +On top of whatever the repo documents, the Standards axis always carries the **smell baseline** below: a fixed set of Fowler code smells (_Refactoring_, ch.3) that applies even when a repo documents nothing. Two rules bind it: + +- **The repo overrides.** A documented repo standard always wins; where it endorses something the baseline would flag, suppress the smell. +- **Always a judgement call.** Each smell is a labelled heuristic ("possible Feature Envy"), never a hard violation. Like any standard here, skip anything tooling already enforces. + +Each smell reads *what it is* → *how to fix*; match it against the diff: + +- **Mysterious Name**: a function, variable, or type whose name doesn't reveal what it does or holds. → rename it; if no honest name comes, the design's murky. +- **Duplicated Code**: the same logic shape appears in more than one hunk or file in the change. → extract the shared shape, call it from both. +- **Feature Envy**: a method that reaches into another object's data more than its own. → move the method onto the data it envies. +- **Data Clumps**: the same few fields or params keep travelling together (a type wanting to be born). → bundle them into one type, pass that. +- **Primitive Obsession**: a primitive or string standing in for a domain concept that deserves its own type. → give the concept its own small type. +- **Repeated Switches**: the same `switch`/`if`-cascade on the same type recurs across the change. → replace with polymorphism, or one map both sites share. +- **Shotgun Surgery**: one logical change forces scattered edits across many files in the diff. → gather what changes together into one module. +- **Divergent Change**: one file or module is edited for several unrelated reasons. → split so each module changes for one reason. +- **Speculative Generality**: abstraction, parameters, or hooks added for needs the spec doesn't have. → delete it; inline back until a real need shows. +- **Message Chains**: long `a.b().c().d()` navigation the caller shouldn't depend on. → hide the walk behind one method on the first object. +- **Middle Man**: a class or function that mostly just delegates onward. → cut it, call the real target direct. +- **Refused Bequest**: a subclass or implementer that ignores or overrides most of what it inherits. → drop the inheritance, use composition. + +### 4. Spawn both sub-agents in parallel + +Issue both sub-agent calls together, in the foreground, and aggregate the reports they return. + +**Standards sub-agent prompt** should include: + +- The full diff command and commit list. +- The list of standards-source files you found in step 3, **plus the smell baseline from step 3** pasted in full (the sub-agent has no other access to it). +- The brief: "Report, per file/hunk where relevant, (a) every place the diff violates a documented standard: cite the standard (file + the rule); and (b) any baseline smell you spot: name it and quote the hunk. Distinguish hard violations from judgement calls: documented-standard breaches can be hard, but baseline smells are always judgement calls, and a documented repo standard overrides the baseline. Skip anything tooling enforces. Under 400 words." + +**Spec sub-agent prompt** should include: + +- The diff command and commit list. +- The path or fetched contents of the spec. +- The brief: "Report: (a) requirements the spec asked for that are missing or partial; (b) behaviour in the diff that wasn't asked for (scope creep); (c) requirements that look implemented but where the implementation looks wrong. Quote the spec line for each finding. Under 400 words." + +If the spec is missing, skip the Spec sub-agent and note this in the final report. + +### 5. Aggregate + +Present the two reports under `## Standards` and `## Spec` headings, verbatim or lightly cleaned. Do **not** merge or rerank findings, because the two axes are deliberately separate (see _Why two axes_). + +End with a one-line summary: total findings per axis, and the worst issue _within each axis_ (if any). Don't pick a single winner across axes: that's the reranking the separation exists to prevent. + +## Why two axes + +A change can pass one axis and fail the other: + +- Code that follows every standard but implements the wrong thing → **Standards pass, Spec fail.** +- Code that does exactly what the issue asked but breaks the project's conventions → **Spec pass, Standards fail.** + +Reporting them separately stops one axis from masking the other. diff --git a/.agents/skills/code-review/agents/openai.yaml b/.agents/skills/code-review/agents/openai.yaml new file mode 100644 index 0000000..9076774 --- /dev/null +++ b/.agents/skills/code-review/agents/openai.yaml @@ -0,0 +1,3 @@ +interface: + display_name: "Code Review" + short_description: "Review a diff on standards and spec" diff --git a/.agents/skills/codebase-design/DEEPENING.md b/.agents/skills/codebase-design/DEEPENING.md new file mode 100644 index 0000000..cd94075 --- /dev/null +++ b/.agents/skills/codebase-design/DEEPENING.md @@ -0,0 +1,37 @@ +# Deepening + +How to deepen a cluster of shallow modules safely, given its dependencies. Assumes the vocabulary in [SKILL.md](SKILL.md): **module**, **interface**, **seam**, **adapter**. + +## Dependency categories + +When assessing a candidate for deepening, classify its dependencies. The category determines how the deepened module is tested across its seam. + +### 1. In-process + +Pure computation, in-memory state, no I/O. Always deepenable: merge the modules and test through the new interface directly. No adapter needed. + +### 2. Local-substitutable + +Dependencies that have local test stand-ins (PGLite for Postgres, in-memory filesystem). Deepenable if the stand-in exists. The deepened module is tested with the stand-in running in the test suite. The seam is internal; no port at the module's external interface. + +### 3. Remote but owned (Ports & Adapters) + +Your own services across a network boundary (microservices, internal APIs). Define a **port** (interface) at the seam. The deep module owns the logic; the transport is injected as an **adapter**. Tests use an in-memory adapter. Production uses an HTTP/gRPC/queue adapter. + +Recommendation shape: *"Define a port at the seam, implement an HTTP adapter for production and an in-memory adapter for testing, so the logic sits in one deep module even though it's deployed across a network."* + +### 4. True external (Mock) + +Third-party services (Stripe, Twilio, etc.) you don't control. The deepened module takes the external dependency as an injected port; tests provide a mock adapter. + +## Seam discipline + +- **One adapter means a hypothetical seam. Two adapters means a real one.** Don't introduce a port unless at least two adapters are justified (typically production + test). A single-adapter seam is just indirection. +- **Internal seams vs external seams.** A deep module can have internal seams (private to its implementation, used by its own tests) as well as the external seam at its interface. Don't expose internal seams through the interface just because tests use them. + +## Testing strategy: replace, don't layer + +- Old unit tests on shallow modules become waste once tests at the deepened module's interface exist; delete them. +- Write new tests at the deepened module's interface. The **interface is the test surface**. +- Tests assert on observable outcomes through the interface, not internal state. +- Tests should survive internal refactors, since they describe behaviour, not implementation. If a test has to change when the implementation changes, it's testing past the interface. diff --git a/.agents/skills/codebase-design/DESIGN-IT-TWICE.md b/.agents/skills/codebase-design/DESIGN-IT-TWICE.md new file mode 100644 index 0000000..d099013 --- /dev/null +++ b/.agents/skills/codebase-design/DESIGN-IT-TWICE.md @@ -0,0 +1,44 @@ +# Design It Twice + +When the user wants to explore alternative interfaces for a chosen deepening candidate, use this parallel sub-agent pattern. Based on "Design It Twice" (Ousterhout): your first idea is unlikely to be the best. + +Uses the vocabulary in [SKILL.md](SKILL.md): **module**, **interface**, **seam**, **adapter**, **leverage**. + +## Process + +### 1. Frame the problem space + +Before spawning sub-agents, write a user-facing explanation of the problem space for the chosen candidate: + +- The constraints any new interface would need to satisfy +- The dependencies it would rely on, and which category they fall into (see [DEEPENING.md](DEEPENING.md)) +- A rough illustrative code sketch to ground the constraints, not a proposal, just a way to make the constraints concrete + +Show this to the user, then immediately proceed to Step 2. The user reads and thinks while the sub-agents work in parallel. + +### 2. Spawn sub-agents + +Spawn 3+ sub-agents in parallel. Each must produce a **radically different** interface for the deepened module. + +Prompt each sub-agent with a separate technical brief (file paths, coupling details, dependency category from [DEEPENING.md](DEEPENING.md), what sits behind the seam). The brief is independent of the user-facing problem-space explanation in Step 1. Give each agent a different design constraint: + +- Agent 1: "Minimize the interface: aim for 1–3 entry points max. Maximise leverage per entry point." +- Agent 2: "Maximise flexibility: support many use cases and extension." +- Agent 3: "Optimise for the most common caller: make the default case trivial." +- Agent 4 (if applicable): "Design around ports & adapters for cross-seam dependencies." + +Include both [SKILL.md](SKILL.md) vocabulary and GLOSSARY.md vocabulary in the brief so each sub-agent names things consistently with the architecture language and the project's domain language. + +Each sub-agent outputs: + +1. Interface (types, methods, params, plus invariants, ordering, error modes) +2. Usage example showing how callers use it +3. What the implementation hides behind the seam +4. Dependency strategy and adapters (see [DEEPENING.md](DEEPENING.md)) +5. Trade-offs: where leverage is high, where it's thin + +### 3. Present and compare + +Present designs sequentially so the user can absorb each one, then compare them in prose. Contrast by **depth** (leverage at the interface), **locality** (where change concentrates), and **seam placement**. + +After comparing, give your own recommendation: which design you think is strongest and why. If elements from different designs would combine well, propose a hybrid. Be opinionated: the user wants a strong read, not a menu. diff --git a/.agents/skills/codebase-design/SKILL.md b/.agents/skills/codebase-design/SKILL.md new file mode 100644 index 0000000..3f63c81 --- /dev/null +++ b/.agents/skills/codebase-design/SKILL.md @@ -0,0 +1,114 @@ +--- +name: codebase-design +description: Shared vocabulary for designing deep modules. Use when the user wants to design or improve a module's interface, find deepening opportunities, decide where a seam goes, make code more testable or AI-navigable, or when another skill needs the deep-module vocabulary. +--- + +# Codebase Design + +Design **deep modules**: a lot of behaviour behind a small interface, placed at a clean seam, testable through that interface. Use this language and these principles wherever code is being designed or restructured. The aim is leverage for callers, locality for maintainers, and testability for everyone. + +## Glossary + +Use these terms exactly: don't substitute "component," "service," "API," or "boundary." Consistent language is the whole point. + +**Module**: anything with an interface and an implementation. Deliberately scale-agnostic: a function, class, package, or tier-spanning slice. _Avoid_: unit, component, service. + +**Interface**: everything a caller must know to use the module correctly: the type signature, but also invariants, ordering constraints, error modes, required configuration, and performance characteristics. _Avoid_: API, signature (too narrow, they refer only to the type-level surface). + +**Implementation**: what's inside a module, its body of code. Distinct from **Adapter**: a thing can be a small adapter with a large implementation (a Postgres repo) or a large adapter with a small implementation (an in-memory fake). Reach for "adapter" when the seam is the topic; "implementation" otherwise. + +**Depth**: leverage at the interface. The amount of behaviour a caller (or test) can exercise per unit of interface they have to learn. A module is **deep** when a large amount of behaviour sits behind a small interface, **shallow** when the interface is nearly as complex as the implementation. + +**Seam** _(Michael Feathers)_: a place where you can alter behaviour without editing in that place; the *location* at which a module's interface lives. Where to put the seam is its own design decision, distinct from what goes behind it. _Avoid_: boundary (overloaded with DDD's bounded context). + +**Adapter**: a concrete thing that satisfies an interface at a seam. Describes *role* (what slot it fills), not substance (what's inside). + +**Leverage**: what callers get from depth. More capability per unit of interface they learn. One implementation pays back across N call sites and M tests. + +**Locality**: what maintainers get from depth. Change, bugs, knowledge, and verification concentrate in one place rather than spreading across callers. Fix once, fixed everywhere. + +## Deep vs shallow + +**Deep module** = small interface + lots of implementation: + +``` +┌─────────────────────┐ +│ Small Interface │ ← Few methods, simple params +├─────────────────────┤ +│ │ +│ Deep Implementation│ ← Complex logic hidden +│ │ +└─────────────────────┘ +``` + +**Shallow module** = large interface + little implementation (avoid): + +``` +┌─────────────────────────────────┐ +│ Large Interface │ ← Many methods, complex params +├─────────────────────────────────┤ +│ Thin Implementation │ ← Just passes through +└─────────────────────────────────┘ +``` + +When designing an interface, ask: + +- Can I reduce the number of methods? +- Can I simplify the parameters? +- Can I hide more complexity inside? + +## Principles + +- **Depth is a property of the interface, not the implementation.** A deep module can be internally composed of small, mockable, swappable parts; they just aren't part of the interface. A module can have **internal seams** (private to its implementation, used by its own tests) as well as the **external seam** at its interface. +- **The deletion test.** Imagine deleting the module. If complexity vanishes, it was a pass-through. If complexity reappears across N callers, it was earning its keep. +- **The interface is the test surface.** Callers and tests cross the same seam. If you want to test *past* the interface, the module is probably the wrong shape. +- **One adapter means a hypothetical seam. Two adapters means a real one.** Don't introduce a seam unless something actually varies across it. + +## Designing for testability + +Good interfaces make testing natural: + +1. **Accept dependencies, don't create them.** + + ```typescript + // Testable + function processOrder(order, paymentGateway) {} + + // Hard to test + function processOrder(order) { + const gateway = new StripeGateway(); + } + ``` + +2. **Return results, don't produce side effects.** + + ```typescript + // Testable + function calculateDiscount(cart): Discount {} + + // Hard to test + function applyDiscount(cart): void { + cart.total -= discount; + } + ``` + +3. **Small surface area.** Fewer methods = fewer tests needed. Fewer params = simpler test setup. + +## Relationships + +- A **Module** has exactly one **Interface** (the surface it presents to callers and tests). +- **Depth** is a property of a **Module**, measured against its **Interface**. +- A **Seam** is where a **Module**'s **Interface** lives. +- An **Adapter** sits at a **Seam** and satisfies the **Interface**. +- **Depth** produces **Leverage** for callers and **Locality** for maintainers. + +## Rejected framings + +- **Depth as ratio of implementation-lines to interface-lines** (Ousterhout): rewards padding the implementation. We use depth-as-leverage instead. +- **"Interface" as the TypeScript `interface` keyword or a class's public methods**: too narrow: interface here includes every fact a caller must know. +- **"Boundary"**: overloaded with DDD's bounded context. Say **seam** or **interface**. + +## Going deeper + +- **Deepening a cluster given its dependencies**, see [DEEPENING.md](DEEPENING.md): dependency categories, seam discipline, and replace-don't-layer testing. +- **Exploring alternative interfaces**, see [DESIGN-IT-TWICE.md](DESIGN-IT-TWICE.md): spin up parallel sub-agents to design the interface several radically different ways, then compare on depth, locality, and seam placement. diff --git a/.agents/skills/codebase-design/agents/openai.yaml b/.agents/skills/codebase-design/agents/openai.yaml new file mode 100644 index 0000000..3180715 --- /dev/null +++ b/.agents/skills/codebase-design/agents/openai.yaml @@ -0,0 +1,3 @@ +interface: + display_name: "Codebase Design" + short_description: "Vocabulary for deep-module design" diff --git a/.agents/skills/domain-modeling/ADR-FORMAT.md b/.agents/skills/domain-modeling/ADR-FORMAT.md new file mode 100644 index 0000000..d7e61f3 --- /dev/null +++ b/.agents/skills/domain-modeling/ADR-FORMAT.md @@ -0,0 +1,47 @@ +# ADR Format + +ADRs live in `docs/adr/` and use sequential numbering: `0001-slug.md`, `0002-slug.md`, etc. + +Create the `docs/adr/` directory lazily: only when the first ADR is needed. + +## Template + +```md +# {Short title of the decision} + +{1-3 sentences: what's the context, what did we decide, and why.} +``` + +That's it. An ADR can be a single paragraph. The value is in recording *that* a decision was made and *why*, not in filling out sections. + +## Optional sections + +Only include these when they add genuine value. Most ADRs won't need them. + +- **Status** frontmatter (`proposed | accepted | deprecated | superseded by ADR-NNNN`): useful when decisions are revisited +- **Considered Options**: only when the rejected alternatives are worth remembering +- **Consequences**: only when non-obvious downstream effects need to be called out + +## Numbering + +Scan `docs/adr/` for the highest existing number and increment by one. + +## When to offer an ADR + +All three of these must be true: + +1. **Hard to reverse**: the cost of changing your mind later is meaningful +2. **Surprising without context**: a future reader will look at the code and wonder "why on earth did they do it this way?" +3. **The result of a real trade-off**: there were genuine alternatives and you picked one for specific reasons + +If a decision is easy to reverse, skip it: you'll just reverse it. If it's not surprising, nobody will wonder why. If there was no real alternative, there's nothing to record beyond "we did the obvious thing." + +### What qualifies + +- **Architectural shape.** "We're using a monorepo." "The write model is event-sourced, the read model is projected into Postgres." +- **Integration patterns between contexts.** "Ordering and Billing communicate via domain events, not synchronous HTTP." +- **Technology choices that carry lock-in.** Database, message bus, auth provider, deployment target. Not every library: just the ones that would take a quarter to swap out. +- **Boundary and scope decisions.** "Customer data is owned by the Customer context; other contexts reference it by ID only." The explicit no-s are as valuable as the yes-s. +- **Deliberate deviations from the obvious path.** "We're using manual SQL instead of an ORM because X." Anything where a reasonable reader would assume the opposite. These stop the next engineer from "fixing" something that was deliberate. +- **Constraints not visible in the code.** "We can't use AWS because of compliance requirements." "Response times must be under 200ms because of the partner API contract." +- **Rejected alternatives when the rejection is non-obvious.** If you considered GraphQL and picked REST for subtle reasons, record it; otherwise someone will suggest GraphQL again in six months. diff --git a/.agents/skills/domain-modeling/GLOSSARY-FORMAT.md b/.agents/skills/domain-modeling/GLOSSARY-FORMAT.md new file mode 100644 index 0000000..9c0b4c7 --- /dev/null +++ b/.agents/skills/domain-modeling/GLOSSARY-FORMAT.md @@ -0,0 +1,60 @@ +# GLOSSARY.md Format + +## Structure + +```md +# {Context Name} + +{One or two sentence description of what this context is and why it exists.} + +## Language + +**Order**: +{A one or two sentence description of the term} +_Avoid_: Purchase, transaction + +**Invoice**: +A request for payment sent to a customer after delivery. +_Avoid_: Bill, payment request + +**Customer**: +A person or organization that places orders. +_Avoid_: Client, buyer, account +``` + +## Rules + +- **Be opinionated.** When multiple words exist for the same concept, pick the best one and list the others under `_Avoid_`. +- **Keep definitions tight.** One or two sentences max. Define what it IS, not what it does. +- **Only include terms specific to this project's context.** General programming concepts (timeouts, error types, utility patterns) don't belong even if the project uses them extensively. Before adding a term, ask: is this a concept unique to this context, or a general programming concept? Only the former belongs. +- **Group terms under subheadings** when natural clusters emerge. If all terms belong to a single cohesive area, a flat list is fine. + +## Single vs multi-context repos + +**Single context (most repos):** One `GLOSSARY.md` at the repo root. + +**Multiple contexts:** A `GLOSSARY-MAP.md` at the repo root lists the contexts, where they live, and how they relate to each other: + +```md +# Glossary Map + +## Contexts + +- [Ordering](./src/ordering/GLOSSARY.md): receives and tracks customer orders +- [Billing](./src/billing/GLOSSARY.md): generates invoices and processes payments +- [Fulfillment](./src/fulfillment/GLOSSARY.md): manages warehouse picking and shipping + +## Relationships + +- **Ordering → Fulfillment**: Ordering emits `OrderPlaced` events; Fulfillment consumes them to start picking +- **Fulfillment → Billing**: Fulfillment emits `ShipmentDispatched` events; Billing consumes them to generate invoices +- **Ordering ↔ Billing**: Shared types for `CustomerId` and `Money` +``` + +The skill infers which structure applies: + +- If `GLOSSARY-MAP.md` exists, read it to find contexts +- If only a root `GLOSSARY.md` exists, single context +- If neither exists, create a root `GLOSSARY.md` lazily when the first term is resolved + +When multiple contexts exist, infer which one the current topic relates to. If unclear, ask. diff --git a/.agents/skills/domain-modeling/SKILL.md b/.agents/skills/domain-modeling/SKILL.md new file mode 100644 index 0000000..a4438c6 --- /dev/null +++ b/.agents/skills/domain-modeling/SKILL.md @@ -0,0 +1,74 @@ +--- +name: domain-modeling +description: Build and sharpen a project's domain model. Use when discussing codebase terminology, writing or editing a GLOSSARY.md, or recording or editing an ADR. +--- + +# Domain Modeling + +Actively build and sharpen the project's domain model as you design. This is the *active* discipline: challenging terms, inventing edge-case scenarios, and writing the glossary and decisions down the moment they crystallise. (Merely *reading* `GLOSSARY.md` for vocabulary is not this skill: that's a one-line habit any skill can do. This skill is for when you're changing the model, not just consuming it.) + +## File structure + +Most repos have a single context: + +``` +/ +├── GLOSSARY.md +├── docs/ +│ └── adr/ +│ ├── 0001-event-sourced-orders.md +│ └── 0002-postgres-for-write-model.md +└── src/ +``` + +If a `GLOSSARY-MAP.md` exists at the root, the repo has multiple contexts. The map points to where each one lives: + +``` +/ +├── GLOSSARY-MAP.md +├── docs/ +│ └── adr/ ← system-wide decisions +├── src/ +│ ├── ordering/ +│ │ ├── GLOSSARY.md +│ │ └── docs/adr/ ← context-specific decisions +│ └── billing/ +│ ├── GLOSSARY.md +│ └── docs/adr/ +``` + +Create files lazily: only when you have something to write. If no `GLOSSARY.md` exists, create one when the first term is resolved. If no `docs/adr/` exists, create it when the first ADR is needed. + +## During the session + +### Challenge against the glossary + +When the user uses a term that conflicts with the existing language in `GLOSSARY.md`, call it out immediately. "Your glossary defines 'cancellation' as X, but you seem to mean Y. Which is it?" + +### Sharpen fuzzy language + +When the user uses vague or overloaded terms, propose a precise canonical term. "You're saying 'account': do you mean the Customer or the User? Those are different things." + +### Discuss concrete scenarios + +When domain relationships are being discussed, stress-test them with specific scenarios. Invent scenarios that probe edge cases and force the user to be precise about the boundaries between concepts. + +### Cross-reference with code + +When the user states how something works, check whether the code agrees. If you find a contradiction, surface it: "Your code cancels entire Orders, but you just said partial cancellation is possible. Which is right?" + +### Update GLOSSARY.md inline + +When a term is resolved, update `GLOSSARY.md` right there. Don't batch these up: capture them as they happen. Use the format in [GLOSSARY-FORMAT.md](./GLOSSARY-FORMAT.md). + +`GLOSSARY.md` should be totally devoid of implementation details. Do not treat `GLOSSARY.md` as a spec, a scratch pad, or a repository for implementation decisions. It is a glossary and nothing else. + +### Offer ADRs sparingly + +Only offer to create an ADR when all three are true: + +1. **Hard to reverse**: the cost of changing your mind later is meaningful +2. **Surprising without context**: a future reader will wonder "why did they do it this way?" +3. **The result of a real trade-off**: there were genuine alternatives and you picked one for specific reasons + +If any of the three is missing, skip the ADR. Use the format in [ADR-FORMAT.md](./ADR-FORMAT.md). diff --git a/.agents/skills/domain-modeling/agents/openai.yaml b/.agents/skills/domain-modeling/agents/openai.yaml new file mode 100644 index 0000000..7f1522d --- /dev/null +++ b/.agents/skills/domain-modeling/agents/openai.yaml @@ -0,0 +1,3 @@ +interface: + display_name: "Domain Modeling" + short_description: "Build and sharpen a domain model" diff --git a/.agents/skills/grilling/SKILL.md b/.agents/skills/grilling/SKILL.md new file mode 100644 index 0000000..df69d99 --- /dev/null +++ b/.agents/skills/grilling/SKILL.md @@ -0,0 +1,30 @@ +--- +name: grilling +description: Grill the user relentlessly about a plan, decision, or idea. Use when the user wants to stress-test their thinking, or uses any 'grill' trigger phrases. +--- + +Interview the user relentlessly until you reach a shared understanding. Map this as a **design tree**: every decision branches into the decisions that hang off it. + +Work the tree in **rounds**. The **frontier** is every decision whose prerequisites are already settled: the questions you can ask _now_ without guessing at answers you haven't heard yet. Ask the whole frontier in one round: number each question and give your recommended answer. Then wait for the user's answers before the next round. + +Format a round like so: + +``` +❓ **Q1** - ****: + +➡️ + +--- + +❓ **Q2** - ****: + +➡️ +``` + +Word each question so "yes" accepts your recommended answer. + +Each round the user answers reshapes the tree: settled decisions push the frontier outward and unblock questions that depended on them. Recompute the frontier and ask the next round. A question whose answer depends on another question still open in this round belongs to a _later_ round, not this one. + +Finding _facts_ is your job, never the user's. When a frontier question needs a fact from the environment (filesystem, tools, etc.), dispatch a sub-agent to find it; don't ask the user for anything you could look up yourself. Don't block on it: a running exploration is an unsettled prerequisite, so only the questions downstream of it wait for the sub-agent to report; ask the rest of the frontier now. The _decisions_ are the user's: put each to them and wait. + +The session is done when the frontier is empty: every branch of the design tree visited, nothing left silently assumed. Do not act on it until the user confirms you have reached a shared understanding. diff --git a/.agents/skills/grilling/agents/openai.yaml b/.agents/skills/grilling/agents/openai.yaml new file mode 100644 index 0000000..ddbdb96 --- /dev/null +++ b/.agents/skills/grilling/agents/openai.yaml @@ -0,0 +1,3 @@ +interface: + display_name: "Grilling" + short_description: "Stress-test thinking a round of questions at a time" diff --git a/.agents/skills/improve-codebase-architecture/HTML-REPORT.md b/.agents/skills/improve-codebase-architecture/HTML-REPORT.md new file mode 100644 index 0000000..e39e825 --- /dev/null +++ b/.agents/skills/improve-codebase-architecture/HTML-REPORT.md @@ -0,0 +1,123 @@ +# HTML Report Format + +The architectural review is rendered as a single self-contained HTML file in the OS temp directory. Tailwind and Mermaid both come from CDNs. Mermaid handles graph-shaped diagrams reliably; hand-built divs and inline SVG handle the more editorial visuals (mass diagrams, cross-sections). Mix the two: don't lean on Mermaid for everything, it'll start to look generic. + +## Scaffold + +```html + + + + + Architecture review for {{repo name}} + + + + + +
+
...
+
...
+
...
+
+ + +``` + +## Header + +Repo name, date, and a compact legend: solid box = module, dashed line = seam, red arrow = leakage, thick dark box = deep module. No introduction paragraph. Straight into the candidates. + +## Candidate card + +The diagrams carry the weight. Prose is sparse, plain, and uses the glossary terms (from the `/codebase-design` skill) without ceremony. + +Each candidate is one `
`: + +- **Title**: short, names the deepening (e.g. "Collapse the Order intake pipeline"). +- **Badge row**: recommendation strength (`Strong` = emerald, `Worth exploring` = amber, `Speculative` = slate), plus a tag for the dependency category (`in-process`, `local-substitutable`, `ports & adapters`, `mock`). +- **Files**: monospaced list, `font-mono text-sm`. +- **Before / After diagram**: the centrepiece. Two columns, side by side. See patterns below. +- **Problem**: one sentence. What hurts. +- **Solution**: one sentence. What changes. +- **Wins**: bullets, ≤6 words each. e.g. "Tests hit one interface", "Pricing logic stops leaking", "Delete 4 shallow wrappers". +- **ADR callout** (if applicable): one line in an amber-tinted box. + +No paragraphs of explanation. If the diagram needs a paragraph to be understood, redraw the diagram. + +## Diagram patterns + +Pick the pattern that fits the candidate. Mix them. Don't make every diagram look the same. Variety is part of the point. + +### Mermaid graph (the workhorse for dependencies / call flow) + +Use a Mermaid `flowchart` or `graph` when the point is "X calls Y calls Z, and look at the mess." Wrap it in a Tailwind-styled card so it doesn't feel parachuted in. Style with classDef to colour leakage edges red and the deep module dark. Sequence diagrams work well for "before: 6 round-trips; after: 1." + +```html +
+
+    flowchart LR
+      A[OrderHandler] --> B[OrderValidator]
+      B --> C[OrderRepo]
+      C -.leak.-> D[PricingClient]
+      classDef leak stroke:#dc2626,stroke-width:2px;
+      class C,D leak
+  
+
+``` + +### Hand-built boxes-and-arrows (when Mermaid's layout fights you) + +Modules as `
`s with borders and labels. Arrows as inline SVG `` or `` elements positioned absolutely over a relative container. Reach for this when you want the "after" diagram to feel like one thick-bordered deep module with greyed-out internals, since Mermaid won't render that with the right weight. + +### Cross-section (good for layered shallowness) + +Stack horizontal bands (`h-12 border-l-4`) to show layers a call passes through. Before: 6 thin layers each doing nothing. After: 1 thick band labelled with the consolidated responsibility. + +### Mass diagram (good for "interface as wide as implementation") + +Two rectangles per module: one for interface surface area, one for implementation. Before: interface rectangle is nearly as tall as the implementation rectangle (shallow). After: interface rectangle is short, implementation rectangle is tall (deep). + +### Call-graph collapse + +Before: a tree of function calls rendered as nested boxes. After: the same tree collapsed into one box, with the now-internal calls shown faded inside it. + +## Style guidance + +- Lean editorial, not corporate-dashboard. Generous whitespace. Serif optional for headings (`font-serif` works well with stone/slate). +- Colour sparingly: one accent (emerald or indigo) plus red for leakage and amber for warnings. +- Keep diagrams ~320px tall so before/after sits comfortably side by side without scrolling. +- Use `text-xs uppercase tracking-wider` for module labels inside diagrams, so they read as schematic, not as UI. +- The only scripts are the Tailwind CDN and the Mermaid ESM import. The report is otherwise static: no app code, no interactivity beyond Mermaid's own rendering. + +## Top recommendation section + +One larger card. Candidate name, one sentence on why, anchor link to its card. That's it. + +## Tone + +Plain English, concise, but the architectural nouns and verbs come straight from the `/codebase-design` skill. Concision is not an excuse to drift. + +**Use exactly:** module, interface, implementation, depth, deep, shallow, seam, adapter, leverage, locality. + +**Never substitute:** component, service, unit (for module) · API, signature (for interface) · boundary (for seam) · layer, wrapper (for module, when you mean module). + +**Phrasings that fit the style:** + +- "Order intake module is shallow: interface nearly matches the implementation." +- "Pricing leaks across the seam." +- "Deepen: one interface, one place to test." +- "Two adapters justify the seam: HTTP in prod, in-memory in tests." + +**Wins bullets** name the gain in glossary terms: *"locality: bugs concentrate in one module"*, *"leverage: one interface, N call sites"*, *"interface shrinks; implementation absorbs the wrappers"*. Don't write *"easier to maintain"* or *"cleaner code"*, because those terms aren't in the glossary and don't earn their place. + +No hedging, no throat-clearing, no "it's worth noting that…". If a sentence could be a bullet, make it a bullet. If a bullet could be cut, cut it. If a term isn't in the `/codebase-design` glossary, reach for one that is before inventing a new one. diff --git a/.agents/skills/improve-codebase-architecture/SKILL.md b/.agents/skills/improve-codebase-architecture/SKILL.md new file mode 100644 index 0000000..44cc7d3 --- /dev/null +++ b/.agents/skills/improve-codebase-architecture/SKILL.md @@ -0,0 +1,71 @@ +--- +name: improve-codebase-architecture +description: Scan a codebase for deepening opportunities, present them as a visual HTML report, then grill through whichever one you pick. +disable-model-invocation: true +--- + +# Improve Codebase Architecture + +Surface architectural friction and propose **deepening opportunities**: refactors that turn shallow modules into deep ones. The aim is testability and AI-navigability. + +This command is _informed_ by the project's domain model and built on a shared design vocabulary: + +- Call the Skill tool with "codebase-design" for the architecture vocabulary (**module**, **interface**, **depth**, **seam**, **adapter**, **leverage**, **locality**) and its principles (the deletion test, "the interface is the test surface", "one adapter = hypothetical seam, two = real"). Use these terms exactly in every suggestion, and don't drift into "component," "service," "API," or "boundary." +- The domain language in `GLOSSARY.md` gives names to good seams; ADRs in `docs/adr/` record decisions this command should not re-litigate. + +## Process + +### 1. Explore + +**Scope before you scan: YAGNI.** Deepening a module pays off by making future changes to it easier, so put extra weight on the parts of the codebase that have recently changed. Decide *where* to look before you look: + +- If the user named a direction (a module, a subsystem, a pain point), take it, and skip the inference below. +- Otherwise, walk back a good stretch of the commit history (`git log --oneline`) to find the codebase's hot spots, the files and areas that keep coming up, and let those paths pull your attention first. If the changes are scattered with no clear hot spot, widen the net. + +Read the project's domain glossary (`GLOSSARY.md`) and any ADRs in the area you're touching first. + +Then spawn a sub-agent to walk the codebase. Don't follow rigid heuristics; explore organically and note where you experience friction: + +- Where does understanding one concept require bouncing between many small modules? +- Where are modules **shallow**, with an interface nearly as complex as the implementation? +- Where have pure functions been extracted just for testability, but the real bugs hide in how they're called (no **locality**)? +- Where do tightly-coupled modules leak across their seams? +- Which parts of the codebase are untested, or hard to test through their current interface? + +Apply the **deletion test** to anything you suspect is shallow: would deleting it concentrate complexity, or just move it? A "yes, concentrates" is the signal you want. + +### 2. Present candidates as an HTML report + +Write a self-contained HTML file to the OS temp directory so nothing lands in the repo. Resolve the temp dir from `$TMPDIR`, falling back to `/tmp` (or `%TEMP%` on Windows), and write to `/architecture-review-.html` so each run gets a fresh file. Open it for the user (`xdg-open ` on Linux, `open ` on macOS, `start ` on Windows) and tell them the absolute path. + +The report uses **Tailwind via CDN** for layout and styling, and **Mermaid via CDN** for diagrams where a graph/flow/sequence reliably communicates the structure. Mix Mermaid with hand-crafted CSS/SVG visuals: use Mermaid when relationships are graph-shaped (call graphs, dependencies, sequences), and hand-built divs/SVG when you want something more editorial (mass diagrams, cross-sections, collapse animations). Each candidate gets a **before/after visualisation**. Be visual. + +For each candidate, render a card with: + +- **Files**: which files/modules are involved +- **Problem**: why the current architecture is causing friction +- **Solution**: plain English description of what would change +- **Benefits**: explained in terms of locality and leverage, and how tests would improve +- **Before / After diagram**: side-by-side, custom-drawn, illustrating the shallowness and the deepening +- **Recommendation strength**: one of `Strong`, `Worth exploring`, `Speculative`, rendered as a badge + +End the report with a **Top recommendation** section: which candidate you'd tackle first and why. + +**Use GLOSSARY.md vocabulary for the domain, and the `/codebase-design` vocabulary for the architecture.** If `GLOSSARY.md` defines "Order," talk about "the Order intake module," not "the FooBarHandler," and not "the Order service." + +**ADR conflicts**: if a candidate contradicts an existing ADR, only surface it when the friction is real enough to warrant revisiting the ADR. Mark it clearly in the card (e.g. a warning callout: _"contradicts ADR-0007, but worth reopening because…"_). Don't list every theoretical refactor an ADR forbids. + +See [HTML-REPORT.md](HTML-REPORT.md) for the full HTML scaffold, diagram patterns, and styling guidance. + +Do NOT propose interfaces yet. After the file is written, ask the user: "Which of these would you like to explore?" + +### 3. Grilling loop + +Once the user picks a candidate, call the Skill tool with "grilling" to walk the decision tree with them: constraints, dependencies, the shape of the deepened module, what sits behind the seam, what tests survive. + +Side effects happen inline as decisions crystallize; call the Skill tool with "domain-modeling" to keep the domain model current as you go: + +- **Naming a deepened module after a concept not in `GLOSSARY.md`?** Add the term to `GLOSSARY.md`. Create the file lazily if it doesn't exist. +- **Sharpening a fuzzy term during the conversation?** Update `GLOSSARY.md` right there. +- **User rejects the candidate with a load-bearing reason?** Offer an ADR, framed as: _"Want me to record this as an ADR so future architecture reviews don't re-suggest it?"_ Only offer when the reason would actually be needed by a future explorer to avoid re-suggesting the same thing; skip ephemeral reasons ("not worth it right now") and self-evident ones. +- **Want to explore alternative interfaces for the deepened module?** Call the Skill tool with "codebase-design" and use its design-it-twice parallel sub-agent pattern. diff --git a/.agents/skills/improve-codebase-architecture/agents/openai.yaml b/.agents/skills/improve-codebase-architecture/agents/openai.yaml new file mode 100644 index 0000000..706fdca --- /dev/null +++ b/.agents/skills/improve-codebase-architecture/agents/openai.yaml @@ -0,0 +1,5 @@ +interface: + display_name: "Improve Codebase Architecture" + short_description: "Find and grill architecture improvements" +policy: + allow_implicit_invocation: false diff --git a/.agents/skills/research/SKILL.md b/.agents/skills/research/SKILL.md new file mode 100644 index 0000000..fecee97 --- /dev/null +++ b/.agents/skills/research/SKILL.md @@ -0,0 +1,12 @@ +--- +name: research +description: Investigate a question against high-trust primary sources and capture the findings as a Markdown file in the repo. Use when the user wants a topic researched, docs or API facts gathered, or reading legwork delegated to a background agent. +--- + +Spin up a **background agent** to do the research, so you keep working while it reads. + +Its job: + +1. Investigate the question against **primary sources** (official docs, source code, specs, first-party APIs), not a secondary write-up of them. Follow every claim back to the source that owns it. +2. Write the findings to a single Markdown file, citing each claim's source. +3. Save it where the repo already keeps such notes; match the existing convention, and if there is none, put it somewhere sensible and say where. diff --git a/.agents/skills/research/agents/openai.yaml b/.agents/skills/research/agents/openai.yaml new file mode 100644 index 0000000..e18b96c --- /dev/null +++ b/.agents/skills/research/agents/openai.yaml @@ -0,0 +1,3 @@ +interface: + display_name: "Research" + short_description: "Research from high-trust sources" diff --git a/.agents/skills/tdd/SKILL.md b/.agents/skills/tdd/SKILL.md new file mode 100644 index 0000000..01eadaa --- /dev/null +++ b/.agents/skills/tdd/SKILL.md @@ -0,0 +1,38 @@ +--- +name: tdd +description: Test-driven development. Use when the user wants to build features or fix bugs test-first, mentions "red-green-refactor", or wants integration tests. +--- + +# Test-Driven Development + +TDD is the red → green loop. This skill is the reference that makes that loop produce tests worth keeping: what a good test is, where tests go, the anti-patterns, and the rules of the loop. Every section applies on every cycle: consult them before and during the loop, not after. + +When exploring the codebase, read `GLOSSARY.md` (if it exists) so test names and interface vocabulary match the project's domain language, and respect ADRs in the area you're touching. + +## What a good test is + +Tests verify behavior through public interfaces, not implementation details. Code can change entirely; tests shouldn't. A good test reads like a specification: "user can checkout with valid cart" tells you exactly what capability exists, and it survives refactors because it doesn't care about internal structure. + +See [tests.md](tests.md) for examples and [mocking.md](mocking.md) for mocking guidelines. + +## Seams: where tests go + +A **seam** is the public boundary you test at: the interface where you observe behavior without reaching inside. Tests live at seams, never against internals. + +**Test only at pre-agreed seams.** Before writing any test, write down the seams under test and confirm them with the user. No test is written at an unconfirmed seam. You can't test everything, so agreeing the seams up front is how testing effort lands on the critical paths and complex logic instead of every edge case. + +Ask: "What's the public interface, and which seams should we test?" Give each proposed seam a one-line note on what it catches and what it misses. + +When the shape of that interface is itself in question (how deep the module is, where the seam belongs, what the interface should expose), call the Skill tool with "codebase-design" for the vocabulary. It is the shared source of the module, interface, depth, seam, adapter, leverage and locality terms, and it is a reference to consult, not a session to run. + +## Anti-patterns + +- **Implementation-coupled**: mocks internal collaborators, tests private methods, or verifies through a side channel (querying the database instead of using the interface). The tell: the test breaks when you refactor but behavior hasn't changed. +- **Tautological**: the assertion recomputes the expected value the way the code does (`expect(add(a, b)).toBe(a + b)`, a snapshot derived by hand the same way, a constant asserted equal to itself), so it passes by construction and can never disagree with the code. Expected values must come from an independent source of truth: a known-good literal, a worked example, the spec. +- **Horizontal slicing**: writing all tests first, then all implementation. Bulk tests verify _imagined_ behavior: you test the _shape_ of things rather than user-facing behavior, the tests go insensitive to real changes, and you commit to test structure before understanding the implementation. Work in **vertical slices** instead: one test → one implementation → repeat, each test a **tracer bullet** that responds to what the last cycle taught you. + +## Rules of the loop + +- **Red before green.** Write the failing test first, then only enough code to pass it. Don't anticipate future tests or add speculative features. +- **One slice at a time.** One seam, one test, one minimal implementation per cycle. +- **Refactoring is not part of the loop.** It belongs to the review stage (see the `code-review` skill), not the red → green implementation cycle. diff --git a/.agents/skills/tdd/agents/openai.yaml b/.agents/skills/tdd/agents/openai.yaml new file mode 100644 index 0000000..651b838 --- /dev/null +++ b/.agents/skills/tdd/agents/openai.yaml @@ -0,0 +1,3 @@ +interface: + display_name: "TDD" + short_description: "Test-driven red-green-refactor" diff --git a/.agents/skills/tdd/mocking.md b/.agents/skills/tdd/mocking.md new file mode 100644 index 0000000..71cbfee --- /dev/null +++ b/.agents/skills/tdd/mocking.md @@ -0,0 +1,59 @@ +# When to Mock + +Mock at **system boundaries** only: + +- External APIs (payment, email, etc.) +- Databases (sometimes - prefer test DB) +- Time/randomness +- File system (sometimes) + +Don't mock: + +- Your own classes/modules +- Internal collaborators +- Anything you control + +## Designing for Mockability + +At system boundaries, design interfaces that are easy to mock: + +**1. Use dependency injection** + +Pass external dependencies in rather than creating them internally: + +```typescript +// Easy to mock +function processPayment(order, paymentClient) { + return paymentClient.charge(order.total); +} + +// Hard to mock +function processPayment(order) { + const client = new StripeClient(process.env.STRIPE_KEY); + return client.charge(order.total); +} +``` + +**2. Prefer SDK-style interfaces over generic fetchers** + +Create specific functions for each external operation instead of one generic function with conditional logic: + +```typescript +// GOOD: Each function is independently mockable +const api = { + getUser: (id) => fetch(`/users/${id}`), + getOrders: (userId) => fetch(`/users/${userId}/orders`), + createOrder: (data) => fetch('/orders', { method: 'POST', body: data }), +}; + +// BAD: Mocking requires conditional logic inside the mock +const api = { + fetch: (endpoint, options) => fetch(endpoint, options), +}; +``` + +The SDK approach means: +- Each mock returns one specific shape +- No conditional logic in test setup +- Easier to see which endpoints a test exercises +- Type safety per endpoint diff --git a/.agents/skills/tdd/tests.md b/.agents/skills/tdd/tests.md new file mode 100644 index 0000000..7ab8647 --- /dev/null +++ b/.agents/skills/tdd/tests.md @@ -0,0 +1,77 @@ +# Good and Bad Tests + +## Good Tests + +**Integration-style**: Test through real interfaces, not mocks of internal parts. + +```typescript +// GOOD: Tests observable behavior +test("user can checkout with valid cart", async () => { + const cart = createCart(); + cart.add(product); + const result = await checkout(cart, paymentMethod); + expect(result.status).toBe("confirmed"); +}); +``` + +Characteristics: + +- Tests behavior users/callers care about +- Uses public API only +- Survives internal refactors +- Describes WHAT, not HOW +- One logical assertion per test + +## Bad Tests + +**Implementation-detail tests**: Coupled to internal structure. + +```typescript +// BAD: Tests implementation details +test("checkout calls paymentService.process", async () => { + const mockPayment = jest.mock(paymentService); + await checkout(cart, payment); + expect(mockPayment.process).toHaveBeenCalledWith(cart.total); +}); +``` + +Red flags: + +- Mocking internal collaborators +- Testing private methods +- Asserting on call counts/order +- Test breaks when refactoring without behavior change +- Test name describes HOW not WHAT +- Verifying through external means instead of interface + +```typescript +// BAD: Bypasses interface to verify +test("createUser saves to database", async () => { + await createUser({ name: "Alice" }); + const row = await db.query("SELECT * FROM users WHERE name = ?", ["Alice"]); + expect(row).toBeDefined(); +}); + +// GOOD: Verifies through interface +test("createUser makes user retrievable", async () => { + const user = await createUser({ name: "Alice" }); + const retrieved = await getUser(user.id); + expect(retrieved.name).toBe("Alice"); +}); +``` + +**Tautological tests**: Expected value restates the implementation, so the test passes by construction. + +```typescript +// BAD: Expected value is recomputed the way the code computes it +test("calculateTotal sums line items", () => { + const items = [{ price: 10 }, { price: 5 }]; + const expected = items.reduce((sum, i) => sum + i.price, 0); + expect(calculateTotal(items)).toBe(expected); +}); + +// GOOD: Expected value is an independent, known literal +test("calculateTotal sums line items", () => { + expect(calculateTotal([{ price: 10 }, { price: 5 }])).toBe(15); +}); +``` diff --git a/.agents/skills/writing-for-agents/SKILL-MECHANICS.md b/.agents/skills/writing-for-agents/SKILL-MECHANICS.md new file mode 100644 index 0000000..9cdbdb2 --- /dev/null +++ b/.agents/skills/writing-for-agents/SKILL-MECHANICS.md @@ -0,0 +1,22 @@ +# Skill mechanics + +The skill-specific branch of [`writing-for-agents`](SKILL.md): what changes when the document is a skill (frontmatter, the invocation choice, and router skills). Everything else about writing it is the universal reference in `SKILL.md`. + +## Invocation + +Two choices, trading the two loads: + +- A **model-invoked** skill keeps a `description`, so the agent can fire it autonomously, and other skills can reach it. You can still type its name: model-invocation always _includes_ user reach; a description only ever adds agent discovery, never removes the human's. The description is the skill's top-level context pointer, forced to stay loaded at all times: permanent context load in exchange for discoverability. A model-invoked skill whose content is all reference is also one home for shared reference: another skill can invoke it, so reference needed by several skills lives in one place. Mechanics: omit `disable-model-invocation`, and write a model-facing description carrying the trigger branches (the pointer-writing rules in `SKILL.md` apply in full). +- A **user-invoked** skill strips the description from the agent's reach: only the human typing its name can invoke it, and no other skill can. Zero context load, but it spends cognitive load: you are the index that must remember it exists. Mechanics: set `disable-model-invocation: true`; the `description` becomes human-facing: a one-line summary, trigger lists stripped. + +Pick model-invocation only when the agent must reach the skill on its own, or another skill must. If it only ever fires by hand, make it user-invoked and pay no context load. + +Shared reference that two user-invoked skills both need can live in neither: with no descriptions, neither can fire the other. Push it to a plain file outside the skill system: external reference any skill can point at. + +## Splitting by invocation + +The invocation cut of splitting (the sequence cut lives in `SKILL.md`): split off a model-invoked skill when you have a distinct leading word that should trigger it on its own (a trigger word you actually use in your prompts), or another skill must reach it. You pay context load for the new always-loaded description, so that independent reach has to be worth it. + +## Router skills + +When user-invoked skills multiply past what you can remember, that piled-up cognitive load is cured by a **router skill**: one user-invoked skill that names the others and when to reach for each, so the human has one skill to remember instead of many. It can only hint, never fire them: user-invoked skills have no description, so nothing but the human can reach them. diff --git a/.agents/skills/writing-for-agents/SKILL.md b/.agents/skills/writing-for-agents/SKILL.md new file mode 100644 index 0000000..a37608d --- /dev/null +++ b/.agents/skills/writing-for-agents/SKILL.md @@ -0,0 +1,81 @@ +--- +name: writing-for-agents +description: Writing documents for agents. Use when creating or editing skills, or modifying AGENTS.md or CLAUDE.md. +--- + +Reference for writing any document an agent consumes: a skill, an `AGENTS.md` / `CLAUDE.md`, a doc reached by a pointer. The packaging differs; the writing does not: the same levers make each one predictable, since the agent takes the same _process_ every run rather than producing the same output. + +When the document you're writing is a skill, read [`SKILL-MECHANICS.md`](SKILL-MECHANICS.md) for frontmatter, invocation choice, and router skills. + +## Context pointers + +A **context pointer** is a reference held in the agent's context that names some out-of-context material and encodes the condition for reaching it. A skill's description is one; a line in `AGENTS.md` naming a doc is the same object. The pointer's _wording_, not its target, decides when the agent reaches the material, and how reliably. A must-have target behind a weakly worded pointer is a variance bug: sharpen the wording first, and inline the material only if sharpening fails. + +A pointer does two jobs: state what the material is, and list the **branches** that should trigger reaching it (a branch is a distinct case the document handles, so different runs take different paths through it). Every word of an always-loaded pointer costs on every turn, so it earns even harder pruning than the body: + +- **Front-load the leading word**: the pointer is where it does its triggering work. +- **One trigger per branch.** Synonyms that rename a single branch are one branch written twice; collapse them and keep only genuinely distinct branches. +- **Cut identity the body already carries.** + +## The two loads + +Every document and pointer you add spends one of two budgets: + +- **Context load** is the cost of always-loaded material on the agent's window: an `AGENTS.md` line, a skill description, anything sitting in context every turn, spending tokens and attention whether or not it fires. +- **Cognitive load** is the cost on the human: which documents exist and when to reach for each. The human is the index. Not a cost to minimise: it is the price of human agency; spend it where human judgement matters, remove it where it does not. + +Material reached only through a pointer escapes context load at the price of the pointer's own line; material with no pointer at all rides entirely on cognitive load. + +## Information hierarchy + +A document is built from two content types: **steps** (the ordered actions the agent performs) and **reference** (definitions, rules, facts consulted on demand). The two mix freely: all steps (a recipe), all reference (a review's rules, this skill), or both. The core decision is where each piece sits on the **information hierarchy**, a ladder ranked by how immediately the agent needs the material: + +1. **In-file step** is the primary tier: what the agent does, in order. +2. **In-file reference** is consulted on demand. Often a legitimately flat peer-set (every rule of a review on one rung), which is a fine arrangement, not a smell. +3. **Disclosed reference** is pushed out into a separate file, reached by a context pointer, loaded only when the pointer fires. Spans a sibling file in the same folder through fully external reference that lives anywhere and any document can point at. + +Push too little down and the top bloats; push too much and you hide material the agent actually needs. That tension is the whole decision. + +**Progressive disclosure** is the move down the ladder (out of the main file and behind a pointer) so the top stays legible. Not primarily a token optimisation: it is how the hierarchy is protected. Branching is the cleanest disclosure test: inline what every branch needs, and push behind a pointer what only some branches reach. When a document has steps, in-file reference that should be disclosed buries them and turns attending to them into a coin-flip: a variance lever, not just a legibility one. + +**Co-location** is the within-file companion: where the ladder decides _how far down_ a piece sits, co-location decides _what sits beside it_ once there. Keep a concept's definition, rules, and caveats under one heading rather than scattered, so reading one part brings its neighbours with it. The test: the document should read like documentation written for the agent. Grouped material reads that way; scattered material does not. (Distinct from duplication: that repeats one meaning in two places; scattering fragments one meaning across many.) + +**Sprawl** is the failure mode here: a document simply too long, even when every line is live and unique. Attention thins across the excess, and every extra line is one more to keep relevant. The cure is the ladder: disclose reference behind pointers, and split by branch or sequence so each path carries only what it needs. + +## Steps and completion criteria + +Every step ends on a **completion criterion**, the condition that tells the agent the work is done. Two properties make it a lever: + +- **Clarity**: can the agent tell done from not-done? A vague bound ("understanding reached") invites **premature completion**: ending the step before it is genuinely done, attention slipping to _being done_. The visible steps still ahead (the **post-completion steps**) supply the pull; the criterion's clarity is the resistance. Defend in order: **sharpen the bound first** (local and cheap); only if it is irreducibly fuzzy _and_ you observe the rush, hide the later steps by splitting the sequence. Hiding only works across a real context boundary (a hand-off or a subagent dispatch; an inline call leaves the later steps in context and clears nothing). +- **Demand**: how much it requires. "Every modified model accounted for" forces thorough work where "produce a change list" does not. Demand drives **legwork** (the digging the agent does within the work, latent in the wording rather than written as its own step), and it is not step-bound: "every rule applied" binds a body of flat reference just as "every step done" binds a sequence, which is how an all-reference document still carries an exhaustiveness bar. + +The strongest criteria are both checkable and exhaustive. + +## When to split + +Splitting one document into two spends one of the two loads, so split only when the cut earns it: + +- **By sequence**: split a run of steps where the post-completion steps tempt the agent to rush the one in front of it. Keeping them out of view drives more legwork on the current task. Beware the reverse: merging sequences exposes each step's later steps to what follows, inviting premature completion. +- **By invocation**, skill-specific: see [`SKILL-MECHANICS.md`](SKILL-MECHANICS.md). + +## Leading words + +A **leading word** is a compact concept already living in the model's pretraining that the agent thinks with while running the document (_lesson_, _fog of war_, _tracer bullets_). Repeated as a token, never as a sentence, it accumulates a distributed definition and anchors a whole region of behaviour in the fewest tokens, by recruiting priors the model already holds. Coining your own works if you define it clearly, but a made-up word recruits no priors: you pay in definition tokens what a pretrained word gives free; reach for an existing word first. + +It anchors twice. In the body, _execution_: the agent reaches for the same behaviour every time the word appears, and inside flat reference it focuses attention on a class of thing to look for. In a pointer, _invocation_: when the same word lives in your prompts, your docs, and your codebase, the agent links that shared language to the material and reaches it more reliably. + +Hunt for opportunities to refactor with leading words. A triad spelled out at three sites, a pointer spending a sentence to gesture at one idea. Each is a passage begging to collapse into a single token: + +- "fast, deterministic, low-overhead" → _tight_ (a _tight_ loop). +- "a loop you believe in" → _red_, turning a fuzzy gate into a binary observable state (the loop goes _red_ on the bug, or it doesn't). + +You win twice: fewer tokens, and a sharper hook for the agent to hang its thinking on. Assume every document is carrying restatements that leading words retire. Go find them. + +**Negation** is the failure mode beside this lever: steering by prohibition drags the forbidden behaviour into context and makes it _more_ available, not less. _Don't think of an elephant_, and the elephant is all there is; the negation is a weak modifier the strongly-activated concept overruns, so the ban half-reads as an instruction to do the thing. Prompt the **positive**: state the target behaviour ("write one-line comments") so the banned one is never spoken. A prohibition earns its place only as a hard guardrail you cannot phrase positively; even then, pair it with the positive target so attention lands on what to do. + +## Pruning + +- Keep each meaning in a **single source of truth**: one authoritative place, so changing the behaviour is a one-place edit. **Duplication** (the same meaning in more than one place) costs maintenance and tokens, and inflates a meaning's prominence on the ladder past its real rank. (The accidental inverse of a leading word, which repeats a token on purpose, never the meaning.) +- The **environment** is a source of truth too (`package.json` scripts, config files, the directory layout, `--help` output), and a document that restates it is a **cache**: a copy of a lookup, earning its load only when the lookup is expensive. Cache what the agent cannot find by looking: the unwritten convention, the reason behind a choice, the gotcha no config confesses. Leave the one-file, one-command lookups to the environment, where they cannot go stale. +- Check every line for **relevance**: does it still bear on what the document does? A line loses relevance by never bearing on the task (mere exposition, or a branch that should be disclosed) or by going stale as the behaviour or world it describes changes. Shorter documents are easier to keep relevant. Without a pruning discipline the default fate is **sediment**: stale layers that settle because adding feels safe and removing feels risky, until you must core down through them to find what is still live. +- Hunt **no-ops** sentence by sentence: an instruction the model already obeys by default pays load to say nothing. The test (does it change behaviour versus the default?) is model-relative, not reader-relative: two people disagreeing about a no-op disagree about the default, and settle it by running the document, not by debate. When a sentence fails, delete the whole sentence rather than trim words from it. The test also grades leading words: a word too weak to beat the default (_be thorough_ when the agent is already thorough-ish) is a no-op, and the fix is a stronger word (_relentless_), not a different technique. diff --git a/.agents/skills/writing-for-agents/agents/openai.yaml b/.agents/skills/writing-for-agents/agents/openai.yaml new file mode 100644 index 0000000..079c933 --- /dev/null +++ b/.agents/skills/writing-for-agents/agents/openai.yaml @@ -0,0 +1,3 @@ +interface: + display_name: "Writing for Agents" + short_description: "Write documents agents consume" diff --git a/.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..e9a15fe --- /dev/null +++ b/.beads/config.yaml @@ -0,0 +1,75 @@ +# 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-alt-tab" diff --git a/.beads/hooks/post-checkout b/.beads/hooks/post-checkout new file mode 100755 index 0000000..797c119 --- /dev/null +++ b/.beads/hooks/post-checkout @@ -0,0 +1,59 @@ +#!/usr/bin/env sh +# --- BEGIN BEADS INTEGRATION v1.3.1 --- +# 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.1 --- diff --git a/.beads/hooks/post-merge b/.beads/hooks/post-merge new file mode 100755 index 0000000..07a8f63 --- /dev/null +++ b/.beads/hooks/post-merge @@ -0,0 +1,59 @@ +#!/usr/bin/env sh +# --- BEGIN BEADS INTEGRATION v1.3.1 --- +# 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.1 --- diff --git a/.beads/hooks/pre-commit b/.beads/hooks/pre-commit new file mode 100755 index 0000000..8b030e7 --- /dev/null +++ b/.beads/hooks/pre-commit @@ -0,0 +1,59 @@ +#!/usr/bin/env sh +# --- BEGIN BEADS INTEGRATION v1.3.1 --- +# 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.1 --- diff --git a/.beads/hooks/pre-push b/.beads/hooks/pre-push new file mode 100755 index 0000000..77a3b8b --- /dev/null +++ b/.beads/hooks/pre-push @@ -0,0 +1,59 @@ +#!/usr/bin/env sh +# --- BEGIN BEADS INTEGRATION v1.3.1 --- +# 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.1 --- diff --git a/.beads/hooks/prepare-commit-msg b/.beads/hooks/prepare-commit-msg new file mode 100755 index 0000000..333f71b --- /dev/null +++ b/.beads/hooks/prepare-commit-msg @@ -0,0 +1,59 @@ +#!/usr/bin/env sh +# --- BEGIN BEADS INTEGRATION v1.3.1 --- +# 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.1 --- diff --git a/.beads/metadata.json b/.beads/metadata.json new file mode 100644 index 0000000..bcc5bdc --- /dev/null +++ b/.beads/metadata.json @@ -0,0 +1,7 @@ +{ + "database": "dolt", + "backend": "dolt", + "dolt_mode": "embedded", + "dolt_database": "herdr_alt_tab", + "project_id": "33c5e970-5dc4-4b72-b404-7db1924359db" +} \ 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..a880e0a --- /dev/null +++ b/.codex/config.toml @@ -0,0 +1,11 @@ +[marketplaces.mattpocock] +source_type = "git" +source = "https://github.com/mattpocock/skills.git" +ref = "HEAD" +sparse_paths = [] + +[plugins."mattpocock-skills@mattpocock"] +enabled = true + +[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 617f37c..b44abe4 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,11 @@ /target .cargo tmp -___* \ No newline at end of file +___* + +# 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 a281fea5cbc85e2936cb75c890d89f6eb50ac72c Mon Sep 17 00:00:00 2001 From: archae0pteryx Date: Thu, 29 Oct 2026 10:59:53 -0700 Subject: [PATCH 2/3] Deepen the Cycle module and tidy the seams around it Presses, focus hooks and the Alt-release watcher are separate processes that agree through a state file. That protocol was spread over Cycler, Tracker, ReleaseWaiter, Session and SessionStore, and had to be called in the right order. It now lives in one module, src/cycle/, whose interface is Cycle::{press, observe_focus, release}, Direction and CycleId. - Rename Session to Cycle; the state file is now cycle-.json. An old session file is simply ignored, and a cycle lasts at most 30s. - observe_focus holds the cycle lock through its History write, as press already did. - Saved state is only reachable through a lock-scoped Turn. - History owns the live-pane recency rule and hands out an opaque Snapshot; Visit is private. - Lock is split from StateFile (Connection::lock). - LiveConfig moves into the herdr module and HerdrBinary::run is private. - Environment reads every variable once; herdr_env and config_path go. - Clock gains pause so the release wait loop and its 30s cap are testable. - Add GLOSSARY.md defining Cycle. Overlapping tests are consolidated (117 -> 103) and new ones cover the hold cap, release grace, idle window and config check/reload. --- GLOSSARY.md | 9 + src/clock.rs | 5 + src/command.rs | 14 +- src/connection.rs | 35 ++-- src/cycle.rs | 349 ++++++++++++++++++++++++++++++++++++++ src/cycle/state.rs | 285 +++++++++++++++++++++++++++++++ src/cycle/store.rs | 42 +++++ src/cycler.rs | 203 ---------------------- src/environment.rs | 135 +++++++++++++++ src/focus_event.rs | 53 ++++++ src/herdr.rs | 54 +++--- src/herdr/binary.rs | 54 +++++- src/herdr_env.rs | 3 - src/history.rs | 88 ++++++++-- src/keys.rs | 2 - src/keys/config_path.rs | 72 -------- src/keys/editor.rs | 23 ++- src/keys/live_config.rs | 24 --- src/lock.rs | 54 ++++++ src/main.rs | 68 ++++---- src/release.rs | 88 ++++------ src/session.rs | 364 ---------------------------------------- src/session_store.rs | 100 ----------- src/state_file.rs | 26 +-- src/test_support.rs | 93 ++++------ src/track.rs | 177 ------------------- 26 files changed, 1224 insertions(+), 1196 deletions(-) create mode 100644 GLOSSARY.md create mode 100644 src/cycle.rs create mode 100644 src/cycle/state.rs create mode 100644 src/cycle/store.rs delete mode 100644 src/cycler.rs create mode 100644 src/environment.rs create mode 100644 src/focus_event.rs delete mode 100644 src/herdr_env.rs delete mode 100644 src/keys/config_path.rs delete mode 100644 src/keys/live_config.rs create mode 100644 src/lock.rs delete mode 100644 src/session.rs delete mode 100644 src/session_store.rs delete mode 100644 src/track.rs diff --git a/GLOSSARY.md b/GLOSSARY.md new file mode 100644 index 0000000..0854058 --- /dev/null +++ b/GLOSSARY.md @@ -0,0 +1,9 @@ +# Herdr Alt-Tab + +A Herdr plugin that moves focus between panes in most-recently-used order, the way Alt+Tab moves between windows. + +## Language + +**Cycle**: +One run of Alt+Tab presses, from the first press until Alt comes up or the user stops pressing. Panes the Cycle passes through do not change their place in recency order; only the pane it ends on does. +_Avoid_: Session diff --git a/src/clock.rs b/src/clock.rs index 98de749..c675312 100644 --- a/src/clock.rs +++ b/src/clock.rs @@ -2,6 +2,7 @@ use std::time::{SystemTime, UNIX_EPOCH}; pub trait Clock { fn now_millis(&self) -> u64; + fn pause(&self, millis: u64); } pub struct SystemClock; @@ -12,4 +13,8 @@ impl Clock for SystemClock { .duration_since(UNIX_EPOCH) .map_or(0, |elapsed| elapsed.as_millis() as u64) } + + fn pause(&self, millis: u64) { + std::thread::sleep(std::time::Duration::from_millis(millis)); + } } diff --git a/src/command.rs b/src/command.rs index a5d996e..753a68a 100644 --- a/src/command.rs +++ b/src/command.rs @@ -1,10 +1,10 @@ -use crate::session::Direction; +use crate::cycle::{CycleId, Direction}; #[derive(Debug, Clone, PartialEq, Eq)] pub enum Command { Press(Direction), Track, - Watch { started_at: u64 }, + Watch { cycle: CycleId }, SetupKeys, RemoveKeys, } @@ -20,8 +20,8 @@ impl Command { ["track"] => Some(Command::Track), ["setup-keys"] => Some(Command::SetupKeys), ["remove-keys"] => Some(Command::RemoveKeys), - ["watch", started_at] => Some(Command::Watch { - started_at: started_at.parse().ok()?, + ["watch", cycle] => Some(Command::Watch { + cycle: cycle.parse().ok()?, }), _ => None, } @@ -32,7 +32,7 @@ impl Command { Command::Press(Direction::Older) => vec!["older".into()], Command::Press(Direction::Newer) => vec!["newer".into()], Command::Track => vec!["track".into()], - Command::Watch { started_at } => vec!["watch".into(), started_at.to_string()], + Command::Watch { cycle } => vec!["watch".into(), cycle.to_string()], Command::SetupKeys => vec!["setup-keys".into()], Command::RemoveKeys => vec!["remove-keys".into()], } @@ -49,7 +49,9 @@ mod tests { Command::Press(Direction::Older), Command::Press(Direction::Newer), Command::Track, - Command::Watch { started_at: 42 }, + Command::Watch { + cycle: "42".parse().unwrap(), + }, Command::SetupKeys, Command::RemoveKeys, ]; diff --git a/src/connection.rs b/src/connection.rs index d219a21..6e82449 100644 --- a/src/connection.rs +++ b/src/connection.rs @@ -1,6 +1,7 @@ use std::path::PathBuf; -use crate::herdr_env; +use crate::environment::Environment; +use crate::lock::Lock; use crate::state_file::StateFile; pub struct Connection { @@ -16,24 +17,28 @@ impl Connection { } } - pub fn from_env() -> Self { - let state_dir = std::env::var_os("HERDR_PLUGIN_STATE_DIR") - .map(PathBuf::from) - .unwrap_or_else(|| std::env::temp_dir().join("herdr-alt-tab")); - Self::new(state_dir, herdr_env::var("HERDR_SOCKET_PATH")) - } - - pub fn socket_path(&self) -> Option<&str> { - self.socket_path.as_deref() + pub fn from_environment(environment: &Environment) -> Self { + Self::new( + environment.state_dir.clone(), + environment.socket_path.clone(), + ) } // Pane ids mean nothing across Herdr instances, so each keeps its own state. pub fn state_file(&self, stem: &str) -> StateFile { + StateFile::at(self.path_of(stem, "json")) + } + + pub fn lock(&self, stem: &str) -> Lock { + Lock::at(self.path_of(stem, "lock")) + } + + fn path_of(&self, stem: &str, extension: &str) -> PathBuf { let file_name = match &self.socket_path { - Some(socket) => format!("{stem}-{:016x}.json", fnv1a(socket)), - None => format!("{stem}.json"), + Some(socket) => format!("{stem}-{:016x}.{extension}", fnv1a(socket)), + None => format!("{stem}.{extension}"), }; - StateFile::at(self.state_dir.join(file_name)) + self.state_dir.join(file_name) } } @@ -86,9 +91,9 @@ mod tests { let connection = connection(&dir, "/run/a.sock"); connection.state_file("history").write("history").unwrap(); - let session = connection.state_file("session").read(); + let cycle_state = connection.state_file("cycle").read(); - assert_eq!(session, None); + assert_eq!(cycle_state, None); } #[test] diff --git a/src/cycle.rs b/src/cycle.rs new file mode 100644 index 0000000..e27862c --- /dev/null +++ b/src/cycle.rs @@ -0,0 +1,349 @@ +mod state; +mod store; + +use crate::clock::Clock; +use crate::connection::Connection; +use crate::herdr::Herdr; +use crate::history::History; +use crate::keyboard::Keyboard; +use crate::release::ReleaseWatcher; +use state::{Sighting, State}; +use store::{Store, Turn}; + +pub use state::{CycleId, Direction, MAX_HOLD_MILLIS}; + +pub struct Collaborators<'a> { + pub herdr: &'a dyn Herdr, + pub keyboard: &'a dyn Keyboard, + pub watcher: &'a dyn ReleaseWatcher, + pub history: &'a History, + pub clock: &'a dyn Clock, +} + +/// Runs the cycles of Alt+Tab presses, and tells them apart from the user's own moves. +/// +/// Presses, focus hooks and the release watcher are separate processes, so each +/// takes a turn on the saved state, and holds it until its history writes are +/// done. The turn is always taken before History's own lock, never after. +pub struct Cycle<'a> { + herdr: &'a dyn Herdr, + keyboard: &'a dyn Keyboard, + watcher: &'a dyn ReleaseWatcher, + history: &'a History, + clock: &'a dyn Clock, + store: Store, +} + +impl<'a> Cycle<'a> { + pub fn new(connection: &Connection, with: Collaborators<'a>) -> Self { + Self { + herdr: with.herdr, + keyboard: with.keyboard, + watcher: with.watcher, + history: with.history, + clock: with.clock, + store: Store::new(connection.state_file("cycle"), connection.lock("cycle")), + } + } + + pub fn press(&self, direction: Direction) -> anyhow::Result<()> { + let turn = self.store.begin_turn()?; + let now = self.clock.now_millis(); + + let panes = self.herdr.panes()?; + let recency = self.history.recency_of(panes.ids()); + let sighting = Sighting { + live_mru: recency.live, + focused_pane: panes.focused().map(|pane| pane.id.clone()), + baseline: recency.snapshot, + alt_held: self.keyboard.alt_held() == Some(true), + }; + + let ongoing = State::ongoing(turn.load(), now); + let starts_new_cycle = ongoing.is_none(); + let Some(state) = State::advance(ongoing, sighting, direction, now) else { + return Ok(()); + }; + + // Saved before focusing so the focus hook, which takes the same turn, + // can tell the focus events that follow are ours. + turn.save(&state)?; + if let Err(error) = self.herdr.focus(state.target()) { + turn.clear(); + return Err(error.into()); + } + self.history + .promote_after_cycle(state.baseline(), state.target(), now)?; + if starts_new_cycle && state.needs_release_watcher() { + self.watcher.watch(state.id())?; + } + Ok(()) + } + + // Herdr does not fire `pane.focused` for every switch, so whatever the + // event was, the pane focused right now is recorded too. + pub fn observe_focus(&self, announced_pane: Option<&str>) -> anyhow::Result<()> { + let observed_at = self.clock.now_millis(); + let turn = self.store.begin_turn()?; + if self.cycle_caused_focus(&turn, observed_at) { + return Ok(()); + } + if let Some(pane_id) = announced_pane { + self.history.record(pane_id, observed_at)?; + } + if let Some(focused) = self.herdr.panes()?.focused() { + self.history.record(&focused.id, self.clock.now_millis())?; + } + Ok(()) + } + + /// Alt came up. Only ends the cycle the watcher was started for. + pub fn release(&self, id: CycleId) -> anyhow::Result<()> { + let turn = self.store.begin_turn()?; + match turn.load() { + Some(state) if state.id() == id => turn.save(&state.released(self.clock.now_millis())), + _ => Ok(()), + } + } + + // A focus the user caused ends the cycle. + fn cycle_caused_focus(&self, turn: &Turn, now: u64) -> bool { + let Some(state) = turn + .load() + .filter(|state| state.may_still_cause_focus_events(now)) + else { + return false; + }; + if self.moved_focus(&state) { + return true; + } + turn.clear(); + false + } + + // Focus that cannot be read is assumed to be the cycle's. Its events must + // stay out of history, or the panes it only passed through would reorder. + fn moved_focus(&self, state: &State) -> bool { + match self.herdr.panes() { + Ok(panes) => panes + .focused() + .is_none_or(|pane| state.has_visited(&pane.id)), + Err(_) => true, + } + } +} + +#[cfg(test)] +mod tests { + use super::state::{IDLE_MILLIS, RELEASE_GRACE_MILLIS}; + use crate::cycle::Direction::{Newer, Older}; + use crate::herdr::HerdrError; + use crate::test_support::Rig; + + #[test] + fn the_first_press_focuses_the_second_most_recent_pane() { + let rig = Rig::with_panes(&["A", "B", "C"]); + rig.press(Older).unwrap(); + + assert_eq!(rig.focused_pane(), "B"); + } + + #[test] + fn holding_alt_keeps_walking_back_however_long_the_pauses() { + let rig = Rig::with_panes(&["A", "B", "C"]); + rig.press(Older).unwrap(); + rig.pass_time(10_000); + rig.press(Older).unwrap(); + + assert_eq!(rig.focused_pane(), "C"); + } + + #[test] + fn newer_walks_forward_again() { + let rig = Rig::with_panes(&["A", "B", "C"]); + rig.press(Older).unwrap(); + rig.press(Older).unwrap(); + rig.press(Newer).unwrap(); + + assert_eq!(rig.focused_pane(), "B"); + } + + #[test] + fn tapping_letting_go_and_tapping_again_toggles_between_two_panes() { + let rig = Rig::with_panes(&["A", "B", "C"]); + rig.press(Older).unwrap(); + rig.release_alt(); + rig.press(Older).unwrap(); + + assert_eq!(rig.focused_pane(), "A"); + } + + #[test] + fn panes_passed_through_keep_their_place_in_history() { + let rig = Rig::with_panes(&["A", "B", "C"]); + rig.press(Older).unwrap(); + rig.press(Older).unwrap(); + + let order = rig.history_order(); + + assert_eq!(order, ["C", "A", "B"]); + } + + #[test] + fn a_cycle_started_from_an_untracked_pane_can_return_to_it() { + let rig = Rig::with_panes(&["A", "B"]); + rig.herdr.open("N"); + rig.user_focuses("N"); + rig.press(Older).unwrap(); + rig.press(Newer).unwrap(); + + assert_eq!(rig.focused_pane(), "N"); + } + + #[test] + fn a_cycle_begun_with_alt_held_gets_exactly_one_release_watcher() { + let rig = Rig::with_panes(&["A", "B", "C"]); + rig.press(Older).unwrap(); + rig.press(Older).unwrap(); + + assert_eq!(rig.watcher.started().len(), 1); + } + + #[test] + fn a_cycle_begun_without_alt_held_gets_no_release_watcher() { + let rig = Rig::with_panes(&["A", "B", "C"]); + rig.keyboard.set_alt(None); + rig.press(Older).unwrap(); + + assert!(rig.watcher.started().is_empty()); + } + + #[test] + fn a_release_for_an_earlier_cycle_leaves_the_current_one_running() { + let rig = Rig::with_panes(&["A", "B", "C"]); + rig.press(Older).unwrap(); + rig.cycle().release("4000".parse().unwrap()).unwrap(); + rig.press(Older).unwrap(); + + assert_eq!(rig.focused_pane(), "C"); + } + + #[test] + fn a_failed_focus_is_reported_as_the_herdr_error() { + let rig = Rig::with_panes(&["A", "B", "C"]); + rig.herdr.fail_focus(); + + let error = rig.press(Older).unwrap_err(); + + assert!(matches!( + error.downcast_ref::(), + Some(HerdrError::Rejected { .. }) + )); + } + + #[test] + fn a_failed_focus_ends_the_cycle() { + let rig = Rig::with_panes(&["A", "B", "C"]); + rig.herdr.fail_focus(); + let _ = rig.press(Older); + rig.herdr.allow_focus(); + rig.press(Older).unwrap(); + + assert_eq!(rig.focused_pane(), "B"); + } + + #[test] + fn with_no_panes_there_is_nothing_to_focus() { + let rig = Rig::with_panes(&[]); + rig.press(Older).unwrap(); + + assert!(rig.herdr.focus_requests().is_empty()); + } + + #[test] + fn moving_by_hand_puts_the_focused_pane_first_in_history() { + let rig = Rig::with_panes(&["A", "B", "C"]); + rig.user_focuses("C"); + rig.cycle().observe_focus(Some("C")).unwrap(); + + let order = rig.history_order(); + + assert_eq!(order, ["C", "A", "B"]); + } + + #[test] + fn the_focused_pane_is_recorded_even_when_the_event_names_none() { + let rig = Rig::with_panes(&["A", "B", "C"]); + rig.user_focuses("B"); + rig.cycle().observe_focus(None).unwrap(); + + let order = rig.history_order(); + + assert_eq!(order, ["B", "A", "C"]); + } + + #[test] + fn focus_a_cycle_caused_is_left_out_of_history() { + let rig = Rig::with_panes(&["A", "B", "C"]); + rig.press(Older).unwrap(); + rig.press(Older).unwrap(); + let history_after_cycle = rig.history_order(); + rig.pass_time(10); + rig.cycle().observe_focus(Some("B")).unwrap(); + + let history_after_hook = rig.history_order(); + + assert_eq!(history_after_hook, history_after_cycle); + } + + #[test] + fn moving_by_hand_during_a_cycle_ends_it_and_is_recorded() { + let rig = Rig::with_panes(&["A", "B", "C"]); + rig.press(Older).unwrap(); + rig.user_focuses("C"); + rig.cycle().observe_focus(Some("C")).unwrap(); + let recorded_first = rig.history_order()[0].clone(); + rig.press(Older).unwrap(); + + assert_eq!(recorded_first, "C"); + assert_eq!(rig.focused_pane(), "B"); + } + + #[test] + fn a_released_cycle_claims_focus_events_only_for_a_grace_period() { + let rig = Rig::with_panes(&["A", "B", "C"]); + rig.press(Older).unwrap(); + rig.press(Older).unwrap(); + rig.release_alt(); + let history_after_cycle = rig.history_order(); + + rig.pass_time(RELEASE_GRACE_MILLIS); + rig.cycle().observe_focus(Some("B")).unwrap(); + let within_grace = rig.history_order(); + rig.pass_time(1); + rig.cycle().observe_focus(Some("B")).unwrap(); + let after_grace = rig.history_order(); + + assert_eq!(within_grace, history_after_cycle); + assert_ne!(after_grace, history_after_cycle); + } + + #[test] + fn without_alt_a_cycle_claims_focus_events_only_until_it_goes_idle() { + let rig = Rig::with_panes(&["A", "B", "C"]); + rig.keyboard.set_alt(None); + rig.press(Older).unwrap(); + rig.press(Older).unwrap(); + let history_after_cycle = rig.history_order(); + + rig.pass_time(IDLE_MILLIS); + rig.cycle().observe_focus(Some("B")).unwrap(); + let while_active = rig.history_order(); + rig.pass_time(1); + rig.cycle().observe_focus(Some("B")).unwrap(); + let once_idle = rig.history_order(); + + assert_eq!(while_active, history_after_cycle); + assert_ne!(once_idle, history_after_cycle); + } +} diff --git a/src/cycle/state.rs b/src/cycle/state.rs new file mode 100644 index 0000000..b7c359e --- /dev/null +++ b/src/cycle/state.rs @@ -0,0 +1,285 @@ +use std::fmt; +use std::num::ParseIntError; +use std::str::FromStr; + +use serde::{Deserialize, Serialize}; + +use crate::history::Snapshot; + +// Only where the platform cannot tell when Alt comes up. +pub(super) const IDLE_MILLIS: u64 = 1500; +// A held cycle whose release watcher died still ends eventually. +pub const MAX_HOLD_MILLIS: u64 = 30_000; +// Hooks for the last stops may still be running just after Alt comes up. +pub(super) const RELEASE_GRACE_MILLIS: u64 = 500; + +/// Names one cycle, so a release watcher only ever ends the cycle it was started for. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct CycleId(u64); + +impl fmt::Display for CycleId { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + self.0.fmt(f) + } +} + +impl FromStr for CycleId { + type Err = ParseIntError; + + fn from_str(text: &str) -> Result { + text.parse().map(CycleId) + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Direction { + Older, + Newer, +} + +pub(super) struct Sighting { + pub(super) live_mru: Vec, + pub(super) focused_pane: Option, + pub(super) baseline: Snapshot, + pub(super) alt_held: bool, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub(super) struct State { + // Index 0 is the pane the cycle started from. + stops: Vec, + baseline: Snapshot, + cursor: usize, + visited: Vec, + last_press_at: u64, + alt_held_at_start: bool, + released_at: Option, + started_at: u64, +} + +impl State { + pub(super) fn ongoing(previous: Option, now: u64) -> Option { + previous.filter(|state| state.is_active(now)) + } + + pub(super) fn advance( + ongoing: Option, + sighting: Sighting, + direction: Direction, + now: u64, + ) -> Option { + let state = match ongoing { + Some(state) => state.without_closed_panes(&sighting.live_mru), + None => State::begin(sighting, now), + }; + state.step(direction, now) + } + + fn begin(sighting: Sighting, now: u64) -> State { + let mut stops = sighting.live_mru; + if let Some(focused) = sighting.focused_pane { + stops.retain(|pane_id| *pane_id != focused); + stops.insert(0, focused); + } + State { + stops, + baseline: sighting.baseline, + cursor: 0, + visited: Vec::new(), + last_press_at: now, + alt_held_at_start: sighting.alt_held, + released_at: None, + started_at: now, + } + } + + fn without_closed_panes(mut self, live: &[String]) -> State { + let is_live = |pane_id: &String| live.contains(pane_id); + let current = self.stops.get(self.cursor).cloned(); + let live_before_cursor = self.stops[..self.cursor.min(self.stops.len())] + .iter() + .filter(|pane_id| is_live(pane_id)) + .count(); + self.stops.retain(is_live); + self.cursor = match current { + Some(current) if self.stops.contains(¤t) => live_before_cursor, + _ => live_before_cursor.saturating_sub(1), + }; + self + } + + fn step(mut self, direction: Direction, now: u64) -> Option { + let count = self.stops.len(); + if count == 0 { + return None; + } + self.cursor = match direction { + Direction::Older => (self.cursor + 1) % count, + Direction::Newer => (self.cursor + count - 1) % count, + }; + self.visited.push(self.stops[self.cursor].clone()); + self.last_press_at = now; + Some(self) + } + + pub(super) fn released(self, now: u64) -> State { + State { + released_at: Some(now), + ..self + } + } + + pub(super) fn is_active(&self, now: u64) -> bool { + let since_press = now.saturating_sub(self.last_press_at); + if self.alt_held_at_start { + self.released_at.is_none() && since_press <= MAX_HOLD_MILLIS + } else { + since_press <= IDLE_MILLIS + } + } + + // Focus events the cycle caused must stay out of history, or the panes it + // only passed through would reorder. + pub(super) fn has_visited(&self, pane_id: &str) -> bool { + self.visited.iter().any(|visited| visited == pane_id) + } + + pub(super) fn may_still_cause_focus_events(&self, now: u64) -> bool { + self.is_active(now) + || self + .released_at + .is_some_and(|released| now.saturating_sub(released) <= RELEASE_GRACE_MILLIS) + } + + pub(super) fn needs_release_watcher(&self) -> bool { + self.alt_held_at_start + } + + pub(super) fn id(&self) -> CycleId { + CycleId(self.started_at) + } + + pub(super) fn baseline(&self) -> &Snapshot { + &self.baseline + } + + pub(super) fn target(&self) -> &str { + &self.stops[self.cursor] + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn ids(panes: &[&str]) -> Vec { + panes.iter().map(|id| id.to_string()).collect() + } + + // Focused on the most recently used pane, as when history is up to date. + fn see(panes: &[&str]) -> Sighting { + Sighting { + live_mru: ids(panes), + focused_pane: panes.first().map(|id| id.to_string()), + baseline: Snapshot::default(), + alt_held: false, + } + } + + fn see_with_alt_held(panes: &[&str]) -> Sighting { + Sighting { + alt_held: true, + ..see(panes) + } + } + + fn begin(panes: &[&str], direction: Direction) -> State { + State::advance(None, see(panes), direction, 5000).unwrap() + } + + fn press(state: State, panes: &[&str], direction: Direction, now: u64) -> State { + let ongoing = State::ongoing(Some(state), now); + State::advance(ongoing, see(panes), direction, now).unwrap() + } + + fn begin_holding_alt(panes: &[&str]) -> State { + State::advance(None, see_with_alt_held(panes), Direction::Older, 5000).unwrap() + } + + fn press_holding_alt(state: State, panes: &[&str], now: u64) -> State { + let ongoing = State::ongoing(Some(state), now); + State::advance(ongoing, see_with_alt_held(panes), Direction::Older, now).unwrap() + } + + #[test] + fn presses_within_the_idle_window_keep_stepping_older() { + let first = begin(&["A", "B", "C"], Direction::Older); + let second = press(first, &["B", "A", "C"], Direction::Older, 5100); + + assert_eq!(second.target(), "C"); + } + + #[test] + fn stepping_wraps_around_in_both_directions() { + let at_last = begin(&["A", "B", "C"], Direction::Newer); + let wrapped = press(at_last.clone(), &["C", "A", "B"], Direction::Older, 5100); + + assert_eq!(at_last.target(), "C"); + assert_eq!(wrapped.target(), "A"); + } + + #[test] + fn a_single_pane_stays_put() { + let state = begin(&["A"], Direction::Older); + + assert_eq!(state.target(), "A"); + } + + #[test] + fn a_press_after_the_idle_window_starts_a_fresh_cycle() { + let first = begin(&["A", "B", "C"], Direction::Older); + let later = press( + first, + &["B", "A", "C"], + Direction::Older, + 5000 + IDLE_MILLIS + 1, + ); + + assert_eq!(later.target(), "A"); + } + + #[test] + fn the_origin_is_the_focused_pane_even_when_history_lags() { + let lagging = Sighting { + focused_pane: Some("B".to_string()), + ..see(&["A", "B", "C"]) + }; + let state = State::advance(None, lagging, Direction::Older, 5000).unwrap(); + + assert_eq!(state.target(), "A"); + } + + #[test] + fn a_pane_closed_mid_cycle_is_never_targeted() { + let first = begin(&["A", "B", "C"], Direction::Older); + let second = press(first, &["A", "B"], Direction::Older, 5100); + + assert_eq!(second.target(), "A"); + } + + #[test] + fn closing_the_current_stop_continues_from_its_neighbour() { + let first = begin(&["A", "B", "C"], Direction::Older); + let second = press(first, &["A", "C"], Direction::Older, 5100); + + assert_eq!(second.target(), "C"); + } + + #[test] + fn a_held_cycle_whose_watcher_vanished_expires_eventually() { + let first = begin_holding_alt(&["A", "B", "C"]); + let much_later = press_holding_alt(first, &["B", "A", "C"], 5000 + MAX_HOLD_MILLIS + 1); + + assert_eq!(much_later.target(), "A"); + } +} diff --git a/src/cycle/store.rs b/src/cycle/store.rs new file mode 100644 index 0000000..dfd4399 --- /dev/null +++ b/src/cycle/store.rs @@ -0,0 +1,42 @@ +use crate::lock::{Held, Lock}; +use crate::state_file::StateFile; + +use super::state::State; + +pub(super) struct Store { + file: StateFile, + lock: Lock, +} + +impl Store { + pub(super) fn new(file: StateFile, lock: Lock) -> Self { + Self { file, lock } + } + + /// The only way to read or change the saved state, so nobody does it unlocked. + pub(super) fn begin_turn(&self) -> std::io::Result> { + Ok(Turn { + store: self, + _held: self.lock.acquire()?, + }) + } +} + +pub(super) struct Turn<'a> { + store: &'a Store, + _held: Held, +} + +impl Turn<'_> { + pub(super) fn load(&self) -> Option { + serde_json::from_str(&self.store.file.read()?).ok() + } + + pub(super) fn save(&self, state: &State) -> anyhow::Result<()> { + Ok(self.store.file.write(&serde_json::to_string(state)?)?) + } + + pub(super) fn clear(&self) { + self.store.file.remove(); + } +} diff --git a/src/cycler.rs b/src/cycler.rs deleted file mode 100644 index 01596d1..0000000 --- a/src/cycler.rs +++ /dev/null @@ -1,203 +0,0 @@ -use crate::clock::Clock; -use crate::herdr::{Herdr, Panes}; -use crate::history::{History, Visit}; -use crate::keyboard::Keyboard; -use crate::release::ReleaseWatcher; -use crate::session::{Direction, Session, Sighting}; -use crate::session_store::SessionStore; - -pub struct Cycler<'a> { - pub herdr: &'a dyn Herdr, - pub keyboard: &'a dyn Keyboard, - pub watcher: &'a dyn ReleaseWatcher, - pub history: &'a History, - pub sessions: &'a SessionStore, - pub clock: &'a dyn Clock, -} - -impl Cycler<'_> { - pub fn press(&self, direction: Direction) -> anyhow::Result<()> { - let _turn = self.sessions.lock()?; - let now = self.clock.now_millis(); - - let panes = self.herdr.panes()?; - let visits = self.history.visits(); - let sighting = Sighting { - live_mru: live_panes_by_recency(&panes, &visits), - focused_pane: panes.focused().map(|pane| pane.id.clone()), - baseline: visits, - alt_held: self.keyboard.alt_held() == Some(true), - }; - - let ongoing = Session::ongoing(self.sessions.load(), now); - let starts_new_cycle = ongoing.is_none(); - let Some(session) = Session::advance(ongoing, sighting, direction, now) else { - return Ok(()); - }; - - // Saved before focusing so the track hook, which takes the same lock, - // can tell the focus events that follow are ours. - self.sessions.save(&session)?; - if let Err(error) = self.herdr.focus(session.target()) { - self.sessions.clear(); - return Err(error.into()); - } - self.history - .promote_after_cycle(session.baseline(), session.target(), now)?; - if starts_new_cycle && session.needs_release_watcher() { - self.watcher.watch(session.started_at())?; - } - Ok(()) - } -} - -fn live_panes_by_recency(panes: &Panes, visits: &[Visit]) -> Vec { - let mut by_recency: Vec = visits - .iter() - .map(|visit| visit.pane_id.clone()) - .filter(|pane_id| panes.contains(pane_id)) - .collect(); - let never_focused: Vec = panes - .ids() - .filter(|pane_id| !by_recency.iter().any(|known| known == pane_id)) - .map(String::from) - .collect(); - by_recency.extend(never_focused); - by_recency -} - -#[cfg(test)] -mod tests { - use crate::herdr::HerdrError; - use crate::session::Direction::{Newer, Older}; - use crate::test_support::Rig; - - #[test] - fn the_first_press_focuses_the_second_most_recent_pane() { - let rig = Rig::with_panes(&["A", "B", "C"]); - rig.press(Older).unwrap(); - - assert_eq!(rig.focused_pane(), "B"); - } - - #[test] - fn holding_alt_keeps_walking_back_however_long_the_pauses() { - let rig = Rig::with_panes(&["A", "B", "C"]); - rig.press(Older).unwrap(); - rig.pass_time(10_000); - rig.press(Older).unwrap(); - - assert_eq!(rig.focused_pane(), "C"); - } - - #[test] - fn newer_walks_forward_again() { - let rig = Rig::with_panes(&["A", "B", "C"]); - rig.press(Older).unwrap(); - rig.press(Older).unwrap(); - rig.press(Newer).unwrap(); - - assert_eq!(rig.focused_pane(), "B"); - } - - #[test] - fn tapping_letting_go_and_tapping_again_toggles_between_two_panes() { - let rig = Rig::with_panes(&["A", "B", "C"]); - rig.press(Older).unwrap(); - rig.release_alt(); - rig.press(Older).unwrap(); - - assert_eq!(rig.focused_pane(), "A"); - } - - #[test] - fn panes_passed_through_keep_their_place_in_history() { - let rig = Rig::with_panes(&["A", "B", "C"]); - rig.press(Older).unwrap(); - rig.press(Older).unwrap(); - - let order = rig.history_order(); - - assert_eq!(order, ["C", "A", "B"]); - } - - #[test] - fn panes_closed_since_they_were_last_focused_are_skipped() { - let rig = Rig::with_panes(&["A", "B", "C"]); - rig.herdr.close("B"); - rig.press(Older).unwrap(); - - assert_eq!(rig.focused_pane(), "C"); - } - - #[test] - fn a_pane_never_focused_since_install_comes_after_every_known_pane() { - let rig = Rig::with_panes(&["A", "B"]); - rig.herdr.open("N"); - rig.press(Older).unwrap(); - rig.press(Older).unwrap(); - - assert_eq!(rig.focused_pane(), "N"); - } - - #[test] - fn a_cycle_started_from_an_untracked_pane_can_return_to_it() { - let rig = Rig::with_panes(&["A", "B"]); - rig.herdr.open("N"); - rig.user_focuses("N"); - rig.press(Older).unwrap(); - rig.press(Newer).unwrap(); - - assert_eq!(rig.focused_pane(), "N"); - } - - #[test] - fn a_cycle_begun_with_alt_held_gets_exactly_one_release_watcher() { - let rig = Rig::with_panes(&["A", "B", "C"]); - rig.press(Older).unwrap(); - rig.press(Older).unwrap(); - - assert_eq!(rig.watcher.started().len(), 1); - } - - #[test] - fn a_cycle_begun_without_alt_held_gets_no_release_watcher() { - let rig = Rig::with_panes(&["A", "B", "C"]); - rig.keyboard.set_alt(None); - rig.press(Older).unwrap(); - - assert!(rig.watcher.started().is_empty()); - } - - #[test] - fn a_failed_focus_is_reported_as_the_herdr_error() { - let rig = Rig::with_panes(&["A", "B", "C"]); - rig.herdr.fail_focus(); - - let error = rig.press(Older).unwrap_err(); - - assert!(matches!( - error.downcast_ref::(), - Some(HerdrError::Rejected { .. }) - )); - } - - #[test] - fn a_failed_focus_ends_the_cycle() { - let rig = Rig::with_panes(&["A", "B", "C"]); - rig.herdr.fail_focus(); - let _ = rig.press(Older); - - let session = rig.sessions.load(); - - assert!(session.is_none()); - } - - #[test] - fn with_no_panes_there_is_nothing_to_focus() { - let rig = Rig::with_panes(&[]); - rig.press(Older).unwrap(); - - assert!(rig.herdr.focus_requests().is_empty()); - } -} diff --git a/src/environment.rs b/src/environment.rs new file mode 100644 index 0000000..449ea38 --- /dev/null +++ b/src/environment.rs @@ -0,0 +1,135 @@ +use std::ffi::OsString; +use std::path::{Path, PathBuf}; + +/// Everything the plugin reads from the process environment, read once. +pub struct Environment { + pub state_dir: PathBuf, + pub socket_path: Option, + pub herdr_bin: String, + /// Where Herdr loads its config from, if it loads one and we can tell. + pub config_path: Option, + pub event_json: Option, +} + +impl Environment { + pub fn from_process() -> Self { + Self::from_lookup(|name| std::env::var_os(name)) + } + + fn from_lookup(get: impl Fn(&str) -> Option) -> Self { + let text = |name: &str| get(name).and_then(|value| value.into_string().ok()); + // Herdr hands us an empty variable where it means "not set". + let filled = |name: &str| text(name).filter(|value| !value.is_empty()); + Self { + state_dir: get("HERDR_PLUGIN_STATE_DIR") + .map(PathBuf::from) + .unwrap_or_else(|| std::env::temp_dir().join("herdr-alt-tab")), + socket_path: filled("HERDR_SOCKET_PATH"), + herdr_bin: filled("HERDR_BIN_PATH").unwrap_or_else(|| "herdr".to_string()), + config_path: config_path( + text("HERDR_CONFIG_PATH"), + filled("XDG_CONFIG_HOME"), + filled("HOME"), + ), + event_json: text("HERDR_PLUGIN_EVENT_JSON"), + } + } +} + +/// Herdr's own lookup order. An explicitly empty path means it loads no config. +fn config_path( + explicit: Option, + xdg_config_home: Option, + home: Option, +) -> Option { + if let Some(explicit) = explicit { + return Some(PathBuf::from(explicit)).filter(|path| !path.as_os_str().is_empty()); + } + xdg_config_home + .map(|xdg| Path::new(&xdg).join("herdr/config.toml")) + .or_else(|| home.map(|home| Path::new(&home).join(".config/herdr/config.toml"))) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::collections::HashMap; + + fn some(text: &str) -> Option { + Some(text.to_string()) + } + + fn environment_of(vars: &[(&str, &str)]) -> Environment { + let vars: HashMap = vars + .iter() + .map(|(name, value)| (name.to_string(), OsString::from(value))) + .collect(); + Environment::from_lookup(|name| vars.get(name).cloned()) + } + + #[test] + fn variables_are_read_as_given() { + let environment = environment_of(&[ + ("HERDR_PLUGIN_STATE_DIR", "/state"), + ("HERDR_SOCKET_PATH", "/run/herdr.sock"), + ("HERDR_BIN_PATH", "/opt/herdr"), + ("HERDR_PLUGIN_EVENT_JSON", "{}"), + ]); + + assert_eq!(environment.state_dir, PathBuf::from("/state")); + assert_eq!(environment.socket_path.as_deref(), Some("/run/herdr.sock")); + assert_eq!(environment.herdr_bin, "/opt/herdr"); + assert_eq!(environment.event_json.as_deref(), Some("{}")); + } + + #[test] + fn unset_or_empty_variables_fall_back_to_defaults() { + let environment = environment_of(&[("HERDR_SOCKET_PATH", ""), ("HERDR_BIN_PATH", "")]); + + assert_eq!(environment.socket_path, None); + assert_eq!(environment.herdr_bin, "herdr"); + assert_eq!( + environment.state_dir, + std::env::temp_dir().join("herdr-alt-tab") + ); + assert_eq!(environment.event_json, None); + } + + #[test] + fn an_explicit_path_wins() { + let found = config_path(some("/x/c.toml"), some("/xdg"), some("/home/me")); + + assert_eq!(found, Some(PathBuf::from("/x/c.toml"))); + } + + #[test] + fn without_an_explicit_path_xdg_config_home_wins() { + let found = config_path(None, some("/xdg"), some("/home/me")); + + assert_eq!(found, Some(PathBuf::from("/xdg/herdr/config.toml"))); + } + + #[test] + fn otherwise_the_home_directory_is_used() { + let found = config_path(None, None, some("/home/me")); + + assert_eq!( + found, + Some(PathBuf::from("/home/me/.config/herdr/config.toml")) + ); + } + + #[test] + fn an_empty_explicit_path_means_herdr_loads_no_config() { + let found = config_path(some(""), some("/xdg"), some("/home/me")); + + assert_eq!(found, None); + } + + #[test] + fn nothing_to_go_on_means_no_config_path() { + let environment = environment_of(&[]); + + assert_eq!(environment.config_path, None); + } +} diff --git a/src/focus_event.rs b/src/focus_event.rs new file mode 100644 index 0000000..97f767c --- /dev/null +++ b/src/focus_event.rs @@ -0,0 +1,53 @@ +use serde::Deserialize; + +const PANE_FOCUSED_EVENT: &str = "pane_focused"; + +#[derive(Deserialize)] +struct HookEvent { + event: String, + #[serde(default)] + data: HookEventData, +} + +#[derive(Deserialize, Default)] +struct HookEventData { + pane_id: Option, +} + +pub fn announced_pane(event_json: &str) -> Result, serde_json::Error> { + let event: HookEvent = serde_json::from_str(event_json)?; + Ok(event + .data + .pane_id + .filter(|_| event.event == PANE_FOCUSED_EVENT)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_pane_focused_event_names_its_pane() { + let event = r#"{"event":"pane_focused","data":{"pane_id":"p1","workspace_id":"w1"}}"#; + + let pane = announced_pane(event).unwrap(); + + assert_eq!(pane.as_deref(), Some("p1")); + } + + #[test] + fn other_events_name_no_pane() { + let event = r#"{"event":"workspace_focused","data":{"workspace_id":"w1"}}"#; + + let pane = announced_pane(event).unwrap(); + + assert_eq!(pane, None); + } + + #[test] + fn a_malformed_event_is_a_json_syntax_error() { + let error = announced_pane("not json").unwrap_err(); + + assert!(error.is_syntax()); + } +} diff --git a/src/herdr.rs b/src/herdr.rs index 25b090f..15f97e3 100644 --- a/src/herdr.rs +++ b/src/herdr.rs @@ -1,4 +1,4 @@ -pub mod binary; +mod binary; mod socket; use std::io; @@ -6,7 +6,7 @@ use std::io; use serde::Deserialize; use serde::de::DeserializeOwned; -use crate::connection::Connection; +use crate::environment::Environment; use binary::HerdrBinary; use socket::Socket; @@ -33,16 +33,17 @@ pub struct Pane { #[derive(Debug, Clone, Deserialize)] pub struct Panes { - pub(crate) panes: Vec, + panes: Vec, } impl Panes { - pub fn focused(&self) -> Option<&Pane> { - self.panes.iter().find(|pane| pane.focused) + #[cfg(test)] + pub fn new(panes: Vec) -> Self { + Self { panes } } - pub fn contains(&self, pane_id: &str) -> bool { - self.panes.iter().any(|pane| pane.id == pane_id) + pub fn focused(&self) -> Option<&Pane> { + self.panes.iter().find(|pane| pane.focused) } pub fn ids(&self) -> impl Iterator { @@ -55,6 +56,16 @@ pub trait Herdr { fn focus(&self, pane_id: &str) -> Result<(), HerdrError>; } +#[derive(Debug, thiserror::Error)] +#[error("`herdr config check` did not pass")] +pub struct CheckFailed; + +/// The config as the running Herdr sees it. +pub trait LiveConfig { + fn check(&self) -> Result<(), CheckFailed>; + fn reload(&self); +} + enum Request<'a> { ListPanes, FocusPane(&'a str), @@ -99,11 +110,16 @@ impl Herdr for Fallback { } } +/// Only the binary can check and reload the config. +pub fn live_config(environment: &Environment) -> impl LiveConfig { + HerdrBinary::at(environment.herdr_bin.clone()) +} + /// The socket is faster; the binary answers when the socket cannot. -pub fn connect(connection: &Connection) -> impl Herdr { +pub fn connect(environment: &Environment) -> impl Herdr { Fallback { - primary: connection.socket_path().map(Socket::at), - secondary: HerdrBinary::from_env(), + primary: environment.socket_path.as_deref().map(Socket::at), + secondary: HerdrBinary::at(environment.herdr_bin.clone()), } } @@ -169,24 +185,6 @@ mod tests { assert_eq!(focused, Some("p2")); } - #[test] - fn panes_contain_the_ids_they_list() { - let panes = two_panes_focused_on_the_second(); - - let contains = panes.contains("p1"); - - assert!(contains); - } - - #[test] - fn panes_do_not_contain_other_ids() { - let panes = two_panes_focused_on_the_second(); - - let contains = panes.contains("p3"); - - assert!(!contains); - } - #[test] fn the_primary_answers_when_it_can() { let herdr = Fallback { diff --git a/src/herdr/binary.rs b/src/herdr/binary.rs index 820b294..d3055ea 100644 --- a/src/herdr/binary.rs +++ b/src/herdr/binary.rs @@ -2,23 +2,18 @@ use std::process::Command; use serde_json::Value; -use super::{HerdrError, Request, Transport}; -use crate::herdr_env; +use super::{CheckFailed, HerdrError, LiveConfig, Request, Transport}; pub struct HerdrBinary { path: String, } impl HerdrBinary { - pub fn from_env() -> Self { - Self::at(herdr_env::var("HERDR_BIN_PATH").unwrap_or_else(|| "herdr".to_string())) - } - - fn at(path: String) -> Self { + pub(super) fn at(path: String) -> Self { Self { path } } - pub fn run(&self, args: &[&str]) -> Result { + fn run(&self, args: &[&str]) -> Result { let output = Command::new(&self.path).args(args).output()?; if !output.status.success() { return Err(HerdrError::Rejected { @@ -44,6 +39,19 @@ impl Transport for HerdrBinary { } } +impl LiveConfig for HerdrBinary { + fn check(&self) -> Result<(), CheckFailed> { + self.run(&["config", "check"]) + .map(drop) + .map_err(|_| CheckFailed) + } + + fn reload(&self) { + // Without a running Herdr the keys are live from its next start. + let _ = self.run(&["server", "reload-config"]); + } +} + #[cfg(test)] mod tests { use super::*; @@ -120,4 +128,34 @@ mod tests { assert!(matches!(error, HerdrError::Io(_))); } + + #[test] + fn a_config_check_passes_when_herdr_exits_cleanly() { + let dir = TempDir::new().unwrap(); + let herdr = herdr_running(&dir, "exit 0"); + + assert!(herdr.check().is_ok()); + } + + #[test] + fn a_config_check_fails_when_herdr_exits_with_an_error() { + let dir = TempDir::new().unwrap(); + let herdr = herdr_running(&dir, "echo bad config >&2; exit 1"); + + assert!(herdr.check().is_err()); + } + + #[test] + fn a_reload_is_asked_for_and_a_failed_one_is_ignored() { + let dir = TempDir::new().unwrap(); + let log = dir.path().join("args"); + let herdr = herdr_running(&dir, &format!("echo \"$@\" > {}; exit 1", log.display())); + + herdr.reload(); + + assert_eq!( + std::fs::read_to_string(log).unwrap().trim(), + "server reload-config" + ); + } } diff --git a/src/herdr_env.rs b/src/herdr_env.rs deleted file mode 100644 index fcb20b9..0000000 --- a/src/herdr_env.rs +++ /dev/null @@ -1,3 +0,0 @@ -pub fn var(name: &str) -> Option { - std::env::var(name).ok().filter(|value| !value.is_empty()) -} diff --git a/src/history.rs b/src/history.rs index a6c0901..4f92538 100644 --- a/src/history.rs +++ b/src/history.rs @@ -2,6 +2,7 @@ use std::cmp::Reverse; use serde::{Deserialize, Serialize}; +use crate::lock::Lock; use crate::state_file::StateFile; const MAX_VISITS: usize = 300; @@ -9,21 +10,32 @@ const MAX_VISITS: usize = 300; const MAX_HOOK_LAG_MILLIS: u64 = 60_000; #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -pub struct Visit { - pub pane_id: String, - pub focused_at: u64, +struct Visit { + pane_id: String, + focused_at: u64, +} + +/// What history looked like when a cycle began. +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +pub struct Snapshot(Vec); + +pub struct Recency { + /// Live panes, most recently focused first; never-focused panes come last. + pub live: Vec, + pub snapshot: Snapshot, } pub struct History { file: StateFile, + lock: Lock, } impl History { - pub fn new(file: StateFile) -> Self { - Self { file } + pub fn new(file: StateFile, lock: Lock) -> Self { + Self { file, lock } } - pub fn visits(&self) -> Vec { + fn visits(&self) -> Vec { let mut visits: Vec = self .file .read() @@ -33,10 +45,38 @@ impl History { visits } + pub fn recency_of<'a>(&self, live: impl IntoIterator) -> Recency { + let visits = self.visits(); + let live: Vec<&str> = live.into_iter().collect(); + let mut by_recency: Vec = visits + .iter() + .map(|visit| visit.pane_id.clone()) + .filter(|pane_id| live.contains(&pane_id.as_str())) + .collect(); + let never_focused: Vec = live + .iter() + .filter(|pane_id| !by_recency.iter().any(|known| known == *pane_id)) + .map(|pane_id| pane_id.to_string()) + .collect(); + by_recency.extend(never_focused); + Recency { + live: by_recency, + snapshot: Snapshot(visits), + } + } + + #[cfg(test)] + pub fn order(&self) -> Vec { + self.visits() + .into_iter() + .map(|visit| visit.pane_id) + .collect() + } + // Hooks run concurrently and finish out of order, so `observed_at` decides // where the pane lands, not the order in which hooks get here. pub fn record(&self, pane_id: &str, observed_at: u64) -> anyhow::Result<()> { - let _turn = self.file.lock()?; + let _turn = self.lock.acquire()?; let mut visits = self.visits(); let observed_at = unless_clock_stepped_back(observed_at, &visits); if has_later_visit(&visits, pane_id, observed_at) { @@ -58,14 +98,14 @@ impl History { /// was taken, however many panes a cycle passed through on the way. pub fn promote_after_cycle( &self, - baseline: &[Visit], + baseline: &Snapshot, promoted: &str, promoted_at: u64, ) -> anyhow::Result<()> { - let _turn = self.file.lock()?; + let _turn = self.lock.acquire()?; let mut visits = self.visits(); for visit in &mut visits { - if let Some(before) = baseline.iter().find(|b| b.pane_id == visit.pane_id) { + if let Some(before) = baseline.0.iter().find(|b| b.pane_id == visit.pane_id) { visit.focused_at = before.focused_at; } } @@ -116,7 +156,10 @@ mod tests { use tempfile::TempDir; fn history_in(dir: &TempDir) -> History { - History::new(StateFile::at(dir.path().join("history.json"))) + History::new( + StateFile::at(dir.path().join("history.json")), + Lock::at(dir.path().join("history.lock")), + ) } fn pane_ids(history: &History) -> Vec { @@ -237,7 +280,7 @@ mod tests { r#"[{"pane_id":"B","focused_at":1},{"pane_id":"C","focused_at":3},{"pane_id":"A","focused_at":0}]"#, ) .unwrap(); - let history = History::new(file); + let history = History::new(file, Lock::at(dir.path().join("history.lock"))); history.record("D", 2).unwrap(); let order = pane_ids(&history); @@ -264,7 +307,7 @@ mod tests { let dir = TempDir::new().unwrap(); let file = StateFile::at(dir.path().join("history.json")); file.write("{{{").unwrap(); - let history = History::new(file); + let history = History::new(file, Lock::at(dir.path().join("history.lock"))); let visits = history.visits(); @@ -283,7 +326,7 @@ mod tests { fn panes_a_cycle_passed_through_keep_their_original_order() { let dir = TempDir::new().unwrap(); let history = history_of_three(&dir); - let baseline = history.visits(); + let baseline = history.recency_of([]).snapshot; history.promote_after_cycle(&baseline, "B", 100).unwrap(); history.promote_after_cycle(&baseline, "A", 200).unwrap(); @@ -299,7 +342,7 @@ mod tests { let now = 10_000_000; history.record("A", now).unwrap(); history.record("B", now - 1).unwrap(); - let baseline = history.visits(); + let baseline = history.recency_of([]).snapshot; history .promote_after_cycle(&baseline, "B", now - 5_000_000) .unwrap(); @@ -313,11 +356,24 @@ mod tests { fn promoting_a_pane_with_no_history_adds_it_at_the_front() { let dir = TempDir::new().unwrap(); let history = history_of_three(&dir); - let baseline = history.visits(); + let baseline = history.recency_of([]).snapshot; history.promote_after_cycle(&baseline, "X", 100).unwrap(); let order = pane_ids(&history); assert_eq!(order, ["X", "C", "B", "A"]); } + + #[test] + fn live_panes_come_newest_first_with_never_focused_ones_last() { + let dir = TempDir::new().unwrap(); + let history = history_in(&dir); + history.record("A", 1).unwrap(); + history.record("B", 2).unwrap(); + history.record("closed", 3).unwrap(); + + let recency = history.recency_of(["new", "A", "B"]); + + assert_eq!(recency.live, ["B", "A", "new"]); + } } diff --git a/src/keys.rs b/src/keys.rs index bdf39e1..6e83f72 100644 --- a/src/keys.rs +++ b/src/keys.rs @@ -1,6 +1,4 @@ mod block; -mod config_path; mod editor; -mod live_config; pub use editor::ConfigEditor; diff --git a/src/keys/config_path.rs b/src/keys/config_path.rs deleted file mode 100644 index d4b3faf..0000000 --- a/src/keys/config_path.rs +++ /dev/null @@ -1,72 +0,0 @@ -use std::path::{Path, PathBuf}; - -use crate::herdr_env; - -pub fn from_env() -> Option { - resolve( - std::env::var("HERDR_CONFIG_PATH").ok(), - herdr_env::var("XDG_CONFIG_HOME"), - herdr_env::var("HOME"), - ) -} - -/// Herdr's own lookup order. An explicitly empty path means it loads no config. -fn resolve( - explicit: Option, - xdg_config_home: Option, - home: Option, -) -> Option { - if let Some(explicit) = explicit { - return Some(PathBuf::from(explicit)).filter(|path| !path.as_os_str().is_empty()); - } - xdg_config_home - .map(|xdg| Path::new(&xdg).join("herdr/config.toml")) - .or_else(|| home.map(|home| Path::new(&home).join(".config/herdr/config.toml"))) -} - -#[cfg(test)] -mod tests { - use super::*; - - fn some(text: &str) -> Option { - Some(text.to_string()) - } - - #[test] - fn an_explicit_path_wins() { - let found = resolve(some("/x/c.toml"), some("/xdg"), some("/home/me")); - - assert_eq!(found, Some(PathBuf::from("/x/c.toml"))); - } - - #[test] - fn without_an_explicit_path_xdg_config_home_wins() { - let found = resolve(None, some("/xdg"), some("/home/me")); - - assert_eq!(found, Some(PathBuf::from("/xdg/herdr/config.toml"))); - } - - #[test] - fn otherwise_the_home_directory_is_used() { - let found = resolve(None, None, some("/home/me")); - - assert_eq!( - found, - Some(PathBuf::from("/home/me/.config/herdr/config.toml")) - ); - } - - #[test] - fn an_empty_explicit_path_means_herdr_loads_no_config() { - let found = resolve(some(""), some("/xdg"), some("/home/me")); - - assert_eq!(found, None); - } - - #[test] - fn nothing_to_go_on_means_no_path() { - let found = resolve(None, None, None); - - assert_eq!(found, None); - } -} diff --git a/src/keys/editor.rs b/src/keys/editor.rs index dc2a6a1..2d241a9 100644 --- a/src/keys/editor.rs +++ b/src/keys/editor.rs @@ -2,9 +2,10 @@ use std::io; use std::path::PathBuf; use super::block::{with_bindings, without_bindings}; -use super::config_path; -use super::live_config::LiveConfig; use crate::connection::Connection; +use crate::environment::Environment; +use crate::herdr::LiveConfig; +use crate::lock::Lock; use crate::state_file::StateFile; #[derive(Debug, thiserror::Error)] @@ -21,18 +22,22 @@ pub enum KeysError { pub struct ConfigEditor<'a> { config_path: PathBuf, - lock: StateFile, + lock: Lock, herdr: &'a dyn LiveConfig, } impl<'a> ConfigEditor<'a> { - pub fn for_connection( + pub fn new( + environment: &Environment, connection: &Connection, herdr: &'a dyn LiveConfig, ) -> Result { Ok(Self { - config_path: config_path::from_env().ok_or(KeysError::ConfigPathUnknown)?, - lock: connection.state_file("keys"), + config_path: environment + .config_path + .clone() + .ok_or(KeysError::ConfigPathUnknown)?, + lock: connection.lock("keys"), herdr, }) } @@ -47,7 +52,7 @@ impl<'a> ConfigEditor<'a> { // Writes through a symlinked config, and puts the original back if Herdr rejects the result. fn rewrite(&self, transform: fn(&str) -> String) -> Result<(), KeysError> { - let _turn = self.lock.lock()?; + let _turn = self.lock.acquire()?; let config = StateFile::at( std::fs::canonicalize(&self.config_path).unwrap_or_else(|_| self.config_path.clone()), ); @@ -76,8 +81,8 @@ impl<'a> ConfigEditor<'a> { #[cfg(test)] mod tests { - use super::super::live_config::CheckFailed; use super::*; + use crate::herdr::CheckFailed; use std::cell::Cell; use std::fs; use std::path::Path; @@ -125,7 +130,7 @@ mod tests { fn editor<'a>(dir: &TempDir, config: &Path, herdr: &'a FakeLiveConfig) -> ConfigEditor<'a> { ConfigEditor { config_path: config.to_path_buf(), - lock: StateFile::at(dir.path().join("state").join("keys.json")), + lock: Lock::at(dir.path().join("state").join("keys.lock")), herdr, } } diff --git a/src/keys/live_config.rs b/src/keys/live_config.rs deleted file mode 100644 index 50d4097..0000000 --- a/src/keys/live_config.rs +++ /dev/null @@ -1,24 +0,0 @@ -use crate::herdr::binary::HerdrBinary; - -#[derive(Debug, thiserror::Error)] -#[error("`herdr config check` did not pass")] -pub struct CheckFailed; - -/// The config as the running Herdr sees it. -pub trait LiveConfig { - fn check(&self) -> Result<(), CheckFailed>; - fn reload(&self); -} - -impl LiveConfig for HerdrBinary { - fn check(&self) -> Result<(), CheckFailed> { - self.run(&["config", "check"]) - .map(drop) - .map_err(|_| CheckFailed) - } - - fn reload(&self) { - // Without a running Herdr the keys are live from its next start. - let _ = self.run(&["server", "reload-config"]); - } -} diff --git a/src/lock.rs b/src/lock.rs new file mode 100644 index 0000000..725e9d5 --- /dev/null +++ b/src/lock.rs @@ -0,0 +1,54 @@ +use std::fs::{self, File, OpenOptions}; +use std::io; +use std::path::PathBuf; + +use fs2::FileExt; + +/// Excludes other Herdr Alt-Tab processes for as long as the guard is held. +pub struct Lock { + path: PathBuf, +} + +pub struct Held { + _file: File, +} + +impl Lock { + pub fn at(path: PathBuf) -> Self { + Self { path } + } + + pub fn acquire(&self) -> io::Result { + if let Some(parent) = self.path.parent() { + fs::create_dir_all(parent)?; + } + let file = OpenOptions::new() + .create(true) + .truncate(false) + .write(true) + .open(&self.path)?; + file.lock_exclusive()?; + Ok(Held { _file: file }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use tempfile::TempDir; + + #[test] + fn the_lock_excludes_others_until_its_guard_drops() { + let dir = TempDir::new().unwrap(); + let path = dir.path().join("nested").join("state.lock"); + let held = Lock::at(path.clone()).acquire().unwrap(); + let rival = || OpenOptions::new().write(true).open(&path).unwrap(); + + let while_held = rival().try_lock_exclusive(); + drop(held); + let after_drop = rival().try_lock_exclusive(); + + assert!(while_held.is_err()); + assert!(after_drop.is_ok()); + } +} diff --git a/src/main.rs b/src/main.rs index eb3b47a..0f7cd50 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,17 +1,16 @@ mod clock; mod command; mod connection; -mod cycler; +mod cycle; +mod environment; +mod focus_event; mod herdr; -mod herdr_env; mod history; mod keyboard; mod keys; +mod lock; mod release; -mod session; -mod session_store; mod state_file; -mod track; #[cfg(test)] mod test_support; @@ -21,57 +20,58 @@ use anyhow::Context; use clock::SystemClock; use command::Command; use connection::Connection; -use cycler::Cycler; -use herdr::binary::HerdrBinary; +use cycle::{Collaborators, Cycle}; +use environment::Environment; use history::History; use keyboard::SystemKeyboard; use keys::ConfigEditor; use release::{DetachedWatcher, ReleaseWaiter}; -use session_store::SessionStore; -use track::Tracker; fn main() -> anyhow::Result<()> { let args: Vec = std::env::args().skip(1).collect(); let command = Command::parse(&args).context(Command::USAGE)?; - let connection = Connection::from_env(); - let history = History::new(connection.state_file("history")); - let sessions = SessionStore::new(connection.state_file("session")); - - match command { - Command::Press(direction) => Cycler { - herdr: &herdr::connect(&connection), + let environment = Environment::from_process(); + let connection = Connection::from_environment(&environment); + let history = History::new(connection.state_file("history"), connection.lock("history")); + let herdr = herdr::connect(&environment); + let cycle = Cycle::new( + &connection, + Collaborators { + herdr: &herdr, keyboard: &SystemKeyboard, watcher: &DetachedWatcher, history: &history, - sessions: &sessions, clock: &SystemClock, - } - .press(direction), + }, + ); + + match command { + Command::Press(direction) => cycle.press(direction), Command::Track => { - let event_json = std::env::var("HERDR_PLUGIN_EVENT_JSON") + let event_json = environment + .event_json + .as_deref() .context("HERDR_PLUGIN_EVENT_JSON is not set")?; - Tracker { - herdr: &herdr::connect(&connection), - history: &history, - sessions: &sessions, - clock: &SystemClock, - } - .track(track::announced_pane(&event_json)?.as_deref()) + cycle.observe_focus(focus_event::announced_pane(event_json)?.as_deref()) } - Command::Watch { started_at } => ReleaseWaiter { + Command::Watch { cycle: id } => ReleaseWaiter { keyboard: &SystemKeyboard, - sessions: &sessions, + cycle: &cycle, clock: &SystemClock, } - .wait(started_at), + .wait(id), Command::SetupKeys => { - let binary = HerdrBinary::from_env(); - Ok(ConfigEditor::for_connection(&connection, &binary)?.bind()?) + Ok( + ConfigEditor::new(&environment, &connection, &herdr::live_config(&environment))? + .bind()?, + ) } Command::RemoveKeys => { - let binary = HerdrBinary::from_env(); - Ok(ConfigEditor::for_connection(&connection, &binary)?.unbind()?) + Ok( + ConfigEditor::new(&environment, &connection, &herdr::live_config(&environment))? + .unbind()?, + ) } } } diff --git a/src/release.rs b/src/release.rs index f9eef2e..fcd53ac 100644 --- a/src/release.rs +++ b/src/release.rs @@ -1,26 +1,24 @@ use std::os::unix::process::CommandExt; use std::process::{Command, Stdio}; -use std::time::{Duration, Instant}; use crate::clock::Clock; use crate::command::Command as Invocation; +use crate::cycle::{Cycle, CycleId, MAX_HOLD_MILLIS}; use crate::keyboard::Keyboard; -use crate::session::MAX_HOLD_MILLIS; -use crate::session_store::SessionStore; -const POLL_INTERVAL: Duration = Duration::from_millis(15); +const POLL_MILLIS: u64 = 15; pub trait ReleaseWatcher { - fn watch(&self, started_at: u64) -> anyhow::Result<()>; + fn watch(&self, cycle: CycleId) -> anyhow::Result<()>; } // Outlives the action that started it, which exits as soon as it has focused a pane. pub struct DetachedWatcher; impl ReleaseWatcher for DetachedWatcher { - fn watch(&self, started_at: u64) -> anyhow::Result<()> { + fn watch(&self, cycle: CycleId) -> anyhow::Result<()> { Command::new(std::env::current_exe()?) - .args(Invocation::Watch { started_at }.args()) + .args(Invocation::Watch { cycle }.args()) .stdin(Stdio::null()) .stdout(Stdio::null()) .stderr(Stdio::null()) @@ -32,79 +30,61 @@ impl ReleaseWatcher for DetachedWatcher { pub struct ReleaseWaiter<'a> { pub keyboard: &'a dyn Keyboard, - pub sessions: &'a SessionStore, + pub cycle: &'a Cycle<'a>, pub clock: &'a dyn Clock, } impl ReleaseWaiter<'_> { - pub fn wait(&self, started_at: u64) -> anyhow::Result<()> { - let give_up_at = Instant::now() + Duration::from_millis(MAX_HOLD_MILLIS); - while self.keyboard.alt_held() == Some(true) && Instant::now() < give_up_at { - std::thread::sleep(POLL_INTERVAL); + pub fn wait(&self, cycle: CycleId) -> anyhow::Result<()> { + let give_up_at = self.clock.now_millis() + MAX_HOLD_MILLIS; + while self.keyboard.alt_held() == Some(true) && self.clock.now_millis() < give_up_at { + self.clock.pause(POLL_MILLIS); } - self.sessions - .mark_released(started_at, self.clock.now_millis()) + self.cycle.release(cycle) } } #[cfg(test)] mod tests { use super::*; - use crate::state_file::StateFile; - use crate::test_support::{FakeClock, FakeKeyboard, session_holding_alt}; - use tempfile::TempDir; + use crate::cycle::Direction::Older; + use crate::test_support::{FakeKeyboard, Rig}; - fn store_with_cycle_started_at(dir: &TempDir, started_at: u64) -> SessionStore { - let store = SessionStore::new(StateFile::at(dir.path().join("session.json"))); - store.save(&session_holding_alt(started_at)).unwrap(); - store - } - - fn wait(keyboard: &FakeKeyboard, store: &SessionStore, started_at: u64) { - let clock = FakeClock::at(5100); + fn wait_for(rig: &Rig, keyboard: &FakeKeyboard) { + let cycle = rig.cycle(); ReleaseWaiter { keyboard, - sessions: store, - clock: &clock, + cycle: &cycle, + clock: &rig.clock, } - .wait(started_at) + .wait(rig.watcher.started()[0]) .unwrap(); } #[test] fn the_cycle_ends_once_alt_comes_up() { - let dir = TempDir::new().unwrap(); - let store = store_with_cycle_started_at(&dir, 5000); - wait( - &FakeKeyboard::reading(&[Some(true), Some(true), Some(false)]), - &store, - 5000, + let rig = Rig::with_panes(&["A", "B", "C"]); + rig.press(Older).unwrap(); + wait_for( + &rig, + &FakeKeyboard::reading(&[Some(true), Some(true), None]), ); + rig.press(Older).unwrap(); - let session = store.load().unwrap(); - - assert!(!session.is_active(5200)); - } - - #[test] - fn a_keyboard_that_cannot_report_alt_ends_the_cycle_at_once() { - let dir = TempDir::new().unwrap(); - let store = store_with_cycle_started_at(&dir, 5000); - wait(&FakeKeyboard::reading(&[None]), &store, 5000); - - let session = store.load().unwrap(); - - assert!(!session.is_active(5200)); + assert_eq!(rig.focused_pane(), "A"); } #[test] - fn a_watcher_for_an_earlier_cycle_leaves_the_current_one_running() { - let dir = TempDir::new().unwrap(); - let store = store_with_cycle_started_at(&dir, 5000); - wait(&FakeKeyboard::reading(&[Some(false)]), &store, 4000); + fn a_hold_that_never_ends_is_given_up_on_at_the_cap() { + let rig = Rig::with_panes(&["A", "B", "C"]); + rig.press(Older).unwrap(); + let keyboard = FakeKeyboard::reading(&[]); + keyboard.set_alt(Some(true)); + let started = rig.clock.now_millis(); + wait_for(&rig, &keyboard); - let session = store.load().unwrap(); + let waited = rig.clock.now_millis() - started; - assert!(session.is_active(5200)); + assert_eq!(waited, MAX_HOLD_MILLIS); } } diff --git a/src/session.rs b/src/session.rs deleted file mode 100644 index ef2bf0d..0000000 --- a/src/session.rs +++ /dev/null @@ -1,364 +0,0 @@ -use serde::{Deserialize, Serialize}; - -use crate::history::Visit; - -// Only where the platform cannot tell when Alt comes up. -const IDLE_MILLIS: u64 = 1500; -// A held cycle whose release watcher died still ends eventually. -pub(crate) const MAX_HOLD_MILLIS: u64 = 30_000; -// Hooks for the last stops may still be running just after Alt comes up. -const RELEASE_GRACE_MILLIS: u64 = 500; - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Direction { - Older, - Newer, -} - -pub struct Sighting { - pub live_mru: Vec, - pub focused_pane: Option, - pub baseline: Vec, - pub alt_held: bool, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct Session { - // Index 0 is the pane the cycle started from. - stops: Vec, - baseline: Vec, - cursor: usize, - visited: Vec, - last_press_at: u64, - alt_held_at_start: bool, - released_at: Option, - started_at: u64, -} - -impl Session { - pub fn ongoing(previous: Option, now: u64) -> Option { - previous.filter(|session| session.is_active(now)) - } - - pub fn advance( - ongoing: Option, - sighting: Sighting, - direction: Direction, - now: u64, - ) -> Option { - let session = match ongoing { - Some(session) => session.without_closed_panes(&sighting.live_mru), - None => Session::begin(sighting, now), - }; - session.step(direction, now) - } - - fn begin(sighting: Sighting, now: u64) -> Session { - let mut stops = sighting.live_mru; - if let Some(focused) = sighting.focused_pane { - stops.retain(|pane_id| *pane_id != focused); - stops.insert(0, focused); - } - Session { - stops, - baseline: sighting.baseline, - cursor: 0, - visited: Vec::new(), - last_press_at: now, - alt_held_at_start: sighting.alt_held, - released_at: None, - started_at: now, - } - } - - fn without_closed_panes(mut self, live: &[String]) -> Session { - let is_live = |pane_id: &String| live.contains(pane_id); - let current = self.stops.get(self.cursor).cloned(); - let live_before_cursor = self.stops[..self.cursor.min(self.stops.len())] - .iter() - .filter(|pane_id| is_live(pane_id)) - .count(); - self.stops.retain(is_live); - self.cursor = match current { - Some(current) if self.stops.contains(¤t) => live_before_cursor, - _ => live_before_cursor.saturating_sub(1), - }; - self - } - - fn step(mut self, direction: Direction, now: u64) -> Option { - let count = self.stops.len(); - if count == 0 { - return None; - } - self.cursor = match direction { - Direction::Older => (self.cursor + 1) % count, - Direction::Newer => (self.cursor + count - 1) % count, - }; - self.visited.push(self.stops[self.cursor].clone()); - self.last_press_at = now; - Some(self) - } - - pub fn released(self, now: u64) -> Session { - Session { - released_at: Some(now), - ..self - } - } - - pub fn is_active(&self, now: u64) -> bool { - let since_press = now.saturating_sub(self.last_press_at); - if self.alt_held_at_start { - self.released_at.is_none() && since_press <= MAX_HOLD_MILLIS - } else { - since_press <= IDLE_MILLIS - } - } - - // Focus events the cycle caused must stay out of history, or the panes it - // only passed through would reorder. - pub fn has_visited(&self, pane_id: &str) -> bool { - self.visited.iter().any(|visited| visited == pane_id) - } - - pub fn may_still_cause_focus_events(&self, now: u64) -> bool { - self.is_active(now) - || self - .released_at - .is_some_and(|released| now.saturating_sub(released) <= RELEASE_GRACE_MILLIS) - } - - pub fn needs_release_watcher(&self) -> bool { - self.alt_held_at_start - } - - pub fn started_at(&self) -> u64 { - self.started_at - } - - pub fn baseline(&self) -> &[Visit] { - &self.baseline - } - - pub fn target(&self) -> &str { - &self.stops[self.cursor] - } -} - -#[cfg(test)] -mod tests { - use super::*; - - fn ids(panes: &[&str]) -> Vec { - panes.iter().map(|id| id.to_string()).collect() - } - - // Focused on the most recently used pane, as when history is up to date. - fn see(panes: &[&str]) -> Sighting { - Sighting { - live_mru: ids(panes), - focused_pane: panes.first().map(|id| id.to_string()), - baseline: Vec::new(), - alt_held: false, - } - } - - fn see_with_alt_held(panes: &[&str]) -> Sighting { - Sighting { - alt_held: true, - ..see(panes) - } - } - - fn begin(panes: &[&str], direction: Direction) -> Session { - Session::advance(None, see(panes), direction, 5000).unwrap() - } - - fn press(session: Session, panes: &[&str], direction: Direction, now: u64) -> Session { - let ongoing = Session::ongoing(Some(session), now); - Session::advance(ongoing, see(panes), direction, now).unwrap() - } - - fn begin_holding_alt(panes: &[&str]) -> Session { - Session::advance(None, see_with_alt_held(panes), Direction::Older, 5000).unwrap() - } - - fn press_holding_alt(session: Session, panes: &[&str], now: u64) -> Session { - let ongoing = Session::ongoing(Some(session), now); - Session::advance(ongoing, see_with_alt_held(panes), Direction::Older, now).unwrap() - } - - #[test] - fn first_older_press_targets_the_second_most_recent_pane() { - let session = begin(&["A", "B", "C"], Direction::Older); - - assert_eq!(session.target(), "B"); - } - - #[test] - fn presses_within_the_idle_window_keep_stepping_older() { - let first = begin(&["A", "B", "C"], Direction::Older); - let second = press(first, &["B", "A", "C"], Direction::Older, 5100); - - assert_eq!(second.target(), "C"); - } - - #[test] - fn newer_press_steps_back_toward_the_origin() { - let first = begin(&["A", "B", "C"], Direction::Older); - let second = press(first, &["B", "A", "C"], Direction::Older, 5100); - let third = press(second, &["C", "A", "B"], Direction::Newer, 5200); - - assert_eq!(third.target(), "B"); - } - - #[test] - fn newer_from_the_origin_wraps_to_the_last_pane() { - let session = begin(&["A", "B", "C"], Direction::Newer); - - assert_eq!(session.target(), "C"); - } - - #[test] - fn older_from_the_last_pane_wraps_to_the_origin() { - let at_last = begin(&["A", "B", "C"], Direction::Newer); - let wrapped = press(at_last, &["C", "A", "B"], Direction::Older, 5100); - - assert_eq!(wrapped.target(), "A"); - } - - #[test] - fn a_single_pane_stays_put() { - let session = begin(&["A"], Direction::Older); - - assert_eq!(session.target(), "A"); - } - - #[test] - fn no_live_panes_means_nothing_to_cycle_to() { - let session = Session::advance(None, see(&[]), Direction::Older, 5000); - - assert!(session.is_none()); - } - - #[test] - fn a_press_after_the_idle_window_starts_a_fresh_cycle() { - let first = begin(&["A", "B", "C"], Direction::Older); - let later = press( - first, - &["B", "A", "C"], - Direction::Older, - 5000 + IDLE_MILLIS + 1, - ); - - assert_eq!(later.target(), "A"); - } - - #[test] - fn the_origin_is_the_focused_pane_even_when_history_lags() { - let lagging = Sighting { - focused_pane: Some("B".to_string()), - ..see(&["A", "B", "C"]) - }; - let session = Session::advance(None, lagging, Direction::Older, 5000).unwrap(); - - assert_eq!(session.target(), "A"); - } - - #[test] - fn a_focused_pane_missing_from_history_is_still_the_origin() { - let untracked = Sighting { - focused_pane: Some("X".to_string()), - ..see(&["A", "B"]) - }; - let session = Session::advance(None, untracked, Direction::Older, 5000).unwrap(); - - assert_eq!(session.target(), "A"); - } - - #[test] - fn a_pane_closed_mid_cycle_is_never_targeted() { - let first = begin(&["A", "B", "C"], Direction::Older); - let second = press(first, &["A", "B"], Direction::Older, 5100); - - assert_eq!(second.target(), "A"); - } - - #[test] - fn closing_the_current_stop_continues_from_its_neighbour() { - let first = begin(&["A", "B", "C"], Direction::Older); - let second = press(first, &["A", "C"], Direction::Older, 5100); - - assert_eq!(second.target(), "C"); - } - - #[test] - fn panes_the_cycle_moved_to_count_as_visited() { - let first = begin(&["A", "B", "C"], Direction::Older); - let second = press(first, &["B", "A", "C"], Direction::Older, 5100); - - assert!(second.has_visited("B")); - assert!(second.has_visited("C")); - } - - #[test] - fn panes_the_cycle_never_moved_to_do_not_count_as_visited() { - let first = begin(&["A", "B", "C"], Direction::Older); - - assert!(!first.has_visited("A")); - assert!(!first.has_visited("D")); - } - - #[test] - fn an_active_cycle_may_still_cause_focus_events() { - let session = begin(&["A", "B", "C"], Direction::Older); - - assert!(session.may_still_cause_focus_events(5000 + IDLE_MILLIS)); - } - - #[test] - fn an_idle_cycle_no_longer_causes_focus_events() { - let session = begin(&["A", "B", "C"], Direction::Older); - - assert!(!session.may_still_cause_focus_events(5000 + IDLE_MILLIS + 1)); - } - - #[test] - fn tapping_releasing_and_tapping_again_starts_a_fresh_cycle() { - let tapped = begin_holding_alt(&["A", "B", "C"]).released(5050); - let again = press_holding_alt(tapped, &["B", "A", "C"], 5100); - - assert_eq!(again.target(), "A"); - } - - #[test] - fn holding_alt_keeps_one_cycle_across_a_long_pause() { - let first = begin_holding_alt(&["A", "B", "C"]); - let after_pause = press_holding_alt(first, &["B", "A", "C"], 5000 + 10 * IDLE_MILLIS); - - assert_eq!(after_pause.target(), "C"); - } - - #[test] - fn a_held_cycle_whose_watcher_vanished_expires_eventually() { - let first = begin_holding_alt(&["A", "B", "C"]); - let much_later = press_holding_alt(first, &["B", "A", "C"], 5000 + MAX_HOLD_MILLIS + 1); - - assert_eq!(much_later.target(), "A"); - } - - #[test] - fn a_released_cycle_may_still_cause_focus_events_for_a_moment() { - let released = begin_holding_alt(&["A", "B", "C"]).released(5100); - - assert!(released.may_still_cause_focus_events(5100 + RELEASE_GRACE_MILLIS)); - } - - #[test] - fn a_released_cycle_stops_causing_focus_events_after_the_grace_period() { - let released = begin_holding_alt(&["A", "B", "C"]).released(5100); - - assert!(!released.may_still_cause_focus_events(5100 + RELEASE_GRACE_MILLIS + 1)); - } -} diff --git a/src/session_store.rs b/src/session_store.rs deleted file mode 100644 index 6addd34..0000000 --- a/src/session_store.rs +++ /dev/null @@ -1,100 +0,0 @@ -use std::fs::File; - -use crate::session::Session; -use crate::state_file::StateFile; - -pub struct SessionStore { - file: StateFile, -} - -impl SessionStore { - pub fn new(file: StateFile) -> Self { - Self { file } - } - - // Held across a whole press, and by the track hook while it decides whether - // a focus event is the cycle's own, so neither sees half a press. - pub fn lock(&self) -> anyhow::Result { - Ok(self.file.lock()?) - } - - pub fn load(&self) -> Option { - serde_json::from_str(&self.file.read()?).ok() - } - - pub fn save(&self, session: &Session) -> anyhow::Result<()> { - Ok(self.file.write(&serde_json::to_string(session)?)?) - } - - pub fn clear(&self) { - self.file.remove(); - } - - pub fn mark_released(&self, started_at: u64, now: u64) -> anyhow::Result<()> { - let _turn = self.lock()?; - match self.load() { - Some(session) if session.started_at() == started_at => { - self.save(&session.released(now)) - } - _ => Ok(()), - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::test_support::session_holding_alt; - use tempfile::TempDir; - - fn store_in(dir: &TempDir) -> SessionStore { - SessionStore::new(StateFile::at(dir.path().join("session.json"))) - } - - #[test] - fn a_saved_session_loads_back() { - let dir = TempDir::new().unwrap(); - let store = store_in(&dir); - store.save(&session_holding_alt(5000)).unwrap(); - - let loaded = store.load(); - - assert_eq!(loaded.unwrap().target(), "B"); - } - - #[test] - fn a_cleared_session_is_gone() { - let dir = TempDir::new().unwrap(); - let store = store_in(&dir); - store.save(&session_holding_alt(5000)).unwrap(); - store.clear(); - - let loaded = store.load(); - - assert!(loaded.is_none()); - } - - #[test] - fn releasing_ends_the_cycle_the_watcher_was_started_for() { - let dir = TempDir::new().unwrap(); - let store = store_in(&dir); - store.save(&session_holding_alt(5000)).unwrap(); - store.mark_released(5000, 5100).unwrap(); - - let session = store.load().unwrap(); - - assert!(!session.is_active(5200)); - } - - #[test] - fn a_watcher_for_an_earlier_cycle_leaves_the_current_one_running() { - let dir = TempDir::new().unwrap(); - let store = store_in(&dir); - store.save(&session_holding_alt(5000)).unwrap(); - store.mark_released(4000, 5100).unwrap(); - - let session = store.load().unwrap(); - - assert!(session.is_active(5200)); - } -} diff --git a/src/state_file.rs b/src/state_file.rs index 82ad459..d6d1394 100644 --- a/src/state_file.rs +++ b/src/state_file.rs @@ -1,9 +1,7 @@ -use std::fs::{self, File, OpenOptions}; +use std::fs; use std::io; use std::path::PathBuf; -use fs2::FileExt; - pub struct StateFile { path: PathBuf, } @@ -31,17 +29,6 @@ impl StateFile { let _ = fs::remove_file(&self.path); } - pub fn lock(&self) -> io::Result { - self.create_parent_dir()?; - let guard = OpenOptions::new() - .create(true) - .truncate(false) - .write(true) - .open(self.path.with_extension("lock"))?; - guard.lock_exclusive()?; - Ok(guard) - } - fn create_parent_dir(&self) -> io::Result<()> { match self.path.parent() { Some(parent) => fs::create_dir_all(parent), @@ -117,15 +104,4 @@ mod tests { assert_eq!(mode, 0o600); } - - #[test] - fn the_lock_is_free_again_once_its_handle_drops() { - let dir = TempDir::new().unwrap(); - let file = state_file_in(&dir); - drop(file.lock().unwrap()); - - let relocked = file.lock(); - - assert!(relocked.is_ok()); - } } diff --git a/src/test_support.rs b/src/test_support.rs index 12daf7b..70e4485 100644 --- a/src/test_support.rs +++ b/src/test_support.rs @@ -5,24 +5,11 @@ use tempfile::TempDir; use crate::clock::Clock; use crate::connection::Connection; -use crate::cycler::Cycler; +use crate::cycle::{Collaborators, Cycle, CycleId, Direction}; use crate::herdr::{Herdr, HerdrError, Pane, Panes}; use crate::history::History; use crate::keyboard::Keyboard; use crate::release::ReleaseWatcher; -use crate::session::{Direction, Session, Sighting}; -use crate::session_store::SessionStore; -use crate::track::Tracker; - -pub fn session_holding_alt(started_at: u64) -> Session { - let sighting = Sighting { - live_mru: vec!["A".into(), "B".into()], - focused_pane: Some("A".into()), - baseline: Vec::new(), - alt_held: true, - }; - Session::advance(None, sighting, Direction::Older, started_at).unwrap() -} pub struct FakeClock(Cell); @@ -36,6 +23,10 @@ impl Clock for FakeClock { fn now_millis(&self) -> u64 { self.0.get() } + + fn pause(&self, millis: u64) { + self.0.set(self.0.get() + millis); + } } pub struct FakeHerdr { @@ -59,14 +50,14 @@ impl FakeHerdr { self.panes.borrow_mut().push(pane_id.to_string()); } - pub fn close(&self, pane_id: &str) { - self.panes.borrow_mut().retain(|id| id != pane_id); - } - pub fn fail_focus(&self) { self.focus_fails.set(true); } + pub fn allow_focus(&self) { + self.focus_fails.set(false); + } + pub fn focus_requests(&self) -> Vec { self.focus_requests.borrow().clone() } @@ -75,9 +66,8 @@ impl FakeHerdr { impl Herdr for FakeHerdr { fn panes(&self) -> Result { let focused = self.focused.borrow(); - Ok(Panes { - panes: self - .panes + Ok(Panes::new( + self.panes .borrow() .iter() .map(|id| Pane { @@ -85,7 +75,7 @@ impl Herdr for FakeHerdr { focused: focused.as_deref() == Some(id), }) .collect(), - }) + )) } fn focus(&self, pane_id: &str) -> Result<(), HerdrError> { @@ -129,17 +119,17 @@ impl Keyboard for FakeKeyboard { } } -pub struct FakeWatcher(RefCell>); +pub struct FakeWatcher(RefCell>); impl FakeWatcher { - pub fn started(&self) -> Vec { + pub fn started(&self) -> Vec { self.0.borrow().clone() } } impl ReleaseWatcher for FakeWatcher { - fn watch(&self, started_at: u64) -> anyhow::Result<()> { - self.0.borrow_mut().push(started_at); + fn watch(&self, cycle: CycleId) -> anyhow::Result<()> { + self.0.borrow_mut().push(cycle); Ok(()) } } @@ -151,8 +141,8 @@ pub struct Rig { pub keyboard: FakeKeyboard, pub watcher: FakeWatcher, pub history: History, - pub sessions: SessionStore, pub clock: FakeClock, + connection: Connection, _state_dir: TempDir, } @@ -160,7 +150,7 @@ impl Rig { pub fn with_panes(panes: &[&str]) -> Self { let state_dir = TempDir::new().unwrap(); let connection = Connection::new(state_dir.path().to_path_buf(), None); - let history = History::new(connection.state_file("history")); + let history = History::new(connection.state_file("history"), connection.lock("history")); for (age, pane_id) in panes.iter().rev().enumerate() { history.record(pane_id, 100 * (age as u64 + 1)).unwrap(); } @@ -171,46 +161,41 @@ impl Rig { keyboard, watcher: FakeWatcher(RefCell::new(Vec::new())), history, - sessions: SessionStore::new(connection.state_file("session")), clock: FakeClock::at(10_000), + connection, _state_dir: state_dir, } } - pub fn press(&self, direction: Direction) -> anyhow::Result<()> { - Cycler { - herdr: &self.herdr, - keyboard: &self.keyboard, - watcher: &self.watcher, - history: &self.history, - sessions: &self.sessions, - clock: &self.clock, - } - .press(direction) + pub fn cycle(&self) -> Cycle<'_> { + Cycle::new( + &self.connection, + Collaborators { + herdr: &self.herdr, + keyboard: &self.keyboard, + watcher: &self.watcher, + history: &self.history, + clock: &self.clock, + }, + ) } - pub fn tracker(&self) -> Tracker<'_> { - Tracker { - herdr: &self.herdr, - history: &self.history, - sessions: &self.sessions, - clock: &self.clock, - } + pub fn press(&self, direction: Direction) -> anyhow::Result<()> { + self.cycle().press(direction) } pub fn pass_time(&self, millis: u64) { - self.clock.0.set(self.clock.0.get() + millis); + self.clock.pause(millis); } pub fn user_focuses(&self, pane_id: &str) { *self.herdr.focused.borrow_mut() = Some(pane_id.to_string()); } + /// Plays the release watcher of the cycle that last started one. pub fn release_alt(&self) { - let started_at = self.sessions.load().unwrap().started_at(); - self.sessions - .mark_released(started_at, self.clock.now_millis()) - .unwrap(); + let id = *self.watcher.started().last().unwrap(); + self.cycle().release(id).unwrap(); } pub fn focused_pane(&self) -> String { @@ -218,10 +203,6 @@ impl Rig { } pub fn history_order(&self) -> Vec { - self.history - .visits() - .into_iter() - .map(|visit| visit.pane_id) - .collect() + self.history.order() } } diff --git a/src/track.rs b/src/track.rs deleted file mode 100644 index 9907362..0000000 --- a/src/track.rs +++ /dev/null @@ -1,177 +0,0 @@ -use serde::Deserialize; - -use crate::clock::Clock; -use crate::herdr::Herdr; -use crate::history::History; -use crate::session::Session; -use crate::session_store::SessionStore; - -const PANE_FOCUSED_EVENT: &str = "pane_focused"; - -#[derive(Deserialize)] -struct HookEvent { - event: String, - #[serde(default)] - data: HookEventData, -} - -#[derive(Deserialize, Default)] -struct HookEventData { - pane_id: Option, -} - -pub fn announced_pane(event_json: &str) -> Result, serde_json::Error> { - let event: HookEvent = serde_json::from_str(event_json)?; - Ok(event - .data - .pane_id - .filter(|_| event.event == PANE_FOCUSED_EVENT)) -} - -#[derive(PartialEq, Eq)] -enum FocusSource { - Cycle, - User, -} - -pub struct Tracker<'a> { - pub herdr: &'a dyn Herdr, - pub history: &'a History, - pub sessions: &'a SessionStore, - pub clock: &'a dyn Clock, -} - -impl Tracker<'_> { - // Herdr does not fire `pane.focused` for every switch, so whatever the - // event was, the pane focused right now is recorded too. - pub fn track(&self, announced_pane: Option<&str>) -> anyhow::Result<()> { - let observed_at = self.clock.now_millis(); - if self.end_cycle_if_user_moved(observed_at)? == FocusSource::Cycle { - return Ok(()); - } - if let Some(pane_id) = announced_pane { - self.history.record(pane_id, observed_at)?; - } - if let Some(focused) = self.herdr.panes()?.focused() { - self.history.record(&focused.id, self.clock.now_millis())?; - } - Ok(()) - } - - fn end_cycle_if_user_moved(&self, now: u64) -> anyhow::Result { - let _turn = self.sessions.lock()?; - let Some(cycle) = self - .sessions - .load() - .filter(|cycle| cycle.may_still_cause_focus_events(now)) - else { - return Ok(FocusSource::User); - }; - if self.cycle_moved_focus(&cycle) { - return Ok(FocusSource::Cycle); - } - self.sessions.clear(); - Ok(FocusSource::User) - } - - // Focus that cannot be read is assumed to be the cycle's. - fn cycle_moved_focus(&self, cycle: &Session) -> bool { - match self.herdr.panes() { - Ok(panes) => panes - .focused() - .is_none_or(|pane| cycle.has_visited(&pane.id)), - Err(_) => true, - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::session::Direction::Older; - use crate::test_support::Rig; - - #[test] - fn a_pane_focused_event_names_its_pane() { - let event = r#"{"event":"pane_focused","data":{"pane_id":"p1","workspace_id":"w1"}}"#; - - let pane = announced_pane(event).unwrap(); - - assert_eq!(pane.as_deref(), Some("p1")); - } - - #[test] - fn other_events_name_no_pane() { - let event = r#"{"event":"workspace_focused","data":{"workspace_id":"w1"}}"#; - - let pane = announced_pane(event).unwrap(); - - assert_eq!(pane, None); - } - - #[test] - fn a_malformed_event_is_a_json_syntax_error() { - let error = announced_pane("not json").unwrap_err(); - - assert!(error.is_syntax()); - } - - #[test] - fn moving_by_hand_puts_the_focused_pane_first_in_history() { - let rig = Rig::with_panes(&["A", "B", "C"]); - rig.user_focuses("C"); - rig.tracker().track(Some("C")).unwrap(); - - let order = rig.history_order(); - - assert_eq!(order, ["C", "A", "B"]); - } - - #[test] - fn the_focused_pane_is_recorded_even_when_the_event_names_none() { - let rig = Rig::with_panes(&["A", "B", "C"]); - rig.user_focuses("B"); - rig.tracker().track(None).unwrap(); - - let order = rig.history_order(); - - assert_eq!(order, ["B", "A", "C"]); - } - - #[test] - fn focus_a_cycle_caused_is_left_out_of_history() { - let rig = Rig::with_panes(&["A", "B", "C"]); - rig.press(Older).unwrap(); - let history_after_cycle = rig.history.visits(); - rig.pass_time(10); - rig.tracker().track(Some("B")).unwrap(); - - let history_after_hook = rig.history.visits(); - - assert_eq!(history_after_hook, history_after_cycle); - } - - #[test] - fn moving_by_hand_during_a_cycle_ends_it() { - let rig = Rig::with_panes(&["A", "B", "C"]); - rig.press(Older).unwrap(); - rig.user_focuses("C"); - rig.tracker().track(Some("C")).unwrap(); - - let session = rig.sessions.load(); - - assert!(session.is_none()); - } - - #[test] - fn moving_by_hand_during_a_cycle_is_recorded() { - let rig = Rig::with_panes(&["A", "B", "C"]); - rig.press(Older).unwrap(); - rig.user_focuses("C"); - rig.tracker().track(Some("C")).unwrap(); - - let order = rig.history_order(); - - assert_eq!(order[0], "C"); - } -} From f192a90a60f18fa5bed60d08799d0d09b2e8651a Mon Sep 17 00:00:00 2001 From: archae0pteryx Date: Thu, 29 Oct 2026 11:18:22 -0700 Subject: [PATCH 3/3] Address review: bound socket waits, keep long holds alive, test the hook lock - Socket reads time out after 2s, so a stalled Herdr cannot hold the cycle lock forever and queue up every press and hook behind it. - The release watcher no longer ends the cycle when it gives up at the hold cap with Alt still down; the cycle expires on its own after its last press. - Test that the focus hook holds the cycle lock while it asks Herdr. - Cycle keeps Collaborators whole instead of copying its five fields. --- src/cycle.rs | 55 ++++++++++++++++++++++++++------------------- src/herdr/socket.rs | 22 ++++++++++++++++++ src/release.rs | 13 ++++++++--- src/test_support.rs | 31 +++++++++++++++++++++++++ 4 files changed, 95 insertions(+), 26 deletions(-) diff --git a/src/cycle.rs b/src/cycle.rs index e27862c..3e25179 100644 --- a/src/cycle.rs +++ b/src/cycle.rs @@ -26,37 +26,29 @@ pub struct Collaborators<'a> { /// takes a turn on the saved state, and holds it until its history writes are /// done. The turn is always taken before History's own lock, never after. pub struct Cycle<'a> { - herdr: &'a dyn Herdr, - keyboard: &'a dyn Keyboard, - watcher: &'a dyn ReleaseWatcher, - history: &'a History, - clock: &'a dyn Clock, + with: Collaborators<'a>, store: Store, } impl<'a> Cycle<'a> { pub fn new(connection: &Connection, with: Collaborators<'a>) -> Self { Self { - herdr: with.herdr, - keyboard: with.keyboard, - watcher: with.watcher, - history: with.history, - clock: with.clock, + with, store: Store::new(connection.state_file("cycle"), connection.lock("cycle")), } } pub fn press(&self, direction: Direction) -> anyhow::Result<()> { let turn = self.store.begin_turn()?; - let now = self.clock.now_millis(); + let now = self.with.clock.now_millis(); - let panes = self.herdr.panes()?; - let recency = self.history.recency_of(panes.ids()); + let panes = self.with.herdr.panes()?; + let recency = self.with.history.recency_of(panes.ids()); let sighting = Sighting { live_mru: recency.live, focused_pane: panes.focused().map(|pane| pane.id.clone()), baseline: recency.snapshot, - alt_held: self.keyboard.alt_held() == Some(true), + alt_held: self.with.keyboard.alt_held() == Some(true), }; let ongoing = State::ongoing(turn.load(), now); @@ -68,14 +60,15 @@ impl<'a> Cycle<'a> { // Saved before focusing so the focus hook, which takes the same turn, // can tell the focus events that follow are ours. turn.save(&state)?; - if let Err(error) = self.herdr.focus(state.target()) { + if let Err(error) = self.with.herdr.focus(state.target()) { turn.clear(); return Err(error.into()); } - self.history + self.with + .history .promote_after_cycle(state.baseline(), state.target(), now)?; if starts_new_cycle && state.needs_release_watcher() { - self.watcher.watch(state.id())?; + self.with.watcher.watch(state.id())?; } Ok(()) } @@ -83,16 +76,18 @@ impl<'a> Cycle<'a> { // Herdr does not fire `pane.focused` for every switch, so whatever the // event was, the pane focused right now is recorded too. pub fn observe_focus(&self, announced_pane: Option<&str>) -> anyhow::Result<()> { - let observed_at = self.clock.now_millis(); + let observed_at = self.with.clock.now_millis(); let turn = self.store.begin_turn()?; if self.cycle_caused_focus(&turn, observed_at) { return Ok(()); } if let Some(pane_id) = announced_pane { - self.history.record(pane_id, observed_at)?; + self.with.history.record(pane_id, observed_at)?; } - if let Some(focused) = self.herdr.panes()?.focused() { - self.history.record(&focused.id, self.clock.now_millis())?; + if let Some(focused) = self.with.herdr.panes()?.focused() { + self.with + .history + .record(&focused.id, self.with.clock.now_millis())?; } Ok(()) } @@ -101,7 +96,9 @@ impl<'a> Cycle<'a> { pub fn release(&self, id: CycleId) -> anyhow::Result<()> { let turn = self.store.begin_turn()?; match turn.load() { - Some(state) if state.id() == id => turn.save(&state.released(self.clock.now_millis())), + Some(state) if state.id() == id => { + turn.save(&state.released(self.with.clock.now_millis())) + } _ => Ok(()), } } @@ -124,7 +121,7 @@ impl<'a> Cycle<'a> { // Focus that cannot be read is assumed to be the cycle's. Its events must // stay out of history, or the panes it only passed through would reorder. fn moved_focus(&self, state: &State) -> bool { - match self.herdr.panes() { + match self.with.herdr.panes() { Ok(panes) => panes .focused() .is_none_or(|pane| state.has_visited(&pane.id)), @@ -271,6 +268,18 @@ mod tests { assert_eq!(order, ["C", "A", "B"]); } + #[test] + fn a_focus_hook_keeps_the_cycle_lock_while_it_asks_herdr() { + let rig = Rig::with_panes(&["A", "B", "C"]); + rig.user_focuses("C"); + rig.watch_cycle_lock(); + rig.cycle().observe_focus(Some("C")).unwrap(); + + let held = rig.cycle_lock_was_held_when_herdr_was_asked(); + + assert!(!held.is_empty() && held.iter().all(|held| *held)); + } + #[test] fn the_focused_pane_is_recorded_even_when_the_event_names_none() { let rig = Rig::with_panes(&["A", "B", "C"]); diff --git a/src/herdr/socket.rs b/src/herdr/socket.rs index 5a18ac0..9c6b909 100644 --- a/src/herdr/socket.rs +++ b/src/herdr/socket.rs @@ -1,18 +1,24 @@ use std::io::{BufRead, BufReader, Write}; use std::os::unix::net::UnixStream; +use std::time::Duration; use serde_json::json; use super::{HerdrError, Request, Transport}; +// Callers hold the cycle lock while waiting, so a stalled Herdr must not hold it forever. +const REPLY_TIMEOUT: Duration = Duration::from_secs(2); + pub struct Socket { path: String, + reply_timeout: Duration, } impl Socket { pub fn at(path: &str) -> Self { Self { path: path.to_string(), + reply_timeout: REPLY_TIMEOUT, } } } @@ -24,6 +30,7 @@ impl Transport for Socket { Request::FocusPane(pane_id) => ("pane.focus", json!({"pane_id": pane_id})), }; let mut stream = UnixStream::connect(&self.path)?; + stream.set_read_timeout(Some(self.reply_timeout))?; let call = json!({"jsonrpc": "2.0", "id": "1", "method": method, "params": params}); writeln!(stream, "{call}")?; @@ -102,6 +109,21 @@ mod tests { assert!(matches!(error, HerdrError::Malformed(_))); } + #[test] + fn a_herdr_that_never_replies_is_an_io_error() { + let dir = TempDir::new().unwrap(); + let path = dir.path().join("herdr.sock"); + let _listener = UnixListener::bind(&path).unwrap(); + let socket = Socket { + reply_timeout: Duration::from_millis(50), + ..Socket::at(path.to_str().unwrap()) + }; + + let error = socket.send(&Request::ListPanes).unwrap_err(); + + assert!(matches!(error, HerdrError::Io(_))); + } + #[test] fn an_unreachable_socket_is_an_io_error() { let dir = TempDir::new().unwrap(); diff --git a/src/release.rs b/src/release.rs index fcd53ac..deba560 100644 --- a/src/release.rs +++ b/src/release.rs @@ -37,10 +37,15 @@ pub struct ReleaseWaiter<'a> { impl ReleaseWaiter<'_> { pub fn wait(&self, cycle: CycleId) -> anyhow::Result<()> { let give_up_at = self.clock.now_millis() + MAX_HOLD_MILLIS; - while self.keyboard.alt_held() == Some(true) && self.clock.now_millis() < give_up_at { + while self.clock.now_millis() < give_up_at { + if self.keyboard.alt_held() != Some(true) { + return self.cycle.release(cycle); + } self.clock.pause(POLL_MILLIS); } - self.cycle.release(cycle) + // Alt is still down, so the cycle is not over; it expires on its own + // MAX_HOLD_MILLIS after its last press. + Ok(()) } } @@ -75,7 +80,7 @@ mod tests { } #[test] - fn a_hold_that_never_ends_is_given_up_on_at_the_cap() { + fn a_hold_that_never_ends_is_given_up_on_at_the_cap_without_ending_the_cycle() { let rig = Rig::with_panes(&["A", "B", "C"]); rig.press(Older).unwrap(); let keyboard = FakeKeyboard::reading(&[]); @@ -84,7 +89,9 @@ mod tests { wait_for(&rig, &keyboard); let waited = rig.clock.now_millis() - started; + rig.press(Older).unwrap(); assert_eq!(waited, MAX_HOLD_MILLIS); + assert_eq!(rig.focused_pane(), "C"); } } diff --git a/src/test_support.rs b/src/test_support.rs index 70e4485..2a196c3 100644 --- a/src/test_support.rs +++ b/src/test_support.rs @@ -1,6 +1,9 @@ use std::cell::{Cell, RefCell}; use std::collections::VecDeque; +use std::fs::OpenOptions; +use std::path::PathBuf; +use fs2::FileExt; use tempfile::TempDir; use crate::clock::Clock; @@ -34,6 +37,8 @@ pub struct FakeHerdr { focused: RefCell>, focus_requests: RefCell>, focus_fails: Cell, + lock_probe: RefCell>, + lock_held_when_asked: RefCell>, } impl FakeHerdr { @@ -43,6 +48,8 @@ impl FakeHerdr { focused: RefCell::new(ids.first().map(|id| id.to_string())), focus_requests: RefCell::new(Vec::new()), focus_fails: Cell::new(false), + lock_probe: RefCell::new(None), + lock_held_when_asked: RefCell::new(Vec::new()), } } @@ -61,10 +68,25 @@ impl FakeHerdr { pub fn focus_requests(&self) -> Vec { self.focus_requests.borrow().clone() } + + fn note_whether_locked(&self) { + if let Some(path) = self.lock_probe.borrow().as_ref() { + let rival = OpenOptions::new() + .create(true) + .truncate(false) + .write(true) + .open(path) + .unwrap(); + self.lock_held_when_asked + .borrow_mut() + .push(rival.try_lock_exclusive().is_err()); + } + } } impl Herdr for FakeHerdr { fn panes(&self) -> Result { + self.note_whether_locked(); let focused = self.focused.borrow(); Ok(Panes::new( self.panes @@ -198,6 +220,15 @@ impl Rig { self.cycle().release(id).unwrap(); } + /// From now on, notes for every pane listing whether the cycle lock was held. + pub fn watch_cycle_lock(&self) { + *self.herdr.lock_probe.borrow_mut() = Some(self._state_dir.path().join("cycle.lock")); + } + + pub fn cycle_lock_was_held_when_herdr_was_asked(&self) -> Vec { + self.herdr.lock_held_when_asked.borrow().clone() + } + pub fn focused_pane(&self) -> String { self.herdr.focused.borrow().clone().unwrap() }