diff --git a/.codex/skills/.gitkeep b/.codex/skills/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/.cursor/rules/.gitkeep b/.cursor/rules/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/.sloop/config.yaml b/.sloop/config.yaml index febdca0..e10ad18 100644 --- a/.sloop/config.yaml +++ b/.sloop/config.yaml @@ -1,5 +1,6 @@ version: 1 tools: + - agy - claude - codex - cursor diff --git a/AGENTS.md b/AGENTS.md index c9ed10a..634d869 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -10,8 +10,8 @@ design: **all per-provider knowledge lives in the adapter manifest** (`internal/ Detect, launch, context delivery, skills, hooks, and completion are all manifest-driven. To support a new CLI, drop in one `.yaml` — no Go changes unless it needs a brand-new mechanism. -- Provider contract + manifest schema: `docs/ADAPTERS.md` -- Config layering (unified user config vs per-provider manifests): `docs/CONFIG.md` +- Provider contract + manifest schema: `docs/reference/ADAPTERS.md` +- Config layering (unified user config vs per-provider manifests): `docs/reference/CONFIG.md` - Runtime capability matrix: `sloop tools` User config is **unified** (one local `.sloop/config.yaml` + one global `~/.sloop/config.yaml` + diff --git a/CHANGELOG.md b/CHANGELOG.md index 94a58a8..2af9200 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,7 +3,7 @@ All notable changes to Sloop are documented here. This project adheres to [Semantic Versioning](https://semver.org/). -## v0.0.1 — first release +## v0.1.0 — first release The initial public release: the local-first control layer for your AI coding CLIs. @@ -16,27 +16,56 @@ The initial public release: the local-first control layer for your AI coding CLI pre-fills `AGENTS.md` from the codebase (offline, no LLM); `--scaffold` creates each tool's standard folders. +### Launch +- `sloop run` syncs context, then launches in a managed session. The target can be a + tool (`claude`), its binary (`agent` → cursor), or a model alias (`opus` → its vendor's + home CLI). Flags: `-m/--model`, `-e/--effort` (low|medium|high), `-p/--provider`, and + `-t/--task` to hand the agent an initial task (interactive session already working on it, + visible in `sloop ps`). The model is forwarded to the CLI as-is, never validated. + `--split` runs several tools side by side; `-w` targets a registered workspace. + ### Cross-repo fleet -- `sloop ps` — every running agent across all your repos; agents waiting on you float - to the top. `--watch` live-monitors and alerts (terminal bell + desktop notify); - `--waiting`, `--all`, and `ps <#>` to jump. -- Interactive control center: jump, send a reply, or kill the highlighted session in place. -- `sloop send` (`--waiting`/`--all` broadcast), `sloop kill`, `sloop attach`, - `sloop run --split`. +- `sloop ps` — every running agent across all your repos; agents waiting on you float to + the top. It reads each waiting agent's own prompt and shows the answer keys, so you can + reply in one keystroke. `--watch` live-monitors and alerts (terminal bell + desktop + notify); `--waiting`, `--all`, and `ps <#>` to jump. +- Interactive control center: arrow-key nav, `Enter` to attach, one key to answer a waiting + agent (`y`/`n`/`1`…), `s` to send a line, `x` to kill — all in place, and Esc/Ctrl-C cancel + back to the fleet (never drops you to a shell). Provider display names, status colors, and + column headers; the screen redraws cleanly with an action notice. +- `sloop approve` — send the affirmative answer to waiting agent(s) in one command + (`--waiting`/`--all`). +- `sloop ls` — registered workspaces with their live agents (colored by status, the same + language as `ps`); `Enter` attaches, `r` launches the default tool, `s` opens a shell, `c` + copies a `cd`. +- `sloop attach` (`a`) — by session name, or with no argument a fleet picker that matches + the `ps` view. `sloop adopt` brings an external tmux session into the fleet. +- `sloop restore` — relaunch the agents you were recently running after a reboot / tmux + restart, each detached; `--resume` continues each tool's prior conversation where supported. +- `sloop popup` / `sloop hud` — the fleet as a floating tmux popup (HUD); `popup setup` binds + a key (needs tmux ≥ 3.2). +- Per-session status bar (`sloop statusline`) shows live `⚓ repo tool ◆ waiting` plus a + persistent detach tip using your real tmux prefix; set only per session (never touches + `~/.tmux.conf`), and `SLOOP_STATUSLINE=0` leaves a custom bar untouched. +- `sloop send` (`--waiting`/`--all` broadcast), `sloop kill`, `sloop run --split`. ### Provider-aware - Tools are declarative adapter manifests (detect/launch/context/skills/hooks/scaffold); adding a CLI is adding a file. Built-ins: Claude, Cursor, Codex, Copilot, Gemini, Antigravity. `sloop tools` shows the capability matrix. -- `sloop hooks` wires each tool's own hooks for authoritative status (Claude & Gemini - auto-install; others print-and-paste). -- `sloop skills new` / `add` — reusable skills shared across every tool. +- `sloop hooks` wires each tool's own **status** hooks for authoritative `sloop ps` state + (Claude, Gemini & Cursor auto-install; others print-and-paste). The reserved callback is + `sloop hooks emit `, keeping the namespace clear for the v0.2.0 workflow-hook library. +- `sloop skills new` / `add` — reusable skills shared across every tool. `.sloop/skills.lock` + records imported skills + source so `sloop skills update` re-fetches reproducibly. ### Cross-platform & DX - Multiplexer-agnostic: tmux on macOS/Linux, **psmux** on native Windows (`SLOOP_MUX` to override). - Contextual education hints (English + Vietnamese); `sloop hints on|off`. - Dynamic shell completion; local SQLite registry + history (WAL + migrations). +- `--debug` (or `SLOOP_DEBUG=1`) logs diagnostics via `log/slog` to stderr, including every + multiplexer call sloop makes. ### Foundation - Single CGO-free Go binary, no daemon, no cloud. diff --git a/Makefile b/Makefile index bf3c0c9..e0b383a 100644 --- a/Makefile +++ b/Makefile @@ -23,6 +23,11 @@ vet: go vet ./... lint: + @if [ -n "$$(gofmt -l .)" ]; then \ + echo "Some files are not formatted correctly. Please run 'make fmt'"; \ + gofmt -l .; \ + exit 1; \ + fi golangci-lint run ./... sec: diff --git a/README.md b/README.md index 122791e..9367756 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,7 @@ > **The local-first control layer for your AI coding CLIs.** > One canonical context for every tool, and one cross-repo view of every agent you're running. -[Documentation](docs/USAGE.md) +[Documentation](docs/guide/USAGE.md) Sloop is a single, lightweight Go binary that sits **above** your AI coding tools — Claude Code, Cursor CLI, Codex CLI, GitHub Copilot CLI, Gemini CLI, Google Antigravity, and future agents. It @@ -23,6 +23,25 @@ Running AI coding agents is powerful but quickly gets messy: - **Per-tool knobs everywhere** — skills, hooks, and standard folders differ per provider, so setup is ad-hoc and hard to share with a team. +Concretely, running two AI CLIs (say Claude and Cursor's `agent`) in one project today means juggling +tmux by hand: + +``` +# The manual way — fiddly and easy to mix up +Terminal 1 → tmux new -s claude_api → cd ~/code/api → claude +Terminal 2 → tmux new -s cursor_api → cd ~/code/api → agent +# …now switch between them yourself, and remember which window is which, +# across every repo, while CLAUDE.md and AGENTS.md drift apart. +``` + +``` +# With sloop — named sessions per workspace+tool, one fleet view, one context +cd ~/code/api +sloop run claude # session api__claude, sees AGENTS.md +sloop run cursor # session api__cursor, same context +sloop ps # one board: who's waiting, who's working — jump/reply/kill in place +``` + Sloop fixes these with three ideas: 1. **Portable context** — write guidance once in `AGENTS.md`; every tool reads it (natively, or via a @@ -94,6 +113,31 @@ In the `sloop ps` menu: `↑/↓` move · `Enter` jump in · `s` reply · `x` ki --- +## Daily use — `sloop ps` is home base + +Most days you live in **one screen**: + +1. **`sloop ps`** — the fleet board. Agents *waiting on you* float to the top, colored by status. +2. **`Enter`** on a row jumps you straight into that agent (attaches its tmux session). +3. Work with the agent. To step out, **detach**: press your tmux prefix then `d` — `Ctrl+b d` by + default, or `Ctrl+a d` if you remapped it. The agent **keeps running**; you land back at the fleet. +4. Back in `sloop ps`, triage without attaching: answer a waiting agent in one key (`y` / `1` …), + `s` to send a line, `x` to kill, or `Enter` into the next one. + +You never lose an agent — detaching hides it, it doesn't stop it. Every sloop session's status bar +shows **`⚓ detach: d`** so you always know how to get back, and `sloop ps` is one keystroke +away. Rebooted? **`sloop restore`** relaunches the fleet. No name to type? **`sloop a`** opens the same +picker. + +> The status bar is set **per session** (`set-option -t`) — sloop never edits your `~/.tmux.conf`, and +> only touches `status-left`/`status-right` (not your colors/theme). Keep your own bar fully intact with +> `SLOOP_STATUSLINE=0`. + +`sloop ls` is the companion view — your registered **workspaces** (running or not) with their live +agents — to launch (`r`), open a shell (`s`), `c` to copy a `cd`, or `Enter` to jump in. + +--- + ## Commands (the menu) `alias` = command shortcut · `-x` = short flag. @@ -108,9 +152,10 @@ In the `sloop ps` menu: `↑/↓` move · `Enter` jump in · `s` reply · `x` ki | `send ` | — | `--waiting`, `--all`, `--yes` | Reply to a running agent without attaching; `--waiting`/`--all` broadcast. | | `kill ` | — | `--all`, `--waiting`, `--yes` | End session(s) — confirms (skip with `--yes` or global `-y`). | | `adopt ` | — | `-w/--workspace`, `--as` | Bring an external tmux session (one you started yourself) into the fleet. | -| `popup` / `popup setup` | — | `--key` | Open the fleet `ps` as a floating tmux popup (HUD); `setup` binds a key. Needs tmux ≥ 3.2. | +| `restore` | — | `--resume`, `--yes` | Relaunch your recent agents (detached) after a reboot / tmux restart. `--resume` continues each tool's prior conversation. | +| `popup` / `popup setup` | `hud` | `--key` | Open the fleet `ps` as a floating tmux popup / HUD; `setup` binds a key. Needs tmux ≥ 3.2. | | `statusline setup` | — | — | Show a session's live status (`⚓ repo tool ◆ waiting`) in its tmux status bar. | -| `attach ` | `a` | — | Attach to a session by full name. | +| `attach [session]` | `a` | — | Attach to a session by name, or `sloop a` (no name) to pick from the fleet. | | `skills new\|add <…>` | `sk`, `skill` | `new`→`n`, `add`→`import` | Scaffold or import a reusable skill (shared across every tool). | | `hooks install\|list\|print [tool]` | — | — | Wire a tool's own hooks so `ps` status is authoritative. | | `tools` | — | — | Capability matrix (context / skills / hooks per tool). | @@ -123,7 +168,7 @@ In the `sloop ps` menu: `↑/↓` move · `Enter` jump in · `s` reply · `x` ki **Global flags** (any command): `-y/--auto` (assume yes), `--no-color`, `--no-input`, `--config `, `--debug` (log diagnostics to stderr; or set `SLOOP_DEBUG=1` — shows every multiplexer call sloop makes). -Full, example-driven walkthrough: **[docs/USAGE.md](docs/USAGE.md)**. +Full, example-driven walkthrough: **[docs/guide/USAGE.md](docs/guide/USAGE.md)**. --- @@ -137,7 +182,7 @@ skills dir. Delivery is **create-if-missing** — sloop never overwrites a file Launch happens in a tmux/psmux session named `__`, which is what makes the fleet view, `send`, and `attach` possible. -Architecture & internals: **[docs/ARCHITECTURE.md](docs/ARCHITECTURE.md)**. +Architecture & internals: **[docs/reference/ARCHITECTURE.md](docs/reference/ARCHITECTURE.md)**. --- @@ -157,7 +202,12 @@ Architecture & internals: **[docs/ARCHITECTURE.md](docs/ARCHITECTURE.md)**. Machine-local state lives under `~/.sloop/`: the workspaces registry + session history (`sloop.db`, SQLite with WAL), hook status markers (`state/`), and any user adapter manifests (`adapters/*.yaml`). -Config layering is documented in **[docs/CONFIG.md](docs/CONFIG.md)**. +Config layering is documented in **[docs/reference/CONFIG.md](docs/reference/CONFIG.md)**. + +**Across restarts.** tmux sessions live in memory, so a reboot ends them (sloop is not tmux-resurrect). +What sloop keeps is the **registry**: after a restart your workspaces and recent sessions are still +there, so `sloop ls` / `sloop ps --all` show them and `sloop run -w ` relaunches from anywhere. +The agent's own conversation is the provider's to resume (e.g. `claude` continues a prior session). --- @@ -165,7 +215,7 @@ Config layering is documented in **[docs/CONFIG.md](docs/CONFIG.md)**. Every tool is a declarative YAML manifest — adding a CLI is adding a file, never editing Go. Built-ins are embedded; user adapters/overrides live in `~/.sloop/adapters/*.yaml`. `sloop tools` shows the -capability matrix. See **[docs/ADAPTERS.md](docs/ADAPTERS.md)** for the contract. +capability matrix. See **[docs/reference/ADAPTERS.md](docs/reference/ADAPTERS.md)** for the contract. ```yaml name: Claude Code @@ -192,10 +242,14 @@ hooks: # status hooks for `sloop ps` ## Docs -- [docs/USAGE.md](docs/USAGE.md) — hands-on guide, every command with examples -- [docs/CONFIG.md](docs/CONFIG.md) — the three config layers (local / global / built-in) -- [docs/ADAPTERS.md](docs/ADAPTERS.md) — the provider-aware adapter contract -- [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) — packages, data flow, internals +- [ROADMAP.md](ROADMAP.md) — pillars, what's next (v0.2.0 workflow hooks), how to contribute +- [docs/guide/USAGE.md](docs/guide/USAGE.md) — hands-on guide, every command with examples +- [docs/reference/CONFIG.md](docs/reference/CONFIG.md) — the three config layers (local / global / built-in) +- [docs/reference/ADAPTERS.md](docs/reference/ADAPTERS.md) — the provider-aware adapter contract +- [docs/design/run.md](docs/design/run.md) — `sloop run` design: CLI · model · effort resolution +- [docs/design/skills.md](docs/design/skills.md) — skills model, lockfile, registry roadmap +- [docs/design/hooks.md](docs/design/hooks.md) — status hooks today, workflow-hook design for v0.2.0 +- [docs/reference/ARCHITECTURE.md](docs/reference/ARCHITECTURE.md) — packages, data flow, internals ## License diff --git a/ROADMAP.md b/ROADMAP.md new file mode 100644 index 0000000..245174a --- /dev/null +++ b/ROADMAP.md @@ -0,0 +1,70 @@ +# Sloop Roadmap + +Sloop is the **local-first layer that makes your project context portable across AI CLIs and gives +you a cross-repo view of all your agents.** It sits *above* your AI coding tools and complements them +— one canonical context, one fleet view, every tool. + +This file is the public, contributor-facing roadmap. It links out to a design doc per pillar so a +contribution starts from a clear contract. For the shipped detail of each release, see +[CHANGELOG.md](CHANGELOG.md). + +## Principles (what keeps sloop sloop) + +- **Provider-respecting.** Never intercept or inject into an AI tool. Use the tool's *own* hook + mechanism or non-invasive local signals only. +- **Provider-aware by construction.** All per-provider knowledge lives in one adapter manifest; no + feature hardcodes a tool name. See [docs/reference/ADAPTERS.md](docs/reference/ADAPTERS.md). +- **One lightweight binary.** CGO-free Go, no daemon, no bundled LLM. Add capability when the first + real feature needs it — never a standalone "foundation" ahead of a consumer. +- **Local-first & portable.** Author context/skills once; every tool and every repo sees them. + +## Pillars + +| Pillar | What it is | Design doc | Status | +|---|---|---|---| +| **Launch (`run`)** | one friendly target → the right CLI, model and effort, in a managed session | [docs/design/run.md](docs/design/run.md) | tool · model · effort shipped (Phase 1–2) | +| **Portable context** | `AGENTS.md` canonical; pointer files + skills delivered to every tool | [docs/reference/ADAPTERS.md](docs/reference/ADAPTERS.md) | shipped (v0.1.0) | +| **Skills** | reusable prompts/workflows shared across tools *and* sources | [docs/design/skills.md](docs/design/skills.md) | shipping incrementally | +| **Cross-repo fleet** | every running agent across all repos; triage who needs you | [docs/guide/USAGE.md](docs/guide/USAGE.md) | shipped (v0.1.0) | +| **Hooks** | precise agent status today; a portable workflow-hook library next | [docs/design/hooks.md](docs/design/hooks.md) | status hooks shipped; workflow hooks → v0.2.0 | + +## Now (v0.1.x — validating the wedge) + +- Dogfood `sloop ps` across repos: does the cross-repo view triage "which agent needs me" better than + single-project tools and raw tmux? +- **Skills:** lockfile (`.sloop/skills.lock`) + `skills update` for reproducible team skills. *(shipped)* +- **Hooks (status):** auto-installers per provider — claude, gemini, cursor done; copilot/codex need a + matcher-aware model (see the hooks doc). +- **`sloop restore`** _(shipped)_ — relaunch the recent agents that aren't currently running, each in a + detached session, so the whole fleet comes back after a reboot / tmux restart. Picks the most recent + session per (workspace, tool) from the registry, skips any already live, and with `--resume` passes + each provider's resume flag (e.g. claude `--continue`) to continue the conversation. *Auto*-restore on + boot would need a shell-init hook (no daemon), so this first cut stays a manual command. +- **`sloop tmux setup`** _(planned)_ — opt-in, append a managed/idempotent block to `~/.tmux.conf` for + the bits that need to survive a tmux restart (popup keybind, optional global status line). Default + stays per-session and non-invasive; this is **not** folded into `hooks` (which is AI-provider status). + +## Next (v0.2.0 — workflow hooks) + +The big one. Today's hooks only report status *to sloop*. v0.2.0 turns hooks into a **portable +workflow-automation library**: pick a hook (format-on-edit, commit-policy, shell-guard, prompt-rule), +and sloop installs it into the right tool's own hook config — author once, run across tools and repos. +This is a large, security-sensitive surface, so it is **designed before it is built**. Full proposal, +categories, project/user levels, cross-tool mapping, and the trust model are in +**[docs/design/hooks.md](docs/design/hooks.md)**. + +## Later / parked + +- Skills registry (`skills search`/`add ` from a curated index) — after the lockfile proves out. +- `init --scan` LLM enrichment — only once a minimal LLM client exists for a real consumer. +- Windows multiplexer verification (psmux); 2nd-brain / RAG bridge. + +## Contributing + +The lowest-barrier, highest-leverage contributions are **data, not code**: + +- **Add an AI tool:** drop one `internal/adapter/builtin/.yaml` — see + [docs/reference/ADAPTERS.md](docs/reference/ADAPTERS.md). No Go changes unless the tool needs a brand-new mechanism. +- **Share a skill:** see [docs/design/skills.md](docs/design/skills.md). +- **Propose a workflow hook:** see the open questions in [docs/design/hooks.md](docs/design/hooks.md) — feedback on + the model is wanted *before* the v0.2.0 build. diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 0000000..09d2968 --- /dev/null +++ b/docs/README.md @@ -0,0 +1,29 @@ +# Sloop docs + +Documentation is organized by **purpose**, so it stays navigable as it grows: + +| Folder | Purpose | Audience | +|---|---|---| +| **[guide/](guide/)** | how-to, hands-on usage | users | +| **[reference/](reference/)** | how the system *is* — stable contracts & internals | users + contributors | +| **[design/](design/)** | how a feature *should be* — proposals, evolving | contributors | +| `local/` | private working notes (gitignored) | maintainers | + +## guide/ +- [USAGE.md](guide/USAGE.md) — every command, with examples + +## reference/ +- [ARCHITECTURE.md](reference/ARCHITECTURE.md) — packages, data flow, internals +- [ADAPTERS.md](reference/ADAPTERS.md) — the provider-aware adapter manifest contract +- [CONFIG.md](reference/CONFIG.md) — the config layers (local / global / built-in) + +## design/ +- [run.md](design/run.md) — `sloop run`: CLI · model · effort resolution +- [hooks.md](design/hooks.md) — status hooks today, workflow hooks (v0.2.0) +- [skills.md](design/skills.md) — skills model, lockfile, registry roadmap + +> Project direction lives in [../ROADMAP.md](../ROADMAP.md); shipped changes in +> [../CHANGELOG.md](../CHANGELOG.md). + +**Adding a doc:** put it in the folder matching its purpose (a new feature design → `design/`; a new +stable contract → `reference/`) and link it here. diff --git a/docs/design/hooks.md b/docs/design/hooks.md new file mode 100644 index 0000000..d0e8a89 --- /dev/null +++ b/docs/design/hooks.md @@ -0,0 +1,110 @@ +# Hooks — status today, portable workflow automation next + +AI CLIs expose **hooks**: events that fire at points in a session (per-session, per-turn, per +tool-call) where a command can observe, react, or block. Sloop uses hooks two ways — and keeping the +two cleanly separated is the whole design. + +> **Status hooks** ship today. **Workflow hooks** are a v0.2.0 proposal — this doc is the contract to +> review *before* it's built. Command reference for status hooks: [USAGE.md](../guide/USAGE.md); the install +> mechanism: [ADAPTERS.md §Hook install strategies](../reference/ADAPTERS.md). + +## Two kinds of hook (don't conflate them) + +| | **Status hooks** (shipped) | **Workflow hooks** (v0.2.0) | +|---|---|---| +| Purpose | tell **sloop** the agent's state for `sloop ps` | run **the user's** automation (format, lint, policy) | +| Consumer | sloop's fleet view | the user / the team | +| Command wired in | `sloop hooks emit ` (reserved, hidden) | an arbitrary command from a library | +| Managed by | `sloop hooks install` (manifest-driven) | `sloop hooks add` (library + lockfile) | +| Tracking | derived from the manifest, recomputable | `.sloop/hooks.lock` | + +### How the two stay non-conflicting + +Both write into the *same* provider hook config (e.g. `.claude/settings.json`), so separation is by +construction: + +1. **Reserved identity.** Sloop's status hook is always the exact command `sloop hooks emit `. + That prefix is sloop's namespace; the merge is idempotent and never duplicates it. (This is why the + internal callback is namespaced as `hooks emit`, not a bare top-level `hook`.) +2. **Separate verbs.** `hooks install`/`uninstall` only ever touch the reserved status hook; + `hooks add`/`remove`/`update` only ever touch lockfile-tracked workflow hooks. Neither command can + see the other's entries. +3. **Separate tracking.** Status hooks are derived from the manifest (sloop can always recompute and + reconcile them). Workflow hooks are recorded in `.sloop/hooks.lock`. Installing/removing one kind + leaves the other untouched, and foreign (hand-written) hooks in the file are always preserved. + +## Status hooks (shipped) + +A provider calls `sloop hooks emit ` from its own lifecycle events; `emit` +writes a short-lived marker under `~/.sloop/state` that `sloop ps` prefers over the screen heuristic +(15-min TTL, so it never goes stale). Per-provider event→state mapping and the install strategy live +in the adapter manifest. Auto-install today: **claude, gemini, cursor**; **copilot, codex** are +`print+paste` pending a matcher-aware model (below). See [ADAPTERS.md](../reference/ADAPTERS.md). + +## Workflow hooks (v0.2.0 proposal) + +Turn hooks into a **portable automation library**: pick a hook, sloop installs it into the right +tool's own config — author once, run across tools and repos. Provider-respecting because it uses each +tool's *own* hook mechanism (or standard git hooks); sloop never intercepts. + +### Categories + +| Category | Typical event | Example | +|---|---|---| +| Quality gate | PostToolUse / afterFileEdit | run formatter/linter after an edit | +| Safety guard | PreToolUse / beforeShellExecution | block or confirm dangerous shell commands | +| Policy / governance | Stop, or git `commit-msg` | enforce a commit trailer, scan for secrets | +| Prompt / context rule | UserPromptSubmit | inject team standards into the prompt | +| Lifecycle / audit | SessionStart / SessionEnd | logging, notifications | +| Observability | Stop / Notification | (this is what status hooks already are) | + +### Levels + +A hook installs at one of two levels — the design must make this explicit: + +- **Project** — `.claude/settings.json`, `.cursor/hooks.json`. Committed, team-shared, reproducible + (pairs with `.sloop/hooks.lock`). +- **User / global** — `~/.claude/…`, `~/.cursor/…`. Personal, applies across every repo. + +### Cross-tool mapping (sloop's value) + +The same *logical* hook ("run formatter after an edit") maps to different events and schemas per tool +— Claude `PostToolUse` with `matcher: "Write|Edit"`, Cursor `afterFileEdit`, Copilot `notification` +with a matcher. A workflow-hook definition is therefore tool-agnostic and sloop **translates** it into +each tool's config — exactly the adapter-manifest pattern, extended with **matchers/cadences**. (The +status-hook schema has no matchers yet; copilot's status hook is the first real consumer that forces +adding them, so the schema gets designed against a concrete need rather than guessed.) + +### Trust model + +A hook **executes commands** and can **block actions** — distributing hooks is distributing code that +runs on a teammate's machine. So, unlike skills, the library needs: + +- a **lockfile** (`.sloop/hooks.lock`) pinning `id` + `source` + **checksum** + target event/level; +- **review before run** — `hooks add` shows exactly what will be installed and where; nothing executes + on `add`, only what the provider later invokes; +- provenance for any future registry (curated index, signing) before `hooks add ` from a remote + source is allowed. + +### Provider-respect boundary + +- Prompt-rule hooks go through the provider's **own** `UserPromptSubmit` mechanism — never by + intercepting or rewriting the user's prompt. +- Commit-policy hooks go through standard **git hooks** (`.git/hooks/commit-msg`), not by wrapping the + AI tool. +- Each definition declares its target mechanism; sloop installs into that and nowhere else. + +## Open questions (feedback wanted before the build) + +- Library distribution: embedded built-ins in this repo first (review via PR, ship with the binary, + zero infra), then `hooks add ` like skills, then a curated index? Or a registry sooner? +- Hook schema: how much of each tool's event model (matcher, cadence, payload, block/allow decision, + `failClosed`, timeout) to model portably vs. pass through per tool. +- Conflict UX when a user already has a hand-written hook on the same event. +- Verification/signing bar for remote hooks. + +## Contributing + +- **Status hooks:** add/correct a tool's `hooks.*` in its adapter manifest — [ADAPTERS.md](../reference/ADAPTERS.md). +- **Workflow hooks (v0.2.0):** comment on the open questions above. The model is intentionally being + settled in public *before* implementation — input now shapes the schema. diff --git a/docs/design/run.md b/docs/design/run.md new file mode 100644 index 0000000..74ec514 --- /dev/null +++ b/docs/design/run.md @@ -0,0 +1,156 @@ +# `sloop run` — launching an agent (CLI · model · effort) + +`sloop run` is the heart of sloop: it takes a short, friendly target and launches the right AI CLI, +with the right model and reasoning effort, in a managed session. This doc is the design contract — +the model, the resolution rules, the manifest schema, and the staged plan — so the upgrade is settled +before it's built. + +> Command reference (today's behaviour): [USAGE.md](../guide/USAGE.md). Provider contract: [ADAPTERS.md](../reference/ADAPTERS.md). + +## Two jobs, one clean seam + +`run` does exactly two things, and keeping them separate is the design: + +1. **Resolve → launch spec.** Turn the target + flags into `{binary, args}` — *what* to run. +2. **Provision → launch.** Create the tmux session/window and run the spec inside it — *where* to run. + +Job 2 already exists and is stable (`runner.Runner`/`tmux.Runner`). The upgrade is **entirely in job +1**: today it only resolves a *tool*; it should resolve a tool **and** a model **and** an effort. No +change to how sessions are provisioned. + +## Three concepts the target conflates + +A single token like `claude`, `opus`, or `agent` can mean different things. Name them: + +| Concept | Examples | Notes | +|---|---|---| +| **CLI / tool** | claude, cursor (`agent`), codex, agy | the binary sloop launches — today's "provider" | +| **Model** | opus, sonnet, gpt-5 | has a fixed **vendor** | +| **Effort** | low / medium / high | each CLI expresses reasoning differently | + +Plus **vendor** (Anthropic, OpenAI, Google) — who makes the model. A model's vendor is unambiguous; a +model can be run by *several* CLIs. + +## Resolving "is opus Claude or Cursor?" — via vendor + +`model → CLI` is many-to-one (Cursor can also run opus), but **`model → vendor` is one-to-one**. So: + +- **`sloop run opus`** → vendor = Anthropic → that vendor's default CLI (`claude`) → `claude --model opus`. +- **`sloop run cursor -m opus`** → CLI is named explicitly → cursor runs opus its own way. + +> Rule: a bare model resolves to its vendor's home CLI; naming a CLI explicitly overrides it. + +## Resolution algorithm + +Given positional token `T` and flags `-p/--provider`, `-m/--model`, `-e/--effort`: + +``` +CLI = --provider + | T if T is a tool key OR a known detect/launch binary (e.g. "agent" → cursor) + | the home CLI of (model's vendor) + | project default_tool +model = --model + | T if T is a known model alias (and wasn't used as the CLI) + | (none → the CLI's own default) +effort = --effort | (none) + +args = [run.model_flag, model] (if model set and the CLI supports it) + + [run.effort_flag, effortToken] (if effort set and the CLI supports it) + + passthrough (everything after `--`) +``` + +Precedence when `T` is ambiguous: **tool key → binary alias → model alias**. Unknown `T` → a clear +error (`unknown tool or model "X"`), never a silent guess. + +### Worked examples + +| Command | CLI | Args | +|---|---|---| +| `sloop run claude` | claude | _(default model)_ | +| `sloop run agent` | cursor | _(binary alias of cursor)_ | +| `sloop run opus` | claude | `--model opus` _(vendor → home CLI)_ | +| `sloop run cursor -m opus` | cursor | cursor's model flag `opus` | +| `sloop run claude -m sonnet -e high` | claude | `--model sonnet` + effort token | +| `sloop run agy -m opus` | agy | **error**: agy has no `run.model_flag` | + +## Where the knowledge lives + +Per the manifest rule, per-CLI knowledge goes in the manifest; only the small, stable model→vendor map +is shared. + +**Manifest `run.*` (per CLI):** +```yaml +launch: claude +run: + vendor: anthropic # the model vendor this CLI natively serves + default_for: [anthropic] # this CLI is the canonical launcher for these vendors (bare-model) + model_flag: "--model" # how to pass a model; "" / omitted = no model selection + effort_flag: "" # how to pass reasoning effort; "" = unsupported + effort_values: # map sloop's low|medium|high → this CLI's own token + low: "" + medium: "" + high: "" + models: [opus, sonnet, haiku, fable] # model aliases this CLI serves (for completion + Phase 2; + # full API strings like claude-opus-4-8 still work via forward) +``` + +**No separate model catalog file.** Model aliases live in the manifest's `run.models`, so the +alias→CLI map is just a reverse index over manifests — one mechanism, zero new files, embedded in the +binary and overridable the same way as any manifest (`~/.sloop/adapters/.yaml`). A bare +`sloop run opus` finds the manifest serving `opus`; if several do, `default_for` picks the home CLI. +The alias's vendor is implied by its home CLI's `run.vendor` — no global `models.yaml` to maintain. + +**What sloop deliberately does *not* do:** keep a full, churning model catalog (ids, pricing, context +windows), nor **validate** the model — model selection is the CLI's own step; sloop only offers a +nice-to-have shortcut. It learns just enough (a small curated alias list) to pick the CLI and power +completion, then **forwards the model string to the CLI** (alias *or* full API id), letting the CLI +accept or reject it. Light, and resilient to new models. + +**Why not persist models in SQLite?** The alias set is small, shared, and ships with the binary — it's +*reference* data (manifest), not *runtime* state. SQLite holds accumulated per-machine data (sessions, +fleet), not a model list that would need seeding/migrating per release. Dynamically discovering a +tool's models — via the tool's *own* `list`-style command (provider-respecting, never the vendor API), +cached with a TTL — is a possible later nicety for CLIs with large/volatile model sets. It's **opt-in +and parked**; curated aliases cover the common case at zero runtime cost. + +> **User preference vs. reference knowledge.** The `run.*`/`models` above is *provider reference +> knowledge* (manifest). A user's own default — "this repo defaults to sonnet at high effort" — is +> *user config* and belongs in `.sloop/config.yaml` (Phase 3), never mixed into the catalog. + +## What we borrow (and don't) from aider & the CLIs + +- **aider** — model-first UX, provider inferred from the model name, shortcuts like `--opus`. We adopt + **model-first + aliases**. We *don't* adopt its litellm-scale model registry: aider calls APIs; + sloop launches a CLI and lets *it* own the model list. +- **The AI CLIs themselves** — each has its own `--model`/effort flag and is mostly single-vendor. We + adopt **forward-to-CLI** and keep every flag name in the manifest, never hardcoded. + +## Staged plan + +- **Phase 1 — explicit flags (deterministic).** _(shipped)_ `-p/--provider`, `-m/--model`, + `-e/--effort` forwarded via manifest `run.*`; plus binary-alias resolution (`run agent` == + `run cursor`). Zero new files, zero new dependencies — just manifest fields (embedded) and flag + parsing (`planLaunch`/`buildRunArgs`). +- **Phase 2 — smart positional.** _(shipped)_ Classifies `T` as tool | binary | model alias by + reverse-indexing manifest `run.models` (`modelHomeTool`), so `sloop run opus` → `claude --model opus`. +- **Initial task.** _(shipped)_ `-t/--task "…"` seeds an **interactive** session already working on + the task (so it lives in the fleet), delivered per `run.prompt` (positional for claude/cursor — + `claude "task"` / `agent "task"`; their `-p` is the non-interactive print mode, which sloop does not + use). A CLI without `run.prompt` errors clearly. (Headless one-shot is parked — it doesn't live in + the fleet, so it adds little over calling the CLI directly.) +- **Phase 3 — profiles & session identity.** User aliases (`sloop run myopus`), and session naming that + includes the model so two Claude sessions (opus + sonnet) can coexist in one repo (today the session + is `__`, which would collide). + +## Open questions (feedback before/while building) + +- Effort vocabulary: is `low|medium|high` enough, or do some CLIs need a numeric/thinking-budget form? +- Session identity with model (Phase 3): always include the model in the name, or only when asked? +- User default model/effort (Phase 3): the shape of the `.sloop/config.yaml` preference (global vs + per-tool). + +## Contributing + +Teaching sloop to launch a tool with a model/effort is **manifest-only**: add a `run:` block to the +tool's adapter (see [ADAPTERS.md](../reference/ADAPTERS.md)) — `model_flag`, `effort_flag`/`effort_values`, +`vendor`, `default_for`, `models`. No Go changes unless the CLI needs a brand-new launch mechanism. diff --git a/docs/design/skills.md b/docs/design/skills.md new file mode 100644 index 0000000..f96ab28 --- /dev/null +++ b/docs/design/skills.md @@ -0,0 +1,58 @@ +# Skills — portable, reusable prompts across every tool + +A **skill** is a reusable prompt/workflow (a markdown file) that sloop delivers to *every* enabled AI +tool from one source. Author or import once; Claude, Cursor, Codex, … all see the same set. This is +context portability across **tools** *and* **sources** — something single-tool orchestrators don't do. + +> Hands-on command reference lives in [USAGE.md §5](../guide/USAGE.md). This doc is the model + the roadmap so +> contributions and integrations start from a clear contract. + +## Model + +- Skills live in **`.sloop/skills/*.md`** (one workspace, one set). +- They are **symlinked** into each tool's skills dir (e.g. `.claude/skills`), resolved from the + manifest's `skills.target` ([ADAPTERS.md](../reference/ADAPTERS.md)). A directory symlink means every skill is + shared at once; it self-heals and falls back to copy when symlinks aren't available. +- `sloop sync` (and `skills new`/`add`) keep the links in place. + +Markdown was chosen deliberately: skills are **inert and tool-agnostic**. There is no per-tool +translation layer — the same file is valid everywhere. (Contrast with hooks, which execute and are +tool-specific; see [hooks.md](hooks.md).) + +## Sources & the lockfile + +Skills come from two places: + +- **Authored** — `sloop skills new ` scaffolds a local skill. No upstream; stays out of the lock. +- **Imported** — `sloop skills add ` fetches a skill from a source. + +Imported skills are recorded in **`.sloop/skills.lock`** (`name` + `source` + `sha256` + fetch time). +Commit the lock so a team gets **reproducible** skills from one source. `sloop skills update [name…]` +re-fetches from the recorded sources and rewrites + relinks only the files whose content changed. + +```yaml +# .sloop/skills.lock +version: 1 +skills: + - name: code-review + source: https://github.com/owner/repo/blob/main/skills/code-review.md + sha256: e3b0c44… + updated: 2026-06-28T10:00:00Z +``` + +## Roadmap + +- **Shipped:** `skills new`, `skills add `, `.sloop/skills.lock`, `skills update`. +- **Next — registry:** `skills search` / `skills add ` resolving from a curated index (or + skills.sh). Gated on investigating that index's API/format first. The lockfile is the foundation: + a registry just resolves a `` to a `source` that lands in the same lock. + +## Contributing a skill + +1. Write a focused markdown skill (one workflow/prompt, a clear `# Title`). +2. Host it at a stable URL (a GitHub blob URL works — sloop rewrites it to raw). +3. Share the `sloop skills add ` line. Teammates' `skills.lock` records it; `skills update` + keeps everyone in sync. + +Open question for the registry phase: naming/namespacing and trust for `add ` (a curated index +needs review + provenance, the same concern hooks have — see [hooks.md](hooks.md#trust-model)). diff --git a/docs/guide/USAGE.md b/docs/guide/USAGE.md new file mode 100644 index 0000000..d0d2346 --- /dev/null +++ b/docs/guide/USAGE.md @@ -0,0 +1,417 @@ +# Sloop — Hands-on Usage (dogfooding guide) + +A practical, example-driven walkthrough. For the "what & why", see `README.md`. + +> **Requirements:** Go 1.26 to build. A **tmux-compatible multiplexer** for the orchestration +> features (`run --split`, `ps`, `send`, `attach`): **tmux** on macOS/Linux, or **[psmux]** +> (native, tmux-CLI-compatible) on Windows — no WSL needed. sloop auto-detects `tmux` then `psmux`; +> override with `SLOOP_MUX=`. Plain `sloop run` works without any multiplexer (single tool). +> The AI tool binaries you target (`claude`, `cursor`/`agent`, `codex`, `copilot`, `gemini`, `agy`) +> must be installed for sloop to launch them. +> +> [psmux]: https://github.com/psmux/psmux + +--- + +## 0. Build + +```sh +go build -o ~/bin/sloop ./cmd/sloop # or: go install ./cmd/sloop +sloop doctor # check tools + tmux are detected +``` + +`sloop doctor` example: +``` +Tools: + ✓ claude 1.x + ✗ codex + ... +tmux: ✓ tmux 3.4 +mode: ask +``` + +--- + +## 1. Set up a project (once per repo) + +From inside an existing codebase: + +```sh +cd ~/code/my-service +sloop init +``` + +This creates: +``` +AGENTS.md # canonical context — YOU write this (the source of truth) +.sloop/ + config.yaml # version, enabled tools + default tool (auto-detected) + skills/ # reusable *.md skills + vault/ # personal notes (not delivered to tools) + .gitignore +``` + +On a real terminal `sloop init` is **interactive** — it shows the tools it detected and asks whether to +pre-fill `AGENTS.md` from your codebase, create the standard provider folders, and install status +hooks, so a newcomer is set up in a few keystrokes. Piped/CI or `--auto`/`-y`/`--no-input` skip the +prompts and keep the scriptable behavior (flags only). + +`init` also **delivers context for every detected tool** right away — it writes the pointer files +(`CLAUDE.md`, `GEMINI.md`, …) and links `.sloop/skills`, so the workspace is usable immediately +(no separate `sloop sync` needed first). It prints a per-tool summary of what it created. The personal +`vault/` is gitignored; `config.yaml` and `skills/` are committed (shared with your team). + +Add `--scaffold` (`-S`) to also create each enabled tool's **standard folders** (e.g. `.claude/skills`, +`.claude/agents`, `.cursor/rules`, `.codex/skills`) — driven by the adapter manifests, so you start +from the provider's expected layout: + +```sh +sloop init --scaffold +``` + +Or let sloop pre-fill `AGENTS.md` from the existing codebase (language, build/test/lint commands — +a `Makefile` target wins — project layout, and a README seed) instead of an empty starter: + +```sh +sloop init --scan +``` + +Either way, then edit `AGENTS.md` with the rest of your guidance (overview, conventions). Commit +`AGENTS.md` and `.sloop/` to git — they're shared with your team. `--scan` is heuristic and offline +(no LLM, no API key); it never overwrites an existing `AGENTS.md`. + +--- + +## 2. Launch a tool + +```sh +sloop run # launch the default tool, context synced first +sloop run claude # launch a specific tool +sloop run agent # binary alias works too (agent → cursor) +sloop run -m sonnet # a model: -m forwards it to the tool (default tool) +sloop run opus # a bare model → its vendor's home CLI (opus → claude --model opus) +sloop run claude -m sonnet -e high # tool + model + reasoning effort (low|medium|high) +sloop run claude -t "fix the auth bug" # hand it a task: interactive session already working on it +sloop run -p cursor -m opus # name the CLI explicitly with --provider/-p +sloop run claude -- --resume # everything after -- is passed straight to the tool +sloop run -w my-service claude # target a registered workspace from anywhere (no cd) +``` + +**Picking a tool / model / effort.** `run ` accepts a tool (`claude`), its binary +(`agent`→cursor), or a model alias (`opus`→its home CLI). Flags are explicit: `-p/--provider` the CLI, +`-m/--model` the model, `-e/--effort` (`low|medium|high`), `-t/--task` an initial task (launches an +interactive session already working on it, so it shows up in `sloop ps`). sloop **forwards the model +string as-is and never validates it** — the CLI accepts or rejects it; selection is the CLI's own step, sloop just makes +it a one-liner. If a CLI has no model/effort knob, `-m`/`-e` errors clearly (run it and pick inside, or +pass flags after `--`). `-m ` completes the known aliases. Which knobs each CLI exposes lives in +its adapter manifest — see [run.md](../design/run.md) and [ADAPTERS.md](../reference/ADAPTERS.md). + +What `run` does: ensures `AGENTS.md`, writes pointer files (e.g. `CLAUDE.md` → `AGENTS.md`), +symlinks `.sloop/skills` into the tool's skills dir, records the session, then launches — +inside a tmux session named `__` when tmux is present. + +**Status bar:** each sloop session shows its own live status in the tmux bar, e.g. +`⚓ myrepo claude ◆ waiting` (the status word is colored: yellow waiting · cyan working · green idle), +refreshed every 2s. It's set **per session** so it never touches your global tmux config. Adopted +sessions get it too; add it to any session with `sloop statusline setup`. + +### Side-by-side panes (the orchestration win) + +```sh +sloop run --split claude cursor # one tmux window, two panes, same repo, side by side +sloop run --split # just the default tool (one pane) +``` + +Great for running two agents on the same code and comparing, or a coder + a reviewer. + +--- + +## 3. Manage the fleet (`sloop ps`) + +The answer to "too many AI windows". From anywhere: + +```sh +sloop ps +``` + +``` +⚓ AI fleet — 2 running, 1 waiting on you + + 1 webapp claude ◆ waiting on you · active 3m ago + └ │ Waiting for your approval to edit main.go + 2 my-service cursor ▸ working · active just now + └ Running tests... 12 passed + +jump: sloop ps <#> · send: sloop send <#> "msg" +``` + +- Each session is classified from **its own terminal** (non-invasive — sloop never + reads the provider): `◆ waiting on you` (blocked on an approval/question), `▸ working`, + `○ idle`, or `● attached`. **Sessions waiting on you float to the top** so you see who + needs you first. Install the Claude hooks (below) to make this status **authoritative** + instead of a heuristic. +- The `└` line is the session's last terminal output (the glance). +- sloop **reads what each waiting agent is asking** (from its own pane — no LLM, no API) and shows the + question + answer keys, e.g. `Apply changes? · answer: [y]es [n]o` or `[1]Yes [2]No`. +- On a real terminal, `sloop ps` is a **control center** — `↑/↓` (or `j/k`) to move, then act on the + highlighted session in place: press its **answer key** (`y`/`n` or `1`/`2`…) to reply, `Enter` jumps, + `s` sends a free-text reply, `x` kills (with a confirm), `q`/`Esc` quits. Piped/CI prints the plain + listing. Colors honor `NO_COLOR`/`--no-color`. +- Jump straight to one: + +```sh +sloop ps 2 # attach (or switch-client if you're already inside tmux) +sloop attach webapp__claude # attach by full session name +``` + +### Live monitor (`--watch`) and filtering (`--waiting`) + +```sh +sloop ps --waiting # show only agents waiting on you +sloop ps -f # follow live (alias of --watch): refresh every 2s, ring the bell +sloop ps -f -n 5s # custom interval +sloop ps -f --notify # also fire a desktop notification on new waiting agents +sloop ps -f --waiting # monitor, but only list those that need you +``` + +> `-f` (follow) is the short for `--watch`. `-w` is reserved for `--workspace` everywhere +> (`run`/`sync`), so it is intentionally not a `ps` shorthand. + +### Precise status via Claude's own hooks + +The pane heuristic is a good guess; Claude's hooks make it exact. Install once per repo: + +```sh +sloop hooks install # merges into .claude/settings.local.json (idempotent, never clobbers) +sloop hooks print # or print the JSON snippet to add by hand +``` + +This registers three of Claude's documented hooks — `UserPromptSubmit` → working, +`Notification` → waiting on you, `Stop` → idle — each calling `sloop hooks emit `, which +records the session's status under `~/.sloop/state`. `sloop ps` then **prefers that marker** +over the heuristic (falling back to the heuristic if no fresh marker exists). This stays +within the provider's rules: Claude calls sloop through its **own** hook mechanism; sloop +never intercepts or injects. Markers older than 15 min are ignored so a crashed session +can't get stuck "waiting". + +**Multi-provider:** every major CLI now has a hook/notify system. `sloop hooks list` shows the +matrix, and `sloop hooks print ` prints the exact event → `sloop hooks emit ` wiring for +each (Claude and Gemini auto-install; Cursor/Copilot/Codex are print-and-paste for now): + +``` +sloop hooks list +TOOL AUTO-INSTALL CONFIG +claude yes .claude/settings.local.json +gemini yes .gemini/settings.json +cursor print+paste .cursor/hooks.json +copilot print+paste ~/.copilot/hooks/notification-hooks.json +codex print+paste ~/.codex/config.toml (notify = [...]) +``` + +Hook knowledge lives in each tool's adapter manifest (see `docs/reference/ADAPTERS.md`), so adding a provider +is "drop one yaml". `sloop tools` shows the full capability matrix (context / skills / hooks). + +### Whole cross-repo board (`ps --all`) + +`sloop ps` lists what's live; `sloop ps --all` also lists registered workspaces that **aren't** +running, with their repo path — the full picture of every project, not just the running ones: + +```sh +sloop ps --all +``` +``` +⚓ AI fleet — 1 running + 1 api claude ◆ waiting on you · active 2m ago + +Known workspaces (not running): + ○ web ~/code/web + ○ infra ~/code/infra + +start one: sloop run -w +``` + +`--watch` turns `ps` from a snapshot into a live board: it re-renders on the interval and, +whenever a session **newly** starts waiting on you, rings the terminal bell (and, with +`--notify`, shows an OS notification via `osascript`/`notify-send`). Captures run concurrently, +so even a large fleet refreshes quickly. Ctrl-C to stop. + +### Answer an agent without attaching (`sloop send`) + +When `ps` shows an agent `◆ waiting on you`, reply without switching to it: + +```sh +sloop send 1 "yes, go ahead" # by fleet number (from ps) +sloop send webapp__claude "use the opus model" # by full session name +sloop send webapp "run the tests" # by workspace (if it has one session) +``` + +`send` types the message into that session's pane and presses Enter — exactly as if you +typed it yourself (via `tmux send-keys`; the provider is never intercepted). Great for +unblocking an agent across repos without losing your place. + +Broadcast to many at once, or end sessions: + +```sh +sloop ps --all # also lists tmux sessions you started yourself (unmanaged) +sloop adopt agy -w myrepo --as agy # bring an external session into the fleet (rename to myrepo__agy) +sloop approve --waiting # send each waiting agent its Yes/Approve answer (one command) +sloop approve 1 # approve just session #1 +sloop send --waiting "yes, go ahead" # custom reply to every agent waiting on you +sloop send --all "stash and pause" # every running session (asks to confirm) +sloop kill 2 # end one session (asks to confirm; -y to skip) +sloop kill --waiting # end all that are waiting +sloop kill --all -y # clean up everything (global -y = assume yes) +``` + +### Fleet HUD popup (tmux ≥ 3.2) + +Pop the whole cross-repo fleet over whatever you're doing — glance, answer, jump, and it closes back +to your work without losing your place: + +```sh +sloop popup # open the fleet popup now (must be inside tmux) +sloop popup setup # bind g to it (and print the line for ~/.tmux.conf) +sloop popup setup --key f # use a different key +``` + +After `setup`, press your tmux **prefix then `g`** from inside any agent to summon the HUD: the `ps` +control center appears floating, you answer/jump with one key, and the popup vanishes. (Native Windows +psmux may not support popups; everything else still works.) + +--- + +## 4. Context delivery without launching + +```sh +sloop sync # (re)deliver for the default tool +sloop sync claude # a specific tool +sloop sync --all # every enabled tool +sloop sync --repair # if a file/dir you didn't create occupies a target, + # move it aside (*.sloopbak-) and write sloop's — never deletes +sloop status # one-line delivery state +``` + +`sloop status` example: +``` +⚓ my-service ~/code/my-service + tools: claude*, codex, cursor, gemini (* default) + context: AGENTS.md ok · CLAUDE.md ok + skills: 3 in .sloop/skills · linked: claude + hooks: auto: claude, gemini (sloop hooks list) + running: 2 sessions (sloop ps) +``` + +Delivery is **create-if-missing**: sloop never overwrites a file you hand-authored (it warns). +`AGENTS.md` is always yours — sync/repair never touch it. + +--- + +## 5. Skills (shared across every tool) + +```sh +sloop skills new code-review # scaffold + link into your tools +sloop skills add https://example.com/review.md # import from a URL +sloop skills add https://github.com/o/r/blob/main/review.md # GitHub blob URL (auto-raw) +sloop skills add --name custom-name # override the derived name +sloop skills update # re-fetch every imported skill +sloop skills update code-review # re-fetch just one +``` + +Skills live in `.sloop/skills/*.md` and are **symlinked** into each tool's skills dir — write or +import once, every tool sees the same set. `skills new`/`add` link them in automatically (`skill` +and `sk` are aliases). If a tool isn't linked yet, run `sloop sync`. + +Imported skills are recorded in **`.sloop/skills.lock`** (name + source + content hash). Commit it so +your team gets reproducible skills, and run `sloop skills update` (`up`) to re-fetch from the recorded +sources — only changed files are rewritten and relinked. Locally authored (`skills new`) skills aren't +locked, since they have no upstream source. + +--- + +## 6. Inventory + +```sh +sloop tools # adapters + install status +sloop ls # registered workspaces + recent sessions (history, from SQLite) +sloop doctor # environment health (tools, tmux, mode) +``` + +(`ls` = registry/history; `ps` = what's live right now.) + +--- + +## 7. Shell completion (autocomplete) + +Install once, then Tab-complete commands, flags **and live values**: + +```sh +# zsh (add to ~/.zshrc, or drop into a completions dir) +source <(sloop completion zsh) +# bash +source <(sloop completion bash) +# fish +sloop completion fish | source +``` + +Completion is **dynamic**: `sloop run ` lists your tools, `-w ` lists registered +workspaces, and `sloop ps`/`send`/`attach ` list the sessions running right now (with the +session name shown next to each `ps` number). + +--- + +## 8. Hints (learn as you go) + +New to tmux/CLI? sloop occasionally prints one short `💡` tip after a command — what "detach" means, +how `ps` works, that `hooks install` makes status precise. They're **contextual** (tied to the +command), **throttled** (never more than one every few minutes, no repeats), and **offline** (ship +with the binary, updated on new releases). + +```sh +sloop hints # list every tip in your language +sloop hints off # turn tips off (sloop hints on to re-enable) +SLOOP_LANG=vi sloop … # tips in Vietnamese (en + vi ship today) +SLOOP_NO_HINTS=1 … # one-off: silence tips for a single command +``` + +Language is picked from `SLOOP_LANG` → the `lang` field in `~/.sloop/config.yaml` → `$LANG` → English. +Add a language by adding its key to `internal/hints/hints.yaml`. (A future release may also pull an +updated hint set from a registry / the global DB — embedded is the source for now.) + +--- + +## Full dogfood walkthrough + +```sh +# Two real projects +cd ~/code/api && sloop init && $EDITOR AGENTS.md # fill in guidance +cd ~/code/web && sloop init && $EDITOR AGENTS.md + +# Work the api with a coder + reviewer side by side +cd ~/code/api && sloop run --split claude cursor + +# Detach (Ctrl-b d), start the web one too +cd ~/code/web && sloop run claude + +# From anywhere, see the whole fleet and who needs you +sloop ps +sloop ps 1 # jump to the one that's waiting +``` + +**What to watch for while dogfooding:** does `sloop ps` + the glance line actually let you triage +"which agent needs me" across repos faster than flipping through tmux windows yourself? That's the +question that decides whether the orchestration direction is worth doubling down on. + +--- + +## Limits (today) + +- Orchestration (`ps`, `run --split`, `attach`, `send`) needs a tmux-compatible multiplexer: + **tmux** on macOS/Linux, **psmux** on native Windows (auto-detected; `SLOOP_MUX` overrides). + Without one, the orchestration commands are unavailable but everything else (`init`, `sync`, + `skills`, `hooks`, `tools`, `status`, the registry DB) works fine. The multiplexer backend lives in + `internal/tmux` behind the `runner.Runner` seam. **Note:** the psmux path is wired but not yet + verified on a real Windows box — please report flag incompatibilities. +- The `ps` glance is a heuristic by default; install each tool's hooks (`sloop hooks install`) to make + status authoritative. +- `sloop` launches tool binaries directly (no shell), so an adapter's `launch:` must be a plain + command, not a shell pipeline. diff --git a/docs/reference/ADAPTERS.md b/docs/reference/ADAPTERS.md new file mode 100644 index 0000000..49c4657 --- /dev/null +++ b/docs/reference/ADAPTERS.md @@ -0,0 +1,114 @@ +# Adapters — the provider-capability contract + +Sloop is multi-provider. **All per-provider knowledge lives in one place: the adapter manifest.** +Every provider-aware feature reads it; no feature hardcodes a tool name. + +> **The rule:** to support a new AI CLI, add one manifest. Never special-case a tool in code. + +## Where manifests live + +- **Built-in:** `internal/adapter/builtin/.yaml`, embedded in the binary (`go:embed`). +- **User overrides / new tools:** `~/.sloop/adapters/.yaml`. A file with the same key + overrides the built-in; a new key adds a tool. Loaded by `adapter.Load()` + (`internal/adapter/adapter.go`). + +Manifests are sloop's *provider knowledge / plugin layer* — **not** user config. Users normally +never touch them (enabled tools are chosen in `.sloop/config.yaml`; see `docs/reference/CONFIG.md`). + +## Manifest schema + +```yaml +name: Claude Code # display name +detect: claude # binary name used to detect installation +launch: claude # binary to launch + +context: # how AGENTS.md context reaches the tool + mode: pointer # "pointer" (write a pointer file) | "native" (reads AGENTS.md itself) + file: CLAUDE.md # pointer file name (pointer mode only) + +skills: # how .sloop/skills is delivered + target: .claude/skills # dir to symlink skills into; "" = tool has no skills dir + +hooks: # status hooks for `sloop ps` (see docs/guide/USAGE.md) + config: .claude/settings.local.json # where the tool configures hooks (repo-relative or ~/…) + install: settings-json # installer strategy: "settings-json" | "" (manual) + docs: https://… # link to the tool's hook docs + notes: "" # caveats for manual setup + events: # the tool's event name for each sloop state + working: UserPromptSubmit # "" if the tool can't signal that state + waiting: Notification + idle: Stop + +run: # `sloop run` model/effort knobs (all optional) — see docs/design/run.md + vendor: anthropic # model vendor this CLI natively serves + default_for: [anthropic] # vendors this CLI is the home launcher for (bare `sloop run opus`) + model_flag: "--model" # how to pass a model; "" = no model selection + effort_flag: "" # how to pass reasoning effort; "" = unsupported + effort_values: {} # low|medium|high → the CLI's own token (e.g. -c model_reasoning_effort=high) + models: [opus, sonnet] # aliases for completion + bare-model resolution (forwarded as-is) + prompt: positional # how `run -t "task"` is passed: "positional" | a flag | "" (none) + +heuristics: # OPTIONAL fallback status markers (see below) — usually omit + waiting: ["shall I apply"] # tool-specific phrasing the cross-tool defaults miss + working: ["indexing repo"] +``` + +## Which features are manifest-driven + +| Feature | Reads | Field | +|---|---|---| +| detect / `sloop tools` | `detect.Tools` | `detect` | +| `sloop run` launch | `run.go` | `launch` | +| `sloop run` model/effort | `run.go` (`planLaunch`/`buildRunArgs`) | `run.*` | +| `sloop sync` context | `sync` | `context.mode/file` | +| skills symlink | `sync` | `skills.target` | +| `sloop hooks` + status | `hooks.go` | `hooks.*` | +| `sloop ps` status fallback | `tmux.ClassifyStatus` | `heuristics.*` (additive; see below) | +| shell completion | `completion.go` | manifest keys | + +The runtime view of all of this is **`sloop tools`** (capability matrix: +`KEY NAME INSTALLED CONTEXT SKILLS HOOKS`). + +## Hook install strategies + +- `settings-json` — merge `events → "sloop hooks emit "` into a JSON settings file + (`mergeSettingsHooks`/`installSettingsHooks`). Used by **claude** and **gemini** (identical nested + `hooks[event] = [{hooks:[{type,command}]}]` shape). Written idempotently, never clobbering keys. +- `cursor-json` — merge into `.cursor/hooks.json`, Cursor's flatter shape + (`{version, hooks[event]=[{command}]}`; `mergeCursorHooks`/`installCursorHooks`). Used by **cursor**. + Note: Cursor has no clean "blocked on user" event (`beforeShellExecution` fires on every command), + so its manifest leaves `waiting: ""` and the pane heuristic covers waiting. +- `""` (manual) — no safe auto-writer yet; `sloop hooks print ` shows the exact + event→command wiring and `sloop hooks list` marks it `print+paste`. **Copilot/Codex** are here: + Copilot uses a single `notification` event with matchers (`permission_prompt`/`agent_idle`/…) plus + per-OS `bash`/`powershell` keys; Codex is TOML with one `notify` program for all events (would need + payload routing). Both need a matcher-aware model before auto-install. + +Strategies dispatch through `hookInstaller(strategy)` — add a `case` there + an `install…Hooks` +writer to teach a new config format. + +## Status heuristics (fallback only) + +`sloop ps` classifies each session as waiting / working / idle. The **precise** signal is the +`hooks` above (the tool tells sloop its state). Heuristics are the **fallback** when hooks aren't +installed: a non-invasive read of the tool's own pane text. + +Most prompt conventions — `(y/n)`, `press enter`, `esc to interrupt`, spinners, `tokens` — are +**cross-tool defaults** baked in once (`defaultWaitingMarkers`/`defaultWorkingMarkers` in +`internal/tmux/status.go`) and applied to **every** manifest. They are terminal conventions, not +per-provider knowledge, so they live in code, not duplicated into each YAML. + +A manifest's optional `heuristics` block is **additive on top of** the defaults — add markers only +for phrasing a specific tool uses that the defaults genuinely miss. If a tool needs none (most don't, +e.g. claude), omit the block. Don't re-list default markers. If you want precision, install the +tool's hooks rather than growing heuristics. + +## Adding a new CLI (checklist) + +1. Drop `internal/adapter/builtin/.yaml` (or `~/.sloop/adapters/.yaml`) with the schema + above. Set `hooks.events`/`install` from the tool's hook docs. +2. Verify with `sloop tools` (capabilities) and `sloop hooks print `. +3. If its hooks use the settings.json shape, `install: settings-json` makes it auto-install for free. + Otherwise leave `install: ""` and it's print-and-paste until a strategy is added. + +No Go code changes are required for a new provider unless it needs a brand-new hook install strategy. diff --git a/docs/reference/ARCHITECTURE.md b/docs/reference/ARCHITECTURE.md new file mode 100644 index 0000000..be91bac --- /dev/null +++ b/docs/reference/ARCHITECTURE.md @@ -0,0 +1,90 @@ +# Sloop — Architecture + +Sloop is a **single, local-first CLI binary** (Cobra). No daemon, no gRPC, no background service — +every command runs to completion over plain files plus a local SQLite database. The design goal is +that **all per-provider knowledge lives in declarative adapter manifests** and the rest is small, +composable packages behind clear seams. + +```text + Developer + │ + ▼ + ┌──────────────┐ + │ sloop │ one binary (cli/commands) + └──────┬───────┘ + ┌───────────┬────────┼───────────┬──────────────┐ + ▼ ▼ ▼ ▼ ▼ + adapter sync runner tmux session + (YAML manifest: (deliver (Runner (multiplexer: (SQLite: workspaces + detect/launch/ pointers + interface: tmux/psmux — + history; WAL + + context/skills/ skills exec or list/capture/ user_version + hooks/scaffold) symlinks) tmux) send/split/ migrations) + │ │ │ kill) │ + ▼ ▼ ▼ │ ▼ + detect scan hints ▼ fleetstate + (which tools (codebase (contextual (ps/send/ (~/.sloop/state: + are on PATH) → AGENTS) tips, i18n) attach) hook status markers) + + AI CLIs (Claude Code, Cursor, Codex, Copilot, Gemini, Antigravity) + ▲ + sloop launches them with context already in place, inside a + `__` session — which is what makes the fleet view work. +``` + +## Packages (`internal/`) + +| Package | Responsibility | +|---|---| +| `cli/commands` | All Cobra commands; the only place that wires the pieces together. | +| `adapter` | Loads embedded + user **manifests** (the single source of per-provider knowledge). | +| `config` | Local project config (`.sloop/config.yaml`) and global config (`~/.sloop/config.yaml`). | +| `detect` | On-demand "which tools / multiplexer are installed" (PATH lookups). | +| `sync` | Context delivery: `AGENTS.md`, pointer files, skills symlinks — all create-if-missing, with `--repair`. | +| `scan` | Heuristic, offline codebase scan → a pre-filled `AGENTS.md` (no LLM). | +| `runner` | The abstract launch seam: `Runner`/`Spec`/`ExecRunner`. tmux-free. | +| `tmux` | The tmux/psmux backend: build args, parse sessions, capture/send/split/kill, status classification, `tmux.Runner`. `Bin()` picks tmux→psmux. | +| `fleetstate` | Per-session status markers under `~/.sloop/state`, written by tool hooks, read by `ps`. | +| `session` | SQLite store (workspaces registry + session history); WAL + `PRAGMA user_version` migrations. | +| `hints` | Embedded, throttled, i18n (en/vi) education tips shown after commands. | +| `tui` | Zero-dependency raw-mode menu (`SelectMenu`/`SelectAction`) + color helpers (NO_COLOR-aware). | +| `workspace` | Resolve the workspace (walk up to `.sloop/`, or `-w` via the registry). | + +## How a launch works + +`sloop run [tool]`: + +1. **Resolve workspace** — walk up from cwd to `.sloop/`, or `-w ` via the global registry. +2. **Resolve tool** — the argument, or `default_tool` from `.sloop/config.yaml` (no per-tool profile + files; the enabled set is the single source). +3. **Sync** — ensure `AGENTS.md`; write the tool's pointer file if it's a pointer-mode adapter and the + file is absent; symlink `.sloop/skills` into the tool's skills dir. +4. **Record the session** — best-effort row in SQLite (a failure warns, never blocks the launch). +5. **Launch** — `tmux.Runner` (`__` session) when a multiplexer is present, else + `runner.ExecRunner` (plain exec). Args after `--` pass straight through. + +`sloop sync` runs steps 1–3 only. The fleet commands (`ps`, `send`, `attach`, `kill`) operate purely +over the multiplexer + `fleetstate`, never touching the AI provider's process or API. + +## Storage + +| Location | Contents | Git | +|---|---|---| +| `/AGENTS.md` | canonical context (hand-authored) | committed | +| `/.sloop/` | `config.yaml`, `skills/` (committed); `vault/` (gitignored) | committed | +| generated `CLAUDE.md`, `.claude/skills`, … | pointer files + symlinks | your choice | +| `~/.sloop/sloop.db` | workspaces registry + session history (SQLite/WAL) | machine-local | +| `~/.sloop/state/*.json` | per-session hook status markers (TTL'd) | machine-local | +| `~/.sloop/adapters/*.yaml` | user-added / override tool manifests | machine-local | +| `~/.sloop/config.yaml`, `hints-state.json` | machine prefs + hint throttle state | machine-local | + +## Principles & seams + +- **Manifest-driven** — every provider-aware feature reads `adapter` manifests; never hardcode a tool. + See [ADAPTERS.md](ADAPTERS.md). +- **Provider-respecting** — status uses each tool's *own* hooks or non-invasive `capture-pane` of your + own terminal; sloop never intercepts the provider's API or process. +- **Lightweight & local-first** — one CGO-free binary (`modernc.org/sqlite`), no daemon, no cloud. +- **The multiplexer is a seam** — tmux today, psmux on Windows, a future backend behind the same + `runner.Runner`/`tmux` boundary. +- **Cede in-repo orchestration** — worktrees/dashboards/conflict-detection belong to ntm / Claude + Squad; sloop's edge is portable context + the cross-repo fleet. diff --git a/docs/reference/CONFIG.md b/docs/reference/CONFIG.md new file mode 100644 index 0000000..207a1ce --- /dev/null +++ b/docs/reference/CONFIG.md @@ -0,0 +1,69 @@ +# Config — the three layers + +Sloop keeps a clear split: **user config is unified** (one local + one global file), and only the +*provider knowledge* (adapter manifests, see `docs/reference/ADAPTERS.md`) is per-provider. This matches how +peers do it — aider has a single `.aider.conf.yml`; Claude Squad a single `~/.claude-squad/config.json` +with programs listed inside — while sloop's extra global/local split fits its cross-repo + per-project +nature. + +## 1. Global — `~/.sloop/` (machine-wide) + +| Path | Purpose | +|---|---| +| `config.yaml` | machine prefs: `version`, `mode` (`ask`/`auto`) | +| `sloop.db` | workspace registry + session history (SQLite, pure-Go) | +| `state/` | hook-written status markers (`.json`) read by `sloop ps` | +| `adapters/` | user adapter overrides / new tools (`.yaml`) | + +```yaml +# ~/.sloop/config.yaml +version: 1 +mode: ask +lang: vi # optional: hint language (en/vi); empty = auto from $SLOOP_LANG/$LANG +hints: false # optional: turn the 💡 education tips off (omit/true = on) +``` + +## 2. Local — `.sloop/` (per repo, committed) + +| Path | Purpose | +|---|---| +| `config.yaml` | project config: `version`, `tools`, `default_tool`, `mode?` | +| `skills/` | reusable `*.md` skills (symlinked into each tool) | +| `vault/` | personal notes (not delivered to tools) | +| `.gitignore` | ignores local caches | + +```yaml +# .sloop/config.yaml +version: 1 +tools: [claude, codex, cursor, gemini] # which tools are enabled (the single source) +default_tool: claude +``` + +Plus, at the repo root: `AGENTS.md` (canonical context, hand-authored, committed) and pointer files +(`CLAUDE.md`/`GEMINI.md`, create-if-missing). + +## 3. Built-in — adapter manifests + +Provider knowledge (`detect/launch/context/skills/hooks`), embedded in the binary, overridable in +`~/.sloop/adapters/`. See `docs/reference/ADAPTERS.md`. **Not** user config. + +## `version` and forward-compat + +Both config files carry `version: 1`. Configs without it still load (defaulted). When the schema +changes, bump `version` and migrate on load. + +### Roadmap homes (why config stays simple) + +Each planned direction has its own home, so user config doesn't fragment per provider: + +| Direction | Lives in | +|---|---| +| Registry (skills / adapters) | `.sloop/skills.lock`, `~/.sloop/adapters/` | +| AI-awareness (status/hooks) | adapter manifest `hooks:` + `~/.sloop/state/` | +| DX / AI-usage | CLI flags + shell completion | +| Guidelines | `AGENTS.md` + `.sloop/skills/` | +| 2nd brain | `.sloop/vault/` + `sloop.db` | + +There are **no per-tool user config files**. If named launch configs are ever wanted (e.g. +`reviewer = claude + args`), they return as a `profiles:` **map inside** `.sloop/config.yaml` +(gated by `version`), not as separate files. diff --git a/internal/adapter/adapter.go b/internal/adapter/adapter.go index 83c9c8b..8f37e5b 100644 --- a/internal/adapter/adapter.go +++ b/internal/adapter/adapter.go @@ -42,6 +42,42 @@ type HooksSpec struct { Events HookEvents `yaml:"events"` } +// HeuristicsSpec defines fallback text-matching rules to classify agent status +// when native hooks aren't available. In the future, this could be extended +// with LLM prompts for deeper "AI awareness" of the session state. +type HeuristicsSpec struct { + Working []string `yaml:"working"` + Waiting []string `yaml:"waiting"` +} + +// RunSpec declares how `sloop run` launches a tool with an optional model and +// reasoning effort. Every field is optional: an empty flag means the CLI has no +// such knob, and sloop errors clearly if the user asks for it. sloop never +// validates the model — it forwards the string and lets the CLI accept/reject it. +type RunSpec struct { + // Vendor is the model vendor this CLI natively serves (e.g. "anthropic"). + Vendor string `yaml:"vendor"` + // DefaultFor lists vendors this CLI is the canonical launcher for, so a bare + // model (`sloop run opus`) resolves to it. + DefaultFor []string `yaml:"default_for"` + // ModelFlag is how the CLI selects a model (e.g. "--model"); "" = unsupported. + ModelFlag string `yaml:"model_flag"` + // EffortFlag + EffortValues express reasoning effort: low|medium|high mapped + // to the CLI's own token. "" flag = the CLI has no effort knob. + EffortFlag string `yaml:"effort_flag"` + EffortValues map[string]string `yaml:"effort_values"` + // Models are the model aliases this CLI serves (completion + bare-model + // resolution). Not exhaustive; full API ids still work via forward. + Models []string `yaml:"models"` + // Prompt is how an initial interactive task (`sloop run … -t "…"`) is passed: + // "positional" appends it as a bare arg, a flag string passes ` `, + // "" = the CLI has no initial-task support via sloop. + Prompt string `yaml:"prompt"` + // ResumeFlag continues the most recent conversation (used by `sloop restore + // --resume`); "" = the CLI can't resume. + ResumeFlag string `yaml:"resume_flag"` +} + type Manifest struct { Name string `yaml:"name"` // Detect is the binary name used to detect installation; Launch is the @@ -51,6 +87,10 @@ type Manifest struct { Context ContextSpec `yaml:"context"` Skills SkillsSpec `yaml:"skills"` Hooks HooksSpec `yaml:"hooks"` + // Run declares model/effort launch knobs for `sloop run`. + Run RunSpec `yaml:"run"` + // Fallback text-parsing rules for status (paving the way for AI-driven awareness) + Heuristics HeuristicsSpec `yaml:"heuristics"` // Scaffold lists the tool's standard project dirs that `sloop init --scaffold` // can create (e.g. .claude/skills, .cursor/rules), so users start from the // provider's expected layout instead of an ad-hoc one. diff --git a/internal/adapter/builtin/claude.yaml b/internal/adapter/builtin/claude.yaml index 348801a..d7cc13b 100644 --- a/internal/adapter/builtin/claude.yaml +++ b/internal/adapter/builtin/claude.yaml @@ -18,3 +18,14 @@ hooks: working: UserPromptSubmit waiting: Notification idle: Stop +run: + vendor: anthropic + default_for: [anthropic] + model_flag: "--model" # accepts opus/sonnet/haiku/fable or a full id (claude-opus-4-8) + models: [opus, sonnet, haiku, fable] + prompt: positional # `claude "task"` seeds an interactive session (claude -p exits) + resume_flag: "--continue" # `claude --continue` resumes the repo's most recent conversation +# No `heuristics:` block: Claude's prompts use the cross-tool defaults (see +# defaultWaitingMarkers/defaultWorkingMarkers in internal/tmux/status.go). +# Precise status comes from the hooks above; heuristics are only the fallback. +# Add a heuristics block here only for phrasing the defaults genuinely miss. diff --git a/internal/adapter/builtin/codex.yaml b/internal/adapter/builtin/codex.yaml index 0b3eeb5..78ca2cd 100644 --- a/internal/adapter/builtin/codex.yaml +++ b/internal/adapter/builtin/codex.yaml @@ -18,3 +18,12 @@ hooks: working: "" waiting: approval-requested idle: agent-turn-complete +run: + vendor: openai + default_for: [openai] + model_flag: "--model" + effort_flag: "-c" # codex takes reasoning effort as a config override + effort_values: + low: model_reasoning_effort=low + medium: model_reasoning_effort=medium + high: model_reasoning_effort=high diff --git a/internal/adapter/builtin/cursor.yaml b/internal/adapter/builtin/cursor.yaml index 40fc132..fe2cc3b 100644 --- a/internal/adapter/builtin/cursor.yaml +++ b/internal/adapter/builtin/cursor.yaml @@ -11,10 +11,13 @@ scaffold: - .cursor/rules hooks: config: .cursor/hooks.json - install: "" + install: cursor-json docs: https://cursor.com/docs/hooks - notes: CLI hooks since v1.7 (sessionStart/stop/prompt) + notes: hooks.json {version,hooks}; no clean "blocked on user" event, so waiting is left to the pane heuristic events: working: beforeSubmitPrompt - waiting: beforeShellExecution + waiting: "" # beforeShellExecution fires on every command, not only when blocked — would mislabel; heuristic handles cursor's approval prompts idle: stop +run: + model_flag: "--model" # e.g. agent --model gpt-5 (Cursor is multi-vendor; no bare-model home) + prompt: positional # `agent "task"` seeds an interactive session (agent -p is print mode) diff --git a/internal/adapter/builtin/gemini.yaml b/internal/adapter/builtin/gemini.yaml index eb84273..70f486c 100644 --- a/internal/adapter/builtin/gemini.yaml +++ b/internal/adapter/builtin/gemini.yaml @@ -15,3 +15,7 @@ hooks: working: BeforeAgent waiting: Notification idle: AfterAgent +run: + vendor: google + default_for: [google] + model_flag: "--model" diff --git a/internal/adapter/builtins_test.go b/internal/adapter/builtins_test.go index be6024c..7509fdc 100644 --- a/internal/adapter/builtins_test.go +++ b/internal/adapter/builtins_test.go @@ -27,7 +27,7 @@ func TestBuiltinManifests(t *testing.T) { }{ "claude": {"claude", "pointer", ".claude/skills", "settings-json"}, "gemini": {"gemini", "pointer", "", "settings-json"}, - "cursor": {"agent", "native", "", ""}, + "cursor": {"agent", "native", "", "cursor-json"}, "codex": {"codex", "native", "", ""}, "copilot": {"copilot", "native", "", ""}, "agy": {"agy", "native", "", ""}, diff --git a/internal/cli/commands/approve.go b/internal/cli/commands/approve.go index 98f4d13..a5f3c0a 100644 --- a/internal/cli/commands/approve.go +++ b/internal/cli/commands/approve.go @@ -6,6 +6,7 @@ import ( "github.com/spf13/cobra" + "github.com/stroops/sloop/internal/adapter" "github.com/stroops/sloop/internal/tmux" ) @@ -18,7 +19,11 @@ func RunApprove(w io.Writer, in io.Reader, targets []string, all, waiting, yes b if !tmux.Available() { return nil, fmt.Errorf("tmux is not installed; `sloop approve` needs tmux") } - rows := enrichGlances(fleetRows(tmux.ParseSessions(tmuxList()))) // need prompts/answers + manifests, _ := adapter.Load() + // Enrich first so each row has a Status; selectSessions does its own + // filterWaiting for the --waiting case (mirrors kill). Pre-filtering here + // would run before Status is set and drop every row. + rows := enrichGlances(fleetRows(tmux.ParseSessions(tmuxList())), manifests) sel, err := selectSessions(rows, targets, all, waiting) if err != nil { return nil, err diff --git a/internal/cli/commands/attach.go b/internal/cli/commands/attach.go index e4e4626..52b8f57 100644 --- a/internal/cli/commands/attach.go +++ b/internal/cli/commands/attach.go @@ -30,12 +30,22 @@ func RunAttach(session string) error { } var attachCmd = &cobra.Command{ - Use: "attach ", + Use: "attach [session]", Aliases: []string{"a"}, - Short: "Attach to a tmux session created by sloop", - Args: cobra.ExactArgs(1), + Short: "Attach to a sloop session (no name = pick from the fleet)", + Long: `Attach to a tmux session sloop created. Give a session name to attach +directly, or run it with no argument (` + "`sloop a`" + `) to pick one from the +running fleet.`, + Args: cobra.MaximumNArgs(1), RunE: func(cmd *cobra.Command, args []string) error { - return RunAttach(args[0]) + if len(args) == 1 { + return RunAttach(args[0]) + } + name, err := pickFleetSession("⚓ Attach to which agent?") + if err != nil || name == "" { + return err + } + return RunAttach(name) }, } diff --git a/internal/cli/commands/completion.go b/internal/cli/commands/completion.go index ad43f7b..97d418e 100644 --- a/internal/cli/commands/completion.go +++ b/internal/cli/commands/completion.go @@ -30,6 +30,27 @@ func completeTools(_ *cobra.Command, _ []string, _ string) ([]string, cobra.Shel return names, cobra.ShellCompDirectiveNoFileComp } +// completeModels suggests the model aliases every adapter declares (run.models), +// e.g. for `run -m`. Aliases only — full API ids still work but aren't listed. +func completeModels(_ *cobra.Command, _ []string, _ string) ([]string, cobra.ShellCompDirective) { + manifests, err := adapter.Load() + if err != nil { + return nil, cobra.ShellCompDirectiveNoFileComp + } + seen := map[string]bool{} + var models []string + for _, m := range manifests { + for _, a := range m.Run.Models { + if !seen[a] { + seen[a] = true + models = append(models, a) + } + } + } + sort.Strings(models) + return models, cobra.ShellCompDirectiveNoFileComp +} + // completeWorkspaces suggests registered workspace names (for -w/--workspace). func completeWorkspaces(_ *cobra.Command, _ []string, _ string) ([]string, cobra.ShellCompDirective) { return workspaceNames(), cobra.ShellCompDirectiveNoFileComp diff --git a/internal/cli/commands/hook.go b/internal/cli/commands/hook.go index 5192bd0..1e007f1 100644 --- a/internal/cli/commands/hook.go +++ b/internal/cli/commands/hook.go @@ -39,25 +39,32 @@ func RunHook(state string) error { return fleetstate.Write(session, state) } -var hookCmd = &cobra.Command{ - Use: "hook ", +// hookRunE validates the state argument, drains any hook payload on stdin, and +// records the marker. It backs the hidden `hooks emit` callback that a provider's +// own lifecycle hooks invoke. +func hookRunE(cmd *cobra.Command, args []string) error { + // Drain any hook payload the tool sends on stdin; we don't need it, but + // reading avoids a broken pipe on the tool's side. + if cmd.InOrStdin() != nil { + _, _ = io.Copy(io.Discard, cmd.InOrStdin()) + } + state := args[0] + switch state { + case "waiting", "working", "idle": + default: + return fmt.Errorf("unknown state %q (want waiting|working|idle)", state) + } + return RunHook(state) +} + +// hooksEmitCmd is the internal callback an AI tool's own hooks invoke +// (`sloop hooks emit `). It lives under the `hooks` namespace for +// consistency with `skills`; it is hidden because users never type it — it is +// wired into a provider's hook config by `sloop hooks install`. +var hooksEmitCmd = &cobra.Command{ + Use: "emit ", Short: "Internal: record agent status (called by an AI tool's own hooks)", Hidden: true, Args: cobra.ExactArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - // Drain any hook payload the tool sends on stdin; we don't need it, but - // reading avoids a broken pipe on the tool's side. - if cmd.InOrStdin() != nil { - _, _ = io.Copy(io.Discard, cmd.InOrStdin()) - } - state := args[0] - switch state { - case "waiting", "working", "idle": - default: - return fmt.Errorf("unknown state %q (want waiting|working|idle)", state) - } - return RunHook(state) - }, + RunE: hookRunE, } - -func RegisterHook(cmd *cobra.Command) { cmd.AddCommand(hookCmd) } diff --git a/internal/cli/commands/hooks.go b/internal/cli/commands/hooks.go index 99e1fc4..d70f693 100644 --- a/internal/cli/commands/hooks.go +++ b/internal/cli/commands/hooks.go @@ -18,11 +18,13 @@ import ( // Hook installation is driven entirely by adapter manifests (the single // provider-aware source). A tool's manifest says where its hook config lives, // which install strategy applies, and which of its events map to sloop's -// working/waiting/idle states. Each event calls `sloop hook `, which +// working/waiting/idle states. Each event calls `sloop hooks emit `, which // records a marker `sloop ps` reads. -// hookCommandFor is the shell command a tool runs for a sloop state. -func hookCommandFor(state string) string { return appName + " hook " + state } +// hookCommandFor is the shell command a tool runs for a sloop state. It is the +// reserved `sloop hooks emit ` callback — its prefix is how sloop's own +// status hooks stay identifiable and never collide with workflow hooks. +func hookCommandFor(state string) string { return appName + " hooks emit " + state } // eventCommands turns a manifest's event→state mapping into the event→command // map the installers and printers use, skipping states the tool can't signal. @@ -118,6 +120,90 @@ func installSettingsHooks(path string, events map[string]string) (bool, error) { return true, os.WriteFile(path, append(out, '\n'), 0o644) } +// mergeCursorHooks adds event→command hooks to a .cursor/hooks.json document. +// Cursor's shape is flatter than settings.json: hooks[event] is an array of +// {command} objects. Existing hooks are preserved and the merge is idempotent. +func mergeCursorHooks(root map[string]any, events map[string]string) (map[string]any, bool) { + if root == nil { + root = map[string]any{} + } + hooks, _ := root["hooks"].(map[string]any) + if hooks == nil { + hooks = map[string]any{} + } + changed := false + for event, cmd := range events { + if hasCursorCommand(hooks[event], cmd) { + continue + } + arr, _ := hooks[event].([]any) + hooks[event] = append(arr, map[string]any{"command": cmd}) + changed = true + } + if changed { + root["hooks"] = hooks + if _, ok := root["version"]; !ok { + root["version"] = 1 + } + } + return root, changed +} + +// hasCursorCommand reports whether an event's hook array already contains the +// given command (so install is idempotent). +func hasCursorCommand(eventVal any, cmd string) bool { + arr, ok := eventVal.([]any) + if !ok { + return false + } + for _, h := range arr { + hm, ok := h.(map[string]any) + if !ok { + continue + } + if c, _ := hm["command"].(string); c == cmd { + return true + } + } + return false +} + +// installCursorHooks merges events into the .cursor/hooks.json file at path, +// creating it if needed. Returns whether the file changed. +func installCursorHooks(path string, events map[string]string) (bool, error) { + doc := map[string]any{} + if b, err := os.ReadFile(path); err == nil { + if err := json.Unmarshal(b, &doc); err != nil { + return false, fmt.Errorf("%s is not valid JSON: %w", path, err) + } + } + merged, changed := mergeCursorHooks(doc, events) + if !changed { + return false, nil + } + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + return false, err + } + out, err := json.MarshalIndent(merged, "", " ") + if err != nil { + return false, err + } + return true, os.WriteFile(path, append(out, '\n'), 0o644) +} + +// hookInstaller returns the writer for a manifest's install strategy, or nil if +// the strategy has no safe auto-writer yet (then `hooks print` shows the wiring). +func hookInstaller(strategy string) func(path string, events map[string]string) (bool, error) { + switch strategy { + case "settings-json": + return installSettingsHooks + case "cursor-json": + return installCursorHooks + default: + return nil + } +} + // resolveHookConfigPath turns a manifest config path into an absolute path: ~/… // expands to the home dir, absolute paths pass through, and a repo-relative path // is joined to the workspace root. @@ -169,8 +255,15 @@ func manifestForTool(tool string) (adapter.Manifest, error) { } var hooksCmd = &cobra.Command{ - Use: "hooks", - Short: "Install AI tool hooks so `sloop ps` knows agent status precisely", + Use: "hooks", + Aliases: []string{"hk", "hook"}, + Short: "Wire a tool's status hooks so `sloop ps` knows agent state precisely", + Long: `Manage status hooks: each tool calls sloop from its own lifecycle events so +sloop ps reports waiting/working/idle precisely (not just a screen guess). + +These are status hooks (for the fleet view). Portable workflow hooks — +format/lint/policy automation installed into each tool — are a v0.2.0 proposal; +see docs/design/hooks.md.`, } var hooksInstallCmd = &cobra.Command{ @@ -186,7 +279,8 @@ var hooksInstallCmd = &cobra.Command{ if err != nil { return err } - if m.Hooks.Install != "settings-json" { + install := hookInstaller(m.Hooks.Install) + if install == nil { cmd.Printf("auto-install isn't available for %s yet.\n", tool) cmd.Printf("Run `sloop hooks print %s` for the exact events to wire in %s.\n", tool, m.Hooks.Config) return nil @@ -203,7 +297,7 @@ var hooksInstallCmd = &cobra.Command{ if err != nil { return err } - changed, err := installSettingsHooks(path, eventCommands(m.Hooks)) + changed, err := install(path, eventCommands(m.Hooks)) if err != nil { return err } @@ -231,11 +325,17 @@ var hooksPrintCmd = &cobra.Command{ if err != nil { return err } - if m.Hooks.Install == "settings-json" { + switch m.Hooks.Install { + case "settings-json": doc, _ := mergeSettingsHooks(nil, eventCommands(m.Hooks)) out, _ := json.MarshalIndent(doc, "", " ") cmd.Printf("# %s — add to %s\n%s\n", tool, m.Hooks.Config, string(out)) return nil + case "cursor-json": + doc, _ := mergeCursorHooks(nil, eventCommands(m.Hooks)) + out, _ := json.MarshalIndent(doc, "", " ") + cmd.Printf("# %s — add to %s\n%s\n", tool, m.Hooks.Config, string(out)) + return nil } cmd.Printf("# %s hooks → call these from %s\n", tool, m.Hooks.Config) cmd.Printf(" working : on %-22s → run: %s\n", orDash(m.Hooks.Events.Working), hookCommandFor("working")) @@ -253,23 +353,25 @@ var hooksPrintCmd = &cobra.Command{ var hooksListCmd = &cobra.Command{ Use: "list", - Short: "Show hook support and event mapping for every AI provider", + Short: "Show status-hook support and event mapping for every AI provider", Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, args []string) error { manifests, err := adapter.Load() if err != nil { return err } + cmd.Println("Status hooks — report waiting/working/idle to `sloop ps`:") cmd.Printf("%-9s %-12s %s\n", "TOOL", "AUTO-INSTALL", "CONFIG") for _, tool := range hookTools() { m := manifests[tool] auto := "print+paste" - if m.Hooks.Install == "settings-json" { + if hookInstaller(m.Hooks.Install) != nil { auto = "yes" } cmd.Printf("%-9s %-12s %s\n", tool, auto, m.Hooks.Config) } cmd.Println("\nDetails: sloop hooks print ") + cmd.Println("(Workflow hooks — format/lint/policy — are v0.2.0; see docs/design/hooks.md.)") hints.Show(cmd.OutOrStdout(), "hooks") return nil }, @@ -282,5 +384,6 @@ func RegisterHooks(cmd *cobra.Command) { hooksCmd.AddCommand(hooksInstallCmd) hooksCmd.AddCommand(hooksPrintCmd) hooksCmd.AddCommand(hooksListCmd) + hooksCmd.AddCommand(hooksEmitCmd) cmd.AddCommand(hooksCmd) } diff --git a/internal/cli/commands/hooks_test.go b/internal/cli/commands/hooks_test.go index 39b8615..4f2ba24 100644 --- a/internal/cli/commands/hooks_test.go +++ b/internal/cli/commands/hooks_test.go @@ -9,17 +9,17 @@ import ( // claudeEvents mirrors the claude manifest's event→command mapping. var claudeEvents = map[string]string{ - "UserPromptSubmit": "sloop hook working", - "Notification": "sloop hook waiting", - "Stop": "sloop hook idle", + "UserPromptSubmit": "sloop hooks emit working", + "Notification": "sloop hooks emit waiting", + "Stop": "sloop hooks emit idle", } // geminiEvents mirrors the gemini manifest's mapping (different event names, // same settings.json shape) — proves the installer is multi-provider. var geminiEvents = map[string]string{ - "BeforeAgent": "sloop hook working", - "Notification": "sloop hook waiting", - "AfterAgent": "sloop hook idle", + "BeforeAgent": "sloop hooks emit working", + "Notification": "sloop hooks emit waiting", + "AfterAgent": "sloop hooks emit idle", } func TestMergeSettingsHooksIdempotentAndPreserving(t *testing.T) { @@ -71,7 +71,7 @@ func TestInstallSettingsHooksGemini(t *testing.T) { t.Fatalf("written file not valid JSON: %v", err) } hooks := doc["hooks"].(map[string]any) - if !hasCommandHook(hooks["Notification"], "sloop hook waiting") { + if !hasCommandHook(hooks["Notification"], "sloop hooks emit waiting") { t.Fatal("gemini Notification hook missing") } // Re-install is idempotent. @@ -80,6 +80,76 @@ func TestInstallSettingsHooksGemini(t *testing.T) { } } +// cursorEvents mirrors the cursor manifest's mapping (no waiting event; flat +// hooks.json shape). +var cursorEvents = map[string]string{ + "beforeSubmitPrompt": "sloop hooks emit working", + "stop": "sloop hooks emit idle", +} + +func TestMergeCursorHooksIdempotentAndPreserving(t *testing.T) { + root := map[string]any{ + "version": float64(1), + "hooks": map[string]any{ + "stop": []any{map[string]any{"command": "./hooks/audit.sh"}}, + }, + } + merged, changed := mergeCursorHooks(root, cursorEvents) + if !changed { + t.Fatal("expected first merge to change") + } + hooks := merged["hooks"].(map[string]any) + for event, cmd := range cursorEvents { + if !hasCursorCommand(hooks[event], cmd) { + t.Fatalf("missing hook for %s", event) + } + } + // Foreign stop hook is preserved alongside sloop's. + if !hasCursorCommand(hooks["stop"], "./hooks/audit.sh") { + t.Fatal("foreign stop hook clobbered") + } + if _, changed := mergeCursorHooks(merged, cursorEvents); changed { + t.Fatal("second merge should not change") + } +} + +func TestInstallCursorHooks(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, ".cursor", "hooks.json") + + changed, err := installCursorHooks(path, cursorEvents) + if err != nil || !changed { + t.Fatalf("install: changed=%v err=%v", changed, err) + } + b, err := os.ReadFile(path) + if err != nil { + t.Fatalf("read: %v", err) + } + var doc map[string]any + if err := json.Unmarshal(b, &doc); err != nil { + t.Fatalf("written file not valid JSON: %v", err) + } + if doc["version"] != float64(1) { + t.Fatalf("version = %v, want 1", doc["version"]) + } + hooks := doc["hooks"].(map[string]any) + if !hasCursorCommand(hooks["beforeSubmitPrompt"], "sloop hooks emit working") { + t.Fatal("cursor beforeSubmitPrompt hook missing") + } + if changed, _ := installCursorHooks(path, cursorEvents); changed { + t.Fatal("re-install should not change") + } +} + +func TestHookInstallerDispatch(t *testing.T) { + if hookInstaller("settings-json") == nil || hookInstaller("cursor-json") == nil { + t.Fatal("known strategies must have an installer") + } + if hookInstaller("") != nil || hookInstaller("codex-toml") != nil { + t.Fatal("unknown/manual strategies must have no installer") + } +} + func TestResolveHookConfigPath(t *testing.T) { if p, _ := resolveHookConfigPath("/repo", ".claude/settings.local.json"); p != "/repo/.claude/settings.local.json" { t.Fatalf("repo-relative = %q", p) diff --git a/internal/cli/commands/kill.go b/internal/cli/commands/kill.go index 49023f8..4919265 100644 --- a/internal/cli/commands/kill.go +++ b/internal/cli/commands/kill.go @@ -8,6 +8,7 @@ import ( "github.com/spf13/cobra" + "github.com/stroops/sloop/internal/adapter" "github.com/stroops/sloop/internal/tmux" ) @@ -22,13 +23,6 @@ func confirm(w io.Writer, in io.Reader, prompt string) bool { return line == "y" || line == "yes" } -// promptLine prints prompt and returns the entered line (trimmed). -func promptLine(w io.Writer, in io.Reader, prompt string) string { - _, _ = fmt.Fprint(w, prompt) - line, _ := bufio.NewReader(in).ReadString('\n') - return strings.TrimSpace(line) -} - func rowNames(rows []FleetRow) []string { out := make([]string, 0, len(rows)) for _, r := range rows { @@ -73,9 +67,10 @@ func RunKill(w io.Writer, in io.Reader, targets []string, all, waiting, yes bool if !tmux.Available() { return nil, fmt.Errorf("tmux is not installed; `sloop kill` needs tmux") } - rows := fleetRows(tmux.ParseSessions(tmuxList())) - if waiting { - rows = enrichGlances(rows) // need status to find who's waiting + manifests, _ := adapter.Load() + rows := enrichGlances(fleetRows(tmux.ParseSessions(tmuxList())), manifests) + if len(rows) == 0 { + rows = enrichGlances(rows, manifests) // need status to find who's waiting } victims, err := selectSessions(rows, targets, all, waiting) if err != nil { diff --git a/internal/cli/commands/ls.go b/internal/cli/commands/ls.go index 036cdaa..9476c48 100644 --- a/internal/cli/commands/ls.go +++ b/internal/cli/commands/ls.go @@ -3,14 +3,105 @@ package commands import ( "fmt" "io" + "os" + "os/exec" + "strings" "github.com/spf13/cobra" + "github.com/stroops/sloop/internal/adapter" "github.com/stroops/sloop/internal/config" "github.com/stroops/sloop/internal/session" + "github.com/stroops/sloop/internal/tmux" "github.com/stroops/sloop/internal/tui" + "github.com/stroops/sloop/internal/workspace" ) +// openShellIn starts the user's shell with its working directory set to dir — a +// real "go there" for a workspace without a session (a binary can't cd the +// parent shell). Exiting the shell returns to `sloop ls`. +func openShellIn(dir string) error { + sh := os.Getenv("SHELL") + if sh == "" { + sh = "/bin/sh" + } + fmt.Printf("\nshell in %s — type `exit` to return to sloop\n\n", dir) + c := exec.Command(sh) + c.Dir = dir + c.Stdin, c.Stdout, c.Stderr = os.Stdin, os.Stdout, os.Stderr + return c.Run() +} + +// enrichedByWorkspace groups the live fleet by workspace name, classified +// (waiting/working/idle) so `ls` can show each workspace's agents with the same +// status dots as `ps` — the bridge between the two views. +func enrichedByWorkspace(manifests map[string]adapter.Manifest) map[string][]FleetRow { + m := map[string][]FleetRow{} + for _, r := range enrichGlances(fleetRows(tmux.ParseSessions(tmuxList())), manifests) { + m[r.Workspace] = append(m[r.Workspace], r) + } + return m +} + +// workspaceDefault returns a workspace's default tool key (what `r`/launch runs), +// or "—" when it can't be read. +func workspaceDefault(path string) string { + proj, err := config.LoadProject(workspace.Workspace{Root: path}.SloopDir()) + if err != nil || proj.DefaultTool == "" { + return "—" + } + return proj.DefaultTool +} + +// agentsInline renders a workspace's live agents as "● Claude ▸ Cursor" using +// the same status dots as `ps`; "—" when nothing is running. +func agentsInline(rows []FleetRow) string { + if len(rows) == 0 { + return tui.Grey("—") + } + parts := make([]string, 0, len(rows)) + for _, r := range rows { + dot, _ := statusDot(r) + parts = append(parts, dot+" "+r.toolName()) + } + return strings.Join(parts, " ") +} + +// abbrevHome shortens a path under $HOME to a leading ~ for compact display. +func abbrevHome(path string) string { + if home, err := os.UserHomeDir(); err == nil && home != "" { + if path == home { + return "~" + } + if strings.HasPrefix(path, home+"/") { + return "~" + path[len(home):] + } + } + return path +} + +// launchWorkspaceDefault launches a workspace's default tool in its own dir — the +// "jump into work" action for a workspace that has no live session yet. +func launchWorkspaceDefault(startDir string) error { + ws, err := workspace.Resolve(startDir) + if err != nil { + return err + } + proj, err := config.LoadProject(ws.SloopDir()) + if err != nil { + return err + } + manifests, err := adapter.Load() + if err != nil { + return err + } + plan, err := planLaunch("", "", "", "", proj.DefaultTool, manifests) + if err != nil { + return err + } + return RunRun(startDir, "", "", "", "", "", nil, selectRunner(ws.Name, plan.toolKey)) +} + func RunLs(w io.Writer) error { dbPath, err := config.GlobalDBPath() if err != nil { @@ -67,29 +158,87 @@ var lsCmd = &cobra.Command{ return nil } - nameW := 0 + manifests, _ := adapter.Load() + + // Per-workspace columns. The default tool doesn't change between keystrokes, + // so compute it once; live agents are re-read each pass. The path goes on a + // second `└` line (like ps), so only name + default need width here. + defaults := make(map[string]string, len(workspaces)) + nameW, defW := len("WORKSPACE"), len("DEFAULT") for _, ws := range workspaces { + defaults[ws.Name] = workspaceDefault(ws.Path) if len(ws.Name) > nameW { nameW = len(ws.Name) } + if len(defaults[ws.Name]) > defW { + defW = len(defaults[ws.Name]) + } } - var options []string - for _, ws := range workspaces { - options = append(options, fmt.Sprintf("%-*s %s", nameW, ws.Name, tui.Grey(ws.Path))) - } + // Same control-center shape as `ps`: arrow-key move + action keys, looping + // so light actions (cd, open a shell) return to the list. The screen is + // cleared each pass and feedback shows in `notice` under the header, so the + // list redraws in place instead of stacking. Enter stays safe (attach a live + // session, else just point at the workspace); launching is the explicit `r` + // key, so the list never spawns an agent by surprise. + var notice string + for { + tui.Clear() + live := enrichedByWorkspace(manifests) + running := 0 + var options []string + for _, ws := range workspaces { + agents := live[ws.Name] + if len(agents) > 0 { + running++ + } + // No leading status glyph (ambiguous-width breaks alignment); the + // AGENTS column carries liveness — colored dots when running, "—" idle. + line := fmt.Sprintf("%-*s %-*s %s", + nameW, ws.Name, defW, defaults[ws.Name], agentsInline(agents)) + line += "\r\n└ " + tui.Grey(abbrevHome(ws.Path)) + options = append(options, line) + } - prompt := fmt.Sprintf("⚓ Sloop workspaces · %d", len(workspaces)) + - "\r\n" + tui.Grey(" ↑/↓ move · ⏎ show cd · q quit") - selected, err := tui.SelectMenu(prompt, options) - if err != nil { - return err - } - if selected >= 0 { + header := fmt.Sprintf("⚓ Workspaces · %d registered", len(workspaces)) + if running > 0 { + header += " · " + tui.Green(fmt.Sprintf("%d running", running)) + } + legend := tui.Grey(" AGENTS = live agents, colored by status (→ sloop ps) · — = idle") + keys := tui.Grey(" ↑/↓ move · ⏎ open · r launch · s shell · c cd · q/esc quit") + cols := tui.Grey(fmt.Sprintf(" %-*s %-*s %s", nameW, "WORKSPACE", defW, "DEFAULT", "AGENTS")) + prompt := header + if notice != "" { + prompt += "\r\n" + notice + } + prompt += "\r\n" + legend + "\r\n" + keys + "\r\n\r\n" + cols + notice = "" // consumed; the handler below sets a fresh one for next pass + + selected, key, err := tui.SelectAction(prompt, options, []byte{'r', 's', 'c'}) + if err != nil { + return err + } + if selected < 0 || key == 0 { + return nil + } ws := workspaces[selected] - fmt.Printf("\nTo jump to workspace, run:\n cd %s\n", ws.Path) + switch key { + case 'r': // launch the default tool (replaces this process via tmux) + return launchWorkspaceDefault(ws.Path) + case 's': // open a shell in the workspace dir, then return to the list + if err := openShellIn(ws.Path); err != nil { + return err + } + case 'c': // surface the cd line (a binary can't change the parent shell) + notice = tui.Cyan("cd " + ws.Path) + default: // Enter + if rows := live[ws.Name]; len(rows) > 0 { + return attachSession(rows[0].Name) + } + notice = tui.Yellow(ws.Name+" isn't running") + + tui.Grey(" — press r to launch · s for a shell · c to copy its cd") + } } - return nil }, } diff --git a/internal/cli/commands/lsview_test.go b/internal/cli/commands/lsview_test.go new file mode 100644 index 0000000..8c0dcc0 --- /dev/null +++ b/internal/cli/commands/lsview_test.go @@ -0,0 +1,37 @@ +package commands + +import ( + "testing" + + "github.com/stroops/sloop/internal/tmux" +) + +func TestAbbrevHome(t *testing.T) { + t.Setenv("HOME", "/Users/me") + cases := []struct{ in, want string }{ + {"/Users/me", "~"}, + {"/Users/me/code/api", "~/code/api"}, + {"/opt/other", "/opt/other"}, + {"/Users/melon/x", "/Users/melon/x"}, // prefix but not a path boundary + } + for _, c := range cases { + if got := abbrevHome(c.in); got != c.want { + t.Errorf("abbrevHome(%q) = %q, want %q", c.in, got, c.want) + } + } +} + +func TestAgentsInline(t *testing.T) { + // Color is off in tests (stdout isn't a tty), so dots render plain. + if got := agentsInline(nil); got != "—" { + t.Errorf("empty = %q, want —", got) + } + rows := []FleetRow{ + {Tool: "claude", Display: "Claude Code", Status: tmux.StatusWaiting}, + {Tool: "cursor", Display: "Cursor", Status: tmux.StatusWorking}, + } + want := "● Claude Code ● Cursor" + if got := agentsInline(rows); got != want { + t.Errorf("agentsInline = %q, want %q", got, want) + } +} diff --git a/internal/cli/commands/popup.go b/internal/cli/commands/popup.go index 44717ce..5ffaea9 100644 --- a/internal/cli/commands/popup.go +++ b/internal/cli/commands/popup.go @@ -13,11 +13,13 @@ import ( const fleetPopupCmd = appName + " ps" var popupCmd = &cobra.Command{ - Use: "popup", - Short: "Open the cross-repo fleet (`ps`) as a floating tmux popup (HUD)", + Use: "popup", + Aliases: []string{"hud"}, + Short: "Open the cross-repo fleet (`ps`) as a floating tmux popup / HUD", Long: `Open ` + "`sloop ps`" + ` in a tmux popup over your current pane: glance at every agent, answer or jump with one key, then the popup closes back to your -work. Bind it to a key with ` + "`sloop popup setup`" + `. Needs tmux ≥ 3.2.`, +work — a heads-up display for the fleet. Aliased as ` + "`sloop hud`" + `. Bind it to +a key with ` + "`sloop popup setup`" + ` (or ` + "`sloop hud setup`" + `). Needs tmux ≥ 3.2.`, Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, args []string) error { if os.Getenv("TMUX") == "" { diff --git a/internal/cli/commands/ps.go b/internal/cli/commands/ps.go index 03e477b..af0d3f4 100644 --- a/internal/cli/commands/ps.go +++ b/internal/cli/commands/ps.go @@ -15,6 +15,7 @@ import ( "github.com/spf13/cobra" "golang.org/x/term" + "github.com/stroops/sloop/internal/adapter" "github.com/stroops/sloop/internal/config" "github.com/stroops/sloop/internal/fleetstate" "github.com/stroops/sloop/internal/hints" @@ -36,6 +37,16 @@ type FleetRow struct { Path string // repo path from the registry (cross-repo context) Prompt string // the question the agent is blocked on (when waiting) Answers []tmux.Answer // parsed choices the agent offers (answer in one key) + Display string // provider display name (e.g. "Google Antigravity" for "agy") +} + +// toolName is the row's provider display name, falling back to the tool key when +// the row hasn't been enriched (e.g. plain listings built straight from tmux). +func (r FleetRow) toolName() string { + if r.Display != "" { + return r.Display + } + return r.Tool } // registryPaths maps each registered workspace name to its repo path, so the @@ -115,7 +126,7 @@ const captureTimeout = 2 * time.Second // writes a distinct index, so no locking is needed, and each capture is bounded // by captureTimeout so a stuck pane can't block. When a fresh hook-written // marker exists for a session it overrides the pane heuristic (authoritative). -func enrichGlances(rows []FleetRow) []FleetRow { +func enrichGlances(rows []FleetRow, manifests map[string]adapter.Manifest) []FleetRow { var wg sync.WaitGroup for i := range rows { wg.Add(1) @@ -123,13 +134,14 @@ func enrichGlances(rows []FleetRow) []FleetRow { defer wg.Done() marker, hasMarker := fleetstate.Read(rows[i].Name) + rows[i].Display = displayTool(rows[i].Tool, manifests) ctx, cancel := context.WithTimeout(context.Background(), captureTimeout) defer cancel() out, err := tmux.OutputContext(ctx, tmux.BuildCaptureArgs(rows[i].Name)...) if err == nil { rows[i].Glance = truncate(tmux.LastNonEmptyLine(string(out)), 72) - rows[i].Status = tmux.ClassifyStatus(string(out)) + rows[i].Status = tmux.ClassifyStatus(string(out), manifests[rows[i].Tool]) } if hasMarker { rows[i].Status = stateToStatus(marker.Status) @@ -221,8 +233,8 @@ func RunPs(w io.Writer, rows []FleetRow) error { } _, _ = fmt.Fprintf(w, "%s\n\n", header) for i, r := range rows { - _, _ = fmt.Fprintf(w, " %-3d %-16s %-9s %s · %s\n", - i+1, r.Workspace, r.Tool, stateLabel(r), humanizeSince(r.Activity)) + _, _ = fmt.Fprintf(w, " %-3d %-16s %-18s %s · %s\n", + i+1, r.Workspace, r.toolName(), stateLabel(r), humanizeSince(r.Activity)) if b := bottomLine(r); b != "" { _, _ = fmt.Fprintf(w, " └ %s\n", b) } @@ -264,10 +276,53 @@ func jumpToFleet(rows []FleetRow, n int) error { if n < 1 || n > len(rows) { return fmt.Errorf("no session #%d (have %d)", n, len(rows)) } + return attachSession(rows[n-1].Name) +} + +// pickFleetSession shows the live fleet and returns the chosen session name ("" if +// cancelled). Backs the no-argument `sloop attach` so you don't have to type a +// session name — using the same WORKSPACE/TOOL/STATUS columns, colors and +// waiting-first order as `ps`, so the picker reads identically to the fleet view. +func pickFleetSession(title string) (string, error) { + manifests, _ := adapter.Load() + rows := enrichGlances(fleetRows(tmux.ParseSessions(tmuxList())), manifests) + if len(rows) == 0 { + return "", fmt.Errorf("no running AI sessions to attach to (start one with `sloop run `)") + } + sortNeedsAttention(rows) + + wsW, _, _ := columnWidths(rows) + if wsW < len("WORKSPACE") { + wsW = len("WORKSPACE") + } + toolW := len("TOOL") + for _, r := range rows { + if n := len(r.toolName()); n > toolW { + toolW = n + } + } + opts := make([]string, len(rows)) + for i, r := range rows { + opts[i] = fmt.Sprintf("%-*s %-*s %s", wsW, r.Workspace, toolW, r.toolName(), statusText(r)) + } + + legend := " " + tui.Yellow("waiting") + " · " + tui.Cyan("working") + " · " + + tui.Blue("attached") + " · " + tui.Green("idle") + cols := tui.Grey(fmt.Sprintf(" %-*s %-*s %s", wsW, "WORKSPACE", toolW, "TOOL", "STATUS")) + tui.Clear() + idx, err := tui.SelectMenu(title+"\r\n"+legend+"\r\n\r\n"+cols, opts) + if err != nil || idx < 0 { + return "", err + } + return rows[idx].Name, nil +} + +// attachSession attaches to a session by name (switches client if already inside +// tmux), replacing this process's foreground with tmux. Shared by `ps` and `ls`. +func attachSession(name string) error { if !tmux.Available() { return fmt.Errorf("tmux is not installed") } - name := rows[n-1].Name args := tmux.BuildAttachArgs(name) if os.Getenv("TMUX") != "" { args = tmux.BuildSwitchArgs(name) @@ -369,7 +424,8 @@ var psCmd = &cobra.Command{ return runWatch(cmd.OutOrStdout(), psInterval, psWaiting, psNotify) } - rows = enrichGlances(rows) + manifests, _ := adapter.Load() + rows = enrichGlances(rows, manifests) sortNeedsAttention(rows) paths := registryPaths() annotatePaths(rows, paths) @@ -380,23 +436,17 @@ var psCmd = &cobra.Command{ return runPsAll(cmd.OutOrStdout(), rows, paths, ext) } - if len(rows) == 0 { - _, _ = fmt.Fprintln(cmd.OutOrStdout(), "⚓ No running AI sessions. Start one with `sloop run ` (or `sloop ps --all` to see known workspaces).") - externalNudge(cmd.OutOrStdout(), ext) - return nil - } - - if psWaiting { - rows = filterWaiting(rows) + // Non-interactive (piped, CI): print the plain listing instead of the + // raw-mode control center, which can't run without a tty. + if !term.IsTerminal(int(os.Stdin.Fd())) { + if psWaiting { + rows = filterWaiting(rows) + } if len(rows) == 0 { - _, _ = fmt.Fprintln(cmd.OutOrStdout(), "⚓ No agents waiting on you.") + _, _ = fmt.Fprintln(cmd.OutOrStdout(), emptyFleetMessage(psWaiting)) + externalNudge(cmd.OutOrStdout(), ext) return nil } - } - - // Non-interactive (piped, CI): print the plain listing instead of the - // raw-mode menu, which can't run without a tty. - if !term.IsTerminal(int(os.Stdin.Fd())) { if err := RunPs(cmd.OutOrStdout(), rows); err != nil { return err } @@ -405,40 +455,95 @@ var psCmd = &cobra.Command{ return nil } - wsW, toolW, waiting := columnWidths(rows) + // Interactive control center: loop so an action (send/answer/kill) or + // cancelling returns to the fleet instead of dropping to the shell. The + // screen is cleared each pass and feedback shows in `notice` under the + // header, so the fleet redraws in place; it's re-read every pass, so kills + // and new sessions show immediately. + var notice string + detach := tui.Grey(" ⏎ enters an agent — to come back, detach (keeps it running): " + tmux.PrefixRaw() + " d") + for { + tui.Clear() + rows = enrichGlances(fleetRows(tmux.ParseSessions(tmuxList())), manifests) + sortNeedsAttention(rows) + annotatePaths(rows, registryPaths()) + if psWaiting { + rows = filterWaiting(rows) + } + if len(rows) == 0 { + _, _ = fmt.Fprintln(cmd.OutOrStdout(), emptyFleetMessage(psWaiting)) + break + } - var options []string - for _, r := range rows { - dot, label := statusDot(r) - line := fmt.Sprintf("%s %-*s %-*s %-16s %s", - dot, wsW, r.Workspace, toolW, r.Tool, label, shortSince(r.Activity)) - if b := bottomLine(r); b != "" { - line += "\r\n└ " + tui.Grey(b) + wsW, _, waiting := columnWidths(rows) + toolW := len("TOOL") + for _, r := range rows { + if n := len(r.toolName()); n > toolW { + toolW = n + } + } + if wsW < len("WORKSPACE") { + wsW = len("WORKSPACE") + } + var options []string + for _, r := range rows { + // No leading status glyph: ●/○ are ambiguous-width and break column + // alignment. Status is the colored STATUS column instead. + line := fmt.Sprintf("%-*s %-*s %s %s", + wsW, r.Workspace, toolW, r.toolName(), statusText(r), shortSince(r.Activity)) + if b := bottomLine(r); b != "" { + line += "\r\n└ " + tui.Grey(b) + } + options = append(options, line) } - options = append(options, line) - } - header := fmt.Sprintf("⚓ AI fleet · %d running", len(rows)) - if waiting > 0 { - header += " · " + tui.Yellow(fmt.Sprintf("%d waiting on you", waiting)) - } - prompt := header + "\r\n" + tui.Grey(" ↑/↓ move · ⏎ attach · 1/y answer · s send · x kill · q quit") + header := fmt.Sprintf("⚓ AI fleet · %d running", len(rows)) + if waiting > 0 { + header += " · " + tui.Yellow(fmt.Sprintf("%d waiting on you", waiting)) + } + legend := " " + tui.Yellow("waiting") + " · " + tui.Cyan("working") + " · " + + tui.Blue("attached") + " · " + tui.Green("idle") + tui.Grey(" · AGE = since last activity") + keys := tui.Grey(" ↑/↓ move · ⏎ attach · 1/y answer · s send · x kill · q/esc quit") + cols := tui.Grey(fmt.Sprintf(" %-*s %-*s %-16s %s", wsW, "WORKSPACE", toolW, "TOOL", "STATUS", "AGE")) + prompt := header + if notice != "" { + prompt += "\r\n" + notice + } + prompt += "\r\n" + legend + "\r\n" + keys + "\r\n" + detach + "\r\n\r\n" + cols + notice = "" // consumed; the handler below sets a fresh one for next pass - actionKeys := []byte{'s', 'x', 'y', 'n', '1', '2', '3', '4', '5', '6', '7', '8', '9'} - idx, key, err := tui.SelectAction(prompt, options, actionKeys) - if err != nil { - return err - } - switch key { - case 13: // Enter → jump - return jumpToFleet(rows, idx+1) - case 's': // send a quick prompt to the highlighted session - return promptAndSend(cmd, rows[idx]) - case 'x': // kill the highlighted session (with confirm) - return confirmAndKill(cmd, rows[idx]) - default: - if a, ok := matchAnswer(rows[idx], key); ok { // one-key answer - return sendAnswer(cmd, rows[idx], a) + actionKeys := []byte{'s', 'x', 'y', 'n', '1', '2', '3', '4', '5', '6', '7', '8', '9'} + idx, key, err := tui.SelectAction(prompt, options, actionKeys) + if err != nil { + return err + } + switch key { + case 0: // q / Esc / Ctrl-C → leave the control center + externalNudge(cmd.OutOrStdout(), ext) + hints.Show(cmd.OutOrStdout(), "ps") + return nil + case 13: // Enter → attach (replaces this process) + return jumpToFleet(rows, idx+1) + case 's': // send a quick prompt; empty cancels back to the fleet + n, err := promptAndSend(cmd, rows[idx]) + if err != nil { + return err + } + notice = n + case 'x': // kill the highlighted session (with confirm) + n, err := confirmAndKill(cmd, rows[idx]) + if err != nil { + return err + } + notice = n + default: + if a, ok := matchAnswer(rows[idx], key); ok { // one-key answer + n, err := sendAnswer(cmd, rows[idx], a) + if err != nil { + return err + } + notice = n + } } } externalNudge(cmd.OutOrStdout(), ext) @@ -489,38 +594,58 @@ func matchAnswer(r FleetRow, key byte) (tmux.Answer, bool) { return tmux.Answer{}, false } -// sendAnswer types the chosen answer into the session. -func sendAnswer(cmd *cobra.Command, row FleetRow, a tmux.Answer) error { +// sendAnswer types the chosen answer into the session, returning a notice line +// for the control center to show on its next redraw. +func sendAnswer(_ *cobra.Command, row FleetRow, a tmux.Answer) (string, error) { if err := tmux.LaunchSend(row.Name, a.Key); err != nil { - return err + return "", err } - cmd.Printf("answered %s: %s\n", row.Name, a.Label) - return nil + return tui.Green(fmt.Sprintf("✓ answered %s: %s", row.Name, a.Label)), nil } // promptAndSend asks for a line and sends it to the row (used by the ps `s` key). -func promptAndSend(cmd *cobra.Command, row FleetRow) error { - msg := promptLine(cmd.OutOrStdout(), os.Stdin, fmt.Sprintf("send to %s: ", row.Name)) - if strings.TrimSpace(msg) == "" { - return nil +// Reading in raw mode means Esc/Ctrl-C cancel back to the fleet instead of +// killing `ps`, and an empty submit cancels too. Returns a notice line ("" when +// cancelled) for the control center to show on its next redraw. +func promptAndSend(_ *cobra.Command, row FleetRow) (string, error) { + msg, ok := tui.ReadLine(fmt.Sprintf("send to %s (Enter to send · Esc to cancel): ", row.Name)) + if !ok || strings.TrimSpace(msg) == "" { + return "", nil } if err := tmux.LaunchSend(row.Name, msg); err != nil { - return err + return "", err } - cmd.Printf("sent to %s\n", row.Name) - return nil + return tui.Green("✓ sent to " + row.Name), nil } // confirmAndKill ends the row's session after a y/N confirm (used by ps `x`). -func confirmAndKill(cmd *cobra.Command, row FleetRow) error { - if !confirm(cmd.OutOrStdout(), os.Stdin, fmt.Sprintf("kill %s? [y/N] ", row.Name)) { - return nil +// Returns a notice line ("" when declined) for the next redraw. +func confirmAndKill(_ *cobra.Command, row FleetRow) (string, error) { + if !tui.Confirm(fmt.Sprintf("kill %s? [y/N] ", row.Name)) { + return "", nil } if err := killFunc(row.Name); err != nil { - return err + return "", err } - cmd.Printf("killed %s\n", row.Name) - return nil + return tui.Yellow("✓ killed " + row.Name), nil +} + +// displayTool returns a friendly name for a tool key (the manifest's display +// name, e.g. "Google Antigravity" for "agy"), falling back to the key for +// unknown/adopted tools. +func displayTool(key string, manifests map[string]adapter.Manifest) string { + if m, ok := manifests[key]; ok && m.Name != "" { + return m.Name + } + return key +} + +// emptyFleetMessage is the "nothing here" line for ps, tailored to --waiting. +func emptyFleetMessage(waitingOnly bool) string { + if waitingOnly { + return "⚓ No agents waiting on you." + } + return "⚓ No running AI sessions. Start one with `sloop run ` (or `sloop ps --all` to see known workspaces)." } // statusDot renders the agent status as a colored dot plus a label for the @@ -539,6 +664,23 @@ func statusDot(r FleetRow) (dot, label string) { return tui.Green("○"), "idle" } +// statusText is the colored, fixed-width STATUS column for the ps control +// center: the status as legible text (no ambiguous-width glyph), padded to 16 +// before coloring so the trailing AGE column stays aligned. +func statusText(r FleetRow) string { + pad := func(s string) string { return fmt.Sprintf("%-16s", s) } + switch r.Status { + case tmux.StatusWaiting: + return tui.Yellow(pad("waiting on you")) + case tmux.StatusWorking: + return tui.Cyan(pad("working")) + } + if r.Attached { + return tui.Blue(pad("attached")) + } + return tui.Green(pad("idle")) +} + // shortSince is a compact relative time ("now", "3m", "2h", "5d"). func shortSince(t time.Time) string { d := time.Since(t) @@ -581,7 +723,8 @@ func runWatch(w io.Writer, interval time.Duration, waitingOnly, notify bool) err } var prev []FleetRow for { - rows := enrichGlances(fleetRows(tmux.ParseSessions(tmuxList()))) + manifests, _ := adapter.Load() + rows := enrichGlances(fleetRows(tmux.ParseSessions(tmuxList())), manifests) sortNeedsAttention(rows) shown := rows diff --git a/internal/cli/commands/registry.go b/internal/cli/commands/registry.go index 86f3657..3fea980 100644 --- a/internal/cli/commands/registry.go +++ b/internal/cli/commands/registry.go @@ -29,10 +29,10 @@ func init() { add(RegisterKill) add(RegisterApprove) add(RegisterAdopt) + add(RegisterRestore) add(RegisterPopup) add(RegisterStatusline) add(RegisterSkill) - add(RegisterHook) add(RegisterHooks) add(RegisterHints) } diff --git a/internal/cli/commands/restore.go b/internal/cli/commands/restore.go new file mode 100644 index 0000000..0a95eb5 --- /dev/null +++ b/internal/cli/commands/restore.go @@ -0,0 +1,155 @@ +package commands + +import ( + "fmt" + "io" + "time" + + "github.com/spf13/cobra" + + "github.com/stroops/sloop/internal/adapter" + "github.com/stroops/sloop/internal/config" + "github.com/stroops/sloop/internal/session" + "github.com/stroops/sloop/internal/tmux" +) + +// restoreTarget is one agent to bring back: a workspace + tool, and the tmux +// session name it will reclaim. +type restoreTarget struct { + WSName string + Path string + Tool string + Session string +} + +// restoreCandidates picks, from session history (most-recent first), the latest +// session per (workspace, tool) that is not currently live — i.e. the recent +// fleet to relaunch after a restart. Pure and testable. Sessions whose workspace +// is no longer in the registry are skipped. +func restoreCandidates(sessions []session.Session, wsName, wsPath map[int64]string, live map[string]bool) []restoreTarget { + seen := map[string]bool{} + var out []restoreTarget + for _, s := range sessions { + name, path := wsName[s.WorkspaceID], wsPath[s.WorkspaceID] + if name == "" || path == "" { + continue + } + key := name + "\x00" + s.Tool + if seen[key] { + continue + } + seen[key] = true + sess := tmux.SessionName(name, s.Tool) + if live[sess] { + continue // already running — nothing to restore + } + out = append(out, restoreTarget{WSName: name, Path: path, Tool: s.Tool, Session: sess}) + } + return out +} + +// liveSessionNames is the set of tmux session names currently running. +func liveSessionNames() map[string]bool { + live := map[string]bool{} + for _, s := range tmux.ParseSessions(tmuxList()) { + live[s.Name] = true + } + return live +} + +// RunRestore relaunches the recent agents that aren't currently running, each in +// a detached session (so the whole fleet comes back at once). With resume it +// passes each tool's resume flag to continue the prior conversation. +func RunRestore(w io.Writer, in io.Reader, resume, yes bool) error { + if !tmux.Available() { + return fmt.Errorf("tmux is not installed; `sloop restore` needs tmux") + } + dbPath, err := config.GlobalDBPath() + if err != nil { + return err + } + store, err := session.Open(dbPath) + if err != nil { + return err + } + defer func() { _ = store.Close() }() + + sessions, err := store.ListSessions(100) + if err != nil { + return err + } + workspaces, err := store.ListWorkspaces() + if err != nil { + return err + } + wsName, wsPath := map[int64]string{}, map[int64]string{} + for _, ws := range workspaces { + wsName[ws.ID], wsPath[ws.ID] = ws.Name, ws.Path + } + + targets := restoreCandidates(sessions, wsName, wsPath, liveSessionNames()) + if len(targets) == 0 { + _, _ = fmt.Fprintln(w, "Nothing to restore — your recent agents are already running, or none are recorded yet.") + return nil + } + + _, _ = fmt.Fprintln(w, "Restore these agents:") + for _, t := range targets { + _, _ = fmt.Fprintf(w, " %s %s\n", t.Session, t.Path) + } + if !yes && !confirm(w, in, fmt.Sprintf("relaunch %d agent(s)? [y/N] ", len(targets))) { + return nil + } + + manifests, _ := adapter.Load() + done := 0 + for _, t := range targets { + m, ok := manifests[t.Tool] + if !ok { + _, _ = fmt.Fprintf(w, " ✗ %s: no adapter for %q\n", t.Session, t.Tool) + continue + } + _, _ = RunSync(t.Path, t.Tool, false) + var args []string + if resume && m.Run.ResumeFlag != "" { + args = append(args, m.Run.ResumeFlag) + } + if err := tmux.LaunchDetached(t.Session, t.Path, m.Launch, args); err != nil { + _, _ = fmt.Fprintf(w, " ✗ %s: %v\n", t.Session, err) + continue + } + if ws, err := store.RegisterWorkspace(t.WSName, t.Path); err == nil { + _, _ = store.RecordSession(session.Session{ + WorkspaceID: ws.ID, Tool: t.Tool, Cwd: t.Path, + TmuxSession: t.Session, StartedAt: time.Now(), + }) + } + done++ + } + _, _ = fmt.Fprintf(w, "restored %d agent(s) — `sloop ps` to see them\n", done) + return nil +} + +var ( + restoreResume bool + restoreYes bool +) + +var restoreCmd = &cobra.Command{ + Use: "restore", + Short: "Relaunch the agents you were recently running (after a reboot / tmux restart)", + Long: `tmux sessions don't survive a reboot. restore re-creates the most recent agent +per workspace that isn't currently running, from sloop's registry — detached, so +the whole fleet comes back at once. With --resume it continues each tool's prior +conversation where the CLI supports it.`, + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, args []string) error { + return RunRestore(cmd.OutOrStdout(), cmd.InOrStdin(), restoreResume, assumeYes(cmd, restoreYes)) + }, +} + +func RegisterRestore(cmd *cobra.Command) { + restoreCmd.Flags().BoolVar(&restoreResume, "resume", false, "continue each agent's prior conversation (where the CLI supports it)") + restoreCmd.Flags().BoolVar(&restoreYes, "yes", false, "skip the confirmation (or use global -y)") + cmd.AddCommand(restoreCmd) +} diff --git a/internal/cli/commands/restore_test.go b/internal/cli/commands/restore_test.go new file mode 100644 index 0000000..95b6707 --- /dev/null +++ b/internal/cli/commands/restore_test.go @@ -0,0 +1,51 @@ +package commands + +import ( + "testing" + + "github.com/stroops/sloop/internal/session" + "github.com/stroops/sloop/internal/tmux" +) + +func TestRestoreCandidates(t *testing.T) { + wsName := map[int64]string{1: "api", 2: "web"} + wsPath := map[int64]string{1: "/repo/api", 2: "/repo/web"} + + // History, most-recent first: api/claude (live), api/cursor, web/claude, + // an older duplicate api/cursor, and a session whose workspace is gone. + sessions := []session.Session{ + {WorkspaceID: 1, Tool: "claude"}, + {WorkspaceID: 1, Tool: "cursor"}, + {WorkspaceID: 2, Tool: "claude"}, + {WorkspaceID: 1, Tool: "cursor"}, // older dup → skipped + {WorkspaceID: 9, Tool: "claude"}, // unknown workspace → skipped + } + live := map[string]bool{tmux.SessionName("api", "claude"): true} // api/claude already up + + got := restoreCandidates(sessions, wsName, wsPath, live) + + // Expect api/cursor and web/claude (api/claude excluded as live, dup + unknown skipped). + if len(got) != 2 { + t.Fatalf("want 2 candidates, got %d: %+v", len(got), got) + } + if got[0].Tool != "cursor" || got[0].WSName != "api" || got[0].Path != "/repo/api" { + t.Fatalf("candidate 0 = %+v", got[0]) + } + if got[1].Tool != "claude" || got[1].WSName != "web" { + t.Fatalf("candidate 1 = %+v", got[1]) + } + if got[1].Session != tmux.SessionName("web", "claude") { + t.Fatalf("session name = %q", got[1].Session) + } +} + +func TestRestoreCandidatesEmpty(t *testing.T) { + // Every recent session is already live → nothing to restore. + wsName := map[int64]string{1: "api"} + wsPath := map[int64]string{1: "/repo/api"} + sessions := []session.Session{{WorkspaceID: 1, Tool: "claude"}} + live := map[string]bool{tmux.SessionName("api", "claude"): true} + if got := restoreCandidates(sessions, wsName, wsPath, live); len(got) != 0 { + t.Fatalf("want 0, got %+v", got) + } +} diff --git a/internal/cli/commands/run.go b/internal/cli/commands/run.go index 1dc6ec1..ccd79e0 100644 --- a/internal/cli/commands/run.go +++ b/internal/cli/commands/run.go @@ -3,6 +3,7 @@ package commands import ( "fmt" "os" + "path/filepath" "strings" "time" @@ -17,7 +18,147 @@ import ( "github.com/stroops/sloop/internal/workspace" ) -func RunRun(startDir, target string, extraArgs []string, r runner.Runner) error { +// launchPlan is the resolved outcome of a `sloop run` target + flags. +type launchPlan struct { + toolKey string // a real manifest key (binary aliases already resolved) + model string // model to forward ("" = the CLI's own default) + effort string // low|medium|high ("" = none) +} + +// toolKeyFor resolves a token to a manifest key: an exact key, else a tool whose +// detect/launch binary matches — so `sloop run agent` == `sloop run cursor`. +func toolKeyFor(token string, manifests map[string]adapter.Manifest) (string, bool) { + if _, ok := manifests[token]; ok { + return token, true + } + for key, m := range manifests { + if m.Detect == token || filepath.Base(m.Launch) == token { + return key, true + } + } + return "", false +} + +// modelHomeTool finds the CLI that should launch a bare model alias: the tool +// listing it in run.models that is the canonical launcher for its own vendor +// (run.default_for). Falls back to any tool that serves the alias. +func modelHomeTool(model string, manifests map[string]adapter.Manifest) (string, bool) { + var fallback string + for key, m := range manifests { + for _, a := range m.Run.Models { + if a != model { + continue + } + if m.Run.Vendor != "" && sliceHas(m.Run.DefaultFor, m.Run.Vendor) { + return key, true + } + if fallback == "" { + fallback = key + } + } + } + return fallback, fallback != "" +} + +func sliceHas(ss []string, s string) bool { + for _, x := range ss { + if x == s { + return true + } + } + return false +} + +// planLaunch resolves the positional target + flags into a CLI, model, and +// effort. Precedence for the positional token: tool key → binary alias → model +// alias. Naming a CLI (positional tool or --provider) wins; a bare model +// resolves to its vendor's home CLI. +func planLaunch(target, provider, model, effort, defaultTool string, manifests map[string]adapter.Manifest) (launchPlan, error) { + p := launchPlan{model: model, effort: effort} + cli := provider + + if target != "" { + switch { + case isToolToken(target, manifests): + key, _ := toolKeyFor(target, manifests) + if cli != "" { + if k2, _ := toolKeyFor(cli, manifests); k2 != key { + return p, fmt.Errorf("conflicting tools: %q and --provider %q", target, provider) + } + } + cli = key + default: + home, ok := modelHomeTool(target, manifests) + if !ok { + return p, fmt.Errorf("unknown tool or model %q (try `sloop run -m `)", target) + } + if p.model == "" { + p.model = target + } + if cli == "" { + cli = home + } + } + } + + if cli == "" { + cli = defaultTool + } + if cli == "" { + return p, fmt.Errorf("no tool given and no default_tool set") + } + key, ok := toolKeyFor(cli, manifests) + if !ok { + return p, fmt.Errorf("unknown tool %q (no adapter)", cli) + } + p.toolKey = key + return p, nil +} + +func isToolToken(token string, manifests map[string]adapter.Manifest) bool { + _, ok := toolKeyFor(token, manifests) + return ok +} + +// buildRunArgs turns a resolved model/effort/task into the CLI's own flags (from +// its manifest), then appends passthrough. Errors clearly if the CLI lacks a +// knob the user asked for. The model string is forwarded as-is — never validated. +func buildRunArgs(m adapter.Manifest, model, effort, task string, passthrough []string) ([]string, error) { + var args []string + if model != "" { + if m.Run.ModelFlag == "" { + return nil, fmt.Errorf("%s has no model selection via sloop — run it and pick the model inside, or pass flags after `--`", m.Name) + } + args = append(args, m.Run.ModelFlag, model) + } + if effort != "" { + switch effort { + case "low", "medium", "high": + default: + return nil, fmt.Errorf("--effort must be low|medium|high, got %q", effort) + } + tok, ok := m.Run.EffortValues[effort] + if m.Run.EffortFlag == "" || !ok { + return nil, fmt.Errorf("%s has no %q reasoning effort via sloop", m.Name, effort) + } + args = append(args, m.Run.EffortFlag, tok) + } + if task != "" { + switch m.Run.Prompt { + case "": + return nil, fmt.Errorf("%s has no initial-task support via sloop — launch it and type the task", m.Name) + case "positional": + args = append(args, task) // e.g. `claude "task"` / `agent "task"` + default: + args = append(args, m.Run.Prompt, task) // flag form: ` ` + } + } + return append(args, passthrough...), nil +} + +// RunRun resolves the target + model/effort/task flags, syncs context, then +// launches the CLI with the right flags in a managed session. +func RunRun(startDir, target, provider, model, effort, task string, passthrough []string, r runner.Runner) error { ws, err := workspace.Resolve(startDir) if err != nil { return err @@ -26,31 +167,32 @@ func RunRun(startDir, target string, extraArgs []string, r runner.Runner) error if err != nil { return err } - tool, err := resolveTool(target, proj.DefaultTool) + manifests, err := adapter.Load() if err != nil { return err } - manifests, err := adapter.Load() + plan, err := planLaunch(target, provider, model, effort, proj.DefaultTool, manifests) if err != nil { return err } - m, ok := manifests[tool] - if !ok { - return fmt.Errorf("unknown tool %q (no adapter)", tool) + m := manifests[plan.toolKey] + args, err := buildRunArgs(m, plan.model, plan.effort, task, passthrough) + if err != nil { + return err } // Sync native files before launch. - if _, err := RunSync(startDir, target, false); err != nil { + if _, err := RunSync(startDir, plan.toolKey, false); err != nil { return err } // Record session (best-effort: never block the launch). - sessID, store := recordSessionBestEffort(ws, tool, target) + sessID, store := recordSessionBestEffort(ws, plan.toolKey, target) if store != nil { defer func() { _ = store.Close() }() } - launchErr := r.Launch(runner.Spec{Dir: ws.Root, Command: m.Launch, Args: extraArgs}) + launchErr := r.Launch(runner.Spec{Dir: ws.Root, Command: m.Launch, Args: args}) if store != nil && sessID > 0 { _ = store.EndSession(sessID, time.Now()) @@ -144,6 +286,10 @@ func RunSplit(startDir string, tools []string) error { var ( runWorkspace string runSplit bool + runProvider string + runModel string + runEffort string + runTask string ) var runCmd = &cobra.Command{ @@ -197,10 +343,18 @@ var runCmd = &cobra.Command{ if len(positional) == 1 { target = positional[0] } - if target == "" { - target = proj.DefaultTool + // Resolve the plan up front so the session is named by the real tool key + // (e.g. `run agent`/`run opus` both land in the canonical cursor/claude + // session), not the raw token. + manifests, err := adapter.Load() + if err != nil { + return err + } + plan, err := planLaunch(target, runProvider, runModel, runEffort, proj.DefaultTool, manifests) + if err != nil { + return err } - if err := RunRun(startDir, target, passthrough, selectRunner(ws.Name, target)); err != nil { + if err := RunRun(startDir, target, runProvider, runModel, runEffort, runTask, passthrough, selectRunner(ws.Name, plan.toolKey)); err != nil { return err } hints.Show(cmd.OutOrStdout(), "run") @@ -211,7 +365,13 @@ var runCmd = &cobra.Command{ func RegisterRun(cmd *cobra.Command) { runCmd.Flags().StringVarP(&runWorkspace, "workspace", "w", "", "target a registered workspace by name") runCmd.Flags().BoolVar(&runSplit, "split", false, "launch multiple tools side-by-side as tmux panes") + runCmd.Flags().StringVarP(&runProvider, "provider", "p", "", "AI CLI to launch (overrides the positional target)") + runCmd.Flags().StringVarP(&runModel, "model", "m", "", "model to pass to the CLI (forwarded as-is, not validated)") + runCmd.Flags().StringVarP(&runEffort, "effort", "e", "", "reasoning effort: low|medium|high (if the CLI supports it)") + runCmd.Flags().StringVarP(&runTask, "task", "t", "", "hand the agent an initial task — launches an interactive session already working on it") runCmd.ValidArgsFunction = completeTools _ = runCmd.RegisterFlagCompletionFunc("workspace", completeWorkspaces) + _ = runCmd.RegisterFlagCompletionFunc("provider", completeTools) + _ = runCmd.RegisterFlagCompletionFunc("model", completeModels) cmd.AddCommand(runCmd) } diff --git a/internal/cli/commands/runcmd_test.go b/internal/cli/commands/runcmd_test.go index a83efee..c8cbd72 100644 --- a/internal/cli/commands/runcmd_test.go +++ b/internal/cli/commands/runcmd_test.go @@ -20,7 +20,7 @@ func TestRunRunSyncsAndLaunches(t *testing.T) { } fr := &fakeRunner{} - if err := RunRun(dir, "claude", nil, fr); err != nil { + if err := RunRun(dir, "claude", "", "", "", "", nil, fr); err != nil { t.Fatalf("RunRun: %v", err) } @@ -47,10 +47,10 @@ func TestRunRunPassesThroughArgs(t *testing.T) { } fr := &fakeRunner{} - if err := RunRun(dir, "claude", []string{"--model", "opus"}, fr); err != nil { + if err := RunRun(dir, "claude", "", "", "", "", []string{"--foo", "bar"}, fr); err != nil { t.Fatalf("RunRun: %v", err) } - if len(fr.got.Args) != 2 || fr.got.Args[0] != "--model" || fr.got.Args[1] != "opus" { - t.Fatalf("want passthrough args [--model opus], got %v", fr.got.Args) + if len(fr.got.Args) != 2 || fr.got.Args[0] != "--foo" || fr.got.Args[1] != "bar" { + t.Fatalf("want passthrough args [--foo bar], got %v", fr.got.Args) } } diff --git a/internal/cli/commands/runplan_test.go b/internal/cli/commands/runplan_test.go new file mode 100644 index 0000000..7edcd97 --- /dev/null +++ b/internal/cli/commands/runplan_test.go @@ -0,0 +1,135 @@ +package commands + +import ( + "strings" + "testing" + + "github.com/stroops/sloop/internal/adapter" +) + +func loadManifestsForTest(t *testing.T) map[string]adapter.Manifest { + t.Helper() + t.Setenv("HOME", t.TempDir()) // hermetic: ignore the user's ~/.sloop/adapters + m, err := adapter.Load() + if err != nil { + t.Fatalf("adapter.Load: %v", err) + } + return m +} + +func TestPlanLaunch(t *testing.T) { + m := loadManifestsForTest(t) + cases := []struct { + name string + target, provider, model, effort string + wantKey, wantModel, wantErrSubstr string + }{ + {name: "tool key", target: "claude", wantKey: "claude"}, + {name: "binary alias", target: "agent", wantKey: "cursor"}, + {name: "bare model -> home CLI", target: "opus", wantKey: "claude", wantModel: "opus"}, + {name: "tool + model flag", target: "claude", model: "sonnet", wantKey: "claude", wantModel: "sonnet"}, + {name: "provider flag + model", provider: "cursor", model: "opus", wantKey: "cursor", wantModel: "opus"}, + {name: "default tool when empty", target: "", wantKey: "claude"}, + {name: "unknown token", target: "nope", wantErrSubstr: "unknown tool or model"}, + {name: "conflict tool vs provider", target: "claude", provider: "codex", wantErrSubstr: "conflicting"}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + p, err := planLaunch(c.target, c.provider, c.model, c.effort, "claude", m) + if c.wantErrSubstr != "" { + if err == nil || !strings.Contains(err.Error(), c.wantErrSubstr) { + t.Fatalf("want error containing %q, got %v", c.wantErrSubstr, err) + } + return + } + if err != nil { + t.Fatalf("planLaunch: %v", err) + } + if p.toolKey != c.wantKey { + t.Fatalf("toolKey = %q, want %q", p.toolKey, c.wantKey) + } + if p.model != c.wantModel { + t.Fatalf("model = %q, want %q", p.model, c.wantModel) + } + }) + } +} + +func TestBuildRunArgs(t *testing.T) { + claude := adapter.Manifest{Name: "Claude", Run: adapter.RunSpec{ModelFlag: "--model", Prompt: "positional"}} + codex := adapter.Manifest{Name: "Codex", Run: adapter.RunSpec{ + ModelFlag: "--model", + EffortFlag: "-c", + EffortValues: map[string]string{"high": "model_reasoning_effort=high"}, + }} + noKnobs := adapter.Manifest{Name: "Agy"} + + t.Run("model forwarded", func(t *testing.T) { + got, err := buildRunArgs(claude, "opus", "", "", []string{"--foo"}) + if err != nil { + t.Fatal(err) + } + want := []string{"--model", "opus", "--foo"} + if !eqStrs(got, want) { + t.Fatalf("got %v want %v", got, want) + } + }) + t.Run("effort forwarded", func(t *testing.T) { + got, err := buildRunArgs(codex, "", "high", "", nil) + if err != nil { + t.Fatal(err) + } + want := []string{"-c", "model_reasoning_effort=high"} + if !eqStrs(got, want) { + t.Fatalf("got %v want %v", got, want) + } + }) + t.Run("task seeds positional after model", func(t *testing.T) { + got, err := buildRunArgs(claude, "opus", "", "fix the auth bug", nil) + if err != nil { + t.Fatal(err) + } + want := []string{"--model", "opus", "fix the auth bug"} + if !eqStrs(got, want) { + t.Fatalf("got %v want %v", got, want) + } + }) + t.Run("task unsupported errors", func(t *testing.T) { + if _, err := buildRunArgs(codex, "", "", "do a thing", nil); err == nil { + t.Fatal("want error for task on a CLI with no prompt support") + } + }) + t.Run("model unsupported errors", func(t *testing.T) { + if _, err := buildRunArgs(noKnobs, "opus", "", "", nil); err == nil { + t.Fatal("want error for model on a CLI with no model_flag") + } + }) + t.Run("effort unsupported errors", func(t *testing.T) { + if _, err := buildRunArgs(claude, "", "high", "", nil); err == nil { + t.Fatal("want error for effort on a CLI with no effort_flag") + } + }) + t.Run("bad effort value errors", func(t *testing.T) { + if _, err := buildRunArgs(codex, "", "turbo", "", nil); err == nil { + t.Fatal("want error for effort not in low|medium|high") + } + }) + t.Run("passthrough only", func(t *testing.T) { + got, err := buildRunArgs(noKnobs, "", "", "", []string{"--help"}) + if err != nil || !eqStrs(got, []string{"--help"}) { + t.Fatalf("got %v err %v", got, err) + } + }) +} + +func eqStrs(a, b []string) bool { + if len(a) != len(b) { + return false + } + for i := range a { + if a[i] != b[i] { + return false + } + } + return true +} diff --git a/internal/cli/commands/send.go b/internal/cli/commands/send.go index 7aa725b..e01c073 100644 --- a/internal/cli/commands/send.go +++ b/internal/cli/commands/send.go @@ -6,6 +6,8 @@ import ( "strings" "github.com/spf13/cobra" + + "github.com/stroops/sloop/internal/adapter" "github.com/stroops/sloop/internal/tmux" ) @@ -74,9 +76,10 @@ func RunSendBroadcast(msg string, all, waiting bool) (int, error) { if !tmux.Available() { return 0, fmt.Errorf("tmux is not installed; `sloop send` needs tmux") } - rows := fleetRows(tmux.ParseSessions(tmuxList())) + manifests, _ := adapter.Load() + rows := enrichGlances(fleetRows(tmux.ParseSessions(tmuxList())), manifests) if waiting { - rows = filterWaiting(enrichGlances(rows)) + rows = filterWaiting(rows) } if len(rows) == 0 { return 0, fmt.Errorf("no matching sessions") diff --git a/internal/cli/commands/skill.go b/internal/cli/commands/skill.go index 8c43ba2..ea3fc74 100644 --- a/internal/cli/commands/skill.go +++ b/internal/cli/commands/skill.go @@ -96,5 +96,6 @@ func RegisterSkill(cmd *cobra.Command) { skillCmd.AddCommand(skillNewCmd) skillAddCmd.Flags().StringVar(&skillAddName, "name", "", "name for the imported skill (default: derived from the URL)") skillCmd.AddCommand(skillAddCmd) + skillCmd.AddCommand(skillUpdateCmd) cmd.AddCommand(skillCmd) } diff --git a/internal/cli/commands/skilladd.go b/internal/cli/commands/skilladd.go index 361d440..b6a4bde 100644 --- a/internal/cli/commands/skilladd.go +++ b/internal/cli/commands/skilladd.go @@ -12,6 +12,7 @@ import ( "github.com/spf13/cobra" + "github.com/stroops/sloop/internal/skills" "github.com/stroops/sloop/internal/workspace" ) @@ -79,9 +80,28 @@ func RunSkillAdd(startDir, url, name string) (string, []string, error) { if err := os.WriteFile(dst, body, 0o600); err != nil { return "", nil, err } + if err := recordSkillLock(ws.SloopDir(), name, url, body); err != nil { + return "", nil, err + } return dst, ensureSkillsLinked(ws), nil } +// recordSkillLock upserts a source-imported skill into .sloop/skills.lock so +// `sloop skills update` can later re-fetch it reproducibly. +func recordSkillLock(sloopDir, name, source string, body []byte) error { + lock, err := skills.Load(sloopDir) + if err != nil { + return err + } + lock.Upsert(skills.Entry{ + Name: name, + Source: source, + SHA256: skills.Hash(body), + Updated: time.Now().UTC().Format(time.RFC3339), + }) + return lock.Save(sloopDir) +} + var skillAddName string var skillAddCmd = &cobra.Command{ diff --git a/internal/cli/commands/skillupdate.go b/internal/cli/commands/skillupdate.go new file mode 100644 index 0000000..c011f11 --- /dev/null +++ b/internal/cli/commands/skillupdate.go @@ -0,0 +1,137 @@ +package commands + +import ( + "fmt" + "os" + "path/filepath" + "strings" + "time" + + "github.com/spf13/cobra" + + "github.com/stroops/sloop/internal/skills" + "github.com/stroops/sloop/internal/workspace" +) + +// SkillUpdateOutcome is the per-skill result of an update pass. +type SkillUpdateOutcome struct { + Name string + Updated bool // content changed and was rewritten + Err error // fetch/write failure (others still proceed) + Source string // for messaging +} + +// SkillUpdateResult summarizes an update run. +type SkillUpdateResult struct { + Outcomes []SkillUpdateOutcome + Linked []string // tools relinked when something changed +} + +// RunSkillUpdate re-fetches locked skills from their recorded sources and +// rewrites any whose content changed. With no names it updates every locked +// skill; otherwise only the named ones. A missing/empty lock is reported, not +// an error. +func RunSkillUpdate(startDir string, names []string) (*SkillUpdateResult, error) { + ws, err := workspace.Resolve(startDir) + if err != nil { + return nil, err + } + lock, err := skills.Load(ws.SloopDir()) + if err != nil { + return nil, err + } + + want := map[string]bool{} + for _, n := range names { + want[n] = true + } + for _, n := range names { + if _, ok := lock.Get(n); !ok { + return nil, fmt.Errorf("skill %q is not in skills.lock; import it with `sloop skills add `", n) + } + } + + res := &SkillUpdateResult{} + changed := false + for _, e := range lock.Skills { + if len(want) > 0 && !want[e.Name] { + continue + } + out := SkillUpdateOutcome{Name: e.Name, Source: e.Source} + body, err := fetchURL(rawURL(e.Source)) + if err != nil { + out.Err = err + res.Outcomes = append(res.Outcomes, out) + continue + } + if len(strings.TrimSpace(string(body))) == 0 { + out.Err = fmt.Errorf("fetched empty content from %s", e.Source) + res.Outcomes = append(res.Outcomes, out) + continue + } + if h := skills.Hash(body); h != e.SHA256 { + dst := filepath.Join(ws.SloopDir(), "skills", e.Name+".md") + if err := os.WriteFile(dst, body, 0o600); err != nil { + out.Err = err + res.Outcomes = append(res.Outcomes, out) + continue + } + e.SHA256 = h + e.Updated = time.Now().UTC().Format(time.RFC3339) + lock.Upsert(e) + out.Updated = true + changed = true + } + res.Outcomes = append(res.Outcomes, out) + } + + if changed { + if err := lock.Save(ws.SloopDir()); err != nil { + return nil, err + } + res.Linked = ensureSkillsLinked(ws) + } + return res, nil +} + +var skillUpdateCmd = &cobra.Command{ + Use: "update [name...]", + Aliases: []string{"up"}, + Short: "Re-fetch locked skills from their sources (.sloop/skills.lock)", + RunE: func(cmd *cobra.Command, args []string) error { + cwd, err := os.Getwd() + if err != nil { + return err + } + res, err := RunSkillUpdate(cwd, args) + if err != nil { + return err + } + if len(res.Outcomes) == 0 { + cmd.Println("no locked skills — import one with `sloop skills add `") + return nil + } + updated, failed := 0, 0 + for _, o := range res.Outcomes { + switch { + case o.Err != nil: + failed++ + cmd.Printf("✗ %s: %v\n", o.Name, o.Err) + case o.Updated: + updated++ + cmd.Printf("↑ %s updated\n", o.Name) + default: + cmd.Printf("= %s unchanged\n", o.Name) + } + } + cmd.Printf("%d updated, %d unchanged, %d failed\n", + updated, len(res.Outcomes)-updated-failed, failed) + if len(res.Linked) > 0 { + cmd.Printf("relinked into: %s\n", strings.Join(res.Linked, ", ")) + } + if failed > 0 { + return fmt.Errorf("%d skill(s) failed to update", failed) + } + return nil + }, +} diff --git a/internal/cli/commands/skillupdate_test.go b/internal/cli/commands/skillupdate_test.go new file mode 100644 index 0000000..e6661fc --- /dev/null +++ b/internal/cli/commands/skillupdate_test.go @@ -0,0 +1,106 @@ +package commands + +import ( + "os" + "path/filepath" + "testing" + + "github.com/stroops/sloop/internal/skills" +) + +// addLockedSkill imports a skill via the fetch seam and returns the workspace dir. +func addLockedSkill(t *testing.T, dir, body string) { + t.Helper() + orig := fetchURL + fetchURL = func(string) ([]byte, error) { return []byte(body), nil } + defer func() { fetchURL = orig }() + if _, _, err := RunSkillAdd(dir, "https://example.com/review.md", ""); err != nil { + t.Fatalf("RunSkillAdd: %v", err) + } +} + +func TestSkillAddRecordsLock(t *testing.T) { + dir := t.TempDir() + t.Setenv("HOME", t.TempDir()) + t.Setenv("PATH", t.TempDir()) + if _, err := RunInit(dir, false); err != nil { + t.Fatalf("RunInit: %v", err) + } + addLockedSkill(t, dir, "# Review\n\nv1\n") + + lock, err := skills.Load(filepath.Join(dir, ".sloop")) + if err != nil { + t.Fatalf("Load lock: %v", err) + } + e, ok := lock.Get("review") + if !ok { + t.Fatal("review not recorded in lock") + } + if e.Source != "https://example.com/review.md" || e.SHA256 != skills.Hash([]byte("# Review\n\nv1\n")) { + t.Fatalf("lock entry wrong: %+v", e) + } +} + +func TestRunSkillUpdateRefetches(t *testing.T) { + dir := t.TempDir() + t.Setenv("HOME", t.TempDir()) + t.Setenv("PATH", t.TempDir()) + if _, err := RunInit(dir, false); err != nil { + t.Fatalf("RunInit: %v", err) + } + addLockedSkill(t, dir, "# Review\n\nv1\n") + + // Re-fetch with changed content → updated; file + lock hash refreshed. + orig := fetchURL + fetchURL = func(string) ([]byte, error) { return []byte("# Review\n\nv2\n"), nil } + defer func() { fetchURL = orig }() + + res, err := RunSkillUpdate(dir, nil) + if err != nil { + t.Fatalf("RunSkillUpdate: %v", err) + } + if len(res.Outcomes) != 1 || !res.Outcomes[0].Updated { + t.Fatalf("expected 1 updated outcome, got %+v", res.Outcomes) + } + b, _ := os.ReadFile(filepath.Join(dir, ".sloop", "skills", "review.md")) + if string(b) != "# Review\n\nv2\n" { + t.Fatalf("file not rewritten: %q", string(b)) + } + + // Same content again → unchanged, no rewrite. + res, err = RunSkillUpdate(dir, nil) + if err != nil { + t.Fatalf("RunSkillUpdate (2): %v", err) + } + if res.Outcomes[0].Updated { + t.Fatal("expected unchanged on identical content") + } +} + +func TestRunSkillUpdateUnknownName(t *testing.T) { + dir := t.TempDir() + t.Setenv("HOME", t.TempDir()) + t.Setenv("PATH", t.TempDir()) + if _, err := RunInit(dir, false); err != nil { + t.Fatalf("RunInit: %v", err) + } + if _, err := RunSkillUpdate(dir, []string{"nope"}); err == nil { + t.Fatal("expected error for unknown skill name") + } +} + +func TestRunSkillUpdateEmptyLock(t *testing.T) { + dir := t.TempDir() + t.Setenv("HOME", t.TempDir()) + t.Setenv("PATH", t.TempDir()) + if _, err := RunInit(dir, false); err != nil { + t.Fatalf("RunInit: %v", err) + } + res, err := RunSkillUpdate(dir, nil) + if err != nil { + t.Fatalf("RunSkillUpdate: %v", err) + } + if len(res.Outcomes) != 0 { + t.Fatalf("expected no outcomes, got %+v", res.Outcomes) + } +} diff --git a/internal/cli/commands/status.go b/internal/cli/commands/status.go index a0cee28..ce316bf 100644 --- a/internal/cli/commands/status.go +++ b/internal/cli/commands/status.go @@ -43,7 +43,7 @@ func RunStatus(startDir string, w io.Writer) error { } tools = append(tools, label) m := manifests[t] - if m.Hooks.Install == "settings-json" { + if hookInstaller(m.Hooks.Install) != nil { autoHooks = append(autoHooks, t) } if m.Skills.Target != "" && syncpkg.SkillsState(ws.Root, ws.SloopDir(), m) == "linked" { diff --git a/internal/cli/commands/statusline.go b/internal/cli/commands/statusline.go index 4d1aef8..51fde73 100644 --- a/internal/cli/commands/statusline.go +++ b/internal/cli/commands/statusline.go @@ -6,6 +6,7 @@ import ( "github.com/spf13/cobra" + "github.com/stroops/sloop/internal/adapter" "github.com/stroops/sloop/internal/fleetstate" "github.com/stroops/sloop/internal/tmux" ) @@ -39,7 +40,8 @@ func renderStatusline(session string) string { if m, ok := fleetstate.Read(session); ok { st = stateToStatus(m.Status) } else if out, err := tmux.Output(tmux.BuildCaptureArgs(session)...); err == nil { - st = tmux.ClassifyStatus(string(out)) + manifests, _ := adapter.Load() + st = tmux.ClassifyStatus(string(out), manifests[tool]) } return fmt.Sprintf("⚓ %s %s %s", ws, tool, tmuxStatusLabel(st)) } @@ -54,7 +56,9 @@ var statuslineCmd = &cobra.Command{ if len(args) == 1 { session = args[0] } - cmd.Print(renderStatusline(session)) + // Must go to stdout: tmux's #() in the status bar captures stdout only. + // (cobra's cmd.Print writes to stderr, which the status bar never sees.) + _, _ = fmt.Fprint(cmd.OutOrStdout(), renderStatusline(session)) return nil }, } diff --git a/internal/cli/commands/statusline_test.go b/internal/cli/commands/statusline_test.go index 015457a..b1015e4 100644 --- a/internal/cli/commands/statusline_test.go +++ b/internal/cli/commands/statusline_test.go @@ -1,12 +1,32 @@ package commands import ( + "bytes" "strings" "testing" "github.com/stroops/sloop/internal/tmux" ) +// The status bar is rendered by tmux's #(), which captures stdout only. cobra's +// cmd.Print writes to stderr, so the command must write to stdout explicitly — +// guard that, or the status bar silently shows nothing. +func TestStatuslineCommandWritesToStdout(t *testing.T) { + t.Setenv("HOME", t.TempDir()) + var out, errb bytes.Buffer + statuslineCmd.SetOut(&out) + statuslineCmd.SetErr(&errb) + if err := statuslineCmd.RunE(statuslineCmd, []string{"myrepo__claude"}); err != nil { + t.Fatal(err) + } + if !strings.Contains(out.String(), "⚓ myrepo claude") { + t.Fatalf("stdout = %q, want the status line", out.String()) + } + if errb.Len() != 0 { + t.Fatalf("stderr should be empty, got %q", errb.String()) + } +} + func TestRenderStatusline(t *testing.T) { t.Setenv("HOME", t.TempDir()) // no markers; no live session → unknown out := renderStatusline("myrepo__claude") diff --git a/internal/cli/commands/tools.go b/internal/cli/commands/tools.go index 5874916..3d7e165 100644 --- a/internal/cli/commands/tools.go +++ b/internal/cli/commands/tools.go @@ -62,7 +62,7 @@ func skillsLabel(m adapter.Manifest) string { } func hooksLabel(m adapter.Manifest) string { - if m.Hooks.Install == "settings-json" { + if hookInstaller(m.Hooks.Install) != nil { return "auto" } if m.Hooks.Events.Working != "" || m.Hooks.Events.Waiting != "" || m.Hooks.Events.Idle != "" { diff --git a/internal/hints/hints.yaml b/internal/hints/hints.yaml index a2791ee..090fdb5 100644 --- a/internal/hints/hints.yaml +++ b/internal/hints/hints.yaml @@ -113,8 +113,14 @@ hints: - id: hooks-multi context: hooks text: - en: "`sloop hooks list` shows every provider; claude and gemini auto-install, others print the exact wiring." - vi: "`sloop hooks list` liệt kê mọi provider; claude và gemini tự cài, các tool khác in sẵn cách nối." + en: "`sloop hooks list` shows every provider; claude, gemini and cursor auto-install, others print the exact wiring." + vi: "`sloop hooks list` liệt kê mọi provider; claude, gemini và cursor tự cài, các tool khác in sẵn cách nối." + + - id: hooks-what + context: hooks + text: + en: "Hooks let a tool report its status to sloop directly — more precise than reading the screen, and the marker expires so it never goes stale." + vi: "Hook cho phép tool tự báo trạng thái cho sloop — chính xác hơn đọc màn hình, và marker tự hết hạn nên không bao giờ cũ." - id: detach-general context: general diff --git a/internal/skills/lock.go b/internal/skills/lock.go new file mode 100644 index 0000000..e8a3fb5 --- /dev/null +++ b/internal/skills/lock.go @@ -0,0 +1,102 @@ +// Package skills manages the workspace skills lockfile (.sloop/skills.lock), +// which records each URL-imported skill and its source so `sloop skills update` +// can re-fetch reproducibly and a team gets the same skills from one source. +// +// Only skills imported from a source (sloop skills add ) are locked; +// locally authored skills (sloop skills new) are not re-fetchable and stay out. +package skills + +import ( + "crypto/sha256" + "encoding/hex" + "os" + "path/filepath" + "sort" + + "gopkg.in/yaml.v3" +) + +// LockVersion is the current skills.lock schema version. +const LockVersion = 1 + +const lockName = "skills.lock" + +// Entry is one locked skill: a stable name, the source it was fetched from, and +// the content hash + fetch time so update can report unchanged vs. refreshed. +type Entry struct { + Name string `yaml:"name"` + Source string `yaml:"source"` + SHA256 string `yaml:"sha256,omitempty"` + Updated string `yaml:"updated,omitempty"` +} + +// Lock is the parsed skills.lock for one workspace. +type Lock struct { + Version int `yaml:"version"` + Skills []Entry `yaml:"skills"` +} + +// LockPath returns the lockfile path for a given .sloop directory. +func LockPath(sloopDir string) string { return filepath.Join(sloopDir, lockName) } + +// Load reads the lockfile. A missing file is an empty lock, not an error. +func Load(sloopDir string) (*Lock, error) { + b, err := os.ReadFile(LockPath(sloopDir)) + if os.IsNotExist(err) { + return &Lock{Version: LockVersion}, nil + } + if err != nil { + return nil, err + } + var l Lock + if err := yaml.Unmarshal(b, &l); err != nil { + return nil, err + } + if l.Version == 0 { + l.Version = LockVersion + } + return &l, nil +} + +// Save writes the lockfile (sorted by name for stable diffs). +func (l *Lock) Save(sloopDir string) error { + if l.Version == 0 { + l.Version = LockVersion + } + sort.Slice(l.Skills, func(i, j int) bool { return l.Skills[i].Name < l.Skills[j].Name }) + if err := os.MkdirAll(sloopDir, 0o700); err != nil { + return err + } + b, err := yaml.Marshal(l) + if err != nil { + return err + } + return os.WriteFile(LockPath(sloopDir), b, 0o600) +} + +// Get returns the entry for name, if present. +func (l *Lock) Get(name string) (Entry, bool) { + for _, e := range l.Skills { + if e.Name == name { + return e, true + } + } + return Entry{}, false +} + +// Upsert replaces the entry with the same name or appends a new one. +func (l *Lock) Upsert(e Entry) { + for i := range l.Skills { + if l.Skills[i].Name == e.Name { + l.Skills[i] = e + return + } + } + l.Skills = append(l.Skills, e) +} + +// Hash returns the hex SHA-256 of content, used to detect changes on update. +func Hash(content []byte) string { + sum := sha256.Sum256(content) + return hex.EncodeToString(sum[:]) +} diff --git a/internal/skills/lock_test.go b/internal/skills/lock_test.go new file mode 100644 index 0000000..f828bd7 --- /dev/null +++ b/internal/skills/lock_test.go @@ -0,0 +1,69 @@ +package skills + +import ( + "os" + "testing" +) + +func TestLoadMissingIsEmpty(t *testing.T) { + l, err := Load(t.TempDir()) + if err != nil { + t.Fatalf("Load: %v", err) + } + if l.Version != LockVersion || len(l.Skills) != 0 { + t.Fatalf("want empty v%d lock, got %+v", LockVersion, l) + } +} + +func TestUpsertSaveLoadRoundTrip(t *testing.T) { + dir := t.TempDir() + l, _ := Load(dir) + l.Upsert(Entry{Name: "review", Source: "https://x/review.md", SHA256: Hash([]byte("a"))}) + l.Upsert(Entry{Name: "apply", Source: "https://x/apply.md"}) + // Replace existing by name. + l.Upsert(Entry{Name: "review", Source: "https://x/review.md", SHA256: Hash([]byte("b"))}) + if err := l.Save(dir); err != nil { + t.Fatalf("Save: %v", err) + } + + got, err := Load(dir) + if err != nil { + t.Fatalf("Load: %v", err) + } + if len(got.Skills) != 2 { + t.Fatalf("want 2 entries, got %d", len(got.Skills)) + } + // Sorted by name: apply before review. + if got.Skills[0].Name != "apply" || got.Skills[1].Name != "review" { + t.Fatalf("not sorted: %+v", got.Skills) + } + if e, ok := got.Get("review"); !ok || e.SHA256 != Hash([]byte("b")) { + t.Fatalf("upsert did not replace: %+v", e) + } +} + +func TestHashStable(t *testing.T) { + x1, x2, y := Hash([]byte("x")), Hash([]byte("x")), Hash([]byte("y")) + if x1 != x2 { + t.Fatal("Hash not deterministic for identical content") + } + if x1 == y { + t.Fatal("Hash collides on different content") + } +} + +func TestSavePermissions(t *testing.T) { + dir := t.TempDir() + l, _ := Load(dir) + l.Upsert(Entry{Name: "a", Source: "s"}) + if err := l.Save(dir); err != nil { + t.Fatalf("Save: %v", err) + } + info, err := os.Stat(LockPath(dir)) + if err != nil { + t.Fatalf("stat: %v", err) + } + if perm := info.Mode().Perm(); perm != 0o600 { + t.Fatalf("perm = %o, want 600", perm) + } +} diff --git a/internal/tmux/status.go b/internal/tmux/status.go index 656c395..04ff94b 100644 --- a/internal/tmux/status.go +++ b/internal/tmux/status.go @@ -3,6 +3,8 @@ package tmux import ( "regexp" "strings" + + "github.com/stroops/sloop/internal/adapter" ) // AgentStatus is a best-effort classification of what an AI session is doing, @@ -37,8 +39,12 @@ func (s AgentStatus) NeedsAttention() bool { return s == StatusWaiting } // spinner is almost always within the last handful of lines. const statusScanLines = 8 -// waitingMarkers signal the agent is blocked on the user. Matched case-insensitively. -var waitingMarkers = []string{ +// defaultWaitingMarkers signal the agent is blocked on the user. These are +// cross-tool terminal conventions (every CLI agent prints them the same way) and +// are applied to every manifest, not special-cased per tool. A manifest's own +// heuristics.waiting is merged on top for genuinely tool-specific phrasing. +// Matched case-insensitively. +var defaultWaitingMarkers = []string{ "do you want to", "(y/n)", "[y/n]", "y/n)", "(yes/no)", "press enter", @@ -52,12 +58,15 @@ var waitingMarkers = []string{ "confirm", } -// workingMarkers signal the agent is actively running. Matched case-insensitively. -var workingMarkers = []string{ +// defaultWorkingMarkers signal the agent is actively running. Cross-tool +// defaults (see defaultWaitingMarkers); a manifest's heuristics.working adds to +// these. Matched case-insensitively. +var defaultWorkingMarkers = []string{ "esc to interrupt", "ctrl+c to", "ctrl-c to", "thinking", "working…", "working...", - "generating", "running", + "generating", "running", "running command", + "reading file", "tokens", "esc to cancel", } @@ -67,21 +76,22 @@ const spinnerRunes = "⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏⣾⣽⣻⢿⡿⣟⣯⣷◐ // ClassifyStatus inspects the tail of a captured pane and returns a best-effort // status. Waiting (needs you) takes precedence over working, which takes // precedence over idle. Empty input is StatusUnknown. -func ClassifyStatus(pane string) AgentStatus { +func ClassifyStatus(pane string, manifest adapter.Manifest) AgentStatus { tail := lastLines(pane, statusScanLines) if tail == "" { return StatusUnknown } low := strings.ToLower(tail) - for _, m := range waitingMarkers { - if strings.Contains(low, m) { - return StatusWaiting - } - } - for _, m := range workingMarkers { - if strings.Contains(low, m) { - return StatusWorking - } + // Default markers are cross-tool defaults; the manifest adds tool-specific + // ones. Check the lists separately rather than append()-ing the per-tool + // slice onto the shared package slice: ClassifyStatus runs concurrently (one + // goroutine per fleet row), and appending could write into the defaults' + // backing array and race. + if containsAny(low, defaultWaitingMarkers, manifest.Heuristics.Waiting) { + return StatusWaiting + } + if containsAny(low, defaultWorkingMarkers, manifest.Heuristics.Working) { + return StatusWorking } if strings.ContainsAny(tail, spinnerRunes) { return StatusWorking @@ -89,6 +99,19 @@ func ClassifyStatus(pane string) AgentStatus { return StatusIdle } +// containsAny reports whether low (already lowercased) contains any marker from +// any of the given lists, matched case-insensitively. +func containsAny(low string, lists ...[]string) bool { + for _, list := range lists { + for _, m := range list { + if strings.Contains(low, strings.ToLower(m)) { + return true + } + } + } + return false +} + // Answer is a choice the agent is offering at a blocking prompt. Key is what to // send to pick it ("y", "n", "1"…); Key "" means "just press Enter". type Answer struct { diff --git a/internal/tmux/status_test.go b/internal/tmux/status_test.go index f37eaa2..90a816e 100644 --- a/internal/tmux/status_test.go +++ b/internal/tmux/status_test.go @@ -1,6 +1,11 @@ package tmux -import "testing" +import ( + "sync" + "testing" + + "github.com/stroops/sloop/internal/adapter" +) func TestClassifyStatus(t *testing.T) { cases := []struct { @@ -23,13 +28,47 @@ func TestClassifyStatus(t *testing.T) { } for _, c := range cases { t.Run(c.name, func(t *testing.T) { - if got := ClassifyStatus(c.pane); got != c.want { + if got := ClassifyStatus(c.pane, adapter.Manifest{}); got != c.want { t.Fatalf("ClassifyStatus(%q) = %v, want %v", c.pane, got, c.want) } }) } } +// TestClassifyStatusManifestMarkers covers the per-tool heuristics path: a phrase +// no built-in marker recognizes is classified via the manifest's own markers. +func TestClassifyStatusManifestMarkers(t *testing.T) { + m := adapter.Manifest{Heuristics: adapter.HeuristicsSpec{ + Waiting: []string{"Shall I apply this fix"}, + Working: []string{"Crunching the repo"}, + }} + if got := ClassifyStatus("Shall I apply this fix?", m); got != StatusWaiting { + t.Fatalf("manifest waiting marker = %v, want waiting", got) + } + if got := ClassifyStatus("Crunching the repo index", m); got != StatusWorking { + t.Fatalf("manifest working marker = %v, want working", got) + } + // Built-in markers still apply alongside the manifest's. + if got := ClassifyStatus("Apply changes? (y/n)", m); got != StatusWaiting { + t.Fatalf("built-in marker with manifest set = %v, want waiting", got) + } +} + +// TestClassifyStatusConcurrent guards against the append-onto-shared-slice race: +// many goroutines classify with a manifest at once (run with -race). +func TestClassifyStatusConcurrent(t *testing.T) { + m := adapter.Manifest{Heuristics: adapter.HeuristicsSpec{Waiting: []string{"custom prompt"}}} + var wg sync.WaitGroup + for i := 0; i < 50; i++ { + wg.Add(1) + go func() { + defer wg.Done() + _ = ClassifyStatus("doing some work\ncustom prompt here", m) + }() + } + wg.Wait() +} + func TestAgentStatusString(t *testing.T) { for s, want := range map[AgentStatus]string{ StatusUnknown: "unknown", diff --git a/internal/tmux/statusline.go b/internal/tmux/statusline.go index 0c3a618..d16b6bc 100644 --- a/internal/tmux/statusline.go +++ b/internal/tmux/statusline.go @@ -3,8 +3,21 @@ package tmux import ( "fmt" "os" + "strings" ) +// statusLineEnabled reports whether sloop should style a session's status bar. +// Power users with their own tmux status bar can keep it untouched by setting +// SLOOP_STATUSLINE=0 (or off/false/no) — sloop then never overrides status-left/ +// status-right, even per session. +func statusLineEnabled() bool { + switch strings.ToLower(os.Getenv("SLOOP_STATUSLINE")) { + case "0", "off", "false", "no": + return false + } + return true +} + // StatusRightFormat is the tmux status-right value that calls back into sloop to // render this session's live status (re-run every status-interval). func StatusRightFormat(exe, session string) string { @@ -13,8 +26,13 @@ func StatusRightFormat(exe, session string) string { // SetStatusLine points a single session's status bar at `sloop statusline`, // refreshed every 2s. It is per-session (`set-option -t`), so it never touches -// the user's global tmux config or other sessions. Best-effort. +// the user's global tmux config (~/.tmux.conf) or other sessions, and only +// overrides status-left/status-right (not colors/theme). Best-effort, and a +// no-op when SLOOP_STATUSLINE is disabled so a custom status bar stays intact. func SetStatusLine(session string) { + if !statusLineEnabled() { + return + } exe, err := os.Executable() if err != nil || exe == "" { exe = "sloop" @@ -25,4 +43,9 @@ func SetStatusLine(session string) { set("status-right", StatusRightFormat(exe, session)) set("status-right-length", "60") set("status-interval", "2") + // status-left becomes a persistent "how to get back" tip, using the user's + // real prefix, so anyone inside the session can see how to detach (return to + // the fleet without stopping the agent). + set("status-left", fmt.Sprintf(" ⚓ detach: %s d ", PrefixRaw())) + set("status-left-length", "24") } diff --git a/internal/tmux/statusline_test.go b/internal/tmux/statusline_test.go index 6d0406c..2046df4 100644 --- a/internal/tmux/statusline_test.go +++ b/internal/tmux/statusline_test.go @@ -9,3 +9,18 @@ func TestStatusRightFormat(t *testing.T) { t.Fatalf("got %q, want %q", got, want) } } + +func TestStatusLineEnabled(t *testing.T) { + for _, off := range []string{"0", "off", "false", "no", "OFF"} { + t.Setenv("SLOOP_STATUSLINE", off) + if statusLineEnabled() { + t.Errorf("SLOOP_STATUSLINE=%q should disable the status line", off) + } + } + for _, on := range []string{"", "1", "on", "yes", "anything"} { + t.Setenv("SLOOP_STATUSLINE", on) + if !statusLineEnabled() { + t.Errorf("SLOOP_STATUSLINE=%q should keep the status line on", on) + } + } +} diff --git a/internal/tmux/tmux.go b/internal/tmux/tmux.go index e56527a..a535f63 100644 --- a/internal/tmux/tmux.go +++ b/internal/tmux/tmux.go @@ -113,6 +113,21 @@ func Prefix() string { return "Ctrl+b" } +// PrefixRaw returns the tmux prefix key in tmux's own notation (e.g. "C-a"), for +// compact display in a status bar; falls back to "C-b". (Prefix returns the +// human "Ctrl+a" form for prose; this is the terse form for the status line.) +func PrefixRaw() string { + out, err := Output("show-options", "-g", "prefix") + if err != nil { + return "C-b" + } + parts := strings.Fields(strings.TrimSpace(string(out))) + if len(parts) == 2 { + return parts[1] + } + return "C-b" +} + func sanitize(s string) string { var b strings.Builder for _, r := range s { @@ -166,6 +181,21 @@ func SessionPath(session string) string { return strings.TrimSpace(string(out)) } +// LaunchDetached creates a detached session running command+args in dir and +// gives it sloop's per-session status bar, without attaching. Used by `sloop +// restore` to bring several sessions back at once. No-op if it already exists. +func LaunchDetached(session, dir, command string, args []string) error { + if hasSession(session) { + return nil + } + create := append([]string{"new-session", "-d", "-s", session, "-c", dir, command}, args...) + if err := Run(create...); err != nil { + return err + } + SetStatusLine(session) + return nil +} + type Runner struct { Session string } diff --git a/internal/tui/input.go b/internal/tui/input.go new file mode 100644 index 0000000..dadd5f9 --- /dev/null +++ b/internal/tui/input.go @@ -0,0 +1,98 @@ +package tui + +import ( + "fmt" + "os" + + "golang.org/x/term" +) + +// ReadLine reads a single line in raw mode so the caller's control loop keeps +// ownership of the terminal: Enter submits (ok=true), while Esc, Ctrl-C and +// Ctrl-D cancel (ok=false) instead of killing the process. This is what lets the +// `ps` control center treat a cancelled send as "back to the fleet" rather than +// dropping to the shell. Backspace deletes a whole rune, so multibyte input +// (e.g. Vietnamese) edits cleanly. Without a tty it returns ("", false). +func ReadLine(prompt string) (string, bool) { + fd := int(os.Stdin.Fd()) + if !term.IsTerminal(fd) { + return "", false + } + oldState, err := term.MakeRaw(fd) + if err != nil { + return "", false + } + defer func() { _ = term.Restore(fd, oldState) }() + + fmt.Print(prompt) + var buf []byte + in := make([]byte, 16) + for { + n, _ := os.Stdin.Read(in) + if n == 0 { + continue + } + b := in[:n] + if n == 1 { + switch b[0] { + case 3, 4, 27: // Ctrl-C, Ctrl-D, Esc → cancel + fmt.Print("\r\n") + return "", false + case 13, 10: // Enter → submit + fmt.Print("\r\n") + return string(buf), true + case 127, 8: // Backspace → drop the last rune and redraw + buf = trimLastRune(buf) + fmt.Print("\r\033[K" + prompt + string(buf)) + continue + } + if b[0] < 32 { // other control byte (Tab, etc.) → ignore + continue + } + } else if b[0] == 27 { + continue // multi-byte escape sequence (arrow keys, …) → ignore + } + buf = append(buf, b...) // printable ASCII or UTF-8 multibyte + fmt.Print(string(b)) + } +} + +// Confirm asks a y/N question in raw mode and returns true only on y/Y. Any +// other key — including Esc and Ctrl-C — answers no without killing the process, +// so a declined confirm returns to the caller's control loop. +func Confirm(prompt string) bool { + fd := int(os.Stdin.Fd()) + if !term.IsTerminal(fd) { + return false + } + oldState, err := term.MakeRaw(fd) + if err != nil { + return false + } + defer func() { _ = term.Restore(fd, oldState) }() + + fmt.Print(prompt) + in := make([]byte, 1) + for { + n, _ := os.Stdin.Read(in) + if n == 0 { + continue + } + yes := in[0] == 'y' || in[0] == 'Y' + fmt.Print("\r\n") + return yes + } +} + +// trimLastRune drops the final UTF-8 rune from b (backing over continuation +// bytes), so Backspace deletes a whole character, not a stray byte. +func trimLastRune(b []byte) []byte { + i := len(b) - 1 + for i > 0 && b[i]&0xC0 == 0x80 { + i-- + } + if i < 0 { + return b[:0] + } + return b[:i] +} diff --git a/internal/tui/input_test.go b/internal/tui/input_test.go new file mode 100644 index 0000000..8019086 --- /dev/null +++ b/internal/tui/input_test.go @@ -0,0 +1,19 @@ +package tui + +import "testing" + +func TestTrimLastRune(t *testing.T) { + cases := []struct{ in, want string }{ + {"", ""}, + {"a", ""}, + {"abc", "ab"}, + {"gõ", "g"}, // multibyte tail (õ is 2 bytes) → drop the whole rune + {"việt", "việ"}, // ệ is 3 bytes → drop the whole rune, keep the rest intact + {"⏎", ""}, // 3-byte rune → empty + } + for _, c := range cases { + if got := string(trimLastRune([]byte(c.in))); got != c.want { + t.Errorf("trimLastRune(%q) = %q, want %q", c.in, got, c.want) + } + } +} diff --git a/internal/tui/menu.go b/internal/tui/menu.go index 28b8ae5..e9f9cf0 100644 --- a/internal/tui/menu.go +++ b/internal/tui/menu.go @@ -8,6 +8,15 @@ import ( "golang.org/x/term" ) +// Clear homes the cursor and clears the screen, but only on a real terminal, so +// a control-center loop can redraw in place instead of stacking a fresh menu +// under the previous one. A no-op when piped/redirected (no escape junk). +func Clear() { + if term.IsTerminal(int(os.Stdout.Fd())) { + fmt.Print("\033[H\033[2J") + } +} + // SelectMenu presents options and lets the user pick one with the arrow keys // (or j/k). It returns the selected index, or -1 if cancelled (Esc/Ctrl-C/q) or // run without a terminal. An option may contain "\r\n" to add indented