@a3t/rapid 0.1.7 → 0.1.8

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.
@@ -1,14 +1,15 @@
1
1
  // src/index.ts
2
- import { Command as Command10 } from "commander";
3
- import { setLogLevel, logger as logger10 } from "@a3t/rapid-core";
4
- import { readFileSync } from "fs";
5
- import { fileURLToPath } from "url";
6
- import { dirname, join as join4 } from "path";
2
+ import { Command as Command13 } from "commander";
3
+ import { setLogLevel, logger as logger14 } from "@a3t/rapid-core";
4
+ import { readFileSync as readFileSync2 } from "fs";
5
+ import { fileURLToPath as fileURLToPath3 } from "url";
6
+ import { dirname as dirname4, join as join7 } from "path";
7
7
 
8
8
  // src/commands/init.ts
9
9
  import { Command } from "commander";
10
- import { writeFile, access, readFile, readdir } from "fs/promises";
10
+ import { writeFile, access, readFile, readdir, mkdir } from "fs/promises";
11
11
  import { join } from "path";
12
+ import { existsSync } from "fs";
12
13
  import {
13
14
  getDefaultConfig,
14
15
  logger,
@@ -195,7 +196,283 @@ async function downloadRemoteTemplate(parsed, destDir, spinner) {
195
196
  return false;
196
197
  }
197
198
  }
198
- var initCommand = new Command("init").description("Initialize RAPID in a project").argument("[template]", "Template: builtin name, github:user/repo, npm:package, or URL").option("--force", "Overwrite existing files", false).option("--agent <name>", "Default agent to configure", "claude").option("--no-devcontainer", "Skip devcontainer creation").option("--mcp <servers>", "MCP servers to enable (comma-separated)", "context7,tavily").option("--no-mcp", "Skip MCP server configuration").option("--no-detect", "Skip auto-detection of project type").action(async (templateArg, options) => {
199
+ var PREBUILT_IMAGE_REGISTRY = "ghcr.io/a3tai/rapid-devcontainer";
200
+ var PREBUILT_IMAGES = {
201
+ typescript: `${PREBUILT_IMAGE_REGISTRY}-typescript:latest`,
202
+ javascript: `${PREBUILT_IMAGE_REGISTRY}-typescript:latest`,
203
+ python: `${PREBUILT_IMAGE_REGISTRY}-python:latest`,
204
+ rust: `${PREBUILT_IMAGE_REGISTRY}-rust:latest`,
205
+ go: `${PREBUILT_IMAGE_REGISTRY}-go:latest`,
206
+ universal: `${PREBUILT_IMAGE_REGISTRY}-universal:latest`,
207
+ infrastructure: `${PREBUILT_IMAGE_REGISTRY}-infrastructure:latest`
208
+ };
209
+ var TEMPLATE_CUSTOMIZATIONS = {
210
+ typescript: {
211
+ vscode: {
212
+ extensions: [
213
+ "dbaeumer.vscode-eslint",
214
+ "esbenp.prettier-vscode",
215
+ "bradlc.vscode-tailwindcss",
216
+ "prisma.prisma",
217
+ "mikestead.dotenv"
218
+ ],
219
+ settings: {
220
+ "editor.formatOnSave": true,
221
+ "editor.defaultFormatter": "esbenp.prettier-vscode"
222
+ }
223
+ }
224
+ },
225
+ python: {
226
+ vscode: {
227
+ extensions: [
228
+ "ms-python.python",
229
+ "ms-python.vscode-pylance",
230
+ "charliermarsh.ruff",
231
+ "ms-toolsai.jupyter"
232
+ ],
233
+ settings: {
234
+ "[python]": {
235
+ "editor.formatOnSave": true,
236
+ "editor.defaultFormatter": "charliermarsh.ruff"
237
+ }
238
+ }
239
+ }
240
+ },
241
+ rust: {
242
+ vscode: {
243
+ extensions: ["rust-lang.rust-analyzer", "tamasfe.even-better-toml", "vadimcn.vscode-lldb"],
244
+ settings: { "[rust]": { "editor.formatOnSave": true } }
245
+ }
246
+ },
247
+ go: {
248
+ vscode: {
249
+ extensions: ["golang.go", "zxh404.vscode-proto3"],
250
+ settings: { "[go]": { "editor.formatOnSave": true } }
251
+ }
252
+ },
253
+ universal: {
254
+ vscode: {
255
+ extensions: [
256
+ "dbaeumer.vscode-eslint",
257
+ "esbenp.prettier-vscode",
258
+ "ms-python.python",
259
+ "golang.go"
260
+ ]
261
+ }
262
+ },
263
+ infrastructure: {
264
+ vscode: {
265
+ extensions: [
266
+ "hashicorp.terraform",
267
+ "ms-kubernetes-tools.vscode-kubernetes-tools",
268
+ "redhat.vscode-yaml"
269
+ ]
270
+ }
271
+ }
272
+ };
273
+ function getPrebuiltConfig(templateName, containerEnv, postStartCommand) {
274
+ const image = PREBUILT_IMAGES[templateName] ?? PREBUILT_IMAGES.universal;
275
+ const customizations = TEMPLATE_CUSTOMIZATIONS[templateName] ?? TEMPLATE_CUSTOMIZATIONS.universal;
276
+ const remoteUser = templateName === "typescript" ? "node" : "vscode";
277
+ return {
278
+ name: `RAPID ${templateName.charAt(0).toUpperCase() + templateName.slice(1)} (Pre-built)`,
279
+ image,
280
+ customizations,
281
+ containerEnv,
282
+ postStartCommand,
283
+ remoteUser
284
+ };
285
+ }
286
+ function getDevContainerConfig(detected, usePrebuilt = false) {
287
+ const baseFeatures = {
288
+ "ghcr.io/devcontainers/features/git:1": {},
289
+ "ghcr.io/devcontainers-contrib/features/direnv:1": {},
290
+ "ghcr.io/devcontainers-contrib/features/starship:1": {},
291
+ "ghcr.io/devcontainers-contrib/features/1password-cli:1": {}
292
+ };
293
+ const containerEnv = {
294
+ OP_SERVICE_ACCOUNT_TOKEN: "${localEnv:OP_SERVICE_ACCOUNT_TOKEN}"
295
+ };
296
+ const postCreateBase = "npm install -g @anthropic-ai/claude-code && curl -fsSL https://opencode.ai/install | bash";
297
+ const postStartCommand = "direnv allow 2>/dev/null || true";
298
+ const language = detected?.language || "unknown";
299
+ const templateName = language === "javascript" ? "typescript" : language === "unknown" ? "universal" : language;
300
+ if (usePrebuilt && PREBUILT_IMAGES[templateName]) {
301
+ return getPrebuiltConfig(templateName, containerEnv, postStartCommand);
302
+ }
303
+ switch (language) {
304
+ case "typescript":
305
+ case "javascript":
306
+ return {
307
+ name: "RAPID TypeScript",
308
+ image: "mcr.microsoft.com/devcontainers/typescript-node:22",
309
+ features: {
310
+ ...baseFeatures,
311
+ "ghcr.io/devcontainers-contrib/features/pnpm:2": {}
312
+ },
313
+ customizations: {
314
+ vscode: {
315
+ extensions: [
316
+ "dbaeumer.vscode-eslint",
317
+ "esbenp.prettier-vscode",
318
+ "bradlc.vscode-tailwindcss",
319
+ "prisma.prisma",
320
+ "mikestead.dotenv"
321
+ ],
322
+ settings: {
323
+ "editor.formatOnSave": true,
324
+ "editor.defaultFormatter": "esbenp.prettier-vscode",
325
+ "editor.codeActionsOnSave": {
326
+ "source.fixAll.eslint": "explicit"
327
+ }
328
+ }
329
+ }
330
+ },
331
+ containerEnv,
332
+ postCreateCommand: postCreateBase,
333
+ postStartCommand,
334
+ remoteUser: "node"
335
+ };
336
+ case "python":
337
+ return {
338
+ name: "RAPID Python",
339
+ image: "mcr.microsoft.com/devcontainers/python:3.12",
340
+ features: {
341
+ ...baseFeatures,
342
+ "ghcr.io/devcontainers/features/node:1": { version: "22" },
343
+ "ghcr.io/devcontainers-contrib/features/poetry:2": {},
344
+ "ghcr.io/devcontainers-contrib/features/uv:1": {}
345
+ },
346
+ customizations: {
347
+ vscode: {
348
+ extensions: [
349
+ "ms-python.python",
350
+ "ms-python.vscode-pylance",
351
+ "ms-python.debugpy",
352
+ "charliermarsh.ruff",
353
+ "ms-toolsai.jupyter",
354
+ "tamasfe.even-better-toml"
355
+ ],
356
+ settings: {
357
+ "python.defaultInterpreterPath": "/usr/local/bin/python",
358
+ "[python]": {
359
+ "editor.formatOnSave": true,
360
+ "editor.defaultFormatter": "charliermarsh.ruff",
361
+ "editor.codeActionsOnSave": {
362
+ "source.fixAll": "explicit",
363
+ "source.organizeImports": "explicit"
364
+ }
365
+ }
366
+ }
367
+ }
368
+ },
369
+ containerEnv,
370
+ postCreateCommand: `${postCreateBase} && pip install aider-chat`,
371
+ postStartCommand,
372
+ remoteUser: "vscode"
373
+ };
374
+ case "rust":
375
+ return {
376
+ name: "RAPID Rust",
377
+ image: "mcr.microsoft.com/devcontainers/rust:latest",
378
+ features: {
379
+ ...baseFeatures,
380
+ "ghcr.io/devcontainers/features/node:1": { version: "22" }
381
+ },
382
+ customizations: {
383
+ vscode: {
384
+ extensions: [
385
+ "rust-lang.rust-analyzer",
386
+ "tamasfe.even-better-toml",
387
+ "serayuzgur.crates",
388
+ "vadimcn.vscode-lldb"
389
+ ],
390
+ settings: {
391
+ "rust-analyzer.checkOnSave.command": "clippy",
392
+ "[rust]": {
393
+ "editor.formatOnSave": true,
394
+ "editor.defaultFormatter": "rust-lang.rust-analyzer"
395
+ }
396
+ }
397
+ }
398
+ },
399
+ containerEnv,
400
+ postCreateCommand: `${postCreateBase} && rustup component add clippy rustfmt`,
401
+ postStartCommand,
402
+ remoteUser: "vscode"
403
+ };
404
+ case "go":
405
+ return {
406
+ name: "RAPID Go",
407
+ image: "mcr.microsoft.com/devcontainers/go:1.23",
408
+ features: {
409
+ ...baseFeatures,
410
+ "ghcr.io/devcontainers/features/node:1": { version: "22" }
411
+ },
412
+ customizations: {
413
+ vscode: {
414
+ extensions: ["golang.go", "zxh404.vscode-proto3", "tamasfe.even-better-toml"],
415
+ settings: {
416
+ "go.useLanguageServer": true,
417
+ "go.lintTool": "golangci-lint",
418
+ "go.lintFlags": ["--fast"],
419
+ "[go]": {
420
+ "editor.formatOnSave": true,
421
+ "editor.codeActionsOnSave": {
422
+ "source.organizeImports": "explicit"
423
+ }
424
+ }
425
+ }
426
+ }
427
+ },
428
+ containerEnv,
429
+ postCreateCommand: `${postCreateBase} && go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest && go install github.com/air-verse/air@latest`,
430
+ postStartCommand,
431
+ remoteUser: "vscode"
432
+ };
433
+ default:
434
+ return {
435
+ name: "RAPID Universal",
436
+ image: "mcr.microsoft.com/devcontainers/base:ubuntu",
437
+ features: {
438
+ ...baseFeatures,
439
+ "ghcr.io/devcontainers/features/node:1": { version: "22" },
440
+ "ghcr.io/devcontainers/features/python:1": { version: "3.12" },
441
+ "ghcr.io/devcontainers/features/go:1": { version: "1.23" },
442
+ "ghcr.io/devcontainers/features/docker-in-docker:2": {}
443
+ },
444
+ customizations: {
445
+ vscode: {
446
+ extensions: [
447
+ "dbaeumer.vscode-eslint",
448
+ "esbenp.prettier-vscode",
449
+ "ms-python.python",
450
+ "ms-python.vscode-pylance",
451
+ "golang.go",
452
+ "tamasfe.even-better-toml",
453
+ "redhat.vscode-yaml"
454
+ ]
455
+ }
456
+ },
457
+ containerEnv,
458
+ postCreateCommand: `${postCreateBase} && pip install aider-chat`,
459
+ postStartCommand,
460
+ remoteUser: "vscode"
461
+ };
462
+ }
463
+ }
464
+ async function createDevContainer(dir, detected, force = false, usePrebuilt = false) {
465
+ const devcontainerDir = join(dir, ".devcontainer");
466
+ const devcontainerJsonPath = join(devcontainerDir, "devcontainer.json");
467
+ if (!force && existsSync(devcontainerJsonPath)) {
468
+ return false;
469
+ }
470
+ await mkdir(devcontainerDir, { recursive: true });
471
+ const config = getDevContainerConfig(detected, usePrebuilt);
472
+ await writeFile(devcontainerJsonPath, JSON.stringify(config, null, 2) + "\n");
473
+ return true;
474
+ }
475
+ var initCommand = new Command("init").description("Initialize RAPID in a project").argument("[template]", "Template: builtin name, github:user/repo, npm:package, or URL").option("--force", "Overwrite existing files", false).option("--agent <name>", "Default agent to configure", "claude").option("--no-devcontainer", "Skip devcontainer creation").option("--prebuilt", "Use pre-built devcontainer images from ghcr.io (faster startup)", false).option("--mcp <servers>", "MCP servers to enable (comma-separated)", "context7,tavily").option("--no-mcp", "Skip MCP server configuration").option("--no-detect", "Skip auto-detection of project type").action(async (templateArg, options) => {
199
476
  const spinner = ora("Initializing RAPID...").start();
200
477
  try {
201
478
  const cwd = process.cwd();
@@ -290,6 +567,17 @@ var initCommand = new Command("init").description("Initialize RAPID in a project
290
567
  spinner.text = "Creating AGENTS.md...";
291
568
  const agentsMdPath = join(cwd, "AGENTS.md");
292
569
  await writeFile(agentsMdPath, getAgentsMdTemplate(cwd, detectedProject));
570
+ let devcontainerCreated = false;
571
+ const usePrebuilt = options.prebuilt === true;
572
+ if (options.devcontainer !== false) {
573
+ spinner.text = usePrebuilt ? "Creating devcontainer configuration (using pre-built image)..." : "Creating devcontainer configuration...";
574
+ devcontainerCreated = await createDevContainer(
575
+ cwd,
576
+ detectedProject,
577
+ options.force,
578
+ usePrebuilt
579
+ );
580
+ }
293
581
  spinner.succeed("RAPID initialized successfully!");
294
582
  if (detectedProject && detectedProject.language !== "unknown") {
295
583
  logger.blank();
@@ -309,6 +597,9 @@ var initCommand = new Command("init").description("Initialize RAPID in a project
309
597
  console.log(` ${logger.dim("\u2022")} .mcp.json`);
310
598
  console.log(` ${logger.dim("\u2022")} opencode.json`);
311
599
  }
600
+ if (devcontainerCreated) {
601
+ console.log(` ${logger.dim("\u2022")} .devcontainer/devcontainer.json`);
602
+ }
312
603
  console.log(` ${logger.dim("\u2022")} CLAUDE.md`);
313
604
  console.log(` ${logger.dim("\u2022")} AGENTS.md`);
314
605
  if (mcpServers.length > 0) {
@@ -323,11 +614,21 @@ var initCommand = new Command("init").description("Initialize RAPID in a project
323
614
  }
324
615
  logger.blank();
325
616
  logger.info("Next steps:");
326
- console.log(` ${logger.dim("1.")} Run ${logger.brand("rapid dev")} to start coding`);
327
- console.log(` ${logger.dim("2.")} Edit ${logger.dim("rapid.json")} to customize your setup`);
617
+ let stepNum = 1;
618
+ console.log(
619
+ ` ${logger.dim(`${stepNum++}.`)} Run ${logger.brand("rapid dev")} to start coding`
620
+ );
621
+ console.log(
622
+ ` ${logger.dim(`${stepNum++}.`)} Edit ${logger.dim("rapid.json")} to customize your setup`
623
+ );
328
624
  if (mcpServers.length > 0) {
329
625
  console.log(
330
- ` ${logger.dim("3.")} Add API keys to ${logger.dim("secrets.items")} in rapid.json`
626
+ ` ${logger.dim(`${stepNum++}.`)} Add API keys to ${logger.dim("secrets.items")} in rapid.json`
627
+ );
628
+ }
629
+ if (devcontainerCreated) {
630
+ console.log(
631
+ ` ${logger.dim(`${stepNum++}.`)} Set ${logger.dim("OP_SERVICE_ACCOUNT_TOKEN")} env var for 1Password secrets`
331
632
  );
332
633
  }
333
634
  logger.blank();
@@ -449,8 +750,8 @@ ${GIT_GUIDELINES}
449
750
 
450
751
  // src/commands/dev.ts
451
752
  import { Command as Command2 } from "commander";
452
- import { writeFile as writeFile2 } from "fs/promises";
453
- import { isAbsolute, join as join2 } from "path";
753
+ import { writeFile as writeFile3 } from "fs/promises";
754
+ import { isAbsolute, join as join4 } from "path";
454
755
  import {
455
756
  loadConfig,
456
757
  getAgent,
@@ -469,10 +770,541 @@ import {
469
770
  agentSupportsRuntimeInjection
470
771
  } from "@a3t/rapid-core";
471
772
  import ora2 from "ora";
773
+
774
+ // src/utils/worktree.ts
775
+ import { execa } from "execa";
776
+ import { access as access2 } from "fs/promises";
777
+ import { basename, dirname, join as join2, resolve } from "path";
778
+ function getErrorMessage(err) {
779
+ if (typeof err.stderr === "string" && err.stderr) {
780
+ return err.stderr;
781
+ }
782
+ return err.message;
783
+ }
784
+ async function isGitRepo(dir) {
785
+ try {
786
+ await execa("git", ["rev-parse", "--git-dir"], { cwd: dir });
787
+ return true;
788
+ } catch {
789
+ return false;
790
+ }
791
+ }
792
+ async function getGitRoot(dir) {
793
+ const { stdout } = await execa("git", ["rev-parse", "--show-toplevel"], { cwd: dir });
794
+ return stdout.trim();
795
+ }
796
+ async function getCurrentBranch(dir) {
797
+ try {
798
+ const { stdout: symbolicRef } = await execa("git", ["symbolic-ref", "-q", "HEAD"], {
799
+ cwd: dir,
800
+ reject: false
801
+ });
802
+ if (!symbolicRef) {
803
+ return { name: null, isDefault: false, detached: true };
804
+ }
805
+ const branchName = symbolicRef.trim().replace("refs/heads/", "");
806
+ const isDefault = branchName === "main" || branchName === "master";
807
+ return { name: branchName, isDefault, detached: false };
808
+ } catch {
809
+ return { name: null, isDefault: false, detached: true };
810
+ }
811
+ }
812
+ async function getDefaultBranch(dir) {
813
+ try {
814
+ const { stdout } = await execa("git", ["symbolic-ref", "refs/remotes/origin/HEAD", "--short"], {
815
+ cwd: dir,
816
+ reject: false
817
+ });
818
+ if (stdout) {
819
+ return stdout.trim().replace("origin/", "");
820
+ }
821
+ const { stdout: branches } = await execa("git", ["branch", "--list", "main", "master"], {
822
+ cwd: dir
823
+ });
824
+ if (branches.includes("main")) return "main";
825
+ if (branches.includes("master")) return "master";
826
+ return "main";
827
+ } catch {
828
+ return "main";
829
+ }
830
+ }
831
+ async function listWorktrees(dir) {
832
+ const { stdout } = await execa("git", ["worktree", "list", "--porcelain"], { cwd: dir });
833
+ const worktrees = [];
834
+ let current = {};
835
+ for (const line of stdout.split("\n")) {
836
+ if (line.startsWith("worktree ")) {
837
+ if (current.path) {
838
+ worktrees.push(current);
839
+ }
840
+ current = {
841
+ path: line.substring(9),
842
+ isMain: false,
843
+ locked: false,
844
+ exists: true,
845
+ prunable: false
846
+ };
847
+ } else if (line.startsWith("HEAD ")) {
848
+ current.head = line.substring(5);
849
+ } else if (line.startsWith("branch ")) {
850
+ current.branch = line.substring(7).replace("refs/heads/", "");
851
+ } else if (line === "bare") {
852
+ current.isMain = true;
853
+ } else if (line === "locked") {
854
+ current.locked = true;
855
+ } else if (line === "prunable") {
856
+ current.prunable = true;
857
+ current.exists = false;
858
+ } else if (line === "detached") {
859
+ current.branch = null;
860
+ }
861
+ }
862
+ if (current.path) {
863
+ worktrees.push(current);
864
+ }
865
+ if (worktrees.length > 0 && worktrees[0]) {
866
+ worktrees[0].isMain = true;
867
+ }
868
+ for (const wt of worktrees) {
869
+ try {
870
+ await access2(wt.path);
871
+ wt.exists = true;
872
+ } catch {
873
+ wt.exists = false;
874
+ wt.prunable = true;
875
+ }
876
+ }
877
+ return worktrees;
878
+ }
879
+ async function findWorktreeByBranch(dir, branch) {
880
+ const worktrees = await listWorktrees(dir);
881
+ return worktrees.find((wt) => wt.branch === branch) ?? null;
882
+ }
883
+ function generateWorktreePath(repoRoot, branchName) {
884
+ const projectName = basename(repoRoot);
885
+ const parentDir = dirname(repoRoot);
886
+ const safeBranchName = branchName.replace(/\//g, "-").replace(/[^a-zA-Z0-9-_]/g, "").toLowerCase();
887
+ return join2(parentDir, `${projectName}-${safeBranchName}`);
888
+ }
889
+ async function createWorktree(repoRoot, worktreePath, branch, options = {}) {
890
+ try {
891
+ const existing = await listWorktrees(repoRoot);
892
+ const existingAtPath = existing.find((wt) => resolve(wt.path) === resolve(worktreePath));
893
+ if (existingAtPath && existingAtPath.exists && !options.force) {
894
+ return { success: true, path: worktreePath };
895
+ }
896
+ if (existingAtPath && !existingAtPath.exists) {
897
+ await execa("git", ["worktree", "remove", "--force", worktreePath], {
898
+ cwd: repoRoot,
899
+ reject: false
900
+ });
901
+ }
902
+ const args = ["worktree", "add"];
903
+ if (options.force) {
904
+ args.push("--force");
905
+ }
906
+ if (options.newBranch) {
907
+ args.push("-b", options.newBranch);
908
+ }
909
+ args.push(worktreePath);
910
+ if (!options.newBranch) {
911
+ args.push(branch);
912
+ } else if (options.startPoint) {
913
+ args.push(options.startPoint);
914
+ }
915
+ await execa("git", args, { cwd: repoRoot });
916
+ return { success: true, path: worktreePath };
917
+ } catch (err) {
918
+ const error = err;
919
+ return {
920
+ success: false,
921
+ path: worktreePath,
922
+ error: getErrorMessage(error)
923
+ };
924
+ }
925
+ }
926
+ async function removeWorktree(repoRoot, worktreePath, options = {}) {
927
+ try {
928
+ const args = ["worktree", "remove"];
929
+ if (options.force) {
930
+ args.push("--force");
931
+ }
932
+ args.push(worktreePath);
933
+ await execa("git", args, { cwd: repoRoot });
934
+ return { success: true };
935
+ } catch (err) {
936
+ const error = err;
937
+ return {
938
+ success: false,
939
+ error: getErrorMessage(error)
940
+ };
941
+ }
942
+ }
943
+ async function pruneWorktrees(repoRoot) {
944
+ try {
945
+ const worktrees = await listWorktrees(repoRoot);
946
+ const prunable = worktrees.filter((wt) => wt.prunable).map((wt) => wt.path);
947
+ await execa("git", ["worktree", "prune"], { cwd: repoRoot });
948
+ return { success: true, pruned: prunable };
949
+ } catch (err) {
950
+ const error = err;
951
+ return {
952
+ success: false,
953
+ pruned: [],
954
+ error: getErrorMessage(error)
955
+ };
956
+ }
957
+ }
958
+ async function getOrCreateWorktreeForBranch(dir) {
959
+ const gitRoot = await getGitRoot(dir);
960
+ const branch = await getCurrentBranch(dir);
961
+ if (branch.isDefault || branch.detached || !branch.name) {
962
+ return { path: gitRoot, created: false, isMain: true };
963
+ }
964
+ const existing = await findWorktreeByBranch(gitRoot, branch.name);
965
+ if (existing && existing.exists) {
966
+ return { path: existing.path, created: false, isMain: existing.isMain };
967
+ }
968
+ const worktreePath = generateWorktreePath(gitRoot, branch.name);
969
+ const result = await createWorktree(gitRoot, worktreePath, branch.name);
970
+ if (!result.success) {
971
+ return { path: gitRoot, created: false, isMain: true };
972
+ }
973
+ return { path: worktreePath, created: true, isMain: false };
974
+ }
975
+ async function cleanupMergedWorktrees(repoRoot) {
976
+ const removed = [];
977
+ const errors = [];
978
+ const defaultBranch = await getDefaultBranch(repoRoot);
979
+ const { stdout } = await execa("git", ["branch", "--merged", defaultBranch], { cwd: repoRoot });
980
+ const mergedBranches = stdout.split("\n").map((b) => b.trim().replace(/^\*\s*/, "")).filter((b) => b && b !== defaultBranch);
981
+ const worktrees = await listWorktrees(repoRoot);
982
+ for (const wt of worktrees) {
983
+ if (wt.isMain || !wt.branch) continue;
984
+ if (mergedBranches.includes(wt.branch)) {
985
+ const result = await removeWorktree(repoRoot, wt.path, { force: true });
986
+ if (result.success) {
987
+ removed.push(wt.path);
988
+ } else if (result.error) {
989
+ errors.push(`${wt.path}: ${result.error}`);
990
+ }
991
+ }
992
+ }
993
+ return { removed, errors };
994
+ }
995
+
996
+ // src/isolation/lima.ts
997
+ import { execa as execa2 } from "execa";
998
+ import { readFile as readFile2, writeFile as writeFile2, mkdir as mkdir2 } from "fs/promises";
999
+ import { homedir, platform } from "os";
1000
+ import { join as join3, dirname as dirname2 } from "path";
1001
+ import { fileURLToPath } from "url";
1002
+ function getErrorMessage2(err) {
1003
+ if (typeof err.stderr === "string" && err.stderr) {
1004
+ return err.stderr;
1005
+ }
1006
+ return err.message;
1007
+ }
1008
+ function getOutputString(output) {
1009
+ if (typeof output === "string") {
1010
+ return output;
1011
+ }
1012
+ return void 0;
1013
+ }
1014
+ var RAPID_LIMA_INSTANCE = "rapid";
1015
+ var RAPID_LIMA_DIR = join3(homedir(), ".rapid", "lima");
1016
+ async function hasLima() {
1017
+ try {
1018
+ await execa2("limactl", ["--version"]);
1019
+ return true;
1020
+ } catch {
1021
+ return false;
1022
+ }
1023
+ }
1024
+ function isMacOS() {
1025
+ return platform() === "darwin";
1026
+ }
1027
+ function getLimaTemplatePath() {
1028
+ const __dirname3 = dirname2(fileURLToPath(import.meta.url));
1029
+ const possiblePaths = [
1030
+ join3(__dirname3, "../../../../templates/lima.yaml"),
1031
+ // From dist/isolation/
1032
+ join3(__dirname3, "../../../templates/lima.yaml"),
1033
+ // From src/isolation/
1034
+ join3(homedir(), ".rapid", "lima.yaml")
1035
+ // User config
1036
+ ];
1037
+ return possiblePaths[0];
1038
+ }
1039
+ async function listInstances() {
1040
+ try {
1041
+ const { stdout } = await execa2("limactl", ["list", "--json"]);
1042
+ const instances = JSON.parse(stdout);
1043
+ return instances.map((inst) => {
1044
+ const result = {
1045
+ name: inst.name,
1046
+ status: inst.status,
1047
+ arch: inst.arch,
1048
+ cpus: inst.cpus,
1049
+ memory: `${Math.round(inst.memory / 1024 / 1024 / 1024)}GiB`,
1050
+ disk: `${Math.round(inst.disk / 1024 / 1024 / 1024)}GiB`,
1051
+ dir: inst.dir
1052
+ };
1053
+ if (inst.sshLocalPort !== void 0) {
1054
+ result.sshLocalPort = inst.sshLocalPort;
1055
+ }
1056
+ return result;
1057
+ });
1058
+ } catch {
1059
+ return [];
1060
+ }
1061
+ }
1062
+ async function getInstance(name = RAPID_LIMA_INSTANCE) {
1063
+ const instances = await listInstances();
1064
+ return instances.find((i) => i.name === name) ?? null;
1065
+ }
1066
+ async function instanceExists(name = RAPID_LIMA_INSTANCE) {
1067
+ const instance = await getInstance(name);
1068
+ return instance !== null;
1069
+ }
1070
+ async function isRunning(name = RAPID_LIMA_INSTANCE) {
1071
+ const instance = await getInstance(name);
1072
+ return instance?.status === "Running";
1073
+ }
1074
+ async function createLimaConfig(projectDir, options = {}) {
1075
+ const templatePath = getLimaTemplatePath();
1076
+ const configDir = RAPID_LIMA_DIR;
1077
+ const configPath = join3(configDir, "lima.yaml");
1078
+ await mkdir2(configDir, { recursive: true });
1079
+ let template;
1080
+ try {
1081
+ template = await readFile2(templatePath, "utf-8");
1082
+ } catch {
1083
+ template = getMinimalLimaConfig();
1084
+ }
1085
+ let config = template;
1086
+ const projectMount = `
1087
+ - location: "${projectDir}"
1088
+ writable: true`;
1089
+ config = config.replace(
1090
+ /mounts:\s*\n\s*- location: "~"/,
1091
+ `mounts:
1092
+ - location: "~"${projectMount}`
1093
+ );
1094
+ if (options.cpus) {
1095
+ config = config.replace(/cpus: \d+/, `cpus: ${options.cpus}`);
1096
+ }
1097
+ if (options.memory) {
1098
+ config = config.replace(/memory: "[^"]*"/, `memory: "${options.memory}"`);
1099
+ }
1100
+ if (options.disk) {
1101
+ config = config.replace(/disk: "[^"]*"/, `disk: "${options.disk}"`);
1102
+ }
1103
+ if (options.env) {
1104
+ const envLines = Object.entries(options.env).map(([key, value]) => ` ${key}: "${value}"`).join("\n");
1105
+ config = config.replace(/env:[\s\S]*?(?=\n\w|\n#|$)/, `env:
1106
+ ${envLines}
1107
+ `);
1108
+ }
1109
+ await writeFile2(configPath, config);
1110
+ return configPath;
1111
+ }
1112
+ function getMinimalLimaConfig() {
1113
+ return `
1114
+ vmType: "vz"
1115
+ rosetta:
1116
+ enabled: true
1117
+ binfmt: true
1118
+ cpus: 4
1119
+ memory: "8GiB"
1120
+ disk: "50GiB"
1121
+ images:
1122
+ - location: "https://cloud-images.ubuntu.com/releases/24.04/release/ubuntu-24.04-server-cloudimg-arm64.img"
1123
+ arch: "aarch64"
1124
+ - location: "https://cloud-images.ubuntu.com/releases/24.04/release/ubuntu-24.04-server-cloudimg-amd64.img"
1125
+ arch: "x86_64"
1126
+ mountType: "virtiofs"
1127
+ mounts:
1128
+ - location: "~"
1129
+ writable: true
1130
+ mountInotify: true
1131
+ ssh:
1132
+ forwardAgent: true
1133
+ localPort: 0
1134
+ networks:
1135
+ - vzNAT: true
1136
+ containerd:
1137
+ system: true
1138
+ user: false
1139
+ portForwards:
1140
+ - guestPort: 3000
1141
+ hostPort: 3000
1142
+ - guestPort: 8080
1143
+ hostPort: 8080
1144
+ provision:
1145
+ - mode: system
1146
+ script: |
1147
+ #!/bin/bash
1148
+ set -eux
1149
+ apt-get update
1150
+ apt-get install -y build-essential curl git jq
1151
+ curl -fsSL https://deb.nodesource.com/setup_22.x | bash -
1152
+ apt-get install -y nodejs
1153
+ npm install -g pnpm
1154
+ - mode: user
1155
+ script: |
1156
+ #!/bin/bash
1157
+ set -eux
1158
+ npm install -g @anthropic-ai/claude-code || true
1159
+ curl -fsSL https://opencode.ai/install | bash || true
1160
+ `;
1161
+ }
1162
+ async function startInstance(projectDir, options = {}) {
1163
+ const name = RAPID_LIMA_INSTANCE;
1164
+ if (!await hasLima()) {
1165
+ return {
1166
+ success: false,
1167
+ error: "Lima is not installed. Install with: brew install lima"
1168
+ };
1169
+ }
1170
+ if (!isMacOS()) {
1171
+ return {
1172
+ success: false,
1173
+ error: "Lima is only available on macOS"
1174
+ };
1175
+ }
1176
+ try {
1177
+ const exists = await instanceExists(name);
1178
+ if (exists) {
1179
+ if (await isRunning(name)) {
1180
+ return { success: true };
1181
+ }
1182
+ await execa2("limactl", ["start", name], {
1183
+ timeout: (options.timeout ?? 300) * 1e3
1184
+ });
1185
+ } else {
1186
+ const configPath = await createLimaConfig(projectDir, options);
1187
+ await execa2("limactl", ["start", "--name", name, configPath], {
1188
+ timeout: (options.timeout ?? 600) * 1e3,
1189
+ stdio: "inherit"
1190
+ // Show progress
1191
+ });
1192
+ }
1193
+ return { success: true };
1194
+ } catch (err) {
1195
+ const error = err;
1196
+ return {
1197
+ success: false,
1198
+ error: getErrorMessage2(error)
1199
+ };
1200
+ }
1201
+ }
1202
+ async function stopInstance(name = RAPID_LIMA_INSTANCE, options = {}) {
1203
+ try {
1204
+ const args = ["stop"];
1205
+ if (options.force) {
1206
+ args.push("--force");
1207
+ }
1208
+ args.push(name);
1209
+ await execa2("limactl", args);
1210
+ return { success: true };
1211
+ } catch (err) {
1212
+ const error = err;
1213
+ return {
1214
+ success: false,
1215
+ error: getErrorMessage2(error)
1216
+ };
1217
+ }
1218
+ }
1219
+ async function deleteInstance(name = RAPID_LIMA_INSTANCE, options = {}) {
1220
+ try {
1221
+ const args = ["delete"];
1222
+ if (options.force) {
1223
+ args.push("--force");
1224
+ }
1225
+ args.push(name);
1226
+ await execa2("limactl", args);
1227
+ return { success: true };
1228
+ } catch (err) {
1229
+ const error = err;
1230
+ return {
1231
+ success: false,
1232
+ error: getErrorMessage2(error)
1233
+ };
1234
+ }
1235
+ }
1236
+ async function execInLima(command, options = {}) {
1237
+ const name = options.name ?? RAPID_LIMA_INSTANCE;
1238
+ try {
1239
+ let fullCommand = command.join(" ");
1240
+ if (options.cwd) {
1241
+ fullCommand = `cd "${options.cwd}" && ${fullCommand}`;
1242
+ }
1243
+ if (options.env) {
1244
+ const exports = Object.entries(options.env).map(([key, value]) => `export ${key}="${value}"`).join(" && ");
1245
+ fullCommand = `${exports} && ${fullCommand}`;
1246
+ }
1247
+ const useInheritStdio = options.interactive || options.tty;
1248
+ const result = await execa2(
1249
+ "limactl",
1250
+ ["shell", name, "--", "bash", "-c", fullCommand],
1251
+ useInheritStdio ? { stdio: "inherit" } : {}
1252
+ );
1253
+ const successResult = {
1254
+ success: true
1255
+ };
1256
+ const stdout = getOutputString(result.stdout);
1257
+ const stderr = getOutputString(result.stderr);
1258
+ if (stdout) successResult.stdout = stdout;
1259
+ if (stderr) successResult.stderr = stderr;
1260
+ return successResult;
1261
+ } catch (err) {
1262
+ const error = err;
1263
+ const errorResult = {
1264
+ success: false,
1265
+ error: error.message
1266
+ };
1267
+ const stdout = getOutputString(error.stdout);
1268
+ const stderr = getOutputString(error.stderr);
1269
+ if (stdout) errorResult.stdout = stdout;
1270
+ if (stderr) errorResult.stderr = stderr;
1271
+ return errorResult;
1272
+ }
1273
+ }
1274
+ async function shellInLima(options = {}) {
1275
+ const name = options.name ?? RAPID_LIMA_INSTANCE;
1276
+ const args = ["shell", name];
1277
+ if (options.cwd) {
1278
+ args.push("--workdir", options.cwd);
1279
+ }
1280
+ if (options.command) {
1281
+ args.push("--", options.command);
1282
+ }
1283
+ await execa2("limactl", args, { stdio: "inherit" });
1284
+ }
1285
+ async function setupGitSsh(name = RAPID_LIMA_INSTANCE) {
1286
+ try {
1287
+ const result = await execInLima(["ssh-add", "-l"], { name });
1288
+ if (!result.success) {
1289
+ return {
1290
+ success: false,
1291
+ error: "SSH agent forwarding is not working. Make sure ssh-agent is running on the host."
1292
+ };
1293
+ }
1294
+ return { success: true };
1295
+ } catch (err) {
1296
+ return {
1297
+ success: false,
1298
+ error: err instanceof Error ? err.message : String(err)
1299
+ };
1300
+ }
1301
+ }
1302
+
1303
+ // src/commands/dev.ts
472
1304
  var devCommand = new Command2("dev").description("Launch AI coding session in the dev container").option("-a, --agent <name>", "Agent to use").option(
473
1305
  "--multi [agents]",
474
1306
  "Launch multiple agents (comma-separated, or interactive if no value)"
475
- ).option("--list", "List available agents without launching").option("--local", "Run locally instead of in container (not recommended)").option("--no-start", "Do not auto-start container if stopped").action(async (options) => {
1307
+ ).option("--list", "List available agents without launching").option("--local", "Run locally instead of in container (not recommended)").option("--no-start", "Do not auto-start container if stopped").option("--no-worktree", "Skip automatic worktree creation for feature branches").action(async (options) => {
476
1308
  try {
477
1309
  const spinner = ora2("Loading configuration...").start();
478
1310
  const loaded = await loadConfig();
@@ -480,12 +1312,34 @@ var devCommand = new Command2("dev").description("Launch AI coding session in th
480
1312
  spinner.fail("No rapid.json found. Run `rapid init` first.");
481
1313
  process.exit(1);
482
1314
  }
483
- const { config, rootDir } = loaded;
1315
+ const { config } = loaded;
1316
+ let { rootDir } = loaded;
484
1317
  spinner.succeed("Configuration loaded");
485
1318
  if (options.list) {
486
1319
  listAgents(config);
487
1320
  return;
488
1321
  }
1322
+ if (options.worktree !== false && await isGitRepo(rootDir)) {
1323
+ const branch = await getCurrentBranch(rootDir);
1324
+ if (!branch.isDefault && !branch.detached && branch.name) {
1325
+ spinner.start(`Checking worktree for branch: ${branch.name}...`);
1326
+ try {
1327
+ const worktree = await getOrCreateWorktreeForBranch(rootDir);
1328
+ if (worktree.created) {
1329
+ spinner.succeed(`Created worktree: ${worktree.path}`);
1330
+ rootDir = worktree.path;
1331
+ } else if (!worktree.isMain) {
1332
+ spinner.succeed(`Using worktree: ${worktree.path}`);
1333
+ rootDir = worktree.path;
1334
+ } else {
1335
+ spinner.info(`Using main directory (branch: ${branch.name})`);
1336
+ }
1337
+ } catch (err) {
1338
+ spinner.warn("Could not create worktree, using main directory");
1339
+ logger2.debug(err instanceof Error ? err.message : String(err));
1340
+ }
1341
+ }
1342
+ }
489
1343
  if (options.multi !== void 0) {
490
1344
  await runMultiAgent(config, rootDir, options);
491
1345
  return;
@@ -625,7 +1479,7 @@ async function prepareMcpEnv(rootDir, mcp) {
625
1479
  return void 0;
626
1480
  }
627
1481
  const configFile = mcp.configFile ?? ".mcp.json";
628
- const configPath = isAbsolute(configFile) ? configFile : join2(rootDir, configFile);
1482
+ const configPath = isAbsolute(configFile) ? configFile : join4(rootDir, configFile);
629
1483
  const servers = {};
630
1484
  for (const [name, serverConfig] of Object.entries(mcp.servers)) {
631
1485
  if (!serverConfig || typeof serverConfig !== "object") {
@@ -640,14 +1494,14 @@ async function prepareMcpEnv(rootDir, mcp) {
640
1494
  if (Object.keys(servers).length === 0) {
641
1495
  return void 0;
642
1496
  }
643
- await writeFile2(configPath, `${JSON.stringify({ servers }, null, 2)}
1497
+ await writeFile3(configPath, `${JSON.stringify({ servers }, null, 2)}
644
1498
  `, "utf-8");
645
1499
  return {
646
1500
  MCP_CONFIG_FILE: configFile
647
1501
  };
648
1502
  }
649
1503
  async function runLocally(agent, agentName, rootDir, config) {
650
- const { execa } = await import("execa");
1504
+ const { execa: execa4 } = await import("execa");
651
1505
  const status = await checkAgentAvailable(agent);
652
1506
  if (!status.available) {
653
1507
  logger2.error(`${agentName} CLI not found locally`);
@@ -720,14 +1574,18 @@ async function runLocally(agent, agentName, rootDir, config) {
720
1574
  }
721
1575
  const mcpEnv = await prepareMcpEnv(rootDir, config.mcp);
722
1576
  const mergedEnv = { ...secrets, ...mcpEnv ?? {} };
1577
+ const builtArgs = buildAgentArgs(agent, { injectSystemPrompt: true });
1578
+ if (isMacOS() && await hasLima()) {
1579
+ await runInLimaVm(agent, agentName, rootDir, builtArgs, mergedEnv);
1580
+ return;
1581
+ }
723
1582
  logger2.info(`Launching ${logger2.brand(agentName)}...`);
724
1583
  logger2.dim(`Working directory: ${rootDir}`);
725
- const builtArgs = buildAgentArgs(agent, { injectSystemPrompt: true });
726
1584
  if (agentSupportsRuntimeInjection(agent)) {
727
1585
  logger2.dim("Injecting RAPID methodology via CLI args");
728
1586
  }
729
1587
  logger2.blank();
730
- await execa(agent.cli, builtArgs, {
1588
+ await execa4(agent.cli, builtArgs, {
731
1589
  cwd: rootDir,
732
1590
  stdio: "inherit",
733
1591
  env: {
@@ -736,6 +1594,47 @@ async function runLocally(agent, agentName, rootDir, config) {
736
1594
  }
737
1595
  });
738
1596
  }
1597
+ async function runInLimaVm(agent, agentName, rootDir, args, env) {
1598
+ const spinner = ora2();
1599
+ if (!await isRunning()) {
1600
+ spinner.start(`Starting Lima VM (${RAPID_LIMA_INSTANCE})...`);
1601
+ const result = await startInstance(rootDir, {
1602
+ env,
1603
+ timeout: 600
1604
+ // 10 minutes for first-time setup
1605
+ });
1606
+ if (!result.success) {
1607
+ spinner.fail("Failed to start Lima VM");
1608
+ logger2.error(result.error ?? "Unknown error");
1609
+ logger2.blank();
1610
+ logger2.info("Falling back to running directly on host...");
1611
+ logger2.blank();
1612
+ const { execa: execa4 } = await import("execa");
1613
+ await execa4(agent.cli, args, {
1614
+ cwd: rootDir,
1615
+ stdio: "inherit",
1616
+ env: {
1617
+ ...process.env,
1618
+ ...env
1619
+ }
1620
+ });
1621
+ return;
1622
+ }
1623
+ spinner.succeed("Lima VM started");
1624
+ } else {
1625
+ logger2.info(`Lima VM (${RAPID_LIMA_INSTANCE}) is running`);
1626
+ }
1627
+ logger2.info(`Launching ${logger2.brand(agentName)} in Lima VM...`);
1628
+ logger2.dim(`Working directory: ${rootDir}`);
1629
+ logger2.dim("SSH agent forwarded for commit signing");
1630
+ logger2.blank();
1631
+ await execInLima([agent.cli, ...args], {
1632
+ cwd: rootDir,
1633
+ env,
1634
+ interactive: true,
1635
+ tty: true
1636
+ });
1637
+ }
739
1638
  function listAgents(config) {
740
1639
  logger2.header("Available Agents");
741
1640
  Object.keys(config.agents.available).forEach((name) => {
@@ -802,10 +1701,10 @@ async function runMultiAgent(config, rootDir, options) {
802
1701
  console.log(` ${logger2.brand("\u2022")} ${name}`);
803
1702
  }
804
1703
  console.log();
805
- const { execa } = await import("execa");
1704
+ const { execa: execa4 } = await import("execa");
806
1705
  let hasTmux = false;
807
1706
  try {
808
- await execa("tmux", ["-V"]);
1707
+ await execa4("tmux", ["-V"]);
809
1708
  hasTmux = true;
810
1709
  } catch {
811
1710
  hasTmux = false;
@@ -816,23 +1715,23 @@ async function runMultiAgent(config, rootDir, options) {
816
1715
  const sessionName = `rapid-${Date.now()}`;
817
1716
  const firstAgent = selectedAgents[0];
818
1717
  const firstCmd = options.local ? `rapid dev --agent ${firstAgent} --local` : `rapid dev --agent ${firstAgent}`;
819
- await execa("tmux", ["new-session", "-d", "-s", sessionName, "-n", "rapid", firstCmd], {
1718
+ await execa4("tmux", ["new-session", "-d", "-s", sessionName, "-n", "rapid", firstCmd], {
820
1719
  cwd: rootDir
821
1720
  });
822
1721
  for (let i = 1; i < selectedAgents.length; i++) {
823
1722
  const agentName = selectedAgents[i];
824
1723
  const cmd = options.local ? `rapid dev --agent ${agentName} --local` : `rapid dev --agent ${agentName}`;
825
- await execa("tmux", ["split-window", "-t", sessionName, "-h", cmd], {
1724
+ await execa4("tmux", ["split-window", "-t", sessionName, "-h", cmd], {
826
1725
  cwd: rootDir
827
1726
  });
828
- await execa("tmux", ["select-layout", "-t", sessionName, "tiled"]);
1727
+ await execa4("tmux", ["select-layout", "-t", sessionName, "tiled"]);
829
1728
  }
830
1729
  logger2.success(`Started ${selectedAgents.length} agents in tmux session: ${sessionName}`);
831
1730
  console.log();
832
1731
  logger2.info("Attaching to tmux session...");
833
1732
  logger2.dim("Press Ctrl+B then D to detach, or Ctrl+B then arrow keys to switch panes");
834
1733
  console.log();
835
- await execa("tmux", ["attach-session", "-t", sessionName], {
1734
+ await execa4("tmux", ["attach-session", "-t", sessionName], {
836
1735
  stdio: "inherit"
837
1736
  });
838
1737
  } else {
@@ -1574,13 +2473,13 @@ secretsCommand.command("run").description("Run a command with secrets loaded int
1574
2473
  }
1575
2474
  console.log();
1576
2475
  }
1577
- const { execa } = await import("execa");
2476
+ const { execa: execa4 } = await import("execa");
1578
2477
  const [cmd, ...args] = commandArgs;
1579
2478
  if (!cmd) {
1580
2479
  logger7.error("No command specified");
1581
2480
  process.exit(1);
1582
2481
  }
1583
- await execa(cmd, args, {
2482
+ await execa4(cmd, args, {
1584
2483
  stdio: "inherit",
1585
2484
  env: {
1586
2485
  ...process.env,
@@ -1783,8 +2682,8 @@ authCommand.command("env").description("Show environment variables for detected
1783
2682
 
1784
2683
  // src/commands/mcp.ts
1785
2684
  import { Command as Command9 } from "commander";
1786
- import { writeFile as writeFile3 } from "fs/promises";
1787
- import { join as join3 } from "path";
2685
+ import { writeFile as writeFile4 } from "fs/promises";
2686
+ import { join as join5 } from "path";
1788
2687
  import {
1789
2688
  loadConfig as loadConfig7,
1790
2689
  logger as logger9,
@@ -1805,8 +2704,8 @@ var mcpCommand = new Command9("mcp").description(
1805
2704
  "Manage MCP (Model Context Protocol) servers"
1806
2705
  );
1807
2706
  async function saveConfig(rootDir, config) {
1808
- const configPath = join3(rootDir, "rapid.json");
1809
- await writeFile3(configPath, JSON.stringify(config, null, 2) + "\n", "utf-8");
2707
+ const configPath = join5(rootDir, "rapid.json");
2708
+ await writeFile4(configPath, JSON.stringify(config, null, 2) + "\n", "utf-8");
1810
2709
  }
1811
2710
  mcpCommand.command("list").description("List configured MCP servers").option("--json", "Output as JSON").option("--templates", "Show available templates instead of configured servers").action(async (options) => {
1812
2711
  try {
@@ -2092,18 +2991,606 @@ function collectHeaders(value, previous) {
2092
2991
  return previous;
2093
2992
  }
2094
2993
 
2994
+ // src/commands/update.ts
2995
+ import { Command as Command10 } from "commander";
2996
+
2997
+ // src/utils/update-checker.ts
2998
+ import updateNotifier from "update-notifier";
2999
+ import semver from "semver";
3000
+ import { execa as execa3 } from "execa";
3001
+ import { logger as logger10 } from "@a3t/rapid-core";
3002
+ import chalk from "chalk";
3003
+ import { readFileSync, existsSync as existsSync2 } from "fs";
3004
+ import { fileURLToPath as fileURLToPath2 } from "url";
3005
+ import { dirname as dirname3, join as join6 } from "path";
3006
+ import prompts from "prompts";
3007
+ var __dirname = dirname3(fileURLToPath2(import.meta.url));
3008
+ function loadPackageJson() {
3009
+ const paths = [
3010
+ join6(__dirname, "../package.json"),
3011
+ // bundled: dist/ -> package root
3012
+ join6(__dirname, "../../package.json")
3013
+ // source: src/utils/ -> package root
3014
+ ];
3015
+ for (const p of paths) {
3016
+ if (existsSync2(p)) {
3017
+ return JSON.parse(readFileSync(p, "utf-8"));
3018
+ }
3019
+ }
3020
+ return { name: "@a3t/rapid", version: "0.0.0" };
3021
+ }
3022
+ var packageJson = loadPackageJson();
3023
+ var UpdateChecker = class {
3024
+ notifier;
3025
+ packageName = packageJson.name;
3026
+ constructor() {
3027
+ this.notifier = updateNotifier({
3028
+ pkg: packageJson,
3029
+ updateCheckInterval: 1e3 * 60 * 60 * 24,
3030
+ // Check daily
3031
+ shouldNotifyInNpmScript: true
3032
+ });
3033
+ }
3034
+ /**
3035
+ * Check if an update is available
3036
+ */
3037
+ hasUpdate() {
3038
+ return !!this.notifier.update;
3039
+ }
3040
+ /**
3041
+ * Get update information
3042
+ */
3043
+ getUpdateInfo() {
3044
+ if (!this.notifier.update) return null;
3045
+ return {
3046
+ current: this.notifier.update.current,
3047
+ latest: this.notifier.update.latest,
3048
+ type: this.getUpdateType(this.notifier.update.current, this.notifier.update.latest)
3049
+ };
3050
+ }
3051
+ /**
3052
+ * Determine the type of update (major, minor, patch)
3053
+ */
3054
+ getUpdateType(current, latest) {
3055
+ const diff = semver.diff(current, latest);
3056
+ if (diff === "premajor" || diff === "preminor" || diff === "prepatch") {
3057
+ return "prerelease";
3058
+ }
3059
+ return diff || "patch";
3060
+ }
3061
+ /**
3062
+ * Show update notification
3063
+ */
3064
+ showNotification() {
3065
+ if (!this.notifier.update) return;
3066
+ const { current, latest } = this.notifier.update;
3067
+ const updateType = this.getUpdateType(current, latest);
3068
+ logger10.info(`Update available: ${logger10.dim(current)} \u2192 ${chalk.green(latest)}`);
3069
+ if (updateType === "major") {
3070
+ logger10.warn("This is a major version update with breaking changes.");
3071
+ }
3072
+ }
3073
+ /**
3074
+ * Verify package signatures using npm audit signatures
3075
+ */
3076
+ async verifySignatures() {
3077
+ try {
3078
+ logger10.info("Verifying package signatures...");
3079
+ const result = await execa3("npm", ["audit", "signatures"], {
3080
+ reject: false
3081
+ });
3082
+ if (result.exitCode === 0) {
3083
+ logger10.success("Package signatures verified successfully");
3084
+ return true;
3085
+ } else {
3086
+ logger10.warn("Package signature verification returned warnings");
3087
+ logger10.debug(result.stdout || result.stderr);
3088
+ return true;
3089
+ }
3090
+ } catch {
3091
+ logger10.debug("Signature verification not available (requires npm >= 9)");
3092
+ return true;
3093
+ }
3094
+ }
3095
+ /**
3096
+ * Perform the update with signature verification
3097
+ */
3098
+ async performUpdate() {
3099
+ try {
3100
+ logger10.info("Updating RAPID CLI...");
3101
+ await execa3("npm", ["install", "-g", `${this.packageName}@latest`], {
3102
+ stdio: "inherit"
3103
+ });
3104
+ await this.verifySignatures();
3105
+ logger10.success("RAPID CLI updated successfully!");
3106
+ logger10.info("Package published with npm provenance - cryptographically verified");
3107
+ return true;
3108
+ } catch (error) {
3109
+ logger10.error("Failed to update RAPID CLI:", error);
3110
+ return false;
3111
+ }
3112
+ }
3113
+ /**
3114
+ * Check for updates and handle them according to version type
3115
+ */
3116
+ async checkAndUpdate() {
3117
+ if (!this.hasUpdate()) return;
3118
+ const updateInfo = this.getUpdateInfo();
3119
+ if (!updateInfo) return;
3120
+ this.showNotification();
3121
+ if (updateInfo.type === "major") {
3122
+ logger10.warn(
3123
+ `This is a major version update (${updateInfo.current} \u2192 ${updateInfo.latest}) that may contain breaking changes.`
3124
+ );
3125
+ try {
3126
+ const response = await prompts({
3127
+ type: "confirm",
3128
+ name: "shouldUpdate",
3129
+ message: "Would you like to update to this major version?",
3130
+ initial: false
3131
+ });
3132
+ if (response.shouldUpdate) {
3133
+ logger10.info(`Updating to ${updateInfo.latest} (major version)...`);
3134
+ await this.performUpdate();
3135
+ } else {
3136
+ logger10.info("Skipping major version update.");
3137
+ logger10.info('You can update later with "rapid update --force"');
3138
+ }
3139
+ } catch {
3140
+ logger10.info(
3141
+ 'Run "rapid update" to update manually, or use "rapid update --force" to update automatically.'
3142
+ );
3143
+ }
3144
+ return;
3145
+ }
3146
+ logger10.info(`Auto-updating to ${updateInfo.latest} (${updateInfo.type} version)...`);
3147
+ await this.performUpdate();
3148
+ }
3149
+ /**
3150
+ * Force update regardless of version type
3151
+ */
3152
+ async forceUpdate() {
3153
+ if (!this.hasUpdate()) {
3154
+ logger10.info("No updates available.");
3155
+ return;
3156
+ }
3157
+ const updateInfo = this.getUpdateInfo();
3158
+ if (updateInfo) {
3159
+ this.showNotification();
3160
+ }
3161
+ await this.performUpdate();
3162
+ }
3163
+ };
3164
+ var updateChecker = new UpdateChecker();
3165
+
3166
+ // src/commands/update.ts
3167
+ import { logger as logger11 } from "@a3t/rapid-core";
3168
+ var updateCommand = new Command10("update").description("Check for and apply updates").option("--check", "Check for updates only").option("--force", "Force update even for major versions").action(async (options) => {
3169
+ try {
3170
+ if (options.check) {
3171
+ logger11.header("Checking for updates...");
3172
+ if (!updateChecker.hasUpdate()) {
3173
+ logger11.success("You are using the latest version!");
3174
+ return;
3175
+ }
3176
+ const updateInfo2 = updateChecker.getUpdateInfo();
3177
+ if (updateInfo2) {
3178
+ updateChecker.showNotification();
3179
+ if (updateInfo2.type === "major") {
3180
+ logger11.warn("This is a major version update with breaking changes.");
3181
+ logger11.info('Use "rapid update --force" to update.');
3182
+ } else {
3183
+ logger11.info('Use "rapid update" to apply the update.');
3184
+ }
3185
+ }
3186
+ return;
3187
+ }
3188
+ if (!updateChecker.hasUpdate()) {
3189
+ logger11.success("You are already using the latest version!");
3190
+ return;
3191
+ }
3192
+ const updateInfo = updateChecker.getUpdateInfo();
3193
+ if (updateInfo && updateInfo.type === "major" && !options.force) {
3194
+ logger11.warn("This is a major version update with breaking changes.");
3195
+ logger11.info("Use --force to update anyway.");
3196
+ return;
3197
+ }
3198
+ await updateChecker.forceUpdate();
3199
+ } catch (error) {
3200
+ logger11.error("Update failed:", error);
3201
+ process.exit(1);
3202
+ }
3203
+ });
3204
+
3205
+ // src/commands/worktree.ts
3206
+ import { Command as Command11 } from "commander";
3207
+ import { logger as logger12 } from "@a3t/rapid-core";
3208
+ import ora9 from "ora";
3209
+ function formatWorktree(wt, currentPath) {
3210
+ const isCurrent = wt.path === currentPath;
3211
+ const marker = isCurrent ? logger12.brand("*") : " ";
3212
+ const status = [];
3213
+ if (wt.isMain) status.push("main");
3214
+ if (wt.locked) status.push("locked");
3215
+ if (wt.prunable) status.push("prunable");
3216
+ if (!wt.exists) status.push("missing");
3217
+ const statusStr = status.length > 0 ? logger12.dim(` (${status.join(", ")})`) : "";
3218
+ const branchStr = wt.branch ? logger12.brand(wt.branch) : logger12.dim("detached");
3219
+ const headShort = wt.head?.substring(0, 7) ?? "";
3220
+ return `${marker} ${branchStr}${statusStr}
3221
+ ${logger12.dim(wt.path)}
3222
+ ${logger12.dim(`HEAD: ${headShort}`)}`;
3223
+ }
3224
+ var listCommand = new Command11("list").alias("ls").description("List all git worktrees").option("--json", "Output as JSON").action(async (options) => {
3225
+ try {
3226
+ const cwd = process.cwd();
3227
+ if (!await isGitRepo(cwd)) {
3228
+ logger12.error("Not a git repository");
3229
+ process.exit(1);
3230
+ }
3231
+ const gitRoot = await getGitRoot(cwd);
3232
+ const worktrees = await listWorktrees(gitRoot);
3233
+ if (options.json) {
3234
+ console.log(JSON.stringify(worktrees, null, 2));
3235
+ return;
3236
+ }
3237
+ if (worktrees.length === 0) {
3238
+ logger12.info("No worktrees found");
3239
+ return;
3240
+ }
3241
+ logger12.header("Git Worktrees");
3242
+ console.log();
3243
+ for (const wt of worktrees) {
3244
+ console.log(formatWorktree(wt, gitRoot));
3245
+ console.log();
3246
+ }
3247
+ const prunable = worktrees.filter((wt) => wt.prunable);
3248
+ if (prunable.length > 0) {
3249
+ logger12.warn(`${prunable.length} worktree(s) can be pruned. Run: rapid worktree prune`);
3250
+ }
3251
+ } catch (error) {
3252
+ logger12.error(error instanceof Error ? error.message : String(error));
3253
+ process.exit(1);
3254
+ }
3255
+ });
3256
+ var pruneCommand = new Command11("prune").description("Remove stale worktree references").option("--dry-run", "Show what would be pruned without removing").action(async (options) => {
3257
+ const spinner = ora9("Checking worktrees...").start();
3258
+ try {
3259
+ const cwd = process.cwd();
3260
+ if (!await isGitRepo(cwd)) {
3261
+ spinner.fail("Not a git repository");
3262
+ process.exit(1);
3263
+ }
3264
+ const gitRoot = await getGitRoot(cwd);
3265
+ const worktrees = await listWorktrees(gitRoot);
3266
+ const prunable = worktrees.filter((wt) => wt.prunable);
3267
+ if (prunable.length === 0) {
3268
+ spinner.succeed("No stale worktrees to prune");
3269
+ return;
3270
+ }
3271
+ if (options.dryRun) {
3272
+ spinner.info(`Would prune ${prunable.length} worktree(s):`);
3273
+ for (const wt of prunable) {
3274
+ console.log(` ${logger12.dim("\u2022")} ${wt.path}`);
3275
+ }
3276
+ return;
3277
+ }
3278
+ spinner.text = `Pruning ${prunable.length} worktree(s)...`;
3279
+ const result = await pruneWorktrees(gitRoot);
3280
+ if (result.success) {
3281
+ spinner.succeed(`Pruned ${result.pruned.length} worktree(s)`);
3282
+ for (const path of result.pruned) {
3283
+ console.log(` ${logger12.dim("\u2022")} ${path}`);
3284
+ }
3285
+ } else {
3286
+ spinner.fail(`Failed to prune: ${result.error}`);
3287
+ process.exit(1);
3288
+ }
3289
+ } catch (error) {
3290
+ spinner.fail(error instanceof Error ? error.message : String(error));
3291
+ process.exit(1);
3292
+ }
3293
+ });
3294
+ var removeCommand = new Command11("remove").alias("rm").description("Remove a worktree").argument("<path-or-branch>", "Worktree path or branch name").option("-f, --force", "Force removal even if worktree is dirty").action(async (pathOrBranch, options) => {
3295
+ const spinner = ora9("Finding worktree...").start();
3296
+ try {
3297
+ const cwd = process.cwd();
3298
+ if (!await isGitRepo(cwd)) {
3299
+ spinner.fail("Not a git repository");
3300
+ process.exit(1);
3301
+ }
3302
+ const gitRoot = await getGitRoot(cwd);
3303
+ const worktrees = await listWorktrees(gitRoot);
3304
+ const worktree = worktrees.find(
3305
+ (wt) => wt.path === pathOrBranch || wt.path.endsWith(pathOrBranch) || wt.branch === pathOrBranch
3306
+ );
3307
+ if (!worktree) {
3308
+ spinner.fail(`Worktree not found: ${pathOrBranch}`);
3309
+ logger12.info("Available worktrees:");
3310
+ for (const wt of worktrees) {
3311
+ console.log(` ${wt.branch || wt.path}`);
3312
+ }
3313
+ process.exit(1);
3314
+ }
3315
+ if (worktree.isMain) {
3316
+ spinner.fail("Cannot remove the main worktree");
3317
+ process.exit(1);
3318
+ }
3319
+ if (worktree.locked && !options.force) {
3320
+ spinner.fail("Worktree is locked. Use --force to remove anyway.");
3321
+ process.exit(1);
3322
+ }
3323
+ spinner.text = `Removing worktree: ${worktree.path}...`;
3324
+ const result = await removeWorktree(gitRoot, worktree.path, { force: options.force });
3325
+ if (result.success) {
3326
+ spinner.succeed(`Removed worktree: ${worktree.path}`);
3327
+ } else {
3328
+ spinner.fail(`Failed to remove: ${result.error}`);
3329
+ process.exit(1);
3330
+ }
3331
+ } catch (error) {
3332
+ spinner.fail(error instanceof Error ? error.message : String(error));
3333
+ process.exit(1);
3334
+ }
3335
+ });
3336
+ var cleanupCommand = new Command11("cleanup").description("Remove worktrees for branches that have been merged").option("--dry-run", "Show what would be removed without removing").action(async (options) => {
3337
+ const spinner = ora9("Analyzing worktrees...").start();
3338
+ try {
3339
+ const cwd = process.cwd();
3340
+ if (!await isGitRepo(cwd)) {
3341
+ spinner.fail("Not a git repository");
3342
+ process.exit(1);
3343
+ }
3344
+ const gitRoot = await getGitRoot(cwd);
3345
+ if (options.dryRun) {
3346
+ const worktrees = await listWorktrees(gitRoot);
3347
+ spinner.info("Dry run - would remove worktrees for merged branches");
3348
+ const nonMain = worktrees.filter((wt) => !wt.isMain && wt.branch);
3349
+ if (nonMain.length === 0) {
3350
+ console.log(" No feature branch worktrees found");
3351
+ } else {
3352
+ console.log(" Feature branch worktrees:");
3353
+ for (const wt of nonMain) {
3354
+ console.log(` ${logger12.dim("\u2022")} ${wt.branch} - ${wt.path}`);
3355
+ }
3356
+ console.log();
3357
+ logger12.info("Run without --dry-run to remove worktrees for merged branches");
3358
+ }
3359
+ return;
3360
+ }
3361
+ spinner.text = "Removing worktrees for merged branches...";
3362
+ const result = await cleanupMergedWorktrees(gitRoot);
3363
+ if (result.removed.length === 0) {
3364
+ spinner.succeed("No worktrees to clean up");
3365
+ return;
3366
+ }
3367
+ spinner.succeed(`Cleaned up ${result.removed.length} worktree(s)`);
3368
+ for (const path of result.removed) {
3369
+ console.log(` ${logger12.dim("\u2022")} ${path}`);
3370
+ }
3371
+ if (result.errors.length > 0) {
3372
+ console.log();
3373
+ logger12.warn("Some worktrees could not be removed:");
3374
+ for (const err of result.errors) {
3375
+ console.log(` ${logger12.dim("\u2022")} ${err}`);
3376
+ }
3377
+ }
3378
+ } catch (error) {
3379
+ spinner.fail(error instanceof Error ? error.message : String(error));
3380
+ process.exit(1);
3381
+ }
3382
+ });
3383
+ var worktreeCommand = new Command11("worktree").alias("wt").description("Manage git worktrees for isolated development").addCommand(listCommand).addCommand(pruneCommand).addCommand(removeCommand).addCommand(cleanupCommand);
3384
+ worktreeCommand.action(async () => {
3385
+ await listCommand.parseAsync([], { from: "user" });
3386
+ });
3387
+
3388
+ // src/commands/lima.ts
3389
+ import { Command as Command12 } from "commander";
3390
+ import { logger as logger13 } from "@a3t/rapid-core";
3391
+ import ora10 from "ora";
3392
+ async function checkLimaAvailable() {
3393
+ if (!isMacOS()) {
3394
+ logger13.error("Lima is only available on macOS");
3395
+ return false;
3396
+ }
3397
+ if (!await hasLima()) {
3398
+ logger13.error("Lima is not installed");
3399
+ logger13.blank();
3400
+ logger13.info("Install Lima with:");
3401
+ console.log(` ${logger13.dim("$")} brew install lima`);
3402
+ logger13.blank();
3403
+ logger13.info("For more information: https://lima-vm.io");
3404
+ return false;
3405
+ }
3406
+ return true;
3407
+ }
3408
+ var statusCommand2 = new Command12("status").description("Show Lima VM status").option("--json", "Output as JSON").action(async (options) => {
3409
+ if (!await checkLimaAvailable()) {
3410
+ process.exit(1);
3411
+ }
3412
+ const instance = await getInstance();
3413
+ if (options.json) {
3414
+ console.log(JSON.stringify(instance, null, 2));
3415
+ return;
3416
+ }
3417
+ if (!instance) {
3418
+ logger13.info(`Lima VM (${RAPID_LIMA_INSTANCE}) is not created`);
3419
+ logger13.blank();
3420
+ logger13.info("Start the VM with:");
3421
+ console.log(` ${logger13.dim("$")} rapid lima start`);
3422
+ logger13.blank();
3423
+ logger13.info("Or use:");
3424
+ console.log(` ${logger13.dim("$")} rapid dev --local`);
3425
+ return;
3426
+ }
3427
+ logger13.header("Lima VM Status");
3428
+ console.log();
3429
+ console.log(` ${logger13.dim("Name:")} ${instance.name}`);
3430
+ console.log(
3431
+ ` ${logger13.dim("Status:")} ${instance.status === "Running" ? logger13.brand(instance.status) : instance.status}`
3432
+ );
3433
+ console.log(` ${logger13.dim("Arch:")} ${instance.arch}`);
3434
+ console.log(` ${logger13.dim("CPUs:")} ${instance.cpus}`);
3435
+ console.log(` ${logger13.dim("Memory:")} ${instance.memory}`);
3436
+ console.log(` ${logger13.dim("Disk:")} ${instance.disk}`);
3437
+ if (instance.sshLocalPort) {
3438
+ console.log(` ${logger13.dim("SSH Port:")} ${instance.sshLocalPort}`);
3439
+ }
3440
+ console.log();
3441
+ if (instance.status === "Running") {
3442
+ logger13.info("To open a shell:");
3443
+ console.log(` ${logger13.dim("$")} rapid lima shell`);
3444
+ } else {
3445
+ logger13.info("To start the VM:");
3446
+ console.log(` ${logger13.dim("$")} rapid lima start`);
3447
+ }
3448
+ console.log();
3449
+ });
3450
+ var startCommand2 = new Command12("start").description("Start the Lima VM").option("--cpus <n>", "Number of CPUs", "4").option("--memory <size>", "Memory size", "8GiB").option("--disk <size>", "Disk size", "50GiB").action(async (options) => {
3451
+ if (!await checkLimaAvailable()) {
3452
+ process.exit(1);
3453
+ }
3454
+ const spinner = ora10("Starting Lima VM...").start();
3455
+ const projectDir = process.cwd();
3456
+ const result = await startInstance(projectDir, {
3457
+ cpus: parseInt(options.cpus, 10),
3458
+ memory: options.memory,
3459
+ disk: options.disk,
3460
+ timeout: 600
3461
+ });
3462
+ if (!result.success) {
3463
+ spinner.fail("Failed to start Lima VM");
3464
+ logger13.error(result.error ?? "Unknown error");
3465
+ process.exit(1);
3466
+ }
3467
+ spinner.succeed("Lima VM started");
3468
+ logger13.blank();
3469
+ const sshSpinner = ora10("Checking SSH agent forwarding...").start();
3470
+ const sshResult = await setupGitSsh();
3471
+ if (sshResult.success) {
3472
+ sshSpinner.succeed("SSH agent forwarding is working");
3473
+ } else {
3474
+ sshSpinner.warn("SSH agent forwarding may not be working");
3475
+ logger13.dim(sshResult.error ?? "Make sure ssh-agent is running on the host");
3476
+ }
3477
+ logger13.blank();
3478
+ logger13.info("To open a shell:");
3479
+ console.log(` ${logger13.dim("$")} rapid lima shell`);
3480
+ console.log();
3481
+ });
3482
+ var stopCommand2 = new Command12("stop").description("Stop the Lima VM").option("-f, --force", "Force stop").action(async (options) => {
3483
+ if (!await checkLimaAvailable()) {
3484
+ process.exit(1);
3485
+ }
3486
+ const instance = await getInstance();
3487
+ if (!instance) {
3488
+ logger13.info("Lima VM is not created");
3489
+ return;
3490
+ }
3491
+ if (instance.status !== "Running") {
3492
+ logger13.info("Lima VM is already stopped");
3493
+ return;
3494
+ }
3495
+ const spinner = ora10("Stopping Lima VM...").start();
3496
+ const result = await stopInstance(RAPID_LIMA_INSTANCE, {
3497
+ force: options.force
3498
+ });
3499
+ if (!result.success) {
3500
+ spinner.fail("Failed to stop Lima VM");
3501
+ logger13.error(result.error ?? "Unknown error");
3502
+ process.exit(1);
3503
+ }
3504
+ spinner.succeed("Lima VM stopped");
3505
+ });
3506
+ var shellCommand = new Command12("shell").description("Open a shell in the Lima VM").option("-c, --command <cmd>", "Command to run instead of interactive shell").action(async (options) => {
3507
+ if (!await checkLimaAvailable()) {
3508
+ process.exit(1);
3509
+ }
3510
+ const instance = await getInstance();
3511
+ if (!instance || instance.status !== "Running") {
3512
+ logger13.error("Lima VM is not running");
3513
+ logger13.info("Start with: rapid lima start");
3514
+ process.exit(1);
3515
+ }
3516
+ await shellInLima({
3517
+ cwd: process.cwd(),
3518
+ command: options.command
3519
+ });
3520
+ });
3521
+ var deleteCommand = new Command12("delete").description("Delete the Lima VM").option("-f, --force", "Force delete without confirmation").action(async (options) => {
3522
+ if (!await checkLimaAvailable()) {
3523
+ process.exit(1);
3524
+ }
3525
+ const instance = await getInstance();
3526
+ if (!instance) {
3527
+ logger13.info("Lima VM does not exist");
3528
+ return;
3529
+ }
3530
+ if (!options.force) {
3531
+ logger13.warn("This will permanently delete the Lima VM and all its data.");
3532
+ logger13.info(`Use ${logger13.brand("--force")} to confirm deletion.`);
3533
+ return;
3534
+ }
3535
+ const spinner = ora10("Deleting Lima VM...").start();
3536
+ const result = await deleteInstance(RAPID_LIMA_INSTANCE, { force: true });
3537
+ if (!result.success) {
3538
+ spinner.fail("Failed to delete Lima VM");
3539
+ logger13.error(result.error ?? "Unknown error");
3540
+ process.exit(1);
3541
+ }
3542
+ spinner.succeed("Lima VM deleted");
3543
+ });
3544
+ var listCommand2 = new Command12("list").alias("ls").description("List all Lima instances").option("--json", "Output as JSON").action(async (options) => {
3545
+ if (!await checkLimaAvailable()) {
3546
+ process.exit(1);
3547
+ }
3548
+ const instances = await listInstances();
3549
+ if (options.json) {
3550
+ console.log(JSON.stringify(instances, null, 2));
3551
+ return;
3552
+ }
3553
+ if (instances.length === 0) {
3554
+ logger13.info("No Lima instances found");
3555
+ return;
3556
+ }
3557
+ logger13.header("Lima Instances");
3558
+ console.log();
3559
+ for (const inst of instances) {
3560
+ const isRapid = inst.name === RAPID_LIMA_INSTANCE;
3561
+ const statusColor = inst.status === "Running" ? logger13.brand : logger13.dim;
3562
+ console.log(
3563
+ ` ${isRapid ? logger13.brand("*") : " "} ${inst.name} ${statusColor(`(${inst.status})`)}`
3564
+ );
3565
+ console.log(` ${logger13.dim(`${inst.cpus} CPUs, ${inst.memory}, ${inst.disk}`)}`);
3566
+ }
3567
+ console.log();
3568
+ });
3569
+ var limaCommand = new Command12("lima").description("Manage Lima VM for local development (macOS)").addCommand(statusCommand2).addCommand(startCommand2).addCommand(stopCommand2).addCommand(shellCommand).addCommand(deleteCommand).addCommand(listCommand2);
3570
+ limaCommand.action(async () => {
3571
+ await statusCommand2.parseAsync([], { from: "user" });
3572
+ });
3573
+
2095
3574
  // src/index.ts
2096
- var __dirname = dirname(fileURLToPath(import.meta.url));
2097
- var packageJson = JSON.parse(readFileSync(join4(__dirname, "../package.json"), "utf-8"));
2098
- var VERSION = packageJson.version;
2099
- var program = new Command10();
2100
- program.name("rapid").description("AI-assisted development with dev containers").version(VERSION, "-v, --version", "Show version").option("--verbose", "Verbose output").option("-q, --quiet", "Minimal output").option("--config <path>", "Path to rapid.json").hook("preAction", (thisCommand) => {
3575
+ var __dirname2 = dirname4(fileURLToPath3(import.meta.url));
3576
+ var packageJson2 = JSON.parse(readFileSync2(join7(__dirname2, "../package.json"), "utf-8"));
3577
+ var VERSION = packageJson2.version;
3578
+ var program = new Command13();
3579
+ program.name("rapid").description("AI-assisted development with dev containers").version(VERSION, "-v, --version", "Show version").option("--verbose", "Verbose output").option("-q, --quiet", "Minimal output").option("--config <path>", "Path to rapid.json").hook("preAction", async (thisCommand) => {
2101
3580
  const opts = thisCommand.opts();
2102
3581
  if (opts.verbose) {
2103
3582
  setLogLevel("debug");
2104
3583
  } else if (opts.quiet) {
2105
3584
  setLogLevel("error");
2106
3585
  }
3586
+ if (thisCommand.name() === "update" || thisCommand.name() === "version") {
3587
+ return;
3588
+ }
3589
+ try {
3590
+ await updateChecker.checkAndUpdate();
3591
+ } catch (error) {
3592
+ logger14.debug("Update check failed:", error);
3593
+ }
2107
3594
  });
2108
3595
  program.addCommand(initCommand);
2109
3596
  program.addCommand(startCommand);
@@ -2114,10 +3601,13 @@ program.addCommand(agentCommand);
2114
3601
  program.addCommand(secretsCommand);
2115
3602
  program.addCommand(authCommand);
2116
3603
  program.addCommand(mcpCommand);
3604
+ program.addCommand(updateCommand);
3605
+ program.addCommand(worktreeCommand);
3606
+ program.addCommand(limaCommand);
2117
3607
  program.action(() => {
2118
3608
  console.log();
2119
- console.log(` ${logger10.brand("RAPID")} ${logger10.dim(`v${VERSION}`)}`);
2120
- console.log(` ${logger10.dim("AI-assisted development with dev containers")}`);
3609
+ console.log(` ${logger14.brand("RAPID")} ${logger14.dim(`v${VERSION}`)}`);
3610
+ console.log(` ${logger14.dim("AI-assisted development with dev containers")}`);
2121
3611
  console.log();
2122
3612
  program.help();
2123
3613
  });
@@ -2125,4 +3615,4 @@ program.action(() => {
2125
3615
  export {
2126
3616
  program
2127
3617
  };
2128
- //# sourceMappingURL=chunk-FICHP3SD.js.map
3618
+ //# sourceMappingURL=chunk-VWXN2TG5.js.map