@mycompbox/compbox-cli 1.20.0 → 1.21.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/.tsbuildinfo +1 -1
  2. package/commands/configure.d.ts +2 -0
  3. package/commands/configure.d.ts.map +1 -1
  4. package/commands/configure.js +34 -55
  5. package/commands/configure.js.map +1 -1
  6. package/commands/deploy.d.ts +22 -0
  7. package/commands/deploy.d.ts.map +1 -0
  8. package/commands/deploy.js +96 -0
  9. package/commands/deploy.js.map +1 -0
  10. package/commands/doctor.d.ts +14 -12
  11. package/commands/doctor.d.ts.map +1 -1
  12. package/commands/doctor.js +35 -19
  13. package/commands/doctor.js.map +1 -1
  14. package/commands/repo.d.ts +24 -0
  15. package/commands/repo.d.ts.map +1 -0
  16. package/commands/repo.js +81 -0
  17. package/commands/repo.js.map +1 -0
  18. package/commands/run.d.ts +0 -15
  19. package/commands/run.d.ts.map +1 -1
  20. package/commands/run.js +45 -28
  21. package/commands/run.js.map +1 -1
  22. package/commands/workspace.d.ts +56 -0
  23. package/commands/workspace.d.ts.map +1 -0
  24. package/commands/workspace.js +177 -0
  25. package/commands/workspace.js.map +1 -0
  26. package/index.js +654 -132
  27. package/index.js.map +1 -1
  28. package/package.json +1 -1
  29. package/utils/agent-invoker.d.ts +33 -1
  30. package/utils/agent-invoker.d.ts.map +1 -1
  31. package/utils/agent-invoker.js +94 -13
  32. package/utils/agent-invoker.js.map +1 -1
  33. package/utils/config-store.d.ts +30 -58
  34. package/utils/config-store.d.ts.map +1 -1
  35. package/utils/config-store.js +27 -47
  36. package/utils/config-store.js.map +1 -1
  37. package/utils/mailbox-client.d.ts +23 -0
  38. package/utils/mailbox-client.d.ts.map +1 -1
  39. package/utils/mailbox-client.js +20 -0
  40. package/utils/mailbox-client.js.map +1 -1
  41. package/utils/run-workspace.d.ts +38 -4
  42. package/utils/run-workspace.d.ts.map +1 -1
  43. package/utils/run-workspace.js +126 -22
  44. package/utils/run-workspace.js.map +1 -1
package/index.js CHANGED
@@ -7,7 +7,7 @@ var __export = (target, all) => {
7
7
 
8
8
  // src/index.ts
9
9
  import { createRequire } from "node:module";
10
- import { Command as Command12 } from "commander";
10
+ import { Command as Command15 } from "commander";
11
11
 
12
12
  // src/commands/install.ts
13
13
  import { Command } from "commander";
@@ -5911,6 +5911,72 @@ function complianceFromRecord(score) {
5911
5911
  return { overall: s.overall, tier: s.tier, issues };
5912
5912
  }
5913
5913
 
5914
+ // ../shared/dist/cloud-connect.js
5915
+ var GITHUB_OIDC_THUMBPRINTS = ["6938fd4d98bab03faadb97b34396831e3780aea1", "1c58a3a8518e8759bf075b76b750d4f2df264fcd"];
5916
+ var AWS_SETUP_FUNCTION = `import json, urllib.error, urllib.request
5917
+ import boto3
5918
+
5919
+ ISSUER = "token.actions.githubusercontent.com"
5920
+
5921
+
5922
+ def respond(event, ok, data=None, reason=""):
5923
+ body = json.dumps({
5924
+ "Status": "SUCCESS" if ok else "FAILED",
5925
+ "Reason": (reason or "See the function's CloudWatch logs")[:1000],
5926
+ "PhysicalResourceId": event.get("PhysicalResourceId") or event["LogicalResourceId"],
5927
+ "StackId": event["StackId"],
5928
+ "RequestId": event["RequestId"],
5929
+ "LogicalResourceId": event["LogicalResourceId"],
5930
+ "Data": data or {},
5931
+ }).encode()
5932
+ req = urllib.request.Request(event["ResponseURL"], data=body, method="PUT", headers={"Content-Type": ""})
5933
+ urllib.request.urlopen(req, timeout=30)
5934
+
5935
+
5936
+ def github_oidc():
5937
+ iam = boto3.client("iam")
5938
+ for p in iam.list_open_id_connect_providers()["OpenIDConnectProviderList"]:
5939
+ arn = p["Arn"]
5940
+ if arn.endswith("/" + ISSUER):
5941
+ if "sts.amazonaws.com" not in iam.get_open_id_connect_provider(OpenIDConnectProviderArn=arn)["ClientIDList"]:
5942
+ iam.add_client_id_to_open_id_connect_provider(OpenIDConnectProviderArn=arn, ClientID="sts.amazonaws.com")
5943
+ return arn
5944
+ return iam.create_open_id_connect_provider(
5945
+ Url="https://" + ISSUER, ClientIDList=["sts.amazonaws.com"], ThumbprintList=${JSON.stringify(GITHUB_OIDC_THUMBPRINTS)}
5946
+ )["OpenIDConnectProviderArn"]
5947
+
5948
+
5949
+ def notify(p):
5950
+ body = json.dumps({
5951
+ "token": p["Token"], "accountId": p["AccountId"], "region": p["Region"],
5952
+ "roleArn": p["RoleArn"], "stateBucket": p["Bucket"],
5953
+ }).encode()
5954
+ req = urllib.request.Request(p["Url"], data=body, method="POST", headers={"Content-Type": "application/json"})
5955
+ try:
5956
+ urllib.request.urlopen(req, timeout=30)
5957
+ except urllib.error.HTTPError as e:
5958
+ raise RuntimeError("CompBox said: " + e.read().decode(errors="replace")[:500])
5959
+
5960
+
5961
+ def handler(event, context):
5962
+ try:
5963
+ props = event["ResourceProperties"]
5964
+ if event["RequestType"] == "Delete":
5965
+ return respond(event, True)
5966
+ if props["Action"] == "oidc":
5967
+ return respond(event, True, {"Arn": github_oidc()})
5968
+ try:
5969
+ notify(props)
5970
+ except Exception:
5971
+ # The connect link expires; a later stack update shouldn't fail on it.
5972
+ if event["RequestType"] != "Update":
5973
+ raise
5974
+ respond(event, True)
5975
+ except Exception as e:
5976
+ print(e)
5977
+ respond(event, False, reason=str(e))
5978
+ `;
5979
+
5914
5980
  // src/utils/config-store.ts
5915
5981
  var CONFIG_DIR_ENV = "COMPBOX_CONFIG_DIR";
5916
5982
  var PROJECT_DIR_ENV = "COMPBOX_PROJECT_DIR";
@@ -5969,28 +6035,22 @@ function applyPxpipeEnv(config, env = process.env) {
5969
6035
  env.PXPIPE_ENABLED = "false";
5970
6036
  }
5971
6037
  }
5972
- function resolveProjectDir(opts) {
5973
- const env = opts.env ?? process.env;
5974
- const candidates = [opts.flag, env[PROJECT_DIR_ENV], opts.config?.projectDir];
5975
- for (const candidate of candidates) {
6038
+ function resolveProjectDirForJob(projectRemote, opts) {
6039
+ const remote = normalizeGitRemote(projectRemote ?? "");
6040
+ if (remote.length === 0) {
6041
+ return { status: "no-remote" };
6042
+ }
6043
+ const entry = (opts.config?.projectDirs ?? []).find((e) => e.remote === remote);
6044
+ return entry ? { status: "registered", path: entry.path } : { status: "unregistered", remote };
6045
+ }
6046
+ function unusedLegacyProjectDir(config, env = process.env) {
6047
+ for (const candidate of [config?.projectDir, env[PROJECT_DIR_ENV]]) {
5976
6048
  if (typeof candidate === "string" && candidate.trim().length > 0) {
5977
6049
  return candidate.trim();
5978
6050
  }
5979
6051
  }
5980
6052
  return void 0;
5981
6053
  }
5982
- function resolveProjectDirForJob(projectRemote, opts) {
5983
- const remote = normalizeGitRemote(projectRemote ?? "");
5984
- if (remote.length > 0) {
5985
- const entry = (opts.config?.projectDirs ?? []).find((e) => e.remote === remote);
5986
- if (entry) {
5987
- return { status: "registered", path: entry.path };
5988
- }
5989
- return { status: "unregistered", remote };
5990
- }
5991
- const fallback = resolveProjectDir({ flag: opts.flag, env: opts.env, config: opts.config });
5992
- return fallback !== void 0 ? { status: "fallback", path: fallback } : { status: "unresolved" };
5993
- }
5994
6054
  function isGitRepoDir(dir) {
5995
6055
  try {
5996
6056
  return existsSync4(join4(dir, ".git")) && statSync(dir).isDirectory();
@@ -6653,6 +6713,25 @@ var MailboxClient = class {
6653
6713
  throw errorFromResponse(res, "saved failed");
6654
6714
  }
6655
6715
  }
6716
+ /**
6717
+ * Asks CompBox to open the run's pull request through the CompBox GitHub
6718
+ * app. Throws when the project isn't connected through the app (409), so
6719
+ * the caller can open it another way.
6720
+ */
6721
+ async openPullRequest(machineToken, jobId, input) {
6722
+ let res;
6723
+ try {
6724
+ res = await this.http.post(`/api/v1/jobs/${jobId}/pull-request`, input, {
6725
+ headers: { Authorization: `Bearer ${machineToken}` }
6726
+ });
6727
+ } catch (error) {
6728
+ throw toMailboxError(error, "pull-request request failed");
6729
+ }
6730
+ if (res.status < 200 || res.status >= 300) {
6731
+ throw errorFromResponse(res, "pull-request failed");
6732
+ }
6733
+ return res.data.data;
6734
+ }
6656
6735
  /** Reports what a run on the person's API key spent. */
6657
6736
  async reportAiUsage(machineToken, jobId, usage) {
6658
6737
  let res;
@@ -6921,6 +7000,7 @@ function installAutostart() {
6921
7000
  }
6922
7001
 
6923
7002
  // src/commands/configure.ts
7003
+ var PROJECT_FOLDER_QUESTION = "Add a project folder (a git checkout) \u2014 leave blank when done:";
6924
7004
  function parseAiMode(value) {
6925
7005
  if (value === "claude-subscription" || value === "api-key") {
6926
7006
  return value;
@@ -7015,78 +7095,47 @@ Device pairing failed: ${message}`));
7015
7095
  console.log(chalk7.gray(`
7016
7096
  Device already paired as "${config.machineName ?? config.machineId}".`));
7017
7097
  }
7018
- const defaultDir = isGitRepoDir(process.cwd()) ? process.cwd() : void 0;
7019
- console.log("\n" + chalk7.bold("Project folder:"));
7098
+ const legacyDir = config.projectDir?.trim();
7099
+ const registeredPaths = () => new Set(listProjectDirs().map((e) => e.path));
7100
+ const firstDefault = [process.cwd(), legacyDir].find(
7101
+ (dir) => typeof dir === "string" && dir.length > 0 && isGitRepoDir(dir) && !registeredPaths().has(dir)
7102
+ );
7103
+ console.log("\n" + chalk7.bold("Project folders:"));
7020
7104
  console.log(
7021
7105
  chalk7.gray(
7022
- " The folder with your code (a git project) where the AI plans, edits and commits.\n Leave blank to skip; add folders per project later with `compbox machines dirs add`."
7106
+ " Each project runs only in the folder you register for its repository (a git checkout\n with an origin remote). Add one folder per project. Leave blank when you are done."
7023
7107
  )
7024
7108
  );
7025
- const projectDirQuestion = "Which project folder should the AI work in?";
7026
- const MAX_PROJECT_DIR_ATTEMPTS = 5;
7027
- let projectDirPersisted = false;
7028
- let projectDirSkipped = false;
7029
- for (let attempt = 0; attempt < MAX_PROJECT_DIR_ATTEMPTS; attempt += 1) {
7030
- const answer = (await promptText(
7031
- projectDirQuestion,
7032
- defaultDir !== void 0 ? { defaultValue: defaultDir } : {}
7033
- )).trim();
7034
- if (answer.length === 0) {
7035
- projectDirSkipped = true;
7036
- break;
7037
- }
7038
- if (isGitRepoDir(answer)) {
7039
- updateConfig({ projectDir: answer });
7040
- console.log(chalk7.green(`\u2714 Project directory set to ${answer}`));
7041
- console.log(
7042
- chalk7.gray(" Dispatched plan/orchestrate runs will operate in this repository.")
7043
- );
7044
- projectDirPersisted = true;
7045
- break;
7046
- }
7047
- console.warn(
7048
- chalk7.yellow(
7049
- `\u26A0 ${answer} is not a git repository. Enter a path to a git checkout, or leave blank to skip.`
7109
+ if (legacyDir) {
7110
+ console.log(
7111
+ chalk7.gray(
7112
+ ` Note: this computer no longer uses a single default folder (${legacyDir}). Register it here if you still want runs for its repository to use it.`
7050
7113
  )
7051
7114
  );
7052
7115
  }
7053
- if (!projectDirPersisted) {
7054
- if (!projectDirSkipped) {
7055
- console.warn(
7056
- chalk7.yellow("\u26A0 No valid git repository entered \u2014 skipping the project directory for now.")
7057
- );
7116
+ const MAX_PROJECT_DIR_PROMPTS = 10;
7117
+ for (let attempt = 0; attempt < MAX_PROJECT_DIR_PROMPTS; attempt += 1) {
7118
+ const offerDefault = attempt === 0 && firstDefault !== void 0;
7119
+ const answer = (await promptText(PROJECT_FOLDER_QUESTION, offerDefault ? { defaultValue: firstDefault } : {})).trim();
7120
+ if (answer.length === 0) break;
7121
+ try {
7122
+ const entry = addProjectDir(answer);
7123
+ console.log(chalk7.green(`\u2714 Registered ${entry.remote} \u2192 ${entry.path}`));
7124
+ } catch (error) {
7125
+ const message = error instanceof Error ? error.message : "unknown error";
7126
+ console.warn(chalk7.yellow(`\u26A0 ${message} Enter another folder, or leave blank to finish.`));
7058
7127
  }
7128
+ }
7129
+ const registered = listProjectDirs();
7130
+ if (registered.length === 0) {
7059
7131
  console.log(
7060
7132
  chalk7.yellow(
7061
- "\n\u26A0 No project directory set \u2014 dispatched plan/orchestrate jobs will fail until one is configured."
7133
+ "\n\u26A0 No project folders registered \u2014 runs sent to this computer will be refused until you add one."
7062
7134
  )
7063
7135
  );
7064
- console.log(
7065
- chalk7.gray(
7066
- " Set it later with `compbox run --project-dir <path>`, the COMPBOX_PROJECT_DIR env var, or by re-running `compbox configure`."
7067
- )
7068
- );
7069
- }
7070
- if (isGitRepoDir(process.cwd())) {
7071
- const registerAllowlist = await promptConfirm(
7072
- "Register this repository (its origin remote \u2192 this path) so dispatched runs targeting it route to this machine?",
7073
- true
7074
- );
7075
- if (registerAllowlist) {
7076
- try {
7077
- const entry = addProjectDir(process.cwd());
7078
- console.log(chalk7.green(`\u2714 Registered ${entry.remote} \u2192 ${entry.path}`));
7079
- console.log(
7080
- chalk7.gray(" Manage the allowlist later with `compbox machines dirs list/add/rm`.")
7081
- );
7082
- } catch (error) {
7083
- const message = error instanceof Error ? error.message : "unknown error";
7084
- console.warn(chalk7.yellow(`\u26A0 Could not register this repository: ${message}`));
7085
- console.warn(
7086
- chalk7.gray(" You can register it later with `compbox machines dirs add`.")
7087
- );
7088
- }
7089
- }
7136
+ console.log(chalk7.gray(" Add one later with `compbox machines dirs add <path-to-checkout>`."));
7137
+ } else {
7138
+ console.log(chalk7.gray(` ${String(registered.length)} project folder(s) registered. Manage them with \`compbox machines dirs list/add/rm\`.`));
7090
7139
  }
7091
7140
  const mcpConfigPath = options.mcpConfig ?? defaultMcpConfigPath();
7092
7141
  const result = patchMcpConfig(mcpConfigPath, {
@@ -7695,26 +7744,40 @@ ${reRun}`
7695
7744
  };
7696
7745
  }
7697
7746
  function projectDirCheck(config) {
7698
- const name = "Project directory configured";
7699
- const dir = resolveProjectDir({ config });
7700
- if (dir === void 0) {
7747
+ const name = "Project folders registered";
7748
+ const entries = config.projectDirs ?? [];
7749
+ if (entries.length === 0) {
7701
7750
  return {
7702
7751
  name,
7703
7752
  passed: false,
7704
- detail: "No CompBox project repository is configured \u2014 run `compbox configure` to set one (start_execution/plan jobs fail until it is set)."
7753
+ detail: "No project folders are registered \u2014 runs sent to this computer are refused until you add one with `compbox machines dirs add <path>` (or `compbox configure`)."
7705
7754
  };
7706
7755
  }
7707
- if (!isGitRepoDir(dir)) {
7756
+ const broken = entries.filter((e) => !isGitRepoDir(e.path));
7757
+ if (broken.length > 0) {
7708
7758
  return {
7709
7759
  name,
7710
7760
  passed: false,
7711
- detail: `configured path is not a git repo: ${dir} \u2014 run \`compbox configure\` to point it at a CompBox repo checkout.`
7761
+ detail: `registered folder is not a git repo: ${broken.map((e) => `${e.remote} \u2192 ${e.path}`).join(", ")} \u2014 re-register it with \`compbox machines dirs add <path>\`.`
7712
7762
  };
7713
7763
  }
7714
7764
  return {
7715
7765
  name,
7716
7766
  passed: true,
7717
- detail: `Project repository configured at ${dir}.`
7767
+ detail: entries.map((e) => `${e.remote} \u2192 ${e.path}`).join("; ")
7768
+ };
7769
+ }
7770
+ function legacyProjectDirCheck(config, env = process.env) {
7771
+ const name = "Old default folder";
7772
+ const dir = unusedLegacyProjectDir(config, env);
7773
+ if (dir === void 0) {
7774
+ return { name, passed: true, skipped: true, detail: "not set" };
7775
+ }
7776
+ return {
7777
+ name,
7778
+ passed: true,
7779
+ warning: true,
7780
+ detail: `${dir} is set as a default folder but is no longer used \u2014 runs go only to the folder registered for their project's repository. Register it with \`compbox machines dirs add ${dir}\` if you still want it.`
7718
7781
  };
7719
7782
  }
7720
7783
  var doctorCommand = new Command7("doctor").description("Diagnose config, connectivity, machine pairing, MCP config, AI mode, and the service").option("--mcp-config <path>", "Path to the MCP config to check (default: ./.mcp.json)").action(async (options) => {
@@ -7867,6 +7930,7 @@ var doctorCommand = new Command7("doctor").description("Diagnose config, connect
7867
7930
  }
7868
7931
  results.push(await agentRuntimeCheck(config));
7869
7932
  results.push(projectDirCheck(config));
7933
+ results.push(legacyProjectDirCheck(config));
7870
7934
  if (process.platform === "darwin") {
7871
7935
  results.push(checkBrewService());
7872
7936
  }
@@ -8209,12 +8273,17 @@ function buildPlannerArgs(epicRequestId) {
8209
8273
  }
8210
8274
  function projectDirNotConfiguredMessage() {
8211
8275
  return [
8212
- "No CompBox project repository is configured for this machine, so the planner has nowhere to run.",
8213
- "Set one of the following and re-run the job:",
8214
- " - `compbox configure` \u2014 the guided setup prompts for and persists the project directory (recommended)",
8215
- " - `compbox run --project-dir <path-to-your-checkout>` (persisted for future runs)",
8216
- " - the COMPBOX_PROJECT_DIR environment variable",
8217
- "The path must be a git checkout of the CompBox repo (it needs the repo's .mcp.json and CLAUDE.md)."
8276
+ "This run has no project folder on this computer, so it can't run.",
8277
+ "Each run works only in the folder registered for its project's repository:",
8278
+ " - `compbox machines dirs add <path-to-your-checkout>` (or re-run `compbox configure`)",
8279
+ "CompBox never falls back to a default folder."
8280
+ ].join("\n");
8281
+ }
8282
+ function noProjectRemoteMessage() {
8283
+ return [
8284
+ "This run isn't linked to a project repository, so this computer won't run it.",
8285
+ "Update CompBox (`brew upgrade compbox`) or connect the project's repository in its Settings \u2192 Repository, then send the run again.",
8286
+ "CompBox only runs work in the folder registered for its project's repository \u2014 never in a default folder."
8218
8287
  ].join("\n");
8219
8288
  }
8220
8289
  function unregisteredRemoteMessage(remote) {
@@ -8230,11 +8299,11 @@ function unregisteredRemoteMessage(remote) {
8230
8299
  }
8231
8300
  function projectDirNotGitRepoMessage(dir) {
8232
8301
  return [
8233
- `The configured CompBox project directory is not a git repository: ${dir}`,
8234
- "The planner runs the local `claude` CLI in this directory so the repo's .mcp.json (CompBox MCP)",
8302
+ `The project folder registered for this run's repository is not a git repository: ${dir}`,
8303
+ "The planner runs the local `claude` CLI in this folder so the repo's .mcp.json (CompBox MCP)",
8235
8304
  "and CLAUDE.md (@agent routing) load \u2014 both require a real checkout.",
8236
- "Re-run `compbox configure` to point it at a git checkout of the CompBox repo (or set --project-dir /",
8237
- "COMPBOX_PROJECT_DIR to one), then re-run the job."
8305
+ "Register the right checkout with `compbox machines dirs add <path>` (or re-run `compbox configure`),",
8306
+ "then re-run the job."
8238
8307
  ].join("\n");
8239
8308
  }
8240
8309
  function scanJsonObjects(text) {
@@ -8321,6 +8390,9 @@ async function invokeStartExecutionPlan(ctx, deps = {}) {
8321
8390
  const baseEnv = {
8322
8391
  ...routedEnv,
8323
8392
  COMPBOX_NONINTERACTIVE: "1",
8393
+ // Claude Code otherwise starts sub-agents in the background; a headless
8394
+ // run then ends its turn and exits while the worker is still going.
8395
+ CLAUDE_CODE_DISABLE_BACKGROUND_TASKS: "1",
8324
8396
  PATH: claudeChildEnvPath(routedEnv.PATH)
8325
8397
  };
8326
8398
  const childEnv = ctx.keyRun ? keyRunEnv(baseEnv, ctx.keyRun) : baseEnv;
@@ -8431,11 +8503,15 @@ ${stderr}`;
8431
8503
  }
8432
8504
  var ORCHESTRATOR_RUN_TIMEOUT_MS = 3 * 60 * 60 * 1e3;
8433
8505
  var ORCHESTRATOR_HEARTBEAT_INTERVAL_MS = PLANNER_HEARTBEAT_INTERVAL_MS;
8506
+ var HEADLESS_ORCHESTRATE_REMINDER = "This is a non-interactive run: do NOT start sub-agents or reviews in the background and do not end your turn to wait for them. Run every step in this process and keep going until every feature is done or a hard gate stops the run.";
8434
8507
  var ORCHESTRATOR_FINAL_TURN_MAX_CHARS = 4e3;
8435
8508
  function buildOrchestratorArgs(epicId) {
8436
8509
  return [
8437
8510
  "-p",
8438
8511
  `@orchestrator execute epic ${epicId} --non-interactive`,
8512
+ // H3 reminder: never background work in a print-mode run.
8513
+ "--append-system-prompt",
8514
+ HEADLESS_ORCHESTRATE_REMINDER,
8439
8515
  // H1: unattended permission mode so print-mode tool use never blocks on an
8440
8516
  // interactive "allow?" prompt (this path grants the full MCP surface).
8441
8517
  "--permission-mode",
@@ -8447,7 +8523,7 @@ function orchestrateNotGitRepoMessage(dir) {
8447
8523
  `The configured CompBox project directory is not a git repository: ${dir}`,
8448
8524
  "The orchestrator runs the local `claude` CLI in this directory so the repo's .mcp.json (CompBox MCP)",
8449
8525
  "and CLAUDE.md (@agent routing) load, and it drives builds/tests through git worktrees \u2014 all require a real checkout.",
8450
- "Point --project-dir / COMPBOX_PROJECT_DIR at a git checkout of the CompBox repo and re-run the job."
8526
+ "Register the right checkout with `compbox machines dirs add <path>` and re-run the job."
8451
8527
  ].join("\n");
8452
8528
  }
8453
8529
  function worktreeUnavailableMessage(dir) {
@@ -8488,7 +8564,19 @@ function defaultToolchainPresent(_dir) {
8488
8564
  }
8489
8565
  return false;
8490
8566
  }
8567
+ function buildIncompleteRunResult(epicId, progress) {
8568
+ return {
8569
+ needsAttention: true,
8570
+ epicId,
8571
+ completedFeatures: progress.completedFeatures,
8572
+ totalFeatures: progress.totalFeatures,
8573
+ message: `The run stopped before finishing: ${String(progress.completedFeatures)} of ${String(progress.totalFeatures)} features done. Send the build again to continue.`
8574
+ };
8575
+ }
8491
8576
  function describeRunBranch(finish) {
8577
+ if (finish.needsAttention) {
8578
+ return `Needs attention: the run's work was kept in ${finish.keptWorktree ?? "its run folder"} (branch ${finish.branch}) because it couldn't all be committed.`;
8579
+ }
8492
8580
  if (finish.prUrl) return `Pull request: ${finish.prUrl}`;
8493
8581
  if (finish.compareUrl) return `Branch ${finish.branch} was pushed. Open the pull request here: ${finish.compareUrl}`;
8494
8582
  if (finish.commits === 0) return "No code changes were made.";
@@ -8554,6 +8642,9 @@ async function invokeStartExecutionOrchestrate(ctx, deps = {}) {
8554
8642
  const baseEnv = {
8555
8643
  ...routedEnv,
8556
8644
  COMPBOX_NONINTERACTIVE: "1",
8645
+ // Claude Code otherwise starts sub-agents in the background; a headless
8646
+ // run then ends its turn and exits while the worker is still going.
8647
+ CLAUDE_CODE_DISABLE_BACKGROUND_TASKS: "1",
8557
8648
  PATH: claudeChildEnvPath(routedEnv.PATH)
8558
8649
  };
8559
8650
  const childEnv = ctx.keyRun ? keyRunEnv(baseEnv, ctx.keyRun) : baseEnv;
@@ -8561,7 +8652,7 @@ async function invokeStartExecutionOrchestrate(ctx, deps = {}) {
8561
8652
  await ctx.mailboxClient.postTurn(
8562
8653
  ctx.machineToken,
8563
8654
  ctx.jobId,
8564
- `Started the orchestrator for epic ${ctx.epicId} (headless, non-interactive). This executes the full epic \u2014 every phase and feature \u2014 and may take a long time.` + (workspace ? ` Working on a new branch, ${workspace.branch}, which will end as a pull request into ${workspace.baseBranch}.` : "") + (workspaceNotes.length > 0 ? ` Note: ${workspaceNotes.join(" ")}` : "")
8655
+ `Started the orchestrator for epic ${ctx.epicId} (headless, non-interactive). This executes the full epic \u2014 every phase and feature \u2014 and may take a long time.` + (workspace ? workspace.continued ? ` Continuing the earlier unfinished work on ${workspace.branch}, which ends as a pull request into ${workspace.baseBranch}.` : ` Working on a new branch, ${workspace.branch}, which will end as a pull request into ${workspace.baseBranch}.` : "") + (workspaceNotes.length > 0 ? ` Note: ${workspaceNotes.join(" ")}` : "")
8565
8656
  );
8566
8657
  } catch {
8567
8658
  }
@@ -8632,6 +8723,25 @@ ${stderr}`;
8632
8723
  finish({ status: "done", result: { epicId: ctx.epicId } });
8633
8724
  });
8634
8725
  });
8726
+ if (outcome.status === "done") {
8727
+ const readProgress = deps.epicProgress ?? (async () => {
8728
+ try {
8729
+ const job = await ctx.mailboxClient.postTurn(
8730
+ ctx.machineToken,
8731
+ ctx.jobId,
8732
+ `The orchestrator finished. Checking epic ${ctx.epicId}'s progress in CompBox\u2026`
8733
+ );
8734
+ return job.progress ?? null;
8735
+ } catch {
8736
+ return null;
8737
+ }
8738
+ });
8739
+ const progress = await readProgress();
8740
+ if (progress && progress.totalFeatures > 0 && progress.completedFeatures < progress.totalFeatures) {
8741
+ outcome.status = "failed";
8742
+ outcome.result = buildIncompleteRunResult(ctx.epicId, progress);
8743
+ }
8744
+ }
8635
8745
  let branchLine = "";
8636
8746
  if (deps.workspace && workspace) {
8637
8747
  const resultError = outcome.result;
@@ -8651,8 +8761,17 @@ ${stderr}`;
8651
8761
  pushed: finished.pushed,
8652
8762
  ...finished.prUrl ? { prUrl: finished.prUrl } : {},
8653
8763
  ...finished.compareUrl ? { compareUrl: finished.compareUrl } : {},
8654
- ...finished.notes.length > 0 ? { branchNotes: finished.notes } : {}
8764
+ ...finished.notes.length > 0 ? { branchNotes: finished.notes } : {},
8765
+ ...finished.keptWorktree ? { keptWorktree: finished.keptWorktree } : {}
8655
8766
  };
8767
+ if (finished.needsAttention) {
8768
+ outcome.status = "failed";
8769
+ outcome.result = {
8770
+ ...outcome.result,
8771
+ needsAttention: true,
8772
+ message: `The run's work couldn't be saved to its branch, so it was kept in ${finished.keptWorktree ?? "its run folder"}.` + (typeof outcome.result.message === "string" ? ` ${outcome.result.message}` : "")
8773
+ };
8774
+ }
8656
8775
  }
8657
8776
  try {
8658
8777
  const summary = (outcome.status === "done" ? `Execution complete \u2014 epic ${ctx.epicId} finished all phases.` : `Orchestrator run ended: ${JSON.stringify(outcome.result).slice(0, ORCHESTRATOR_FINAL_TURN_MAX_CHARS)}`) + (branchLine ? `
@@ -8831,7 +8950,9 @@ var RunWorkspaceManager = class {
8831
8950
  exists;
8832
8951
  copyFile;
8833
8952
  env;
8953
+ openPullRequest;
8834
8954
  constructor(deps = {}) {
8955
+ this.openPullRequest = deps.openPullRequest;
8835
8956
  this.run = deps.run ?? defaultCommandRunner;
8836
8957
  this.now = deps.now ?? (() => /* @__PURE__ */ new Date());
8837
8958
  this.runsRoot = deps.runsRoot ?? join10(getConfigDir(), "runs");
@@ -8899,11 +9020,25 @@ var RunWorkspaceManager = class {
8899
9020
  baseRef = "HEAD";
8900
9021
  }
8901
9022
  const when = stamp(this.now());
8902
- const branch = `compbox/epic-${slugForBranch(epicId)}-${when}`;
8903
9023
  const dir = join10(this.runsRoot, `${slugForBranch(basename2(projectDir))}-${slugForBranch(epicId)}-${when}`);
8904
9024
  mkdirSync6(this.runsRoot, { recursive: true });
8905
- const add = await this.git(["worktree", "add", "-b", branch, dir, baseRef], projectDir);
8906
- if (add.status !== 0) {
9025
+ let branch = `compbox/epic-${slugForBranch(epicId)}-${when}`;
9026
+ let continued = false;
9027
+ const previous = remote ? await this.unfinishedBranch(remote, slugForBranch(epicId), baseRef, projectDir) : null;
9028
+ if (remote && previous) {
9029
+ const resume = await this.git(["worktree", "add", "-B", previous, dir, `${remote}/${previous}`], projectDir);
9030
+ if (resume.status === 0) {
9031
+ branch = previous;
9032
+ continued = true;
9033
+ notes.push(`Continuing the earlier unfinished work on ${previous}.`);
9034
+ } else {
9035
+ notes.push(
9036
+ `Couldn't continue the earlier unfinished branch ${previous} (${firstLine(resume.stderr) || "unknown error"}), so the run starts a new branch.`
9037
+ );
9038
+ }
9039
+ }
9040
+ const add = continued ? null : await this.git(["worktree", "add", "-b", branch, dir, baseRef], projectDir);
9041
+ if (add && add.status !== 0) {
8907
9042
  return {
8908
9043
  ok: false,
8909
9044
  error: [
@@ -8926,7 +9061,18 @@ ${untracked.stdout}`.split("\n").map((p) => p.trim()).filter((p) => p && !p.ends
8926
9061
  notes.push(`Couldn't copy ${path3} into the run workspace.`);
8927
9062
  }
8928
9063
  }
8929
- return { ok: true, workspace: { dir, projectDir, branch, baseRef, baseBranch, remote }, notes };
9064
+ return { ok: true, workspace: { dir, projectDir, branch, baseRef, baseBranch, remote, continued }, notes };
9065
+ }
9066
+ /** The newest pushed run branch for this epic that isn't merged into the base yet, if any. */
9067
+ async unfinishedBranch(remote, epicSlug, baseRef, projectDir) {
9068
+ const refs = await this.git(
9069
+ ["for-each-ref", "--sort=-refname", "--format=%(refname:short)", `refs/remotes/${remote}/compbox/epic-${epicSlug}-*`],
9070
+ projectDir
9071
+ );
9072
+ const latest = refs.stdout.split("\n").map((r) => r.trim()).find(Boolean);
9073
+ if (!latest?.startsWith(`${remote}/`)) return null;
9074
+ if ((await this.git(["merge-base", "--is-ancestor", latest, baseRef], projectDir)).status === 0) return null;
9075
+ return latest.slice(remote.length + 1);
8930
9076
  }
8931
9077
  /** Commits, pushes and opens the pull request; then cleans up the worktree. */
8932
9078
  finish(input) {
@@ -8935,26 +9081,42 @@ ${untracked.stdout}`.split("\n").map((p) => p.trim()).filter((p) => p && !p.ends
8935
9081
  async finishLocked(input) {
8936
9082
  const { workspace: ws } = input;
8937
9083
  const notes = [];
8938
- if ((await this.git(["status", "--porcelain"], ws.dir)).stdout.trim()) {
9084
+ const dirtyBefore = await this.isDirty(ws.dir);
9085
+ let commitFailed = false;
9086
+ if (dirtyBefore) {
8939
9087
  await this.git(["add", "-A"], ws.dir);
8940
9088
  const commit = await this.git(
8941
- ["commit", "-m", `chore(compbox): save work left uncommitted by the orchestrator (epic ${input.epicId})`],
9089
+ ["commit", "--no-verify", "-m", `chore(compbox): save work left uncommitted by the orchestrator (epic ${input.epicId})`],
8942
9090
  ws.dir
8943
9091
  );
8944
9092
  if (commit.status !== 0) {
8945
- notes.push(`Couldn't commit the remaining changes: ${firstLine(commit.stderr) || firstLine(commit.stdout)}`);
9093
+ commitFailed = true;
9094
+ notes.push(`Couldn't commit the remaining changes: ${firstLine(commit.stderr) || firstLine(commit.stdout) || "unknown error"}`);
8946
9095
  }
8947
9096
  }
8948
9097
  const commits = Number.parseInt((await this.git(["rev-list", "--count", `${ws.baseRef}..HEAD`], ws.dir)).stdout.trim(), 10) || 0;
8949
9098
  const base = { branch: ws.branch, commits, pushed: false, notes };
9099
+ if (commitFailed || dirtyBefore && await this.isDirty(ws.dir)) {
9100
+ notes.push(`The run's changes couldn't all be committed, so nothing was removed. They are safe in ${ws.dir} on branch ${ws.branch}.`);
9101
+ return { ...base, keptWorktree: ws.dir, needsAttention: true };
9102
+ }
8950
9103
  if (commits === 0) {
8951
- await this.git(["worktree", "remove", "--force", ws.dir], ws.projectDir);
8952
- await this.git(["branch", "-D", ws.branch], ws.projectDir);
8953
- notes.push("The run made no code changes, so there is nothing to review.");
8954
- return base;
9104
+ if (!dirtyBefore) {
9105
+ if (await this.removeWorktree(ws, notes)) {
9106
+ await this.git(["branch", "-D", ws.branch], ws.projectDir);
9107
+ } else {
9108
+ return { ...base, keptWorktree: ws.dir, needsAttention: true };
9109
+ }
9110
+ notes.push("The run made no code changes, so there is nothing to review.");
9111
+ return base;
9112
+ }
9113
+ notes.push(`The run's changes didn't end up in a commit, so nothing was removed. Check ${ws.dir} on branch ${ws.branch}.`);
9114
+ return { ...base, keptWorktree: ws.dir, needsAttention: true };
8955
9115
  }
8956
9116
  if (!ws.remote || this.env[RUN_PUSH_ENV] === "0") {
8957
- await this.git(["worktree", "remove", "--force", ws.dir], ws.projectDir);
9117
+ if (!await this.removeWorktree(ws, notes)) {
9118
+ return { ...base, keptWorktree: ws.dir, needsAttention: true };
9119
+ }
8958
9120
  notes.push(
8959
9121
  ws.remote ? `Pushing is turned off (${RUN_PUSH_ENV}=0). The work is on the local branch ${ws.branch}.` : `The repository has no remote, so the work is on the local branch ${ws.branch}.`
8960
9122
  );
@@ -8975,10 +9137,25 @@ ${untracked.stdout}`.split("\n").map((p) => p.trim()).filter((p) => p && !p.ends
8975
9137
  "",
8976
9138
  `${String(commits)} commit${commits === 1 ? "" : "s"} on \`${ws.branch}\`, based on \`${ws.baseBranch}\`.`
8977
9139
  ].join("\n");
8978
- const prArgs = ["pr", "create", "--base", ws.baseBranch, "--head", ws.branch, "--title", title, "--body", body];
8979
- if (!input.completed) prArgs.push("--draft");
8980
- const pr = await this.run("gh", prArgs, ws.dir);
8981
- const prUrl = pr.status === 0 ? /https:\/\/\S+/.exec(pr.stdout)?.[0] : void 0;
9140
+ let prUrl;
9141
+ if (this.openPullRequest) {
9142
+ try {
9143
+ prUrl = (await this.openPullRequest({ branch: ws.branch, base: ws.baseBranch, title, body, draft: !input.completed })).url;
9144
+ } catch {
9145
+ prUrl = void 0;
9146
+ }
9147
+ }
9148
+ let pr = { status: 0, stdout: "", stderr: "" };
9149
+ if (!prUrl) {
9150
+ const prArgs = ["pr", "create", "--base", ws.baseBranch, "--head", ws.branch, "--title", title, "--body", body];
9151
+ if (!input.completed) prArgs.push("--draft");
9152
+ pr = await this.run("gh", prArgs, ws.dir);
9153
+ prUrl = pr.status === 0 ? /https:\/\/\S+/.exec(pr.stdout)?.[0] : void 0;
9154
+ if (!prUrl && ws.continued) {
9155
+ const existing = await this.run("gh", ["pr", "view", ws.branch, "--json", "url", "--jq", ".url"], ws.dir);
9156
+ if (existing.status === 0) prUrl = /https:\/\/\S+/.exec(existing.stdout)?.[0];
9157
+ }
9158
+ }
8982
9159
  let compareUrl;
8983
9160
  if (!prUrl) {
8984
9161
  const remoteUrl = (await this.git(["remote", "get-url", ws.remote], ws.dir)).stdout.trim();
@@ -8987,8 +9164,32 @@ ${untracked.stdout}`.split("\n").map((p) => p.trim()).filter((p) => p && !p.ends
8987
9164
  `The branch was pushed, but the pull request couldn't be opened automatically${firstLine(pr.stderr) ? ` (${firstLine(pr.stderr)})` : ""}.` + (compareUrl ? " Use the link to open it." : ` Open a pull request for ${ws.branch} on your git host.`)
8988
9165
  );
8989
9166
  }
9167
+ const removed = await this.removeWorktree(ws, notes);
9168
+ return {
9169
+ ...base,
9170
+ pushed: true,
9171
+ ...prUrl ? { prUrl } : {},
9172
+ ...compareUrl ? { compareUrl } : {},
9173
+ ...removed ? {} : { keptWorktree: ws.dir, needsAttention: true }
9174
+ };
9175
+ }
9176
+ /** True when the worktree has uncommitted (or unreadable) state. */
9177
+ async isDirty(dir) {
9178
+ const status = await this.git(["status", "--porcelain"], dir);
9179
+ return status.status !== 0 || status.stdout.trim().length > 0;
9180
+ }
9181
+ /**
9182
+ * Removes a run's worktree — a separate step, run only once the worktree is
9183
+ * verified clean (everything is committed). Returns false, keeping the
9184
+ * worktree and noting why, when it still has changes.
9185
+ */
9186
+ async removeWorktree(ws, notes) {
9187
+ if (await this.isDirty(ws.dir)) {
9188
+ notes.push(`The run's folder still has uncommitted changes, so it was kept: ${ws.dir} (branch ${ws.branch}).`);
9189
+ return false;
9190
+ }
8990
9191
  await this.git(["worktree", "remove", "--force", ws.dir], ws.projectDir);
8991
- return { ...base, pushed: true, ...prUrl ? { prUrl } : {}, ...compareUrl ? { compareUrl } : {} };
9192
+ return true;
8992
9193
  }
8993
9194
  };
8994
9195
 
@@ -9230,15 +9431,16 @@ async function handleStartExecution(ctx, job) {
9230
9431
  );
9231
9432
  return;
9232
9433
  }
9233
- const routed = resolveProjectDirForJob(payload.projectRemote, {
9234
- flag: ctx.projectDirFlag,
9235
- config: readConfig()
9236
- });
9434
+ const routed = resolveProjectDirForJob(payload.projectRemote, { config: readConfig() });
9237
9435
  if (routed.status === "unregistered") {
9238
9436
  await completeWithFailure(ctx, job, unregisteredRemoteMessage(routed.remote));
9239
9437
  return;
9240
9438
  }
9241
- const jobProjectDir = routed.status === "registered" || routed.status === "fallback" ? routed.path : void 0;
9439
+ if (routed.status === "no-remote") {
9440
+ await completeWithFailure(ctx, job, noProjectRemoteMessage());
9441
+ return;
9442
+ }
9443
+ const jobProjectDir = routed.path;
9242
9444
  let keyRun;
9243
9445
  if (payload.useAiKey) {
9244
9446
  try {
@@ -9311,8 +9513,11 @@ async function handleStartExecution(ctx, job) {
9311
9513
  // H4: keep this machine online during the long orchestrator run — the
9312
9514
  // poll loop (its own heartbeat) is blocked for the whole job.
9313
9515
  heartbeat: () => ctx.client.heartbeat(ctx.machineToken).catch(() => void 0),
9314
- // Own branch + worktree per run, finishing with a pull request.
9315
- workspace: new RunWorkspaceManager()
9516
+ // Own branch + worktree per run, finishing with a pull request (opened
9517
+ // through CompBox's GitHub app when the project is connected to it).
9518
+ workspace: new RunWorkspaceManager({
9519
+ openPullRequest: (input) => ctx.client.openPullRequest(ctx.machineToken, job.id, input)
9520
+ })
9316
9521
  }
9317
9522
  )
9318
9523
  );
@@ -9400,10 +9605,18 @@ var runCommand = new Command8("run").description("Start the Agent Runner daemon
9400
9605
  `Server-side hold per request, ms (default ${String(POLL_WAIT_MS)} \u2014 the server answers immediately and the daemon paces itself; raising this bills Cloud Run vCPU for the whole hold)`
9401
9606
  ).option(
9402
9607
  "--project-dir <path>",
9403
- "CompBox project repo the planner runs in for start_execution jobs (persisted; also settable via COMPBOX_PROJECT_DIR)"
9608
+ "Register a project folder (a git checkout) for its repository before starting \u2014 same as `compbox machines dirs add <path>`. There is no default folder."
9404
9609
  ).action(async (options) => {
9405
9610
  if (options.projectDir && options.projectDir.trim().length > 0) {
9406
- updateConfig({ projectDir: options.projectDir.trim() });
9611
+ try {
9612
+ const entry = addProjectDir(options.projectDir.trim());
9613
+ console.log(chalk9.green(`Registered ${entry.remote} \u2192 ${entry.path}`));
9614
+ } catch (error) {
9615
+ console.error(chalk9.red(`
9616
+ Couldn't register ${options.projectDir.trim()}: ${error instanceof Error ? error.message : String(error)}`));
9617
+ process.exit(1);
9618
+ return;
9619
+ }
9407
9620
  }
9408
9621
  const config = readConfig();
9409
9622
  applyPxpipeEnv(config);
@@ -9438,23 +9651,29 @@ var runCommand = new Command8("run").description("Start the Agent Runner daemon
9438
9651
  }
9439
9652
  const waitMs = options.waitMs ? Number.parseInt(options.waitMs, 10) : POLL_WAIT_MS;
9440
9653
  const client = new MailboxClient(config.apiBaseUrl);
9441
- const projectDir = resolveProjectDir({ flag: options.projectDir, config });
9442
9654
  const jobContext = {
9443
9655
  client,
9444
9656
  machineToken,
9445
9657
  apiBaseUrl: config.apiBaseUrl,
9446
9658
  aiMode: config.aiMode,
9447
- userApiToken: config.apiToken,
9448
- projectDir,
9449
- // ENG-179: preserve the raw flag so per-job fallback resolution reproduces
9450
- // flag→env→config precedence for jobs without a projectRemote.
9451
- projectDirFlag: options.projectDir
9659
+ userApiToken: config.apiToken
9452
9660
  };
9661
+ const folders = config.projectDirs ?? [];
9662
+ const legacyDir = unusedLegacyProjectDir(config);
9453
9663
  console.log(chalk9.bold("\nCompBox Agent Runner\n"));
9454
9664
  console.log(chalk9.gray(` Central: ${config.apiBaseUrl}`));
9455
9665
  console.log(chalk9.gray(` Machine: ${config.machineName ?? config.machineId}`));
9456
9666
  console.log(chalk9.gray(` AI mode: ${config.aiMode ?? "unset"}`));
9457
- console.log(chalk9.gray(` Project: ${projectDir ?? "(unset \u2014 run `compbox configure` to set it; start_execution/plan jobs fail until then)"}`));
9667
+ if (folders.length === 0) {
9668
+ console.log(chalk9.yellow(" Projects: none registered \u2014 runs are refused until you add one (`compbox machines dirs add <path>`)."));
9669
+ } else {
9670
+ for (const entry of folders) {
9671
+ console.log(chalk9.gray(` Project: ${entry.remote} \u2192 ${entry.path}`));
9672
+ }
9673
+ }
9674
+ if (legacyDir) {
9675
+ console.log(chalk9.yellow(` Note: the old default folder (${legacyDir}) is no longer used. Runs go only to a project's registered folder.`));
9676
+ }
9458
9677
  console.log(
9459
9678
  chalk9.gray(
9460
9679
  ` Polling for jobs (every ${String(Math.round(IDLE_POLL_INTERVAL_MS / 1e3))}s idle, ${String(Math.round(ACTIVE_POLL_INTERVAL_MS / 1e3))}s while a session is active)...
@@ -9811,16 +10030,316 @@ machinesCommand.command("rm <id>").description("Remove (revoke) a paired machine
9811
10030
  }
9812
10031
  });
9813
10032
 
10033
+ // src/commands/repo.ts
10034
+ import { Command as Command12 } from "commander";
10035
+ import chalk13 from "chalk";
10036
+ function findProject(projects, query) {
10037
+ const q = query.trim().toLowerCase();
10038
+ return projects.find((p) => p.key.toLowerCase() === q) ?? projects.find((p) => p.name.toLowerCase() === q) ?? null;
10039
+ }
10040
+ async function listProjects(apiBaseUrl, apiToken) {
10041
+ const res = await fetch(`${apiBaseUrl.replace(/\/+$/, "")}/api/v1/teams?limit=100`, {
10042
+ headers: { Authorization: `Bearer ${apiToken}` }
10043
+ });
10044
+ if (!res.ok) throw new Error(`CompBox returned ${String(res.status)} listing projects`);
10045
+ const body = await res.json();
10046
+ return body.data ?? [];
10047
+ }
10048
+ var repoCommand = new Command12("repo").description("Set up projects' repositories on this computer");
10049
+ repoCommand.command("setup <project>").description("Clone (or adopt) a project's repository on this computer so its runs land there").option("--folder <path>", "Where to put it (default ~/CompBox/<repo>)").action(async (project, options) => {
10050
+ const config = readConfig();
10051
+ if (!config.apiBaseUrl || !config.apiToken) {
10052
+ console.error(chalk13.red("\nNot logged in. Run `compbox login` first."));
10053
+ process.exit(1);
10054
+ return;
10055
+ }
10056
+ let projects;
10057
+ try {
10058
+ projects = await listProjects(config.apiBaseUrl, config.apiToken);
10059
+ } catch (error) {
10060
+ console.error(chalk13.red(`
10061
+ ${error instanceof Error ? error.message : "Could not reach CompBox."}`));
10062
+ process.exit(1);
10063
+ return;
10064
+ }
10065
+ const match = findProject(projects, project);
10066
+ if (!match) {
10067
+ console.error(chalk13.red(`
10068
+ No project called "${project}". Your projects: ${projects.map((p) => p.key).join(", ") || "none"}.`));
10069
+ process.exit(1);
10070
+ return;
10071
+ }
10072
+ if (!match.gitRemote) {
10073
+ console.error(
10074
+ chalk13.red(`
10075
+ ${match.name} has no repository yet. Connect one on the project's Settings \u2192 Repository page first.`)
10076
+ );
10077
+ process.exit(1);
10078
+ return;
10079
+ }
10080
+ console.log(chalk13.gray(`
10081
+ Setting up ${match.name} (${match.gitRemote})...`));
10082
+ const outcome = await invokeConnectRepo({
10083
+ teamId: match.id,
10084
+ projectRemote: match.gitRemote,
10085
+ projectName: match.name,
10086
+ ...options.folder && { folder: options.folder }
10087
+ });
10088
+ const result = outcome.result;
10089
+ if (outcome.status === "done") {
10090
+ console.log(chalk13.green(`\u2713 ${typeof result.message === "string" ? result.message : "Set up."}`));
10091
+ console.log(chalk13.gray(" The CompBox app reports it to CompBox on its next check-in."));
10092
+ } else {
10093
+ console.error(chalk13.red(`\u2716 ${typeof result.error === "string" ? result.error : "Setting it up failed."}`));
10094
+ process.exit(1);
10095
+ }
10096
+ });
10097
+
10098
+ // src/commands/workspace.ts
10099
+ import { Command as Command13 } from "commander";
10100
+ import chalk14 from "chalk";
10101
+ import { spawnSync as spawnSync2 } from "node:child_process";
10102
+ import { mkdirSync as mkdirSync8, writeFileSync as writeFileSync5 } from "node:fs";
10103
+ import { homedir as homedir7 } from "node:os";
10104
+ import { join as join12 } from "node:path";
10105
+ function readWorkspaceEnv(env = process.env) {
10106
+ const apiUrl = env.COMPBOX_API_URL?.trim();
10107
+ const jobId = env.COMPBOX_JOB_ID?.trim();
10108
+ const token = env.COMPBOX_WORKSPACE_TOKEN?.trim();
10109
+ if (!apiUrl || !jobId || !token) return null;
10110
+ return { apiUrl: apiUrl.replace(/\/+$/, ""), jobId, token };
10111
+ }
10112
+ async function workspaceApi(env, path3, method, fetchFn) {
10113
+ const res = await fetchFn(`${env.apiUrl}/api/v1/cloud-runs/workspace/${path3}`, {
10114
+ method,
10115
+ headers: { Authorization: `Bearer ${env.token}`, ...method === "POST" && { "Content-Type": "application/json" } },
10116
+ ...method === "POST" && { body: "{}" }
10117
+ });
10118
+ if (!res.ok) {
10119
+ const body = await res.json().catch(() => null);
10120
+ throw new Error(body?.error?.message ?? `CompBox returned ${String(res.status)} for ${path3}`);
10121
+ }
10122
+ return (await res.json()).data;
10123
+ }
10124
+ var defaultRunner = (command, args, cwd) => {
10125
+ const res = spawnSync2(command, args, { cwd, encoding: "utf-8", env: { ...process.env, GIT_TERMINAL_PROMPT: "0" } });
10126
+ if (res.status !== 0) {
10127
+ throw new Error(`${command} ${args[0] ?? ""} failed: ${(res.stderr || res.stdout || "").trim().split("\n").pop() ?? ""}`);
10128
+ }
10129
+ };
10130
+ function agentRoutingInstructions(agentsDir, compboxRoot = "/opt/compbox") {
10131
+ return `# CompBox cloud workspace
10132
+
10133
+ When a prompt starts with \`@<agent-name>\` (for example \`@planner\` or \`@orchestrator\`), read the agent file at \`${agentsDir}/<agent-name>.md\` in full and follow it exactly.
10134
+
10135
+ CompBox's own files live outside the project: any path an agent file mentions under \`.github/agents/\` or \`.github/skills/\` is at \`${compboxRoot}/.github/agents/\` or \`${compboxRoot}/.github/skills/\`. Never copy them into the project.
10136
+
10137
+ Never push to the default branch: work on the run's own branch.
10138
+ `;
10139
+ }
10140
+ async function runWorkspace(deps = {}) {
10141
+ const env = readWorkspaceEnv(deps.env);
10142
+ if (!env) {
10143
+ console.error(chalk14.red("Not a CompBox cloud workspace (COMPBOX_API_URL, COMPBOX_JOB_ID, COMPBOX_WORKSPACE_TOKEN)."));
10144
+ return 2;
10145
+ }
10146
+ const fetchFn = deps.fetchFn ?? fetch;
10147
+ const run = deps.run ?? defaultRunner;
10148
+ const home = deps.home ?? homedir7();
10149
+ const agentsDir = deps.agentsDir ?? "/opt/compbox/.github/agents/claude";
10150
+ const workDir = deps.workDir ?? "/workspace";
10151
+ const client = deps.client ?? new MailboxClient(env.apiUrl);
10152
+ const job = await client.nextJob(env.token, 0);
10153
+ if (job?.id !== env.jobId) {
10154
+ console.log("Nothing to do: the job has already finished.");
10155
+ return 0;
10156
+ }
10157
+ const fail = async (error) => {
10158
+ console.error(chalk14.red(error));
10159
+ await client.completeJob(env.token, job.id, "failed", { error }).catch(() => void 0);
10160
+ return 1;
10161
+ };
10162
+ const payload = job.payload ?? {};
10163
+ const repoDir = join12(workDir, "repo");
10164
+ let userApiToken;
10165
+ let keyRun;
10166
+ try {
10167
+ const git = await workspaceApi(env, "git-credentials", "GET", fetchFn);
10168
+ userApiToken = (await workspaceApi(env, "session", "POST", fetchFn)).userApiToken;
10169
+ const key = await client.getAiKey(env.token, job.id);
10170
+ keyRun = { apiKey: key.apiKey, model: key.model };
10171
+ run("git", ["config", "--global", "credential.helper", "!compbox workspace git-credential"]);
10172
+ run("git", ["config", "--global", "user.name", "CompBox"]);
10173
+ run("git", ["config", "--global", "user.email", "bot@mycompbox.com"]);
10174
+ mkdirSync8(workDir, { recursive: true });
10175
+ run("git", ["clone", "--branch", git.defaultBranch, git.cloneUrl, repoDir]);
10176
+ run("claude", [
10177
+ "mcp",
10178
+ "add",
10179
+ "--scope",
10180
+ "user",
10181
+ "-e",
10182
+ `API_BASE_URL=${env.apiUrl}`,
10183
+ "-e",
10184
+ `API_TOKEN=${userApiToken}`,
10185
+ "compbox",
10186
+ "--",
10187
+ "compbox-mcp"
10188
+ ]);
10189
+ mkdirSync8(join12(home, ".claude"), { recursive: true });
10190
+ writeFileSync5(join12(home, ".claude", "CLAUDE.md"), agentRoutingInstructions(agentsDir));
10191
+ } catch (error) {
10192
+ return fail(`Setting up the cloud workspace failed: ${error instanceof Error ? error.message : String(error)}`);
10193
+ }
10194
+ const heartbeat = () => client.heartbeat(env.token).then(() => void 0).catch(() => void 0);
10195
+ let outcome;
10196
+ if (payload.kind === "plan" && payload.epicRequestId) {
10197
+ outcome = await (deps.plan ?? invokeStartExecutionPlan)(
10198
+ {
10199
+ mailboxClient: client,
10200
+ machineToken: env.token,
10201
+ jobId: job.id,
10202
+ apiBaseUrl: env.apiUrl,
10203
+ userApiToken,
10204
+ epicRequestId: payload.epicRequestId,
10205
+ projectDir: repoDir,
10206
+ keyRun
10207
+ },
10208
+ { heartbeat }
10209
+ );
10210
+ } else if (payload.kind === "orchestrate" && payload.epicId) {
10211
+ outcome = await (deps.orchestrate ?? invokeStartExecutionOrchestrate)(
10212
+ {
10213
+ mailboxClient: client,
10214
+ machineToken: env.token,
10215
+ jobId: job.id,
10216
+ epicId: payload.epicId,
10217
+ projectDir: repoDir,
10218
+ keyRun
10219
+ },
10220
+ {
10221
+ heartbeat,
10222
+ workspace: new RunWorkspaceManager({
10223
+ openPullRequest: (input) => client.openPullRequest(env.token, job.id, input)
10224
+ })
10225
+ }
10226
+ );
10227
+ } else {
10228
+ return fail("The job is missing what to plan or build.");
10229
+ }
10230
+ await client.completeJob(env.token, job.id, outcome.status, outcome.result);
10231
+ console.log(outcome.status === "done" ? chalk14.green("Finished.") : chalk14.yellow(`Stopped: ${JSON.stringify(outcome.result)}`));
10232
+ return outcome.status === "done" ? 0 : 1;
10233
+ }
10234
+ async function gitCredential(action, deps = {}) {
10235
+ if (action !== "get") return;
10236
+ const env = readWorkspaceEnv(deps.env);
10237
+ if (!env) return;
10238
+ const git = await workspaceApi(env, "git-credentials", "GET", deps.fetchFn ?? fetch);
10239
+ (deps.write ?? ((s) => process.stdout.write(s)))(`username=${git.username}
10240
+ password=${git.token}
10241
+ `);
10242
+ }
10243
+ var workspaceCommand = new Command13("workspace").description("Run inside a CompBox cloud workspace (used by CompBox)");
10244
+ workspaceCommand.command("run").description("Run this workspace's one plan or build job").action(async () => {
10245
+ process.exitCode = await runWorkspace();
10246
+ });
10247
+ workspaceCommand.command("git-credential <action>").description("Git credential helper for the workspace repository").action(async (action) => {
10248
+ await gitCredential(action);
10249
+ });
10250
+
10251
+ // src/commands/deploy.ts
10252
+ import { Command as Command14 } from "commander";
10253
+ import chalk15 from "chalk";
10254
+ var SLACK_MS = 6e4;
10255
+ var WAIT_LIMIT_MS = 30 * 6e4;
10256
+ async function call(deps, path3, init = {}) {
10257
+ const res = await (deps.fetchFn ?? fetch)(`${deps.apiBaseUrl.replace(/\/+$/, "")}/api/v1${path3}`, {
10258
+ method: init.method ?? "GET",
10259
+ headers: {
10260
+ Authorization: `Bearer ${deps.apiToken}`,
10261
+ ...init.body !== void 0 && { "Content-Type": "application/json" }
10262
+ },
10263
+ ...init.body !== void 0 && { body: JSON.stringify(init.body) }
10264
+ });
10265
+ const body = await res.json().catch(() => null);
10266
+ if (!res.ok) throw new Error(body?.error?.message ?? body?.message ?? `CompBox returned ${String(res.status)}`);
10267
+ return body?.data;
10268
+ }
10269
+ async function deployProject(deps, teamId, environment, wait) {
10270
+ const log = deps.log ?? ((line) => {
10271
+ console.log(line);
10272
+ });
10273
+ const now = deps.now ?? Date.now;
10274
+ const sleep2 = deps.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
10275
+ const startedAt = now();
10276
+ const queued = await call(deps, `/teams/${teamId}/deployments`, { method: "POST", body: { environment } });
10277
+ log(chalk15.gray(`Deploying to ${environment}...`));
10278
+ if (!wait) {
10279
+ log(`Started. When it's done it'll be at ${queued.url}`);
10280
+ return 0;
10281
+ }
10282
+ let last = "";
10283
+ while (now() - startedAt < WAIT_LIMIT_MS) {
10284
+ await sleep2(5e3);
10285
+ const list = await call(deps, `/teams/${teamId}/deployments`);
10286
+ const d = list.find((x) => x.environment === environment);
10287
+ const current = d?.runUrl && d.startedAt && Date.parse(d.startedAt) >= startedAt - SLACK_MS ? d : null;
10288
+ if (!current) continue;
10289
+ if (current.state !== last) {
10290
+ last = current.state;
10291
+ if (current.state === "in_progress") log(chalk15.gray(`Building and deploying (${current.runUrl ?? ""})...`));
10292
+ }
10293
+ if (current.state === "success") {
10294
+ log(chalk15.green(`
10295
+ Live: ${current.url}`));
10296
+ return 0;
10297
+ }
10298
+ if (current.state === "failure" || current.state === "cancelled") {
10299
+ log(chalk15.red(`
10300
+ The deploy ${current.state === "failure" ? "failed" : "was cancelled"}. Run log: ${current.runUrl ?? ""}`));
10301
+ return 1;
10302
+ }
10303
+ }
10304
+ log(chalk15.yellow(`
10305
+ Still running after 30 minutes. Follow it on GitHub; it'll be at ${queued.url}`));
10306
+ return 1;
10307
+ }
10308
+ var deployCommand = new Command14("deploy").description("Deploy a project (its default branch) and print the live address").argument("<project>", "The project's key (e.g. SHOP) or name").option("--env <environment>", "dev, stage or prod", "dev").option("--no-wait", "Start the deploy and don't wait for it").action(async (project, options) => {
10309
+ const config = readConfig();
10310
+ if (!config.apiBaseUrl || !config.apiToken) {
10311
+ console.error(chalk15.red("\nNot logged in. Run `compbox login` first."));
10312
+ process.exit(1);
10313
+ return;
10314
+ }
10315
+ const deps = { apiBaseUrl: config.apiBaseUrl, apiToken: config.apiToken };
10316
+ try {
10317
+ const projects = await listProjects(config.apiBaseUrl, config.apiToken);
10318
+ const match = findProject(projects, project);
10319
+ if (!match) {
10320
+ console.error(chalk15.red(`
10321
+ No project called "${project}". Your projects: ${projects.map((p) => p.key).join(", ") || "none"}.`));
10322
+ process.exit(1);
10323
+ return;
10324
+ }
10325
+ process.exitCode = await deployProject(deps, match.id, options.env, options.wait);
10326
+ } catch (error) {
10327
+ console.error(chalk15.red(`
10328
+ ${error instanceof Error ? error.message : String(error)}`));
10329
+ process.exit(1);
10330
+ }
10331
+ });
10332
+
9814
10333
  // src/index.ts
9815
10334
  function resolveCliVersion() {
9816
10335
  if (true) {
9817
- return "1.20.0";
10336
+ return "1.21.1";
9818
10337
  }
9819
10338
  const require2 = createRequire(import.meta.url);
9820
10339
  const pkg = require2("../package.json");
9821
10340
  return pkg.version;
9822
10341
  }
9823
- var program = new Command12();
10342
+ var program = new Command15();
9824
10343
  program.name("compbox").description("CompBox CLI \u2014 pair this machine, manage Skill Packs, and run the Agent Runner daemon").version(resolveCliVersion());
9825
10344
  program.addCommand(installCommand);
9826
10345
  program.addCommand(updateCommand);
@@ -9832,4 +10351,7 @@ program.addCommand(doctorCommand);
9832
10351
  program.addCommand(runCommand);
9833
10352
  program.addCommand(serviceCommand);
9834
10353
  program.addCommand(machinesCommand);
10354
+ program.addCommand(repoCommand);
10355
+ program.addCommand(workspaceCommand);
10356
+ program.addCommand(deployCommand);
9835
10357
  program.parse(process.argv);