@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.
package/dist/lockfile.js DELETED
@@ -1,203 +0,0 @@
1
- /**
2
- * Plan-import lockfile (Phase 8c.2).
3
- *
4
- * Tracks `(workspaceId, planId) → { lastImportedRevision,
5
- * lastImportedVersion, lastImportedAt }` so `yolo plan import` (8c.3)
6
- * can detect drift between the file and the DB. The lockfile is NOT
7
- * an identity remap — `planId` IS the workspace-scoped DB identifier
8
- * (substrate enforces `(workspaceId, planId)` uniqueness directly).
9
- *
10
- * Two locations, per design F8.2:
11
- * - **Default** (`.yolo/plans/.imports.json`) — gitignored. Per-developer
12
- * state. Each engineer's local Plan Run / staging workspace lands here.
13
- * - **Env-named** (`.yolo/plans/.imports.<env>.json`) — opt-in checked-in.
14
- * Use for shared stable workspaces (e.g., the team's prod workspace)
15
- * so reproducible imports work across machines. Selected via
16
- * `--env <name>` on the CLI.
17
- *
18
- * Canonical write shape:
19
- * - JSON, 2-space indent, single trailing `\n`.
20
- * - Workspace IDs sorted lexicographically; planIds within each
21
- * workspace also sorted; entry keys in fixed order
22
- * (lastImportedAt, lastImportedRevision, lastImportedVersion —
23
- * alphabetical, mirroring how the plan-file canonicalizer treats
24
- * free-form maps).
25
- * - Same input → byte-identical output (idempotent re-write).
26
- *
27
- * Out of scope here (lands in 8c.3 import):
28
- * - The actual import flow (mint token → call work.create_plan /
29
- * work.update_plan → update lockfile).
30
- * - Divergence-policy decisions (`--force` to override DB version
31
- * drift, etc.) — `lockfile.ts` is just storage.
32
- *
33
- * Out of scope (8c.5 / future):
34
- * - Lockfile schema evolution. v1 has no version field; if the shape
35
- * ever changes, add a `$version` top-level field then.
36
- */
37
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
38
- import path from 'node:path';
39
- import { isWellFormedRevision } from './revision.js';
40
- const LOCKFILE_DEFAULT_BASENAME = '.imports.json';
41
- export class LockfileError extends Error {
42
- code;
43
- constructor(message, code) {
44
- super(message);
45
- this.name = 'LockfileError';
46
- this.code = code;
47
- }
48
- }
49
- /**
50
- * Resolve the lockfile path for a given plans directory and optional
51
- * env name.
52
- *
53
- * @param plansDir - the absolute or relative path to `.yolo/plans/`.
54
- * @param env - if set, picks `.imports.<env>.json` (the opt-in
55
- * checked-in variant). If unset, picks the gitignored default.
56
- */
57
- export function resolveLockfilePath(plansDir, env) {
58
- if (env !== undefined) {
59
- if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$/.test(env)) {
60
- throw new LockfileError(`--env name must match /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$/, got '${env}'`, 'malformed');
61
- }
62
- return path.join(plansDir, `.imports.${env}.json`);
63
- }
64
- return path.join(plansDir, LOCKFILE_DEFAULT_BASENAME);
65
- }
66
- /**
67
- * Read a lockfile from disk. Returns an empty object if the file
68
- * doesn't exist (first-import case). Throws `LockfileError` if the
69
- * file is unreadable or malformed.
70
- */
71
- export function readLockfile(filePath) {
72
- if (!existsSync(filePath))
73
- return {};
74
- let text;
75
- try {
76
- text = readFileSync(filePath, 'utf8');
77
- }
78
- catch (err) {
79
- const msg = err instanceof Error ? err.message : String(err);
80
- throw new LockfileError(`could not read lockfile at ${filePath}: ${msg}`, 'unreadable');
81
- }
82
- if (text.trim() === '')
83
- return {};
84
- let parsed;
85
- try {
86
- parsed = JSON.parse(text);
87
- }
88
- catch (err) {
89
- const msg = err instanceof Error ? err.message : String(err);
90
- throw new LockfileError(`malformed JSON in lockfile at ${filePath}: ${msg}`, 'malformed');
91
- }
92
- if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
93
- throw new LockfileError(`malformed lockfile at ${filePath}: top-level must be a JSON object, got ${describe(parsed)}`, 'malformed');
94
- }
95
- return validateShape(parsed, filePath);
96
- }
97
- /**
98
- * Write a lockfile to disk in canonical form. Creates the parent
99
- * directory if missing. Idempotent: same lockfile contents always
100
- * produce byte-identical output.
101
- */
102
- export function writeLockfile(filePath, lockfile) {
103
- const dir = path.dirname(filePath);
104
- try {
105
- mkdirSync(dir, { recursive: true });
106
- }
107
- catch (err) {
108
- const msg = err instanceof Error ? err.message : String(err);
109
- throw new LockfileError(`could not create lockfile dir ${dir}: ${msg}`, 'unwritable');
110
- }
111
- const sorted = canonicalize(lockfile);
112
- const text = JSON.stringify(sorted, null, 2) + '\n';
113
- try {
114
- writeFileSync(filePath, text, 'utf8');
115
- }
116
- catch (err) {
117
- const msg = err instanceof Error ? err.message : String(err);
118
- throw new LockfileError(`could not write lockfile at ${filePath}: ${msg}`, 'unwritable');
119
- }
120
- }
121
- /**
122
- * Lookup helper. Returns the entry for a `(workspaceId, planId)` pair,
123
- * or `null` if either key is missing. Pure read — does not mutate the
124
- * lockfile.
125
- */
126
- export function getEntry(lockfile, workspaceId, planId) {
127
- return lockfile[workspaceId]?.[planId] ?? null;
128
- }
129
- /**
130
- * Mutator. Inserts or replaces the entry for a `(workspaceId, planId)`
131
- * pair. Mutates `lockfile` in place AND returns it (for chaining /
132
- * test ergonomics).
133
- */
134
- export function setEntry(lockfile, workspaceId, planId, entry) {
135
- if (!lockfile[workspaceId])
136
- lockfile[workspaceId] = {};
137
- lockfile[workspaceId][planId] = entry;
138
- return lockfile;
139
- }
140
- // ─── Internals ────────────────────────────────────────────────────────────
141
- /**
142
- * Reorder the lockfile to canonical shape: workspace IDs sorted,
143
- * planIds within each sorted, entry fields in fixed alphabetical
144
- * order. Same canonicalization rule as the plan-file canonicalizer's
145
- * `sortNestedKeys`: lex sort because the schema doesn't dictate
146
- * order. Pure — does not mutate input.
147
- */
148
- function canonicalize(lockfile) {
149
- const out = {};
150
- for (const ws of Object.keys(lockfile).sort()) {
151
- out[ws] = {};
152
- for (const planId of Object.keys(lockfile[ws]).sort()) {
153
- const e = lockfile[ws][planId];
154
- // Fixed alphabetical entry-field order (matches a future
155
- // round-trip test: read → write → read produces same object).
156
- out[ws][planId] = {
157
- lastImportedAt: e.lastImportedAt,
158
- lastImportedRevision: e.lastImportedRevision,
159
- lastImportedVersion: e.lastImportedVersion,
160
- };
161
- }
162
- }
163
- return out;
164
- }
165
- /**
166
- * Validate the shape of a parsed lockfile. Throws `LockfileError`
167
- * with `code: 'malformed_entry'` if any entry is missing required
168
- * fields or has wrong types. Returns the validated object cast to
169
- * `Lockfile`.
170
- */
171
- function validateShape(parsed, filePath) {
172
- for (const [ws, plans] of Object.entries(parsed)) {
173
- if (plans === null || typeof plans !== 'object' || Array.isArray(plans)) {
174
- throw new LockfileError(`malformed lockfile at ${filePath}: entry for workspace '${ws}' must be an object, got ${describe(plans)}`, 'malformed_entry');
175
- }
176
- for (const [planId, entry] of Object.entries(plans)) {
177
- if (entry === null || typeof entry !== 'object' || Array.isArray(entry)) {
178
- throw new LockfileError(`malformed lockfile at ${filePath}: entry for ${ws}/${planId} must be an object, got ${describe(entry)}`, 'malformed_entry');
179
- }
180
- const e = entry;
181
- if (typeof e.lastImportedRevision !== 'string') {
182
- throw new LockfileError(`malformed lockfile at ${filePath}: ${ws}/${planId}.lastImportedRevision must be a string, got ${describe(e.lastImportedRevision)}`, 'malformed_entry');
183
- }
184
- if (!isWellFormedRevision(e.lastImportedRevision)) {
185
- throw new LockfileError(`malformed lockfile at ${filePath}: ${ws}/${planId}.lastImportedRevision must match 'sha256:<64-hex>', got '${e.lastImportedRevision}'`, 'malformed_entry');
186
- }
187
- if (typeof e.lastImportedVersion !== 'number' || !Number.isInteger(e.lastImportedVersion) || e.lastImportedVersion < 1) {
188
- throw new LockfileError(`malformed lockfile at ${filePath}: ${ws}/${planId}.lastImportedVersion must be a positive integer, got ${describe(e.lastImportedVersion)}`, 'malformed_entry');
189
- }
190
- if (typeof e.lastImportedAt !== 'string' || Number.isNaN(Date.parse(e.lastImportedAt))) {
191
- throw new LockfileError(`malformed lockfile at ${filePath}: ${ws}/${planId}.lastImportedAt must be an ISO-8601 timestamp, got ${describe(e.lastImportedAt)}`, 'malformed_entry');
192
- }
193
- }
194
- }
195
- return parsed;
196
- }
197
- function describe(value) {
198
- if (value === null)
199
- return 'null';
200
- if (Array.isArray(value))
201
- return 'array';
202
- return typeof value;
203
- }
@@ -1,191 +0,0 @@
1
- {
2
- "$schema": "http://json-schema.org/draft-07/schema#",
3
- "$id": "https://yolo.studio/schemas/plan-frontmatter.json",
4
- "title": "YOLO Studio Plan Frontmatter",
5
- "description": "Schema for the YAML frontmatter of a `.yolo/plans/<slug>.md` file. Mirrors the WorkPlan TypeScript type in common-api/src/types/work.ts. Lossless round-trip with the canonicalizer at packages/yolo-cli/src/canonicalizer.ts.",
6
- "type": "object",
7
- "required": [
8
- "planId",
9
- "name",
10
- "state",
11
- "failurePolicy",
12
- "steps"
13
- ],
14
- "additionalProperties": false,
15
- "properties": {
16
- "planId": {
17
- "type": "string",
18
- "pattern": "^[a-zA-Z0-9][a-zA-Z0-9_-]{0,127}$",
19
- "description": "Workspace-scoped slug. Must equal the file stem (e.g., `final-launch.md` → `planId: final-launch`). Substrate-side regex enforced at /internal/work create_plan."
20
- },
21
- "name": {
22
- "type": "string",
23
- "minLength": 1,
24
- "maxLength": 80,
25
- "description": "Human-readable Plan name. Tighter character-class rules (Unicode-aware) live in semantic validation, not in this schema (Draft-07 `pattern` runs through validators that don't all support `\\p{L}`/`\\p{N}` consistently)."
26
- },
27
- "state": {
28
- "type": "string",
29
- "enum": ["draft", "active", "archived"]
30
- },
31
- "failurePolicy": {
32
- "type": "string",
33
- "enum": ["pause-and-wait", "abort-run", "proceed-on-non-blocked", "auto-retry"]
34
- },
35
- "autoRetryCap": {
36
- "type": "integer",
37
- "minimum": 0,
38
- "description": "Required when failurePolicy is auto-retry; ignored otherwise."
39
- },
40
- "autoRetryFallback": {
41
- "type": "string",
42
- "enum": ["pause-and-wait", "abort-run", "proceed-on-non-blocked"],
43
- "description": "Fallback when auto-retry exhausts the cap."
44
- },
45
- "inputs": {
46
- "type": "array",
47
- "items": { "$ref": "#/definitions/PlanInputDecl" }
48
- },
49
- "integrationPolicy": {
50
- "type": "object",
51
- "additionalProperties": true,
52
- "description": "Free-form per-Plan integration knobs (base branch, merge strategy, etc.). Canonicalizer sorts keys lexicographically."
53
- },
54
- "steps": {
55
- "type": "array",
56
- "items": { "$ref": "#/definitions/StepDefinition" }
57
- }
58
- },
59
- "definitions": {
60
- "PlanInputDecl": {
61
- "type": "object",
62
- "required": ["name", "required"],
63
- "additionalProperties": false,
64
- "properties": {
65
- "name": { "type": "string", "minLength": 1 },
66
- "required": { "type": "boolean" },
67
- "default": { "type": "string", "description": "Default value (string-typed; substrate inputs are always string per R5)." },
68
- "description": { "type": "string" }
69
- }
70
- },
71
- "StepDefinition": {
72
- "type": "object",
73
- "required": ["stepId", "name", "mode", "gates"],
74
- "additionalProperties": false,
75
- "properties": {
76
- "stepId": { "type": "string", "minLength": 1 },
77
- "name": { "type": "string", "minLength": 1 },
78
- "description": { "type": "string" },
79
- "mode": {
80
- "type": "string",
81
- "enum": ["workstream", "test", "critic", "manual", "preview", "automation", "decision"]
82
- },
83
- "runner": { "type": "string" },
84
- "gates": {
85
- "type": "array",
86
- "items": { "$ref": "#/definitions/GateDefinition" }
87
- },
88
- "declaredOutputs": {
89
- "type": "array",
90
- "items": { "$ref": "#/definitions/StepDeclaredOutput" }
91
- },
92
- "failurePolicy": {
93
- "type": "string",
94
- "enum": ["pause-and-wait", "abort-run", "proceed-on-non-blocked", "auto-retry"]
95
- },
96
- "autoRetryCap": { "type": "integer", "minimum": 0 },
97
- "autoRetryFallback": {
98
- "type": "string",
99
- "enum": ["pause-and-wait", "abort-run", "proceed-on-non-blocked"]
100
- },
101
- "template": { "$ref": "#/definitions/StepTemplate" }
102
- }
103
- },
104
- "GateDefinition": {
105
- "type": "object",
106
- "required": ["gateId", "type", "config"],
107
- "additionalProperties": false,
108
- "properties": {
109
- "gateId": { "type": "string", "minLength": 1 },
110
- "type": {
111
- "type": "string",
112
- "enum": ["dependency", "dependency-failed", "dependency-any-of", "dependency-quorum", "acceptance", "artifact-presence", "test-result", "approval", "critique", "merge"]
113
- },
114
- "config": {
115
- "type": "object",
116
- "additionalProperties": true,
117
- "description": "Free-form per-gate-type config. Canonicalizer sorts keys lexicographically. Conventional shapes: dependency.requires (string[]); artifact-presence.{name,producerStepId}; test-result.{minPassRate,requiredSuites,retryFlakes}; critique.{rubric,minScore,reviewers}; merge.{baseBranch,allowedStrategies,requireGreenCi,blockOnConflict}."
118
- }
119
- }
120
- },
121
- "StepDeclaredOutput": {
122
- "type": "object",
123
- "required": ["name", "artifactType"],
124
- "additionalProperties": false,
125
- "properties": {
126
- "name": { "type": "string", "minLength": 1 },
127
- "artifactType": { "type": "string", "minLength": 1 },
128
- "required": { "type": "boolean" }
129
- }
130
- },
131
- "StepTemplate": {
132
- "type": "object",
133
- "additionalProperties": false,
134
- "properties": {
135
- "todoContent": { "type": "string" },
136
- "todoFile": { "type": "string" },
137
- "branch": { "type": "string" },
138
- "surfacesArtifacts": {
139
- "type": "array",
140
- "maxItems": 8,
141
- "uniqueItems": true,
142
- "items": { "type": "string", "minLength": 1, "maxLength": 64, "pattern": "\\S" },
143
- "description": "work.report_artifact artifactTypes to relay to the requester as they land (e.g. a preview URL), instead of only at run terminal. Default: none. Max 8 unique non-blank types, each \u2264 64 chars. NOTE: currently honored ONLY for assistant quick-job (ephemeral) runs; inert on a standard Plan Run (no channel to relay to)."
144
- },
145
- "metadata": {
146
- "type": "object",
147
- "additionalProperties": { "type": "string" },
148
- "description": "Free-form key-value metadata (string-valued). Canonicalizer sorts keys lexicographically."
149
- },
150
- "agentType": {
151
- "type": "string",
152
- "enum": ["claude", "codex", "opencode-yolo", "yolo", "yolo-code"],
153
- "description": "Item 16 follow-up — per-Step agent label (workstream-mode only). Forwarded to container-api's /lanes/:name/spawn-agent so the lane runner picks the matching adapter, AND used by the dispatcher to append the agent to the Plan Run's operators[] on Step Run spawn (addedReason 'step-spawn') so the agent fan grows to match actual execution. Must be in the substrate's container-spawnable set; the alias 'yolo-code' canonicalizes to 'yolo' (the canonical id token-minting expects) before persisted on the binding. test / critic / preview / automation modes don't use this field. Enum mirrors the server-side check in common-api/src/services/work/plan-validators.ts; keep them in sync."
154
- },
155
- "decision": {
156
- "type": "object",
157
- "additionalProperties": false,
158
- "required": ["prompt"],
159
- "properties": {
160
- "prompt": { "type": "string", "minLength": 1, "maxLength": 2000 },
161
- "options": {
162
- "type": "array",
163
- "items": {
164
- "type": "object",
165
- "additionalProperties": false,
166
- "required": ["id", "label"],
167
- "properties": {
168
- "id": { "type": "string", "minLength": 1 },
169
- "label": { "type": "string", "minLength": 1 },
170
- "description": { "type": "string" }
171
- }
172
- }
173
- }
174
- },
175
- "description": "Decision-mode config (mode: 'decision'). A human-in-the-loop choice gate: the Run PAUSES (pauseReasonStructured.kind 'awaiting-decision') and the operator resolves via work.resolve_decision, which records the choice, completes the Step, and resumes the Run. Requires `prompt`; `options` are author-supplied or, when omitted, derived from the Step's dependency / dependency-any-of candidate gates (the bake-off 'operator picks the winner' shape). Only valid on mode='decision' Steps. Mirrors the server-side check in common-api/src/services/work/plan-validators.ts."
176
- },
177
- "uiBehavior": {
178
- "type": "object",
179
- "additionalProperties": false,
180
- "properties": {
181
- "keepFullSizeOnTerminal": {
182
- "type": "boolean",
183
- "description": "SUBSTRATE_IMPROVEMENTS #31 addendum (2026-05-11) — keep this Step's tile at full chrome on the Run desktop after the Step Run reaches terminal success / skip / cancelled. Use sparingly: workstream / critic / test / automation Steps whose generated artifact (rendered dashboard, demo page, etc.) the operator wants to keep looking at after the agent finishes. Default false / undefined. Preview-mode and manual-mode Steps are exempt from compact-on-terminal regardless of this field — those modes' tiles always stay full."
184
- }
185
- },
186
- "description": "Plan-author UI hints. Currently the only field is `keepFullSizeOnTerminal`; future hints land here as additional properties (each closed-schema)."
187
- }
188
- }
189
- }
190
- }
191
- }
@@ -1,270 +0,0 @@
1
- /**
2
- * `yolo plan validate` core (Phase 8c.1).
3
- *
4
- * Pure offline validation of a `.yolo/plans/<slug>.md` plan file. No
5
- * network I/O. Three checks, in order:
6
- *
7
- * 1. **Parse** — file must split cleanly into YAML frontmatter +
8
- * markdown body via the standard `---` delimiters.
9
- * 2. **Schema** — frontmatter must satisfy the Draft-07 JSON Schema
10
- * shipped at `src/plan-frontmatter.schema.json` (a copy of the
11
- * repo's `.yolo/plans/.schema.json`; a drift-check test enforces
12
- * they stay byte-equal).
13
- * 3. **Canonical** — running the file through `canonicalizePlanFile`
14
- * must return the same bytes. This is the parity that
15
- * `yolo plan import` will rely on, and that 8c.5's CI check
16
- * enforces across all `.yolo/plans/*.md` files in the repo.
17
- *
18
- * The first failing check short-circuits subsequent ones (a parse
19
- * failure makes "schema" / "canonical" meaningless). Successful checks
20
- * still run all three and report all errors when the `collectAll`
21
- * flag is true (used by tests; the CLI prints the first one).
22
- *
23
- * Exit codes (used by cli.ts):
24
- * - 0 = valid
25
- * - 1 = validation failure (parse / schema / canonical)
26
- * - 64 = usage error (missing file argument, file not found at path)
27
- *
28
- * Out of scope (lands in 8c.3 import):
29
- * - planId-vs-filename equality (semantic check; the import command
30
- * enforces it because the file path is the source of truth there).
31
- * - Stricter `name` regex (semantic, Unicode-aware — was deliberately
32
- * dropped from the schema in Phase 8b Round 1 because Draft-07
33
- * pattern doesn't support `\\p{L}`/`\\p{N}` consistently across
34
- * validators).
35
- * - Cross-step / cross-gate semantic checks (gate.requires resolves
36
- * to a sibling step, declaredOutput names unique within a step,
37
- * etc.) — these belong in plan-validators.ts on the server side
38
- * and run at import-time anyway.
39
- *
40
- * No-coercion rule (Phase 8 contract; Codex 8c.1 Round 1 Medium):
41
- * The Phase 8 design and the canonicalizer's docstring both pin a
42
- * "no boolean/numeric coercion" rule on validate/import. js-yaml's
43
- * default `load` happily coerces unquoted scalars
44
- * (`minPassRate: 0.95` → JS number 0.95). For schema-typed
45
- * positions (PlanInputDecl.required: boolean, autoRetryCap: integer,
46
- * StepDeclaredOutput.required: boolean, etc.) coercion is fine
47
- * because Ajv enforces the declared type. For the free-form maps
48
- * (`gate.config`, `integrationPolicy`) the JSON Schema is
49
- * intentionally `additionalProperties: true` and can't catch silent
50
- * type drift. The `assertStringValuedFreeFormMap` walk below is
51
- * the enforcement point: every leaf in those maps must be a string
52
- * or array of strings, and the user is told to quote the value if
53
- * not.
54
- * (`template.metadata` is already string-locked at the schema level
55
- * via `additionalProperties: { type: string }`, so a coerced int
56
- * there fails Ajv directly — no extra walk needed.)
57
- */
58
- import { readFileSync } from 'node:fs';
59
- import { dirname } from 'node:path';
60
- import { fileURLToPath } from 'node:url';
61
- import path from 'node:path';
62
- import yaml from 'js-yaml';
63
- import Ajv from 'ajv';
64
- import { canonicalizePlanFile } from './canonicalizer.js';
65
- const __dirname = dirname(fileURLToPath(import.meta.url));
66
- const SCHEMA_PATH = path.join(__dirname, 'plan-frontmatter.schema.json');
67
- // Lazy-load + cache: keeps test parallelism cheap. The schema is
68
- // small (<10 KB), so synchronous read + JSON.parse on first use is
69
- // fine.
70
- let cachedSchema;
71
- function getSchema() {
72
- if (!cachedSchema) {
73
- cachedSchema = JSON.parse(readFileSync(SCHEMA_PATH, 'utf8'));
74
- }
75
- return cachedSchema;
76
- }
77
- let cachedValidator = null;
78
- function getValidator() {
79
- if (!cachedValidator) {
80
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
81
- const ajv = new Ajv({ allErrors: true });
82
- cachedValidator = ajv.compile(getSchema());
83
- }
84
- return cachedValidator;
85
- }
86
- const FRONTMATTER_RE = /^---\r?\n([\s\S]*?)\r?\n---\r?\n([\s\S]*)$/;
87
- /**
88
- * Validate the contents of a plan file (already read into memory).
89
- * Pure — no fs access; the caller owns reading the file. Used by both
90
- * the CLI (`validatePlanFile` wraps a `readFileSync`) and tests
91
- * (which feed in synthesized strings).
92
- */
93
- export function validatePlanText(text) {
94
- const errors = [];
95
- // 1) Parse
96
- const match = text.match(FRONTMATTER_RE);
97
- if (!match) {
98
- return {
99
- ok: false,
100
- errors: [
101
- {
102
- kind: 'parse',
103
- message: 'plan file must start with `---` frontmatter delimiter, contain a closing `---`, and have a body — no match',
104
- },
105
- ],
106
- };
107
- }
108
- const [, fmText, body] = match;
109
- let frontmatter;
110
- try {
111
- const loaded = yaml.load(fmText);
112
- if (loaded === null || typeof loaded !== 'object' || Array.isArray(loaded)) {
113
- return {
114
- ok: false,
115
- errors: [
116
- {
117
- kind: 'parse',
118
- message: 'frontmatter must be a YAML mapping (object), not a list or scalar',
119
- },
120
- ],
121
- };
122
- }
123
- frontmatter = loaded;
124
- }
125
- catch (err) {
126
- const msg = err instanceof Error ? err.message : String(err);
127
- return {
128
- ok: false,
129
- errors: [{ kind: 'parse', message: `YAML parse failed: ${msg}` }],
130
- };
131
- }
132
- // 2) Schema
133
- const validate = getValidator();
134
- const ok = validate(frontmatter);
135
- if (!ok) {
136
- const ajvErrors = validate.errors ?? [];
137
- for (const err of ajvErrors) {
138
- errors.push({
139
- kind: 'schema',
140
- message: err.message ?? 'schema validation failed',
141
- path: err.dataPath || '',
142
- });
143
- }
144
- }
145
- // 2b) No-coercion rule on free-form maps. See header comment.
146
- if ('integrationPolicy' in frontmatter) {
147
- assertStringValuedFreeFormMap(frontmatter.integrationPolicy, '.integrationPolicy', errors);
148
- }
149
- if (Array.isArray(frontmatter.steps)) {
150
- for (let i = 0; i < frontmatter.steps.length; i++) {
151
- const step = frontmatter.steps[i];
152
- if (!step || !Array.isArray(step.gates))
153
- continue;
154
- for (let j = 0; j < step.gates.length; j++) {
155
- const gate = step.gates[j];
156
- if (gate && 'config' in gate) {
157
- assertStringValuedFreeFormMap(gate.config, `.steps[${i}].gates[${j}].config`, errors);
158
- }
159
- }
160
- }
161
- }
162
- // 3) Canonical
163
- // Only meaningful when the parse step succeeded — schema fails
164
- // don't preclude canonicalization, so we always run this check too
165
- // and the caller gets a complete report.
166
- const canonical = canonicalizePlanFile(frontmatter, body);
167
- if (canonical !== text) {
168
- errors.push({
169
- kind: 'canonical',
170
- message: 'file is not in canonical form (frontmatter field order / lex-sort / body normalization). Run `yolo plan import` to rewrite, or canonicalize manually.',
171
- });
172
- }
173
- if (errors.length > 0) {
174
- return { ok: false, errors };
175
- }
176
- const planId = typeof frontmatter.planId === 'string' ? frontmatter.planId : '';
177
- return { ok: true, planId, bytes: text.length };
178
- }
179
- /**
180
- * Read a plan file from disk and validate it.
181
- *
182
- * Throws `ENOENT`-style errors through the caller (cli.ts maps them
183
- * to exit code 64 + a friendly message).
184
- */
185
- export function validatePlanFile(filePath) {
186
- const text = readFileSync(filePath, 'utf8');
187
- return validatePlanText(text);
188
- }
189
- /**
190
- * Walk a free-form map (gate.config / integrationPolicy) recursively
191
- * and reject any non-string LEAF. Phase 8 + the 8b canonicalizer
192
- * explicitly support nested mappings/arrays in these positions
193
- * (`sortNestedKeys` recurses through them); the no-coercion contract
194
- * applies only at the leaves — every terminal value must be a string,
195
- * because js-yaml's default load coerces unquoted scalars to JS
196
- * booleans/numbers and the JSON Schema's `additionalProperties: true`
197
- * can't catch it (Codex 8c.1 Round 1 Medium).
198
- *
199
- * Recursion rules:
200
- * - object → recurse into each property (path: `.key`).
201
- * - array → recurse into each item (path: `[i]`).
202
- * - string → OK (leaf).
203
- * - anything else (number / boolean / null / undefined) → REJECT.
204
- *
205
- * The top-level value (gate.config or integrationPolicy itself) MUST
206
- * be a mapping; a list or scalar there is also a structural error.
207
- *
208
- * Error paths use dot/bracket notation matching Ajv's `dataPath` style
209
- * so the rendered output stays consistent.
210
- */
211
- function assertStringValuedFreeFormMap(value, pathPrefix, errors) {
212
- if (value === undefined)
213
- return;
214
- if (value === null || typeof value !== 'object' || Array.isArray(value)) {
215
- errors.push({
216
- kind: 'schema',
217
- path: pathPrefix,
218
- message: 'free-form map must be a YAML mapping (object), not a list, scalar, or null',
219
- });
220
- return;
221
- }
222
- walkLeaves(value, pathPrefix, errors);
223
- }
224
- /**
225
- * Recursive helper: walk a value of any shape and report non-string
226
- * leaves. Used by `assertStringValuedFreeFormMap` once we've confirmed
227
- * the outer value is a mapping.
228
- */
229
- function walkLeaves(value, pathPrefix, errors) {
230
- if (typeof value === 'string')
231
- return;
232
- if (Array.isArray(value)) {
233
- for (let i = 0; i < value.length; i++) {
234
- walkLeaves(value[i], `${pathPrefix}[${i}]`, errors);
235
- }
236
- return;
237
- }
238
- if (value !== null && typeof value === 'object') {
239
- for (const [key, leaf] of Object.entries(value)) {
240
- walkLeaves(leaf, `${pathPrefix}.${key}`, errors);
241
- }
242
- return;
243
- }
244
- errors.push({
245
- kind: 'schema',
246
- path: pathPrefix,
247
- message: `value must be a string (got ${describeJsType(value)}). YAML scalar coercion is disallowed in free-form config maps; quote the value explicitly to keep it as a string`,
248
- });
249
- }
250
- function describeJsType(value) {
251
- if (value === null)
252
- return 'null';
253
- if (Array.isArray(value))
254
- return 'array';
255
- return typeof value;
256
- }
257
- /**
258
- * Render a `ValidationFail` result as human-readable text for the
259
- * CLI. One line per error, with kind tag + optional path. Caller
260
- * appends a trailing newline if needed.
261
- */
262
- export function formatErrors(errors) {
263
- return errors
264
- .map((e) => {
265
- const tag = `[${e.kind}]`;
266
- const loc = e.path ? ` (at ${e.path})` : '';
267
- return `${tag}${loc} ${e.message}`;
268
- })
269
- .join('\n');
270
- }