Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
#6712 PR 4b: an alias bomb an older gbrain validated is held alone, not a parser regression
garrytanc69aadb7d72c
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex b315a58cdc..18ca058d42 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -1442,6 +1442,14 @@ More: [docs/guides/shared-brain-skills.md#approve-publication-following-and-edit|---|---|---|---|---|---|---|| A caller asked to forget a fact (remote forget) or remove a take (takes_remove) more trusted than its own writes, so nothing was removed and the owner was asked instead. | Lower-trust writers cannot overwrite, supersede or forget what the owner confirmed or curated (#5575 guarded supersession). The request became a trust proposal the owner can accept on the brain host; forget's frozen expired meaning is unchanged because nothing expired. | Do not retry. Tell the user the fact or take needs their decision and give them the command in fix (gbrain trust confirm <proposal_ref> on the brain host). | user | `repeat the read that failed` | 3 | no |+### frontmatter_alias_limit++<a id="frontmatter_alias_limit"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| A file an older gbrain imported nests YAML aliases in its frontmatter that expand past the size limit, so sync holds it alone. | #7018 bounds YAML alias expansion on purpose (a few hundred bytes of nested anchors expand into gigabytes), so refusing bytes an older gbrain imported is intended, not a parser regression: the page keeps its last imported version and the rest of the source syncs. | Reduce the alias nesting in the frontmatter (or write the values out), or remove the file, then commit and sync again. | agent | `repeat the read that failed` | 1 | no |+### frontmatter_slug_conflict<a id="frontmatter_slug_conflict"></a>diff --git a/docs/guides/sync-unblock-runbook.md b/docs/guides/sync-unblock-runbook.mdindex ada104d376..13c0ac7795 100644--- a/docs/guides/sync-unblock-runbook.md+++ b/docs/guides/sync-unblock-runbook.md@@ -127,6 +127,7 @@ Every hold and error has three fields, from one table| `file_too_large` | page | none | yes | always || `content_rejected` | page | none | yes | always || `parser_regression` | page | upgrade | yes | always: a gbrain bug |+| `frontmatter_alias_limit` | page | none | yes | always: only an edit to the file or its removal clears it || `managed_image_sync_unsupported` | page | none | no | never: images stay held while multimodal embedding is off || `purged_content` | page | none | yes | always: only the owner clears a purge tombstone || `write_gate_rejected` | page | none | yes | always: write_gate.external_mode=reject is the user's setting |diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.mdindex b1581307bd..81f0047976 100644--- a/docs/guides/write-refusals.md+++ b/docs/guides/write-refusals.md@@ -211,6 +211,7 @@ with each file and fix the ones that need no guessing."*| <a id="rename_held"></a><a id="rename_held-rename_source_changed"></a>`rename_held` (`rename_source_changed`) | A renamed file's hold cleared, but the page it was renamed from changed after the rename was recorded, so the page did not move. | `gbrain repair frontmatter --source <source> --include-ambiguous` proposes re-binding the rename to the old page's current revision; apply after the user agrees. Or restore the old file name. || <a id="concurrent_write"></a>`concurrent_write` | Managed sync was importing a newer Git version of the file while a database-only write (write-through off, a sandboxed or derived write) committed a different version of the same page, so the two diverge (#6194). The proof is the page's revision itself: it was written by a committed non-sync request for that page. Neither version was overwritten: the page keeps the database version, the file is held and the rest of the source syncs. Since #6340 a page that moved with no such request to name is held the same way (the hold records `page_revision` and `expected_revision` instead of a competing request), and so is a page that changed, was deleted or was re-bound in the database between the manifest freeze and the entry's turn; a page that still holds exactly what the file would import is re-bound to its new revision and passed. | `gbrain sources status <source>` names the page and the competing request. Preview with `gbrain sources reconcile <source> <slug> --preview`, decide with the user which content wins, apply the resolved preview, then `gbrain sources retry-held <source>` and `gbrain sync --source <source> --no-pull` re-screen the file. A new commit of the file re-screens it too. || <a id="file_drift"></a>`file_drift` | Managed sync would have imported a file over a database version of its page that sync never saw (#6712). Every import records its provenance (the bytes left on disk, the page revision it wrote, the parser); a page that moved since that record (a database-only write, write-through off) while its file did not change, or, in a tree walk (first sync, `--full`, an unreachable checkpoint), a page whose file and revision both moved or that has no usable record (an upgraded brain: none, a pre-PR 0 record, a partial one), is imported only when the import changes nothing, a sync request wrote its current revision, or its writer's write-through wrote that revision to the file. Otherwise the file is held, the page keeps the database version and the rest of the source syncs. The hold names `sides` (`database`, `both`, `unknown`) and the database request that wrote the page when there was one; a hold the live pass writes also names its Decision, `side` (`both`, `unknown`, `deleted`) and, for a deleted side, `state` (`tombstone_edited`, `purged_differs`, `file_gone`). Pages under `storage.keep_db` prefixes whose file is clean in committed mode are not held: the pass writes the database copy back to the file (at most 200 per pass, the rest the next pass); an uncommitted edit there is held. Holds of this code never escalate; with `sync.holds=fail` the run stops with `file_drift` instead of holding. | `gbrain sources status <source>` names the page. Preview `gbrain repair file-drift --source <source> --slug <slug> --prefer database` (keep the database copy, rewrite the file) or `--prefer file` (import the file), decide with the user, apply it with the plan hash, then `gbrain sync --source <source> --no-pull`. Held pages of one Decision resolve together with [`--held --side <side> [--state <state>]`](repair.md#file-drift-held). A changed file or page revision re-screens the hold by itself. |+| <a id="frontmatter_alias_limit"></a>`frontmatter_alias_limit` | A file whose exact bytes an older gbrain imported and validated nests YAML aliases in its frontmatter that expand past the size limit (#7018). This release refuses them on purpose, so only that file is held (its page keeps the last imported version) and the rest of the source syncs; it is never a parser regression. | Reduce the alias nesting in the frontmatter (or write the values out), or remove the file, then commit and `gbrain sync --source <source> --no-pull`. The hold re-screens when the file changes. Before 4b such a file stopped the source as `sync_parser_regression`; the workaround there was `GBRAIN_SYNC_PARSER_REGRESSION=hold` for the process that syncs. || <a id="parser_regression"></a>`parser_regression` | With `GBRAIN_SYNC_PARSER_REGRESSION=hold`, a file whose exact bytes imported under an earlier gbrain is now refused. This is a gbrain bug. | Report it with the gbrain version, the file and the code; upgrade or pin the last good version. After a fixed gbrain is installed, `gbrain sources retry-held <source>` and then `gbrain sync --source <source> --no-pull` re-screen it. || <a id="settle_mismatch"></a>`settle_mismatch` | A live managed sync pass settled this file at the same level in three consecutive passes, but the next round never classified it settled (#6712). Instead of re-importing it every pass, sync held it at that level and stamped the rest of the source. The hold records the level and `meta.mismatch_streak`. The file is usually fine: a path that keeps coming back unsettled points to a broken writer, a stuck effect or a damaged record. | Run `gbrain doctor --json` and `gbrain sources writer status --source <source> --json` (both read-only), fix or report what they name with the gbrain version, then `gbrain sources retry-held <source>` and `gbrain sync --source <source> --no-pull`. A mismatch that comes back is held again after three passes. || <a id="write_interrupted-hold"></a>`write_interrupted` | The database ended this file's statements (a statement timeout or cancel) at every attempt, so the sync held the file and kept going. The file is fine: no repair applies, and it is not imported until it is retried. Full reference: [`write_interrupted`](#write_interrupted). | `gbrain sources writer status --source <source> --json` (read-only) names the load on the write owner; reduce it, then `gbrain sources retry-held <source>` and the same sync with its options. |diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex c5e8a6b732..88905767a3 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -450,6 +450,7 @@ export const CODES = {page_shrink_refused: { class: 'caller', summary: "put_page refused to replace a large page with content much smaller than the stored body; nothing was written.", why: "Above the inline read size (mcp.inline_body_bytes, 256 KB) a get_page read returns a window, not the body, so a replacement far smaller than the page is most often a window sent back as the whole page, which would delete the unread rest.", docs: 'docs/guides/windowed-reads.md#page_shrink_refused', suggestion: "Change part of the page with edit_page (revision from get_page body: 'none'). Pass allow_shrink: true only when the smaller content is the intended complete page.", fix: { argv: ['gbrain', 'get', '--source', '{source_id}', '--', '{slug}'], mcp: { tool: 'get_page', arguments: { slug: '{slug}', source_id: '{source_id}', body: 'none' } }, consent: [], actor: 'agent', why: "Returns the page's revision and size without its body; edit_page with that revision changes only the text it names.", requires_exclusive: false } },page_too_large_for_inline: { class: 'caller', summary: "The whole page does not fit one result on this connection, so get_page did not return its body.", why: "A result is measured as the complete encoded frame; a body over the connection's cap (mcp.max_result_bytes_stdio, 4 MiB; mcp.max_result_bytes_http, 1 MiB) would be cut or rejected by the client. Nothing was truncated: windowed reads cover the whole page in pieces.", docs: 'docs/guides/windowed-reads.md#page_too_large_for_inline', legacy_error: 'invalid_params', suggestion: "Read the outline (body: 'outline'), then windows (body: 'window' with lines, bytes, around_chunk_id or the returned next_cursor). To replace the page, edit it with edit_page and the revision from body: 'none'.", fix: { argv: ['gbrain', 'get', '--source', '{source_id}', '--', '{slug}'], mcp: { tool: 'get_page', arguments: { slug: '{slug}', source_id: '{source_id}', body: 'outline' } }, consent: [], actor: 'agent', why: "Returns the page's size, revision and outline; each entry names the lines to read with body: 'window'.", requires_exclusive: false, verify: { mcp: { tool: 'get_page', arguments: { slug: '{slug}', source_id: '{source_id}', body: 'none' } } } } },parse_error: { class: 'caller', summary: "The request body is not valid JSON." },+ frontmatter_alias_limit: { class: 'caller', summary: "A file an older gbrain imported nests YAML aliases in its frontmatter that expand past the size limit, so sync holds it alone.", why: "#7018 bounds YAML alias expansion on purpose (a few hundred bytes of nested anchors expand into gigabytes), so refusing bytes an older gbrain imported is intended, not a parser regression: the page keeps its last imported version and the rest of the source syncs.", suggestion: 'Reduce the alias nesting in the frontmatter (or write the values out), or remove the file, then commit and sync again.' },parser_regression: { class: 'server', summary: "A file whose exact bytes imported before is now refused by gbrain's frontmatter reader.", why: "The same bytes imported under an earlier gbrain version, so only gbrain changed; with `GBRAIN_SYNC_PARSER_REGRESSION=hold` for the process that syncs, such a file is held and the rest of the sync continues.", suggestion: 'Report it as a gbrain bug with the gbrain version, the file and the code; upgrade or pin the last good version, then sync again.' },pasted_wrong_url: { class: 'caller', summary: "Google connect credential error: pasted wrong url.", docs: 'docs/guides/google-connect.md#troubleshooting' },payload_too_large: { class: 'caller', summary: "The payload exceeds the configured size cap." },diff --git a/src/core/markdown.ts b/src/core/markdown.tsindex 9c3b78eb80..e5588d99b0 100644--- a/src/core/markdown.ts+++ b/src/core/markdown.ts@@ -1,4 +1,4 @@-import { dataFrontmatter as matter, FrontmatterLanguageError, loadBoundedYaml as yamlLoad } from './data-frontmatter.ts';+import { dataFrontmatter as matter, FrontmatterLanguageError, loadBoundedYaml as yamlLoad, YamlAliasBoundError } from './data-frontmatter.ts';import type { Page, PageType } from './types.ts';import { resolveSlugForPath, slugifyPath } from './sync.ts';import {@@ -30,6 +30,7 @@ export interface ParseValidationError {recoverable?: boolean;/** YAML_PARSE only: what ingestion changed to read it; content-free, so it can be recorded as provenance. */recovery?: Array<{ kind: RecoveryKind; key: string; line: number; recovery_version: number }>;+ /** YAML_PARSE only: a bound this release refuses on purpose, not a reading it cannot make. */ intended?: IntendedRefusal;}export type ParseWarningCode = 'FRONTMATTER_RECOVERED' | 'FRONTMATTER_COMMENT_VALUE';@@ -509,10 +510,13 @@ export const HOLD_CODES = ['invalid_frontmatter', 'frontmatter_slug_conflict', 'export type HoldCode = typeof HOLD_CODES[number];export const INVALID_FRONTMATTER_REASONS = ['yaml_parse', 'needs_interpretation', 'ambiguous_identity_key', 'ambiguous_protected_key'] as const;export type InvalidFrontmatterReason = typeof INVALID_FRONTMATTER_REASONS[number];+/** Refusals a release makes on purpose (`yaml_alias_limit`: #7018's alias bound): validated older bytes they refuse are held alone, never a parser regression (sync-screen.ts). */+export type IntendedRefusal = 'yaml_alias_limit';export interface ContentHold {code: HoldCode;reason?: InvalidFrontmatterReason;+ /** A refusal this release makes on purpose; structured, never read from the message. */ intended?: IntendedRefusal;key?: string;line?: number;/** Safe to persist and show remotely: names the key, line and cause, never a frontmatter value. */@@ -578,7 +582,7 @@ export function classifyImportHold(parsed: ParsedMarkdown, ctx: {: reason === 'ambiguous_identity_key' ? `ambiguous identity key "${key}"${where}`: reason === 'needs_interpretation' ? `key "${key}"${where} ${step!.kind === 'dup' ? 'appears more than once' : step!.kind === 'fold' ? 'continues on unquoted lines' : 'opens [ or { without closing it'}`: `${(yaml?.message ?? '').replace(/^YAML parse failed:\s*/, '') || 'malformed YAML'}${key ? ` (key "${key}")` : ''}`;- return { code: 'invalid_frontmatter', reason, ...(key ? { key } : {}), ...(line !== undefined ? { line } : {}),+ return { code: 'invalid_frontmatter', reason, ...(key ? { key } : {}), ...(line !== undefined ? { line } : {}), ...(yaml?.intended ? { intended: yaml.intended } : {}),message: `Invalid YAML frontmatter: ${detail}. ${HOLD_GUIDANCE[reason]}` };}const expected = ctx.expectedSlug;@@ -755,6 +759,7 @@ function collectValidationErrors(line: ctx.recovery?.line ?? (recoverable ? ctx.recovered[0]!.line : located?.line) ?? firstNonEmpty + 1,recoverable,...(recoverable ? { recovery: ctx.recovered.map(step => ({ kind: step.kind, key: step.key, line: step.line, recovery_version: RECOVERY_VERSION })) } : {}),+ ...(located?.intended ? { intended: located.intended } : {}),});}@@ -815,15 +820,15 @@ export function yamlBlockError(block: string): Error | null {}}-/** 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 {+/** Where js-yaml refuses a raw block: its reason phrase and the file line and column, and whether the refusal is the alias bound. */+function yamlFailureLocation(block: string, lineOffset: number): { reason: string; line: number; column: number; intended?: IntendedRefusal } | null {try {yamlLoad(block);return null;} catch (e) {const err = e as { reason?: string; mark?: { line?: number; column?: number } };if (typeof err.mark?.line !== 'number') return null;- return { reason: err.reason ?? 'malformed YAML', line: lineOffset + err.mark.line + 1, column: (err.mark.column ?? 0) + 1 };+ return { reason: err.reason ?? 'malformed YAML', line: lineOffset + err.mark.line + 1, column: (err.mark.column ?? 0) + 1, ...(e instanceof YamlAliasBoundError ? { intended: 'yaml_alias_limit' as const } : {}) };}}diff --git a/src/core/persistence/public-category.ts b/src/core/persistence/public-category.tsindex 698bbf7bbc..85cb80160c 100644--- a/src/core/persistence/public-category.ts+++ b/src/core/persistence/public-category.ts@@ -38,7 +38,7 @@ export const PUBLIC_BY_CODE: Readonly<Record<string, PublicCategory>> = {settle_mismatch: 'defect', page_write_failed: 'defect',invalid_fence: 'content_refused', invalid_frontmatter: 'content_refused', frontmatter_slug_conflict: 'content_refused', rename_held: 'content_refused',file_too_large: 'content_refused', content_rejected: 'content_refused', managed_image_sync_unsupported: 'content_refused',- purged_content: 'content_refused', write_gate_rejected: 'content_refused', file_unreadable: 'content_refused',+ purged_content: 'content_refused', write_gate_rejected: 'content_refused', file_unreadable: 'content_refused', frontmatter_alias_limit: 'content_refused',file_database_drift: 'drift', raw_file_changed: 'drift', pending_import: 'transient',source_binding_changed: 'config', unsafe_file_target: 'config',canonical_file_missing: 'file_missing',diff --git a/src/core/persistence/sync-fault-class.ts b/src/core/persistence/sync-fault-class.tsindex 1192d348fe..a15e20c9c5 100644--- a/src/core/persistence/sync-fault-class.ts+++ b/src/core/persistence/sync-fault-class.ts@@ -71,6 +71,9 @@ export const SYNC_FAULT_TABLE: ReadonlyArray<SyncFaultRule> = [{ code: 'file_too_large', class: 'page', safe_actions: ['none'], needs_human: true, escalate: 'always', human_reason: 'The file is over the page size limit; exclude it with sync.exclude, or split it into files under the limit.' },{ code: 'content_rejected', class: 'page', safe_actions: ['none'], needs_human: true, escalate: 'always', human_reason: 'The content-sanity gate rejected the file; remove the junk or change junk_disposition.' },{ code: 'parser_regression', class: 'page', safe_actions: ['upgrade'], needs_human: true, escalate: 'always: a gbrain bug', human_reason: 'Report the file and gbrain version, then upgrade or pin the last good release.' },+ // #6712 PR 4b (S-47): bytes an older gbrain imported whose frontmatter aliases expand past #7018's intended bound; only an edit clears it.+ { code: 'frontmatter_alias_limit', class: 'page', safe_actions: ['none'], needs_human: true, escalate: 'always: only an edit to the file or its removal clears it',+ human_reason: 'The file\'s frontmatter nests YAML aliases past the size limit; reduce the alias nesting (or write the values out), or remove the file, and commit.' },{ code: 'managed_image_sync_unsupported', class: 'page', safe_actions: ['none'], needs_human: false, escalate: 'never: images stay held while multimodal embedding is off', human_reason: 'Leave images held, exclude them with sync.exclude, or set GBRAIN_EMBEDDING_MULTIMODAL=true so the next sync imports them.' },// #6712 PR 2 (L4): two content refusals that hold the file; only the owner or the user changes the outcome.{ code: 'purged_content', class: 'page', safe_actions: ['none'], needs_human: true, escalate: 'always: only the owner clears a purge tombstone',diff --git a/src/core/persistence/sync-holds.ts b/src/core/persistence/sync-holds.tsindex 923b8a0cbb..6eb5a646a4 100644--- a/src/core/persistence/sync-holds.ts+++ b/src/core/persistence/sync-holds.ts@@ -78,7 +78,9 @@ export type GitHoldCode = ContentRefusal['code'] | 'rename_held' | 'parser_regre/** GBRA-130 A-7: a file sync cannot read as a regular file inside its root (a symlink, a non-regular file, a permission error). */| 'file_unreadable'/** GBRA-130 A-17/B-3/B-4: a path whose page identity sync cannot decide (several tombstones, a spelling twin, a takeover whose ids differ). */- | 'page_identity_changed';+ | 'page_identity_changed'+ /** #6712 PR 4b (S-47): bytes an older gbrain imported and validated whose frontmatter aliases expand past #7018's bound; held alone, never a parser regression. */+ | 'frontmatter_alias_limit';/** GBRA-130 A-6: the fault a `page_write_failed` hold stands for (identifiers and classes only, never content). */export interface PageWriteFailureMeta { code: string; origin: string | null; error_class: string | null; errno: string | null; request_id: string; attempts: number; gbrain_version: string }/**@@ -547,7 +549,9 @@ export async function holdBasisMoved(engine: Pick<BrainEngine, 'executeRaw'>, so* `purged_content` hold rests on a setting, an allow rule or a tombstone its fix lets the user change, so it* re-screens on every sync too. #6727: so does a `legacy_slug_conflict` hold, which rests on the legacy pages a person removes. #6948: and an* `origin_conflict` hold, which rests on the twin pages the heal, the repair or a person removes. GBRA-130: and a `page_identity_changed`- * hold, which rests on pages (tombstones, a page at the slug) or spellings a person changes.+ * hold, which rests on pages (tombstones, a page at the slug) or spellings a person changes. A `frontmatter_alias_limit` hold+ * rests on the file's bytes alone (the bound is intended, not transient), so like `invalid_frontmatter` it re-screens when+ * the file changes.*/export function holdRescreenDue(record: Pick<GitHoldRecord, 'code' | 'meta'>, retried: boolean): boolean {return retried || ['frontmatter_slug_conflict', 'file_too_large', 'rename_held', 'parser_regression', 'content_rejected', 'write_gate_rejected', 'purged_content', 'legacy_slug_conflict', 'origin_conflict', 'page_identity_changed'].includes(record.code)@@ -796,6 +800,11 @@ export function gitHoldFix(record: Pick<GitHoldRecord, 'source_id' | 'path' | 'cuser_message: `Multimodal embedding is off, so managed sync holds ${record.path} and the rest of source ${source} keeps syncing. Keeping images held is fine; to import them, set GBRAIN_EMBEDDING_MULTIMODAL=true for the gbrain process (image embeddings can cost money) and sync again; to stop holding them, leave images out of the source with sync.exclude.`,why: 'Whether images are embedded is the user\'s call (it costs provider calls). With GBRAIN_EMBEDDING_MULTIMODAL=true the next sync imports every held image; the hold also clears when the file is deleted or excluded, and is re-screened when it changes or on gbrain sources retry-held.',verify: { argv: ['gbrain', 'sources', 'status', source, '--json'] } };+ case 'frontmatter_alias_limit':+ return { argv: ['gbrain', 'sources', 'status', source, '--json'], consent: [], actor: 'user', requires_exclusive: false, docs: gitHoldDocs(record.code),+ user_message: `${record.path} nests YAML aliases in its frontmatter that expand past gbrain's size limit, so sync holds it and the rest of source ${source} keeps syncing. An older gbrain imported these bytes; this version refuses them on purpose. Reduce the alias nesting in its frontmatter (or write the values out), or remove the file, then commit and run gbrain sync --source ${source} --no-pull.`,+ why: 'The alias bound (#7018) stops a few hundred bytes of nested anchors from expanding into gigabytes; it is intended, so the page keeps its last imported version until the file changes.',+ verify: { argv: ['gbrain', 'sources', 'status', source, '--json'] } };case 'parser_regression':return { argv: ['gbrain', 'doctor', '--json'], consent: [], actor: 'user', requires_exclusive: false,user_message: `gbrain refuses ${record.path}, whose exact bytes imported under an earlier version. This is a gbrain bug: report it with the gbrain version, the file and the code, then upgrade or pin the last good version.`,diff --git a/src/core/persistence/sync-screen.ts b/src/core/persistence/sync-screen.tsindex 6ed62387e7..348f8c6fb0 100644--- a/src/core/persistence/sync-screen.ts+++ b/src/core/persistence/sync-screen.ts@@ -4,7 +4,9 @@* the caller writes the hold and advances the cursor in one transaction. A* pinned Git blob over the sync read bound is held by its size before its* content is loaded. `sync_parser_regression` stops the run only when the- * page's import provenance proves the exact bytes imported validated before.+ * page's import provenance proves the exact bytes imported validated before+ * and the refusal is not one this release makes on purpose (an intended+ * refusal, such as #7018's alias bound, holds that page alone).* Dry runs screen every pending import read-only with batched Git reads.* #6188: the screen runs with `fences: 'coordinated'` (see `screenSyncImport`):* a fence Tier 1 rewrites losslessly is admitted (publication commits the@@ -18,7 +20,7 @@ import { OperationError, opError } from '../ops/contract.ts';import { loadImportSanityConfig, screenNormalized, type ContentRefusal, type ImportSanityConfig, type ImportScreenResult } from '../import-screen.ts';import { fencesNormalizeEnabled } from '../fence-repair/config.ts';import type { FenceFix } from '../fence-repair/types.ts';-import { parseMarkdown, RECOVERY_VERSION } from '../markdown.ts';+import { parseMarkdown, RECOVERY_VERSION, type IntendedRefusal } from '../markdown.ts';import { fenceMessage, type FenceMessageLocation } from '../fence-repair/reasons.ts';import { completeFenceLocation, FENCE_VERSION, type ReceiptFenceLocation } from '../fence-repair/refusal.ts';import { fenceFileLine } from '../fence-repair/hold-fix.ts';@@ -34,7 +36,7 @@ import { readSyncContent, readSyncFile, syncGitPath, UNREADABLE_SYNC_FILE, typeimport { pinnedWindowBlock, readBlobBytes, readBlobContents, readPinnedBlob, readPinnedBytes, readPinnedContent, readTreeBlobs, SYNC_READ_BOUND, type TreeBlob } from './sync-blobs.ts';import { screenSyncImport, type SyncImportScreenInput } from './sync-prepare.ts';import type { SyncProcessingOptions } from './sync-authority.ts';-import { gitHoldItem, readSyncHoldPolicy, readSyncImportProvenance, type GitHoldItem, type GitHoldRecord, type PreparationStallMeta, type SyncHoldPolicy } from './sync-holds.ts';+import { gitHoldItem, readSyncHoldPolicy, readSyncImportProvenance, type GitHoldCode, type GitHoldItem, type GitHoldRecord, type PreparationStallMeta, type SyncHoldPolicy } from './sync-holds.ts';import type { WriteRequest } from './model.ts';type Snapshot = Awaited<ReturnType<BrainEngine['readPageSnapshot']>>;@@ -120,6 +122,15 @@ export function heldImageEntry(cursor: SyncDiscovery & { index: number }, entry:return managedImageHold(entry, bytes === null ? null : bytes.toString('utf8'), blob);}+/**+ * The hold each intended refusal (markdown.ts `IntendedRefusal`) earns when the page's provenance says a validating older+ * gbrain imported the same bytes: that page alone is held, and the run goes on.+ */+const INTENDED_HOLDS: Record<IntendedRefusal, { code: GitHoldCode; cause: string; fix: string }> = {+ yaml_alias_limit: { code: 'frontmatter_alias_limit', cause: 'its frontmatter YAML aliases expand past the size limit',+ fix: 'Reduce the alias nesting in its frontmatter (or write the values out), or remove the file, then commit.' },+};+function heldEntry(entry: Pick<SyncEntry, 'path' | 'sourcePath' | 'working' | 'renameFrom' | 'renameHeld'>, slug: string, pageId: number | null,refusal: { code: GitHoldRecord['code']; reason?: GitHoldRecord['meta']['reason']; key?: string; line?: number; message: string; fence?: FenceMessageLocation },content: string | null, blob: Pick<TreeBlob, 'oid'> | null | undefined): HeldEntry {@@ -325,6 +336,13 @@ export async function screenFrozenImport(engine: BrainEngine, input: FrozenImporif (refusal.code === 'invalid_frontmatter' && snapshot && snapshot.page.deleted_at == null) {const provenance = await readSyncImportProvenance(engine, input.cursor.sourceId, input.cursor.incarnation, snapshot.page.id);if (provenance?.validated === true && provenance.raw_sha256 === sha256(content) && provenance.origin === entry.sourcePath) {+ // A refusal this release makes on purpose holds that page alone; it is never a parser regression.+ if (refusal.intended) {+ const intended = INTENDED_HOLDS[refusal.intended];+ return heldEntry(entry, slug, pageId, { code: intended.code, ...(refusal.line !== undefined ? { line: refusal.line } : {}),+ message: `${entry.path} is held: ${intended.cause}${refusal.line !== undefined ? ` (line ${refusal.line})` : ''}, which gbrain ${VERSION} refuses on purpose although gbrain ${provenance.gbrain_version} `+ + `imported these exact bytes. ${intended.fix} The rest of the source keeps syncing.` }, content, blob);+ }const why = `gbrain ${VERSION} refuses ${entry.path} (${refusal.reason ?? 'yaml_parse'}${refusal.line !== undefined ? `, line ${refusal.line}` : ''}), but gbrain ${provenance.gbrain_version} imported these exact bytes and validated them.`;if (run.policy.parserRegression === 'hold') return heldEntry(entry, slug, pageId, { code: 'parser_regression', message: `${why} Held under GBRAIN_SYNC_PARSER_REGRESSION=hold.` }, content, blob);throw opError('sync_parser_regression', `Sync stopped: ${why}`,diff --git a/test/e2e/sync-alias-limit-hold-6712-postgres.test.ts b/test/e2e/sync-alias-limit-hold-6712-postgres.test.tsnew file mode 100644index 0000000000..8ddf1bc3fc--- /dev/null+++ b/test/e2e/sync-alias-limit-hold-6712-postgres.test.ts@@ -0,0 +1,3 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(() => import('../sync-alias-limit-hold-6712.test.ts'));diff --git a/test/sync-alias-limit-hold-6712.test.ts b/test/sync-alias-limit-hold-6712.test.tsnew file mode 100644index 0000000000..e70a67077c--- /dev/null+++ b/test/sync-alias-limit-hold-6712.test.ts@@ -0,0 +1,81 @@+/**+ * #6712 PR 4b (GBRA-108, S-47 follow-up): a page whose stored bytes are a YAML alias bomb that an older, validating gbrain+ * imported is held alone when it is re-screened, never treated as a parser regression. #7018 bounds alias expansion on+ * purpose, so this release refusing those bytes is intended: the refusal carries a structured marker (`intended:+ * 'yaml_alias_limit'`, set where `YamlAliasBoundError` becomes the `invalid_frontmatter` refusal), and the provenance+ * check holds that page under `frontmatter_alias_limit` while the rest of the source syncs.+ *+ * Protects:+ * - an alias bomb whose provenance says a validating older gbrain imported those exact bytes, re-screened on a full+ * listing: held `frontmatter_alias_limit` alone, the other files import, the run is not stopped, nothing is expanded;+ * - an ordinary `invalid_frontmatter` refusal (no marker) under the same provenance still stops the run with+ * `sync_parser_regression` under the default policy.+ *+ * Six-level bomb only (~530k nodes once expanded, refused before anything walks it); never build a nine-level value.+ * PGLite here; Postgres through test/e2e/sync-alias-limit-hold-6712-postgres.test.ts.+ */+import { describe, expect, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { mkdirSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import { readGitSourceHolds, SYNC_IMPORT_PROVENANCE_OP } from '../src/core/persistence/sync-holds.ts';+import { sha256 } from '../src/core/persistence/digest.ts';+import { performManagedSync } from '../src/core/persistence/sync-run.ts';+import { managedBrain } from './helpers/managed-brain.ts';+import { testBackends } from './helpers/test-backends.ts';++const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();+const commit = (root: string, message: string) => { git(root, 'add', '-A'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', message); };+const note = (title: string, extra = '') => `---\ntitle: ${title}\ntype: note\n${extra ? `${extra}\n` : ''}---\n# ${title}\n\nBody of ${title}.\n`;+/** `levels` nested anchors, each a flow sequence of nine aliases to the one before: 9^levels leaves once expanded. */+const aliasBomb = (levels: number) => ['a0: &a0 [leaf]', ...Array.from({ length: levels }, (_, i) => `a${i + 1}: &a${i + 1} [${Array(9).fill(`*a${i}`).join(', ')}]`)].join('\n');+const BOMB_6 = note('Bomb note', aliasBomb(6));+/** An ordinary refusal with no marker: a key whose value runs onto an unquoted second line. */+const FOLDED = '---\ntitle: first line\nsecond line\n---\nA synthetic post.\n';+const OPTS = { sourceId: 'default', noPull: true, noEmbed: true, noExtract: true };+const setup = ({ root }: { root: string }) => {+ mkdirSync(join(root, 'notes'), { recursive: true }); git(root, 'init', '-q');+ writeFileSync(join(root, 'notes/target.md'), note('Target')); writeFileSync(join(root, 'notes/ok.md'), note('Ok'));+ commit(root, 'notes');+};++/** The page's import provenance now claims an older, validating gbrain imported `content` exactly. */+async function provenanceClaims(engine: BrainEngine, slug: string, content: string): Promise<void> {+ const page = (await engine.getPage(slug, { sourceId: 'default' }))!;+ const updated = await engine.executeRaw(`UPDATE op_checkpoints SET completed_keys=jsonb_set(jsonb_set(completed_keys,'{0,raw_sha256}',to_jsonb($3::text)),'{0,gbrain_version}','"0.60.100.0"'::jsonb)+ WHERE op=$1 AND fingerprint LIKE $2 AND (completed_keys->0->>'validated')::boolean RETURNING 1`, [SYNC_IMPORT_PROVENANCE_OP, `default:%:${page.id}`, sha256(content)]);+ expect(updated).toHaveLength(1);+}+const lastCommit = async (engine: BrainEngine) => (await engine.executeRaw<{ c: string | null }>("SELECT last_commit AS c FROM sources WHERE id='default'"))[0]!.c;+const holds = async (engine: BrainEngine) => ((await readGitSourceHolds(engine, { sourceIds: ['default'] }))[0]?.holds ?? []).map(hold => ({ path: hold.path, code: hold.code }));+const largestFrontmatter = async (engine: BrainEngine) => (await engine.executeRaw<{ n: number | null }>("SELECT max(length(frontmatter::text))::int AS n FROM pages WHERE source_id='default'"))[0]?.n ?? 0;++for (const backend of testBackends()) {+ const databaseUrl = backend === 'postgres' ? process.env.DATABASE_URL : undefined;+ const brain = (run: Parameters<typeof managedBrain>[0]) => managedBrain(run, { ...(databaseUrl ? { databaseUrl } : {}), setup });++ describe(`#6712 PR 4b alias-limit refusals of validated bytes (${backend})`, () => {+ test('a stored alias bomb a validating older gbrain imported is held frontmatter_alias_limit alone on a full re-screen; the rest syncs', () => brain(async ({ engine, root }) => {+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');+ writeFileSync(join(root, 'notes/target.md'), BOMB_6); writeFileSync(join(root, 'notes/new.md'), note('New')); commit(root, 'bomb and new');+ await provenanceClaims(engine, 'notes/target', BOMB_6);+ const result = await performManagedSync(engine, { ...OPTS, full: true });+ expect(result.held?.map(hold => ({ path: hold.path, code: hold.code }))).toEqual([{ path: 'notes/target.md', code: 'frontmatter_alias_limit' }]);+ expect(await holds(engine)).toEqual([{ path: 'notes/target.md', code: 'frontmatter_alias_limit' }]);+ expect(await lastCommit(engine)).toBe(git(root, 'rev-parse', 'HEAD'));+ expect((await engine.getPage('notes/new', { sourceId: 'default' }))?.compiled_truth).toContain('Body of New.');+ expect((await engine.getPage('notes/target', { sourceId: 'default' }))?.compiled_truth).toContain('Body of Target.');+ expect(await largestFrontmatter(engine)).toBeLessThan(10_000);+ }), 180_000);++ test('an ordinary invalid_frontmatter refusal of validated bytes (no marker) still stops the run with sync_parser_regression', () => brain(async ({ engine, root }) => {+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');+ writeFileSync(join(root, 'notes/target.md'), FOLDED); commit(root, 'fold target');+ await provenanceClaims(engine, 'notes/target', FOLDED);+ const before = await lastCommit(engine);+ await expect(performManagedSync(engine, { ...OPTS, full: true })).rejects.toMatchObject({ code: 'sync_parser_regression' });+ expect(await lastCommit(engine)).toBe(before);+ }), 180_000);+ });+}