agentleFS
weill-labsweill-labs/amux/CLAUDE.md

amux

CLAUDE.md34 starsChanged 6 months agoMITView on GitHub

See README.md -- How it works for the project overview and system model. Client-server architecture. The server is a background daemon that owns PTYs and layout state. Clients connect over a Unix socket, receive layout snapshots and raw pane output, and render locally. This enables hot-reload: rebuilding the binary auto-restarts the client with new rendering code while preserving running shells. Pane metadata is in-memory. All pane state lives in mux.PaneMeta structs on the server. No external database or state files.

  • Commits and pushes

The file

Show its rules and text

We split this CLAUDE.md into the rules it gives an agent

28 rules. About 0 are common, 8 are distinctive, and 20 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈8

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 20

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  • could be automatic: a setting could enforce it
  1. Very specific:

    Pane metadata is in-memory: All pane state lives in mux.PaneMeta structs on the server.

    line 9
  2. Very specific:

    Use the persistent harness when server lifetime matters: Prefer newServerHarnessPersistent() for integration tests that must keep the …

    line 41
  3. Very specific:

    When troubleshooting spawn or assignment failures, fix the specific problem (clean up duplicate panes, check amux state) rather than …

    line 85
  4. Very specific:

    When a worker pushes fixes for Claude review findings, scripts/check-claude-review.sh reports whether the latest Claude verdict is lgtm or …

    line 104
  5. Distinctive:

    All development follows red-green-refactor with separate commits for each phase:

    line 108
  6. Very specific:

    When a change adds a new test or modifies an existing test, run that targeted test slice with -count=100 before calling the work done.

    line 120
  7. Very specific:

    Do not git pull a dirty local main.

    line 141
  8. Very specific:

    If a PR is already open and git fetch origin main or git pull advances origin/main, refresh that PR branch onto origin/main before treating …

    line 143
  9. Distinctive:

    Commit design specs and implementation plans to the feature branch, not main.

    line 147
  10. Distinctive:

    Description: must include four sections:

    line 155
  11. Very specific:

    Use matter-of-fact language.

    line 162
  12. Very specific:

    After opening a PR, run scripts/watch-pr-ci.sh once to wait for its required checks.

    line 166
  13. Distinctive:

    After creating or updating a PR, run a review pass and a simplification pass before considering the work done.

    line 174
  14. Very specific:

    Prefer external review tooling like codex review when it returns promptly, but do not block the PR on it.

    line 176
  15. Distinctive:

    If a change in this repo is ready for review, open the PR proactively instead of asking whether to make one.

    line 178
  16. Distinctive:

    Before stopping to wait for user input, suggest the next concrete action the user should take or approve.

    line 182
  17. Very specific:

    If you ran $postmortem, provide the log path, summarize the key learnings, list the concrete action items, and say whether you already …

    line 184
  18. Very specific:

    After resolving merge conflicts, run go vet ./...

    line 188
  19. Very specific:

    Before telling the user a PR is safe to merge, check for merge conflicts with main: git fetch origin main && git merge-tree --write-tree …

    line 192
  20. Very specific:

    After merging, verify local state explicitly: check that the checkout is on main, the worktree is clean, and HEAD matches origin/main.

    line 198
  21. Very specific:

    After merging, explicitly run $postmortem.

    line 202
  22. Very specific:

    When creating PRs that add or modify benchmarks, include a Baseline numbers section in the PR description with representative results in a …

    line 208
  23. Very specific:

    Check what dependencies already provide: Before designing a custom solution, check if the underlying library (for example, …

    line 214
  24. Very specific:

    Use amux capture --format json to inspect composited output programmatically.

    line 226
  25. Distinctive:

    If the zoomed view is clean but the unzoomed view is corrupted, the bug is in the compositor or diff renderer (cell-grid boundary …

    line 230
  26. Distinctive:

    If the zoomed view is also corrupted, the bug is in the terminal emulator or PTY output

    line 231
  27. Very specific:

    Prefer the built-in amux debug commands — they target the latest attached client pprof endpoint directly, so you skip hand-probing for a …

    line 243
  28. Very specific:

    If the amux debug client-* commands cannot reach the client (none attached, or you need the raw socket), fall back to probing by hand — …

    line 254

≈ “Common” is an estimate: at least 1 in 5 of the 28,029 CLAUDE.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
CLAUDE.md

CLAUDE.md

Design Philosophy

See README.md -- How it works for the project overview and system model.

Client-server architecture. The server is a background daemon that owns PTYs and layout state. Clients connect over a Unix socket, receive layout snapshots and raw pane output, and render locally. This enables hot-reload: rebuilding the binary auto-restarts the client with new rendering code while preserving running shells.

Pane metadata is in-memory. All pane state lives in mux.PaneMeta structs on the server. No external database or state files.

Names over IDs. Users reference panes by name (pane-3) or numeric ID (3). Window.ResolvePane() handles resolution. Prefix matches are also supported.

Architecture

Key Abstractions

Client-server protocol -- Clients send MsgTypeInput, MsgTypeResize, MsgTypeCommand. Server sends MsgTypePaneOutput (raw PTY bytes per pane), MsgTypeLayout (layout tree snapshot), MsgTypeRender (legacy pre-rendered ANSI).

mux.Window -- Owns the layout tree (LayoutCell) and active pane. All layout operations (split, close, resize, focus) go through Window methods.

mux.LayoutCell -- Binary tree of splits. Leaves hold panes. Internal nodes hold a split direction and children. Walk() for traversal, FindPane() for lookup, FixOffsets() after structural changes.

Window.ResolvePane(ref) -- Accepts pane name (pane-1), numeric ID (1), or prefix match. All CLI commands route through this.

render.RenderFull() -- Composites pane content, borders with junction characters, per-pane status lines, and the global session bar into a single ANSI output string.

Capture architecture -- The target split for amux capture is documented in docs/capture-architecture.md: server-side capture becomes the default source-of-truth path, and client-side capture remains an opt-in user-perspective path.

Patterns To Follow

One package per concern. Layout logic in mux/, rendering in render/, server protocol in server/. Packages depend on interfaces and shared types (proto/), not on each other's internals.

Unit tests for layout/rendering logic. See layout_test.go, window_test.go, emulator_test.go. Use fakePaneID() helper to create minimal panes for testing.

Integration tests for end-to-end behavior. The harness in test/server_harness_test.go drives amux directly over the Unix socket -- no tmux dependency. Tests run in ~6s total.

Inject dependencies, do not add package-level var for test seams. When production code needs a swappable dependency (e.g., clipboard command, time function, exec resolver), pass it as a function parameter or struct field -- never as a mutable package-level var. Tests pass stubs directly; production call sites pass the real implementation. This keeps tests parallel and eliminates shared mutable state. See PR #388 for the canonical pattern.

The same lever covers branches that are unreachable through real I/O. When an error or empty-result branch can only be hit behind an SSH dial or a live client connection, lift the decision into a pure function over a small interface and fake it in a unit test, rather than fighting to reach it through the integration path (which also keeps diff coverage honest). See sendRemoteChooser/chooserSender (the empty-list + send-failure paths) and mirror.Dialer for the canonical shape.

Use the persistent harness when server lifetime matters. Prefer newServerHarnessPersistent() for integration tests that must keep the server alive independent of client detach timing or transient attachment windows. Use the default harness when exit-on-unattached behavior is part of the behavior under test.

Guard against impossible states. Focus fallback finds nearest pane when strict overlap matching fails.

Commands fail loudly on no-ops. A command must return an error, not a success Output, when it performs no observable action -- no pane created, an empty remote pane list, dropped/unforwarded input, an unconfigured host. Three federation bugs fit this "reports success while doing nothing" shape (spawn --attach to an unknown host, the chooser on an empty remote list, the local-only kill default). When a handler returns commandpkg.Result{Output: ...}, confirm the action actually happened first.

Save/restore cursor state in copy mode motions. Compound motions (word, paragraph, etc.) call moveDown()/moveUp() in scanning loops. These helpers mutate cy/oy on each call, so the caller must save both values before the loop and restore them when returning ActionNone. Otherwise the cursor drifts silently on failed motions.

Colors live in config/config.go. The Catppuccin Mocha palette (CatppuccinMocha), letter abbreviations (CatppuccinLetters), and named hex constants (DimColorHex, TextColorHex) are defined once in the config package. Reference these constants instead of hardcoding hex values like "f5e0dc" or "6c7086".

Development

Build And Test

make setup                         # activate repo git hooks
make install                       # install amux (client hot-reloads automatically)
go test ./... -timeout 120s        # run all tests
make coverage                      # merged unit + integration coverage (use this, not go test -coverprofile)

Testing Live

See README.md -- CLI Reference for the full command reference. Key commands for testing:

amux                              # start or reattach
amux capture --format json        # structured JSON for agents
amux capture --format json pane-1 # single pane JSON

Confirm Before Any Destructive Pane or Daemon Action

Get explicit user approval before killing panes, closing windows, restarting orca, cancelling tasks, or any action that destroys worker state. No exceptions. These actions lose running agent context, in-progress work, and session history that cannot be recovered.

Destructive actions that require user confirmation:

  • Killing or closing a pane (amux kill, closing a window)
  • Restarting orca (orca stop, orca start) — kills worker panes and orphans active tasks
  • Cancelling an orca task (orca cancel)
  • Killing a process in a worker pane — capture diagnostics first (kill -3 / SIGQUIT for Go goroutine trace). The trace is the only evidence for deadlock root cause and is destroyed on kill.
  • /exit on codex — run postmortem first. Session context (reasoning, corrections, decisions) is destroyed on exit and cannot be recovered.
  • Mass send-keys — if sending to more than 3 panes, present the message and pane list to the user for approval. Batch operations are where mistakes scale.

When troubleshooting spawn or assignment failures, fix the specific problem (clean up duplicate panes, check amux state) rather than restarting orca.

  • Recovery ≠ assignment: restoring a codex process is a separate action from giving it work. After recovery, leave workers at idle prompts. Only assign specific, user-approved issues.
  • Detecting when a codex pane finishes: poll amux capture for the absence of the esc to interrupt line (shown as Working (Ns • esc to interrupt) while codex is busy). Do not key on the input-box placeholder (Improve documentation in @filename) — it is always present, even mid-task, so it false-signals "idle" immediately. Give codex a few seconds to pick up a submitted prompt before the first poll.

Working In amux

When working in an amux pane, start Linear work with the helper script so the current pane is tagged automatically. Outside an amux pane, pass the pane explicitly. Open PRs with scripts/gh-pr-create.sh ... so pane PR metadata syncs regardless of which agent created the PR. With make setup active, the repo pre-push hook also re-syncs pane PR metadata for any later git push. Keep the repair helpers handy:

scripts/set-pane-issue.sh LAB-XXX
scripts/set-pane-issue.sh pane-3 LAB-XXX
scripts/gh-pr-create.sh --fill
scripts/sync-pane-pr-meta.sh
scripts/sync-pane-pr-meta.sh 123

Any agent can run scripts/check-pane-issue-meta.sh manually to check whether the current pane is tagged with a Linear issue.

When a worker pushes fixes for Claude review findings, scripts/check-claude-review.sh reports whether the latest Claude verdict is lgtm or findings. Add --watch to wait for the next Claude review comment after the push before deciding whether more fixes are needed.

TDD Workflow

All development follows red-green-refactor with separate commits for each phase:

  1. Red -- Write failing tests. Commit them alone. Confirm they fail for the right reason (missing feature, not a syntax error).
  2. Green -- Minimal production code to make tests pass. Commit separately.
  3. Refactor -- Simplify, extract helpers, remove duplication. Commit separately.

The integration test harness makes this fast (~6s for the full suite).

Test Philosophy

Tests should read like specs. Minimize logic in assertions so a human can read the test and immediately understand what behavior is expected. Prefer golden file comparisons (assertGolden) over inline predicate functions -- the golden file is the spec, viewable as a standalone document. Use table-driven tests for unit tests with multiple cases -- define a tests slice of structs, iterate with t.Run(tt.name, ...), and call t.Parallel() in each subtest.

When a change adds a new test or modifies an existing test, run that targeted test slice with -count=100 before calling the work done. Treat any failure in those repeated runs as a flake to investigate, not as an acceptable one-off.

Fix flaky tests by finding the root cause. Never make tests serial to avoid a flake — that hides the bug (shared state, resource contention, missing synchronization) instead of fixing it. If tests deadlock under -count=3 -parallel=2, the fix is in the code, not the test runner flags.

CLI subprocess tests must use the shared hermetic helper. Do not open-code exec.Command(os.Args[0], ...) or exec.Command(amuxBin, ...), and do not inherit ambient AMUX_SESSION / TMUX state in root or test/ package tests. Route those tests through the shared helper, for example newHermeticAmuxCommand(t, "-s", session, "list"), so they always run with an isolated session and scrubbed env.

Changes to main.go CLI dispatch need direct unit coverage on the touched lines. Keep the hermetic subprocess tests for end-to-end CLI behavior, but when a change touches the dispatch branches in main.go, add direct unit coverage (for example in main_test.go) for those specific lines too. Codecov patch coverage measures the changed main.go lines directly and may miss coverage that only arrives through subprocess tests.

Cover every branch of a new function before pushing. The pre-push hook runs scripts/check-diff-coverage.sh and rejects the push when changed lines fall below the patch target (currently 70%). Write unit tests for the early returns too -- nil guards and error paths, not just the happy path -- so the function's branches are covered up front. To exercise a tty-ioctl error path on macOS, pass a regular file as the fd: it reliably yields ENOTTY, whereas a pipe fd does not.

Golden files live in test/testdata/. Two types:

  • .golden -- structural layout frame (status lines, borders, global bar). Open one and you see the expected screen layout.
  • .color -- border color map using Catppuccin color initials (R=Rosewater, F=Flamingo, M=Mauve, .=dim, |=global bar). Shows which borders should be colored at a glance.

Regenerate goldens after intentional rendering changes: cd test && go test -run TestGolden -update

Pre-Push Rebase

Rebase onto origin/main before the first push (git fetch origin main && git rebase origin/main). Multiple features often land in parallel; rebasing before push avoids repeated merge conflict resolution after the PR is open.

Do not git pull a dirty local main. If main has uncommitted work, leave it alone and start the next change from a fresh branch based on origin/main instead. Do not use git worktree unless the user explicitly asks for it.

If a PR is already open and git fetch origin main or git pull advances origin/main, refresh that PR branch onto origin/main before treating it as current again. After the refresh, rerun verification on the rebased branch before pushing.

Specs And Plans On Feature Branches

Commit design specs and implementation plans to the feature branch, not main. Committing to main before creating the feature branch causes divergent branches on subsequent pulls.

PR Title And Description

PR title and description are the permanent record of why a change was made. Write them for a reviewer seeing the diff for the first time.

Title: State what changed in imperative mood, under 70 characters. Always include the Linear issue prefix (e.g., LAB-314:) when a ticket exists, so the PR list shows the ticket inline. Example: "LAB-314: Timestamp crash checkpoint filenames to prevent overwriting".

Description must include four sections:

  1. Motivation -- Why this change? What broke, what was missing, or what user need does it address? One to three sentences.
  2. Summary -- What changed? Bullet the key changes. Describe the PR as a complete unit, not per-commit.
  3. Testing -- How was it verified? Include the exact test commands a reviewer can copy-paste.
  4. Review focus -- What should reviewers look at? Call out non-obvious design decisions, edge cases, or areas where you are least confident.

Use matter-of-fact language. State what the PR does, not how good it is. Avoid vague qualifiers like "robust", "comprehensive", "elegant", or "production-ready". If a Linear issue exists, add Closes LAB-NNN at the bottom.

PR CI Ownership

After opening a PR, run scripts/watch-pr-ci.sh once to wait for its required checks. For later updates to an open PR, prefer scripts/push-and-watch-ci.sh instead of bare git push so the CI watch step is not skipped.

If CI fails, inspect the failed-check summary and failed-step logs from scripts/watch-pr-ci.sh, fix issues that plausibly come from your diff, rerun the relevant local tests, and push again. Repeat up to 3 attempts. If the failure looks flaky or unrelated to your change, say so explicitly with evidence instead of churning.

Confirm the required test check actually passed before merging — do not treat the watch script's exit as proof. scripts/watch-pr-ci.sh can return a clean "no failed runs" message for a head SHA while test is still pending (it reports absence of failures, not presence of success). Before gh pr merge, run gh pr checks <PR> and verify test shows pass (not pending/fail).

Review Before Done

After creating or updating a PR, run a review pass and a simplification pass before considering the work done. Claude Code gets hook reminders for this. Codex users should use the repo PR workflow skill or perform the steps explicitly.

Prefer external review tooling like codex review when it returns promptly, but do not block the PR on it. If the tool stalls or is unavailable, do a manual diff review and say that explicitly.

If a change in this repo is ready for review, open the PR proactively instead of asking whether to make one.

User Handoffs

Before stopping to wait for user input, suggest the next concrete action the user should take or approve. Do not end at "waiting on you" without a specific next step.

If you ran $postmortem, provide the log path, summarize the key learnings, list the concrete action items, and say whether you already implemented them or left them for follow-up.

Merge Conflict Resolution

After resolving merge conflicts, run go vet ./... locally before committing. Git auto-merge can silently produce duplicate declarations (e.g., methods defined in both sides) that compile but fail vet.

Verify Mergeability Before Declaring PRs Ready

Before telling the user a PR is safe to merge, check for merge conflicts with main: git fetch origin main && git merge-tree --write-tree origin/main origin/BRANCH. If there are conflicts, rebase the branch onto origin/main and resolve them before declaring ready.

Merge Policy

GitHub PRs for this repo are squash-only. gh pr merge --merge and gh pr merge --rebase will fail.

After merging, verify local state explicitly: check that the checkout is on main, the worktree is clean, and HEAD matches origin/main. If you need another change after the merge, start a fresh branch and PR instead of committing follow-up fixes on local main.

Claude's post-merge hook now auto-runs scripts/post-merge-main-sync.sh after a successful gh pr merge, which checks out main and runs git pull --ff-only. Other agents can run that script manually when they need the same behavior.

After merging, explicitly run $postmortem. A short manual recap is not a substitute for the postmortem workflow, and do not claim it ran unless you have the logged ~/.local/share/postmortems/... path.

In the final merge closeout, tell the user what the postmortem found and what follow-up actions, if any, came out of it, alongside the logged path.

Include Baseline Numbers In Performance PRs

When creating PRs that add or modify benchmarks, include a Baseline numbers section in the PR description with representative results in a markdown table. Include the hardware (for example, Apple M4, macOS) for context. Development run results are ephemeral -- the PR description is the permanent record.

Adding A New Feature

See CONTRIBUTING.md for the workflow. Additional note for agents:

  1. Check what dependencies already provide. Before designing a custom solution, check if the underlying library (for example, charmbracelet/x/vt) already supports the capability. Read tests and exported methods in go/pkg/mod/.

Fixing A Bug

See CONTRIBUTING.md for the workflow.

Adding A New CLI Command

See CONTRIBUTING.md for the workflow.

Debugging Rendering

Use amux capture --format json to inspect composited output programmatically. To isolate whether a rendering bug is in the compositor (multi-pane compositing) or per-pane terminal emulation:

  1. Capture the full session: amux capture --format json -- identify which panes show artifacts
  2. Zoom the affected pane: amux zoom pane-N -- wait a few seconds, capture again
  3. If the zoomed view is clean but the unzoomed view is corrupted, the bug is in the compositor or diff renderer (cell-grid boundary calculation, status bar overlay, or border compositing)
  4. If the zoomed view is also corrupted, the bug is in the terminal emulator or PTY output

For cursor bugs in TUIs that may draw their own cursor (for example, Claude Code), compare amux capture --format json with amux capture --ansi pane-N. If ANSI shows a reverse-video block in pane content but JSON reports a stale cursor position, treat the app-drawn cursor as the visible source of truth and debug cursor-block detection separately from emulator cursor metadata.

Trigger patterns for compositor bugs: long or truncated lines near pane boundaries, status bar overlays adjacent to wrapped content, and high-frequency output (for example, htop or progress bars).

Debugging Client Performance

When the user reports cross-pane lag (typing in one pane stalls others, scrollback feels slow under load), the bottleneck is almost always the client renderer actor — a single goroutine that drains PTY output, publishes captures, and serves snapshot queries for every pane. Server pprof will not show it; capture the client.

Enable pprof first in ~/.config/amux/config.toml: [debug]\npprof = true, then restart.

Prefer the built-in amux debug commands — they target the latest attached client pprof endpoint directly, so you skip hand-probing for a live socket (the main.client.pprof symlink can be stale):

amux -s <session> debug frames                         # render frame stats: p50/p95/p99 frame time, cells diffed
amux -s <session> debug client-profile --duration 20s  # client CPU profile while the user reproduces the lag
amux -s <session> debug client-goroutines              # live client goroutine dump
amux -s <session> debug client-heap                    # client heap summary

debug frames is the fastest triage: high p95/p99 frame times point straight at the renderer actor. For a CPU profile, run debug client-profile while the user reproduces the lag, then analyze with go tool pprof -top -cum <file> — look for cumulative time under actorLoop and per-line cost in capturePaneRenderSnapshot, publishPaneCapture, or withRendererActorValue call sites.

If the amux debug client-* commands cannot reach the client (none attached, or you need the raw socket), fall back to probing by hand — probe by PID since the symlink may be stale:

for s in /tmp/amux-$UID/<session>.client.*.pprof; do
  curl -s --max-time 2 --unix-socket "$s" http://amux/debug/pprof/ -o /dev/null -w "$s: %{http_code}\n"
done
curl -s --max-time 30 --unix-socket "$LIVE_SOCKET" \
  "http://amux/debug/pprof/profile?seconds=20" -o /tmp/amux-client.pprof

Before forming a code-analysis hypothesis on a capture-path regression, read the full commit-message bodies of the adjacent PRs in that area (LAB-1634, LAB-1663, LAB-1731, LAB-1833 as of 2026-05). Each one documents a deliberate trade-off (what was kept on the actor vs moved off, what was left as a follow-up) that is invisible from the diff alone. Skipping this step has produced wrong-function hypotheses that pprof later corrected.

Hot-Reload

Both client and server watch the binary and re-exec on changes (reload.go). Running make install replaces the installed binary atomically, which then triggers automatic reload of both -- panes and shells are preserved across server reloads via checkpoint and restore.

Socket location: /tmp/amux-$UID/<session-name>

Configuration

See README.md -- Configuration for the config.toml format. Config parsing lives in config/config.go.

Issue Tracking

File bugs and feature requests for this repository in the amux project. GitHub Issues is not actively monitored.

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.