Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
#6712 PR 4b lane F: a committed name that is not UTF-8 is held path_not_utf8 with its rename (GBRA-133 S-7)
garrytanf04ccd31f699
diff --git a/docs/architecture/key-files/files-and-sync-2.md b/docs/architecture/key-files/files-and-sync-2.mdindex b4f7f343a8..d5569f39c3 100644--- a/docs/architecture/key-files/files-and-sync-2.md+++ b/docs/architecture/key-files/files-and-sync-2.md@@ -22,7 +22,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/persistence/sync-prescreen.ts` — #6712 PR 1 (L1): the discovery prescreen and drift baseline. After `discoverManagedSync` freezes identities, `prescreenSyncEntries` reads the pinned blobs (`readTreeBlobs`, one recursive listing for a large set) and the import provenance of every Git import of an existing page, and `classifyBaseline` marks each `prescreened` (disk blob, revision and `syncImportParserFor` fingerprint all match; bypassed under `--full` and for held paths) or `drift` (`database`: the page moved, the file did not; `both`/`unknown` in a tree walk or for a `file_drift` hold). A page whose current revision a committed managed-sync request wrote, or whose writer's publication wrote to its file (a write-through `git` effect), is not guarded (`fileBackedRevisions`), and drifted pages under `storage.keep_db` prefixes leave the manifest as drift candidates (`releaseKeepDbDrift`, `recordDriftSkip`). The run passes prescreened entries through `waivePrescreenedRun` (`sync-waivers.ts`); `freezeEntry` holds a drifted import `file_drift` (`fileDriftHold`, `sync-page-fault.ts`) unless `sameContentAtOrigin` proves it a no-op. `movedDriftHolds` re-screens drift holds whose page moved. Tests: `test/sync-prescreen-drift-6712.test.ts` (both engines).- `src/core/persistence/sync-image.ts` — #6529: managed sync's image branch. With multimodal embedding on, `freezeEntry` (`sync-run.ts`) freezes an image entry as its bytes in base64 (`frozenImageIntent`; `rawHash` stays the file sha256, so the working-tree check and the hash no-op are unchanged) and `prepareManagedSyncMutation` (`sync-prepare.ts`) hands it to `prepareManagedSyncImage`, which runs `importImageFile` with `prepare` (the coordinated path `gbrain import` uses in `import-prepare.ts`): the importer decides the hash no-op, OCRs and embeds the image at preparation inside the sync budget (`--no-embed` skips both; the caption chunk's text vector is deferred to `embed --stale`), and the apply records `source_path`, releases the path's hold and re-reads the snapshot. A company plan refuses (`profile_incompatible`), a screening preparation (`sameContentAtOrigin`, the no-op waiver in `sync-waivers.ts` and `unchangedManagedImport` in `import-mutations.ts` return early for images) is refused rather than paid for, newer working-tree bytes or a vanished file refuse `source_changed`, and a Git rename publishes the new slug and soft-deletes the old page. `import-file.ts` records `source_path` on the legacy importer's hash-skip path too (`refreshSourcePath`), so no image import leaves it NULL. Tests: `test/managed-sync-images-5493.test.ts` (both engines), `test/embed-stale-images-managed-6529.test.ts`.- `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`. `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` is held under its code, 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/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/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`); 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?, 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) 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 3def5382e6..16ade8e9ca 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -2660,6 +2660,16 @@ More: [docs/guides/google-connect.md#troubleshooting](../../docs/guides/google-c|---|---|---|---|---|---|---|| The --pat-file token file is missing, empty, holds more than one token, or is readable by other users, so it was not read. | The token is read from a private file so it never appears on a command line or in a process list; a file other users can read would leak it, so the verb refuses before any credential is written. | Write exactly one token on one line to a file, chmod 600 it, and pass its path with --pat-file. | agent | `repeat the read that failed` | 1 | no |+### path_not_utf8++<a id="path_not_utf8"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| A committed file's name is not valid UTF-8, so managed sync holds that file alone. | Git hands the name back with U+FFFD for the bytes that are not UTF-8 (a Latin-1 name from an older system, an archive or a network share), and no Git read or file matches that decoded name, so nothing is imported from it. The rest of the source keeps syncing. | Rename the file to a UTF-8 name (git ls-files with core.quotePath shows its exact bytes; convmv -f latin1 -t utf8 converts a Latin-1 name), commit, then sync again; the rename clears the hold. | agent | `repeat the read that failed` | 1 | no |++More: [docs/guides/write-refusals.md#path_not_utf8](../../docs/guides/write-refusals.md#path_not_utf8)+### pattern_claims_pending<a id="pattern_claims_pending"></a>diff --git a/docs/guides/sync-unblock-runbook.md b/docs/guides/sync-unblock-runbook.mdindex d1c1a8c26f..d28239fdd6 100644--- a/docs/guides/sync-unblock-runbook.md+++ b/docs/guides/sync-unblock-runbook.md@@ -142,6 +142,7 @@ Every hold and error has three fields, from one table| `file_unreadable` | page | none | yes | always: only a change to the checkout makes the file readable || `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 |+| `path_not_utf8` | page | none | yes | always: only renaming the file clears it || `origin_conflict` | page | repair | no | the hold carries a reason (the pages differ, ids conflict or none is the page the path names), or the heal is off || `origin_conflict_decision` | page | none | yes | always: the pages differ, their ids conflict or none is the page the path names || `page_identity_decision` | page | none | yes | always: only a person decides which page the file is |diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.mdindex 812a691b12..ea6ace219c 100644--- a/docs/guides/write-refusals.md+++ b/docs/guides/write-refusals.md@@ -102,6 +102,7 @@ of making a duplicate.| <a id="page_write_failed"></a>`page_write_failed` (sync hold) | `page_write_failed` | A managed sync held one file because its write failed the same way three times (the same code, origin, error class and SQLSTATE in this source), with an error gbrain cannot classify: an owner exception (for example Postgres 54000 when a frontmatter tag is too long for its index), or a refusal the receipt does not explain. Until GBRA-130 every sync stopped `blocked_by_failures` at that file and the rest of the source never imported; now the file is held and the rest of the source syncs. The first two failures still stop the run, so a one-off defect never holds a file. | Read the receipt the hold names (`gbrain write-request <request_id>`, read-only). Fix the file when the error names its content (shorten the tag, split the page), or report the receipt with the gbrain version. Then `gbrain sources retry-held <source>` and the same sync. An upgrade re-tests the file on its own. A hold whose `meta.write_failure.origin` is `freeze` (GBRA-133) is different: sync could not even prepare the file (an unexpected error while reading or screening it, before any request was admitted), so it holds it on the first failure and names the error in the hold message; the next syncs re-test it on their own until it has been held 3 times, so a transient fault clears without help. When most files of one run fail that way the run stops instead (the cause is not the files). || <a id="content_null_bytes"></a>`content_null_bytes` (sync hold) | `content_null_bytes` | A managed sync held one Markdown file because its text holds NUL bytes (U+0000). Page text is stored as UTF-8 without NUL bytes. The usual cause is a UTF-16 file (a Windows "Unicode" save; the hold says so when the file starts with a UTF-16 byte order mark), a binary file named `.md` or a crash-padded file. Until GBRA-133 the whole managed sync stopped at that file on every run (`storage_error`, SQLSTATE 22P05) and the rest of the source never imported; now only the file waits. With `sync.holds=fail` the run stops with `content_null_bytes` instead of holding. | Save a UTF-16 file as UTF-8, remove the NUL bytes, or remove a binary file (or leave it out with `sync.exclude`), then commit and `gbrain sync --source <source> --no-pull`. The hold re-screens when the file changes. || <a id="git_object_missing"></a>`git_object_missing` (sync hold) | `git_object_missing` | A managed sync held one committed file because the commit names a Git object the checkout no longer has (an interrupted `git gc`, a partial clone without its promisor remote, disk corruption) and the working-tree copy differs from it or is gone. When the working-tree bytes hash to the committed blob id, sync imports them and holds nothing. Until GBRA-133 the whole managed sync stopped at that file on every run. | Run `git fsck --connectivity-only` in the checkout to see what is missing, restore it with `git fetch` (a partial or shallow clone) or from a backup, then `gbrain sync --source <source> --no-pull`. Every sync re-tests the hold. |+| <a id="path_not_utf8"></a>`path_not_utf8` (sync hold) | `path_not_utf8` | A managed sync held one committed file because its name is not valid UTF-8 (a Latin-1 name from an older system, an archive or a network share). Git hands the name back with U+FFFD for the bytes that are not UTF-8, and no Git read or file matches that decoded name, so nothing is imported from it. Until GBRA-133 the managed sync either stopped at that file on every run or skipped it with no hold; now only the file waits and the hold names it. With `sync.holds=fail` the run stops with `path_not_utf8` instead of holding. | Rename the file to a UTF-8 name (`git -c core.quotePath=true ls-files` shows its exact bytes; `convmv -f latin1 -t utf8` converts a Latin-1 name), commit, then `gbrain sync --source <source> --no-pull`. The rename clears the hold. || <a id="write_interrupted"></a>`write_interrupted` | `write_interrupted` | The database ended this managed write's own statements (SQLSTATE `57014`, a statement timeout or cancel) at preparation or inside its publication transaction, and the request reached `persistence.max_preparation_attempts` (default 2) counted attempts, so the owner finished it `failed` instead of preparing it again. Nothing was published: a worktree-backed write's canonical file is restored before the failure is recorded. Each interruption throws the preparation away, so it counts with the preparations cut off at their deadline ([`preparation_stalled`](#preparation_stalled)); before, a write the database ended every time (a large page publishing under the 5-second statement bound on a loaded host) was released as `database_contention` and prepared again, its whole body streamed again, without limit. Contention with other transactions (`55P03` lock timeout, `40001` serialization failure, `40P01` deadlock) is still released as `database_contention` uncounted, and a dropped connection or a database that is restarting or out of connections is never counted. The receipt's message and owner-only `error_detail` name the attempts, the limit and the SQLSTATE (`sqlstate`, public). A managed sync member is held like [`preparation_stalled`](#write_interrupted-hold): the run moves past it and the rest of the source lands, `gbrain sync status` lists the hold (class `page`, safe action `retry`, [runbook row](sync-unblock-runbook.md)), and `gbrain sources retry-held` re-admits it. Only the database ending the write's own statement counts: a group's shared read the database cancels is charged once, to the first member that settles with it, never to every member, so a read cancelled on every pass still ends each member `write_interrupted` at the limit; and the charge commits with the claim's release, so a crash between them never counts it twice. With `persistence.preparation_deadlines` off nothing is counted, as before. | Run `gbrain sources writer status --source <source> --json` (read-only: the owner, its pool, what its writes wait on), then submit the write again with a new `request_id` once the database is less loaded; for a held sync file, run `gbrain sources retry-held <source>` and the same sync with its options. If the same write ends this way again, report its request id with `gbrain doctor --json`. Do not raise `persistence.max_preparation_attempts` to get past it. || <a id="write_outcome_unknown"></a>`write_outcome_unknown` | `write_outcome_unknown` | The database session dropped while the write was being admitted (a pooler reap, a failover, `pg_terminate_backend`), and it kept dropping through the re-reads, so whether the write was accepted is unknown (#6355). A single drop never reaches you: the admission attempt is re-run after 100, 300 and 900 ms, and every attempt begins by reading the retained `request_id`, so a re-run replays an admitted row instead of admitting again. Before this code existed the raw socket error (`write CONNECTION_CLOSED …`, `57P01`) reached the caller while the write went on to commit, and a receipt oracle took it for a refusal. | Read the request first: `gbrain write-request -- <request_id>` or `get_write_request { request_id }` (the error's `fix` names it). A committed or pending row means the write was accepted: replay the same `request_id` to wait for it. No row means it was not: submit it again with the same `request_id`. Never resubmit under a new `request_id` without that read. || <a id="page_body_segmented"></a>`page_body_segmented` | `page_body_segmented` (a memory verb: `invalid_params` with `write_error: page_body_segmented`) | The target page stores its body in segments (a page over 1 MiB written while `pages.segmented_storage` was on), and this write needs the whole body as one string: `remember` against an entity page over 24 MiB (named, or inferred from the fact), and the other whole-body writers listed under [page_body_segmented](windowed-reads.md#page_body_segmented). It refused before changing anything and is not retryable. | For `remember`, save the claim without an entity (`infer_entity: false`); remembering it with `entity` once that page accepts fact rows replaces that copy. Otherwise edit the page's file and sync it, or read it with `get_page` `body: "auto"`. |diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex f87dd3b48d..6090eb5735 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -935,6 +935,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: '0.60.300.0', text: 'A file whose exact bytes an earlier gbrain imported and validated, and which this release refuses (a parser regression), no longer stops the sync by default: it is held `parser_regression` alone (a gbrain bug to report; it needs a person) and the rest of the source syncs. `GBRAIN_SYNC_PARSER_REGRESSION=stop` for the process that syncs restores the old stop (`sync_parser_regression`, the checkpoint does not advance). A refusal this release makes on purpose, such as the YAML alias bound (`frontmatter_alias_limit`), is held as before under either setting.' },{ since: '0.60.300.0', text: 'Doctor `managed_sync_blocked` (and get_brain_health `sync_blocked`) now count a managed sync pass that stopped with a recorded failure before finishing, in discovery (path `<discovery>`) or on one file, until a later sync of the source succeeds; before, such a source indexed nothing while the check said no run was blocked.' },{ since: '0.60.300.0', text: 'A managed sync no longer stops a whole source when a file it would skip as already imported (a no-op waiver) has meanwhile become a symlink, a FIFO or an unreadable file in the working tree: that entry is simply not skipped and goes on like any other, where an unreadable file is held `file_unreadable`.' },+ { since: '0.60.300.0', text: 'A managed sync holds a committed file whose name is not valid UTF-8 (a Latin-1 name from an older system or an archive) under the new hold code `path_not_utf8`, naming the rename that fixes it, and the rest of the source syncs; before, the file was held with a raw Git error or stopped the source. Renaming the file to a UTF-8 name clears the hold. With `sync.holds=fail` the run stops with `path_not_utf8`.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex ac61f09976..93f84b18e1 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -456,6 +456,7 @@ export const CODES = {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; such a file is held and the rest of the sync continues (`GBRAIN_SYNC_PARSER_REGRESSION=stop` for the process that syncs stops the run instead).", suggestion: 'Report it as a gbrain bug with the gbrain version, the file and the code; upgrade or pin the last good version, then sync again.' },pasted_wrong_url: { class: 'caller', summary: "Google connect credential error: pasted wrong url.", docs: 'docs/guides/google-connect.md#troubleshooting' },payload_too_large: { class: 'caller', summary: "The payload exceeds the configured size cap." },+ path_not_utf8: { class: 'caller', summary: "A committed file's name is not valid UTF-8, so managed sync holds that file alone.", why: "Git hands the name back with U+FFFD for the bytes that are not UTF-8 (a Latin-1 name from an older system, an archive or a network share), and no Git read or file matches that decoded name, so nothing is imported from it. The rest of the source keeps syncing.", docs: 'docs/guides/write-refusals.md#path_not_utf8', suggestion: 'Rename the file to a UTF-8 name (git ls-files with core.quotePath shows its exact bytes; convmv -f latin1 -t utf8 converts a Latin-1 name), commit, then sync again; the rename clears the hold.' },pattern_claims_pending: { class: 'retryable', summary: "An existing pattern page is waiting on the rewrite that de-duplicates its claim sources, so no patterns child was submitted this run.", why: "The patterns child reads existing pattern pages; until their claim records reference one shared reflection list, the pages can overflow the model's window and the run pays for nothing.", fix: { argv: ['gbrain', 'write-requests', '--source', '{source_id}'], consent: [], actor: 'agent', why: 'Lists the write receipts of the source, newest first, so the held rewrites show, read-only.', requires_exclusive: false } },patterns_min_interval: { class: 'consent', summary: "An in-cycle dream patterns run was skipped because the partition's last completed patterns run ended less than dream.patterns.min_interval_hours ago; nothing was submitted.", why: 'Every maintenance pass writes new reflections, so the evidence watermark alone re-ran a paid patterns child on each pass. The skip names next_eligible_at; a direct `gbrain dream --phase patterns` or `--once` is not held to the interval, and `gbrain config set dream.patterns.min_interval_hours 0` turns it off.', docs: 'docs/guides/dream-patterns.md#cadence', suggestion: 'Wait for next_eligible_at, or, with the user\'s paid authorization, run `gbrain dream --phase patterns` now.', fix: { argv: ['gbrain', 'dream', '--phase', 'patterns'], consent: ['paid'], actor: 'agent', why: 'A direct run is not held to the cadence; it is a paid model run, so ask the user first.', requires_exclusive: false } },pending_verify: { class: 'host_only', summary: "`gbrain bootstrap harness --token` wired the harness on a PGLite brain while no `gbrain serve` answered, so the wiring is not verified yet; nothing failed.", why: 'On PGLite the serve holds the single-writer lock, so a stopped serve is the normal state for wiring; the smoke test needs the serve, so it waits for the re-run.', docs: 'docs/guides/bootstrap.md#pending-verify', suggestion: 'Start `gbrain serve --http` for this brain, then re-run the same `gbrain bootstrap harness` command with the same --token; `gbrain bootstrap harness --status` stays partial until that run passes its smoke test.', exit: 13 },diff --git a/src/core/persistence/public-category.ts b/src/core/persistence/public-category.tsindex c4bdb08787..a7ceed7e08 100644--- a/src/core/persistence/public-category.ts+++ b/src/core/persistence/public-category.ts@@ -51,7 +51,7 @@ export const PUBLIC_BY_CODE: Readonly<Record<string, PublicCategory>> = {owner_unavailable: 'config', writer_coordinator_required: 'config', write_quota_exhausted: 'config', write_quota_insufficient: 'config', plan_stale: 'config',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',+ content_null_bytes: 'content_refused', git_object_missing: 'storage', path_not_utf8: 'content_refused',};/** A registry code's class, for a code neither table names. */diff --git a/src/core/persistence/sync-entry-fault.ts b/src/core/persistence/sync-entry-fault.tsindex 3605150d5f..3ab5b3e389 100644--- a/src/core/persistence/sync-entry-fault.ts+++ b/src/core/persistence/sync-entry-fault.ts@@ -9,6 +9,9 @@* - `committedContentOrMissing` (S-33): a committed file whose Git blob is gone (an interrupted gc, a partial clone* without its promisor, disk corruption) imports from the working tree when those bytes hash to the committed blob* id; otherwise it is refused `git_object_missing`, which the freeze holds, naming `git fsck` / `git fetch`.+ * - `committedContentOrMissing` (S-7): a committed name that is not valid UTF-8 (Latin-1 bytes from an old system or a zip)+ * reads back from Git with U+FFFD for its undecodable bytes, a name no Git read or file finds; it is refused+ * `path_not_utf8`, which the freeze holds, naming the rename that fixes it.* - `freezeFaultHold` (S-63/S-64): any other unexpected throw while freezing one entry (a Git read, the in-process* screen, a TypeError) is held `page_write_failed` (origin `freeze`) with the error class and message, re-screened* by the next syncs until it has been held `HOLD_ATTEMPTS_NEEDS_HUMAN` times, so a transient fault clears on its own.@@ -50,6 +53,13 @@ export function nullBytesRefusal(path: string, content: string): { code: 'conten* otherwise `git_object_missing` is thrown. Any other failure (no blob at the path, the object present) is rethrown.*/export function committedContentOrMissing(cursor: { root: string; gitRoot: string; sourceId: string }, entry: Pick<SyncEntry, 'path'>, blob: TreeBlob | null, error: unknown): string {+ if (entry.path.includes('\uFFFD') && !existsAt(cursor.root, entry.path)) {+ throw opError('path_not_utf8', `The committed name of ${entry.path} is not valid UTF-8.`,+ `${entry.path} is shown with U+FFFD where its name has bytes that are not UTF-8 (a Latin-1 name from an older system, an archive or a network share), so sync cannot read it by name and imported nothing from it. `+ + `Rename it to a UTF-8 name (for example git mv with the name as git ls-files shows it, or convmv -f latin1 -t utf8), commit, then run gbrain sync --source ${cursor.sourceId} --no-pull.`,+ { fix: { argv: ['git', '-C', cursor.gitRoot, '-c', 'core.quotePath=true', 'ls-files', '--', entry.path.slice(0, Math.max(0, entry.path.lastIndexOf('/') + 1)) || '.'], consent: [], actor: 'user', requires_exclusive: false,+ why: 'Lists the names in that folder with their bytes escaped (read-only), so the one to rename can be typed exactly.', verify: { argv: ['gbrain', 'sources', 'status', cursor.sourceId, '--json'] } } });+ }if (!blob || readBlobBytes(cursor.gitRoot, [blob]).has(blob.oid)) throw error;let bytes: Buffer | null = null;try { bytes = readSyncFile(cursor.root, entry.path); } catch { bytes = null; }@@ -61,6 +71,11 @@ export function committedContentOrMissing(cursor: { root: string; gitRoot: strinwhy: 'Lists the missing objects (read-only); git fetch, or a restore from a backup, brings them back.', verify: { argv: ['gbrain', 'sources', 'status', cursor.sourceId, '--json'] } } });}+/** S-7: whether anything stands at `path` (a file, a folder, a link); nothing is read. */+function existsAt(root: string, path: string): boolean {+ try { lstatSync(join(root, path)); return true; } catch { return false; }+}+/** S-22: whether a directory stands where an entry's file was (a deleted file whose name became a folder); nothing is read from it. */export function directoryAt(root: string, path: string): boolean {try { return lstatSync(join(root, path)).isDirectory(); } catch { return false; }@@ -82,13 +97,13 @@ function runScoped(error: unknown): boolean {}/**- * S-63/S-64/S-33: the hold a throw while freezing one entry earns when holds are on, or null to rethrow it. A- * `git_object_missing` refusal is held under its code; any other `OperationError` is a deliberate refusal and keeps+ * S-63/S-64/S-33/S-7: the hold a throw while freezing one entry earns when holds are on, or null to rethrow it. A+ * `git_object_missing` or `path_not_utf8` refusal is held under its code; any other `OperationError` is a deliberate refusal and keeps* its route. An unexpected throw is held `page_write_failed` (origin `freeze`) unless it is run-scoped or the run* looks systemic (`ITEM_BREAKER_MIN_ITEMS` faults and at least as many faults as clean freezes).*/export function freezeFaultHold(run: object, entry: HoldEntry, slug: string, pageId: number | null, error: unknown, blob: () => TreeBlob | null): HeldFault | null {- const missing = error instanceof OperationError && error.code === 'git_object_missing';+ const missing = error instanceof OperationError && (error.code === 'git_object_missing' || error.code === 'path_not_utf8');if (!missing && (error instanceof OperationError || runScoped(error))) return null;if (!missing) {const tally = tallies.get(run) ?? { faults: 0, frozen: 0 };@@ -100,7 +115,7 @@ export function freezeFaultHold(run: object, entry: HoldEntry, slug: string, pagconst rename = entry.renameFrom ?? entry.renameHeld;const meta = { recovery_version: RECOVERY_VERSION, ...(pinned ? { blob_oid: pinned.oid } : {}), ...(entry.working ? { working: true as const } : {}),...(rename ? { rename_from: rename } : {}), ...(entry.action === 'delete' ? { deleted: true as const } : {}) };- if (missing) return { path: entry.path, source_path: entry.sourcePath, slug, page_id: pageId, code: 'git_object_missing',+ if (missing) return { path: entry.path, source_path: entry.sourcePath, slug, page_id: pageId, code: (error as OperationError).code as 'git_object_missing' | 'path_not_utf8',message: `${(error as OperationError).message} ${(error as OperationError).suggestion ?? ''}`.trim(), upstream_version: null, meta };const name = error instanceof Error ? error.name : typeof error;const errno = (error as { code?: unknown } | null)?.code;diff --git a/src/core/persistence/sync-fault-class.ts b/src/core/persistence/sync-fault-class.tsindex f94565ba9f..fac000c7fc 100644--- a/src/core/persistence/sync-fault-class.ts+++ b/src/core/persistence/sync-fault-class.ts@@ -100,6 +100,9 @@ export const SYNC_FAULT_TABLE: ReadonlyArray<SyncFaultRule> = [// GBRA-133 S-33: the commit names a Git object the checkout no longer has and the working-tree copy differs; only restoring the object clears it.{ code: 'git_object_missing', class: 'page', safe_actions: ['none'], needs_human: true, escalate: 'always: only restoring the Git object clears it',human_reason: 'The checkout lost the Git object of this committed file and its working-tree copy differs or is gone; run git fsck in the checkout, restore the object with git fetch or from a backup, then sync (every sync re-tests the hold).' },+ // GBRA-133 S-7: the committed name is not valid UTF-8; only renaming the file clears it.+ { code: 'path_not_utf8', class: 'page', safe_actions: ['none'], needs_human: true, escalate: 'always: only renaming the file clears it',+ human_reason: 'The file name is not valid UTF-8, so sync cannot read it by name; rename it to a UTF-8 name (convmv -f latin1 -t utf8 converts a Latin-1 name) and commit.' },// #6948: several live pages record the file as their origin; the sync-time heal resolves verified duplicates, a person decides the rest.{ code: 'origin_conflict', class: 'page', safe_actions: ['repair'], needs_human: false, escalate: 'the hold carries a reason (the pages differ, ids conflict or none is the page the path names), or the heal is off',human_reason: 'Several live pages record this file as their origin and sync cannot prove they are one document; a person keeps the page that is the file\'s and soft-deletes the others (gbrain repair origin-twins --source <source> lists them with the commands), then syncs.' },diff --git a/src/core/persistence/sync-holds.ts b/src/core/persistence/sync-holds.tsindex 0643b4fb6b..66b82f79b2 100644--- a/src/core/persistence/sync-holds.ts+++ b/src/core/persistence/sync-holds.ts@@ -84,7 +84,9 @@ export type GitHoldCode = ContentRefusal['code'] | 'rename_held' | 'parser_regre/** GBRA-133 S-39: a Markdown file whose text holds a NUL byte (U+0000): a binary file, a padded file, a UTF-16 save. */| 'content_null_bytes'/** GBRA-133 S-33: a committed file whose Git blob the repository no longer has, and whose working-tree copy differs or is gone. */- | 'git_object_missing';+ | 'git_object_missing'+ /** GBRA-133 S-7: a committed file whose name is not valid UTF-8, so no Git read or file finds it by its decoded name. */+ | 'path_not_utf8';/** GBRA-130 A-6: the fault a `page_write_failed` hold stands for (identifiers and classes only, never content). */export interface PageWriteFailureMeta { code: string; origin: string | null; error_class: string | null; errno: string | null;/** The newest failed receipt; null for a GBRA-133 S-63 freeze fault (origin `freeze`), which threw before any request was admitted. */@@ -829,6 +831,11 @@ export function gitHoldFix(record: Pick<GitHoldRecord, 'source_id' | 'path' | 'cuser_message: `The Git object of ${record.path}${record.meta.blob_oid ? ` (blob ${record.meta.blob_oid})` : ''} is missing from the checkout of source ${source}, and its working-tree copy differs or is gone, so sync holds it and the rest of the source keeps syncing. Run git fsck in the checkout to see what is missing, restore it with git fetch (a partial or shallow clone) or from a backup, then run gbrain sync --source ${source} --no-pull.`,why: 'An interrupted gc, a partial clone without its promisor remote or disk corruption can drop an object a commit still names; nothing is imported from a guess, and every sync re-tests the hold.',verify: { argv: ['gbrain', 'sources', 'status', source, '--json'] } };+ case 'path_not_utf8':+ return { argv: ['gbrain', 'sources', 'status', source, '--json'], consent: [], actor: 'user', requires_exclusive: false, docs: gitHoldDocs(record.code),+ user_message: `The committed name of ${record.path} is not valid UTF-8 (U+FFFD marks the bytes that are not), so sync holds it and the rest of source ${source} keeps syncing. Rename the file to a UTF-8 name (git ls-files with core.quotePath shows the exact bytes; convmv -f latin1 -t utf8 converts a Latin-1 name), commit, then run gbrain sync --source ${source} --no-pull.`,+ why: 'Page paths are UTF-8 text; a name that is not cannot be read back or written again by the name sync would record, so nothing is imported until the file is renamed (the rename clears the hold).',+ verify: { argv: ['gbrain', 'sources', 'status', source, '--json'] } };case 'parser_regression':return { argv: ['gbrain', 'doctor', '--json'], consent: [], actor: 'user', requires_exclusive: false,user_message: `gbrain refuses ${record.path}, whose exact bytes imported under an earlier version. This is a gbrain bug: report it with the gbrain version, the file and the code, then upgrade or pin the last good version.`,diff --git a/test/behavior-change-notice-6712-block.test.ts b/test/behavior-change-notice-6712-block.test.tsindex 914bb7799f..e4fba69793 100644--- a/test/behavior-change-notice-6712-block.test.ts+++ b/test/behavior-change-notice-6712-block.test.ts@@ -12,7 +12,7 @@ import { join } from 'node:path';import { BEHAVIOR_CHANGES, compareReleases } from '../src/core/behavior-change-notice.ts';const MARKER = '// #6712 PR 4b (the level-triggered sync pass';-const ROWS = 31;+const ROWS = 32;const NOTICE_CAP = 2_000;/** The array literal's row lines in order, and where the block's rows start and how many there are. */diff --git a/test/sync-entry-faults-6712.test.ts b/test/sync-entry-faults-6712.test.tsindex c1a0da202f..bef4002c5d 100644--- a/test/sync-entry-faults-6712.test.ts+++ b/test/sync-entry-faults-6712.test.ts@@ -22,13 +22,15 @@* doctor `managed_sync_blocked` (`readBlockedManagedSyncs`) said nothing was blocked; it lists the stop until a sync succeeds.* - S-69: a non-Error rejection (`undefined`) while a pass batches a level's entries was replaced by a TypeError about* `.code`; it now reaches the caller and the failure record as itself (red with the `sync:batch_entries` seam alone).+ * - S-7: a committed file whose name is not valid UTF-8 (a Latin-1 byte) was held `page_write_failed` with a Git error (and+ * stopped the source before this lane); it is held `path_not_utf8` naming the rename, which clears the hold.* The deliberate-refusal, systemic and changing-message guards pass before and after.** PGLite here; Postgres through test/e2e/sync-entry-faults-6712-postgres.test.ts.*/import { afterEach, describe, expect, test } from 'bun:test';import { execFileSync } from 'node:child_process';-import { mkdirSync, rmSync, writeFileSync } from 'node:fs';+import { mkdirSync, renameSync, rmSync, writeFileSync } from 'node:fs';import { join } from 'node:path';import type { BrainEngine } from '../src/core/engine.ts';import { opError } from '../src/core/ops/contract.ts';@@ -233,4 +235,23 @@ for (const backend of testBackends()) describe(`[${backend}] GBRA-133: one odd fexpect(await performManagedSync(engine, OPTS).then(() => 'resolved', (error: unknown) => error)).toBeUndefined();expect((await readSyncStatus(engine, 'default')).last_error).toMatchObject({ code: 'storage_error', path: '<discovery>', message: 'undefined' });}), 240_000);+ const latin1 = (root: string) => Buffer.concat([Buffer.from(join(root, 'notes/caf')), Buffer.from([0xe9]), Buffer.from('.md')]);+ test('S-7: a committed file whose name is not valid UTF-8 is held path_not_utf8 naming the rename; the rename imports it', () => brain(async ({ engine, root }) => {+ const first = await oddThenHealthy(engine, root, () => writeFileSync(latin1(root), note('notes/cafe')));+ expect(first.held?.map(hold => [hold.path, hold.code])).toEqual([['notes/caf\uFFFD.md', 'path_not_utf8']]);+ const [hold] = await holds(engine);+ expect(hold!.message).toContain('Rename it to a UTF-8 name');+ expect(await live(engine)).toEqual(['notes/fd', 'notes/ok', 'notes/ok2', 'notes/seed']);+ renameSync(latin1(root), join(root, 'notes/cafe.md')); commit(root, 'rename');+ expect((await performManagedSync(engine, OPTS)).status).toBe('synced');+ expect(await holds(engine)).toEqual([]);+ expect(await live(engine)).toEqual(['notes/cafe', 'notes/fd', 'notes/ok', 'notes/ok2', 'notes/seed']);+ }), 240_000);++ test('S-7 with sync.holds=fail: the run stops with the typed path_not_utf8 refusal', () => brain(async ({ engine, root }) => {+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');+ await engine.setConfig('sync.holds', 'fail');+ writeFileSync(latin1(root), note('notes/cafe')); commit(root, 'odd');+ await expect(performManagedSync(engine, OPTS)).rejects.toMatchObject({ code: 'path_not_utf8' });+ }), 240_000);});