YAML Foundations
YAML data serialization: collections, scalar resolution, quoting, blocks, documents, diagnostics, aliases, presentation-aware edits, JSON boundaries and separate application validation. No deployment-system integration or general language conformance claim.
Audience: Learners familiar with basic JavaScript values and the Data Formats pack.
Practice: 4 to 6 hours.
Website reference edition
This introductory material is available here for reading and practice planning. New offline workbench exports, PDF and ZIP editions for these additions are not published. The released Atlas 0.11 downloads cover the earlier 19 packs only. These pages do not run teaching code or contact an AI service.
Runtime and boundaries
Export one .cjs entry, all its listed companions and YAML support.cjs into a new owned practice folder. Run /usr/local/bin/node --max-old-space-size=64 "YAML 01 Collections.cjs", replacing the filename as needed. The support module uses the already installed /usr/local/lib/node_modules/openclaw/node_modules/yaml/dist/index.js (yaml 2.9.0). This application-bundled path is host-specific and may change; no dependency is copied or installed. Drivers read only their fixed local companions, never write configuration, and do not make network calls. Helper limits are 4096 UTF-8 bytes, four documents and a conversion alias bound of 10. These are tiny-fixture contracts, not an arbitrary-input sandbox; file reads occur before the byte check, so it is not a bounded file reader. YAML 1.2/core is explicit; known-tag extensions and merge keys are disabled. Warnings and version overrides are rejected by local policy. HTML exports text and never launches Node.
Lessons
Treat YAML as data, with a chosen parser contract
A YAML document describes values; the JavaScript driver is only the installed parser host. Keep authored YAML separate from code and read it as text. Record version, schema and parser options before predicting types. In this pack, YAML 1.2 core is selected, merge-key support and known-tag extensions are disabled, duplicate keys are checked and all diagnostics are inspected. Successful parsing establishes neither application validity nor safety for a real service. No deployment configuration is consumed here.
Mappings, sequences and scalar types
Use a sequence when order is part of the data meaning. A mapping associates keys with values; do not invent meaning from its printed order. Indentation uses spaces. The selected core rules resolve examples such as true and ~ to boolean and null, while yes stays text. Quote values that must be strings and inspect their actual type after parsing. The helper stringKeys option converts scalar mapping keys to strings and rejects collection keys; it is a library policy, not a claim that YAML only permits string keys.
Quote and fold deliberately
Choose scalar style by intended value. Single quotes keep backslashes literal and double an internal apostrophe; double quotes support YAML escapes. A colon followed by separation or a hash in plain scalar context can change how text is read. Literal and folded blocks differ in how line breaks become value content, and chomping indicators affect trailing breaks. Predict the exact string with JSON.stringify during a small test, then check the result instead of judging only the YAML appearance.
Distinguish one document from a stream
A stream may contain several documents separated by markers. Use the matching parser entry point and decide the permitted count. This pack allows at most four documents and at most 4096 UTF-8 input bytes for its tiny authored fixtures. The limits are local teaching contracts, not protection against every expensive or malicious input. An explicit version directive can override a default option, so the helper rejects documents declaring anything other than 1.2. No 1.1 compatibility is claimed.
Check diagnostics before converting
parseDocument returns a Document that can carry errors and warnings. Do not assume a returned object is valid or convert it while ignoring those arrays. This installed Document.toJS does not replace the explicit diagnostic gate. Duplicate keys and tab indentation are parser errors in our tests. An unavailable tag produces a warning; rejecting warnings is a separate application policy. Use the documented diagnostic code where available and keep parser, conversion and application-contract failures distinct.
Aliases are relationships, not copies
An anchor names a node for later aliases in a document. The installed conversion preserves the shared mapping in our fixture, so editing one alias changes the other view. Check alias limits at conversion, and use zero when the caller must reject aliases. A positive alias count does not bound input bytes, nesting, cycles or all subsequent work. This pack tests small authored aliases only, excludes merge-key behavior and never constructs an expansion bomb.
Preserve presentation only when that is the goal
Plain values do not retain source comments, quote choices or whitespace. The Document API can edit values while retaining selected presentation details; example 08 verifies one actual comment. That is different from exact byte preservation. For new data, serialize values instead of constructing YAML by string concatenation. Test a value round trip and specify any formatting requirements separately. Do not assume arbitrary YAML is directly representable as JSON: numbers, keys, sharing and cycles require explicit conversion contracts.
Validate the application and record evidence
After parsing, check allowed keys, types, ranges and lengths before using values. Exercise A applies a deliberately small record contract; JSON Schema is a separate Atlas scope. Keep failures observable and test boundaries independently of syntax. The examples use fixed local files and authored in-memory inputs, never live system configuration or secrets. Recorded execution covers only the installed Node and yaml library on one macOS arm64 host; it is not full YAML conformance, cross-platform evidence or a security certification.
Reference cards
Mapping: title: Read
A key/value association; printed key order is not the data contract.
Sequence: - Read - Code
An ordered list of values.
Indentation: Two spaces for this pack
Use spaces consistently; tabs are not indentation here.
Scalar resolution: version: '1.2', schema: 'core'
Choose explicit parser resolution rules; verify declared document version too.
Text values: 'true' / !!str 20
Keep these values as strings under the chosen schema.
Quoted apostrophe: 'It''s practice'
Double an apostrophe in single-quoted YAML.
Literal block: |-
Preserve interior line breaks; strip trailing breaks in the shown fixture.
Folded block: >-
Fold ordinary same-indent lines; strip trailing breaks.
Document markers: --- / ...
Start and end document boundaries in a stream.
Diagnostics: doc.errors / doc.warnings
Inspect before conversion; warnings and parser errors are distinct.
Aliases: &task / *task
Name and reuse a node; not a deep-copy operation.
Conversion bound: doc.toJS({maxAliasCount: 0})
Reject aliases; a positive bound is not a complete resource defense.
Document edit: doc.set('minutes', 30)
Change a value while retaining some presentation information.
Serialization: YAML.stringify(value, options)
Serialize values; presentation style may change.
JSON boundary: Number.isFinite / Number.isSafeInteger
Check the numeric contract before relying on JSON conversion.
Application validation: validate(parsedValue)
A separate step; YAML core schema is not JSON Schema.
Support file: YAML support.cjs
const fs = require('node:fs');
const path = require('node:path');
const YAML = require('/usr/local/lib/node_modules/openclaw/node_modules/yaml/dist/index.js');
const options = {version: '1.2', schema: 'core', merge: false,
resolveKnownTags: false, uniqueKeys: true, strict: true,
stringKeys: true, prettyErrors: false};
function bounded(text) {
if (typeof text !== 'string' || Buffer.byteLength(text, 'utf8') > 4096)
throw new RangeError('Input contract: at most 4096 UTF-8 bytes');
return text;
}
function checked(doc) {
if (doc.errors.length) throw new Error('YAML parse: ' + doc.errors[0].code);
if (doc.warnings.length) throw new Error('YAML warning policy: ' + doc.warnings[0].code);
if (doc.directives.yaml.version !== '1.2')
throw new Error('YAML version policy: only 1.2');
return doc;
}
function inspectOne(text) { return checked(YAML.parseDocument(bounded(text), options)); }
function parseOne(text) { return inspectOne(text).toJS({maxAliasCount: 10}); }
function parseStream(text) {
const docs = YAML.parseAllDocuments(bounded(text), options);
if (docs.length > 4) throw new RangeError('Document contract: at most four');
return docs.map(doc => checked(doc).toJS({maxAliasCount: 10}));
}
function loadText(name) {
if (!name || path.basename(name) !== name || name === '.' || name === '..')
throw new Error('Use an authored companion basename');
return bounded(fs.readFileSync(path.join(__dirname, name), 'utf8'));
}
module.exports = {YAML, options, bounded, checked, inspectOne, parseOne, parseStream, loadText};
Support file: YAML run instructions.txt
Export one .cjs entry, all its listed companions and YAML support.cjs into a new owned practice folder. Run /usr/local/bin/node --max-old-space-size=64 "YAML 01 Collections.cjs", replacing the filename as needed. The support module uses the already installed /usr/local/lib/node_modules/openclaw/node_modules/yaml/dist/index.js (yaml 2.9.0). This application-bundled path is host-specific and may change; no dependency is copied or installed. Drivers read only their fixed local companions, never write configuration, and do not make network calls. Helper limits are 4096 UTF-8 bytes, four documents and a conversion alias bound of 10. These are tiny-fixture contracts, not an arbitrary-input sandbox; file reads occur before the byte check, so it is not a bounded file reader. YAML 1.2/core is explicit; known-tag extensions and merge keys are disabled. Warnings and version overrides are rejected by local policy. HTML exports text and never launches Node.
Expected YAML input rejections
Four authored YAML inputs are deliberately rejected: two parser errors, one conversion error and one local warning-policy rejection. These are separate from twelve accepted example drivers. YAML data is never executed as JavaScript source.
Examples and practice
All code and values below are inert reading material. Preserve each exact filename and companion when making your own practice copy.
YAML 01 - Collections and typed values
The authored mapping contains a nested mapping and a sequence. The JavaScript driver projects fields in an explicit order; it does not turn YAML mapping order into an application contract.
Filename: YAML 01 Collections.cjs
const {parseOne, loadText} = require('./YAML support.cjs');
const value = parseOne(loadText('YAML 01 Task.yaml'));
console.log(value.task.title + ': ' + value.task.minutes);
console.log('Topics: ' + value.topics.join(', '));
console.log('Root array: ' + Array.isArray(value));
Expected output:
Read: 20 Topics: YAML, JSON Root array: false
Companion: YAML 01 Task.yaml
task: title: Read minutes: 20 topics: - YAML - JSON
Separate expected rejection
- code
task: minutes: 20
- diagnostic
YAML parse: TAB_AS_INDENT
- category
YAML parsing error; tab indentation
- phase
parse
Authored input parsed or converted as data, deliberately rejected; not a JavaScript compiler fixture.
YAML 02 - Core scalar resolution
The selected YAML 1.2 core schema resolves these plain scalars. Quotes and the explicit core !!str tag keep text as text. The helper rejects a document declaring YAML 1.1 instead of silently accepting a different declared version.
Filename: YAML 02 Scalars.cjs
const {parseOne, loadText} = require('./YAML support.cjs');
const value = parseOne(loadText('YAML 02 Scalars.yaml'));
console.log(JSON.stringify([value.word, value.flag, value.quoted, value.empty, value.forced]));
console.log([value.word, value.flag, value.quoted, value.forced].map(x => typeof x).join(', '));
Expected output:
["yes",true,"true",null,"20"] string, boolean, string, string
Companion: YAML 02 Scalars.yaml
word: yes flag: true quoted: "true" empty: ~ forced: !!str 20
YAML 03 - Quoting is format-specific
Single-quoted YAML doubles an apostrophe and keeps a backslash literal. Double quotes interpret YAML escapes. Quoting a colon and hash avoids accidentally introducing a mapping delimiter or comment in this fixture.
Filename: YAML 03 Quotes.cjs
const {parseOne, loadText} = require('./YAML support.cjs');
const value = parseOne(loadText('YAML 03 Quotes.yaml'));
console.log(value.path);
console.log(value.title);
console.log(JSON.stringify(value.lines));
console.log(value.note);
Expected output:
C:\notes It's practice "Line\nTwo" Read: #1
Companion: YAML 03 Quotes.yaml
path: 'C:\notes' title: 'It''s practice' lines: "Line\nTwo" note: "Read: #1"
YAML 04 - Literal and folded blocks
For these ordinary equally indented lines, literal style preserves the interior newline while folded style turns it into a space. The minus and plus chomping indicators control trailing line breaks. Folding has further rules for blank and more-indented lines; this fixture does not establish all of them.
Filename: YAML 04 Blocks.cjs
const {parseOne, loadText} = require('./YAML support.cjs');
const value = parseOne(loadText('YAML 04 Blocks.yaml'));
console.log(JSON.stringify(value.literal));
console.log(JSON.stringify(value.folded));
console.log(JSON.stringify(value.kept));
Expected output:
"Read\nCode" "Read Code" "Read\n\n"
Companion: YAML 04 Blocks.yaml
literal: |- Read Code folded: >- Read Code kept: |+ Read
YAML 05 - Document boundaries
The authored stream contains two explicit documents. The helper checks every document before conversion and permits at most four in this teaching contract. A one-document API rejecting the stream is an expected handled outcome, not a failed example driver.
Filename: YAML 05 Documents.cjs
const {parseOne, parseStream, loadText} = require('./YAML support.cjs');
const text = loadText('YAML 05 Documents.yaml');
console.log(JSON.stringify(parseStream(text).map(x => x.title)));
try { parseOne(text); console.log('Unexpected acceptance'); }
catch (error) {
if (!error.message.includes('MULTIPLE_DOCS')) throw error;
console.log('Single-document API: rejected');
}
Expected output:
["Read","Code"] Single-document API: rejected
Companion: YAML 05 Documents.yaml
--- title: Read ... --- title: Code
YAML 06 - Errors and warnings are separate
parseDocument can return a Document with diagnostics rather than throwing. This driver inspects those arrays without converting the erroneous document. The unknown tag is a warning in this parser; rejecting that warning is our explicit local policy, not a claim that all YAML warnings are syntax errors.
Filename: YAML 06 Diagnostics.cjs
const {YAML, options, parseOne, loadText} = require('./YAML support.cjs');
const duplicate = YAML.parseDocument(loadText('YAML 06 Duplicate.yaml'), options);
const taggedText = loadText('YAML 06 Unknown tag.yaml');
const tagged = YAML.parseDocument(taggedText, options);
console.log('Errors: ' + duplicate.errors.map(x => x.code).join(', '));
console.log('Warnings: ' + tagged.warnings.map(x => x.code).join(', '));
try { parseOne(taggedText); console.log('Unexpected acceptance'); }
catch (error) {
if (!error.message.includes('YAML warning policy: TAG_RESOLVE_FAILED')) throw error;
console.log('Warning policy: rejected');
}
Expected output:
Errors: DUPLICATE_KEY Warnings: TAG_RESOLVE_FAILED Warning policy: rejected
Companion: YAML 06 Duplicate.yaml
minutes: 10 minutes: 20
Companion: YAML 06 Unknown tag.yaml
note: !atlas value
Separate expected rejection
- code
minutes: 10 minutes: 20
- diagnostic
YAML parse: DUPLICATE_KEY
- category
YAML parsing error; duplicate mapping key
- phase
parse
Authored input parsed or converted as data, deliberately rejected; not a JavaScript compiler fixture.
Separate expected rejection
- code
note: !atlas value
- diagnostic
YAML warning policy: TAG_RESOLVE_FAILED
- category
Local warning rejection policy; not a parser syntax error
- phase
warning-policy
Authored input parsed or converted as data, deliberately rejected; not a JavaScript compiler fixture.
YAML 07 - Aliases share a value
The installed converter preserves this shared mapping relationship; an alias is not a deep copy. Alias checks happen during toJS conversion. A zero limit rejects aliases; a positive limit does not bound all parser work, object depth, cycles or application behavior. No expansion bomb is tested.
Filename: YAML 07 Aliases.cjs
const {inspectOne, loadText} = require('./YAML support.cjs');
const doc = inspectOne(loadText('YAML 07 Aliases.yaml'));
const value = doc.toJS({maxAliasCount: 10});
console.log('Same object: ' + (value.base === value.copy));
value.copy.title = 'Code';
console.log('Base title after alias edit: ' + value.base.title);
try { doc.toJS({maxAliasCount: 0}); console.log('Unexpected acceptance'); }
catch (error) {
if (!(error instanceof ReferenceError)) throw error;
console.log('Aliases disabled: rejected');
}
Expected output:
Same object: true Base title after alias edit: Code Aliases disabled: rejected
Companion: YAML 07 Aliases.yaml
base: &task title: Read copy: *task
Separate expected rejection
- code
copy: *missing
- diagnostic
Unresolved alias
- category
YAML-to-JavaScript conversion error; unresolved alias
- phase
conversion
Authored input parsed or converted as data, deliberately rejected; not a JavaScript compiler fixture.
YAML 08 - Edit a document without promising byte preservation
The Document API retains the shown comment while changing a scalar. This is an observed fixture result, not a guarantee that every source character or comment placement survives every transformation. Converting to plain objects and serializing again loses presentation information.
Filename: YAML 08 Comments.cjs
const {inspectOne, parseOne, loadText} = require('./YAML support.cjs');
const text = loadText('YAML 08 Comments.yaml');
const doc = inspectOne(text);
doc.set('minutes', 30);
const rewritten = String(doc);
console.log('Comment retained: ' + rewritten.includes('# Keep this label'));
console.log('Minutes: ' + parseOne(rewritten).minutes);
console.log('Byte-identical: ' + (rewritten === text));
Expected output:
Comment retained: true Minutes: 30 Byte-identical: false
Companion: YAML 08 Comments.yaml
# Practice note title: Read # Keep this label minutes: 20
YAML 09 - JSON conversion has a contract
YAML core can represent values that do not have the intended JSON meaning. The default JavaScript numeric representation cannot exactly retain this authored large integer. JSON.stringify changes NaN and Infinity to null in the shown array. Validate finite safe numbers and a supported acyclic value shape before conversion; aliases, non-string keys and other types need separate policies.
Filename: YAML 09 JSON boundary.cjs
const {parseOne, loadText} = require('./YAML support.cjs');
const value = parseOne(loadText('YAML 09 Numeric boundary.yaml'));
console.log('Nonfinite values: ' + value.values.every(x => !Number.isFinite(x)));
console.log('Safe integer: ' + Number.isSafeInteger(value.count));
console.log('JSON loses nonfinite values: ' + (JSON.stringify(value.values) === '[null,null]'));
Expected output:
Nonfinite values: true Safe integer: false JSON loses nonfinite values: true
Companion: YAML 09 Numeric boundary.yaml
values: [.nan, .inf] count: 9007199254740993
YAML exercise A - Validate a small record
The application requires exactly two keys and validates the parsed value separately. The title bound uses JavaScript UTF-16 length, not grapheme count. Integer/range checks reject boolean and text minutes. This hand-written check is not JSON Schema validation or a general schema engine.
Filename: YAML exercise A Study contract.cjs
const {parseOne, loadText} = require('./YAML support.cjs');
function study(text) {
const value = parseOne(text);
if (!value || Array.isArray(value) || typeof value !== 'object' ||
Object.keys(value).sort().join(',') !== 'minutes,title' ||
typeof value.title !== 'string' || value.title.length < 1 || value.title.length > 40 ||
!Number.isInteger(value.minutes) || value.minutes < 0 || value.minutes > 120)
throw new Error('Study contract rejected');
return value.title + ': ' + value.minutes;
}
if (require.main === module) console.log(study(loadText('YAML exercise A Study.yaml')));
module.exports = {study};
Expected output:
Read: 20
Companion: YAML exercise A Study.yaml
title: Read minutes: 20
Practice: Accept exactly title and minutes. Require a title of 1 to 40 JavaScript UTF-16 units and an integer from 0 through 120. Reject other shapes and extra keys before using the record.
YAML exercise B - Serialize values rather than splice text
The serializer chooses quoting or block style for the values. The test checks restored values and the final newline, not one particular presentation style. The authored object is already restricted to an ordinary JSON-shaped mapping with a small finite integer.
Filename: YAML exercise B Serialize values.cjs
const {YAML, options, parseOne} = require('./YAML support.cjs');
const original = {title: 'Read: #1\nThen code', minutes: 25};
const text = YAML.stringify(original, options);
const restored = parseOne(text);
console.log(JSON.stringify(restored.title));
console.log('Values match: ' + (restored.title === original.title && restored.minutes === original.minutes));
console.log('Ends with newline: ' + text.endsWith('\n'));
Expected output:
"Read: #1\nThen code" Values match: true Ends with newline: true
Practice: Serialize a title containing a colon, hash and newline with a numeric minutes value. Reparse it and verify the intended values without comparing formatting byte-for-byte.
YAML exercise C - Eight observable contract cases
Eight fixed cases exercise both boundaries and invalid data types/shapes. An assertion failure is not intentionally produced. The helper checks parser diagnostics separately, so unexpected parser failures do not masquerade as expected application rejections.
Filename: YAML exercise C Contract checks.cjs
const assert = require('node:assert/strict');
const {study} = require('./YAML exercise A Study contract.cjs');
const cases = [
['title: Read\nminutes: 0\n', true],
['title: Read\nminutes: 120\n', true],
['title: Read\nminutes: -1\n', false],
['title: Read\nminutes: 121\n', false],
['title: Read\nminutes: true\n', false],
['title: Read\nminutes: "20"\n', false],
['title: Read\nminutes: 20\nextra: true\n', false],
['title: Read\n', false]
];
for (const [text, expected] of cases) {
let accepted;
try { study(text); accepted = true; }
catch (error) {
if (error.message !== 'Study contract rejected') throw error;
accepted = false;
}
assert.equal(accepted, expected);
}
console.log('Contract cases: ' + cases.length + ' passed');
Expected output:
Contract cases: 8 passed
Companion: YAML exercise A Study contract.cjs
const {parseOne, loadText} = require('./YAML support.cjs');
function study(text) {
const value = parseOne(text);
if (!value || Array.isArray(value) || typeof value !== 'object' ||
Object.keys(value).sort().join(',') !== 'minutes,title' ||
typeof value.title !== 'string' || value.title.length < 1 || value.title.length > 40 ||
!Number.isInteger(value.minutes) || value.minutes < 0 || value.minutes > 120)
throw new Error('Study contract rejected');
return value.title + ': ' + value.minutes;
}
if (require.main === module) console.log(study(loadText('YAML exercise A Study.yaml')));
module.exports = {study};
Practice: Test both accepted boundaries, values just outside the range, boolean and text minutes, an extra key and a missing key. Fail loudly if observed acceptance differs from the table.
Prompt templates
Planning text only; no AI service or export control is activated here.
Build an explicit YAML contract
For {language}, help with {goal}. Runtime: {runtime}. Constraints: {constraints}. Provide tiny authored YAML, separate parser-driver code, exact options, companion files and expected typed values. Keep parse success separate from application validity.Debug the correct phase
For {language}, debug {goal}. Runtime: {runtime}. Constraints: {constraints}. Reproduce the smallest input. Distinguish parser errors, warnings, conversion failures and application-contract rejection. Report diagnostic codes and avoid silently ignoring arrays of diagnostics.Test values and boundaries
For {language}, test {goal}. Runtime: {runtime}. Constraints: {constraints}. Cover scalar types, duplicate keys, version directives, document count, alias policy and application boundaries with fixed tiny cases. Report accepted drivers and expected input rejections separately.Refactor without losing intent
For {language}, refactor {goal}. Runtime: {runtime}. Constraints: {constraints}. Preserve typed values and observable failure behavior. State whether comments or exact source bytes must survive, then choose a value or Document API and verify the stated requirement.Document version and safety limits
For {language}, document {goal}. Runtime: {runtime}. Constraints: {constraints}. State YAML version, resolution schema, parser version, options, byte/document/alias limits and expected diagnostics. Do not call toy limits a hostile-input sandbox or claim deployment-system compatibility.Explain and practice
For {language}, explain {goal}. Runtime: {runtime}. Constraints: {constraints}. Give one original example and a separate exercise solution. Contrast serialization format, parser library and application schema validation without counting them as additional languages.Recorded test scope
- result
passed
- runtime
Node 24.18.0 / V8 13.6.233.17-node.50; yaml 2.9.0; YAML 1.2 core
- operating system
macOS-27.0.1-arm64-arm-64bit
- tested on
2026-10-26
- assertion count
91
- example count
12
- accepted drivers
12
- expected input rejections
4
- boundary cases
18
- embedded exercise cases
8
- limits
Trusted authored drivers and tiny local YAML only; no arbitrary-input safety, whole-spec or cross-platform conformance claim.
JavaScript driver syntax checks are not YAML compilation. Expected parser, conversion and warning-policy failures remain distinct from accepted driver executions.
Node heap bound 64 MiB, CPU 6 seconds and wall 10 seconds apply to owned direct processes; not a sandbox or arbitrary process-tree cleanup claim.
Browser, PDF and release evidence are separate gates.
Accepted counts describe JavaScript example drivers, including handled diagnostic demonstrations; they are not a count of valid YAML documents.
These are dated source-example results, not website browser, export, PDF or cross-platform acceptance.
Further reading
- YAML Language Development Team: YAML 1.2.2 specification — Data model, collections, scalar styles, documents, aliases and core resolution; introductory subset only.
- yaml maintainer: version 2 parser and Document APIs — parseDocument/parseAllDocuments, options, diagnostics, toJS alias limits, Document edits and serialization. Live v2 documentation is checked against installed 2.9.0 behavior.
References are the reviewed source snapshot; they have not been rechecked at website publication time.