@yolo-labs/yolo-cli 0.32.0 → 0.33.0

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.
@@ -242,6 +242,12 @@ export async function bundleProject(shape, cwd, ceilings = {}, options = {}) {
242
242
  const assetsDir = shape.assetsDir;
243
243
  if (assetsDir !== undefined) {
244
244
  const rootAbs = path.resolve(cwd, assetsDir);
245
+ // Root-dir ships (assetsDir == the project root) serve whatever the walk
246
+ // finds — which for repo-rooted static sites includes tests, README, and
247
+ // the substrate's LANE.md. Those are excluded at the TOP level only:
248
+ // a deliberately-shipped docs/README.md deeper in the tree still ships.
249
+ const isRootShip = rootAbs === path.resolve(cwd);
250
+ const rootShipSkipped = [];
245
251
  let rootStat;
246
252
  try {
247
253
  rootStat = statSync(rootAbs);
@@ -258,6 +264,10 @@ export async function bundleProject(shape, cwd, ceilings = {}, options = {}) {
258
264
  };
259
265
  }
260
266
  for (const relPosix of walkAssetFiles(rootAbs)) {
267
+ if (isRootShip && !relPosix.includes('/') && isRootShipExcludedName(relPosix)) {
268
+ rootShipSkipped.push(relPosix);
269
+ continue;
270
+ }
261
271
  const absPath = path.join(rootAbs, ...relPosix.split('/'));
262
272
  const size = statSync(absPath).size;
263
273
  if (size > caps.maxFileBytes) {
@@ -292,6 +302,11 @@ export async function bundleProject(shape, cwd, ceilings = {}, options = {}) {
292
302
  assetPaths[manifestPath] = absPath;
293
303
  assets.push({ path: manifestPath, hash, size, absPath });
294
304
  }
305
+ if (rootShipSkipped.length > 0) {
306
+ warnings.push(`root-dir ship: excluded ${rootShipSkipped.sort().join(', ')} from the public bundle ` +
307
+ `(tests, README, and lane files don't ship from a repo-root assets dir; ` +
308
+ `use a dist/ publish dir to control exactly what ships)`);
309
+ }
295
310
  }
296
311
  else if (shape.type === 'static') {
297
312
  // Type system prevents this (static requires assetsDir), but guard anyway.
@@ -540,6 +555,21 @@ async function buildWorkerModule(entry, cwd, prebuilt, caps, warnings, compatibi
540
555
  }
541
556
  return { ok: true, module: { name, contents }, source, ...(sourceMap ? { sourceMap } : {}) };
542
557
  }
558
+ /**
559
+ * Top-level names excluded from a ROOT-DIR ship (assetsDir == project root).
560
+ * Repo-rooted static sites otherwise serve their tests, README, and the
561
+ * substrate's LANE.md publicly (2026-07-22 field report). Applies ONLY at the
562
+ * top level of a root ship — never inside an explicit dist/public dir, and a
563
+ * nested docs/README.md still ships. (`.yolo/` and other dot-entries are
564
+ * already dropped by the dotfile rule in walkAssetFiles.)
565
+ */
566
+ function isRootShipExcludedName(name) {
567
+ if (name === 'LANE.md')
568
+ return true;
569
+ if (name.toLowerCase() === 'readme.md')
570
+ return true;
571
+ return /\.test\.(js|mjs|cjs|ts|tsx|jsx)$/i.test(name);
572
+ }
543
573
  /**
544
574
  * Depth-first walk returning sorted posix-relative file paths. Skips
545
575
  * dotfiles/dot-dirs and node_modules at every level. Symlinked DIRS are
@@ -3,7 +3,7 @@
3
3
  * (docs/MANAGED_HOSTING_CLI_SPEC.md §1).
4
4
  *
5
5
  * yolo deploy [--env <staging|prod>] [--dry-run] [--json] ← bare = ship
6
- * yolo deploy init [--slug <slug>] [--type <static|worker>]
6
+ * yolo deploy init [--slug <slug>] [--type <static|worker>] [--json]
7
7
  * yolo deploy status [--json]
8
8
  * yolo deploy logs [--tail] [--since <dur>] [--json]
9
9
  * yolo deploy rollback [releaseId] [--json]
@@ -14,8 +14,9 @@
14
14
  * final JSON object on stdout is the machine-readable result).
15
15
  * - Failures: single structured stderr line `FAIL [<reason>]: <msg> | hint: …`
16
16
  * - awaiting-approval: `PENDING [awaiting-approval]: …` (NOT FAIL) + exit 3
17
- * + the approval URL + the "do NOT rerun" hint. Two independent signals
18
- * so neither prefix-matching nor exit-code-matching agents retry-loop.
17
+ * + the approval URL + the resume hint (rerun ONCE after the grant — the
18
+ * server redeems it automatically; don't loop while pending). Two
19
+ * independent signals so agents don't blind retry-loop.
19
20
  *
20
21
  * Exit codes are EXACTLY spec §5 via deploy-ship's `exitCodeForFailure`:
21
22
  * 0 ok / 64 usage / 78 env / 1 local / 2 backend-rejected / 3 pending / 4 network.
@@ -40,7 +41,7 @@ import { runDeployDev } from './deploy-dev.js';
40
41
  import { defaultReadFile } from './auth-context.js';
41
42
  const USAGE = [
42
43
  'Usage: yolo deploy [--env <staging|prod>] [--dry-run] [--json]',
43
- ' yolo deploy init [--slug <slug>] [--type <static|worker>]',
44
+ ' yolo deploy init [--slug <slug>] [--type <static|worker>] [--json]',
44
45
  ' yolo deploy link (--project-id <id> | --slug <slug>) [--type <static|worker>]',
45
46
  ' yolo deploy validate [--json]',
46
47
  ' yolo deploy doctor [--json]',
@@ -175,7 +176,7 @@ async function runShipCmd(args, deps, io) {
175
176
  if (parsed.jsonOutput) {
176
177
  io.out(`${formatJsonResult({
177
178
  ...result,
178
- hint: "poll 'yolo deploy status'; do NOT rerun 'yolo deploy' — the bundle is already staged",
179
+ hint: "after the operator approves (Approvals panel / notification), rerun 'yolo deploy --env prod' — the grant is redeemed automatically for this bundle. Use --env prod: a bare 'yolo deploy' targets staging and won't resume this prod bundle. An early rerun is harmless (same PENDING, same approvalId). MCP callers can poll deploy.approval_status.",
179
180
  })}\n`);
180
181
  }
181
182
  else {
@@ -183,15 +184,22 @@ async function runShipCmd(args, deps, io) {
183
184
  }
184
185
  return 3;
185
186
  }
186
- io.err(parsed.jsonOutput ? `${formatJsonResult(result)}\n` : `${formatFail(result)}\n`);
187
+ if (parsed.jsonOutput)
188
+ io.out(`${formatJsonResult(result)}\n`);
189
+ else
190
+ io.err(`${formatFail(result)}\n`);
187
191
  return exitCodeForFailure(result.kind);
188
192
  }
189
193
  export function parseInitArgs(args) {
190
194
  let slug;
191
195
  let type;
196
+ let jsonOutput = false;
192
197
  for (let i = 0; i < args.length; i++) {
193
198
  const a = args[i];
194
- if (a === '--slug') {
199
+ if (a === '--json') {
200
+ jsonOutput = true;
201
+ }
202
+ else if (a === '--slug') {
195
203
  const v = args[++i];
196
204
  if (!v || v.startsWith('--'))
197
205
  return { ok: false, message: '--slug requires a value' };
@@ -221,12 +229,21 @@ export function parseInitArgs(args) {
221
229
  return { ok: false, message: `unexpected positional argument: ${a}` };
222
230
  }
223
231
  }
224
- return { ok: true, slug, type };
232
+ return { ok: true, slug, type, jsonOutput };
225
233
  }
226
234
  async function runInitCmd(args, deps, io) {
227
235
  const parsed = parseInitArgs(args);
228
236
  if (!parsed.ok) {
229
- io.err(`yolo deploy init: ${parsed.message}\nUsage: yolo deploy init [--slug <slug>] [--type <static|worker>]\n`);
237
+ // Honor --json even on an ARG error (codex gpt-5.6-sol P2 r6): the flag is
238
+ // detected independently of the (failed) parse so a `--json` caller that
239
+ // always parses the final stdout object still gets a machine-readable
240
+ // result instead of human usage text on stderr.
241
+ if (args.includes('--json')) {
242
+ io.out(`${formatJsonResult({ kind: 'usage', message: parsed.message })}\n`);
243
+ }
244
+ else {
245
+ io.err(`yolo deploy init: ${parsed.message}\nUsage: yolo deploy init [--slug <slug>] [--type <static|worker>] [--json]\n`);
246
+ }
230
247
  return 64;
231
248
  }
232
249
  const cwd = deps.cwd ?? process.cwd();
@@ -235,14 +252,20 @@ async function runInitCmd(args, deps, io) {
235
252
  const readResult = readConfig(cwd);
236
253
  if (!readResult.ok) {
237
254
  // Never silently clobber a malformed/invalid link file.
238
- io.err(`${formatFail({ kind: readResult.kind, message: readResult.message })}\n`);
255
+ const failure = { kind: readResult.kind, message: readResult.message };
256
+ if (parsed.jsonOutput)
257
+ io.out(`${formatJsonResult(failure)}\n`);
258
+ else
259
+ io.err(`${formatFail(failure)}\n`);
239
260
  return exitCodeForFailure(readResult.kind);
240
261
  }
241
262
  const existing = readResult.config;
242
263
  if (existing?.projectId) {
243
264
  // Idempotent: a committed link means future sessions ship to the SAME
244
265
  // project instead of forking a new slug — never silently re-create.
245
- io.out(`OK: already linked to project ${existing.projectId}${existing.slug ? ` (slug ${existing.slug})` : ''} — .yolo/deploy.json left unchanged\n`);
266
+ io.out(parsed.jsonOutput
267
+ ? `${formatJsonResult({ status: 'already-linked', projectId: existing.projectId, ...(existing.slug ? { slug: existing.slug } : {}) })}\n`
268
+ : `OK: already linked to project ${existing.projectId}${existing.slug ? ` (slug ${existing.slug})` : ''} — .yolo/deploy.json left unchanged\n`);
246
269
  return 0;
247
270
  }
248
271
  // Fresh init in a project that has a wrangler config but no .yolo/deploy.json:
@@ -252,7 +275,11 @@ async function runInitCmd(args, deps, io) {
252
275
  const adapted = existing == null ? adaptWrangler(cwd, deps.readFileImpl) : undefined;
253
276
  const auth = resolveAuth(deps);
254
277
  if (!auth.ok) {
255
- io.err(`${formatFail({ kind: 'auth', message: auth.message })}\n`);
278
+ const failure = { kind: 'auth', message: auth.message };
279
+ if (parsed.jsonOutput)
280
+ io.out(`${formatJsonResult(failure)}\n`);
281
+ else
282
+ io.err(`${formatFail({ kind: 'auth', message: auth.message })}\n`);
256
283
  return 78;
257
284
  }
258
285
  const create = deps.createProjectImpl ?? createProject;
@@ -282,11 +309,22 @@ async function runInitCmd(args, deps, io) {
282
309
  const owned = lookup.ok ? lookup.project : undefined;
283
310
  const projectId = owned ? resolveProjectId(owned) : undefined;
284
311
  if (projectId) {
285
- return writeLinkFile(cwd, writeConfig, io, { projectId, slug: str(owned.slug) ?? takenSlug, type: parsed.type, existing, adapted }, `OK: slug '${takenSlug}' was already yours — linked existing project ${projectId} — wrote .yolo/deploy.json`);
312
+ return writeLinkFile(cwd, writeConfig, io, {
313
+ projectId,
314
+ slug: str(owned.slug) ?? takenSlug,
315
+ type: parsed.type,
316
+ existing,
317
+ adapted,
318
+ jsonOutput: parsed.jsonOutput,
319
+ jsonStatus: 'linked-existing',
320
+ }, `OK: slug '${takenSlug}' was already yours — linked existing project ${projectId} — wrote .yolo/deploy.json`);
286
321
  }
287
322
  }
288
323
  }
289
- io.err(`${formatFail(created)}\n`);
324
+ if (parsed.jsonOutput)
325
+ io.out(`${formatJsonResult(created)}\n`);
326
+ else
327
+ io.err(`${formatFail(created)}\n`);
290
328
  return exitCodeForFailure(created.kind);
291
329
  }
292
330
  const raw = created.value;
@@ -294,10 +332,14 @@ async function runInitCmd(args, deps, io) {
294
332
  const projectId = resolveProjectId(project);
295
333
  const slug = str(project.slug) ?? parsed.slug;
296
334
  if (!projectId) {
297
- io.err(`${formatFail({ kind: 'invalid-response', message: 'create-project response missing a project id' })}\n`);
335
+ const failure = { kind: 'invalid-response', message: 'create-project response missing a project id' };
336
+ if (parsed.jsonOutput)
337
+ io.out(`${formatJsonResult(failure)}\n`);
338
+ else
339
+ io.err(`${formatFail(failure)}\n`);
298
340
  return 2;
299
341
  }
300
- return writeLinkFile(cwd, writeConfig, io, { projectId, slug, type: parsed.type, existing, adapted }, `OK: linked project ${projectId}${slug ? ` (slug ${slug})` : ''} — wrote .yolo/deploy.json`);
342
+ return writeLinkFile(cwd, writeConfig, io, { projectId, slug, type: parsed.type, existing, adapted, jsonOutput: parsed.jsonOutput, jsonStatus: 'created' }, `OK: linked project ${projectId}${slug ? ` (slug ${slug})` : ''} — wrote .yolo/deploy.json`);
301
343
  }
302
344
  export function parseLinkArgs(args) {
303
345
  let projectId;
@@ -1603,9 +1645,30 @@ function writeLinkFile(cwd, writeConfig, io, params, message) {
1603
1645
  writeConfig(cwd, config);
1604
1646
  }
1605
1647
  catch (err) {
1606
- io.err(`${formatFail({ kind: 'config-write-failed', message: `failed to write .yolo/deploy.json: ${describeError(err)}` })}\n`);
1648
+ const failure = {
1649
+ kind: 'config-write-failed',
1650
+ message: `failed to write .yolo/deploy.json: ${describeError(err)}`,
1651
+ };
1652
+ if (params.jsonOutput)
1653
+ io.out(`${formatJsonResult(failure)}\n`);
1654
+ else
1655
+ io.err(`${formatFail(failure)}\n`);
1607
1656
  return 1;
1608
1657
  }
1658
+ if (params.jsonOutput) {
1659
+ io.out(`${formatJsonResult({
1660
+ status: params.jsonStatus ?? 'created',
1661
+ projectId: params.projectId,
1662
+ ...(params.slug ? { slug: params.slug } : {}),
1663
+ ...(params.type ? { type: params.type } : {}),
1664
+ configPath: '.yolo/deploy.json',
1665
+ ...(params.adapted
1666
+ ? { adapted: { sourceFile: params.adapted.sourceFile, migrated: params.adapted.migrated, warnings: params.adapted.warnings } }
1667
+ : {}),
1668
+ note: '.yolo/deploy.json is committed by design; it contains no secrets — commit it so future sessions, teammates, and CI ship to the same project.',
1669
+ })}\n`);
1670
+ return 0;
1671
+ }
1609
1672
  io.out(`${message}\n`);
1610
1673
  if (params.adapted) {
1611
1674
  io.out(`note: adapted ${params.adapted.sourceFile} → .yolo/deploy.json (${params.adapted.migrated.join(', ')})\n`);
@@ -112,7 +112,7 @@ export function runContextHeaders(env) {
112
112
  headers['X-Yolo-Session-Id'] = env.SESSION_ID;
113
113
  return headers;
114
114
  }
115
- export async function finalizeShip(ctx, projectId, shipId, modules = [], sourceMap) {
115
+ export async function finalizeShip(ctx, projectId, shipId, modules = [], sourceMap, opts = {}) {
116
116
  // NOT auto-retried (unlike ship/start + assets). finalize is single-shot per
117
117
  // ship session: if the first request reached the server and created the
118
118
  // release but the response was lost to a transient 5xx/522, a blind retry
@@ -129,6 +129,12 @@ export async function finalizeShip(ctx, projectId, shipId, modules = [], sourceM
129
129
  const url = `${stripTrailingSlash(ctx.commonApiUrl)}/v1/deploy/projects/${enc(projectId)}/ship/${enc(shipId)}/finalize`;
130
130
  // Substrate run-context provenance headers (best-effort; empty outside a lane).
131
131
  const runHeaders = runContextHeaders(ctx.env);
132
+ // Resume-after-grant: the pending-store rerun redeems the operator's grant
133
+ // explicitly (x-approval-id → approvalNonce server-side), which yields crisp
134
+ // approval-pending/-denied/-expired outcomes instead of the nonce-less
135
+ // retry-redeem's blended ones.
136
+ if (opts.approvalId)
137
+ runHeaders['x-approval-id'] = opts.approvalId;
132
138
  let response;
133
139
  try {
134
140
  if (modules.length > 0) {
@@ -0,0 +1,113 @@
1
+ /**
2
+ * deploy-pending.ts — machine-local staged-ship state for the T3 approval
3
+ * round-trip (codex gpt-5.6-sol P1, round 3).
4
+ *
5
+ * Problem: a prod finalize that parks on `awaiting-approval` leaves the ship
6
+ * session OPEN server-side (assets staged, approval bound to the exact
7
+ * bundleDigest) — but a plain `yolo deploy` rerun REBUILDS first. Any
8
+ * nondeterminism in the build (timestamps, hash salts, ordering) changes the
9
+ * digest, the grant never matches, and the retry loops on fresh approvals
10
+ * forever. The approved BYTES must be what ships.
11
+ *
12
+ * Fix: on PENDING, persist a resume record — shipId, digest, approvalId, and
13
+ * the exact worker module bytes (base64; pure-static ships have none — their
14
+ * assets are already staged server-side). The next `yolo deploy` for the same
15
+ * project+env resumes by re-FINALIZING that session (no build, no bundle, no
16
+ * re-upload) and only falls back to a fresh build when the server says the
17
+ * session/approval is gone.
18
+ *
19
+ * Location: `~/.config/yolo/deploy-pending/<projectId>.json` (0600) — the
20
+ * same machine-local config root as the auth token, NOT the repo. In-repo
21
+ * state would surface in `git status` of arbitrary user repos and could ride
22
+ * a lane's `git add -A` WIP-rescue; here it also survives lane teardown, so a
23
+ * later lane can resume a ship the operator approved after the original step
24
+ * ended.
25
+ */
26
+ import * as fs from 'node:fs';
27
+ import * as os from 'node:os';
28
+ import * as path from 'node:path';
29
+ /** Resume records older than this are stale — the ship session is long gone. */
30
+ export const PENDING_MAX_AGE_MS = 24 * 60 * 60 * 1000;
31
+ function pendingRoot(env) {
32
+ // `||` (not `??`) + os.homedir() fallback (matching auth-context.ts): an
33
+ // unset OR EMPTY HOME must not resolve the store into the CURRENT REPO,
34
+ // where the persisted bundle would surface in `git status` and could ride
35
+ // a `git add -A` (codex P2 r4+r5).
36
+ const home = env.HOME || process.env.HOME || os.homedir();
37
+ return path.join(home, '.config', 'yolo', 'deploy-pending');
38
+ }
39
+ // server-issued ids; sanitize anyway so a hostile value can't escape the dir.
40
+ const safe = (id) => id.replace(/[^A-Za-z0-9_-]/g, '_');
41
+ function projectDir(env, projectId) {
42
+ return path.join(pendingRoot(env), safe(projectId));
43
+ }
44
+ function shipPath(env, projectId, shipId) {
45
+ return path.join(projectDir(env, projectId), `${safe(shipId)}.json`);
46
+ }
47
+ function parseRecord(raw) {
48
+ try {
49
+ const parsed = JSON.parse(raw);
50
+ if (parsed?.$version !== 1 ||
51
+ typeof parsed.shipId !== 'string' ||
52
+ typeof parsed.bundleDigest !== 'string' ||
53
+ typeof parsed.approvalId !== 'string') {
54
+ return null;
55
+ }
56
+ return parsed;
57
+ }
58
+ catch {
59
+ return null;
60
+ }
61
+ }
62
+ export function defaultPendingStore(env) {
63
+ return {
64
+ loadAll(projectId) {
65
+ let names;
66
+ try {
67
+ names = fs.readdirSync(projectDir(env, projectId));
68
+ }
69
+ catch {
70
+ return []; // no dir → nothing staged
71
+ }
72
+ const records = [];
73
+ for (const name of names) {
74
+ if (!name.endsWith('.json'))
75
+ continue;
76
+ try {
77
+ const rec = parseRecord(fs.readFileSync(path.join(projectDir(env, projectId), name), 'utf8'));
78
+ if (rec)
79
+ records.push(rec);
80
+ }
81
+ catch {
82
+ // unreadable — skip
83
+ }
84
+ }
85
+ return records.sort((a, b) => Date.parse(b.createdAt) - Date.parse(a.createdAt));
86
+ },
87
+ save(record) {
88
+ const dir = projectDir(env, record.projectId);
89
+ fs.mkdirSync(dir, { recursive: true });
90
+ fs.writeFileSync(shipPath(env, record.projectId, record.shipId), `${JSON.stringify(record, null, 2)}\n`, {
91
+ mode: 0o600,
92
+ });
93
+ },
94
+ clear(projectId, shipId) {
95
+ if (shipId !== undefined) {
96
+ try {
97
+ fs.unlinkSync(shipPath(env, projectId, shipId));
98
+ }
99
+ catch {
100
+ // absent — fine
101
+ }
102
+ return;
103
+ }
104
+ // Whole-project clear: remove the dir and everything under it.
105
+ try {
106
+ fs.rmSync(projectDir(env, projectId), { recursive: true, force: true });
107
+ }
108
+ catch {
109
+ // absent — fine
110
+ }
111
+ },
112
+ };
113
+ }
@@ -25,6 +25,7 @@ import { readDeployConfig } from './deploy-config.js';
25
25
  import { detectProjectShape } from './deploy-detect.js';
26
26
  import { bundleProject } from './deploy-bundle.js';
27
27
  import { resolveDeployContext, startShip, uploadAssetBucket, finalizeShip, } from './deploy-client.js';
28
+ import { defaultPendingStore, PENDING_MAX_AGE_MS, } from './deploy-pending.js';
28
29
  const NOT_LINKED_HINT = "run 'yolo deploy init' to create or link a hosting project";
29
30
  // ─── Orchestration ────────────────────────────────────────────────────────
30
31
  export async function runDeployShip(options) {
@@ -56,6 +57,87 @@ export async function runDeployShip(options) {
56
57
  }
57
58
  const projectId = config.projectId;
58
59
  progress(`deploy: link ok (project ${projectId}${config.slug ? `, slug ${config.slug}` : ''}${config.type ? `, type ${config.type}` : ''})`);
60
+ const pendingStore = deps.pendingStoreImpl ?? defaultPendingStore(options.env ?? process.env);
61
+ const resolveCtx = () => {
62
+ const auth = resolveDeployContext(options.env ?? process.env, options.readFileImpl, options.fetchImpl);
63
+ if (!auth.ok)
64
+ return fail('auth', auth.message);
65
+ // Bounded auto-retry for transient edge/origin 5xx (incl. CF 522) on the
66
+ // ship legs — a single transient blip shouldn't hard-fail a prod deploy.
67
+ return {
68
+ ok: true,
69
+ ctx: {
70
+ ...auth.context,
71
+ retry: {
72
+ onRetry: ({ leg, attempt, maxAttempts, delayMs, failure }) => progress(`deploy: ${leg} transient error (${failure.message}); retrying ${attempt}/${maxAttempts - 1} in ${Math.round(delayMs)}ms`),
73
+ },
74
+ },
75
+ };
76
+ };
77
+ // 1.5 Resume a staged, approval-parked ship BEFORE building. A rebuild is
78
+ // not digest-stable for every project (timestamps/salts), and the operator
79
+ // approved the EXACT staged bytes — so a rerun after PENDING re-finalizes
80
+ // the original ship session (no build, no bundle, no re-upload; codex
81
+ // gpt-5.6-sol P1 round 3). Falls through to a fresh build only when the
82
+ // server says the session/approval is gone.
83
+ if (!dryRun) {
84
+ // Try EVERY staged record for this project+env, newest first — two
85
+ // concurrent same-project deploys each stage their own record, and either
86
+ // may be the one the operator granted (codex P2 r7). A record that
87
+ // finalizes (granted) wins; a still-pending one is remembered; the rest
88
+ // fall through. Only when NONE finalizes and NONE is still pending do we
89
+ // build fresh.
90
+ const staged = pendingStore.loadAll(projectId).filter((r) => r.env === envFlag);
91
+ let anyStillPending = null;
92
+ for (const rec of staged) {
93
+ if (Date.now() - Date.parse(rec.createdAt) > PENDING_MAX_AGE_MS) {
94
+ pendingStore.clear(projectId, rec.shipId);
95
+ progress(`deploy: staged ship ${rec.shipId} discarded (older than 24h)`);
96
+ continue;
97
+ }
98
+ const resolved = resolveCtx();
99
+ if (!resolved.ok)
100
+ return resolved;
101
+ const resumed = await resumeStagedShip(resolved.ctx, rec, {
102
+ projectId,
103
+ slug: config.slug,
104
+ envFlag,
105
+ channel,
106
+ finalizeLeg,
107
+ pendingStore,
108
+ progress,
109
+ });
110
+ if (!resumed)
111
+ continue; // this record not resumable (cleared) — try the next
112
+ if (resumed.ok) {
113
+ // A staged ship went LIVE. Every OTHER staged record for this
114
+ // project+env is now stale — auto-resuming one on a future
115
+ // `yolo deploy` would unexpectedly repoint prod to a prior concurrent
116
+ // attempt's bundle (codex P1 r11). Purge the whole set so the next
117
+ // deploy builds CURRENT code. Re-load at purge time (NOT the
118
+ // pre-finalize `staged` snapshot) so a record a CONCURRENT deploy saved
119
+ // DURING this resume's finalize is cleared too (codex P1 r19).
120
+ // (resumeStagedShip already cleared `rec`.)
121
+ for (const other of pendingStore.loadAll(projectId)) {
122
+ if (other.env === envFlag && other.shipId !== rec.shipId) {
123
+ pendingStore.clear(projectId, other.shipId);
124
+ }
125
+ }
126
+ return resumed;
127
+ }
128
+ // A denial or the ambiguous upload-expired are terminal answers about a
129
+ // real staged ship — return immediately (leave siblings for their own
130
+ // resolution; nothing went live).
131
+ if (resumed.kind !== 'awaiting-approval')
132
+ return resumed;
133
+ // Still awaiting the grant — remember it, but keep checking the others
134
+ // (a LATER record may already be granted).
135
+ anyStillPending = resumed;
136
+ }
137
+ if (anyStillPending)
138
+ return anyStillPending;
139
+ // No staged record finalized or is pending → build fresh below.
140
+ }
59
141
  // 2. Detect.
60
142
  const detected = detect({ cwd, config });
61
143
  if (!detected.ok)
@@ -103,17 +185,10 @@ export async function runDeployShip(options) {
103
185
  // resolution happen below this line).
104
186
  if (dryRun)
105
187
  return { ok: true, dryRun: true, ...base };
106
- const auth = resolveDeployContext(options.env ?? process.env, options.readFileImpl, options.fetchImpl);
107
- if (!auth.ok)
108
- return fail('auth', auth.message);
109
- // Bounded auto-retry for transient edge/origin 5xx (incl. CF 522) on the
110
- // ship legs — a single transient blip shouldn't hard-fail a prod deploy.
111
- const ctx = {
112
- ...auth.context,
113
- retry: {
114
- onRetry: ({ leg, attempt, maxAttempts, delayMs, failure }) => progress(`deploy: ${leg} transient error (${failure.message}); retrying ${attempt}/${maxAttempts - 1} in ${Math.round(delayMs)}ms`),
115
- },
116
- };
188
+ const resolved = resolveCtx();
189
+ if (!resolved.ok)
190
+ return resolved;
191
+ const ctx = resolved.ctx;
117
192
  // 6. ship/start — manifest up, missing-hash buckets back.
118
193
  const manifest = bundled.manifest;
119
194
  const request = {
@@ -170,6 +245,38 @@ export async function runDeployShip(options) {
170
245
  if (!finalized.ok) {
171
246
  if (finalized.kind === 'awaiting-approval' && 'approvalId' in finalized) {
172
247
  progress('deploy: finalize → pending operator approval (T3 prod ship)');
248
+ // Persist the staged ship so the post-grant rerun re-finalizes THESE
249
+ // exact bytes instead of rebuilding (a rebuild may change the digest and
250
+ // orphan the grant). Best-effort: a failed save just means the rerun
251
+ // rebuilds — same as before this existed.
252
+ try {
253
+ pendingStore.save({
254
+ $version: 1,
255
+ projectId,
256
+ shipId,
257
+ env: envFlag,
258
+ ...(config.slug !== undefined ? { slug: config.slug } : {}),
259
+ type: shape.type,
260
+ bundleDigest: bundled.bundleDigest,
261
+ approvalId: finalized.approvalId,
262
+ fileCount,
263
+ totalAssetBytes: bundled.totalAssetBytes,
264
+ createdAt: new Date().toISOString(),
265
+ ...(workerModules.length > 0
266
+ ? {
267
+ workerModules: workerModules.map((m) => ({
268
+ name: m.name,
269
+ contentsBase64: Buffer.from(m.contents).toString('base64'),
270
+ })),
271
+ }
272
+ : {}),
273
+ ...(bundled.sourceMap ? { sourceMap: bundled.sourceMap } : {}),
274
+ });
275
+ progress('deploy: staged bundle saved — a rerun after the grant resumes this exact bundle (no rebuild)');
276
+ }
277
+ catch (err) {
278
+ progress(`deploy: warn — could not save the staged-ship resume record (${describeErrorMessage(err)}); a rerun will rebuild`);
279
+ }
173
280
  return {
174
281
  ok: false,
175
282
  kind: 'awaiting-approval',
@@ -199,6 +306,116 @@ export async function runDeployShip(options) {
199
306
  ...(bootCheck ? { bootCheck } : {}),
200
307
  };
201
308
  }
309
+ /**
310
+ * Re-finalize a staged, approval-parked ship session with the operator's
311
+ * grant. Returns a terminal DeployShipResult, or null ⇒ the staged session is
312
+ * unusable (expired/consumed/denied-and-cleared cases that warrant a fresh
313
+ * build) and the caller falls through to the normal pipeline.
314
+ */
315
+ async function resumeStagedShip(ctx, resume, io) {
316
+ const { projectId, envFlag, channel, finalizeLeg, pendingStore, progress } = io;
317
+ progress(`deploy: resuming staged ship ${resume.shipId} (digest ${shortDigest(resume.bundleDigest)}, approval ${resume.approvalId})`);
318
+ const modules = (resume.workerModules ?? []).map((m) => ({
319
+ name: m.name,
320
+ contents: new Uint8Array(Buffer.from(m.contentsBase64, 'base64')),
321
+ }));
322
+ const finalized = await finalizeLeg(ctx, projectId, resume.shipId, modules, resume.sourceMap ?? null, {
323
+ approvalId: resume.approvalId,
324
+ });
325
+ if (finalized.ok) {
326
+ pendingStore.clear(projectId, resume.shipId);
327
+ progress('deploy: finalize ok (resumed the approved bundle — no rebuild)');
328
+ const bootCheck = parseBootCheck(finalized.value.bootCheck);
329
+ if (bootCheck)
330
+ progress(`deploy: warn — deployed Worker failed to boot (HTTP ${bootCheck.status})`);
331
+ return {
332
+ ok: true,
333
+ dryRun: false,
334
+ projectId,
335
+ slug: resume.slug ?? io.slug,
336
+ env: envFlag,
337
+ channel,
338
+ type: resume.type,
339
+ fileCount: resume.fileCount,
340
+ totalAssetBytes: resume.totalAssetBytes,
341
+ bundleDigest: resume.bundleDigest,
342
+ shipId: resume.shipId,
343
+ releaseId: finalized.value.releaseId,
344
+ url: finalized.value.url,
345
+ ...(bootCheck ? { bootCheck } : {}),
346
+ };
347
+ }
348
+ // Still parked: the grant hasn't landed yet (approval-pending), or the
349
+ // server re-issued the pending envelope. Keep the staged record — the next
350
+ // rerun retries the SAME session.
351
+ if (finalized.kind === 'approval-pending') {
352
+ progress('deploy: staged ship still awaiting the operator grant');
353
+ return {
354
+ ok: false,
355
+ kind: 'awaiting-approval',
356
+ projectId,
357
+ slug: resume.slug ?? io.slug,
358
+ approvalId: resume.approvalId,
359
+ message: finalized.message,
360
+ };
361
+ }
362
+ if (finalized.kind === 'awaiting-approval' && 'approvalId' in finalized) {
363
+ progress('deploy: staged ship still awaiting the operator grant');
364
+ return {
365
+ ok: false,
366
+ kind: 'awaiting-approval',
367
+ projectId,
368
+ slug: resume.slug ?? io.slug,
369
+ approvalId: finalized.approvalId,
370
+ approvalUrl: finalized.approvalUrl,
371
+ releaseId: finalized.releaseId,
372
+ statement: finalized.statement,
373
+ expiresAt: finalized.expiresAt,
374
+ message: finalized.message,
375
+ };
376
+ }
377
+ // Denied is a terminal answer about THIS bundle — surface it; don't
378
+ // silently rebuild what the operator just rejected.
379
+ if (finalized.kind === 'approval-denied') {
380
+ pendingStore.clear(projectId, resume.shipId);
381
+ return clientFail(finalized);
382
+ }
383
+ // Transient transport / auth: keep the staged record and surface the error
384
+ // — the session may still be perfectly resumable.
385
+ if (finalized.kind === 'network' || finalized.kind === 'auth' || finalized.kind === 'session-required') {
386
+ return clientFail(finalized);
387
+ }
388
+ // AMBIGUOUS-on-resume outcomes — the staged session/grant may have been
389
+ // completed by a CONCURRENT retry that's still finalizing or already went
390
+ // live, so auto-rebuilding could duplicate a live release / re-mint the
391
+ // approval. Surface and require a status check; never rebuild automatically.
392
+ // - upload-expired (codex P2 r4): the open→finalized CAS answers every
393
+ // retry of an already-finalized session with 410 — a prior resume may
394
+ // have gone live with a lost response.
395
+ // - approval-consumed (codex P2 r14): two post-grant retries raced; the
396
+ // WINNER consumed the nonce and may still be finalizing, the LOSER lands
397
+ // here. The deployment is (being) applied — a fresh ship would orphan a
398
+ // session and re-apply the same bundle.
399
+ if (finalized.kind === 'upload-expired' || finalized.kind === 'approval-consumed') {
400
+ pendingStore.clear(projectId, resume.shipId);
401
+ return {
402
+ ok: false,
403
+ kind: finalized.kind,
404
+ message: `staged ship ${resume.shipId} is finished or already being applied by a concurrent retry — a prior resume may have gone live`,
405
+ hint: "run 'yolo deploy status' first: if the release is live you are done; otherwise rerun 'yolo deploy --env prod' for a fresh ship",
406
+ status: finalized.kind === 'upload-expired' ? 410 : 409,
407
+ };
408
+ }
409
+ // Everything else (approval-expired/-required, bundle-invalid, …): the staged
410
+ // grant is gone but nothing finalized — fall back to a fresh build+ship,
411
+ // which re-enters the normal approval flow if needed.
412
+ pendingStore.clear(projectId, resume.shipId);
413
+ progress(`deploy: staged ship not resumable (${finalized.kind}: ${finalized.message}) — building fresh`);
414
+ return null;
415
+ }
416
+ function describeErrorMessage(err) {
417
+ return err instanceof Error ? err.message : String(err);
418
+ }
202
419
  /** Narrow the backend's optional `bootCheck` envelope; ignore anything malformed. */
203
420
  function parseBootCheck(raw) {
204
421
  if (!raw || typeof raw !== 'object')
@@ -259,8 +476,16 @@ export function formatShipSuccess(result) {
259
476
  return `OK: shipped ${name} release ${result.releaseId ?? '(unknown)'} → ${result.url ?? '(no url reported)'} (${result.env})`;
260
477
  }
261
478
  /**
262
- * Two independent "do not retry" signals: the PENDING prefix (not FAIL) and
263
- * exit 3 — so neither prefix-matching nor exit-code-matching agents loop.
479
+ * Two independent "not-an-error, don't blind-loop" signals: the PENDING
480
+ * prefix (not FAIL) and exit 3. The correct resume is a re-run AFTER the
481
+ * grant — the server redeems the granted approval automatically for the same
482
+ * bundle (exact-digest match), and staged assets hash-skip so the re-run is
483
+ * cheap. A premature re-run is idempotent server-side (re-issues this
484
+ * PENDING with the SAME approval id — no duplicate approvals). The CLI has
485
+ * no approval-status poll (`yolo deploy status` can't see pre-finalize
486
+ * approvals — no release row exists yet); the operator's grant surface is
487
+ * the notification + Approvals panel, and MCP agents have
488
+ * deploy.approval_status.
264
489
  */
265
490
  export function formatPending(result) {
266
491
  const name = result.slug ?? result.projectId;
@@ -271,7 +496,11 @@ export function formatPending(result) {
271
496
  return [
272
497
  `PENDING [awaiting-approval]: prod ship of ${name}${releaseTag} needs operator confirmation.`,
273
498
  approveLine,
274
- ' then: poll `yolo deploy status` — do NOT rerun `yolo deploy`; the bundle is already staged.',
499
+ ' then: after the operator approves (they got a notification; the Approvals panel is the surface),',
500
+ ' rerun `yolo deploy --env prod` — it RESUMES this exact staged bundle (no rebuild, no re-upload;',
501
+ ' the grant is redeemed automatically). Rerun with --env prod: a bare `yolo deploy` targets STAGING',
502
+ ' and will NOT resume this prod bundle. A rerun BEFORE the grant is harmless (same PENDING, same',
503
+ ' approval id). MCP callers can poll deploy.approval_status; the CLI has no approval poll.',
275
504
  ].join('\n');
276
505
  }
277
506
  export function formatFail(result) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yolo-labs/yolo-cli",
3
- "version": "0.32.0",
3
+ "version": "0.33.0",
4
4
  "description": "YOLO Studio substrate CLI — owns yolo plan/workspace/artifact substrate-tooling commands. Distinct from yolo-code (the agent CLI) and yolo-router (the LLM gateway client).",
5
5
  "license": "MIT",
6
6
  "type": "module",