Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(write): refuse tags over the tags index byte limit as tag_too_long instead of a storage_error (#7052)
garrytanc63af2d75fe1
diff --git a/docs/architecture/key-files/files-and-sync-2.md b/docs/architecture/key-files/files-and-sync-2.mdindex 3bf572f4ce..7a2ad7d00f 100644--- a/docs/architecture/key-files/files-and-sync-2.md+++ b/docs/architecture/key-files/files-and-sync-2.md@@ -28,5 +28,6 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/persistence/sync-streamed.ts` — Wave B PR 2: managed sync of a Markdown file over the 24 MiB single-string ceiling. With `pages.segmented_storage` on, `freezeEntry` (`sync-run.ts`) freezes such a file by reference instead of holding it by its size: `streamedSyncBodyRef` hashes the sha256 and the Git blob id as a stream (sha1 or sha256 by the pinned commit's length) into `intent.body_ref` (`git_blob`, or `input_file` for an uncommitted working-tree file); the journal carries no content, and a committed entry whose working tree does not hold its pinned blob, a file over `pages.max_bytes` or a non-Markdown file is held as before. `prepareManagedSyncMutation` (`sync-prepare.ts`) hands it to `prepareManagedSyncStreamed`, which streams it through `importStreamedMarkdownFile` (`page-body/streamed-import.ts`, `coordinated`; `moved` on a rename keeps an implicit type following the new path; `slug` is the admitted page, the one recording the file as its origin, as the inline import targets) and publishes database-only, recording the origin through `bindOrigin` (B-14: a renamed page keeping its origin takes the file, no twin at the path's slug); a rename moves the page first and re-seals an unchanged body (`sealSegmentedPage`). A file the streamed path refuses (a facts fence) fails its request with the refusal's code and the run holds it (`streamedRefusalHold` in `sync-screen.ts`); a dry run lists it in `screen_skipped` as `page_body_segmented`; `groupableIntent` (`sync-group.ts`) keeps it out of bulk groups. Tests: `test/large-pages/managed-sync-streamed.test.ts` (both engines), `managed-sync-streamed-crash.test.ts` (owner killed at `consumer:prepared`), `managed-sync-streamed-memory.slow.test.ts` (VmHWM), `streamed-sync-origin-b14.test.ts` (both engines).- `src/core/persistence/sync-entry-fault.ts` — GBRA-133 (#6712 PR 4b): the per-entry faults of a managed sync freeze, so one odd file never stops its source. `nullBytesRefusal` holds a Markdown text with U+0000 `content_null_bytes` (line of the first NUL; a UTF-16 byte order mark says save as UTF-8), from `screenFrozenImport` with holds on and as a typed run stop under `sync.holds=fail`. `committedContentOrMissing` (called by `pinnedContent` when the pinned read fails) imports a committed file whose blob object is gone from working-tree bytes that hash to that blob id, else throws `git_object_missing`; a committed name with U+FFFD that names nothing on disk (a name that is not UTF-8) throws `path_not_utf8` first. `directoryAt` lets a deletion whose name became a directory apply (freeze and the owner's raw-hash check). `freezeFaultHold` is `freezeEntry`'s catch (`sync-run.ts` wraps `freezeEntryOnce`): `git_object_missing` and `path_not_utf8` are held under their codes, any other `OperationError` and every run-scoped error (`classifyItemFailure` scope run, connection, statement timeout, lock, back-pressure, abort) rethrows, and an unexpected throw is held `page_write_failed` with `write_failure.origin: 'freeze'` and `request_id: null`, re-tested by every sync until held `HOLD_ATTEMPTS_NEEDS_HUMAN` times; a run with `ITEM_BREAKER_MIN_ITEMS` faults and no more clean freezes than faults is systemic and rethrows.+- `src/core/tag-limit.ts` — `TAG_MAX_BYTES` (2688, the longest tag both btree indexes on `tags` store, in UTF-8 bytes) and `tagLengthHold`, the `tag_too_long` hold `classifyImportHold` returns, so every content screen, file import and legacy sync hold refuses it; `prepareSegmentedTagMutation` throws it before an `add_tag` flip. The message names the tag's position and size, never its text (#7052). Pinned by `test/tag-length-7052.test.ts`.- `src/core/url-clone.ts` — gbrain-owned `sources add --url` clones (#6946, GBRA-130 C-2). `isOwnedClone` (config `managed_clone` or a `local_path` under the default clone dir) and `defaultCloneDir`; `urlCloneReadOnly` is the one predicate (owned clone on a brain without managed persistence) the fence writer (`fence-write.ts`, `databaseOnlyReason: 'url_clone'`), write-through (`skipped: 'url_clone'`), timeline write-through, unfenced-facts adoption, the empty-fence guard and `sourceMirrorReadOnly` consult, so nothing gbrain writes lands in a checkout it updates with `git pull --ff-only`. `urlClonePullBlock` reads the tracked changes of a clone whose pull failed and returns `pull_blocked_local_changes` with an `ask_user` fix naming the preview `gbrain repair url-clone-fences --source <id>`; `formatUrlClonePullBlock` renders it for sync's stderr (`sync/preflight.ts`) and `cycle.ts` puts it in the sync phase detail as `pull_blocked`. Test: `test/pathological/c2-url-clone-fences.test.ts`.- `src/core/write-through.ts` — shared atomic disk write-through for the canonical ingestion path. `resolvePageWriteTarget(engine, slug, sourceId, { includeDeleted? })` (active rows by default; `includeDeleted: true` resolves a tombstone's recorded `source_path` for the purge remediation retry) is the exported single source of truth for the ONE file a (source, slug) pair lives in on disk: a source with its own `local_path` writes at that tree's ROOT (never nested under `.sources/`); a source without one nests under the host repo (`sync.repo_path`, default at root, non-default under `.sources/<id>/`) unless that path is another source's own working tree (leak guard → `source_repo_belongs_to_other_source`; a live source whose `local_path` is relative counts as owning every tree, and a relative `local_path` or `sync.repo_path` target is `repo_not_found`); the page's recorded `source_path` (or a contained absolute `file://` `source_uri`; a relative or host-only `file://` names no local file and is read as absent) is preferred over a slug-derived name so writes land in the file of record instead of minting a twin; and `isWriteTargetContained` rejects hostile rows escaping the tree (`path_escapes_source_root`). The ok-result also carries `sourcePathToBind` — the target expressed in the file scanner's `source_path` convention for the source's pinned `slug_root_mode` (or the mode its first sync would pin, via `scannerSlugRootMode`): GIT-ROOT-relative under `git-root` when the scan root sits inside a git repo, scan-root-relative under `source-root` and for non-git or git-root scan roots, so a put-born page binds the same form managed sync and delete-reconcile key on. Every recorded-path reader (write targets, takes, reconcile, audit, export restore, doctor) decodes with the same mode (`resolveSourceLocalFilePath(..., slugRootMode)`): under `source-root` the scope prefix is removed only from the legacy Git-root form whose remainder names the page slug, and basename rows resolve under the unstripped slug directory. The resolver is shared by `writePageThrough`, the facts fence writer (`src/core/facts/fence-write.ts`), and fence forget (`src/core/facts/forget.ts`) — the fence appends to the page's file, so all writers MUST compute the identical path or the fence lands in a file sync never reads back and the next extract_facts reconcile deletes the fence-owned DB rows. `writePageThrough(engine, slug, {sourceId?, frontmatterOverrides?, logger?, expectedFileBytes?})` resolves the target through it, re-reads the just-written DB row (`getPage`), renders it via `serializePageToMarkdown`, and writes the `.md` so the brain has a committable artifact that round-trips through `gbrain sync`. Rendering from the row keeps the serialized content consistent at write time. The fsync-backed `atomicWriteFileSync` stages and renames the file after required source-path bookkeeping; lock/lease checks run before publication. `put_page` holds the root lock before importing and invokes write-through inside its database transaction, so ordinary filesystem rejection rolls back existing content, tags, chunks, and versions. A crash or database COMMIT failure after rename can still leave canonical Markdown ahead of the index; this is not distributed ACID or a durable queue. Never throws — returns `WriteThroughResult { written, path?, content? (the bytes written), skipped?: 'disabled_by_config' | 'no_repo_configured' | 'repo_not_found' | 'source_repo_belongs_to_other_source' | 'page_not_found_after_write' | 'path_escapes_source_root' | 'case_insensitive_collision' | 'file_changed', warning?, error? }` (`file_changed`: the caller's `expectedFileBytes` preimage, null for absent, no longer matches the file under the source filesystem lock, so the file is left untouched) so the caller decides messaging + exit codes. `withNoRepoWriteThroughWarning(result, sourceId)` decorates an unwritten `no_repo_configured` result with `warning` (the write landed only in the database; bind the token/server to a git-backed source or configure `local_path`/`sync.repo_path`); `put_page` applies it for untrusted callers only (`ctx.remote !== false`), so local CLI responses and the `disabled_by_config` operator opt-out stay silent. `isWriteThroughDisabled` (shared with the fence lane, ~30s per-engine cache) honors the `sync.write_through` opt-out. Trust gating (subagent sandbox, dry-run) stays at the CALLER. On a durability-hardened repo (`isDurabilityHardened` — the gbrain post-commit hook is installed, i.e. the user ran `gbrain sources harden`), a successful write is best-effort COMMITTED via `commitWriteThroughFile` (path-limited `git commit -- <file>`, never sweeps unrelated edits; the hook then background-pushes) unless the caller passes `deferCommit` (the derived write-through commits its batch itself, #8073; `deletePageThrough` takes it too) so write-through content reaches git instead of accumulating uncommitted forever; result carries `committed?: boolean`. Unhardened repos keep write-only behavior. `deletePageThrough(engine, slug, {sourceId?, target?, logger?})` is the delete-side sink (sole caller: the `delete_page` op): resolves the same target, unlinks the `.md`, and on a hardened repo best-effort commits the removal path-limited through the same helper with subject `gbrain: delete write-through <slug>`, reporting `committed?: boolean` on `DeleteThroughResult` (absent when unhardened or when the commit did not land — the unlink still stands; a never-committed page leaves nothing to commit, so no empty commit). Pinned by `test/delete-write-through-commit.test.ts`. Consumers: `put_page` op and `gbrain brainstorm/lsd --save` via `persistSavedIdea`. Pinned by `test/write-through.test.ts` + `test/write-through-commit.test.ts`. The `put_page` op is that deciding caller for direct writes: a skip outside the deliberate DB-only set (`no_repo_configured`/`disabled_by_config`/`subagent_sandbox`/`dry_run`) throws `storage_error` inside the import transaction, rolling back the page revision, tags, chunks and version snapshot instead of deleting a just-created row afterward. #6946: on a gbrain-owned `--url` clone of an unmanaged brain (`urlCloneReadOnly`), `writePageThrough` returns `skipped: 'url_clone'` and `deletePageThrough` returns `removed: false, skipped: 'url_clone'`; `timeline-write-through.ts` skips the same way.diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex 85da49e76e..9290e0d77c 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -4293,6 +4293,16 @@ Reasons: `content_directory`.|---|---|---|---|---|---|---|| A sync pass's checkpoint did not publish because the pass that admitted it no longer holds the source (it ended, or another pass started); the next pass stamps its own checkpoint. | A pass's checkpoint is bound to its drain lease and pass row, so it can never publish after that pass ends. Its receipt is a conflict that records no managed-sync failure and reads superseded in gbrain sources writer failures; a pass that stops with the checkpoint still pending reports disposition superseded instead of a request to resume. | Nothing to repair or resubmit: the pages the pass committed stand. Let the next sync pass run (gbrain sync --source <id> --no-pull), and read gbrain sync status --source <id> --json to confirm the source converges. | agent | `repeat the read that failed` | 1 | no |+### tag_too_long++<a id="tag_too_long"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| A page's tag is longer than the 2688 bytes a tag can be, so nothing was written (sync holds the file). | Tags are stored in a btree index whose entries are at most 2704 bytes; a longer tag would fail the database insert (error 54000) and report a storage failure instead of naming the tag (#7052). The message names the tag's position and size, never its text. | Shorten that tag or split it into shorter tags, then write the page again (for a file: edit it, commit and sync). | agent | `repeat the read that failed` | 1 | no |++More: [docs/guides/write-refusals.md#tag_too_long](../../docs/guides/write-refusals.md#tag_too_long)+### tail_changed<a id="tail_changed"></a>diff --git a/docs/guides/sync-unblock-runbook.md b/docs/guides/sync-unblock-runbook.mdindex c9025269a9..ab483f765d 100644--- a/docs/guides/sync-unblock-runbook.md+++ b/docs/guides/sync-unblock-runbook.md@@ -150,6 +150,7 @@ Every hold and error has three fields, from one table| `settle_mismatch` | page | none | yes | always: the pass cannot tell why the path does not settle || `page_write_failed` | page | upgrade | yes | always: the writer cannot place the failure || `file_unreadable` | page | none | yes | always: only a change to the checkout makes the file readable |+| `tag_too_long` | page | none | yes | always: only an edit to the file clears it || `visibility_noncanonical` | page | none | yes | always: only an edit to the file clears it || `content_null_bytes` | page | none | yes | always: only an edit to the file or its removal clears it || `git_object_missing` | page | none | yes | always: only restoring the Git object clears it |diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.mdindex e43d770ea2..16efe32735 100644--- a/docs/guides/write-refusals.md+++ b/docs/guides/write-refusals.md@@ -261,6 +261,7 @@ with each file and fix the ones that need no guessing."*| <a id="file_wins_rewrite"></a>`file_wins_rewrite` | `gbrain repair file-drift --prefer file` keeps the canonical file's bytes and adds only the protected parts reconcile keeps from the database: protected frontmatter keys the file lacks (inserted before the closing `---`) and database-only timeline rows (appended to the file's timeline, with a `<!-- timeline -->` line above a bare `## Timeline` heading so they stay in it). When the resolved page also differs in anything else (a value, a tag, the title, the body), keeping the file would mean re-rendering all of it, so the preview refuses the page and nothing is written. | Show the user the page's differences. Commit them into the file through the door (`gbrain git commit-push`) and preview again, or preview `--prefer database` if the database copy should win. || <a id="frontmatter_alias_limit"></a>`frontmatter_alias_limit` | A file whose exact bytes an older gbrain imported and validated nests YAML aliases in its frontmatter that expand past the size limit (#7018). This release refuses them on purpose, so only that file is held (its page keeps the last imported version) and the rest of the source syncs; it is never a parser regression. | Reduce the alias nesting in the frontmatter (or write the values out), or remove the file, then commit and `gbrain sync --source <source> --no-pull`. The hold re-screens when the file changes. Before 4b such a file stopped the source as `sync_parser_regression`; the workaround there was `GBRAIN_SYNC_PARSER_REGRESSION=hold` for the process that syncs. || <a id="visibility_noncanonical"></a>`visibility_noncanonical` | The file's frontmatter asks for `visibility: private` in a spelling page privacy does not read: another case (`Visibility: private`, `visibility: Private`), a block scalar, a list, a flow mapping or a merge key. Page privacy reads only the exact lowercase key and value, so importing it would store a world-readable page its author believes is private. Git sync (classic and managed) holds the file and the rest of the source syncs; `gbrain import` (with or without a Git checkout) refuses it and imports the rest. An existing page keeps its last imported version. Company-brain connects and syncs, and the GitHub and Google connectors on a database-only source, hold it the same way (#7880); `gbrain repair url-clone-fences` lists a clone file whose HEAD asks for it this way under this code; apply restores the file from HEAD with its fence rows kept database-only, so the clone can pull, but does not import HEAD and reports `held` (#7897). `put_page`, `edit_page`, `capture`, `ingest_capture`, `brainstorm --save` and `sources reconcile` refuse the same request as [`visibility_not_applied`](#visibility_not_applied). Doctor `git_held_files` counts the held files and the stored pages that ask for private this way (`details.visibility_noncanonical`). | Write `visibility: private` on its own frontmatter line (lowercase key and value), commit, and run `gbrain sync --source <source> --no-pull` (or import the file again). The hold re-screens when the file changes; no frontmatter repair rewrites a privacy request. For a stored page doctor names, rewrite its frontmatter the same way with `put_page` or by editing its file. |+| <a id="tag_too_long"></a>`tag_too_long` | A frontmatter tag (or an `add_tag` tag) is over 2688 bytes, the longest tag the btree indexes on `tags` store (#7052). Before this check the database insert failed with error 54000 and the write reported `storage_error`. On a write nothing is written; Git sync holds the file and the rest of the source syncs; `gbrain import` skips it and imports the rest. The message names the tag's position and size, never its text. | Shorten the tag or split it into shorter tags, then write the page again (for a file: edit it, commit and `gbrain sync --source <source> --no-pull`). || <a id="parser_regression"></a>`parser_regression` | A file whose exact bytes imported under an earlier gbrain is now refused. It is held and the rest of the source syncs (the default; `GBRAIN_SYNC_PARSER_REGRESSION=stop` stops the run instead). This is a gbrain bug. | Report it with the gbrain version, the file and the code; upgrade or pin the last good version. After a fixed gbrain is installed, `gbrain sources retry-held <source>` and then `gbrain sync --source <source> --no-pull` re-screen it. || <a id="settle_mismatch"></a>`settle_mismatch` | A live managed sync pass settled this file at the same level in three consecutive passes, but the next round never classified it settled (#6712). Instead of re-importing it every pass, sync held it at that level and stamped the rest of the source. The hold records the level and `meta.mismatch_streak`. The file is usually fine: a path that keeps coming back unsettled points to a broken writer, a stuck effect or a damaged record. | Run `gbrain doctor --json` and `gbrain sources writer status --source <source> --json` (both read-only), fix or report what they name with the gbrain version, then `gbrain sources retry-held <source>` and `gbrain sync --source <source> --no-pull`. A mismatch that comes back is held again after three passes. || <a id="write_interrupted-hold"></a>`write_interrupted` | The database ended this file's statements (a statement timeout or cancel) at every attempt, so the sync held the file and kept going. The file is fine: no repair applies, and it is not imported until it is retried. Full reference: [`write_interrupted`](#write_interrupted). | `gbrain sources writer status --source <source> --json` (read-only) names the load on the write owner; reduce it, then `gbrain sources retry-held <source>` and the same sync with its options. |diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 950eadc398..30dfd3c96e 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -742,6 +742,7 @@ export const CODES = {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; with `GBRAIN_SYNC_PARSER_REGRESSION=stop` set for the process that syncs (the default holds the file), 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.' },tail_changed: { class: 'caller', summary: "The end of the page no longer has the sha256 the append expected, so nothing was appended.", why: "append_page's expected_tail_sha256 binds an append to the tail its caller read; another write changed it, and appending anyway could interleave text with a tail the caller never saw.", suggestion: "Read the page again (get_page body: 'none' returns tail_sha256), check whether the text is still missing, and append against the current tail with a new request_id.", fix: { argv: ['gbrain', 'get', '--source', '{source_id}', '--', '{slug}'], mcp: { tool: 'get_page', arguments: { slug: '{slug}', source_id: '{source_id}', body: 'none' } }, consent: [], actor: 'agent', why: "Returns the current revision and tail_sha256.", requires_exclusive: false } },tail_exposure_approval: { class: 'caller', summary: "A fence on a world-visible page has no end marker and prose follows its table; closing it after the last row is safe for the table but makes those lines visible to remote readers, so the content-repair lane previews the close and waits for a hash-bound approval instead of applying it unattended.", why: "Everything after an unpaired begin marker is hidden by the privacy boundary. The repair model read the tail as prose (not rows), so the only judgment left is whether those exact lines may become visible, and that is the user's: the preview prints them and the hash binds them. On a private page nothing new is disclosed and the lane closes the fence by itself.", actor: 'user', docs: 'docs/guides/write-refusals.md#tail_exposure_approval', suggestion: 'Show the user the preview\'s exposed lines (gbrain repair content --source <id> --only <path>, read-only), then run the printed gbrain repair content --source <id> --only <path> --apply --expect <hash> only after they agree; a changed tail invalidates the hash. By hand: add the end marker directly after the last table row and move the trailing text where it belongs, commit, then gbrain sync --source <id> --no-pull.' },+ tag_too_long: { class: 'caller', summary: "A page's tag is longer than the 2688 bytes a tag can be, so nothing was written (sync holds the file).", why: "Tags are stored in a btree index whose entries are at most 2704 bytes; a longer tag would fail the database insert (error 54000) and report a storage failure instead of naming the tag (#7052). The message names the tag's position and size, never its text.", docs: 'docs/guides/write-refusals.md#tag_too_long', suggestion: 'Shorten that tag or split it into shorter tags, then write the page again (for a file: edit it, commit and sync).' },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." },timeline_comment_markup: { class: 'caller', summary: "A stored timeline row carries HTML comment markup, so gbrain keeps it database-side and never writes it back into the page; clean it with gbrain repair timeline-comments.", docs: 'docs/guides/repair.md#timeline-comments' },diff --git a/src/core/import-file.ts b/src/core/import-file.tsindex 6628f6255c..c71b411f8c 100644--- a/src/core/import-file.ts+++ b/src/core/import-file.ts@@ -1084,7 +1084,7 @@ export async function importFromFile(const preInferenceParsed = parseMarkdown(content, relativePath, { validate: true });const preInferenceHold = classifyImportHold(preInferenceParsed);if (preInferenceHold) {- return { slug: slugifyPath(relativePath), status: 'skipped', chunks: 0, error: preInferenceHold.message, refusal: preInferenceHold, skip_reason: 'invalid_frontmatter' };+ return { slug: slugifyPath(relativePath), status: 'skipped', chunks: 0, error: preInferenceHold.message, refusal: preInferenceHold, skip_reason: preInferenceHold.code };}const privateHold = noncanonicalPrivateHold(content, preInferenceParsed.frontmatter);if (privateHold) return { slug: slugifyPath(relativePath), status: 'skipped', chunks: 0, error: privateHold.message, refusal: privateHold, skip_reason: privateHold.code };@@ -1128,7 +1128,7 @@ export async function importFromFile(let fallbackReason: 'path slugified empty' | 'normalization-equivalent identity restore' ='path slugified empty';- if (frontmatterHold) return { slug: expectedSlug, status: 'skipped', chunks: 0, error: frontmatterHold.message, refusal: frontmatterHold, skip_reason: 'invalid_frontmatter' };+ if (frontmatterHold) return { slug: expectedSlug, status: 'skipped', chunks: 0, error: frontmatterHold.message, refusal: frontmatterHold, skip_reason: frontmatterHold.code };if (expectedSlug === '') {if (parsed.slug && parsed.slug.length > 0) {diff --git a/src/core/import-screen.ts b/src/core/import-screen.tsindex dce45eac77..05d95aefd1 100644--- a/src/core/import-screen.ts+++ b/src/core/import-screen.ts@@ -25,6 +25,7 @@ import {} from './write-gate.ts';import { clearStalePageGateReceipts, recordPageGateReceipt } from './write-gate-store.ts';import { loadOperatorLiterals } from './content-sanity-literals.ts';+import { TAG_MAX_BYTES } from './tag-limit.ts';import { classifyImportHold, contentSizeHold, parseMarkdown, type ContentHold, type ParseOpts, type ParsedMarkdown } from './markdown.ts';import { isCodeFilePath } from './sync.ts';import { contentHash } from './utils.ts';@@ -468,6 +469,9 @@ export function screenImportContent(input: ImportScreenInput): ImportScreenResulreturn { status: 'importable', parsed, ...(fences ? { fences } : {}) };}+/** #7052: the next step of a write carrying a tag over `TAG_MAX_BYTES`. */+export const TAG_TOO_LONG_SUGGESTION = `A tag is over the ${TAG_MAX_BYTES}-byte tag limit, so the write refuses on every retry. Shorten that tag or split it into shorter tags, then submit with a new request_id.`;+/** The next step of a page write over the page limit; a page under it never needs splitting. */export const PAGE_OVER_LIMIT_SUGGESTION = `The content is over the ${MAX_FILE_SIZE}-byte page limit, so it refuses on every retry. Every page under the limit is stored and searchable; only content over it must become several pages, each submitted with its own request_id.`;@@ -503,6 +507,7 @@ export function contentRefusalFromReceipt(code: string | null | undefined, messaconst typed = CONTENT_REFUSAL_CODES.has(code!) ? code as ContentRefusal['code']: /^Invalid YAML frontmatter/.test(text) ? 'invalid_frontmatter': /slug/.test(text) ? 'frontmatter_slug_conflict'+ : TAG_TOO_LONG_MESSAGE.test(text) ? 'tag_too_long': /PAGE_JUNK_PATTERN/.test(text) ? 'content_rejected' : /which the owner purged/.test(text) ? 'purged_content' : 'file_too_large';const reason = typed !== 'invalid_frontmatter' ? undefined: /ambiguous protected key/.test(text) ? 'ambiguous_protected_key' as const@@ -514,12 +519,14 @@ export function contentRefusalFromReceipt(code: string | null | undefined, messa: 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.': typed === 'purged_content' ? 'This content was purged by the owner and stays out of the brain. Do not resubmit it; write new content, or ask the user to clear the tombstone on the brain host (gbrain pages unpurge).': typed === 'write_gate_rejected' ? 'The write gate refuses this external instruction-like content under the operator\'s write_gate.external_mode=reject setting, so it refuses on every retry. Tell the user; changing that setting is their decision.'+ : typed === 'tag_too_long' ? TAG_TOO_LONG_SUGGESTION: typed === 'visibility_noncanonical' ? 'The content asks for visibility: private in a spelling page privacy does not read, so it refuses on every retry. Write visibility: private on its own frontmatter line (lowercase key and value), then submit with a new request_id.': PAGE_OVER_LIMIT_SUGGESTION;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', 'purged_content', 'write_gate_rejected', 'visibility_noncanonical']);+const CONTENT_REFUSAL_CODES = new Set(['invalid_frontmatter', 'frontmatter_slug_conflict', 'file_too_large', 'content_rejected', 'purged_content', 'write_gate_rejected', 'visibility_noncanonical', 'tag_too_long']);+const TAG_TOO_LONG_MESSAGE = /^Tag \d+ of \d+ is \d+ bytes; a tag can be at most \d+ bytes, so the page was not written\./;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]*"\./],@@ -528,6 +535,7 @@ const LEGACY_CONTENT_MESSAGES: Array<[code: string, pattern: RegExp]> = [['invalid_params', /^File too large \(/],['invalid_params', /^[^\n]+ carries the content of page [^\n]+, which the owner purged; it was not imported\.$/],['invalid_params', /^Code file too large \(\d+ bytes\)/],+ ['invalid_params', TAG_TOO_LONG_MESSAGE],['request_too_large', /^Sync file exceeds the bounded import size\.$/],['storage_error', /^Publication failed \(PAGE_JUNK_PATTERN\)\. Inspect owner diagnostics\.$/],];diff --git a/src/core/markdown.ts b/src/core/markdown.tsindex cc5069efdd..bdd30e8800 100644--- a/src/core/markdown.ts+++ b/src/core/markdown.ts@@ -6,6 +6,7 @@ import {RECOVERY_VERSION, type FrontmatterRecovery, type RecoveryKind,} from './frontmatter-recovery.ts';import { findLineOutsideFencedCode } from './fence-scan.ts';+import { tagLengthHold } from './tag-limit.ts';export {recoverFrontmatter, RECOVERY_VERSION, PROTECTED_FRONTMATTER_KEYS, IDENTITY_FRONTMATTER_KEYS,@@ -506,7 +507,7 @@ export function resolveParsedSubtype(* file and keeps going instead of failing the whole sync. Defined once here;* managed and legacy sync, import and `validate --importable` share it.*/-export const HOLD_CODES = ['invalid_frontmatter', 'frontmatter_slug_conflict', 'file_too_large', 'rename_held', 'parser_regression'] as const;+export const HOLD_CODES = ['invalid_frontmatter', 'frontmatter_slug_conflict', 'file_too_large', 'rename_held', 'parser_regression', 'tag_too_long'] as const;export type HoldCode = typeof HOLD_CODES[number];export const INVALID_FRONTMATTER_REASONS = ['yaml_parse', 'needs_interpretation', 'ambiguous_identity_key', 'ambiguous_protected_key'] as const;export type InvalidFrontmatterReason = typeof INVALID_FRONTMATTER_REASONS[number];@@ -590,7 +591,7 @@ export function classifyImportHold(parsed: ParsedMarkdown, ctx: {return { code: 'frontmatter_slug_conflict', key: 'slug',message: ctx.slugConflictMessage?.(parsed.slug, expected) ?? `Frontmatter slug "${parsed.slug}" does not match path-derived slug "${expected}".` };}- return null;+ return tagLengthHold(parsed.tags);}/** The NULL_BYTES finding for the first NUL on 1-based `line`. */diff --git a/src/core/page-body/streamed-import.ts b/src/core/page-body/streamed-import.tsindex 3cb2b32b21..660f37b8dd 100644--- a/src/core/page-body/streamed-import.ts+++ b/src/core/page-body/streamed-import.ts@@ -344,7 +344,7 @@ async function importScanned(engine: BrainEngine, input: { file: FileHandle; bomconst sourceId = opts.sourceId ?? 'default';const parsed = { ...scan.parsed, compiled_truth: '', timeline: '' } as ParsedMarkdown;const frontmatterHold = classifyImportHold(parsed);- if (frontmatterHold) return { slug: expectedSlug, status: 'skipped', chunks: 0, error: frontmatterHold.message, refusal: frontmatterHold, skip_reason: 'invalid_frontmatter' };+ if (frontmatterHold) return { slug: expectedSlug, status: 'skipped', chunks: 0, error: frontmatterHold.message, refusal: frontmatterHold, skip_reason: frontmatterHold.code };// #7848: a private request page privacy would not read is held; only an upload session (`content` plus `coordinated`) refuses it at its own guard.const privateHold = opts.content && opts.coordinated ? null : noncanonicalPrivateHold('', parsed.frontmatter);if (privateHold) return { slug: expectedSlug, status: 'skipped', chunks: 0, error: privateHold.message, refusal: privateHold, skip_reason: privateHold.code };diff --git a/src/core/persistence/import-prepare.ts b/src/core/persistence/import-prepare.tsindex e03d188260..1cf40b8958 100644--- a/src/core/persistence/import-prepare.ts+++ b/src/core/persistence/import-prepare.ts@@ -91,6 +91,7 @@ function managedImportRefusal(refusal: ContentRefusal, sourcePath: string): Oper: refusal.code === 'content_rejected' ? `Remove the matched junk from ${sourcePath}, then import it again.`: refusal.code === 'write_gate_rejected' ? `The write gate refuses ${sourcePath} (external instruction-like content under write_gate.external_mode=reject); tell the user, the decision is theirs.`: refusal.code === 'visibility_noncanonical' ? `Write visibility: private on its own frontmatter line of ${sourcePath} (lowercase key and value), then import it again.`+ : refusal.code === 'tag_too_long' ? `Shorten the tag the message names in ${sourcePath}, or split it into shorter tags, 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' });}diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.tsindex 4cd0ffd2de..333d5ca897 100644--- a/src/core/persistence/page-prepare.ts+++ b/src/core/persistence/page-prepare.ts@@ -26,7 +26,8 @@ import { isOpPageSlug } from '../ops/context.ts';import { shellQuote, type Action } from '../agent-output.ts';import type { RegistryCode } from '../error-registry.ts';import { pageIdentityError } from './page-identity.ts';-import { contentRefusalError, PAGE_OVER_LIMIT_SUGGESTION, type ContentRefusal } from '../import-screen.ts';+import { contentRefusalError, PAGE_OVER_LIMIT_SUGGESTION, TAG_TOO_LONG_SUGGESTION, type ContentRefusal } from '../import-screen.ts';+import { tagLengthHold } from '../tag-limit.ts';import { ContentSanityBlockError } from '../content-sanity.ts';import { assertPageRevision, type PageSnapshot } from '../page-state/types.ts';import { GIT_HOLD_OP, gitHoldFingerprint, gitHoldFix, readGitHold } from './sync-holds.ts';@@ -694,6 +695,8 @@ export const segmentedTagWork = { flips: 0, hashStreams: 0 };* Null when the write gate would scan the whole body (an external_untrusted writer): that write takes the put path.*/export async function prepareSegmentedTagMutation(engine: BrainEngine, row: WriteRequest, snapshot: PageSnapshot, tags: string[]): Promise<PreparedMutation | null> {+ const tagHold = tagLengthHold(tags);+ if (tagHold) throw contentRefusalError(tagHold, TAG_TOO_LONG_SUGGESTION, { legacy_error: 'invalid_params' });const source = { sourceId: row.source_id };const [, pack, storedTier] = await Promise.all([assertKnowledgePublicationAllowed(engine, row),loadActivePackForEngine(engine, { remote: row.authority.remote, sourceId: row.source_id }).catch(() => null), storedPageTier(engine, row.source_id, row.slug)]);diff --git a/src/core/persistence/public-category.ts b/src/core/persistence/public-category.tsindex 967856df29..9bf44b8ee4 100644--- a/src/core/persistence/public-category.ts+++ b/src/core/persistence/public-category.ts@@ -55,7 +55,7 @@ export const PUBLIC_BY_CODE: Readonly<Record<string, PublicCategory>> = {slug_root_mode_mismatch: 'config', invalid_params: 'config',// GBRA-133 (#6712 PR 4b lane F): a file whose text holds NUL bytes, and a committed file whose Git object is gone.content_null_bytes: 'content_refused', git_object_missing: 'storage', path_not_utf8: 'content_refused',- visibility_noncanonical: 'content_refused',+ visibility_noncanonical: 'content_refused', tag_too_long: 'content_refused',};/** A registry code's class, for a code neither table names. */diff --git a/src/core/persistence/sync-fault-class.ts b/src/core/persistence/sync-fault-class.tsindex c58d0313d6..42aa168a08 100644--- a/src/core/persistence/sync-fault-class.ts+++ b/src/core/persistence/sync-fault-class.ts@@ -94,6 +94,9 @@ export const SYNC_FAULT_TABLE: ReadonlyArray<SyncFaultRule> = [// GBRA-130 A-7: the file is not a readable regular file inside the source root (a symlink, a non-regular file, a permission error).{ code: 'file_unreadable', class: 'page', safe_actions: ['none'], needs_human: true, escalate: 'always: only a change to the checkout makes the file readable',human_reason: 'Sync cannot read this file as a regular file inside the source root (a symlink, a non-regular file or a permission error) and never follows it; make it a readable regular file in the checkout (or exclude it with sync.exclude) and commit, then run gbrain sources retry-held <source>.' },+ // #7052: a frontmatter tag is over the tags index's byte limit; only an edit to the file clears it.+ { code: 'tag_too_long', class: 'page', safe_actions: ['none'], needs_human: true, escalate: 'always: only an edit to the file clears it',+ human_reason: 'A frontmatter tag is longer than a tag can be; shorten it or split it into shorter tags and commit.' },// #7848: the file asks for visibility: private in a spelling page privacy does not read; only an edit to the file clears it.{ code: 'visibility_noncanonical', class: 'page', safe_actions: ['none'], needs_human: true, escalate: 'always: only an edit to the file clears it',human_reason: 'The file asks for visibility: private in a spelling page privacy does not read; write visibility: private on its own frontmatter line (lowercase) and commit.' },diff --git a/src/core/persistence/sync-holds.ts b/src/core/persistence/sync-holds.tsindex 2869d53aba..15c298eb79 100644--- a/src/core/persistence/sync-holds.ts+++ b/src/core/persistence/sync-holds.ts@@ -36,6 +36,7 @@ import type { BrainEngine } from '../engine.ts';import type { Action } from '../agent-output.ts';import type { ContentRefusal } from '../import-screen.ts';import { RECOVERY_VERSION, type InvalidFrontmatterReason } from '../markdown.ts';+import { TAG_MAX_BYTES } from '../tag-limit.ts';import { ORIGIN_TWINS_AUTO_RESOLVE_KEY, originTwinsPreviewArgv, type OriginConflictReason } from './origin-twins.ts';import { FENCE_REASONS, type FenceMessageLocation } from '../fence-repair/reasons.ts';import type { FenceReason, FenceTier, GateLetter } from '../fence-repair/types.ts';@@ -885,6 +886,11 @@ export function gitHoldFix(record: Pick<GitHoldRecord, 'source_id' | 'path' | 'cuser_message: `${record.path} nests YAML aliases in its frontmatter that expand past gbrain's size limit, so sync holds it and the rest of source ${source} keeps syncing. An older gbrain imported these bytes; this version refuses them on purpose. Reduce the alias nesting in its frontmatter (or write the values out), or remove the file, then commit and run gbrain sync --source ${source} --no-pull.`,why: 'The alias bound (#7018) stops a few hundred bytes of nested anchors from expanding into gigabytes; it is intended, so the page keeps its last imported version until the file changes.',verify: { argv: ['gbrain', 'sources', 'status', source, '--json'] } };+ case 'tag_too_long':+ return { argv: ['gbrain', 'sources', 'status', source, '--json'], consent: [], actor: 'user', requires_exclusive: false, docs: gitHoldDocs(record.code),+ user_message: `${record.path} has a frontmatter tag longer than the ${TAG_MAX_BYTES} bytes a tag can be, so sync holds it and the rest of source ${source} keeps syncing. Shorten that tag or split it into shorter tags, commit, then run gbrain sync --source ${source} --no-pull.`,+ why: 'Tags are stored in an index whose entries have a fixed size limit; no frontmatter repair shortens a tag, and the hold re-screens when the file changes.',+ verify: { argv: ['gbrain', 'sources', 'status', source, '--json'] } };case 'visibility_noncanonical':return { argv: ['gbrain', 'sources', 'status', source, '--json'], consent: [], actor: 'user', requires_exclusive: false, docs: gitHoldDocs(record.code),user_message: `${record.path} asks for visibility: private in a spelling page privacy does not read (another case, a block scalar, a list, a flow mapping or a merge key), so sync holds it instead of storing a world-readable page, and the rest of source ${source} keeps syncing. Write visibility: private on its own frontmatter line (lowercase key and value), commit, then run gbrain sync --source ${source} --no-pull.`,diff --git a/src/core/repair/frontmatter.ts b/src/core/repair/frontmatter.tsindex c1d1fda76f..fcfbd82f0d 100644--- a/src/core/repair/frontmatter.ts+++ b/src/core/repair/frontmatter.ts@@ -184,6 +184,7 @@ function resolution(hold: Pick<ContentRefusal, 'code' | 'reason' | 'key' | 'linecase 'purged_content': return `${path} carries purged page content; delete or edit it and commit, or the owner clears the tombstone with gbrain pages unpurge.`;case 'write_gate_rejected': return `The write gate refused ${path} as external instruction-like content; ask the user whether to edit it or whether write_gate.external_mode should stay reject.`;case 'rename_held': return `Re-run the preview with --include-ambiguous to re-bind the rename of ${path} to the current page, or restore the old file name.`;+ case 'tag_too_long': return `${path} has a frontmatter tag over the tag size limit, which no repair shortens; shorten it or split it into shorter tags and commit.`;case 'visibility_noncanonical': return `${path} asks for visibility: private in a spelling page privacy does not read, which no repair rewrites; write visibility: private on its own frontmatter line (lowercase) and commit.`;case 'parser_regression': return `This is a gbrain bug: report the gbrain version, ${path} and the code; upgrade, or keep GBRAIN_SYNC_PARSER_REGRESSION=hold set for the process that syncs; never pin a release older than 0.60.305.0.`;default: return hold.reason === 'ambiguous_protected_key' ? `Write ${where} on one line with one quoted value; gbrain never guesses who may read a page or where it came from.`diff --git a/src/core/tag-limit.ts b/src/core/tag-limit.tsnew file mode 100644index 0000000000..332ac94e6a--- /dev/null+++ b/src/core/tag-limit.ts@@ -0,0 +1,19 @@+/**+ * #7052: the tag byte limit, checked by `classifyImportHold` (every content screen) and the segmented-page tag flip.+ */+import type { ContentHold } from './markdown.ts';++/**+ * The longest tag, in UTF-8 bytes, both btree indexes on `tags` store. A btree v4 entry is at most 2704 bytes+ * on an 8 kB page; `UNIQUE(page_id, tag)` spends 16 of them (tuple header, page_id, the text length word). Counting+ * bytes, not characters, keeps multibyte tags inside the bound; a longer tag failed the insert with error 54000.+ */+export const TAG_MAX_BYTES = 2688;++/** The `tag_too_long` hold for the first tag over `TAG_MAX_BYTES`, or null. Names the tag's position and size, never its text. */+export function tagLengthHold(tags: readonly string[]): ContentHold | null {+ const index = tags.findIndex(tag => Buffer.byteLength(tag, 'utf-8') > TAG_MAX_BYTES);+ if (index < 0) return null;+ return { code: 'tag_too_long', key: 'tags', message: `Tag ${index + 1} of ${tags.length} is ${Buffer.byteLength(tags[index]!, 'utf-8')} bytes; `+ + `a tag can be at most ${TAG_MAX_BYTES} bytes, so the page was not written. Shorten that tag or split it into shorter tags, then write the page again.` };+}diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.jsonindex 57e6b83586..cd4d3c0964 100644--- a/test/fixtures/goldens/exports/types.json+++ b/test/fixtures/goldens/exports/types.json@@ -4672,7 +4672,7 @@"searchable?: boolean | \"pending\" | undefined","searchable_fix?: Record<string, unknown> | undefined","searchable_retry_after_ms?: number | undefined",- "skip_reason?: \"purged_content\" | \"content_rejected\" | \"file_too_large\" | \"frontmatter_slug_conflict\" | \"invalid_fence\" | \"invalid_frontmatter\" | \"parser_regression\" | \"rename_held\" | \"visibility_noncanonical\" | \"write_gate_rejected\" | \"malformed_path\" | \"slug_collision\" | undefined",+ "skip_reason?: \"purged_content\" | \"content_rejected\" | \"file_too_large\" | \"frontmatter_slug_conflict\" | \"invalid_fence\" | \"invalid_frontmatter\" | \"parser_regression\" | \"rename_held\" | \"tag_too_long\" | \"visibility_noncanonical\" | \"write_gate_rejected\" | \"malformed_path\" | \"slug_collision\" | undefined","slug: string","status: \"error\" | \"imported\" | \"skipped\"","type_warning?: { kind: \"alias_of\" | \"undeclared\"; type: string; canonical?: string; directory?: string; } | undefined"@@ -5475,7 +5475,7 @@{"kind": "interface","members": [- "code: \"file_too_large\" | \"frontmatter_slug_conflict\" | \"invalid_frontmatter\" | \"parser_regression\" | \"rename_held\"",+ "code: \"file_too_large\" | \"frontmatter_slug_conflict\" | \"invalid_frontmatter\" | \"parser_regression\" | \"rename_held\" | \"tag_too_long\"","intended?: \"yaml_alias_limit\" | undefined","key?: string | undefined","line?: number | undefined",@@ -5528,14 +5528,14 @@"kind": "variable","name": "HOLD_CODES","signature": [- "readonly [\"invalid_frontmatter\", \"frontmatter_slug_conflict\", \"file_too_large\", \"rename_held\", \"parser_regression\"]"+ "readonly [\"invalid_frontmatter\", \"frontmatter_slug_conflict\", \"file_too_large\", \"rename_held\", \"parser_regression\", \"tag_too_long\"]"]},{"kind": "type","name": "HoldCode","signature": [- "\"file_too_large\" | \"frontmatter_slug_conflict\" | \"invalid_frontmatter\" | \"parser_regression\" | \"rename_held\""+ "\"file_too_large\" | \"frontmatter_slug_conflict\" | \"invalid_frontmatter\" | \"parser_regression\" | \"rename_held\" | \"tag_too_long\""]},{@@ -6487,7 +6487,7 @@{"kind": "class","members": [- "canonical?: \"unknown\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"timeout\" | \"rate_limited\" | \"embedding_disabled\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"write_quota_exhausted\" | \"write_quota_insufficient\" | \"write_capacity_backpressure\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"purged_content\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"page_body_segmented\" | \"revision_changed\" | \"tail_changed\" | \"write_outcome_unknown\" | \"write_interrupted\" | \"connection_inherited_read_only\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"absent_from_worktree\" | \"access_command_failed\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"admission_paused\" | \"ambient_capture_off\" | \"ambiguous_id\" | \"ambiguous_ref\" | \"ambiguous_skill\" | \"answer_not_yours\" | \"answer_pending\" | \"answer_unavailable\" | \"api_not_enabled\" | \"approval_required\" | \"atom_drain_incomplete\" | \"atom_drain_no_progress\" | \"atom_drain_provider_failure\" | \"autopilot_job_owned_by_other_brain\" | \"body_staging_expired\" | \"budget_below_recent_runtime\" | \"backup_dump_failed\" | \"backup_too_large\" | \"belief_coverage_required\" | \"belief_stale_preparation\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_cleanup_pending\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"coverage_from\" | \"coverage_gap\" | \"clock_mismatch\" | \"extract_write_lost\" | \"item_failures_systemic\" | \"known_as_of_unproven\" | \"cache_quota_exceeded\" | \"calendar_unreadable\" | \"capacity_paused\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"no_pricing\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_not_found\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"commit_lock_busy\" | \"commit_paths_invalid\" | \"commit_prestaged_paths\" | \"commit_outside_source_root\" | \"concurrent_write\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"connection_lost\" | \"chunkless_pages_healable\" | \"consent_required\" | \"consent_timeout\" | \"consumers_without_heartbeat\" | \"content_repair_needs_human\" | \"content_null_bytes\" | \"content_rejected\" | \"continuation_unproven\" | \"corpus_chat_unavailable\" | \"corpus_window_backoff\" | \"corpus_window_dead_lettered\" | \"convergence_read_failed\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cursor_incarnation_retired\" | \"cycle_failed\" | \"d_sel_too_small\" | \"delta_cursor_upgrade_required\" | \"deleted_page_chunks_overdue\" | \"demo_graph_failed\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"drain_holder_stalled\" | \"drain_stalled\" | \"managed_sync_not_moving\" | \"dream_breaker_tripped\" | \"dirty_tree\" | \"doctor_tier_unavailable\" | \"effect_not_failed\" | \"embed_backfill_stalled\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_identity_unqualified\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_state_unknown\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"engine_graduated\" | \"entity_types_unavailable\" | \"eval_suite_unwired\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"fact_withdrawn\" | \"fact_rows_collide\" | \"fence_row_changed\" | \"facts_absorb_write_refused\" | \"facts_backstop_skipped\" | \"facts_drain_deferred\" | \"facts_drain_job_failed\" | \"facts_payload_expired\" | \"feedback_disabled\" | \"feedback_not_authorized\" | \"fetch_failed\" | \"file_database_drift\" | \"fix_not_writable\" | \"file_drift\" | \"file_drift_mixed_selection\" | \"file_drift_state_required\" | \"file_removed_during_scan\" | \"file_unreadable\" | \"file_wins_rewrite\" | \"file_too_large\" | \"follow_approval_required\" | \"forget_requires_owner\" | \"reserved_frontmatter_key\" | \"generation_fenced\" | \"generation_held\" | \"generation_live_conflict\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"ghost_mass_delete_refused\" | \"notifier_stalled\" | \"origin_twin_mass_merge_refused\" | \"ghost_storage_unknown\" | \"git_branch_unborn\" | \"git_durability_not_enabled\" | \"git_checkout_required\" | \"git_worktree_link_broken\" | \"hosted_repo_refused\" | \"git_detached_head\" | \"git_index_conflict\" | \"git_index_locked\" | \"git_index_stale\" | \"git_target_pending\" | \"git_operation_in_progress\" | \"git_push_unavailable\" | \"git_target_changed\" | \"git_target_ignored\" | \"git_target_unsafe\" | \"git_unavailable\" | \"git_object_missing\" | \"git_conversion_blocked\" | \"git_conversion_incomplete\" | \"git_home_required\" | \"git_private_commit_refused\" | \"git_protocol_required\" | \"git_lfs_not_enabled\" | \"gitlink_not_followed\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"grant_scope\" | \"graph_incomplete\" | \"host_identity_mismatch\" | \"harness_hook_duplicates\" | \"harness_hook_unowned\" | \"head_blocked\" | \"held_failed\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"integrate_conflict\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_acknowledgment\" | \"invalid_client\" | \"invalid_fence\" | \"unclosed_ambiguous_tail\" | \"tail_exposure_approval\" | \"sync_in_progress\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_rating\" | \"invalid_receipt\" | \"invalid_receipt_transition\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"ipc_path_too_long\" | \"legacy_twin_mass_merge_refused\" | \"legacy_twins_storage_unknown\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"legacy_lock_removal_refused\" | \"link_cursor_invalid\" | \"local_conflict\" | \"lock_busy\" | \"loops_extraction_skipped\" | \"maintenance_backpressure\" | \"maintenance_lock_busy\" | \"managed_failure_unsettled\" | \"managed_remedy_unavailable\" | \"merge_recommended\" | \"movement_unknown\" | \"managed_sync_flag_refused\" | \"managed_pull_skipped\" | \"manual_only_skipped\" | \"membership_inactive\" | \"membership_not_found\" | \"method_not_allowed\" | \"migration_lease_lost\" | \"migration_declined\" | \"migration_failed\" | \"migration_host_work_pending\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_context_ceiling\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_converged\" | \"not_owner_host\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"page_projection_conflict\" | \"page_body_rows_unreadable\" | \"page_projection_stale\" | \"page_shrink_refused\" | \"page_too_large_for_inline\" | \"parse_error\" | \"part_splits_code_point\" | \"part_too_large\" | \"frontmatter_alias_limit\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"path_not_utf8\" | \"pattern_claims_pending\" | \"patterns_min_interval\" | \"pending_verify\" | \"pending_writes\" | \"persistence_restart_required\" | \"pool_inflight_over_budget\" | \"deep_health_probe_failed\" | \"refresh_required\" | \"serve_self_exit_suppressed\" | \"serve_unhealthy_exit\" | \"persistence_write_stall\" | \"push_unconfirmed\" | \"schema_lock_blocked\" | \"pg_connection_recovery_failed\" | \"pg_connection_stuck\" | \"pg_pool_stalled\" | \"pg_statement_build_failed\" | \"pglite_busy\" | \"pglite_vector_index_too_large\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"knock_on_exhausted\" | \"keyword_skipped_after_timeout\" | \"publication_pending\" | \"pull_blocked_local_changes\" | \"purge_blocked_pending_recovery\" | \"purge_lookup_timeout\" | \"purge_mirror_unwritable\" | \"question_not_found\" | \"question_owner_only\" | \"rank_entities_timeout\" | \"read_budget_exhausted\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"pat_file_unreadable\" | \"reconcile_host_required\" | \"reconcile_read_incomplete\" | \"recovery_prior_stage_unavailable\" | \"recovery_version_unsupported\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"refresh_source_changed\" | \"refresh_sync_timeout\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"rename_identity_unreadable\" | \"rename_reconcile_failed\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"restart_refused\" | \"restart_unverified\" | \"runtime_build_skew\" | \"reset_upstream_refused\" | \"resume_spec_mismatch\" | \"result_too_large\" | \"revision_unavailable\" | \"schema_owner_required\" | \"scope_missing\" | \"search_cursor_requires_keyword\" | \"search_mode_local_only\" | \"scorecard_group_by_local_only\" | \"search_offset_over_cap\" | \"segmented_mirror_writer_gate\" | \"serve_build_drift\" | \"serve_port_in_use\" | \"serve_status_only\" | \"settle_mismatch\" | \"setup_harness_unsupported\" | \"setup_hosted_connection\" | \"setup_owner_conflict\" | \"turn_hook_not_loaded\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_retention_capacity\" | \"skill_unavailable\" | \"slug_page_mismatch\" | \"slug_root_mode_mismatch\" | \"source_binding_required\" | \"source_id_taken\" | \"source_mismatch\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_referenced\" | \"source_root_conflict\" | \"sources_not_readable\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stable_channel_unresolved\" | \"stale_unavailable\" | \"state_mismatch\" | \"strict_requires_managed\" | \"sync_anchor_relative\" | \"sync_not_applicable\" | \"sync_admission_restricted\" | \"sync_deadline_stalled\" | \"sync_drain_lease_held\" | \"content_receipt_stale\" | \"sync_first_run_in_progress\" | \"sync_no_successful_sync\" | \"sync_cursor_replaced\" | \"sync_pass_superseded\" | \"sync_parser_regression\" | \"target_escape\" | \"timeline_comment_markup\" | \"topology_change_required\" | \"transcript_secret_exposure\" | \"transcript_source_mismatch\" | \"triage_unreliable_backoff\" | \"trust_raise_refused\" | \"two_consumers_on_host\" | \"trusted_local_only\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unpriced_model\" | \"unmanaged_database_path\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"unsupported_path\" | \"upload_expired\" | \"upload_not_found\" | \"upload_protected_content\" | \"upload_too_many_parts\" | \"upstream\" | \"upstream_diverged\" | \"upstream_rewritten\" | \"upstream_unknown\" | \"vector_prewarm_extension_missing\" | \"vector_prewarm_unsupported_engine\" | \"vector_prewarm_wont_fit\" | \"verification_failed\" | \"visibility_noncanonical\" | \"visibility_not_applied\" | \"withdrawal_capacity\" | \"withdrawal_mirror_failed\" | \"withdrawal_mirror_pending\" | \"withdrawal_provenance\" | \"write_capacity_low\" | \"write_gate_rejected\" | \"write_held\" | \"worktree_dirty\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_rescope_required\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | \"schema_pack_too_large\" | \"schema_pack_emit_mismatch\" | undefined",+ "canonical?: \"unknown\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"timeout\" | \"rate_limited\" | \"embedding_disabled\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"write_quota_exhausted\" | \"write_quota_insufficient\" | \"write_capacity_backpressure\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"purged_content\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"page_body_segmented\" | \"revision_changed\" | \"tail_changed\" | \"write_outcome_unknown\" | \"write_interrupted\" | \"connection_inherited_read_only\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"absent_from_worktree\" | \"access_command_failed\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"admission_paused\" | \"ambient_capture_off\" | \"ambiguous_id\" | \"ambiguous_ref\" | \"ambiguous_skill\" | \"answer_not_yours\" | \"answer_pending\" | \"answer_unavailable\" | \"api_not_enabled\" | \"approval_required\" | \"atom_drain_incomplete\" | \"atom_drain_no_progress\" | \"atom_drain_provider_failure\" | \"autopilot_job_owned_by_other_brain\" | \"body_staging_expired\" | \"budget_below_recent_runtime\" | \"backup_dump_failed\" | \"backup_too_large\" | \"belief_coverage_required\" | \"belief_stale_preparation\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_cleanup_pending\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"coverage_from\" | \"coverage_gap\" | \"clock_mismatch\" | \"extract_write_lost\" | \"item_failures_systemic\" | \"known_as_of_unproven\" | \"cache_quota_exceeded\" | \"calendar_unreadable\" | \"capacity_paused\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"no_pricing\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_not_found\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"commit_lock_busy\" | \"commit_paths_invalid\" | \"commit_prestaged_paths\" | \"commit_outside_source_root\" | \"concurrent_write\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"connection_lost\" | \"chunkless_pages_healable\" | \"consent_required\" | \"consent_timeout\" | \"consumers_without_heartbeat\" | \"content_repair_needs_human\" | \"content_null_bytes\" | \"content_rejected\" | \"continuation_unproven\" | \"corpus_chat_unavailable\" | \"corpus_window_backoff\" | \"corpus_window_dead_lettered\" | \"convergence_read_failed\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cursor_incarnation_retired\" | \"cycle_failed\" | \"d_sel_too_small\" | \"delta_cursor_upgrade_required\" | \"deleted_page_chunks_overdue\" | \"demo_graph_failed\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"drain_holder_stalled\" | \"drain_stalled\" | \"managed_sync_not_moving\" | \"dream_breaker_tripped\" | \"dirty_tree\" | \"doctor_tier_unavailable\" | \"effect_not_failed\" | \"embed_backfill_stalled\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_identity_unqualified\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_state_unknown\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"engine_graduated\" | \"entity_types_unavailable\" | \"eval_suite_unwired\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"fact_withdrawn\" | \"fact_rows_collide\" | \"fence_row_changed\" | \"facts_absorb_write_refused\" | \"facts_backstop_skipped\" | \"facts_drain_deferred\" | \"facts_drain_job_failed\" | \"facts_payload_expired\" | \"feedback_disabled\" | \"feedback_not_authorized\" | \"fetch_failed\" | \"file_database_drift\" | \"fix_not_writable\" | \"file_drift\" | \"file_drift_mixed_selection\" | \"file_drift_state_required\" | \"file_removed_during_scan\" | \"file_unreadable\" | \"file_wins_rewrite\" | \"file_too_large\" | \"follow_approval_required\" | \"forget_requires_owner\" | \"reserved_frontmatter_key\" | \"generation_fenced\" | \"generation_held\" | \"generation_live_conflict\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"ghost_mass_delete_refused\" | \"notifier_stalled\" | \"origin_twin_mass_merge_refused\" | \"ghost_storage_unknown\" | \"git_branch_unborn\" | \"git_durability_not_enabled\" | \"git_checkout_required\" | \"git_worktree_link_broken\" | \"hosted_repo_refused\" | \"git_detached_head\" | \"git_index_conflict\" | \"git_index_locked\" | \"git_index_stale\" | \"git_target_pending\" | \"git_operation_in_progress\" | \"git_push_unavailable\" | \"git_target_changed\" | \"git_target_ignored\" | \"git_target_unsafe\" | \"git_unavailable\" | \"git_object_missing\" | \"git_conversion_blocked\" | \"git_conversion_incomplete\" | \"git_home_required\" | \"git_private_commit_refused\" | \"git_protocol_required\" | \"git_lfs_not_enabled\" | \"gitlink_not_followed\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"grant_scope\" | \"graph_incomplete\" | \"host_identity_mismatch\" | \"harness_hook_duplicates\" | \"harness_hook_unowned\" | \"head_blocked\" | \"held_failed\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"integrate_conflict\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_acknowledgment\" | \"invalid_client\" | \"invalid_fence\" | \"unclosed_ambiguous_tail\" | \"tail_exposure_approval\" | \"sync_in_progress\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_rating\" | \"invalid_receipt\" | \"invalid_receipt_transition\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"ipc_path_too_long\" | \"legacy_twin_mass_merge_refused\" | \"legacy_twins_storage_unknown\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"legacy_lock_removal_refused\" | \"link_cursor_invalid\" | \"local_conflict\" | \"lock_busy\" | \"loops_extraction_skipped\" | \"maintenance_backpressure\" | \"maintenance_lock_busy\" | \"managed_failure_unsettled\" | \"managed_remedy_unavailable\" | \"merge_recommended\" | \"movement_unknown\" | \"managed_sync_flag_refused\" | \"managed_pull_skipped\" | \"manual_only_skipped\" | \"membership_inactive\" | \"membership_not_found\" | \"method_not_allowed\" | \"migration_lease_lost\" | \"migration_declined\" | \"migration_failed\" | \"migration_host_work_pending\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_context_ceiling\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_converged\" | \"not_owner_host\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"page_projection_conflict\" | \"page_body_rows_unreadable\" | \"page_projection_stale\" | \"page_shrink_refused\" | \"page_too_large_for_inline\" | \"parse_error\" | \"part_splits_code_point\" | \"part_too_large\" | \"frontmatter_alias_limit\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"path_not_utf8\" | \"pattern_claims_pending\" | \"patterns_min_interval\" | \"pending_verify\" | \"pending_writes\" | \"persistence_restart_required\" | \"pool_inflight_over_budget\" | \"deep_health_probe_failed\" | \"refresh_required\" | \"serve_self_exit_suppressed\" | \"serve_unhealthy_exit\" | \"persistence_write_stall\" | \"push_unconfirmed\" | \"schema_lock_blocked\" | \"pg_connection_recovery_failed\" | \"pg_connection_stuck\" | \"pg_pool_stalled\" | \"pg_statement_build_failed\" | \"pglite_busy\" | \"pglite_vector_index_too_large\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"knock_on_exhausted\" | \"keyword_skipped_after_timeout\" | \"publication_pending\" | \"pull_blocked_local_changes\" | \"purge_blocked_pending_recovery\" | \"purge_lookup_timeout\" | \"purge_mirror_unwritable\" | \"question_not_found\" | \"question_owner_only\" | \"rank_entities_timeout\" | \"read_budget_exhausted\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"pat_file_unreadable\" | \"reconcile_host_required\" | \"reconcile_read_incomplete\" | \"recovery_prior_stage_unavailable\" | \"recovery_version_unsupported\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"refresh_source_changed\" | \"refresh_sync_timeout\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"rename_identity_unreadable\" | \"rename_reconcile_failed\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"restart_refused\" | \"restart_unverified\" | \"runtime_build_skew\" | \"reset_upstream_refused\" | \"resume_spec_mismatch\" | \"result_too_large\" | \"revision_unavailable\" | \"schema_owner_required\" | \"scope_missing\" | \"search_cursor_requires_keyword\" | \"search_mode_local_only\" | \"scorecard_group_by_local_only\" | \"search_offset_over_cap\" | \"segmented_mirror_writer_gate\" | \"serve_build_drift\" | \"serve_port_in_use\" | \"serve_status_only\" | \"settle_mismatch\" | \"setup_harness_unsupported\" | \"setup_hosted_connection\" | \"setup_owner_conflict\" | \"turn_hook_not_loaded\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_retention_capacity\" | \"skill_unavailable\" | \"slug_page_mismatch\" | \"slug_root_mode_mismatch\" | \"source_binding_required\" | \"source_id_taken\" | \"source_mismatch\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_referenced\" | \"source_root_conflict\" | \"sources_not_readable\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stable_channel_unresolved\" | \"stale_unavailable\" | \"state_mismatch\" | \"strict_requires_managed\" | \"sync_anchor_relative\" | \"sync_not_applicable\" | \"sync_admission_restricted\" | \"sync_deadline_stalled\" | \"sync_drain_lease_held\" | \"content_receipt_stale\" | \"sync_first_run_in_progress\" | \"sync_no_successful_sync\" | \"sync_cursor_replaced\" | \"sync_pass_superseded\" | \"sync_parser_regression\" | \"tag_too_long\" | \"target_escape\" | \"timeline_comment_markup\" | \"topology_change_required\" | \"transcript_secret_exposure\" | \"transcript_source_mismatch\" | \"triage_unreliable_backoff\" | \"trust_raise_refused\" | \"two_consumers_on_host\" | \"trusted_local_only\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unpriced_model\" | \"unmanaged_database_path\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"unsupported_path\" | \"upload_expired\" | \"upload_not_found\" | \"upload_protected_content\" | \"upload_too_many_parts\" | \"upstream\" | \"upstream_diverged\" | \"upstream_rewritten\" | \"upstream_unknown\" | \"vector_prewarm_extension_missing\" | \"vector_prewarm_unsupported_engine\" | \"vector_prewarm_wont_fit\" | \"verification_failed\" | \"visibility_noncanonical\" | \"visibility_not_applied\" | \"withdrawal_capacity\" | \"withdrawal_mirror_failed\" | \"withdrawal_mirror_pending\" | \"withdrawal_provenance\" | \"write_capacity_low\" | \"write_gate_rejected\" | \"write_held\" | \"worktree_dirty\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_rescope_required\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | \"schema_pack_too_large\" | \"schema_pack_emit_mismatch\" | undefined","canonicalCode: string","cause?: unknown","code: ErrorCode",diff --git a/test/frontmatter-recovery.test.ts b/test/frontmatter-recovery.test.tsindex 1de1bee9a2..51e4eda62c 100644--- a/test/frontmatter-recovery.test.ts+++ b/test/frontmatter-recovery.test.ts@@ -182,7 +182,7 @@ describe('contract surfaces', () => {});test('HOLD_CODES is the canonical hold set', () => {- expect([...HOLD_CODES]).toEqual(['invalid_frontmatter', 'frontmatter_slug_conflict', 'file_too_large', 'rename_held', 'parser_regression']);+ expect([...HOLD_CODES]).toEqual(['invalid_frontmatter', 'frontmatter_slug_conflict', 'file_too_large', 'rename_held', 'parser_regression', 'tag_too_long']);});test('slug conflicts hold unless the recorded-origin exemption applies', () => {diff --git a/test/large-pages/segmented-semantic-writes.test.ts b/test/large-pages/segmented-semantic-writes.test.tsindex 6482cedd74..eeb198690b 100644--- a/test/large-pages/segmented-semantic-writes.test.ts+++ b/test/large-pages/segmented-semantic-writes.test.ts@@ -210,6 +210,14 @@ for (const kind of testBackends()) {} finally { Object.assign(e, { stageSegmentTexts: originals.texts, stageManifestRows: originals.manifest, stageSegmentChunks: originals.chunks }); }}, 600_000);+ test('#7052: add_tag with a tag over the tag byte limit refuses tag_too_long on the segmented page and changes nothing', async () => {+ const before = await counts();+ const refused = await call('add_tag', { slug: HUGE, tag: 'x'.repeat(3000) });+ expect(refused.code ?? refused.error).toBe('tag_too_long');+ expect(await counts()).toEqual(before);+ expect((await brain.engine.readPageSnapshot(HUGE, { sourceId: brain.sourceId }))!.tags).toEqual([]);+ }, 600_000);+test('timeline, takes and facts writes refuse page_body_segmented naming the 24 MiB limit and change nothing', async () => {const before = await counts();const fileBefore = fileBody();diff --git a/test/tag-length-7052.test.ts b/test/tag-length-7052.test.tsnew file mode 100644index 0000000000..3fb8b3aa06--- /dev/null+++ b/test/tag-length-7052.test.ts@@ -0,0 +1,103 @@+/**+ * #7052 — a tag longer than the btree indexes on `tags` store is refused at the+ * write boundary as `tag_too_long` (put_page, add_tag, file import, the shared+ * content screen sync uses) instead of failing the insert with error 54000 and+ * reporting `storage_error`. The bound counts UTF-8 bytes, so multibyte tags+ * are measured as stored; a tag exactly at the bound stores.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { randomInt } from 'node:crypto';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { dispatchToolCall } from '../src/mcp/dispatch.ts';+import { classifyImportHold, parseMarkdown } from '../src/core/markdown.ts';+import { TAG_MAX_BYTES } from '../src/core/tag-limit.ts';+import { contentRefusalFromReceipt, isContentRefusal, screenImportContent } from '../src/core/import-screen.ts';+import { importFromFile } from '../src/core/import-file.ts';++const config = { engine: 'pglite' } as never;+const LOCAL = { remote: false, sourceId: 'default', config };+const REMOTE = { remote: true, transport: 'stdio' as const, sourceId: 'default', takesHoldersAllowList: ['world'], config };++/** `bytes` of incompressible text: random 3-byte CJK characters, padded with ASCII letters. */+function randomTag(bytes: number): string {+ let tag = '';+ while (Buffer.byteLength(tag) + 3 <= bytes) tag += String.fromCodePoint(0x4e00 + randomInt(0x5000));+ while (Buffer.byteLength(tag) < bytes) tag += String.fromCharCode(97 + randomInt(26));+ return tag;+}+const page = (tags: string[]) => `---\ntitle: Tagged\ntags: [${tags.map(t => JSON.stringify(t)).join(', ')}]\n---\n\nBody text.\n`;++let engine: PGLiteEngine;+let dir: string;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ dir = mkdtempSync(join(tmpdir(), 'gbrain-7052-'));+}, 120_000);++afterAll(async () => {+ if (engine) await engine.disconnect();+ rmSync(dir, { recursive: true, force: true });+}, 60_000);++async function call(op: string, args: Record<string, unknown>, ctx: Record<string, unknown>) {+ const r = await dispatchToolCall(engine, op, args, ctx as never);+ return { isError: r.isError === true, body: JSON.parse(r.content[0].text) as Record<string, unknown> };+}++describe('#7052 tag byte limit', () => {+ test('the bound is the real one: an incompressible tag at the bound stores, one byte over fails the index', async () => {+ await engine.putPage('notes/bound', { type: 'note', title: 'Bound', compiled_truth: 'x', frontmatter: {} }, { sourceId: 'default' });+ const atLimit = randomTag(TAG_MAX_BYTES);+ expect(Buffer.byteLength(atLimit)).toBe(TAG_MAX_BYTES);+ await engine.addTag('notes/bound', atLimit, { sourceId: 'default' });+ expect(await engine.getTags('notes/bound', { sourceId: 'default' })).toEqual([atLimit]);+ await expect(engine.addTag('notes/bound', randomTag(TAG_MAX_BYTES + 1), { sourceId: 'default' })).rejects.toThrow(/index row size/);+ });++ test('the shared screen holds a tag over the bound by its byte length, naming position and size but not the text', () => {+ const over = randomTag(TAG_MAX_BYTES + 1);+ expect(over.length).toBeLessThan(TAG_MAX_BYTES);+ expect(classifyImportHold(parseMarkdown(page(['ok', randomTag(TAG_MAX_BYTES)]), 'notes/a.md', { validate: true }))).toBeNull();+ const hold = classifyImportHold(parseMarkdown(page(['ok', over]), 'notes/a.md', { validate: true }))!;+ expect(hold).toEqual(expect.objectContaining({ code: 'tag_too_long', key: 'tags' }));+ expect(hold.message).toContain(`Tag 2 of 2 is ${TAG_MAX_BYTES + 1} bytes`);+ expect(hold.message).not.toContain(over.slice(0, 20));+ const screen = screenImportContent({ content: page([over]), path: 'notes/a.md', expectedSlug: 'notes/a' });+ expect(screen).toEqual({ status: 'refused', refusal: expect.objectContaining({ code: 'tag_too_long' }) });+ expect(isContentRefusal('invalid_params', hold.message)).toBe(true);+ expect(contentRefusalFromReceipt('invalid_params', hold.message)?.code).toBe('tag_too_long');+ });++ test('put_page refuses tag_too_long for local and remote callers and writes nothing', async () => {+ for (const [i, ctx] of [LOCAL, REMOTE].entries()) {+ const slug = `notes/put-${i}`;+ const r = await call('put_page', { slug, content: page(['ok', randomTag(3200)]) }, ctx);+ expect(r.isError).toBe(true);+ expect(r.body.code).toBe('tag_too_long');+ expect(String(r.body.suggestion)).toContain('Shorten that tag');+ expect(await engine.getPage(slug, { sourceId: 'default' })).toBeNull();+ }+ });++ test('add_tag refuses tag_too_long and leaves the page\'s tags as they were', async () => {+ expect((await call('put_page', { slug: 'notes/add', content: page(['ok']) }, LOCAL)).isError).toBe(false);+ const r = await call('add_tag', { slug: 'notes/add', tag: randomTag(3200) }, REMOTE);+ expect(r.isError).toBe(true);+ expect(r.body.code).toBe('tag_too_long');+ expect(await engine.getTags('notes/add', { sourceId: 'default' })).toEqual(['ok']);+ });++ test('a file import skips the file as tag_too_long instead of failing the insert', async () => {+ const file = join(dir, 'imported.md');+ writeFileSync(file, page([randomTag(3200)]));+ const result = await importFromFile(engine, file, 'notes/imported.md', { noEmbed: true } as never);+ expect(result).toEqual(expect.objectContaining({ status: 'skipped', skip_reason: 'tag_too_long', refusal: expect.objectContaining({ code: 'tag_too_long' }) }));+ expect(await engine.getPage('notes/imported', { sourceId: 'default' })).toBeNull();+ });+});