Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(deps): js-yaml 4 drops argparse@1/sprintf-js (GHSA-hp3w-g68c-fv3c); frontmatter parses as YAML 1.2; osv ignore removed

garrytan89cc414d9094
diff --git a/CHANGELOG.md b/CHANGELOG.md
index adf2e52ef8..c53d9d4cd0 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,36 @@ credits are retained; no result has been reassigned to another provider. Origina
identifiers and attribution are available in the pre-removal Git revision
`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).
+## [0.60.79.0] - 2026-10-06
+
+**js-yaml 4: no more vulnerable YAML command-line dependency, and frontmatter reads clock times and leading-zero numbers the way YAML 1.2 does.**
+
+gbrain parsed YAML with js-yaml 3, whose command-line tool pulls in `argparse@1` and `sprintf-js`, which has an unpatched denial-of-service advisory (GHSA-hp3w-g68c-fv3c). gbrain never loaded that tool, but the dependency audit blocked every push to master. gbrain now uses js-yaml 4: `bun audit` and the OSV scan are both clean, with no ignore entries. The YAML parser also moves from YAML 1.1 to YAML 1.2 number rules, which changes a few frontmatter values.
+
+| Frontmatter value | Before | After |
+| --- | --- | --- |
+| `start: 10:30` | `630` (read as base-60) | `"10:30"` |
+| `id: 010` | `8` (octal) | `10` |
+| `mode: 0o755` | `"0o755"` | `493` |
+| `count: 1_000` | `1000` | `"1_000"` |
+| Dates, `yes`/`no`, duplicate keys, merge keys | unchanged | unchanged |
+
+Written frontmatter quotes fewer strings (for example `${{ github.token }}` and URLs are written without quotes); every string still reads back as the same string.
+
+## To take advantage of v0.60.79.0
+
+`gbrain upgrade` installs the binary. There are no schema migrations. Upgraded brains show a one-time notice listing the behavior change below; `gbrain doctor --only behavior_changes` shows it again.
+
+1. **Verify:**
+ ```bash
+ gbrain doctor
+ ```
+2. **If any step fails,** file an issue at https://github.com/garrytan/gbrain/issues with the output of `gbrain doctor` and `~/.gbrain/upgrade-errors.jsonl` if it exists.
+
+### Behavior changes
+
+- **Frontmatter numbers follow YAML 1.2.** A page whose frontmatter used a clock-like value (`10:30`), a leading-zero number (`010`), `0o` octal or an underscore-separated number stores the new value the next time it syncs. Quote the value in the file to keep it as text either way.
+
## [0.60.78.0] - 2026-10-06
**Green master wave: a brain with embedding turned off no longer sends your text to an embedding provider, lint survives a file vanishing mid-scan, embed and reindex-code stop failing when a background rebuild wins a race, and a release only publishes after its tests pass.**
diff --git a/TODOS.md b/TODOS.md
index f2faee36b5..aec5909970 100644
--- a/TODOS.md
+++ b/TODOS.md
@@ -14,7 +14,6 @@
## Dependency hygiene (filed 2026-10-06, GBRA-40)
-- [ ] **P3 — Move js-yaml 3 → 4 to drop argparse@1 / sprintf-js.** **What:** `osv-scanner.toml` ignores GHSA-hp3w-g68c-fv3c (sprintf-js, no patched version) until 2027-01-06 because only js-yaml 3's CLI loads argparse@1 → sprintf-js. **Fix:** upgrade js-yaml to 4 (argparse 2 has no sprintf-js; `safeLoad`/`safeDump` become `load`/`dump`), update `@types/js-yaml` and the override, then delete the ignore entry. **Effort:** S. **Priority:** P3.
## Contributor audit wave follow-ups (filed 2026-10-05, GBRA-40)
diff --git a/bun.lock b/bun.lock
index 04ed263493..160fbfacec 100644
--- a/bun.lock
+++ b/bun.lock
@@ -26,7 +26,7 @@
"express": "^5.1.0",
"express-rate-limit": "^7.5.0",
"heic-decode": "^2.1.0",
- "js-yaml": "^3.15.2",
+ "js-yaml": "^4.3.2",
"jsonc-parser": "^3.3.1",
"marked": "^18.0.2",
"openai": "^4.0.0",
@@ -41,7 +41,7 @@
"@types/cookie-parser": "^1.4.7",
"@types/cors": "^2.8.19",
"@types/express": "^5.0.6",
- "@types/js-yaml": "^3.12.10",
+ "@types/js-yaml": "^4.0.9",
"bun-types": "^1.3.13",
"fast-check": "^4.8.0",
"typescript": "^5.6.0",
@@ -61,7 +61,7 @@
"form-data": "^4.0.6",
"hono": "^4.13.5",
"ip-address": "^10.5.1",
- "js-yaml": "^3.15.2",
+ "js-yaml": "^4.3.2",
"qs": "6.16.0",
},
"packages": {
@@ -297,7 +297,7 @@
"@types/http-errors": ["@types/[email protected]", "", {}, "sha512-r8Tayk8HJnX0FztbZN7oVqGccWgw98T/0neJphO91KkmOzug1KkofZURD4UaD5uH8AqcFLfdPErnBod0u71/qg=="],
- "@types/js-yaml": ["@types/[email protected]", "", {}, "sha512-/Mtaq/wf+HxXpvhzFYzrzCqNRcA958sW++7JOFC8nPrZcvfi/TrzOaaGbvt27ltJB2NQbHVAg5a1wUCsyMH7NA=="],
+ "@types/js-yaml": ["@types/[email protected]", "", {}, "sha512-k4MGaQl5TGo/iipqb2UDG2UwjXziSWkh0uysQelTlJpX1qGlpUZYm8PnO4DxG1qBomtJUdYJ6qR6xdIah10JLg=="],
"@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~7.18.0" } }, "sha512-tO4ZIRKNC+MDWV4qKVZe3Ql/woTnmHDr5JD8UI5hn2pwBrHEwOEMZK7WlNb5RKB6EoJ02gwmQS9OrjuFnZYdpg=="],
@@ -327,7 +327,7 @@
"anynum": ["[email protected]", "", {}, "sha512-N6//FLET/tXYNM/F6ABca1oH6fWB+KlTt909Le28WMDBk8oaT4vY17DCrwg2MvmuqUKt3Ni4N5dGJ/EoBgcO6A=="],
- "argparse": ["[email protected]", "", { "dependencies": { "sprintf-js": "~1.0.2" } }, "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg=="],
+ "argparse": ["[email protected]", "", {}, "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q=="],
"asynckit": ["[email protected]", "", {}, "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q=="],
@@ -385,8 +385,6 @@
"escape-html": ["[email protected]", "", {}, "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow=="],
- "esprima": ["[email protected]", "", { "bin": { "esparse": "./bin/esparse.js", "esvalidate": "./bin/esvalidate.js" } }, "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A=="],
-
"etag": ["[email protected]", "", {}, "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg=="],
"event-target-shim": ["[email protected]", "", {}, "sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ=="],
@@ -461,7 +459,7 @@
"jose": ["[email protected]", "", {}, "sha512-d7kPDd34KO/YnzaDOlikGpOurfF0ByC2sEV4cANCtdqLlTfBlw2p14O/5d/zv40gJPbIQxfES3nSx1/oYNyuZQ=="],
- "js-yaml": ["[email protected]", "", { "dependencies": { "argparse": "^1.0.7", "esprima": "^4.0.0" }, "bin": { "js-yaml": "bin/js-yaml.js" } }, "sha512-6EuL879VkRA+1Cz578mKMiKvjPNEuk6+r1JaFzoSWejZmtf7xWbIyw1e3KkxlkzTIt9Taw6JBhEppG7utc1P+w=="],
+ "js-yaml": ["[email protected]", "", { "dependencies": { "argparse": "^2.0.1" }, "bin": { "js-yaml": "bin/js-yaml.js" } }, "sha512-SFNOvSJ+Dgf/9An904Yx+CgSlIPCkIpao4qo51lpee25TIRejdH3rhR4EZMGoNx3/TP3O+wzWuiTFl4sqbltzA=="],
"json-schema": ["[email protected]", "", {}, "sha512-es94M3nTIfsEPisRafak+HDLfHXnKBhV3vU5eqPcS3flIWqcxJWgXHXiey3YrpaNsanY5ei1VoYEbOzijuq9BA=="],
@@ -555,8 +553,6 @@
"side-channel-weakmap": ["[email protected]", "", { "dependencies": { "call-bound": "^1.0.2", "es-errors": "^1.3.0", "get-intrinsic": "^1.2.5", "object-inspect": "^1.13.3", "side-channel-map": "^1.0.1" } }, "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A=="],
- "sprintf-js": ["[email protected]", "", {}, "sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g=="],
-
"statuses": ["[email protected]", "", {}, "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw=="],
"strnum": ["[email protected]", "", { "dependencies": { "anynum": "^1.0.1" } }, "sha512-M9eUSMT2dCB2cTNPG7UYj6KuK7RJR2SN2+yCV/fTW3xzTCS6EaGZ5pSMgDIjB7r8zSfTGk+dvvn9rTjpVS9Mwg=="],
diff --git a/osv-scanner.toml b/osv-scanner.toml
deleted file mode 100644
index a570ced5df..0000000000
--- a/osv-scanner.toml
+++ /dev/null
@@ -1,17 +0,0 @@
-# OSV-Scanner configuration (picked up from the repository root by osv-scan).
-# Every entry needs a reason, an owner-visible expiry, and evidence that the
-# vulnerable code is unreachable from gbrain. Remove an entry as soon as a
-# fixed version exists or the dependency is gone.
-
-[[IgnoredVulns]]
-id = "GHSA-hp3w-g68c-fv3c"
-ignoreUntil = 2027-01-06T00:00:00Z
-reason = """
-sprintf-js <= 1.1.3 (no patched version) throws RangeError on attacker-chosen
-precision specifiers. It reaches bun.lock only as [email protected]'s dependency,
-and argparse@1 only through js-yaml@3's CLI (node_modules/js-yaml/bin/js-yaml.js).
-gbrain uses js-yaml's library API, which never loads argparse or sprintf-js, and
-nothing in src/ or scripts/ imports either package, so no gbrain format string
-reaches sprintf-js. Real fix: move to js-yaml 4 (argparse 2, no sprintf-js),
-tracked in TODOS.md.
-"""
diff --git a/package.json b/package.json
index eb3ba59518..e636103311 100644
--- a/package.json
+++ b/package.json
@@ -197,7 +197,7 @@
"express": "^5.1.0",
"express-rate-limit": "^7.5.0",
"heic-decode": "^2.1.0",
- "js-yaml": "^3.15.2",
+ "js-yaml": "^4.3.2",
"jsonc-parser": "^3.3.1",
"marked": "^18.0.2",
"openai": "^4.0.0",
@@ -212,7 +212,7 @@
"@types/cookie-parser": "^1.4.7",
"@types/cors": "^2.8.19",
"@types/express": "^5.0.6",
- "@types/js-yaml": "^3.12.10",
+ "@types/js-yaml": "^4.0.9",
"bun-types": "^1.3.13",
"fast-check": "^4.8.0",
"typescript": "^5.6.0"
@@ -236,6 +236,6 @@
"hono": "^4.13.5",
"ip-address": "^10.5.1",
"qs": "6.16.0",
- "js-yaml": "^3.15.2"
+ "js-yaml": "^4.3.2"
}
}
diff --git a/scripts/check-postgres-lane-coverage.ts b/scripts/check-postgres-lane-coverage.ts
index f4f6ee3cc7..86dce68d32 100644
--- a/scripts/check-postgres-lane-coverage.ts
+++ b/scripts/check-postgres-lane-coverage.ts
@@ -30,7 +30,7 @@
*/
import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
import { dirname, join, relative, resolve } from 'node:path';
-import { safeLoad } from 'js-yaml';
+import { load } from 'js-yaml';
import ts from 'typescript';
import { ARMS_LIST, readArmsList } from './postgres-unit-arms.ts';
@@ -143,7 +143,7 @@ export function postgresLanes(): Map<string, string> {
const add = (path: string, lane: string) => { if (!laned.has(path)) laned.set(path, lane); };
for (const path of readArmsList(ROOT).files) add(path, ARMS_LIST);
for (const workflow of files(join(ROOT, '.github', 'workflows'), name => /\.ya?ml$/.test(name))) {
- const doc = safeLoad(readFileSync(workflow, 'utf8')) as { env?: Record<string, unknown>; jobs?: Record<string, { env?: Record<string, unknown>; steps?: Array<{ name?: string; env?: Record<string, unknown>; run?: string }> }> } | undefined;
+ const doc = load(readFileSync(workflow, 'utf8')) as { env?: Record<string, unknown>; jobs?: Record<string, { env?: Record<string, unknown>; steps?: Array<{ name?: string; env?: Record<string, unknown>; run?: string }> }> } | undefined;
for (const [jobName, job] of Object.entries(doc?.jobs ?? {})) for (const step of job.steps ?? []) {
const run = String(step.run ?? '');
if (!(step.env?.DATABASE_URL || job.env?.DATABASE_URL || doc?.env?.DATABASE_URL || /\bDATABASE_URL=/.test(run))) continue;
diff --git a/scripts/generate-plugin-tree.ts b/scripts/generate-plugin-tree.ts
index 4e3eeac0f8..ed9f85ee61 100644
--- a/scripts/generate-plugin-tree.ts
+++ b/scripts/generate-plugin-tree.ts
@@ -44,7 +44,7 @@ import { REGISTRATION_SURFACE } from '../src/core/mcp-registration.ts';
import { operations } from '../src/core/operations.ts';
import { cliEquivalent } from '../src/core/ops/cli-equivalent.ts';
import { parseSkillFrontmatter } from '../src/core/skill-frontmatter.ts';
-import { FAILSAFE_SCHEMA, safeLoad } from 'js-yaml';
+import { FAILSAFE_SCHEMA, load } from 'js-yaml';
// Personas: the SINGLE validation implementation (the harness-bridge CLI
// imports the same module), so CLI errors and CI errors match by construction.
import { loadPersonas, type PersonaDef } from '../src/core/skillpack/personas.ts';
@@ -199,7 +199,7 @@ function withWhenToUse(text: string): string {
if (!fm || triggers.length === 0 || /^when_to_use:/m.test(fm.raw)) return text;
let description = '';
try {
- const data: unknown = safeLoad(fm.raw, { schema: FAILSAFE_SCHEMA });
+ const data: unknown = load(fm.raw, { schema: FAILSAFE_SCHEMA });
if (data && typeof data === 'object' && typeof (data as { description?: unknown }).description === 'string') description = (data as { description: string }).description;
} catch { return text; }
const room = SKILL_LISTING_CHARS - description.length - 1;
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 63bfd7cb63..cf47d654ef 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -241,6 +241,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
{ since: '0.60.77.0', text: 'think answers, saved syntheses, concept narratives and pattern pages check their quotes against their sources: a quote found nowhere loses its quotation marks and is marked [unverified]. It is not yet measured as a catch for made-up quotes. `gbrain config set think.quote_verify false` and `gbrain config set dream.quote_verify false` turn it off.' },
{ since: '0.60.77.0', text: 'forget responses list close active facts it did not withdraw (`similar_active`); with a TypeSafe key, forgetting also queues an overnight review that only proposes withdrawing rewordings (`gbrain decide proposals list`; `gbrain config set decide.slots.conflict.review_withdraw false` turns it off).' },
{ since: '0.60.78.0', text: 'On a brain with embedding turned off, search, query, recall, think and fact writes no longer send text to an embedding provider: reads run keyword-only and say so, and `gbrain doctor --json` names the enable command if the user wants semantic search back.' },
+ { since: '0.60.79.0', text: 'Frontmatter is parsed as YAML 1.2: clock-like values such as `10:30` stay text (they were read as base-60 numbers, so 10:30 became 630), a leading zero is decimal (`010` is 10, not 8), `0o` marks octal, and `1_000` stays text. Re-syncing a page whose frontmatter used those forms stores the new values.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/data-frontmatter.ts b/src/core/data-frontmatter.ts
index 5222b4d3bb..59eb333430 100644
--- a/src/core/data-frontmatter.ts
+++ b/src/core/data-frontmatter.ts
@@ -1,11 +1,11 @@
-import { safeLoad, safeDump, Schema, Type, DEFAULT_SAFE_SCHEMA } from 'js-yaml';
+import { load, dump, Type, DEFAULT_SCHEMA } from 'js-yaml';
import { NAIVE_DATETIME } from './effective-date.ts';
// js-yaml's timestamp type builds `2024-02-30` as March 1 (Date.UTC rolls the
// day over). A calendar-invalid timestamp stays the string the author wrote,
// so date consumers reject it instead of storing the wrong day.
type TimestampBehavior = { resolve(data: string): boolean; construct(data: string): Date; represent(data: object): string };
-const baseTimestamp = (DEFAULT_SAFE_SCHEMA as unknown as { compiledTypeMap: { scalar: Record<string, TimestampBehavior> } })
+const baseTimestamp = (DEFAULT_SCHEMA as unknown as { compiledTypeMap: { scalar: Record<string, TimestampBehavior> } })
.compiledTypeMap.scalar['tag:yaml.org,2002:timestamp']!;
const calendarTimestamp = new Type('tag:yaml.org,2002:timestamp', {
kind: 'scalar',
@@ -27,7 +27,7 @@ const calendarTimestamp = new Type('tag:yaml.org,2002:timestamp', {
instanceOf: Date,
represent: baseTimestamp.represent,
});
-export const FRONTMATTER_SCHEMA = new Schema({ include: [DEFAULT_SAFE_SCHEMA], implicit: [calendarTimestamp] });
+export const FRONTMATTER_SCHEMA = DEFAULT_SCHEMA.extend({ implicit: [calendarTimestamp] });
export interface DataFrontmatter {
data: Record<string, unknown>;
@@ -62,7 +62,7 @@ export function parseDataFrontmatter(input: string): DataFrontmatter {
const block = closing ? rest.slice(0, closing.index) : rest;
let value: unknown;
try {
- value = block.trim() === '' ? {} : language === 'json' ? JSON.parse(block) : safeLoad(block, { schema: FRONTMATTER_SCHEMA });
+ value = block.trim() === '' ? {} : language === 'json' ? JSON.parse(block) : load(block, { schema: FRONTMATTER_SCHEMA });
} catch (error) {
// Parser messages can contain the document itself. Report only location,
// so request/job diagnostics never copy private frontmatter into logs.
@@ -81,7 +81,7 @@ export function parseDataFrontmatter(input: string): DataFrontmatter {
/** Serialize metadata without ever interpreting the body as frontmatter. */
export function stringifyDataFrontmatter(content: string, data: Record<string, unknown>): string {
- const yaml = safeDump(data).trim();
+ const yaml = dump(data).trim();
const header = yaml === '{}' ? '' : `---\n${yaml}\n---\n`;
return header + (content.endsWith('\n') ? content : content + '\n');
}
diff --git a/src/core/frontmatter-recovery.ts b/src/core/frontmatter-recovery.ts
index 884b326db8..c7c8a6c282 100644
--- a/src/core/frontmatter-recovery.ts
+++ b/src/core/frontmatter-recovery.ts
@@ -15,7 +15,7 @@
* rewritten, folded into or guessed; identity keys are never resolved from a
* duplicate.
*/
-import { safeLoad } from 'js-yaml';
+import { load } from 'js-yaml';
import { FRONTMATTER_SCHEMA } from './data-frontmatter.ts';
/** Bump when a rule widens; older holds are re-screened. */
@@ -65,7 +65,7 @@ interface YamlFailure { reason: string; line: number | null; column: number | nu
function loadBlock(text: string): { ok: true; data: unknown } | { ok: false; failure: YamlFailure } {
try {
- return { ok: true, data: safeLoad(text, { schema: FRONTMATTER_SCHEMA }) };
+ return { ok: true, data: load(text, { schema: FRONTMATTER_SCHEMA }) };
} catch (error) {
const e = error as { reason?: string; mark?: { line?: number; column?: number } };
return { ok: false, failure: { reason: e.reason ?? 'malformed YAML', line: e.mark?.line ?? null, column: e.mark?.column ?? null } };
diff --git a/src/core/markdown.ts b/src/core/markdown.ts
index 5541a7e67a..803edc9e15 100644
--- a/src/core/markdown.ts
+++ b/src/core/markdown.ts
@@ -1,5 +1,5 @@
import { dataFrontmatter as matter, FrontmatterLanguageError } from './data-frontmatter.ts';
-import { safeLoad as yamlSafeLoad } from 'js-yaml';
+import { load as yamlLoad } from 'js-yaml';
import type { Page, PageType } from './types.ts';
import { resolveSlugForPath, slugifyPath } from './sync.ts';
import {
@@ -673,7 +673,7 @@ function collectValidationErrors(
// genuinely broken. Parse the value to disambiguate.
let isValidYaml = false;
try {
- yamlSafeLoad(value);
+ yamlLoad(value);
isValidYaml = true;
} catch {
// YAML parse failed — line is genuinely broken
@@ -698,7 +698,7 @@ function collectValidationErrors(
let detectedYamlParseError = looksLikeFrontmatter ? ctx.yamlParseError : null;
if (!detectedYamlParseError && looksLikeFrontmatter) {
try {
- yamlSafeLoad(fmBody);
+ yamlLoad(fmBody);
} catch (e) {
detectedYamlParseError = e as Error;
}
@@ -752,7 +752,7 @@ function collectValidationErrors(
/** Where js-yaml refuses a raw block: its reason phrase and the file line and column. */
function yamlFailureLocation(block: string, lineOffset: number): { reason: string; line: number; column: number } | null {
try {
- yamlSafeLoad(block);
+ yamlLoad(block);
return null;
} catch (e) {
const err = e as { reason?: string; mark?: { line?: number; column?: number } };
diff --git a/src/core/shared-skills/manifest.ts b/src/core/shared-skills/manifest.ts
index 05629eb323..9802df37a1 100644
--- a/src/core/shared-skills/manifest.ts
+++ b/src/core/shared-skills/manifest.ts
@@ -1,6 +1,6 @@
import { opError } from '../ops/contract.ts';
import { sha256 } from '../persistence/digest.ts';
-import { FAILSAFE_SCHEMA, safeLoad } from 'js-yaml';
+import { FAILSAFE_SCHEMA, load } from 'js-yaml';
import { SHARED_SKILL_LIMITS, type SharedSkillFileInput, type SkillFileClass, type SkillMetadata, type StoredSkillFile } from './model.ts';
export function skillName(value: unknown, field = 'name'): string {
@@ -139,7 +139,7 @@ export function skillToolsDeclared(metadata: Pick<SkillMetadata, 'tools_declared
if (!/^---[ \t]*\n/.test(normalized)) return false;
const match = normalized.match(/^---[ \t]*\n([\s\S]*?)\n---[ \t]*(?:\n|$)/);
try {
- const parsed: unknown = match ? safeLoad(match[1], { schema: FAILSAFE_SCHEMA }) : undefined;
+ const parsed: unknown = match ? load(match[1], { schema: FAILSAFE_SCHEMA }) : undefined;
return !(parsed && typeof parsed === 'object' && !Array.isArray(parsed)) || Object.hasOwn(parsed, 'tools');
} catch { return true; }
}
@@ -154,7 +154,7 @@ export function skillMetadata(name: string, files: StoredSkillFile[], params: Re
`Close skills/${name}/SKILL.md's frontmatter with a --- line after the YAML block (or remove the opening ---), then resubmit.`);
}
try {
- const parsed: unknown = safeLoad(match[1], { schema: FAILSAFE_SCHEMA });
+ const parsed: unknown = load(match[1], { schema: FAILSAFE_SCHEMA });
if (parsed !== undefined && parsed !== null && (typeof parsed !== 'object' || Array.isArray(parsed))) throw new Error('not a mapping');
fm = parsed as Record<string, unknown> ?? {};
} catch {
diff --git a/src/core/skill-catalog.ts b/src/core/skill-catalog.ts
index 428f7315d0..b35d02c325 100644
--- a/src/core/skill-catalog.ts
+++ b/src/core/skill-catalog.ts
@@ -38,7 +38,7 @@
import { existsSync, readFileSync, realpathSync, statSync } from 'fs';
import { basename, join, relative, resolve } from 'path';
-import { FAILSAFE_SCHEMA, safeLoad } from 'js-yaml';
+import { FAILSAFE_SCHEMA, load } from 'js-yaml';
import {
autoDetectSkillsDir,
autoDetectSkillsDirReadOnly,
@@ -356,7 +356,7 @@ function resolveSkillTools(
if (parsed?.tools !== undefined) return crossReferenceTools(parsed.tools, ctx, gateDisabled);
if (parsed) {
try {
- const data = safeLoad(parsed.raw, { schema: FAILSAFE_SCHEMA });
+ const data = load(parsed.raw, { schema: FAILSAFE_SCHEMA });
if (data && typeof data === 'object' && !Array.isArray(data) && !Object.hasOwn(data, 'tools')) {
return { usable_tools: availableBrainTools(ctx, gateDisabled), unavailable_tools: [] };
}
diff --git a/src/core/skill-frontmatter.ts b/src/core/skill-frontmatter.ts
index 84c1b4e5f1..b0e473967d 100644
--- a/src/core/skill-frontmatter.ts
+++ b/src/core/skill-frontmatter.ts
@@ -27,7 +27,7 @@
* not a silent failure to exempt.
*/
-import { FAILSAFE_SCHEMA, safeLoad as yamlSafeLoad } from 'js-yaml';
+import { FAILSAFE_SCHEMA, load as yamlLoad } from 'js-yaml';
// ---------------------------------------------------------------------------
// Types
@@ -137,7 +137,7 @@ export function parseSkillFrontmatter(content: string): ParsedFrontmatter | null
*/
function parseArrayField(raw: string, field: string): string[] | undefined {
try {
- const parsed = yamlSafeLoad(raw, { schema: FAILSAFE_SCHEMA });
+ const parsed = yamlLoad(raw, { schema: FAILSAFE_SCHEMA });
if (parsed && typeof parsed === 'object' && Object.hasOwn(parsed, field)) {
const value = (parsed as Record<string, unknown>)[field];
if (!Array.isArray(value)) return undefined;
diff --git a/src/core/transcripts/render.ts b/src/core/transcripts/render.ts
index 4f93f724c0..8afc6b85aa 100644
--- a/src/core/transcripts/render.ts
+++ b/src/core/transcripts/render.ts
@@ -27,7 +27,7 @@
* per-session id would make parts 2..N skip as cross-slug duplicates.
*/
-import { safeDump } from 'js-yaml';
+import { dump } from 'js-yaml';
import { homedir } from 'node:os';
import { join } from 'node:path';
import { DEFAULT_BYTES_WARN } from '../content-sanity.ts';
@@ -278,7 +278,7 @@ export interface RenderedPart {
}
export function renderPartContent(frontmatter: Record<string, unknown>, body: string): string {
- return `---\n${safeDump(frontmatter, { lineWidth: 1000 })}---\n\n${body}\n`;
+ return `---\n${dump(frontmatter, { lineWidth: 1000 })}---\n\n${body}\n`;
}
export interface RenderSessionResult {
diff --git a/test/behavior-change-notice.test.ts b/test/behavior-change-notice.test.ts
index 2ae40ad900..407166cb31 100644
--- a/test/behavior-change-notice.test.ts
+++ b/test/behavior-change-notice.test.ts
@@ -38,6 +38,19 @@ import {
import { VERSION } from '../src/version.ts';
import { checkBehaviorChanges } from '../src/commands/doctor/checks/behavior-changes.ts';
import { dispatchToolCall } from '../src/mcp/dispatch.ts';
+
+// Expectations derive from the BEHAVIOR_CHANGES table, so adding a release's
+// rows does not require re-pinning every count; each release's own content is
+// still asserted by text below.
+const NEWEST = BEHAVIOR_NOTICE_SINCE;
+const NEXT_PATCH = NEWEST.replace(/^(\d+\.\d+\.)(\d+)(.*)$/, (_m, a: string, b: string, c: string) => `${a}${Number(b) + 1}${c}`);
+const NEWEST_TEXT = (BEHAVIOR_CHANGES.find(c => c.since === NEWEST && typeof c.text === 'string')!.text as string).slice(0, 48);
+function noticeHeader(after: string, withChain = false): string {
+ const rows = BEHAVIOR_CHANGES.filter(c => compareReleases(c.since, after) > 0 && (withChain || typeof c.text === 'string'));
+ const releases = [...new Set(rows.map(c => `v${c.since}`))];
+ const list = releases.length > 1 ? `${releases.slice(0, -1).join(', ')} and ${releases.at(-1)}` : releases[0];
+ return `gbrain ${list} changed ${rows.length} behavior${rows.length === 1 ? '' : 's'}`;
+}
import { NoticeLedger, __resetProcessNoticeLedgerForTests } from '../src/core/notice-ledger.ts';
import { _resetDbPlaneMergeMemoForTests } from '../src/core/config-db-merge.ts';
import type { GBrainConfig } from '../src/core/config.ts';
@@ -232,7 +245,7 @@ for (const backend of testBackends()) {
expect(await takeLocalBehaviorNotice(engine, 'cli', { cfg: null, brainKey: 'doctor' })).not.toBeNull();
const again = await checkBehaviorChanges(engine, { cfg: null, brainKey: 'doctor' });
expect(again.details).toMatchObject({ shown: { cli: true, stdio: false } });
- expect(again.message).toContain('gbrain v0.60.68.0, v0.60.74.0, v0.60.77.0 and v0.60.78.0 changed 12 behaviors');
+ expect(again.message).toContain(noticeHeader('0'));
});
});
@@ -303,7 +316,7 @@ describe('per-release content', () => {
expect(later.why).not.toContain('chat_fallback_chain is live');
expect(later.fix?.argv).toEqual(['gbrain', 'doctor', '--only', 'behavior_changes', '--json']);
const all = behaviorChangesNotice(chain)!;
- expect(all.why).toContain('gbrain v0.60.68.0, v0.60.74.0, v0.60.77.0 and v0.60.78.0 changed 13 behaviors');
+ expect(all.why).toContain(noticeHeader('0', true));
expect(all.fix?.argv).toEqual(['unset', 'GBRAIN_CHAT_FALLBACK_CHAIN']);
});
});
@@ -367,8 +380,8 @@ describe('upgrades across releases (each step a new process pinned to a gbrain V
test('a brain that saw the notice gets nothing from a later release that adds no behavior changes', async () => {
const home = freshHome();
for (const channel of ['cli', 'http:client-a']) {
- expect(await runAt(home, '0.60.78.0', 'seen', channel)).toContain(OPT_OUT);
- expect(await runAt(home, '0.60.78.0', 'seen', channel)).toBeNull();
+ expect(await runAt(home, NEWEST, 'seen', channel)).toContain(NEWEST_TEXT);
+ expect(await runAt(home, NEWEST, 'seen', channel)).toBeNull();
expect(await runAt(home, '0.60.99.0', 'seen', channel)).toBeNull();
}
}, 60_000);
@@ -380,27 +393,28 @@ describe('upgrades across releases (each step a new process pinned to a gbrain V
writeFileSync(join(noticeDir(home), 'behavior_changes_0.60.68.0.b68.cli.shown'), '2026-10-05T00:00:00.000Z\n');
writeFileSync(join(home, 'brain-config.json'), JSON.stringify({ [HTTP_SHOWN_KEY]: JSON.stringify({ id: '[email protected]', clients: { 'client-a': '2026-10-05T00:00:00.000Z' } }) }));
for (const channel of ['cli', 'http:client-a']) {
- const why = await runAt(home, '0.60.78.0', 'b68', channel);
- expect(why).toContain('gbrain v0.60.74.0, v0.60.77.0 and v0.60.78.0 changed 9 behaviors');
+ const why = await runAt(home, NEWEST, 'b68', channel);
+ expect(why).toContain(noticeHeader('0.60.68.0'));
expect(why).toContain(WAVE9);
expect(why).toContain(OPT_OUT);
expect(why).not.toContain(V68);
expect(why).not.toContain('v0.60.68.0');
- expect(await runAt(home, '0.60.78.0', 'b68', channel)).toBeNull();
- expect(await runAt(home, '0.60.79.0', 'b68', channel)).toBeNull();
+ expect(await runAt(home, NEWEST, 'b68', channel)).toBeNull();
+ expect(await runAt(home, NEXT_PATCH, 'b68', channel)).toBeNull();
}
}, 60_000);
test('a brain older than 0.60.68 sees every item, labeled with its release, once', async () => {
const home = freshHome();
for (const channel of ['cli', 'stdio', 'http:client-a']) {
- const why = await runAt(home, '0.60.78.0', 'old', channel);
- expect(why).toContain('gbrain v0.60.68.0, v0.60.74.0, v0.60.77.0 and v0.60.78.0 changed 12 behaviors');
+ const why = await runAt(home, NEWEST, 'old', channel);
+ expect(why).toContain(noticeHeader('0'));
expect(why).toContain(`v0.60.68.0: (1) On a managed brain`);
expect(why).toContain(`v0.60.74.0: (4) A shell job`);
expect(why).toContain(`v0.60.77.0: (10) think answers`);
expect(why).toContain(`v0.60.78.0: (12) On a brain with embedding turned off`);
- expect(await runAt(home, '0.60.78.0', 'old', channel)).toBeNull();
+ expect(why).toContain(`v0.60.79.0: (13) Frontmatter is parsed as YAML 1.2`);
+ expect(await runAt(home, NEWEST, 'old', channel)).toBeNull();
expect(await runAt(home, '0.60.99.0', 'old', channel)).toBeNull();
}
expect(readFileSync(join(noticeDir(home), 'old.baseline'), 'utf8').trim()).toBe('0');
@@ -409,9 +423,9 @@ describe('upgrades across releases (each step a new process pinned to a gbrain V
test('a fresh brain sees nothing, then or after later upgrades', async () => {
const home = freshHome();
for (const channel of ['cli', 'http:client-a']) {
- expect(await runAt(home, '0.60.78.0', 'new', channel, { createdAgoMs: 0 })).toBeNull();
+ expect(await runAt(home, NEWEST, 'new', channel, { createdAgoMs: 0 })).toBeNull();
expect(await runAt(home, '0.60.99.0', 'new', channel, { createdAgoMs: 2 * DAY })).toBeNull();
}
- expect(readFileSync(join(noticeDir(home), 'new.baseline'), 'utf8').trim()).toBe('0.60.78.0');
+ expect(readFileSync(join(noticeDir(home), 'new.baseline'), 'utf8').trim()).toBe(NEWEST);
}, 60_000);
});
diff --git a/test/e2e/install-real-hermes.serial.test.ts b/test/e2e/install-real-hermes.serial.test.ts
index c094b55cb1..3fbc5f7aa3 100644
--- a/test/e2e/install-real-hermes.serial.test.ts
+++ b/test/e2e/install-real-hermes.serial.test.ts
@@ -181,7 +181,7 @@ interface HermesMcpConfig {
function readHermesConfig(home: string): HermesMcpConfig {
const p = join(home, '.hermes', 'config.yaml');
expect(existsSync(p)).toBe(true);
- return (yaml.safeLoad(readFileSync(p, 'utf-8')) ?? {}) as HermesMcpConfig;
+ return (yaml.load(readFileSync(p, 'utf-8')) ?? {}) as HermesMcpConfig;
}
/** Shared registration: real `hermes mcp add` with the piped-Y confirmation.
@@ -276,7 +276,7 @@ describe.skipIf(!CAN_RUN)('install real-hermes door (serial e2e)', () => {
},
},
};
- writeFileSync(configPath, yaml.safeDump(doc), 'utf-8');
+ writeFileSync(configPath, yaml.dump(doc), 'utf-8');
// Targeted probe, asserted HARD (eng D3): `mcp test` connects to exactly
// the entry under test. Global `doctor` is NOT asserted here — it
diff --git a/test/envelope-to-gbrain.test.ts b/test/envelope-to-gbrain.test.ts
index 3734af72d5..9a4bbe0f1c 100644
--- a/test/envelope-to-gbrain.test.ts
+++ b/test/envelope-to-gbrain.test.ts
@@ -8,7 +8,7 @@ import { tmpdir } from 'node:os';
import { join } from 'node:path';
// The same parser gbrain uses to ingest frontmatter (src/core/markdown.ts), so
// the injection test asserts against the real consumer rather than a substring.
-import { safeLoad as yamlSafeLoad } from 'js-yaml';
+import { load as yamlLoad } from 'js-yaml';
// F5 asserts against gbrain's REAL consumers, not against a copy of their
// regexes: `parseConversation` is what decides whether an imported page yields
// any conversation-facts at all, and `parseMarkdown`/`serializeMarkdown` are
@@ -80,7 +80,7 @@ function frontmatterBlock(page: string): string {
}
function frontmatterOf(page: string): Record<string, unknown> {
- return (yamlSafeLoad(frontmatterBlock(page)) ?? {}) as Record<string, unknown>;
+ return (yamlLoad(frontmatterBlock(page)) ?? {}) as Record<string, unknown>;
}
function bodyOf(page: string): string {
diff --git a/test/frontmatter-writers-roundtrip.test.ts b/test/frontmatter-writers-roundtrip.test.ts
index 95c63a101a..fa317fcd1e 100644
--- a/test/frontmatter-writers-roundtrip.test.ts
+++ b/test/frontmatter-writers-roundtrip.test.ts
@@ -9,7 +9,7 @@ import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
-import { safeLoad } from 'js-yaml';
+import { load } from 'js-yaml';
import { FRONTMATTER_SCHEMA } from '../src/core/data-frontmatter.ts';
import { serializeFrontmatter, yamlScalar } from '../src/core/frontmatter-inference.ts';
@@ -29,7 +29,7 @@ const HOSTILE = [
function strictFrontmatter(doc: string): Record<string, unknown> {
const m = /^---\n([\s\S]*?)\n---(?:\n|$)/.exec(doc);
if (!m) throw new Error(`no frontmatter block in:\n${doc}`);
- return safeLoad(m[1]!, { schema: FRONTMATTER_SCHEMA }) as Record<string, unknown>;
+ return load(m[1]!, { schema: FRONTMATTER_SCHEMA }) as Record<string, unknown>;
}
describe('frontmatter writers round-trip hostile strings under a strict YAML parse', () => {
@@ -73,7 +73,7 @@ describe('schema init pack.yaml', () => {
for (const name of ['a: b #c', '[x]', '"q" tail', '---', 'yes']) {
await withEnv({ GBRAIN_HOME: home }, () => runSchema(['init', name, '--json']));
const yaml = readFileSync(join(home, '.gbrain', 'schema-packs', name, 'pack.yaml'), 'utf8');
- expect((safeLoad(yaml, { schema: FRONTMATTER_SCHEMA }) as { name: unknown }).name).toBe(name);
+ expect((load(yaml, { schema: FRONTMATTER_SCHEMA }) as { name: unknown }).name).toBe(name);
}
} finally {
console.log = logOrig;
diff --git a/test/loops-extract-wiring.test.ts b/test/loops-extract-wiring.test.ts
index 2f494878c1..ce065cc036 100644
--- a/test/loops-extract-wiring.test.ts
+++ b/test/loops-extract-wiring.test.ts
@@ -21,7 +21,7 @@
import { describe, test, expect } from 'bun:test';
import * as fs from 'node:fs';
import * as path from 'node:path';
-import { safeLoad } from 'js-yaml';
+import { load } from 'js-yaml';
import { KNOWN_CONFIG_KEYS } from '../src/core/config.ts';
import { KNOWN_LINK_TYPES } from '../src/core/search/relational-intent.ts';
@@ -67,7 +67,7 @@ describe('relational edge vocabulary', () => {
path.join(REPO, 'src', 'core', 'schema-pack', 'base', 'gbrain-base-v2.yaml'),
'utf8',
);
- const pack = safeLoad(raw) as { link_types?: Array<{ name: string }> };
+ const pack = load(raw) as { link_types?: Array<{ name: string }> };
expect(Array.isArray(pack.link_types)).toBe(true);
const names = pack.link_types!.map((lt) => lt.name);
expect(names).toContain('owes_to');
diff --git a/test/plugin-tree-when-to-use-5858.test.ts b/test/plugin-tree-when-to-use-5858.test.ts
index eb03511019..ccae6c66d9 100644
--- a/test/plugin-tree-when-to-use-5858.test.ts
+++ b/test/plugin-tree-when-to-use-5858.test.ts
@@ -7,12 +7,12 @@
import { describe, expect, test } from 'bun:test';
import { existsSync, readdirSync, readFileSync } from 'node:fs';
import { join, resolve } from 'node:path';
-import { FAILSAFE_SCHEMA, safeLoad } from 'js-yaml';
+import { FAILSAFE_SCHEMA, load } from 'js-yaml';
const ROOT = resolve(import.meta.dir, '..');
function frontmatter(path: string): Record<string, unknown> | null {
const match = readFileSync(path, 'utf8').match(/^---\n([\s\S]*?)\n---/);
- return match ? safeLoad(match[1], { schema: FAILSAFE_SCHEMA }) as Record<string, unknown> : null;
+ return match ? load(match[1], { schema: FAILSAFE_SCHEMA }) as Record<string, unknown> : null;
}
function skillFiles(dir: string): string[] {
return readdirSync(dir, { withFileTypes: true }).filter(entry => entry.isDirectory())
diff --git a/test/release-workflow.test.ts b/test/release-workflow.test.ts
index 939fb84d10..d83c6ea6b1 100644
--- a/test/release-workflow.test.ts
+++ b/test/release-workflow.test.ts
@@ -186,8 +186,8 @@ Release summary line.
describe('release.yml publish-template skip is visible (D-10)', () => {
test('an empty TEMPLATE_REPO_PAT warns with the owner-only fix and writes a step summary', async () => {
- const { safeLoad } = await import('js-yaml');
- const wf = safeLoad(WORKFLOW) as { jobs: Record<string, { steps: Array<{ id?: string; run?: string }> }> };
+ const { load } = await import('js-yaml');
+ const wf = load(WORKFLOW) as { jobs: Record<string, { steps: Array<{ id?: string; run?: string }> }> };
const gate = wf.jobs['publish-template']!.steps.find(s => s.id === 'gate')!.run!;
const dir = mkdtempSync(join(tmpdir(), 'gbrain-publish-template-gate-'));
try {
diff --git a/test/scripts/ci-gates.test.ts b/test/scripts/ci-gates.test.ts
index 4b063ba44f..4522d6060c 100644
--- a/test/scripts/ci-gates.test.ts
+++ b/test/scripts/ci-gates.test.ts
@@ -3,12 +3,12 @@ import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'nod
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { spawnSync } from 'node:child_process';
-import { safeLoad } from 'js-yaml';
+import { load } from 'js-yaml';
const root = join(import.meta.dir, '..', '..');
type Job = { needs?: string | string[]; if?: string; steps: Array<{ name?: string; run?: string; uses?: string; env?: Record<string, string> }> };
type Workflow = { on: Record<string, { paths?: string[] }>; jobs: Record<string, Job> };
-const loadWorkflow = (name: string) => safeLoad(readFileSync(join(root, '.github/workflows', name), 'utf8')) as Workflow;
+const loadWorkflow = (name: string) => load(readFileSync(join(root, '.github/workflows', name), 'utf8')) as Workflow;
const unit = loadWorkflow('test.yml');
const e2e = loadWorkflow('e2e.yml');
diff --git a/test/scripts/ci-manifest-diff.test.ts b/test/scripts/ci-manifest-diff.test.ts
index b3a8f8e785..faf17f8b05 100644
--- a/test/scripts/ci-manifest-diff.test.ts
+++ b/test/scripts/ci-manifest-diff.test.ts
@@ -9,7 +9,7 @@ import { spawnSync } from 'node:child_process';
import { chmodSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
-import { safeLoad } from 'js-yaml';
+import { load } from 'js-yaml';
const root = join(import.meta.dir, '../..');
const SCRIPT = join(root, 'scripts/ci-manifest-diff.sh');
@@ -81,7 +81,7 @@ describe('ci-manifest-diff.sh', () => {
});
describe('test.yml dependency-audit scope', () => {
- const step = (safeLoad(readFileSync(join(root, '.github/workflows/test.yml'), 'utf8')) as {
+ const step = (load(readFileSync(join(root, '.github/workflows/test.yml'), 'utf8')) as {
jobs: Record<string, { steps: Array<{ id?: string; run?: string }> }>;
}).jobs['dependency-audit'].steps.find(s => s.id === 'scope')!;
diff --git a/test/scripts/ci-pr-scope.test.ts b/test/scripts/ci-pr-scope.test.ts
index 47aea5f23b..7e94642277 100644
--- a/test/scripts/ci-pr-scope.test.ts
+++ b/test/scripts/ci-pr-scope.test.ts
@@ -4,13 +4,13 @@ import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { spawnSync } from 'node:child_process';
import { runInNewContext } from 'node:vm';
-import { safeLoad } from 'js-yaml';
+import { load as loadYaml } from 'js-yaml';
import { MINIMUM_BUN_VERSION } from '../../src/core/runtime-version.ts';
type Matrix = Record<string, unknown> & { exclude?: string };
type Job = { if?: string; 'runs-on'?: string; strategy?: { matrix: Matrix }; steps?: Array<{ id?: string; run?: string; env?: Record<string, string> }> };
const root = join(import.meta.dir, '../..');
-const load = (name: string) => safeLoad(readFileSync(join(root, '.github/workflows', name), 'utf8')) as { jobs: Record<string, Job> };
+const load = (name: string) => loadYaml(readFileSync(join(root, '.github/workflows', name), 'utf8')) as { jobs: Record<string, Job> };
const evaluate = (expression: string, context: Record<string, unknown>) =>
runInNewContext(expression.replace(/^\$\{\{\s*|\s*\}\}$/g, ''), { fromJSON: JSON.parse, ...context }, { timeout: 100 });
diff --git a/test/scripts/ci-runner-routing.test.ts b/test/scripts/ci-runner-routing.test.ts
index 9a7b010747..a2ce9b0959 100644
--- a/test/scripts/ci-runner-routing.test.ts
+++ b/test/scripts/ci-runner-routing.test.ts
@@ -2,14 +2,14 @@ import { describe, expect, test } from 'bun:test';
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
import { runInNewContext } from 'node:vm';
-import { safeLoad } from 'js-yaml';
+import { load as loadYaml } from 'js-yaml';
type Job = {
'runs-on'?: string;
strategy?: { matrix: { os?: string[]; target?: string[] } };
};
const root = join(import.meta.dir, '../..');
-const load = (name: string) => safeLoad(readFileSync(join(root, '.github/workflows', name), 'utf8')) as { jobs: Record<string, Job> };
+const load = (name: string) => loadYaml(readFileSync(join(root, '.github/workflows', name), 'utf8')) as { jobs: Record<string, Job> };
const normal = 'ubicloud-standard-16-ubuntu-2404';
const heavy = 'ubicloud-standard-30-ubuntu-2404';
const small = 'ubicloud-standard-2-ubuntu-2404';
@@ -88,7 +88,7 @@ describe('CI runner routing', () => {
test('macOS 26 validation is pinned, time-boxed, label-gated on pull requests and uses no secrets', () => {
const text = readFileSync(join(root, '.github/workflows/macos-validation.yml'), 'utf8');
- const workflow = safeLoad(text) as { on: Record<string, unknown>; jobs: Record<string, Job & { 'timeout-minutes'?: number; if?: string }> };
+ const workflow = loadYaml(text) as { on: Record<string, unknown>; jobs: Record<string, Job & { 'timeout-minutes'?: number; if?: string }> };
expect(Object.keys(workflow.on).sort()).toEqual(['pull_request', 'schedule', 'workflow_dispatch']);
const job = workflow.jobs['macos-26']!;
expect(job['runs-on']).toBe('macos-26');
@@ -109,9 +109,9 @@ describe('CI runner routing', () => {
});
test('actionlint recognizes every configured custom label and watches its configuration', () => {
- const config = safeLoad(readFileSync(join(root, '.github/actionlint.yaml'), 'utf8')) as { 'self-hosted-runner': { labels: string[] } };
+ const config = loadYaml(readFileSync(join(root, '.github/actionlint.yaml'), 'utf8')) as { 'self-hosted-runner': { labels: string[] } };
expect(config['self-hosted-runner'].labels.sort()).toEqual([small, report, pooled, normal, heavy, arm].sort());
- const workflow = safeLoad(readFileSync(join(root, '.github/workflows/actionlint.yml'), 'utf8')) as { on: Record<string, { paths: string[] }> };
+ const workflow = loadYaml(readFileSync(join(root, '.github/workflows/actionlint.yml'), 'utf8')) as { on: Record<string, { paths: string[] }> };
for (const event of ['push', 'pull_request']) expect(workflow.on[event].paths).toContain('.github/actionlint.yaml');
});
});
diff --git a/test/scripts/data-safety-native-workflow.test.ts b/test/scripts/data-safety-native-workflow.test.ts
index cb66abfa8b..f20e0cf582 100644
--- a/test/scripts/data-safety-native-workflow.test.ts
+++ b/test/scripts/data-safety-native-workflow.test.ts
@@ -3,7 +3,7 @@ import { createHash } from 'node:crypto';
import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
-import { safeLoad } from 'js-yaml';
+import { load } from 'js-yaml';
type Step = {
name?: string;
@@ -13,7 +13,7 @@ type Step = {
env?: Record<string, string>;
'continue-on-error'?: boolean;
};
-const workflow = safeLoad(readFileSync(join(import.meta.dir, '../../.github/workflows/native-locks.yml'), 'utf8')) as {
+const workflow = load(readFileSync(join(import.meta.dir, '../../.github/workflows/native-locks.yml'), 'utf8')) as {
jobs: {
native: { steps: Step[]; strategy: { matrix: { target: string[]; bun: string[] } } };
'windows-backup-console': { steps: Step[]; 'runs-on': string; 'timeout-minutes': number;
@@ -155,7 +155,7 @@ describe('data-safety native CI coverage', () => {
});
for (const exitCode of [0, 1]) test(`read diagnostics run with PostgreSQL and retain test failure (${exitCode})`, () => {
- const persistence = safeLoad(readFileSync(join(import.meta.dir, '../../.github/workflows/persistence-validation.yml'), 'utf8')) as {
+ const persistence = load(readFileSync(join(import.meta.dir, '../../.github/workflows/persistence-validation.yml'), 'utf8')) as {
jobs: { 'deployment-matrix': { steps: Step[] } };
};
const step = persistence.jobs['deployment-matrix'].steps.find(entry => entry.name === 'Require PostgreSQL lifecycle, projection and recovery contracts');
@@ -173,7 +173,7 @@ describe('data-safety native CI coverage', () => {
});
for (const exitCode of [0, 1]) test(`read latency is advisory without swallowing invalid workloads (${exitCode})`, () => {
- const persistence = safeLoad(readFileSync(join(import.meta.dir, '../../.github/workflows/persistence-validation.yml'), 'utf8')) as {
+ const persistence = load(readFileSync(join(import.meta.dir, '../../.github/workflows/persistence-validation.yml'), 'utf8')) as {
jobs: { 'read-performance': { steps: Step[]; 'continue-on-error'?: boolean } };
};
const job = persistence.jobs['read-performance'];
@@ -193,7 +193,7 @@ describe('data-safety native CI coverage', () => {
});
test('publication and sync safety suites run in separate PostgreSQL-bearing CI processes', () => {
- const persistence = safeLoad(readFileSync(join(import.meta.dir, '../../.github/workflows/persistence-validation.yml'), 'utf8')) as {
+ const persistence = load(readFileSync(join(import.meta.dir, '../../.github/workflows/persistence-validation.yml'), 'utf8')) as {
jobs: { 'deployment-matrix': { steps: Step[] } };
};
const step = persistence.jobs['deployment-matrix'].steps.find(entry => entry.name === 'Require data-safety on PostgreSQL');
@@ -212,7 +212,7 @@ describe('data-safety native CI coverage', () => {
});
test('pull requests and merge-queue runs run a 2,500-write persistence soak while master keeps the full 10,000-write gate', () => {
- const persistence = safeLoad(readFileSync(join(import.meta.dir, '../../.github/workflows/persistence-validation.yml'), 'utf8')) as {
+ const persistence = load(readFileSync(join(import.meta.dir, '../../.github/workflows/persistence-validation.yml'), 'utf8')) as {
jobs: { invariants: { steps: Step[] } };
};
const step = persistence.jobs.invariants.steps.find(entry => entry.run?.includes('scripts/persistence/validate.ts'));
@@ -232,7 +232,7 @@ describe('data-safety native CI coverage', () => {
});
test('the crash robot runs beside the soak: 150 s on pull requests, 600 s elsewhere, Postgres through PgBouncer', () => {
- const persistence = safeLoad(readFileSync(join(import.meta.dir, '../../.github/workflows/persistence-validation.yml'), 'utf8')) as {
+ const persistence = load(readFileSync(join(import.meta.dir, '../../.github/workflows/persistence-validation.yml'), 'utf8')) as {
jobs: { 'crash-robot': { steps: Step[]; services: Record<string, { env?: Record<string, string> }> } };
};
const job = persistence.jobs['crash-robot'];
diff --git a/test/scripts/fix-wave-closeout.test.ts b/test/scripts/fix-wave-closeout.test.ts
index ffc9686f46..8908df037c 100644
--- a/test/scripts/fix-wave-closeout.test.ts
+++ b/test/scripts/fix-wave-closeout.test.ts
@@ -11,7 +11,7 @@
import { describe, expect, test } from 'bun:test';
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
-import { safeLoad } from 'js-yaml';
+import { load } from 'js-yaml';
import {
COMMENT_MARKER, closeoutMessage, isMergedWave, runCloseout, supersededNumbers,
type CloseoutClient, type CloseoutEvent, type PullInfo,
@@ -140,7 +140,7 @@ describe('fix-wave closeout run', () => {
});
describe('fix-wave-closeout workflow', () => {
- const wf = safeLoad(readFileSync(join(ROOT, '.github', 'workflows', 'fix-wave-closeout.yml'), 'utf8')) as {
+ const wf = load(readFileSync(join(ROOT, '.github', 'workflows', 'fix-wave-closeout.yml'), 'utf8')) as {
on: Record<string, { branches?: string[]; types?: string[] }>;
permissions: Record<string, string>;
jobs: Record<string, { if?: string; permissions: Record<string, string>; steps: Array<{ uses?: string; with?: Record<string, unknown>; run?: string }> }>;
diff --git a/test/scripts/fix-wave-gate.test.ts b/test/scripts/fix-wave-gate.test.ts
index 883ef41d77..f9c3b120a6 100644
--- a/test/scripts/fix-wave-gate.test.ts
+++ b/test/scripts/fix-wave-gate.test.ts
@@ -13,7 +13,7 @@ import { describe, expect, test } from 'bun:test';
import { spawnSync } from 'node:child_process';
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
-import { safeLoad } from 'js-yaml';
+import { load as loadYaml } from 'js-yaml';
import {
COMMENT_MARKER, MAINTAINERS, OVERRIDE_LABEL, decide, gateMessage, runGate,
type GateClient, type GateEvent, type TimelineEvent,
@@ -127,7 +127,7 @@ describe('fix-wave gate decision', () => {
describe('fix-wave gate workflow', () => {
const text = readFileSync(join(ROOT, '.github', 'workflows', 'fix-wave-gate.yml'), 'utf8');
type Step = { uses?: string; run?: string; with?: Record<string, unknown>; env?: Record<string, string> };
- const wf = safeLoad(text) as { on: Record<string, { branches: string[]; types: string[] }>; permissions: unknown; jobs: Record<string, { permissions: Record<string, string>; steps: Step[]; if?: string }> };
+ const wf = loadYaml(text) as { on: Record<string, { branches: string[]; types: string[] }>; permissions: unknown; jobs: Record<string, { permissions: Record<string, string>; steps: Step[]; if?: string }> };
test('a PR that edits the workflow or the gate script cannot change its own result', async () => {
// pull_request_target runs the default-branch copy of both files; a pull_request trigger would run the PR's copy.
diff --git a/test/scripts/heavy-door-workflow.test.ts b/test/scripts/heavy-door-workflow.test.ts
index ad7e5cee1e..85da8a2932 100644
--- a/test/scripts/heavy-door-workflow.test.ts
+++ b/test/scripts/heavy-door-workflow.test.ts
@@ -3,12 +3,12 @@ import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'nod
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { spawnSync } from 'node:child_process';
-import { safeLoad } from 'js-yaml';
+import { load } from 'js-yaml';
type Step = { name?: string; id?: string; if?: string; run?: string; env?: Record<string, string>; with?: Record<string, string> };
type Job = { name: string; env: Record<string, string>; strategy?: { 'fail-fast': boolean; matrix: { lane: string } }; steps: Step[] };
const root = join(import.meta.dir, '../..');
-const workflow = safeLoad(readFileSync(join(root, '.github/workflows/heavy-tests.yml'), 'utf8')) as {
+const workflow = load(readFileSync(join(root, '.github/workflows/heavy-tests.yml'), 'utf8')) as {
on: { workflow_dispatch: { inputs: Record<string, { default: boolean }> } };
jobs: Record<string, Job>;
};
diff --git a/test/scripts/native-lock-prebuilds.test.ts b/test/scripts/native-lock-prebuilds.test.ts
index 4917dc94ce..48b54f1b21 100644
--- a/test/scripts/native-lock-prebuilds.test.ts
+++ b/test/scripts/native-lock-prebuilds.test.ts
@@ -3,7 +3,7 @@ import { cpSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:f
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { spawnSync } from 'node:child_process';
-import { safeLoad } from 'js-yaml';
+import { load } from 'js-yaml';
import manifest from '../../native/locks/manifest.json';
const repo = join(import.meta.dir, '../..');
@@ -71,7 +71,7 @@ describe('native lock distribution integrity', () => {
strategy: { matrix: { bun: string[]; target: string[] } };
steps: Array<{ run?: string }>;
};
- const workflow = safeLoad(readFileSync(join(repo, '.github/workflows/native-locks.yml'), 'utf8')) as {
+ const workflow = load(readFileSync(join(repo, '.github/workflows/native-locks.yml'), 'utf8')) as {
jobs: Record<string, NativeJob>;
};
const pairs: string[] = [];
diff --git a/test/scripts/native-only-workflow.test.ts b/test/scripts/native-only-workflow.test.ts
index c120855abd..d88bd805c0 100644
--- a/test/scripts/native-only-workflow.test.ts
+++ b/test/scripts/native-only-workflow.test.ts
@@ -4,10 +4,10 @@ import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { spawnSync } from 'node:child_process';
import { runInNewContext } from 'node:vm';
-import { safeLoad } from 'js-yaml';
+import { load } from 'js-yaml';
type Job = { if?: string; name?: string; needs?: string[]; uses?: string; steps?: Array<{ name: string; run?: string }> };
-const workflow = safeLoad(readFileSync(join(import.meta.dir, '../../.github/workflows/test.yml'), 'utf8')) as {
+const workflow = load(readFileSync(join(import.meta.dir, '../../.github/workflows/test.yml'), 'utf8')) as {
on: { workflow_dispatch: { inputs: Record<string, { type: string; default: boolean | string }> } };
concurrency: { group: string; 'cancel-in-progress': boolean }; jobs: Record<string, Job>;
};
diff --git a/test/scripts/nightly-e2e.test.ts b/test/scripts/nightly-e2e.test.ts
index a12af95daf..78c79523ac 100644
--- a/test/scripts/nightly-e2e.test.ts
+++ b/test/scripts/nightly-e2e.test.ts
@@ -3,7 +3,7 @@ import { mkdtempSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSyn
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { spawnSync } from 'node:child_process';
-import { safeLoad } from 'js-yaml';
+import { load } from 'js-yaml';
import { verifyNightlyE2E } from '../../scripts/verify-nightly-e2e.ts';
import { classifyShards, main as classifyMain, DOCS as CLASSIFY_DOCS, type ShardJob } from '../../scripts/classify-full-e2e-shards.ts';
@@ -53,7 +53,7 @@ describe('nightly E2E execution receipts', () => {
describe('nightly E2E scheduling', () => {
test('full-profile shell flags use environment data instead of expression interpolation', () => {
- const workflow = safeLoad(readFileSync(join(repo, '.github/workflows/e2e.yml'), 'utf8')) as any;
+ const workflow = load(readFileSync(join(repo, '.github/workflows/e2e.yml'), 'utf8')) as any;
const steps = [
workflow.jobs['prepare-e2e'].steps.find((step: any) => step.id === 'select'),
workflow.jobs['e2e-status'].steps.find((step: any) => step.name === 'Aggregate result'),
@@ -94,7 +94,7 @@ describe('nightly E2E scheduling', () => {
}, partitions);
});
test('nightly jobs preserve job-local Postgres, independent artifacts, always-reporting and required execution evidence', () => {
- const workflow = safeLoad(readFileSync(join(repo, '.github/workflows/e2e.yml'), 'utf8')) as any;
+ const workflow = load(readFileSync(join(repo, '.github/workflows/e2e.yml'), 'utf8')) as any;
const job = workflow.jobs['coverage-full-e2e'];
expect(job.if).toBe(fullProfile);
expect(job.strategy).toEqual({ 'fail-fast': false, matrix: { shard: [1, 2, 3, 4] } });
@@ -159,7 +159,7 @@ describe('nightly E2E scheduling', () => {
expect(validate.run).toBe('bun scripts/verify-nightly-e2e.ts "$RUNNER_TEMP/e2e-execution" 4 "$GITHUB_SHA"');
});
test('manual full corpus is opt-in and uses the complete scheduled profile without cancelling ordinary runs', () => {
- const workflow = safeLoad(readFileSync(join(repo, '.github/workflows/e2e.yml'), 'utf8')) as any;
+ const workflow = load(readFileSync(join(repo, '.github/workflows/e2e.yml'), 'utf8')) as any;
expect(workflow.on.workflow_dispatch.inputs.full_corpus).toMatchObject({ type: 'boolean', default: false });
for (const name of ['coverage-full-unit', 'coverage-full-serial', 'coverage-full-slow', 'coverage-full-e2e']) expect(workflow.jobs[name].if).toBe(fullProfile);
for (const step of workflow.jobs['e2e-status'].steps.slice(1)) expect(step.if).toBe(fullProfile);
diff --git a/test/scripts/nightly-issue.test.ts b/test/scripts/nightly-issue.test.ts
index 24a434360f..aa6fc3163a 100644
--- a/test/scripts/nightly-issue.test.ts
+++ b/test/scripts/nightly-issue.test.ts
@@ -10,7 +10,7 @@ import { existsSync, mkdtempSync, readdirSync, readFileSync, writeFileSync } fro
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { deflateRawSync } from 'node:zlib';
-import { safeLoad } from 'js-yaml';
+import { load as loadYaml } from 'js-yaml';
import { loadReceiptDir } from '../../scripts/ci-executed-counts.ts';
import { buildManifest, checkManifest, failureSignature, junitMessages, MANIFEST_ARTIFACT, MANIFEST_SCHEMA, type CiManifest } from '../../scripts/ci-manifest.ts';
import { failureSignature as gateSignature, parseExemptionBlocks } from '../fixtures/nightly-watch/stress-exemption-contract.ts';
@@ -233,8 +233,8 @@ describe('.github/nightly-known-red.tsv', () => {
describe('nightly-watch coverage ratchet', () => {
test('every workflow with a schedule trigger is watched', () => {
const dir = join(ROOT, '.github/workflows');
- const watch = safeLoad(readFileSync(join(dir, 'nightly-watch.yml'), 'utf8')) as { on: { workflow_run: { workflows: string[] } } };
- const scheduled = readdirSync(dir).filter(f => f.endsWith('.yml')).map(f => safeLoad(readFileSync(join(dir, f), 'utf8')) as { name: string; on?: { schedule?: unknown } })
+ const watch = loadYaml(readFileSync(join(dir, 'nightly-watch.yml'), 'utf8')) as { on: { workflow_run: { workflows: string[] } } };
+ const scheduled = readdirSync(dir).filter(f => f.endsWith('.yml')).map(f => loadYaml(readFileSync(join(dir, f), 'utf8')) as { name: string; on?: { schedule?: unknown } })
.filter(w => w.on && typeof w.on === 'object' && 'schedule' in w.on).map(w => w.name);
expect(scheduled.length).toBeGreaterThan(5);
const missing = scheduled.filter(name => !watch.on.workflow_run.workflows.includes(name));
@@ -774,7 +774,7 @@ describe('nightly-watch routing and guard', () => {
test('push run of a non-allowlisted workflow refused', () => refuse({ ...T.r8320, name: 'Heavy Tests', path: '.github/workflows/heavy-tests.yml' }, 'which master-red does not watch'));
test('a replay must be an E2E Tests dispatch on master', () => refuse({ ...T.r8320, event: 'workflow_dispatch' }, 'issue-bound replay must be an E2E Tests dispatch', 7));
- const yaml = (f: string) => safeLoad(readFileSync(join(ROOT, '.github/workflows', f), 'utf8')) as Record<string, any>;
+ const yaml = (f: string) => loadYaml(readFileSync(join(ROOT, '.github/workflows', f), 'utf8')) as Record<string, any>;
test('nightly-watch.yml: master-only workflow_run, guard for schedule + allowlisted push-to-master from this repo, one queue per repo + workflow + track', () => {
const w = yaml('nightly-watch.yml');
expect(w.on.workflow_run.branches).toEqual(['master']);
diff --git a/test/scripts/release-gate.test.ts b/test/scripts/release-gate.test.ts
index fcff5257b8..df624974f7 100644
--- a/test/scripts/release-gate.test.ts
+++ b/test/scripts/release-gate.test.ts
@@ -9,7 +9,7 @@
import { describe, expect, test } from 'bun:test';
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
-import { safeLoad } from 'js-yaml';
+import { load } from 'js-yaml';
import { evaluate, gate, GATED, type GateDeps, type GateRun } from '../../scripts/release-gate.ts';
const A = 'a'.repeat(40);
@@ -93,7 +93,7 @@ describe('release gate', () => {
});
describe('release.yml waits for the CI gate', () => {
- const wf = safeLoad(readFileSync(join(import.meta.dir, '../../.github/workflows/release.yml'), 'utf8')) as { on: Record<string, unknown>; jobs: Record<string, { needs?: string[] | string; if?: string; steps: Array<{ run?: string; with?: Record<string, string>; env?: Record<string, string> }>; permissions?: Record<string, string> }> };
+ const wf = load(readFileSync(join(import.meta.dir, '../../.github/workflows/release.yml'), 'utf8')) as { on: Record<string, unknown>; jobs: Record<string, { needs?: string[] | string; if?: string; steps: Array<{ run?: string; with?: Record<string, string>; env?: Record<string, string> }>; permissions?: Record<string, string> }> };
test('build, release, latest-stable and the publish jobs need ci-gate and use its commit', () => {
expect(wf.on.workflow_dispatch).toBeDefined();
const gateJob = wf.jobs['ci-gate']!;
diff --git a/test/scripts/stress-plan.test.ts b/test/scripts/stress-plan.test.ts
index 9b4b067d56..0f29d49ec5 100644
--- a/test/scripts/stress-plan.test.ts
+++ b/test/scripts/stress-plan.test.ts
@@ -8,7 +8,7 @@ import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'nod
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { runInNewContext } from 'node:vm';
-import { safeLoad } from 'js-yaml';
+import { load } from 'js-yaml';
import {
HELPER_FAN_IN_LIMIT, SPECIAL_FILES, allTestFiles, changedFiles, defaultSeed, directImporters, expandHelper,
notStressedReason, parseFileList, planShards, profileFor, redact, reproduceLine, seededSample, validRef,
@@ -44,7 +44,7 @@ describe('execution profiles', () => {
});
test('slow-file specifics mirror the workflow values a pull request uses', () => {
- const wf = safeLoad(readFileSync(join(REPO, '.github/workflows/test.yml'), 'utf8')) as { jobs: Record<string, { steps: Array<{ run?: string; env?: Record<string, string> }> }> };
+ const wf = load(readFileSync(join(REPO, '.github/workflows/test.yml'), 'utf8')) as { jobs: Record<string, { steps: Array<{ run?: string; env?: Record<string, string> }> }> };
const exportStep = wf.jobs['slow-entity-resolve-perf']!.steps.find(s => s.run?.includes('test/export-scale.slow.test.ts'))!;
const pages = runInNewContext(exportStep.env!.GBRAIN_TEST_EXPORT_SCALE_PAGES!.replace(/^\$\{\{\s*|\s*\}\}$/g, ''), { github: { event_name: 'pull_request' } });
expect(profileFor('test/export-scale.slow.test.ts', { armed: true, postgres: false }).vars).toEqual({ GBRAIN_TEST_EXPORT_SCALE_PAGES: pages });
diff --git a/test/transcript-render.test.ts b/test/transcript-render.test.ts
index ebd6a04c84..4951c709da 100644
--- a/test/transcript-render.test.ts
+++ b/test/transcript-render.test.ts
@@ -5,7 +5,7 @@
* embed-skip-driven part splitting with overlap.
*/
import { describe, test, expect } from 'bun:test';
-import { safeLoad } from 'js-yaml';
+import { load } from 'js-yaml';
import {
escapeAnchorLines,
@@ -41,7 +41,7 @@ function splitBody(content: string): string {
function frontmatter(content: string): Record<string, any> {
const end = content.indexOf('---', 4);
- return safeLoad(content.slice(4, end)) as Record<string, any>;
+ return load(content.slice(4, end)) as Record<string, any>;
}
const BASIC = session([
diff --git a/test/yaml-1-2-frontmatter.test.ts b/test/yaml-1-2-frontmatter.test.ts
new file mode 100644
index 0000000000..9422b2ed76
--- /dev/null
+++ b/test/yaml-1-2-frontmatter.test.ts
@@ -0,0 +1,56 @@
+import { describe, expect, test } from 'bun:test';
+import { dump, load } from 'js-yaml';
+import { parseDataFrontmatter, stringifyDataFrontmatter } from '../src/core/data-frontmatter.ts';
+import { NAIVE_DATETIME } from '../src/core/effective-date.ts';
+
+// js-yaml 4 parses YAML 1.2 core scalars. These cases pin what changed from
+// js-yaml 3 (YAML 1.1 integers) and what must not change (dates, duplicate
+// keys, merge keys), so a parser upgrade cannot silently rewrite page data.
+const fm = (yaml: string) => parseDataFrontmatter(`---\n${yaml}\n---\nbody\n`).data;
+
+describe('frontmatter scalars under YAML 1.2 (js-yaml 4)', () => {
+ test('clock-like values stay strings instead of base-60 numbers', () => {
+ expect(fm('start: 10:30')).toEqual({ start: '10:30' });
+ expect(fm('duration: 1:20:05')).toEqual({ duration: '1:20:05' });
+ });
+
+ test('a leading zero is decimal, 0o is octal, underscores are not digit separators', () => {
+ expect(fm('id: 010')).toEqual({ id: 10 });
+ expect(fm('mode: 0o755')).toEqual({ mode: 0o755 });
+ expect(fm('count: 1_000')).toEqual({ count: '1_000' });
+ });
+
+ test('yes/no/on/off stay strings; only true/false are booleans', () => {
+ expect(fm('a: yes\nb: off\nc: true\nd: False')).toEqual({ a: 'yes', b: 'off', c: true, d: false });
+ });
+
+ test('dates still load as Date, calendar-invalid dates stay strings, naive datetimes keep their marker', () => {
+ const data = fm('date: 2024-02-29\nbad: 2024-02-30\nat: 2024-03-01 09:15:00');
+ expect(data.date).toBeInstanceOf(Date);
+ expect((data.date as Date).toISOString()).toBe('2024-02-29T00:00:00.000Z');
+ expect(data.bad).toBe('2024-02-30');
+ expect((data.at as Date & Record<symbol, unknown>)[NAIVE_DATETIME]).toBe(true);
+ });
+
+ test('duplicate keys are refused and merge keys still merge', () => {
+ expect(() => fm('title: a\ntitle: b')).toThrow(/Malformed YAML frontmatter/);
+ expect(fm('base: &b {x: 1}\npage:\n <<: *b\n y: 2').page).toEqual({ x: 1, y: 2 });
+ });
+});
+
+describe('frontmatter writes round-trip', () => {
+ const risky = ['2024-01-01', 'yes', 'no', 'on', 'null', '~', '', '010', '0o10', '1e3', '0x10', '.inf',
+ '12:30', ' lead', 'trail ', '# hash', 'a: b', '-x', '[x]', '{x}', '${{ github.token }}', '"q"', "'s'",
+ 'multi\nline', 'unicode é ✓', 'https://x.y/z?a=b#c', 'C:\\path', '<<', '---', '1_000'];
+
+ test('every risky string survives stringify then parse as the same string', () => {
+ for (const value of risky) {
+ const text = stringifyDataFrontmatter('body\n', { value, list: [value] });
+ expect(parseDataFrontmatter(text).data).toEqual({ value, list: [value] });
+ }
+ });
+
+ test('dump never emits a value that load reads back as a different type', () => {
+ for (const value of risky) expect(load(dump({ value }))).toEqual({ value });
+ });
+});