Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(import): one content screen for every ingestion path (#5988)

garrytaneba73b29cfeb
diff --git a/docs/architecture/key-files/files-and-sync-1.md b/docs/architecture/key-files/files-and-sync-1.md
index f4d329c0c6..1731c70eb3 100644
--- a/docs/architecture/key-files/files-and-sync-1.md
+++ b/docs/architecture/key-files/files-and-sync-1.md
@@ -11,7 +11,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/content-sanity.ts` — pure assessor for the content-sanity defense. `assessContent(content, opts): SanityVerdict` returns one of `ok | warn_oversize | hard_block_junk_pattern | soft_block_oversize` with `{reason, bytes, matched_pattern_name?}`. Six built-in junk patterns (Cloudflare challenge dumps, CAPTCHAs, 403 dumps, bare error-page titles) compiled at module load; operator literal substrings via `loadOperatorLiterals()` from `src/core/content-sanity-literals.ts`. `ContentSanityBlockError` tagged class is the typed throw shape every wrapper site (`gbrain import`, `put_page` MCP op, `gbrain sync`, `/ingest` webhook) catches via the existing exception flow. The bytes-parity contract pins `Buffer.byteLength(content, 'utf8')` against the embedder's actual byte count so a 499K-byte page can't be soft-blocked on assessment then overflow on embed. Knob resolution chain env > file (`~/.gbrain/config.json`) > DB > defaults. Four knobs: `content_sanity.bytes_warn` (50_000), `content_sanity.bytes_block` (500_000), `content_sanity.junk_patterns_enabled` (true), `content_sanity.disabled` (false; `GBRAIN_NO_SANITY=1` is the loud-stderr kill-switch). `assessContentSanity(opts): SanityAssessment` returns the three-tier disposition (`shouldQuarantine` / `shouldFlag` + reason/detail) consumed by `importFromContent` and `gbrain quarantine scan`; adds the fuzzy prose-vs-markup ratio pass (markup chars / total above `max_markup_ratio`; code pages exempt; gated by `prose_check_enabled`) on top of the byte + junk-pattern passes. Three more knobs: `content_sanity.junk_disposition` (`quarantine` default | `reject`; no env override — a destructive flip belongs in explicit config), `content_sanity.max_markup_ratio` (0.85, env `GBRAIN_MAX_MARKUP_RATIO`, clamped `(0,1]`), `content_sanity.prose_check_enabled` (true). Pinned by `test/content-sanity.test.ts`. Per-pattern opt-out without the kill-switch: `content_sanity.disabled_patterns` names built-in junk patterns to skip (a JSON array `["access_denied"]` or a comma list `access_denied,error_title`; malformed JSON falls back to the comma parse so a hand-typed value still lands) — the file plane takes the array, the DB plane the string.
-- `src/core/data-frontmatter.ts` — shared data-only YAML/JSON parsing and serialization. Rejects unsupported language selectors before parsing, uses js-yaml safe schema with existing scalar types (a calendar-invalid timestamp such as `2024-02-30` stays a string instead of rolling over to March 1), sanitizes parser errors, and keeps body text opaque. Used by markdown, capture, recipes, plugins, and greenfield ingestion. Independent fixtures: `test/data-frontmatter.test.ts`, `test/frontmatter-security.test.ts`.
+- `src/core/data-frontmatter.ts` — shared data-only YAML/JSON parsing and serialization. Rejects unsupported language selectors before parsing, uses js-yaml safe schema (exported `FRONTMATTER_SCHEMA`) with existing scalar types (a calendar-invalid timestamp such as `2024-02-30` stays a string instead of rolling over to March 1), sanitizes parser errors, and keeps body text opaque. Used by markdown, capture, recipes, plugins, and greenfield ingestion. Independent fixtures: `test/data-frontmatter.test.ts`, `test/frontmatter-security.test.ts`.
- `src/core/default-source-path-check.ts` — pure `assessDefaultSourcePath(input)` verdict for the `default_source_local_path` doctor check (no DB/FS access — caller supplies gathered inputs, the npm-squat-check.ts shape). INVARIANT: `default.local_path: null` is the DESIGNED fallback topology (write-through nests under `sync.repo_path`), NOT an error — the check warns ONLY when the null pointer provably breaks something: the fallback repo is another source's own working tree (the leak-guard collision: every unscoped default write-through silently skipped), or default has file-backed pages and no resolvable root. Everything else (no pages, resolvable fallback, deliberate DB-only brain) is ok. The repair it names is the non-destructive `gbrain sources set-path default <path>`.
@@ -19,17 +19,21 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/file-resolver.ts` — File resolution with fallback chain (local -> .redirect.yaml -> .redirect -> .supabase).
+- `src/core/frontmatter-recovery.ts` — `recoverFrontmatter(block)` (`RECOVERY_VERSION`): rules touch only the suspect run at the parser's error mark, keep CRLF per line, and never rewrite, fold into or guess a `PROTECTED_FRONTMATTER_KEYS` key or resolve a duplicated `IDENTITY_FRONTMATTER_KEYS` key. `quote` is safe; `fold`/`dup`/`unclosed` classify `needs_interpretation` with the proposed block kept. `frontmatterKeyHazard` (swallowed or pre-quoted protected keys), `unclosedFenceProtectedKey`, `commentValueKeys`. Tests: `test/frontmatter-recovery.test.ts`.
+
- `src/core/git-head.ts` — local git HEAD freshness probe for `gbrain doctor`. `isSourceUnchangedSinceSync(localPath, lastCommit, opts?)` returns true iff `localPath` is a git repo whose current HEAD matches `lastCommit`; when `opts.requireCleanWorkingTree` is true also requires a clean working tree (mirrors `gbrain sync`'s force-walk gate at `sync.ts:1075` so doctor and sync agree on "is there work to do?"). `requireCleanWorkingTree` is `boolean | 'ignore-untracked'` — in `'ignore-untracked'` mode the clean probe runs `git status --porcelain --untracked-files=no` so a quiet repo with stray untracked dirs (`?? companies/`, `?? media/`) is still "unchanged" (sync's incremental path keys off the commit diff and does not import untracked files by default — it counts them as `uncommitted` drift with a stderr warning; `--working-tree` opts into importing them); `GitCleanProbe` gains an `ignoreUntracked?` second arg. Two probe seams (`_setGitHeadProbeForTests`, `_setGitCleanProbeForTests`) keep unit tests R2-compliant (no `mock.module`). Uses `execFileSync` with array args so shell metachars in `local_path` cannot escape to a shell (the test runs real `execFileSync` against `'/nonexistent/$(touch <sentinel>)/repo'` and asserts the sentinel is never created). Fail-open on every error (missing path, not a git repo, git not installed, timeout, NULL inputs, dirty-probe errored → false) so the caller falls back to its time-based check. The chunker-version-match check lives in the caller (doctor.ts) because it depends on engine state (`sources.chunker_version` vs `CHUNKER_VERSION` from `src/core/chunkers/code.ts`). Pinned by `test/core/git-head.test.ts` (incl. the shell-injection guard).
- `src/core/git-remote.ts` — SSRF-hardened git invocations for remote-source `cloneRepo`, `pullRepo`, and `fetchRemote(repoPath, branch)` (the last used by the sync cost-estimator's fetch-first path, so a cost preview / dry-run fetches through the same hardened flags + `GIT_TERMINAL_PROMPT=0` as real sync rather than a less-protected route). Exports two distinct flag constants because `git`'s argv grammar treats them differently: `GIT_SSRF_FLAGS` (3 `-c` config flags — `http.followRedirects=false`, `protocol.file.allow=never`, `protocol.ext.allow=never`) is global config, spread BEFORE the subcommand verb; `GIT_SSRF_SUBCOMMAND_FLAGS = ['--no-recurse-submodules']` is subcommand-scoped, spread AFTER the verb (a combined array would spread `--no-recurse-submodules` before the verb where real git rejects it exit 129). `cloneRepo` argv: `git <GIT_SSRF_FLAGS> clone <GIT_SSRF_SUBCOMMAND_FLAGS> --depth=1 [--branch X] <url> <dir>`. `pullRepo` argv: `git -C <dir> <durableSsrfFlags()> pull <GIT_SSRF_SUBCOMMAND_FLAGS> --ff-only` — `durableSsrfFlags()`, not the hardcoded `GIT_SSRF_FLAGS`: identical `-c` flags except `protocol.file.allow` honors the `GBRAIN_GIT_ALLOW_FILE_TRANSPORT=1` escape hatch. `fetchRemote` uses the same helper. Pinned by `test/git-remote.test.ts` position-anchored guard (`argv.indexOf('--no-recurse-submodules') > argv.indexOf(verb)`). Also exports the durability-side helpers that power `gbrain sources harden/pull`: `GIT_ENV_AUTH` (the no-prompt env minus the askpass `/bin/false` overrides, so an auth'd push/fetch can consult the repo's configured credential helper while `GIT_TERMINAL_PROMPT=0` still fails fast on a missing credential), `divergenceSafePull(repoPath, branch)` (fetch + `pull --rebase`; returns `skipped_dirty` on a dirty tree, `conflict_aborted` on ANY `pull --rebase` failure (the catch doesn't classify the cause — it's treated as a conflict) after up to two best-effort `rebase --abort` attempts (each swallows its own failure; `conflict_aborted` is still returned even if rebase state remains), else `up_to_date`/`advanced`), `detectDefaultBranch` (origin/HEAD → current branch → `main`), `pushProbe(repoPath, branch)` (authenticated `push --dry-run` that proves push access and classifies `auth`/`protected`/`unreachable`), and `isWorkingTreeDirty`. These auth'd paths route their `protocol.file.allow` through `GBRAIN_GIT_ALLOW_FILE_TRANSPORT` (default `never`; set `=1` for self-hosted filesystem remotes), unlike `cloneRepo`, which still uses the hardcoded `GIT_SSRF_FLAGS` and stays strict.
- `src/core/import-checkpoint.ts` — `loadCheckpoint(path, currentDir)`, `saveCheckpoint(path, cp)`, `resumeFilter(allFiles, dir, completed)`, `clearCheckpoint(path)`, `resolveImportTargetDir(dir)`, and the `ImportCheckpoint` type. Payload: `{schema_version: 1, owner: 'gbrain', kind: 'import', dir, completedPaths, timestamp}`; `dir` is the absolute realpath of the import target, never the caller's CWD. Paths record successful/unchanged progress, not content identity; ordinary `runImport` revalidates all current files via `importFile`'s existing content-hash comparison rather than using `resumeFilter`. Company-brain ingestion uses separate protected database checkpoints for an immutable approved manifest. The exported pure filter returns a path array and skips completed paths for company-brain manifest resume; by itself it is not proof that mutable file content is unchanged. `loadCheckpoint` returns `null` for missing/malformed payloads, target mismatch, invalid path/timestamp fields, or incompatible producer metadata; absent producer fields in legacy path-set checkpoints remain accepted. Old positional checkpoints log a stderr diagnostic before discard. `saveCheckpoint` sorts paths and atomically writes via `.tmp` + `rename()`; save/clear failures are non-fatal and silent. The caller supplies the checkpoint path via `gbrainPath()`, preserving `GBRAIN_HOME` isolation. Pinned by `test/import-checkpoint.test.ts`, `test/import-resume.test.ts`, and `test/import-json-stdout.serial.test.ts`.
+- `src/core/import-screen.ts` — `screenImportContent`: the one content screen (working-tree-published exemption first, then size, frontmatter hold, slug conflict with a caller exemption, optional content-sanity reject) shared by `importFromContent`, managed import and managed sync publication. `contentRefusalError` keeps each site's wire `error`; `isContentRefusal(code, message)` matches new codes and exact pre-upgrade strings, never capacity or transient refusals; `contentRefusalFromReceipt` restores code, reason, key and line on receipt replies. Tests: `test/import-screen.test.ts`, `test/sync-frontmatter-recovery.test.ts`, `test/put-page-recoverable-frontmatter.test.ts`.
+
- `src/core/import-file.ts` — importFromFile + importFromContent (chunk + embed + tags). Every markdown import resolves and stamps `contextual_retrieval_mode` and `corpus_generation` with the canonical write, `--no-embed` included (#5621), so later embed passes reproduce the page's wrapping; a failed source-policy read fails the import unless the row or table is missing (`SourceRowNotFoundError`, `isUndefinedTableError`). Unchanged markdown or code content whose page is below the safe-chunk fence is re-sealed projection-only (direct imports install it; coordinated `prepare` imports stay no-ops and queue a `safe_chunk_reseal` projection job), with no page write or admission. Freshly embedded chunks carry `embedding_input_hash` for the tier they were built under. The `beforeCommit` hook runs inside the guarded canonical transaction so a rejected file write rolls back its projections; optional legacy source-path repair uses a savepoint. Deferred importer embedding callbacks capture the committed text projection and indexing context, then install with an UPDATE-only revision/chunk/hash check. Tests: `test/import-publication-guards.test.ts`. Coordinated `prepare` imports resolve and atomically stamp the page/source/global contextual wrapping mode even with `noEmbed:true`; the durable outbox later embeds that revision. The existing paid-synopsis title fallback and mount trust gate remain in force, while embedding signatures only certify completed vectors. `test/persistence-contextual-embedding.test.ts` covers both engines, policy precedence, deferred provider execution, and a competing title replacement. `importFromContent` and `importCodeFile` stamp `pages.embedding_signature` via `setPageEmbeddingSignature(slug, {sourceId, signature: currentEmbeddingSignature()})` when the import actually embedded (not `--no-embed`) so a model/dims swap is detectable as stale; `importCodeFile` only stamps when every chunk was freshly embedded this call (`needsEmbedIndexes.length === chunks.length`), mixed reuse-by-hash pages stay unstamped (`reindex --code --force` / `embed --stale` handle those). `importFromContent` reconciles tags by provenance (`tags.tag_source`, migration v175): frontmatter tags go through `addTag(..., { tagSource: 'frontmatter' })`, and a row still marked 'frontmatter' whose tag left the frontmatter is deleted in the import transaction. Every other `addTag` stamps 'added' (add_tag, enrichment, the code importer) and is never import-deleted, so `gbrain reindex --markdown` keeps enrichment tags; legacy NULL rows are adopted only while the frontmatter still lists them; prepared (managed) imports keep add-only tags, matching the union their canonical file renders. Pinned by `test/reindex-preserve-tags.test.ts`, `test/import-frontmatter-tag-removal.test.ts` + `test/import-file.test.ts`. identity decisions live in `src/core/import-identity.ts` (`decideImportIdentity`, `collidingSlugOwner`; pure reads, the importer applies them). The dedup pre-check calls `engine.findDuplicatePage?.(sourceId, {hash, frontmatterId, excludeSlug})` (optional `?` so test doubles compile; the caller's own slug never matches, and a `frontmatter.id` match ranks ahead of a bare hash match). Posture: MOVE when the `frontmatter.id` matches and the other page's OWN origin proves it moved (#5675): that origin is the `file://` path `importFromFile` records in `pages.source_uri` (never replacing non-file provenance), else the source's configured root (`local_path`, or the default source's legacy `sync.repo_path`). An origin that still exists moves only when it is this very file under another relative path (overlapping roots converge); a gone origin needs this file under that same root, and differing content also needs the same file name or title, so a missing path under another root, or a new note reusing a deleted note's template id, never renames a live page. `updateSlug` carries the row (page id, links, facts incl. `entity_slug`/`source_markdown_slug`, `page_aliases`, timeline, plus a rename alias) and the new content imports onto it, so a full sync's delete-reconcile has nothing live to remove; SKIP only when the id AND the content (`content_hash`, or title and body for a row written outside the importer) both match while the recorded file still exists (overlapping ingest roots); IMPORT with a warning when the id matches but content differs (templates, copy-paste; an edit is never frozen by the other page); WARN-ALWAYS on a bare content_hash collision; FAIL CLOSED on lookup error; bypass via `--force-rechunk`. Content-only callers (`put_page`, transcripts) never move a page. Soft-deleted pages excluded at the engine layer so tombstones don't block legitimate re-imports under new slugs. Slug collisions: when another live file (`existing.source_path`, realpath-distinct) already owns the slug, the incoming file is skipped with `skip_reason: 'slug_collision'` and a stderr warning, unless the incoming file is named exactly `<slug>.md` (the file the link extractor reads for that slug), so two spellings never overwrite each other. An embedding failure never blocks the text write: chunks commit with NULL vectors, no embedding signature is stamped, the result carries `embedding_deferred: true`, and the stale sweep embeds them later (a code file whose embed failed is not stamped either). An inline markdown re-import embeds only chunks whose embedding input changed: `planEmbeddingReuse` (keyed on chunk source + exact text) reuses a stored vector when the old index is sealed (`requireSafeChunks`), the page's `embedding_signature`, contextual mode, `corpus_generation` and (under the title wrapper) sanitized title are unchanged, and neither the old nor the new body holds protected fences; prepared, `--no-embed`, `--force-rechunk` and post-commit-embedding imports reuse nothing (`test/import-markdown-embedding-reuse.test.ts`). Offset-less frontmatter datetimes are read in the brain's `brain.timezone` (IANA, validated by `gbrain config set`; unset or invalid = UTC; the YAML parser tags naive timestamps with `NAIVE_DATETIME` so the wall-clock reading survives), while date-only values stay UTC calendar dates (`test/effective-date-brain-timezone.test.ts`). `effective_date` for an undated page falls back to `fallbackCreatedAt` (stored fallback date, else the earliest of the file's birth/modification time and — when `sync.git_first_commit_dates` is on — its git first-commit date via `fileTimes`, else now; `src/core/git-first-commit.ts` maps paths in one `git log --diff-filter=A` pass per `runImport`, skipping shallow clones; `test/effective-date-git-first-commit.test.ts`), never the latest write. Pinned by `test/import-dedup-frontmatter-id.test.ts`, `test/import-identity-move.test.ts`, `test/import-slug-collision.test.ts`, `test/import-embed-outage.test.ts` and `test/effective-date-calendar.test.ts`. `importFromContent` is the narrow waist every ingest path passes through (`gbrain import`, `gbrain sync`, `put_page` MCP, `/ingest` webhook). It runs a three-tier content-quality disposition via `assessContentSanity` from `src/core/content-sanity.ts` BEFORE chunking: (1) high-confidence junk (built-in Cloudflare/CAPTCHA interstitial patterns + operator literals) → QUARANTINE (stamps the `quarantine` frontmatter marker, writes ZERO chunks, hides the page from search) OR REJECT (throw → sync-failure) when `content_sanity.junk_disposition` is `reject`; (2) fuzzy markup-heavy (prose-vs-markup ratio above `content_sanity.max_markup_ratio`, warn-tier byte window, code pages exempt) → `content_flag:markup_heavy` marker (page stays fully searchable, marker rides search results + get_page to warn the agent); (3) oversize → `embed_skip` soft-block via `buildEmbedSkipMarker()` PLUS a `content_flag:oversized` marker, AND deletes any pre-existing chunks in the same transaction so search can't surface stale chunks. Gate-owned markers (`quarantine`, `content_flag`) are STRIPPED from untrusted (remote MCP, `ctx.remote !== false`) frontmatter so a write-scoped client can't hide pages or forge the warning channel; markers are excluded from `content_hash` so a flagged page doesn't re-embed every sync. `gbrain import` honors `errors > 0` for non-zero exit. `classifyErrorCode` in `src/core/sync.ts` recognizes the `PAGE_JUNK_PATTERN` code so sync-failures.jsonl grouping bins these. `extractEntityRefs` (canonical; matches both `[Name](../people/slug)` markdown links and Obsidian `[[people/slug|Name]]` wikilinks), `extractPageLinks`, `inferLinkType` heuristics (attended/works_at/invested_in/founded/advises/source/mentions), `parseTimelineEntries`, `isAutoLinkEnabled` config helper. Link candidates match any dir-shaped path (existence-checked at persist). Used by extract.ts, operations.ts auto-link post-hook, and backlinks.ts. Pinned by `test/import-file-content-sanity.test.ts`. `importImageFile` records `source_path` on every image page and skips an unchanged image only when its index is complete for the run: a visual vector when embedding is on, and OCR (`ocr_status: 'done'` in frontmatter, or legacy stored OCR text) when OCR is enabled, so an image first imported under `--no-embed` or an OCR skip is rebuilt on its next import (`test/import-image-retry.test.ts`). `importCodeFile` writes `source_path: relativePath` on every code page (the same repo-relative path markdown imports record) so the full-sync reconcile — which only considers `source_path IS NOT NULL` rows — can retire a deleted code file's page; `putPage` COALESCEs the column, so rows imported before this keep NULL until the file changes, `sync --force`, or `gbrain reindex-code --force`.
- `src/core/link-source-check-repair.ts` — schema-drift self-heal for the `links_link_source_check` CHECK constraint (third instance of the `timeline-dedup-repair.ts` / `pages-upsert-arbiter.ts` class). Migration v114 opened `link_source` from a closed allowlist to the kebab-case gate; the migrator trusts the version ledger, so a brain stamped >= 114 whose live constraint reverted to the pre-v114 allowlist (drifted restore, manual DDL) rejects every kebab provenance write (`atom-provenance`, `concept-provenance`) while the ledger reads current. `LINK_SOURCE_KEBAB_RE` is the ONE exported copy of the regex (a drift-guard test pins it to the literal in migrate.ts v114, `schema.sql`, `pglite-schema.ts`). `checkLinkSourceCheck(engine)` probes `pg_constraint` (`pg_get_constraintdef` + `convalidated`) and classifies the drift as `absent` / `wrong_def` / `not_validated` (read-only; powers the `links_link_source_check` doctor check in `doctor/checks/core-health.ts`, whose severity follows what writes do: only `wrong_def` rejects kebab writes → fail; `absent` / `not_validated` still accept them → warn). `repairLinkSourceCheck(engine)` first COUNTs rows that fail the gate and returns `reason: 'violations'` WITHOUT any DDL when there are any (the prior constraint survives; rows are never touched; a brain with a bad row never pays for a failing ALTER at every engine open), then restores v114's definition mirroring the migration's engine split: Postgres runs DROP + `ADD ... NOT VALID` in one `engine.transaction` (atomic, no scan) and `VALIDATE CONSTRAINT` as a separate `engine.runMigration` outside it (SHARE UPDATE EXCLUSIVE, never a plain ADD's ACCESS EXCLUSIVE + full-table scan), with a `not_validated` drift getting the VALIDATE only; PGLite keeps the one-shot DROP+ADD transaction. A DDL failure re-counts violators (a row written between probe and ALTER) and rethrows when there are none. `LINK_SOURCE_GATE_MIGRATION_VERSION` (114) is the ledger gate `runMigrations` applies before calling it. Pinned by `test/link-source-check-repair.test.ts` (PGLite, incl. a recording-engine assertion that violators trigger no DDL and that a sub-114 ledger never probes) and the DATABASE_URL-gated `test/e2e/link-source-check-repair-postgres.test.ts` (two-phase DDL sequence on real Postgres).
-- `src/core/markdown.ts` — Frontmatter parsing + body splitter. `coerceFrontmatterString(v)` coerces a non-string `title`/`slug`/`type` to a deterministic string at parse time so a YAML-typed value never reaches `.toLowerCase()` and throws (`title: 2024-06-01` parses as a `Date`, `title: 1458` as a number, and a throw would block the sync bookmark from advancing); a `Date` becomes its UTC ISO date (`2024-06-01`, machine-independent and matching the on-disk token, unlike `String(date)`), `null`/`undefined` become `''`, everything else uses `String()`. `splitBody` requires an explicit timeline sentinel (`<!-- timeline -->`, `--- timeline ---`, or `---` immediately before `## Timeline`/`## History`). Plain `---` in body text is a markdown horizontal rule, not a separator. `inferType` auto-types `/wiki/analysis/` → analysis, `/wiki/guides/` → guide, `/wiki/hardware/` → hardware, `/wiki/architecture/` → architecture, `/writing/` → writing (plus existing people/companies/deals/etc heuristics). `resolveSourceLocalFilePath` maps Git-root-relative `pages.source_path` values into a source whose `local_path` scopes a repo subdirectory; it finds the Git root with filesystem checks only, strips the exact root-relative scope, rejects unsafe/non-markdown paths, and when given a slug it tolerates historical basename-relative `source_path` rows by checking the slug directory only after the direct path is absent. It leaves write containment to the caller.
+- `src/core/markdown.ts` — Frontmatter parsing + body splitter. `coerceFrontmatterString(v)` coerces a non-string `title`/`slug`/`type` to a deterministic string at parse time so a YAML-typed value never reaches `.toLowerCase()` and throws (`title: 2024-06-01` parses as a `Date`, `title: 1458` as a number, and a throw would block the sync bookmark from advancing); a `Date` becomes its UTC ISO date (`2024-06-01`, machine-independent and matching the on-disk token, unlike `String(date)`), `null`/`undefined` become `''`, everything else uses `String()`. `splitBody` requires an explicit timeline sentinel (`<!-- timeline -->`, `--- timeline ---`, or `---` immediately before `## Timeline`/`## History`). Plain `---` in body text is a markdown horizontal rule, not a separator. `inferType` auto-types `/wiki/analysis/` → analysis, `/wiki/guides/` → guide, `/wiki/hardware/` → hardware, `/wiki/architecture/` → architecture, `/writing/` → writing (plus existing people/companies/deals/etc heuristics). `resolveSourceLocalFilePath` maps Git-root-relative `pages.source_path` values into a source whose `local_path` scopes a repo subdirectory; it finds the Git root with filesystem checks only, strips the exact root-relative scope, rejects unsafe/non-markdown paths, and when given a slug it tolerates historical basename-relative `source_path` rows by checking the slug directory only after the direct path is absent. It leaves write containment to the caller. After its pre-quote pass, a block the strict parse refuses goes to `recoverFrontmatter`; only `quote` recoveries are applied. Under `validate`, YAML_PARSE stays in `errors` (location-only message, `recoverable` plus a content-free `recovery` record), advisories go to `warnings` (`FRONTMATTER_RECOVERED`, `FRONTMATTER_COMMENT_VALUE`), and `recovery` carries interpretive, protected-key and identity-key findings. `HOLD_CODES` and `classifyImportHold(parsed, ctx)` define the ingestion hold set once; `isFrontmatterHoldMessage` recognizes its exact messages. Tests: `test/frontmatter-recovery.test.ts`.
- `src/core/quarantine.ts` — the two frontmatter markers the content-quality gate writes, sibling of `src/core/embed-skip.ts` (same marker-as-JSONB-object pattern, same JSONB `?` existence check that works on Postgres AND PGLite; no schema migration — both are frontmatter JSONB keys). `quarantine` (key `QUARANTINE_KEY`) HIDES: set ONLY for high-confidence junk, writes zero chunks, excluded from search via `quarantineFilterFragment(pageAlias)` / `QUARANTINE_FILTER_FRAGMENT` (the `p`-aliased constant), the single source of truth `buildVisibilityClause` calls so the search filter and marker key can't drift. `content_flag` (key `CONTENT_FLAG_KEY`) WARNS, does NOT hide: set for fuzzy markup-heavy / oversize, page stays searchable, marker is READ INTO search/get_page output — deliberately NO SQL filter fragment. Three distinct markers, three reasons (never overloaded): `embed_skip` = oversized-but-clean, `quarantine` = junk hidden, `content_flag` = odd-examine-still-here; a page can carry more than one (oversize → embed_skip + content_flag:oversized) and each clears independently. Exports `buildQuarantineMarker` / `isQuarantined` / `filterOutQuarantined`, `buildContentFlagMarker` / `getContentFlag` / `hasContentFlag`, plus the two key constants. Pinned by `test/quarantine.test.ts`.
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.md
index 77c22becc8..9990e5a362 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -289,6 +289,14 @@ More: [docs/guides/google-connect.md#troubleshooting](../../docs/guides/google-c
|---|---|---|---|---|---|---|
| Shared skill storage is not ready on this brain. | A temporary condition (a lock, a pending write, a rate limit); the same request can succeed later. | Wait briefly, then retry the same request (writes: reuse the same request_id). | agent | `repeat the read that failed` | 1 | yes |
+### changed_since_preview
+
+<a id="changed_since_preview"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| The file changed after its repair was previewed, so nothing was written. | A repair writes exactly the bytes the operator approved; it binds approval to the previewed file hash and refuses when the file moved on. | Preview the repair again, review the new proposal, and approve its new hash. | agent | `repeat the read that failed` | 1 | no |
+
### checkpoint_missing
<a id="checkpoint_missing"></a>
@@ -471,6 +479,14 @@ More: [docs/guides/write-refusals.md#colon_slug_windows_write_through](../../doc
More: [docs/guides/google-connect.md#troubleshooting](../../docs/guides/google-connect.md#troubleshooting)
+### content_rejected
+
+<a id="content_rejected"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| The content-sanity gate rejected the content because the operator set `content_sanity.junk_disposition` to `reject`. | A junk-pattern or operator-literal hit is refused instead of quarantined under that setting, so the page was not written. The same content refuses on every retry. | Remove the matched junk from the file, or switch `content_sanity.junk_disposition` back to `quarantine` (a user decision), then import it again. | agent | `repeat the read that failed` | 1 | no |
+
### cost_cap_exceeded
<a id="cost_cap_exceeded"></a>
@@ -725,6 +741,22 @@ More: [docs/guides/write-refusals.md#facts_absorb_write_refused](../../docs/guid
More: [docs/guides/write-refusals.md#fetch_failed](../../docs/guides/write-refusals.md#fetch_failed)
+### file_too_large
+
+<a id="file_too_large"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| The file is over the import size limit (5 MB for Markdown and code, 10 MiB for any sync read), so it was not imported. | Size limits bound parsing, chunking and embedding cost. The same bytes refuse on every retry. | Split the file into smaller files, or leave it out of the source (sync.exclude), then sync or import again. | agent | `repeat the read that failed` | 1 | no |
+
+### frontmatter_slug_conflict
+
+<a id="frontmatter_slug_conflict"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| The file's frontmatter `slug:` names a different page than its path does. | The path decides a file's page; a conflicting declared slug would overwrite or fork another page, so the file is refused until one of them changes. | Remove the `slug:` line or make it match the path, then commit and sync again. | agent | `repeat the read that failed` | 1 | no |
+
### full_resync_required
<a id="full_resync_required"></a>
@@ -871,6 +903,16 @@ More: [docs/guides/google-connect.md#troubleshooting](../../docs/guides/google-c
|---|---|---|---|---|---|---|
| Invalid connector text. | The request itself was wrong or no longer matches the brain; nothing was changed. | Correct the request using the message above, then retry. | agent | `repeat the read that failed` | 1 | no |
+### invalid_frontmatter
+
+<a id="invalid_frontmatter"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| The file's YAML frontmatter cannot be read without guessing, so it was not imported. | gbrain imports frontmatter it can read exactly (quoting an unquoted value at most). Guessing could store a wrong title, merge a duplicate, or read a protected key such as `visibility` as a broader value. | Fix the named line in the file (one line per key, the whole value quoted), then commit and sync or import again. | agent | `repeat the read that failed` | 1 | no |
+
+Reasons: `yaml_parse`, `needs_interpretation`, `ambiguous_identity_key`, `ambiguous_protected_key`.
+
### invalid_grant_clock_skew
<a id="invalid_grant_clock_skew"></a>
@@ -1187,6 +1229,14 @@ More: [docs/guides/google-connect.md#troubleshooting](../../docs/guides/google-c
|---|---|---|---|---|---|---|
| The request body is not valid JSON. | The request itself was wrong or no longer matches the brain; nothing was changed. | Correct the request using the message above, then retry. | agent | `repeat the read that failed` | 1 | no |
+### parser_regression
+
+<a id="parser_regression"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| A file whose exact bytes imported before is now refused by gbrain's frontmatter reader. | The same bytes imported under an earlier gbrain version, so only gbrain changed; with `sync.parser_regression=hold` such a file is held and the rest of the sync continues. | 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 with --retry-failed. | host_admin | `gbrain doctor --json` | 1 | no |
+
### pasted_wrong_url
<a id="pasted_wrong_url"></a>
@@ -1443,6 +1493,16 @@ More: [docs/guides/google-connect.md#troubleshooting](../../docs/guides/google-c
More: [docs/guides/google-connect.md#troubleshooting](../../docs/guides/google-connect.md#troubleshooting)
+### rename_held
+
+<a id="rename_held"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| A renamed file is held because the page it was renamed from changed after the rename was recorded. | Moving the page now could carry the newer edit to the wrong file, so the rename waits for an explicit re-bind. | Preview the frontmatter repair with --include-ambiguous to re-bind the rename to the current page, and approve it. | agent | `repeat the read that failed` | 1 | no |
+
+Reasons: `rename_source_changed`.
+
### request_already_submitted
<a id="request_already_submitted"></a>
@@ -1725,6 +1785,14 @@ More: [docs/guides/write-refusals.md#sync_in_progress](../../docs/guides/write-r
Reasons: `content_directory`.
+### sync_parser_regression
+
+<a id="sync_parser_regression"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| Sync stopped because gbrain would hold a file whose exact bytes imported before; this is a gbrain bug. | The upgrade invariant says a newer reader never refuses bytes an older one imported, so the run stops without advancing rather than hide a regression. | Report it with the gbrain version, the file and the code; upgrade or pin the last good version, then run gbrain sync --source <id> --no-pull --retry-failed. | host_admin | `gbrain doctor --json` | 1 | no |
+
### take_row_collision
<a id="take_row_collision"></a>
diff --git a/scripts/function-size-baseline.tsv b/scripts/function-size-baseline.tsv
index 60694e6450..fa37bc14be 100644
--- a/scripts/function-size-baseline.tsv
+++ b/scripts/function-size-baseline.tsv
@@ -41,7 +41,7 @@ src/core/cycle/propose-takes.ts ProposeTakesPhase.process 427 seed: W5 baseline,
src/core/cycle/synthesize-concepts.ts runPhaseSynthesizeConcepts 447 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/core/cycle/synthesize.ts runPhaseSynthesizeInner 1046 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +3 #5854: publish_pending from postprocess, a pending summary publish deferred instead of failing the phase
src/core/facts/backstop.ts runPipelineBodyInner 358 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
-src/core/import-file.ts importFromContent 859 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +2 wave 8 lane D1 #5158: key-order fallback equality and legacy-hash ordering
+src/core/import-file.ts importFromContent 807 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +2 wave 8 lane D1 #5158: key-order fallback equality and legacy-hash ordering; lowered to 807 (#5988: screen and sanity config peeled to core/import-screen.ts)
src/core/minions/handlers/subagent-oneshot.ts runSubagentOneshot 377 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/core/minions/handlers/subagent.ts makeSubagentHandler 884 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/core/minions/handlers/subagent.ts makeSubagentHandler>subagentHandlerInner 814 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 2f17eb42f6..fdc004996b 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -17,7 +17,7 @@ src/core/cycle.ts 3207 ratchet +2 System One v1 S9: extract_facts phase tail run
src/core/cycle/synthesize.ts 3297 ratchet +26 System One v1 S7/S8: triage and grounding decide delegation (triage-decide.ts, grounding-decide.ts); merged waves; grown v0.46.26.0 megawave + master rolling lease via shared throttled renewer; grown wave-g (#4506): cycle summaries can stay out of the source repo; +18: expired-verdict sweep + DeepSeek judge thinking pin (#4069); +47: #4077 cooperative-abort threading; +110: eval fix wave F6 spend surfacing (withChatPhase wrap, triage/child token telemetry, zero-page counter); +32: F1b quote-verify call site + kill switch; +2: F1a/F3/F4a OUTPUT POLICY rules; +59: F2 verified-segment rescue (gate at report construction, rescue knobs, telemetry); +19: rubric v2 peak-scoring + docblock rescue branch; +50: #4337 summary link-sample cap + dream_created_cycle_date preserve-on-rerun; +5: #4348 resolveCycleDate wiring (local-day summary bucketing); +3 round-3 rebase true-up; +55: #4805 synth-v2 completion skip (findSynthV2Completion + prefix-parameterized loadSuccessfulSynthesisKeys); +10: #4886 mode-aware buildSynthesisPrompt (oneshot children drop tool-use/final-prose guidance); #5105: small legacy writer/refusal and shared revision CAS delegates; +4: merge of #5666 durable synthesis completions with the v0.59.18.0 verify-epoch wiring; +7 #5413/#5471 discovery exclusions (self-capture session ids, dream output directories); +6 fix wave 2 (v0.60.5.0) integration: W7 paid-loop breaker check before submission and released-key daily-cap count on top of the W1b discovery exclusions; +6 v0.60.5.0 master-merge true-up: the wave-2 growth (+13 W1b, +6 W7) re-summed over master v0.59.18.0 at 3222 lines with no slack; +76 fix wave 3: per-run USD gate + fail-closed daily cap (C-13), child first-write ownership for stamp/reverse-write (C-8, #5685), cycle-date prompt hint (C-15), opt-in attribution rule (#5425); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +19 at the merge; +2 #5806 triageNow clock seam forwarded to triage (interface field + call-site option); +4 #5854: a postprocess or summary publish still pending after its wait is deferred (publish_pending warn, no cooldown stamp; helper in synthesize-postprocess.ts)
src/core/cycle/extract-atoms.ts 1808 ratchet crossed the 1500 unlisted cap in the atoms/extraction fix wave: +21 embed-aware cost gate (#4878), +65 atoms-array anchor scan (#4913); peel candidate: the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) into extract-atoms-parse.ts; +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize; +10 #5856/#5854: drain attempt state (one BudgetTracker + one publish wait across batches) and the opt-in connector email/meeting exclusion (predicate in connector-atoms.ts)
src/core/engine.ts 2678 ratchet grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count; wave-k: +4 fail-closed TrajectoryOpts.remote contract doc (#3855), +2 FactListOpts.unconsolidatedOnly (#4070), +14 getAllConfig bulk-read contract (#3980); +1: getBacklinkCounts page-id contract doc (#4380); +9: FactListOpts.grep SQL pre-limit contract (#3851); +13: dream-verdict TTL contract (#4069); +33: softDeletePages batch soft-delete contract (#4587); +8: #4592 scoped getStats/getHealth contract doc; +5 read-time TTL validity contract docs (active vs history read semantics); +12: #4280 findOrphanPages type/quarantined metadata contract; +14: traversePathsDetailed row-cap contract (ship-review); +12: resolveSlugWithAliasDetailed owning-source contract (ship-review) | merged v0.48.1.0: master #4788 + wave traversePathsDetailed/resolveSlugWithAliasDetailed; master: | merged v0.48.1.0 true-up; corrective release: read-policy signatures and Chronicle scope; +7: #4882 listFactsSince entitySlug/sessionId composition doc; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop registration and direct transaction contract; #5105: +1 raw preservation contract for legacy engine migration; merged company ingestion/schema routing changes; safety wave: fact embedding model and text identity contract; +5 write-path wave: findDuplicatePage excludeSlug + id-first ranking contract; +2 fw3 A14: addTag tagSource provenance contract; evidence delivery: getChunkWindows interface member + type import (+3); #5761: +4 markPagesAttendanceBlocked member + countStalePagesForExtraction attendance option; +4 #5888: FactListOpts.fingerprint + FactRow.fact_fingerprint contract (hot-memory duplicate collapse)
-src/core/import-file.ts 2233 ratchet +2: pre-publication withdrawal validation; grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); security: durable queued authority and confined filesystem dispatch; master integration: grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: withdrawal preservation after data-only frontmatter parsing; #5105: small legacy writer/refusal and shared revision CAS delegates; #5105: +8 prepared contextual retrieval policy and retry boundary wiring; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: shared provider-free Markdown and code preparation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared content: prepare managed image imports without bypassing canonical publication; +29 write-path wave: identity move/collision wiring (logic in import-identity.ts), deferred embedding on provider failure, image index completeness, file-time date anchor; +22 fw3 A13: markdown re-import reuses unchanged chunk vectors under the seal/wrapper/signature/protected-fence gate; +2 fw3 A12: importFromFile firstCommitAt option; +3 fw3 A14: managed imports keep add-only tags; +4 #5675: record the file origin move inference binds to (logic in import-identity.ts); fw3 integration: A12/A13/A14 (+27) and #5675 (+4) compose; +17 wave-2 W4: safe-chunk re-seal of unchanged legacy markdown/code pages (#5050 #5247) and embedding-input provenance on inline imports (#5553); -1 fix wave 2 (v0.60.5.0) integration: W4 delta re-summed over the merged master line count; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +16 at the merge; +11 #4616: markdown and code imports keep the usable vectors of a partially refused batch and leave refused chunks for embed --stale; lowered to 2230: #5621 contextual-mode resolution peeled to core/import-contextual-mode.ts (shared with gbrain repair contextual-mode); +2 wave 8 lane D1 #5158: key-order fallback equality call (comparison lives in page-state/import-guard.ts); +1 F1c: direct imports run in maintenanceTransaction (write attribution; helper in persistence/attribution.ts)
+src/core/import-file.ts 2178 ratchet +2: pre-publication withdrawal validation; grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); security: durable queued authority and confined filesystem dispatch; master integration: grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: withdrawal preservation after data-only frontmatter parsing; #5105: small legacy writer/refusal and shared revision CAS delegates; #5105: +8 prepared contextual retrieval policy and retry boundary wiring; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: shared provider-free Markdown and code preparation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared content: prepare managed image imports without bypassing canonical publication; +29 write-path wave: identity move/collision wiring (logic in import-identity.ts), deferred embedding on provider failure, image index completeness, file-time date anchor; +22 fw3 A13: markdown re-import reuses unchanged chunk vectors under the seal/wrapper/signature/protected-fence gate; +2 fw3 A12: importFromFile firstCommitAt option; +3 fw3 A14: managed imports keep add-only tags; +4 #5675: record the file origin move inference binds to (logic in import-identity.ts); fw3 integration: A12/A13/A14 (+27) and #5675 (+4) compose; +17 wave-2 W4: safe-chunk re-seal of unchanged legacy markdown/code pages (#5050 #5247) and embedding-input provenance on inline imports (#5553); -1 fix wave 2 (v0.60.5.0) integration: W4 delta re-summed over the merged master line count; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +16 at the merge; +11 #4616: markdown and code imports keep the usable vectors of a partially refused batch and leave refused chunks for embed --stale; lowered to 2230: #5621 contextual-mode resolution peeled to core/import-contextual-mode.ts (shared with gbrain repair contextual-mode); +2 wave 8 lane D1 #5158: key-order fallback equality call (comparison lives in page-state/import-guard.ts); +1 F1c: direct imports run in maintenanceTransaction (write attribution; helper in persistence/attribution.ts); lowered to 2178: #5988 content screen and content-sanity config peeled to core/import-screen.ts
src/core/migrate.ts 602 ratchet schema-migration runner only; migrations live in src/core/schema-migrations/ (W3); +3 #5216: resumable page revision backfill runs after every migration pass while pages.knowledge_revision is nullable
src/core/operations.ts 336 ratchet peel target: containment sprint C4-C7; grown v0.46.26.0 megawave op wiring; +chat-connectors wiring (master merge); +5 v0.47 gmail-loops: loopsOperations spread + OP_AREAS; #5105: receipt operation registry wiring; shared-skills integration on company-ingestion base; +2 security wave: withOutputRedaction applied at op registration; +1 #5616: pageEditOperations import (spread shares the pages line); +1 Foundations 1 F1b: attributionOperations import (spread shares the admin line); +1 agent operator wave A6: ops/notices.ts import (mute_notice); +2 agent operator closeout A1: registerOpRoutes import + call (routing logic in fix-routing.ts)
src/core/pglite-engine.ts 2926 ratchet +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts)
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index 8505872e35..18bb96e9af 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -77,6 +77,7 @@ export const CODES = {
budget_unsatisfiable: { class: 'unavailable', summary: "Reserved by MEMORY_VERBS v1; never returned." },
cancelled: { class: 'caller', summary: "The write was cancelled before it committed." },
catalog_unavailable: { class: 'retryable', summary: "Shared skill storage is not ready on this brain." },
+ changed_since_preview: { class: 'caller', summary: "The file changed after its repair was previewed, so nothing was written.", why: "A repair writes exactly the bytes the operator approved; it binds approval to the previewed file hash and refuses when the file moved on.", suggestion: 'Preview the repair again, review the new proposal, and approve its new hash.' },
checkpoint_missing: { class: 'caller', summary: "The approved source plan is missing; do not restart from a different revision." },
checkpoint_validation_timeout: { class: 'retryable', summary: "Validating the managed-sync checkpoint timed out." },
claim_already_used: { class: 'caller', summary: "Google connect credential error: claim already used.", docs: 'docs/guides/google-connect.md#troubleshooting' },
@@ -98,6 +99,7 @@ export const CODES = {
connector_holds_exhausted: { class: 'caller', summary: "The source holds the maximum number of failed items; its cursor did not advance." },
connector_intent_outdated: { class: 'caller', summary: "The connector request no longer matches the stored connector intent." },
consent_timeout: { class: 'consent', summary: "Google connect credential error: consent timeout.", docs: 'docs/guides/google-connect.md#troubleshooting' },
+ content_rejected: { class: 'caller', summary: "The content-sanity gate rejected the content because the operator set `content_sanity.junk_disposition` to `reject`.", why: "A junk-pattern or operator-literal hit is refused instead of quarantined under that setting, so the page was not written. The same content refuses on every retry.", suggestion: 'Remove the matched junk from the file, or switch `content_sanity.junk_disposition` back to `quarantine` (a user decision), then import it again.' },
cost_cap_exceeded: { class: 'server', summary: "The run reached its cost cap before finishing." },
cost_preview_requires_yes: { class: 'consent', summary: "Cost preview requires yes." },
cycle_failed: { class: 'server', summary: "The maintenance (dream) cycle failed, or a phase threw and was contained so later phases could run." },
@@ -129,6 +131,8 @@ export const CODES = {
facts_absorb_write_refused: { class: 'caller', summary: "Facts absorb refused the write." },
facts_payload_expired: { class: 'server', summary: "The accepted fact extraction failed and its retained payload has expired." },
fetch_failed: { class: 'retryable', summary: "Fetching the upstream failed." },
+ file_too_large: { class: 'caller', summary: "The file is over the import size limit (5 MB for Markdown and code, 10 MiB for any sync read), so it was not imported.", why: "Size limits bound parsing, chunking and embedding cost. The same bytes refuse on every retry.", suggestion: 'Split the file into smaller files, or leave it out of the source (sync.exclude), then sync or import again.' },
+ frontmatter_slug_conflict: { class: 'caller', summary: "The file's frontmatter `slug:` names a different page than its path does.", why: "The path decides a file's page; a conflicting declared slug would overwrite or fork another page, so the file is refused until one of them changes.", suggestion: 'Remove the `slug:` line or make it match the path, then commit and sync again.' },
full_resync_required: { class: 'retryable', summary: "The catalog cursor is invalid or expired." },
gate_failed: { class: 'caller', summary: "The eval gate found retrieval regressions or correctness below its thresholds." },
git_index_locked: { class: 'retryable', summary: "Another Git process holds the canonical checkout index lock." },
@@ -147,6 +151,7 @@ export const CODES = {
interrupted: { class: 'server', summary: "The operation was interrupted by a signal before it finished.", exit: 130 },
invalid_client: { class: 'caller', summary: "Google connect credential error: invalid client.", docs: 'docs/guides/google-connect.md#troubleshooting' },
invalid_connector_text: { class: 'caller', summary: "Invalid connector text." },
+ invalid_frontmatter: { class: 'caller', summary: "The file's YAML frontmatter cannot be read without guessing, so it was not imported.", why: "gbrain imports frontmatter it can read exactly (quoting an unquoted value at most). Guessing could store a wrong title, merge a duplicate, or read a protected key such as `visibility` as a broader value.", reasons: ['yaml_parse', 'needs_interpretation', 'ambiguous_identity_key', 'ambiguous_protected_key'], suggestion: 'Fix the named line in the file (one line per key, the whole value quoted), then commit and sync or import again.' },
invalid_grant_clock_skew: { class: 'caller', summary: "Google connect credential error: invalid grant clock skew.", docs: 'docs/guides/google-connect.md#troubleshooting' },
invalid_grant_revoked: { class: 'caller', summary: "Google connect credential error: invalid grant revoked.", docs: 'docs/guides/google-connect.md#troubleshooting' },
invalid_grant_testing_expiry: { class: 'caller', summary: "Google connect credential error: invalid grant testing expiry.", docs: 'docs/guides/google-connect.md#troubleshooting' },
@@ -186,6 +191,7 @@ export const CODES = {
page_identity_changed: { class: 'caller', summary: "The page was deleted or replaced while the operation ran.", fix: { argv: ['gbrain', 'get', '--source', '{source_id}', '--', '{slug}'], mcp: { tool: 'get_page', arguments: { slug: '{slug}', source_id: '{source_id}' } }, consent: [], actor: 'agent', why: "Shows which page holds the slug now and its revision; a new attempt needs a new request_id.", requires_exclusive: false } },
page_not_found: { class: 'caller', summary: "No page with that slug exists in the selected source.", legacy_error: 'page_identity_changed', fix: { argv: ['gbrain', 'get', '--source', '{source_id}', '--', '{slug}'], mcp: { tool: 'get_page', arguments: { slug: '{slug}', source_id: '{source_id}' } }, consent: [], actor: 'agent', why: "Confirms whether the page exists in this source before anything is recreated.", requires_exclusive: false } },
parse_error: { class: 'caller', summary: "The request body is not valid JSON." },
+ 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 `sync.parser_regression=hold` 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 with --retry-failed.' },
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." },
pending_writes: { class: 'retryable', summary: "A pending source write prevents verified completion." },
@@ -214,6 +220,7 @@ export const CODES = {
relay_disabled: { class: 'caller', summary: "Google connect credential error: relay disabled.", docs: 'docs/guides/google-connect.md#troubleshooting' },
relay_session_expired: { class: 'caller', summary: "Google connect credential error: relay session expired.", docs: 'docs/guides/google-connect.md#troubleshooting' },
relay_unreachable: { class: 'retryable', summary: "Google connect credential error: relay unreachable.", docs: 'docs/guides/google-connect.md#troubleshooting' },
+ rename_held: { class: 'caller', summary: "A renamed file is held because the page it was renamed from changed after the rename was recorded.", reasons: ['rename_source_changed'], why: "Moving the page now could carry the newer edit to the wrong file, so the rename waits for an explicit re-bind.", suggestion: 'Preview the frontmatter repair with --include-ambiguous to re-bind the rename to the current page, and approve it.' },
request_already_submitted: { class: 'caller', summary: "This optimizer publication request has already been submitted." },
request_too_large: { class: 'caller', summary: "The request exceeds a configured capacity; narrow it." },
requirements_changed: { class: 'caller', summary: "The runtime requirements exceed the owner-approved publication policy." },
@@ -248,6 +255,7 @@ export const CODES = {
storage_error: { class: 'server', summary: "Reading or writing durable storage failed." },
sync_not_applicable: { class: 'caller', summary: "Sync does not apply to this source: its directory is not a Git checkout.", why: "Sync imports changes between Git commits. A gbrain-owned content directory (created by init) holds files gbrain manages itself and is not a Git repository, so there is nothing to sync; gbrain never initializes Git on its own.", reasons: ['content_directory'] },
sync_in_progress: { class: 'retryable', summary: "A sync is running on this source." },
+ sync_parser_regression: { class: 'server', summary: "Sync stopped because gbrain would hold a file whose exact bytes imported before; this is a gbrain bug.", why: "The upgrade invariant says a newer reader never refuses bytes an older one imported, so the run stops without advancing rather than hide a regression.", suggestion: 'Report it with the gbrain version, the file and the code; upgrade or pin the last good version, then run gbrain sync --source <id> --no-pull --retry-failed.' },
take_row_collision: { class: 'caller', summary: "A takes fence row number is already used by a different take that is not in this page's canonical fence." },
target_escape: { class: 'caller', summary: "The skill target must remain within its selected root." },
timeout: { class: 'retryable', summary: "The operation did not finish within its time bound.", exit: 124 },
diff --git a/src/core/import-file.ts b/src/core/import-file.ts
index 009416e134..f7b09011ba 100644
--- a/src/core/import-file.ts
+++ b/src/core/import-file.ts
@@ -8,7 +8,8 @@ import { readFileSync, statSync, lstatSync } from 'fs';
import { basename, extname, resolve } from 'path';
import { createHash } from 'crypto';
import type { BrainEngine, FileSpec } from './engine.ts';
-import { parseMarkdown, resolveParsedSubtype, type ParseOpts } from './markdown.ts';
+import { classifyImportHold, parseMarkdown, resolveParsedSubtype, type ParseOpts, type ParsedMarkdown } from './markdown.ts';
+import { assessImportSanity, loadImportSanityConfig, MAX_FILE_SIZE, screenImportContent, type ContentRefusal } from './import-screen.ts';
import { classifyStoredType } from './schema-pack/type-usage.ts';
import { prepareMarkdownChunks } from './markdown-chunks.ts';
import { prepareCodeChunks, installCodeChunkEdges } from './code-chunks.ts';
@@ -34,8 +35,7 @@ import type { ChunkInput, Page, PageInput, PageType } from './types.ts';
import { computeEffectiveDate, fallbackCreatedAt, isValidTimeZone } from './effective-date.ts';
import { MARKDOWN_CHUNKER_VERSION } from './chunkers/recursive.ts';
import { logSlugFallback } from './audit-slug-fallback.ts';
-import { assessContentSanity, ContentSanityBlockError } from './content-sanity.ts';
-import { loadOperatorLiterals } from './content-sanity-literals.ts';
+import { ContentSanityBlockError } from './content-sanity.ts';
import { logContentSanityAssessment } from './audit/content-sanity-audit.ts';
import { buildEmbedSkipMarker, EMBED_SKIP_KEY } from './embed-skip.ts';
import {
@@ -44,7 +44,6 @@ import {
buildQuarantineMarker,
buildContentFlagMarker,
} from './quarantine.ts';
-import { loadConfig, loadConfigWithEngine } from './config.ts';
import {
buildContextualPrefix,
modeRequiresSynopsis,
@@ -161,16 +160,14 @@ export interface ImportResult {
/** True when the text committed but the embedding provider failed; the
* chunks carry NULL vectors until the stale sweep embeds them. */
embedding_deferred?: boolean;
+ /** #5988: the typed content refusal behind `error`, for callers that refuse with its code. */
+ refusal?: ContentRefusal;
}
-export const MAX_FILE_SIZE = 5_000_000; // 5MB
+export { MAX_FILE_SIZE };
-function invalidYamlFrontmatterError(parsed: ReturnType<typeof parseMarkdown>): string | null {
- const yamlError = parsed.errors?.find((error) => error.code === 'YAML_PARSE');
- if (!yamlError) return null;
- const detail = yamlError.message.replace(/^YAML parse failed:\s*/, '').trim();
- return `Invalid YAML frontmatter: ${detail}. Quote scalar values that contain ": " or fix the frontmatter block.`;
-}
+/** #5988: the frontmatter hold text for a validated parse (location only), or null when it imports. */
+const invalidYamlFrontmatterError = (parsed: ParsedMarkdown): string | null => classifyImportHold(parsed)?.message ?? null;
/**
* #4588: refresh `pages.source_path` on the import SKIP path. A row whose slug
@@ -321,23 +318,11 @@ export async function importFromContent(
// Reject oversized payloads before any parsing, chunking, or embedding happens.
// Uses Buffer.byteLength to count UTF-8 bytes the same way disk size would,
// so the network path behaves identically to the file path.
- const byteLength = Buffer.byteLength(content, 'utf-8');
- if (byteLength > MAX_FILE_SIZE) {
- return {
- slug,
- status: 'skipped',
- chunks: 0,
- error: `Content too large (${byteLength} bytes, max ${MAX_FILE_SIZE}). Split the content into smaller files or remove large embedded assets.`,
- };
- }
- const parsed = parseMarkdown(content, slug + '.md', {
- validate: true,
- ...(opts.activePack ? { activePack: opts.activePack } : {}),
- });
- const frontmatterError = invalidYamlFrontmatterError(parsed);
- if (frontmatterError) {
- return { slug, status: 'error', chunks: 0, error: frontmatterError };
+ const screen = screenImportContent({ content, path: slug + '.md', ...(opts.activePack ? { activePack: opts.activePack } : {}) });
+ if (screen.status === 'refused') {
+ return { slug, status: screen.refusal.code === 'file_too_large' ? 'skipped' : 'error', chunks: 0, error: screen.refusal.message, refusal: screen.refusal };
}
+ const parsed = (screen as { parsed: ParsedMarkdown }).parsed;
if (!opts.prepare) await assertUnmanagedCanonicalWriter(engine, 'direct content import');
// Canonicalize only free-prose fields before protected-fence parsing, hidden
// row merging, hashing and indexing. Frontmatter identities stay untouched.
@@ -418,52 +403,12 @@ export async function importFromContent(
let pageFlagged = false;
let pageFlagReason: 'markup_heavy' | 'oversized' | undefined;
{
- const baseCfg = loadConfig();
- let effectiveCfg = baseCfg;
- try {
- // loadConfigWithEngine merges DB-plane content_sanity.* on top
- // of file/env. Wrapped in try/catch so a transient engine error
- // doesn't kill the import — the gate falls back to file/env
- // values (which include defaults via the assessor itself).
- effectiveCfg = await loadConfigWithEngine(engine, baseCfg);
- } catch (err) {
- const msg = err instanceof Error ? err.message : String(err);
- process.stderr.write(`[gbrain] content-sanity: DB config lift failed (${msg}); falling back to file/env\n`);
- }
- const cs = effectiveCfg?.content_sanity ?? {};
- // GBRAIN_NO_SANITY=1 fast-path: loadConfig() returns null when
- // there's no `~/.gbrain/config.json` AND no DATABASE_URL env var
- // (e.g., fresh PGLite-only setups, hermetic tests). The merged
- // content_sanity block never carries `disabled` in that case. Read
- // the kill-switch env directly so it works regardless of whether
- // any other config plumbing fired. Same direct-env-check pattern
- // applies to the patterns_enabled flip below.
- const sanityDisabled =
- cs.disabled === true || process.env.GBRAIN_NO_SANITY === '1';
- const extra_literals =
- cs.junk_patterns_enabled !== false && !sanityDisabled ? loadOperatorLiterals() : [];
+ const sanityCfg = await loadImportSanityConfig(engine);
+ const sanityDisabled = sanityCfg.disabled;
// Disposition for the high-confidence junk path: quarantine (hide) by
// default, or reject (throw → sync-failure) when the operator opts in.
- const junkDisposition: 'quarantine' | 'reject' =
- cs.junk_disposition === 'reject' ? 'reject' : 'quarantine';
- const sanityResult = assessContentSanity({
- compiled_truth: parsed.compiled_truth,
- timeline: parsed.timeline ?? '',
- title: parsed.title,
- bytes_warn: cs.bytes_warn,
- bytes_block: cs.bytes_block,
- max_markup_ratio: cs.max_markup_ratio,
- prose_check_enabled: cs.prose_check_enabled,
- page_kind: parsed.type,
- extra_literals,
- // #4702 `content_sanity.disabled_patterns`: turn off individual
- // built-in junk patterns without junk_patterns_enabled (all patterns)
- // or the kill-switch (which also drops the size gates). Defensive
- // Array.isArray: the file plane is hand-edited JSON.
- disabled_patterns: Array.isArray(cs.disabled_patterns)
- ? cs.disabled_patterns
- : undefined,
- });
+ const junkDisposition = sanityCfg.junkDisposition;
+ const sanityResult = assessImportSanity(parsed, sanityCfg);
if (sanityDisabled) {
// Kill-switch active: loud stderr per offending ingest. Operator
diff --git a/src/core/import-screen.ts b/src/core/import-screen.ts
new file mode 100644
index 0000000000..13bf9dbbaf
--- /dev/null
+++ b/src/core/import-screen.ts
@@ -0,0 +1,179 @@
+/**
+ * #5988: the one content screen every ingestion path shares. It decides,
+ * without preparing or writing anything, whether content is importable or a
+ * deterministic content refusal (size, unreadable or ambiguous frontmatter,
+ * a frontmatter slug that names another page, a content-sanity reject).
+ * Managed sync freezes, managed sync and import publication, and
+ * `importFromContent` (put_page, capture, legacy import) all call it, so a
+ * file is held or refused for the same reason everywhere.
+ */
+import type { BrainEngine } from './engine.ts';
+import { loadConfig, loadConfigWithEngine } from './config.ts';
+import { assessContentSanity, type ContentSanityResult } from './content-sanity.ts';
+import { loadOperatorLiterals } from './content-sanity-literals.ts';
+import { classifyImportHold, contentSizeHold, parseMarkdown, type ContentHold, type ParseOpts, type ParsedMarkdown } from './markdown.ts';
+import { isCodeFilePath } from './sync.ts';
+import { opError, type OperationError } from './ops/contract.ts';
+import type { Action } from './agent-output.ts';
+
+export const MAX_FILE_SIZE = 5_000_000; // 5MB
+
+type ContentSanityConfig = NonNullable<NonNullable<ReturnType<typeof loadConfig>>['content_sanity']>;
+
+export interface ImportSanityConfig {
+ cs: ContentSanityConfig;
+ disabled: boolean;
+ extraLiterals: ReturnType<typeof loadOperatorLiterals>;
+ junkDisposition: 'quarantine' | 'reject';
+}
+
+/**
+ * Effective content-sanity config: env > file > DB > defaults. A transient
+ * engine error falls back to file/env values. `GBRAIN_NO_SANITY=1` is read
+ * directly because loadConfig() is null on config-less PGLite setups.
+ */
+export async function loadImportSanityConfig(engine: BrainEngine): Promise<ImportSanityConfig> {
+ const baseCfg = loadConfig();
+ let effectiveCfg = baseCfg;
+ try {
+ effectiveCfg = await loadConfigWithEngine(engine, baseCfg);
+ } catch (err) {
+ const msg = err instanceof Error ? err.message : String(err);
+ process.stderr.write(`[gbrain] content-sanity: DB config lift failed (${msg}); falling back to file/env\n`);
+ }
+ const cs = effectiveCfg?.content_sanity ?? {};
+ const disabled = cs.disabled === true || process.env.GBRAIN_NO_SANITY === '1';
+ return {
+ cs, disabled,
+ extraLiterals: cs.junk_patterns_enabled !== false && !disabled ? loadOperatorLiterals() : [],
+ junkDisposition: cs.junk_disposition === 'reject' ? 'reject' : 'quarantine',
+ };
+}
+
+export function assessImportSanity(page: Pick<ParsedMarkdown, 'compiled_truth' | 'timeline' | 'title' | 'type'>, cfg: ImportSanityConfig): ContentSanityResult {
+ return assessContentSanity({
+ compiled_truth: page.compiled_truth,
+ timeline: page.timeline ?? '',
+ title: page.title,
+ bytes_warn: cfg.cs.bytes_warn,
+ bytes_block: cfg.cs.bytes_block,
+ max_markup_ratio: cfg.cs.max_markup_ratio,
+ prose_check_enabled: cfg.cs.prose_check_enabled,
+ page_kind: page.type,
+ extra_literals: cfg.extraLiterals,
+ // #4702: the file plane is hand-edited JSON.
+ disabled_patterns: Array.isArray(cfg.cs.disabled_patterns) ? cfg.cs.disabled_patterns : undefined,
+ });
+}
+
+/** A refusal the screen returns: a hold code, or `content_rejected` for an operator-configured sanity reject. */
+export interface ContentRefusal extends Omit<ContentHold, 'code'> {
+ code: ContentHold['code'] | 'content_rejected';
+}
+
+export interface ImportScreenInput {
+ /** The decoded text exactly as it would be imported. */
+ content: string;
+ /** Filename for parsing; it also decides code vs Markdown. */
+ path: string;
+ /** Raw byte length when the bytes differ from the UTF-8 encoding of `content`. */
+ byteLength?: number;
+ expectedSlug?: string | null;
+ slugExempt?: (declared: string) => boolean;
+ slugConflictMessage?: (found: string, expected: string) => string;
+ activePack?: ParseOpts['activePack'];
+ /**
+ * The working tree already holds bytes whose import equals the current
+ * page (a repaired file published but not yet committed). Checked before
+ * any content refusal, so such a file is never refused or held.
+ */
+ published?: () => boolean;
+ /** Pre-loaded config: a junk hit under `junk_disposition: reject` refuses as `content_rejected`. */
+ sanity?: ImportSanityConfig;
+}
+
+export type ImportScreenResult =
+ | { status: 'published' }
+ | { status: 'importable'; parsed: ParsedMarkdown | null }
+ | { status: 'refused'; refusal: ContentRefusal };
+
+export function screenImportContent(input: ImportScreenInput): ImportScreenResult {
+ if (input.published?.()) return { status: 'published' };
+ const codeFile = isCodeFilePath(input.path);
+ const size = contentSizeHold(input.byteLength ?? Buffer.byteLength(input.content, 'utf-8'), MAX_FILE_SIZE, codeFile);
+ if (size) return { status: 'refused', refusal: size };
+ if (codeFile) return { status: 'importable', parsed: null };
+ const parsed = parseMarkdown(input.content, input.path, { validate: true, ...(input.activePack ? { activePack: input.activePack } : {}) });
+ const hold = classifyImportHold(parsed, { expectedSlug: input.expectedSlug, slugExempt: input.slugExempt, slugConflictMessage: input.slugConflictMessage });
+ if (hold) return { status: 'refused', refusal: hold };
+ if (input.sanity && !input.sanity.disabled && input.sanity.junkDisposition === 'reject') {
+ const result = assessImportSanity(parsed, input.sanity);
+ if (result.shouldQuarantine) return { status: 'refused', refusal: { code: 'content_rejected', message: `Content rejected by sanity gate: ${result.reason_messages.join('; ')}` } };
+ }
+ return { status: 'importable', parsed };
+}
+
+/**
+ * The typed refusal a publication path throws. `legacy_error` keeps the wire
+ * `error` the site always returned, so stored receipts keep matching
+ * `isContentRefusal`. `detail` names the key and line, never a value.
+ */
+export function contentRefusalError(refusal: ContentRefusal, suggestion: string, opts: { legacy_error?: string; fix?: Action } = {}): OperationError {
+ const where = [refusal.key ? `key ${refusal.key}` : '', refusal.line !== undefined ? `line ${refusal.line}` : ''].filter(Boolean).join(', ');
+ return opError(refusal.code, refusal.message, suggestion, {
+ ...(refusal.reason ? { reason: refusal.reason } : {}), ...(where ? { detail: where } : {}), ...opts,
+ });
+}
+
+/**
+ * A stored receipt only keeps the wire code and message. Recover the typed
+ * refusal from them (the message names the cause, key and line), so a
+ * replayed or awaited write reports the same code, reason and next step.
+ */
+export function contentRefusalFromReceipt(code: string | null | undefined, message: string | null | undefined): (Omit<ContentRefusal, 'message'> & { suggestion: string }) | null {
+ if (!isContentRefusal(code, message)) return null;
+ const text = message ?? '';
+ const key = /key "([^"\n]{1,200})"/.exec(text)?.[1];
+ const lineText = /\bat line (\d+)/.exec(text)?.[1];
+ const line = lineText === undefined ? undefined : Number(lineText);
+ const typed = CONTENT_REFUSAL_CODES.has(code!) ? code as ContentRefusal['code']
+ : /^Invalid YAML frontmatter/.test(text) ? 'invalid_frontmatter'
+ : /slug/.test(text) ? 'frontmatter_slug_conflict'
+ : /PAGE_JUNK_PATTERN/.test(text) ? 'content_rejected' : 'file_too_large';
+ const reason = typed !== 'invalid_frontmatter' ? undefined
+ : /ambiguous protected key/.test(text) ? 'ambiguous_protected_key' as const
+ : /ambiguous identity key/.test(text) ? 'ambiguous_identity_key' as const
+ : /continues on unquoted lines|appears more than once|opens \[ or \{/.test(text) ? 'needs_interpretation' as const : 'yaml_parse' as const;
+ const where = line !== undefined ? `frontmatter line ${line}${key ? ` (key "${key}")` : ''}` : 'the frontmatter';
+ const suggestion = typed === 'invalid_frontmatter' ? `The content itself was refused, so resubmitting it unchanged refuses again. Correct ${where}: one line per key with its whole value quoted, then submit the corrected content with a new request_id.`
+ : typed === 'frontmatter_slug_conflict' ? 'The content declares a slug that conflicts with its path. Remove the `slug:` line or make it match, then submit with a new request_id.'
+ : typed === 'content_rejected' ? 'The content-sanity gate rejects this content under the operator\'s junk_disposition=reject setting. Remove the matched junk, then submit with a new request_id.'
+ : 'The content is over the import size limit. Split it into smaller pages, then submit each with its own request_id.';
+ return { code: typed, ...(reason ? { reason } : {}), ...(key ? { key } : {}), ...(line !== undefined ? { line } : {}), suggestion };
+}
+
+const CONTENT_REFUSAL_CODES = new Set(['invalid_frontmatter', 'frontmatter_slug_conflict', 'file_too_large', 'content_rejected']);
+const LEGACY_CONTENT_MESSAGES: Array<[code: string, pattern: RegExp]> = [
+ ['invalid_params', /^Invalid YAML frontmatter(?::| at line \d| in )/],
+ ['invalid_params', /^The frontmatter slug "[^"\n]*" in [^\n]+ conflicts with its path, which expects slug "[^"\n]*"\./],
+ ['invalid_params', /^Frontmatter slug "[^"\n]*" does not match path-derived slug "[^"\n]*"/],
+ ['invalid_params', /^Content too large \(\d+ bytes, max \d+\)/],
+ ['invalid_params', /^File too large \(/],
+ ['invalid_params', /^Code file too large \(\d+ bytes\)/],
+ ['request_too_large', /^Sync file exceeds the bounded import size\.$/],
+ ['storage_error', /^Publication failed \(PAGE_JUNK_PATTERN\)\. Inspect owner diagnostics\.$/],
+];
+
+/**
+ * True when a stored refusal (receipt `error_code` + `error_message`) is a
+ * deterministic content refusal no retry can fix: the new typed codes, and
+ * the exact strings older gbrain versions stored for the same causes.
+ * Cursor-size and admission-capacity `request_too_large`, and every transient
+ * or conflict code, never match.
+ */
+export function isContentRefusal(code: string | null | undefined, message: string | null | undefined): boolean {
+ if (!code) return false;
+ if (CONTENT_REFUSAL_CODES.has(code)) return true;
+ const text = message ?? '';
+ return LEGACY_CONTENT_MESSAGES.some(([legacy, pattern]) => legacy === code && pattern.test(text));
+}
diff --git a/src/core/persistence/import-prepare.ts b/src/core/persistence/import-prepare.ts
index 10da646aca..9579426324 100644
--- a/src/core/persistence/import-prepare.ts
+++ b/src/core/persistence/import-prepare.ts
@@ -9,7 +9,7 @@ import { applyInference } from '../frontmatter-inference.ts';
import { getCompanyBrainProfile } from '../company-brain/profile.ts';
import { hasMalformedPathSegment, isCodeFilePath, slugifyCodePath, slugifyPath } from '../sync.ts';
import { OperationError, opError } from '../ops/contract.ts';
-import { yamlLocator } from './page-identity.ts';
+import { contentRefusalError, screenImportContent, type ContentRefusal } from '../import-screen.ts';
import { isWriteTargetContained } from '../path-confine.ts';
import { assertPageRevision } from '../page-state/types.ts';
import { sealPageTextProjection } from '../page-state/projections.ts';
@@ -52,6 +52,16 @@ export function readImportBytes(path: string): Buffer {
return readFileSync(path);
}
+/** #5988: the typed import refusal; the wire `error` stays `invalid_params` as before. */
+function managedImportRefusal(refusal: ContentRefusal, sourcePath: string): OperationError {
+ const suggestion = refusal.code === 'frontmatter_slug_conflict'
+ ? `In ${sourcePath}, remove the frontmatter slug or set it to the path-derived slug (the path decides the slug), or move the file to the path that matches its slug, then import again.`
+ : refusal.code === 'file_too_large' ? `${sourcePath} is over the import size limit and was not imported. Split it into smaller files or leave it out of the import.`
+ : refusal.code === 'content_rejected' ? `Remove the matched junk from ${sourcePath}, then import it again.`
+ : `Fix line ${refusal.line ?? '?'} of ${sourcePath}${refusal.key ? ` (key "${refusal.key}")` : ''}: one line per key with its whole value quoted. Run gbrain frontmatter validate on the file to see every problem, then import it again.`;
+ return contentRefusalError(refusal, suggestion, { legacy_error: 'invalid_params' });
+}
+
export function managedImportContent(sourcePath: string, bytes: Buffer, activePack?: ImportPack): { slug: string; content: string } {
if (isAbsolute(sourcePath) || sourcePath.split(/[\\/]/).some(part => part === '..') || hasMalformedPathSegment(sourcePath)) {
throw opError('invalid_params', 'The import path must be a well-formed source-relative path.',
@@ -66,19 +76,12 @@ export function managedImportContent(sourcePath: string, bytes: Buffer, activePa
if (isCodeFilePath(sourcePath)) return { slug: slugifyCodePath(sourcePath), content };
if (!/\.mdx?$/i.test(sourcePath)) throw opError('invalid_params', 'Managed import supports Markdown, code and supported image files.',
`${sourcePath} is not a Markdown (.md, .mdx), code or supported image file, so it was not imported. Convert it to Markdown or leave it out.`);
- const original = parseMarkdown(content, sourcePath, { validate: true });
- const invalid = original.errors?.find(error => error.code === 'YAML_PARSE');
- if (invalid) {
- throw opError('invalid_params', `Invalid YAML frontmatter${yamlLocator(invalid.message)} in ${sourcePath}.`,
- `Quote frontmatter values that contain ": " or start with a special character in ${sourcePath}, then run the import again.`);
- }
+ const screen = screenImportContent({ content, path: sourcePath, byteLength: bytes.length, expectedSlug: slugifyPath(sourcePath),
+ slugConflictMessage: (found, expected) => `Frontmatter slug "${found}" does not match path-derived slug "${expected}".` });
+ if (screen.status === 'refused') throw managedImportRefusal(screen.refusal, sourcePath);
content = applyInference(sourcePath, content).content;
- const parsed = parseMarkdown(content, sourcePath, { validate: true, ...(activePack ? { activePack } : {}) });
+ const parsed = parseMarkdown(content, sourcePath, { ...(activePack ? { activePack } : {}) });
const expected = slugifyPath(sourcePath);
- if (expected && parsed.slug !== expected && slugifyPath(parsed.slug) !== expected) {
- throw opError('invalid_params', `Frontmatter slug "${parsed.slug}" does not match path-derived slug "${expected}".`,
- `In ${sourcePath}, set the frontmatter slug to "${expected}" or remove it (the path decides the slug), or move the file to the path that matches "${parsed.slug}", then import again.`);
- }
const slug = parsed.slug || expected;
if (!slug) throw opError('invalid_params', 'The filename produces no usable slug; add a slug in frontmatter.',
`Rename ${sourcePath} to a name with letters or digits, or add a slug: line to its frontmatter, then import again.`);
diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.ts
index 74f3fd9e26..354120ce73 100644
--- a/src/core/persistence/page-prepare.ts
+++ b/src/core/persistence/page-prepare.ts
@@ -11,7 +11,9 @@ import { OperationError, opError } from '../ops/contract.ts';
import { readFix } from '../ops/op-fix.ts';
import type { Action } from '../agent-output.ts';
import type { RegistryCode } from '../error-registry.ts';
-import { pageIdentityError, yamlLocator } from './page-identity.ts';
+import { pageIdentityError } from './page-identity.ts';
+import { contentRefusalError } from '../import-screen.ts';
+import { ContentSanityBlockError } from '../content-sanity.ts';
import { assertPageRevision, type PageSnapshot } from '../page-state/types.ts';
import { isWriteTargetContained } from '../path-confine.ts';
import { recordedPathFromFileUri, scannerSlugRootMode, scannerSourcePath } from '../write-through.ts';
@@ -300,17 +302,18 @@ export async function preparePageMutation(engine: BrainEngine, row: WriteRequest
ingested_via: typeof p.ingested_via === 'string' ? p.ingested_via : null,
prepareFrontmatter: page => { provenance = putProvenance(row, snapshot, page); },
prepare: async value => { prepared = value; return value.result; },
+ }).catch(error => {
+ if (!(error instanceof ContentSanityBlockError)) throw error;
+ throw contentRefusalError({ code: 'content_rejected', message: error.message },
+ 'The operator set content_sanity.junk_disposition to reject, so this content refuses on every retry. Remove the matched junk and submit the corrected content with a new request_id.');
});
signal?.throwIfAborted();
if (!prepared) {
- const oversized = result.error?.startsWith('Content too large') === true;
- const yaml = !oversized && /yaml/i.test(result.error ?? '');
- throw opError(oversized ? 'request_too_large' : 'invalid_params', oversized ? result.error!
- : yaml ? `Invalid YAML frontmatter${yamlLocator(result.error)}. Quote scalar values or fix the frontmatter block.`
- : 'The content was rejected before publication.',
- oversized ? 'Split the content into smaller pages, then submit each with its own request_id.'
- : yaml ? 'Quote frontmatter values that contain ": " or start with a special character, then submit the corrected content with a new request_id.'
- : 'Check the content and frontmatter, then submit the corrected content with a new request_id.');
+ const refusal = result.refusal;
+ if (refusal?.code === 'file_too_large') throw contentRefusalError(refusal, 'Split the content into smaller pages, then submit each with its own request_id.', { legacy_error: 'request_too_large' });
+ if (refusal) throw contentRefusalError(refusal, `Correct ${refusal.line !== undefined ? `frontmatter line ${refusal.line}${refusal.key ? ` (key "${refusal.key}")` : ''}` : 'the frontmatter'}: one line per key with its whole value quoted, then submit the corrected content with a new request_id.`,
+ { legacy_error: 'invalid_params' });
+ throw opError('invalid_params', 'The content was rejected before publication.', 'Check the content and frontmatter, then submit the corrected content with a new request_id.');
}
const ready = prepared;
if (ready.observedRevision !== observedRevision) throw pageRefusal('revision_conflict', 'The page changed during import preparation.', row,
diff --git a/src/core/persistence/service.ts b/src/core/persistence/service.ts
index 56a320794d..779e824f19 100644
--- a/src/core/persistence/service.ts
+++ b/src/core/persistence/service.ts
@@ -11,6 +11,7 @@ import { registerPgliteReopen } from '../pglite-lifecycle.ts';
import { assertMutationProtocol } from './protocol.ts';
import { pendingWriteHint } from './health.ts';
import { receiptDeliveredHint } from './connector-errors.ts';
+import { contentRefusalFromReceipt } from '../import-screen.ts';
import { isMissingPageMessage } from './page-identity.ts';
interface Service { consumer: PersistenceConsumer; stopping: boolean; unregisterStop?: () => void; unregisterReopen?: () => void; }
@@ -152,11 +153,18 @@ export function writeResponse(row: WriteRequest): Record<string, unknown> {
if (row.state === 'committed') return { ...receipt, write_request: receipt };
const reason = !isTerminal(row) ? 'write_pending' : row.error_code ?? (row.state === 'cancelled' ? 'cancelled' : 'storage_error');
const delivered = isTerminal(row) ? receiptDeliveredHint(row) : null;
+ // #5988: a content refusal reports its typed code, reason, key and line, and the content fix.
+ const content = isTerminal(row) ? contentRefusalFromReceipt(row.error_code, row.error_message) : null;
const error = new OperationError(reason, !isTerminal(row) ? 'The write is accepted and is still pending.'
: row.error_message ?? 'The write did not commit.', !isTerminal(row)
? pendingWriteHint(receipt)
- : delivered?.suggestion ?? terminalReceiptHint(row, reason), delivered?.docs);
+ : delivered?.suggestion ?? content?.suggestion ?? terminalReceiptHint(row, reason), delivered?.docs);
if (delivered?.detail) error.detail = delivered.detail;
+ if (content) {
+ if (content.code !== reason) error.canonical = content.code;
+ if (content.reason) error.reason = content.reason;
+ if (content.key || content.line !== undefined) error.detail = [content.key ? `key ${content.key}` : '', content.line !== undefined ? `line ${content.line}` : ''].filter(Boolean).join(', ');
+ }
if (reason === 'page_identity_changed' && isMissingPageMessage(row.error_message)) error.canonical = 'page_not_found';
error.receiptFields = { operation: row.operation, source_id: row.source_id, slug: row.slug || null, principal_kind: row.principal_kind, principal_id: row.principal_id };
error.writeRequest = receipt as WriteReceipt;
diff --git a/src/core/persistence/sync-prepare.ts b/src/core/persistence/sync-prepare.ts
index 91bb8754f3..1ec0abbed1 100644
--- a/src/core/persistence/sync-prepare.ts
+++ b/src/core/persistence/sync-prepare.ts
@@ -3,10 +3,12 @@ import { basename, join } from 'node:path';
import type { BrainEngine } from '../engine.ts';
import type { GBrainConfig } from '../config.ts';
import type { Page } from '../types.ts';
-import { OperationError, opError } from '../ops/contract.ts';
+import { OperationError, opError, type OpErrorOpts } from '../ops/contract.ts';
import type { Action } from '../agent-output.ts';
import type { RegistryCode } from '../error-registry.ts';
import { importFromContent, importCodeFile } from '../import-file.ts';
+import { screenImportContent, type ContentRefusal } from '../import-screen.ts';
+import { ContentSanityBlockError } from '../content-sanity.ts';
import { parseMarkdown, resolveParsedSubtype, serializePageToMarkdown } from '../markdown.ts';
import { resolveSlugForPath, slugifyPath, isCodeFilePath } from '../sync.ts';
import { SOURCE_CONFIG_OBJECT_SQL } from '../source-config-sql.ts';
@@ -72,11 +74,29 @@ function syncInspectFix(row: WriteRequest, requestId: string, owner: boolean): A
* keeps only code and message, so the suggestion stands alone: inspect the
* request, then rerun the exact failed-run command once the cause is fixed.
*/
-function syncPublicationRefusal(code: RegistryCode, message: string, row: WriteRequest, p: SyncIntent | null, cause: string, inspectOwner = false): OperationError {
+function syncPublicationRefusal(code: RegistryCode, message: string, row: WriteRequest, p: SyncIntent | null, cause: string, inspectOwner = false, extra: OpErrorOpts = {}): OperationError {
const fix = syncInspectFix(row, row.request_id, inspectOwner);
const rerun = checkpointRetryCommand({ sourceId: row.source_id, processingOptions: p?.processingOptions, syncOptions: p?.syncOptions, repoPath: p?.repoPath });
return opError(code, message, `${cause} Request ${row.request_id} in ${row.source_id} was refused; inspect it first (${fix.argv!.join(' ')}) and do not resubmit it. `
- + `Once it is final and the cause is fixed, run: ${rerun}`, { fix });
+ + `Once it is final and the cause is fixed, run: ${rerun}`, { fix, ...extra });
+}
+
+/**
+ * #5988: a deterministic content refusal at publication. The wire `error`
+ * stays `invalid_params` (what older receipts stored), so the stored code and
+ * message keep matching `isContentRefusal`; `code` is the typed one.
+ */
+function syncContentRefusal(refusal: ContentRefusal, row: WriteRequest, p: SyncIntent): OperationError {
+ const where = refusal.line !== undefined ? `line ${refusal.line}${refusal.key ? ` (key "${refusal.key}")` : ''} of ${p.sourcePath}` : p.sourcePath;
+ const cause = refusal.code === 'frontmatter_slug_conflict' ? 'Correct the frontmatter `slug:` in the file and commit the change.'
+ : refusal.code === 'file_too_large' ? `${p.sourcePath} is over the import size limit; split it into smaller files or add it to sync.exclude, then commit.`
+ : refusal.code === 'content_rejected' ? `The content-sanity gate rejects ${p.sourcePath} under junk_disposition=reject; remove the matched junk and commit.`
+ : `Fix ${where} (one line per key, the whole value quoted) and commit the change; gbrain frontmatter validate on the file lists every problem.`;
+ return syncPublicationRefusal(refusal.code, refusal.message, row, p, cause, false, {
+ ...(refusal.code === 'content_rejected' ? {} : { legacy_error: 'invalid_params' }),
+ ...(refusal.reason ? { reason: refusal.reason } : {}),
+ ...(refusal.key || refusal.line !== undefined ? { detail: [refusal.key ? `key ${refusal.key}` : '', refusal.line !== undefined ? `line ${refusal.line}` : ''].filter(Boolean).join(', ') } : {}),
+ });
}
export async function prepareManagedSyncMutation(engine: BrainEngine, row: WriteRequest, _config: GBrainConfig): Promise<PreparedMutation> {
@@ -225,6 +245,8 @@ export async function prepareManagedSyncMutation(engine: BrainEngine, row: Write
throw syncPublicationRefusal('source_changed', 'Newer code file bytes disagree with the pinned import.', row, p,
`The working tree holds newer bytes for ${row.slug} than the pinned import; sync did not overwrite them. Preserve the local edit and commit it.`);
}
+ const codeScreen = screenImportContent({ content: p.content, path: p.sourcePath });
+ if (codeScreen.status === 'refused') throw syncContentRefusal(codeScreen.refusal, row, p);
let prepared: PreparedContentImport | undefined;
const result = await importCodeFile(engine, p.sourcePath, p.content, { ...source, noEmbed: true,
prepare: async value => { prepared = value; return value.result; } });
@@ -257,27 +279,27 @@ export async function prepareManagedSyncMutation(engine: BrainEngine, row: Write
// row.slug is already resolved; parseMarkdown expects a filename, as in importFromContent.
const parsedInput = parseMarkdown(p.content, `${row.slug}.md`, { activePack });
resolveParsedSubtype(parsedInput, base?.page);
- const expectedSlug = resolveSlugForPath(p.sourcePath);
- const retainedRecordedOrigin = snapshot?.page.source_path != null &&
- syncOriginPath(snapshot.page.source_path) === syncOriginPath(p.sourcePath) && parsedInput.slug === snapshot.page.slug;
- if (expectedSlug && parsedInput.slug !== expectedSlug && slugifyPath(parsedInput.slug) !== expectedSlug && !retainedRecordedOrigin) {
- throw syncPublicationRefusal('invalid_params', frontmatterSlugConflictMessage(p.sourcePath, parsedInput.slug, expectedSlug), row, p,
- 'Correct the frontmatter `slug:` in the file and commit the change.');
- }
- if (!p.companyApproval && base && !p.lineEndingOnly && p.rawHash !== sha256(p.content) && !sameCanonicalImport(base, parsedInput)) {
- // The pinned commit can simply trail the coordinator: a committed page write reaches the
- // working tree before its Git effect lands. When the newer working-tree bytes are the
- // current page itself, there is nothing to import and nothing to protect; the commit that
- // carries them is imported as a no-op by a later run.
- // The checkpoint may advance past the pinned commit's bytes because the working tree wins, as for any local edit.
- const working = renamed ? null : readSyncFile(root, p.path);
- if (!working || sha256(working) !== p.rawHash
- || !sameCanonicalImport(base, parseMarkdown(working.toString('utf8'), `${row.slug}.md`, { activePack }))) {
- throw syncPublicationRefusal('source_changed', 'Newer working-tree bytes and the current page disagree with this pinned Git import.', row, p,
- `The working tree holds newer bytes for ${row.slug} that match neither the pinned import nor the current page; sync did not overwrite them. Preserve the local edit and commit it.`);
- }
- return { observedRevision: snapshot?.revision ?? null, noop: true, contentUnchanged: true, validate,
- apply: async () => ({ status: 'skipped', slug: row.slug, source_id: row.source_id, chunks: 0, noop: true, imported_file: true }) };
+ // The pinned commit can simply trail the coordinator: a committed page write reaches the
+ // working tree before its Git effect lands. When the newer working-tree bytes are the
+ // current page itself, there is nothing to import and nothing to protect; the commit that
+ // carries them is imported as a no-op by a later run. This is checked before any content
+ // refusal, so a file already repaired and published is never refused for its pinned bytes.
+ // The checkpoint may advance past the pinned commit's bytes because the working tree wins, as for any local edit.
+ const newerWorkingTree = !p.companyApproval && !!base && !p.lineEndingOnly && p.rawHash !== sha256(p.content) && !sameCanonicalImport(base, parsedInput);
+ const sourcePath = p.sourcePath;
+ const screen = screenImportContent({ content: p.content, path: `${row.slug}.md`, activePack, expectedSlug: resolveSlugForPath(sourcePath),
+ slugExempt: declared => snapshot?.page.source_path != null && syncOriginPath(snapshot.page.source_path) === syncOriginPath(sourcePath) && declared === snapshot.page.slug,
+ slugConflictMessage: (found, expected) => frontmatterSlugConflictMessage(sourcePath, found, expected),
+ ...(newerWorkingTree ? { published: () => {
+ const working = renamed ? null : readSyncFile(root, p.path!);
+ return !!working && sha256(working) === p.rawHash && sameCanonicalImport(base!, parseMarkdown(working.toString('utf8'), `${row.slug}.md`, { activePack }));
+ } } : {}) });
+ if (screen.status === 'published') return { observedRevision: snapshot?.revision ?? null, noop: true, contentUnchanged: true, validate,
+ apply: async () => ({ status: 'skipped', slug: row.slug, source_id: row.source_id, chunks: 0, noop: true, imported_file: true }) };
+ if (screen.status === 'refused') throw syncContentRefusal(screen.refusal, row, p);
+ if (newerWorkingTree) {
+ throw syncPublicationRefusal('source_changed', 'Newer working-tree bytes and the current page disagree with this pinned Git import.', row, p,
+ `The working tree holds newer bytes for ${row.slug} that match neither the pinned import nor the current page; sync did not overwrite them. Preserve the local edit and commit it.`);
}
let importContent = p.content;
if (row.authority.remote) {
@@ -292,8 +314,11 @@ export async function prepareManagedSyncMutation(engine: BrainEngine, row: Write
const importOptions = { ...source, noEmbed: true, remote: row.authority.remote, activePack,
filename: basename(p.sourcePath).replace(/\.mdx?$/i, ''), sourcePath: p.sourcePath, allowEmptyOverwrite: true };
const result = await importFromContent(engine, renamed?.slug ?? row.slug, importContent, { ...importOptions,
- prepare: async value => { prepared = value; return value.result; } });
- if (!prepared) throw syncPublicationRefusal('invalid_params', result.error ?? 'The sync file could not be prepared.', row, p,
+ prepare: async value => { prepared = value; return value.result; } }).catch(error => {
+ if (!(error instanceof ContentSanityBlockError)) throw error;
+ throw syncContentRefusal({ code: 'content_rejected', message: error.message }, row, p);
+ });
+ if (!prepared) throw result.refusal ? syncContentRefusal(result.refusal, row, p) : syncPublicationRefusal('invalid_params', result.error ?? 'The sync file could not be prepared.', row, p,
`The file could not be prepared as page ${row.slug}.`);
const ready = prepared;
if (ready.observedRevision !== (base?.revision ?? null)) throw syncPublicationRefusal('revision_conflict', 'The page changed during sync preparation.', row, p,
diff --git a/src/core/persistence/verb-errors.ts b/src/core/persistence/verb-errors.ts
index 5ee2a4bad4..ea68f1064a 100644
--- a/src/core/persistence/verb-errors.ts
+++ b/src/core/persistence/verb-errors.ts
@@ -2,6 +2,7 @@ import { verbError, OperationError } from '../ops/contract.ts';
import { isTerminalWriteState, isWriteErrorCode, type WriteErrorCode, type WriteReceipt } from './types.ts';
import { pendingWriteHint } from './health.ts';
import { UNBOUND_COLLISION_MESSAGE, UNBOUND_PUBLICATION_MESSAGE } from './unbound-source.ts';
+import { isFrontmatterHoldMessage } from '../markdown.ts';
const FRONTMATTER_SLUG_CONFLICT = /^The frontmatter slug "[^"\n]{1,300}" in [^/"\n][^"\n]{0,1000} conflicts with its path, which expects slug "[^"\n]{1,300}"\. Remove `slug:` or make it match the path\.$/;
@@ -60,6 +61,8 @@ export function writeFailureDiagnostic(code: string, message?: string | null): {
suggestion: 'Read the current page and review the intended change before submitting a corrected write.' };
if (code === 'invalid_params' && message && FRONTMATTER_SLUG_CONFLICT.test(message)) return { reason: code, message,
suggestion: 'Correct the frontmatter in the file and commit the change.' };
+ if (code === 'invalid_params' && isFrontmatterHoldMessage(message)) return { reason: code, message: message!,
+ suggestion: 'Correct the named frontmatter line in the file (one line per key, the whole value quoted) and commit the change.' };
return { reason: isWriteErrorCode(code) ? code : 'storage_error', message: 'The write did not commit. Inspect its durable request on the source host.',
suggestion: 'Resolve the reported write failure before starting a corrected attempt.' };
}
diff --git a/test/import-screen.test.ts b/test/import-screen.test.ts
new file mode 100644
index 0000000000..c88994d9b9
--- /dev/null
+++ b/test/import-screen.test.ts
@@ -0,0 +1,169 @@
+/**
+ * #5988 Lane A: one content screen decides refusals for every ingestion
+ * path, and `isContentRefusal` recognizes exactly the deterministic content
+ * refusals (new and pre-upgrade receipts) that no retry can fix.
+ *
+ * Regressions it catches: a publication path refusing (or accepting) content
+ * the screen judged differently, which would leave a held file importable or
+ * a screened file blocking a sync; and a transient or capacity refusal being
+ * treated as a content refusal, which would silently skip a retryable write.
+ */
+import { describe, expect, test } from 'bun:test';
+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { importFromContent, MAX_FILE_SIZE } from '../src/core/import-file.ts';
+import { isContentRefusal, screenImportContent, type ImportSanityConfig } from '../src/core/import-screen.ts';
+import { managedImportContent, readImportBytes } from '../src/core/persistence/import-prepare.ts';
+import { readSyncFile } from '../src/core/persistence/sync-discovery.ts';
+import { frontmatterSlugConflictMessage } from '../src/core/persistence/verb-errors.ts';
+import { OperationError } from '../src/core/ops/contract.ts';
+
+function mockEngine(): BrainEngine {
+ const pages = new Map<string, unknown>();
+ const engine: BrainEngine = new Proxy({} as Record<string, unknown>, {
+ get(_, prop: string) {
+ if (prop === 'getTags') return () => Promise.resolve([]);
+ if (prop === 'getPage') return (slug: string) => Promise.resolve(pages.get(slug) ?? null);
+ if (prop === 'putPage') return async (slug: string, page: unknown) => { pages.set(slug, page); return page; };
+ if (prop === 'transaction') return async (fn: (tx: BrainEngine) => Promise<unknown>) => fn(engine);
+ return () => Promise.resolve(prop === 'executeRaw' ? [] : null);
+ },
+ }) as unknown as BrainEngine;
+ return engine;
+}
+
+const doc = (block: string, body = 'Body text.') => `---\n${block}\n---\n\n${body}\n`;
+const CORPUS: Array<[label: string, content: string]> = [
+ ['clean', doc('title: Clean\ntype: note')],
+ ['issue author line', doc('title: Roundup\nauthor: PYMNTS (citing Reuters / Bloomberg) (original: https://x.com/a)')],
+ ['quoted trailing', doc('title: "Quoted" trailing')],
+ ['nested quotes', doc('title: "Name "Nick" Last"')],
+ ['fold', doc('title: First line\nsecond line\ntype: note')],
+ ['duplicate', doc('title: a\ntitle: b')],
+ ['duplicate identity', doc('type: note\ntitle: a\ntype: thread')],
+ ['unclosed bracket', doc('tags: [a, b\ntype: note')],
+ ['bad indentation', doc('tags:\n - a\n - b')],
+ ['swallowed visibility', doc('title: "Hello\nvisibility: private\nsummary: x"')],
+ ['pre-quoted visibility', doc('visibility: private # note: x')],
+ ['unclosed fence with visibility', '---\ntitle: a\nvisibility: private\n\n# Heading\nbody\n'],
+ ['comment value', doc('title: #1 thing')],
+ ['crlf recoverable', '---\r\ntitle: Re: hi\r\n---\r\nbody\r\n'],
+ ['slug conflict', doc('slug: elsewhere/page\ntitle: a')],
+ ['oversize', doc('title: big', 'x'.repeat(MAX_FILE_SIZE + 10))],
+];
+
+describe('the screen and every publication path agree', () => {
+ for (const [label, content] of CORPUS) {
+ test(label, async () => {
+ const screened = screenImportContent({ content, path: 'notes/page.md', expectedSlug: 'notes/page' });
+ expect(screened.status).not.toBe('published');
+ const refusal = screened.status === 'refused' ? screened.refusal : null;
+
+ // importFromContent (put_page, capture, legacy import) checks no slug: the slug is the caller's.
+ const contentScreen = screenImportContent({ content, path: 'notes/page.md' });
+ const imported = await importFromContent(mockEngine(), 'notes/page', content, { noEmbed: true });
+ if (contentScreen.status === 'refused') {
+ expect(imported.status).not.toBe('imported');
+ expect(imported.error).toBe(contentScreen.refusal.message);
+ expect(imported.refusal).toEqual(contentScreen.refusal);
+ } else {
+ expect(imported.error).toBeUndefined();
+ expect(imported.status).toBe('imported');
+ }
+
+ let thrown: OperationError | null = null;
+ try { managedImportContent('notes/page.md', Buffer.from(content)); } catch (error) { thrown = error as OperationError; }
+ if (!refusal) {
+ expect(thrown).toBeNull();
+ return;
+ }
+ expect(thrown).toBeInstanceOf(OperationError);
+ expect(thrown!.canonical ?? thrown!.code).toBe(refusal.code);
+ expect(thrown!.code).toBe('invalid_params');
+ expect(thrown!.reason).toBe(refusal.reason);
+ if (refusal.code !== 'frontmatter_slug_conflict') expect(thrown!.message).toBe(refusal.message);
+ expect(isContentRefusal(thrown!.code, thrown!.message)).toBe(true);
+ expect(isContentRefusal(refusal.code, refusal.message)).toBe(true);
+ }, 30_000);
+ }
+
+ test('the published exemption is checked before any content refusal', () => {
+ let asked = false;
+ const result = screenImportContent({ content: doc('title: a\nsecond line'), path: 'notes/page.md', published: () => { asked = true; return true; } });
+ expect(asked).toBe(true);
+ expect(result.status).toBe('published');
+ });
+
+ test('a content-sanity reject disposition refuses as content_rejected; quarantine does not', () => {
+ const sanity = (junkDisposition: 'reject' | 'quarantine'): ImportSanityConfig => ({ cs: {}, disabled: false, extraLiterals: [], junkDisposition });
+ const junk = doc('title: Just a moment...', 'Cloudflare Ray ID: abc123');
+ const rejected = screenImportContent({ content: junk, path: 'notes/page.md', sanity: sanity('reject') });
+ expect(rejected).toMatchObject({ status: 'refused', refusal: { code: 'content_rejected' } });
+ expect(screenImportContent({ content: junk, path: 'notes/page.md', sanity: sanity('quarantine') }).status).toBe('importable');
+ });
+
+ test('code files are screened for size only', () => {
+ expect(screenImportContent({ content: 'const a: "b" c = 1;\n', path: 'src/a.ts' })).toEqual({ status: 'importable', parsed: null });
+ const big = screenImportContent({ content: 'x', byteLength: MAX_FILE_SIZE + 1, path: 'src/a.ts' });
+ expect(big).toMatchObject({ status: 'refused', refusal: { code: 'file_too_large', message: `Code file too large (${MAX_FILE_SIZE + 1} bytes)` } });
+ });
+});
+
+describe('isContentRefusal', () => {
+ test('matches the real messages the import paths produce today', () => {
+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-content-refusal-'));
+ try {
+ const big = join(dir, 'big.md');
+ writeFileSync(big, Buffer.alloc(MAX_FILE_SIZE + 1, 'a'));
+ let importRefusal: OperationError | null = null;
+ try { readImportBytes(big); } catch (error) { importRefusal = error as OperationError; }
+ expect(isContentRefusal(importRefusal!.code, importRefusal!.message)).toBe(true);
+ const huge = join(dir, 'huge.md');
+ writeFileSync(huge, Buffer.alloc(10 * 1024 ** 2 + 1, 'a'));
+ let syncRefusal: OperationError | null = null;
+ try { readSyncFile(dir, 'huge.md'); } catch (error) { syncRefusal = error as OperationError; }
+ expect(syncRefusal!.code).toBe('request_too_large');
+ expect(isContentRefusal(syncRefusal!.code, syncRefusal!.message)).toBe(true);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ expect(isContentRefusal('invalid_params', frontmatterSlugConflictMessage('books/a/ch01.md', 'books/other', 'books/a/ch01'))).toBe(true);
+ });
+
+ test('matches the strings older gbrain versions stored', () => {
+ for (const message of [
+ 'Invalid YAML frontmatter: Malformed YAML frontmatter at line 3. Quote scalar values that contain ": " or fix the frontmatter block.',
+ 'Invalid YAML frontmatter: YAML parse failed: incomplete explicit mapping pair; a key node is missed at line 3, column 54. Quote scalar values that contain ": " or fix the frontmatter block.',
+ 'Invalid YAML frontmatter at line 3 in notes/a.md.',
+ 'Invalid YAML frontmatter at line 3, column 7. Quote scalar values or fix the frontmatter block.',
+ 'The frontmatter slug "books/other-chapter" in books/fairml/ch01.md conflicts with its path, which expects slug "books/fairml/ch01". Remove `slug:` or make it match the path.',
+ 'Frontmatter slug "my-friend-mike" does not match path-derived slug "2008-03-20-my-friend-mike".',
+ 'Content too large (6000000 bytes, max 5000000). Split the content into smaller files or remove large embedded assets.',
+ 'File too large (8432105 bytes)',
+ 'File too large (max 5000000 bytes).',
+ 'Code file too large (8000000 bytes)',
+ ]) expect(isContentRefusal('invalid_params', message)).toBe(true);
+ expect(isContentRefusal('request_too_large', 'Sync file exceeds the bounded import size.')).toBe(true);
+ expect(isContentRefusal('storage_error', 'Publication failed (PAGE_JUNK_PATTERN). Inspect owner diagnostics.')).toBe(true);
+ });
+
+ test('never matches capacity, cursor-size, transient or unrelated refusals', () => {
+ for (const [code, message] of [
+ ['request_too_large', 'Sync discovery exceeds the bounded cursor size.'],
+ ['request_too_large', 'The approved selection exceeds source policy capacity; narrow the selection.'],
+ ['request_too_large', 'Markdown exceeds the import file limit; split it into smaller files.'],
+ ['invalid_params', 'Unsupported internal sync intent.'],
+ ['invalid_params', 'The sync file could not be prepared.'],
+ ['source_changed', 'Newer working-tree bytes and the current page disagree with this pinned Git import.'],
+ ['revision_conflict', 'The page changed during sync preparation.'],
+ ['storage_error', 'Publication failed. Inspect owner diagnostics.'],
+ ['storage_error', 'Publication failed (57014). Inspect owner diagnostics.'],
+ ['queue_capacity', 'The persistence listener is at capacity; retry shortly.'],
+ ['database_error', 'Invalid YAML frontmatter: x'],
+ ['page_identity_changed', 'The imported path no longer names the accepted page.'],
+ [null, 'Invalid YAML frontmatter: x'],
+ ] as Array<[string | null, string]>) expect(isContentRefusal(code, message)).toBe(false);
+ });
+});
diff --git a/test/import-yaml-frontmatter.test.ts b/test/import-yaml-frontmatter.test.ts
index f64824c0c8..fe3e194f2d 100644
--- a/test/import-yaml-frontmatter.test.ts
+++ b/test/import-yaml-frontmatter.test.ts
@@ -42,9 +42,14 @@ function mockEngine(): BrainEngine {
describe('import YAML frontmatter validation', () => {
test('importFromContent rejects invalid YAML frontmatter instead of importing it as body', async () => {
+ // #5988: an unquoted `Re: ...` value is read by quoting it (see the
+ // recoverable test below); a value spilling onto an unquoted second line
+ // can only be read by guessing, so it is still refused, by line, never
+ // echoing the value.
const content = `---
type: note
-title: Re: October booking
+title: October booking
+continued on a stray line
---
Body text.
@@ -55,7 +60,8 @@ Body text.
expect(result.status).toBe('error');
expect(result.error).toContain('Invalid YAML frontmatter');
- expect(result.error).toContain('title: Re: October booking');
+ expect(result.error).toContain('line 3');
+ expect(result.error).not.toContain('stray line');
expect((engine as any)._calls).toEqual([]);
});
@@ -65,7 +71,8 @@ Body text.
const filePath = join(dir, 'reply.md');
writeFileSync(filePath, `---
type: note
-title: Re: October booking
+title: October booking
+continued on a stray line
---
Body text.
@@ -76,13 +83,31 @@ Body text.
expect(result.status).toBe('skipped');
expect(result.error).toContain('Invalid YAML frontmatter');
- expect(result.error).toContain('title: Re: October booking');
+ expect(result.error).toContain('line 3');
+ expect(result.error).not.toContain('stray line');
expect((engine as any)._calls).toEqual([]);
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
+ test('an unquoted colon-space value imports with its exact text (#5988)', async () => {
+ const content = `---
+type: note
+title: Re: October booking
+---
+
+Body text.
+`;
+
+ const engine = mockEngine();
+ const result = await importFromContent(engine, 'emails/reply-october-booking', content, { noEmbed: true });
+
+ expect(result.status).toBe('imported');
+ const putCall = (engine as any)._calls.find((call: any) => call.method === 'putPage');
+ expect(putCall.args[1].title).toBe('Re: October booking');
+ });
+
test('quoted frontmatter values with colon-space still import', async () => {
const content = `---
type: note
diff --git a/test/persistence-file-import.test.ts b/test/persistence-file-import.test.ts
index 87135153e9..5a76fb6bc5 100644
--- a/test/persistence-file-import.test.ts
+++ b/test/persistence-file-import.test.ts
@@ -150,7 +150,8 @@ test('managed import refuses cross-source input, symlink targets, skills, malfor
symlinkSync(other.root, join(f.root, 'escape'));
await expect(importManagedFile(engine, file, 'escape/note.md', opts)).rejects.toThrow('escapes');
await expect(importManagedFile(engine, file, 'skills/unsafe.md', opts)).rejects.toThrow('skill');
- writeFileSync(file, '---\ntitle: invalid: yaml\n---\nBody\n');
+ // #5988: `title: invalid: yaml` now imports by quoting; a mis-indented list cannot be read.
+ writeFileSync(file, '---\ntags:\n - a\n - b\n---\nBody\n');
await expect(importManagedFile(engine, file, 'note.md', opts)).rejects.toThrow('Invalid YAML');
await expect(importManagedFile(engine, file, 'image.png', opts)).rejects.toThrow('GBRAIN_EMBEDDING_MULTIMODAL=true');
expect(await engine.getPage('note', { sourceId: f.sourceId })).toBeNull();
diff --git a/test/put-page-recoverable-frontmatter.test.ts b/test/put-page-recoverable-frontmatter.test.ts
new file mode 100644
index 0000000000..1a54baa000
--- /dev/null
+++ b/test/put-page-recoverable-frontmatter.test.ts
@@ -0,0 +1,106 @@
+/**
+ * #5988 Lane A: put_page accepts frontmatter gbrain can read exactly by
+ * quoting it and writes the quoted canonical form, so anything written
+ * through gbrain is clean on disk; frontmatter it would have to guess at is
+ * refused with a typed code, the key and line, and no raw value.
+ *
+ * Regression it catches: put_page refusing the issue's files (the R2
+ * validator bug), writing the unparseable original bytes to the canonical
+ * file, or refusing without the key/line an agent needs to fix it.
+ */
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test as bunTest } from 'bun:test';
+import { mkdirSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { randomUUID } from 'node:crypto';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { resetGateway } from '../src/core/ai/gateway.ts';
+import { dispatchToolCall } from '../src/mcp/dispatch.ts';
+import { registerLocalWriter, withVerifiedLocalRegistration, type LocalRegistration } from '../src/core/persistence/identity.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { _resetWriteThroughCacheForTest } from '../src/core/write-through.ts';
+import { parseDataFrontmatter } from '../src/core/data-frontmatter.ts';
+
+let engine: PGLiteEngine;
+let root: string;
+let fixtureDir: string;
+let registration: LocalRegistration;
+const auth = { token: 'fixture', clientId: 'fixture-client', scopes: ['read', 'write'], sourceId: 'default', boundSlugPrefixes: ['notes'] };
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+}, 120_000);
+
+afterAll(async () => {
+ await engine.disconnect();
+});
+
+beforeEach(async () => {
+ await disposePersistenceConsumer(engine);
+ await resetPgliteState(engine);
+ resetGateway();
+ _resetWriteThroughCacheForTest();
+ fixtureDir = mkdtempSync(join(tmpdir(), 'gbrain-put-recoverable-'));
+ root = join(fixtureDir, 'brain'); mkdirSync(root);
+ await engine.setConfig('sync.repo_path', root);
+});
+
+afterEach(async () => {
+ await disposePersistenceConsumer(engine);
+ resetGateway();
+ _resetWriteThroughCacheForTest();
+ rmSync(fixtureDir, { recursive: true, force: true });
+});
+
+function test(name: string, run: () => Promise<void>, timeout = 20_000) {
+ bunTest(name, () => withEnv({ GBRAIN_HOME: join(fixtureDir, 'home') }, async () => {
+ registration = await registerLocalWriter(engine, 'stdio', {
+ sourceIds: ['*'], operations: null, scopes: ['read', 'write'], slugPrefixes: ['notes'],
+ });
+ try { await run(); } finally { await disposePersistenceConsumer(engine); }
+ }), timeout);
+}
+async function put(slug: string, content: string) {
+ const response = await withVerifiedLocalRegistration(engine, registration, () => dispatchToolCall(engine, 'put_page', { slug, content, request_id: randomUUID() }, {
+ remote: true, config: { engine: 'pglite' }, sourceId: 'default', auth,
+ logger: { info() {}, warn() {}, error() {} },
+ }));
+ return { response, payload: JSON.parse((response.content[0] as { text: string }).text) };
+}
+
+describe('put_page with recoverable frontmatter', () => {
+ test('a quote-recoverable block commits and the canonical file is written in quoted, strictly parseable form', async () => {
+ const slug = 'notes/payments-roundup';
+ const author = 'PYMNTS (citing Reuters / Bloomberg) (original: https://x.com/a/status/1)';
+ const result = await put(slug, `---\ntitle: Re: payments roundup\ntype: note\nauthor: ${author}\nsource: "Quoted" trailing\n---\n\nBody text.\n`);
+ expect(result.response.isError).not.toBe(true);
+ expect(result.payload.state).toBe('committed');
+ const page = (await engine.readPageSnapshot(slug, { sourceId: 'default' }))!.page;
+ expect(page.title).toBe('Re: payments roundup');
+ expect(page.frontmatter).toMatchObject({ author, source: '"Quoted" trailing' });
+ const disk = readFileSync(join(root, `${slug}.md`), 'utf8');
+ const strict = parseDataFrontmatter(disk);
+ expect(strict.data).toMatchObject({ title: 'Re: payments roundup', author, source: '"Quoted" trailing' });
+ });
+
+ test('frontmatter that needs guessing is refused with a typed code, its key and line, and no raw value', async () => {
+ const result = await put('notes/guess', '---\ntitle: alice-example first line\nalice-example second line\ntype: note\n---\n\nBody.\n');
+ expect(result.response.isError).toBe(true);
+ const text = JSON.stringify(result.payload);
+ expect(text).not.toContain('alice-example');
+ expect(result.payload).toMatchObject({ error: 'invalid_params', code: 'invalid_frontmatter', reason: 'needs_interpretation', detail: 'key title, line 2' });
+ expect(result.payload.suggestion).toContain('frontmatter line 2 (key "title")');
+ expect(await engine.readPageSnapshot('notes/guess', { sourceId: 'default' })).toBeNull();
+ });
+
+ test('a protected key that would be read as a broader value is refused', async () => {
+ const result = await put('notes/private', '---\ntitle: "Hello\nvisibility: private\nsummary: x"\n---\n\nBody.\n');
+ expect(result.response.isError).toBe(true);
+ expect(result.payload).toMatchObject({ code: 'invalid_frontmatter', reason: 'ambiguous_protected_key', detail: 'key visibility, line 3' });
+ expect(await engine.readPageSnapshot('notes/private', { sourceId: 'default' })).toBeNull();
+ });
+});
diff --git a/test/sync-frontmatter-recovery.test.ts b/test/sync-frontmatter-recovery.test.ts
new file mode 100644
index 0000000000..bdcf7f882d
--- /dev/null
+++ b/test/sync-frontmatter-recovery.test.ts
@@ -0,0 +1,107 @@
+/**
+ * #5988 Lane A: managed sync publication uses the shared content screen.
+ * A file whose frontmatter gbrain can read by quoting (the issue's exact
+ * `author:` line) syncs instead of blocking; a file it would have to guess at
+ * is refused with the typed, location-only `Invalid YAML frontmatter:`
+ * message, which sync output and `get_write_request` show as is, and which
+ * `isContentRefusal` recognizes from the stored receipt.
+ *
+ * Holding such files instead of blocking is Lane 2; this pins the refusal
+ * the hold store and auto-conversion read.
+ */
+import { afterAll, beforeAll, expect, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { randomUUID } from 'node:crypto';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { operations } from '../src/core/operations.ts';
+import type { OperationContext } from '../src/core/ops/contract.ts';
+import { claimWorktree } from '../src/core/persistence/ownership.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { performManagedSync } from '../src/core/persistence/sync-run.ts';
+import { printSyncResult } from '../src/commands/sync.ts';
+import { isContentRefusal } from '../src/core/import-screen.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { makeGitFixture } from './helpers/git-fixture.ts';
+import { testBackends } from './helpers/test-backends.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const backends = testBackends();
+const home = mkdtempSync(join(tmpdir(), 'gbrain-fm-recovery-'));
+const engines: BrainEngine[] = [];
+let closePostgres: (() => Promise<void>) | undefined;
+const env = { GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home };
+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8' }).trim();
+const author = 'PYMNTS (citing Reuters / Bloomberg) (original: https://x.com/a/status/1)';
+
+beforeAll(async () => {
+ if (backends.includes('pglite')) {
+ const engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); engines.push(engine);
+ }
+ if (backends.includes('postgres')) {
+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!); engines.push(pg.engine); closePostgres = pg.close;
+ }
+}, 120_000);
+
+afterAll(async () => {
+ for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); }
+ await closePostgres?.(); rmSync(home, { recursive: true, force: true });
+});
+
+async function source(engine: BrainEngine, files: Record<string, string>): Promise<string> {
+ const id = `fm-${randomUUID().replace(/-/g, '').slice(0, 20)}`, root = join(home, id);
+ mkdirSync(join(root, 'notes'), { recursive: true }); await makeGitFixture(root);
+ for (const [path, content] of Object.entries(files)) writeFileSync(join(root, path), content);
+ git(root, 'add', '.'); git(root, 'commit', '-qm', 'fixture content');
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,'{}')", [id, root]);
+ await claimWorktree(engine, id, root);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ return id;
+}
+
+test('a quote-recoverable file syncs with its exact value', async () => withEnv(env, async () => {
+ for (const engine of engines) {
+ const id = await source(engine, { 'notes/roundup.md': `---\ntitle: Payments roundup\nauthor: ${author}\n---\nA synthetic roundup.\n` });
+ try {
+ const result = await performManagedSync(engine, { sourceId: id, noPull: true, noEmbed: true, noExtract: true });
+ expect(result.status).not.toBe('blocked_by_failures');
+ const page = (await engine.readPageSnapshot('notes/roundup', { sourceId: id }))!.page;
+ expect(page.frontmatter).toMatchObject({ author });
+ expect(page.title).toBe('Payments roundup');
+ } finally {
+ await disposePersistenceConsumer(engine);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ }
+ }
+}), 120_000);
+
+test('a file that needs guessing refuses with the typed location-only message in sync output and the receipt', async () => withEnv(env, async () => {
+ for (const engine of engines) {
+ const id = await source(engine, { 'notes/post.md': '---\ntitle: alice-example first line\nalice-example second line\n---\nA synthetic post.\n' });
+ const expected = 'Invalid YAML frontmatter: key "title" at line 2 continues on unquoted lines.';
+ try {
+ const result = await performManagedSync(engine, { sourceId: id, noPull: true, noEmbed: true, noExtract: true });
+ expect(result).toMatchObject({ status: 'blocked_by_failures', managedWrite: { write_error: 'invalid_params' } });
+ expect(result.managedWrite!.message.startsWith(expected)).toBe(true);
+ let output = '';
+ printSyncResult(result, { write: (text: string) => { output += text; return true; } } as NodeJS.WriteStream);
+ expect(output).toContain(expected);
+ expect(output).not.toContain('alice-example');
+
+ const requestId = result.managedWrite!.write_request.request_id;
+ const ctx: OperationContext = { engine, config: { engine: engine.kind }, sourceId: id, remote: false, dryRun: false,
+ logger: { info() {}, warn() {}, error() {} } };
+ const receipt = await operations.find(op => op.name === 'get_write_request')!.handler(ctx, { request_id: requestId }) as Record<string, string>;
+ expect(receipt).toMatchObject({ state: 'failed', write_error: 'invalid_params' });
+ expect(receipt.write_error_message.startsWith(expected)).toBe(true);
+ expect(isContentRefusal(receipt.write_error, receipt.write_error_message)).toBe(true);
+ } finally {
+ await disposePersistenceConsumer(engine);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ }
+ }
+}), 120_000);