Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(schema-pack): decode quoted YAML scalars, guard the write boundary and the pack size (#6432)

garrytan905ac385b4d9
diff --git a/docs/architecture/key-files/schema-mutation.md b/docs/architecture/key-files/schema-mutation.md
index a99a87c513..1c94a7d885 100644
--- a/docs/architecture/key-files/schema-mutation.md
+++ b/docs/architecture/key-files/schema-mutation.md
@@ -24,7 +24,7 @@ Key files:
- `src/core/schema-pack/lint-rules.ts` — 14 pure rule functions. `withMutation`'s pre-write validation gate composes the 10 file-plane rules; the 4 DB-aware rules (`extractable_empty_corpus`, `mutation_count_anomaly`, `stored_type_is_alias`, `stored_type_undeclared`) need an engine (CLI `--with-db`; the stored-type pair accepts `LintOpts.sourceId` scoping, not yet threaded from the CLI). Single source of truth consumed by CLI lint + MCP `schema_lint` + the pre-write validation gate. File-plane rule `link_regex_catastrophic_backtrack` — advisory ReDoS pre-screen flagging the classic nested-quantifier shapes (`(a+)+`, `(a*)*`, `(a+)*`, `(\w+)+`) in a link_type's `inference.regex` via `NESTED_QUANTIFIER_RE`. WARNING not error: a hard reject would disable the whole pack on upgrade (pages fall back to legacy typing). The runtime input-length cap in `redos-guard.ts` is the actual safety net; this rule tells the pack author to fix the pattern.
- `src/core/schema-pack/redos-guard.ts` + `src/core/schema-pack/link-inference.ts` — ReDoS hardening for pack inference regexes. `redos-guard.ts` provides `MAX_REGEX_INPUT_CHARS` (default 64_000, env `GBRAIN_MAX_REGEX_INPUT_CHARS`) — a hard input-length cap, the real runtime safety net (catastrophic backtracking needs a long input; a link-extraction `context` is normally a sentence or short paragraph). Over the cap, `runRegexBounded` throws the tagged `RegexInputTooLargeError` and the regex is skipped (degrade-to-mentions) without entering the `node:vm`. `link-inference.ts:inferLinkTypeFromPack` no-budget branch (test contexts) routes through `runRegexBounded` so the input-length cap + per-regex vm timeout (`PER_REGEX_TIMEOUT_MS = 50`) apply on every path. Defensive hardening + diagnostics; the deterministic ~3100-file sync-wedge root cause remains open. Pinned by `test/redos-hardening.test.ts` + `test/schema-pack-lint-rules.test.ts`.
- `src/core/schema-pack/query-cache-invalidator.ts` — `invalidateQueryCache(engine, sourceId?)` DELETEs query_cache rows so cached search results bound to old page types don't survive a schema mutation.
-- `src/core/schema-pack/mutate.ts` — 8-step `withMutation` skeleton (bundled-guard → lock → read → mutator → validate → atomic write → audit → invalidate) backs the 11 single-mutation primitives: `addTypeToPack`, `removeTypeFromPack` (with reference check), `updateTypeOnPack`, `addAliasToType`, `removeAliasFromType`, `addPrefixToType`, `removePrefixFromType`, `addLinkTypeToPack`, `removeLinkTypeFromPack`, `setExtractableOnType`, `setExpertRoutingOnType`. Each primitive's business-rule validation + transform is factored into a `build*Mutator(...)` pure `(manifest) => manifest` function shared with `applyMutationsAtomic` (the `schema_apply_mutations` batch entry point) so single-call and batched mutations can never validate differently. `applyMutationsAtomic` locks + reads the pack file ONCE, applies + lint-validates every mutation in the batch against an in-memory manifest, and calls `writePackManifest` at MOST ONCE — only after the whole batch checks out — so a batch that fails partway leaves the pack file byte-identical to its pre-batch state. Atomic single write via `.tmp + fsync + rename` — the pack file on disk is NEVER partial, for either a single mutation or a batch. Inline minimal JSON→YAML emitter so YAML packs stay YAML (does NOT preserve comments — pin pack.json if you care about layout). `AddTypeOpts.noPrefix` (batch field `no_prefix`) declares a frontmatter-only type with `path_prefixes: []` (#6135); it refuses alongside a prefix, `extractable` (lint rule `extractable_empty_corpus`) or `expertRouting` (lint rule `expert_routing_without_prefix`), and a missing prefix without it stays `INVALID_RESULT`.
+- `src/core/schema-pack/mutate.ts` — 8-step `withMutation` skeleton (bundled-guard → lock → read → mutator → validate → atomic write → audit → invalidate) backs the 11 single-mutation primitives: `addTypeToPack`, `removeTypeFromPack` (with reference check), `updateTypeOnPack`, `addAliasToType`, `removeAliasFromType`, `addPrefixToType`, `removePrefixFromType`, `addLinkTypeToPack`, `removeLinkTypeFromPack`, `setExtractableOnType`, `setExpertRoutingOnType`. Each primitive's business-rule validation + transform is factored into a `build*Mutator(...)` pure `(manifest) => manifest` function shared with `applyMutationsAtomic` (the `schema_apply_mutations` batch entry point) so single-call and batched mutations can never validate differently. `applyMutationsAtomic` locks + reads the pack file ONCE, applies + lint-validates every mutation in the batch against an in-memory manifest, and calls `writePackManifest` at MOST ONCE — only after the whole batch checks out — so a batch that fails partway leaves the pack file byte-identical to its pre-batch state. Atomic single write via `.tmp + fsync + rename` — the pack file on disk is NEVER partial, for either a single mutation or a batch. Inline minimal JSON→YAML emitter so YAML packs stay YAML (does NOT preserve comments — pin pack.json if you care about layout); double-quoted scalars are JSON-escaped and `src/core/schema-pack/loader.ts`'s `parseYamlMini` decodes exactly that subset (single quotes are literal with `''`), so emit → parse is the identity (#6432). `writePackManifest` parses its own output and compares it to the manifest as normalized structures (key order free) before the atomic write, refusing `EMIT_MISMATCH` with the file unchanged; `loadPackFromFile` refuses `PACK_TOO_LARGE` from the open descriptor's size before reading (8 MiB, `GBRAIN_SCHEMA_PACK_MAX_BYTES`), and `withMutation` / `applyMutationsAtomic` keep that typed code instead of wrapping it as `PACK_CORRUPT`. Doctor's `schema_pack_active` warns on a mutable pack above 1 MiB (`GBRAIN_SCHEMA_PACK_WARN_BYTES`) with the hand-repair runbook (`docs/architecture/schema-packs.md#oversized-pack`). Pinned by `test/schema-pack-roundtrip.test.ts`, the `#6432` cases of `test/schema-pack-loader.test.ts` and `test/schema-pack-mutate.test.ts`, and `test/doctor-schema-pack.test.ts`. `AddTypeOpts.noPrefix` (batch field `no_prefix`) declares a frontmatter-only type with `path_prefixes: []` (#6135); it refuses alongside a prefix, `extractable` (lint rule `extractable_empty_corpus`) or `expertRouting` (lint rule `expert_routing_without_prefix`), and a missing prefix without it stays `INVALID_RESULT`.
- `src/core/schema-pack/stats.ts` — `runStatsCore(engine, opts)` returns per-source + aggregate page counts + coverage % + `dead_prefixes` (declared prefixes with zero matching pages — agent drilldown signal). Multi-source aware (`sourceIds[]` federated, `sourceId` single, or whole-brain). PGLite + Postgres parity via `executeRaw`. `undeclared_pages` counts pages whose non-empty type the active pack neither declares nor aliases; `coverage` is the share of pages matching the pack (untyped and undeclared both count against it). Empty brain → coverage:1.0 (vacuous truth).
- `src/core/schema-pack/review.ts` — `schema review-candidates` / `review-orphans`. `findTypeOrphans(engine, manifest, scope, limit)` (shared by the CLI and the `schema_review_orphans` MCP op) returns pages with no active-pack type match (untyped or undeclared, each with `type` + `reason`), the true `orphan_count`, `undeclared_types` counts and `truncated`; a query failure throws instead of reading as zero orphans.
- `src/core/schema-pack/sync.ts` — `runSyncCore(engine, opts)` chunked UPDATE in 1000-row batches per declared prefix. Concurrent writers never block on a single row >100ms. Write-side scoping via `ctx.sourceId` directly (NOT `sourceScopeOpts`, which inherits OAuth read federation). Idempotent on `--apply` re-run.
diff --git a/docs/architecture/schema-packs.md b/docs/architecture/schema-packs.md
index aabaaf31e6..775f5e6e0a 100644
--- a/docs/architecture/schema-packs.md
+++ b/docs/architecture/schema-packs.md
@@ -337,6 +337,50 @@ The cache + eval rows that pack-aware code wrote are isolated by the
`knobsHash` pack-folding — they become unreachable under the
restored pack so no eviction is needed.
+### YAML scalars: what the pack parser reads
+
+The pack YAML parser is a hand-rolled subset (no anchors, tags, or flow
+mappings; ship JSON for those). Quoted scalars decode their escapes:
+
+- A double-quoted scalar carries the JSON escape subset (`\\`, `\"`, `\/`,
+ `\b`, `\f`, `\n`, `\r`, `\t`, `\uXXXX`), which is exactly what every
+ `gbrain schema` mutation writes. An escape outside that subset (`"\q"`, a
+ YAML-only `"\x41"`) refuses with the line number instead of being kept as
+ literal text.
+- A single-quoted scalar is literal text; `''` is one quote.
+- A `#` inside either kind of quote is content, and a backslash inside
+ double quotes never ends the string.
+
+So a link-type regex written as `regex: \b(works? at)\b` (bare) or
+`regex: "\\b(works? at)\\b"` (double-quoted) loads as `\b(works? at)\b`,
+and a mutation writes it back as the same bytes. Before the wave 14 release a
+mutation doubled every backslash in a quoted scalar (the parser kept the
+escapes), so a pack with one regex grew 2x per `add-alias`.
+
+### Oversized pack
+
+Every mutation now parses its own output and refuses with
+`schema_pack_emit_mismatch` when it does not read back as the manifest, so
+the growth cannot recur. A pack that already grew is handled like this:
+
+- `gbrain schema <mutation>`, `gbrain schema active` and every query refuse
+ to load a pack file above 8 MiB with `schema_pack_too_large` (the size is
+ read before any byte is), and `gbrain doctor` warns on a mutable pack above
+ 1 MiB (`schema_pack_active`, `details.code: schema_pack_oversized`).
+- The original text is not recoverable automatically: after N doublings only
+ the author knows the intended regex. Open the pack file the message names
+ (`~/.gbrain/schema-packs/<name>/pack.yaml`), find the grown lines (usually
+ `inference.regex` under `link_types`; each is a very long run of
+ backslashes), rewrite each as the intended expression, save, and re-run
+ `gbrain schema validate <name>`. A `cp pack.yaml pack.yaml.bak` first costs
+ nothing.
+- `GBRAIN_SCHEMA_PACK_MAX_BYTES=<bytes>` raises the load bound for one
+ command when a pack is legitimately large; `GBRAIN_SCHEMA_PACK_WARN_BYTES`
+ moves the doctor warn bound.
+
+**Say to your agent:** *"gbrain says my schema pack is too large; help me
+restore the regex lines by hand."*
+
## Distribution
`.gbrain-schema` tarballs ride the same distribution pipeline as
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.md
index 2ccff6d661..59430ec766 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -2384,6 +2384,26 @@ Reasons: `rename_source_changed`.
|---|---|---|---|---|---|---|
| The exact authorized revision is unavailable. | A capability this request needs is not configured or not reachable on this brain. | A required capability is not available on this brain. Run `gbrain doctor --json` to see what is missing. | agent | `gbrain doctor --json` | 1 | no |
+### schema_pack_emit_mismatch
+
+<a id="schema_pack_emit_mismatch"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| A pack mutation refused to write because the YAML it emitted did not read back as the manifest it holds; the pack file on disk is unchanged. | The write boundary parses its own output and compares it to the manifest as normalized structures, so an emitter/parser asymmetry can no longer corrupt a pack silently. | Re-run the mutation on the current release; if it refuses again, run `gbrain schema validate <pack>` and report the named key with `gbrain doctor --json`. Run: gbrain schema active --json | agent | `gbrain doctor --json` | 1 | no |
+
+More: [docs/architecture/schema-packs.md#oversized-pack](../../docs/architecture/schema-packs.md#oversized-pack)
+
+### schema_pack_too_large
+
+<a id="schema_pack_too_large"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| The schema pack file is larger than the load bound, so it was not read; a pack this large is almost always a quoted scalar (a link-type regex) whose backslashes an older release doubled on every mutation. | Loading a pack of that size took every CLI process to tens of GB of memory. The original text cannot be recovered automatically: after N doublings only the author knows the intended regex, so the fix is a hand edit of the grown lines. | Open the pack file named in the message, restore the grown quoted lines (usually `inference.regex` under `link_types`) to their intended text, save, and re-run. `GBRAIN_SCHEMA_PACK_MAX_BYTES` raises the bound for one command when a pack is legitimately large. Run: gbrain schema active --json | user | `gbrain doctor --json` | 1 | no |
+
+More: [docs/architecture/schema-packs.md#oversized-pack](../../docs/architecture/schema-packs.md#oversized-pack)
+
### scope_denied
<a id="scope_denied"></a>
diff --git a/src/commands/doctor/schema-pack-checks.ts b/src/commands/doctor/schema-pack-checks.ts
index 68f812132f..df7ced9a23 100644
--- a/src/commands/doctor/schema-pack-checks.ts
+++ b/src/commands/doctor/schema-pack-checks.ts
@@ -6,7 +6,9 @@
import type { BrainEngine } from '../../core/engine.ts';
import type { Check } from '../doctor.ts';
import type { MisroutedResult } from '../../core/multi-source-drift.ts';
+import { statSync } from 'node:fs';
import { redactConnectionInfo } from '../../core/audit/redact-connection-info.ts';
+import { formatPackBytes, OVERSIZED_PACK_RUNBOOK, schemaPackMaxBytes } from '../../core/schema-pack/loader.ts';
import { loadActivePackForLocalEngine } from '../../core/schema-pack/best-effort.ts';
import { sanitizeTypeForDisplay, storedTypeMissesPack } from '../../core/schema-pack/type-usage.ts';
@@ -34,11 +36,20 @@ export async function checkSchemaPackActive(engine: BrainEngine): Promise<Check>
dbConfig = (await engine.getConfig('schema_pack')) ?? undefined;
} catch { /* engine.config may not exist on very old brains */ }
const pack = await loadActivePack({ cfg: loadConfigFileOnly(), remote: false, dbConfig });
- return {
- name: 'schema_pack_active',
- status: 'ok',
- message: `Active pack: ${pack.manifest.name} v${pack.manifest.version} (${pack.manifest.page_types.length} types, ${pack.manifest.link_types?.length ?? 0} link verbs)`,
- };
+ const summary = `Active pack: ${pack.manifest.name} v${pack.manifest.version} (${pack.manifest.page_types.length} types, ${pack.manifest.link_types?.length ?? 0} link verbs)`;
+ // #6432: a mutable pack file past the warn bound is almost always the
+ // backslash-doubling growth an older release produced; say so before
+ // every process pays for loading it, and before it hits the hard bound.
+ const oversized = await oversizedMutablePack(pack.manifest.name);
+ if (oversized) {
+ return {
+ name: 'schema_pack_active',
+ status: 'warn',
+ message: `${summary}. Its file is ${formatPackBytes(oversized.bytes)} (warn bound ${formatPackBytes(oversized.bound)}; loading refuses at ${formatPackBytes(schemaPackMaxBytes())}). Open ${oversized.path} and restore the grown quoted lines (usually a link-type regex) by hand; runbook ${OVERSIZED_PACK_RUNBOOK}.`,
+ details: { code: 'schema_pack_oversized', path: oversized.path, bytes: oversized.bytes, warn_bytes: oversized.bound, docs: OVERSIZED_PACK_RUNBOOK },
+ };
+ }
+ return { name: 'schema_pack_active', status: 'ok', message: summary };
} catch (e) {
return {
name: 'schema_pack_active',
@@ -50,6 +61,22 @@ export async function checkSchemaPackActive(engine: BrainEngine): Promise<Check>
const SCHEMA_PACK_DOCS = 'docs/architecture/schema-packs.md#undeclared-page-types';
+/** The mutable active pack's file when it exceeds the warn bound (`GBRAIN_SCHEMA_PACK_WARN_BYTES`, default 1 MiB), else null. */
+async function oversizedMutablePack(name: string): Promise<{ path: string; bytes: number; bound: number } | null> {
+ const raw = process.env.GBRAIN_SCHEMA_PACK_WARN_BYTES;
+ const parsed = raw ? Number(raw) : NaN;
+ const bound = Number.isFinite(parsed) && parsed > 0 ? Math.floor(parsed) : 1024 * 1024;
+ try {
+ const { BUNDLED_PACK_NAMES, locateMutablePackFile } = await import('../../core/schema-pack/mutate.ts');
+ if (BUNDLED_PACK_NAMES.has(name)) return null;
+ const { path } = locateMutablePackFile(name);
+ const bytes = statSync(path).size;
+ return bytes > bound ? { path, bytes, bound } : null;
+ } catch {
+ return null;
+ }
+}
+
/**
* #5432: a check that could not read its input says "not verified" (warn),
* never ok. The redacted reason rides in `details.reason` for `--json`.
diff --git a/src/commands/schema.ts b/src/commands/schema.ts
index 16b5a63790..f96ac69cf4 100644
--- a/src/commands/schema.ts
+++ b/src/commands/schema.ts
@@ -1025,6 +1025,10 @@ function handleMutationError(err: unknown): never {
console.error(`Error: ${err.message}`);
if (err.code === 'PACK_READONLY') {
console.error(' Hint: fork the pack first, then mutate the fork.');
+ } else if (err.code === 'PACK_TOO_LARGE') {
+ console.error(' Hint: `gbrain errors schema_pack_too_large` explains the hand repair.');
+ } else if (err.code === 'EMIT_MISMATCH') {
+ console.error(' Hint: `gbrain errors schema_pack_emit_mismatch` explains what refused.');
} else if (err.code === 'STILL_REFERENCED') {
const refs = (err.details?.references as string[] | undefined) ?? [];
if (refs.length > 0) console.error(` Still referenced by: ${refs.join(', ')}`);
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 548ebfc68a..0a72c1934b 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -373,6 +373,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
{ since: '0.60.147.0', text: 'In a brain folder with the Git durability hook, a write that arrives while the effect worker commits a backlog of Git effects now publishes after the group in flight, inside its 5 s wait, instead of returning pending after the whole backlog; Git effects still commit in order. A write waiting on a busy worktree is reported as `writer_busy` without a stale preparing phase.' },
// `since` is a placeholder equal to the branch's VERSION until the merge-slot stamp.
{ since: '0.60.151.0', text: '`delta` and `context_pack` called without `include_private`, and the per-turn context block that harness hooks inject, now apply to their facts the same page-visibility rule they already apply to their pages. With `include_private` from the local CLI, `delta` and `context_pack` output is unchanged.' },
+ // W14 PR1 P1.2 (#6432). `since` is a placeholder equal to the branch's VERSION until the merge-slot stamp.
+ { since: '0.60.156.0', text: 'Schema-pack YAML now decodes quoted scalars: a double-quoted value carries the JSON escape subset and a single-quoted value is literal text with `\'\'` for one quote, so a link-type regex written as `"\\\\b"` loads as `\\b` and a `gbrain schema` mutation writes it back unchanged (before, every mutation doubled the backslashes of every quoted scalar). A hand-written double-quoted value that meant two backslashes now means one. A mutation whose emitted YAML does not read back as the manifest refuses with `schema_pack_emit_mismatch` and leaves the file unchanged; a pack file above 8 MiB refuses to load with `schema_pack_too_large` instead of being read, and `gbrain doctor` warns on a mutable pack above 1 MiB with the hand-repair runbook.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index afa8c60013..2ce94ca936 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -457,6 +457,17 @@ export const CODES = {
writer_transfer_required: { class: 'caller', summary: "Writer transfer required." },
writer_upgrade_required: { class: 'host_only', summary: "Apply the canonical writer guard, outbox, and source lifecycle migrations before activation." },
wrong_account_consented: { class: 'caller', summary: "Google connect credential error: wrong account consented.", docs: 'docs/guides/google-connect.md#troubleshooting' },
+ // W14 PR1 P1.2 (#6432): schema-pack file growth. Both are SchemaPackMutationError/SchemaPackLoaderError codes (PACK_TOO_LARGE, EMIT_MISMATCH) in their snake_case registry form.
+ schema_pack_too_large: { class: 'host_only', actor: 'user', summary: "The schema pack file is larger than the load bound, so it was not read; a pack this large is almost always a quoted scalar (a link-type regex) whose backslashes an older release doubled on every mutation.",
+ why: 'Loading a pack of that size took every CLI process to tens of GB of memory. The original text cannot be recovered automatically: after N doublings only the author knows the intended regex, so the fix is a hand edit of the grown lines.',
+ docs: 'docs/architecture/schema-packs.md#oversized-pack',
+ suggestion: 'Open the pack file named in the message, restore the grown quoted lines (usually `inference.regex` under `link_types`) to their intended text, save, and re-run. `GBRAIN_SCHEMA_PACK_MAX_BYTES` raises the bound for one command when a pack is legitimately large.',
+ fix: { argv: ['gbrain', 'schema', 'active', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Shows which pack is active and where it resolved; changes nothing.' } },
+ schema_pack_emit_mismatch: { class: 'server', summary: "A pack mutation refused to write because the YAML it emitted did not read back as the manifest it holds; the pack file on disk is unchanged.",
+ why: 'The write boundary parses its own output and compares it to the manifest as normalized structures, so an emitter/parser asymmetry can no longer corrupt a pack silently.',
+ docs: 'docs/architecture/schema-packs.md#oversized-pack',
+ suggestion: 'Re-run the mutation on the current release; if it refuses again, run `gbrain schema validate <pack>` and report the named key with `gbrain doctor --json`.',
+ fix: { argv: ['gbrain', 'schema', 'active', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Shows which pack is active and where it resolved; changes nothing.' } },
} as const satisfies Record<string, CodeEntry>;
export type RegistryCode = keyof typeof CODES;
diff --git a/src/core/schema-pack/loader.ts b/src/core/schema-pack/loader.ts
index e418a3a9e5..ec914ae906 100644
--- a/src/core/schema-pack/loader.ts
+++ b/src/core/schema-pack/loader.ts
@@ -16,15 +16,17 @@
// when available. Empty file → INVALID_SHAPE. Unknown extension → falls
// through to JSON.parse attempt.
-import { readFileSync } from 'node:fs';
+import { closeSync, fstatSync, openSync, readSync } from 'node:fs';
import { extname } from 'node:path';
import { parseSchemaPackManifest, type SchemaPackManifest } from './manifest-v1.ts';
+export type SchemaPackLoaderErrorCode = 'PARSE_ERROR' | 'FILE_NOT_FOUND' | 'UNSUPPORTED_EXTENSION' | 'PACK_TOO_LARGE';
+
export class SchemaPackLoaderError extends Error {
- readonly code: 'PARSE_ERROR' | 'FILE_NOT_FOUND' | 'UNSUPPORTED_EXTENSION';
+ readonly code: SchemaPackLoaderErrorCode;
readonly path: string;
- constructor(code: 'PARSE_ERROR' | 'FILE_NOT_FOUND' | 'UNSUPPORTED_EXTENSION', message: string, path: string) {
+ constructor(code: SchemaPackLoaderErrorCode, message: string, path: string) {
super(message);
this.name = 'SchemaPackLoaderError';
this.code = code;
@@ -32,17 +34,63 @@ export class SchemaPackLoaderError extends Error {
}
}
+/**
+ * The most bytes a pack file may hold (#6432). A hand-written manifest is
+ * tens of KB; a mutable pack past this bound is almost certainly the
+ * backslash-doubling growth an older release produced, and loading it is
+ * what took every CLI process to tens of GB of memory. The bound is read
+ * from the file size before any byte is allocated. Override:
+ * `GBRAIN_SCHEMA_PACK_MAX_BYTES` (also the doctor warn bound's default).
+ */
+export const SCHEMA_PACK_MAX_BYTES_DEFAULT = 8 * 1024 * 1024;
+export const OVERSIZED_PACK_RUNBOOK = 'docs/architecture/schema-packs.md#oversized-pack';
+
+export function schemaPackMaxBytes(): number {
+ const raw = process.env.GBRAIN_SCHEMA_PACK_MAX_BYTES;
+ const n = raw ? Number(raw) : NaN;
+ return Number.isFinite(n) && n > 0 ? Math.floor(n) : SCHEMA_PACK_MAX_BYTES_DEFAULT;
+}
+
+export function formatPackBytes(bytes: number): string {
+ if (bytes >= 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)} MiB`;
+ if (bytes >= 1024) return `${(bytes / 1024).toFixed(1)} KiB`;
+ return `${bytes} B`;
+}
+
/**
* Load + parse + validate a pack from disk. Returns the validated manifest.
- * Throws SchemaPackLoaderError (file/parse errors) or
- * SchemaPackManifestError (shape/version errors).
+ * Throws SchemaPackLoaderError (file/parse/size errors) or
+ * SchemaPackManifestError (shape/version errors). The size check runs on
+ * the open descriptor before the read, and the read is bounded to that
+ * size, so a file that grows under us never allocates past the bound.
*/
-export function loadPackFromFile(path: string): SchemaPackManifest {
+export function loadPackFromFile(path: string, opts: { maxBytes?: number } = {}): SchemaPackManifest {
+ const maxBytes = opts.maxBytes ?? schemaPackMaxBytes();
+ let fd = -1;
let content: string;
try {
- content = readFileSync(path, 'utf-8');
+ fd = openSync(path, 'r');
+ const size = fstatSync(fd).size;
+ if (size > maxBytes) {
+ throw new SchemaPackLoaderError(
+ 'PACK_TOO_LARGE',
+ `pack file ${path} is ${formatPackBytes(size)}, above the ${formatPackBytes(maxBytes)} bound; it was not read. A pack this large is usually a quoted scalar (a link-type regex) whose backslashes an older release doubled on every mutation: open the file in an editor, restore the affected lines by hand, and re-run. Runbook: ${OVERSIZED_PACK_RUNBOOK}.`,
+ path,
+ );
+ }
+ const buf = Buffer.allocUnsafe(size);
+ let read = 0;
+ while (read < size) {
+ const n = readSync(fd, buf, read, size - read, read);
+ if (n === 0) break;
+ read += n;
+ }
+ content = buf.subarray(0, read).toString('utf-8');
} catch (e) {
+ if (e instanceof SchemaPackLoaderError) throw e;
throw new SchemaPackLoaderError('FILE_NOT_FOUND', `cannot read pack file: ${(e as Error).message}`, path);
+ } finally {
+ if (fd !== -1) try { closeSync(fd); } catch { /* already closed */ }
}
return loadPackFromString(content, path);
}
@@ -95,12 +143,20 @@ export function parseYamlMini(content: string): unknown {
let i = 0;
function stripComment(line: string): string {
- // Strip comments outside quoted strings. Simple state machine.
+ // Strip comments outside quoted strings. Inside double quotes a
+ // backslash escapes the next character (so `\"` and `\\` never toggle
+ // the state, #6432); inside single quotes `''` toggles twice and lands
+ // back inside, which is the YAML rule.
let result = '';
let inSingle = false;
let inDouble = false;
for (let j = 0; j < line.length; j++) {
const c = line[j];
+ if (inDouble && c === '\\' && j + 1 < line.length) {
+ result += c + line[j + 1];
+ j++;
+ continue;
+ }
if (c === "'" && !inDouble) inSingle = !inSingle;
else if (c === '"' && !inSingle) inDouble = !inDouble;
else if (c === '#' && !inSingle && !inDouble) break;
@@ -109,6 +165,25 @@ export function parseYamlMini(content: string): unknown {
return result;
}
+ /**
+ * Decode a quoted scalar (#6432). Double quotes carry the JSON escape
+ * subset (`\\ \" \/ \b \f \n \r \t \uXXXX`), which is exactly what the
+ * emitter writes; anything else (`\q`, a YAML-only `\x41` or `\e`) is
+ * outside the supported subset and refuses naming the line, never a raw
+ * slice that would keep the escapes as content. Single quotes hold
+ * literal text with `''` for one quote.
+ */
+ function decodeQuoted(trimmed: string): string {
+ if (trimmed.startsWith("'")) return trimmed.slice(1, -1).replace(/''/g, "'");
+ try {
+ const decoded = JSON.parse(trimmed);
+ if (typeof decoded === 'string') return decoded;
+ } catch { /* fall through to the declared refusal */ }
+ throw new Error(
+ `line ${i}: double-quoted scalar ${trimmed.length > 60 ? trimmed.slice(0, 60) + '…' : trimmed} is outside the supported escape subset (JSON escapes only: \\\\ \\" \\/ \\b \\f \\n \\r \\t \\uXXXX); use single quotes for literal text or ship JSON`,
+ );
+ }
+
function parseScalar(raw: string): unknown {
const trimmed = raw.trim();
if (trimmed === '' || trimmed === '~' || trimmed === 'null') return null;
@@ -126,9 +201,9 @@ export function parseYamlMini(content: string): unknown {
}
}
// Quoted string
- if ((trimmed.startsWith('"') && trimmed.endsWith('"')) ||
- (trimmed.startsWith("'") && trimmed.endsWith("'"))) {
- return trimmed.slice(1, -1);
+ if (trimmed.length >= 2 && ((trimmed.startsWith('"') && trimmed.endsWith('"')) ||
+ (trimmed.startsWith("'") && trimmed.endsWith("'")))) {
+ return decodeQuoted(trimmed);
}
// Number
if (/^-?\d+$/.test(trimmed)) return parseInt(trimmed, 10);
diff --git a/src/core/schema-pack/mutate.ts b/src/core/schema-pack/mutate.ts
index a0cc05f902..322aebe281 100644
--- a/src/core/schema-pack/mutate.ts
+++ b/src/core/schema-pack/mutate.ts
@@ -60,7 +60,7 @@ import type {
SchemaPackManifest,
} from './manifest-v1.ts';
import { PACK_PRIMITIVES } from './manifest-v1.ts';
-import { loadPackFromFile, parseYamlMini } from './loader.ts';
+import { loadPackFromFile, parseYamlMini, SchemaPackLoaderError } from './loader.ts';
import { invalidatePackCache } from './registry.ts';
import { invalidateQueryCache } from './query-cache-invalidator.ts';
import { logMutationFailure, logMutationSuccess, type MutationActor, type MutationOp } from './mutate-audit.ts';
@@ -82,7 +82,9 @@ export class SchemaPackMutationError extends Error {
| 'INVALID_PRIMITIVE'
| 'INVALID_RESULT'
| 'IO_ERROR'
- | 'STILL_REFERENCED';
+ | 'STILL_REFERENCED'
+ | 'EMIT_MISMATCH'
+ | 'PACK_TOO_LARGE';
readonly details?: Record<string, unknown>;
constructor(
code: SchemaPackMutationError['code'],
@@ -194,7 +196,7 @@ export function locateMutablePackFile(name: string): { path: string; format: Pac
// Does NOT preserve comments or original formatting (documented in plan).
// ────────────────────────────────────────────────────────────────────────
-function emitYaml(value: unknown): string {
+export function emitYaml(value: unknown): string {
return emitYamlNode(value, 0).trimEnd() + '\n';
}
@@ -314,21 +316,55 @@ function writeAtomic(path: string, body: string): void {
}
}
-function writePackManifest(
+/** Key-order-insensitive canonical form for the emit guard. */
+function canonicalJson(value: unknown): string {
+ if (Array.isArray(value)) return `[${value.map(canonicalJson).join(',')}]`;
+ if (value && typeof value === 'object') {
+ const o = value as Record<string, unknown>;
+ return `{${Object.keys(o).sort().filter(k => o[k] !== undefined).map(k => `${JSON.stringify(k)}:${canonicalJson(o[k])}`).join(',')}}`;
+ }
+ return JSON.stringify(value);
+}
+
+/** The first top-level key whose canonical form differs, for the EMIT_MISMATCH message. */
+function firstDivergingKey(a: unknown, b: unknown): string | null {
+ const ao = (a ?? {}) as Record<string, unknown>;
+ const bo = (b ?? {}) as Record<string, unknown>;
+ for (const k of new Set([...Object.keys(ao), ...Object.keys(bo)])) {
+ if (canonicalJson(ao[k]) !== canonicalJson(bo[k])) return k;
+ }
+ return null;
+}
+
+/**
+ * Publication boundary for a mutated manifest. The emitted text is parsed
+ * back and compared to the manifest as normalized structures (key order is
+ * free; values are not) before the atomic write, so an emitter/parser
+ * asymmetry (#6432: a quoted scalar whose backslashes doubled) refuses with
+ * `EMIT_MISMATCH` and the file on disk keeps its bytes. `emit` is the test
+ * seam for an emitter that drops or reorders a key.
+ */
+export function writePackManifest(
path: string,
manifest: SchemaPackManifest,
format: PackFileFormat,
+ emit: (m: SchemaPackManifest) => string = emitYaml,
): void {
assertManagedFilesystemWrite(path);
// Validate the manifest shape BEFORE write so an invalid manifest can never
// hit disk (the in-memory manifest must round-trip cleanly first).
- parseSchemaPackManifest(manifest, { path });
+ const expected = parseSchemaPackManifest(manifest, { path });
if (format === 'yaml') {
- const yaml = emitYaml(manifest);
- // Belt-and-suspenders: re-parse what we're about to write to catch
- // any emitter bugs before the rename.
- const reparsed = parseYamlMini(yaml);
- parseSchemaPackManifest(reparsed, { path });
+ const yaml = emit(manifest);
+ const reparsed = parseSchemaPackManifest(parseYamlMini(yaml), { path });
+ if (canonicalJson(reparsed) !== canonicalJson(expected)) {
+ const key = firstDivergingKey(expected, reparsed) ?? '(unknown)';
+ throw new SchemaPackMutationError(
+ 'EMIT_MISMATCH',
+ `refusing to write ${path}: the emitted YAML does not read back as the manifest (first difference under \`${key}\`). The file on disk is unchanged. Run \`gbrain errors schema_pack_emit_mismatch\` for the recovery steps.`,
+ { path, key },
+ );
+ }
writeAtomic(path, yaml);
return;
}
@@ -380,11 +416,14 @@ export async function withMutation(
current = loadPackFromFile(path);
prevSha8 = await computeManifestSha8(current);
} catch (e) {
- const err = new SchemaPackMutationError(
- 'PACK_CORRUPT',
- `cannot read or parse pack file at ${path}: ${(e as Error).message}`,
- { path },
- );
+ // #6432: the size refusal keeps its typed code (an agent must not read it as corruption).
+ const err = e instanceof SchemaPackLoaderError && e.code === 'PACK_TOO_LARGE'
+ ? new SchemaPackMutationError('PACK_TOO_LARGE', e.message, { path })
+ : new SchemaPackMutationError(
+ 'PACK_CORRUPT',
+ `cannot read or parse pack file at ${path}: ${(e as Error).message}`,
+ { path },
+ );
await logMutationFailure({ op, pack: packName, actor, ...primitiveContext, reason: err.code });
throw err;
}
@@ -867,11 +906,13 @@ export async function applyMutationsAtomic(
current = loadPackFromFile(path);
batchPrevSha8 = await computeManifestSha8(current);
} catch (e) {
- const err = new SchemaPackMutationError(
- 'PACK_CORRUPT',
- `cannot read or parse pack file at ${path}: ${(e as Error).message}`,
- { path },
- );
+ const err = e instanceof SchemaPackLoaderError && e.code === 'PACK_TOO_LARGE'
+ ? new SchemaPackMutationError('PACK_TOO_LARGE', e.message, { path })
+ : new SchemaPackMutationError(
+ 'PACK_CORRUPT',
+ `cannot read or parse pack file at ${path}: ${(e as Error).message}`,
+ { path },
+ );
await logMutationFailure({ op: firstOp, pack: packName, actor, reason: err.code, batch_id: opts.batchId });
throw err;
}
diff --git a/test/doctor-schema-pack.test.ts b/test/doctor-schema-pack.test.ts
new file mode 100644
index 0000000000..2a9bb7f204
--- /dev/null
+++ b/test/doctor-schema-pack.test.ts
@@ -0,0 +1,76 @@
+/**
+ * doctor `schema_pack_active` size warning (#6432, wave 14 P1.2).
+ *
+ * Protects: an operator learns that a mutable pack file has grown past the
+ * size a hand-written manifest ever reaches (the backslash-doubling class
+ * grows a pack 2x per mutation) before every CLI process pays for loading
+ * it, with the runbook that names the manual fix. Regression: the check
+ * stays `ok` on a bloated pack. Existing coverage checks pack resolution,
+ * not its size. No production seam: the warn bound is the documented
+ * GBRAIN_SCHEMA_PACK_WARN_BYTES override.
+ */
+import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { checkSchemaPackActive } from '../src/commands/doctor/schema-pack-checks.ts';
+import { _resetPackCacheForTests } from '../src/core/schema-pack/registry.ts';
+import { withEnv } from './helpers/with-env.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+
+let tmpHome: string;
+
+beforeEach(() => {
+ _resetPackCacheForTests();
+ tmpHome = mkdtempSync(join(tmpdir(), 'gbrain-doctor-pack-size-'));
+});
+
+afterEach(() => {
+ _resetPackCacheForTests();
+ rmSync(tmpHome, { recursive: true, force: true });
+});
+
+const engine = { getConfig: async (key: string) => (key === 'schema_pack' ? 'mine' : null) } as unknown as BrainEngine;
+
+function seedPack(padding: number): void {
+ const dir = join(tmpHome, '.gbrain', 'schema-packs', 'mine');
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(join(dir, 'pack.yaml'), `api_version: gbrain-schema-pack-v1
+name: mine
+version: 1.0.0
+description: a pack
+extends: null
+page_types:
+ - name: person
+ primitive: entity
+ path_prefixes:
+ - people/
+ aliases: []
+ extractable: false
+ expert_routing: false
+${'# '.padEnd(padding, 'x')}
+`, 'utf-8');
+}
+
+describe('schema_pack_active size warning', () => {
+ test('a normal-sized mutable pack is ok', async () => {
+ seedPack(10);
+ await withEnv({ GBRAIN_HOME: tmpHome, GBRAIN_SCHEMA_PACK: undefined, GBRAIN_SCHEMA_PACK_WARN_BYTES: '4096' }, async () => {
+ const check = await checkSchemaPackActive(engine);
+ expect(check.status).toBe('ok');
+ expect(check.message).toContain('mine');
+ });
+ });
+
+ test('an oversized mutable pack warns with the runbook pointer and the size', async () => {
+ seedPack(6000);
+ await withEnv({ GBRAIN_HOME: tmpHome, GBRAIN_SCHEMA_PACK: undefined, GBRAIN_SCHEMA_PACK_WARN_BYTES: '4096' }, async () => {
+ const check = await checkSchemaPackActive(engine);
+ expect(check.status).toBe('warn');
+ expect(check.message).toContain('mine');
+ expect(check.message).toContain('KiB');
+ expect(check.message).toContain('schema-packs.md#oversized-pack');
+ expect(check.details).toMatchObject({ code: 'schema_pack_oversized' });
+ });
+ });
+});
diff --git a/test/schema-pack-loader.test.ts b/test/schema-pack-loader.test.ts
index 34b164dc39..97b7395631 100644
--- a/test/schema-pack-loader.test.ts
+++ b/test/schema-pack-loader.test.ts
@@ -9,8 +9,13 @@
// (T6/T7) when hardcoded sites get refactored. This file pins the
// module's internal contracts.
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, spyOn, test } from 'bun:test';
+import * as fs from 'node:fs';
+import { closeSync, ftruncateSync, mkdtempSync, openSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
import { withEnv } from './helpers/with-env.ts';
+import { loadPackFromFile, SchemaPackLoaderError } from '../src/core/schema-pack/loader.ts';
import {
buildAliasGraph,
expandClosure,
@@ -377,6 +382,61 @@ name: hashy`;
const result = parseYamlMini('# top comment\nname: value # inline comment') as Record<string, unknown>;
expect(result.name).toBe('value');
});
+
+ // #6432 (wave 14 P1.2): quoted scalars decode their escapes, so what the
+ // emitter writes reads back as the same string.
+ test.each([
+ ['double-quoted JSON escapes decode', 'r: "\\\\b"', '\\b'],
+ ['escaped quote then backslash', 'r: "a\\\\\\"b"', 'a\\"b'],
+ ['escaped quote inside', 'r: "x\\"#y"', 'x"#y'],
+ ['single-quoted doubles the quote', "r: 'it''s'", "it's"],
+ ['hash inside single quotes is content', "r: 'a # b'", 'a # b'],
+ ['hash inside double quotes is content', 'r: "a # b"', 'a # b'],
+ ['comment after a closing double quote is stripped', 'r: "a" # c', 'a'],
+ ['comment after a closing single quote is stripped', "r: 'a' # c", 'a'],
+ ['tab and newline escapes', 'r: "t\\tn\\n"', 't\tn\n'],
+ ['unicode escape', 'r: "\\u00e9"', 'é'],
+ ])('%s', (_name, yaml, expected) => {
+ expect((parseYamlMini(yaml) as Record<string, unknown>).r).toBe(expected);
+ });
+
+ test('a double-quoted scalar outside the JSON escape subset refuses naming the line, never a raw slice', () => {
+ let err: Error | null = null;
+ try { parseYamlMini('name: ok\nr: "\\q"'); } catch (e) { err = e as Error; }
+ expect(err).not.toBeNull();
+ expect(err!.message).toContain('line 2');
+ expect(err!.message).toContain('double-quoted');
+ try { loadPackFromString('api_version: gbrain-schema-pack-v1\nname: x\nversion: 0.1.0\ndescription: "\\q"\n', 'p.yaml'); }
+ catch (e) { expect((e as SchemaPackLoaderError).code).toBe('PARSE_ERROR'); return; }
+ throw new Error('expected a PARSE_ERROR');
+ });
+});
+
+describe('loadPackFromFile size guard (#6432)', () => {
+ test('refuses PACK_TOO_LARGE from the file size before reading the bytes', () => {
+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-pack-size-'));
+ try {
+ const path = join(dir, 'pack.yaml');
+ const fd = openSync(path, 'w');
+ // 20 MiB sparse: the size is what the guard must read, never the bytes.
+ ftruncateSync(fd, 20 * 1024 * 1024);
+ closeSync(fd);
+ const reads = spyOn(fs, 'readFileSync');
+ try {
+ loadPackFromFile(path, { maxBytes: 10 * 1024 * 1024 });
+ throw new Error('expected PACK_TOO_LARGE');
+ } catch (e) {
+ expect((e as SchemaPackLoaderError).code).toBe('PACK_TOO_LARGE');
+ expect((e as Error).message).toContain('20.0 MiB');
+ expect((e as Error).message).toContain('schema-packs.md');
+ expect(reads.mock.calls.filter(c => c[0] === path)).toHaveLength(0);
+ } finally {
+ reads.mockRestore();
+ }
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
});
describe('loadPackFromString end-to-end', () => {
diff --git a/test/schema-pack-mutate.test.ts b/test/schema-pack-mutate.test.ts
index d43435ed63..3f7790356c 100644
--- a/test/schema-pack-mutate.test.ts
+++ b/test/schema-pack-mutate.test.ts
@@ -10,6 +10,8 @@ import {
addPrefixToType,
addTypeToPack,
BUNDLED_PACK_NAMES,
+ emitYaml,
+ writePackManifest,
locateMutablePackFile,
removeAliasFromType,
removeLinkTypeFromPack,
@@ -489,6 +491,50 @@ filing_rules: []
});
});
+// ─── #6432 (wave 14 P1.2): the publication boundary refuses what it cannot read back ───
+
+describe('writePackManifest emit guard (#6432)', () => {
+ const manifest = (): SchemaPackManifest => ({
+ api_version: 'gbrain-schema-pack-v1', name: 'mine', version: '1.0.0', description: 'd',
+ gbrain_min_version: '0.38.0', extends: null, borrow_from: [],
+ page_types: [{ name: 'person', primitive: 'entity', path_prefixes: ['people/'], aliases: ['human'], extractable: false, expert_routing: false }],
+ link_types: [{ name: 'works_at', inverse: 'employs', inference: { regex: '\\b(works? at)\\b' } }],
+ frontmatter_links: [], takes_kinds: ['fact', 'take', 'bet', 'hunch'], enrichable_types: [], filing_rules: [],
+ } as SchemaPackManifest);
+
+ it('an emitter that drops a key refuses EMIT_MISMATCH and leaves the file bytes unchanged', () => {
+ const path = join(tmpDir, 'pack.yaml');
+ writeFileSync(path, 'original bytes\n', 'utf-8');
+ const dropping = (m: SchemaPackManifest) => emitYaml({ ...m, page_types: m.page_types.map(t => ({ ...t, aliases: [] })) });
+ try {
+ writePackManifest(path, manifest(), 'yaml', dropping);
+ throw new Error('expected EMIT_MISMATCH');
+ } catch (e) {
+ expect((e as SchemaPackMutationError).code).toBe('EMIT_MISMATCH');
+ expect((e as Error).message).toContain('page_types');
+ }
+ expect(readFileSync(path, 'utf-8')).toBe('original bytes\n');
+ });
+
+ it('a key-order-only difference is not a mismatch', () => {
+ const path = join(tmpDir, 'pack.yaml');
+ const reordered = (m: SchemaPackManifest) => {
+ const { name, api_version, ...rest } = m as Record<string, unknown>;
+ return emitYaml({ ...rest, name, api_version });
+ };
+ writePackManifest(path, manifest(), 'yaml', reordered);
+ expect(loadPackFromFile(path).link_types![0]!.inference!.regex).toBe('\\b(works? at)\\b');
+ });
+
+ it('PACK_TOO_LARGE keeps its typed code through withMutation', async () => {
+ await withEnv({ GBRAIN_HOME: tmpDir, GBRAIN_AUDIT_DIR: auditDir, GBRAIN_SCHEMA_PACK_MAX_BYTES: '1024' }, async () => {
+ const path = seedPack('mine', 'yaml');
+ writeFileSync(path, readFileSync(path, 'utf-8') + '# ' + 'x'.repeat(2048) + '\n', 'utf-8');
+ await expect(addAliasToType('mine', 'person', 'human', { lockDir })).rejects.toMatchObject({ code: 'PACK_TOO_LARGE' });
+ });
+ });
+});
+
// ─── atomicity ────────────────────────────────────────────────────────
describe('atomicity invariants', () => {
diff --git a/test/schema-pack-roundtrip.test.ts b/test/schema-pack-roundtrip.test.ts
new file mode 100644
index 0000000000..9d568b463d
--- /dev/null
+++ b/test/schema-pack-roundtrip.test.ts
@@ -0,0 +1,111 @@
+/**
+ * Schema-pack YAML round trip (#6432, wave 14 P1.2).
+ *
+ * Protects: a pack mutation leaves every scalar it did not touch
+ * byte-identical. Before the fix the emitter JSON-quoted any string with a
+ * `|` and the parser read a double-quoted scalar back with its escapes
+ * intact, so a link-type regex holding `\b` doubled its backslashes on
+ * every `add-alias` (2 → 4 → 8; a reporter's pack.yaml reached 1 GB and
+ * every CLI process 50 GB RSS). Existing coverage drives single primitives
+ * and never re-reads the regex. No production seam: the real
+ * `addAliasToType` path, the real file.
+ */
+import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { addAliasToType, emitYaml } from '../src/core/schema-pack/mutate.ts';
+import { loadPackFromFile, parseYamlMini } from '../src/core/schema-pack/loader.ts';
+import { _resetPackCacheForTests } from '../src/core/schema-pack/registry.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const REGEX = '\\b(works? at|employed by)\\b';
+const PACK_YAML = `api_version: gbrain-schema-pack-v1
+name: mine
+version: 1.0.0
+description: 'it''s a "quoted" # pack'
+gbrain_min_version: 0.38.0
+extends: null
+page_types:
+ - name: person
+ primitive: entity
+ path_prefixes:
+ - people/
+ aliases: []
+ extractable: false
+ expert_routing: false
+link_types:
+ - name: works_at
+ inverse: employs
+ inference:
+ regex: ${REGEX}
+`;
+
+let tmpDir: string;
+let auditDir: string;
+let lockDir: string;
+
+beforeEach(() => {
+ _resetPackCacheForTests();
+ tmpDir = mkdtempSync(join(tmpdir(), 'gbrain-roundtrip-'));
+ auditDir = mkdtempSync(join(tmpdir(), 'gbrain-roundtrip-audit-'));
+ lockDir = mkdtempSync(join(tmpdir(), 'gbrain-roundtrip-locks-'));
+});
+
+afterEach(() => {
+ _resetPackCacheForTests();
+ for (const d of [tmpDir, auditDir, lockDir]) rmSync(d, { recursive: true, force: true });
+});
+
+function seed(): string {
+ const dir = join(tmpDir, '.gbrain', 'schema-packs', 'mine');
+ mkdirSync(dir, { recursive: true });
+ const path = join(dir, 'pack.yaml');
+ writeFileSync(path, PACK_YAML, 'utf-8');
+ return path;
+}
+
+describe('mutations keep untouched scalars byte-identical', () => {
+ test('three add-alias runs leave the regex and the quoted description unchanged', async () => {
+ await withEnv({ GBRAIN_HOME: tmpDir, GBRAIN_AUDIT_DIR: auditDir }, async () => {
+ const path = seed();
+ expect(loadPackFromFile(path).link_types![0]!.inference!.regex).toBe(REGEX);
+ let previous: string | null = null;
+ for (const alias of ['zz-probe-1', 'zz-probe-2', 'zz-probe-3']) {
+ await addAliasToType('mine', 'person', alias, { lockDir });
+ const manifest = loadPackFromFile(path);
+ expect(manifest.link_types![0]!.inference!.regex).toBe(REGEX);
+ expect(manifest.description).toBe('it\'s a "quoted" # pack');
+ expect(manifest.page_types[0]!.aliases).toContain(alias);
+ const regexLine = readFileSync(path, 'utf-8').split('\n').find(l => l.includes('regex:'))!;
+ expect(regexLine.length).toBeLessThan(80);
+ if (previous) expect(regexLine).toBe(previous);
+ previous = regexLine;
+ }
+ });
+ });
+});
+
+describe('emit → parse → emit is the identity for every string shape', () => {
+ test.each([
+ ['\\b(works? at|employed by)\\b'],
+ ['a\\"b'],
+ ['a\\\\"b'],
+ ["it's # not a comment"],
+ ['x"#y'],
+ ['tab\there'],
+ ['new\nline'],
+ ['trailing backslash \\'],
+ [' leading and trailing '],
+ ['true'],
+ ['42'],
+ ['[not, a, list]'],
+ [''],
+ ])('%j survives a round trip', (s) => {
+ const manifest = { description: s, items: [s], nested: { deep: s } };
+ const once = emitYaml(manifest);
+ const parsed = parseYamlMini(once) as typeof manifest;
+ expect(parsed).toEqual(manifest);
+ expect(emitYaml(parsed)).toBe(once);
+ });
+});