Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
docs(key-files): classic rename holds and S-51 rename identity; type the held origin (GBRA-133 PR 1)
garrytan1dd70469b2e4
diff --git a/docs/architecture/key-files/files-and-sync-1.md b/docs/architecture/key-files/files-and-sync-1.mdindex 2f20455601..057e5bc414 100644--- a/docs/architecture/key-files/files-and-sync-1.md+++ b/docs/architecture/key-files/files-and-sync-1.md@@ -8,6 +8,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/brain-repo-durability.ts` + `src/commands/sources-harden.ts` — brain-repo git durability. `hardenBrainRepo(opts)` makes a brain's working tree durable, idempotently: divergence-safe pull, a LOCAL untracked `.git/hooks/post-commit` auto-push safety net (never committed — a pulled commit can't rewrite executed code next to the token; installed into the active `core.hooksPath` dir and excluded via `.git/info/exclude` when that dir is tracked), a committed `scripts/brain-commit-push.sh` delegating to `gbrain git commit-push` (`src/core/git/commit-push.ts`, #6530; guide `docs/guides/shared-checkout-git.md`) that never exits 0 without a confirmed push, and a hook running the harden-captured CLI with `--push-only --require-clean` (both `# gbrain-protocol: 2`; harden never downgrades), durability rules patched into the active resolver file (`findResolverFile` → RESOLVER.md > AGENTS.md; taxonomy rendered from the bundled `_brain-filing-rules.json`), a minimal DB-free pull cron (launchd/crontab running `gbrain sources pull --path <dir>` so it never opens the PGLite single-writer lock), and a push-probe verify (no heartbeat commit). Credential is REPO-scoped (`acceptPat` from `--pat-file`/`GBRAIN_GITHUB_PAT`, warns on loose perms; reuses an existing repo-local `credential.helper`, else a `0600` store wired via repo-local config); the token is redacted everywhere via `redactSecretsInText` and never enters the repo, remote URL, logs, or `DurabilityReport`. `unhardenBrainRepo` removes the cron/hook/credential wiring (ownership-fingerprinted); `sources remove` runs it only AFTER the source row's DELETE commits (a refused or raced delete leaves the scaffolding intact; post-commit teardown failure is loud but non-fatal). CLI: `gbrain sources harden <id|--all>` / `pull <id>|--path <dir>` / `unharden <id>`; auto-harden fires on `sources add --url ... --pat-file` for managed clones (`--no-harden` opts out). `sources pull --path` is dispatched in `src/cli.ts` BEFORE `connectEngine` so the cron stays DB-free. CLI-only (writes executables + an OS cron + a credential helper on the host); never exposed over MCP. `isDurabilityHardened(repoPath)` (the durability hook banner is installed) and `commitWriteThroughFile(repoPath, absPath, slug, action = 'write-through')` are the shared helpers every write-through sink (page write/delete, facts fence, timeline, lint --fix) uses to best-effort commit ONE file path-limited on a hardened repo — never throws, false on any failure; `action` only labels the subject (`gbrain: <action> <slug>`; `'delete write-through'` for removals). `isDurabilityHardenedAsync(repoPath)` is the owners' non-blocking probe (#6210: rejects `git_unavailable` when unsure); it and the persistence Git runner (`effect-git.ts`) spawn through `execFileBounded` (defined in the import-free `src/core/bounded-child-exec.ts` and re-exported here; `git-remote.ts` `pullRepo` shares it), which settles at its deadline or on abort from its own timer because Bun can drop a child's pipe events and, before 1.3.14, its exit event (oven-sh/bun#30301) when bun:test `expect().resolves/.rejects` re-enters the event loop; an unbounded wait there stranded `disposePersistenceConsumer` and hung every later test in the file (test: `test/bounded-child-exec.test.ts`). Tests: `test/brain-repo-durability.serial.test.ts`, `test/git-remote-durable.serial.test.ts`, `test/brain-durability-hook.serial.test.ts`, `test/durability-cron.test.ts`. `brain_remote_contains_commit` checks the exact `refs/heads/<branch>` at every effective push URL, fetches each advertised tip without writing `FETCH_HEAD`, and proves ancestry of the captured commit; branch existence, a different fetch destination, or a stale tracking ref is not enough. Probe diagnostics are suppressed, ambiguous URL resolution fails closed, and recovery is skipped if local HEAD has moved since the failed push. This check runs after a rejected push and after retry failure, logging `ok-already-on-remote` on confirmation; `getLastPushOutcome` recognizes it as success. Existing unmanaged installations must rerun `gbrain sources harden <source-id>` to refresh both the local hook and committed helper; upgrading the CLI alone does not rewrite those scripts. Managed worktrees retain the persistence outbox as their Git writer; generated legacy helpers refuse to bypass it. Locks, waits, outcomes and the per-checkout conflict record: the guide. Tests: `test/git-commit-push-6530.serial.test.ts`.- `src/core/classic-file-holds.ts` — classic sync's deterministic per-file refusals as holds in the shared hold store. `classifyClassicFile(root, relPath, gitRoot)` reads metadata only (lstat, the symlink target's realpath, an open+close of a regular file; for a missing path `git ls-tree HEAD` and `git ls-files -v` with optional locks off) and returns `file_unreadable` (`symlink_in_repo`, `symlink_outside_root`, `symlink_dangling`, `symlink_loop`, `permission_denied`, `not_regular_file`), `absent_from_worktree` (`skip_worktree`, `deleted_locally`), or null (a readable file, a directory, a path HEAD lacks, any other error, all left to the drain's existing paths). `classicFileHoldFix` is `gitHoldFix`'s builder for both codes: the user's step for a symlink or permission, `ask_user` between restore and committing the deletion for an absent file; `<checkout>` is an `inputs` placeholder. Pinned by `test/pathological/s-classic-file-holds.test.ts` (+ its Postgres wrapper).+- `src/core/classic-rename-holds.ts` — `gitHoldFix`'s builder for classic sync's two rename holds (GBRA-133): `rename_identity_unreadable` (S-51; the database refused to compare a renamed file's title or id, so the new file waits and the old page stays whole; written by `holdUnreadableRenames` in `src/commands/sync/holds.ts` and decided again by `redecideUnreadableRenames` when the file changes) and `rename_reconcile_failed` (S-67; the `renames.ts` reconcile threw something other than its unprovable verdict or a transient database error while finding stale rows, so the rename is held with the error's class and code only; a failed delete keeps the `<rename:…>` marker). Both fixes are the user's. Pinned by `test/pathological/s-51-rename-identity-unreadable.test.ts` and `test/pathological/s-70-classifier-origin.test.ts`.- `src/core/content-sanity-literals.ts` — operator literal-substring loader. Reads `~/.gbrain/junk-substrings.txt`, one literal per non-comment non-blank line; optional `# name=<id>` header pairs an identifier with the following literal so audit JSONL groups by site (`linkedin_auth_wall`, `reddit_blocked`, etc.). Fail-soft on ENOENT (missing file = empty array). Loaded on every ingest. Deliberately literal substrings (NOT regex) to defeat ReDoS. Pinned by `test/content-sanity-literals.test.ts`.- `src/core/content-sanity.ts` — pure assessor for the content-sanity defense. `assessContent(content, opts): SanityVerdict` returns one of `ok | warn_oversize | hard_block_junk_pattern | soft_block_oversize` with `{reason, bytes, matched_pattern_name?}`. Six built-in junk patterns (Cloudflare challenge dumps, CAPTCHAs, 403 dumps, bare error-page titles) compiled at module load; operator literal substrings via `loadOperatorLiterals()` from `src/core/content-sanity-literals.ts`. `ContentSanityBlockError` tagged class is the typed throw shape every wrapper site (`gbrain import`, `put_page` MCP op, `gbrain sync`, `/ingest` webhook) catches via the existing exception flow. The bytes-parity contract pins `Buffer.byteLength(content, 'utf8')` against the embedder's actual byte count so a 499K-byte page can't be soft-blocked on assessment then overflow on embed. Knob resolution chain env > file (`~/.gbrain/config.json`) > DB > defaults. Four knobs: `content_sanity.bytes_warn` (50_000), `content_sanity.bytes_block` (500_000), `content_sanity.junk_patterns_enabled` (true), `content_sanity.disabled` (false; `GBRAIN_NO_SANITY=1` is the loud-stderr kill-switch). `assessContentSanity(opts): SanityAssessment` returns the three-tier disposition (`shouldQuarantine` / `shouldFlag` + reason/detail) consumed by `importFromContent` and `gbrain quarantine scan`; adds the fuzzy prose-vs-markup ratio pass (markup chars / total above `max_markup_ratio`; code pages exempt; gated by `prose_check_enabled`) on top of the byte + junk-pattern passes. Three more knobs: `content_sanity.junk_disposition` (`quarantine` default | `reject`; no env override — a destructive flip belongs in explicit config), `content_sanity.max_markup_ratio` (0.85, env `GBRAIN_MAX_MARKUP_RATIO`, clamped `(0,1]`), `content_sanity.prose_check_enabled` (true). Pinned by `test/content-sanity.test.ts`. Per-pattern opt-out without the kill-switch: `content_sanity.disabled_patterns` names built-in junk patterns to skip (a JSON array `["access_denied"]` or a comma list `access_denied,error_title`; malformed JSON falls back to the comma parse so a hand-typed value still lands) — the file plane takes the array, the DB plane the string.diff --git a/docs/architecture/key-files/files-and-sync-2.md b/docs/architecture/key-files/files-and-sync-2.mdindex c40a4d7d4d..3401db8987 100644--- a/docs/architecture/key-files/files-and-sync-2.md+++ b/docs/architecture/key-files/files-and-sync-2.md@@ -15,7 +15,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/sync.ts` — Pure sync functions (manifest parsing, filtering, slug conversion). Exported `pruneDir(name: string): boolean` is the single source of truth for descent-time directory exclusion across walkers — blocks `node_modules` (no leading dot, so a naive walker would descend into it and inflate MISSING_OPEN counts via vendor packages), `vendor`/`dist`/`build`/`venv`, dot-prefix dirs, and `*.raw` sidecars — NOT `ops/`, which is ordinary user content (the bundled daily-task-manager stores `ops/tasks` there); `isSyncable` applies it per path segment, and `walkMarkdownFiles` in `src/commands/extract.ts` + `listTextFiles` in `src/core/cycle/transcript-discovery.ts` consult it BEFORE recursing to save the IO of walking thousands of vendor files. `manageGitignore` worktree discriminator matches the gitdir path segment (`/modules/<name>` = submodule, `/worktrees/<name>` = worktree, per Git's documented layout) so Conductor worktrees (first-class repos) get `.gitignore` management for storage-tiering. The sync-failure ledger (failure store, error classifier, the shared bookmark gate, and the doctor severity rule) lives in `src/core/sync-failure-ledger.ts`; `sync.ts` re-exports `classifyErrorCode`, `summarizeFailuresByCode`, `loadSyncFailures`, `unacknowledgedSyncFailures`, `acknowledgeSyncFailures`, `recordSyncFailures`, `decideSyncFailureSeverity`, `applySyncFailureGate`, and the `SyncFailure` type for backward-compatible imports — see its entry below. `isSyncable` factored through private `classifySync(path, opts): SyncableReason | null`; exported companion `unsyncableReason(path, opts)` returns the same tagged reason or null when syncable. `SYNC_SKIP_FILES` is a named export (the canonical metafile basenames `schema.md`, `index.md`, `log.md`, `README.md`, `RESOLVER.md`, skipped at any depth); `SYNC_ROOT_SKIP_FILES` (#5186, W14 P1.5b) adds the bootstrap scaffolding `AGENTS.md` / `CLAUDE.md` at depth 0 only, and `isSyncMetafile(path)` is the one predicate `classifySync` and the bulk-import collector (`commands/import.ts`) share (the managed effect scan's `isMetafilePage` in `persistence/effects.ts` still reads `SYNC_SKIP_FILES` directly), so an earlier-indexed root `agents` page survives under the #1433 guard (`test/sync-root-agents-metafile.test.ts`). `SyncableReason` union: `'metafile' | 'strategy' | 'pruned-dir' | 'include-glob-miss' | 'exclude-glob-hit' | 'malformed-path'`. Malformed filenames are TWO-TIER: `hasMalformedPathSegment` (ADMISSION — control chars on any path; square brackets on `.md`/`.mdx` paths only, so code-strategy lanes keep indexing `app/[id]/page.tsx` framework layouts) vs `isPoisonedPath` (DESTRUCTION — only the injection signature `](` or control chars; sync's row-DELETING lanes gate on this so a bare-bracket markdown row already in the DB survives reconcile while its file exists). `sanitizePathForDisplay` scrubs control bytes + caps length before echoing such paths. The un-syncable cleanup loop (`sweepUnsyncableModified` in `src/commands/sync/deletes.ts`) guards on `unsyncableReason(path)` being `'metafile'` OR `'pruned-dir'` so previously-indexed metafile pages AND deliberately put-created pages under pruned dirs survive every re-sync. Does NOT cover `manifest.deleted` (the upstream filter already strips metafiles). Pinned by `test/sync-isSyncable-shape.test.ts` (15 cases, duality contract) + `test/sync-metafile-skip.test.ts` (3 PGLite cases incl. the renamed `.md → .txt` negative). `pruneDir`: `pruneDir(name, parentDir?)` extended with optional `parentDir`. When provided, additionally rejects directories containing `.git` as a FILE — the git submodule gitfile pattern (regular repos have `.git` as a DIRECTORY; submodules as a file pointing into the parent's `.git/modules/`). Sync + extract walkers thread `parentDir` so the gitfile-as-FILE check fires per descend step. Best-effort: `statSync` failures fall through and treat as a normal dir. Prevents phantom imports from a worktree-with-submodules sync walking into submodule trees. Pinned by `test/sync-walker-submodule.test.ts`. The legacy failure ledger re-export is distinct from managed cursor-keyed mirrors: repeat managed observation does not inflate attempts, success clears only the matching cursor, and managed failures cannot be acknowledged or auto-skipped. `isMultimodalEnabled(env)` (`GBRAIN_EMBEDDING_MULTIMODAL=true`) is the one predicate managed discovery, the hold re-screen, `embed --stale`, the blocked-projection hint and doctor `image_embedding_coverage` read for whether images are imported and embedded.-- `src/core/sync-rename-identity.ts` — the one confirmation stage for inexact Git renames (#6729). `confirmRenameIdentities` reads committed sides through one `git cat-file --batch` stream (64 KiB heads) and the dirty tree's working side from disk, with id and `slug:` from the frontmatter and the title by parseMarkdown precedence (frontmatter, then the first H1, no filename fallback; `markdown.ts` `explicitMarkdownTitle`), the old side taking the title its page row stores; it keeps an R<100 pair on a same-slug respelling, a unique shared `id`, or with no id on either side a unique `slug:` line or title (titles also unique among live pages). `explicitIdVeto` is the one explicit-id veto the managed takeovers consult (also the #6727 legacy-slug adoption in `sync-discovery.ts`: two different explicit ids hold `legacy_slug_conflict`, reason `explicit_id_conflict`). An add whose id uniquely matches a delete in the range becomes a rename only with continuity (same file name, title or bytes; `digest` is the sha256 of a file that fits the head read), as decideImportIdentity asks of a move. Downgraded pairs record `read.from` / `read.to`. A dirty-tree verdict is bound to the bytes it read: each kept rename carries `identityHead` (sha256 of the first 64 KiB), classic `applyRename` re-checks it before the identity moves and managed `readSyncContent` refuses `source_changed` on frozen bytes that differ.+- `src/core/sync-rename-identity.ts` — the one confirmation stage for inexact Git renames (#6729). `confirmRenameIdentities` reads committed sides through one `git cat-file --batch` stream (64 KiB heads) and the dirty tree's working side from disk, with id and `slug:` from the frontmatter and the title by parseMarkdown precedence (frontmatter, then the first H1, no filename fallback; `markdown.ts` `explicitMarkdownTitle`), the old side taking the title its page row stores; it keeps an R<100 pair on a same-slug respelling, a unique shared `id`, or with no id on either side a unique `slug:` line or title (titles also unique among live pages). `explicitIdVeto` is the one explicit-id veto the managed takeovers consult (also the #6727 legacy-slug adoption in `sync-discovery.ts`: two different explicit ids hold `legacy_slug_conflict`, reason `explicit_id_conflict`). An add whose id uniquely matches a delete in the range becomes a rename only with continuity (same file name, title or bytes; `digest` is the sha256 of a file that fits the head read), as decideImportIdentity asks of a move. Downgraded pairs record `read.from` / `read.to`. A dirty-tree verdict is bound to the bytes it read: each kept rename carries `identityHead` (sha256 of the first 64 KiB), classic `applyRename` re-checks it before the identity moves and managed `readSyncContent` refuses `source_changed` on frozen bytes that differ. GBRA-133 S-51: an id, `slug:` or title holding U+0000 or a lone surrogate is absent before any SQL (never normalized), so the pair takes the ordinary unconfirmed-rename rules; both identity reads batch every path and, on SQLSTATE 22021/22P05 only, retry path by path, and the inexact pairs carrying a refused value come back in `heldRenames` (classic `preflight.ts` holds them as `rename_identity_unreadable`, keeping the old page; with `holdUnreadable` unset, as in managed discovery, the error is rethrown). `redecideHeldRename` decides a held pair again from the kept page's stored id and title once its file changes. Any other error propagates. Pinned by `test/pathological/s-51-rename-identity-unreadable.test.ts`.- `src/core/sync-identity-downgrades.ts` — durable records of downgraded pairs (`op_checkpoints` op `sync-identity-downgrade`, fingerprint = old page id, open until a disposition is set or the old page is restored or purged; no time window; the checkpoint sweep keeps open records), the purge-hold SQL predicate, the live list (new slug read live), the report lines and the restore argv; the per-pair remedy every surface prints (`identityRemedyParts`, `identityRemedy`, `withIdentityRemedies`, `renameIdentityPreviewArgv`, `remedyAction`; on a managed brain the remedy is `--close` with `carry_unavailable: managed_remedy_unavailable`); `settleIdentityDowngrade` (sets `completed_keys[0].disposition = { kind: remedied | closed, at }` on an open record); `identityRestoreAvailable` (the decideUnboundWrite rule) keeps the restore off the report and doctor on an unbound Postgres source with a checkout, where it would refuse `owner_unavailable`.- `src/core/repair/rename-identity.ts` — `gbrain repair rename-identity` (#6729), explicit-only, preview-bound, destructive. `plan` selects one open pair (`--slug`/`--from`), hashes `identityRemedyParts` (brain, pair, both page ids and revisions, disposition) and saves the approved set; with no pair named it lists the open pairs. On a managed brain a carry preview returns no items with `details.code: managed_remedy_unavailable` and the `--close` preview, and an apply refuses with that code. `carryIdentity` (classic only): one maintenance transaction under both page locks re-checks the hash, the open record and `fenceRowChecks`, merges matching fence rows onto the old rows, retires the provisional page under `purgedSlug`, moves the old page to the new slug (`updateSlug` redirect), moves the provisional's page-id rows (`movePageIdReferences`), imports the new file, settles the record `remedied`. `--close` settles `closed`. Refusals: `fact_rows_collide`, `managed_remedy_unavailable`, `changed_since_preview`, `preview_changed`, `invalid_params`.diff --git a/test/pathological/s-51-rename-identity-unreadable.test.ts b/test/pathological/s-51-rename-identity-unreadable.test.tsindex afdbc3e9e3..7949dc0cf8 100644--- a/test/pathological/s-51-rename-identity-unreadable.test.ts+++ b/test/pathological/s-51-rename-identity-unreadable.test.ts@@ -103,7 +103,7 @@ for (const { backend, databaseUrl } of pathologicalArms()) {const held = (await holdsOf(engine, r.sourceId)).find(h => h.path === 'notes/b.md');expect({ cursor: await r.lastCommit() === r.head(), healthy: await page(engine, r.sourceId, 'ok/healthy-1') !== null,a: await page(engine, r.sourceId, 'notes/a'), b: await page(engine, r.sourceId, 'notes/b'), d: await page(engine, r.sourceId, 'notes/d'), c: await page(engine, r.sourceId, 'notes/c'),- hold: held && { code: held.code, origin: held.meta.rename_from?.pageId }, ledger: loadSyncFailures().filter(f => f.source_id === r.sourceId).length })+ hold: held && { code: held.code, origin: held.meta.rename_from?.pageId ?? null }, ledger: loadSyncFailures().filter(f => f.source_id === r.sourceId).length }).toEqual({ cursor: true, healthy: true, a, b: null, d: c, c: null, hold: { code: 'rename_identity_unreadable', origin: a }, ledger: 0 });const fix = gitHoldItem(held!).fix;expect({ actor: fix.actor, argv: fix.argv, then: fix.then?.argv }).toEqual({ actor: 'user', argv: ['gbrain', 'sources', 'status', r.sourceId, '--json'],