but-axi 0.0.0-stage → 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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Ed Heltzel
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,295 @@
1
- # Temporary Holding Version
1
+ ```text
2
+ ██████╗ ██╗ ██╗████████╗ █████╗ ██╗ ██╗██╗
3
+ ██╔══██╗██║ ██║╚══██╔══╝ ██╔══██╗╚██╗██╔╝██║
4
+ ██████╔╝██║ ██║ ██║ ███████║ ╚███╔╝ ██║
5
+ ██╔══██╗██║ ██║ ██║ ██╔══██║ ██╔██╗ ██║
6
+ ██████╔╝╚██████╔╝ ██║ ██║ ██║██╔╝ ██╗██║
7
+ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚═╝
8
+ ```
2
9
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
10
+ <h1 align="center">but-axi</h1>
11
+
12
+ GitButler CLI for agents, designed with [AXI](https://axi.md) (Agent eXperience Interface).
13
+
14
+ `but-axi` wraps the official GitButler [`but`](https://docs.gitbutler.com/cli-overview) CLI. It runs `but ... --json` underneath and returns token-efficient [TOON](https://github.com/toon-format/toon) output with counts up front, explicit empty states, truncated diffs, structured errors, and `help[]` next-step hints.
15
+ Mutations (commit, branch new, push, undo, redo, oplog snapshot, oplog restore) return their result and a compact workspace summary in one call: workspace path, counts, upstream, and applied branches. That summary is not the full `status` payload (no file list, no commit list).
16
+ It is built for agents that drive version control through a shell.
17
+
18
+ ## AXI principles
19
+
20
+ `but-axi` follows the [10 AXI principles](https://axi.md):
21
+
22
+ | # | Principle | How but-axi does it |
23
+ | - | --------- | ------------------- |
24
+ | 1 | Token-efficient output | TOON tables such as `branches[2]{name,commits,state}:` instead of raw JSON |
25
+ | 2 | Minimal default schemas | 3-4 fields per row. `--fields a,b` adds more |
26
+ | 3 | Content truncation | Patches over 3000 chars and commit bodies over 800 chars are cut, with a size hint and `--full` |
27
+ | 4 | Pre-computed aggregates | A `count:` line first: stacks, branches, commits, uncommitted, conflicts, worktrees |
28
+ | 5 | Definitive empty states | `branches: 0 applied branches`, `hunks: 0 matching hunks`, `pushed 0 branches (already up to date)` |
29
+ | 6 | Structured errors and exit codes | `error:`, `code:`, `help[]` on stdout. Exit 0 ok, 1 runtime error, 2 usage error. Never prompts. Idempotent commit, branch new, push |
30
+ | 7 | Ambient context | `but-axi setup hooks` installs a SessionStart dashboard for Claude Code, Codex, OpenCode, Cursor, and omp |
31
+ | 8 | Content first | Bare `but-axi` shows live workspace state, not help text |
32
+ | 9 | Contextual disclosure | Every output ends with `help[]` command templates. `-C <path>` is carried forward and runtime values stay placeholders like `<branch>` |
33
+ | 10 | Consistent help | `but-axi <command> --help` is short |
34
+
35
+ ## Quick Start
36
+
37
+ Install the but-axi skill in the [Agent Skills](https://agentskills.io) format with [`npx skills`](https://github.com/vercel-labs/skills):
38
+
39
+ ```sh
40
+ npx skills add edheltzel/but-axi --skill but-axi -g
41
+ ```
42
+
43
+ That is the entire setup - no npm install needed.
44
+ The skill is a minimal discovery stub that directs your agent to the always-current `npx -y but-axi` dashboard and help output instead of duplicating command guidance.
45
+ You still need [GitButler](https://gitbutler.com/downloads) with its [`but`](https://docs.gitbutler.com/cli-overview) CLI, Git, and Node.js 22+.
46
+
47
+ The skill is not a user-facing slash command (`user-invocable: false`).
48
+ Just ask for anything that touches GitButler version control - status, diffs, commits, branches, push, undo/redo - and the agent loads the skill on its own when it recognizes the task.
49
+
50
+ `-g` installs the skill for all projects (`~/.agents/skills/` / `~/.claude/skills/`, for example); drop it to install for the current project only.
51
+
52
+ ## Other Ways to Install
53
+
54
+ The skill is the recommended path, but it is not the only one.
55
+
56
+ ### Zero setup
57
+
58
+ but-axi is an AXI, so any capable agent can run the CLI directly with nothing installed at all.
59
+ Just tell your agent:
60
+
61
+ ```
62
+ Execute `npx -y but-axi` to get GitButler tools.
63
+ ```
64
+
65
+ ### Session hook
66
+
67
+ Want ambient GitButler context - the current workspace dashboard - fed into every agent session instead of loading on demand?
68
+ Install the CLI globally and opt into the hook:
69
+
70
+ ```sh
71
+ npm install -g but-axi
72
+ but-axi setup hooks
73
+ ```
74
+
75
+ This installs a `SessionStart` hook for **Claude Code**, **Codex**, **OpenCode**, **Cursor**, and **omp** that surfaces the current GitButler workspace state at the start of each session.
76
+ **Restart your agent session after running this** so the new hook takes effect.
77
+
78
+ ### Clone (development)
79
+
80
+ ```sh
81
+ git clone https://github.com/edheltzel/but-axi.git
82
+ cd but-axi
83
+ npm install
84
+ npm link
85
+ but-axi
86
+ but-axi setup hooks
87
+ ```
88
+
89
+ ### Session hook
90
+
91
+ ```sh
92
+ but-axi setup hooks # install for every agent found (claude, codex, opencode, cursor, omp)
93
+ but-axi setup hooks --agents claude # only some agents
94
+ but-axi setup hooks --dry-run # show what would change
95
+ but-axi setup hooks --status # installed or not, per agent
96
+ but-axi setup hooks --uninstall # remove the managed entries
97
+ ```
98
+
99
+ | Agent | Config file | Hook |
100
+ | ----- | ----------- | ---- |
101
+ | Claude Code | `~/.claude/settings.json` | `hooks.SessionStart` group, plain text output |
102
+ | Codex | `~/.codex/hooks.json` | `hooks.SessionStart` group, plain text output (needs `[features] hooks = true` in `~/.codex/config.toml`) |
103
+ | OpenCode | `~/.config/opencode/plugins/but-axi.js` | Managed plugin that adds the dashboard to the session's system context (OpenCode 1 and 2) |
104
+ | Cursor | `~/.cursor/hooks.json` | `hooks.sessionStart` entry, output `{"additional_context": "..."}` |
105
+ | omp | `~/.omp/agent/extensions/but-axi.ts` | Auto-discovered TypeScript extension (no config edit), see below |
106
+
107
+ Setup merges into the existing file and never replaces it. Each file it edits is first copied to `<file>.bak-but-axi-<timestamp>`.
108
+ Running setup again changes nothing (`already installed (no change)`), and a stale entry is repaired in place.
109
+ Install and uninstall find the entry by the marker `# but-axi hook session-start` in the command.
110
+ The hook command is plain `but-axi` when that name on `PATH` resolves to the running script. Otherwise it uses absolute paths to `node` (a `PATH` symlink such as Homebrew's, which survives upgrades, when one points at the running node) and the script. Rerun setup after moving or reinstalling to repair it.
111
+ The hook reads the session directory from the hook's stdin JSON (`cwd`, or Cursor's `workspace_roots`) and prints nothing outside a GitButler workspace or on any error.
112
+
113
+ omp has no shell hook config, so but-axi writes a small extension instead, rendered from [`omp/but-axi.ts`](omp/but-axi.ts) with the absolute `node` and script paths baked in.
114
+ On `session_start` it runs `but-axi hook session-start --agent omp` in the session directory (5 second timeout, then SIGTERM and SIGKILL; output capped at 64 KB).
115
+ Before the first agent turn it appends the dashboard to the system prompt. Outside a GitButler workspace, on an error, or on a timeout it adds nothing.
116
+ The file carries the marker `but-axi-omp-extension`. Setup only overwrites or removes a `but-axi.ts` that has the marker, and refuses to touch one that does not.
117
+ Before it updates or removes the file, setup copies it to `~/.omp/agent/but-axi.ts.bak-but-axi-<timestamp>`. The copy goes outside `extensions/` so omp does not load it.
118
+
119
+ The OpenCode plugin follows the same rules: marker `but-axi managed opencode plugin`, foreign files are refused, backups go to `~/.config/opencode/` (outside `plugins/`). It runs the hook once per session (5 second timeout) and adds nothing outside a GitButler workspace.
120
+
121
+ Not covered: jcode (its `session_start` setting is a single command that is already in use).
122
+ Cursor note: Cursor has a [known issue](https://forum.cursor.com/t/sessionstart-hook-additional-context-is-never-injected-into-agents-initial-system-context/158452) where `sessionStart` `additional_context` can be dropped.
123
+
124
+ ## Usage
125
+
126
+ ```sh
127
+ but-axi # home view: live workspace state + next steps
128
+ but-axi status # uncommitted files, branches, commits, with IDs
129
+ but-axi status --fields sha,author # extra columns
130
+ but-axi diff # all uncommitted hunks + truncated patch
131
+ but-axi diff <id> --full # one file/commit/branch, complete patch
132
+ but-axi diff --query login # only hunks and patch lines that match
133
+ but-axi show <commit-id|branch> # commit details or branch commit list
134
+ but-axi commit -b <branch> -m "<msg>" # commit everything, return compact summary
135
+ but-axi commit -m "<msg>" <id> <id> # commit selected hunks/files
136
+ but-axi branch # applied + unapplied branches
137
+ but-axi branch list --query <text> # filter that list; --above is only for branch new
138
+ but-axi branch new <name> # idempotent create
139
+ but-axi push [<branch>] [--dry-run] # push, return pushed refs + summary
140
+ but-axi undo | but-axi redo # oplog undo/redo, return compact summary
141
+ but-axi oplog [--limit 20] # operation history
142
+ but-axi oplog snapshot -m "<msg>" # snapshot id + compact summary
143
+ but-axi oplog restore <id> # restore, return compact summary
144
+ but-axi log [-n 20] [--path <file>] # commit history (grit when installed, else git)
145
+ but-axi blame <file> -L 1,40 # line ranges grouped by commit
146
+ but-axi -C ~/code/app status # any command against another directory
147
+ ```
148
+
149
+ Home view in a fresh workspace with two uncommitted files:
150
+
151
+ ```text
152
+ $ but-axi -C /tmp/but-axi-demo/app
153
+ bin: /opt/homebrew/bin/but-axi
154
+ description: Agent-ergonomic GitButler CLI that wraps `but --json` with compact TOON views and combined actions
155
+ workspace: /private/tmp/but-axi-demo/app
156
+ count: 0 stacks; 0 branches; 0 commits; 2 uncommitted; 0 conflicts
157
+ upstream: up to date
158
+ branches: 0 applied branches
159
+ help[4]:
160
+ Run `but-axi -C /tmp/but-axi-demo/app diff` to inspect 2 uncommitted
161
+ Run `but-axi -C /tmp/but-axi-demo/app commit -b <branch> -m "<message>"`
162
+ Run `but-axi -C /tmp/but-axi-demo/app status` for IDs, files and commits
163
+ Run `but-axi -C /tmp/but-axi-demo/app --help` for all commands
164
+ ```
165
+
166
+ A commit returns the new commit and a compact workspace summary in one call:
167
+
168
+ ```text
169
+ $ but-axi -C /tmp/but-axi-demo/app commit -b feature/login -m "feat: add login helper"
170
+ committed:
171
+ id: rqk
172
+ sha: fb48aec
173
+ branch: feature/login
174
+ subject: "feat: add login helper"
175
+ workspace: /private/tmp/but-axi-demo/app
176
+ count: 1 stack; 1 branch; 1 commit (1 on unpushed branches); 0 uncommitted; 0 conflicts
177
+ upstream: up to date
178
+ branches[1]{name,commits,state}:
179
+ feature/login,1,unpushed
180
+ help[3]:
181
+ Run `but-axi -C /tmp/but-axi-demo/app push feature/login`
182
+ Run `but-axi -C /tmp/but-axi-demo/app show rqk`
183
+ Run `but-axi -C /tmp/but-axi-demo/app undo` to revert this commit
184
+ ```
185
+
186
+ Push works the same way:
187
+
188
+ ```text
189
+ $ but-axi -C /tmp/but-axi-demo/app push feature/login
190
+ result: pushed 1 branch
191
+ pushed[1]{branch,remote,from,to}:
192
+ feature/login,origin,(new),fb48aec
193
+ workspace: /private/tmp/but-axi-demo/app
194
+ count: 1 stack; 1 branch; 1 commit (0 on unpushed branches); 0 uncommitted; 0 conflicts
195
+ upstream: up to date
196
+ branches[1]{name,commits,state}:
197
+ feature/login,1,pushed
198
+ help[2]:
199
+ Run `but pr new <branch> -m "<title>"` to open a PR (raw but)
200
+ Run `but-axi -C /tmp/but-axi-demo/app status`
201
+ ```
202
+
203
+ Long patches are cut with a size hint:
204
+
205
+ ```text
206
+ patch_note: "(truncated, 24979 chars total — use --full to see complete diff)"
207
+ ```
208
+
209
+ ### Commands
210
+
211
+ | Command | Description |
212
+ | ------- | ----------- |
213
+ | *(none)* | Home view: `bin`, `description`, workspace, counts, branches, `help[]` |
214
+ | `status` | `uncommitted{id,path,change}`, `branches{id,name,commits,state}`, `commits{id,branch,subject}` |
215
+ | `diff [<id>]` | `hunks{id,path,status,lines}` plus a truncated `patch` |
216
+ | `show <id\|branch>` | Commit: id, sha, author, date, subject, body, files. Branch: commits, base, stackedOn |
217
+ | `commit` | `-m` (repeatable), `-b <branch>`, `-n`/`--no-hooks`, optional change IDs. Never opens an editor. With nothing to commit it prints `skipped` and exits 0. A failing Git hook gives `HOOK_FAILED` |
218
+ | `branch [list\|new\|show]` | List, create (an existing branch is reported as `already exists (no change)`), show |
219
+ | `push [<branch>]` | `--dry-run`, `--with-force`, `--no-verify`. Already pushed gives `pushed 0 branches` and exit 0. A dry run that `but` would refuse (conflicted commits) exits 1 with `PUSH_REFUSED` and the reason per branch |
220
+ | `undo`, `redo` | Oplog undo or redo plus the compact workspace summary |
221
+ | `oplog [list\|snapshot\|restore]` | list: `--limit <n>`. snapshot: `-m <msg>`, returns the snapshot id and compact summary. restore: `<id>` and that summary. A flag from the wrong subcommand is a usage error |
222
+ | `log [<rev>]` | `commits{sha,subject,when}` (+`author,date,refs`), `-n`/`--limit`, `--path` (repeatable). Read-only |
223
+ | `blame <file>` | `blame{lines,sha,author,summary}` (+`date,when`), `-L a,b`, `--rev`. Uncommitted lines show `uncommitted`. Read-only |
224
+ | `setup hooks` | `--status`, `--uninstall`, `--agents`, `--dry-run` |
225
+ | `hook session-start` | Hook entrypoint (`--agent claude\|codex\|opencode\|cursor\|omp`). Any other agent name is a usage error |
226
+ | `version` | Print the version. Extra arguments are a usage error |
227
+
228
+ ### Global flags
229
+
230
+ - `-C <path>` runs against another directory. It is carried forward into `help[]`.
231
+ - `--fields a,b` adds columns from a list's extra fields. `<command> --help` lists them. An unknown field exits 2.
232
+ - `--full` turns off truncation and row caps.
233
+ - `--query <text>` (`-q`) keeps only matching rows and patch lines, and reports `query:` and `matched: N of M`.
234
+ - `--help` (`-h`) prints short help for any command.
235
+ - `--version` (`-v`, `-V`) prints the version. A bare version flag does not load command handlers.
236
+
237
+ ### Exit codes and errors
238
+
239
+ | Exit | Meaning |
240
+ | ---- | ------- |
241
+ | 0 | Success, including no-op results such as `skipped` or `already exists` |
242
+ | 1 | Runtime error from `but` or but-axi, such as not a workspace, unknown ID, or a failed push |
243
+ | 2 | Usage error: unknown command, flag, or `--fields` value; missing or invalid argument (including missing `-m` and a bad `--limit`); extra argument |
244
+
245
+ Errors go to stdout in the same TOON shape. Debug output goes to stderr, and only when `BUT_AXI_DEBUG=1` is set.
246
+
247
+ ```text
248
+ $ but-axi status --verbose
249
+ error: unknown flag --verbose
250
+ code: UNKNOWN_FLAG
251
+ help[1]:
252
+ Run `but-axi status --help` to see supported flags
253
+ ```
254
+
255
+ ### help[] hints
256
+
257
+ Each response ends with `help[N]:` lines, which are ready-to-run command templates.
258
+ Fixed context (`-C <path>`) is carried forward. Values the agent has to choose stay as placeholders (`<branch>`, `<id>`, `"<message>"`). Values known from the result, such as the branch a commit landed on, are filled in.
259
+
260
+ ### Environment
261
+
262
+ - `BUT_AXI_BUT=/path/to/but` sets which `but` binary to use. By default but-axi looks on `PATH`, then in `/opt/homebrew/bin`, `/usr/local/bin`, and `~/.local/bin`.
263
+ - `BUT_AXI_GRIT=/path/to/grit` sets which `grit` to use for `log` and `blame`. By default but-axi looks on `PATH`, then in `~/.local/bin` (where the grit install script puts it). `BUT_AXI_NO_GRIT=1` forces plain `git`.
264
+ - `BUT_AXI_DEBUG=1` writes the `but`, `grit`, and `git` invocations to stderr.
265
+
266
+ ## History with grit
267
+
268
+ [grit](https://github.com/gitbutlerapp/grit) is GitButler's Git engine in Rust. Its `grit` CLI has `--json` output, which `log` and `blame` use when it is installed (`curl -fsSL https://grit-scm.com/install | sh`). Without it they fall back to `git` with the same output shape, and the `engine:` line says which one ran.
269
+ but-axi only runs grit's read-only `log` and `blame`. grit's own `commit`, `switch`, and `reset` move `HEAD` without GitButler, so do not use them inside a GitButler workspace.
270
+
271
+ ## Fallback to raw `but`
272
+
273
+ but-axi wraps the core loop: inspect, commit, branch, push, and undo.
274
+ For everything else, use `but` directly: `amend`, `absorb`, `squash`, `move`, `reword`, `uncommit`, `discard`, `resolve`, `apply`, `unapply`, `pull`, `pr`, `merge`, `pick`, `split`, `worktree`, `init`, `teardown`.
275
+ If you call one of these on but-axi, it exits 2 and tells you to use `but <command> --help`.
276
+ CLI IDs from `but-axi status` and `but-axi diff` are the same IDs `but` uses, so you can pass them straight to `but`.
277
+
278
+ ## Agent skill
279
+
280
+ The `but-axi` Agent Skill ([`skills/but-axi/SKILL.md`](skills/but-axi/SKILL.md), generated by `src/skill.ts` and checked by `npm run skill:check`) tells agents when to use but-axi and sends them to `npx -y but-axi --help` for current usage.
281
+ The hook gives an agent context at the start of every session. The skill gives it the full guide when it needs one.
282
+
283
+ ## Development
284
+
285
+ ```sh
286
+ npm install # dependencies + build (prepare)
287
+ npm run build # tsc -> dist/
288
+ npm test # build + vitest (unit tests + CLI exit-code tests + a real `but` flow in /tmp)
289
+ ```
290
+
291
+ The integration suite creates a throwaway repo and a bare remote under `/tmp`, then commits, pushes, and undoes there. It is skipped when `but` is not installed.
292
+
293
+ ## License
294
+
295
+ MIT
@@ -0,0 +1,16 @@
1
+ #!/usr/bin/env node
2
+ import { isBareVersion, VERSION } from "../src/version.js";
3
+ process.stdout.on("error", (e) => {
4
+ if (e.code === "EPIPE")
5
+ process.exit(0);
6
+ throw e;
7
+ });
8
+ const argv = process.argv.slice(2);
9
+ if (isBareVersion(argv)) {
10
+ process.stdout.write(`${VERSION}\n`, () => process.exit(0));
11
+ }
12
+ else {
13
+ const { main } = await import("../src/cli.js");
14
+ const { stdout, exitCode } = await main(argv);
15
+ process.stdout.write(stdout, () => process.exit(exitCode));
16
+ }
@@ -0,0 +1,118 @@
1
+ import { UsageError } from "./errors.js";
2
+ /** Flags every command accepts. */
3
+ export const GLOBAL_FLAGS = {
4
+ help: { type: "boolean", short: "h" },
5
+ full: { type: "boolean" },
6
+ fields: { type: "string" },
7
+ query: { type: "string", short: "q" },
8
+ cwd: { type: "string", short: "C" },
9
+ };
10
+ /**
11
+ * Strict argv parser: unknown flags and missing values throw UsageError (exit 2).
12
+ * Supports `--flag value`, `--flag=value`, `-f value`, `-fvalue` is NOT supported, `--` ends flags.
13
+ */
14
+ export function parseArgs(argv, spec, cmd) {
15
+ const all = { ...GLOBAL_FLAGS, ...spec };
16
+ const byLong = new Map();
17
+ const byShort = new Map();
18
+ for (const [name, def] of Object.entries(all)) {
19
+ byLong.set(name, name);
20
+ for (const a of def.aliases ?? [])
21
+ byLong.set(a, name);
22
+ if (def.short)
23
+ byShort.set(def.short, name);
24
+ for (const s of def.shorts ?? [])
25
+ byShort.set(s, name);
26
+ }
27
+ const flags = {};
28
+ const positionals = [];
29
+ const helpHint = `Run \`but-axi ${cmd ? cmd + " " : ""}--help\` to see supported flags`;
30
+ for (let i = 0; i < argv.length; i++) {
31
+ const arg = argv[i];
32
+ if (arg === "--") {
33
+ positionals.push(...argv.slice(i + 1));
34
+ break;
35
+ }
36
+ let name;
37
+ let inline;
38
+ let display = arg;
39
+ if (arg.startsWith("--")) {
40
+ const eq = arg.indexOf("=");
41
+ const key = eq >= 0 ? arg.slice(2, eq) : arg.slice(2);
42
+ if (eq >= 0)
43
+ inline = arg.slice(eq + 1);
44
+ display = `--${key}`;
45
+ name = byLong.get(key);
46
+ }
47
+ else if (arg.startsWith("-") && arg.length > 1 && !/^-\d/.test(arg)) {
48
+ const key = arg.slice(1);
49
+ name = key.length === 1 ? byShort.get(key) : undefined;
50
+ }
51
+ else {
52
+ positionals.push(arg);
53
+ continue;
54
+ }
55
+ if (!name)
56
+ throw new UsageError(`unknown flag ${display}`, [helpHint], "UNKNOWN_FLAG");
57
+ const def = all[name];
58
+ if (def.type === "boolean") {
59
+ if (inline !== undefined)
60
+ throw new UsageError(`flag ${display} does not take a value`, [helpHint]);
61
+ flags[name] = true;
62
+ continue;
63
+ }
64
+ let value = inline;
65
+ if (value === undefined) {
66
+ const next = argv[i + 1];
67
+ if (next === undefined)
68
+ throw new UsageError(`flag ${display} requires a value`, [helpHint], "MISSING_VALUE");
69
+ value = next;
70
+ i++;
71
+ }
72
+ if (def.type === "strings") {
73
+ const prev = flags[name] ?? [];
74
+ flags[name] = [...prev, value];
75
+ }
76
+ else {
77
+ flags[name] = value;
78
+ }
79
+ }
80
+ return { flags, positionals };
81
+ }
82
+ export function str(p, name) {
83
+ const v = p.flags[name];
84
+ return typeof v === "string" ? v : undefined;
85
+ }
86
+ export function bool(p, name) {
87
+ return p.flags[name] === true;
88
+ }
89
+ export function strs(p, name) {
90
+ const v = p.flags[name];
91
+ return Array.isArray(v) ? v : [];
92
+ }
93
+ export function fieldsOf(p) {
94
+ const v = str(p, "fields");
95
+ if (!v)
96
+ return [];
97
+ return v
98
+ .split(",")
99
+ .map((s) => s.trim())
100
+ .filter(Boolean);
101
+ }
102
+ /** Reject surplus positionals (fail loud instead of silently ignoring). */
103
+ export function maxPositionals(p, n, cmd) {
104
+ if (p.positionals.length > n) {
105
+ throw new UsageError(`unexpected argument ${p.positionals[n]}`, [`Run \`but-axi ${cmd} --help\``], "UNEXPECTED_ARGUMENT");
106
+ }
107
+ }
108
+ /** Reject flags that belong to a sibling subcommand (fail loud instead of silently ignoring). */
109
+ export function rejectFlags(p, names, cmd, hint) {
110
+ for (const name of names) {
111
+ if (p.flags[name] === undefined)
112
+ continue;
113
+ const help = [`Run \`but-axi ${cmd} --help\``];
114
+ if (hint)
115
+ help.push(hint);
116
+ throw new UsageError(`unexpected flag --${name}`, help, "UNEXPECTED_FLAG");
117
+ }
118
+ }
@@ -0,0 +1,136 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { existsSync } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import { delimiter, join } from "node:path";
5
+ import { AxiError } from "./errors.js";
6
+ export function debug(msg) {
7
+ if (process.env.BUT_AXI_DEBUG)
8
+ process.stderr.write(`[but-axi] ${msg}\n`);
9
+ }
10
+ let cachedBut;
11
+ /** Locate the `but` binary: $BUT_AXI_BUT, then PATH, then common install dirs (hooks may run with a thin PATH). */
12
+ export function resolveBut() {
13
+ if (process.env.BUT_AXI_BUT)
14
+ return process.env.BUT_AXI_BUT;
15
+ if (cachedBut)
16
+ return cachedBut;
17
+ const dirs = [
18
+ ...(process.env.PATH ?? "").split(delimiter).filter(Boolean),
19
+ "/opt/homebrew/bin",
20
+ "/usr/local/bin",
21
+ join(homedir(), ".local", "bin"),
22
+ ];
23
+ for (const d of dirs) {
24
+ const p = join(d, "but");
25
+ if (existsSync(p)) {
26
+ cachedBut = p;
27
+ return p;
28
+ }
29
+ }
30
+ cachedBut = "but";
31
+ return cachedBut;
32
+ }
33
+ function parseJson(text) {
34
+ const t = text.trim();
35
+ if (!t || (t[0] !== "{" && t[0] !== "["))
36
+ return undefined;
37
+ try {
38
+ return JSON.parse(t);
39
+ }
40
+ catch {
41
+ return undefined;
42
+ }
43
+ }
44
+ /** Run `but -C <cwd> <args> --json` non-interactively (stdin closed, pager/editor disabled). */
45
+ export function runBut(args, cwd, json = true) {
46
+ const bin = resolveBut();
47
+ const full = ["-C", cwd, ...args, ...(json ? ["--json"] : [])];
48
+ debug(`exec ${bin} ${full.join(" ")}`);
49
+ const r = spawnSync(bin, full, {
50
+ encoding: "utf8",
51
+ stdio: ["ignore", "pipe", "pipe"],
52
+ timeout: 120_000,
53
+ maxBuffer: 64 * 1024 * 1024,
54
+ env: {
55
+ ...process.env,
56
+ BUT_PAGER: "cat",
57
+ PAGER: "cat",
58
+ GIT_PAGER: "cat",
59
+ NO_COLOR: "1",
60
+ GIT_TERMINAL_PROMPT: "0",
61
+ GIT_EDITOR: "true",
62
+ EDITOR: "true",
63
+ VISUAL: "true",
64
+ },
65
+ });
66
+ if (r.error) {
67
+ const code = r.error.code;
68
+ if (code === "ENOENT") {
69
+ throw new AxiError("GitButler CLI `but` not found", "BUT_NOT_FOUND", [
70
+ "Install GitButler (https://gitbutler.com) and enable its CLI: https://docs.gitbutler.com/cli-overview",
71
+ "Or set BUT_AXI_BUT=/path/to/but",
72
+ ]);
73
+ }
74
+ throw new AxiError(`failed to run but: ${r.error.message}`, "BUT_EXEC_FAILED");
75
+ }
76
+ const stdout = r.stdout ?? "";
77
+ const stderr = r.stderr ?? "";
78
+ debug(`exit ${r.status} stdout=${stdout.length}B stderr=${stderr.length}B`);
79
+ if (stderr && process.env.BUT_AXI_DEBUG)
80
+ process.stderr.write(stderr);
81
+ return { code: r.status ?? 1, stdout, stderr, json: parseJson(stdout) };
82
+ }
83
+ /** Run and return parsed JSON, throwing a structured AxiError on failure. */
84
+ export function butJson(args, cwd) {
85
+ const r = runBut(args, cwd);
86
+ if (r.code !== 0)
87
+ throw butError(r, args);
88
+ if (r.json === undefined) {
89
+ // Some mutations print nothing in JSON mode; treat as an empty object.
90
+ return {};
91
+ }
92
+ return r.json;
93
+ }
94
+ export function cleanMessage(text) {
95
+ const lines = text
96
+ .split("\n")
97
+ .map((l) => l.trim())
98
+ .filter(Boolean)
99
+ .filter((l) => !/^(Usage:|For more information)/.test(l));
100
+ let first = (lines[0] ?? "").replace(/^Error:\s*/i, "").replace(/^error:\s*/, "");
101
+ if (first.endsWith(":") && lines[1])
102
+ first = `${first} ${lines.slice(1, 4).join(" | ")}`;
103
+ return first;
104
+ }
105
+ /** Convert a failed `but` invocation into a structured error. */
106
+ export function butError(r, args) {
107
+ const j = r.json;
108
+ const help = [];
109
+ let code = "BUT_ERROR";
110
+ let message;
111
+ if (j && typeof j === "object" && typeof j.error === "string") {
112
+ code = j.error.toUpperCase();
113
+ message = j.message ?? j.error;
114
+ if (j.hint)
115
+ help.push(`but hint: ${j.hint}`);
116
+ }
117
+ else {
118
+ message = cleanMessage(r.stderr) || cleanMessage(r.stdout) || `but ${args[0]} exited ${r.code}`;
119
+ // but sometimes repeats the message twice on one line
120
+ const half = message.length / 2;
121
+ if (Number.isInteger(half - 0.5) && message.slice(0, half - 0.5) === message.slice(half + 0.5)) {
122
+ message = message.slice(0, half - 0.5);
123
+ }
124
+ }
125
+ if (/No GitButler project|No git repository|setup required/i.test(message) || code === "SETUP_REQUIRED") {
126
+ code = "NOT_A_WORKSPACE";
127
+ help.length = 0;
128
+ help.push("Run `but init` to create a git repo (GitButler 0.23+ needs no `but setup`; raw but, not wrapped)");
129
+ help.push("Or pass `-C <path>` to point at a GitButler workspace");
130
+ }
131
+ else {
132
+ const label = ["branch", "oplog"].includes(args[0] ?? "") && args[1] && !args[1].startsWith("-") ? `${args[0]} ${args[1]}` : args[0];
133
+ help.push(`Run \`but ${label} --help\` for raw but usage`);
134
+ }
135
+ return new AxiError(message, code, help);
136
+ }