@termwire/cli 0.1.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,30 @@
1
1
  # @termwire/cli
2
2
 
3
+ ## 0.2.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 6f485f3: Add configurable tmux window and pane layouts for new workspaces.
8
+
9
+ Support optional global and project JSONC configuration, strict Zod validation,
10
+ explicit editor pane selection, and deferred pane command startup with complete
11
+ workspace environment variables.
12
+
13
+ ### Patch Changes
14
+
15
+ - Updated dependencies [6f485f3]
16
+ - @termwire/tmux@0.2.0
17
+ - @termwire/nvim@0.2.0
18
+
19
+ ## 0.1.2
20
+
21
+ ### Patch Changes
22
+
23
+ - Add explicit Git branch selection to `termwire up`, preserve slashes in branch names, and document
24
+ the default branch and worktree derivation rules.
25
+ - @termwire/tmux@0.1.2
26
+ - @termwire/nvim@0.1.2
27
+
3
28
  ## 0.1.1
4
29
 
5
30
  ### Patch Changes
package/README.md CHANGED
@@ -8,9 +8,10 @@ termwire --help
8
8
  termwire up dev
9
9
  ```
10
10
 
11
- The project's main entry point — the `termwire` command. Orchestrates the
12
- other packages. Fully **stateless**: no config files, no state files —
13
- workspace identity lives in environment variables set by `termwire up <name>`.
11
+ The project's main entry point — the `termwire` command. It orchestrates the
12
+ other packages. Runtime workspace identity is stateless and lives in the
13
+ environment variables set by `termwire up <name>`; layout configuration is
14
+ optional JSONC, not persistent workspace state.
14
15
 
15
16
  ## Why it exists
16
17
 
@@ -20,28 +21,140 @@ the explicit `termwire_open({ path, line? })` OpenCode plugin tool.
20
21
 
21
22
  ## Commands
22
23
 
23
- | Command | What it does |
24
- | -------------------------------------------- | ------------ |
25
- | `termwire up <name>` | create or attach to `<project>-<name>` in the current directory |
26
- | `termwire up <name> -w` | create or reuse sibling worktree `<project>-<name>` on branch `<name>` |
27
- | `termwire up <name> --worktree <wt-name>` | create or reuse the explicit sibling worktree while retaining session `<project>-<name>` |
28
-
29
- ## How it works
30
-
31
- - `up <name>` creates `editor` (`nvim --listen <socket>`) and free `shell`
32
- windows. Final processes receive `TERMWIRE_SESSION`, `TERMWIRE_SOCKET`,
33
- and `TERMWIRE_EDITOR_PANE`.
34
- - OpenCode is not started automatically. Users may start it in the shell and
35
- reshape the workspace with tmux.
36
- - Existing sessions attach immediately without worktree mutation. Bare
37
- `-w` uses the workspace name; an explicit worktree value selects its branch
38
- and sibling directory while the session name stays `<project>-<name>`.
39
- - There are no config files or persistent state.
24
+ | Command | Workspace | Branch |
25
+ | --- | --- | --- |
26
+ | `termwire up chore/improve` | current directory | unchanged |
27
+ | `termwire up chore/improve -w` | sibling `<project>-chore-improve` | `chore/improve` |
28
+ | `termwire up session -w -b feature/api` | sibling `<project>-session` | `feature/api` |
29
+ | `termwire up session -b feature/api` | current directory | switch to it, or create it from current `HEAD` |
30
+ | `termwire up session -w legacy-name` | sibling `<project>-legacy-name` | `legacy-name` |
31
+ | `termwire up session -w legacy-name -b feature/api` | sibling `<project>-legacy-name` | `feature/api` |
32
+
33
+ `<name>` always determines the tmux identity. With `-w`, an explicit optional worktree value
34
+ selects the directory key; otherwise `<name>` does. `--branch` selects the exact Git branch when
35
+ present; otherwise the worktree directory key is also the branch name. Slashes are preserved in
36
+ Git branch names and replaced only in filesystem-safe worktree directory names. Without `-w`, Git
37
+ is changed only when `--branch` is present. Existing tmux sessions attach without Git mutations or
38
+ rereading/reconciling configuration.
39
+
40
+ ## Layout configuration
41
+
42
+ TermWire discovers optional JSONC files in this order:
43
+
44
+ 1. Global: `$XDG_CONFIG_HOME/termwire/config.jsonc`, or
45
+ `~/.config/termwire/config.jsonc` when `XDG_CONFIG_HOME` is unset.
46
+ 2. Project: `<resolved-workspace-git-root>/.termwire.jsonc`. For `up -w`, this
47
+ is the resolved target worktree's file, not the invoking checkout's file.
48
+
49
+ Both present files are validated. Project `windows` fully replace global
50
+ `windows`; they are never merged. A version-only project file falls through to
51
+ global windows, and a version-only global file falls through to the exact
52
+ default layout:
53
+
54
+ ```json
55
+ {
56
+ "windows": [
57
+ { "name": "editor", "panes": [{ "id": "editor", "role": "editor" }] },
58
+ { "name": "shell", "panes": [{ "id": "shell" }] }
59
+ ]
60
+ }
61
+ ```
62
+
63
+ When neither source provides `windows`, that same editor-then-shell two-window
64
+ default is used.
65
+
66
+ ### Schema
67
+
68
+ Each configuration root is an object with required numeric `"version": 1`,
69
+ optional nonempty-string `"$schema"` for future compatibility, and optional
70
+ `windows`; unknown keys are rejected at every level. `windows`, when provided,
71
+ is a nonempty array of uniquely named window objects. Each window has only
72
+ `name` and a nonempty `panes` array. Pane ids are nonempty and unique within
73
+ their window.
74
+
75
+ A pane may contain only `id`, `role`, `command`, `splitFrom`, `direction`, and
76
+ `sizePercent`:
77
+
78
+ - `role`, when present, is only `"editor"`. Exactly one editor exists across
79
+ the effective layout, and it cannot have a `command`.
80
+ - `command`, when present, is a nonempty argv array of nonempty strings. Shell
81
+ command strings are not supported.
82
+ - The first pane of a window has no split fields. Every later pane must name an
83
+ earlier pane in the same window with `splitFrom` and set `direction` to
84
+ `"horizontal"` or `"vertical"`. An optional `sizePercent` is an integer from
85
+ 1 through 99.
86
+
87
+ This release provides no official JSON Schema file or URL, generation command,
88
+ publishing, autocomplete, or editor integration. `$schema` is accepted for
89
+ future compatibility only; it does not point to a TermWire-provided artifact.
90
+
91
+ Panes are created in declaration order. This valid multi-window example has one
92
+ editor and demonstrates argv commands and ordered splits:
93
+
94
+ ```jsonc
95
+ // ~/.config/termwire/config.jsonc or .termwire.jsonc
96
+ {
97
+ "version": 1,
98
+ "windows": [
99
+ {
100
+ "name": "editor",
101
+ "panes": [
102
+ { "id": "editor", "role": "editor" },
103
+ {
104
+ "id": "watch",
105
+ "splitFrom": "editor",
106
+ "direction": "vertical",
107
+ "sizePercent": 35,
108
+ "command": ["bun", "run", "dev"],
109
+ },
110
+ ],
111
+ },
112
+ {
113
+ "name": "shell",
114
+ "panes": [
115
+ { "id": "shell", "command": ["zsh", "-l"] },
116
+ {
117
+ "id": "tests",
118
+ "splitFrom": "shell",
119
+ "direction": "horizontal",
120
+ "sizePercent": 40,
121
+ "command": ["bun", "test"],
122
+ },
123
+ ],
124
+ },
125
+ ],
126
+ }
127
+ ```
128
+
129
+ JSONC comments and trailing commas are accepted. There is no interpolation,
130
+ custom pane cwd, custom pane environment, shell-string command syntax, or
131
+ configuration/state persistence beyond reading these optional files for a new
132
+ session.
133
+
134
+ ### Errors and session behavior
135
+
136
+ JSONC parse errors identify the source and one-based line and column. Schema
137
+ errors identify the source and JSON path; unreadable existing files retain their
138
+ original error as the cause. After workspace/worktree resolution, configuration
139
+ is loaded and validated before socket or tmux session side effects. Once a new
140
+ session exists, layout or attach failure triggers best-effort session cleanup
141
+ while preserving the original failure.
142
+
143
+ ## Runtime behavior
144
+
145
+ - `up <name>` starts the editor as `nvim --listen <socket>` and uses a pane's
146
+ argv command, or tmux's default shell when an ordinary pane has no command.
147
+ Final processes receive `TERMWIRE_SESSION`, `TERMWIRE_SOCKET`, and
148
+ `TERMWIRE_EDITOR_PANE`.
149
+ - OpenCode is not started automatically. Users may start it in a shell pane and
150
+ reshape the workspace with tmux after creation.
40
151
  - The CLI has no shell-facing `open` command and does not need to be in `PATH`
41
152
  for the plugin: the plugin composes the nvim and tmux adapters directly.
42
153
 
43
154
  ## Dependencies
44
155
 
45
- Commander 15 is the CLI runtime dependency for parsing `up`. `@termwire/tmux`
46
- and `@termwire/nvim` are thin adapters over their binaries; the CLI owns
47
- workspace policy and orchestration.
156
+ Commander 15 parses `up`; `jsonc-parser` handles JSONC parsing and diagnostics;
157
+ Zod 4 provides strict structural config validation. All three are direct runtime
158
+ dependencies.
159
+ `@termwire/tmux` and `@termwire/nvim` are thin adapters over their binaries;
160
+ the CLI owns workspace policy and orchestration.
@@ -0,0 +1,2 @@
1
+ import type { GitExec } from "./worktree";
2
+ export declare function prepareBranch(exec: GitExec, cwd: string, name: string): Promise<void>;
package/dist/branch.js ADDED
@@ -0,0 +1,13 @@
1
+ export async function prepareBranch(exec, cwd, name) {
2
+ const existing = await exec(["git", "show-ref", "--verify", "--quiet", `refs/heads/${name}`], {
3
+ cwd,
4
+ });
5
+ if (existing.exitCode !== 0 && existing.exitCode !== 1) {
6
+ throw new Error(`git show-ref failed: ${existing.stderr}`);
7
+ }
8
+ const command = existing.exitCode === 0 ? ["git", "switch", name] : ["git", "switch", "-c", name];
9
+ const switched = await exec(command, { cwd });
10
+ if (switched.exitCode !== 0) {
11
+ throw new Error(`git switch failed: ${switched.stderr}`);
12
+ }
13
+ }
@@ -0,0 +1,11 @@
1
+ import type { LoadedConfig } from "./config-types";
2
+ export interface ConfigLoaderDependencies {
3
+ env: Record<string, string | undefined>;
4
+ homedir: () => string;
5
+ exists: (path: string) => Promise<boolean>;
6
+ readFile: (path: string, encoding: "utf8") => Promise<string>;
7
+ }
8
+ export declare function createConfigLoader(dependencies: ConfigLoaderDependencies): {
9
+ loadGlobal(): Promise<LoadedConfig | undefined>;
10
+ loadProject(gitRoot: string): Promise<LoadedConfig | undefined>;
11
+ };
@@ -0,0 +1,62 @@
1
+ import { isAbsolute, join } from "node:path";
2
+ import { parse } from "jsonc-parser";
3
+ export function createConfigLoader(dependencies) {
4
+ return {
5
+ async loadGlobal() {
6
+ return loadFile(dependencies, globalConfigPath(dependencies));
7
+ },
8
+ async loadProject(gitRoot) {
9
+ return loadFile(dependencies, join(gitRoot, ".termwire.jsonc"));
10
+ },
11
+ };
12
+ }
13
+ function globalConfigPath(dependencies) {
14
+ const xdgConfigHome = dependencies.env.XDG_CONFIG_HOME;
15
+ const configHome = xdgConfigHome && isAbsolute(xdgConfigHome)
16
+ ? xdgConfigHome
17
+ : join(dependencies.homedir(), ".config");
18
+ return join(configHome, "termwire", "config.jsonc");
19
+ }
20
+ function lineColumn(text, offset) {
21
+ let line = 1;
22
+ let column = 1;
23
+ for (let index = 0; index < offset; index += 1) {
24
+ if (text[index] === "\r") {
25
+ if (text[index + 1] === "\n" && index + 1 < offset) {
26
+ index += 1;
27
+ }
28
+ line += 1;
29
+ column = 1;
30
+ }
31
+ else if (text[index] === "\n") {
32
+ line += 1;
33
+ column = 1;
34
+ }
35
+ else {
36
+ column += 1;
37
+ }
38
+ }
39
+ return { line, column };
40
+ }
41
+ async function loadFile(dependencies, path) {
42
+ if (!(await dependencies.exists(path))) {
43
+ return undefined;
44
+ }
45
+ let text;
46
+ try {
47
+ text = await dependencies.readFile(path, "utf8");
48
+ }
49
+ catch (error) {
50
+ if (error.code === "ENOENT") {
51
+ return undefined;
52
+ }
53
+ throw new Error(`Failed to read config ${path}`, { cause: error });
54
+ }
55
+ const errors = [];
56
+ const value = parse(text, errors, { allowTrailingComma: true, disallowComments: false });
57
+ if (errors.length > 0) {
58
+ const { line, column } = lineColumn(text, errors[0].offset);
59
+ throw new Error(`${path}:${line}:${column}: ${errors[0].error}`);
60
+ }
61
+ return { source: path, value };
62
+ }
@@ -0,0 +1,50 @@
1
+ import { z } from "zod";
2
+ export declare const paneSchema: z.ZodObject<{
3
+ id: z.ZodString;
4
+ role: z.ZodOptional<z.ZodLiteral<"editor">>;
5
+ command: z.ZodOptional<z.ZodArray<z.ZodString>>;
6
+ splitFrom: z.ZodOptional<z.ZodString>;
7
+ direction: z.ZodOptional<z.ZodEnum<{
8
+ horizontal: "horizontal";
9
+ vertical: "vertical";
10
+ }>>;
11
+ sizePercent: z.ZodOptional<z.ZodNumber>;
12
+ }, z.core.$strict>;
13
+ export declare const windowSchema: z.ZodObject<{
14
+ name: z.ZodString;
15
+ panes: z.ZodArray<z.ZodObject<{
16
+ id: z.ZodString;
17
+ role: z.ZodOptional<z.ZodLiteral<"editor">>;
18
+ command: z.ZodOptional<z.ZodArray<z.ZodString>>;
19
+ splitFrom: z.ZodOptional<z.ZodString>;
20
+ direction: z.ZodOptional<z.ZodEnum<{
21
+ horizontal: "horizontal";
22
+ vertical: "vertical";
23
+ }>>;
24
+ sizePercent: z.ZodOptional<z.ZodNumber>;
25
+ }, z.core.$strict>>;
26
+ }, z.core.$strict>;
27
+ export declare const configV1Schema: z.ZodObject<{
28
+ version: z.ZodLiteral<1>;
29
+ $schema: z.ZodOptional<z.ZodString>;
30
+ windows: z.ZodOptional<z.ZodArray<z.ZodObject<{
31
+ name: z.ZodString;
32
+ panes: z.ZodArray<z.ZodObject<{
33
+ id: z.ZodString;
34
+ role: z.ZodOptional<z.ZodLiteral<"editor">>;
35
+ command: z.ZodOptional<z.ZodArray<z.ZodString>>;
36
+ splitFrom: z.ZodOptional<z.ZodString>;
37
+ direction: z.ZodOptional<z.ZodEnum<{
38
+ horizontal: "horizontal";
39
+ vertical: "vertical";
40
+ }>>;
41
+ sizePercent: z.ZodOptional<z.ZodNumber>;
42
+ }, z.core.$strict>>;
43
+ }, z.core.$strict>>>;
44
+ }, z.core.$strict>;
45
+ export type PaneConfig = z.infer<typeof paneSchema>;
46
+ export type WindowConfig = z.infer<typeof windowSchema>;
47
+ export type ConfigV1 = z.infer<typeof configV1Schema>;
48
+ export type LayoutConfig = {
49
+ windows: NonNullable<ConfigV1["windows"]>;
50
+ };
@@ -0,0 +1,18 @@
1
+ import { z } from "zod";
2
+ export const paneSchema = z.strictObject({
3
+ id: z.string().min(1),
4
+ role: z.literal("editor").optional(),
5
+ command: z.array(z.string().min(1)).min(1).optional(),
6
+ splitFrom: z.string().optional(),
7
+ direction: z.enum(["horizontal", "vertical"]).optional(),
8
+ sizePercent: z.number().int().min(1).max(99).optional(),
9
+ });
10
+ export const windowSchema = z.strictObject({
11
+ name: z.string().min(1),
12
+ panes: z.array(paneSchema).min(1),
13
+ });
14
+ export const configV1Schema = z.strictObject({
15
+ version: z.literal(1),
16
+ $schema: z.string().min(1).optional(),
17
+ windows: z.array(windowSchema).min(1).optional(),
18
+ });
@@ -0,0 +1,4 @@
1
+ export interface LoadedConfig {
2
+ source: string;
3
+ value: unknown;
4
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,3 @@
1
+ import { type LayoutConfig } from "./config-schema";
2
+ import type { LoadedConfig } from "./config-types";
3
+ export declare function resolveLayout(globalConfig?: LoadedConfig, projectConfig?: LoadedConfig): LayoutConfig;
@@ -0,0 +1,117 @@
1
+ import { configV1Schema, } from "./config-schema";
2
+ const defaultLayout = {
3
+ windows: [
4
+ { name: "editor", panes: [{ id: "editor", role: "editor" }] },
5
+ { name: "shell", panes: [{ id: "shell" }] },
6
+ ],
7
+ };
8
+ export function resolveLayout(globalConfig, projectConfig) {
9
+ const global = globalConfig ? validateConfig(globalConfig) : undefined;
10
+ const project = projectConfig ? validateConfig(projectConfig) : undefined;
11
+ const globalWindows = global?.windows;
12
+ const projectWindows = project?.windows;
13
+ return copyLayout(projectWindows ?? globalWindows ?? defaultLayout.windows);
14
+ }
15
+ function expectUnique(source, path, values, value) {
16
+ if (values.has(value)) {
17
+ throw new Error(`${source}: ${path}: must be unique`);
18
+ }
19
+ values.add(value);
20
+ }
21
+ function copyLayout(windows) {
22
+ return {
23
+ windows: windows.map((window) => ({
24
+ ...window,
25
+ panes: window.panes.map((pane) => pane.command === undefined ? { ...pane } : { ...pane, command: [...pane.command] }),
26
+ })),
27
+ };
28
+ }
29
+ function validateWindow(source, path, value, names, editors) {
30
+ expectUnique(source, `${path}.name`, names, value.name);
31
+ validatePanes(source, path, value.panes, editors);
32
+ }
33
+ function validatePanes(source, windowPath, value, editors) {
34
+ const ids = new Set();
35
+ const earlierIds = new Set();
36
+ for (let paneIndex = 0; paneIndex < value.length; paneIndex += 1) {
37
+ const panePath = `${windowPath}.panes[${paneIndex}]`;
38
+ const id = validatePane(source, panePath, value[paneIndex], paneIndex, ids, earlierIds, editors);
39
+ earlierIds.add(id);
40
+ }
41
+ }
42
+ function validatePane(source, path, value, index, ids, earlierIds, editors) {
43
+ expectUnique(source, `${path}.id`, ids, value.id);
44
+ validateEditor(source, path, value, editors);
45
+ validateSplitRules(source, path, value, index, earlierIds);
46
+ return value.id;
47
+ }
48
+ function validateEditor(source, path, pane, editors) {
49
+ if (pane.role === "editor") {
50
+ if (pane.command !== undefined) {
51
+ throw new Error(`${source}: ${path}.command: is not allowed for the editor`);
52
+ }
53
+ editors.count += 1;
54
+ if (editors.count > 1) {
55
+ throw new Error(`${source}: ${path}.role: exactly one editor is required`);
56
+ }
57
+ }
58
+ }
59
+ function validateSplitRules(source, path, pane, index, earlierIds) {
60
+ if (index === 0) {
61
+ for (const key of ["splitFrom", "direction", "sizePercent"]) {
62
+ if (pane[key] !== undefined) {
63
+ throw new Error(`${source}: ${path}.${key}: is not allowed on the first pane`);
64
+ }
65
+ }
66
+ }
67
+ else {
68
+ if (pane.splitFrom === undefined || !earlierIds.has(pane.splitFrom)) {
69
+ throw new Error(`${source}: ${path}.splitFrom: must reference an earlier pane`);
70
+ }
71
+ if (pane.direction === undefined) {
72
+ throw new Error(`${source}: ${path}.direction: must be horizontal or vertical`);
73
+ }
74
+ }
75
+ }
76
+ function expectSingleEditor(source, editors) {
77
+ if (editors.count !== 1) {
78
+ throw new Error(`${source}: $.windows: exactly one editor is required`);
79
+ }
80
+ }
81
+ function validateWindows(source, value) {
82
+ const names = new Set();
83
+ const editors = { count: 0 };
84
+ for (let index = 0; index < value.length; index += 1) {
85
+ validateWindow(source, `$.windows[${index}]`, value[index], names, editors);
86
+ }
87
+ expectSingleEditor(source, editors);
88
+ }
89
+ function validateConfig(config) {
90
+ const result = configV1Schema.safeParse(config.value);
91
+ if (!result.success) {
92
+ throw configError(config.source, result.error.issues[0]);
93
+ }
94
+ if (result.data.windows !== undefined) {
95
+ validateWindows(config.source, result.data.windows);
96
+ }
97
+ return result.data;
98
+ }
99
+ function configError(source, issue) {
100
+ const path = issue.code === "unrecognized_keys" ? [...issue.path, issue.keys[0]] : issue.path;
101
+ return new Error(`${source}: ${jsonPath(path)}: ${issue.message}`);
102
+ }
103
+ function jsonPath(path) {
104
+ let result = "$";
105
+ for (const segment of path) {
106
+ if (typeof segment === "number") {
107
+ result += `[${segment}]`;
108
+ }
109
+ else if (/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(String(segment))) {
110
+ result += `.${String(segment)}`;
111
+ }
112
+ else {
113
+ result += `[${JSON.stringify(String(segment))}]`;
114
+ }
115
+ }
116
+ return result;
117
+ }
package/dist/index.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ export { prepareBranch } from "./branch";
1
2
  export type { ProgramDependencies, RuntimeDependencies } from "./program";
2
3
  export { createProgram, createRuntimeUp, executeGit, removeStaleSocket, run } from "./program";
3
4
  export type { UpDependencies, UpRequest } from "./up";
package/dist/index.js CHANGED
@@ -1,3 +1,4 @@
1
+ export { prepareBranch } from "./branch";
1
2
  export { createProgram, createRuntimeUp, executeGit, removeStaleSocket, run } from "./program";
2
3
  export { up } from "./up";
3
4
  export { findGitRoot, parseWorktreeList, prepareWorktree } from "./worktree";
@@ -0,0 +1,19 @@
1
+ import type { createTmux } from "@termwire/tmux";
2
+ import type { LayoutConfig } from "./config-schema";
3
+ export declare function createLayout(options: {
4
+ tmux: ReturnType<typeof createTmux>;
5
+ session: string;
6
+ workspace: string;
7
+ socket: string;
8
+ layout: LayoutConfig;
9
+ initial: {
10
+ windowId: string;
11
+ paneId: string;
12
+ };
13
+ }): Promise<{
14
+ editor: {
15
+ windowId: string;
16
+ paneId: string;
17
+ };
18
+ environment: Record<string, string>;
19
+ }>;
package/dist/layout.js ADDED
@@ -0,0 +1,106 @@
1
+ export async function createLayout(options) {
2
+ const paneMappings = await createPaneMappings(options);
3
+ const editor = findEditor(options.layout, paneMappings);
4
+ const environment = createWorkspaceEnvironment(options.session, options.socket, editor.paneId);
5
+ await setSessionEnvironment(options.tmux, options.session, environment);
6
+ await respawnPanes({
7
+ tmux: options.tmux,
8
+ workspace: options.workspace,
9
+ socket: options.socket,
10
+ layout: options.layout,
11
+ paneMappings,
12
+ environment,
13
+ });
14
+ await focusEditor(options.tmux, editor);
15
+ return { editor, environment };
16
+ }
17
+ function setPaneMapping(mappings, windowName, paneId, mappedPane) {
18
+ let windowMappings = mappings.get(windowName);
19
+ if (!windowMappings) {
20
+ windowMappings = new Map();
21
+ mappings.set(windowName, windowMappings);
22
+ }
23
+ windowMappings.set(paneId, mappedPane);
24
+ }
25
+ function getPaneMapping(mappings, windowName, paneId) {
26
+ return mappings.get(windowName)?.get(paneId);
27
+ }
28
+ function createWorkspaceEnvironment(session, socket, editorPane) {
29
+ return {
30
+ TERMWIRE_SESSION: session,
31
+ TERMWIRE_SOCKET: socket,
32
+ TERMWIRE_EDITOR_PANE: editorPane,
33
+ };
34
+ }
35
+ function commandForPane(pane, socket) {
36
+ return pane.role === "editor" ? ["nvim", "--listen", socket] : pane.command;
37
+ }
38
+ async function createPaneMappings(options) {
39
+ const paneMappings = new Map();
40
+ const firstWindow = options.layout.windows[0];
41
+ const firstPane = firstWindow.panes[0];
42
+ setPaneMapping(paneMappings, firstWindow.name, firstPane.id, options.initial);
43
+ for (const [windowIndex, window] of options.layout.windows.entries()) {
44
+ let windowId = windowIndex === 0 ? options.initial.windowId : undefined;
45
+ for (const [paneIndex, pane] of window.panes.entries()) {
46
+ if (windowIndex === 0 && paneIndex === 0)
47
+ continue;
48
+ if (paneIndex === 0) {
49
+ const created = await options.tmux.newWindow({
50
+ target: options.session,
51
+ name: window.name,
52
+ cwd: options.workspace,
53
+ });
54
+ windowId = created.windowId;
55
+ setPaneMapping(paneMappings, window.name, pane.id, created);
56
+ continue;
57
+ }
58
+ const target = getPaneMapping(paneMappings, window.name, pane.splitFrom ?? "");
59
+ const paneId = await options.tmux.splitPane({
60
+ target: target?.paneId ?? "",
61
+ direction: pane.direction ?? "horizontal",
62
+ sizePercent: pane.sizePercent,
63
+ cwd: options.workspace,
64
+ });
65
+ setPaneMapping(paneMappings, window.name, pane.id, { windowId: windowId ?? "", paneId });
66
+ }
67
+ }
68
+ return paneMappings;
69
+ }
70
+ function findEditor(layout, paneMappings) {
71
+ let editor;
72
+ for (const window of layout.windows) {
73
+ for (const pane of window.panes) {
74
+ const mappedPane = getPaneMapping(paneMappings, window.name, pane.id);
75
+ if (pane.role === "editor")
76
+ editor = mappedPane;
77
+ }
78
+ }
79
+ if (!editor)
80
+ throw new Error("layout does not contain an editor pane");
81
+ return editor;
82
+ }
83
+ async function setSessionEnvironment(tmux, session, environment) {
84
+ for (const [key, value] of Object.entries(environment)) {
85
+ await tmux.setEnvironment(session, key, value);
86
+ }
87
+ }
88
+ async function respawnPanes(options) {
89
+ for (const window of options.layout.windows) {
90
+ for (const pane of window.panes) {
91
+ const mappedPane = getPaneMapping(options.paneMappings, window.name, pane.id);
92
+ if (!mappedPane)
93
+ throw new Error(`layout pane is not mapped: ${pane.id}`);
94
+ await options.tmux.respawnPane({
95
+ target: mappedPane.paneId,
96
+ cwd: options.workspace,
97
+ environment: options.environment,
98
+ command: commandForPane(pane, options.socket),
99
+ });
100
+ }
101
+ }
102
+ }
103
+ async function focusEditor(tmux, editor) {
104
+ await tmux.selectWindow(editor.windowId);
105
+ await tmux.selectPane(editor.paneId);
106
+ }
package/dist/program.d.ts CHANGED
@@ -10,6 +10,9 @@ export interface ProgramDependencies {
10
10
  export interface RuntimeDependencies {
11
11
  createTmux: () => ReturnType<typeof createTmux>;
12
12
  cwd: () => string;
13
+ env: Record<string, string | undefined>;
14
+ homedir: () => string;
15
+ readFile: (path: string, encoding: "utf8") => Promise<string>;
13
16
  gitExec: GitExec;
14
17
  mkdir: (path: string, options: {
15
18
  recursive: true;
package/dist/program.js CHANGED
@@ -1,6 +1,11 @@
1
- import { mkdir as mkdirDirectory, stat, unlink as unlinkFile } from "node:fs/promises";
1
+ import { mkdir as mkdirDirectory, readFile as readFileFromDisk, stat, unlink as unlinkFile, } from "node:fs/promises";
2
+ import { homedir as getHomeDirectory } from "node:os";
2
3
  import { createTmux } from "@termwire/tmux";
3
4
  import { Command, CommanderError } from "commander";
5
+ import { prepareBranch } from "./branch";
6
+ import { createConfigLoader } from "./config-loader";
7
+ import { resolveLayout } from "./config-validation";
8
+ import { createLayout } from "./layout";
4
9
  import { up } from "./up";
5
10
  import { findGitRoot, prepareWorktree } from "./worktree";
6
11
  export const executeGit = async (argv, options) => {
@@ -32,6 +37,9 @@ export async function removeStaleSocket(path, unlink) {
32
37
  export function createRuntimeUp(dependencies = {}) {
33
38
  const tmux = (dependencies.createTmux ?? (() => createTmux()))();
34
39
  const cwd = dependencies.cwd ?? (() => process.cwd());
40
+ const env = dependencies.env ?? process.env;
41
+ const homedir = dependencies.homedir ?? getHomeDirectory;
42
+ const readFile = dependencies.readFile ?? ((path, encoding) => readFileFromDisk(path, encoding));
35
43
  const gitExec = dependencies.gitExec ?? executeGit;
36
44
  const mkdir = dependencies.mkdir ?? mkdirDirectory;
37
45
  const pathExists = dependencies.pathExists ??
@@ -47,15 +55,23 @@ export function createRuntimeUp(dependencies = {}) {
47
55
  }
48
56
  });
49
57
  const unlink = dependencies.unlink ?? unlinkFile;
58
+ const loader = createConfigLoader({ env, homedir, exists: pathExists, readFile });
59
+ const loadGlobalConfig = loader.loadGlobal;
60
+ const loadProjectConfig = loader.loadProject;
50
61
  return (request) => up(request, {
51
62
  cwd,
52
63
  findGitRoot: (directory) => findGitRoot(gitExec, directory),
64
+ prepareBranch: ({ cwd: directory, name }) => prepareBranch(gitExec, directory, name),
53
65
  prepareWorktree: (options) => prepareWorktree({ ...options, exec: gitExec, pathExists }),
54
66
  mkdir: async (path) => {
55
67
  await mkdir(path, { recursive: true });
56
68
  },
57
69
  removeFile: (path) => removeStaleSocket(path, unlink),
58
70
  tmux,
71
+ loadGlobalConfig,
72
+ loadProjectConfig,
73
+ resolveLayout,
74
+ createLayout,
59
75
  });
60
76
  }
61
77
  export function createProgram(dependencies) {
@@ -68,13 +84,26 @@ export function createProgram(dependencies) {
68
84
  program
69
85
  .command("up <name>")
70
86
  .option("-w, --worktree [wt-name]", "create or reuse a Git worktree")
87
+ .option("-b, --branch <name>", "select the exact Git branch")
88
+ .addHelpText("after", `
89
+ Branch and worktree selection:
90
+ Without -w, --branch switches the current checkout, creating the branch when absent.
91
+ With -w, the optional worktree name selects the directory; otherwise <name> is used.
92
+ --branch selects the branch; otherwise the worktree directory key is also the branch.
93
+ Slashes are preserved in Git branch names and sanitized only in worktree directory names.
94
+ Existing sessions attach without Git changes.
95
+ `)
71
96
  .action(async (name, options) => {
72
97
  if (options.worktree === "") {
73
98
  throw new Error("worktree name must not be empty");
74
99
  }
100
+ if (options.branch === "") {
101
+ throw new Error("branch name must not be empty");
102
+ }
75
103
  await dependencies.up({
76
104
  name,
77
105
  ...(options.worktree === undefined ? {} : { worktree: options.worktree }),
106
+ ...(options.branch === undefined ? {} : { branch: options.branch }),
78
107
  });
79
108
  });
80
109
  return program;
package/dist/up.d.ts CHANGED
@@ -1,18 +1,31 @@
1
1
  import type { createTmux } from "@termwire/tmux";
2
+ import type { LayoutConfig } from "./config-schema";
3
+ import type { LoadedConfig } from "./config-types";
4
+ import type { createLayout } from "./layout";
2
5
  export interface UpRequest {
3
6
  name: string;
4
7
  worktree?: true | string;
8
+ branch?: string;
5
9
  }
6
10
  export interface UpDependencies {
7
11
  cwd: () => string;
8
12
  findGitRoot: (cwd: string) => Promise<string | undefined>;
13
+ prepareBranch: (options: {
14
+ cwd: string;
15
+ name: string;
16
+ }) => Promise<void>;
9
17
  prepareWorktree: (options: {
10
18
  gitRoot: string;
11
19
  project: string;
12
20
  name: string;
21
+ branch: string;
13
22
  }) => Promise<string>;
14
23
  mkdir: (path: string) => Promise<void>;
15
24
  removeFile: (path: string) => Promise<void>;
16
25
  tmux: ReturnType<typeof createTmux>;
26
+ loadGlobalConfig: () => Promise<LoadedConfig | undefined>;
27
+ loadProjectConfig: (gitRoot: string) => Promise<LoadedConfig | undefined>;
28
+ resolveLayout: (globalConfig: LoadedConfig | undefined, projectConfig: LoadedConfig | undefined) => LayoutConfig;
29
+ createLayout: typeof createLayout;
17
30
  }
18
31
  export declare function up(request: UpRequest, dependencies: UpDependencies): Promise<void>;
package/dist/up.js CHANGED
@@ -3,6 +3,9 @@ export async function up(request, dependencies) {
3
3
  if (request.worktree === "") {
4
4
  throw new Error("worktree name must not be empty");
5
5
  }
6
+ if (request.branch === "") {
7
+ throw new Error("branch name must not be empty");
8
+ }
6
9
  const cwd = dependencies.cwd();
7
10
  const gitRoot = await dependencies.findGitRoot(cwd);
8
11
  const identity = createIdentity({ cwd, gitRoot, name: request.name });
@@ -11,67 +14,56 @@ export async function up(request, dependencies) {
11
14
  return;
12
15
  }
13
16
  const workspace = await resolveWorkspace(request, dependencies, identity, gitRoot, cwd);
17
+ const layout = await loadEffectiveLayout(workspace, dependencies);
14
18
  await dependencies.mkdir("/tmp/termwire");
15
19
  await dependencies.removeFile(identity.socket);
16
- const editor = await dependencies.tmux.newSession({
20
+ const initial = await dependencies.tmux.newSession({
17
21
  session: identity.session,
18
- name: "editor",
22
+ name: layout.windows[0].name,
19
23
  cwd: workspace,
20
24
  });
21
- const environment = createWorkspaceEnvironment(identity, editor.paneId);
22
25
  try {
23
- await configureWorkspaceSession({
26
+ await dependencies.createLayout({
24
27
  tmux: dependencies.tmux,
25
- identity,
28
+ session: identity.session,
26
29
  workspace,
27
- editor,
28
- environment,
30
+ socket: identity.socket,
31
+ layout,
32
+ initial,
29
33
  });
34
+ await dependencies.tmux.attach(identity.session);
30
35
  }
31
36
  catch (error) {
32
37
  await bestEffortKillSession(dependencies.tmux, identity.session);
33
38
  throw error;
34
39
  }
35
- await dependencies.tmux.attach(identity.session);
40
+ }
41
+ async function loadEffectiveLayout(workspace, dependencies) {
42
+ const globalConfig = await dependencies.loadGlobalConfig();
43
+ const gitRoot = await dependencies.findGitRoot(workspace);
44
+ const projectConfig = gitRoot === undefined ? undefined : await dependencies.loadProjectConfig(gitRoot);
45
+ return dependencies.resolveLayout(globalConfig, projectConfig);
36
46
  }
37
47
  async function resolveWorkspace(request, dependencies, identity, gitRoot, cwd) {
38
48
  if (request.worktree === undefined) {
49
+ if (request.branch !== undefined) {
50
+ if (!gitRoot) {
51
+ throw new Error("branch requires a Git repository");
52
+ }
53
+ await dependencies.prepareBranch({ cwd, name: request.branch });
54
+ }
39
55
  return cwd;
40
56
  }
41
57
  if (!gitRoot) {
42
58
  throw new Error("worktree requires a Git repository");
43
59
  }
60
+ const name = request.worktree === true ? request.name : request.worktree;
44
61
  return dependencies.prepareWorktree({
45
62
  gitRoot,
46
63
  project: identity.project,
47
- name: request.worktree === true ? request.name : request.worktree,
48
- });
49
- }
50
- function createWorkspaceEnvironment(identity, editorPane) {
51
- return {
52
- TERMWIRE_SESSION: identity.session,
53
- TERMWIRE_SOCKET: identity.socket,
54
- TERMWIRE_EDITOR_PANE: editorPane,
55
- };
56
- }
57
- async function configureWorkspaceSession(options) {
58
- for (const [key, value] of Object.entries(options.environment)) {
59
- await options.tmux.setEnvironment(options.identity.session, key, value);
60
- }
61
- await options.tmux.respawnPane({
62
- target: options.editor.paneId,
63
- cwd: options.workspace,
64
- command: ["nvim", "--listen", options.identity.socket],
65
- environment: options.environment,
66
- });
67
- await options.tmux.newWindow({
68
- target: options.identity.session,
69
- name: "shell",
70
- cwd: options.workspace,
71
- environment: options.environment,
64
+ name,
65
+ branch: request.branch ?? name,
72
66
  });
73
- await options.tmux.selectWindow(options.editor.windowId);
74
- await options.tmux.selectPane(options.editor.paneId);
75
67
  }
76
68
  async function bestEffortKillSession(tmux, session) {
77
69
  try {
@@ -22,4 +22,5 @@ export declare function prepareWorktree(options: {
22
22
  gitRoot: string;
23
23
  project: string;
24
24
  name: string;
25
+ branch?: string;
25
26
  }): Promise<string>;
package/dist/worktree.js CHANGED
@@ -38,14 +38,15 @@ export function parseWorktreeList(output) {
38
38
  });
39
39
  }
40
40
  export async function prepareWorktree(options) {
41
- const name = sanitizeComponent(options.name, "name");
42
- const target = join(dirname(options.gitRoot), `${options.project}-${name}`);
41
+ const pathName = sanitizeComponent(options.name, "name");
42
+ const branch = options.branch ?? options.name;
43
+ const target = join(dirname(options.gitRoot), `${options.project}-${pathName}`);
43
44
  const entries = await listWorktrees(options.exec, options.gitRoot);
44
45
  const registered = findWorktreeAt(entries, target);
45
46
  if (registered) {
46
47
  return reuseRegisteredWorktree({
47
48
  entry: registered,
48
- name,
49
+ branch,
49
50
  target,
50
51
  gitRoot: options.gitRoot,
51
52
  exec: options.exec,
@@ -56,11 +57,11 @@ export async function prepareWorktree(options) {
56
57
  if (await options.pathExists(target)) {
57
58
  throw new Error(`Worktree conflict: target path is occupied: ${target}`);
58
59
  }
59
- const branchAt = findBranchCheckout(entries, name);
60
+ const branchAt = findBranchCheckout(entries, branch);
60
61
  if (branchAt) {
61
- throw new Error(`Worktree conflict: branch ${name} is already checked out at ${branchAt.path}`);
62
+ throw new Error(`Worktree conflict: branch ${branch} is already checked out at ${branchAt.path}`);
62
63
  }
63
- await addWorktree(options.exec, options.gitRoot, target, name);
64
+ await addWorktree(options.exec, options.gitRoot, target, branch);
64
65
  return target;
65
66
  }
66
67
  async function listWorktrees(exec, gitRoot) {
@@ -75,7 +76,7 @@ async function listWorktrees(exec, gitRoot) {
75
76
  function findWorktreeAt(entries, target) {
76
77
  return entries.find((entry) => resolve(entry.path) === resolve(target));
77
78
  }
78
- function validateRegistrationMetadata(entry, name) {
79
+ function validateRegistrationMetadata(entry, branch) {
79
80
  if (entry.prunable) {
80
81
  throw new Error(`Worktree conflict: registered target is prunable${typeof entry.prunable === "string" ? `: ${entry.prunable}` : ""}`);
81
82
  }
@@ -85,12 +86,12 @@ function validateRegistrationMetadata(entry, name) {
85
86
  if (entry.detached) {
86
87
  throw new Error("Worktree conflict: registered target is detached");
87
88
  }
88
- if (entry.branch !== name) {
89
- throw new Error(`Worktree conflict: expected ${name}, found ${entry.branch ?? "detached HEAD"}`);
89
+ if (entry.branch !== branch) {
90
+ throw new Error(`Worktree conflict: expected ${branch}, found ${entry.branch ?? "detached HEAD"}`);
90
91
  }
91
92
  }
92
93
  async function reuseRegisteredWorktree(options) {
93
- validateRegistrationMetadata(options.entry, options.name);
94
+ validateRegistrationMetadata(options.entry, options.branch);
94
95
  if (!(await options.pathExists(options.target))) {
95
96
  throw new Error(`Worktree conflict: registered target path is missing: ${options.target}`);
96
97
  }
@@ -99,23 +100,23 @@ async function reuseRegisteredWorktree(options) {
99
100
  realpath: options.realpath,
100
101
  target: options.target,
101
102
  gitRoot: options.gitRoot,
102
- name: options.name,
103
+ branch: options.branch,
103
104
  });
104
105
  return options.target;
105
106
  }
106
- function findBranchCheckout(entries, name) {
107
- return entries.find((entry) => entry.branch === name);
107
+ function findBranchCheckout(entries, branch) {
108
+ return entries.find((entry) => entry.branch === branch);
108
109
  }
109
- async function addWorktree(exec, gitRoot, target, name) {
110
- const branch = await exec(["git", "show-ref", "--verify", "--quiet", `refs/heads/${name}`], {
110
+ async function addWorktree(exec, gitRoot, target, branch) {
111
+ const existing = await exec(["git", "show-ref", "--verify", "--quiet", `refs/heads/${branch}`], {
111
112
  cwd: gitRoot,
112
113
  });
113
- if (branch.exitCode !== 0 && branch.exitCode !== 1) {
114
- throw new Error(`git show-ref failed: ${branch.stderr}`);
114
+ if (existing.exitCode !== 0 && existing.exitCode !== 1) {
115
+ throw new Error(`git show-ref failed: ${existing.stderr}`);
115
116
  }
116
- const command = branch.exitCode === 0
117
- ? ["git", "worktree", "add", target, name]
118
- : ["git", "worktree", "add", "-b", name, target];
117
+ const command = existing.exitCode === 0
118
+ ? ["git", "worktree", "add", target, branch]
119
+ : ["git", "worktree", "add", "-b", branch, target];
119
120
  const added = await exec(command, { cwd: gitRoot });
120
121
  if (added.exitCode !== 0) {
121
122
  throw new Error(`git worktree add failed: ${added.stderr}`);
@@ -156,8 +157,8 @@ async function validateRegisteredWorktree(options) {
156
157
  if (liveBranch.exitCode !== 0) {
157
158
  throw new Error(`Worktree conflict: registered target has no symbolic HEAD: ${liveBranch.stderr}`);
158
159
  }
159
- if (liveBranch.stdout.trim() !== `refs/heads/${options.name}`) {
160
- throw new Error(`Worktree conflict: registered target live branch is ${liveBranch.stdout.trim()}, expected refs/heads/${options.name}`);
160
+ if (liveBranch.stdout.trim() !== `refs/heads/${options.branch}`) {
161
+ throw new Error(`Worktree conflict: registered target live branch is ${liveBranch.stdout.trim()}, expected refs/heads/${options.branch}`);
161
162
  }
162
163
  }
163
164
  function resolveGitPath(path, cwd) {
package/package.json CHANGED
@@ -1,11 +1,11 @@
1
1
  {
2
2
  "name": "@termwire/cli",
3
- "version": "0.1.1",
3
+ "version": "0.2.0",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
7
7
  "bin": {
8
- "termwire": "./dist/bin/termwire.js"
8
+ "termwire": "dist/bin/termwire.js"
9
9
  },
10
10
  "exports": {
11
11
  ".": {
@@ -37,8 +37,10 @@
37
37
  "url": "https://github.com/max-konin/termwire/issues"
38
38
  },
39
39
  "dependencies": {
40
- "@termwire/nvim": "^0.1.1",
41
- "@termwire/tmux": "^0.1.1",
42
- "commander": "^15.0.0"
40
+ "@termwire/nvim": "^0.2.0",
41
+ "@termwire/tmux": "^0.2.0",
42
+ "commander": "^15.0.0",
43
+ "jsonc-parser": "^3.3.1",
44
+ "zod": "^4.0.0"
43
45
  }
44
46
  }