smux-cli 0.1.4

Small Rust CLI for tmux session selection and creation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
# smux v1 Specification

## Purpose

`smux` is a small Rust CLI for tmux session selection and creation.

It combines:

- `tmux` as the execution/runtime layer
- `fzf` as the interactive picker
- `zoxide` as the recent-directory source
- declarative TOML templates for session layout

`smux` is intentionally a thin orchestration layer over existing tools. It must stay small, predictable, and easy to debug.

## Product Goals

Version 1 exists to solve four core problems well:

1. Present a unified picker of existing tmux sessions and recent directories.
2. Reuse an existing session when one already matches the selected directory-derived session name.
3. Create a new session from a directory when no session exists.
4. Apply a small, validated TOML template that defines windows, panes, layouts, and startup commands.

## Non-Goals

The following are explicitly out of scope for v1:

- full tmuxinator compatibility
- YAML support
- embedded TUI framework
- plugin system
- arbitrary pane tree modeling
- arbitrary lifecycle hooks
- full tmux option passthrough at every config layer
- git worktree management
- project-local config discovery
- session persistence beyond tmux

## Core User Flows

### Select flow

Primary usage is from inside tmux, but should also work outside when no tmux session exists.

```tmux
bind-key f display-popup -E "smux select"
```

and/or zsh alieas/keybinding.

When the user runs:

```bash
smux select
```

`smux` must:

1. query tmux for existing sessions
2. query `zoxide` for recent directories
3. merge both into one picker list
4. run `fzf`
5. perform one of the following actions:
   - selected session: switch or attach to it
   - selected directory: create or reuse a session for it
   - start tmux if not running yet

### Connect flow

When the user runs:

```bash
smux connect ~/code/myapp
smux connect --template rust ~/code/myapp
```

`smux` must:

1. normalize the input path
2. resolve the session name
3. resolve the template
4. reuse the session if it already exists
5. otherwise create the session and apply the template
6. switch or attach when ready

### Switch flow

When the user runs:

```bash
smux switch myapp
```

`smux` must:

- use `tmux switch-client -t <session>` when inside tmux
- use `tmux attach-session -t <session>` when outside tmux (or create if missing)

## CLI Surface

### `smux select`

Open the unified interactive picker.

Flags:

- `--choose-template`
- `--no-project-detect`
- `--config <path>`

### `smux connect <path>`

Create or reuse a session for a directory.

Flags:

- `--template <name>`
- `--session-name <name>`
- `--config <path>`

### `smux switch <session>`

Switch to or attach to an existing tmux session.

### `smux list-sessions`

Print current tmux session names.

### `smux list-templates`

Print configured template names.

### `smux list-projects`

Print configured project entries with resolved paths.

### `smux doctor`

Validate runtime dependencies and config.

### `smux init`

Create a starter config at `~/.config/smux/config.toml` if it does not already exist.

## Runtime Dependencies

`smux` invokes the following external programs:

- `tmux`
- `fzf`
- `zoxide`

Dependency behavior:

- missing `tmux`: hard error
- missing `fzf`: hard error for `select`
- missing `zoxide`: degrade gracefully to session-only mode, with a warning

This behavior must be documented and tested.

## Development Environment

The project must use Nix for local development.

Required setup:

- a repository `flake.nix`
- `nix-direnv` integration via `.envrc`
- a dev shell that provides the Rust toolchain and required developer utilities

The environment already has Nix and `nix-direnv` available, so the project should assume those tools are present and wire the repository around them.

The dev shell should include at minimum:

- Rust toolchain (`cargo`, `rustc`, `clippy`, `rustfmt`, `rust-analyzer`)
- `pkg-config` if needed by transitive dependencies
- `tmux`
- `fzf`
- `zoxide`

If a pinned Rust toolchain is needed, it should be declared through the flake rather than relying on host-global Rust installation.

## Configuration

Configuration format is TOML.

Default config path:

```text
~/.config/smux/config.toml
```

Top-level config sections:

1. `settings`
2. `templates`

Project definitions live in:

```text
~/.config/smux/projects/*.toml
```

### Example

```toml
[settings]
default_template = "default"
icons = "auto"

[settings.icon_colors]
session = 75
directory = 108
template = 179
project = 81

[templates.default]
startup_window = "main"
windows = [{ name = "main" }]

[templates.rust]
startup_window = "editor"
startup_pane = 0
windows = [
  { name = "editor", pre_command = "source .venv/bin/activate", command = "nvim" },
  { name = "run", synchronize = true, layout = "main-horizontal", panes = [
      { command = "cargo run" },
      { layout = "right 40%", command = "cargo test" },
    ] },
]
```

Example project file:

```toml
path = "~/code/example"
template = "rust"
session_name = "example"
```

## Config Schema

### `[settings]`

```toml
[settings]
default_template = "default"
```

Fields:

- `default_template: string?`
- `icons: "auto" | "always" | "never"` default `auto`
- `icon_colors.session: integer?` default `75`
- `icon_colors.directory: integer?` default `108`
- `icon_colors.template: integer?` default `179`
- `icon_colors.project: integer?` default `81`

Icon behavior:

- session, project, directory, and template pickers may render Nerd Font icons
- icon rendering must remain optional
- `auto` may use terminal capability heuristics, but font support is not reliably detectable
- icon colors may be configured with ANSI-256 palette indexes
- `doctor` should report configured icon mode and effective icon enablement

### `[templates.<name>]`

```toml
[templates.default]
root = "."
startup_window = "editor"
startup_pane = 0
windows = [{ name = "editor" }]
```

Fields:

- `root: string?`
- `startup_window: string?`
- `startup_pane: integer?`
- `windows: array[window]` required
  The recommended and documented format uses TOML 1.1 inline tables for `windows` and nested `panes`.

### `windows = [{ ... }]`

```toml
windows = [
  { name = "editor", cwd = ".", command = "nvim", layout = "main-horizontal" },
]
```

Fields:

- `name: string` required
- `cwd: string?`
- `pre_command: string?`
- `command: string?`
- `layout: string?`
- `synchronize: bool` default `false`
- `panes: array[pane]?`

Rules:

- a window may define `command`
- a window may define `panes`
- a window may define neither for an empty window
- a window must not define both `command` and `panes`
- `pre_command` runs before the pane or window command

### `panes = [{ ... }]`

```toml
panes = [
  { command = "pnpm dev" },
  { layout = "right 30%", command = "pnpm test --watch", cwd = "./server" },
]
```

Fields:

- `layout: string?`
- `command: string?`
- `cwd: string?`

Rules:

- the first pane does not require `layout`
- additional panes should specify `layout`
- pane layout syntax is `<position>` or `<position> <size>`
- supported positions are `right`, `left`, `bottom`, and `top`
- `startup_pane` is a zero-based pane index within the startup window

### Project definition files

Project definitions are individual TOML files under `~/.config/smux/projects/`.
The project name comes from the file name.

```toml
path = "~/code/myapp"
template = "rust"
session_name = "myapp"
```

Fields:

- `path: string` required
- `session_name: string?`
- `template: string?`
- `root: string?`
- `startup_window: string?`
- `startup_pane: integer?`
- `windows: array[window]?`

Rules:

- project matching is by normalized absolute path
- a project may point at a reusable template
- a project may define its own windows directly
- a project may use a template as a base and override it
- if a project defines `windows`, they replace template windows instead of merging window-by-window

## Resolution Rules

### Template resolution

When connecting a directory, template resolution order is:

1. CLI `--template`
2. matching project definition
3. `settings.default_template`
4. built-in fallback template

### Session name resolution

Session name resolution order is:

1. CLI `--session-name`
2. matching `project.session_name`
3. derived name from selected path basename

### Working directory resolution

Working directory resolution order is:

1. window `cwd`
2. template `root`
3. selected directory

Relative `cwd` and `root` values are resolved relative to the selected directory.

## Session Naming Rules

Default session name is derived from the selected directory basename.

Required sanitization:

- trim surrounding whitespace
- replace spaces with `_`
- replace `:` with `_`
- replace `.` with `_`
- replace any remaining tmux-target-unsafe characters with `_`
- reject an empty final session name as an error

If the resolved session name already exists, `smux` must reuse it. v1 does not add numeric suffixes automatically.

## Template Application Rules

Session creation behavior:

- create the session detached first
- fully apply the template
- select the configured startup window, if any
- only then switch or attach

Window creation behavior:

- first window is created by `tmux new-session`
- additional windows are created by `tmux new-window`

Pane creation behavior:

- the first pane is the implicit starting pane
- each additional pane is created in declared order using `split-window`
- pane commands are applied after pane creation
- pane layout strings determine side and optional size for each additional pane
- window layout is applied last

v1 must use a simple deterministic pane strategy. It must not attempt to model arbitrary nested pane trees.

## tmux Integration

All tmux interaction must go through subprocess calls. Do not use a Rust tmux crate in v1.

Allowed commands include:

- `tmux list-sessions -F "#{session_name}"`
- `tmux has-session -t <name>`
- `tmux new-session -d -s <name> -c <dir> -n <window>`
- `tmux new-window -t <session> -n <window> -c <dir>`
- `tmux split-window ...`
- `tmux send-keys ... C-m`
- `tmux select-layout ...`
- `tmux select-window ...`
- `tmux switch-client -t <session>`
- `tmux attach-session -t <session>`

Inside/outside tmux behavior:

- inside tmux: `switch-client`
- outside tmux: `attach-session`

## Interactive Picker

`smux select` must display a unified list of:

- `session`
- `directory`

Each picker entry must contain:

- entry kind
- display label
- raw internal value

Example display:

```text
session  dotfiles
session  api
dir      ~/code/myapp
dir      ~/code/admin
```

Required behavior:

- selecting a session switches or attaches to it
- selecting a directory creates or reuses a session
- `--choose-template` enables interactive template selection for directory entries
- v1 may additionally support an `fzf` expected key such as `ctrl-t`, but that is optional unless implementation cost remains low

Deduplication rule:

- sessions and directories may both appear even when a directory would resolve to an existing session
- directory selection must still reuse the existing session instead of creating a duplicate

## Built-In Fallback Template

`smux` must work without a config file.

The built-in fallback template for v1 is:

- one empty window named `main`

This is the default when no configured template resolves.

## Error Handling

Errors must be:

- clear
- actionable
- contextual

Examples:

- missing `tmux`
- missing `fzf`
- malformed config
- unknown template
- invalid project reference
- invalid template shape
- invalid selected path
- tmux subprocess failure

Example:

```text
error: template "rust" referenced by project "myapp" was not found
hint: define [templates.rust] in ~/.config/smux/config.toml
```

The CLI must return non-zero exit codes on failure.

## Recommended Rust Stack

Recommended dependencies:

- `clap`
- `serde`
- `toml`
- `anyhow` or `eyre`
- `thiserror`
- `directories` or `dirs`
- `which`

Optional:

- `camino`
- `tracing`
- `tracing-subscriber`

## Suggested Architecture

```text
src/
  main.rs
  cli.rs
  config.rs
  model.rs
  tmux.rs
  zoxide.rs
  fzf.rs
  session.rs
  templates.rs
  doctor.rs
  util.rs
```

Module responsibilities:

- `main.rs`: entrypoint and command dispatch
- `cli.rs`: clap definitions
- `config.rs`: config path resolution, loading, validation
- `model.rs`: config and picker types
- `tmux.rs`: subprocess wrappers for tmux operations
- `zoxide.rs`: recent directory discovery
- `fzf.rs`: picker input/output handling
- `session.rs`: core connect/switch orchestration
- `templates.rs`: convert template model into tmux operations
- `doctor.rs`: environment and config diagnostics
- `util.rs`: path expansion, normalization, sanitization helpers

## Recommended Data Model

```rust
struct Config {
    settings: Option<Settings>,
    templates: HashMap<String, Template>,
}

struct Settings {
    default_template: Option<String>,
}

struct Project {
    path: String,
    session_name: Option<String>,
    template: Option<String>,
    root: Option<String>,
    startup_window: Option<String>,
    startup_pane: Option<usize>,
    windows: Option<Vec<Window>>,
}

struct Template {
    root: Option<String>,
    startup_window: Option<String>,
    windows: Vec<Window>,
}

struct Window {
    name: String,
    cwd: Option<String>,
    pre_command: Option<String>,
    command: Option<String>,
    layout: Option<String>,
    synchronize: bool,
    panes: Option<Vec<Pane>>,
}

struct Pane {
    layout: Option<String>,
    command: Option<String>,
    cwd: Option<String>,
}
```

Picker model:

```rust
enum EntryKind {
    Session,
    Project,
    Directory,
}

struct Entry {
    kind: EntryKind,
    label: String,
    value: String,
}
```

## Validation Rules

Validation must enforce:

- every referenced template exists
- `startup_window`, if set, exists in that template
- a template contains at least one window
- a window does not define both `command` and `panes`
- `panes`, if present, is not empty
- project template references are valid
- project paths are parseable
- pane layout strings are valid

Layout validation may either:

- pass through arbitrary tmux layout strings and rely on tmux errors
- or validate against a small whitelist

For v1, pass-through with clear tmux error reporting is acceptable.

## MVP Scope

v1 must include:

- `smux select`
- `smux connect`
- `smux switch`
- `smux list-sessions`
- `smux list-templates`
- `smux list-projects`
- `smux doctor`
- `smux init`
- TOML config loading
- template validation
- template application for windows, panes, layouts, and commands
- project path mapping
- project file loading from `~/.config/smux/projects/`
- deterministic session name derivation
- inside/outside tmux handling
- graceful operation when `zoxide` is unavailable
- zsh completion generation
- proper man pages for the CLI

v1 does not require:

- local per-project config discovery
- `fzf` preview pane
- rename/kill session commands
- tmuxinator import helpers
- config hot reload

## Testing Requirements

### Unit tests

Must cover:

- config parsing
- config validation
- template validation
- session name sanitization
- project path matching
- template-to-tmux command planning

### Integration tests

Use a mockable subprocess boundary.

Must cover:

- selecting an existing session switches or attaches
- selecting a directory with no session creates and then switches or attaches
- selecting a directory with an existing session reuses it
- template with single-command windows
- template with pane-based windows and layout
- unknown template error
- malformed config error

### Manual verification

- run inside tmux selector workflow
- run outside tmux
- run with missing config
- run with missing `zoxide`
- run after `smux init`

## Acceptance Criteria

The implementation is complete when all of the following are true:

1. `smux select` shows tmux sessions, saved projects, and zoxide directories in one `fzf` picker.
2. Selecting a session switches or attaches correctly.
3. Selecting a directory creates or reuses a session correctly.
4. Session names default to the sanitized folder basename.
5. Templates support windows, panes, pane layouts, window layouts, and commands.
6. Saved project definitions apply project-specific session and layout behavior automatically.
7. The tool works without shell scripts or tmuxinator-style wrappers.
8. Errors are readable and actionable.
9. Documentation covers install, config, tmux binding, and examples.
10. Proper man pages and zsh completions are generated and documented.

## Starter Config

```toml
[settings]
default_template = "default"
icons = "auto"

[settings.icon_colors]
session = 75
directory = 108
template = 179
project = 81

[templates.default]
startup_window = "main"
windows = [{ name = "main" }]

[templates.rust]
startup_window = "editor"
windows = [
  { name = "editor", command = "nvim" },
  { name = "run", layout = "main-horizontal", panes = [
      { command = "cargo run" },
      { layout = "right 40%", command = "cargo test" },
    ] },
]
```

Starter project file:

```toml
path = "~/code/example"
template = "rust"
session_name = "example"
```

## Documentation Requirements

`README.md` should include:

- project purpose
- install instructions
- quickstart
- config reference
- tmux binding example
- shell completion usage
- man page usage or installation notes

Quickstart should include:

```tmux
set -g detach-on-destroy off
bind-key t display-popup -w 70% -h 70% -E "smux select"
bind-key T display-popup -w 70% -h 70% -E "smux select --choose-template"
```

```bash
smux init
smux select
smux connect ~/code/myapp
smux connect --template rust ~/code/myapp
```

Additional deliverables:

- starter config generated by `smux init`
- tests for core parsing and session behavior
- clear user-facing error messages
- short design note in `docs/design.md`
- `flake.nix` and `.envrc` for reproducible development
- generated man pages
- generated zsh completion scripts

## Implementation Plan

### Phase 0: Project skeleton

Deliver:

- `flake.nix`
- `.envrc`
- cargo project scaffold
- `clap` command tree
- subprocess abstraction
- shared error type and result wiring

Exit criteria:

- entering the repo activates the Nix dev shell through `nix-direnv`
- binary builds
- help output is stable
- subprocess boundary is testable

### Phase 1: Session discovery and selector MVP

Deliver:

- tmux session listing
- zoxide directory listing
- unified picker entry model
- `fzf` integration
- session selection path

Exit criteria:

- `smux select` can list sessions and directories
- selecting a session switches or attaches correctly
- missing `zoxide` degrades cleanly

### Phase 2: Connect orchestration

Deliver:

- path normalization and expansion
- session name derivation and sanitization
- existing-session reuse
- inside/outside tmux attach behavior

Exit criteria:

- `smux connect <path>` works without templates
- reuse-vs-create behavior is deterministic

### Phase 3: Config loading and resolution

Deliver:

- config path resolution
- TOML parsing
- validation
- project matching
- template resolution

Exit criteria:

- config errors are surfaced clearly
- template/project selection rules match this spec

### Phase 4: Template application

Deliver:

- window creation planner
- pane creation planner
- command dispatch to tmux
- startup window selection

Exit criteria:

- multi-window templates work
- pane-based templates work
- layout application is deterministic

### Phase 5: Operator commands and docs

Deliver:

- `list-templates`
- `list-projects`
- `doctor`
- `init`
- README
- `docs/design.md`
- man pages
- zsh completions

Exit criteria:

- doctor reports dependency and config issues
- init writes the starter config safely
- docs are sufficient for first use

### Phase 6: Test hardening

Deliver:

- unit tests for config, naming, validation, and planning
- integration tests against mocked subprocesses
- manual verification checklist execution

Exit criteria:

- core happy paths and failure paths are covered
- manual tmux workflow is validated once

## Risks and Open Decisions

The draft is mostly stable. The remaining implementation decisions worth making early are:

1. Whether `ctrl-t` template selection is in v1 or deferred behind `--choose-template` only. Recommendation: make `--choose-template` required for v1, add `ctrl-t` only if trivial.
2. Whether tmux commands are executed immediately during template application or planned first and then executed. Recommendation: plan first, execute second, because it improves testability.
3. Whether to validate tmux layout strings proactively. Recommendation: pass through in v1 and surface tmux errors clearly.
4. How much shell quoting logic is owned by `smux` for `send-keys`. Recommendation: keep commands as raw strings sent to tmux, avoid inventing a shell mini-language.

## Final Guidance

`smux` should remain:

- small
- explicit
- deterministic
- easy to debug
- easy to extend

It should not become a framework.