@alecrust/workbox 0.4.1

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 ADDED
@@ -0,0 +1 @@
1
+ ## [0.4.1] - 2026-05-19
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Alec Rust
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 ADDED
@@ -0,0 +1,105 @@
1
+ # workbox (wkb) [![CI](https://github.com/AlecRust/workbox/actions/workflows/ci.yml/badge.svg)](https://github.com/AlecRust/workbox/actions/workflows/ci.yml)
2
+
3
+ Minimal Bun-first CLI for Git worktrees. Creates a worktree per sandbox and removes it cleanly.
4
+
5
+ ## Install
6
+
7
+ Requires Bun `1.3.13` or newer.
8
+
9
+ ```sh
10
+ bun add -g @alecrust/workbox
11
+ ```
12
+
13
+ Verify the install:
14
+
15
+ ```sh
16
+ wkb --version
17
+ ```
18
+
19
+ ## Use
20
+
21
+ ```sh
22
+ wkb new <name> [--from <ref>] # create and provision sandbox worktree
23
+ wkb rm <name> [--force] [--unmanaged] [--delete-branch] # remove worktree
24
+ wkb list # list workbox worktrees
25
+ wkb prune # prune stale git worktree metadata
26
+ wkb status [name] # show repo/worktree info and cleanliness
27
+ wkb setup # run configured bootstrap steps (in current worktree)
28
+ wkb dev <name> # run configured dev command in a sandbox
29
+ wkb exec <name> -- <cmd...> # run a command in a sandbox
30
+ ```
31
+
32
+ `workbox` and `wkb` are equivalent.
33
+
34
+ ## Config
35
+
36
+ Looks for global config in:
37
+
38
+ 1. `$XDG_CONFIG_HOME/workbox/config.toml`
39
+ 2. `~/.workbox/config.toml` when `$XDG_CONFIG_HOME` is not set
40
+
41
+ Then looks for project config in:
42
+
43
+ 1. `.workbox/config.toml`
44
+ 2. `workbox.toml`
45
+
46
+ Config is required from at least one global or project location. Global config provides defaults;
47
+ project config overrides only the settings it defines. Paths are resolved relative to the repo root.
48
+ `worktrees.directory` must resolve within the repo root.
49
+
50
+ Example:
51
+
52
+ ```toml
53
+ [worktrees]
54
+ directory = ".workbox/worktrees"
55
+ branch_prefix = "wkb/"
56
+ base_ref = "main"
57
+
58
+ [bootstrap]
59
+ enabled = true
60
+ steps = [
61
+ { name = "install", run = "bun install" },
62
+ { name = "build", run = "bun run build" }
63
+ ]
64
+
65
+ [provision]
66
+ enabled = true
67
+
68
+ [[provision.copy]]
69
+ from = ".env"
70
+ to = ".env"
71
+
72
+ [[provision.copy]]
73
+ from = ".env.local"
74
+ to = ".env.local"
75
+ required = false
76
+
77
+ [[provision.steps]]
78
+ name = "generate"
79
+ run = "bun run generate"
80
+
81
+ [dev]
82
+ command = "bun run dev"
83
+ # Optional (explicit opt-in): open an editor when running `wkb dev`.
84
+ # open = "code ."
85
+ ```
86
+
87
+ Provision runs automatically after `wkb new` creates a worktree. Copy sources resolve from the
88
+ current worktree where `wkb new` is run, copy destinations and steps run inside the new worktree,
89
+ and missing copied files are skipped unless `required = true`.
90
+
91
+ Bootstrap is separate: `wkb setup` runs bootstrap in the current worktree, and `wkb dev <name>`
92
+ runs bootstrap in the named sandbox before the dev command.
93
+
94
+ ## Development
95
+
96
+ ```sh
97
+ bun install
98
+ bun test
99
+ bun run check
100
+ bun run format
101
+ ```
102
+
103
+ ## Commit conventions
104
+
105
+ Conventional Commits are enforced. See `cog.toml`.
package/package.json ADDED
@@ -0,0 +1,59 @@
1
+ {
2
+ "name": "@alecrust/workbox",
3
+ "version": "0.4.1",
4
+ "description": "Bun-first CLI for managing Git worktree sandboxes.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "packageManager": "bun@1.3.13",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/AlecRust/workbox.git"
11
+ },
12
+ "homepage": "https://github.com/AlecRust/workbox#readme",
13
+ "bugs": {
14
+ "url": "https://github.com/AlecRust/workbox/issues"
15
+ },
16
+ "publishConfig": {
17
+ "access": "public"
18
+ },
19
+ "files": [
20
+ "src/**/*.ts",
21
+ "!src/**/*.test.ts",
22
+ "README.md",
23
+ "LICENSE",
24
+ "CHANGELOG.md"
25
+ ],
26
+ "bin": {
27
+ "workbox": "./src/cli.ts",
28
+ "wkb": "./src/cli.ts"
29
+ },
30
+ "engines": {
31
+ "bun": "1.3.13"
32
+ },
33
+ "scripts": {
34
+ "prepare": "bun scripts/prepare.ts",
35
+ "test": "bun test",
36
+ "lint": "biome lint .",
37
+ "check:types": "tsc --noEmit",
38
+ "check:unused": "knip",
39
+ "check": "bun run lint && bun run check:types && bun run check:unused",
40
+ "format": "biome check --write ."
41
+ },
42
+ "dependencies": {
43
+ "zod": "^4.4.1"
44
+ },
45
+ "devDependencies": {
46
+ "@biomejs/biome": "^2.4.13",
47
+ "@tsconfig/bun": "^1.0.10",
48
+ "@types/bun": "^1.3.13",
49
+ "knip": "^6.9.0",
50
+ "lefthook": "^2.1.6",
51
+ "typescript": "^6.0.3"
52
+ },
53
+ "keywords": [
54
+ "git",
55
+ "worktree",
56
+ "cli",
57
+ "bun"
58
+ ]
59
+ }
@@ -0,0 +1,89 @@
1
+ import { resolve } from "node:path";
2
+
3
+ import { checkPathWithinRoot } from "../core/path";
4
+ import { runShellCommand } from "../core/process";
5
+ import { CliError } from "../ui/errors";
6
+ import type { BootstrapStep } from "./steps";
7
+
8
+ type BootstrapStepResult = {
9
+ name: string;
10
+ command: string;
11
+ cwd: string;
12
+ exitCode: number;
13
+ stdout?: string;
14
+ stderr?: string;
15
+ };
16
+
17
+ type BootstrapResult = {
18
+ status: "ok" | "failed";
19
+ message: string;
20
+ steps: BootstrapStepResult[];
21
+ exitCode: number;
22
+ };
23
+
24
+ type OutputMode = "inherit" | "capture";
25
+
26
+ const resolveStepCwd = async (repoRoot: string, stepCwd?: string): Promise<string> => {
27
+ if (!stepCwd) {
28
+ return repoRoot;
29
+ }
30
+ const resolved = resolve(repoRoot, stepCwd);
31
+ const within = await checkPathWithinRoot({
32
+ rootDir: repoRoot,
33
+ candidatePath: resolved,
34
+ label: "bootstrap step cwd",
35
+ });
36
+ if (!within.ok) {
37
+ throw new CliError(within.reason, { exitCode: 2 });
38
+ }
39
+ return resolved;
40
+ };
41
+
42
+ export const runBootstrap = async (
43
+ steps: BootstrapStep[],
44
+ options: { repoRoot: string; mode: OutputMode }
45
+ ): Promise<BootstrapResult> => {
46
+ if (steps.length === 0) {
47
+ return {
48
+ status: "ok",
49
+ message: "no bootstrap steps configured.",
50
+ steps: [],
51
+ exitCode: 0,
52
+ };
53
+ }
54
+
55
+ const results: BootstrapStepResult[] = [];
56
+ for (const step of steps) {
57
+ const cwd = await resolveStepCwd(options.repoRoot, step.cwd);
58
+ const { stdout, stderr, exitCode } = await runShellCommand({
59
+ command: step.run,
60
+ cwd,
61
+ mode: options.mode,
62
+ env: step.env,
63
+ });
64
+
65
+ results.push({
66
+ name: step.name,
67
+ command: step.run,
68
+ cwd,
69
+ exitCode,
70
+ ...(options.mode === "capture" ? { stdout: stdout.trim(), stderr: stderr.trim() } : {}),
71
+ });
72
+
73
+ if (exitCode !== 0) {
74
+ return {
75
+ status: "failed",
76
+ message: `bootstrap step "${step.name}" failed (exit ${exitCode}).`,
77
+ steps: results,
78
+ exitCode,
79
+ };
80
+ }
81
+ }
82
+
83
+ return {
84
+ status: "ok",
85
+ message: "bootstrap completed.",
86
+ steps: results,
87
+ exitCode: 0,
88
+ };
89
+ };
@@ -0,0 +1,6 @@
1
+ export type BootstrapStep = {
2
+ name: string;
3
+ run: string;
4
+ cwd?: string;
5
+ env?: Record<string, string>;
6
+ };
@@ -0,0 +1,144 @@
1
+ import { parseArgs } from "node:util";
2
+
3
+ type CliFlags = {
4
+ help: boolean;
5
+ json: boolean;
6
+ nonInteractive: boolean;
7
+ version: boolean;
8
+ };
9
+
10
+ type ParsedArgs = {
11
+ command: string | null;
12
+ commandArgs: string[];
13
+ flags: CliFlags;
14
+ errors: string[];
15
+ };
16
+
17
+ const GLOBAL_OPTIONS = {
18
+ help: { type: "boolean", short: "h" },
19
+ json: { type: "boolean" },
20
+ "non-interactive": { type: "boolean" },
21
+ version: { type: "boolean" },
22
+ } as const;
23
+
24
+ type ParsedToken =
25
+ | {
26
+ kind: "option";
27
+ index: number;
28
+ name: string;
29
+ rawName?: string;
30
+ value?: string;
31
+ inlineValue?: boolean;
32
+ }
33
+ | {
34
+ kind: "positional";
35
+ index: number;
36
+ value: string;
37
+ }
38
+ | {
39
+ kind: "option-terminator";
40
+ index: number;
41
+ };
42
+
43
+ const flagFromOption = (name: string): keyof CliFlags | null => {
44
+ switch (name) {
45
+ case "help":
46
+ return "help";
47
+ case "json":
48
+ return "json";
49
+ case "non-interactive":
50
+ return "nonInteractive";
51
+ case "version":
52
+ return "version";
53
+ default:
54
+ return null;
55
+ }
56
+ };
57
+
58
+ const pushOptionArgs = (token: ParsedToken, argv: string[], commandArgs: string[]): void => {
59
+ if (token.kind !== "option") {
60
+ return;
61
+ }
62
+
63
+ const optionArg = argv[token.index];
64
+ if (optionArg !== undefined) {
65
+ commandArgs.push(optionArg);
66
+ }
67
+
68
+ if ("value" in token && token.value !== undefined && token.inlineValue === false) {
69
+ const valueArg = argv[token.index + 1];
70
+ if (valueArg !== undefined) {
71
+ commandArgs.push(valueArg);
72
+ }
73
+ }
74
+ };
75
+
76
+ export const parseCliArgs = (argv: string[]): ParsedArgs => {
77
+ const flags: CliFlags = {
78
+ help: false,
79
+ json: false,
80
+ nonInteractive: false,
81
+ version: false,
82
+ };
83
+ const errors: string[] = [];
84
+ const commandArgs: string[] = [];
85
+ let command: string | null = null;
86
+ let passthrough = false;
87
+
88
+ const parsed = parseArgs({
89
+ args: argv,
90
+ options: GLOBAL_OPTIONS,
91
+ strict: false,
92
+ allowPositionals: true,
93
+ tokens: true,
94
+ });
95
+ const tokens = parsed.tokens as ParsedToken[] | undefined;
96
+
97
+ for (const token of tokens ?? []) {
98
+ if (token.kind === "option-terminator") {
99
+ passthrough = true;
100
+ commandArgs.push("--");
101
+ continue;
102
+ }
103
+
104
+ if (token.kind === "option" && !passthrough) {
105
+ const flag = flagFromOption(token.name);
106
+ if (flag) {
107
+ flags[flag] = true;
108
+ continue;
109
+ }
110
+ if (!command) {
111
+ const rawName = "rawName" in token ? token.rawName : argv[token.index];
112
+ errors.push(`Unknown flag "${rawName ?? token.name}".`);
113
+ continue;
114
+ }
115
+ pushOptionArgs(token, argv, commandArgs);
116
+ continue;
117
+ }
118
+
119
+ if (!command && token.kind === "positional") {
120
+ command = token.value;
121
+ continue;
122
+ }
123
+
124
+ if (!command && passthrough && token.kind === "option") {
125
+ command = argv[token.index] ?? token.name;
126
+ continue;
127
+ }
128
+
129
+ if (token.kind === "positional") {
130
+ const value = argv[token.index] ?? token.value;
131
+ commandArgs.push(value);
132
+ continue;
133
+ }
134
+
135
+ pushOptionArgs(token, argv, commandArgs);
136
+ }
137
+
138
+ return {
139
+ command,
140
+ commandArgs,
141
+ flags,
142
+ errors,
143
+ };
144
+ };
@@ -0,0 +1,42 @@
1
+ import { commands } from "../commands";
2
+ import type { CommandDefinition } from "../commands/types";
3
+
4
+ const TOOL_DESCRIPTION = "workbox manages fast Git worktree sandboxes with optional bootstraps.";
5
+
6
+ export const renderGlobalHelp = (toolName: string, alias: string): string => {
7
+ const commandLines = commands.map((command) => ` ${command.name.padEnd(8)} ${command.summary}`);
8
+
9
+ return [
10
+ `${toolName} - ${TOOL_DESCRIPTION}`,
11
+ `Alias: ${alias}`,
12
+ "",
13
+ "Usage:",
14
+ ` ${toolName} <command> [options]`,
15
+ "",
16
+ "Commands:",
17
+ ...commandLines,
18
+ "",
19
+ "Global options:",
20
+ " --help Show help for a command",
21
+ " --json Output machine-readable JSON",
22
+ " --non-interactive Disable prompts and fail fast",
23
+ " --version Show the current version",
24
+ ].join("\n");
25
+ };
26
+
27
+ export const renderCommandHelp = (toolName: string, command: CommandDefinition): string =>
28
+ [
29
+ `${toolName} ${command.name} - ${command.summary}`,
30
+ "",
31
+ "Usage:",
32
+ ` ${command.usage}`,
33
+ "",
34
+ "Description:",
35
+ ` ${command.description}`,
36
+ "",
37
+ "Global options:",
38
+ " --help Show help for this command",
39
+ " --json Output machine-readable JSON",
40
+ " --non-interactive Disable prompts and fail fast",
41
+ " --version Show the current version",
42
+ ].join("\n");
package/src/cli.ts ADDED
@@ -0,0 +1,145 @@
1
+ #!/usr/bin/env bun
2
+ import { parseCliArgs } from "./cli/args";
3
+ import { renderCommandHelp, renderGlobalHelp } from "./cli/help";
4
+ import { getCommand } from "./commands";
5
+ import { loadConfig } from "./core/config";
6
+ import { getRepoInfo } from "./core/repo";
7
+ import { CliError, UsageError } from "./ui/errors";
8
+ import { formatOutput } from "./ui/log";
9
+
10
+ const TOOL_NAME = "workbox";
11
+ const TOOL_ALIAS = "wkb";
12
+
13
+ type OutputTarget = NodeJS.WritableStream;
14
+
15
+ const loadPackageVersion = async (): Promise<string> => {
16
+ const packageJson = (await Bun.file(new URL("../package.json", import.meta.url)).json()) as {
17
+ version?: unknown;
18
+ };
19
+ return typeof packageJson.version === "string" ? packageJson.version : "unknown";
20
+ };
21
+
22
+ const writeOutput = (output: string, stream: OutputTarget): void => {
23
+ if (output.trim().length === 0) {
24
+ return;
25
+ }
26
+ stream.write(`${output}\n`);
27
+ };
28
+
29
+ export const runCli = async (argv: string[], cwd = process.cwd()): Promise<number> => {
30
+ const parsed = parseCliArgs(argv);
31
+ const outputMode = parsed.flags.json ? "json" : "text";
32
+
33
+ if (parsed.errors.length > 0) {
34
+ throw new UsageError(`${parsed.errors.join(" ")} Run '${TOOL_NAME} --help' for usage.`);
35
+ }
36
+
37
+ if (parsed.flags.version) {
38
+ const version = await loadPackageVersion();
39
+ writeOutput(
40
+ formatOutput(
41
+ {
42
+ ok: true,
43
+ message: `${TOOL_NAME} ${version}`,
44
+ data: { version },
45
+ },
46
+ outputMode
47
+ ),
48
+ process.stdout
49
+ );
50
+ return 0;
51
+ }
52
+
53
+ if (parsed.flags.nonInteractive) {
54
+ process.env.CI ??= "1";
55
+ process.env.GIT_TERMINAL_PROMPT ??= "0";
56
+ process.env.GCM_INTERACTIVE ??= "Never";
57
+ }
58
+
59
+ const command = parsed.command ? getCommand(parsed.command) : undefined;
60
+
61
+ if (!parsed.command || parsed.flags.help) {
62
+ if (parsed.command && !command) {
63
+ throw new UsageError(`Unknown command "${parsed.command}".`);
64
+ }
65
+
66
+ const helpText = command
67
+ ? renderCommandHelp(TOOL_NAME, command)
68
+ : renderGlobalHelp(TOOL_NAME, TOOL_ALIAS);
69
+
70
+ writeOutput(
71
+ formatOutput(
72
+ {
73
+ ok: true,
74
+ command: command?.name,
75
+ help: helpText,
76
+ },
77
+ outputMode
78
+ ),
79
+ process.stdout
80
+ );
81
+ return 0;
82
+ }
83
+
84
+ if (!command) {
85
+ throw new UsageError(`Unknown command "${parsed.command}".`);
86
+ }
87
+
88
+ const { repoRoot, worktreeRoot } = await getRepoInfo(cwd);
89
+ const { config, path } = await loadConfig(repoRoot);
90
+ const result = await command.run(
91
+ {
92
+ cwd,
93
+ repoRoot,
94
+ worktreeRoot,
95
+ config,
96
+ configPath: path,
97
+ flags: parsed.flags,
98
+ },
99
+ parsed.commandArgs
100
+ );
101
+
102
+ const exitCode = result.exitCode ?? 0;
103
+ writeOutput(
104
+ formatOutput(
105
+ {
106
+ ok: exitCode === 0,
107
+ command: command.name,
108
+ message: result.message,
109
+ data: result.data,
110
+ },
111
+ outputMode
112
+ ),
113
+ process.stdout
114
+ );
115
+
116
+ return exitCode;
117
+ };
118
+
119
+ const main = async () => {
120
+ const outputMode = parseCliArgs(Bun.argv.slice(2)).flags.json ? "json" : "text";
121
+ try {
122
+ const exitCode = await runCli(Bun.argv.slice(2));
123
+ process.exitCode = exitCode;
124
+ } catch (error) {
125
+ const exitCode = error instanceof CliError ? error.exitCode : 1;
126
+ const message = error instanceof Error ? error.message : String(error);
127
+
128
+ writeOutput(
129
+ formatOutput(
130
+ {
131
+ ok: false,
132
+ message: `Error: ${message}`,
133
+ ...(outputMode === "json" ? { errors: [message] } : {}),
134
+ },
135
+ outputMode
136
+ ),
137
+ process.stderr
138
+ );
139
+ process.exitCode = exitCode;
140
+ }
141
+ };
142
+
143
+ if (import.meta.main) {
144
+ await main();
145
+ }
@@ -0,0 +1,90 @@
1
+ import { runBootstrap } from "../bootstrap/runner";
2
+ import { getWorkboxWorktree } from "../core/git";
3
+ import { runShellCommand } from "../core/process";
4
+ import { UsageError } from "../ui/errors";
5
+ import { parseArgsOrUsage } from "./parse";
6
+ import type { CommandDefinition } from "./types";
7
+
8
+ export const devCommand: CommandDefinition = {
9
+ name: "dev",
10
+ summary: "Start a dev session in a sandbox",
11
+ description: "Start a development session inside a workbox sandbox.",
12
+ usage: "workbox dev <name>",
13
+ run: async (context, args) => {
14
+ const { positionals } = parseArgsOrUsage({
15
+ args,
16
+ allowPositionals: true,
17
+ strict: true,
18
+ });
19
+ const [name, ...rest] = positionals;
20
+ if (!name) {
21
+ const message = context.flags.nonInteractive
22
+ ? "Missing worktree name in non-interactive mode."
23
+ : "Missing worktree name.";
24
+ throw new UsageError(message);
25
+ }
26
+ if (rest.length > 0) {
27
+ throw new UsageError(`Unexpected arguments: ${rest.join(" ")}`);
28
+ }
29
+
30
+ if (!context.config.dev) {
31
+ throw new UsageError('Dev is not configured. Add a [dev] section with a "command".');
32
+ }
33
+
34
+ const worktree = await getWorkboxWorktree({
35
+ repoRoot: context.repoRoot,
36
+ worktreesDir: context.config.worktrees.directory,
37
+ branchPrefix: context.config.worktrees.branch_prefix,
38
+ name,
39
+ });
40
+
41
+ const mode = context.flags.json ? "capture" : "inherit";
42
+
43
+ let bootstrapResult: unknown;
44
+ if (context.config.bootstrap.enabled) {
45
+ const result = await runBootstrap(context.config.bootstrap.steps, {
46
+ repoRoot: worktree.path,
47
+ mode,
48
+ });
49
+ bootstrapResult = result;
50
+ if (result.exitCode !== 0) {
51
+ return {
52
+ message: result.message,
53
+ data: { worktree, bootstrap: result },
54
+ exitCode: result.exitCode,
55
+ };
56
+ }
57
+ }
58
+
59
+ let openResult: Awaited<ReturnType<typeof runShellCommand>> | undefined;
60
+ if (context.config.dev.open) {
61
+ openResult = await runShellCommand({
62
+ command: context.config.dev.open,
63
+ cwd: worktree.path,
64
+ mode,
65
+ });
66
+ if (openResult.exitCode !== 0)
67
+ return {
68
+ message: `dev open command failed (exit ${openResult.exitCode}).`,
69
+ data: { worktree, bootstrap: bootstrapResult, open: openResult },
70
+ exitCode: openResult.exitCode,
71
+ };
72
+ }
73
+
74
+ const devResult = await runShellCommand({
75
+ command: context.config.dev.command,
76
+ cwd: worktree.path,
77
+ mode,
78
+ });
79
+ return {
80
+ message: devResult.exitCode === 0 ? "" : `dev command exited with ${devResult.exitCode}.`,
81
+ data: {
82
+ worktree,
83
+ bootstrap: bootstrapResult,
84
+ open: openResult,
85
+ dev: devResult,
86
+ },
87
+ exitCode: devResult.exitCode,
88
+ };
89
+ },
90
+ };