@mycompbox/compbox-cli 1.21.3 → 1.21.5

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/index.js CHANGED
@@ -1269,7 +1269,7 @@ var SessionEventType;
1269
1269
  })(SessionEventType || (SessionEventType = {}));
1270
1270
 
1271
1271
  // ../shared/dist/types/mailbox.js
1272
- var START_EXECUTION_KINDS = ["plan", "orchestrate"];
1272
+ var START_EXECUTION_KINDS = ["plan", "orchestrate", "refine"];
1273
1273
  function normalizeGitRemote(raw) {
1274
1274
  const input = (raw ?? "").trim();
1275
1275
  if (input === "")
@@ -5700,6 +5700,18 @@ function looksLikeCompletionAttempt(text) {
5700
5700
  var COMPLETION_REPAIR_INSTRUCTION = 'Your last message looked like a completion but I could NOT parse it as a valid JSON object with all required fields. Re-emit ONLY a single valid JSON object inside a ```json code fence \u2014 no other text \u2014 with every string value properly escaped (escape any internal double-quotes as \\" and any line breaks as \\n), and make sure title, problemStatement, proposedSolution, impactAssessment, and description are all present and non-empty:\n```json\n{"done": true, "title": "...", "problemStatement": "...", "proposedSolution": "...", "impactAssessment": "...", "description": "..."}\n```';
5701
5701
 
5702
5702
  // ../shared/dist/interview-conversation.js
5703
+ function requestLockReason(saved) {
5704
+ if (!saved)
5705
+ return null;
5706
+ if (saved.status !== "pending")
5707
+ return "status";
5708
+ if (!saved.canEdit)
5709
+ return "ownership";
5710
+ return null;
5711
+ }
5712
+ function lockedRequestMessage(reason) {
5713
+ return reason === "ownership" ? "Only the request's creator can change it; you can still discuss it." : "This request is locked, so it can't be changed any more.";
5714
+ }
5703
5715
  var CONVERSATION_QUALITY_ROUNDS = 2;
5704
5716
  var JSON_REPAIRS = 3;
5705
5717
  var STARTER = "Hi! I'd like to propose something.";
@@ -5714,8 +5726,10 @@ function renderSaved(saved) {
5714
5726
  const issues = saved.compliance && saved.compliance.issues.length > 0 ? `
5715
5727
  What the score says is missing or weak:
5716
5728
  ${saved.compliance.issues.slice(0, 8).map((i) => `- ${i.message}`).join("\n")}` : "";
5717
- const locked = saved.status === "pending" ? "It can still be changed." : `Its status is "${saved.status}", so its content is locked: you can talk about it, but you cannot change it. Never emit the completion JSON for a locked request.`;
5718
- return `THE REQUEST IS ALREADY SAVED. This conversation created the request "${saved.title}". ${score} ${locked}${issues}
5729
+ const reason = requestLockReason(saved);
5730
+ const locked = reason === null ? "It can still be changed." : reason === "status" ? `Its status is "${saved.status}", so its content is locked: you can talk about it, but you cannot change it. Never emit the completion JSON for a locked request.` : "Only the request's creator can change it, and the person you're talking to is not its creator, so its content is locked for them: you can talk about it, but you cannot change it. Never emit the completion JSON for a locked request. If they ask for a change, explain that only the creator can make it.";
5731
+ const origin = saved.discussed ? `THE REQUEST ALREADY EXISTS. The person is discussing the existing request "${saved.title}"; this conversation did not create it.` : `THE REQUEST IS ALREADY SAVED. This conversation created the request "${saved.title}".`;
5732
+ return `${origin} ${score} ${locked}${issues}
5719
5733
 
5720
5734
  Its current content:
5721
5735
  title: ${saved.title}
@@ -5791,7 +5805,7 @@ ${followUp}` : text;
5791
5805
  async function runConversationStep(input, deps) {
5792
5806
  const system = buildConversationSystemPrompt(input.saved);
5793
5807
  const messages = toConversationMessages(input.turns);
5794
- const locked = input.saved !== null && input.saved.status !== "pending";
5808
+ const lockReason = requestLockReason(input.saved);
5795
5809
  let requestId = input.saved?.id ?? null;
5796
5810
  let savedNow = null;
5797
5811
  let createdHere = false;
@@ -5814,10 +5828,11 @@ Send another message (for example "try again") when you're ready and I'll pick u
5814
5828
  }
5815
5829
  const draft = extractCompletionJson(reply);
5816
5830
  if (draft) {
5817
- if (locked) {
5818
- messages.push({ role: "assistant", content: reply }, { role: "user", content: "That request is locked and can't be changed. Reply to me in plain text instead." });
5831
+ if (lockReason) {
5832
+ const why = lockReason === "ownership" ? "Only the request's creator can change it, and I'm not its creator." : "That request is locked and can't be changed.";
5833
+ messages.push({ role: "assistant", content: reply }, { role: "user", content: `${why} Reply to me in plain text instead.` });
5819
5834
  if (++repairs > JSON_REPAIRS)
5820
- return { kind: "error", text: "This request is locked, so it can't be changed any more." };
5835
+ return { kind: "error", text: lockedRequestMessage(lockReason) };
5821
5836
  continue;
5822
5837
  }
5823
5838
  let saved;
@@ -5860,7 +5875,7 @@ The request IS already saved, and the person will be shown its score. If you ask
5860
5875
  return { kind: "message", text };
5861
5876
  }
5862
5877
  }
5863
- function savedContextFromRecord(record) {
5878
+ function savedContextFromRecord(record, access) {
5864
5879
  if (typeof record !== "object" || record === null)
5865
5880
  return null;
5866
5881
  const r = record;
@@ -5895,7 +5910,9 @@ function savedContextFromRecord(record) {
5895
5910
  status: typeof r.status === "string" ? r.status : "pending",
5896
5911
  description: typeof r.description === "string" ? r.description : "",
5897
5912
  fields,
5898
- compliance: complianceFromRecord(score)
5913
+ compliance: complianceFromRecord(score),
5914
+ canEdit: access.canEdit,
5915
+ ...access.discussed ? { discussed: true } : {}
5899
5916
  };
5900
5917
  }
5901
5918
  function complianceFromRecord(score) {
@@ -8172,14 +8189,19 @@ function runClaudeCliTurn(prompt, opts) {
8172
8189
  });
8173
8190
  });
8174
8191
  }
8175
- async function loadSavedRequest(apiBaseUrl, userApiToken, epicRequestId) {
8176
- const res = await fetch(
8177
- `${apiBaseUrl.replace(/\/+$/, "")}/api/v1/epic-requests/${encodeURIComponent(epicRequestId)}`,
8178
- { headers: { Authorization: `Bearer ${userApiToken}` } }
8179
- );
8192
+ async function loadSavedRequest(apiBaseUrl, userApiToken, epicRequestId, discussed) {
8193
+ const base = apiBaseUrl.replace(/\/+$/, "");
8194
+ const headers = { Authorization: `Bearer ${userApiToken}` };
8195
+ const [res, meRes] = await Promise.all([
8196
+ fetch(`${base}/api/v1/epic-requests/${encodeURIComponent(epicRequestId)}`, { headers }),
8197
+ fetch(`${base}/api/v1/auth/me`, { headers }).catch(() => null)
8198
+ ]);
8180
8199
  if (!res.ok) return null;
8181
8200
  const body = await res.json().catch(() => null);
8182
- return savedContextFromRecord(body?.data);
8201
+ const me = meRes?.ok ? await meRes.json().catch(() => null) : null;
8202
+ const requestedById = body?.data?.requestedById;
8203
+ const canEdit = typeof me?.id === "string" && typeof requestedById === "string" && me.id === requestedById;
8204
+ return savedContextFromRecord(body?.data, { canEdit, discussed });
8183
8205
  }
8184
8206
  function needsDefaultModel(error) {
8185
8207
  const message = error instanceof Error ? error.message : String(error);
@@ -8208,7 +8230,8 @@ Send another message (for example "try again") and I'll pick up where we left of
8208
8230
  async function takeConversationStep(job, ctx) {
8209
8231
  const routing = await resolveRouting();
8210
8232
  const requestId = savedRequestIdOf(job);
8211
- const saved = requestId ? await loadSavedRequest(ctx.apiBaseUrl, ctx.userApiToken, requestId) : null;
8233
+ const discussed = requestId !== null && parseSeedPayload(job.payload)?.targetEpicRequestId === requestId;
8234
+ const saved = requestId ? await loadSavedRequest(ctx.apiBaseUrl, ctx.userApiToken, requestId, discussed) : null;
8212
8235
  const turns = job.turns.map((t) => ({
8213
8236
  role: t.role,
8214
8237
  content: t.role === "user" ? appendAttachmentNote(t.content, imageAttachmentCount(t.attachments)) : t.content
@@ -8370,6 +8393,62 @@ async function fetchConvertedEpicId(apiBaseUrl, userApiToken, epicRequestId, fet
8370
8393
  return null;
8371
8394
  }
8372
8395
  }
8396
+ function summarizeComplianceScore(raw) {
8397
+ let score = raw;
8398
+ if (typeof score === "string") {
8399
+ try {
8400
+ score = JSON.parse(score);
8401
+ } catch {
8402
+ return null;
8403
+ }
8404
+ }
8405
+ if (!score || typeof score !== "object" || Array.isArray(score)) return null;
8406
+ const s = score;
8407
+ const overall = typeof s.overall === "number" ? s.overall : null;
8408
+ const tier = typeof s.tier === "string" ? s.tier : null;
8409
+ if (overall === null && tier === null) return null;
8410
+ const criticalIssueCodes = Array.isArray(s.issues) ? s.issues.filter(
8411
+ (i) => !!i && typeof i === "object" && typeof i.code === "string"
8412
+ ).filter((i) => i.tier === "critical").map((i) => i.code) : [];
8413
+ return { overall, tier, criticalIssueCodes };
8414
+ }
8415
+ async function fetchEpicComplianceSummary(apiBaseUrl, userApiToken, epicId, fetchImpl) {
8416
+ try {
8417
+ const res = await fetchImpl(
8418
+ `${apiBaseUrl.replace(/\/+$/, "")}/api/v1/epics/${encodeURIComponent(epicId)}`,
8419
+ { headers: { Authorization: `Bearer ${userApiToken}` } }
8420
+ );
8421
+ if (!res.ok) return null;
8422
+ const body = await res.json();
8423
+ return summarizeComplianceScore(body.data?.complianceScore);
8424
+ } catch {
8425
+ return null;
8426
+ }
8427
+ }
8428
+ function buildPlannerFinalTurn(outcome) {
8429
+ const r = outcome.result;
8430
+ if (outcome.status === "done") {
8431
+ const epicId = typeof r.epicId === "string" ? r.epicId : "";
8432
+ return `Planning complete \u2014 created epic ${epicId}.`;
8433
+ }
8434
+ if (r.needsHumanReview === true) {
8435
+ const marker = r.marker && typeof r.marker === "object" ? r.marker : {};
8436
+ const overall = typeof r.overallScore === "number" ? r.overallScore : typeof marker.overallScore === "number" ? marker.overallScore : null;
8437
+ const tier = typeof r.tier === "string" ? r.tier : typeof marker.tier === "string" ? marker.tier : null;
8438
+ const codes = Array.isArray(r.criticalIssueCodes) ? r.criticalIssueCodes.filter((c) => typeof c === "string") : [];
8439
+ const epicId = typeof r.epicId === "string" ? r.epicId : typeof marker.epicId === "string" ? marker.epicId : "";
8440
+ const parts = ["Planner run needs human review"];
8441
+ if (epicId) parts.push(`(epic ${epicId})`);
8442
+ let text = `${parts.join(" ")}.`;
8443
+ if (overall !== null) text += ` Latest audit score: ${String(overall)}/100${tier ? ` (${tier})` : ""}.`;
8444
+ else if (tier) text += ` Latest audit tier: ${tier}.`;
8445
+ if (codes.length > 0) text += ` Critical issues: ${codes.join(", ")}.`;
8446
+ const message = typeof r.message === "string" ? r.message : typeof r.error === "string" ? r.error : "";
8447
+ if (message) text += ` ${message}`;
8448
+ return text.slice(0, PLANNER_FINAL_TURN_MAX_CHARS);
8449
+ }
8450
+ return `Planner run ended: ${JSON.stringify(r).slice(0, PLANNER_FINAL_TURN_MAX_CHARS)}`;
8451
+ }
8373
8452
  async function invokeStartExecutionPlan(ctx, deps = {}) {
8374
8453
  const spawnImpl = deps.spawnImpl ?? spawn3;
8375
8454
  const fetchImpl = deps.fetchImpl ?? fetch;
@@ -8484,19 +8563,198 @@ ${stderr}`;
8484
8563
  finish({
8485
8564
  status: "failed",
8486
8565
  result: {
8566
+ needsHumanReview: true,
8567
+ stage: "VERIFY",
8487
8568
  error: "The planner finished but no epic was produced (the Epic Request was not converted to an epic). It may need human review."
8488
8569
  }
8489
8570
  });
8490
8571
  return;
8491
8572
  }
8573
+ const compliance = await fetchEpicComplianceSummary(
8574
+ ctx.apiBaseUrl,
8575
+ ctx.userApiToken,
8576
+ epicId,
8577
+ fetchImpl
8578
+ );
8579
+ if (compliance?.tier === "critical-fail") {
8580
+ finish({
8581
+ status: "failed",
8582
+ result: {
8583
+ needsHumanReview: true,
8584
+ stage: "EVALUATE",
8585
+ epicId,
8586
+ tier: compliance.tier,
8587
+ overallScore: compliance.overall,
8588
+ criticalIssueCodes: compliance.criticalIssueCodes,
8589
+ message: "The planner exited cleanly but the epic's latest audit is critical-fail; human review required before execution."
8590
+ }
8591
+ });
8592
+ return;
8593
+ }
8492
8594
  finish({ status: "done", result: { epicId } });
8493
8595
  })();
8494
8596
  });
8495
8597
  });
8496
8598
  try {
8497
- const epicId = typeof outcome.result.epicId === "string" ? outcome.result.epicId : "";
8498
- const summary = outcome.status === "done" ? `Planning complete \u2014 created epic ${epicId}.` : `Planner run ended: ${JSON.stringify(outcome.result).slice(0, PLANNER_FINAL_TURN_MAX_CHARS)}`;
8499
- await ctx.mailboxClient.postTurn(ctx.machineToken, ctx.jobId, summary);
8599
+ await ctx.mailboxClient.postTurn(ctx.machineToken, ctx.jobId, buildPlannerFinalTurn(outcome));
8600
+ } catch {
8601
+ }
8602
+ return outcome;
8603
+ }
8604
+ var REFINE_NOTES_ENV = "COMPBOX_REFINE_NOTES";
8605
+ function buildRefineArgs(epicId) {
8606
+ return [
8607
+ "-p",
8608
+ `@planner --refine ${epicId} --gates=auto --non-interactive`,
8609
+ "--permission-mode",
8610
+ "bypassPermissions"
8611
+ ];
8612
+ }
8613
+ function buildRefineEnv(routedEnv, notes) {
8614
+ const { [REFINE_NOTES_ENV]: _inherited, ...rest } = routedEnv;
8615
+ const trimmed = notes?.trim();
8616
+ return {
8617
+ ...rest,
8618
+ COMPBOX_NONINTERACTIVE: "1",
8619
+ PATH: claudeChildEnvPath(routedEnv.PATH),
8620
+ ...trimmed ? { [REFINE_NOTES_ENV]: trimmed } : {}
8621
+ };
8622
+ }
8623
+ function buildRefineFinalTurn(outcome) {
8624
+ const r = outcome.result;
8625
+ const text = (value) => typeof value === "string" && value ? value : void 0;
8626
+ if (outcome.status === "done") {
8627
+ return `Refine finished. The epic ${text(r.epicId) ?? ""} was updated in place.`;
8628
+ }
8629
+ if (r.needsHumanReview === true) {
8630
+ return `Refine needs human review: ${text(r.message) ?? text(r.error) ?? "the epic is still critical-fail"}`.slice(0, PLANNER_FINAL_TURN_MAX_CHARS);
8631
+ }
8632
+ return `Refine run ended: ${text(r.error) ?? JSON.stringify(r)}`.slice(0, PLANNER_FINAL_TURN_MAX_CHARS);
8633
+ }
8634
+ async function invokeStartExecutionRefine(ctx, deps = {}) {
8635
+ const spawnImpl = deps.spawnImpl ?? spawn3;
8636
+ const fetchImpl = deps.fetchImpl ?? fetch;
8637
+ const isGitRepo = deps.isGitRepo ?? isGitRepoDir;
8638
+ const resolveRoutingImpl = deps.resolveRoutingImpl ?? resolveRouting;
8639
+ const heartbeatIntervalMs = deps.heartbeatIntervalMs ?? PLANNER_HEARTBEAT_INTERVAL_MS;
8640
+ const timeoutMs = deps.timeoutMs ?? PLANNER_RUN_TIMEOUT_MS;
8641
+ if (!ctx.projectDir) {
8642
+ return { status: "failed", result: { error: projectDirNotConfiguredMessage() } };
8643
+ }
8644
+ if (!isGitRepo(ctx.projectDir)) {
8645
+ return { status: "failed", result: { error: projectDirNotGitRepoMessage(ctx.projectDir) } };
8646
+ }
8647
+ const routing = await resolveRoutingImpl();
8648
+ const command = resolveClaudeBinary() ?? "claude";
8649
+ const args = ctx.keyRun ? keyRunArgs(buildRefineArgs(ctx.epicId)) : buildRefineArgs(ctx.epicId);
8650
+ const baseEnv = buildRefineEnv(claudeSpawnEnv(process.env, routing), ctx.notes);
8651
+ const childEnv = ctx.keyRun ? keyRunEnv(baseEnv, ctx.keyRun) : baseEnv;
8652
+ try {
8653
+ await ctx.mailboxClient.postTurn(
8654
+ ctx.machineToken,
8655
+ ctx.jobId,
8656
+ `Started the planner in refine mode for epic ${ctx.epicId} (headless)${ctx.notes?.trim() ? ", with your notes" : ""}. This may take several minutes.`
8657
+ );
8658
+ } catch {
8659
+ }
8660
+ const outcome = await new Promise((resolve3) => {
8661
+ let stdout2 = "";
8662
+ let stderr = "";
8663
+ let settled = false;
8664
+ const child = spawnImpl(command, args, {
8665
+ cwd: ctx.projectDir,
8666
+ stdio: ["ignore", "pipe", "pipe"],
8667
+ env: childEnv
8668
+ });
8669
+ const heartbeatTimer = deps.heartbeat ? setInterval(() => {
8670
+ void Promise.resolve(deps.heartbeat?.()).catch(() => {
8671
+ });
8672
+ }, heartbeatIntervalMs) : void 0;
8673
+ const finish = (result) => {
8674
+ if (settled) return;
8675
+ settled = true;
8676
+ if (heartbeatTimer) clearInterval(heartbeatTimer);
8677
+ clearTimeout(timer);
8678
+ resolve3(result);
8679
+ };
8680
+ const timer = setTimeout(() => {
8681
+ child.kill("SIGKILL");
8682
+ finish({
8683
+ status: "failed",
8684
+ result: {
8685
+ error: `The refine run timed out after ${String(Math.round(timeoutMs / 6e4))} minutes and was terminated. The epic may be partially refined.`
8686
+ }
8687
+ });
8688
+ }, timeoutMs);
8689
+ child.stdout.on("data", (chunk) => {
8690
+ stdout2 += chunk.toString("utf-8");
8691
+ });
8692
+ child.stderr.on("data", (chunk) => {
8693
+ stderr += chunk.toString("utf-8");
8694
+ });
8695
+ child.on("error", (error) => {
8696
+ finish({
8697
+ status: "failed",
8698
+ result: {
8699
+ error: error.code === "ENOENT" ? claudeNotFoundMessage() : error.message || "Failed to spawn the planner."
8700
+ }
8701
+ });
8702
+ });
8703
+ child.on("close", (code) => {
8704
+ void (async () => {
8705
+ if (ctx.keyRun) stdout2 = await settleKeyRun(ctx, ctx.keyRun, stdout2);
8706
+ const combined = `${stdout2}
8707
+ ${stderr}`;
8708
+ const review = detectNeedsHumanReview(combined);
8709
+ if (review.needsReview) {
8710
+ finish({
8711
+ status: "failed",
8712
+ result: {
8713
+ needsHumanReview: true,
8714
+ stage: "REFINE",
8715
+ epicId: ctx.epicId,
8716
+ message: "Refine could not clear the epic's critical audit issues; human review required before execution.",
8717
+ ...review.marker ? { marker: review.marker } : {}
8718
+ }
8719
+ });
8720
+ return;
8721
+ }
8722
+ if (code !== 0) {
8723
+ finish({
8724
+ status: "failed",
8725
+ result: {
8726
+ error: stderr.trim() || stdout2.trim().slice(-PLANNER_FINAL_TURN_MAX_CHARS) || `The planner (refine) exited with code ${String(code ?? "null")}.`
8727
+ }
8728
+ });
8729
+ return;
8730
+ }
8731
+ const compliance = await fetchEpicComplianceSummary(
8732
+ ctx.apiBaseUrl,
8733
+ ctx.userApiToken,
8734
+ ctx.epicId,
8735
+ fetchImpl
8736
+ );
8737
+ if (compliance?.tier === "critical-fail") {
8738
+ finish({
8739
+ status: "failed",
8740
+ result: {
8741
+ needsHumanReview: true,
8742
+ stage: "REFINE",
8743
+ epicId: ctx.epicId,
8744
+ tier: compliance.tier,
8745
+ overallScore: compliance.overall,
8746
+ criticalIssueCodes: compliance.criticalIssueCodes,
8747
+ message: "Refine finished but the epic's latest audit is still critical-fail; human review required before execution."
8748
+ }
8749
+ });
8750
+ return;
8751
+ }
8752
+ finish({ status: "done", result: { epicId: ctx.epicId, refined: true } });
8753
+ })();
8754
+ });
8755
+ });
8756
+ try {
8757
+ await ctx.mailboxClient.postTurn(ctx.machineToken, ctx.jobId, buildRefineFinalTurn(outcome));
8500
8758
  } catch {
8501
8759
  }
8502
8760
  return outcome;
@@ -8918,8 +9176,13 @@ function stamp(now) {
8918
9176
  const pad = (n) => String(n).padStart(2, "0");
8919
9177
  return `${String(now.getFullYear())}${pad(now.getMonth() + 1)}${pad(now.getDate())}-${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}`;
8920
9178
  }
8921
- function firstLine(text) {
8922
- return text.trim().split("\n")[0] ?? "";
9179
+ var EMPTY_TREE = "4b825dc642cb6eb9a060e54bf8d69288fbee4904";
9180
+ function gitReason(text) {
9181
+ const lines = text.split("\n").map((l) => l.trim()).filter(Boolean);
9182
+ const failure = lines.find((l) => /^(fatal|error):/i.test(l));
9183
+ if (failure) return failure;
9184
+ const notProgress = lines.filter((l) => !/^(Preparing worktree|HEAD is now at|Updating files)/.test(l));
9185
+ return notProgress.at(-1) ?? lines.at(-1) ?? "";
8923
9186
  }
8924
9187
  function installCommand2(dir, exists = existsSync9) {
8925
9188
  if (exists(join10(dir, "pnpm-lock.yaml"))) return ["pnpm", ["install", "--frozen-lockfile", "--prefer-offline"]];
@@ -8984,7 +9247,7 @@ var RunWorkspaceManager = class {
8984
9247
  return {
8985
9248
  ok: false,
8986
9249
  error: [
8987
- `Installing the project's dependencies failed (${command} ${args.join(" ")}): ${firstLine(res.stderr) || firstLine(res.stdout) || "unknown error"}`,
9250
+ `Installing the project's dependencies failed (${command} ${args.join(" ")}): ${gitReason(res.stderr) || gitReason(res.stdout) || "unknown error"}`,
8988
9251
  "The run was not started. Check that the same command works in your project folder."
8989
9252
  ].join("\n")
8990
9253
  };
@@ -8992,10 +9255,43 @@ var RunWorkspaceManager = class {
8992
9255
  }
8993
9256
  return { ok: true, workspace, notes };
8994
9257
  }
9258
+ /**
9259
+ * When neither the folder nor its remote has any commit, records one empty
9260
+ * commit on `main` (and pushes it) so runs can branch and open pull requests.
9261
+ * Built with plumbing from git's empty tree, so nothing staged or sitting in
9262
+ * the folder is swept in: the person's files stay exactly as they were.
9263
+ */
9264
+ async startEmptyRepository(projectDir, remote) {
9265
+ if ((await this.git(["rev-parse", "--verify", "--quiet", "HEAD"], projectDir)).status === 0) return { ok: true };
9266
+ if (remote) {
9267
+ const heads = await this.git(["ls-remote", "--heads", remote], projectDir);
9268
+ if (heads.status !== 0 || heads.stdout.trim() !== "") return { ok: true };
9269
+ }
9270
+ const fail = (what, res) => ({
9271
+ ok: false,
9272
+ error: [
9273
+ `This repository has no commits yet, and CompBox couldn't ${what}: ${gitReason(res.stderr) || "unknown error"}`,
9274
+ "The run was not started. Make a first commit on main in your project folder (or push one to GitHub), then try again."
9275
+ ].join("\n")
9276
+ });
9277
+ const commit = await this.git(["commit-tree", EMPTY_TREE, "-m", "Start the project"], projectDir);
9278
+ if (commit.status !== 0) return fail("make its first commit", commit);
9279
+ const sha = commit.stdout.trim();
9280
+ const ref = await this.git(["update-ref", "refs/heads/main", sha, ""], projectDir);
9281
+ if (ref.status !== 0) return fail("create the main branch", ref);
9282
+ await this.git(["symbolic-ref", "HEAD", "refs/heads/main"], projectDir);
9283
+ if (!remote) return { ok: true, note: "The repository had no commits, so CompBox started main with an empty first commit." };
9284
+ const push = await this.git(["push", remote, "main"], projectDir);
9285
+ if (push.status !== 0) return fail(`push its first commit to ${remote}`, push);
9286
+ return { ok: true, note: `The repository had no commits, so CompBox started main with an empty first commit and pushed it to ${remote}.` };
9287
+ }
8995
9288
  async createWorktree(projectDir, epicId) {
8996
9289
  const notes = [];
8997
9290
  const remotes = (await this.git(["remote"], projectDir)).stdout.split("\n").map((r) => r.trim()).filter(Boolean);
8998
9291
  const remote = remotes.includes("origin") ? "origin" : remotes[0] ?? null;
9292
+ const started = await this.startEmptyRepository(projectDir, remote);
9293
+ if (!started.ok) return started;
9294
+ if (started.note) notes.push(started.note);
8999
9295
  let baseBranch = "";
9000
9296
  let baseRef = "HEAD";
9001
9297
  if (remote) {
@@ -9033,7 +9329,7 @@ var RunWorkspaceManager = class {
9033
9329
  notes.push(`Continuing the earlier unfinished work on ${previous}.`);
9034
9330
  } else {
9035
9331
  notes.push(
9036
- `Couldn't continue the earlier unfinished branch ${previous} (${firstLine(resume.stderr) || "unknown error"}), so the run starts a new branch.`
9332
+ `Couldn't continue the earlier unfinished branch ${previous} (${gitReason(resume.stderr) || "unknown error"}), so the run starts a new branch.`
9037
9333
  );
9038
9334
  }
9039
9335
  }
@@ -9042,7 +9338,7 @@ var RunWorkspaceManager = class {
9042
9338
  return {
9043
9339
  ok: false,
9044
9340
  error: [
9045
- `Couldn't create a separate workspace for this run (git worktree add failed): ${firstLine(add.stderr) || "unknown error"}`,
9341
+ `Couldn't create a separate workspace for this run (git worktree add failed): ${gitReason(add.stderr) || "unknown error"}`,
9046
9342
  "The run was not started, and your project folder was not changed."
9047
9343
  ].join("\n")
9048
9344
  };
@@ -9091,7 +9387,7 @@ ${untracked.stdout}`.split("\n").map((p) => p.trim()).filter((p) => p && !p.ends
9091
9387
  );
9092
9388
  if (commit.status !== 0) {
9093
9389
  commitFailed = true;
9094
- notes.push(`Couldn't commit the remaining changes: ${firstLine(commit.stderr) || firstLine(commit.stdout) || "unknown error"}`);
9390
+ notes.push(`Couldn't commit the remaining changes: ${gitReason(commit.stderr) || gitReason(commit.stdout) || "unknown error"}`);
9095
9391
  }
9096
9392
  }
9097
9393
  const commits = Number.parseInt((await this.git(["rev-list", "--count", `${ws.baseRef}..HEAD`], ws.dir)).stdout.trim(), 10) || 0;
@@ -9125,7 +9421,7 @@ ${untracked.stdout}`.split("\n").map((p) => p.trim()).filter((p) => p && !p.ends
9125
9421
  const push = await this.git(["push", "--set-upstream", ws.remote, ws.branch], ws.dir);
9126
9422
  if (push.status !== 0) {
9127
9423
  notes.push(
9128
- `Couldn't push the branch to ${ws.remote}: ${firstLine(push.stderr) || "unknown error"}. The work is safe in ${ws.dir} on branch ${ws.branch}.`
9424
+ `Couldn't push the branch to ${ws.remote}: ${gitReason(push.stderr) || "unknown error"}. The work is safe in ${ws.dir} on branch ${ws.branch}.`
9129
9425
  );
9130
9426
  return { ...base, keptWorktree: ws.dir };
9131
9427
  }
@@ -9161,7 +9457,7 @@ ${untracked.stdout}`.split("\n").map((p) => p.trim()).filter((p) => p && !p.ends
9161
9457
  const remoteUrl = (await this.git(["remote", "get-url", ws.remote], ws.dir)).stdout.trim();
9162
9458
  compareUrl = githubCompareUrl(remoteUrl, ws.baseBranch, ws.branch) ?? void 0;
9163
9459
  notes.push(
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.`)
9460
+ `The branch was pushed, but the pull request couldn't be opened automatically${gitReason(pr.stderr) ? ` (${gitReason(pr.stderr)})` : ""}.` + (compareUrl ? " Use the link to open it." : ` Open a pull request for ${ws.branch} on your git host.`)
9165
9461
  );
9166
9462
  }
9167
9463
  const removed = await this.removeWorktree(ws, notes);
@@ -9250,7 +9546,7 @@ function parsePayload(payload) {
9250
9546
  ...typeof p.projectName === "string" ? { projectName: p.projectName } : {}
9251
9547
  };
9252
9548
  }
9253
- function firstLine2(text) {
9549
+ function firstLine(text) {
9254
9550
  return text.trim().split("\n").filter(Boolean).pop() ?? "";
9255
9551
  }
9256
9552
  async function invokeConnectRepo(payload, deps = {}) {
@@ -9314,7 +9610,7 @@ async function invokeConnectRepo(payload, deps = {}) {
9314
9610
  cloned = true;
9315
9611
  break;
9316
9612
  }
9317
- errors.push(firstLine2(res.stderr));
9613
+ errors.push(firstLine(res.stderr));
9318
9614
  }
9319
9615
  if (!cloned) {
9320
9616
  return {
@@ -9437,6 +9733,16 @@ function parseStartExecutionPayload(payload) {
9437
9733
  if (p.kind === "orchestrate" && typeof p.epicId === "string" && p.epicId.length > 0) {
9438
9734
  return { kind: "orchestrate", epicId: p.epicId, ...projectRemote && { projectRemote }, ...useAiKey && { useAiKey } };
9439
9735
  }
9736
+ if (p.kind === "refine" && typeof p.epicId === "string" && p.epicId.length > 0) {
9737
+ const notes = typeof p.notes === "string" && p.notes.trim().length > 0 ? p.notes : void 0;
9738
+ return {
9739
+ kind: "refine",
9740
+ epicId: p.epicId,
9741
+ ...notes && { notes },
9742
+ ...projectRemote && { projectRemote },
9743
+ ...useAiKey && { useAiKey }
9744
+ };
9745
+ }
9440
9746
  return null;
9441
9747
  }
9442
9748
  async function handleStartExecution(ctx, job) {
@@ -9445,7 +9751,7 @@ async function handleStartExecution(ctx, job) {
9445
9751
  await completeWithFailure(
9446
9752
  ctx,
9447
9753
  job,
9448
- 'The start_execution job payload was missing or malformed (expected {kind:"plan",epicRequestId} or {kind:"orchestrate",epicId}).'
9754
+ 'The start_execution job payload was missing or malformed (expected {kind:"plan",epicRequestId}, {kind:"orchestrate",epicId} or {kind:"refine",epicId,notes?}).'
9449
9755
  );
9450
9756
  return;
9451
9757
  }
@@ -9505,6 +9811,39 @@ async function handleStartExecution(ctx, job) {
9505
9811
  );
9506
9812
  return;
9507
9813
  }
9814
+ if (payload.kind === "refine") {
9815
+ const userApiToken2 = ctx.userApiToken;
9816
+ if (!userApiToken2) {
9817
+ await completeWithFailure(
9818
+ ctx,
9819
+ job,
9820
+ "This device is not paired with a user API token, so the planner cannot refine the epic. Run `compbox configure` to re-pair."
9821
+ );
9822
+ return;
9823
+ }
9824
+ console.log(chalk9.gray(" Running the planner headless (start_execution / refine)..."));
9825
+ await runInvokerAndComplete(
9826
+ ctx,
9827
+ job,
9828
+ () => invokeStartExecutionRefine(
9829
+ {
9830
+ mailboxClient: ctx.client,
9831
+ machineToken: ctx.machineToken,
9832
+ jobId: job.id,
9833
+ apiBaseUrl: ctx.apiBaseUrl,
9834
+ userApiToken: userApiToken2,
9835
+ epicId: payload.epicId,
9836
+ ...payload.notes && { notes: payload.notes },
9837
+ projectDir: jobProjectDir,
9838
+ ...keyRun && { keyRun }
9839
+ },
9840
+ {
9841
+ heartbeat: () => ctx.client.heartbeat(ctx.machineToken).catch(() => void 0)
9842
+ }
9843
+ )
9844
+ );
9845
+ return;
9846
+ }
9508
9847
  const userApiToken = ctx.userApiToken;
9509
9848
  if (!userApiToken) {
9510
9849
  await completeWithFailure(
@@ -10245,6 +10584,21 @@ async function runWorkspace(deps = {}) {
10245
10584
  })
10246
10585
  }
10247
10586
  );
10587
+ } else if (payload.kind === "refine" && payload.epicId) {
10588
+ outcome = await (deps.refine ?? invokeStartExecutionRefine)(
10589
+ {
10590
+ mailboxClient: client,
10591
+ machineToken: env.token,
10592
+ jobId: job.id,
10593
+ apiBaseUrl: env.apiUrl,
10594
+ userApiToken,
10595
+ epicId: payload.epicId,
10596
+ notes: typeof payload.notes === "string" ? payload.notes : void 0,
10597
+ projectDir: repoDir,
10598
+ keyRun
10599
+ },
10600
+ { heartbeat }
10601
+ );
10248
10602
  } else {
10249
10603
  return fail("The job is missing what to plan or build.");
10250
10604
  }
@@ -10354,7 +10708,7 @@ ${error instanceof Error ? error.message : String(error)}`));
10354
10708
  // src/index.ts
10355
10709
  function resolveCliVersion() {
10356
10710
  if (true) {
10357
- return "1.21.3";
10711
+ return "1.21.5";
10358
10712
  }
10359
10713
  const require2 = createRequire(import.meta.url);
10360
10714
  const pkg = require2("../package.json");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mycompbox/compbox-cli",
3
- "version": "1.21.3",
3
+ "version": "1.21.5",
4
4
  "description": "CompBox CLI - Install, update, and manage Skill Packs",
5
5
  "type": "module",
6
6
  "bin": {