@tokenoftrust/cli 1.4.0 → 1.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -39,8 +39,24 @@ import { planForAction, printPlanAndConfirm } from "../plan.mjs";
39
39
  // Reuse `tot ship`'s operator-secret precedence verbatim so accept + ship + pr-list
40
40
  // speak ONE operator-auth contract, not three.
41
41
  import { resolveOperatorSecret } from "./ship.mjs";
42
+ // Automate-first conflict recovery (workstream tot-merge-conflict-resolution-ux, unit
43
+ // u5): the ONE-CLICK `--refresh` path calls the `candidate_refresh` MCP tool (u1) —
44
+ // which has NO operator-secret HTTP route, so it is reached over the MCP client the
45
+ // same way `tot pr` reaches `candidate_status`/`candidate_close`.
46
+ import { createMcpClient } from "../mcp.mjs";
47
+ import { establishSession, AuthUnavailableError } from "../auth.mjs";
42
48
 
43
49
  const DEFAULT_STOREFRONT_URL = "https://storefront.tokenoftrust.store";
50
+ const DEFAULT_MCP_URL = "https://mcp.tokenoftrust.com";
51
+
52
+ // The three refresh strategies `candidate_refresh` (u1) accepts, mirroring the admin
53
+ // panel's one-click resolver (keep-mine / keep-current / smart-merge). `merge` is the
54
+ // DEFAULT: a real forge three-way merge that refuses cleanly (with the diverged file
55
+ // list) on a genuine same-line overlap rather than silently clobbering either side —
56
+ // exactly the automate-first posture (auto-resolve where safe, name the conflict when
57
+ // not, never a raw rebase instruction).
58
+ export const REFRESH_STRATEGIES = ["ours", "theirs", "merge"];
59
+ const DEFAULT_REFRESH_STRATEGY = "merge";
44
60
 
45
61
  const USAGE = `tot accept — queue a PR's integration into the preview aggregate (alias: tot merge)
46
62
 
@@ -57,6 +73,11 @@ const USAGE = `tot accept — queue a PR's integration into the preview aggregat
57
73
  exact plan and asks for an explicit confirm. There is no default-yes; a non-TTY
58
74
  without --yes is refused rather than silently proceeding.
59
75
 
76
+ If the preview branch has moved under your change so it is no longer mergeable,
77
+ accept does NOT hand you a rebase — it offers to REBUILD the change on the current
78
+ preview tip for you. Pass --refresh to do it in one step (no local git), choosing
79
+ how to resolve any file that changed on both sides with --strategy.
80
+
60
81
  Options:
61
82
  --tenant <appDomain> Target tenant (e.g. tokenoftrust.com). Defaults to the
62
83
  current checkout's tenant when run inside one.
@@ -65,7 +86,15 @@ Options:
65
86
  --change-id <id> Target a specific change record instead of a PR number.
66
87
  --head-sha <sha> Optional expected PR head sha (expectedHeadSha) — an
67
88
  optimistic-concurrency guard against a PR that moved.
89
+ --refresh If the candidate isn't mergeable, rebuild it on the current
90
+ preview tip (via candidate_refresh) and then integrate — no
91
+ local rebase. Needs your \`tot login\` sign-in + promote access.
92
+ --strategy <s> How --refresh resolves a file changed on BOTH sides:
93
+ "merge" (real 3-way merge, refuses on a genuine conflict —
94
+ the default), "ours" (keep your version), "theirs" (keep
95
+ preview's version).
68
96
  --url <origin> storefront origin (default: env TOT_STOREFRONT_URL)
97
+ --mcp <url> MCP base URL for --refresh (default: env TOT_MCP_URL)
69
98
  --secret <s> operator secret (prefer the env vars below)
70
99
  --yes, -y Skip the interactive confirm (still an explicit human
71
100
  affirmative — there is no default-yes).
@@ -82,8 +111,11 @@ export function parseAcceptArgs(argv) {
82
111
  changeId: null,
83
112
  headSha: null,
84
113
  url: null,
114
+ mcp: null,
85
115
  secret: null,
86
116
  identity: null,
117
+ refresh: false,
118
+ strategy: null,
87
119
  yes: false,
88
120
  help: false,
89
121
  };
@@ -94,8 +126,11 @@ export function parseAcceptArgs(argv) {
94
126
  else if (t === "--change-id") a.changeId = argv[++i];
95
127
  else if (t === "--head-sha" || t === "--head") a.headSha = argv[++i];
96
128
  else if (t === "--url") a.url = argv[++i];
129
+ else if (t === "--mcp") a.mcp = argv[++i];
97
130
  else if (t === "--secret") a.secret = argv[++i];
98
131
  else if (t === "--identity") a.identity = argv[++i];
132
+ else if (t === "--refresh") a.refresh = true;
133
+ else if (t === "--strategy") a.strategy = argv[++i];
99
134
  else if (t === "--yes" || t === "-y") a.yes = true;
100
135
  else if (t === "--help" || t === "-h") a.help = true;
101
136
  }
@@ -128,6 +163,255 @@ export function normalizeIntegrateResponse(data) {
128
163
  };
129
164
  }
130
165
 
166
+ /** A human label for a candidate: its PR number when known, else its changeId. Pure. */
167
+ function candidateLabel(pr, changeId) {
168
+ return pr != null ? `PR #${pr}` : `change ${changeId}`;
169
+ }
170
+
171
+ /**
172
+ * Read the forge `mergeable` verdict for a candidate out of a `GET /api/changes`
173
+ * body (b07's operator queue — its BUILT entries carry the full ReviewEnvironment
174
+ * shape, incl. `mergeable`). This is the mergeable PREFLIGHT source: one read over the
175
+ * SAME operator-secret transport accept already uses, so a not-mergeable candidate is
176
+ * caught BEFORE a doomed integrate round-trips to the forge. Best-effort by design —
177
+ * `known:false` (proceed as normal) whenever the candidate isn't found or isn't built
178
+ * yet (no `mergeable`), so this never turns a transient listing gap into a false
179
+ * refusal. Pure — unit-tested.
180
+ * @param {any} data
181
+ * @param {{ pr:number|null, changeId:string|null }} target
182
+ * @returns {{ known:boolean, mergeable:boolean|null, changeId:string|null, prNumber:number|null }}
183
+ */
184
+ export function readCandidateVerdict(data, { pr, changeId }) {
185
+ const list = Array.isArray(data)
186
+ ? data
187
+ : data && Array.isArray(data.changes)
188
+ ? data.changes
189
+ : [];
190
+ const wantPr =
191
+ typeof pr === "number"
192
+ ? pr
193
+ : pr != null && `${pr}`.trim() && Number.isFinite(Number(pr))
194
+ ? Number(pr)
195
+ : null;
196
+ const wantId = typeof changeId === "string" && changeId ? changeId : null;
197
+ const match =
198
+ list.find(
199
+ (c) =>
200
+ c &&
201
+ typeof c === "object" &&
202
+ ((wantId && c.changeId === wantId) || (wantPr != null && c.prNumber === wantPr)),
203
+ ) || null;
204
+ if (!match) return { known: false, mergeable: null, changeId: wantId, prNumber: wantPr };
205
+ const mergeable = match.mergeable === true ? true : match.mergeable === false ? false : null;
206
+ return {
207
+ known: mergeable !== null,
208
+ mergeable,
209
+ changeId: typeof match.changeId === "string" ? match.changeId : wantId,
210
+ prNumber: typeof match.prNumber === "number" ? match.prNumber : wantPr,
211
+ };
212
+ }
213
+
214
+ /**
215
+ * Normalise a `candidate_refresh` (u1) result read back over the MCP client.
216
+ * `status:"committed"` is the ONLY success (the candidate was rebuilt and is now
217
+ * mergeable); a `merge_failed` refusal carries `unresolved` (the diverged files);
218
+ * any other status is an honest refusal/error surfaced by its `message`. Reads
219
+ * defensively — a plausible field rename degrades, never crashes. Pure — unit-tested.
220
+ * @param {any} data
221
+ */
222
+ export function normalizeRefreshResult(data) {
223
+ const o = data && typeof data === "object" ? data : {};
224
+ const ok = o.status === "committed";
225
+ return {
226
+ ok,
227
+ status: typeof o.status === "string" ? o.status : ok ? "committed" : "error",
228
+ changeId: typeof o.changeId === "string" ? o.changeId : null,
229
+ prNumber: typeof o.prNumber === "number" ? o.prNumber : null,
230
+ mergeable: typeof o.mergeable === "boolean" ? o.mergeable : null,
231
+ strategy: typeof o.strategy === "string" ? o.strategy : null,
232
+ refreshedFiles: Array.isArray(o.refreshedFiles)
233
+ ? o.refreshedFiles.filter((x) => typeof x === "string")
234
+ : [],
235
+ unresolved: Array.isArray(o.unresolved)
236
+ ? o.unresolved.filter((x) => typeof x === "string")
237
+ : [],
238
+ message: typeof o.message === "string" ? o.message : null,
239
+ };
240
+ }
241
+
242
+ /**
243
+ * The automate-first OFFER printed when a candidate isn't mergeable and --refresh was
244
+ * NOT passed: the one-click rebuild, never a raw git/rebase instruction and never the
245
+ * banned "resolve the conflict, then retry". Pure — returns the lines to print.
246
+ * @param {string} tenant
247
+ * @param {{ pr:number|null, changeId:string|null }} target
248
+ * @returns {string[]}
249
+ */
250
+ export function notMergeableOfferLines(tenant, { pr, changeId }) {
251
+ const sel = pr != null ? `--pr ${pr}` : `--change-id ${changeId}`;
252
+ const cmd = `tot accept --tenant ${tenant} ${sel}`;
253
+ return [
254
+ " Rebuild it automatically on the current preview tip — no local checkout, one command:",
255
+ ` ${cmd} --refresh smart 3-way merge (the default)`,
256
+ ` ${cmd} --refresh --strategy=ours keep your version on any clash`,
257
+ ` ${cmd} --refresh --strategy=theirs take preview's version on any clash`,
258
+ " Nothing was integrated.",
259
+ ];
260
+ }
261
+
262
+ /**
263
+ * Run `candidate_refresh` (u1) over the MCP client — the ONE-CLICK rebuild of a
264
+ * not-mergeable candidate onto the current preview tip. `candidate_refresh` has no
265
+ * operator-secret HTTP route, so this reaches it exactly as `tot pr` reaches
266
+ * `candidate_status`: an OAuth developer session (`tot login`) + `client_switch` to
267
+ * bind the tenant scope. `createClient`/`establishSession` are injected so it's
268
+ * unit-tested with no live MCP.
269
+ *
270
+ * @param {{ tenant:string, changeId:string, strategy:string, mcpUrl?:string|null,
271
+ * identity?:string|null, env?:NodeJS.ProcessEnv }} params
272
+ * @param {{ createClient?:typeof createMcpClient, establishSession?:typeof establishSession }} [deps]
273
+ * @returns {Promise<ReturnType<typeof normalizeRefreshResult> & { hint?:string|null }>}
274
+ */
275
+ export async function runRefresh(
276
+ { tenant, changeId, strategy, mcpUrl = null, identity = null, env = process.env },
277
+ deps = {},
278
+ ) {
279
+ const create = deps.createClient || createMcpClient;
280
+ const establish = deps.establishSession || establishSession;
281
+ const baseUrl = mcpUrl || env.MCP_BASE_URL || env.TOT_MCP_URL || DEFAULT_MCP_URL;
282
+ const client = create(baseUrl);
283
+ try {
284
+ await establish(client, { env, prefer: identity || undefined });
285
+ // Bind the active tenant so candidate_refresh resolves the right scope (mirrors
286
+ // `tot pr`). Best-effort — the tool also takes `repo` explicitly.
287
+ try {
288
+ await client.callTool("client_switch", { tenant });
289
+ } catch {
290
+ /* best-effort scope bind */
291
+ }
292
+ const raw = await client.callTool("candidate_refresh", { repo: tenant, changeId, strategy });
293
+ return normalizeRefreshResult(raw);
294
+ } catch (e) {
295
+ if (e instanceof AuthUnavailableError) {
296
+ return { ...normalizeRefreshResult(null), status: "auth", message: e.message, hint: e.hint };
297
+ }
298
+ return { ...normalizeRefreshResult(null), status: "error", message: String(e?.message || e) };
299
+ }
300
+ }
301
+
302
+ /**
303
+ * Render a `candidate_refresh` FAILURE in the automate-first house style — a genuine
304
+ * conflict names the diverged files and offers the ours/theirs escape hatch; an auth
305
+ * gap points to `tot login`; any other refusal surfaces the MCP's own message. NEVER
306
+ * prints raw git/rebase or the banned "resolve the conflict, then retry". Returns the
307
+ * process exit code (always 1). Pure given console.
308
+ */
309
+ function reportRefreshFailure(rr, { tenant, pr, changeId, strategy }) {
310
+ const sel = pr != null ? `--pr ${pr}` : `--change-id ${changeId}`;
311
+ const cmd = `tot accept --tenant ${tenant} ${sel}`;
312
+ if (rr.status === "auth") {
313
+ console.error(
314
+ fail(
315
+ "auto-refresh needs your Token of Trust sign-in",
316
+ rr.hint || "run `tot login`, then re-run with --refresh",
317
+ ),
318
+ );
319
+ return 1;
320
+ }
321
+ if (rr.status === "merge_failed") {
322
+ console.log(
323
+ `\n ✗ couldn't auto-merge ${candidateLabel(pr, changeId)} onto ${tenant}'s current preview with --strategy=${strategy}.`,
324
+ );
325
+ if (rr.unresolved.length) {
326
+ console.log(" These files changed on both sides and need your call:");
327
+ for (const f of rr.unresolved) console.log(` - ${f}`);
328
+ }
329
+ console.log(" Re-run choosing which side wins on those files:");
330
+ console.log(` ${cmd} --refresh --strategy=ours keep your version`);
331
+ console.log(` ${cmd} --refresh --strategy=theirs take preview's version`);
332
+ console.log(" Nothing was integrated.");
333
+ return 1;
334
+ }
335
+ // Any other refusal (not_found / not_open / base_not_found / a capability guard /
336
+ // an unexpected error): surface the MCP's own message honestly — never dressed up.
337
+ console.error(
338
+ fail(
339
+ rr.message || `couldn't refresh ${candidateLabel(pr, changeId)} (${rr.status})`,
340
+ "check the candidate is open and that you have promote access for this store",
341
+ ),
342
+ );
343
+ return 1;
344
+ }
345
+
346
+ /**
347
+ * Decide + act on a NOT-mergeable candidate (the automate-first fork): without
348
+ * --refresh, print the one-click offer and stop (never a rebase); with --refresh,
349
+ * rebuild via `candidate_refresh` and, on success, hand back the (possibly new) PR
350
+ * handle so the caller integrates the rebuilt candidate. Returns
351
+ * `{ integrate:false, code }` to stop, or `{ integrate:true, pr, changeId }` to
352
+ * proceed.
353
+ */
354
+ async function handleNotMergeable(
355
+ { tenant, pr, changeId, strategy, refresh, mcpUrl, identity, env },
356
+ deps,
357
+ ) {
358
+ if (!refresh) {
359
+ console.log(
360
+ `\n ✗ ${candidateLabel(pr, changeId)} isn't mergeable into ${tenant}'s preview — the preview branch moved under it.`,
361
+ );
362
+ for (const line of notMergeableOfferLines(tenant, { pr, changeId })) console.log(line);
363
+ return { integrate: false, code: 1 };
364
+ }
365
+ if (!changeId) {
366
+ // candidate_refresh keys off the stable changeId; a bare PR number we couldn't
367
+ // resolve to one (not built yet / listing gap) can't be auto-rebuilt.
368
+ console.error(
369
+ fail(
370
+ `can't auto-refresh ${candidateLabel(pr, changeId)} — its change id isn't resolved yet`,
371
+ `check it's built (\`tot pr list --tenant ${tenant}\`), or pass --change-id`,
372
+ ),
373
+ );
374
+ return { integrate: false, code: 1 };
375
+ }
376
+ const rr = await runRefresh({ tenant, changeId, strategy, mcpUrl, identity, env }, deps);
377
+ if (!rr.ok) {
378
+ return { integrate: false, code: reportRefreshFailure(rr, { tenant, pr, changeId, strategy }) };
379
+ }
380
+ console.log(
381
+ `\n ✓ rebuilt ${candidateLabel(rr.prNumber ?? pr, changeId)} on ${tenant}'s current preview (${rr.strategy ?? strategy}) — now mergeable.`,
382
+ );
383
+ if (rr.refreshedFiles.length) console.log(` reapplied: ${rr.refreshedFiles.join(", ")}`);
384
+ // The rebuild opens a FRESH PR (prNumber may change; changeId is stable), so
385
+ // integrate by the new PR number + changeId and drop the now-stale head sha.
386
+ return { integrate: true, pr: rr.prNumber ?? pr, changeId };
387
+ }
388
+
389
+ /** POST `/api/changes/integrate` and normalise the outcome. Returns { res, result }. */
390
+ async function postIntegrate({ base, authHeaders, body }, fetchImpl) {
391
+ const res = await fetchImpl(`${base}/api/changes/integrate`, {
392
+ method: "POST",
393
+ headers: { "content-type": "application/json", ...authHeaders },
394
+ body: JSON.stringify(body),
395
+ });
396
+ let data = {};
397
+ try {
398
+ data = await res.json();
399
+ } catch {
400
+ /* non-JSON / empty body */
401
+ }
402
+ return { res, result: normalizeIntegrateResponse(data) };
403
+ }
404
+
405
+ /** The integrate request body for a target. Pure. */
406
+ function integrateBody({ tenant, pr, changeId, headSha }) {
407
+ return {
408
+ repo: tenant,
409
+ ...(pr != null ? { prNumber: pr } : {}),
410
+ ...(changeId ? { changeId } : {}),
411
+ ...(headSha ? { expectedHeadSha: headSha } : {}),
412
+ };
413
+ }
414
+
131
415
  /**
132
416
  * Render the terminal aggregate status in house style — the honest queue/run state,
133
417
  * NEVER a bare "merged". Pure given its inputs; returns the process exit code.
@@ -144,6 +428,16 @@ export function reportIntegrated(result, { tenant, label }) {
144
428
  console.log(" → next: `tot ship` to promote this green aggregate live.");
145
429
  return 0;
146
430
  }
431
+ // Already integrated (candidate_not_open): the PR merged before this attempt —
432
+ // a SUCCESS the operator is re-hearing, not a failure. Never render the
433
+ // fix-and-retry template for it (live confusion, 2026-08-20: it told an
434
+ // operator to re-submit a change that had already landed). Exit 0 — the
435
+ // desired end state ("this change is in the aggregate") already holds.
436
+ if (result.reason === "candidate_not_open") {
437
+ console.log(`\n ✓ ${label} was ALREADY integrated into ${tenant}'s preview aggregate — nothing left to accept.`);
438
+ console.log(" → next: `tot ship` to promote the aggregate live, or `tot revert` to pull the change back out.");
439
+ return 0;
440
+ }
147
441
  // Honest non-green: the candidate did NOT land in the shippable aggregate.
148
442
  console.log(`\n ✗ ${label} did NOT integrate into ${tenant}'s preview aggregate.`);
149
443
  console.log(` aggregate: ${state}${result.reason ? ` (${result.reason})` : ""}`);
@@ -164,7 +458,20 @@ export function reportIntegrated(result, { tenant, label }) {
164
458
  * @returns {Promise<number>} process exit code
165
459
  */
166
460
  export async function runIntegrate(
167
- { tenant, pr, changeId, headSha, secret, storefrontUrl = null, yes = false },
461
+ {
462
+ tenant,
463
+ pr,
464
+ changeId,
465
+ headSha,
466
+ secret,
467
+ storefrontUrl = null,
468
+ yes = false,
469
+ refresh = false,
470
+ strategy = DEFAULT_REFRESH_STRATEGY,
471
+ mcpUrl = null,
472
+ identity = null,
473
+ env = process.env,
474
+ },
168
475
  deps = {},
169
476
  ) {
170
477
  const fetchImpl = deps.fetch || globalThis.fetch;
@@ -177,7 +484,9 @@ export async function runIntegrate(
177
484
  const planLines = planForAction({ action: "accept", tenant, pr, changeId, headSha });
178
485
  const { confirmed, reason } = await confirmPlan(planLines, {
179
486
  yes,
180
- question: `Queue ${label} for integration into ${tenant}'s preview aggregate?`,
487
+ question: refresh
488
+ ? `Queue ${label} for integration into ${tenant}'s preview aggregate (rebuilding it first if the preview moved)?`
489
+ : `Queue ${label} for integration into ${tenant}'s preview aggregate?`,
181
490
  });
182
491
  if (!confirmed) {
183
492
  if (reason === "non-tty") {
@@ -194,7 +503,8 @@ export async function runIntegrate(
194
503
  }
195
504
 
196
505
  // 2. Operator-secret transport — the CLI holds no storefront cookie, so the
197
- // Bearer + X-Tot-Owner path is its route (same as `tot ship --pr`).
506
+ // Bearer + X-Tot-Owner path is its route (same as `tot ship --pr`). No
507
+ // `content-type` here: it's added per-POST; the mergeable preflight GET wants none.
198
508
  if (!secret) {
199
509
  console.error(
200
510
  fail(
@@ -205,26 +515,48 @@ export async function runIntegrate(
205
515
  return 2;
206
516
  }
207
517
  const authHeaders = {
208
- "content-type": "application/json",
209
518
  authorization: `Bearer ${secret}`,
210
519
  "x-tot-owner": tenant,
211
520
  "x-tot-capability": "ship-on-behalf",
212
521
  };
213
- const requestBody = {
214
- repo: tenant,
215
- ...(pr != null ? { prNumber: pr } : {}),
216
- ...(changeId ? { changeId } : {}),
217
- ...(headSha ? { expectedHeadSha: headSha } : {}),
218
- };
522
+
523
+ // 2.5. MERGEABLE PREFLIGHT — read the candidate's forge verdict from b07's queue
524
+ // (`GET /api/changes`, SAME transport) so a doomed accept never round-trips to
525
+ // the forge. Best-effort: on any listing gap it's `known:false` → proceed as
526
+ // normal. When it KNOWS the candidate isn't mergeable, take the automate-first
527
+ // fork (offer/do --refresh) instead of a raw rebase.
528
+ let curPr = pr;
529
+ let curChangeId = changeId;
530
+ let curHead = headSha;
531
+ const verdict = await preflightMergeable({ base, authHeaders, pr, changeId }, fetchImpl);
532
+ if (verdict.mergeable === false) {
533
+ const handled = await handleNotMergeable(
534
+ {
535
+ tenant,
536
+ pr: verdict.prNumber ?? curPr,
537
+ changeId: verdict.changeId ?? curChangeId,
538
+ strategy,
539
+ refresh,
540
+ mcpUrl,
541
+ identity,
542
+ env,
543
+ },
544
+ deps,
545
+ );
546
+ if (!handled.integrate) return handled.code;
547
+ curPr = handled.pr ?? curPr;
548
+ curChangeId = handled.changeId ?? curChangeId;
549
+ curHead = null; // the rebuilt PR has a fresh head; let the server re-resolve.
550
+ }
219
551
 
220
552
  // 3. POST the honest accept path (b07 queue enqueue) and render the terminal state.
221
553
  let res;
554
+ let result;
222
555
  try {
223
- res = await fetchImpl(`${base}/api/changes/integrate`, {
224
- method: "POST",
225
- headers: authHeaders,
226
- body: JSON.stringify(requestBody),
227
- });
556
+ ({ res, result } = await postIntegrate(
557
+ { base, authHeaders, body: integrateBody({ tenant, pr: curPr, changeId: curChangeId, headSha: curHead }) },
558
+ fetchImpl,
559
+ ));
228
560
  } catch (e) {
229
561
  console.error(
230
562
  fail(`couldn't reach the integration queue at ${base}: ${String(e?.message || e)}`, "check --url / your network, then re-run"),
@@ -232,34 +564,97 @@ export async function runIntegrate(
232
564
  return 1;
233
565
  }
234
566
 
235
- let data = {};
236
- try {
237
- data = await res.json();
238
- } catch {
239
- /* non-JSON / empty body */
240
- }
241
- const result = normalizeIntegrateResponse(data);
242
-
243
567
  // A pre-flight error (auth, unknown tenant, candidate not found) is an HTTP 4xx
244
568
  // with `{ error }` and no queue verdict — surface it distinctly from a red run.
245
569
  if (!res.ok && result.queueState == null) {
246
- const msg = result.error || `HTTP ${res.status}`;
247
- console.error(
248
- fail(
249
- `the integration queue refused the request: ${msg}`,
250
- res.status === 401 || res.status === 403
251
- ? "check the operator secret and that it's authorised for this tenant"
252
- : res.status === 404
253
- ? `check that ${label} has a built candidate in ${tenant}'s queue (\`tot pr list --tenant ${tenant}\`)`
254
- : "check --tenant / --url / --pr, then re-run",
255
- ),
570
+ return reportIntegrateHttpError(result, res, { tenant, label });
571
+ }
572
+
573
+ // 4. A not_mergeable outcome the preflight MISSED (listing gap / a race between
574
+ // read and enqueue): take the same automate-first fork rather than the generic
575
+ // "fix the candidate" copy. Guarded by `!verdict.known` so a candidate the
576
+ // preflight already routed through --refresh can't loop here.
577
+ if (!result.ok && result.reason === "not_mergeable" && !verdict.known) {
578
+ const handled = await handleNotMergeable(
579
+ { tenant, pr: curPr, changeId: result.changeId ?? curChangeId, strategy, refresh, mcpUrl, identity, env },
580
+ deps,
256
581
  );
582
+ if (!handled.integrate) return handled.code;
583
+ try {
584
+ ({ res, result } = await postIntegrate(
585
+ {
586
+ base,
587
+ authHeaders,
588
+ body: integrateBody({
589
+ tenant,
590
+ pr: handled.pr ?? curPr,
591
+ changeId: handled.changeId ?? curChangeId,
592
+ headSha: null,
593
+ }),
594
+ },
595
+ fetchImpl,
596
+ ));
597
+ } catch (e) {
598
+ console.error(
599
+ fail(`couldn't reach the integration queue at ${base}: ${String(e?.message || e)}`, "check --url / your network, then re-run"),
600
+ );
601
+ return 1;
602
+ }
603
+ if (!res.ok && result.queueState == null) {
604
+ return reportIntegrateHttpError(result, res, { tenant, label });
605
+ }
606
+ }
607
+
608
+ // A not_mergeable that survived a refresh attempt (or arrived with --refresh unset
609
+ // on the preflight-known path): the honest one-click offer, never a raw rebase.
610
+ if (!result.ok && result.reason === "not_mergeable") {
611
+ console.log(
612
+ `\n ✗ ${label} still isn't mergeable into ${tenant}'s preview.`,
613
+ );
614
+ for (const line of notMergeableOfferLines(tenant, { pr: curPr, changeId: curChangeId })) {
615
+ console.log(line);
616
+ }
257
617
  return 1;
258
618
  }
259
619
 
260
620
  return reportIntegrated(result, { tenant, label });
261
621
  }
262
622
 
623
+ /** The mergeable PREFLIGHT read (best-effort). See readCandidateVerdict. */
624
+ async function preflightMergeable({ base, authHeaders, pr, changeId }, fetchImpl) {
625
+ try {
626
+ const res = await fetchImpl(`${base}/api/changes`, { method: "GET", headers: authHeaders });
627
+ if (!res || !res.ok) {
628
+ return { known: false, mergeable: null, changeId: changeId ?? null, prNumber: pr ?? null };
629
+ }
630
+ let data = {};
631
+ try {
632
+ data = await res.json();
633
+ } catch {
634
+ return { known: false, mergeable: null, changeId: changeId ?? null, prNumber: pr ?? null };
635
+ }
636
+ return readCandidateVerdict(data, { pr, changeId });
637
+ } catch {
638
+ return { known: false, mergeable: null, changeId: changeId ?? null, prNumber: pr ?? null };
639
+ }
640
+ }
641
+
642
+ /** Surface an integrate HTTP pre-flight error (4xx, no queue verdict). Returns exit 1. */
643
+ function reportIntegrateHttpError(result, res, { tenant, label }) {
644
+ const msg = result.error || `HTTP ${res.status}`;
645
+ console.error(
646
+ fail(
647
+ `the integration queue refused the request: ${msg}`,
648
+ res.status === 401 || res.status === 403
649
+ ? "check the operator secret and that it's authorised for this tenant"
650
+ : res.status === 404
651
+ ? `check that ${label} has a built candidate in ${tenant}'s queue (\`tot pr list --tenant ${tenant}\`)`
652
+ : "check --tenant / --url / --pr, then re-run",
653
+ ),
654
+ );
655
+ return 1;
656
+ }
657
+
263
658
  /**
264
659
  * @param {string[]} argv
265
660
  * @param {any} ctx
@@ -301,6 +696,18 @@ export async function run(argv, ctx) {
301
696
  const storefrontUrl =
302
697
  args.url || env.TOT_STOREFRONT_URL || env.STOREFRONT_BASE_URL || DEFAULT_STOREFRONT_URL;
303
698
 
699
+ // --strategy only means something with --refresh; validate its value whenever given.
700
+ const strategy = (args.strategy || DEFAULT_REFRESH_STRATEGY).trim();
701
+ if (args.strategy != null && !REFRESH_STRATEGIES.includes(strategy)) {
702
+ console.error(
703
+ fail(
704
+ `unknown --strategy "${args.strategy}"`,
705
+ `use one of: ${REFRESH_STRATEGIES.join(", ")} (default "${DEFAULT_REFRESH_STRATEGY}")`,
706
+ ),
707
+ );
708
+ return 2;
709
+ }
710
+
304
711
  return await runIntegrate({
305
712
  tenant,
306
713
  pr,
@@ -309,5 +716,10 @@ export async function run(argv, ctx) {
309
716
  secret: resolveOperatorSecret(args.secret, env),
310
717
  storefrontUrl,
311
718
  yes: args.yes,
719
+ refresh: args.refresh,
720
+ strategy,
721
+ mcpUrl: args.mcp || env.MCP_BASE_URL || env.TOT_MCP_URL || DEFAULT_MCP_URL,
722
+ identity: args.identity || null,
723
+ env,
312
724
  });
313
725
  }