@yolo-labs/yolo-cli 0.42.0 → 0.43.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.
@@ -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>] [--parent <id|slug>] [--json]
6
+ * yolo deploy init [--slug <slug>] [--type <static|worker>] [--parent <id|slug> | --no-parent] [--json]
7
7
  * yolo deploy status [--json]
8
8
  * yolo deploy logs [--tail] [--since <dur>] [--json]
9
9
  * yolo deploy rollback [releaseId] [--json]
@@ -36,14 +36,14 @@ function defaultStatPath(p) {
36
36
  }
37
37
  import { runDeployShip, exitCodeForFailure, formatShipSuccess, formatPending, formatFail, } from './deploy-ship.js';
38
38
  import { resolveDeployContext, createProject, getProjectStatus, listProjects, rollbackProject, unpublishProject, republishProject, renameProject, setProjectParent, addAlias, removeAlias, setRedirect, deleteProject, cloneProject, getLogs, pollTail, queryD1, } from './deploy-client.js';
39
- import { readDeployConfig, writeDeployConfig } from './deploy-config.js';
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';
42
42
  import { runDeployDev } from './deploy-dev.js';
43
43
  import { defaultReadFile } from './auth-context.js';
44
44
  const USAGE = [
45
45
  'Usage: yolo deploy [--env <staging|prod>] [--dry-run] [--json]',
46
- ' yolo deploy init [--slug <slug>] [--type <static|worker>] [--parent <id|slug>] [--json]',
46
+ ' yolo deploy init [--slug <slug>] [--type <static|worker>] [--parent <id|slug> | --no-parent] [--json]',
47
47
  ' yolo deploy link (--project-id <id> | --slug <slug>) [--type <static|worker>]',
48
48
  ' yolo deploy validate [--json]',
49
49
  ' yolo deploy doctor [--json]',
@@ -200,6 +200,7 @@ export function parseInitArgs(args) {
200
200
  let slug;
201
201
  let type;
202
202
  let parentProjectId;
203
+ let noParent = false;
203
204
  let jsonOutput = false;
204
205
  for (let i = 0; i < args.length; i++) {
205
206
  const a = args[i];
@@ -229,6 +230,9 @@ export function parseInitArgs(args) {
229
230
  return { ok: false, message: '--parent requires a project id' };
230
231
  parentProjectId = v;
231
232
  }
233
+ else if (a === '--no-parent') {
234
+ noParent = true;
235
+ }
232
236
  else if (a.startsWith('--parent=')) {
233
237
  parentProjectId = a.slice('--parent='.length);
234
238
  }
@@ -248,7 +252,12 @@ export function parseInitArgs(args) {
248
252
  if (parentProjectId !== undefined && parentProjectId.length === 0) {
249
253
  return { ok: false, message: '--parent requires a project id or slug' };
250
254
  }
251
- return { ok: true, slug, type, parentProjectId, jsonOutput };
255
+ // Refuse rather than pick a winner: the two flags express opposite intents,
256
+ // and silently honouring one would create a project the caller did not ask for.
257
+ if (noParent && parentProjectId !== undefined) {
258
+ return { ok: false, message: '--parent and --no-parent are mutually exclusive' };
259
+ }
260
+ return { ok: true, slug, type, parentProjectId, noParent, jsonOutput };
252
261
  }
253
262
  async function runInitCmd(args, deps, io) {
254
263
  const parsed = parseInitArgs(args);
@@ -268,6 +277,19 @@ async function runInitCmd(args, deps, io) {
268
277
  const cwd = deps.cwd ?? process.cwd();
269
278
  const readConfig = deps.readDeployConfigImpl ?? readDeployConfig;
270
279
  const writeConfig = deps.writeDeployConfigImpl ?? writeDeployConfig;
280
+ // 🚨 `deps.env` is a TEST SEAM, not the environment. The real CLI reaches here
281
+ // as `runDeployCmd(args)` with no deps at all (`cli.ts:739`), so `deps.env?.X`
282
+ // is always undefined in production — a shape that reads like an env lookup and
283
+ // silently is not one. `resolveDeployContext` already uses the `?? process.env`
284
+ // form; these two had not. Behind it were:
285
+ // - the ancestor walk's `$HOME` floor, which would have been DISABLED in
286
+ // production, permitting exactly the machine-wide capture it exists to stop;
287
+ // - `WORKSPACE_ID` on create, so a hosting project made by `yolo deploy init`
288
+ // inside a session pod has NEVER carried the `workspaceId` that routes deploy
289
+ // lifecycle events back to the workspace (and to VibeAssist watchers).
290
+ // Pre-existing, and dead since it shipped.
291
+ // Injection still wins, so tests are unaffected.
292
+ const env = deps.env ?? process.env;
271
293
  const readResult = readConfig(cwd);
272
294
  if (!readResult.ok) {
273
295
  // Never silently clobber a malformed/invalid link file.
@@ -283,7 +305,10 @@ async function runInitCmd(args, deps, io) {
283
305
  // 🚨 `--parent` on an ALREADY-LINKED directory would otherwise report
284
306
  // `already-linked` and exit 0, having silently ignored the flag — the same
285
307
  // false-success the slug-reconciliation guard below exists to prevent.
286
- // Parent links are create-only, so there is nothing `init` can do here.
308
+ // `init` itself can do nothing here — its parent link is create-only — but
309
+ // re-parenting IS possible since S5 (2026-08-09): `yolo deploy set-parent`.
310
+ // The advice below used to say there was no re-parent route at all, which
311
+ // sent people to recreate a project when one command would have done.
287
312
  const message = 'this directory is already linked to a project; --parent only applies when creating one';
288
313
  // JSON mode keeps stderr EMPTY — automation treats it as diagnostics, and
289
314
  // the init contract is a clean stream split.
@@ -295,8 +320,8 @@ async function runInitCmd(args, deps, io) {
295
320
  // Only advice that actually works: parent links are create-only and
296
321
  // there is no re-parent route or console control, so the recovery is
297
322
  // to create the child as a NEW project.
298
- + ' Nesting is set at creation. Create the child in its own directory with\n'
299
- + ' `yolo deploy init --parent <id|slug>`, or from the Hosting console\'s New project dialog.\n');
323
+ + ' To re-parent THIS project: `yolo deploy set-parent <id|slug>`.\n'
324
+ + ' To create a NEW child: `yolo deploy init --parent <id|slug>` in its own directory.\n');
300
325
  }
301
326
  return 1;
302
327
  }
@@ -358,6 +383,44 @@ async function runInitCmd(args, deps, io) {
358
383
  // Else: not a slug of ours, but id-shaped — pass through and let the
359
384
  // server's ownership-asserted read be the authority.
360
385
  }
386
+ // ── Inferred parent (nesting §10 S4) ────────────────────────────────────
387
+ // No `--parent` given: look UP for an ancestor that is already a hosting
388
+ // project. `yolo deploy init` inside `apps/api` otherwise mints a fully
389
+ // independent project named after the directory — which is exactly how
390
+ // `El Paso Ballroom API` came to sit as an unrelated top-level card beside the
391
+ // site it serves. The relationship already exists in the filesystem; this
392
+ // records it.
393
+ //
394
+ // 🚨 INFERRED IS BEST-EFFORT; EXPLICIT IS AUTHORITATIVE. An inference must
395
+ // never fail an `init` that would otherwise succeed, so the candidate is
396
+ // VALIDATED against the caller's own projects before use and simply dropped if
397
+ // it does not qualify. A bad `--parent`, by contrast, still fails loudly above
398
+ // — the user asked for that specific parent and did not get it.
399
+ let inferredParent;
400
+ if (!resolvedParentId && !parsed.noParent) {
401
+ const ancestor = findAncestorLink(cwd, deps.readFileImpl, { ...(env.HOME ? { home: env.HOME } : {}) });
402
+ if (ancestor) {
403
+ const listImpl = deps.listProjectsImpl ?? listProjects;
404
+ const listed = await listImpl(auth.context);
405
+ // A list failure is NOT a reason to fail: we are only looking for a
406
+ // default. Fall through and create a root.
407
+ if (listed.ok) {
408
+ const match = listed.value.find((p) => resolveProjectId(p) === ancestor.projectId);
409
+ // Roots only, and only a project in a state the server will accept as a
410
+ // parent — the same rule the console's picker applies. Anything else is
411
+ // dropped silently: it is a suggestion, not an instruction.
412
+ const parentOfParent = match ? match.parentProjectId : undefined;
413
+ const status = match ? str(match.status) : undefined;
414
+ const eligible = !!match
415
+ && (parentOfParent === null || parentOfParent === undefined)
416
+ && (status === undefined || status === 'active' || status === 'published');
417
+ if (eligible) {
418
+ resolvedParentId = ancestor.projectId;
419
+ inferredParent = { link: ancestor, ...(str(match.slug) ? { slug: str(match.slug) } : {}) };
420
+ }
421
+ }
422
+ }
423
+ }
361
424
  const create = deps.createProjectImpl ?? createProject;
362
425
  const created = await create(auth.context, {
363
426
  name: parsed.slug ?? path.basename(cwd),
@@ -366,7 +429,7 @@ async function runInitCmd(args, deps, io) {
366
429
  // lets server-side deploy lifecycle events route back to the workspace
367
430
  // (and therefore to VibeAssist event watchers). Local CLI use remains
368
431
  // unchanged because the field is optional.
369
- ...(deps.env?.WORKSPACE_ID ? { workspaceId: deps.env.WORKSPACE_ID } : {}),
432
+ ...(env.WORKSPACE_ID ? { workspaceId: env.WORKSPACE_ID } : {}),
370
433
  // Nesting S4 — passed straight through; the server verifies ownership,
371
434
  // depth and parent state. Not written to `.yolo/deploy.json`.
372
435
  ...(resolvedParentId ? { parentProjectId: resolvedParentId } : {}),
@@ -399,6 +462,21 @@ async function runInitCmd(args, deps, io) {
399
462
  && str(owned?.parentProjectId)?.toLowerCase()
400
463
  !== resolvedParentId?.toLowerCase();
401
464
  if (projectId && !parentMismatch) {
465
+ // 🚨 An INFERRED parent must not silently evaporate here (codex P2).
466
+ // Reconciliation is still right — refusing would strand a project the
467
+ // caller already owns, which `init` must never do, and parent links
468
+ // are create-only so this path cannot apply one. But the caller was
469
+ // about to get a nested project and is instead getting a link to an
470
+ // existing one that may sit elsewhere in the tree. Say so, and name
471
+ // the command that closes the gap.
472
+ const existingParent = str(owned?.parentProjectId);
473
+ const inferenceLost = !!inferredParent
474
+ && existingParent?.toLowerCase() !== resolvedParentId?.toLowerCase();
475
+ if (inferenceLost && !parsed.jsonOutput) {
476
+ io.out(`note: this project already existed and is NOT under ${inferredParent.slug ?? resolvedParentId}.\n`
477
+ + ` Nesting was inferred from ${inferredParent.link.path} but only applies when creating.\n`
478
+ + ` Run \`yolo deploy set-parent ${inferredParent.slug ?? resolvedParentId}\` to nest it.\n`);
479
+ }
402
480
  return writeLinkFile(cwd, writeConfig, io, {
403
481
  projectId,
404
482
  slug: str(owned.slug) ?? takenSlug,
@@ -407,6 +485,9 @@ async function runInitCmd(args, deps, io) {
407
485
  adapted,
408
486
  jsonOutput: parsed.jsonOutput,
409
487
  jsonStatus: 'linked-existing',
488
+ // Machine callers get the same fact as a field, never a claim
489
+ // that the nesting happened.
490
+ ...(inferenceLost ? { parentNotApplied: resolvedParentId } : {}),
410
491
  }, `OK: slug '${takenSlug}' was already yours — linked existing project ${projectId} — wrote .yolo/deploy.json`);
411
492
  }
412
493
  }
@@ -429,7 +510,29 @@ async function runInitCmd(args, deps, io) {
429
510
  io.err(`${formatFail(failure)}\n`);
430
511
  return 2;
431
512
  }
432
- 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`);
513
+ // 🚨 SAY SO. A parent nobody asked for, applied silently, is the worst
514
+ // outcome available here — the caller would only discover the nesting from
515
+ // the console. Human mode names the ancestor file it came from and the exact
516
+ // command to undo it; JSON mode carries the same facts as fields.
517
+ if (inferredParent && !parsed.jsonOutput) {
518
+ const label = inferredParent.slug ? `${inferredParent.slug} (${resolvedParentId})` : resolvedParentId;
519
+ io.out(`note: nested under ${label}, inferred from ${inferredParent.link.path}\n`
520
+ + ' Use --no-parent to create a top-level project instead,\n'
521
+ + ' or `yolo deploy set-parent --none` to detach this one.\n');
522
+ }
523
+ return writeLinkFile(cwd, writeConfig, io, {
524
+ projectId,
525
+ slug,
526
+ type: parsed.type,
527
+ existing,
528
+ adapted,
529
+ jsonOutput: parsed.jsonOutput,
530
+ jsonStatus: 'created',
531
+ ...(resolvedParentId ? { parentProjectId: resolvedParentId } : {}),
532
+ ...(inferredParent
533
+ ? { parentInferredFrom: inferredParent.link.path }
534
+ : {}),
535
+ }, `OK: linked project ${projectId}${slug ? ` (slug ${slug})` : ''} — wrote .yolo/deploy.json`);
433
536
  }
434
537
  export function parseLinkArgs(args) {
435
538
  let projectId;
@@ -1889,6 +1992,13 @@ function writeLinkFile(cwd, writeConfig, io, params, message) {
1889
1992
  ...(params.slug ? { slug: params.slug } : {}),
1890
1993
  ...(params.type ? { type: params.type } : {}),
1891
1994
  configPath: '.yolo/deploy.json',
1995
+ // Nesting is invisible in `.yolo/deploy.json` by design (the link lives
1996
+ // on the project document), so JSON callers would have no way to see it
1997
+ // happened. `parentInferredFrom` is present ONLY when the CLI chose the
1998
+ // parent — its absence means the caller asked for it or there is none.
1999
+ ...(params.parentProjectId ? { parentProjectId: params.parentProjectId } : {}),
2000
+ ...(params.parentInferredFrom ? { parentInferredFrom: params.parentInferredFrom } : {}),
2001
+ ...(params.parentNotApplied ? { parentNotApplied: params.parentNotApplied } : {}),
1892
2002
  ...(params.adapted
1893
2003
  ? { adapted: { sourceFile: params.adapted.sourceFile, migrated: params.adapted.migrated, warnings: params.adapted.warnings } }
1894
2004
  : {}),
@@ -26,7 +26,7 @@
26
26
  * (e.g. `compatibilityDate`, which the platform fixes and does not read)
27
27
  * surfaces in `yolo deploy validate` instead of misleading the author.
28
28
  */
29
- import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
29
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
30
30
  import path from 'node:path';
31
31
  export class DeployConfigError extends Error {
32
32
  code;
@@ -43,6 +43,85 @@ export class DeployConfigError extends Error {
43
43
  export function deployConfigPath(cwd) {
44
44
  return path.join(cwd, '.yolo', 'deploy.json');
45
45
  }
46
+ /** How far up to look before giving up. A backstop against a pathological tree. */
47
+ const ANCESTOR_WALK_MAX_DEPTH = 24;
48
+ /**
49
+ * Walk UP from `cwd` looking for an ancestor already linked to a hosting project.
50
+ *
51
+ * WHY: `yolo deploy init` inside `apps/api` mints a fully independent project
52
+ * named after the directory — which is exactly how `El Paso Ballroom API` came
53
+ * to exist as an unrelated top-level card next to the site it serves. The
54
+ * relationship already exists in the filesystem; nothing recorded it. This finds
55
+ * it so `init` can offer it (nesting plan §10 S4).
56
+ *
57
+ * 🚨 THE STOP CONDITIONS ARE THE DESIGN. An unbounded walk is actively harmful:
58
+ *
59
+ * - **Never `cwd` itself.** That is the already-linked case, which `init`
60
+ * handles separately; treating it as an ancestor would make every project
61
+ * its own parent.
62
+ * - **Stop at a `.git` directory.** That is the repo boundary and therefore
63
+ * the monorepo boundary. The repo root is CHECKED first and only then
64
+ * becomes a stopping point, so a deployed monorepo root is still found.
65
+ * - **Stop BEFORE `$HOME`, and never inspect it.** Someone who once ran
66
+ * `yolo deploy init` in their home directory would otherwise have every
67
+ * future project on the machine silently adopted by that one — a
68
+ * machine-wide capture from a single stray file.
69
+ * - **Depth cap** as a backstop, and the filesystem root always terminates.
70
+ *
71
+ * Pure and injectable so the walk is testable without touching a real tree.
72
+ */
73
+ export function findAncestorDeployLink(cwd, readFileImpl = defaultReadFile, opts = {}) {
74
+ const exists = opts.existsImpl ?? ((p) => existsSync(p));
75
+ const maxDepth = opts.maxDepth ?? ANCESTOR_WALK_MAX_DEPTH;
76
+ const home = opts.home ? path.resolve(opts.home) : undefined;
77
+ const start = path.resolve(cwd);
78
+ // The repo boundary applies to `cwd` ITSELF (codex P2). Running `init` at the
79
+ // root of a nested repository would otherwise begin the walk one level ABOVE
80
+ // it and adopt a parent from the enclosing tree — crossing exactly the
81
+ // boundary the ancestor-level check below exists to hold.
82
+ if (exists(path.join(start, '.git')))
83
+ return null;
84
+ let dir = path.dirname(start);
85
+ for (let depth = 0; depth < maxDepth; depth += 1) {
86
+ // Home is a hard FLOOR: reaching it ends the walk, and it is never
87
+ // inspected. Walking upward from anywhere inside home always arrives here
88
+ // before `/`, so this one check covers the whole case — an earlier version
89
+ // tried to test "is dir inside home" and had the sense inverted, which
90
+ // refused every directory UNDER home and quietly disabled the feature for
91
+ // every user whose repos live there (i.e. almost all of them).
92
+ if (home && dir === home)
93
+ return null;
94
+ const filePath = deployConfigPath(dir);
95
+ const text = readFileImpl(filePath);
96
+ if (text !== undefined && text.trim() !== '') {
97
+ try {
98
+ const parsed = JSON.parse(text);
99
+ if (typeof parsed.projectId === 'string' && parsed.projectId.length > 0) {
100
+ return {
101
+ projectId: parsed.projectId,
102
+ ...(typeof parsed.slug === 'string' && parsed.slug ? { slug: parsed.slug } : {}),
103
+ dir,
104
+ path: filePath,
105
+ };
106
+ }
107
+ }
108
+ catch {
109
+ // A malformed ancestor link is not this command's problem to report —
110
+ // it belongs to that directory, and failing `init` here would block a
111
+ // child on a file the user may not even know exists. Keep walking.
112
+ }
113
+ }
114
+ // Repo boundary. Checked AFTER the link above so a deployed monorepo root
115
+ // still counts as an ancestor.
116
+ if (exists(path.join(dir, '.git')))
117
+ return null;
118
+ const parent = path.dirname(dir);
119
+ if (parent === dir)
120
+ return null; // filesystem root
121
+ dir = parent;
122
+ }
123
+ return null;
124
+ }
46
125
  /**
47
126
  * Read `.yolo/deploy.json` from a project root. Absent file is the
48
127
  * non-error `{ ok: true, config: null }` case (detection falls through
@@ -12,8 +12,8 @@
12
12
  * keyed by that workspaceId — `--workspace` is optional in containers
13
13
  * because the session record IS the source of truth.
14
14
  *
15
- * 2. `authenticatedRequest` is the helper used by `yolo plan
16
- * import/export` (8c.3+) to call `/internal/work/*`. It sends
15
+ * 2. `authenticatedRequest` is the helper used by `yolo run list` /
16
+ * `yolo artifact get/list` to call `/internal/work/*`. It sends
17
17
  * `Authorization: Bearer <delegated>` — the delegated MCP token is the
18
18
  * capability (the per-agent allowedScopes check at the work routes is
19
19
  * satisfied by the token's claims). The CLI is user-JWT-only; the
@@ -25,32 +25,29 @@
25
25
  * globally — `engines: ">=20"` is pinned in package.json.
26
26
  *
27
27
  * Substrate-CLI v1 scopes (capped per agents.json `substrate-cli`):
28
- * - Plan authoring: work.create_plan, work.update_plan,
29
- * work.get_plan, work.list_plans
30
28
  * - Run lifecycle: work.start_run, work.get_run,
31
29
  * work.list_runs, work.pause_run, work.resume_run,
32
30
  * work.cancel_run, work.transfer_run_operator
33
31
  * - Artifact reads: work.get_artifact, work.list_artifacts, work.transfer_run_operator
34
32
  *
33
+ * (The Plan-authoring scopes — work.create_plan/update_plan/get_plan/
34
+ * list_plans — backed `yolo plan import/export/get/list/open/activate/
35
+ * archive`. Those subcommands had no backing `/internal/work` route and
36
+ * were removed as dead CLI surface during the Plan Run substrate
37
+ * tear-down; `SUBSTRATE_CLI_PLAN_SCOPES` was removed with them. `yolo
38
+ * plan validate` is unaffected — it's a pure offline file check with no
39
+ * network call and no scope requirement.)
40
+ *
35
41
  * Run-lifecycle implication: `work.start_run` binds the calling agent
36
- * as the Run's Operator (route handler, Phase 4/6 R4). So a Run started
37
- * via `yolo run start` has `operatorAgentId === 'substrate-cli'`, and
38
- * only the substrate CLI can pause/resume/cancel it via MCP. The
39
- * natural handoff loop is `yolo run transfer <runId> --to claude` —
40
- * substrate-cli is the current Operator, claude/codex is an
41
- * Operator-tier target, route's R4 self-transfer path applies.
42
- * Substrate-cli is NOT itself Operator-tier (per
43
- * `OPERATOR_TIER_AGENT_IDS` in operator-binding.ts), so `--to
44
- * substrate-cli` is rejected by the route's `isValidOperatorTarget`
45
- * check.
42
+ * as the Run's Operator (route handler, Phase 4/6 R4). Historically a Run
43
+ * started via `yolo run start` had `operatorAgentId === 'substrate-cli'`,
44
+ * and only the substrate CLI could pause/resume/cancel it via MCP, with
45
+ * `yolo run transfer <runId> --to claude` as the handoff. `run start`,
46
+ * `run get`, `run pause/resume/cancel`, and `run transfer` were all
47
+ * removed as dead CLI surface (no backing route) in the same tear-down;
48
+ * `yolo run list` is the only survivor.
46
49
  */
47
50
  export const SUBSTRATE_CLI_AGENT_ID = 'substrate-cli';
48
- export const SUBSTRATE_CLI_PLAN_SCOPES = [
49
- 'work.create_plan',
50
- 'work.update_plan',
51
- 'work.get_plan',
52
- 'work.list_plans',
53
- ];
54
51
  export const SUBSTRATE_CLI_RUN_SCOPES = [
55
52
  'work.start_run',
56
53
  'work.get_run',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yolo-labs/yolo-cli",
3
- "version": "0.42.0",
3
+ "version": "0.43.0",
4
4
  "description": "YOLO Studio substrate CLI \u2014 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",
package/dist/plan-diff.js DELETED
@@ -1,162 +0,0 @@
1
- /**
2
- * Plan diff → mutations (Phase 8c.3 helper).
3
- *
4
- * Given the DB's current Plan and the parsed-from-file Plan,
5
- * compute the mutation list that `work.update_plan` needs to bring
6
- * the DB into the file's state. Pure — no I/O, no Mongo, no fetch.
7
- *
8
- * Mutation shapes match `common-api/src/services/work/plan-mutations.ts`:
9
- *
10
- * { op: 'set-plan-fields', fields: { name?, description?, inputs?,
11
- * failurePolicy?, autoRetryCap?, autoRetryFallback?, integrationPolicy? } }
12
- * { op: 'add-step', step: StepDefinition }
13
- * { op: 'update-step', stepId: string, fields: <full new step shape, used as patch> }
14
- * { op: 'remove-step', stepId: string }
15
- * { op: 'set-state', state: 'draft' | 'active' | 'archived' }
16
- *
17
- * Re-import strategy notes:
18
- * - Top-level fields: emit `set-plan-fields` with only the fields
19
- * that differ. Compared via canonical JSON for inputs /
20
- * integrationPolicy (free-form objects); primitive equality for
21
- * scalars. The substrate validator at the Worker tier ignores any
22
- * field absent from the patch, so this is safe to send selectively.
23
- * - Steps: emit add/remove/update by stepId. `update-step.fields` is
24
- * the FULL new step shape used as a patch — the substrate's
25
- * `applyAndValidateStepPatch` re-validates after applying, so
26
- * sending the whole shape is equivalent to a per-step replace.
27
- * - Step ORDER inside the file is NOT enforced as a diff target in
28
- * v1: the substrate's executor reads `gate.config.requires`, not
29
- * array order, so reordering is semantically a no-op. New steps
30
- * from `add-step` land at the end of the array. (A later phase
31
- * can add `reorder-steps` if a UI reason emerges.)
32
- * - Description: the design says body IS Plan.description (no
33
- * frontmatter description field). The caller passes the body as
34
- * `filePlan.description`; the diff treats it as a regular
35
- * top-level string field.
36
- * - state: emit `set-state` only if the file's state differs from
37
- * the DB. Substrate-side validates the transition; this layer
38
- * just produces the request. (Renamed from `authoringState` /
39
- * `set-authoring-state` 2026-05-09 — item 17.)
40
- *
41
- * Input shape:
42
- * - `dbPlan` = the response from `work.get_plan` (already validated
43
- * by common-api).
44
- * - `filePlan` = the validated frontmatter object plus the body
45
- * string used as `description`.
46
- */
47
- /**
48
- * Top-level fields that round-trip through `set-plan-fields`. Order
49
- * matters for nothing here — we compare by name and emit only deltas.
50
- */
51
- const TOP_LEVEL_DIFF_FIELDS = [
52
- 'name',
53
- 'description',
54
- 'failurePolicy',
55
- 'autoRetryCap',
56
- 'autoRetryFallback',
57
- 'inputs',
58
- 'integrationPolicy',
59
- ];
60
- /**
61
- * Compute the mutation list required to bring `dbPlan` to match
62
- * `filePlan`. Empty array means "nothing to do". The caller is
63
- * responsible for guarding on `filePlan.planId === dbPlan.planId`
64
- * before calling this — diff doesn't cross identity.
65
- */
66
- export function computeMutations(dbPlan, filePlan) {
67
- const mutations = [];
68
- // 1) Top-level fields (set-plan-fields)
69
- const fieldDelta = {};
70
- for (const field of TOP_LEVEL_DIFF_FIELDS) {
71
- const fileValue = filePlan[field];
72
- const dbValue = dbPlan[field];
73
- if (!equalDeep(fileValue, dbValue)) {
74
- // Server validator coerces null → undefined for description; we
75
- // mirror that here so the produced mutation is what the route
76
- // already accepts.
77
- fieldDelta[field] = fileValue ?? undefined;
78
- }
79
- }
80
- if (Object.keys(fieldDelta).length > 0) {
81
- mutations.push({ op: 'set-plan-fields', fields: fieldDelta });
82
- }
83
- // 2) Steps diff (add / update / remove)
84
- const dbStepIndex = new Map();
85
- for (const step of dbPlan.steps) {
86
- const id = step.stepId;
87
- if (typeof id === 'string')
88
- dbStepIndex.set(id, step);
89
- }
90
- const fileStepIds = new Set();
91
- for (const step of filePlan.steps) {
92
- const id = step.stepId;
93
- if (typeof id !== 'string')
94
- continue;
95
- fileStepIds.add(id);
96
- const dbStep = dbStepIndex.get(id);
97
- if (!dbStep) {
98
- mutations.push({ op: 'add-step', step });
99
- }
100
- else if (!equalDeep(step, dbStep)) {
101
- mutations.push({ op: 'update-step', stepId: id, fields: step });
102
- }
103
- }
104
- for (const id of dbStepIndex.keys()) {
105
- if (!fileStepIds.has(id)) {
106
- mutations.push({ op: 'remove-step', stepId: id });
107
- }
108
- }
109
- // 3) Plan state (set-state)
110
- if (filePlan.state !== dbPlan.state) {
111
- mutations.push({ op: 'set-state', state: filePlan.state });
112
- }
113
- return mutations;
114
- }
115
- // ─── Internals ────────────────────────────────────────────────────────────
116
- /**
117
- * Structural equality for the value shapes that show up in plan
118
- * frontmatter: strings / numbers / booleans / null / undefined / arrays
119
- * of same / plain objects of same. NOT a general-purpose deep equality;
120
- * doesn't handle Date, RegExp, Map, Set, class instances. None of those
121
- * appear in the file → DB diff path because we're comparing JSON-shaped
122
- * data on both sides.
123
- *
124
- * Treats `undefined` and missing keys identically, so a file that omits
125
- * `autoRetryCap` matches a DB where `autoRetryCap: undefined`. Treats
126
- * `null` and `undefined` as equal too — the substrate validator
127
- * normalizes both ways.
128
- */
129
- function equalDeep(a, b) {
130
- if (a === b)
131
- return true;
132
- if (a == null && b == null)
133
- return true; // null/undefined normalize
134
- if (a == null || b == null)
135
- return false;
136
- if (typeof a !== typeof b)
137
- return false;
138
- if (typeof a !== 'object')
139
- return false;
140
- if (Array.isArray(a) !== Array.isArray(b))
141
- return false;
142
- if (Array.isArray(a) && Array.isArray(b)) {
143
- if (a.length !== b.length)
144
- return false;
145
- for (let i = 0; i < a.length; i++)
146
- if (!equalDeep(a[i], b[i]))
147
- return false;
148
- return true;
149
- }
150
- const ao = a;
151
- const bo = b;
152
- // Ignore keys whose values are undefined — they're equivalent to absent.
153
- const aKeys = Object.keys(ao).filter((k) => ao[k] !== undefined);
154
- const bKeys = Object.keys(bo).filter((k) => bo[k] !== undefined);
155
- if (aKeys.length !== bKeys.length)
156
- return false;
157
- for (const k of aKeys) {
158
- if (!equalDeep(ao[k], bo[k]))
159
- return false;
160
- }
161
- return true;
162
- }