@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.
@@ -1,261 +0,0 @@
1
- /**
2
- * `yolo plan export <planId>` orchestration (Phase 8c.4).
3
- *
4
- * Inverse of `yolo plan import`: DB → file. Composes everything from
5
- * earlier slices:
6
- * - `work-client` (8c.2) — mint + authenticatedRequest for
7
- * `work.get_plan`.
8
- * - `canonicalizer` (8b) — pure object → canonical YAML+body.
9
- * - `revision` (8c.2) — sha256 of the bytes we just wrote.
10
- * - `lockfile` (8c.2) — refresh `(workspaceId, planId)`
11
- * entry so a follow-up `import` is
12
- * NO_CHANGE.
13
- *
14
- * High-level flow:
15
- *
16
- * 1. Resolve substrate context (env trio); error if missing.
17
- * 2. Mint a session-bound delegated token; the response is the
18
- * authoritative `workspaceId`.
19
- * 3. If `--workspace` was passed, assert it matches the minted
20
- * workspaceId (same ergonomics as import).
21
- * 4. Call `work.get_plan(workspaceId, planId)`; serialize to the
22
- * canonical file form.
23
- * 5. Write the canonical bytes to `-o <file>` (default
24
- * `<plansDir>/<planId>.md`). Errors out if the destination
25
- * directory doesn't exist UNLESS `--force` is set, in which
26
- * case it `mkdir -p`s.
27
- * 6. Refresh the lockfile entry so `import` of the freshly
28
- * written file is detected as NO_CHANGE on the next run.
29
- *
30
- * Out of scope (deferred):
31
- * - `--diff` / dry-run output. Add when there's real demand.
32
- * - File-watch / auto-export daemon. Manual export only per the
33
- * Phase 8 design ("Bidirectional file ↔ DB sync... out of scope").
34
- * - Outside-container login. v1 errors out without `SESSION_ID`
35
- * (substrate CLI is container-only — design Round 5).
36
- *
37
- * Errors map to exit codes via the CLI wrapper:
38
- * - 0 = success
39
- * - 1 = HTTP / file-write / lockfile failure
40
- * - 64 = usage error (missing planId, workspace mismatch, missing env trio)
41
- */
42
- import { mkdirSync, writeFileSync } from 'node:fs';
43
- import path from 'node:path';
44
- import { canonicalizePlanFile } from './canonicalizer.js';
45
- import { computeRevisionHash } from './revision.js';
46
- import { LockfileError, readLockfile, resolveLockfilePath, setEntry, writeLockfile, } from './lockfile.js';
47
- import { SUBSTRATE_CLI_PLAN_SCOPES, WorkClientError, authenticatedRequest, mintSubstrateToken, } from './work-client.js';
48
- import { resolveSubstrateContext } from './auth-context.js';
49
- // ─── Public entry ─────────────────────────────────────────────────────────
50
- const PLAN_ID_REGEX = /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,127}$/;
51
- export async function runPlanExport(options) {
52
- const env = options.env ?? process.env;
53
- const now = options.now ?? (() => new Date().toISOString());
54
- // 1) planId shape (matches substrate's PLAN_ID_REGEX)
55
- if (!PLAN_ID_REGEX.test(options.planId)) {
56
- return fail('usage', `invalid planId '${options.planId}': must match /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,127}$/`);
57
- }
58
- // 1b) -o basename stem must equal planId so the exported file
59
- // round-trips through `yolo plan import`, which enforces
60
- // `frontmatter.planId === file-stem` (plan-import.ts:172).
61
- // Otherwise `yolo plan export foo -o custom-name.md` produces
62
- // a file the import command refuses (Codex 8c.4 R1 Medium).
63
- // -o is for changing the DIRECTORY, not the filename.
64
- if (options.outputFlag !== undefined) {
65
- const outStem = path.basename(options.outputFlag, path.extname(options.outputFlag));
66
- if (outStem !== options.planId) {
67
- return fail('usage', `-o basename stem '${outStem}' must equal planId '${options.planId}' so the exported file round-trips through \`yolo plan import\`. ` +
68
- `Either rename the output to '${options.planId}.md' (with any directory you like) or drop -o to use the default <plansDir>/${options.planId}.md.`);
69
- }
70
- }
71
- // 2) Substrate context
72
- const auth = resolveSubstrateContext(env);
73
- if (!auth.ok)
74
- return fail('auth', auth.message);
75
- const { sessionId, commonApiUrl, userToken } = auth.context;
76
- // 3) Mint token
77
- let mint;
78
- try {
79
- mint = await mintSubstrateToken({
80
- commonApiUrl,
81
- userToken,
82
- sessionId,
83
- scopes: SUBSTRATE_CLI_PLAN_SCOPES,
84
- fetchImpl: options.fetchImpl,
85
- });
86
- }
87
- catch (err) {
88
- if (err instanceof WorkClientError) {
89
- return fail('auth', `failed to mint substrate token: ${err.message}`, { status: err.status, code: err.code });
90
- }
91
- return fail('auth', `failed to mint substrate token: ${describeError(err)}`);
92
- }
93
- // 4) --workspace assertion
94
- if (options.workspaceFlag && options.workspaceFlag !== mint.workspaceId) {
95
- return fail('workspace_mismatch', `--workspace ${options.workspaceFlag} does not match the workspace bound to this session (${mint.workspaceId}).`);
96
- }
97
- // 5) work.get_plan
98
- const plansDir = options.plansDir ?? path.resolve('.yolo', 'plans');
99
- const requestCtx = {
100
- commonApiUrl,
101
- delegatedToken: mint.token,
102
- fetchImpl: options.fetchImpl,
103
- };
104
- const fetched = await tryGet(requestCtx, mint.workspaceId, options.planId);
105
- if (!fetched.ok)
106
- return fetched.error;
107
- // 6) Convert to canonical file bytes
108
- const dbPlan = fetched.plan;
109
- const { frontmatter, body } = dbPlanToFile(dbPlan);
110
- const canonicalBytes = canonicalizePlanFile(frontmatter, body);
111
- // 7) Resolve output path + ensure dir
112
- const outputPath = options.outputFlag
113
- ? path.resolve(options.outputFlag)
114
- : path.join(plansDir, `${dbPlan.planId}.md`);
115
- try {
116
- mkdirSync(path.dirname(outputPath), { recursive: true });
117
- writeFileSync(outputPath, canonicalBytes, 'utf8');
118
- }
119
- catch (err) {
120
- return fail('write', `could not write '${outputPath}': ${describeError(err)}`);
121
- }
122
- // 8) Refresh lockfile so a subsequent `yolo plan import` of this
123
- // file is a NO_CHANGE (file revision == lockfile entry).
124
- const revision = computeRevisionHash(canonicalBytes);
125
- const exportedAt = now();
126
- let lockfilePath;
127
- let lockfile;
128
- try {
129
- lockfilePath = resolveLockfilePath(plansDir, options.lockfileFlag);
130
- lockfile = readLockfile(lockfilePath);
131
- }
132
- catch (err) {
133
- if (err instanceof LockfileError) {
134
- return fail('lockfile', err.message, { code: err.code });
135
- }
136
- return fail('lockfile', describeError(err));
137
- }
138
- const newEntry = {
139
- lastImportedRevision: revision,
140
- lastImportedVersion: dbPlan.version,
141
- lastImportedAt: exportedAt,
142
- };
143
- setEntry(lockfile, mint.workspaceId, dbPlan.planId, newEntry);
144
- try {
145
- writeLockfile(lockfilePath, lockfile);
146
- }
147
- catch (err) {
148
- if (err instanceof LockfileError) {
149
- return fail('lockfile', err.message, { code: err.code });
150
- }
151
- return fail('lockfile', describeError(err));
152
- }
153
- return {
154
- ok: true,
155
- planId: dbPlan.planId,
156
- workspaceId: mint.workspaceId,
157
- version: dbPlan.version,
158
- revision,
159
- outputPath,
160
- exportedAt,
161
- lockfilePath,
162
- };
163
- }
164
- /**
165
- * Convert a `work.get_plan` response (the `serializePlan` shape from
166
- * `common-api/src/routes/work.ts`) to the canonical file form
167
- * (frontmatter object + body string). Pure, no I/O.
168
- *
169
- * Strips DB-only fields (`version`, `latestRunId`, `createdAt`,
170
- * `updatedAt`) per the Phase 8 design — those don't round-trip.
171
- * Converts nulls back to `undefined` so the canonicalizer drops them
172
- * via `reorderObject`'s "skip undefined" rule.
173
- *
174
- * Empty `inputs: []` is preserved in the frontmatter so a follow-up
175
- * `import` produces a stable diff (round-trip equivalence). Empty
176
- * `integrationPolicy: {}` is dropped since the substrate validator
177
- * normalizes it to `undefined` anyway.
178
- */
179
- export function dbPlanToFile(dbPlan) {
180
- const frontmatter = {
181
- planId: dbPlan.planId,
182
- name: dbPlan.name,
183
- state: dbPlan.state,
184
- failurePolicy: dbPlan.failurePolicy ?? 'pause-and-wait',
185
- steps: dbPlan.steps,
186
- };
187
- if (dbPlan.autoRetryCap !== undefined && dbPlan.autoRetryCap !== null) {
188
- frontmatter.autoRetryCap = dbPlan.autoRetryCap;
189
- }
190
- if (dbPlan.autoRetryFallback !== undefined && dbPlan.autoRetryFallback !== null) {
191
- frontmatter.autoRetryFallback = dbPlan.autoRetryFallback;
192
- }
193
- if (Array.isArray(dbPlan.inputs)) {
194
- frontmatter.inputs = dbPlan.inputs;
195
- }
196
- if (dbPlan.integrationPolicy !== undefined &&
197
- dbPlan.integrationPolicy !== null &&
198
- Object.keys(dbPlan.integrationPolicy).length > 0) {
199
- frontmatter.integrationPolicy = dbPlan.integrationPolicy;
200
- }
201
- // Body = description. canonicalizePlanFile's body-side normalization
202
- // (CRLF→LF, strip leading `\n+`, exactly one trailing newline)
203
- // handles whatever comes out of the DB. Treat `null`/`undefined` as
204
- // empty string — canonical form will be `---\n…\n---\n\n\n`, which
205
- // is an empty body plus the mandatory trailing newline.
206
- const body = typeof dbPlan.description === 'string' ? dbPlan.description : '';
207
- return { frontmatter, body };
208
- }
209
- async function tryGet(ctx, workspaceId, planId) {
210
- const response = await authenticatedRequest(ctx, `/workspaces/${workspaceId}/plans/${planId}`, { method: 'GET' });
211
- if (!response.ok) {
212
- const text = await safeReadText(response);
213
- return {
214
- ok: false,
215
- error: fail('http', `work.get_plan failed: HTTP ${response.status} — ${text}`, { status: response.status }),
216
- };
217
- }
218
- const json = (await response.json());
219
- if (!json.plan) {
220
- return { ok: false, error: fail('http', 'work.get_plan response missing `plan` field') };
221
- }
222
- return { ok: true, plan: json.plan };
223
- }
224
- // ─── Helpers + CLI surface ────────────────────────────────────────────────
225
- function fail(kind, message, detail) {
226
- return { ok: false, kind, message, detail };
227
- }
228
- function describeError(err) {
229
- return err instanceof Error ? err.message : String(err);
230
- }
231
- async function safeReadText(response) {
232
- try {
233
- return await response.text();
234
- }
235
- catch {
236
- return '<no body>';
237
- }
238
- }
239
- /**
240
- * Map an `ExportFailure.kind` to a CLI exit code. Used by cli.ts and
241
- * exported for tests.
242
- */
243
- export function exitCodeForFailure(kind) {
244
- switch (kind) {
245
- case 'usage':
246
- case 'auth':
247
- case 'workspace_mismatch':
248
- return 64; // EX_USAGE
249
- case 'http':
250
- case 'write':
251
- case 'lockfile':
252
- return 1;
253
- }
254
- }
255
- /**
256
- * Render an `ExportSuccess` as a single-line CLI summary. Caller
257
- * appends `\n` if needed.
258
- */
259
- export function formatSuccess(result) {
260
- return `OK: exported plan '${result.planId}' (workspace ${result.workspaceId}, version ${result.version}) to ${result.outputPath} (revision ${result.revision.slice(0, 14)}…)`;
261
- }
package/dist/plan-get.js DELETED
@@ -1,244 +0,0 @@
1
- /**
2
- * `yolo plan get <planId>` — read a Plan from the substrate.
3
- *
4
- * The thinnest of the three workflow commands. No file I/O, no
5
- * lockfile mutation, no canonicalization. Mints a session-bound
6
- * delegated token (work.get_plan scope) and prints the plan.
7
- *
8
- * Three output modes:
9
- * - default (`--summary`): one-line plan header + per-step rows
10
- * in declared order, with stepId, mode, and dependency
11
- * stepIds. Good for an operator's "is the import what I
12
- * expected" sanity check.
13
- * - `--waves`: same header, but steps grouped by topological
14
- * wave (computed from dependency gates). A wave is the set of
15
- * steps whose dependencies are all satisfied by earlier waves;
16
- * a step's wave is `1 + max(wave of any dependency)`. Good for
17
- * "what runs in parallel at each stage" reading.
18
- * - `--json`: pretty-printed `work.get_plan` response. Useful in
19
- * pipelines / for `jq` consumers.
20
- *
21
- * Errors map to exit codes via the CLI wrapper:
22
- * - 0 = success
23
- * - 1 = http (plan not found, etc.)
24
- * - 64 = usage error (bad planId, missing env trio,
25
- * --workspace mismatch)
26
- */
27
- import { SUBSTRATE_CLI_PLAN_SCOPES, WorkClientError, authenticatedRequest, mintSubstrateToken, } from './work-client.js';
28
- import { resolveSubstrateContext } from './auth-context.js';
29
- import { planDagUrl } from './webapp-url.js';
30
- // ─── Public entry ─────────────────────────────────────────────────────────
31
- const PLAN_ID_REGEX = /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,127}$/;
32
- export async function runPlanGet(options) {
33
- const env = options.env ?? process.env;
34
- const format = options.outputFormat ?? 'summary';
35
- // 1) planId shape (matches substrate's PLAN_ID_REGEX)
36
- if (!PLAN_ID_REGEX.test(options.planId)) {
37
- return fail('usage', `invalid planId '${options.planId}': must match /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,127}$/`);
38
- }
39
- // 2) Substrate context
40
- const auth = resolveSubstrateContext(env);
41
- if (!auth.ok)
42
- return fail('auth', auth.message);
43
- const { sessionId, commonApiUrl, userToken } = auth.context;
44
- // 3) Mint token
45
- let mint;
46
- try {
47
- mint = await mintSubstrateToken({
48
- commonApiUrl,
49
- userToken,
50
- sessionId,
51
- scopes: SUBSTRATE_CLI_PLAN_SCOPES,
52
- fetchImpl: options.fetchImpl,
53
- });
54
- }
55
- catch (err) {
56
- if (err instanceof WorkClientError) {
57
- return fail('auth', `failed to mint substrate token: ${err.message}`, { status: err.status, code: err.code });
58
- }
59
- return fail('auth', `failed to mint substrate token: ${describeError(err)}`);
60
- }
61
- // 4) --workspace assertion
62
- if (options.workspaceFlag && options.workspaceFlag !== mint.workspaceId) {
63
- return fail('workspace_mismatch', `--workspace ${options.workspaceFlag} does not match the workspace bound to this session (${mint.workspaceId}).`);
64
- }
65
- // 5) work.get_plan
66
- const ctx = {
67
- commonApiUrl,
68
- delegatedToken: mint.token,
69
- fetchImpl: options.fetchImpl,
70
- };
71
- const response = await authenticatedRequest(ctx, `/workspaces/${mint.workspaceId}/plans/${options.planId}`, { method: 'GET' });
72
- if (!response.ok) {
73
- const text = await safeReadText(response);
74
- return fail('http', `work.get_plan failed: HTTP ${response.status} — ${text}`, { status: response.status });
75
- }
76
- const json = (await response.json());
77
- if (!json.plan) {
78
- return fail('http', 'work.get_plan response missing `plan` field');
79
- }
80
- let output;
81
- if (format === 'json')
82
- output = formatJson(json.plan);
83
- else if (format === 'waves')
84
- output = formatWaves(json.plan, mint.workspaceId, env);
85
- else
86
- output = formatSummary(json.plan, mint.workspaceId, env);
87
- return {
88
- ok: true,
89
- output,
90
- plan: json.plan,
91
- workspaceId: mint.workspaceId,
92
- };
93
- }
94
- // ─── Output formatting ────────────────────────────────────────────────────
95
- /**
96
- * One-line header + per-step rows. Each row: `<stepId> (<mode>)`
97
- * with `← deps: <predId1>, <predId2>` if the step has dependency
98
- * gates. Matches the substrate's actual gate shape (single
99
- * `config.stepId` per dependency gate, per gate-readiness.ts:180);
100
- * one row per step lists ALL its dependency-gate stepIds.
101
- */
102
- export function formatSummary(plan, workspaceId, env = process.env) {
103
- const lines = [];
104
- lines.push(`Plan '${plan.planId}' (workspace ${workspaceId}, version ${plan.version}, ${plan.state})`);
105
- const dagUrl = planDagUrl(env, workspaceId, plan.planId);
106
- if (dagUrl)
107
- lines.push(` view: ${dagUrl}`);
108
- if (plan.failurePolicy)
109
- lines.push(` failurePolicy: ${plan.failurePolicy}`);
110
- if (typeof plan.autoRetryCap === 'number')
111
- lines.push(` autoRetryCap: ${plan.autoRetryCap}`);
112
- const inputCount = Array.isArray(plan.inputs) ? plan.inputs.length : 0;
113
- lines.push(` inputs: ${inputCount}`);
114
- lines.push(` steps: ${plan.steps.length}`);
115
- for (const step of plan.steps) {
116
- const deps = depStepIds(step);
117
- const depTag = deps.length > 0 ? ` ← deps: ${deps.join(', ')}` : '';
118
- lines.push(` - ${step.stepId} (${step.mode ?? '?'})${depTag}`);
119
- }
120
- return lines.join('\n');
121
- }
122
- /**
123
- * Wave-grouped renderer. Same header as formatSummary, then steps
124
- * grouped by their topological wave. Within a wave, step order
125
- * matches the declared order in `plan.steps` so output is stable
126
- * across runs.
127
- *
128
- * Defensive on bad shapes the substrate would normally reject:
129
- * unknown predecessor stepIds collapse to wave 1, cycles short-circuit
130
- * to wave 1 for the visiting node (so we never recurse forever).
131
- */
132
- export function formatWaves(plan, workspaceId, env = process.env) {
133
- const lines = [];
134
- lines.push(`Plan '${plan.planId}' (workspace ${workspaceId}, version ${plan.version}, ${plan.state})`);
135
- const dagUrl = planDagUrl(env, workspaceId, plan.planId);
136
- if (dagUrl)
137
- lines.push(` view: ${dagUrl}`);
138
- if (plan.failurePolicy)
139
- lines.push(` failurePolicy: ${plan.failurePolicy}`);
140
- if (typeof plan.autoRetryCap === 'number')
141
- lines.push(` autoRetryCap: ${plan.autoRetryCap}`);
142
- const inputCount = Array.isArray(plan.inputs) ? plan.inputs.length : 0;
143
- lines.push(` inputs: ${inputCount}`);
144
- const waves = computeWaves(plan.steps);
145
- const waveCount = waves.length;
146
- const stepWord = plan.steps.length === 1 ? 'step' : 'steps';
147
- lines.push(` steps: ${plan.steps.length} ${stepWord} in ${waveCount} ${waveCount === 1 ? 'wave' : 'waves'}`);
148
- lines.push('');
149
- for (let i = 0; i < waves.length; i++) {
150
- const stepsInWave = waves[i];
151
- const count = stepsInWave.length;
152
- const parallelTag = count > 1 ? ', parallel' : '';
153
- lines.push(` Wave ${i + 1} (${count} ${count === 1 ? 'step' : 'steps'}${parallelTag}):`);
154
- for (const step of stepsInWave) {
155
- const deps = depStepIds(step);
156
- const depTag = deps.length > 0 ? ` ← deps: ${deps.join(', ')}` : '';
157
- lines.push(` - ${step.stepId} (${step.mode ?? '?'})${depTag}`);
158
- }
159
- }
160
- return lines.join('\n');
161
- }
162
- /**
163
- * Topological wave grouping. Returns an array of arrays — index 0 is
164
- * wave 1, index 1 is wave 2, etc. Within each wave, steps appear in
165
- * the order they were declared in `plan.steps`.
166
- */
167
- function computeWaves(steps) {
168
- const stepById = new Map();
169
- for (const s of steps)
170
- stepById.set(s.stepId, s);
171
- const waveOfStep = new Map();
172
- const waveOf = (stepId, visiting) => {
173
- const cached = waveOfStep.get(stepId);
174
- if (cached !== undefined)
175
- return cached;
176
- const step = stepById.get(stepId);
177
- if (!step)
178
- return 1; // unknown predecessor — substrate rejects on import
179
- visiting.add(stepId);
180
- let max = 0;
181
- for (const dep of depStepIds(step)) {
182
- if (!stepById.has(dep))
183
- continue; // unknown predecessor → ignore
184
- if (visiting.has(dep))
185
- continue; // cycle: ignore the back-edge
186
- const w = waveOf(dep, visiting);
187
- if (w > max)
188
- max = w;
189
- }
190
- visiting.delete(stepId);
191
- const wave = max + 1;
192
- waveOfStep.set(stepId, wave);
193
- return wave;
194
- };
195
- for (const s of steps)
196
- waveOf(s.stepId, new Set());
197
- const grouped = [];
198
- for (const s of steps) {
199
- const w = waveOfStep.get(s.stepId) ?? 1;
200
- while (grouped.length < w)
201
- grouped.push([]);
202
- grouped[w - 1].push(s);
203
- }
204
- return grouped;
205
- }
206
- function depStepIds(step) {
207
- const out = [];
208
- for (const gate of step.gates ?? []) {
209
- if (gate.type === 'dependency') {
210
- const predId = gate.config?.stepId;
211
- if (typeof predId === 'string')
212
- out.push(predId);
213
- }
214
- }
215
- return out;
216
- }
217
- function formatJson(plan) {
218
- return JSON.stringify(plan, null, 2);
219
- }
220
- // ─── Helpers ──────────────────────────────────────────────────────────────
221
- function fail(kind, message, detail) {
222
- return { ok: false, kind, message, detail };
223
- }
224
- function describeError(err) {
225
- return err instanceof Error ? err.message : String(err);
226
- }
227
- async function safeReadText(response) {
228
- try {
229
- return await response.text();
230
- }
231
- catch {
232
- return '<no body>';
233
- }
234
- }
235
- export function exitCodeForFailure(kind) {
236
- switch (kind) {
237
- case 'usage':
238
- case 'auth':
239
- case 'workspace_mismatch':
240
- return 64;
241
- case 'http':
242
- return 1;
243
- }
244
- }