@mycompbox/compbox-cli 1.21.14 → 1.21.16

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 (71) hide show
  1. package/.tsbuildinfo +1 -1
  2. package/commands/configure.d.ts.map +1 -1
  3. package/commands/configure.js +3 -3
  4. package/commands/configure.js.map +1 -1
  5. package/commands/doctor.d.ts +21 -3
  6. package/commands/doctor.d.ts.map +1 -1
  7. package/commands/doctor.js +93 -8
  8. package/commands/doctor.js.map +1 -1
  9. package/commands/run.d.ts +2 -0
  10. package/commands/run.d.ts.map +1 -1
  11. package/commands/run.js +22 -7
  12. package/commands/run.js.map +1 -1
  13. package/commands/service.d.ts +10 -19
  14. package/commands/service.d.ts.map +1 -1
  15. package/commands/service.js +107 -73
  16. package/commands/service.js.map +1 -1
  17. package/commands/workspace.d.ts +18 -1
  18. package/commands/workspace.d.ts.map +1 -1
  19. package/commands/workspace.js +122 -12
  20. package/commands/workspace.js.map +1 -1
  21. package/index.js +1925 -533
  22. package/package.json +1 -1
  23. package/utils/agent-invoker.d.ts +103 -3
  24. package/utils/agent-invoker.d.ts.map +1 -1
  25. package/utils/agent-invoker.js +426 -123
  26. package/utils/agent-invoker.js.map +1 -1
  27. package/utils/claude-runtime.d.ts +63 -7
  28. package/utils/claude-runtime.d.ts.map +1 -1
  29. package/utils/claude-runtime.js +203 -67
  30. package/utils/claude-runtime.js.map +1 -1
  31. package/utils/claude-stream.d.ts +38 -0
  32. package/utils/claude-stream.d.ts.map +1 -0
  33. package/utils/claude-stream.js +125 -0
  34. package/utils/claude-stream.js.map +1 -0
  35. package/utils/config-store.d.ts.map +1 -1
  36. package/utils/config-store.js +7 -4
  37. package/utils/config-store.js.map +1 -1
  38. package/utils/mailbox-client.d.ts +61 -2
  39. package/utils/mailbox-client.d.ts.map +1 -1
  40. package/utils/mailbox-client.js +131 -3
  41. package/utils/mailbox-client.js.map +1 -1
  42. package/utils/mcp-config-writer.d.ts +30 -4
  43. package/utils/mcp-config-writer.d.ts.map +1 -1
  44. package/utils/mcp-config-writer.js +33 -6
  45. package/utils/mcp-config-writer.js.map +1 -1
  46. package/utils/package-manager-shims.d.ts +20 -4
  47. package/utils/package-manager-shims.d.ts.map +1 -1
  48. package/utils/package-manager-shims.js +84 -13
  49. package/utils/package-manager-shims.js.map +1 -1
  50. package/utils/process-group.d.ts +9 -2
  51. package/utils/process-group.d.ts.map +1 -1
  52. package/utils/process-group.js +14 -4
  53. package/utils/process-group.js.map +1 -1
  54. package/utils/process-spawn.d.ts +68 -0
  55. package/utils/process-spawn.d.ts.map +1 -0
  56. package/utils/process-spawn.js +119 -0
  57. package/utils/process-spawn.js.map +1 -0
  58. package/utils/project-checks.d.ts +28 -0
  59. package/utils/project-checks.d.ts.map +1 -1
  60. package/utils/project-checks.js +58 -50
  61. package/utils/project-checks.js.map +1 -1
  62. package/utils/repo-setup.js +3 -3
  63. package/utils/repo-setup.js.map +1 -1
  64. package/utils/windows-runner.d.ts +136 -0
  65. package/utils/windows-runner.d.ts.map +1 -0
  66. package/utils/windows-runner.js +407 -0
  67. package/utils/windows-runner.js.map +1 -0
  68. package/utils/wrap-up.d.ts +81 -3
  69. package/utils/wrap-up.d.ts.map +1 -1
  70. package/utils/wrap-up.js +240 -8
  71. package/utils/wrap-up.js.map +1 -1
@@ -18,14 +18,25 @@
18
18
  */
19
19
  import Anthropic from "@anthropic-ai/sdk";
20
20
  import { execFile, spawn, spawnSync } from "node:child_process";
21
+ import { planCrossPlatformSpawn, spawnCrossPlatform } from "./process-spawn.js";
21
22
  import { randomUUID } from "node:crypto";
22
- import { mkdirSync } from "node:fs";
23
+ import { copyFileSync, existsSync, mkdirSync, mkdtempSync } from "node:fs";
23
24
  import { mkdir, mkdtemp, realpath, rm, writeFile } from "node:fs/promises";
24
25
  import { homedir, tmpdir } from "node:os";
25
26
  import { join } from "node:path";
26
- import { resolveRouting, extractCompletionJson, looksLikeCompletionAttempt, meetsComplianceTarget, buildAuditFeedback, COMPLETION_REPAIR_INSTRUCTION, renderConversationPrompt, runConversationStep, savedContextFromRecord, formatNeedsInputText, parseNeedsInputMarker, stripRunnerOnlyFields, } from "@mycompbox/shared";
27
+ import { resolveRouting, extractCompletionJson, looksLikeCompletionAttempt, meetsComplianceTarget, buildAuditFeedback, COMPLETION_REPAIR_INSTRUCTION, renderConversationPrompt, contentText, runConversationStep, savedContextFromRecord, isConversationChatModel, formatNeedsInputText, parseNeedsInputMarker, stripRunnerOnlyFields, } from "@mycompbox/shared";
27
28
  // Completion parsing lives in @mycompbox/shared so CompBox's server-side
28
29
  // (API-key) interview finishes the same way; re-exported for existing callers.
30
+ /**
31
+ * ENG-404: spawns through `spawnCrossPlatform` so a `.cmd` shim (e.g. an npm-installed
32
+ * `claude.cmd`) runs via cmd.exe on Windows; POSIX spawns are unchanged.
33
+ */
34
+ function spawnPiped(spawnImpl, command, args, options, platform) {
35
+ return spawnCrossPlatform(command, args, options, {
36
+ spawn: spawnImpl,
37
+ ...(platform ? { platform } : {}),
38
+ });
39
+ }
29
40
  export { extractCompletionJson, looksLikeCompletionAttempt, meetsComplianceTarget, buildAuditFeedback, COMPLETION_REPAIR_INSTRUCTION, };
30
41
  import { buildJobTimings, CiWaitTracker, parseClaudeDurations, } from "./run-timings.js";
31
42
  import { defaultPreflightExecFile, formatPreflightTurn, preflightNeedsInput, repoFromRemote, runCloudPreflight, } from "./cloud-preflight.js";
@@ -35,6 +46,7 @@ import { mergeGuardArgs, withMergeGuardPath } from "./merge-guard.js";
35
46
  import { keyRunArgs, keyRunEnv, parseClaudeJsonResult } from "./key-run.js";
36
47
  import { CANCEL_GRACE_MS, cancelledRunResult, groupSpawnOptions, killGroupOnAbort, killProcessGroupNow, terminateProcessGroup, } from "./process-group.js";
37
48
  import { startProgressWatcher } from "./progress-watcher.js";
49
+ import { parseClaudeStream } from "./claude-stream.js";
38
50
  import { classifyUsageLimit } from "./usage-limit.js";
39
51
  import { defaultCommandRunner, } from "./run-workspace.js";
40
52
  import { createWrapUp } from "./wrap-up.js";
@@ -43,6 +55,44 @@ import { createWrapUp } from "./wrap-up.js";
43
55
  // quality loss. Opus/Sonnet are deliberately NOT used here — pxpipe passes
44
56
  // Opus through uncompressed, defeating the token savings.
45
57
  const ANTHROPIC_MODEL = "claude-fable-5";
58
+ /**
59
+ * Request-conversation models (ENG-390): plain chat turns use the fast model so
60
+ * replies feel instant; turns that write up or improve a saved request (the
61
+ * save/compliance pass and JSON repairs) keep the stronger model.
62
+ */
63
+ export const CHAT_MODEL = "claude-haiku-5-5";
64
+ export const SAVE_MODEL = ANTHROPIC_MODEL;
65
+ /**
66
+ * The model for one AI call in a request conversation step. `chosenChatModel`
67
+ * (the person's pick from the job payload, ENG-390-2) applies to chat turns
68
+ * only; save and repair turns always keep SAVE_MODEL.
69
+ */
70
+ export function modelForTurn(kind, chosenChatModel = null) {
71
+ if (kind !== "chat")
72
+ return SAVE_MODEL;
73
+ return chosenChatModel ?? CHAT_MODEL;
74
+ }
75
+ /**
76
+ * The chat model the person picked for this request conversation, read from
77
+ * the job payload (an object, or the JSON string it is stored as). Only ids in
78
+ * the shared allowlist count; anything else, or no model, returns null so the
79
+ * caller falls back to CHAT_MODEL.
80
+ */
81
+ export function chosenChatModelOf(payload) {
82
+ let p = payload;
83
+ if (typeof p === "string") {
84
+ try {
85
+ p = JSON.parse(p);
86
+ }
87
+ catch {
88
+ return null;
89
+ }
90
+ }
91
+ if (typeof p !== "object" || p === null)
92
+ return null;
93
+ const model = p.model;
94
+ return isConversationChatModel(model) ? model : null;
95
+ }
46
96
  /** Per-turn wall-clock budget for a single `claude -p` child process. */
47
97
  const CLAUDE_CLI_TURN_TIMEOUT_MS = 4 * 60 * 1_000; // 4 minutes: a full write-up can take a while
48
98
  /**
@@ -61,6 +111,52 @@ export function claudeSpawnEnv(base, routing) {
61
111
  ? { ...base, ANTHROPIC_BASE_URL: routing.anthropicBaseUrl }
62
112
  : base;
63
113
  }
114
+ /**
115
+ * ENG-394: env that points `core.hooksPath` at `hooksDir` for every git the
116
+ * child runs, so the repo's own hooks (e.g. a pre-commit running the whole
117
+ * test suite) don't fire on each agent commit — the build's own checks run
118
+ * them once at the end. Uses GIT_CONFIG_COUNT/KEY_n/VALUE_n (git >= 2.31),
119
+ * appended after any entries already set; older git just ignores it and the
120
+ * hooks run as before. A malformed existing count is left alone (git would
121
+ * otherwise reject every command). Pure — unit tested.
122
+ */
123
+ export function withHooksDisabled(env, hooksDir) {
124
+ const raw = env.GIT_CONFIG_COUNT?.trim();
125
+ if (raw && !/^\d+$/.test(raw))
126
+ return env;
127
+ const n = raw ? Number(raw) : 0;
128
+ return {
129
+ ...env,
130
+ GIT_CONFIG_COUNT: String(n + 1),
131
+ [`GIT_CONFIG_KEY_${String(n)}`]: "core.hooksPath",
132
+ [`GIT_CONFIG_VALUE_${String(n)}`]: hooksDir,
133
+ };
134
+ }
135
+ /**
136
+ * ENG-394: a fresh hooks folder for one run's agent. Holds nothing except a
137
+ * copy of the run copy's pre-push merge guard (ENG-346), when it has one, so
138
+ * the env override above never lets the agent push to the base branch.
139
+ * Undefined (hooks left as they are) when the folder can't be made.
140
+ */
141
+ export function makeAgentHooksDir(runDir) {
142
+ try {
143
+ const dir = mkdtempSync(join(tmpdir(), "compbox-nohooks-"));
144
+ if (runDir) {
145
+ const res = spawnSync("git", ["rev-parse", "--path-format=absolute", "--git-dir"], {
146
+ cwd: runDir,
147
+ encoding: "utf-8",
148
+ });
149
+ const gitDir = res.status === 0 ? res.stdout.trim() : "";
150
+ const guard = gitDir ? join(gitDir, "compbox-hooks", "pre-push") : "";
151
+ if (guard && existsSync(guard))
152
+ copyFileSync(guard, join(dir, "pre-push"));
153
+ }
154
+ return dir;
155
+ }
156
+ catch {
157
+ return undefined;
158
+ }
159
+ }
64
160
  // ---------------------------------------------------------------------
65
161
  // Image attachments (ENG-153). A user turn can carry image attachments
66
162
  // (ENG-151 read-contract). In API mode they become Anthropic vision content
@@ -517,25 +613,43 @@ export function claudeToolArgs(attachmentsDir) {
517
613
  `Read(/${attachmentsDir}/**)`,
518
614
  ];
519
615
  }
520
- function runClaudeCliTurn(prompt, opts) {
616
+ /**
617
+ * ENG-387: true when claude's stderr says it does not know
618
+ * `--include-partial-messages` (an older CLI), as opposed to any other failure.
619
+ */
620
+ function rejectsPartialMessagesFlag(stderr) {
621
+ return (stderr.includes("--include-partial-messages") &&
622
+ /unknown|unrecognized|invalid|unexpected|not supported/i.test(stderr));
623
+ }
624
+ export function runClaudeCliTurn(prompt, opts) {
521
625
  return new Promise((resolve, reject) => {
522
626
  const model = opts.model === undefined ? ANTHROPIC_MODEL : opts.model;
523
- const args = [
524
- "-p",
525
- prompt,
526
- ...(model ? ["--model", model] : []),
527
- "--output-format",
528
- "json",
529
- ...claudeToolArgs(opts.attachmentsDir),
530
- "--permission-mode",
531
- "dontAsk",
532
- "--safe-mode",
533
- "--system-prompt",
534
- opts.systemPrompt,
535
- ];
536
- if (opts.resumeSessionId) {
537
- args.push("--resume", opts.resumeSessionId);
538
- }
627
+ const onText = opts.onText;
628
+ const streaming = typeof onText === "function";
629
+ // ENG-387: `withPartial` adds --include-partial-messages (token deltas).
630
+ // An older claude CLI that rejects the flag gets one retry without it
631
+ // (whole assistant messages still stream as deltas) — see the close handler.
632
+ const buildArgs = (withPartial) => {
633
+ const args = [
634
+ "-p",
635
+ prompt,
636
+ ...(model ? ["--model", model] : []),
637
+ "--output-format",
638
+ ...(streaming
639
+ ? ["stream-json", "--verbose", ...(withPartial ? ["--include-partial-messages"] : [])]
640
+ : ["json"]),
641
+ ...claudeToolArgs(opts.attachmentsDir),
642
+ "--permission-mode",
643
+ "dontAsk",
644
+ "--safe-mode",
645
+ "--system-prompt",
646
+ opts.systemPrompt,
647
+ ];
648
+ if (opts.resumeSessionId) {
649
+ args.push("--resume", opts.resumeSessionId);
650
+ }
651
+ return args;
652
+ };
539
653
  // ENG-135: resolve `claude` to an absolute path using the login-shell PATH
540
654
  // + well-known install dirs. A launchd/GUI-spawned daemon inherits a PATH
541
655
  // that often lacks ~/.local/bin, so a bare-name spawn fails "not found on
@@ -547,67 +661,121 @@ function runClaudeCliTurn(prompt, opts) {
547
661
  // otherwise. Layered on top (ENG-135): augment PATH with the login-shell +
548
662
  // well-known dirs so the child (and any helpers it spawns) can be located.
549
663
  const pxpipeEnv = claudeSpawnEnv(process.env, opts.routing);
550
- const child = spawn(command, args, {
551
- cwd: claudeCliSessionCwd(),
552
- stdio: ["ignore", "pipe", "pipe"],
553
- env: { ...pxpipeEnv, PATH: claudeChildEnvPath(pxpipeEnv.PATH) },
554
- });
555
- let stdout = "";
556
- let stderr = "";
557
- let settled = false;
558
- const timer = setTimeout(() => {
559
- if (settled)
560
- return;
561
- settled = true;
562
- child.kill("SIGKILL");
563
- reject(new Error(`claude CLI timed out after ${String(CLAUDE_CLI_TURN_TIMEOUT_MS / 1000)}s`));
564
- }, CLAUDE_CLI_TURN_TIMEOUT_MS);
565
- child.stdout.on("data", (chunk) => {
566
- stdout += chunk.toString("utf-8");
567
- });
568
- child.stderr.on("data", (chunk) => {
569
- stderr += chunk.toString("utf-8");
570
- });
571
- child.on("error", (error) => {
572
- if (settled)
573
- return;
574
- settled = true;
575
- clearTimeout(timer);
576
- if (error.code === "ENOENT") {
577
- // ENG-135: actionable message naming every location that was searched.
578
- reject(new Error(claudeNotFoundMessage()));
579
- return;
580
- }
581
- reject(error);
582
- });
583
- child.on("close", (code) => {
584
- if (settled)
585
- return;
586
- settled = true;
587
- clearTimeout(timer);
588
- if (code !== 0) {
589
- reject(new Error(stderr.trim() || `claude CLI exited with code ${String(code ?? "null")}`));
590
- return;
591
- }
592
- let parsed;
593
- try {
594
- parsed = JSON.parse(stdout);
595
- }
596
- catch {
597
- reject(new Error(`claude CLI returned non-JSON output: ${stdout.slice(0, 500)}`));
598
- return;
599
- }
600
- const shaped = parsed;
601
- if (shaped.is_error) {
602
- reject(new Error(shaped.result ?? "claude CLI reported an error"));
603
- return;
604
- }
605
- if (typeof shaped.result !== "string" || typeof shaped.session_id !== "string") {
606
- reject(new Error("claude CLI returned an unexpected JSON shape (missing result/session_id)."));
607
- return;
608
- }
609
- resolve({ text: shaped.result, sessionId: shaped.session_id });
610
- });
664
+ const attempt = (withPartial) => {
665
+ // ENG-404: through spawnCrossPlatform so an npm-installed `claude.cmd`
666
+ // runs via cmd.exe on Windows; POSIX spawns are unchanged.
667
+ const child = spawnPiped(spawn, command, buildArgs(withPartial), {
668
+ cwd: claudeCliSessionCwd(),
669
+ stdio: ["ignore", "pipe", "pipe"],
670
+ env: { ...pxpipeEnv, PATH: claudeChildEnvPath(pxpipeEnv.PATH) },
671
+ }, undefined);
672
+ let stdout = "";
673
+ let stderr = "";
674
+ let settled = false;
675
+ let sawStdout = false;
676
+ const stream = streaming ? parseClaudeStream() : null;
677
+ const emit = (deltas) => {
678
+ if (!onText || settled)
679
+ return;
680
+ for (const delta of deltas) {
681
+ try {
682
+ onText(delta);
683
+ }
684
+ catch {
685
+ // A failing listener must not break the turn itself.
686
+ }
687
+ }
688
+ };
689
+ const timer = setTimeout(() => {
690
+ if (settled)
691
+ return;
692
+ settled = true;
693
+ // Windows: taskkill /T so claude under a cmd.exe wrapper dies too.
694
+ killProcessGroupNow(child);
695
+ reject(new Error(`claude CLI timed out after ${String(CLAUDE_CLI_TURN_TIMEOUT_MS / 1000)}s`));
696
+ }, CLAUDE_CLI_TURN_TIMEOUT_MS);
697
+ child.stdout.on("data", (chunk) => {
698
+ if (chunk.length > 0)
699
+ sawStdout = true;
700
+ if (stream) {
701
+ emit(stream.push(chunk));
702
+ return;
703
+ }
704
+ stdout += chunk.toString("utf-8");
705
+ });
706
+ child.stderr.on("data", (chunk) => {
707
+ stderr += chunk.toString("utf-8");
708
+ });
709
+ child.on("error", (error) => {
710
+ if (settled)
711
+ return;
712
+ settled = true;
713
+ clearTimeout(timer);
714
+ if (error.code === "ENOENT") {
715
+ // ENG-135: actionable message naming every location that was searched.
716
+ reject(new Error(claudeNotFoundMessage()));
717
+ return;
718
+ }
719
+ reject(error);
720
+ });
721
+ child.on("close", (code) => {
722
+ if (settled)
723
+ return;
724
+ if (stream) {
725
+ // Flush the trailing line before settling so its deltas still reach onText.
726
+ const { deltas, result } = stream.finish();
727
+ emit(deltas);
728
+ settled = true;
729
+ clearTimeout(timer);
730
+ if (code !== 0) {
731
+ // ENG-387: the CLI rejected --include-partial-messages before
732
+ // producing any output → retry once without it. Nothing reached
733
+ // onText yet, so the retry cannot duplicate deltas.
734
+ if (withPartial && !sawStdout && rejectsPartialMessagesFlag(stderr)) {
735
+ attempt(false);
736
+ return;
737
+ }
738
+ reject(new Error(stderr.trim() || `claude CLI exited with code ${String(code ?? "null")}`));
739
+ return;
740
+ }
741
+ if (result.isError) {
742
+ reject(new Error(result.text || "claude CLI reported an error"));
743
+ return;
744
+ }
745
+ if (!result.done || result.sessionId === null) {
746
+ reject(new Error("claude CLI stream ended without a result event (missing result/session_id)."));
747
+ return;
748
+ }
749
+ resolve({ text: result.text, sessionId: result.sessionId });
750
+ return;
751
+ }
752
+ settled = true;
753
+ clearTimeout(timer);
754
+ if (code !== 0) {
755
+ reject(new Error(stderr.trim() || `claude CLI exited with code ${String(code ?? "null")}`));
756
+ return;
757
+ }
758
+ let parsed;
759
+ try {
760
+ parsed = JSON.parse(stdout);
761
+ }
762
+ catch {
763
+ reject(new Error(`claude CLI returned non-JSON output: ${stdout.slice(0, 500)}`));
764
+ return;
765
+ }
766
+ const shaped = parsed;
767
+ if (shaped.is_error) {
768
+ reject(new Error(shaped.result ?? "claude CLI reported an error"));
769
+ return;
770
+ }
771
+ if (typeof shaped.result !== "string" || typeof shaped.session_id !== "string") {
772
+ reject(new Error("claude CLI returned an unexpected JSON shape (missing result/session_id)."));
773
+ return;
774
+ }
775
+ resolve({ text: shaped.result, sessionId: shaped.session_id });
776
+ });
777
+ };
778
+ attempt(streaming);
611
779
  });
612
780
  }
613
781
  // ---------------------------------------------------------------------
@@ -641,6 +809,41 @@ export function needsDefaultModel(error) {
641
809
  const message = error instanceof Error ? error.message : String(error);
642
810
  return /requires usage credits|switch to another model|model.*not available|not have access to/i.test(message);
643
811
  }
812
+ const MAX_CONVERSATION_SESSIONS = 50;
813
+ const conversationSessions = new Map();
814
+ function rememberConversationSession(jobId, session) {
815
+ conversationSessions.delete(jobId);
816
+ conversationSessions.set(jobId, session);
817
+ while (conversationSessions.size > MAX_CONVERSATION_SESSIONS) {
818
+ const oldest = conversationSessions.keys().next().value;
819
+ if (oldest === undefined)
820
+ break;
821
+ conversationSessions.delete(oldest);
822
+ }
823
+ }
824
+ /** Test hook: forget every remembered conversation session. */
825
+ export function resetConversationSessions() {
826
+ conversationSessions.clear();
827
+ }
828
+ /** A comparable fingerprint of one message as the AI saw it. */
829
+ export function sessionMessageKey(m) {
830
+ return `${m.role}\u0000${contentText(m.content)}`;
831
+ }
832
+ /**
833
+ * True when `next` starts with everything the session already saw and adds at
834
+ * least one new message; anything else (an edited or shortened history) means
835
+ * the session no longer matches and the turn must run fresh.
836
+ */
837
+ export function extendsSession(seen, next) {
838
+ if (next.length <= seen.length)
839
+ return false;
840
+ return seen.every((key, i) => next[i] === key);
841
+ }
842
+ /** The prompt for a resumed turn: only the messages the session hasn't seen. */
843
+ export function renderResumePrompt(fresh) {
844
+ const lines = fresh.map((m) => `${m.role === "assistant" ? "You" : "Them"}: ${contentText(m.content)}`);
845
+ return `${lines.join("\n\n")}\n\nWrite your next reply to them.`;
846
+ }
644
847
  function savedRequestIdOf(job) {
645
848
  const result = job.result;
646
849
  if (typeof result?.epicRequestId === "string")
@@ -670,6 +873,8 @@ export async function invokeEpicRequestStep(job, ctx) {
670
873
  }
671
874
  }
672
875
  async function takeConversationStep(job, ctx) {
876
+ // ENG-392: the clock starts as soon as the daemon picks the step up.
877
+ const timer = startTurnTimer();
673
878
  const routing = await resolveRouting();
674
879
  const requestId = savedRequestIdOf(job);
675
880
  const discussed = requestId !== null && parseSeedPayload(job.payload)?.targetEpicRequestId === requestId;
@@ -691,6 +896,7 @@ async function takeConversationStep(job, ctx) {
691
896
  saved,
692
897
  anthropic,
693
898
  attachmentsDir,
899
+ timer,
694
900
  });
695
901
  }
696
902
  finally {
@@ -698,8 +904,30 @@ async function takeConversationStep(job, ctx) {
698
904
  await rm(attachmentsDir, { recursive: true, force: true });
699
905
  }
700
906
  }
907
+ export function startTurnTimer(now = () => performance.now()) {
908
+ const startedAt = now();
909
+ let firstTextAt = null;
910
+ const elapsed = (at) => Math.max(0, Math.round(at - startedAt));
911
+ return {
912
+ markFirstText() {
913
+ firstTextAt ??= now();
914
+ },
915
+ finish(model) {
916
+ const metrics = {
917
+ firstTokenMs: firstTextAt === null ? null : elapsed(firstTextAt),
918
+ totalMs: elapsed(now()),
919
+ };
920
+ if (model)
921
+ metrics.model = model;
922
+ return metrics;
923
+ },
924
+ };
925
+ }
701
926
  async function converseWithAttachments(job, ctx, step) {
702
927
  const { routing, saved, anthropic, attachmentsDir } = step;
928
+ const timer = step.timer ?? startTurnTimer();
929
+ // ENG-392: the model that produced the last reply; null → the sign-in default.
930
+ let replyModel = null;
703
931
  let usedFiles = false;
704
932
  const turns = [];
705
933
  for (const [index, t] of job.turns.entries()) {
@@ -720,41 +948,82 @@ async function converseWithAttachments(job, ctx, step) {
720
948
  }
721
949
  }
722
950
  const readDir = usedFiles ? attachmentsDir : undefined;
723
- let cliModel = ANTHROPIC_MODEL;
951
+ // Once the person's plan rejects a chosen model, use their default for the rest of the step.
952
+ let useDefaultModel = false;
953
+ const chosenChatModel = chosenChatModelOf(job.payload);
724
954
  const outcome = await runConversationStep({ turns, saved }, {
725
- reply: async (system, messages) => {
955
+ reply: async (system, messages, kind) => {
956
+ const model = modelForTurn(kind, chosenChatModel);
726
957
  if (anthropic) {
727
958
  const response = await anthropic.messages.create({
728
- model: ANTHROPIC_MODEL,
959
+ model,
729
960
  max_tokens: 4096,
730
961
  system,
731
962
  messages,
732
963
  });
733
964
  const text = response.content.find((b) => b.type === "text");
734
- return text?.type === "text" ? text.text : "";
965
+ const reply = text?.type === "text" ? text.text : "";
966
+ replyModel = response.model || model;
967
+ if (reply)
968
+ timer.markFirstText();
969
+ return reply;
735
970
  }
736
- const prompt = renderConversationPrompt(messages);
737
- try {
738
- return (await runClaudeCliTurn(prompt, {
739
- systemPrompt: system,
740
- resumeSessionId: undefined,
741
- routing,
742
- model: cliModel,
743
- attachmentsDir: readDir,
744
- })).text;
971
+ // ENG-391: a later turn resumes this job's claude session and sends
972
+ // only what's new; if that fails, forget the session and run once
973
+ // fresh with the whole transcript.
974
+ const sent = messages.map(sessionMessageKey);
975
+ const runFresh = async () => {
976
+ const prompt = renderConversationPrompt(messages);
977
+ try {
978
+ return await runClaudeCliTurn(prompt, {
979
+ systemPrompt: system,
980
+ resumeSessionId: undefined,
981
+ routing,
982
+ model: useDefaultModel ? null : model,
983
+ attachmentsDir: readDir,
984
+ });
985
+ }
986
+ catch (error) {
987
+ if (useDefaultModel || !needsDefaultModel(error))
988
+ throw error;
989
+ useDefaultModel = true;
990
+ return await runClaudeCliTurn(prompt, {
991
+ systemPrompt: system,
992
+ resumeSessionId: undefined,
993
+ routing,
994
+ model: null,
995
+ attachmentsDir: readDir,
996
+ });
997
+ }
998
+ };
999
+ const session = conversationSessions.get(job.id);
1000
+ let turn = null;
1001
+ if (session && extendsSession(session.sent, sent)) {
1002
+ try {
1003
+ turn = await runClaudeCliTurn(renderResumePrompt(messages.slice(session.sent.length)), {
1004
+ systemPrompt: system,
1005
+ resumeSessionId: session.sessionId,
1006
+ routing,
1007
+ model: useDefaultModel ? null : model,
1008
+ attachmentsDir: readDir,
1009
+ });
1010
+ }
1011
+ catch {
1012
+ turn = null;
1013
+ }
745
1014
  }
746
- catch (error) {
747
- if (cliModel === null || !needsDefaultModel(error))
748
- throw error;
749
- cliModel = null;
750
- return (await runClaudeCliTurn(prompt, {
751
- systemPrompt: system,
752
- resumeSessionId: undefined,
753
- routing,
754
- model: null,
755
- attachmentsDir: readDir,
756
- })).text;
1015
+ if (!turn) {
1016
+ conversationSessions.delete(job.id);
1017
+ turn = await runFresh();
757
1018
  }
1019
+ rememberConversationSession(job.id, {
1020
+ sessionId: turn.sessionId,
1021
+ sent: [...sent, sessionMessageKey({ role: "assistant", content: turn.text })],
1022
+ });
1023
+ replyModel = useDefaultModel ? null : model;
1024
+ if (turn.text)
1025
+ timer.markFirstText();
1026
+ return turn.text;
758
1027
  },
759
1028
  save: async (existingId, draft) => {
760
1029
  const submitted = await submitAndScore(ctx, existingId, draft);
@@ -764,7 +1033,7 @@ async function converseWithAttachments(job, ctx, step) {
764
1033
  if (outcome.kind === "saved") {
765
1034
  await ctx.mailboxClient.markRequestSaved(ctx.machineToken, job.id, outcome.saved.id);
766
1035
  }
767
- await ctx.mailboxClient.postTurn(ctx.machineToken, job.id, outcome.text);
1036
+ await ctx.mailboxClient.postTurn(ctx.machineToken, job.id, outcome.text, timer.finish(replyModel));
768
1037
  return { status: "yield" };
769
1038
  }
770
1039
  // ---------------------------------------------------------------------
@@ -1153,13 +1422,13 @@ export async function invokeStartExecutionPlan(ctx, deps = {}) {
1153
1422
  let stdout = "";
1154
1423
  let stderr = "";
1155
1424
  let settled = false;
1156
- const child = spawnImpl(command, args, {
1425
+ const child = spawnPiped(spawnImpl, command, args, {
1157
1426
  cwd: ctx.projectDir,
1158
1427
  stdio: ["ignore", "pipe", "pipe"],
1159
1428
  env: childEnv,
1160
1429
  // ENG-300: lead its own process group so a cancel can stop everything it started.
1161
1430
  ...groupSpawnOptions(deps.processGroup?.platform),
1162
- });
1431
+ }, deps.processGroup?.platform);
1163
1432
  // ENG-300: a cancel from the website terminates the whole group; the run is
1164
1433
  // reported once the child has actually exited (or after a grace backstop).
1165
1434
  let cancelled = false;
@@ -1387,13 +1656,13 @@ export async function invokeStartExecutionRefine(ctx, deps = {}) {
1387
1656
  let stdout = "";
1388
1657
  let stderr = "";
1389
1658
  let settled = false;
1390
- const child = spawnImpl(command, args, {
1659
+ const child = spawnPiped(spawnImpl, command, args, {
1391
1660
  cwd: ctx.projectDir,
1392
1661
  stdio: ["ignore", "pipe", "pipe"],
1393
1662
  env: childEnv,
1394
1663
  // ENG-300: lead its own process group so a cancel can stop everything it started.
1395
1664
  ...groupSpawnOptions(deps.processGroup?.platform),
1396
- });
1665
+ }, deps.processGroup?.platform);
1397
1666
  // ENG-300: a cancel from the website terminates the whole group; the run is
1398
1667
  // reported once the child has actually exited (or after a grace backstop).
1399
1668
  let cancelled = false;
@@ -1656,12 +1925,12 @@ export function createClaudeConflictResolver(opts) {
1656
1925
  const timeoutMs = opts.timeoutMs ?? CONFLICT_RESOLVE_TIMEOUT_MS;
1657
1926
  return ({ dir, files, baseBranch, signal }) => new Promise((resolve) => {
1658
1927
  let settled = false;
1659
- const child = spawnImpl(opts.command, buildConflictResolveArgs(files, baseBranch), {
1928
+ const child = spawnPiped(spawnImpl, opts.command, buildConflictResolveArgs(files, baseBranch), {
1660
1929
  cwd: dir,
1661
1930
  stdio: ["ignore", "ignore", "pipe"],
1662
1931
  env: opts.env,
1663
1932
  ...groupSpawnOptions(opts.processGroup?.platform),
1664
- });
1933
+ }, opts.processGroup?.platform);
1665
1934
  let stderr = "";
1666
1935
  child.stderr.on("data", (chunk) => {
1667
1936
  stderr += chunk.toString("utf-8");
@@ -1722,7 +1991,10 @@ export function buildOrchestratorArgs(epicId, sessionId, ownerReply, baseBranch,
1722
1991
  : "") +
1723
1992
  (extra?.followUp ? `\n\n${followUpContext(extra.followUp)}` : "") +
1724
1993
  (extra?.ownerNote ? `\n\n${ownerNoteContext(extra.ownerNote)}` : "") +
1725
- (extra?.deferred && extra.deferred.length > 0 ? `\n\n${deferredFeaturesText(extra.deferred)}` : ""),
1994
+ (extra?.deferred && extra.deferred.length > 0
1995
+ ? `\n\n${deferredFeaturesText(extra.deferred)}`
1996
+ : "") +
1997
+ (extra?.checkMode ? `\n\n${checkModeText(extra.checkMode)}` : ""),
1726
1998
  // A known session id lets the runner resume this same conversation when
1727
1999
  // the agent ends its turn early (see buildOrchestratorContinueArgs).
1728
2000
  ...(sessionId ? ["--session-id", sessionId] : []),
@@ -1747,14 +2019,23 @@ export function buildOrchestratorArgs(epicId, sessionId, ownerReply, baseBranch,
1747
2019
  */
1748
2020
  export const MAX_ORCHESTRATOR_CONTINUES = 5;
1749
2021
  /** The prompt that resumes a stopped orchestrator in the same session. */
1750
- export function orchestratorContinuePrompt(epicId, done, total, deferred = []) {
2022
+ export function orchestratorContinuePrompt(epicId, done, total, deferred = [], checkMode) {
1751
2023
  return [
1752
2024
  `Continue executing epic ${epicId} in non-interactive mode. CompBox shows ${String(done)} of ${String(total)} features done.`,
1753
2025
  "You ended your turn early, which stopped the run. Do not announce the next step: take it.",
1754
2026
  "Keep going until every feature is done and recorded in CompBox, or a hard gate stops the run.",
1755
2027
  ...(deferred.length > 0 ? [deferredFeaturesText(deferred)] : []),
2028
+ ...(checkMode ? [checkModeText(checkMode)] : []),
1756
2029
  ].join(" ");
1757
2030
  }
2031
+ /**
2032
+ * ENG-395: the project's check cadence, for every orchestrator prompt, so the
2033
+ * orchestrator runs reviewer/QA/security checks every feature ("every"), once
2034
+ * per phase ("smart"), or once at the end ("end"). Pure — exported for tests.
2035
+ */
2036
+ export function checkModeText(checkMode) {
2037
+ return `Check mode: ${checkMode}`;
2038
+ }
1758
2039
  /**
1759
2040
  * ER-130: the features the owner deferred, for every orchestrator prompt, so
1760
2041
  * a continue or restart never picks them up again. Pure — exported for tests.
@@ -1811,7 +2092,9 @@ function parseReplyAttachments(raw) {
1811
2092
  if (typeof item !== "object" || item === null)
1812
2093
  continue;
1813
2094
  const a = item;
1814
- if (typeof a.id !== "string" || typeof a.mimeType !== "string" || typeof a.signedUrl !== "string")
2095
+ if (typeof a.id !== "string" ||
2096
+ typeof a.mimeType !== "string" ||
2097
+ typeof a.signedUrl !== "string")
1815
2098
  continue;
1816
2099
  if (a.signedUrl.trim() === "")
1817
2100
  continue;
@@ -1845,7 +2128,9 @@ export function parseReplyResume(job) {
1845
2128
  if (r.reply.trim() === "" && attachments.length === 0)
1846
2129
  return null;
1847
2130
  const str = (v) => (typeof v === "string" && v.trim() !== "" ? v : null);
1848
- const result = typeof job.result === "object" && job.result !== null ? job.result : {};
2131
+ const result = typeof job.result === "object" && job.result !== null
2132
+ ? job.result
2133
+ : {};
1849
2134
  return {
1850
2135
  sessionId: str(r.sessionId),
1851
2136
  runDir: str(r.runDir),
@@ -1985,10 +2270,13 @@ export function defaultWorktreeCapable(dir) {
1985
2270
  export function defaultToolchainPresent(_dir) {
1986
2271
  for (const pm of ["pnpm", "npm"]) {
1987
2272
  try {
1988
- const res = spawnSync(pm, ["--version"], {
2273
+ // ENG-404: pnpm/npm are .cmd shims on Windows, which spawnSync can't run
2274
+ // without cmd.exe — plan the spawn the same way spawnCrossPlatform does.
2275
+ const plan = planCrossPlatformSpawn(pm, ["--version"], {
1989
2276
  stdio: "ignore",
1990
2277
  env: { ...process.env, PATH: claudeChildEnvPath(process.env.PATH) },
1991
2278
  });
2279
+ const res = spawnSync(plan.command, plan.args, plan.options);
1992
2280
  if (res.status === 0)
1993
2281
  return true;
1994
2282
  }
@@ -2010,7 +2298,7 @@ export function mergePullRequestsRequest(prs) {
2010
2298
  question: `${count} your review and merge before the build can continue.`,
2011
2299
  why: "The rest of the build builds on this work, so continuing now would redo it or conflict with it.",
2012
2300
  steps: prs.map((pr, i) => `${String(i + 1)}. Merge #${String(pr.number)}${pr.title ? ` ${pr.title}` : ""}: ${pr.htmlUrl}`),
2013
- afterAnswer: "The build continues by itself once they're merged. You can also press \"All merged — continue\".",
2301
+ afterAnswer: 'The build continues by itself once they\'re merged. You can also press "All merged — continue".',
2014
2302
  kind: "merge_prs",
2015
2303
  prNumbers: prs.map((pr) => pr.number),
2016
2304
  };
@@ -2304,6 +2592,7 @@ export async function invokeStartExecutionOrchestrate(ctx, deps = {}) {
2304
2592
  ...(ctx.deferredFeatures && { deferred: ctx.deferredFeatures }),
2305
2593
  ...(ctx.followUp && { followUp: ctx.followUp }),
2306
2594
  ...(attachmentsNote && { replyAttachmentsNote: attachmentsNote }),
2595
+ ...(ctx.checkMode && { checkMode: ctx.checkMode }),
2307
2596
  });
2308
2597
  const args = ctx.keyRun ? keyRunArgs(runArgs) : runArgs;
2309
2598
  // pxpipe (ENG-136): inject ANTHROPIC_BASE_URL when routed. COMPBOX_NONINTERACTIVE
@@ -2322,6 +2611,11 @@ export async function invokeStartExecutionOrchestrate(ctx, deps = {}) {
2322
2611
  // git/gh calls (push, pull request) use its own env and never see it.
2323
2612
  PATH: withMergeGuardPath(claudeChildEnvPath(routedEnv.PATH), deps.mergeGuardDir === undefined ? join(getConfigDir(), "merge-guard") : deps.mergeGuardDir),
2324
2613
  };
2614
+ // ENG-394: the agent's commits skip the repo's own hooks (orchestrator,
2615
+ // conflict fix and follow-up all use this env); the run's checks cover them.
2616
+ const agentHooksDir = makeAgentHooksDir(runDir);
2617
+ if (agentHooksDir)
2618
+ Object.assign(baseEnv, withHooksDisabled(baseEnv, agentHooksDir));
2325
2619
  const childEnv = ctx.keyRun ? keyRunEnv(baseEnv, ctx.keyRun) : baseEnv;
2326
2620
  // H4: relay a START turn immediately so the web shows the run began even if the
2327
2621
  // orchestrator produces no stdout for minutes. postTurn failures are swallowed.
@@ -2380,13 +2674,13 @@ export async function invokeStartExecutionOrchestrate(ctx, deps = {}) {
2380
2674
  let stderr = "";
2381
2675
  let outputBytes = 0;
2382
2676
  let settled = false;
2383
- const child = spawnImpl(command, runArgsNow, {
2677
+ const child = spawnPiped(spawnImpl, command, runArgsNow, {
2384
2678
  cwd: runDir,
2385
2679
  stdio: ["ignore", "pipe", "pipe"],
2386
2680
  env: childEnv,
2387
2681
  // ENG-300: lead its own process group so a cancel can stop everything it started.
2388
2682
  ...groupSpawnOptions(deps.processGroup?.platform),
2389
- });
2683
+ }, deps.processGroup?.platform);
2390
2684
  // ENG-300: a cancel from the website terminates the whole group; the run is
2391
2685
  // reported once the child has actually exited (or after a grace backstop).
2392
2686
  let cancelled = false;
@@ -2580,7 +2874,10 @@ export async function invokeStartExecutionOrchestrate(ctx, deps = {}) {
2580
2874
  /** One run, then a resume of the same session for each note the owner sent during it. */
2581
2875
  const runDeliveringNotes = async (runArgsNow, budgetMs) => {
2582
2876
  let result = await runOnce(runArgsNow, budgetMs);
2583
- while (sessionId && pendingNotes.length > 0 && !ctx.signal?.aborted && deadline - Date.now() > 60_000) {
2877
+ while (sessionId &&
2878
+ pendingNotes.length > 0 &&
2879
+ !ctx.signal?.aborted &&
2880
+ deadline - Date.now() > 60_000) {
2584
2881
  const notes = pendingNotes.splice(0);
2585
2882
  try {
2586
2883
  await ctx.mailboxClient.postTurn(ctx.machineToken, ctx.jobId, `Got your note. Stopped the agent's current step and passed the note on; the build carries on from here.`);
@@ -2606,7 +2903,9 @@ export async function invokeStartExecutionOrchestrate(ctx, deps = {}) {
2606
2903
  (async () => {
2607
2904
  try {
2608
2905
  const job = await ctx.mailboxClient.postTurn(ctx.machineToken, ctx.jobId, `The orchestrator finished. Checking epic ${ctx.epicId}'s progress in CompBox…`);
2609
- return job.progress ? { ...job.progress, waitingPullRequests: job.waitingPullRequests ?? [] } : null;
2906
+ return job.progress
2907
+ ? { ...job.progress, waitingPullRequests: job.waitingPullRequests ?? [] }
2908
+ : null;
2610
2909
  }
2611
2910
  catch {
2612
2911
  return null;
@@ -2636,7 +2935,7 @@ export async function invokeStartExecutionOrchestrate(ctx, deps = {}) {
2636
2935
  // Best-effort status turn.
2637
2936
  }
2638
2937
  const before = progress.completedFeatures;
2639
- const continueArgs = buildOrchestratorContinueArgs(sessionId, orchestratorContinuePrompt(ctx.epicId, progress.completedFeatures, progress.totalFeatures, ctx.deferredFeatures), workspace?.baseBranch, ctx.fastMode);
2938
+ const continueArgs = buildOrchestratorContinueArgs(sessionId, orchestratorContinuePrompt(ctx.epicId, progress.completedFeatures, progress.totalFeatures, ctx.deferredFeatures, ctx.checkMode), workspace?.baseBranch, ctx.fastMode);
2640
2939
  outcome = await runDeliveringNotes(ctx.keyRun ? keyRunArgs(continueArgs) : continueArgs, deadline - Date.now());
2641
2940
  if (outcome.status !== "done")
2642
2941
  break;
@@ -2678,7 +2977,9 @@ export async function invokeStartExecutionOrchestrate(ctx, deps = {}) {
2678
2977
  ...outcome.result,
2679
2978
  fastMode: { requested: true, used: fastModeUsed },
2680
2979
  ...(fastModeUsed === false
2681
- ? { fastModeNote: "Fast mode was requested but isn't available on this computer's Claude account, so the run used standard speed." }
2980
+ ? {
2981
+ fastModeNote: "Fast mode was requested but isn't available on this computer's Claude account, so the run used standard speed.",
2982
+ }
2682
2983
  : {}),
2683
2984
  };
2684
2985
  }
@@ -2786,6 +3087,8 @@ export async function invokeStartExecutionOrchestrate(ctx, deps = {}) {
2786
3087
  deps.activeRunDirs?.delete(workspace.dir);
2787
3088
  if (replyAttachmentsDir)
2788
3089
  await rm(replyAttachmentsDir, { recursive: true, force: true }).catch(() => undefined);
3090
+ if (agentHooksDir)
3091
+ await rm(agentHooksDir, { recursive: true, force: true }).catch(() => undefined);
2789
3092
  // ENG-352: where the run's time went, for the run page's breakdown.
2790
3093
  const timings = buildJobTimings({
2791
3094
  install: workspace?.install,