Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
docs(sync): held files walkthrough with a doc test, content-refusal anchors, agent guidance; register sync.hold* config keys (#5988)
garrytanf75a79d08ca3
diff --git a/AGENTS.md b/AGENTS.mdindex 61c60b14b9..977ecff35a 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -115,6 +115,17 @@ writing or reviewing an operation, consult `src/core/operations.ts` for the contdatabase unreachable or `GBRAIN_DB_ACCESS`: `gbrain db-repair`([`docs/ENGINES.md`](./docs/ENGINES.md#engine-detection-and-access-repair)); healthchecks: [`docs/GBRAIN_VERIFY.md`](./docs/GBRAIN_VERIFY.md).+- **Sync held a file** (`Held <path>: invalid_frontmatter …`, doctor+ `git_held_files`, `get_page.file_held`, `stale` search hits): the sync+ succeeded and only that file waits. Read it with `gbrain sources status <id>`,+ preview the fix with `gbrain repair frontmatter --source <id>` (writes+ nothing), and ask the user before any `--apply`, especially+ `--include-ambiguous` interpretations; never retry a `put_page` refused on a+ held page. A source a broken file blocked before upgrading recovers on its+ next sync (`gbrain sync --source <id> --no-pull` does it now). Write brain+ files through `put_page`/`capture` or a YAML serializer and check generated+ content with `gbrain frontmatter validate --stdin --path <p>`. Walkthrough:+ [held files](docs/guides/repair.md#held-files).- **Migrate / upgrade:** `gbrain upgrade` (binary self-update + schema migrations + post-upgrade prompts),[`docs/UPGRADING_DOWNSTREAM_AGENTS.md`](./docs/UPGRADING_DOWNSTREAM_AGENTS.md),[`skills/migrations/`](./skills/migrations/), `gbrain apply-migrations --yes --no-autopilot-install` (manual migration orchestration without service installation).diff --git a/docs/guides/live-sync.md b/docs/guides/live-sync.mdindex 6e28a3aa60..d704535aee 100644--- a/docs/guides/live-sync.md+++ b/docs/guides/live-sync.md@@ -162,20 +162,49 @@ vars — incident-time escape hatches, not everyday knobs.server is down when a push happens, that sync is missed. Pair webhookswith a cron fallback that catches anything the webhook missed.-4. **A single un-parseable file can't wedge legacy indexing.** When a file fails- to import (malformed YAML frontmatter, an unquoted colon, etc.), sync holds- the bookmark and tells you exactly which file broke — a *fresh* failure- fails closed so nothing is silently dropped. But a file that fails the same- way `GBRAIN_SYNC_AUTOSKIP_AFTER` consecutive syncs (default 3, set `0` to- disable) is auto-skipped so the rest of the brain keeps indexing past it.- Skipped files don't disappear: `gbrain doctor` keeps warning until you fix- or delete them, and fixing the file clears it on the next sync. A repository+4. **One broken file never blocks a sync: it is held.** When a file's content+ refuses deterministically (frontmatter gbrain cannot read without guessing,+ a frontmatter `slug:` naming another page, a file over the size limit, or+ content the operator's `content_sanity.junk_disposition=reject` refuses),+ sync holds that file and keeps going: every other file imports, the+ checkpoint advances, and the run reports the hold (`Held <path>: <code> …+ Next: <command>`; JSON `held`, `held_count`, `holds_outstanding`). Files+ gbrain can read exactly after quoting an unquoted value (`author: a (b)+ (original: https://…)`) import and are counted under+ `recovered_frontmatter`, so the generator that writes them can be fixed.+ Holds are durable and visible everywhere an agent looks: `gbrain sources+ status <source>`, doctor `git_held_files`, `get_page` (`file_held`) and+ search (`stale` hits, the `held_files` notice). A held file's page keeps its+ last good revision and is read-only for `put_page` until the file is+ repaired. A hold clears when the file changes, is deleted, or a newer+ gbrain can read it; `gbrain sync --dry-run` lists would-be holds+ (`would_hold`) without writing anything. The backlog fix is one previewed,+ hash-bound command:++ ```bash+ gbrain sources status <source-id> # what is held and why+ gbrain repair frontmatter --source <source-id> # preview; writes nothing+ ```++ Walkthrough with real output: [held files](repair.md#held-files); codes:+ [content refusals](write-refusals.md#held-files-and-content-refusals).+ Managed and legacy sync behave the same, and holds never count toward the+ legacy auto-skip streak below. A source blocked by such a file before this+ release recovers on its next sync, or now with+ `gbrain sync --source <source-id> --no-pull`. Teams that want fail-closed+ blocking set `gbrain config set sync.holds fail`. Company-brain profile+ sources never hold: their approved manifest keeps blocking.++ Other failures still fail closed. In legacy sync a file that fails the+ same way `GBRAIN_SYNC_AUTOSKIP_AFTER` consecutive syncs (default 3, set `0`+ to disable) is auto-skipped so the rest of the brain keeps indexing past+ it; `gbrain doctor` keeps warning until you fix or delete it. A repositoryhistory rewrite still hard-blocks even with `--skip-failed`. For legacysync only, `gbrain sync --skip-failed` acknowledges a known-bad set.**Managed sync never acknowledges or auto-skips failed cursors.** Its- durable failed receipt remains immutable on ordinary replay. Correct and- commit the source, inspect local `gbrain doctor`, then explicitly retry an- idle ordinary-source cursor with the same full/working-tree/filter options:+ durable failed receipt remains immutable on ordinary replay. Correct the+ cause, inspect local `gbrain doctor`, then explicitly retry an idle+ ordinary-source cursor with the same full/working-tree/filter options:```bashgbrain sync --source <source-id> --no-pull --retry-failed@@ -188,6 +217,9 @@ vars — incident-time escape hatches, not everyday knobs.run, not evidence of repeated deletions. Remote doctor exposes onlysource-scoped aggregate diagnostics, not paths or receipt identifiers.+ **Say to your agent:** *"Some files in my notes source are held. Show me+ why and preview the fix."*+5. **Staleness can't read "fresh" forever.** A source whose content stoppedmoving (or whose local clone vanished) would otherwise report freshindefinitely off the stored content timestamp. Content-relative stalenessdiff --git a/docs/guides/repair.md b/docs/guides/repair.mdindex 7c95a78c3e..af5743953a 100644--- a/docs/guides/repair.md+++ b/docs/guides/repair.md@@ -570,6 +570,174 @@ request). Attribution names the local owner's writer for that lane. A replay thebrain refuses reports `refused` with the code. The failed receipts stay ashistory.+<a id="held-files"></a>+### Held files++A file gbrain cannot import without guessing (#5988) no longer stops a sync.+Sync holds it, imports the rest of the source, advances the checkpoint and+keeps reporting the file until it changes, is deleted, or a newer gbrain can+read it. A held new file has no page yet; a page whose newer file is held keeps+its last good revision, search marks it `stale`, `get_page` carries+`file_held`, and `put_page` refuses it until the file is repaired, so an agent+must not retry a refused write. Hold codes and their fixes are in+[write refusal reasons](write-refusals.md#invalid_frontmatter).++**Say to your agent:** *"Sync says some files in my notes source are held.+Show me what is wrong with each one and what gbrain would change, then fix the+safe ones."* or *"After the upgrade my notes source was blocked by one broken+file. Get it syncing again."*++The session below is real output (volatile ids, hashes and times shown as+`<id>`, `<hash>`, `<time>`; `test/held-files-walkthrough.serial.test.ts` runs+these commands and checks every line shown). Before the upgrade, a generator+committed three notes to the `notes` source: `notes/standup.md` with a title+that continues on an unquoted line, a new `notes/digest.md` with `title:`+twice, and a new `notes/roundup.md` with an unquoted `: ` in `author:`. The+older gbrain blocked the source on the first file it refused.++1. After upgrading, `gbrain post-upgrade` names the blocked source and the+ command that unblocks it now. Doing nothing also works: the next scheduled+ or manual sync recovers the source by itself.++ ```console+ $ gbrain post-upgrade+ frontmatter_holds: 1 source(s) are blocked by a file gbrain could not import (notes). The next scheduled or manual sync recovers a blocked source automatically; to do it now run gbrain sync --source notes --no-pull.+ ```++2. The sync converts the blocked request in place: both broken files are held,+ the readable one imports (after quoting `author`, which gbrain reports so the+ generator can be fixed), and the checkpoint advances.++ ```console+ $ gbrain sync --source notes --no-pull+ +1 added, ~0 modified, -0 soft-deleted (recoverable 72h), R0 renamed+ Held notes/digest.md: invalid_frontmatter (needs_interpretation) at line 4, key "title"; its page is missing until the file imports. Next: gbrain repair frontmatter --source notes --include-ambiguous (docs/guides/write-refusals.md#invalid_frontmatter-needs_interpretation)+ Held notes/standup.md: invalid_frontmatter (needs_interpretation) at line 2, key "title"; its page keeps its last good revision and is read-only for put_page until the file is repaired. Next: gbrain repair frontmatter --source notes --include-ambiguous (docs/guides/write-refusals.md#invalid_frontmatter-needs_interpretation)+ 2 file(s) held this run, 2 held in source notes; they do not block sync. Inspect them with 'gbrain sources status notes'; the repair preview proposes each fix and writes nothing. Preview the repair: gbrain repair frontmatter --source notes+ Converted 1 failed request(s) of the blocked cursor in place: <id>.+ 1 file(s) under notes/ imported only after quoting unquoted frontmatter values: whatever writes them emits YAML other tools refuse. Fix the generator to quote values (or write through put_page); the preview shows the on-disk quoting fix. Preview: gbrain repair frontmatter --source notes+ ```++3. `gbrain sources status <id>` lists every hold with its code, line, key and+ next command (`--json` adds the structured `git_holds` shown in step 6).++ ```console+ $ gbrain sources status notes+ notes: 2 held file(s): not imported, and they do not block sync. A page whose newer file is held keeps its last good revision and is read-only for put_page until the file is repaired.+ Held notes/digest.md: invalid_frontmatter (needs_interpretation) at line 4, key "title"; its page is missing until the file imports. Next: gbrain repair frontmatter --source notes --include-ambiguous (docs/guides/write-refusals.md#invalid_frontmatter-needs_interpretation) Held since <time>.+ Most holds re-screen on the next sync by themselves (the file changed or was deleted, or a newer gbrain can read it): gbrain sync --source notes --no-pull+ ```++4. Preview, pass 1 (safe changes only). Nothing is written. The safe class+ only quotes values exactly as gbrain already reads them; the two held files+ need an interpretation, so they are listed as not selected and the preview+ names the `--include-ambiguous` pass.++ ```console+ $ gbrain repair frontmatter --source notes+ safe: notes:notes/roundup.md (Quoted the value of "author" at line 3 (value unchanged))+ interpretive_pending: notes:notes/digest.md (Kept the later "title" (line 4) and dropped the earlier one (line 2))+ interpretive_pending: notes:notes/standup.md (Folded the unquoted lines after "title" (line 2) into its value)+ classes: safe=1, interpretive=0, interpretive (needs --include-ambiguous)=2, needs_review=0+ -author: acme-example (citing fund-a) (original: https://example.com/post/1)+ +author: "acme-example (citing fund-a) (original: https://example.com/post/1)"+ next: gbrain repair frontmatter --source notes --apply --expect <hash> --yes (asks the user first: destructive)+ next: gbrain repair frontmatter --source notes --include-ambiguous+ ```++5. Preview, pass 2, with the interpretations. Show the user each diff. Here the+ user approves the folded standup title and wants to look at the digest+ later, so the preview skips it; `--only` and `--skip` are bound into the+ hash. After the user agrees, apply exactly that preview.++ ```console+ $ gbrain repair frontmatter --source notes --include-ambiguous --skip notes/digest.md+ classes: safe=1, interpretive=1, interpretive (needs --include-ambiguous)=0, needs_review=0+ -title: Standup with acme-example+ -the team agreed to ship on Friday+ +title: "Standup with acme-example\nthe team agreed to ship on Friday"+ next: gbrain repair frontmatter --source notes --skip notes/digest.md --include-ambiguous --apply --expect <hash> --yes (asks the user first: destructive)+ $ gbrain repair frontmatter --source notes --include-ambiguous --skip notes/digest.md --apply --expect <hash> --yes+ applied 2, skipped 0, complete+ repaired: notes:notes/roundup path=notes/roundup.md, written=true, imported=skipped, hold_cleared=false, committed=queued+ repaired: notes:notes/standup path=notes/standup.md, written=true, imported=updated, hold_cleared=true, committed=queued+ ```++ `imported=skipped` means the page already held those values (quoting+ changed nothing gbrain reads). `committed=queued` means the Git target effect+ records the change; a checkout without gbrain's Git durability hook keeps the+ repaired files uncommitted, so commit them the way you commit any edit. The+ next sync never re-holds a repaired file that is published but not yet+ committed.++6. Commit, sync, and read the remaining hold as JSON.++ ```console+ $ git -C ~/brain/notes commit -qam "Repair frontmatter"+ $ gbrain sync --source notes --no-pull+ 0 file(s) held this run, 1 held in source notes; they do not block sync. Inspect them with 'gbrain sources status notes'; the repair preview proposes each fix and writes nothing. Preview the repair: gbrain repair frontmatter --source notes+ $ gbrain sources status notes --json+ "git_holds": {+ "count": 1,+ "path": "notes/digest.md",+ "code": "invalid_frontmatter",+ "reason": "needs_interpretation",+ "key": "title",+ "line": 4,+ "message": "Invalid YAML frontmatter: key \"title\" at line 4 appears more than once. Reading it would mean guessing, so it was not imported. Keep one line per key with its whole value quoted on that line, then import it again.",+ "stale": false,+ "held_since": "<time>",+ "actor": "agent",+ "docs": "docs/guides/write-refusals.md#invalid_frontmatter-needs_interpretation"+ "outcome": "held",+ ```++ Every hold carries `code`, `reason`, `key`, `line`, a location-only+ `message` (never a frontmatter value), `stale` (a page exists and keeps its+ older revision), `fix` (the exact argv) and `docs`. `recent_conversions`+ records the blocked request the upgrade converted.++7. Later the user approves the digest interpretation (keep the later title).+ The apply creates its page and clears the last hold; the next sync is clean.++ ```console+ $ gbrain repair frontmatter --source notes --include-ambiguous --only notes/digest.md+ interpretive: notes:notes/digest.md (Kept the later "title" (line 4) and dropped the earlier one (line 2))+ $ gbrain repair frontmatter --source notes --include-ambiguous --only notes/digest.md --apply --expect <hash> --yes+ repaired: notes:notes/digest path=notes/digest.md, written=true, imported=created, hold_cleared=true, committed=queued+ $ git -C ~/brain/notes commit -qam "Keep the later digest title"+ $ gbrain sync --source notes --no-pull+ +0 added, ~0 modified, -0 soft-deleted (recoverable 72h), R0 renamed+ $ gbrain doctor --only git_held_files,frontmatter_repairable+ [OK] git_held_files: No Git source files are held.+ [OK] frontmatter_repairable: No file has frontmatter gbrain repair frontmatter would fix.+ ```++Doctor reports the same state: `git_held_files` (warn per source with counts,+the first paths and the commands; `fail` above `sync.hold_escalate_count`,+default 50) and `frontmatter_repairable` (files the repair can fix, including+ones that import only after quoting). Both are explicit-only findings:+`gbrain doctor --remediation-plan --json` lists them as `explicit_kind_required`+with `gbrain repair frontmatter --source <id>`, and `--remediate` never runs the+repair. `frontmatter_hook` warns when an installed pre-commit hook predates+this release; refresh it with `gbrain frontmatter install-hook --force`.++Settings, all read by every sync:++| Key | Default | Effect |+| --- | --- | --- |+| `sync.holds` | `hold` | `fail` restores fail-closed blocking: a content refusal blocks the sync as it did before holds. |+| `sync.hold_cap` | `500` | How many holds a sync result lists in detail; storage is never capped and valid files always import. |+| `sync.hold_escalate_count` / `sync.hold_escalate_pct` | `50` / `5` | A source holding more files, or a run holding more than that share of at least 40 screened imports, reports `holds_escalated` and doctor `git_held_files` fails. |+| `sync.parser_regression` | `stop` | `hold` holds a file whose exact bytes imported under an earlier gbrain (`parser_regression`) instead of stopping the run with `sync_parser_regression`. |++To prevent new broken files, write brain files through `put_page`/`capture`+or a YAML serializer, check generated content with+`gbrain frontmatter validate --stdin --path <source-relative path>` before+writing it, and install the staged-content pre-commit hook with+`gbrain frontmatter install-hook` (the user's decision: it writes into their+repository). See the `frontmatter-guard` skill.+<a id="frontmatter"></a>### Frontmatter@@ -796,6 +964,7 @@ walk me through it before changing anything."*| Symptom or error text | Issue | Preview | Apply | Verify | Who acts | Consent || --- | --- | --- | --- | --- | --- | --- |+| Sync `BLOCKED` on one file (`Invalid YAML frontmatter`, a frontmatter slug conflict, `Content too large`); after upgrading, sync prints `Held <path>: …`; doctor `git_held_files` or `frontmatter_repairable` warns; the upgrade banner prints `frontmatter_holds:` | #5988 | `gbrain sources status <source>`, then `gbrain repair frontmatter --source <source>` (add `--include-ambiguous` for interpretations) | nothing to unblock: the next sync converts the blocked request in place (`gbrain sync --source <source> --no-pull` does it now); for the backlog, the printed `gbrain repair frontmatter … --apply --expect <hash> --yes` ([held files](#held-files)) | `gbrain doctor --only git_held_files,frontmatter_repairable --json` (both ok) | brain host; the repair apply after the user agrees | `destructive` (repair apply rewrites the previewed lines) || Tag, timeline or take writes fail with `writer_coordinator_required` or `storage_error: Publication failed (P0001)` on a managed brain; sync ends `PARTIAL` at a tagged page | #5983 | `gbrain doctor --json` (`schema_version` is 197 or later) | the original `gbrain sync --source <source> … --no-pull --retry-failed --json`, then `gbrain extract --stale --source-id <source>` and `gbrain extract timeline --source db --source-id <source>`, then `gbrain facts relink --source <source> --dry-run` (paid tier only after the user agrees), then `gbrain repair failed-writes --source <source>` and, after the user agrees, its printed `--apply --expect <hash>` | `gbrain sources status` shows the new `last_commit`; a second `gbrain extract timeline --source db` run adds no rows; a second `gbrain repair failed-writes` preview lists nothing to replay | brain host; the replay apply after the user agrees | paid (relink tier), destructive (replay apply) || Sync `BLOCKED` with `checkpoint_validation_timeout` | #5762 | `gbrain doctor` (`persistence_request_indexes`) | `gbrain repair request-indexes --apply` when an index is missing or INVALID, then the printed `gbrain sync --source <source> --no-pull --retry-failed …` | `gbrain doctor --only persistence_request_indexes --json` reports `ok`; `gbrain sources status` shows the new `last_commit` | brain host | none || Doctor `persistence_request_indexes` warns | #5762 | `gbrain repair request-indexes` | `gbrain repair request-indexes --apply` | `gbrain doctor --only persistence_request_indexes --json` | brain host | none |diff --git a/docs/guides/troubleshooting.md b/docs/guides/troubleshooting.mdindex 8c8a8bf853..6fb49ae886 100644--- a/docs/guides/troubleshooting.md+++ b/docs/guides/troubleshooting.md@@ -20,6 +20,7 @@| [Keyword-only recall; the user wants semantic search](#embedding-dimensions) | the readiness fix: `gbrain init --force --embedding-model <provider:model> --path <brain path>` (keeps pages and facts) | agent, after the user agrees | `credentials`, `paid`; needs the brain's writer lock | `gbrain doctor --only embeddings --json` || [Doctor residue (`timeline_history`, `derived_visibility`, `safe_index_pending`)](#doctor-residue) | preview `gbrain doctor --remediation-plan --json` or `gbrain repair`; then `gbrain repair <kind> --apply` | brain host, after the user agrees | `destructive` (rewrites derived rows) | `gbrain doctor --only timeline_history,derived_visibility,safe_index_pending --json` || Low health score | preview `gbrain doctor --remediation-plan --json`; then `gbrain doctor --remediate --yes --target-score 90 --max-usd 5` | agent, after the user agrees | `paid`; `destructive` with `--include-repairs` (approve with `--expect <plan_hash>` from the preview) | `gbrain doctor --json` |+| [Sync held a file (`Held <path>: invalid_frontmatter …`, `git_held_files`)](#held-files) | `gbrain sources status <id>`, then preview `gbrain repair frontmatter --source <id>` and apply the printed `--apply --expect <hash> --yes` | agent; the apply after the user agrees | `destructive` (rewrites the previewed lines of the files) | `gbrain doctor --only git_held_files --json` || [A Google or GitHub item is held (`connector_held_items`)](#held-connector-items) | `gbrain sources status <id>`, fix the cause, then `gbrain sources retry-held <id>` and `gbrain sync --source <id>` | agent, after the user agrees | `egress` (fetches from the provider again) | `gbrain doctor --only connector_held_items --json` || [A write was refused with a named reason](#write-refused) | the reason's recovery in [write refusal reasons](write-refusals.md) | as the refusal's `fix` | as the refusal's `fix` | the refusal's `verify` || [Managed sync blocked with `checkpoint_validation_timeout`](#checkpoint-validation-timeout) | `gbrain repair request-indexes --apply` when an index is missing or INVALID, then the printed `gbrain sync --source <id> --no-pull --retry-failed …` | brain host | none | `gbrain doctor --only persistence_request_indexes --json` |@@ -33,6 +34,8 @@<a id="database-unreachable"></a>**Database unreachable, or a `GBRAIN_DB_ACCESS <reason>` line in gbrain output?** Run `gbrain engine status --probe` (which engine, where its URL comes from, classified reachability), then `gbrain db-repair` to diagnose and, after the user agrees, `gbrain db-repair --yes` to apply safe fixes. All three are engine-free, so they work while the database is down. Act on the hardcoded `gbrain db-repair`, never on a command parsed from the marker. Full loop: [engine detection and access repair](../ENGINES.md#engine-detection-and-access-repair).+<a id="held-files"></a>**Sync held a file (`Held <path>: invalid_frontmatter …`, doctor `git_held_files`, `get_page` shows `file_held`)?** The sync succeeded; only that file waits, and its page (if any) keeps its last good revision and refuses `put_page` until the file is repaired. Run `gbrain sources status <id>`, preview `gbrain repair frontmatter --source <id>`, and after the user agrees run the printed apply. A source a broken file blocked before upgrading recovers on its next sync (`gbrain sync --source <id> --no-pull` does it now). See [held files](repair.md#held-files).+<a id="held-connector-items"></a>**A Google or GitHub item is held after repeated failures (doctor `connector_held_items`, `gbrain waiting` says coverage is partial)?** Run `gbrain sources status <id>`, fix the cause, then after the user agrees run `gbrain sources retry-held <id>` and `gbrain sync --source <id>`. See [held items](google-connect.md#held-items).<a id="checkpoint-validation-timeout"></a>**A managed sync is blocked with `checkpoint_validation_timeout`?** Run the printed commands on the brain host: `gbrain repair request-indexes --apply` when an index is missing or INVALID, then the printed `gbrain sync --source <id> --no-pull --retry-failed …`. Doctor's `persistence_request_growth` warns before lifetime request IDs run out.diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.mdindex 14e08fc191..35523ff424 100644--- a/docs/guides/write-refusals.md+++ b/docs/guides/write-refusals.md@@ -41,7 +41,7 @@ of making a duplicate.| `ambiguous_source_path` | `page_identity_changed` | A source registered at a Git subfolder `<sub>` has a page whose stored path `<sub>/<file>` could mean either `<file>` in the source directory (the older Git-root spelling) or `<sub>/<file>` inside a folder of the source that repeats its name, and both files exist. Sync refuses instead of guessing. See [sources in a Git subfolder](multi-source-brains.md#sources-in-a-git-subfolder). | Rename or move one of the two files, commit, then `gbrain sync --source <source> --no-pull --retry-failed`. || `physical_root_device_changed` | `recovery_required` | The checkout's filesystem device number changed while everything else matches, which macOS can do after a reboot. When the owner token, brain, worktree, root, inode and a non-zero birth time all match and the caller can verify database ownership, the write path re-stamps ownership by itself and the write proceeds. This refusal means the automatic re-stamp could not be verified; the suggestion says why. | Do a deliberate self-transfer: `gbrain sources writer status <source>` (note `admin_state`), then `gbrain sources writer transfer prepare <source> --self-transfer --admin-intent writer_transfer_prepare --expected-state <admin_state>`, then `gbrain sources writer transfer accept <source> --path <root> --expected-epoch <epoch> --manifest <digest from prepare> --self-transfer --admin-intent writer_transfer_accept --expected-state <fresh admin_state>`. Retry the original write with the **same** request ID. Never delete ownership marker files. || <a id="embedding_budget_below_worst_case"></a>`embedding_budget_below_worst_case` | `embedding_budget_below_worst_case` | `gbrain migrate embeddings` (or the local `migrate_embeddings` operation) was given a `--max-cost-usd` cap below the migration's worst-case authorization: every planned provider request at its maximum input size, plus any debits a resumed run already holds. The run stopped before any provider request, re-chunk or vector invalidation, so nothing changed. The message and JSON carry `cap_usd`, `worst_case_usd`, `debited_usd` and `required_cap_usd`. | Re-run with the value the `suggestion` names, for example `gbrain migrate embeddings --to <provider:model> --dim <N> --max-cost-usd <required_cap_usd> --yes` (operation: `max_cost_usd`). Preview first with `--dry-run`, which prints the worst-case authorization beside the estimate. Requests settle to reported usage, so actual spend is usually far below the cap. See [embedding migration](embedding-migration.md). |-| frontmatter slug conflict | `invalid_params` | `gbrain sync` found a file whose frontmatter `slug:` names a different page than its path. The message names the file, the frontmatter slug and the slug its path expects. Nothing was written. | Remove the `slug:` line or make it match the path, commit, then run `gbrain sync --source <source> --retry-failed`. |+| frontmatter slug conflict | `frontmatter_slug_conflict` (`invalid_params` before #5988) | A file's frontmatter `slug:` names a different page than its path. On a write nothing is written; during sync the file is held and the rest of the source imports. | Remove the `slug:` line or make it match the path, commit, then sync. See [`frontmatter_slug_conflict`](#frontmatter_slug_conflict). || `cursor_processing_options_conflict` | `invalid_params` | An unfinished sync's processing options (`--no-embed`, `--no-extract`, `--no-schema-pack`) conflict with this run, or the cursor predates saved options and has none. When options are saved, a run that omits those flags, including autopilot and `sync` jobs, adopts them. | When the message prints a resume command (`gbrain sync --source <source> --no-pull` plus the saved flags), run it or drop the conflicting flag. When it reports no saved options, resolve pending requests first, then rediscover with `gbrain sync --source <source> --no-pull --retry-failed` and the processing flags you want. || `take_row_collision` | `take_row_collision` | A save adds a takes-table row whose row number already belongs to a different take that exists only in the database. The save stops instead of overwriting that take. | Renumber the new takes row, or add the existing take to the page's takes table, then save with the current `expected_revision` and a **new** request ID (the content changed). || `invalid_source_uri` | `invalid_source_uri` | The brain has shared skillpacks, and the page's stored `source_uri` is a `file:` URI that cannot be turned into a local path, so gbrain cannot prove the write stays outside a skillpack. Shared-skill protection stays on. | The source owner inspects the page's stored `source_uri` on the brain host and replaces it with an absolute file URI or clears it; there is no dedicated command yet. Retry with a **new** request ID. |@@ -111,6 +111,53 @@ when lifetime request IDs or receipt bytes reach 80% of a limit, with the`gbrain config set` value to use; outstanding-request, queued-byte andrecovery-byte limits can refuse writes without that warning.+<a id="held-files-and-content-refusals"></a>+## Held files and content refusals++Some content refuses deterministically: the same bytes refuse on every retry.+On a write (`put_page`, `capture`, `gbrain import`) the call fails with the code+below and nothing is written. During `gbrain sync` the file is **held**+instead (#5988): the rest of the source imports, the checkpoint advances, and+the hold is reported by the sync result (`held`, `held_count`,+`holds_outstanding`), `gbrain sources status <source>`, doctor+`git_held_files`, `get_page` (`file_held`) and search (`stale` hits and the+`held_files` notice). A held new file has no page; a page whose newer file is+held keeps its last good revision and is read-only for `put_page` until the+file is repaired, so do not retry a refused write. A hold clears by itself+when the file changes, is deleted, or a newer gbrain can read it.++Every hold carries `code`, `reason`, `key`, `line`, a location-only `message`+(never a frontmatter value), `fix` (the exact command) and `docs` (the anchor+below). Walkthrough: [held files](repair.md#held-files).++**Say to your agent:** *"Sync held some of my notes. Tell me what is wrong+with each file and fix the ones that need no guessing."*++| Code (`reason`) | What it means | Recovery |+| --- | --- | --- |+| <a id="invalid_frontmatter"></a>`invalid_frontmatter` | The file's YAML frontmatter cannot be read without guessing. gbrain imports frontmatter it can read exactly, quoting at most an unquoted value (`author: a (b) (original: https://…)` imports and is reported under `recovered_frontmatter`). Producer checks stay strict: `gbrain frontmatter validate` and the pre-commit hook still fail on it. | Preview the fix: `gbrain repair frontmatter --source <source>`; it writes nothing until `--apply --expect <hash> --yes`. On a write, correct the named line and submit with a new request ID. |+| <a id="invalid_frontmatter-yaml_parse"></a>`invalid_frontmatter` (`yaml_parse`) | YAML no rule reads safely: a mis-indented list or mapping entry, a key line with no colon. | The preview lists it as `needs_review` with the exact line to fix by hand: one line per key, the whole value quoted. Commit and sync. |+| <a id="invalid_frontmatter-needs_interpretation"></a>`invalid_frontmatter` (`needs_interpretation`) | Reading it means choosing an interpretation: unquoted continuation lines after a value, a duplicated key, an unclosed `[` or `{`. gbrain never imports a guess. | `gbrain repair frontmatter --source <source> --include-ambiguous` shows the exact interpretation per file. Show the user each diff; apply only what they approve (`--only <path>` / `--skip <path>` select files). |+| <a id="invalid_frontmatter-ambiguous_identity_key"></a>`invalid_frontmatter` (`ambiguous_identity_key`) | `slug`, `type`, `id` or `source_id` appears twice, or its line was swallowed into another value, so gbrain cannot tell which page the file is. | Edit the file by hand: keep exactly one line for the key. The user decides which value is right. |+| <a id="invalid_frontmatter-ambiguous_protected_key"></a>`invalid_frontmatter` (`ambiguous_protected_key`) | A key that decides access or provenance (`visibility`, `derived_from`, …) is malformed, duplicated, swallowed into another value, rewritten by quoting, or inside an unclosed fence. gbrain never reads such a key as a broader value. | Edit the file by hand: write the key on one line with one quoted value. Ask the user which visibility is intended; never guess it. |+| <a id="frontmatter_slug_conflict"></a>`frontmatter_slug_conflict` | The file's frontmatter `slug:` names a different page than its path does (earlier releases reported this as `invalid_params`). The path decides the slug. | Remove the `slug:` line or make it match the path, or move the file to the path its slug names; `gbrain repair frontmatter --source <source> --include-ambiguous` proposes removing the line. Commit and sync. |+| <a id="file_too_large"></a>`file_too_large` | Over the import size limit (5 MB for Markdown and code, 10 MiB for any sync read). The limit is fixed. | Split the file into smaller files and commit, or leave it out of the source: read `gbrain config get sync.exclude`, then `gbrain config set sync.exclude '<current list>,<path>'`. The next `gbrain sync --source <source> --no-pull` clears the hold. |+| <a id="content_rejected"></a>`content_rejected` | The content-sanity gate matched junk and the operator set `content_sanity.junk_disposition` to `reject`, so the file is never imported and always visible. | Remove the matched junk from the file, or ask the user whether `junk_disposition` should go back to `quarantine`; that setting is the user's decision. |+| <a id="rename_held"></a><a id="rename_held-rename_source_changed"></a>`rename_held` (`rename_source_changed`) | A renamed file's hold cleared, but the page it was renamed from changed after the rename was recorded, so the page did not move. | `gbrain repair frontmatter --source <source> --include-ambiguous` proposes re-binding the rename to the old page's current revision; apply after the user agrees. Or restore the old file name. |+| <a id="parser_regression"></a>`parser_regression` | With `sync.parser_regression=hold`, a file whose exact bytes imported under an earlier gbrain is now refused. This is a gbrain bug. | Report it with the gbrain version, the file and the code; upgrade or pin the last good version. After a fixed gbrain is installed, `gbrain sources retry-held <source>` and then `gbrain sync --source <source> --no-pull` re-screen it. |+| <a id="sync_parser_regression"></a>`sync_parser_regression` | Sync stopped without advancing because it would hold a file whose exact bytes imported before (default `sync.parser_regression=stop`). This is a gbrain bug, not a content problem. | Report it with the gbrain version, the file and the code; upgrade or pin the last good version, then `gbrain sync --source <source> --no-pull --retry-failed`. To keep syncing meanwhile, `gbrain config set sync.parser_regression hold` (ask the user). |+| <a id="changed_since_preview"></a>`changed_since_preview` | A `gbrain repair frontmatter --apply` found a file, its proposed change or its page different from what the preview showed, so that file was not written. | Preview again, show the user the new diff and approve its new hash. |++A source blocked by one of these refusals before this release recovers on its+next sync (scheduled or manual) with no ledger surgery: the blocked request is+converted in place and reported as `converted_from_failed`. To do it now run+`gbrain sync --source <source> --no-pull`. `gbrain config set sync.holds fail`+restores fail-closed blocking for teams that want it. Escalation:+more than `sync.hold_escalate_count` (default 50) holds in a source, or more+than `sync.hold_escalate_pct` (default 5%) of a run's screened imports (at+least 40), sets `holds_escalated` and makes doctor `git_held_files` fail: a+generator or an upgrade is likely writing or reading files wrong.+## Worktree refresh refusals`gbrain sources refresh <source>` is the one supported way to move a managed@@ -132,7 +179,7 @@ this anchor (`--json` puts them in one object on stdout); the command exits 1.| <a id="fetch_failed"></a>`fetch_failed` | `fetch_failed` | `git fetch` failed or did not finish within `sources.refresh_fetch_timeout_ms` (default 120000; `GBRAIN_REFRESH_FETCH_TIMEOUT_MS`; `--fetch-timeout-ms` wins over both). Nothing changed and no refresh record was written. | Retry. For a slow remote, raise the bound with `--fetch-timeout-ms <ms>` or `gbrain config set sources.refresh_fetch_timeout_ms <ms>`. Credentials are the user's: ask them to fix authentication rather than changing the remote. || <a id="refresh_diverged"></a>`refresh_diverged` | `refresh_diverged` | The checkout has commits its upstream lacks, so a fast-forward is impossible. Nothing changed. | Reconcile the histories and push from a clone that is not managed, then retry. `gbrain sources reclone <source>` replaces the checkout; ask the user first, because local commits are dropped. || <a id="refresh_dirty"></a>`refresh_dirty` | `refresh_dirty` | Uncommitted or untracked files overlap the incoming upstream changes (the first 20 are named), or `git merge --ff-only` refused for the same reason. HEAD did not move. Uncommitted files outside the incoming changes do not refuse; they are kept and listed as `preserved_uncommitted`. | Commit or discard the named paths, then retry. Check `gbrain sources writer status <source> --json` first: a pending Git effect may be about to commit a gbrain-published file. |-| <a id="sync_in_progress"></a>`sync_in_progress` | `sync_in_progress` | A managed sync of one of the checkout's sources has an unfinished cursor. Moving the checkout now would strand it, and the refresh never waits on a sync. | Run the printed `gbrain sync --source <source> --no-pull ...` resume command (it keeps the cursor's options), then retry. |+| <a id="sync_in_progress"></a>`sync_in_progress` | `sync_in_progress` | A managed sync of one of the checkout's sources has an unfinished cursor. Moving the checkout now would strand it, and the refresh never waits on a sync. `gbrain repair frontmatter --apply` refuses the same way while an unfinished cursor still names a selected file. | Run the printed `gbrain sync --source <source> --no-pull ...` resume command (it keeps the cursor's options), then retry (for a repair, preview again and approve the new hash). || <a id="refresh_in_progress"></a>`refresh_in_progress` | `refresh_in_progress` | Another refresh of the same checkout is active, or a command that changes which sources share the checkout (`sources add`, `remove`, `archive`, `restore`, `reclone`) ran while one was active. | `gbrain sources refresh <source> --resume`, then retry the source command with the same request ID. || <a id="refresh_drain_timeout"></a>`refresh_drain_timeout` | `refresh_drain_timeout` | Queued writes or Git effects on the checkout did not finish within `--wait-drain` (default 60 s; `sources.refresh_drain_wait_ms`; `GBRAIN_REFRESH_DRAIN_WAIT_MS`). The counts are in the message. The fence was lifted and HEAD did not move. | Retry, or wait longer with `--wait-drain <seconds>`. Inspect what is queued with `gbrain sources writer status <source> --json`. || <a id="refresh_source_changed"></a>`refresh_source_changed` | `refresh_source_changed` | HEAD moved (an outside commit or checkout), or the checkout's ownership or set of sources changed, between the precheck and the merge. Nothing was merged and the fence was lifted. | Retry `gbrain sources refresh <source>`. |diff --git a/skills/frontmatter-guard/SKILL.md b/skills/frontmatter-guard/SKILL.mdindex 17601ee038..73be161a13 100644--- a/skills/frontmatter-guard/SKILL.md+++ b/skills/frontmatter-guard/SKILL.md@@ -1,17 +1,21 @@---name: frontmatter-guard-version: 1.0.0+version: 1.1.0description: |Validate and auto-repair YAML frontmatter on brain pages. Catches malformedpages before they enter the brain (missing closing ---, nested quotes, slug- mismatches, null bytes, empty frontmatter, YAML parse failures). Wraps the- `gbrain frontmatter` CLI for agent-driven workflows.+ mismatches, null bytes, empty frontmatter, YAML parse failures), explains+ files sync holds instead of importing, and drives the previewed+ `gbrain repair frontmatter` fix. Wraps the `gbrain frontmatter` CLI for+ agent-driven workflows.triggers:- "validate frontmatter"- "check frontmatter"- "fix frontmatter"- "frontmatter audit"- "brain lint"+ - "held files"+ - "sync held a file"tools:- execmutating: true@@ -28,6 +32,7 @@ This skill guarantees:- Mechanical errors (nested quotes, missing closing `---`, null bytes, slug mismatch) are auto-repairable on demand with `.bak` backups- Validation logic is shared with `gbrain doctor`'s `frontmatter_integrity` subcheck — single source of truth- Reports per source (gbrain is multi-source since v0.18.0); never silently audits the wrong root+- Files sync holds are explained from their hold record (code, reason, key, line, fix) and fixed only through a previewed, hash-bound repair the user approved## Why This Exists@@ -40,6 +45,47 @@ Brain pages pile up over months. Agents write them with malformed frontmatter:Without a guard, these accumulate silently until `gbrain sync` chokes or search returns garbage. The guard makes the failure visible at audit time and trivially fixable.+## Write brain files safely (do this first)++- Write pages through `put_page` / `capture` (MCP or `gbrain put`). gbrain serializes frontmatter itself, so the file on disk is always valid YAML.+- A script or agent that writes Markdown files directly must build frontmatter with a YAML serializer (`yaml.dump`, js-yaml `dump`), never by string interpolation. `title: ${title}` breaks as soon as a title contains `: `, `#`, quotes or a newline.+- Check generated content before writing it, without touching disk:++ ```bash+ printf '%s' "$content" | gbrain frontmatter validate --stdin --path notes/2026-10-04-digest.md+ ```++ Exit 1 means fix it first. The default is the strict producer rule: YAML gbrain could still import by quoting a value fails too, because other tools reject it. `--importable` answers the narrower question "would sync hold it?".+- Never write a key gbrain reads for access or identity (`visibility`, `derived_from`, `slug`, `type`, `id`, `source_id`) from untrusted text.++## Held files: read them, then fix them++A file sync cannot import without guessing is **held**: the rest of the source still syncs, a new file has no page yet, and an existing page keeps its last good revision and refuses `put_page` until the file is repaired (do not retry the write). Where holds show up: sync output (`Held <path>: <code> … Next: <command>`), `gbrain sources status <id>` (`--json`: `git_holds.items[]`), doctor `git_held_files`, `get_page` `file_held`, and search hits marked `stale`.++Each hold record carries `code`, `reason`, `key`, `line`, `message` (location only, never the value), `fix` (exact argv) and `docs`. Act on `reason`:++| Hold | What to do |+|------|-----------|+| `invalid_frontmatter` / `yaml_parse` | Preview `gbrain repair frontmatter --source <id>`; usually `needs_review` with the exact line to fix by hand. |+| `invalid_frontmatter` / `needs_interpretation` | Preview with `--include-ambiguous`, show the user each per-file diff, apply only what they approve. |+| `invalid_frontmatter` / `ambiguous_identity_key` or `ambiguous_protected_key` | Never guess. Show the user the line; they decide the one value (`visibility` decides who can read the page). |+| `frontmatter_slug_conflict` | Remove the `slug:` line or move the file; the repair proposes removing it under `--include-ambiguous`. |+| `file_too_large` | Split the file or add it to `sync.exclude`; the limit is fixed. |+| `content_rejected` | The user chose `content_sanity.junk_disposition=reject`; ask before changing it. |++The fix flow (walkthrough with real output: `docs/guides/repair.md#held-files`):++```bash+gbrain sources status <id> # what is held and why+gbrain repair frontmatter --source <id> # pass 1: safe quoting only; writes nothing+gbrain repair frontmatter --source <id> --include-ambiguous --diff # pass 2: every interpretation+gbrain repair frontmatter --source <id> --include-ambiguous --only <path> --apply --expect <hash> --yes+```++**Ask the user before** every `--apply` (it rewrites their files) and before any `--include-ambiguous` apply: each interpretation (folding lines into a title, keeping the later duplicate) is a guess only the user can confirm. Show the diff, then apply exactly the previewed hash. Safe-class changes only quote a value exactly as gbrain already reads it, but they still rewrite files, so they need the same agreement.++A source that a broken file blocked before the upgrade recovers on its next sync; to do it now run `gbrain sync --source <id> --no-pull`.+## Validation classes| Code | Meaning | Auto-fixable? |@@ -89,10 +135,12 @@ When issues are found:gbrain frontmatter validate <path> --fix```-`--fix` writes `<file>.bak` for every modified file before mutating. The backup is the safety contract — works whether the brain is a git repo or a plain directory.+`--fix` backs up every modified file under `~/.gbrain/backups/frontmatter/` before mutating, quotes YAML gbrain reads by quoting (only those lines change), re-validates, and exits 1 when errors remain. Restage fixed files in git (`git add`). `--include-ambiguous` adds interpretations; preview them with `--dry-run` first.`--dry-run` previews without writing. Use this before applying fixes in batch.+On a managed brain `--fix` in place is refused: use `gbrain repair frontmatter --source <id>` (above), which publishes each repaired file through the coordinated writer.+### Phase 4: Pre-commit hook (optional)For brain repos that ARE git repos, install the pre-commit hook to block malformed pages from being committed in the first place:@@ -101,7 +149,7 @@ For brain repos that ARE git repos, install the pre-commit hook to block malformgbrain frontmatter install-hook [--source <id>]```-The hook runs `gbrain frontmatter validate` against staged `.md`/`.mdx` files. Bypass with `git commit --no-verify`.+The hook runs one `gbrain frontmatter validate --staged` process over the staged content of `.md`/`.mdx` files (what will be committed, not the working copy). Bypass with `git commit --no-verify`. Installing writes into the user's repository, so ask first. When doctor `frontmatter_hook` reports an older hook, refresh it with `gbrain frontmatter install-hook --force`.## Trigger words@@ -122,7 +170,7 @@ When the user says any of these, route here:## Chains with-- `gbrain doctor` — the `frontmatter_integrity` subcheck reports the same counts as `audit`.+- `gbrain doctor` — the `frontmatter_integrity` subcheck reports the same counts as `audit`; `frontmatter_repairable` counts files `gbrain repair frontmatter` can fix and `git_held_files` lists held files.- `skills/maintain/SKILL.md` — broader brain health audit; chain after this skill if other classes of issue are suspected.- `gbrain lint` — overlapping rules for skill-file lint (a CLI command, not a skill); the `frontmatter-*` rule names in lint output come from this skill's validation surface.@@ -225,7 +273,8 @@ Follow the [agent operator protocol](../../docs/protocol/AGENT_OPERATOR_v1.md) f- `gbrain frontmatter validate` exits 1: errors were found (that is the result, not a crash). Parse `errors_by_code` and report counts per source.- Before a fix pass, state how many files will change and get the user's agreement; the fix writes `.bak` backups, and YAML_PARSE errors are not always auto-repairable.-- `gbrain sync` afterwards still refuses a page (`invalid_params`, frontmatter slug conflict): fix the `slug:` line the message names, commit, and retry the sync.+- `gbrain sync` holds a file (`invalid_frontmatter`, `frontmatter_slug_conflict`, `file_too_large`, `content_rejected`): the sync still succeeded. Read the hold (`gbrain sources status <id>`) and follow "Held files" above.+- `put_page` refuses a page whose newer file is held: repair the file; retrying the write refuses again.## Anti-Patternsdiff --git a/src/commands/repair.ts b/src/commands/repair.tsindex 8228c2a5eb..107c4a6371 100644--- a/src/commands/repair.ts+++ b/src/commands/repair.ts@@ -64,7 +64,8 @@ Options:Any other option is refused. There is no --max-usd here: to cap paid embeddingwork, preview gbrain doctor --remediation-plan --json and, after the user agrees, rungbrain doctor --remediate --yes --include-repairs --max-usd <n> --expect <plan_hash>.-With no kind, previews every kind. Run it on the brain host.`;+With no kind, previews every kind. Run it on the brain host.+Held files (two-pass frontmatter repair with real output): docs/guides/repair.md#held-files.`;const BOOLEAN_FLAGS = new Set(['--apply', '--all', '--json', '--no-embed', '--include-ambiguous', '--diff', '--yes']);const VALUE_FLAGS = new Set(['--source', '--limit', '--expect', '--only', '--skip']);diff --git a/src/commands/sources.ts b/src/commands/sources.tsindex 3efee68a2a..3c384fe310 100644--- a/src/commands/sources.ts+++ b/src/commands/sources.ts@@ -1936,7 +1936,10 @@ Subcommands:restore <id> [--no-federate] Un-archive a soft-deleted source.status [<id>] [--json] v0.40.3.0 — read-only per-source dashboard:last sync, staleness, page count,- embedding coverage, unacked failures, held files.+ embedding coverage, unacked failures, held files+ (each Git hold with its code, line, key and+ next command; recent blocked-cursor conversions).+ <id> filters to that source.--json emits {schema_version:1, ...} onstdout for monitoring pipelines.archived [--json] List soft-deleted sources and their expiry.@@ -1979,6 +1982,8 @@ Subcommands:default_source_local_path check.retry-held <id> [--dry-run] [--json]Re-attempt a connector source's held items, or re-screen a Git source's held files, on its next sync.+ Runs nothing now. Most Git holds re-screen by themselves (file changed or+ deleted, newer gbrain); fix the files with gbrain repair frontmatter --source <id>.set-path <id> --clear Clear a connector source's (google, github)stale local_path; takes no path.webhook <set|show|rotate|clear> <id> [options]diff --git a/src/commands/sync/args.ts b/src/commands/sync/args.tsindex bb05bb2598..594bdd9107 100644--- a/src/commands/sync/args.ts+++ b/src/commands/sync/args.ts@@ -18,6 +18,15 @@ export function printSyncHelp(): void {Sync the brain repo's text content into the engine, then embed.+A file whose content refuses deterministically (frontmatter gbrain cannot+read without guessing, a conflicting frontmatter slug, over-size, or a+content_sanity reject) is held: the rest of the source imports, the+checkpoint advances, and each hold prints its code, line, key and next+command. Inspect holds with 'gbrain sources status <id>'; preview the fix+with 'gbrain repair frontmatter --source <id>'. A source a file blocked+before this release recovers on its next sync ('--no-pull' on a managed+brain). 'gbrain config set sync.holds fail' restores fail-closed blocking.+Options:--no-embed Skip the embed step. Use this when the embedprovider is misconfigured or you want to defer@@ -62,10 +71,16 @@ Options:Caution: imports untracked files as-is — unignoredscratch files and secrets included; review 'git status'before enabling, especially as persisted config.- --dry-run Show what would be synced without writing.- --skip-failed Acknowledge previously-recorded sync failures so- the bookmark can advance past unparseable files.+ --dry-run Show what would be synced without writing; lists+ every file the content screen would hold (would_hold)+ and screen errors separately (screen_skipped).+ --skip-failed Legacy sync only: acknowledge previously-recorded+ sync failures so the bookmark can advance. Held files+ never need it; managed sync refuses it.--retry-failed Re-attempt previously-failed files; clear on success.+ Not needed for held files, which re-screen on the next+ sync when they change (or with 'gbrain sources+ retry-held <id>').--reset-checkpoint Connector source only: re-walk its window once from an emptycheckpoint; unchanged pages are not admitted again.--watch Re-sync continuously on an interval.@@ -113,6 +128,9 @@ Options:See also:gbrain embed --stale Re-embed all stale chunks (post --no-embed).gbrain doctor Diagnose dim mismatches and other sync issues.+ gbrain sources status <id> Held files with their next command.+ gbrain repair frontmatter --source <id> Preview the fix for held files.+ docs/guides/repair.md#held-files Walkthrough.`);}diff --git a/src/core/config.ts b/src/core/config.tsindex 6bbcc6313d..3eb3f1dee8 100644--- a/src/core/config.ts+++ b/src/core/config.ts@@ -1603,6 +1603,14 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [// #4901: the dot-directory WAIVER's persisted twin (unioned with the per-call// include-hidden flag, which bulk sync refuses); registered so `config set` accepts it.'sync.include_hidden',+ // #5988: Git sync holds (read by readSyncHoldPolicy). `sync.holds=fail`+ // restores fail-closed blocking; the rest tune detail, escalation and the+ // parser-regression stop. Registered so the documented `config set` works.+ 'sync.holds',+ 'sync.hold_cap',+ 'sync.hold_escalate_count',+ 'sync.hold_escalate_pct',+ 'sync.parser_regression',// #2179: clamp window for DCR-requested per-client token TTLs. Read by// `gbrain serve --http` at startup; unset min defaults to 300s, unset max// defaults fail-closed to max(--token-ttl, min).diff --git a/test/doctor-frontmatter-holds.test.ts b/test/doctor-frontmatter-holds.test.tsindex d07148a22b..76b608f246 100644--- a/test/doctor-frontmatter-holds.test.ts+++ b/test/doctor-frontmatter-holds.test.ts@@ -19,7 +19,8 @@ import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { claimWorktree } from '../src/core/persistence/ownership.ts';import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';import { performManagedSync } from '../src/core/persistence/sync-run.ts';-import { readGitSourceHolds } from '../src/core/persistence/sync-holds.ts';+import { gitHoldDocs, readGitSourceHolds } from '../src/core/persistence/sync-holds.ts';+import { CODES } from '../src/core/error-registry.ts';import type { SyncOpts } from '../src/commands/sync.ts';import { gitHeldFilesCheck } from '../src/commands/doctor/checks/git-holds.ts';import { frontmatterRepairableCheck, frontmatterRepairableFromReport } from '../src/commands/doctor/checks/frontmatter-repairable.ts';@@ -98,6 +99,19 @@ test('the frontmatter kind owns both findings and both are host-only repair findexpect(WAVE_CHECKS.find(s => s.id === 'frontmatter_hook')).toMatchObject({ resolution: 'operator' });});+test('every docs anchor a hold can name exists in write-refusals.md', () => {+ const guide = readFileSync(join(import.meta.dir, '..', 'docs', 'guides', 'write-refusals.md'), 'utf8');+ const anchors: string[] = [];+ for (const code of ['invalid_frontmatter', 'frontmatter_slug_conflict', 'file_too_large', 'content_rejected', 'rename_held', 'parser_regression'] as const) {+ anchors.push(gitHoldDocs(code));+ for (const reason of (CODES[code] as { reasons?: readonly string[] }).reasons ?? []) anchors.push(gitHoldDocs(code, reason as never));+ }+ expect(anchors).toContain('docs/guides/write-refusals.md#invalid_frontmatter-ambiguous_protected_key');+ for (const anchor of [...anchors, 'docs/guides/write-refusals.md#sync_parser_regression', 'docs/guides/write-refusals.md#changed_since_preview']) {+ expect(guide).toContain(`<a id="${anchor.split('#')[1]}"></a>`);+ }+});+test('a clean brain has no held, repairable or hook finding', () => each(async engine => {const s = await source(engine, { 'notes/a.md': note('A'), 'notes/b.md': note('B') });expect((await s.sync()).status).toBe('first_sync');diff --git a/test/held-files-walkthrough.serial.test.ts b/test/held-files-walkthrough.serial.test.tsnew file mode 100644index 0000000000..9f8a6bc1d9--- /dev/null+++ b/test/held-files-walkthrough.serial.test.ts@@ -0,0 +1,117 @@+/**+ * Doc test for docs/guides/repair.md "Held files" (#5988). It builds the+ * walkthrough's fixture with the real CLI on a throwaway PGLite brain: a Git+ * source synced once, then three generator-written notes committed while+ * `sync.holds=fail` (the pre-upgrade fail-closed behavior) so the source is+ * blocked. Then it runs every `$ ` command in the section's console blocks, in+ * order, and checks that each output line the guide shows appears in the+ * real output (ids, hashes, times and the checkout path normalized), and that+ * every command exits 0. A changed message, command or flow fails here before+ * the guide can drift from the CLI.+ *+ * Protects: the documented recovery path (post-upgrade notice, in-place+ * conversion, sources status, two-pass hash-bound repair with --skip/--only,+ * clean sync, doctor). Serial: it spawns about twenty CLI processes.+ */+import { afterAll, expect, test } from 'bun:test';+import { spawnSync } from 'node:child_process';+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';++const REPO = join(import.meta.dir, '..');+const work = mkdtempSync(join(tmpdir(), 'gbrain-held-walkthrough-'));+const checkout = join(work, 'notes');+const env: Record<string, string> = Object.fromEntries(Object.entries(process.env)+ .filter(([key, value]) => value !== undefined && !['DATABASE_URL', 'GBRAIN_DATABASE_URL', 'GBRAIN_SOURCE', 'GBRAIN_BRAIN_ID'].includes(key))) as Record<string, string>;+env.GBRAIN_HOME = join(work, 'home');++afterAll(() => rmSync(work, { recursive: true, force: true }));++function run(argv: string[]): { out: string; status: number | null } {+ const [cmd, ...args] = argv[0] === 'gbrain' ? [process.execPath, '--no-env-file', join(REPO, 'src', 'cli.ts'), ...argv.slice(1)] : argv;+ const result = spawnSync(cmd!, args, { cwd: REPO, env, encoding: 'utf8', timeout: 120_000 });+ return { out: `${result.stdout ?? ''}${result.stderr ?? ''}`, status: result.status };+}++function ok(argv: string[]): string {+ const result = run(argv);+ if (result.status !== 0) throw new Error(`${argv.join(' ')} exited ${result.status}:\n${result.out}`);+ return result.out;+}++const write = (files: Record<string, string>) => { for (const [path, content] of Object.entries(files)) writeFileSync(join(checkout, path), content); };+const commit = (message: string) => { ok(['git', '-C', checkout, 'add', '-A']); ok(['git', '-C', checkout, 'commit', '-qm', message]); };++/** The guide's placeholders for values that differ per run. */+function normalize(text: string): string {+ return text.split(checkout).join('~/brain/notes')+ .replace(/\b[0-9a-f]{64}\b/g, '<hash>')+ .replace(/\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/g, '<id>')+ .replace(/\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}(?::\d{2}(?:\.\d+)?Z?)?/g, '<time>');+}++/** `a "b c" d` -> [a, b c, d]; `\"` stays a literal quote outside the guide's simple commands. */+function tokens(command: string): string[] {+ return [...command.matchAll(/"([^"]*)"|(\S+)/g)].map(m => m[1] ?? m[2]!);+}++interface Step { command: string; expected: string[] }++function walkthrough(): Step[] {+ const guide = readFileSync(join(REPO, 'docs', 'guides', 'repair.md'), 'utf8');+ const section = guide.slice(guide.indexOf('<a id="held-files"></a>'), guide.indexOf('<a id="frontmatter"></a>'));+ const steps: Step[] = [];+ for (const block of section.matchAll(/```console\n([\s\S]*?)```/g)) {+ for (const raw of block[1]!.split('\n')) {+ const line = raw.trim();+ if (!line) continue;+ if (line.startsWith('$ ')) steps.push({ command: line.slice(2), expected: [] });+ else steps.at(-1)!.expected.push(line);+ }+ }+ return steps;+}++test('docs/guides/repair.md "Held files": every command runs and prints every line the guide shows', () => {+ const steps = walkthrough();+ expect(steps.map(step => step.command.split(' ').slice(0, 3).join(' '))).toContain('gbrain repair frontmatter');+ expect(steps.length).toBeGreaterThanOrEqual(12);++ // A source synced once by the older gbrain.+ mkdirSync(join(checkout, 'notes'), { recursive: true });+ ok(['git', 'init', '-q', checkout]);+ ok(['git', '-C', checkout, 'config', 'user.name', 'Example']);+ ok(['git', '-C', checkout, 'config', 'user.email', '[email protected]']);+ write({ 'notes/roadmap.md': '---\ntitle: Widget roadmap\n---\nThe quarterly widget roadmap.\n', 'notes/standup.md': '---\ntitle: Standup\n---\nDaily standup notes.\n' });+ commit('init');+ ok(['gbrain', 'init', '--pglite', '--no-embedding']);+ ok(['gbrain', 'config', 'set', 'self_upgrade.mode', 'off']);+ ok(['gbrain', 'sources', 'add', 'notes', '--path', checkout]);+ ok(['gbrain', 'sync', '--source', 'notes', '--no-pull']);++ // The generator's notes block the source under the pre-upgrade behavior.+ ok(['gbrain', 'config', 'set', 'sync.holds', 'fail']);+ write({+ 'notes/standup.md': '---\ntitle: Standup with acme-example\nthe team agreed to ship on Friday\n---\nDaily standup notes.\n',+ 'notes/digest.md': '---\ntitle: Weekly digest\ntags: [launch, widgets]\ntitle: Weekly digest (draft)\n---\nWhat shipped this week.\n',+ 'notes/roundup.md': '---\ntitle: Payments roundup\nauthor: acme-example (citing fund-a) (original: https://example.com/post/1)\n---\nA roundup of payments news.\n',+ });+ commit('notes from the generator');+ const blocked = run(['gbrain', 'sync', '--source', 'notes', '--no-pull']);+ expect(blocked.status).not.toBe(0);+ expect(blocked.out).toContain('Sync BLOCKED');+ ok(['gbrain', 'config', 'unset', 'sync.holds']);++ let lastHash: string | undefined;+ for (const step of steps) {+ const argv = tokens(step.command).map(token => token === '<hash>' ? lastHash ?? '<no preview hash yet>' : token.replace('~/brain/notes', checkout));+ const out = ok(argv);+ lastHash = [...out.matchAll(/--expect ([0-9a-f]{64})/g)].at(-1)?.[1] ?? lastHash;+ const shown = normalize(out);+ for (const line of step.expected) {+ if (!shown.includes(line)) throw new Error(`"$ ${step.command}" no longer prints the guide's line:\n ${line}\nActual output:\n${shown}`);+ }+ }+ expect(run(['git', '-C', checkout, 'status', '--porcelain']).out).toBe('');+}, 600_000);