@yolo-labs/yolo-cli 0.45.1 → 0.47.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.
package/README.md CHANGED
@@ -43,13 +43,17 @@ yolo preview status
43
43
  yolo preview status <tile-id> --json
44
44
  yolo preview logs <tile-id> --tail 100
45
45
  yolo preview stop <tile-id>
46
+ yolo preview update <tile-id> --env API_MOCKS=1 --health-path /health
46
47
  ```
47
48
 
48
49
  Choose commands appropriate to your app; the example assumes its start script
49
50
  accepts `--hostname` and `--port`. Single-quote commands to preserve `$PORT` and
50
51
  `$HOST` for the service. It uses isolated checkouts, checks candidate health, and
51
52
  switches the tile's stable port only after a successful build and start. Failed
52
- updates keep the last working version. The required runtime must already be
53
+ updates keep the last working version, and `status` reports why a commit was
54
+ refused (health probe outcomes and the last output line). `update` changes the
55
+ command, env or health settings in place, keeping the tile and port, and rebuilds
56
+ the branch head once. The required runtime must already be
53
57
  installed; this service targets stateless HTTP apps, not database migrations.
54
58
 
55
59
  The session resolves the authoritative workspace. Preview operations use delegated
package/dist/cli.js CHANGED
@@ -64,6 +64,15 @@ function printHelp() {
64
64
  ' [--workspace <wsId>] Sanity-check the workspace bound to this session.',
65
65
  ' kanban models List the model ids a card can be pinned to, and whether each can run now.',
66
66
  ' [--json] [--workspace <wsId>] Raw JSON instead of the table; sanity-check the workspace.',
67
+ ' routing status Background Runner routing: on/off, Jev\'s state and why, policies.',
68
+ ' routing on | off Turn routing on or off for cards admitted from now on.',
69
+ ' routing decisions [--card <id>] Recorded routing decisions for a card, or the latest.',
70
+ ' [--limit <n>] How many (1-200).',
71
+ ' routing preview <cardId> Where routing would send a card now (read-only).',
72
+ ' routing policy get|set|delete [opts] Runner/board policies; `yolo routing --help` for options.',
73
+ ' [--json] [--workspace <wsId>] The API response as-is; sanity-check the workspace.',
74
+ ' workspace set-repository <url> [opts] Point this workspace at a different repository: preview, then --confirm <snapshot>.',
75
+ ' [--default-branch B] [--auth https|ssh] [--keep-old-remote-as N | --drop-old-remote] [--json]',
67
76
  ' git doctor [opts] Diagnose why git (not gh) can\'t authenticate to github.com.',
68
77
  ' [--fix] Repair what is safe to (store file, helpers, remote URL), then re-check.',
69
78
  ' [--offline] [--remote <name>] [--json] Skip network checks; remote to probe (default: origin); JSON output.',
@@ -750,6 +759,14 @@ async function main(argv) {
750
759
  const { runKanbanCmd } = await import('./kanban-cli.js');
751
760
  return runKanbanCmd(args.slice(1));
752
761
  }
762
+ if (cmd === 'routing') {
763
+ const { runRoutingCmd } = await import('./routing-cli.js');
764
+ return runRoutingCmd(args.slice(1));
765
+ }
766
+ if (cmd === 'workspace') {
767
+ const { runWorkspaceCmd } = await import('./workspace-cli.js');
768
+ return runWorkspaceCmd(args.slice(1));
769
+ }
753
770
  if (cmd === 'mcp') {
754
771
  const sub = args[1];
755
772
  if (sub === 'scopes')
@@ -35,7 +35,7 @@ function defaultStatPath(p) {
35
35
  }
36
36
  }
37
37
  import { runDeployShip, exitCodeForFailure, formatShipSuccess, formatPending, formatFail, } from './deploy-ship.js';
38
- import { resolveDeployContext, createProject, getProjectStatus, listProjects, rollbackProject, unpublishProject, republishProject, renameProject, setProjectParent, addAlias, removeAlias, setRedirect, deleteProject, cloneProject, getLogs, pollTail, queryD1, } from './deploy-client.js';
38
+ import { resolveDeployContext, createProject, getProjectStatus, listProjects, rollbackProject, unpublishProject, republishProject, renameProject, setProjectParent, setProjectWorkspace, addAlias, removeAlias, setRedirect, deleteProject, cloneProject, getLogs, pollTail, queryD1, } from './deploy-client.js';
39
39
  import { readDeployConfig, writeDeployConfig, findAncestorDeployLink as findAncestorLink, } from './deploy-config.js';
40
40
  import { adaptWrangler, detectProjectShape } from './deploy-detect.js';
41
41
  import { collectNodeBuiltinsFromText } from './deploy-bundle.js';
@@ -44,7 +44,7 @@ import { defaultReadFile } from './auth-context.js';
44
44
  const USAGE = [
45
45
  'Usage: yolo deploy [--env <staging|prod>] [--dry-run] [--json]',
46
46
  ' yolo deploy init [--slug <slug>] [--type <static|worker>] [--parent <id|slug> | --no-parent] [--json]',
47
- ' yolo deploy link (--project-id <id> | --slug <slug>) [--type <static|worker>]',
47
+ ' yolo deploy link (--project-id <id> | --slug <slug>) [--type <static|worker>] [--workspace-id <id> | --unlink-workspace | --local-only]',
48
48
  ' yolo deploy validate [--json]',
49
49
  ' yolo deploy doctor [--json]',
50
50
  ' yolo deploy dev [--port <n>] [--host <h>] [--var KEY=VALUE ...]',
@@ -331,6 +331,8 @@ async function runInitCmd(args, deps, io) {
331
331
  io.out(parsed.jsonOutput
332
332
  ? `${formatJsonResult({ status: 'already-linked', projectId: existing.projectId, ...(existing.slug ? { slug: existing.slug } : {}) })}\n`
333
333
  : `OK: already linked to project ${existing.projectId}${existing.slug ? ` (slug ${existing.slug})` : ''} — .yolo/deploy.json left unchanged\n`);
334
+ if (!parsed.jsonOutput)
335
+ io.out(`Local repository configuration only. To save the server workspace association, run 'yolo deploy link --project-id ${existing.projectId} --workspace-id <workspace-id>'.\n`);
334
336
  return 0;
335
337
  }
336
338
  // Fresh init in a project that has a wrangler config but no .yolo/deploy.json:
@@ -535,12 +537,31 @@ async function runInitCmd(args, deps, io) {
535
537
  }, `OK: linked project ${projectId}${slug ? ` (slug ${slug})` : ''} — wrote .yolo/deploy.json`);
536
538
  }
537
539
  export function parseLinkArgs(args) {
540
+ let workspaceId;
541
+ let localOnly = false;
542
+ let unlinkWorkspace = false;
538
543
  let projectId;
539
544
  let slug;
540
545
  let type;
541
546
  for (let i = 0; i < args.length; i++) {
542
547
  const a = args[i];
543
- if (a === '--project-id') {
548
+ if (a === '--workspace-id') {
549
+ workspaceId = args[++i];
550
+ if (!workspaceId || !/^[a-f0-9]{24}$/i.test(workspaceId))
551
+ return { ok: false, message: '--workspace-id requires a 24-hex workspace id' };
552
+ }
553
+ else if (a.startsWith('--workspace-id=')) {
554
+ workspaceId = a.slice('--workspace-id='.length);
555
+ if (!/^[a-f0-9]{24}$/i.test(workspaceId))
556
+ return { ok: false, message: '--workspace-id requires a 24-hex workspace id' };
557
+ }
558
+ else if (a === '--unlink-workspace') {
559
+ unlinkWorkspace = true;
560
+ }
561
+ else if (a === '--local-only') {
562
+ localOnly = true;
563
+ }
564
+ else if (a === '--project-id') {
544
565
  const v = args[++i];
545
566
  if (!v || v.startsWith('--'))
546
567
  return { ok: false, message: '--project-id requires a value' };
@@ -587,7 +608,11 @@ export function parseLinkArgs(args) {
587
608
  // link metadata that disagrees with the project the id resolves to.
588
609
  return { ok: false, message: 'pass either --project-id or --slug, not both (the project\'s slug is resolved server-side)' };
589
610
  }
590
- return { ok: true, projectId, slug, type };
611
+ if ((workspaceId && unlinkWorkspace) || (localOnly && unlinkWorkspace))
612
+ return { ok: false, message: 'choose only one workspace association option' };
613
+ if (workspaceId && localOnly)
614
+ return { ok: false, message: '--workspace-id and --local-only cannot be combined' };
615
+ return { ok: true, projectId, slug, type, ...(workspaceId ? { workspaceId } : {}), ...(localOnly ? { localOnly } : {}), ...(unlinkWorkspace ? { unlinkWorkspace } : {}) };
591
616
  }
592
617
  async function runLinkCmd(args, deps, io) {
593
618
  const parsed = parseLinkArgs(args);
@@ -654,6 +679,41 @@ async function runLinkCmd(args, deps, io) {
654
679
  })}\n`);
655
680
  return exitCodeForFailure('already-linked');
656
681
  }
682
+ const workspaceId = parsed.unlinkWorkspace ? null : parsed.localOnly ? undefined : parsed.workspaceId ?? (deps.env ?? process.env).WORKSPACE_ID;
683
+ if (workspaceId !== undefined) {
684
+ // Always read project.workspaceId, never the release-derived workspace.
685
+ const read = deps.getProjectStatusImpl ?? getProjectStatus;
686
+ const before = await read(auth.context, projectId);
687
+ if (!before.ok) {
688
+ io.err(`${formatFail(before)}\n`);
689
+ return exitCodeForFailure(before.kind);
690
+ }
691
+ const snapshot = before.value;
692
+ if (!snapshot?.project || (snapshot.project.workspaceId !== null && typeof snapshot.project.workspaceId !== 'string')) {
693
+ io.err('FAIL [invalid-response]: server did not return a persisted workspace association\n');
694
+ return 2;
695
+ }
696
+ const linked = await (deps.setProjectWorkspaceImpl ?? setProjectWorkspace)(auth.context, projectId, {
697
+ workspaceId, expectedWorkspaceId: snapshot.project.workspaceId ?? null,
698
+ });
699
+ if (!linked.ok) {
700
+ io.err(`${formatFail(linked)}\n`);
701
+ return exitCodeForFailure(linked.kind);
702
+ }
703
+ const after = await read(auth.context, projectId);
704
+ if (!after.ok) {
705
+ io.err(`${formatFail(after)}\n`);
706
+ return exitCodeForFailure(after.kind);
707
+ }
708
+ if (after.value?.project?.workspaceId !== (workspaceId?.toLowerCase() ?? null)) {
709
+ io.err('FAIL [workspace-link-conflict]: server association could not be verified; refresh and retry\n');
710
+ return 2;
711
+ }
712
+ io.out(`OK: verified server workspace association ${workspaceId ?? 'none'}. Old standing grants are revoked on change; review new grants separately.\n`);
713
+ }
714
+ else {
715
+ io.out('Local repository configuration only; server workspace association unchanged. Use --workspace-id <id> to associate this project.\n');
716
+ }
657
717
  if (existing?.projectId === projectId) {
658
718
  // Already linked to this project. Still honor a requested --type that isn't
659
719
  // already set (the deploy_create_project link block has no `type`, so the
@@ -511,3 +511,7 @@ function enc(value) {
511
511
  function stripTrailingSlash(url) {
512
512
  return url.endsWith('/') ? url.slice(0, -1) : url;
513
513
  }
514
+ /** Explicit persisted association, separate from .yolo/deploy.json. */
515
+ export async function setProjectWorkspace(ctx, projectId, request) {
516
+ return jsonLeg(ctx, `/deploy/projects/${enc(projectId)}/workspace`, { method: 'PUT', jsonBody: request });
517
+ }
@@ -6,7 +6,10 @@
6
6
  * wrapper) re-reads ~/.yolo-env on every call, so it always holds the current
7
7
  * token. git asks its credential helpers: `store` (~/.git-credentials), then
8
8
  * the github.com-scoped `gh auth git-credential` fallback from setup-git.sh.
9
- * When the two disagree, `gh` works and `git push` fails with "could not read
9
+ * That fallback must name the wrapper by absolute path: the real /usr/bin/gh
10
+ * answers from its own GH_TOKEN, which is stale in a long-lived shell, and
11
+ * `gh auth setup-git` writes exactly that path, plus a '' reset that hides
12
+ * `store` for github.com. When the two disagree, `gh` works and `git push` fails with "could not read
10
13
  * Username" — which is what a root exec leaving ~/.git-credentials root-owned
11
14
  * 0600 looked like (the lane-gc probe, until #1181). This command looks at
12
15
  * every link in git's chain and says which one is broken.
@@ -20,7 +23,8 @@
20
23
  * - rewrites ~/.git-credentials from the current token by temp file + rename
21
24
  * (a rename replaces a file we cannot write through; we own the directory),
22
25
  * keeping readable non-github lines, or the forge line from the pod env
23
- * - sets `credential.helper store` / the github.com gh fallback if missing
26
+ * - sets `credential.helper store` if missing, and points the github.com gh
27
+ * fallback at the wrapper (dropping a '' reset and real-binary values)
24
28
  * - strips credentials embedded in a github.com remote URL
25
29
  * It only writes a token GitHub accepted in this run, and never while the
26
30
  * Auth V2 purge fence is up: that fence means GitHub access was withdrawn, and
@@ -43,8 +47,10 @@ Diagnose why git (not gh) can't authenticate to github.com over HTTPS.
43
47
  --remote <name> Remote to inspect and probe (default: origin).
44
48
  --json Print {checks, fixed} as JSON.
45
49
  `;
50
+ export const GH_WRAPPER = '/usr/local/bin/gh';
46
51
  const GH_FALLBACK_KEY = 'credential.https://github.com.helper';
47
- const GH_FALLBACK_VALUE = '!gh auth git-credential';
52
+ const BARE_GH_VALUE = '!gh auth git-credential';
53
+ const GH_HELPER = /^!(\S+) auth git-credential$/;
48
54
  const GITHUB_LINE = /^https:\/\/[^:@/\s]+:([^@\s]+)@github\.com\/?$/;
49
55
  /** prefix…last4, so two tokens can be told apart without either being shown. */
50
56
  export function maskToken(token) {
@@ -96,16 +102,26 @@ function defaultGit(cwd, env) {
96
102
  return { status: r.status, stdout: r.stdout ?? '', stderr: r.stderr ?? (r.error ? String(r.error.message) : '') };
97
103
  };
98
104
  }
99
- function defaultHasCommand(env) {
100
- return (name) => (env.PATH ?? '').split(':').some((dir) => {
101
- try {
102
- fs.accessSync(path.join(dir, name), fs.constants.X_OK);
103
- return true;
104
- }
105
- catch {
106
- return false;
107
- }
108
- });
105
+ function isExecutable(file) {
106
+ try {
107
+ fs.accessSync(file, fs.constants.X_OK);
108
+ return fs.statSync(file).isFile();
109
+ }
110
+ catch {
111
+ return false;
112
+ }
113
+ }
114
+ function defaultWhich(env) {
115
+ return (name) => (env.PATH ?? '').split(':').filter(Boolean)
116
+ .map((dir) => path.join(dir, name)).find(isExecutable);
117
+ }
118
+ function sameFile(a, b) {
119
+ try {
120
+ return fs.realpathSync(a) === fs.realpathSync(b);
121
+ }
122
+ catch {
123
+ return a === b;
124
+ }
109
125
  }
110
126
  function getAll(git, args) {
111
127
  const r = git(['config', ...args]);
@@ -218,16 +234,56 @@ function checkHelpers(ctx, d) {
218
234
  if (status === 'ok')
219
235
  status = 'warn';
220
236
  }
221
- if (!fallback.includes(GH_FALLBACK_VALUE)) {
222
- if (ctx.hasCommand('gh')) {
223
- problems.push(`no github.com gh fallback (${GH_FALLBACK_KEY})`);
224
- d.needFallback = true;
237
+ // The wrapper by absolute path; a bare `gh` only where no wrapper is installed.
238
+ const wrapperInstalled = isExecutable(ctx.ghWrapper);
239
+ const want = wrapperInstalled ? `!${ctx.ghWrapper} auth git-credential` : ctx.which('gh') ? BARE_GH_VALUE : undefined;
240
+ const ghValues = fallback.filter((v) => v === '' || GH_HELPER.test(v));
241
+ const fallbackProblems = [];
242
+ let fallbackStatus = 'ok';
243
+ if (!want) {
244
+ if (!ghValues.some((v) => v !== ''))
245
+ fallbackProblems.push('no github.com gh fallback, and gh is not on PATH');
246
+ }
247
+ else if (ghValues.length === 0) {
248
+ fallbackProblems.push(`no github.com gh fallback (${GH_FALLBACK_KEY})`);
249
+ }
250
+ for (const v of new Set(ghValues)) {
251
+ if (v === '') {
252
+ fallbackProblems.push(`${GH_FALLBACK_KEY} has a '' reset (left by \`gh auth setup-git\`): git skips the store helper for github.com`);
253
+ fallbackStatus = 'fail';
254
+ continue;
255
+ }
256
+ if (!want || v === want)
257
+ continue;
258
+ const bin = GH_HELPER.exec(v)[1];
259
+ if (bin.includes('/')) {
260
+ fallbackProblems.push(`'${v}' bypasses the token-refreshing wrapper ${ctx.ghWrapper}: it answers from a stale GH_TOKEN`);
261
+ fallbackStatus = 'fail';
225
262
  }
226
263
  else {
227
- problems.push('no github.com gh fallback, and gh is not on PATH');
264
+ const resolved = ctx.which(bin);
265
+ if (resolved && sameFile(resolved, ctx.ghWrapper)) {
266
+ fallbackProblems.push(`'${v}' depends on PATH (the wrapper here, the real gh where git's PATH differs)`);
267
+ if (fallbackStatus === 'ok')
268
+ fallbackStatus = 'warn';
269
+ }
270
+ else {
271
+ fallbackProblems.push(`'${v}' resolves to ${resolved ?? 'nothing'}, not the token-refreshing wrapper ${ctx.ghWrapper}`);
272
+ fallbackStatus = 'fail';
273
+ }
228
274
  }
229
- if (status === 'ok')
230
- status = 'warn';
275
+ }
276
+ if (want && ghValues.filter((v) => v === want).length > 1) {
277
+ fallbackProblems.push(`${GH_FALLBACK_KEY} lists '${want}' more than once`);
278
+ }
279
+ if (fallbackProblems.length) {
280
+ problems.push(...fallbackProblems);
281
+ if (fallbackStatus === 'ok')
282
+ fallbackStatus = 'warn';
283
+ if (status !== 'fail')
284
+ status = fallbackStatus;
285
+ if (want)
286
+ d.needFallback = want;
231
287
  }
232
288
  if (d.inRepo) {
233
289
  const local = getAll(ctx.git, ['--local', '--get-all', 'credential.helper']);
@@ -238,7 +294,7 @@ function checkHelpers(ctx, d) {
238
294
  }
239
295
  }
240
296
  d.checks.push({ id: 'helper', status, detail: problems.length ? problems.join('; ')
241
- : `store, then ${GH_FALLBACK_VALUE} for github.com` });
297
+ : `store, then ${want ?? 'no gh fallback'} for github.com` });
242
298
  }
243
299
  function checkRemote(ctx, d) {
244
300
  if (!d.inRepo) {
@@ -287,7 +343,7 @@ function checkLsRemote(ctx, d) {
287
343
  }
288
344
  async function diagnose(ctx) {
289
345
  const inRepo = ctx.git(['rev-parse', '--is-inside-work-tree']).stdout.trim() === 'true';
290
- const d = { checks: [], inRepo, credsNeedRewrite: false, needStoreHelper: false, needFallback: false };
346
+ const d = { checks: [], inRepo, credsNeedRewrite: false, needStoreHelper: false };
291
347
  const token = await checkToken(ctx, d);
292
348
  checkCredentialsFile(ctx, d, token);
293
349
  checkHelpers(ctx, d);
@@ -356,8 +412,13 @@ function applyFixes(ctx, d) {
356
412
  : `credential.helper: git config failed (${r.stderr.trim()})`);
357
413
  }
358
414
  if (d.needFallback) {
359
- const r = ctx.git(['config', '--global', GH_FALLBACK_KEY, GH_FALLBACK_VALUE]);
360
- (r.status === 0 ? fixed : refused).push(r.status === 0 ? `set ${GH_FALLBACK_KEY} '${GH_FALLBACK_VALUE}'`
415
+ // Drop every gh-shaped value and '' reset, then add exactly one; a helper the
416
+ // user put on this key for something else stays. Exit 5 = nothing to unset.
417
+ const unset = ctx.git(['config', '--global', '--unset-all', GH_FALLBACK_KEY, '^$|auth git-credential$']);
418
+ const r = unset.status === 0 || unset.status === 5
419
+ ? ctx.git(['config', '--global', '--add', GH_FALLBACK_KEY, d.needFallback])
420
+ : unset;
421
+ (r.status === 0 ? fixed : refused).push(r.status === 0 ? `set ${GH_FALLBACK_KEY} '${d.needFallback}'`
361
422
  : `${GH_FALLBACK_KEY}: git config failed (${r.stderr.trim()})`);
362
423
  }
363
424
  if (d.embeddedUrl) {
@@ -402,7 +463,8 @@ export async function runGitDoctor(opts, deps = {}) {
402
463
  git: deps.git ?? defaultGit(cwd, { ...env, HOME: home }),
403
464
  fetchImpl: deps.fetchImpl ?? globalThis.fetch,
404
465
  getuid: deps.getuid ?? (() => process.getuid?.() ?? -1),
405
- hasCommand: deps.hasCommand ?? defaultHasCommand(env),
466
+ which: deps.which ?? defaultWhich(env),
467
+ ghWrapper: deps.ghWrapper ?? GH_WRAPPER,
406
468
  opts,
407
469
  };
408
470
  let d = await diagnose(ctx);
@@ -41,7 +41,7 @@ export async function runKanbanExport(options) {
41
41
  const env = options.env ?? process.env;
42
42
  if (!options.tileId)
43
43
  return fail('usage', 'a tileId is required');
44
- const resolved = resolveContext(env, options.workspaceFlag);
44
+ const resolved = resolveKanbanContext(env, options.workspaceFlag);
45
45
  if (!resolved.ok)
46
46
  return resolved.failure;
47
47
  const { commonApiUrl, userToken, workspaceId } = resolved;
@@ -101,7 +101,7 @@ export async function runKanbanImport(options) {
101
101
  return fail('usage', 'a boardId is required');
102
102
  if (!options.file)
103
103
  return fail('usage', 'a seed document path is required');
104
- const resolved = resolveContext(env, options.workspaceFlag);
104
+ const resolved = resolveKanbanContext(env, options.workspaceFlag);
105
105
  if (!resolved.ok)
106
106
  return resolved.failure;
107
107
  const { commonApiUrl, userToken, workspaceId } = resolved;
@@ -155,7 +155,7 @@ export async function runKanbanImport(options) {
155
155
  }
156
156
  export async function runKanbanModels(options = {}) {
157
157
  const env = options.env ?? process.env;
158
- const resolved = resolveContext(env, options.workspaceFlag);
158
+ const resolved = resolveKanbanContext(env, options.workspaceFlag);
159
159
  if (!resolved.ok)
160
160
  return resolved.failure;
161
161
  const { commonApiUrl, userToken, workspaceId } = resolved;
@@ -220,7 +220,7 @@ export function formatImportSummary(body, boardId) {
220
220
  * already writes (which names both places a token can live) rather than a
221
221
  * workspace complaint that would send an operator looking in the wrong place.
222
222
  */
223
- function resolveContext(env, workspaceFlag) {
223
+ export function resolveKanbanContext(env, workspaceFlag) {
224
224
  const auth = resolveSubstrateContext(env);
225
225
  if (!auth.ok)
226
226
  return { ok: false, failure: fail('auth', auth.message) };
package/dist/preview.js CHANGED
@@ -6,11 +6,17 @@ export const PREVIEW_HELP = `Usage:
6
6
  yolo preview status [tile-id] [--json]
7
7
  yolo preview logs <tile-id> [--tail 50] [--json]
8
8
  yolo preview stop <tile-id> [--json]
9
+ yolo preview update <tile-id> [--env KEY=VALUE ...] [--unset-env KEY ...] [options]
9
10
 
10
11
  Create options:
11
12
  --cwd <dir> Repository-relative app directory (default: .)
12
13
  --setup <command> Install dependencies in each candidate checkout
13
14
  --build <command> Build each candidate
15
+ --mode <production|dev> production: build each landed commit once (--build
16
+ required), then serve it with a production --command;
17
+ the start command gets NODE_ENV=production. Default:
18
+ run --command as given (dev servers compile on request
19
+ and can time out under load)
14
20
  --health-path <path> Readiness endpoint (default: /)
15
21
  --port <auto|number> Public preview port (default: auto)
16
22
  --poll-seconds <n> Branch polling interval, 5..3600 (default: 30)
@@ -22,16 +28,39 @@ Create options:
22
28
  --desktop <id> Destination desktop
23
29
  --json Print structured output
24
30
 
31
+ Update options (same tile and port; rebuilds the branch head once and
32
+ forgets the failed commit):
33
+ --env KEY=VALUE Set an environment variable (repeatable)
34
+ --unset-env KEY Remove an environment variable (repeatable)
35
+ --command <command> Server start command
36
+ --setup <command> Setup command
37
+ --build <command> Build command
38
+ --mode <production|dev> Switch serving mode (production needs a build command)
39
+ --health-path <path> Readiness endpoint
40
+ --ready-seconds <n> Server readiness timeout, 1..300
41
+ --timeout-seconds <n> Setup/build timeout, 1..1800
42
+
43
+ Production starts (with --mode production; run setup such as npm ci first):
44
+ Next.js: --build 'npx next build' --command 'npx next start -p "$PORT" -H "$HOST"'
45
+ OpenNext: --build 'npx next build' --command 'npx next start -p "$PORT" -H "$HOST"'
46
+ (opennextjs-cloudflare targets Workers; preview the Next server)
47
+ vinext: --build 'npx vinext build' --command 'npx vinext start --port "$PORT" --hostname "$HOST"'
48
+ Vite SPA: --build 'npx vite build' --command 'npx vite preview --port "$PORT" --host "$HOST" --strictPort'
49
+ Static: --build 'npm run build' --command 'python3 -m http.server "$PORT" --bind "$HOST" -d dist'
50
+
25
51
  Run inside a Studio workspace. Quote commands so $PORT and $HOST reach the
26
52
  managed server unchanged. Stop keeps the tile and prevents automatic restart.
27
53
  `;
28
54
  function parse(args) {
29
55
  const action = args[0];
30
- if (!['create', 'status', 'logs', 'stop'].includes(action || ''))
31
- throw new Error('Choose create, status, logs, or stop');
56
+ if (!['create', 'status', 'logs', 'stop', 'update'].includes(action || ''))
57
+ throw new Error('Choose create, status, logs, stop, or update');
32
58
  const values = {};
59
+ const env = {};
60
+ const unsetEnv = [];
33
61
  let id, json = false;
34
- const allowed = action === 'create' ? ['name', 'branch', 'command', 'cwd', 'setup', 'build', 'health-path', 'port', 'poll-seconds', 'timeout-seconds', 'ready-seconds', 'wait-for', 'request-id', 'desktop'] : action === 'logs' ? ['tail'] : [];
62
+ const allowed = action === 'create' ? ['name', 'branch', 'command', 'cwd', 'setup', 'build', 'health-path', 'port', 'poll-seconds', 'timeout-seconds', 'ready-seconds', 'wait-for', 'request-id', 'desktop', 'mode'] : action === 'logs' ? ['tail']
63
+ : action === 'update' ? ['env', 'unset-env', 'command', 'setup', 'build', 'mode', 'health-path', 'ready-seconds', 'timeout-seconds'] : [];
35
64
  for (let i = 1; i < args.length; i++) {
36
65
  const arg = args[i];
37
66
  if (arg === '--json') {
@@ -51,13 +80,27 @@ function parse(args) {
51
80
  if (values[key] !== undefined)
52
81
  throw new Error(`Repeated option: --${key}`);
53
82
  const value = match[2] ?? args[++i];
83
+ if (key === 'env') {
84
+ // `--env KEY=` sets an empty value; the name is checked here, the rest by the service.
85
+ const pair = value === undefined ? null : /^([A-Za-z_][A-Za-z0-9_]{0,127})=(.*)$/s.exec(value);
86
+ if (!pair)
87
+ throw new Error('--env requires KEY=VALUE');
88
+ env[pair[1]] = pair[2];
89
+ continue;
90
+ }
54
91
  if (!value || (match[2] === undefined && value.startsWith('--')))
55
92
  throw new Error(`--${key} requires a value`);
93
+ if (key === 'unset-env') {
94
+ if (!/^[A-Za-z_][A-Za-z0-9_]{0,127}$/.test(value))
95
+ throw new Error('--unset-env requires a variable name');
96
+ unsetEnv.push(value);
97
+ continue;
98
+ }
56
99
  values[key] = value;
57
100
  }
58
101
  if (id && !/^[a-zA-Z0-9_-]{1,128}$/.test(id))
59
102
  throw new Error('Invalid preview tile ID');
60
- if ((action === 'logs' || action === 'stop') && !id)
103
+ if ((action === 'logs' || action === 'stop' || action === 'update') && !id)
61
104
  throw new Error(`${action} requires a preview tile ID`);
62
105
  const number = (key, min, max, fallback) => {
63
106
  const raw = values[key];
@@ -68,6 +111,9 @@ function parse(args) {
68
111
  throw new Error(`--${key} must be an integer in ${min}..${max}`);
69
112
  return n;
70
113
  };
114
+ const mode = values.mode;
115
+ if (mode !== undefined && mode !== 'production' && mode !== 'dev')
116
+ throw new Error('--mode must be production or dev');
71
117
  const result = { action: action, id, json, tail: number('tail', 1, 200, 50) };
72
118
  if (action === 'create') {
73
119
  for (const key of ['name', 'branch', 'command'])
@@ -76,6 +122,8 @@ function parse(args) {
76
122
  const cwd = values.cwd || '.';
77
123
  if (cwd.startsWith('/') || cwd.split(/[\\/]/).includes('..'))
78
124
  throw new Error('--cwd must stay inside the repository');
125
+ if (mode === 'production' && !values.build?.trim())
126
+ throw new Error('--mode production requires --build');
79
127
  const waitFor = values['wait-for'];
80
128
  if (waitFor !== undefined && (waitFor.length > 1024 || waitFor.startsWith('/') || waitFor.split(/[\\/]/).includes('..') || /[\r\n]/.test(waitFor)))
81
129
  throw new Error('--wait-for must be a repository-relative path');
@@ -85,7 +133,22 @@ function parse(args) {
85
133
  followBranch: { branch: values.branch, ...(values.setup && { setup: values.setup }), ...(values.build && { build: values.build }),
86
134
  healthPath: values['health-path'] || '/', pollSeconds: number('poll-seconds', 5, 3600, 30),
87
135
  timeoutSeconds: number('timeout-seconds', 1, 1800, 300), readySeconds: number('ready-seconds', 1, 300, 60),
88
- ...(waitFor && { waitFor }) } };
136
+ ...(waitFor && { waitFor }), ...(mode && { mode }) } };
137
+ }
138
+ if (action === 'update') {
139
+ const healthPath = values['health-path'];
140
+ if (healthPath !== undefined && (!healthPath.startsWith('/') || healthPath.startsWith('//')))
141
+ throw new Error('--health-path must start with a single /');
142
+ const body = {
143
+ ...(Object.keys(env).length && { env }), ...(unsetEnv.length && { unsetEnv }),
144
+ ...(values.command !== undefined && { command: values.command }), ...(values.setup !== undefined && { setup: values.setup }),
145
+ ...(values.build !== undefined && { build: values.build }), ...(mode !== undefined && { mode }), ...(healthPath !== undefined && { healthPath }),
146
+ ...(values['ready-seconds'] !== undefined && { readySeconds: number('ready-seconds', 1, 300, 60) }),
147
+ ...(values['timeout-seconds'] !== undefined && { timeoutSeconds: number('timeout-seconds', 1, 1800, 300) }),
148
+ };
149
+ if (!Object.keys(body).length)
150
+ throw new Error('update needs at least one change (e.g. --env KEY=VALUE)');
151
+ result.body = body;
89
152
  }
90
153
  return result;
91
154
  }
@@ -110,14 +173,14 @@ export async function runPreviewCmd(args, deps = {}) {
110
173
  return 78;
111
174
  }
112
175
  try {
113
- const scope = input.action === 'create' ? 'studio.create_preview' : input.action === 'stop' ? 'studio.stop_preview' : 'studio.read_preview';
176
+ const scope = input.action === 'create' || input.action === 'update' ? 'studio.create_preview' : input.action === 'stop' ? 'studio.stop_preview' : 'studio.read_preview';
114
177
  const token = await mintSubstrateToken({ ...auth.context, scopes: [scope], fetchImpl: deps.fetchImpl });
115
178
  const base = `${auth.context.commonApiUrl.replace(/\/+$/, '')}/internal/mcp/workspaces/${encodeURIComponent(token.workspaceId)}`;
116
179
  const route = input.action === 'create' ? '/tiles/preview' : input.action === 'status'
117
180
  ? `/previews${input.id ? `/${encodeURIComponent(input.id)}` : ''}`
118
181
  : `/previews/${encodeURIComponent(input.id)}/${input.action}${input.action === 'logs' ? `?tail=${input.tail}` : ''}`;
119
182
  const response = await (deps.fetchImpl ?? globalThis.fetch)(base + route, {
120
- method: input.action === 'create' || input.action === 'stop' ? 'POST' : 'GET',
183
+ method: input.action === 'status' || input.action === 'logs' ? 'GET' : 'POST',
121
184
  headers: { Authorization: `Bearer ${token.token}`, 'Content-Type': 'application/json' },
122
185
  ...(input.body && { body: JSON.stringify(input.body) }),
123
186
  });
@@ -130,11 +193,15 @@ export async function runPreviewCmd(args, deps = {}) {
130
193
  out(`Preview ${body.tile?.id || body.previewId} follows ${input.body.followBranch && input.body.followBranch.branch} on port ${body.preview?.port}.\nUse yolo preview status to check build progress.\n`);
131
194
  else if (input.action === 'stop')
132
195
  out(`Stopped preview ${input.id}. The tile is retained.\n`);
196
+ else if (input.action === 'update')
197
+ out(`Updated preview ${input.id} on port ${body.port}${body.version ? ` (config v${body.version})` : ''}; ${body.confirmed === false
198
+ ? 'saved; the workspace has not confirmed it yet and will be sent it again on the next status check.'
199
+ : 'rebuilding the branch head with the new configuration.'}\nUse yolo preview status ${input.id} to follow it.\n`);
133
200
  else if (input.action === 'logs')
134
201
  out((body.lines?.map((line) => line.text).join('') || '(no logs)') + '\n');
135
202
  else {
136
203
  const previews = body.previews || [body.preview];
137
- out(previews.length ? previews.map((p) => `${p.tileId}\t${p.name}\t${p.status}\t${p.branchStatus?.phase || '-'}\t${p.branch}\t:${p.port}\t${p.branchStatus?.servedCommit?.slice(0, 12) || '-'}${p.branchStatus?.error ? `\n ${p.branchStatus.error}` : ''}`).join('\n') + '\n' : 'No managed branch previews.\n');
204
+ out(previews.length ? previews.map((p) => `${p.tileId}\t${p.name}\t${p.status}\t${p.branchStatus?.phase || '-'}\t${p.branch}\t:${p.port}\t${p.branchStatus?.servedCommit?.slice(0, 12) || '-'}${p.branchStatus?.mode || p.branchStatus?.lastBuild ? `\n ${p.branchStatus.mode || 'unset'} mode${p.branchStatus.lastBuild ? `, last build ${(p.branchStatus.lastBuild.durationMs / 1000).toFixed(1)}s (${p.branchStatus.lastBuild.commit.slice(0, 12)})` : ''}` : ''}${p.update && p.update.state !== 'applied' ? `\n Config v${p.update.version} update ${p.update.state}${p.update.error ? `: ${p.update.error}` : ''}` : ''}${p.branchStatus?.error ? `\n ${p.branchStatus.error}\n See: yolo preview logs ${p.tileId}` : ''}`).join('\n') + '\n' : 'No managed branch previews.\n');
138
205
  }
139
206
  return 0;
140
207
  }
@@ -0,0 +1,302 @@
1
+ /**
2
+ * `yolo routing …` — Background Runner routing (which model runs each card)
3
+ * and Jev from a shell: status, on/off, decisions, a route preview, and the
4
+ * runner/board policy.
5
+ *
6
+ * Every verb is one of the owner REST routes in
7
+ * `common-api/src/routes/yolo-background-routing.ts`, reached with the USER
8
+ * token through `userRouteRequest`, like `yolo kanban models`. Nothing is
9
+ * decided here: `--json` prints the response body as-is, and the default
10
+ * output is a short reading of the same body.
11
+ *
12
+ * Exit codes as `kanban-cli.ts`: 0 success, 1 http, 64 usage/auth/workspace.
13
+ */
14
+ import * as fs from 'node:fs';
15
+ import { userRouteRequest } from './work-client.js';
16
+ import { exitCodeForFailure, resolveKanbanContext } from './kanban-cli.js';
17
+ const OBJECT_ID = /^[a-f0-9]{24}$/;
18
+ /** `args` is everything after `routing`. */
19
+ export function parseRoutingArgs(args) {
20
+ const positional = [];
21
+ const flags = {};
22
+ const VALUED = new Set(['--workspace', '--card', '--board', '--limit', '--file', '--policy', '--expected-revision']);
23
+ for (let i = 0; i < args.length; i++) {
24
+ const a = args[i];
25
+ const eq = a.indexOf('=');
26
+ const name = a.startsWith('--') && eq > 0 ? a.slice(0, eq) : a;
27
+ if (VALUED.has(name)) {
28
+ const v = eq > 0 && a.startsWith('--') ? a.slice(eq + 1) : args[++i];
29
+ if (!v || (eq < 0 && v.startsWith('--')))
30
+ return { ok: false, message: `${name} requires a value` };
31
+ flags[name] = v;
32
+ }
33
+ else if (a === '--json' || a === '--runner') {
34
+ flags[a] = true;
35
+ }
36
+ else if (a.startsWith('-')) {
37
+ return { ok: false, message: `unknown option: ${a}` };
38
+ }
39
+ else {
40
+ positional.push(a);
41
+ }
42
+ }
43
+ const json = flags['--json'] === true;
44
+ const workspaceFlag = flags['--workspace'];
45
+ const allow = (...names) => {
46
+ const extra = Object.keys(flags).find(f => f !== '--json' && f !== '--workspace' && !names.includes(f));
47
+ return extra ? `${extra} does not apply here` : null;
48
+ };
49
+ const card = flags['--card'];
50
+ if (card !== undefined && !OBJECT_ID.test(card))
51
+ return { ok: false, message: '--card takes a card id (24 hex characters)' };
52
+ const board = flags['--board'];
53
+ if (board !== undefined && !OBJECT_ID.test(board))
54
+ return { ok: false, message: '--board takes a board id (24 hex characters)' };
55
+ const revision = flags['--expected-revision'] === undefined ? undefined : Number(flags['--expected-revision']);
56
+ if (revision !== undefined && (!Number.isInteger(revision) || revision < 0)) {
57
+ return { ok: false, message: '--expected-revision takes a non-negative integer' };
58
+ }
59
+ const [verb, sub, ...rest] = positional;
60
+ const done = (command, ...names) => {
61
+ const problem = allow(...names);
62
+ return problem ? { ok: false, message: problem } : { ok: true, command, json, workspaceFlag };
63
+ };
64
+ const noMore = (list) => list.find(v => v !== undefined);
65
+ switch (verb) {
66
+ case 'status':
67
+ case 'on':
68
+ case 'off': {
69
+ const extra = noMore([sub, ...rest]);
70
+ if (extra)
71
+ return { ok: false, message: `unexpected positional argument: ${extra}` };
72
+ return done(verb === 'status' ? { verb } : { verb });
73
+ }
74
+ case 'decisions': {
75
+ const extra = noMore([sub, ...rest]);
76
+ if (extra)
77
+ return { ok: false, message: `unexpected positional argument: ${extra}` };
78
+ const limit = flags['--limit'] === undefined ? undefined : Number(flags['--limit']);
79
+ if (limit !== undefined && (!Number.isInteger(limit) || limit < 1 || limit > 200)) {
80
+ return { ok: false, message: '--limit takes an integer from 1 to 200' };
81
+ }
82
+ return done({ verb, ...(card ? { cardId: card } : {}), ...(limit !== undefined ? { limit } : {}) }, '--card', '--limit');
83
+ }
84
+ case 'preview': {
85
+ if (!sub)
86
+ return { ok: false, message: 'a <cardId> is required' };
87
+ if (!OBJECT_ID.test(sub))
88
+ return { ok: false, message: '<cardId> must be a card id (24 hex characters)' };
89
+ const extra = noMore(rest);
90
+ if (extra)
91
+ return { ok: false, message: `unexpected positional argument: ${extra}` };
92
+ return done({ verb, cardId: sub });
93
+ }
94
+ case 'policy': {
95
+ const extra = noMore(rest);
96
+ if (extra)
97
+ return { ok: false, message: `unexpected positional argument: ${extra}` };
98
+ if (sub === 'get')
99
+ return done({ verb: 'policy-get', ...(card ? { cardId: card } : {}) }, '--card');
100
+ const targets = [flags['--runner'] === true, board !== undefined, card !== undefined].filter(Boolean).length;
101
+ if (sub === 'set') {
102
+ if (card !== undefined)
103
+ return { ok: false, message: 'a card\'s model pin is set on the card, not with `routing policy set`' };
104
+ if (targets !== 1)
105
+ return { ok: false, message: 'choose one of --runner or --board <id>' };
106
+ const file = flags['--file'];
107
+ const inline = flags['--policy'];
108
+ if ((file === undefined) === (inline === undefined))
109
+ return { ok: false, message: 'give the policy with exactly one of --file <path> or --policy <json>' };
110
+ const target = board ? { scope: 'board', scopeId: board } : { scope: 'runner' };
111
+ return done({ verb: 'policy-set', target, ...(file ? { policyFile: file } : { policyJson: inline }),
112
+ ...(revision !== undefined ? { expectedRevision: revision } : {}) }, '--runner', '--board', '--file', '--policy', '--expected-revision');
113
+ }
114
+ if (sub === 'delete') {
115
+ if (targets !== 1)
116
+ return { ok: false, message: 'choose one of --runner, --board <id> or --card <id>' };
117
+ if (revision === 0)
118
+ return { ok: false, message: '--expected-revision for a delete is 1 or more' };
119
+ const target = board ? { scope: 'board', scopeId: board } : card ? { scope: 'card', scopeId: card } : { scope: 'runner' };
120
+ return done({ verb: 'policy-delete', target, ...(revision !== undefined ? { expectedRevision: revision } : {}) }, '--runner', '--board', '--card', '--expected-revision');
121
+ }
122
+ return { ok: false, message: sub ? `unknown policy subcommand '${sub}'` : 'policy requires get, set or delete' };
123
+ }
124
+ default:
125
+ return { ok: false, message: verb ? `unknown routing subcommand '${verb}'` : 'routing requires a subcommand' };
126
+ }
127
+ }
128
+ export async function runRouting(parsed, deps = {}) {
129
+ const env = deps.env ?? process.env;
130
+ const resolved = resolveKanbanContext(env, parsed.workspaceFlag);
131
+ if (!resolved.ok)
132
+ return resolved.failure;
133
+ const { commonApiUrl, userToken, workspaceId } = resolved;
134
+ const base = `/workspaces/${encodeURIComponent(workspaceId)}/yolo-background/routing`;
135
+ const send = async ({ method, path, body, label }) => {
136
+ let response;
137
+ try {
138
+ response = await userRouteRequest({ commonApiUrl, userToken, fetchImpl: deps.fetchImpl }, `${base}/${path}`, { method, ...(body !== undefined ? { jsonBody: body } : {}) });
139
+ }
140
+ catch (err) {
141
+ return fail('http', `${label} failed: ${err instanceof Error ? err.message : String(err)}`);
142
+ }
143
+ const text = await response.text().catch(() => '<no body>');
144
+ if (!response.ok)
145
+ return fail('http', `${label} failed: HTTP ${response.status} — ${text}`, { status: response.status });
146
+ return { ok: true, text };
147
+ };
148
+ const finish = (text, human) => {
149
+ if (parsed.json)
150
+ return { ok: true, output: text, raw: true, workspaceId };
151
+ let body;
152
+ try {
153
+ body = JSON.parse(text);
154
+ }
155
+ catch {
156
+ return { ok: true, output: text, raw: false, workspaceId };
157
+ }
158
+ return { ok: true, output: human(body), raw: false, workspaceId };
159
+ };
160
+ const { command } = parsed;
161
+ switch (command.verb) {
162
+ case 'status': {
163
+ const r = await send({ method: 'GET', path: 'config', label: 'routing.config' });
164
+ return r.ok ? finish(r.text, formatStatus) : r;
165
+ }
166
+ case 'on':
167
+ case 'off': {
168
+ const r = await send({ method: 'PUT', path: 'enabled', body: { enabled: command.verb === 'on' }, label: 'routing.enabled' });
169
+ return r.ok ? finish(r.text, (body) => `Routing is ${body.enabled ? 'on: Jev assesses cards admitted from now on' : 'off: cards admitted from now on run on the background agent\'s default model'}. Running work is untouched.`) : r;
170
+ }
171
+ case 'decisions': {
172
+ const qs = new URLSearchParams();
173
+ if (command.cardId)
174
+ qs.set('cardIds', command.cardId);
175
+ if (command.limit !== undefined)
176
+ qs.set('limit', String(command.limit));
177
+ const q = qs.toString();
178
+ const r = await send({ method: 'GET', path: `decisions${q ? `?${q}` : ''}`, label: 'routing.decisions' });
179
+ return r.ok ? finish(r.text, formatDecisions) : r;
180
+ }
181
+ case 'preview': {
182
+ const r = await send({ method: 'POST', path: 'preview', body: { cardId: command.cardId }, label: 'routing.preview' });
183
+ // A preview's shape is the router's; the summary is its decision, the rest is `--json`.
184
+ return r.ok ? finish(r.text, (body) => JSON.stringify(body.decision ?? body, null, 2)) : r;
185
+ }
186
+ case 'policy-get': {
187
+ const r = await send({ method: 'GET', path: `config${command.cardId ? `?cardId=${command.cardId}` : ''}`, label: 'routing.config' });
188
+ if (!r.ok)
189
+ return r;
190
+ if (parsed.json) {
191
+ const body = JSON.parse(r.text);
192
+ return { ok: true, output: JSON.stringify({ policies: body.policies ?? [], cardPolicies: body.cardPolicies ?? null }, null, 2), raw: false, workspaceId };
193
+ }
194
+ return finish(r.text, formatPolicies);
195
+ }
196
+ case 'policy-set': {
197
+ let policy;
198
+ try {
199
+ const source = command.policyFile !== undefined ? (deps.readFileImpl ?? defaultReadFile)(command.policyFile) : command.policyJson;
200
+ policy = JSON.parse(source);
201
+ }
202
+ catch (err) {
203
+ return fail('usage', `the policy is not readable JSON: ${err instanceof Error ? err.message : String(err)}`);
204
+ }
205
+ if (!policy || typeof policy !== 'object' || Array.isArray(policy))
206
+ return fail('usage', 'the policy must be a JSON object');
207
+ const scopeId = command.target.scope === 'board' ? command.target.scopeId : null;
208
+ let expectedRevision = command.expectedRevision;
209
+ if (expectedRevision === undefined) {
210
+ // Unfenced: overwrite what is stored now (revision 0: nothing is).
211
+ const r = await send({ method: 'GET', path: 'config', label: 'routing.config' });
212
+ if (!r.ok)
213
+ return r;
214
+ const policies = JSON.parse(r.text).policies ?? [];
215
+ expectedRevision = policies.find(doc => doc.scope === command.target.scope && (doc.scopeId ?? null) === scopeId)?.revision ?? 0;
216
+ }
217
+ const r = await send({ method: 'PUT', path: 'policy', body: { scope: command.target.scope, scopeId, policy, expectedRevision }, label: 'routing.policy' });
218
+ return r.ok ? finish(r.text, (body) => `Saved the ${describeScope(command.target)} policy (revision ${body.revision}).`) : r;
219
+ }
220
+ case 'policy-delete': {
221
+ const t = command.target;
222
+ const path = `policy/${t.scope}${t.scope === 'runner' ? '' : `/${t.scopeId}`}${command.expectedRevision !== undefined ? `?expectedRevision=${command.expectedRevision}` : ''}`;
223
+ const r = await send({ method: 'DELETE', path, label: 'routing.policy.delete' });
224
+ return r.ok ? finish(r.text, () => `Deleted the ${describeScope(t)} policy; it inherits again.`) : r;
225
+ }
226
+ }
227
+ }
228
+ // ─── Human output ─────────────────────────────────────────────────────────
229
+ const describeScope = (t) => t.scope === 'runner' ? 'runner' : `${t.scope} ${t.scopeId}`;
230
+ export function formatStatus(body) {
231
+ const jev = body.jev;
232
+ const usage = jev?.usage ?? [];
233
+ const calls = usage.reduce((n, d) => n + (d.calls ?? 0), 0);
234
+ const cost = usage.every(d => typeof d.costUsd === 'number') ? usage.reduce((n, d) => n + d.costUsd, 0) : null;
235
+ return [
236
+ `Routing: ${body.enabled ? 'on' : 'off'}`,
237
+ `Jev: ${jev?.state ?? 'unknown'}${jev?.reason ? ` (${jev.reason})` : ''}${jev?.model ? ` — ${jev.model}` : ''}`,
238
+ ` ${calls} call${calls === 1 ? '' : 's'} in the last ${usage.length} day${usage.length === 1 ? '' : 's'}${cost === null ? '' : `, $${cost.toFixed(4)}`}`,
239
+ formatPolicies(body),
240
+ ].join('\n');
241
+ }
242
+ export function formatPolicies(body) {
243
+ const lines = (body.policies ?? []).map(p => ` ${p.scope === 'runner' ? 'runner' : `${p.scope} ${p.scopeId}`} revision ${p.revision}`);
244
+ return [
245
+ `Policies:${lines.length ? '' : ' none (built-in defaults)'}`,
246
+ ...lines,
247
+ `Card policies (model pins): ${body.cardPolicies?.count ?? 0}`,
248
+ ].join('\n');
249
+ }
250
+ export function formatDecisions(body) {
251
+ const decisions = body.decisions ?? [];
252
+ if (decisions.length === 0)
253
+ return 'No routing decisions recorded.';
254
+ return decisions.map(d => {
255
+ const detail = d.decision?.selected?.configurationId ?? d.decision?.waiting?.code;
256
+ return `${d.createdAt} ${d.cardId} ${d.kind} ${d.decision?.status ?? '?'}${detail ? ` ${detail}` : ''}`;
257
+ }).join('\n');
258
+ }
259
+ // ─── CLI surface ──────────────────────────────────────────────────────────
260
+ export const ROUTING_USAGE = [
261
+ 'Usage: yolo routing <subcommand> [--json] [--workspace <wsId>]',
262
+ '',
263
+ 'Subcommands:',
264
+ ' status Routing on/off, Jev\'s state and why it is unavailable, policies',
265
+ ' on | off Turn routing on or off (cards admitted from now on)',
266
+ ' decisions [--card <id>] [--limit <n>] Recorded decisions for one card, or the latest (1-200)',
267
+ ' preview <cardId> Where routing would send a card now (read-only)',
268
+ ' policy get [--card <id>] Runner and board policies with their revisions',
269
+ ' policy set (--runner | --board <id>) Replace a policy: --file <path> or --policy <json>',
270
+ ' [--expected-revision <n>] Refuse if the policy changed since revision <n>',
271
+ ' policy delete (--runner | --board <id> | --card <id>) [--expected-revision <n>]',
272
+ ' Delete a policy so it inherits again',
273
+ '',
274
+ '--json prints the API response as-is.',
275
+ '',
276
+ ].join('\n');
277
+ /** `args` is everything after `routing`. */
278
+ export async function runRoutingCmd(args, deps = {}) {
279
+ if (args.length === 0 || args.some(a => a === '--help' || a === '-h') || args[0] === 'help') {
280
+ (args.length === 0 ? process.stderr : process.stdout).write(ROUTING_USAGE);
281
+ return args.length === 0 ? 64 : 0;
282
+ }
283
+ const parsed = parseRoutingArgs(args);
284
+ if (!parsed.ok) {
285
+ process.stderr.write(`yolo: routing: ${parsed.message}\n`);
286
+ process.stderr.write(ROUTING_USAGE);
287
+ return 64;
288
+ }
289
+ const result = await runRouting(parsed, deps);
290
+ if (result.ok) {
291
+ process.stdout.write(result.raw ? result.output : `${result.output}\n`);
292
+ return 0;
293
+ }
294
+ process.stderr.write(`FAIL [${result.kind}]: ${result.message}\n`);
295
+ return exitCodeForFailure(result.kind);
296
+ }
297
+ function fail(kind, message, detail) {
298
+ return { ok: false, kind, message, detail };
299
+ }
300
+ function defaultReadFile(filePath) {
301
+ return fs.readFileSync(filePath, 'utf-8');
302
+ }
@@ -0,0 +1,186 @@
1
+ /**
2
+ * `yolo workspace set-repository <url>` — point this workspace at a different
3
+ * repository. A thin client over `POST /v1/workspaces/:id/repository`
4
+ * (docs/plans/workspace-set-repository.md §7.2), the operator's own
5
+ * user-token route, so it mints no delegated token and needs no MCP scope.
6
+ *
7
+ * Two steps, like the MCP tool:
8
+ * - without `--confirm` it prints the preview and its snapshot; nothing changes;
9
+ * - `--confirm <snapshot>` applies, and is refused if anything moved since.
10
+ *
11
+ * Exit codes: 0 success (a preview with blockers included) · 1 http/refused · 64 usage/auth.
12
+ */
13
+ import { userRouteRequest } from './work-client.js';
14
+ import { resolveSubstrateContext } from './auth-context.js';
15
+ export const SET_REPOSITORY_USAGE = [
16
+ 'Usage: yolo workspace set-repository <url> [options]',
17
+ '',
18
+ ' --default-branch <b> Branch to check out (default: the new remote\'s HEAD). Alias: --branch',
19
+ ' --auth <https|ssh> Transport (default: keep the current one when the host supports it)',
20
+ ' --keep-old-remote-as <n> Name for the old origin remote (default: yolo-studio). Alias: --keep-old-as',
21
+ ' --drop-old-remote Remove the old origin instead of keeping it',
22
+ ' --confirm <snapshot> Apply the preview that returned this snapshot',
23
+ ' --json Print the raw response',
24
+ ' --workspace <wsId> Defaults to this session\'s workspace',
25
+ '',
26
+ 'Without --confirm nothing changes: the command prints what would happen and the snapshot to confirm.',
27
+ '',
28
+ ].join('\n');
29
+ const WORKSPACE_USAGE = [
30
+ 'Usage: yolo workspace <subcommand>',
31
+ '',
32
+ 'Subcommands:',
33
+ ' set-repository <url> Point this workspace at a different repository (preview, then --confirm)',
34
+ '',
35
+ ].join('\n');
36
+ export function parseSetRepositoryArgs(args) {
37
+ let url;
38
+ const out = { json: false };
39
+ let keep;
40
+ let drop = false;
41
+ for (let i = 0; i < args.length; i++) {
42
+ const raw = args[i];
43
+ const eq = raw.startsWith('--') ? raw.indexOf('=') : -1;
44
+ const flag = eq > 0 ? raw.slice(0, eq) : raw;
45
+ const value = () => {
46
+ const v = eq > 0 ? raw.slice(eq + 1) : args[++i];
47
+ if (!v || (eq < 0 && v.startsWith('--')))
48
+ throw new Error(`${flag} requires a value`);
49
+ return v;
50
+ };
51
+ try {
52
+ if (flag === '--default-branch' || flag === '--branch')
53
+ out.defaultBranch = value();
54
+ else if (flag === '--auth') {
55
+ const v = value();
56
+ if (v !== 'https' && v !== 'ssh')
57
+ return { ok: false, message: '--auth must be https or ssh' };
58
+ out.authMethod = v;
59
+ }
60
+ else if (flag === '--keep-old-remote-as' || flag === '--keep-old-as')
61
+ keep = value();
62
+ else if (flag === '--drop-old-remote')
63
+ drop = true;
64
+ else if (flag === '--confirm') {
65
+ const v = value();
66
+ if (!/^[a-f0-9]{64}$/.test(v))
67
+ return { ok: false, message: '--confirm takes the 64-character snapshot a preview printed' };
68
+ out.confirm = v;
69
+ }
70
+ else if (flag === '--json')
71
+ out.json = true;
72
+ else if (flag === '--workspace')
73
+ out.workspaceFlag = value();
74
+ else if (raw.startsWith('-'))
75
+ return { ok: false, message: `unknown option: ${raw}` };
76
+ else if (url === undefined)
77
+ url = raw;
78
+ else
79
+ return { ok: false, message: `unexpected positional argument: ${raw}` };
80
+ }
81
+ catch (error) {
82
+ return { ok: false, message: error.message };
83
+ }
84
+ }
85
+ if (!url)
86
+ return { ok: false, message: 'a repository <url> is required' };
87
+ if (keep !== undefined && drop)
88
+ return { ok: false, message: '--keep-old-remote-as and --drop-old-remote are mutually exclusive' };
89
+ return { ok: true, url, ...out, ...(drop ? { keepOldRemoteAs: null } : keep !== undefined ? { keepOldRemoteAs: keep } : {}) };
90
+ }
91
+ /** What an operator reads before confirming; `--json` prints the response as-is. */
92
+ export function formatSetRepository(body, url) {
93
+ if (body.error) {
94
+ const lines = [`Refused (${body.code ?? 'error'}): ${body.error}`];
95
+ for (const blocker of body.preview?.blockers ?? [])
96
+ lines.push(` ✗ ${blocker.code}: ${blocker.message}`);
97
+ return lines.join('\n');
98
+ }
99
+ const oldRemote = body.oldRemote?.dropped ? 'dropped' : `kept as '${body.oldRemote?.keptAs ?? 'yolo-studio'}'`;
100
+ const lines = [
101
+ `${body.applied ? 'Switched' : 'Would switch'}: ${body.from?.url ?? '(none)'} → ${body.to?.url ?? url}`,
102
+ ` default branch: ${body.to?.defaultBranch ?? '(unknown)'} transport: ${body.to?.authMethod ?? '?'} old remote: ${oldRemote}`,
103
+ ];
104
+ if (body.credential)
105
+ lines.push(` access: ${body.credential.method ?? 'none'} (${body.credential.probe ?? 'unchecked'})`);
106
+ const lanes = body.applied ? body.lanesFlagged ?? [] : (body.lanes ?? []).map((lane) => lane.name);
107
+ if (lanes.length)
108
+ lines.push(` lanes staying on the previous repository: ${lanes.join(', ')}`);
109
+ for (const blocker of body.blockers ?? [])
110
+ lines.push(` ✗ ${blocker.code}: ${blocker.message}`);
111
+ for (const warning of body.warnings ?? [])
112
+ lines.push(` ! ${warning}`);
113
+ if (body.restart?.required)
114
+ lines.push(` ↻ restart required (${body.restart.reason ?? 'credentials'})${body.restart.message ? `: ${body.restart.message}` : ''}`);
115
+ if (!body.applied) {
116
+ lines.push(body.blockers?.length
117
+ ? 'Blocked: resolve the items marked ✗, then preview again.'
118
+ : `To apply: yolo workspace set-repository ${url} --confirm ${body.snapshot}`);
119
+ }
120
+ return lines.join('\n');
121
+ }
122
+ export async function runSetRepository(args, deps = {}) {
123
+ const env = deps.env ?? process.env;
124
+ const auth = resolveSubstrateContext(env);
125
+ if (!auth.ok)
126
+ return { code: 64, stderr: `FAIL [auth]: ${auth.message}` };
127
+ const sessionWorkspace = env.WORKSPACE_ID?.trim() || undefined;
128
+ if (args.workspaceFlag && sessionWorkspace && args.workspaceFlag !== sessionWorkspace) {
129
+ return { code: 64, stderr: `FAIL [workspace_mismatch]: --workspace ${args.workspaceFlag} does not match this session's workspace (${sessionWorkspace}).` };
130
+ }
131
+ const workspaceId = args.workspaceFlag ?? sessionWorkspace;
132
+ if (!workspaceId)
133
+ return { code: 64, stderr: 'FAIL [usage]: no workspace: WORKSPACE_ID is unset — pass --workspace <workspaceId>' };
134
+ const body = {
135
+ url: args.url,
136
+ ...(args.defaultBranch ? { defaultBranch: args.defaultBranch } : {}),
137
+ ...(args.authMethod ? { authMethod: args.authMethod } : {}),
138
+ ...(args.keepOldRemoteAs !== undefined ? { keepOldRemoteAs: args.keepOldRemoteAs } : {}),
139
+ ...(args.confirm ? { expectedSnapshot: args.confirm } : {}),
140
+ };
141
+ let response;
142
+ try {
143
+ response = await userRouteRequest({ commonApiUrl: auth.context.commonApiUrl, userToken: auth.context.userToken, fetchImpl: deps.fetchImpl }, `/workspaces/${encodeURIComponent(workspaceId)}/repository`, { method: 'POST', jsonBody: body });
144
+ }
145
+ catch (err) {
146
+ return { code: 1, stderr: `FAIL [http]: workspace.set_repository failed: ${err instanceof Error ? err.message : String(err)}` };
147
+ }
148
+ const text = await response.text().catch(() => '');
149
+ let parsed = null;
150
+ try {
151
+ parsed = JSON.parse(text);
152
+ }
153
+ catch { /* reported raw below */ }
154
+ if (args.json)
155
+ return { code: response.ok ? 0 : 1, stdout: text };
156
+ if (!parsed)
157
+ return { code: 1, stderr: `FAIL [http]: HTTP ${response.status} — ${text}` };
158
+ return response.ok ? { code: 0, stdout: formatSetRepository(parsed, args.url) } : { code: 1, stderr: formatSetRepository(parsed, args.url) };
159
+ }
160
+ /** `args` is everything after `workspace`. */
161
+ export async function runWorkspaceCmd(args, deps = {}) {
162
+ const sub = args[0];
163
+ if (!sub || sub === '--help' || sub === '-h' || sub === 'help') {
164
+ process.stdout.write(WORKSPACE_USAGE);
165
+ return sub ? 0 : 64;
166
+ }
167
+ if (sub !== 'set-repository') {
168
+ process.stderr.write(`yolo: unknown workspace subcommand '${sub}'\n${WORKSPACE_USAGE}`);
169
+ return 64;
170
+ }
171
+ if (args.slice(1).some((a) => a === '--help' || a === '-h')) {
172
+ process.stdout.write(SET_REPOSITORY_USAGE);
173
+ return 0;
174
+ }
175
+ const parsed = parseSetRepositoryArgs(args.slice(1));
176
+ if (!parsed.ok) {
177
+ process.stderr.write(`yolo: workspace set-repository: ${parsed.message}\n${SET_REPOSITORY_USAGE}`);
178
+ return 64;
179
+ }
180
+ const result = await runSetRepository(parsed, deps);
181
+ if (result.stdout)
182
+ process.stdout.write(`${result.stdout}\n`);
183
+ if (result.stderr)
184
+ process.stderr.write(`${result.stderr}\n`);
185
+ return result.code;
186
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yolo-labs/yolo-cli",
3
- "version": "0.45.1",
3
+ "version": "0.47.0",
4
4
  "description": "YOLO Studio CLI for workspace context, artifacts, personal apps and hosting.",
5
5
  "license": "MIT",
6
6
  "repository": {