@yolo-labs/yolo-cli 0.42.1 → 0.44.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.
@@ -0,0 +1,145 @@
1
+ /** Session-bound CLI for the workspace-owned branch preview service. */
2
+ import { resolveSubstrateContext } from './auth-context.js';
3
+ import { mintSubstrateToken } from './work-client.js';
4
+ export const PREVIEW_HELP = `Usage:
5
+ yolo preview create --name <name> --branch <branch> --command <command> [options]
6
+ yolo preview status [tile-id] [--json]
7
+ yolo preview logs <tile-id> [--tail 50] [--json]
8
+ yolo preview stop <tile-id> [--json]
9
+
10
+ Create options:
11
+ --cwd <dir> Repository-relative app directory (default: .)
12
+ --setup <command> Install dependencies in each candidate checkout
13
+ --build <command> Build each candidate
14
+ --health-path <path> Readiness endpoint (default: /)
15
+ --port <auto|number> Public preview port (default: auto)
16
+ --poll-seconds <n> Branch polling interval, 5..3600 (default: 30)
17
+ --timeout-seconds <n> Setup/build timeout, 1..1800 (default: 300)
18
+ --ready-seconds <n> Server readiness timeout, 1..300 (default: 60)
19
+ --wait-for <path> Repository-relative file to wait for on the branch
20
+ before checkout/build (e.g. app/package.json)
21
+ --request-id <id> Reuse for retrying the same create request
22
+ --desktop <id> Destination desktop
23
+ --json Print structured output
24
+
25
+ Run inside a Studio workspace. Quote commands so $PORT and $HOST reach the
26
+ managed server unchanged. Stop keeps the tile and prevents automatic restart.
27
+ `;
28
+ function parse(args) {
29
+ const action = args[0];
30
+ if (!['create', 'status', 'logs', 'stop'].includes(action || ''))
31
+ throw new Error('Choose create, status, logs, or stop');
32
+ const values = {};
33
+ 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'] : [];
35
+ for (let i = 1; i < args.length; i++) {
36
+ const arg = args[i];
37
+ if (arg === '--json') {
38
+ json = true;
39
+ continue;
40
+ }
41
+ if (!arg.startsWith('-')) {
42
+ if (action === 'create' || id)
43
+ throw new Error(`Unexpected argument: ${arg}`);
44
+ id = arg;
45
+ continue;
46
+ }
47
+ const match = /^--([^=]+)(?:=(.*))?$/.exec(arg);
48
+ if (!match || !allowed.includes(match[1]))
49
+ throw new Error(`Unknown option: ${arg}`);
50
+ const key = match[1];
51
+ if (values[key] !== undefined)
52
+ throw new Error(`Repeated option: --${key}`);
53
+ const value = match[2] ?? args[++i];
54
+ if (!value || (match[2] === undefined && value.startsWith('--')))
55
+ throw new Error(`--${key} requires a value`);
56
+ values[key] = value;
57
+ }
58
+ if (id && !/^[a-zA-Z0-9_-]{1,128}$/.test(id))
59
+ throw new Error('Invalid preview tile ID');
60
+ if ((action === 'logs' || action === 'stop') && !id)
61
+ throw new Error(`${action} requires a preview tile ID`);
62
+ const number = (key, min, max, fallback) => {
63
+ const raw = values[key];
64
+ if (raw === undefined)
65
+ return fallback;
66
+ const n = Number(raw);
67
+ if (!/^\d+$/.test(raw) || !Number.isInteger(n) || n < min || n > max)
68
+ throw new Error(`--${key} must be an integer in ${min}..${max}`);
69
+ return n;
70
+ };
71
+ const result = { action: action, id, json, tail: number('tail', 1, 200, 50) };
72
+ if (action === 'create') {
73
+ for (const key of ['name', 'branch', 'command'])
74
+ if (!values[key]?.trim())
75
+ throw new Error(`--${key} is required`);
76
+ const cwd = values.cwd || '.';
77
+ if (cwd.startsWith('/') || cwd.split(/[\\/]/).includes('..'))
78
+ throw new Error('--cwd must stay inside the repository');
79
+ const waitFor = values['wait-for'];
80
+ if (waitFor !== undefined && (waitFor.length > 1024 || waitFor.startsWith('/') || waitFor.split(/[\\/]/).includes('..') || /[\r\n]/.test(waitFor)))
81
+ throw new Error('--wait-for must be a repository-relative path');
82
+ result.body = { name: values.name, command: values.command, cwd,
83
+ port: !values.port || values.port === 'auto' ? 'auto' : number('port', 1024, 65535, 3100),
84
+ ...(values['request-id'] && { requestId: values['request-id'] }), ...(values.desktop && { desktopId: values.desktop }),
85
+ followBranch: { branch: values.branch, ...(values.setup && { setup: values.setup }), ...(values.build && { build: values.build }),
86
+ healthPath: values['health-path'] || '/', pollSeconds: number('poll-seconds', 5, 3600, 30),
87
+ timeoutSeconds: number('timeout-seconds', 1, 1800, 300), readySeconds: number('ready-seconds', 1, 300, 60),
88
+ ...(waitFor && { waitFor }) } };
89
+ }
90
+ return result;
91
+ }
92
+ export async function runPreviewCmd(args, deps = {}) {
93
+ const out = deps.stdout ?? (text => process.stdout.write(text));
94
+ const err = deps.stderr ?? (text => process.stderr.write(text));
95
+ if (args[0] === '--help' || args[0] === '-h' || args.slice(1).includes('--help')) {
96
+ out(PREVIEW_HELP);
97
+ return 0;
98
+ }
99
+ let input;
100
+ try {
101
+ input = parse(args);
102
+ }
103
+ catch (error) {
104
+ err(`yolo preview: ${error.message}\n${PREVIEW_HELP}`);
105
+ return 64;
106
+ }
107
+ const auth = resolveSubstrateContext(deps.env ?? process.env);
108
+ if (!auth.ok) {
109
+ err(`yolo preview: ${auth.message}\n`);
110
+ return 78;
111
+ }
112
+ try {
113
+ const scope = input.action === 'create' ? 'studio.create_preview' : input.action === 'stop' ? 'studio.stop_preview' : 'studio.read_preview';
114
+ const token = await mintSubstrateToken({ ...auth.context, scopes: [scope], fetchImpl: deps.fetchImpl });
115
+ const base = `${auth.context.commonApiUrl.replace(/\/+$/, '')}/internal/mcp/workspaces/${encodeURIComponent(token.workspaceId)}`;
116
+ const route = input.action === 'create' ? '/tiles/preview' : input.action === 'status'
117
+ ? `/previews${input.id ? `/${encodeURIComponent(input.id)}` : ''}`
118
+ : `/previews/${encodeURIComponent(input.id)}/${input.action}${input.action === 'logs' ? `?tail=${input.tail}` : ''}`;
119
+ const response = await (deps.fetchImpl ?? globalThis.fetch)(base + route, {
120
+ method: input.action === 'create' || input.action === 'stop' ? 'POST' : 'GET',
121
+ headers: { Authorization: `Bearer ${token.token}`, 'Content-Type': 'application/json' },
122
+ ...(input.body && { body: JSON.stringify(input.body) }),
123
+ });
124
+ const body = await response.json();
125
+ if (!response.ok)
126
+ throw new Error(`${body.code || response.status}: ${body.error || 'Preview request failed'}`);
127
+ if (input.json)
128
+ out(JSON.stringify(body, null, 2) + '\n');
129
+ else if (input.action === 'create')
130
+ 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
+ else if (input.action === 'stop')
132
+ out(`Stopped preview ${input.id}. The tile is retained.\n`);
133
+ else if (input.action === 'logs')
134
+ out((body.lines?.map((line) => line.text).join('') || '(no logs)') + '\n');
135
+ else {
136
+ 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');
138
+ }
139
+ return 0;
140
+ }
141
+ catch (error) {
142
+ err(`yolo preview: ${error.message}\n`);
143
+ return 1;
144
+ }
145
+ }
@@ -360,11 +360,11 @@ function loadDockerignore(contextDir) {
360
360
  if (/[*?]/.test(line)) {
361
361
  const re = new RegExp('^' + line.split('').map((ch) => {
362
362
  if (ch === '*')
363
- return 'STAR';
363
+ return '\x00STAR\x00';
364
364
  if (ch === '?')
365
365
  return '[^/]';
366
366
  return ch.replace(/[.+^${}()|[\]\\]/g, '\\$&');
367
- }).join('').replace(/STARSTAR/g, '.*').replace(/STAR/g, '[^/]*') + '$');
367
+ }).join('').replace(/\x00STAR\x00\x00STAR\x00/g, '.*').replace(/\x00STAR\x00/g, '[^/]*') + '$');
368
368
  // Slash-less glob (`*.log`) matches by BASENAME at any depth; a glob with
369
369
  // `/` matches the full path.
370
370
  rules.push({ negate, test: (rel) => hasSlash ? re.test(rel) : re.test(rel.split('/').pop() ?? rel) });
@@ -134,6 +134,10 @@ export function parsePermissionShape(raw) {
134
134
  if (action || !arg)
135
135
  return null; // arg = KEY_NAME (preset membership checked server-side)
136
136
  return { raw, namespace: 'secret', action: arg };
137
+ case 'notifications':
138
+ if (head !== 'notifications.send' || (arg !== 'global' && arg !== 'workspace'))
139
+ return null;
140
+ return { raw, namespace: 'notifications', action, arg };
137
141
  case 'device':
138
142
  if (!action)
139
143
  return null;
@@ -247,6 +251,8 @@ export function validateManifest(raw, opts = {}) {
247
251
  errors.push('changelog must be a string when present');
248
252
  if (raw.featured !== undefined && typeof raw.featured !== 'boolean')
249
253
  errors.push('featured must be a boolean when present');
254
+ if (raw.marketplaceListed !== undefined && typeof raw.marketplaceListed !== 'boolean')
255
+ errors.push('marketplaceListed must be a boolean when present');
250
256
  if (raw.pricing !== undefined) {
251
257
  const p = raw.pricing;
252
258
  if (!isObj(p)) {
@@ -1,62 +1,5 @@
1
- /**
2
- * Substrate-CLI work client (Phase 8c.2).
3
- *
4
- * Replaces the 8a Group 9 scaffold stub with the real auth flow:
5
- *
6
- * 1. `mintSubstrateToken` POSTs to `/internal/mcp/tokens` with
7
- * `Authorization: Bearer <user JWT>` and the session-bound payload
8
- * `{ sessionId, agentId: 'substrate-cli', scopes: [...] }`. The endpoint
9
- * (`internalOrUserAuth`) verifies the JWT's userId owns the session,
10
- * derives `workspaceId`, and returns a delegated JWT in `result.token`
11
- * plus `result.claims.workspaceId`. The substrate CLI's lockfile is
12
- * keyed by that workspaceId — `--workspace` is optional in containers
13
- * because the session record IS the source of truth.
14
- *
15
- * 2. `authenticatedRequest` is the helper used by `yolo run list` /
16
- * `yolo artifact get/list` to call `/internal/work/*`. It sends
17
- * `Authorization: Bearer <delegated>` — the delegated MCP token is the
18
- * capability (the per-agent allowedScopes check at the work routes is
19
- * satisfied by the token's claims). The CLI is user-JWT-only; the
20
- * INTERNAL_API_KEY / X-Internal-Auth path was removed.
21
- *
22
- * Both calls take an injectable `fetchImpl` so unit tests can stub
23
- * the transport without touching real `globalThis.fetch`. In v1 the
24
- * substrate CLI requires Node 20+, which guarantees `fetch` exists
25
- * globally — `engines: ">=20"` is pinned in package.json.
26
- *
27
- * Substrate-CLI v1 scopes (capped per agents.json `substrate-cli`):
28
- * - Run lifecycle: work.start_run, work.get_run,
29
- * work.list_runs, work.pause_run, work.resume_run,
30
- * work.cancel_run, work.transfer_run_operator
31
- * - Artifact reads: work.get_artifact, work.list_artifacts, work.transfer_run_operator
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
- *
41
- * Run-lifecycle implication: `work.start_run` binds the calling agent
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.
49
- */
1
+ /** Session-bound delegated authentication and workspace artifact transport. */
50
2
  export const SUBSTRATE_CLI_AGENT_ID = 'substrate-cli';
51
- export const SUBSTRATE_CLI_RUN_SCOPES = [
52
- 'work.start_run',
53
- 'work.get_run',
54
- 'work.list_runs',
55
- 'work.pause_run',
56
- 'work.resume_run',
57
- 'work.cancel_run',
58
- 'work.transfer_run_operator',
59
- ];
60
3
  export const SUBSTRATE_CLI_ARTIFACT_SCOPES = [
61
4
  'work.get_artifact',
62
5
  'work.list_artifacts',
@@ -157,7 +100,11 @@ export async function authenticatedRequest(options, workPath, init = {}) {
157
100
  method: init.method ?? 'GET',
158
101
  headers,
159
102
  };
160
- if (init.jsonBody !== undefined) {
103
+ if (init.rawBody !== undefined) {
104
+ headers['Content-Type'] = 'application/json';
105
+ fetchInit.body = init.rawBody;
106
+ }
107
+ else if (init.jsonBody !== undefined) {
161
108
  headers['Content-Type'] = 'application/json';
162
109
  fetchInit.body = JSON.stringify(init.jsonBody);
163
110
  }
@@ -181,7 +128,11 @@ export async function userRouteRequest(options, routePath, init = {}) {
181
128
  method: init.method ?? 'GET',
182
129
  headers,
183
130
  };
184
- if (init.jsonBody !== undefined) {
131
+ if (init.rawBody !== undefined) {
132
+ headers['Content-Type'] = 'application/json';
133
+ fetchInit.body = init.rawBody;
134
+ }
135
+ else if (init.jsonBody !== undefined) {
185
136
  headers['Content-Type'] = 'application/json';
186
137
  fetchInit.body = JSON.stringify(init.jsonBody);
187
138
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@yolo-labs/yolo-cli",
3
- "version": "0.42.1",
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).",
3
+ "version": "0.44.0",
4
+ "description": "YOLO Studio CLI for workspace context, artifacts, personal apps and hosting.",
5
5
  "license": "MIT",
6
6
  "type": "module",
7
7
  "bin": {
@@ -18,7 +18,7 @@
18
18
  "README.md"
19
19
  ],
20
20
  "scripts": {
21
- "build": "tsc -p tsconfig.json && cp src/plan-frontmatter.schema.json dist/ && node scripts/build-vendored-flexdb.mjs",
21
+ "build": "rm -rf dist && tsc -p tsconfig.json && node scripts/build-vendored-flexdb.mjs",
22
22
  "test": "npm run build && node --test --test-reporter=spec dist/*.test.js",
23
23
  "clean": "rm -rf dist",
24
24
  "prepublishOnly": "npm test"
@@ -27,14 +27,11 @@
27
27
  "node": ">=20"
28
28
  },
29
29
  "dependencies": {
30
- "ajv": "^6.12.6",
31
30
  "esbuild": "^0.24.0",
32
- "js-yaml": "^4.1.0",
33
31
  "miniflare": "^3.20250718.3"
34
32
  },
35
33
  "devDependencies": {
36
- "typescript": "^5.4.0",
37
34
  "@types/node": "^20.0.0",
38
- "@types/js-yaml": "^4.0.9"
35
+ "typescript": "^5.4.0"
39
36
  }
40
37
  }
@@ -1,208 +0,0 @@
1
- /**
2
- * Plan-file canonicalizer (Phase 8b).
3
- *
4
- * Pure function: a parsed plan-frontmatter object → canonical YAML
5
- * string. The canonical form is what `import` writes to the file
6
- * after parsing/normalizing user input AND what `export` emits when
7
- * snapshotting the live DB plan back to disk. Both paths share this
8
- * one engine so a round-trip through import → export produces a
9
- * byte-identical file.
10
- *
11
- * Round 5 stance #7 + Round 2 stance answers locked these rules:
12
- * - Stable key order at the schema-defined level (planId, name,
13
- * state, …, steps[]). Top-level field order is fixed.
14
- * - Step-level + gate-level + input-level + declared-output-level +
15
- * template-level orders are also schema-defined.
16
- * - Nested arbitrary-keyed objects (gate.config,
17
- * integrationPolicy, template.metadata) sort recursively
18
- * lexicographically. The schema says nothing about their key
19
- * order, so alphabetical is the only stable rule.
20
- * - Unknown top-level keys (forward-compat) trail the known schema
21
- * fields in lexicographic order.
22
- * - Output uses `\n` line endings, single trailing newline, 2-space
23
- * indent, plain scalars where unambiguous (double-quoted when a
24
- * string would otherwise parse as a non-string YAML value), and
25
- * no boolean/numeric coercion at parse time (caller's
26
- * responsibility — js-yaml's default load is happy to coerce, so
27
- * callers should run their own validator that doesn't).
28
- *
29
- * NOT enforced here (caller's job):
30
- * - Schema validation (frontmatter shape).
31
- * - Stripping DB-only fields (`_id`, `workspaceId`, `version`,
32
- * `latestRunId`, `nextRunNumber`, `createdAt`, `updatedAt`).
33
- * - Verifying `planId` matches the file stem.
34
- * - Asserting stepId uniqueness, gate `requires` resolves to
35
- * siblings, etc.
36
- */
37
- import yaml from 'js-yaml';
38
- // ─── Schema-defined field orders ──────────────────────────────────────────
39
- // NB: no `description` at the plan level. Per the Phase 8 design
40
- // (`docs/_ORCHESTRATION_PHASE8_PLAN_FILES_DESIGN.md` §"body is
41
- // Plan.description"), the markdown body IS `Plan.description` —
42
- // frontmatter has no description field, by design, to avoid dual
43
- // sources. Step- and input-level `description` fields are unrelated
44
- // and remain in their respective `*_FIELD_ORDER`s below.
45
- const PLAN_FIELD_ORDER = [
46
- 'planId',
47
- 'name',
48
- 'state',
49
- 'failurePolicy',
50
- 'autoRetryCap',
51
- 'autoRetryFallback',
52
- 'inputs',
53
- 'integrationPolicy',
54
- 'steps',
55
- ];
56
- const STEP_FIELD_ORDER = [
57
- 'stepId',
58
- 'name',
59
- 'description',
60
- 'mode',
61
- 'runner',
62
- 'gates',
63
- 'declaredOutputs',
64
- 'failurePolicy',
65
- 'autoRetryCap',
66
- 'autoRetryFallback',
67
- 'template',
68
- ];
69
- const GATE_FIELD_ORDER = ['gateId', 'type', 'config'];
70
- const INPUT_FIELD_ORDER = ['name', 'required', 'default', 'description'];
71
- const DECLARED_OUTPUT_FIELD_ORDER = ['name', 'artifactType', 'required'];
72
- const TEMPLATE_FIELD_ORDER = ['todoContent', 'todoFile', 'branch', 'surfacesArtifacts', 'metadata'];
73
- // ─── Helpers ──────────────────────────────────────────────────────────────
74
- /**
75
- * Reorder an object's keys: known schema keys first (in the given
76
- * order), then any unknown keys lexicographically. Missing schema
77
- * keys are skipped (we never emit `null` for unset optional fields).
78
- */
79
- function reorderObject(obj, order) {
80
- const out = {};
81
- for (const key of order) {
82
- if (key in obj && obj[key] !== undefined) {
83
- out[key] = obj[key];
84
- }
85
- }
86
- const known = new Set(order);
87
- const extras = Object.keys(obj)
88
- .filter((k) => !known.has(k) && obj[k] !== undefined)
89
- .sort();
90
- for (const k of extras) {
91
- out[k] = obj[k];
92
- }
93
- return out;
94
- }
95
- /**
96
- * Recursively sort the keys of arbitrary-keyed nested objects
97
- * lexicographically. Arrays preserve their declared order; primitives
98
- * pass through unchanged.
99
- *
100
- * Used for `gate.config`, `integrationPolicy`, `template.metadata`,
101
- * and any future free-form nested map. The schema doesn't dictate
102
- * key order for these, so alphabetical is the only deterministic
103
- * choice.
104
- */
105
- function sortNestedKeys(value) {
106
- if (Array.isArray(value)) {
107
- return value.map(sortNestedKeys);
108
- }
109
- if (value !== null && typeof value === 'object') {
110
- const obj = value;
111
- const out = {};
112
- for (const key of Object.keys(obj).sort()) {
113
- out[key] = sortNestedKeys(obj[key]);
114
- }
115
- return out;
116
- }
117
- return value;
118
- }
119
- /**
120
- * Reorder a parsed plan frontmatter to canonical shape. Pure — does
121
- * not mutate the input.
122
- */
123
- export function canonicalizeFrontmatterObject(plan) {
124
- const ordered = reorderObject(plan, PLAN_FIELD_ORDER);
125
- if (Array.isArray(ordered.inputs)) {
126
- ordered.inputs = ordered.inputs.map((input) => reorderObject(input, INPUT_FIELD_ORDER));
127
- }
128
- if (ordered.integrationPolicy && typeof ordered.integrationPolicy === 'object') {
129
- ordered.integrationPolicy = sortNestedKeys(ordered.integrationPolicy);
130
- }
131
- if (Array.isArray(ordered.steps)) {
132
- ordered.steps = ordered.steps.map((step) => {
133
- const orderedStep = reorderObject(step, STEP_FIELD_ORDER);
134
- if (Array.isArray(orderedStep.gates)) {
135
- orderedStep.gates = orderedStep.gates.map((gate) => {
136
- const og = reorderObject(gate, GATE_FIELD_ORDER);
137
- if (og.config && typeof og.config === 'object') {
138
- og.config = sortNestedKeys(og.config);
139
- }
140
- return og;
141
- });
142
- }
143
- if (Array.isArray(orderedStep.declaredOutputs)) {
144
- orderedStep.declaredOutputs = orderedStep.declaredOutputs.map((d) => reorderObject(d, DECLARED_OUTPUT_FIELD_ORDER));
145
- }
146
- if (orderedStep.template && typeof orderedStep.template === 'object') {
147
- const ot = reorderObject(orderedStep.template, TEMPLATE_FIELD_ORDER);
148
- if (ot.metadata && typeof ot.metadata === 'object') {
149
- ot.metadata = sortNestedKeys(ot.metadata);
150
- }
151
- orderedStep.template = ot;
152
- }
153
- return orderedStep;
154
- });
155
- }
156
- return ordered;
157
- }
158
- // ─── YAML emission ────────────────────────────────────────────────────────
159
- /**
160
- * Emit a canonical YAML string for the given (already-reordered)
161
- * frontmatter object. Always ends with a single `\n`.
162
- */
163
- export function emitCanonicalYaml(ordered) {
164
- return yaml.dump(ordered, {
165
- noRefs: true, // no anchors/aliases
166
- sortKeys: false, // we control order ourselves; js-yaml leaves it alone
167
- lineWidth: -1, // never wrap long scalars
168
- quotingType: '"', // double-quotes when quoting is needed
169
- forceQuotes: false, // only quote when ambiguous
170
- indent: 2,
171
- flowLevel: -1, // always block style for objects/arrays (except where the YAML grammar requires flow)
172
- });
173
- }
174
- // ─── Public entry points ──────────────────────────────────────────────────
175
- /**
176
- * Canonicalize a parsed plan frontmatter object to its YAML string.
177
- * Pure: same input → same byte-identical output.
178
- */
179
- export function canonicalizeFrontmatter(plan) {
180
- const ordered = canonicalizeFrontmatterObject(plan);
181
- return emitCanonicalYaml(ordered);
182
- }
183
- /**
184
- * Canonicalize a full plan file (frontmatter + body). Output shape:
185
- *
186
- * ---
187
- * <frontmatter>
188
- * ---
189
- *
190
- * <body>
191
- *
192
- * Body is normalized to LF-only, exactly one trailing newline, no
193
- * trailing whitespace beyond that. Frontmatter and body are
194
- * separated by `---` plus one blank line (markdown-friendly).
195
- */
196
- export function canonicalizePlanFile(plan, body) {
197
- const fm = canonicalizeFrontmatter(plan);
198
- // js-yaml's dump always ends with a single \n; collapse any
199
- // accidental trailing blanks just in case.
200
- const fmTrimmed = fm.replace(/\n+$/, '\n');
201
- // Body: LF-only, strip CR; strip any leading newlines (the
202
- // frontmatter-body separator is owned by this function, not the
203
- // caller's body string — a parsed file's body capture often starts
204
- // with the blank line after the closing `---`); trim trailing
205
- // whitespace; ensure exactly one trailing newline.
206
- const bodyTrimmed = body.replace(/\r\n/g, '\n').replace(/^\n+/, '').replace(/\s+$/, '');
207
- return `---\n${fmTrimmed}---\n\n${bodyTrimmed}\n`;
208
- }