Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

wip(#6865): different_type fixture, docs

garrytanf682f846e91a
diff --git a/docs/architecture/key-files/core-utilities-2.md b/docs/architecture/key-files/core-utilities-2.md
index 5a638b27dc..6b3afa7ff7 100644
--- a/docs/architecture/key-files/core-utilities-2.md
+++ b/docs/architecture/key-files/core-utilities-2.md
@@ -18,6 +18,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/repair/fences.ts` — `gbrain repair fences` (#6188), preview-bound, `spends: 'llm'`, not explicit-only (no destructive consent). Candidates: the fence census (`listFenceCandidates` after a bounded `runFenceCensus`, `GBRAIN_FENCE_REPAIR_SCAN_MS`, default 10 s) filtered by `--only`/`--skip <path>` and `--slug <slug>`, plus files or pages the selection names that the census has not judged. Per candidate (`fence-repair/repair-io.ts` reads the current bytes): a host that may not write the source is skipped with the owner condition as its reason (`host_mismatch`, `transfer_in_progress`, `clone_in_progress`, `incarnation_changed`, `local_path_missing`, `coordination_path_missing`; `owner_unavailable` is the fallback; the skip's detail carries `why`, the read-only fix and `retryable`), a candidate a write in flight or an unfinished sync's frozen manifest still names is `sync_in_progress` (#6278: checked at plan, at apply and again at the write's admission in `file-repair.ts`; the rest of the source repairs while the sync runs, and a held path is not busy); `analyzeFences` (`repair-tiers.ts`) decides `proposal` (Tier 1 or Tier 2, validated, a fixed point, the exact diff), `llm` (only Tier 3 residuals: `fences.repair.llm`/`--no-llm` → `llm_disabled`, a page whose tags its file lacks → `canonical_overlay` before any spend, no measured model with a key and `models.fence_repair` unset → `no_measured_model`, an unpriced model under a user cap → `no_pricing`, under the default caps a warn-and-run notice naming `gbrain pricing set`, 0 caps or an estimate over `fences.repair.max_usd_per_page` → `budget_exhausted`, an attempt memo already rejected for these bytes → its stored verdict at $0) or `manual` with the exact location-only edit. The model is `resolveFenceRepairModel` (`fence-repair/model.ts`: `models.fence_repair`, else the first measured model with a key, else none). The preview saves the approved set (`previewHash` over sources, selection and each item's location, bytes hash, revision, tier and after-hash) and prints `apply_command` with `--expect`; `--apply --expect` replays it (`changed_since_preview` for moved bytes or revision), a bare `--apply` applies the current plan starting after the last candidate the previous bare run touched (`fence-repair-rotation`). Apply refuses a remote caller (`trusted_cli_required`) and runs Tier 3 through `runTier3` (ledger reservation, attempt claim, a corrective re-ask only after gate (a) or (e)); a daily-ledger refusal stops the run (`budget_exhausted`, D15: spent and cap, reset time, pages waiting, `gbrain config set fences.repair.max_usd_per_day <usd>` with consent `paid`). Outcomes `repaired` / `held` (FenceReason, also written to the hold with `recordFenceHoldRepair`) / `skipped`; `report` adds `repaired`, `remaining` by reason (an `--expect` apply re-checks the selection for what stays held) and `verification` (`FenceRepairVerification`: repaired per tier, held per reason, oldest hold, USD per Tier 3 repair). Tests: `test/repair-fences.test.ts` (PGLite and Postgres), `test/fence-repair-llm.test.ts`.
- `src/core/repair/content-lane.ts` — the content-repair lane (#6377). `CONTENT_REPAIR_KINDS` is the ordered list of repair kinds that clear managed-sync content holds (today `fences`; the GBRA-72 integration appends `slug-conflicts`), read by `gbrain repair content` (`src/commands/repair-content.ts`), the `content_repair` cycle phase and `gbrain sync unblock --apply`, so a new kind plugs in with one entry. `CONTENT_REPAIR_HOLD_KINDS` maps a hold code to the kind that clears it (`invalid_fence` → `fences`; `frontmatter_slug_conflict` → `null` until Lane B's kind lands, which keeps the surfaces' refusal text). `runContentLane(engine, scope, { apply, kinds?, only, skip, expect?, noLlm, maxLlmUsd, deadline, registry? })` has no rule logic: it runs each kind through `repairRunner` in order, passing the run's paid allowance minus what earlier kinds spent (read from each result's `cost.llm_usd`; the daily ledger is `FENCE_REPAIR_LEDGER` for every kind) and one absolute deadline (a `time_budget` stop ends the pass; any other stop lets the next kind run), and returns per-kind results, each kind's own `preview_hash` (no combined hash: `--expect` is one hash per kind in lane order, `parseContentLaneExpect` refuses a wrong count with `invalid_params` before any kind runs), the lane's spend and remaining allowance, and `apply_command` (`contentLaneArgv`). A preview plans every kind before any mutation; `--apply --expect` binds each kind to its approved set; a bare apply runs each kind's own plan-and-apply (`changed_since_read` binding, held reasons recorded on the holds). `contentHoldDisposition(record, auto)` reads a hold's stored repair state (`fenceHoldStatus` for a fence hold; `meta.content_repair.action` for a slug-conflict hold, read loosely) and says whether an unattended surface may run the kind (`repair`), must list it (`listed`: `needs_human` for a manual reason or a recommended merge, `paid`, `owner`) or has no kind for it (`unsupported`). Output is counts, codes, hashes and paths only. Tests: `test/cycle-content-repair.test.ts` (stub kinds), `test/repair-content.test.ts` (the real `fences` kind through the CLI).
- `src/core/repair/slug-conflicts.ts` — `gbrain repair slug-conflicts` (#6377, Lane B), the lane kind that clears `frontmatter_slug_conflict` holds: preview-bound, `spends: 'llm'`, `checks: []` (doctor keeps `git_held_files` on `frontmatter`), not explicit-only. Candidates are the source's slug-conflict holds (plus `--only <path>`); identity is resolved, not textual: the frontmatter slug is normalized the way the screen does and resolved through `slug_aliases` to a page id in the same source (a slug resolving to the held file's own page is exempt; a held file with no page yet is a normal candidate). Deterministic tier (`remove_slug`, confidence high): the named slug resolves to no page and names no other file, or to a page of a different type sharing no title token; besides SLUG_MISMATCH `autoFixFrontmatter` may propose only style-only `NESTED_QUOTES` (left as written, listed as `style_only`), any other code holds it `still_invalid` naming it; the one-line edit publishes through the frontmatter repair's coordinated path (`prepareRepairPublication` / `submitManagedFileRepair`: bytes bound to the sha256 the preview read, import, hold clear and Git effect in one write). Every verdict uses managed sync's own screen (`sync-screen.ts` `loadSyncScreenRun` + `frozenImportScreenInput` + `screenFrozenContent`, on the file's bytes and on the edited bytes): a held file the screen now admits as it is (its line is clean, or names the file's own page as written) is planned as `import` and published unchanged through `submitManagedFileRepair` with an `import` receipt and `holdObservedAt` (the hold observation the plan read; a newer hold is kept and the hold records a `changed_since_read` retry); a file sync would hold whatever the lane writes (the page it is filed as carries another slug than its path, or the line reaches the own page only through an alias) is held `slug_page_mismatch` with both slugs (`named` on the hold). Everything else goes to the model tier (`src/core/content-repair/judgment.ts`): `remove_slug` applies the same way, `merge_into <canonical>` and `needs_human` are recorded on the hold as codes and slugs only (`recordContentHoldRepair`, `meta.content_repair`) and rendered by `sync status` as `needs_human` paragraphs; nothing merges pages. Caps and ledger are the fence repair's (`FENCE_REPAIR_LEDGER`, `fences.repair.max_usd_per_page` / `_per_day`, `fences.repair.llm`, `--no-llm`, `--max-usd`); the receipt is a `content_repair` receipt (action, tier, confidence, model, cost, before/after sha256, style_only) carried by the write and the commit trailer `gbrain-repair: <hold_code> <tier> <confidence>`. Tests: `test/repair-slug-conflicts.test.ts`, `test/repair-slug-conflicts-sync-screen.test.ts`.
+- `src/core/repair/slug-autoheal.ts` — the sync-time heal of stray `slug:` lines (#6865): `healAfterManagedSync`, called once from `commands/sync/perform.ts` `performManagedBranch` after the drain lease is released, runs `slug-conflicts`' `healAbsentSlugLine` (deterministic `absent_page` only, bound to the held bytes, nothing recorded for any other analysis) over the source's slug-conflict holds through the same `submitManagedFileRepair` write, with the receipt's `declared_alias` recorded as a `slug_aliases` row in that write. Skipped (and said why on `slug_lines_removed`) under `sync.slug_conflicts.auto_remove false`, `fences.repair.enabled false`, remote submission authority, an unfinished managed-sync cursor, or a host that may not write the checkout; bounded by `SLUG_HEAL_MAX_FILES` and `SLUG_HEAL_BUDGET_MS` (or the caller deadline), one checkout scan per source; never throws. Lane verdicts carry `lane_version` (`CONTENT_REPAIR_LANE_VERSION` in `persistence/sync-fault-class.ts`): an older verdict is `repair` in `contentHoldDisposition` and never a person's decision in `classifySyncFault`. Tests: `test/slug-autoheal-6865.test.ts` (Postgres arm `test/e2e/slug-autoheal-6865-postgres.test.ts`), `test/slug-conflict-verdict-6865.test.ts`.
- `src/core/repair/frontmatter.ts` — `gbrain repair frontmatter` (#5988), explicit-only, preview-bound, destructive consent (`--yes` with the hash, registry `consent`). #5966 (W14 P1.7): the slug rule itself is `slugStampedFrontmatter(slug, fm)` in `src/core/markdown.ts` (stamps `slug:` when the path cannot derive it, such as a doubled hyphen, and replaces a foreign `fm.slug`; used by `serializePageToMarkdown` and `commands/export.ts`, digest-neutral since `parseMarkdown` drops `fm.slug`); `slugStampCandidate` proposes a SAFE `slug:` stamp for a well-formed file at a page's recorded `source_path` whose path derives another slug and that declares none (a legacy render of a slug the path cannot derive), inserted as `serializeMarkdown` writes it; never normalizes or guesses. Scope: Git-visible `.md`/`.mdx` per source (managed owner root or legacy `local_path`) plus every Git hold row; database side, pages whose body begins with an embedded frontmatter block or whose title is the humanized slug while the file names one. `frontmatterCandidates` builds a safe rewrite (NUL strip, nested-quote swap, `repairRecoverableFrontmatter` quoting; parsed values must be unchanged) and an interpretive one (`autoFixFrontmatter` missing close / slug line, fold, dup, unclosed, `#` rescue); both must strict-parse with no hold. `prepareRepairPublication` binds each proposal to the page fields its import would store; a refusal or canonical overlay is `needs_review`. The hash covers sources, `include_ambiguous`, `--only`/`--skip`, and per file before/after sha256, page id/revision, result digest and `rename_from`; the approved set stores no frontmatter text. An `invalid_fence` hold is listed with a resolution that defers to `gbrain repair fences --source <id> --only <path>` (frontmatter repair never changes fences). Apply refuses while an unfinished managed sync cursor names a selected path, re-derives each change, then publishes through `managed_file_repair` (managed) or backup, write, `importFromFile`, hold clear and a printed commit step (legacy). Tests: `test/repair-frontmatter.test.ts`.
- `src/core/persistence/mirror-read-only.ts` and `src/commands/sources-mirror.ts` — #5409 read-only mirror sources. `sourceMirrorReadOnly(engine, sourceId)` reads `sources.config.mirror_read_only` (default false). When true, `prepareFileTarget` (`page-prepare.ts`) returns no file for any coordinated page write into the source (receipt `write_through.skipped: 'mirror_read_only'`, `storage: 'database_only'`, set in `coordinator.ts`), and managed sync (`sync-prepare.ts`) imports an overlay (canonical form differs from the file bytes) database-only: no `file`, no newer-working-tree refusal, and `contentUnchanged` ignores the overlay. A page created that way with no recorded file is stamped `pages.database_only_reason='mirror_read_only'` (`classifyMirrorPage`, in the publication) and stays database-only after the flag is cleared; the coordinator refuses (`source_changed`) a file target prepared before the flag was set (rechecked under the publication with the source row `FOR SHARE`); `gitPage` (`effects.ts`) completes a mirror source's Git effects as skipped. `gbrain sources mirror-readonly|mirror-writable <id>` set and clear the key like `federate`/`unfederate`; `sources list --json` reports `mirror_read_only`.
diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.md
index 247ee7e832..0b7da830f0 100644
--- a/docs/guides/write-refusals.md
+++ b/docs/guides/write-refusals.md
@@ -193,7 +193,7 @@ with each file and fix the ones that need no guessing."*
| <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. The hold has three outcomes once the content-repair lane's `slug-conflicts` kind runs it (the maintenance run's `content_repair` phase, `gbrain sync unblock --apply`, or `gbrain repair content --source <source>`): **removed** (the named slug resolves to no page and names no other file, or to a page of a different type sharing no title token: the stray `slug:` line is removed, the file imported and committed, the hold cleared, with a receipt; a model under the `fences.repair` caps makes the same call when the two pages are not obviously different), **merge recommended** ([`merge_recommended`](#merge_recommended): the two files describe the same thing; gbrain recommends the merge and names the canonical page but never merges pages by itself), or **undecided** ([`content_repair_needs_human`](#content_repair_needs_human)). The lane judges the file with the screen managed sync froze it with: a hold the sync screen now admits as the file is (its slug line names the file's own page as written, or it no longer declares a conflicting slug) is **imported** unchanged in one guarded write that clears only the hold observation the lane read (a hold a newer sync wrote stays, with a retry), and a file sync would hold whatever the lane writes is [`slug_page_mismatch`](#slug_page_mismatch). Until that kind ships, the lane leaves the hold to the frontmatter repair preview below. | Nothing to run when the lane removes the line: the hold clears on the sync it prints. For a recommendation or an undecided hold, `gbrain sync status --source <source> --json` carries the paragraph (`human_reason`): merge the unique sections into the canonical page by hand or decide which page keeps the slug, delete or edit the file, commit, then `gbrain sync --source <source> --no-pull`. By hand at any time: 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, for approval). |
+| <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. A managed sync removes the line by itself when the slug it names has no page and no file (#6865, `absent_page`): right after the sync releases its drain lease the held file is rewritten without that line, imported under its path slug, the hold cleared and the edit committed (`gbrain: repair frontmatter slug in <path>`), and the declared slug becomes an alias of the page; a file edited since the hold, a source with an unfinished sync and a sync under a remote job or agent are left for the next pass (`sync.slug_conflicts.auto_remove false` turns it off; the result's `slug_lines_removed` counts it). Every other case waits for the lane. The hold has three outcomes once the content-repair lane's `slug-conflicts` kind runs it (the maintenance run's `content_repair` phase, `gbrain sync unblock --apply`, or `gbrain repair content --source <source>`): **removed** (the named slug resolves to no page and names no other file, or to a page of a different type sharing no title token: the stray `slug:` line is removed, the file imported and committed, the hold cleared, with a receipt; a model under the `fences.repair` caps makes the same call when the two pages are not obviously different), **merge recommended** ([`merge_recommended`](#merge_recommended): the two files describe the same thing; gbrain recommends the merge and names the canonical page but never merges pages by itself), or **undecided** ([`content_repair_needs_human`](#content_repair_needs_human)). The lane judges the file with the screen managed sync froze it with: a hold the sync screen now admits as the file is (its slug line names the file's own page as written, or it no longer declares a conflicting slug) is **imported** unchanged in one guarded write that clears only the hold observation the lane read (a hold a newer sync wrote stays, with a retry), and a file sync would hold whatever the lane writes is [`slug_page_mismatch`](#slug_page_mismatch). Until that kind ships, the lane leaves the hold to the frontmatter repair preview below. | Nothing to run when the lane removes the line: the hold clears on the sync it prints. For a recommendation or an undecided hold, `gbrain sync status --source <source> --json` carries the paragraph (`human_reason`): merge the unique sections into the canonical page by hand or decide which page keeps the slug, delete or edit the file, commit, then `gbrain sync --source <source> --no-pull`. `human_reason` says what the lane found: "decide which page keeps the slug" only when the line names a live page (a database-only page is labelled), `still_invalid` names the other frontmatter fix codes, and a hold with no verdict yet never asks a person. A verdict an older gbrain recorded is rechecked once by the next sync or maintenance run. By hand at any time: 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, for approval). |
| <a id="file_too_large"></a>`file_too_large` | Over the page size limit: 24 MiB for a Markdown page, 5 MB for a code file ([limits per entry point](memory-boundaries.md#large-page-limits)). Every page under the limit is stored, chunked and searchable whatever its size, so this hold only fires above it, and the same bytes are held on every retry. A smaller page refused by an MCP or HTTP transport limit is a different refusal: send it by file. | Leave the file out of the source: read `gbrain config get sync.exclude`, then `gbrain config set sync.exclude '<current list>,<path>'`; or, if it must be in the brain, split it into files under the limit and commit. The next `gbrain sync --source <source> --no-pull` clears the hold, also when nothing was committed since (#6712 PR 2). |
| <a id="managed_image_sync_unsupported"></a>`managed_image_sync_unsupported` | Managed sync imports image files only while multimodal embedding is on (`GBRAIN_EMBEDDING_MULTIMODAL=true`): the image page, its OCR text and its image vector are built by the coordinated image importer at preparation, and `source_path` is recorded. While multimodal embedding is off, each image import is held with this code instead of refusing the whole sync (#5493); deleting or renaming an image still reconciles its page. These holds count as missing coverage (the image is not searchable) but never escalate, because they are not a content fault. | Nothing is broken. To import the images, set `GBRAIN_EMBEDDING_MULTIMODAL=true` on the owner and run `gbrain sync --source <source> --no-pull`: the next discovery re-screens every image hold and imports the files (#6529). To stop holding them instead, leave them out of the source (`gbrain config get sync.exclude`, then `gbrain config set sync.exclude '<current list>,**/*.png'`); that clears the holds on the next sync. A held image is also re-screened when it changes and on `gbrain sources retry-held <source>`. |
| <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 managed-sync hold re-screens on every sync, so either clears it on the next one. |
diff --git a/test/helpers/slug-autoheal-scenarios.ts b/test/helpers/slug-autoheal-scenarios.ts
index 23a07090eb..7107bfc2f8 100644
--- a/test/helpers/slug-autoheal-scenarios.ts
+++ b/test/helpers/slug-autoheal-scenarios.ts
@@ -38,6 +38,7 @@ const ALIASES = 'aliases: ["Fund A", "Fund A Capital"]';
const STRAY_BYTES = `---\ntitle: "Fund A"\ntype: company\nslug: fund-a\n${ALIASES}\n---\nFund A invests in example companies.\n`;
const DB_ONLY_HELD = 'companies/fund-b-partners.md';
const FILE_HELD = 'people/alice-example.md';
+const OTHER_TYPE = 'media/quarterly-talk.md';
/** A git checkout with the fixture committed, before the managed brain claims it; `dbOnly` adds a database-only page `fund-b`. */
function plant(files: Record<string, string>, dbOnly = false) {
@@ -117,18 +118,22 @@ export async function existingPageStopsAndAsks(databaseUrl?: string) {
[DB_ONLY_HELD]: '---\ntitle: Fund B Partners\ntype: company\nslug: fund-b\n---\nFund B Partners notes.\n',
'concepts/fund-c.md': '---\ntitle: Fund C\ntype: concept\n---\nThe Fund C idea.\n',
[FILE_HELD]: '---\ntitle: Fund C notes\ntype: concept\nslug: concepts/fund-c\n---\nMore on Fund C.\n',
+ [OTHER_TYPE]: '---\ntitle: Quarterly talk\ntype: media\nslug: fund-b\n---\nA recorded talk.\n',
};
await managedBrain(async ({ engine, root }) => {
const result = await sync(engine);
expect(result.slug_lines_removed).toMatchObject({ removed: 0, failed: 0 });
- expect(Object.values(result.slug_lines_removed!.left_by_reason).reduce((a, b) => a + b, 0)).toBe(2);
+ expect(Object.values(result.slug_lines_removed!.left_by_reason).reduce((a, b) => a + b, 0)).toBe(3);
+ expect(result.slug_lines_removed!.left_by_reason.different_type).toBe(1);
for (const [path, content] of Object.entries(files)) expect(read(root, path)).toBe(content);
const held = await holds(engine);
- expect(held.map(hold => hold.path).sort()).toEqual([DB_ONLY_HELD, FILE_HELD]);
+ expect(held.map(hold => hold.path).sort()).toEqual([DB_ONLY_HELD, OTHER_TYPE, FILE_HELD].sort());
for (const hold of held) expect(hold.meta.content_repair).toBeUndefined();
const runner = await repairRunner(engine, { apply: true, noEmbed: true, logger: quiet });
await runner.run('slug-conflicts', await resolveRepairScope(engine, 'default'), { explicit: true, sourceFlag: 'default', noLlm: true });
const judged = new Map((await holds(engine)).map(hold => [hold.path, hold]));
+ expect([...judged.keys()].sort()).toEqual([DB_ONLY_HELD, FILE_HELD]);
+ expect(read(root, OTHER_TYPE)).not.toContain('slug: fund-b');
expect(judged.get(DB_ONLY_HELD)!.meta.content_repair).toMatchObject({ action: 'pending', reason: 'llm_disabled', named: 'fund-b', named_db_only: true, lane_version: CONTENT_REPAIR_LANE_VERSION });
expect(judged.get(FILE_HELD)!.meta.content_repair).toMatchObject({ action: 'pending', reason: 'llm_disabled', named: 'concepts/fund-c', lane_version: CONTENT_REPAIR_LANE_VERSION });
expect(judged.get(FILE_HELD)!.meta.content_repair!.named_db_only).toBeUndefined();
@@ -143,7 +148,7 @@ export async function existingPageStopsAndAsks(databaseUrl?: string) {
expect(verdict.human_reason).toContain(FILE_HELD);
expect(verdict.human_reason).toContain('page `concepts/fund-c`');
expect(verdict.human_reason).toContain('decide which page keeps the slug');
- for (const [path, content] of Object.entries(files)) expect(read(root, path)).toBe(content);
+ for (const path of [DB_ONLY_HELD, FILE_HELD]) expect(read(root, path)).toBe(files[path]!);
}, { databaseUrl, setup: plant(files, true) });
}