bamboo-agents 0.1.5-dev.38.aeaecba → 0.1.5-dev.40.51dbc4d

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/dist/index.js CHANGED
@@ -3037,7 +3037,7 @@ var VERSION;
3037
3037
  var init_version = __esm({
3038
3038
  "src/version.ts"() {
3039
3039
  "use strict";
3040
- VERSION = "0.1.5-dev.38.aeaecba";
3040
+ VERSION = "0.1.5-dev.40.51dbc4d";
3041
3041
  }
3042
3042
  });
3043
3043
 
@@ -7351,6 +7351,234 @@ var init_state = __esm({
7351
7351
  }
7352
7352
  });
7353
7353
 
7354
+ // src/lib/git.ts
7355
+ var git_exports = {};
7356
+ __export(git_exports, {
7357
+ GitError: () => GitError,
7358
+ checkGitCredentialForGitHub: () => checkGitCredentialForGitHub,
7359
+ cloneRepo: () => cloneRepo,
7360
+ getGitConfig: () => getGitConfig,
7361
+ getRepoRemoteUrl: () => getRepoRemoteUrl,
7362
+ gitPullFFOnly: () => gitPullFFOnly,
7363
+ gitVersion: () => gitVersion,
7364
+ installGithubCredential: () => installGithubCredential,
7365
+ isGitRecentEnough: () => isGitRecentEnough,
7366
+ remoteUrlMatchesRepo: () => remoteUrlMatchesRepo
7367
+ });
7368
+ import { execFile } from "node:child_process";
7369
+ import { promisify } from "node:util";
7370
+ async function gitVersion() {
7371
+ try {
7372
+ const { stdout } = await execFileP("git", ["--version"], { encoding: "utf8" });
7373
+ const m = stdout.match(/git version (\d+)\.(\d+)\.(\d+)/);
7374
+ if (!m) return null;
7375
+ return [Number(m[1]), Number(m[2]), Number(m[3])];
7376
+ } catch (err) {
7377
+ if (err.code === "ENOENT") return null;
7378
+ throw err;
7379
+ }
7380
+ }
7381
+ function isGitRecentEnough(version) {
7382
+ const [major, minor] = version;
7383
+ return major > 2 || major === 2 && minor >= 11;
7384
+ }
7385
+ async function installGithubCredential(token) {
7386
+ const input = `protocol=https
7387
+ host=github.com
7388
+ username=x-access-token
7389
+ password=${token}
7390
+
7391
+ `;
7392
+ const child = execFile("git", ["credential", "approve"], { encoding: "utf8" });
7393
+ const proc = child;
7394
+ proc.stdin?.write(input);
7395
+ proc.stdin?.end();
7396
+ await new Promise((resolve2, reject) => {
7397
+ proc.on("exit", (code) => {
7398
+ if (code === 0) resolve2();
7399
+ else reject(new GitError(`git credential approve exited with code ${code}`));
7400
+ });
7401
+ proc.on("error", reject);
7402
+ });
7403
+ }
7404
+ async function cloneRepo(repoFullName, targetDir) {
7405
+ const url = `https://github.com/${repoFullName}.git`;
7406
+ try {
7407
+ await execFileP("git", ["clone", url, targetDir], { encoding: "utf8" });
7408
+ } catch (err) {
7409
+ const errAny = err;
7410
+ throw new GitError(
7411
+ `git clone failed: ${errAny.stderr ?? errAny.message}`,
7412
+ errAny.stdout,
7413
+ errAny.stderr
7414
+ );
7415
+ }
7416
+ }
7417
+ async function checkGitCredentialForGitHub() {
7418
+ return new Promise((resolve2) => {
7419
+ const proc = execFile(
7420
+ "git",
7421
+ ["credential", "fill"],
7422
+ {
7423
+ encoding: "utf8",
7424
+ env: { ...process.env, GIT_TERMINAL_PROMPT: "0" }
7425
+ },
7426
+ (err, stdout) => {
7427
+ if (err) {
7428
+ resolve2(false);
7429
+ return;
7430
+ }
7431
+ const hasOurUsername = /^username=x-access-token\s*$/m.test(stdout);
7432
+ const hasPassword = /^password=\S+/m.test(stdout);
7433
+ resolve2(hasOurUsername && hasPassword);
7434
+ }
7435
+ );
7436
+ proc.stdin?.write("protocol=https\nhost=github.com\n\n");
7437
+ proc.stdin?.end();
7438
+ });
7439
+ }
7440
+ async function getRepoRemoteUrl(repoPath, remoteName = "origin") {
7441
+ try {
7442
+ const { stdout } = await execFileP(
7443
+ "git",
7444
+ ["-C", repoPath, "remote", "get-url", remoteName],
7445
+ { encoding: "utf8" }
7446
+ );
7447
+ return stdout.trim() || null;
7448
+ } catch {
7449
+ return null;
7450
+ }
7451
+ }
7452
+ function remoteUrlMatchesRepo(remoteUrl, repoFullName) {
7453
+ const expected = repoFullName.replace(/\.git$/i, "").toLowerCase();
7454
+ const url = remoteUrl.trim().replace(/\.git$/i, "");
7455
+ const httpsMatch = url.match(/^https?:\/\/[^/]*github\.com\/(.+)$/i);
7456
+ if (httpsMatch && httpsMatch[1].toLowerCase() === expected) return true;
7457
+ const sshMatch = url.match(/^[^@]+@github\.com:(.+)$/i);
7458
+ if (sshMatch && sshMatch[1].toLowerCase() === expected) return true;
7459
+ return false;
7460
+ }
7461
+ async function gitPullFFOnly(repoPath) {
7462
+ try {
7463
+ await execFileP("git", ["-C", repoPath, "pull", "--ff-only"], {
7464
+ encoding: "utf8"
7465
+ });
7466
+ } catch (err) {
7467
+ const errAny = err;
7468
+ const stderr = (errAny.stderr ?? "").toLowerCase();
7469
+ let summary;
7470
+ if (stderr.includes("non-fast-forward") || stderr.includes("not possible to fast-forward")) {
7471
+ summary = "local branch has diverged from origin \u2014 commit or `save-bamboo` first, then retry";
7472
+ } else if (stderr.includes("uncommitted") || stderr.includes("would be overwritten")) {
7473
+ summary = "uncommitted changes block fast-forward \u2014 commit or `save-bamboo` first, then retry";
7474
+ } else {
7475
+ summary = (errAny.stderr ?? errAny.message).trim().split("\n")[0] ?? errAny.message;
7476
+ }
7477
+ throw new GitError(summary, errAny.stdout, errAny.stderr);
7478
+ }
7479
+ }
7480
+ async function getGitConfig(key) {
7481
+ try {
7482
+ const { stdout } = await execFileP("git", ["config", "--global", "--get", key], {
7483
+ encoding: "utf8"
7484
+ });
7485
+ return stdout.trim() || null;
7486
+ } catch (err) {
7487
+ if (err.code === 1) return null;
7488
+ throw err;
7489
+ }
7490
+ }
7491
+ var execFileP, GitError;
7492
+ var init_git = __esm({
7493
+ "src/lib/git.ts"() {
7494
+ "use strict";
7495
+ execFileP = promisify(execFile);
7496
+ GitError = class extends Error {
7497
+ constructor(message, stdout, stderr) {
7498
+ super(message);
7499
+ this.stdout = stdout;
7500
+ this.stderr = stderr;
7501
+ this.name = "GitError";
7502
+ }
7503
+ };
7504
+ }
7505
+ });
7506
+
7507
+ // src/lib/workspace.ts
7508
+ import { existsSync } from "node:fs";
7509
+ import os from "node:os";
7510
+ import { resolve as pathResolve } from "node:path";
7511
+ function defaultClonePath(orgSlug) {
7512
+ const cleanSlug = orgSlug.replace(/^bamboo-?/i, "") || orgSlug;
7513
+ return pathResolve(os.homedir(), "Bamboo", cleanSlug);
7514
+ }
7515
+ async function resolveWorkspace() {
7516
+ const state = await readState();
7517
+ if (state) {
7518
+ if (!existsSync(state.workspace_path)) {
7519
+ throw new NoWorkspaceError(
7520
+ `Bamboo workspace not found.
7521
+ (State recorded ${state.workspace_path} but it's missing on disk \u2014 run \`bamboo-agents init --reset\` to re-clone.)`
7522
+ );
7523
+ }
7524
+ return { path: state.workspace_path, orgId: state.org_id };
7525
+ }
7526
+ const config = await readConfig();
7527
+ if (config) {
7528
+ if (!existsSync(config.repo_path)) {
7529
+ throw new NoWorkspaceError(
7530
+ `Bamboo workspace not found.
7531
+ (Config recorded ${config.repo_path} but it's missing on disk \u2014 run \`bamboo-agents init --reset\` to re-clone.)`
7532
+ );
7533
+ }
7534
+ return { path: config.repo_path, orgId: config.org_id };
7535
+ }
7536
+ throw new NoWorkspaceError(
7537
+ "No Bamboo workspace yet. Run `bamboo-agents init` first."
7538
+ );
7539
+ }
7540
+ function shouldAutoSync() {
7541
+ if (process.env.BAMBOO_AUTO_SYNC === "false") return false;
7542
+ if (process.argv.includes("--no-sync")) return false;
7543
+ return true;
7544
+ }
7545
+ async function withFreshWorkspace(fn) {
7546
+ if (!shouldAutoSync()) return fn();
7547
+ let state;
7548
+ try {
7549
+ state = await readState();
7550
+ } catch {
7551
+ return fn();
7552
+ }
7553
+ if (!state) return fn();
7554
+ const lastSyncMs = new Date(state.last_sync).getTime();
7555
+ const since = Number.isFinite(lastSyncMs) ? Date.now() - lastSyncMs : Infinity;
7556
+ if (since < AUTO_SYNC_MIN_INTERVAL_MS) return fn();
7557
+ try {
7558
+ await gitPullFFOnly(state.workspace_path);
7559
+ await updateLastSync(/* @__PURE__ */ new Date());
7560
+ } catch (err) {
7561
+ const msg = err instanceof Error ? err.message : String(err);
7562
+ console.warn(`[bamboo] auto-sync warning: ${msg}`);
7563
+ }
7564
+ return fn();
7565
+ }
7566
+ var NoWorkspaceError, AUTO_SYNC_MIN_INTERVAL_MS;
7567
+ var init_workspace = __esm({
7568
+ "src/lib/workspace.ts"() {
7569
+ "use strict";
7570
+ init_git();
7571
+ init_state();
7572
+ NoWorkspaceError = class extends Error {
7573
+ constructor(message) {
7574
+ super(message);
7575
+ this.name = "NoWorkspaceError";
7576
+ }
7577
+ };
7578
+ AUTO_SYNC_MIN_INTERVAL_MS = 6e4;
7579
+ }
7580
+ });
7581
+
7354
7582
  // ../../node_modules/is-docker/index.js
7355
7583
  import fs from "node:fs";
7356
7584
  function hasDockerEnv() {
@@ -7405,7 +7633,7 @@ var init_is_inside_container = __esm({
7405
7633
 
7406
7634
  // ../../node_modules/is-wsl/index.js
7407
7635
  import process2 from "node:process";
7408
- import os from "node:os";
7636
+ import os2 from "node:os";
7409
7637
  import fs3 from "node:fs";
7410
7638
  var isWsl, is_wsl_default;
7411
7639
  var init_is_wsl = __esm({
@@ -7415,7 +7643,7 @@ var init_is_wsl = __esm({
7415
7643
  if (process2.platform !== "linux") {
7416
7644
  return false;
7417
7645
  }
7418
- if (os.release().toLowerCase().includes("microsoft")) {
7646
+ if (os2.release().toLowerCase().includes("microsoft")) {
7419
7647
  if (isInsideContainer()) {
7420
7648
  return false;
7421
7649
  }
@@ -7507,9 +7735,9 @@ var init_define_lazy_prop = __esm({
7507
7735
  });
7508
7736
 
7509
7737
  // ../../node_modules/default-browser-id/index.js
7510
- import { promisify } from "node:util";
7738
+ import { promisify as promisify2 } from "node:util";
7511
7739
  import process4 from "node:process";
7512
- import { execFile } from "node:child_process";
7740
+ import { execFile as execFile2 } from "node:child_process";
7513
7741
  async function defaultBrowserId() {
7514
7742
  if (process4.platform !== "darwin") {
7515
7743
  throw new Error("macOS only");
@@ -7525,14 +7753,14 @@ async function defaultBrowserId() {
7525
7753
  var execFileAsync;
7526
7754
  var init_default_browser_id = __esm({
7527
7755
  "../../node_modules/default-browser-id/index.js"() {
7528
- execFileAsync = promisify(execFile);
7756
+ execFileAsync = promisify2(execFile2);
7529
7757
  }
7530
7758
  });
7531
7759
 
7532
7760
  // ../../node_modules/run-applescript/index.js
7533
7761
  import process5 from "node:process";
7534
- import { promisify as promisify2 } from "node:util";
7535
- import { execFile as execFile2, execFileSync } from "node:child_process";
7762
+ import { promisify as promisify3 } from "node:util";
7763
+ import { execFile as execFile3, execFileSync } from "node:child_process";
7536
7764
  async function runAppleScript(script, { humanReadableOutput = true, signal } = {}) {
7537
7765
  if (process5.platform !== "darwin") {
7538
7766
  throw new Error("macOS only");
@@ -7548,7 +7776,7 @@ async function runAppleScript(script, { humanReadableOutput = true, signal } = {
7548
7776
  var execFileAsync2;
7549
7777
  var init_run_applescript = __esm({
7550
7778
  "../../node_modules/run-applescript/index.js"() {
7551
- execFileAsync2 = promisify2(execFile2);
7779
+ execFileAsync2 = promisify3(execFile3);
7552
7780
  }
7553
7781
  });
7554
7782
 
@@ -7564,8 +7792,8 @@ var init_bundle_name = __esm({
7564
7792
  });
7565
7793
 
7566
7794
  // ../../node_modules/default-browser/windows.js
7567
- import { promisify as promisify3 } from "node:util";
7568
- import { execFile as execFile3 } from "node:child_process";
7795
+ import { promisify as promisify4 } from "node:util";
7796
+ import { execFile as execFile4 } from "node:child_process";
7569
7797
  async function defaultBrowser(_execFileAsync = execFileAsync3) {
7570
7798
  const { stdout } = await _execFileAsync("reg", [
7571
7799
  "QUERY",
@@ -7587,7 +7815,7 @@ async function defaultBrowser(_execFileAsync = execFileAsync3) {
7587
7815
  var execFileAsync3, windowsBrowserProgIds, _windowsBrowserProgIdMap, UnknownBrowserError;
7588
7816
  var init_windows = __esm({
7589
7817
  "../../node_modules/default-browser/windows.js"() {
7590
- execFileAsync3 = promisify3(execFile3);
7818
+ execFileAsync3 = promisify4(execFile4);
7591
7819
  windowsBrowserProgIds = {
7592
7820
  MSEdgeHTM: { name: "Edge", id: "com.microsoft.edge" },
7593
7821
  // The missing `L` is correct.
@@ -7614,9 +7842,9 @@ var init_windows = __esm({
7614
7842
  });
7615
7843
 
7616
7844
  // ../../node_modules/default-browser/index.js
7617
- import { promisify as promisify4 } from "node:util";
7845
+ import { promisify as promisify5 } from "node:util";
7618
7846
  import process6 from "node:process";
7619
- import { execFile as execFile4 } from "node:child_process";
7847
+ import { execFile as execFile5 } from "node:child_process";
7620
7848
  async function defaultBrowser2() {
7621
7849
  if (process6.platform === "darwin") {
7622
7850
  const id = await defaultBrowserId();
@@ -7640,7 +7868,7 @@ var init_default_browser = __esm({
7640
7868
  init_default_browser_id();
7641
7869
  init_bundle_name();
7642
7870
  init_windows();
7643
- execFileAsync4 = promisify4(execFile4);
7871
+ execFileAsync4 = promisify5(execFile5);
7644
7872
  titleize = (string) => string.toLowerCase().replaceAll(/(?:^|\s|-)\S/g, (x) => x.toUpperCase());
7645
7873
  }
7646
7874
  });
@@ -7650,14 +7878,14 @@ import process7 from "node:process";
7650
7878
  import { Buffer as Buffer2 } from "node:buffer";
7651
7879
  import path from "node:path";
7652
7880
  import { fileURLToPath } from "node:url";
7653
- import { promisify as promisify5 } from "node:util";
7881
+ import { promisify as promisify6 } from "node:util";
7654
7882
  import childProcess from "node:child_process";
7655
7883
  import fs5, { constants as fsConstants2 } from "node:fs/promises";
7656
7884
  async function getWindowsDefaultBrowserFromWsl() {
7657
7885
  const powershellPath = await powerShellPath();
7658
7886
  const rawCommand = String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`;
7659
7887
  const encodedCommand = Buffer2.from(rawCommand, "utf16le").toString("base64");
7660
- const { stdout } = await execFile5(
7888
+ const { stdout } = await execFile6(
7661
7889
  powershellPath,
7662
7890
  [
7663
7891
  "-NoProfile",
@@ -7697,14 +7925,14 @@ function detectPlatformBinary({ [platform]: platformBinary }, { wsl }) {
7697
7925
  }
7698
7926
  return detectArchBinary(platformBinary);
7699
7927
  }
7700
- var execFile5, __dirname, localXdgOpenPath, platform, arch, pTryEach, baseOpen, open, apps, open_default;
7928
+ var execFile6, __dirname, localXdgOpenPath, platform, arch, pTryEach, baseOpen, open, apps, open_default;
7701
7929
  var init_open = __esm({
7702
7930
  "node_modules/open/index.js"() {
7703
7931
  init_wsl_utils();
7704
7932
  init_define_lazy_prop();
7705
7933
  init_default_browser();
7706
7934
  init_is_inside_container();
7707
- execFile5 = promisify5(childProcess.execFile);
7935
+ execFile6 = promisify6(childProcess.execFile);
7708
7936
  __dirname = path.dirname(fileURLToPath(import.meta.url));
7709
7937
  localXdgOpenPath = path.join(__dirname, "xdg-open");
7710
7938
  ({ platform, arch } = process7);
@@ -7854,14 +8082,14 @@ var init_open = __esm({
7854
8082
  }
7855
8083
  const subprocess = childProcess.spawn(command, cliArguments, childProcessOptions);
7856
8084
  if (options.wait) {
7857
- return new Promise((resolve, reject) => {
8085
+ return new Promise((resolve2, reject) => {
7858
8086
  subprocess.once("error", reject);
7859
8087
  subprocess.once("close", (exitCode) => {
7860
8088
  if (!options.allowNonzeroExitCode && exitCode > 0) {
7861
8089
  reject(new Error(`Exited with code ${exitCode}`));
7862
8090
  return;
7863
8091
  }
7864
- resolve(subprocess);
8092
+ resolve2(subprocess);
7865
8093
  });
7866
8094
  });
7867
8095
  }
@@ -8111,7 +8339,7 @@ var init_ansi_styles = __esm({
8111
8339
 
8112
8340
  // ../../node_modules/ora/node_modules/chalk/source/vendor/supports-color/index.js
8113
8341
  import process8 from "node:process";
8114
- import os2 from "node:os";
8342
+ import os3 from "node:os";
8115
8343
  import tty from "node:tty";
8116
8344
  function hasFlag(flag, argv = globalThis.Deno ? globalThis.Deno.args : process8.argv) {
8117
8345
  const prefix = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--";
@@ -8169,7 +8397,7 @@ function _supportsColor(haveStream, { streamIsTTY, sniffFlags = true } = {}) {
8169
8397
  return min;
8170
8398
  }
8171
8399
  if (process8.platform === "win32") {
8172
- const osRelease = os2.release().split(".");
8400
+ const osRelease = os3.release().split(".");
8173
8401
  if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
8174
8402
  return Number(osRelease[2]) >= 14931 ? 3 : 2;
8175
8403
  }
@@ -10683,7 +10911,7 @@ var init_ansi_styles2 = __esm({
10683
10911
 
10684
10912
  // ../../node_modules/log-symbols/node_modules/chalk/source/vendor/supports-color/index.js
10685
10913
  import process12 from "node:process";
10686
- import os3 from "node:os";
10914
+ import os4 from "node:os";
10687
10915
  import tty2 from "node:tty";
10688
10916
  function hasFlag2(flag, argv = globalThis.Deno ? globalThis.Deno.args : process12.argv) {
10689
10917
  const prefix = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--";
@@ -10741,7 +10969,7 @@ function _supportsColor2(haveStream, { streamIsTTY, sniffFlags = true } = {}) {
10741
10969
  return min;
10742
10970
  }
10743
10971
  if (process12.platform === "win32") {
10744
- const osRelease = os3.release().split(".");
10972
+ const osRelease = os4.release().split(".");
10745
10973
  if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
10746
10974
  return Number(osRelease[2]) >= 14931 ? 3 : 2;
10747
10975
  }
@@ -12049,7 +12277,7 @@ var init_api = __esm({
12049
12277
 
12050
12278
  // src/lib/util.ts
12051
12279
  function sleep(ms) {
12052
- return new Promise((resolve) => setTimeout(resolve, ms));
12280
+ return new Promise((resolve2) => setTimeout(resolve2, ms));
12053
12281
  }
12054
12282
  var init_util2 = __esm({
12055
12283
  "src/lib/util.ts"() {
@@ -12117,8 +12345,8 @@ async function handleMissingGithubToken(bambooSession) {
12117
12345
  async function startCallbackServer(expectedState) {
12118
12346
  let resolveSession;
12119
12347
  let rejectSession;
12120
- const session = new Promise((resolve, reject) => {
12121
- resolveSession = resolve;
12348
+ const session = new Promise((resolve2, reject) => {
12349
+ resolveSession = resolve2;
12122
12350
  rejectSession = reject;
12123
12351
  });
12124
12352
  const server = createServer((req, res) => {
@@ -12176,10 +12404,10 @@ async function startCallbackServer(expectedState) {
12176
12404
  server.close();
12177
12405
  }, LOGIN_TIMEOUT_MS);
12178
12406
  timer.unref();
12179
- const port = await new Promise((resolve, reject) => {
12407
+ const port = await new Promise((resolve2, reject) => {
12180
12408
  server.once("listening", () => {
12181
12409
  const addr = server.address();
12182
- if (addr && typeof addr === "object") resolve(addr.port);
12410
+ if (addr && typeof addr === "object") resolve2(addr.port);
12183
12411
  else reject(new Error("Couldn't bind localhost port"));
12184
12412
  });
12185
12413
  server.once("error", reject);
@@ -12311,169 +12539,48 @@ var init_login_phase = __esm({
12311
12539
  }
12312
12540
  });
12313
12541
 
12314
- // src/lib/git.ts
12315
- import { execFile as execFile6 } from "node:child_process";
12316
- import { promisify as promisify6 } from "node:util";
12317
- async function gitVersion() {
12542
+ // src/lib/prompt.ts
12543
+ import { createInterface } from "node:readline";
12544
+ async function promptStdin(question, opts = {}) {
12545
+ const maxRetries = opts.maxRetries ?? 2;
12546
+ const isInteractive2 = process.stdin.isTTY === true;
12547
+ const rl = createInterface({
12548
+ input: process.stdin,
12549
+ output: process.stdout,
12550
+ terminal: isInteractive2
12551
+ });
12552
+ const onSigInt = () => {
12553
+ rl.close();
12554
+ };
12555
+ rl.on("SIGINT", onSigInt);
12318
12556
  try {
12319
- const { stdout } = await execFileP("git", ["--version"], { encoding: "utf8" });
12320
- const m = stdout.match(/git version (\d+)\.(\d+)\.(\d+)/);
12321
- if (!m) return null;
12322
- return [Number(m[1]), Number(m[2]), Number(m[3])];
12323
- } catch (err) {
12324
- if (err.code === "ENOENT") return null;
12325
- throw err;
12557
+ let attempts = 0;
12558
+ while (attempts <= maxRetries) {
12559
+ const answer = await readOnce(rl, question);
12560
+ if (answer === null) return null;
12561
+ const trimmed = answer.trim();
12562
+ if (trimmed.length > 0) return trimmed;
12563
+ attempts += 1;
12564
+ if (attempts > maxRetries || !isInteractive2) return null;
12565
+ console.log(" (Press Enter without typing to skip \u2014 or answer Boo's question.)");
12566
+ }
12567
+ return null;
12568
+ } finally {
12569
+ rl.off("SIGINT", onSigInt);
12570
+ rl.close();
12326
12571
  }
12327
12572
  }
12328
- function isGitRecentEnough(version) {
12329
- const [major, minor] = version;
12330
- return major > 2 || major === 2 && minor >= 11;
12331
- }
12332
- async function installGithubCredential(token) {
12333
- const input = `protocol=https
12334
- host=github.com
12335
- username=x-access-token
12336
- password=${token}
12337
-
12338
- `;
12339
- const child = execFile6("git", ["credential", "approve"], { encoding: "utf8" });
12340
- const proc = child;
12341
- proc.stdin?.write(input);
12342
- proc.stdin?.end();
12343
- await new Promise((resolve, reject) => {
12344
- proc.on("exit", (code) => {
12345
- if (code === 0) resolve();
12346
- else reject(new GitError(`git credential approve exited with code ${code}`));
12347
- });
12348
- proc.on("error", reject);
12349
- });
12350
- }
12351
- async function cloneRepo(repoFullName, targetDir) {
12352
- const url = `https://github.com/${repoFullName}.git`;
12353
- try {
12354
- await execFileP("git", ["clone", url, targetDir], { encoding: "utf8" });
12355
- } catch (err) {
12356
- const errAny = err;
12357
- throw new GitError(
12358
- `git clone failed: ${errAny.stderr ?? errAny.message}`,
12359
- errAny.stdout,
12360
- errAny.stderr
12361
- );
12362
- }
12363
- }
12364
- async function checkGitCredentialForGitHub() {
12365
- return new Promise((resolve) => {
12366
- const proc = execFile6(
12367
- "git",
12368
- ["credential", "fill"],
12369
- {
12370
- encoding: "utf8",
12371
- env: { ...process.env, GIT_TERMINAL_PROMPT: "0" }
12372
- },
12373
- (err, stdout) => {
12374
- if (err) {
12375
- resolve(false);
12376
- return;
12377
- }
12378
- const hasOurUsername = /^username=x-access-token\s*$/m.test(stdout);
12379
- const hasPassword = /^password=\S+/m.test(stdout);
12380
- resolve(hasOurUsername && hasPassword);
12381
- }
12382
- );
12383
- proc.stdin?.write("protocol=https\nhost=github.com\n\n");
12384
- proc.stdin?.end();
12385
- });
12386
- }
12387
- async function getRepoRemoteUrl(repoPath, remoteName = "origin") {
12388
- try {
12389
- const { stdout } = await execFileP(
12390
- "git",
12391
- ["-C", repoPath, "remote", "get-url", remoteName],
12392
- { encoding: "utf8" }
12393
- );
12394
- return stdout.trim() || null;
12395
- } catch {
12396
- return null;
12397
- }
12398
- }
12399
- function remoteUrlMatchesRepo(remoteUrl, repoFullName) {
12400
- const expected = repoFullName.replace(/\.git$/i, "").toLowerCase();
12401
- const url = remoteUrl.trim().replace(/\.git$/i, "");
12402
- const httpsMatch = url.match(/^https?:\/\/[^/]*github\.com\/(.+)$/i);
12403
- if (httpsMatch && httpsMatch[1].toLowerCase() === expected) return true;
12404
- const sshMatch = url.match(/^[^@]+@github\.com:(.+)$/i);
12405
- if (sshMatch && sshMatch[1].toLowerCase() === expected) return true;
12406
- return false;
12407
- }
12408
- async function getGitConfig(key) {
12409
- try {
12410
- const { stdout } = await execFileP("git", ["config", "--global", "--get", key], {
12411
- encoding: "utf8"
12412
- });
12413
- return stdout.trim() || null;
12414
- } catch (err) {
12415
- if (err.code === 1) return null;
12416
- throw err;
12417
- }
12418
- }
12419
- var execFileP, GitError;
12420
- var init_git = __esm({
12421
- "src/lib/git.ts"() {
12422
- "use strict";
12423
- execFileP = promisify6(execFile6);
12424
- GitError = class extends Error {
12425
- constructor(message, stdout, stderr) {
12426
- super(message);
12427
- this.stdout = stdout;
12428
- this.stderr = stderr;
12429
- this.name = "GitError";
12430
- }
12431
- };
12432
- }
12433
- });
12434
-
12435
- // src/lib/prompt.ts
12436
- import { createInterface } from "node:readline";
12437
- async function promptStdin(question, opts = {}) {
12438
- const maxRetries = opts.maxRetries ?? 2;
12439
- const isInteractive2 = process.stdin.isTTY === true;
12440
- const rl = createInterface({
12441
- input: process.stdin,
12442
- output: process.stdout,
12443
- terminal: isInteractive2
12444
- });
12445
- const onSigInt = () => {
12446
- rl.close();
12447
- };
12448
- rl.on("SIGINT", onSigInt);
12449
- try {
12450
- let attempts = 0;
12451
- while (attempts <= maxRetries) {
12452
- const answer = await readOnce(rl, question);
12453
- if (answer === null) return null;
12454
- const trimmed = answer.trim();
12455
- if (trimmed.length > 0) return trimmed;
12456
- attempts += 1;
12457
- if (attempts > maxRetries || !isInteractive2) return null;
12458
- console.log(" (Press Enter without typing to skip \u2014 or answer Boo's question.)");
12459
- }
12460
- return null;
12461
- } finally {
12462
- rl.off("SIGINT", onSigInt);
12463
- rl.close();
12464
- }
12465
- }
12466
- function readOnce(rl, question) {
12467
- return new Promise((resolve) => {
12468
- let resolved = false;
12469
- const settle = (value) => {
12470
- if (resolved) return;
12471
- resolved = true;
12472
- resolve(value);
12473
- };
12474
- rl.once("close", () => settle(null));
12475
- rl.question(question, (answer) => settle(answer));
12476
- });
12573
+ function readOnce(rl, question) {
12574
+ return new Promise((resolve2) => {
12575
+ let resolved = false;
12576
+ const settle = (value) => {
12577
+ if (resolved) return;
12578
+ resolved = true;
12579
+ resolve2(value);
12580
+ };
12581
+ rl.once("close", () => settle(null));
12582
+ rl.question(question, (answer) => settle(answer));
12583
+ });
12477
12584
  }
12478
12585
  var init_prompt = __esm({
12479
12586
  "src/lib/prompt.ts"() {
@@ -12481,53 +12588,6 @@ var init_prompt = __esm({
12481
12588
  }
12482
12589
  });
12483
12590
 
12484
- // src/lib/workspace.ts
12485
- import { existsSync } from "node:fs";
12486
- import os4 from "node:os";
12487
- import { resolve as pathResolve } from "node:path";
12488
- function defaultClonePath(orgSlug) {
12489
- const cleanSlug = orgSlug.replace(/^bamboo-?/i, "") || orgSlug;
12490
- return pathResolve(os4.homedir(), "Bamboo", cleanSlug);
12491
- }
12492
- async function resolveWorkspace() {
12493
- const state = await readState();
12494
- if (state) {
12495
- if (!existsSync(state.workspace_path)) {
12496
- throw new NoWorkspaceError(
12497
- `Bamboo workspace not found.
12498
- (State recorded ${state.workspace_path} but it's missing on disk \u2014 run \`bamboo-agents init --reset\` to re-clone.)`
12499
- );
12500
- }
12501
- return { path: state.workspace_path, orgId: state.org_id };
12502
- }
12503
- const config = await readConfig();
12504
- if (config) {
12505
- if (!existsSync(config.repo_path)) {
12506
- throw new NoWorkspaceError(
12507
- `Bamboo workspace not found.
12508
- (Config recorded ${config.repo_path} but it's missing on disk \u2014 run \`bamboo-agents init --reset\` to re-clone.)`
12509
- );
12510
- }
12511
- return { path: config.repo_path, orgId: config.org_id };
12512
- }
12513
- throw new NoWorkspaceError(
12514
- "No Bamboo workspace yet. Run `bamboo-agents init` first."
12515
- );
12516
- }
12517
- var NoWorkspaceError;
12518
- var init_workspace = __esm({
12519
- "src/lib/workspace.ts"() {
12520
- "use strict";
12521
- init_state();
12522
- NoWorkspaceError = class extends Error {
12523
- constructor(message) {
12524
- super(message);
12525
- this.name = "NoWorkspaceError";
12526
- }
12527
- };
12528
- }
12529
- });
12530
-
12531
12591
  // src/commands/init.ts
12532
12592
  var init_exports = {};
12533
12593
  __export(init_exports, {
@@ -13274,11 +13334,11 @@ async function runUploadFlow(ctx) {
13274
13334
  console.log(" \u2026");
13275
13335
  }
13276
13336
  console.log("");
13277
- const confirm = await promptChoice(
13337
+ const confirm2 = await promptChoice(
13278
13338
  " Upload this? [y/n]: ",
13279
13339
  ["y", "n", "Y", "N"]
13280
13340
  );
13281
- if (confirm === null || confirm.toLowerCase() !== "y") return null;
13341
+ if (confirm2 === null || confirm2.toLowerCase() !== "y") return null;
13282
13342
  console.log("");
13283
13343
  const name = await promptStdin(
13284
13344
  " Name this agent (e.g. My Existing Agent): "
@@ -13777,6 +13837,9 @@ function printNeedsAction(reason) {
13777
13837
  console.error("");
13778
13838
  }
13779
13839
  async function runOrchestrator() {
13840
+ return withFreshWorkspace(async () => runOrchestratorImpl());
13841
+ }
13842
+ async function runOrchestratorImpl() {
13780
13843
  if (process.platform === "win32") {
13781
13844
  console.error("");
13782
13845
  console.error(" Bamboo CLI doesn't support native Windows yet.");
@@ -13842,6 +13905,7 @@ var init_orchestrator = __esm({
13842
13905
  "use strict";
13843
13906
  init_credentials();
13844
13907
  init_state();
13908
+ init_workspace();
13845
13909
  init_login_phase();
13846
13910
  init_provision_phase();
13847
13911
  init_clone_or_adopt_phase();
@@ -13909,35 +13973,37 @@ __export(open_exports, {
13909
13973
  runOpen: () => runOpen
13910
13974
  });
13911
13975
  async function runOpen() {
13912
- let workspacePath;
13913
- try {
13914
- workspacePath = (await resolveWorkspace()).path;
13915
- } catch (err) {
13916
- if (err instanceof NoWorkspaceError) {
13917
- console.error(err.message);
13918
- process.exit(2);
13976
+ return withFreshWorkspace(async () => {
13977
+ let workspacePath;
13978
+ try {
13979
+ workspacePath = (await resolveWorkspace()).path;
13980
+ } catch (err) {
13981
+ if (err instanceof NoWorkspaceError) {
13982
+ console.error(err.message);
13983
+ process.exit(2);
13984
+ }
13985
+ throw err;
13919
13986
  }
13920
- throw err;
13921
- }
13922
- const status = await detectClaudeDesktop();
13923
- if (status.kind === "missing") {
13924
- console.error(
13925
- `Claude Desktop isn't installed. Get it at ${DOWNLOAD_URL}, then re-run \`bamboo-agents open\`.`
13926
- );
13927
- console.error(`(Your workspace is cloned at ${workspacePath}.)`);
13928
- process.exit(1);
13929
- }
13930
- if (status.kind === "unsupported_platform") {
13931
- console.log("");
13932
- console.log(" Claude Desktop isn't available on Linux yet.");
13933
- console.log(` Your workspace is cloned at: ${workspacePath}`);
13934
- console.log("");
13935
- return;
13936
- }
13937
- const url = `claude://code/new?folder=${encodeURIComponent(workspacePath)}`;
13938
- await open_default(url);
13939
- console.log(`Opening Claude Code at ${workspacePath}\u2026`);
13940
- console.log("(Claude Desktop will ask you to trust the folder the first time.)");
13987
+ const status = await detectClaudeDesktop();
13988
+ if (status.kind === "missing") {
13989
+ console.error(
13990
+ `Claude Desktop isn't installed. Get it at ${DOWNLOAD_URL}, then re-run \`bamboo-agents open\`.`
13991
+ );
13992
+ console.error(`(Your workspace is cloned at ${workspacePath}.)`);
13993
+ process.exit(1);
13994
+ }
13995
+ if (status.kind === "unsupported_platform") {
13996
+ console.log("");
13997
+ console.log(" Claude Desktop isn't available on Linux yet.");
13998
+ console.log(` Your workspace is cloned at: ${workspacePath}`);
13999
+ console.log("");
14000
+ return;
14001
+ }
14002
+ const url = `claude://code/new?folder=${encodeURIComponent(workspacePath)}`;
14003
+ await open_default(url);
14004
+ console.log(`Opening Claude Code at ${workspacePath}\u2026`);
14005
+ console.log("(Claude Desktop will ask you to trust the folder the first time.)");
14006
+ });
13941
14007
  }
13942
14008
  var DOWNLOAD_URL;
13943
14009
  var init_open2 = __esm({
@@ -13972,44 +14038,46 @@ function formatSubscriptionLine(billing) {
13972
14038
  }
13973
14039
  }
13974
14040
  async function runStatus() {
13975
- const creds = await readCredentials();
13976
- const state = await readState().catch(() => null);
13977
- const cfg = await readConfig();
13978
- console.log("");
13979
- console.log(" Bamboo CLI status");
13980
- console.log("");
13981
- if (!creds) {
13982
- console.log(" Credentials: not set (run `bamboo-agents login`)");
13983
- } else {
13984
- console.log(
13985
- ` Credentials: set${creds.github_username ? ` (@${creds.github_username})` : ""}`
13986
- );
13987
- console.log(` Written: ${creds.written_at}`);
13988
- if (creds.github_token_expires_at) {
13989
- console.log(` GitHub expires: ${creds.github_token_expires_at}`);
14041
+ return withFreshWorkspace(async () => {
14042
+ const creds = await readCredentials();
14043
+ const state = await readState().catch(() => null);
14044
+ const cfg = await readConfig();
14045
+ console.log("");
14046
+ console.log(" Bamboo CLI status");
14047
+ console.log("");
14048
+ if (!creds) {
14049
+ console.log(" Credentials: not set (run `bamboo-agents login`)");
14050
+ } else {
14051
+ console.log(
14052
+ ` Credentials: set${creds.github_username ? ` (@${creds.github_username})` : ""}`
14053
+ );
14054
+ console.log(` Written: ${creds.written_at}`);
14055
+ if (creds.github_token_expires_at) {
14056
+ console.log(` GitHub expires: ${creds.github_token_expires_at}`);
14057
+ }
13990
14058
  }
13991
- }
13992
- const workspacePath = state?.workspace_path ?? cfg?.repo_path ?? null;
13993
- if (!workspacePath) {
13994
- console.log(" Workspace: not configured (run `bamboo-agents init`)");
13995
- } else {
13996
- const repoLabel = cfg?.workspace_repo ?? state?.remote_url?.replace(/^https?:\/\/github\.com\//, "") ?? "(unknown)";
13997
- console.log(` Workspace: ${repoLabel}`);
13998
- console.log(` Repo path: ${workspacePath}`);
13999
- console.log(` Org: ${cfg?.org_name ?? state?.org_slug ?? "(unknown)"}`);
14000
- console.log(` Installed: ${cfg?.installed_at ?? state?.cloned_at ?? "(unknown)"}`);
14001
- if (state?.last_sync) {
14002
- console.log(` Last sync: ${state.last_sync}`);
14059
+ const workspacePath = state?.workspace_path ?? cfg?.repo_path ?? null;
14060
+ if (!workspacePath) {
14061
+ console.log(" Workspace: not configured (run `bamboo-agents init`)");
14062
+ } else {
14063
+ const repoLabel = cfg?.workspace_repo ?? state?.remote_url?.replace(/^https?:\/\/github\.com\//, "") ?? "(unknown)";
14064
+ console.log(` Workspace: ${repoLabel}`);
14065
+ console.log(` Repo path: ${workspacePath}`);
14066
+ console.log(` Org: ${cfg?.org_name ?? state?.org_slug ?? "(unknown)"}`);
14067
+ console.log(` Installed: ${cfg?.installed_at ?? state?.cloned_at ?? "(unknown)"}`);
14068
+ if (state?.last_sync) {
14069
+ console.log(` Last sync: ${state.last_sync}`);
14070
+ }
14003
14071
  }
14004
- }
14005
- if (creds?.bamboo_session) {
14006
- try {
14007
- const billing = await getCliBillingStatus(creds.bamboo_session);
14008
- console.log(` ${formatSubscriptionLine(billing)}`);
14009
- } catch {
14072
+ if (creds?.bamboo_session) {
14073
+ try {
14074
+ const billing = await getCliBillingStatus(creds.bamboo_session);
14075
+ console.log(` ${formatSubscriptionLine(billing)}`);
14076
+ } catch {
14077
+ }
14010
14078
  }
14011
- }
14012
- console.log("");
14079
+ console.log("");
14080
+ });
14013
14081
  }
14014
14082
  var init_status = __esm({
14015
14083
  "src/commands/status.ts"() {
@@ -14017,6 +14085,308 @@ var init_status = __esm({
14017
14085
  init_state();
14018
14086
  init_credentials();
14019
14087
  init_api();
14088
+ init_workspace();
14089
+ }
14090
+ });
14091
+
14092
+ // src/lib/workspace-health.ts
14093
+ import { execFile as execFile8 } from "node:child_process";
14094
+ import { promisify as promisify8 } from "node:util";
14095
+ import { lstat, readlink, readdir as readdir2, mkdir as mkdir3, symlink, rm as rm2, access as access3 } from "node:fs/promises";
14096
+ import { join as join2, dirname as dirname2, resolve } from "node:path";
14097
+ import { homedir as homedir2 } from "node:os";
14098
+ function getStaleSyncHours() {
14099
+ const raw = process.env.BAMBOO_STALE_SYNC_HOURS;
14100
+ if (!raw) return DEFAULT_STALE_SYNC_HOURS;
14101
+ const n = Number(raw);
14102
+ if (!Number.isFinite(n) || n <= 0) return DEFAULT_STALE_SYNC_HOURS;
14103
+ return n;
14104
+ }
14105
+ function cloneSearchRoots(cwd) {
14106
+ const overridden = process.env.BAMBOO_CLONE_SEARCH_DIRS;
14107
+ const home = homedir2();
14108
+ const base = overridden ? overridden.split(":").filter(Boolean) : [home, join2(home, "Documents"), join2(home, "Downloads"), join2(home, "Desktop")];
14109
+ const walk = [];
14110
+ let cur = cwd ?? process.cwd();
14111
+ for (let i = 0; i < 20; i++) {
14112
+ walk.push(cur);
14113
+ const parent = dirname2(cur);
14114
+ if (parent === cur) break;
14115
+ if (parent === home) {
14116
+ walk.push(home);
14117
+ break;
14118
+ }
14119
+ cur = parent;
14120
+ }
14121
+ const seen = /* @__PURE__ */ new Set();
14122
+ const out = [];
14123
+ for (const p of [...base, ...walk]) {
14124
+ const norm = resolve(p);
14125
+ if (seen.has(norm)) continue;
14126
+ seen.add(norm);
14127
+ out.push(norm);
14128
+ }
14129
+ return out;
14130
+ }
14131
+ async function findClones(remoteUrl, roots, maxDepth = 4) {
14132
+ const found = /* @__PURE__ */ new Set();
14133
+ let scanned = 0;
14134
+ async function visit(dir, depth) {
14135
+ if (scanned >= MAX_DIRS_SCANNED) return;
14136
+ if (depth < 0) return;
14137
+ scanned += 1;
14138
+ const gitDir = join2(dir, ".git");
14139
+ let isRepo = false;
14140
+ try {
14141
+ const s = await lstat(gitDir);
14142
+ isRepo = s.isDirectory() || s.isFile();
14143
+ } catch {
14144
+ isRepo = false;
14145
+ }
14146
+ if (isRepo) {
14147
+ const url = await getRepoRemoteUrl(dir);
14148
+ if (url && matchesRemote(url, remoteUrl)) {
14149
+ found.add(resolve(dir));
14150
+ }
14151
+ return;
14152
+ }
14153
+ let entries = [];
14154
+ try {
14155
+ entries = await readdir2(dir, { withFileTypes: true });
14156
+ } catch {
14157
+ return;
14158
+ }
14159
+ for (const entry of entries) {
14160
+ if (!entry.isDirectory() || entry.isSymbolicLink()) continue;
14161
+ if (entry.name.startsWith(".")) {
14162
+ if (SKIP_DIRS.has(entry.name)) continue;
14163
+ }
14164
+ if (SKIP_DIRS.has(entry.name)) continue;
14165
+ await visit(join2(dir, entry.name), depth - 1);
14166
+ }
14167
+ }
14168
+ for (const root of roots) {
14169
+ try {
14170
+ await access3(root);
14171
+ } catch {
14172
+ continue;
14173
+ }
14174
+ await visit(root, maxDepth);
14175
+ }
14176
+ return [...found];
14177
+ }
14178
+ function matchesRemote(a, b) {
14179
+ const slugA = remoteUrlSlug(a);
14180
+ const slugB = remoteUrlSlug(b);
14181
+ if (!slugA || !slugB) return false;
14182
+ return slugA.toLowerCase() === slugB.toLowerCase();
14183
+ }
14184
+ function remoteUrlSlug(url) {
14185
+ const cleaned = url.trim().replace(/\.git$/i, "");
14186
+ const https = cleaned.match(/^https?:\/\/[^/]*github\.com\/(.+)$/i);
14187
+ if (https && https[1]) return https[1];
14188
+ const ssh = cleaned.match(/^[^@]+@github\.com:(.+)$/i);
14189
+ if (ssh && ssh[1]) return ssh[1];
14190
+ if (/^[^/]+\/[^/]+$/.test(cleaned)) return cleaned;
14191
+ return null;
14192
+ }
14193
+ async function checkAdapters(workspacePath) {
14194
+ const out = [];
14195
+ for (const { path: path2, target } of CROSS_TOOL_ADAPTERS) {
14196
+ const full = join2(workspacePath, path2);
14197
+ let s;
14198
+ try {
14199
+ s = await lstat(full);
14200
+ } catch {
14201
+ out.push({ path: path2, expectedTarget: target, ok: false, state: "missing", actualTarget: null });
14202
+ continue;
14203
+ }
14204
+ if (!s.isSymbolicLink()) {
14205
+ out.push({
14206
+ path: path2,
14207
+ expectedTarget: target,
14208
+ ok: false,
14209
+ state: "not_symlink",
14210
+ actualTarget: null
14211
+ });
14212
+ continue;
14213
+ }
14214
+ let actual;
14215
+ try {
14216
+ actual = await readlink(full);
14217
+ } catch {
14218
+ out.push({ path: path2, expectedTarget: target, ok: false, state: "missing", actualTarget: null });
14219
+ continue;
14220
+ }
14221
+ if (actual === target) {
14222
+ out.push({ path: path2, expectedTarget: target, ok: true, state: "ok", actualTarget: actual });
14223
+ } else {
14224
+ out.push({
14225
+ path: path2,
14226
+ expectedTarget: target,
14227
+ ok: false,
14228
+ state: "wrong_target",
14229
+ actualTarget: actual
14230
+ });
14231
+ }
14232
+ }
14233
+ return out;
14234
+ }
14235
+ async function healAdapters(workspacePath) {
14236
+ const fixed = [];
14237
+ const current = await checkAdapters(workspacePath);
14238
+ for (const status of current) {
14239
+ if (status.ok) continue;
14240
+ const full = join2(workspacePath, status.path);
14241
+ if (status.state === "wrong_target" || status.state === "not_symlink") {
14242
+ try {
14243
+ await rm2(full, { recursive: true, force: true });
14244
+ } catch {
14245
+ }
14246
+ }
14247
+ await mkdir3(dirname2(full), { recursive: true });
14248
+ await symlink(status.expectedTarget, full);
14249
+ fixed.push(status.path);
14250
+ }
14251
+ return fixed;
14252
+ }
14253
+ function isStaleSync(lastSync, hours = getStaleSyncHours()) {
14254
+ const parsed = Date.parse(lastSync);
14255
+ if (Number.isNaN(parsed)) return true;
14256
+ return Date.now() - parsed > hours * 60 * 60 * 1e3;
14257
+ }
14258
+ function describeAge(lastSync) {
14259
+ const parsed = Date.parse(lastSync);
14260
+ if (Number.isNaN(parsed)) return "unknown";
14261
+ const ms = Date.now() - parsed;
14262
+ const hours = Math.floor(ms / (60 * 60 * 1e3));
14263
+ if (hours < 1) return "<1h";
14264
+ if (hours < 48) return `${hours}h`;
14265
+ const days = Math.floor(hours / 24);
14266
+ return `${days}d`;
14267
+ }
14268
+ async function gitPullFfOnly(workspacePath) {
14269
+ try {
14270
+ const { stderr } = await execFileP3("git", ["-C", workspacePath, "pull", "--ff-only"], {
14271
+ encoding: "utf8"
14272
+ });
14273
+ return { ok: true, stderr };
14274
+ } catch (err) {
14275
+ const e = err;
14276
+ return { ok: false, stderr: e.stderr ?? e.message };
14277
+ }
14278
+ }
14279
+ async function pathExists(p) {
14280
+ try {
14281
+ await access3(p);
14282
+ return true;
14283
+ } catch {
14284
+ return false;
14285
+ }
14286
+ }
14287
+ var execFileP3, CROSS_TOOL_ADAPTERS, DEFAULT_STALE_SYNC_HOURS, MAX_DIRS_SCANNED, SKIP_DIRS;
14288
+ var init_workspace_health = __esm({
14289
+ "src/lib/workspace-health.ts"() {
14290
+ "use strict";
14291
+ init_git();
14292
+ execFileP3 = promisify8(execFile8);
14293
+ CROSS_TOOL_ADAPTERS = [
14294
+ { path: ".claude/skills", target: "../skills" },
14295
+ { path: ".cursor/skills", target: "../skills" },
14296
+ { path: ".agents/skills", target: "../skills" }
14297
+ ];
14298
+ DEFAULT_STALE_SYNC_HOURS = 24;
14299
+ MAX_DIRS_SCANNED = 2e3;
14300
+ SKIP_DIRS = /* @__PURE__ */ new Set([
14301
+ "node_modules",
14302
+ ".git",
14303
+ ".cache",
14304
+ ".npm",
14305
+ ".pnpm",
14306
+ ".pnpm-store",
14307
+ ".turbo",
14308
+ ".next",
14309
+ ".vercel",
14310
+ "dist",
14311
+ "build",
14312
+ "out",
14313
+ "Library",
14314
+ // macOS — never anything interesting for our purposes
14315
+ "Pictures",
14316
+ "Movies",
14317
+ "Music"
14318
+ ]);
14319
+ }
14320
+ });
14321
+
14322
+ // src/lib/heal-prompt.ts
14323
+ import { createInterface as createInterface2 } from "node:readline";
14324
+ async function confirm(question, defaultValue = true) {
14325
+ if (!process.stdin.isTTY) return defaultValue;
14326
+ const hint = defaultValue ? "[Y/n]" : "[y/N]";
14327
+ const ask = `${question} ${hint} `;
14328
+ const rl = createInterface2({
14329
+ input: process.stdin,
14330
+ output: process.stdout,
14331
+ terminal: true
14332
+ });
14333
+ try {
14334
+ const answer = await readOnce2(rl, ask);
14335
+ if (answer === null) return null;
14336
+ const trimmed = answer.trim().toLowerCase();
14337
+ if (trimmed === "") return defaultValue;
14338
+ if (trimmed === "y" || trimmed === "yes") return true;
14339
+ if (trimmed === "n" || trimmed === "no") return false;
14340
+ return defaultValue;
14341
+ } finally {
14342
+ rl.close();
14343
+ }
14344
+ }
14345
+ async function choose(question, choices, defaultIndex = 0) {
14346
+ if (!process.stdin.isTTY) return defaultIndex;
14347
+ if (choices.length === 0) return null;
14348
+ console.log(question);
14349
+ for (let i = 0; i < choices.length; i++) {
14350
+ const letter = String.fromCharCode(65 + i);
14351
+ const marker = i === defaultIndex ? "\u203A" : " ";
14352
+ console.log(` ${marker} ${letter}. ${choices[i]}`);
14353
+ }
14354
+ const defaultLetter = String.fromCharCode(65 + defaultIndex);
14355
+ const ask = ` Pick [${defaultLetter}]: `;
14356
+ const rl = createInterface2({
14357
+ input: process.stdin,
14358
+ output: process.stdout,
14359
+ terminal: true
14360
+ });
14361
+ try {
14362
+ const answer = await readOnce2(rl, ask);
14363
+ if (answer === null) return null;
14364
+ const trimmed = answer.trim().toUpperCase();
14365
+ if (trimmed === "") return defaultIndex;
14366
+ if (trimmed.length === 1) {
14367
+ const idx = trimmed.charCodeAt(0) - 65;
14368
+ if (idx >= 0 && idx < choices.length) return idx;
14369
+ }
14370
+ return defaultIndex;
14371
+ } finally {
14372
+ rl.close();
14373
+ }
14374
+ }
14375
+ function readOnce2(rl, question) {
14376
+ return new Promise((resolve2) => {
14377
+ let resolved = false;
14378
+ const settle = (value) => {
14379
+ if (resolved) return;
14380
+ resolved = true;
14381
+ resolve2(value);
14382
+ };
14383
+ rl.once("close", () => settle(null));
14384
+ rl.question(question, (answer) => settle(answer));
14385
+ });
14386
+ }
14387
+ var init_heal_prompt = __esm({
14388
+ "src/lib/heal-prompt.ts"() {
14389
+ "use strict";
14020
14390
  }
14021
14391
  });
14022
14392
 
@@ -14025,9 +14395,11 @@ var doctor_exports = {};
14025
14395
  __export(doctor_exports, {
14026
14396
  checkBambooSession: () => checkBambooSession,
14027
14397
  checkGitCredential: () => checkGitCredential,
14398
+ collectDriftFindings: () => collectDriftFindings,
14028
14399
  runDoctor: () => runDoctor
14029
14400
  });
14030
- import { access as access3 } from "node:fs/promises";
14401
+ import { access as access4 } from "node:fs/promises";
14402
+ import { rm as rm3 } from "node:fs/promises";
14031
14403
  async function checkGit() {
14032
14404
  const v = await gitVersion();
14033
14405
  if (!v) {
@@ -14120,7 +14492,7 @@ async function checkRepoPath() {
14120
14492
  };
14121
14493
  }
14122
14494
  try {
14123
- await access3(cfg.repo_path);
14495
+ await access4(cfg.repo_path);
14124
14496
  return { name: "Repo cloned", ok: true, detail: cfg.repo_path };
14125
14497
  } catch {
14126
14498
  return {
@@ -14130,26 +14502,331 @@ async function checkRepoPath() {
14130
14502
  };
14131
14503
  }
14132
14504
  }
14133
- async function runDoctor() {
14134
- const checks = await Promise.all([
14505
+ async function collectDriftFindings(state, cwd) {
14506
+ const stateExists = await pathExists(state.workspace_path);
14507
+ const staleStateFinding = stateExists ? {
14508
+ kind: "stale_state",
14509
+ ok: true,
14510
+ summary: state.workspace_path
14511
+ } : {
14512
+ kind: "stale_state",
14513
+ ok: false,
14514
+ summary: `recorded workspace ${state.workspace_path} doesn't exist`,
14515
+ data: { workspace_path: state.workspace_path }
14516
+ };
14517
+ const found = await findClones(state.remote_url, cloneSearchRoots(cwd));
14518
+ const candidates = new Set(found);
14519
+ if (stateExists) {
14520
+ const { getRepoRemoteUrl: getRepoRemoteUrl2 } = await Promise.resolve().then(() => (init_git(), git_exports));
14521
+ const url = await getRepoRemoteUrl2(state.workspace_path);
14522
+ if (url && slugMatch(url, state.remote_url)) {
14523
+ candidates.add(state.workspace_path);
14524
+ }
14525
+ }
14526
+ const cloneList = [...candidates];
14527
+ const multiCloneFinding = cloneList.length > 1 ? {
14528
+ kind: "multi_clone",
14529
+ ok: false,
14530
+ summary: `found ${cloneList.length} clones of ${state.remote_url}`,
14531
+ data: { clones: cloneList, canonical: state.workspace_path }
14532
+ } : {
14533
+ kind: "multi_clone",
14534
+ ok: true,
14535
+ summary: cloneList.length === 1 ? "single clone" : "no extra clones found",
14536
+ data: { clones: cloneList }
14537
+ };
14538
+ const wrongStateFinding = await (async () => {
14539
+ if (stateExists) {
14540
+ const { getRepoRemoteUrl: getRepoRemoteUrl2 } = await Promise.resolve().then(() => (init_git(), git_exports));
14541
+ const url = await getRepoRemoteUrl2(state.workspace_path);
14542
+ if (!url || !slugMatch(url, state.remote_url)) {
14543
+ const better2 = cloneList.find((p) => p !== state.workspace_path);
14544
+ if (better2) {
14545
+ return {
14546
+ kind: "wrong_state",
14547
+ ok: false,
14548
+ summary: `${state.workspace_path} doesn't match remote ${state.remote_url}`,
14549
+ data: {
14550
+ recorded: state.workspace_path,
14551
+ actual: better2,
14552
+ recorded_origin: url ?? null
14553
+ }
14554
+ };
14555
+ }
14556
+ }
14557
+ return { kind: "wrong_state", ok: true, summary: "state matches workspace" };
14558
+ }
14559
+ const better = cloneList.find((p) => p !== state.workspace_path);
14560
+ if (better) {
14561
+ return {
14562
+ kind: "wrong_state",
14563
+ ok: false,
14564
+ summary: `recorded path missing, but a clone exists at ${better}`,
14565
+ data: { recorded: state.workspace_path, actual: better }
14566
+ };
14567
+ }
14568
+ return { kind: "wrong_state", ok: true, summary: "no alternate clone to switch to" };
14569
+ })();
14570
+ const adapterFinding = await (async () => {
14571
+ if (!stateExists) {
14572
+ return {
14573
+ kind: "missing_adapters",
14574
+ ok: true,
14575
+ summary: "skipped (workspace path missing)"
14576
+ };
14577
+ }
14578
+ const adapters = await checkAdapters(state.workspace_path);
14579
+ const broken = adapters.filter((a) => !a.ok);
14580
+ if (broken.length === 0) {
14581
+ return { kind: "missing_adapters", ok: true, summary: "all adapter symlinks present" };
14582
+ }
14583
+ return {
14584
+ kind: "missing_adapters",
14585
+ ok: false,
14586
+ summary: `${broken.length}/${adapters.length} adapter symlinks missing or wrong`,
14587
+ data: { adapters, broken: broken.map((b) => b.path) }
14588
+ };
14589
+ })();
14590
+ const staleSyncFinding = isStaleSync(state.last_sync) ? {
14591
+ kind: "stale_sync",
14592
+ ok: false,
14593
+ summary: `last sync was ${describeAge(state.last_sync)} ago (threshold: ${getStaleSyncHours()}h)`,
14594
+ data: { last_sync: state.last_sync }
14595
+ } : {
14596
+ kind: "stale_sync",
14597
+ ok: true,
14598
+ summary: `synced ${describeAge(state.last_sync)} ago`
14599
+ };
14600
+ return [
14601
+ staleStateFinding,
14602
+ multiCloneFinding,
14603
+ wrongStateFinding,
14604
+ adapterFinding,
14605
+ staleSyncFinding
14606
+ ];
14607
+ }
14608
+ function slugMatch(a, b) {
14609
+ const slug = (u) => {
14610
+ const cleaned = u.trim().replace(/\.git$/i, "");
14611
+ const https = cleaned.match(/^https?:\/\/[^/]*github\.com\/(.+)$/i);
14612
+ if (https && https[1]) return https[1].toLowerCase();
14613
+ const ssh = cleaned.match(/^[^@]+@github\.com:(.+)$/i);
14614
+ if (ssh && ssh[1]) return ssh[1].toLowerCase();
14615
+ if (/^[^/]+\/[^/]+$/.test(cleaned)) return cleaned.toLowerCase();
14616
+ return null;
14617
+ };
14618
+ const sa = slug(a);
14619
+ const sb = slug(b);
14620
+ return sa !== null && sb !== null && sa === sb;
14621
+ }
14622
+ async function healStaleState(finding, state, opts) {
14623
+ console.log("");
14624
+ console.log(` \u2717 Recorded workspace path missing: ${finding.data?.workspace_path}`);
14625
+ if (opts.quiet) return state;
14626
+ const want = await confirm(" Re-run init to re-clone?", true);
14627
+ if (!want) {
14628
+ console.log(" Skipped. Run `bamboo-agents init` manually when ready.");
14629
+ return state;
14630
+ }
14631
+ console.log(" Launching `bamboo-agents init` flow\u2026");
14632
+ const { runInit: runInit2 } = await Promise.resolve().then(() => (init_init(), init_exports));
14633
+ await runInit2();
14634
+ const fresh = await readState();
14635
+ return fresh ?? state;
14636
+ }
14637
+ async function healMultiClone(finding, state, opts) {
14638
+ const clones = finding.data?.clones ?? [];
14639
+ console.log("");
14640
+ console.log(` \u2717 Found ${clones.length} clones of ${state.remote_url}:`);
14641
+ for (const p of clones) console.log(` \u2022 ${p}`);
14642
+ if (opts.quiet) return state;
14643
+ const choices = [...clones, "Skip (leave both)"];
14644
+ const defaultIdx = clones.findIndex((p) => p === state.workspace_path);
14645
+ const idx = await choose(
14646
+ " Which clone should be canonical?",
14647
+ choices,
14648
+ defaultIdx >= 0 ? defaultIdx : 0
14649
+ );
14650
+ if (idx === null || idx === choices.length - 1) {
14651
+ console.log(" Skipped. Multi-clone left as-is.");
14652
+ return state;
14653
+ }
14654
+ const canonical = clones[idx];
14655
+ const nonCanonical = clones.filter((p) => p !== canonical);
14656
+ let next = state;
14657
+ if (canonical !== state.workspace_path) {
14658
+ next = { ...state, workspace_path: canonical };
14659
+ await writeState(next);
14660
+ console.log(` Updated state.json \u2192 ${canonical}`);
14661
+ }
14662
+ if (nonCanonical.length > 0) {
14663
+ console.log(" Other clones:");
14664
+ for (const p of nonCanonical) console.log(` \u2022 ${p}`);
14665
+ const wantDelete = await confirm(" Delete the non-canonical clones?", false);
14666
+ if (wantDelete) {
14667
+ for (const p of nonCanonical) {
14668
+ try {
14669
+ await rm3(p, { recursive: true, force: true });
14670
+ console.log(` \u2713 removed ${p}`);
14671
+ } catch (err) {
14672
+ console.log(` \u2717 couldn't remove ${p}: ${err.message}`);
14673
+ }
14674
+ }
14675
+ } else {
14676
+ console.log(" Left non-canonical clones in place.");
14677
+ }
14678
+ }
14679
+ return next;
14680
+ }
14681
+ async function healWrongState(finding, state, opts) {
14682
+ const actual = finding.data?.actual;
14683
+ const recorded = finding.data?.recorded;
14684
+ if (!actual || !recorded) return state;
14685
+ console.log("");
14686
+ console.log(` \u2717 state.workspace_path = ${recorded}, but workspace lives at ${actual}`);
14687
+ if (opts.quiet) return state;
14688
+ const useActual = opts.autoHeal ? true : await confirm(` Update state.json \u2192 ${actual}?`, true);
14689
+ if (useActual === null || !useActual) {
14690
+ console.log(" Skipped. state.json still points at the recorded path.");
14691
+ return state;
14692
+ }
14693
+ const next = { ...state, workspace_path: actual };
14694
+ await writeState(next);
14695
+ console.log(` Updated state.json \u2192 ${actual}`);
14696
+ return next;
14697
+ }
14698
+ async function healMissingAdapters(finding, state, opts) {
14699
+ const broken = finding.data?.broken ?? [];
14700
+ console.log("");
14701
+ console.log(` \u2717 Missing/wrong adapter symlinks: ${broken.join(", ")}`);
14702
+ if (opts.quiet) return state;
14703
+ const want = opts.autoHeal ? true : await confirm(" Add the missing adapter symlinks?", true);
14704
+ if (!want) {
14705
+ console.log(" Skipped. Add manually with `ln -s ../skills <path>` from your workspace root.");
14706
+ return state;
14707
+ }
14708
+ try {
14709
+ const fixed = await healAdapters(state.workspace_path);
14710
+ for (const p of fixed) console.log(` \u2713 created ${p} \u2192 ../skills`);
14711
+ } catch (err) {
14712
+ console.log(` \u2717 couldn't create symlinks: ${err.message}`);
14713
+ }
14714
+ return state;
14715
+ }
14716
+ async function healStaleSync(_finding, state, opts) {
14717
+ console.log("");
14718
+ console.log(` \u2717 Last sync was ${describeAge(state.last_sync)} ago.`);
14719
+ if (opts.quiet) return state;
14720
+ const want = opts.autoHeal ? true : await confirm(" Pull now (ff-only)?", true);
14721
+ if (!want) {
14722
+ console.log(" Skipped. Run `git pull` in your workspace when ready.");
14723
+ return state;
14724
+ }
14725
+ const result = await gitPullFfOnly(state.workspace_path);
14726
+ if (result.ok) {
14727
+ const next = { ...state, last_sync: (/* @__PURE__ */ new Date()).toISOString() };
14728
+ await writeState(next);
14729
+ console.log(" \u2713 pulled cleanly");
14730
+ return next;
14731
+ }
14732
+ console.log(` \u2717 pull failed: ${result.stderr.trim().split("\n")[0]}`);
14733
+ console.log(" Run `git pull` manually to diagnose.");
14734
+ return state;
14735
+ }
14736
+ async function runDoctor(options = {}) {
14737
+ const opts = {
14738
+ quiet: options.quiet === true,
14739
+ autoHeal: options.autoHeal === true
14740
+ };
14741
+ const baseChecks = await Promise.all([
14135
14742
  checkGit(),
14136
14743
  checkBambooSession(),
14137
14744
  checkGitCredential(),
14138
14745
  checkConfig(),
14139
14746
  checkRepoPath()
14140
14747
  ]);
14748
+ const state = await readState().catch(() => null);
14749
+ const drift = state ? await collectDriftFindings(state) : null;
14750
+ if (opts.quiet) {
14751
+ const payload = {
14752
+ ok: baseChecks.every((c) => c.ok) && (drift ?? []).every((d) => d.ok),
14753
+ checks: baseChecks.map((c) => ({ name: c.name, ok: c.ok, detail: c.detail })),
14754
+ drift: drift ?? []
14755
+ };
14756
+ console.log(JSON.stringify(payload, null, 2));
14757
+ process.exit(payload.ok ? 0 : 1);
14758
+ return;
14759
+ }
14141
14760
  console.log("");
14142
- for (const c of checks) {
14761
+ for (const c of baseChecks) {
14143
14762
  const mark = c.ok ? "\u2713" : "\u2717";
14144
14763
  console.log(` ${mark} ${c.name.padEnd(28)} ${c.detail}`);
14145
14764
  }
14765
+ if (drift) {
14766
+ console.log("");
14767
+ const labels = {
14768
+ stale_state: "Workspace path on disk",
14769
+ multi_clone: "Single clone",
14770
+ wrong_state: "State matches workspace",
14771
+ missing_adapters: "Cross-tool adapters",
14772
+ stale_sync: "Recent sync"
14773
+ };
14774
+ for (const f of drift) {
14775
+ const mark = f.ok ? "\u2713" : "\u2717";
14776
+ console.log(` ${mark} ${labels[f.kind].padEnd(28)} ${f.summary}`);
14777
+ }
14778
+ }
14146
14779
  console.log("");
14147
- const failures = checks.filter((c) => !c.ok);
14148
- if (failures.length > 0) {
14149
- console.log(` ${failures.length} check(s) failing.`);
14150
- process.exit(1);
14780
+ const remaining = (drift ?? []).filter((f) => !f.ok);
14781
+ if (remaining.length === 0) {
14782
+ const baseFailures = baseChecks.filter((c) => !c.ok).length;
14783
+ if (baseFailures > 0) {
14784
+ console.log(` ${baseFailures} check(s) failing.`);
14785
+ process.exit(1);
14786
+ }
14787
+ console.log(" All checks passing.");
14788
+ return;
14151
14789
  }
14152
- console.log(" All checks passing.");
14790
+ console.log(` ${remaining.length} drift issue(s) detected \u2014 let's fix them.`);
14791
+ let cur = state;
14792
+ const order = [
14793
+ "stale_state",
14794
+ "wrong_state",
14795
+ "multi_clone",
14796
+ "missing_adapters",
14797
+ "stale_sync"
14798
+ ];
14799
+ for (const kind of order) {
14800
+ const f = remaining.find((r) => r.kind === kind);
14801
+ if (!f) continue;
14802
+ switch (kind) {
14803
+ case "stale_state":
14804
+ cur = await healStaleState(f, cur, opts);
14805
+ break;
14806
+ case "multi_clone":
14807
+ cur = await healMultiClone(f, cur, opts);
14808
+ break;
14809
+ case "wrong_state":
14810
+ cur = await healWrongState(f, cur, opts);
14811
+ break;
14812
+ case "missing_adapters":
14813
+ cur = await healMissingAdapters(f, cur, opts);
14814
+ break;
14815
+ case "stale_sync":
14816
+ cur = await healStaleSync(f, cur, opts);
14817
+ break;
14818
+ }
14819
+ }
14820
+ const post = await readState().catch(() => null);
14821
+ const postDrift = post ? await collectDriftFindings(post) : drift;
14822
+ const stillBroken = (postDrift ?? []).filter((d) => !d.ok);
14823
+ console.log("");
14824
+ if (stillBroken.length === 0) {
14825
+ console.log(" \u2713 Workspace healthy.");
14826
+ return;
14827
+ }
14828
+ console.log(` ${stillBroken.length} issue(s) remain \u2014 re-run \`bamboo-agents doctor\` after addressing.`);
14829
+ process.exit(1);
14153
14830
  }
14154
14831
  var init_doctor = __esm({
14155
14832
  "src/commands/doctor.ts"() {
@@ -14158,6 +14835,8 @@ var init_doctor = __esm({
14158
14835
  init_git();
14159
14836
  init_state();
14160
14837
  init_credentials();
14838
+ init_workspace_health();
14839
+ init_heal_prompt();
14161
14840
  }
14162
14841
  });
14163
14842
 
@@ -14166,10 +14845,10 @@ var save_exports = {};
14166
14845
  __export(save_exports, {
14167
14846
  runSave: () => runSave
14168
14847
  });
14169
- import { execFile as execFile8 } from "node:child_process";
14170
- import { promisify as promisify8 } from "node:util";
14848
+ import { execFile as execFile9 } from "node:child_process";
14849
+ import { promisify as promisify9 } from "node:util";
14171
14850
  async function gitC(repoPath, args) {
14172
- const { stdout, stderr } = await execFileP3("git", ["-C", repoPath, ...args], {
14851
+ const { stdout, stderr } = await execFileP4("git", ["-C", repoPath, ...args], {
14173
14852
  encoding: "utf8"
14174
14853
  });
14175
14854
  return { stdout, stderr };
@@ -14218,12 +14897,12 @@ async function runSave(message) {
14218
14897
  process.exit(1);
14219
14898
  }
14220
14899
  }
14221
- var execFileP3;
14900
+ var execFileP4;
14222
14901
  var init_save = __esm({
14223
14902
  "src/commands/save.ts"() {
14224
14903
  "use strict";
14225
14904
  init_workspace();
14226
- execFileP3 = promisify8(execFile8);
14905
+ execFileP4 = promisify9(execFile9);
14227
14906
  }
14228
14907
  });
14229
14908
 
@@ -14232,8 +14911,8 @@ var sync_exports = {};
14232
14911
  __export(sync_exports, {
14233
14912
  runSync: () => runSync
14234
14913
  });
14235
- import { execFile as execFile9 } from "node:child_process";
14236
- import { promisify as promisify9 } from "node:util";
14914
+ import { execFile as execFile10 } from "node:child_process";
14915
+ import { promisify as promisify10 } from "node:util";
14237
14916
  async function runSync() {
14238
14917
  let workspacePath;
14239
14918
  try {
@@ -14246,7 +14925,7 @@ async function runSync() {
14246
14925
  throw err;
14247
14926
  }
14248
14927
  try {
14249
- const { stdout } = await execFileP4(
14928
+ const { stdout } = await execFileP5(
14250
14929
  "git",
14251
14930
  ["-C", workspacePath, "pull", "--ff-only"],
14252
14931
  { encoding: "utf8" }
@@ -14275,19 +14954,19 @@ async function runSync() {
14275
14954
  throw err;
14276
14955
  }
14277
14956
  }
14278
- var execFileP4;
14957
+ var execFileP5;
14279
14958
  var init_sync = __esm({
14280
14959
  "src/commands/sync.ts"() {
14281
14960
  "use strict";
14282
14961
  init_state();
14283
14962
  init_workspace();
14284
- execFileP4 = promisify9(execFile9);
14963
+ execFileP5 = promisify10(execFile10);
14285
14964
  }
14286
14965
  });
14287
14966
 
14288
14967
  // src/lib/skills-local.ts
14289
- import { readdir as readdir2, readFile as readFile4, stat as stat2 } from "node:fs/promises";
14290
- import { join as join2 } from "node:path";
14968
+ import { readdir as readdir3, readFile as readFile4, stat as stat2 } from "node:fs/promises";
14969
+ import { join as join3 } from "node:path";
14291
14970
  function parseSimpleFrontmatter(raw) {
14292
14971
  const text = raw.replace(/\r\n/g, "\n");
14293
14972
  const m = text.match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/);
@@ -14402,7 +15081,7 @@ function parseSkillContent(raw, sourcePath) {
14402
15081
  };
14403
15082
  }
14404
15083
  async function resolveSkillsDir(repoPath) {
14405
- const dir = join2(repoPath, "skills");
15084
+ const dir = join3(repoPath, "skills");
14406
15085
  try {
14407
15086
  const s = await stat2(dir);
14408
15087
  return s.isDirectory() ? dir : null;
@@ -14413,11 +15092,11 @@ async function resolveSkillsDir(repoPath) {
14413
15092
  async function listLocalSkills(repoPath) {
14414
15093
  const dir = await resolveSkillsDir(repoPath);
14415
15094
  if (!dir) return [];
14416
- const entries = await readdir2(dir, { withFileTypes: true });
15095
+ const entries = await readdir3(dir, { withFileTypes: true });
14417
15096
  const skillDirs = entries.filter((e) => e.isDirectory());
14418
15097
  const skills2 = [];
14419
15098
  for (const entry of skillDirs) {
14420
- const full = join2(dir, entry.name, "SKILL.md");
15099
+ const full = join3(dir, entry.name, "SKILL.md");
14421
15100
  let raw;
14422
15101
  try {
14423
15102
  raw = await readFile4(full, "utf8");
@@ -14438,7 +15117,7 @@ async function listLocalSkills(repoPath) {
14438
15117
  async function getLocalSkill(repoPath, name) {
14439
15118
  const dir = await resolveSkillsDir(repoPath);
14440
15119
  if (!dir) return null;
14441
- const full = join2(dir, name, "SKILL.md");
15120
+ const full = join3(dir, name, "SKILL.md");
14442
15121
  let raw;
14443
15122
  try {
14444
15123
  raw = await readFile4(full, "utf8");
@@ -14523,6 +15202,9 @@ async function requireSession() {
14523
15202
  return creds.bamboo_session;
14524
15203
  }
14525
15204
  async function runSkillsList(options = {}) {
15205
+ return withFreshWorkspace(async () => runSkillsListImpl(options));
15206
+ }
15207
+ async function runSkillsListImpl(options = {}) {
14526
15208
  if (options.agent) {
14527
15209
  const bambooSession = await requireSession();
14528
15210
  const resolved = await resolveAgent(bambooSession, options.agent);
@@ -14607,18 +15289,20 @@ async function runSkillsList(options = {}) {
14607
15289
  console.log("");
14608
15290
  }
14609
15291
  async function runSkillsGet(name) {
14610
- if (!name || !name.trim()) {
14611
- console.error("bamboo-agents: skills get requires a skill name.");
14612
- console.error("Example: bamboo-agents skills get enhance-instructions");
14613
- process.exit(2);
14614
- }
14615
- const repoPath = await resolveWorkspacePath();
14616
- const skill = await getLocalSkill(repoPath, name.trim());
14617
- if (!skill) {
14618
- await printNotFound(repoPath, name);
14619
- process.exit(2);
14620
- }
14621
- printSkillToStdout(skill);
15292
+ return withFreshWorkspace(async () => {
15293
+ if (!name || !name.trim()) {
15294
+ console.error("bamboo-agents: skills get requires a skill name.");
15295
+ console.error("Example: bamboo-agents skills get enhance-instructions");
15296
+ process.exit(2);
15297
+ }
15298
+ const repoPath = await resolveWorkspacePath();
15299
+ const skill = await getLocalSkill(repoPath, name.trim());
15300
+ if (!skill) {
15301
+ await printNotFound(repoPath, name);
15302
+ process.exit(2);
15303
+ }
15304
+ printSkillToStdout(skill);
15305
+ });
14622
15306
  }
14623
15307
  function printSkillToStdout(skill) {
14624
15308
  process.stdout.write("---\n");
@@ -14661,10 +15345,14 @@ async function printNotFound(repoPath, name) {
14661
15345
  }
14662
15346
  }
14663
15347
  async function runSkillsSubscribe(agentIdentifier, skillName) {
14664
- await runSubscribeOp("subscribe", agentIdentifier, skillName);
15348
+ return withFreshWorkspace(
15349
+ async () => runSubscribeOp("subscribe", agentIdentifier, skillName)
15350
+ );
14665
15351
  }
14666
15352
  async function runSkillsUnsubscribe(agentIdentifier, skillName) {
14667
- await runSubscribeOp("unsubscribe", agentIdentifier, skillName);
15353
+ return withFreshWorkspace(
15354
+ async () => runSubscribeOp("unsubscribe", agentIdentifier, skillName)
15355
+ );
14668
15356
  }
14669
15357
  async function runSubscribeOp(action, agentIdentifier, skillName) {
14670
15358
  if (!agentIdentifier || !skillName) {
@@ -14712,6 +15400,9 @@ async function runSubscribeOp(action, agentIdentifier, skillName) {
14712
15400
  console.log("");
14713
15401
  }
14714
15402
  async function runSkillsCreate(skillName, options = {}) {
15403
+ return withFreshWorkspace(async () => runSkillsCreateImpl(skillName, options));
15404
+ }
15405
+ async function runSkillsCreateImpl(skillName, options = {}) {
14715
15406
  if (!skillName || !skillName.trim()) {
14716
15407
  console.error("bamboo-agents: skills create requires a skill name.");
14717
15408
  console.error("Example: bamboo-agents skills create analyze-creative");
@@ -14748,6 +15439,11 @@ async function runSkillsCreate(skillName, options = {}) {
14748
15439
  console.log("");
14749
15440
  }
14750
15441
  async function runSkillsUpdate(agentIdentifier, skillName) {
15442
+ return withFreshWorkspace(
15443
+ async () => runSkillsUpdateImpl(agentIdentifier, skillName)
15444
+ );
15445
+ }
15446
+ async function runSkillsUpdateImpl(agentIdentifier, skillName) {
14751
15447
  if (!agentIdentifier || !skillName) {
14752
15448
  console.error(
14753
15449
  "bamboo-agents: `skills update` requires an agent identifier and a skill name."
@@ -14783,6 +15479,7 @@ var init_skills = __esm({
14783
15479
  init_workspace();
14784
15480
  init_skills_local();
14785
15481
  init_api();
15482
+ init_workspace();
14786
15483
  }
14787
15484
  });
14788
15485
 
@@ -14806,7 +15503,7 @@ var {
14806
15503
  // src/index.ts
14807
15504
  init_version();
14808
15505
  var program2 = new Command();
14809
- program2.name("bamboo-agents").description("Set up your local Bamboo workspace and drop into Claude.").version(VERSION);
15506
+ program2.name("bamboo-agents").description("Set up your local Bamboo workspace and drop into Claude.").version(VERSION).option("--no-sync", "Skip the auto-sync git pull on this command");
14810
15507
  program2.action(async () => {
14811
15508
  const { runOrchestrator: runOrchestrator2 } = await Promise.resolve().then(() => (init_orchestrator(), orchestrator_exports));
14812
15509
  await runOrchestrator2();
@@ -14822,17 +15519,17 @@ program2.command("init").description("Clone your workspace + set up git credenti
14822
15519
  const { runInit: runInit2 } = await Promise.resolve().then(() => (init_init(), init_exports));
14823
15520
  await runInit2({ reset: options.reset });
14824
15521
  });
14825
- program2.command("open").description("Launch Claude Code at your workspace").action(async () => {
15522
+ program2.command("open").description("Launch Claude Code at your workspace").option("--no-sync", "Skip the auto-sync git pull on this command").action(async () => {
14826
15523
  const { runOpen: runOpen2 } = await Promise.resolve().then(() => (init_open2(), open_exports));
14827
15524
  await runOpen2();
14828
15525
  });
14829
- program2.command("status").description("Show current Bamboo CLI state").action(async () => {
15526
+ program2.command("status").description("Show current Bamboo CLI state").option("--no-sync", "Skip the auto-sync git pull on this command").action(async () => {
14830
15527
  const { runStatus: runStatus2 } = await Promise.resolve().then(() => (init_status(), status_exports));
14831
15528
  await runStatus2();
14832
15529
  });
14833
- program2.command("doctor").description("Verify your local setup is ready").action(async () => {
15530
+ program2.command("doctor").description("Verify your local setup is ready + heal workspace drift").option("--quiet", "Emit JSON without prompting (CI / scripts)").option("--auto-heal", "Apply non-destructive fixes silently").action(async (options) => {
14834
15531
  const { runDoctor: runDoctor2 } = await Promise.resolve().then(() => (init_doctor(), doctor_exports));
14835
- await runDoctor2();
15532
+ await runDoctor2({ quiet: options.quiet, autoHeal: options.autoHeal });
14836
15533
  });
14837
15534
  program2.command("save <message>").description("Commit + push everything in your workspace (cwd-agnostic)").action(async (message) => {
14838
15535
  const { runSave: runSave2 } = await Promise.resolve().then(() => (init_save(), save_exports));
@@ -14846,29 +15543,29 @@ var skills = program2.command("skills").description("Read workspace skills from
14846
15543
  skills.command("list").description("List every skill in the workspace").option(
14847
15544
  "--agent <slug>",
14848
15545
  "Filter to one agent's subscribed skills (via server)"
14849
- ).action(async (options) => {
15546
+ ).option("--no-sync", "Skip the auto-sync git pull on this command").action(async (options) => {
14850
15547
  const { runSkillsList: runSkillsList2 } = await Promise.resolve().then(() => (init_skills(), skills_exports));
14851
15548
  await runSkillsList2(options);
14852
15549
  });
14853
- skills.command("get <name>").description("Print one skill's SKILL.md body to stdout").action(async (name) => {
15550
+ skills.command("get <name>").description("Print one skill's SKILL.md body to stdout").option("--no-sync", "Skip the auto-sync git pull on this command").action(async (name) => {
14854
15551
  const { runSkillsGet: runSkillsGet2 } = await Promise.resolve().then(() => (init_skills(), skills_exports));
14855
15552
  await runSkillsGet2(name);
14856
15553
  });
14857
- skills.command("subscribe <agent> <skill-name>").description("Subscribe an agent to a skill from the catalog").action(async (agent, skillName) => {
15554
+ skills.command("subscribe <agent> <skill-name>").description("Subscribe an agent to a skill from the catalog").option("--no-sync", "Skip the auto-sync git pull on this command").action(async (agent, skillName) => {
14858
15555
  const { runSkillsSubscribe: runSkillsSubscribe2 } = await Promise.resolve().then(() => (init_skills(), skills_exports));
14859
15556
  await runSkillsSubscribe2(agent, skillName);
14860
15557
  });
14861
- skills.command("unsubscribe <agent> <skill-name>").description("Unsubscribe an agent from a skill").action(async (agent, skillName) => {
15558
+ skills.command("unsubscribe <agent> <skill-name>").description("Unsubscribe an agent from a skill").option("--no-sync", "Skip the auto-sync git pull on this command").action(async (agent, skillName) => {
14862
15559
  const { runSkillsUnsubscribe: runSkillsUnsubscribe2 } = await Promise.resolve().then(() => (init_skills(), skills_exports));
14863
15560
  await runSkillsUnsubscribe2(agent, skillName);
14864
15561
  });
14865
- skills.command("create <skill-name>").description("Scaffold a new org-custom skill in your workspace").option("--category <category>", "Optional category label (e.g. analysis)").option("--description <description>", "Optional one-line description").action(
15562
+ skills.command("create <skill-name>").description("Scaffold a new org-custom skill in your workspace").option("--category <category>", "Optional category label (e.g. analysis)").option("--description <description>", "Optional one-line description").option("--no-sync", "Skip the auto-sync git pull on this command").action(
14866
15563
  async (skillName, options) => {
14867
15564
  const { runSkillsCreate: runSkillsCreate2 } = await Promise.resolve().then(() => (init_skills(), skills_exports));
14868
15565
  await runSkillsCreate2(skillName, options);
14869
15566
  }
14870
15567
  );
14871
- skills.command("update <agent> <skill-name>").description("Update an installed skill from the bamboo registry").action(async (agent, skillName) => {
15568
+ skills.command("update <agent> <skill-name>").description("Update an installed skill from the bamboo registry").option("--no-sync", "Skip the auto-sync git pull on this command").action(async (agent, skillName) => {
14872
15569
  const { runSkillsUpdate: runSkillsUpdate2 } = await Promise.resolve().then(() => (init_skills(), skills_exports));
14873
15570
  await runSkillsUpdate2(agent, skillName);
14874
15571
  });