@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.
@@ -225,6 +225,28 @@ export interface NeedsReviewResult {
225
225
  * to surface for review than to mis-report success).
226
226
  */
227
227
  export declare function detectNeedsHumanReview(output: string): NeedsReviewResult;
228
+ /** The parts of an epic's stored complianceScore the planner runner acts on. */
229
+ export interface EpicComplianceSummary {
230
+ overall: number | null;
231
+ tier: string | null;
232
+ /** Codes of the `critical` issues in the latest audit. */
233
+ criticalIssueCodes: string[];
234
+ }
235
+ /**
236
+ * Reduce an epic's API `complianceScore` (parsed object, or a JSON string from
237
+ * older servers) to the fields the planner runner needs. Returns null when no
238
+ * usable score is present. Pure + exported for unit testing (ENG-287-2).
239
+ */
240
+ export declare function summarizeComplianceScore(raw: unknown): EpicComplianceSummary | null;
241
+ /**
242
+ * Build the FINAL mailbox turn for a planner run (H4). A needs-review outcome
243
+ * always names the latest overall score and the critical issue codes when they
244
+ * are known, so the person sees why the plan was held back. Pure + exported.
245
+ */
246
+ export declare function buildPlannerFinalTurn(outcome: {
247
+ status: 'done' | 'failed';
248
+ result: Record<string, unknown>;
249
+ }): string;
228
250
  export interface StartExecutionPlanCtx {
229
251
  mailboxClient: MailboxClient;
230
252
  machineToken: string;
@@ -266,6 +288,45 @@ export interface StartExecutionPlanDeps {
266
288
  * non-zero exit, fail with a result the web failure banner can display.
267
289
  */
268
290
  export declare function invokeStartExecutionPlan(ctx: StartExecutionPlanCtx, deps?: StartExecutionPlanDeps): Promise<InvokeResult>;
291
+ /** The env var the planner's Refine Mode reads the user's notes from. */
292
+ export declare const REFINE_NOTES_ENV = "COMPBOX_REFINE_NOTES";
293
+ /**
294
+ * Argv for the headless refine run. Mirrors {@link buildPlannerArgs}; the notes
295
+ * are deliberately NOT a parameter — see {@link buildRefineEnv}.
296
+ */
297
+ export declare function buildRefineArgs(epicId: string): string[];
298
+ /**
299
+ * Child env for the refine run: the routed (pxpipe) env plus the headless
300
+ * signal, an augmented PATH and — only when non-empty — the notes. Any
301
+ * COMPBOX_REFINE_NOTES inherited from the daemon's own env is dropped so a
302
+ * stale value can never leak into an unrelated run.
303
+ */
304
+ export declare function buildRefineEnv(routedEnv: NodeJS.ProcessEnv, notes: string | undefined): NodeJS.ProcessEnv;
305
+ export interface StartExecutionRefineCtx {
306
+ mailboxClient: MailboxClient;
307
+ machineToken: string;
308
+ jobId: string;
309
+ apiBaseUrl: string;
310
+ userApiToken: string;
311
+ /** The existing epic to refine (payload.epicId). */
312
+ epicId: string;
313
+ /** Optional user notes (payload.notes) — passed via env only. */
314
+ notes?: string | undefined;
315
+ projectDir: string | undefined;
316
+ keyRun?: KeyRun;
317
+ }
318
+ export type StartExecutionRefineDeps = StartExecutionPlanDeps;
319
+ /** One-line final mailbox turn for a refine run. */
320
+ export declare function buildRefineFinalTurn(outcome: InvokeResult): string;
321
+ /**
322
+ * Run the planner headless in Refine Mode for a `start_execution`/`refine` job
323
+ * (ENG-289). Validates the repo, spawns `@planner --refine <epicId> --gates=auto
324
+ * --non-interactive`, keeps the machine alive, and on a clean exit re-reads the
325
+ * epic's latest audit: still critical-fail → needs human review; otherwise
326
+ * done `{ epicId, refined: true }`. The planner's needs-review marker wins
327
+ * regardless of exit code.
328
+ */
329
+ export declare function invokeStartExecutionRefine(ctx: StartExecutionRefineCtx, deps?: StartExecutionRefineDeps): Promise<InvokeResult>;
269
330
  /**
270
331
  * Per-run wall-clock budget for the headless orchestrator child (H4). Executing
271
332
  * a full epic (every phase, every feature-worker, reviewer + QA + security
@@ -1 +1 @@
1
- {"version":3,"file":"agent-invoker.d.ts","sourceRoot":"","sources":["../../src/utils/agent-invoker.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAEH,OAAO,SAAS,MAAM,mBAAmB,CAAC;AAC1C,OAAO,EAAE,KAAK,EAAa,MAAM,oBAAoB,CAAC;AAItD,OAAO,EAEL,KAA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(prompt, opts) {
396
396
  // ---------------------------------------------------------------------
397
397
  // Request conversations (always open): one AI reply per claim.
398
398
  // ---------------------------------------------------------------------
399
- /** The request this conversation already saved, read with the person's token. */
400
- async function loadSavedRequest(apiBaseUrl, userApiToken, epicRequestId) {
401
- const res = await fetch(`${apiBaseUrl.replace(/\/+$/, '')}/api/v1/epic-requests/${encodeURIComponent(epicRequestId)}`, { headers: { Authorization: `Bearer ${userApiToken}` } });
399
+ /**
400
+ * The request this conversation is about, read with the person's token. The
401
+ * person may change it only if they created it (the API's own rule for content
402
+ * edits, ENG-291); if we can't tell who they are, treat it as not theirs.
403
+ */
404
+ async function loadSavedRequest(apiBaseUrl, userApiToken, epicRequestId, discussed) {
405
+ const base = apiBaseUrl.replace(/\/+$/, '');
406
+ const headers = { Authorization: `Bearer ${userApiToken}` };
407
+ const [res, meRes] = await Promise.all([
408
+ fetch(`${base}/api/v1/epic-requests/${encodeURIComponent(epicRequestId)}`, { headers }),
409
+ fetch(`${base}/api/v1/auth/me`, { headers }).catch(() => null),
410
+ ]);
402
411
  if (!res.ok)
403
412
  return null;
404
413
  const body = (await res.json().catch(() => null));
405
- return savedContextFromRecord(body?.data);
414
+ const me = meRes?.ok ? (await meRes.json().catch(() => null)) : null;
415
+ const requestedById = body?.data?.requestedById;
416
+ const canEdit = typeof me?.id === 'string' && typeof requestedById === 'string' && me.id === requestedById;
417
+ return savedContextFromRecord(body?.data, { canEdit, discussed });
406
418
  }
407
419
  /**
408
420
  * True when the person's Claude plan can't use the requested model (for
@@ -443,7 +455,8 @@ export async function invokeEpicRequestStep(job, ctx) {
443
455
  async function takeConversationStep(job, ctx) {
444
456
  const routing = await resolveRouting();
445
457
  const requestId = savedRequestIdOf(job);
446
- const saved = requestId ? await loadSavedRequest(ctx.apiBaseUrl, ctx.userApiToken, requestId) : null;
458
+ const discussed = requestId !== null && parseSeedPayload(job.payload)?.targetEpicRequestId === requestId;
459
+ const saved = requestId ? await loadSavedRequest(ctx.apiBaseUrl, ctx.userApiToken, requestId, discussed) : null;
447
460
  const turns = job.turns.map((t) => ({
448
461
  role: t.role,
449
462
  content: t.role === 'user' ? appendAttachmentNote(t.content, imageAttachmentCount(t.attachments)) : t.content,
@@ -694,6 +707,89 @@ async function fetchConvertedEpicId(apiBaseUrl, userApiToken, epicRequestId, fet
694
707
  return null;
695
708
  }
696
709
  }
710
+ /**
711
+ * Reduce an epic's API `complianceScore` (parsed object, or a JSON string from
712
+ * older servers) to the fields the planner runner needs. Returns null when no
713
+ * usable score is present. Pure + exported for unit testing (ENG-287-2).
714
+ */
715
+ export function summarizeComplianceScore(raw) {
716
+ let score = raw;
717
+ if (typeof score === 'string') {
718
+ try {
719
+ score = JSON.parse(score);
720
+ }
721
+ catch {
722
+ return null;
723
+ }
724
+ }
725
+ if (!score || typeof score !== 'object' || Array.isArray(score))
726
+ return null;
727
+ const s = score;
728
+ const overall = typeof s.overall === 'number' ? s.overall : null;
729
+ const tier = typeof s.tier === 'string' ? s.tier : null;
730
+ if (overall === null && tier === null)
731
+ return null;
732
+ const criticalIssueCodes = Array.isArray(s.issues)
733
+ ? s.issues
734
+ .filter((i) => !!i && typeof i === 'object' && typeof i.code === 'string')
735
+ .filter((i) => i.tier === 'critical')
736
+ .map((i) => i.code)
737
+ : [];
738
+ return { overall, tier, criticalIssueCodes };
739
+ }
740
+ /** Fetch the epic's latest stored audit (complianceScore). Best-effort: null on any failure. */
741
+ async function fetchEpicComplianceSummary(apiBaseUrl, userApiToken, epicId, fetchImpl) {
742
+ try {
743
+ const res = await fetchImpl(`${apiBaseUrl.replace(/\/+$/, '')}/api/v1/epics/${encodeURIComponent(epicId)}`, { headers: { Authorization: `Bearer ${userApiToken}` } });
744
+ if (!res.ok)
745
+ return null;
746
+ const body = (await res.json());
747
+ return summarizeComplianceScore(body.data?.complianceScore);
748
+ }
749
+ catch {
750
+ return null;
751
+ }
752
+ }
753
+ /**
754
+ * Build the FINAL mailbox turn for a planner run (H4). A needs-review outcome
755
+ * always names the latest overall score and the critical issue codes when they
756
+ * are known, so the person sees why the plan was held back. Pure + exported.
757
+ */
758
+ export function buildPlannerFinalTurn(outcome) {
759
+ const r = outcome.result;
760
+ if (outcome.status === 'done') {
761
+ const epicId = typeof r.epicId === 'string' ? r.epicId : '';
762
+ return `Planning complete — created epic ${epicId}.`;
763
+ }
764
+ if (r.needsHumanReview === true) {
765
+ const marker = r.marker && typeof r.marker === 'object' ? r.marker : {};
766
+ const overall = typeof r.overallScore === 'number'
767
+ ? r.overallScore
768
+ : typeof marker.overallScore === 'number'
769
+ ? marker.overallScore
770
+ : null;
771
+ const tier = typeof r.tier === 'string' ? r.tier : typeof marker.tier === 'string' ? marker.tier : null;
772
+ const codes = Array.isArray(r.criticalIssueCodes)
773
+ ? r.criticalIssueCodes.filter((c) => typeof c === 'string')
774
+ : [];
775
+ const epicId = typeof r.epicId === 'string' ? r.epicId : typeof marker.epicId === 'string' ? marker.epicId : '';
776
+ const parts = ['Planner run needs human review'];
777
+ if (epicId)
778
+ parts.push(`(epic ${epicId})`);
779
+ let text = `${parts.join(' ')}.`;
780
+ if (overall !== null)
781
+ text += ` Latest audit score: ${String(overall)}/100${tier ? ` (${tier})` : ''}.`;
782
+ else if (tier)
783
+ text += ` Latest audit tier: ${tier}.`;
784
+ if (codes.length > 0)
785
+ text += ` Critical issues: ${codes.join(', ')}.`;
786
+ const message = typeof r.message === 'string' ? r.message : typeof r.error === 'string' ? r.error : '';
787
+ if (message)
788
+ text += ` ${message}`;
789
+ return text.slice(0, PLANNER_FINAL_TURN_MAX_CHARS);
790
+ }
791
+ return `Planner run ended: ${JSON.stringify(r).slice(0, PLANNER_FINAL_TURN_MAX_CHARS)}`;
792
+ }
697
793
  /**
698
794
  * Run the planner headless for a `start_execution`/`plan` job (ENG-164).
699
795
  *
@@ -835,25 +931,232 @@ export async function invokeStartExecutionPlan(ctx, deps = {}) {
835
931
  // independent of stdout formatting.
836
932
  const epicId = await fetchConvertedEpicId(ctx.apiBaseUrl, ctx.userApiToken, ctx.epicRequestId, fetchImpl);
837
933
  if (!epicId) {
934
+ // ENG-287-2: an unconverted ER is never a success — surface it for review.
838
935
  finish({
839
936
  status: 'failed',
840
937
  result: {
938
+ needsHumanReview: true,
939
+ stage: 'VERIFY',
841
940
  error: 'The planner finished but no epic was produced (the Epic Request was not converted to an epic). It may need human review.',
842
941
  },
843
942
  });
844
943
  return;
845
944
  }
945
+ // ENG-287-2: a clean exit is not enough — if the produced epic's latest
946
+ // audit is critical-fail, hold it for human review instead of success.
947
+ const compliance = await fetchEpicComplianceSummary(ctx.apiBaseUrl, ctx.userApiToken, epicId, fetchImpl);
948
+ if (compliance?.tier === 'critical-fail') {
949
+ finish({
950
+ status: 'failed',
951
+ result: {
952
+ needsHumanReview: true,
953
+ stage: 'EVALUATE',
954
+ epicId,
955
+ tier: compliance.tier,
956
+ overallScore: compliance.overall,
957
+ criticalIssueCodes: compliance.criticalIssueCodes,
958
+ message: 'The planner exited cleanly but the epic\'s latest audit is critical-fail; human review required before execution.',
959
+ },
960
+ });
961
+ return;
962
+ }
846
963
  finish({ status: 'done', result: { epicId } });
847
964
  })();
848
965
  });
849
966
  });
850
967
  // H4: relay a FINAL turn summarizing the outcome (best-effort).
851
968
  try {
852
- const epicId = typeof outcome.result.epicId === 'string' ? outcome.result.epicId : '';
853
- const summary = outcome.status === 'done'
854
- ? `Planning complete — created epic ${epicId}.`
855
- : `Planner run ended: ${JSON.stringify(outcome.result).slice(0, PLANNER_FINAL_TURN_MAX_CHARS)}`;
856
- await ctx.mailboxClient.postTurn(ctx.machineToken, ctx.jobId, summary);
969
+ await ctx.mailboxClient.postTurn(ctx.machineToken, ctx.jobId, buildPlannerFinalTurn(outcome));
970
+ }
971
+ catch {
972
+ // Best-effort final turn.
973
+ }
974
+ return outcome;
975
+ }
976
+ // ---------------------------------------------------------------------
977
+ // start_execution / kind:'refine' (ENG-289) — re-run the local @planner in
978
+ // `--refine` mode against an EXISTING epic. Same spawn profile as the plan
979
+ // runner (H1 unattended permissions + MCP/CLAUDE.md routing, H4 heartbeat,
980
+ // COMPBOX_NONINTERACTIVE=1, pxpipe ANTHROPIC_BASE_URL). The user's free-text
981
+ // notes travel ONLY through the COMPBOX_REFINE_NOTES env var — never argv —
982
+ // so they can't inject flags or leak into process listings.
983
+ // ---------------------------------------------------------------------
984
+ /** The env var the planner's Refine Mode reads the user's notes from. */
985
+ export const REFINE_NOTES_ENV = 'COMPBOX_REFINE_NOTES';
986
+ /**
987
+ * Argv for the headless refine run. Mirrors {@link buildPlannerArgs}; the notes
988
+ * are deliberately NOT a parameter — see {@link buildRefineEnv}.
989
+ */
990
+ export function buildRefineArgs(epicId) {
991
+ return [
992
+ '-p',
993
+ `@planner --refine ${epicId} --gates=auto --non-interactive`,
994
+ '--permission-mode',
995
+ 'bypassPermissions',
996
+ ];
997
+ }
998
+ /**
999
+ * Child env for the refine run: the routed (pxpipe) env plus the headless
1000
+ * signal, an augmented PATH and — only when non-empty — the notes. Any
1001
+ * COMPBOX_REFINE_NOTES inherited from the daemon's own env is dropped so a
1002
+ * stale value can never leak into an unrelated run.
1003
+ */
1004
+ export function buildRefineEnv(routedEnv, notes) {
1005
+ const { [REFINE_NOTES_ENV]: _inherited, ...rest } = routedEnv;
1006
+ const trimmed = notes?.trim();
1007
+ return {
1008
+ ...rest,
1009
+ COMPBOX_NONINTERACTIVE: '1',
1010
+ PATH: claudeChildEnvPath(routedEnv.PATH),
1011
+ ...(trimmed ? { [REFINE_NOTES_ENV]: trimmed } : {}),
1012
+ };
1013
+ }
1014
+ /** One-line final mailbox turn for a refine run. */
1015
+ export function buildRefineFinalTurn(outcome) {
1016
+ const r = outcome.result;
1017
+ const text = (value) => (typeof value === 'string' && value ? value : undefined);
1018
+ if (outcome.status === 'done') {
1019
+ return `Refine finished. The epic ${text(r.epicId) ?? ''} was updated in place.`;
1020
+ }
1021
+ if (r.needsHumanReview === true) {
1022
+ return `Refine needs human review: ${text(r.message) ?? text(r.error) ?? 'the epic is still critical-fail'}`.slice(0, PLANNER_FINAL_TURN_MAX_CHARS);
1023
+ }
1024
+ return `Refine run ended: ${text(r.error) ?? JSON.stringify(r)}`.slice(0, PLANNER_FINAL_TURN_MAX_CHARS);
1025
+ }
1026
+ /**
1027
+ * Run the planner headless in Refine Mode for a `start_execution`/`refine` job
1028
+ * (ENG-289). Validates the repo, spawns `@planner --refine <epicId> --gates=auto
1029
+ * --non-interactive`, keeps the machine alive, and on a clean exit re-reads the
1030
+ * epic's latest audit: still critical-fail → needs human review; otherwise
1031
+ * done `{ epicId, refined: true }`. The planner's needs-review marker wins
1032
+ * regardless of exit code.
1033
+ */
1034
+ export async function invokeStartExecutionRefine(ctx, deps = {}) {
1035
+ const spawnImpl = deps.spawnImpl ?? spawn;
1036
+ const fetchImpl = deps.fetchImpl ?? fetch;
1037
+ const isGitRepo = deps.isGitRepo ?? isGitRepoDir;
1038
+ const resolveRoutingImpl = deps.resolveRoutingImpl ?? resolveRouting;
1039
+ const heartbeatIntervalMs = deps.heartbeatIntervalMs ?? PLANNER_HEARTBEAT_INTERVAL_MS;
1040
+ const timeoutMs = deps.timeoutMs ?? PLANNER_RUN_TIMEOUT_MS;
1041
+ if (!ctx.projectDir) {
1042
+ return { status: 'failed', result: { error: projectDirNotConfiguredMessage() } };
1043
+ }
1044
+ if (!isGitRepo(ctx.projectDir)) {
1045
+ return { status: 'failed', result: { error: projectDirNotGitRepoMessage(ctx.projectDir) } };
1046
+ }
1047
+ const routing = await resolveRoutingImpl();
1048
+ const command = resolveClaudeBinary() ?? 'claude';
1049
+ const args = ctx.keyRun ? keyRunArgs(buildRefineArgs(ctx.epicId)) : buildRefineArgs(ctx.epicId);
1050
+ const baseEnv = buildRefineEnv(claudeSpawnEnv(process.env, routing), ctx.notes);
1051
+ const childEnv = ctx.keyRun ? keyRunEnv(baseEnv, ctx.keyRun) : baseEnv;
1052
+ try {
1053
+ await ctx.mailboxClient.postTurn(ctx.machineToken, ctx.jobId, `Started the planner in refine mode for epic ${ctx.epicId} (headless)${ctx.notes?.trim() ? ', with your notes' : ''}. This may take several minutes.`);
1054
+ }
1055
+ catch {
1056
+ // Best-effort start turn.
1057
+ }
1058
+ const outcome = await new Promise((resolve) => {
1059
+ let stdout = '';
1060
+ let stderr = '';
1061
+ let settled = false;
1062
+ const child = spawnImpl(command, args, {
1063
+ cwd: ctx.projectDir,
1064
+ stdio: ['ignore', 'pipe', 'pipe'],
1065
+ env: childEnv,
1066
+ });
1067
+ const heartbeatTimer = deps.heartbeat
1068
+ ? setInterval(() => {
1069
+ void Promise.resolve(deps.heartbeat?.()).catch(() => {
1070
+ // Best-effort keep-alive.
1071
+ });
1072
+ }, heartbeatIntervalMs)
1073
+ : undefined;
1074
+ const finish = (result) => {
1075
+ if (settled)
1076
+ return;
1077
+ settled = true;
1078
+ if (heartbeatTimer)
1079
+ clearInterval(heartbeatTimer);
1080
+ clearTimeout(timer);
1081
+ resolve(result);
1082
+ };
1083
+ const timer = setTimeout(() => {
1084
+ child.kill('SIGKILL');
1085
+ finish({
1086
+ status: 'failed',
1087
+ result: {
1088
+ error: `The refine run timed out after ${String(Math.round(timeoutMs / 60_000))} minutes and was terminated. The epic may be partially refined.`,
1089
+ },
1090
+ });
1091
+ }, timeoutMs);
1092
+ child.stdout.on('data', (chunk) => {
1093
+ stdout += chunk.toString('utf-8');
1094
+ });
1095
+ child.stderr.on('data', (chunk) => {
1096
+ stderr += chunk.toString('utf-8');
1097
+ });
1098
+ child.on('error', (error) => {
1099
+ finish({
1100
+ status: 'failed',
1101
+ result: {
1102
+ error: error.code === 'ENOENT'
1103
+ ? claudeNotFoundMessage()
1104
+ : error.message || 'Failed to spawn the planner.',
1105
+ },
1106
+ });
1107
+ });
1108
+ child.on('close', (code) => {
1109
+ void (async () => {
1110
+ if (ctx.keyRun)
1111
+ stdout = await settleKeyRun(ctx, ctx.keyRun, stdout);
1112
+ const combined = `${stdout}\n${stderr}`;
1113
+ const review = detectNeedsHumanReview(combined);
1114
+ if (review.needsReview) {
1115
+ finish({
1116
+ status: 'failed',
1117
+ result: {
1118
+ needsHumanReview: true,
1119
+ stage: 'REFINE',
1120
+ epicId: ctx.epicId,
1121
+ message: 'Refine could not clear the epic\'s critical audit issues; human review required before execution.',
1122
+ ...(review.marker ? { marker: review.marker } : {}),
1123
+ },
1124
+ });
1125
+ return;
1126
+ }
1127
+ if (code !== 0) {
1128
+ finish({
1129
+ status: 'failed',
1130
+ result: {
1131
+ error: stderr.trim() ||
1132
+ stdout.trim().slice(-PLANNER_FINAL_TURN_MAX_CHARS) ||
1133
+ `The planner (refine) exited with code ${String(code ?? 'null')}.`,
1134
+ },
1135
+ });
1136
+ return;
1137
+ }
1138
+ const compliance = await fetchEpicComplianceSummary(ctx.apiBaseUrl, ctx.userApiToken, ctx.epicId, fetchImpl);
1139
+ if (compliance?.tier === 'critical-fail') {
1140
+ finish({
1141
+ status: 'failed',
1142
+ result: {
1143
+ needsHumanReview: true,
1144
+ stage: 'REFINE',
1145
+ epicId: ctx.epicId,
1146
+ tier: compliance.tier,
1147
+ overallScore: compliance.overall,
1148
+ criticalIssueCodes: compliance.criticalIssueCodes,
1149
+ message: 'Refine finished but the epic\'s latest audit is still critical-fail; human review required before execution.',
1150
+ },
1151
+ });
1152
+ return;
1153
+ }
1154
+ finish({ status: 'done', result: { epicId: ctx.epicId, refined: true } });
1155
+ })();
1156
+ });
1157
+ });
1158
+ try {
1159
+ await ctx.mailboxClient.postTurn(ctx.machineToken, ctx.jobId, buildRefineFinalTurn(outcome));
857
1160
  }
858
1161
  catch {
859
1162
  // Best-effort final turn.