Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(persistence): the writer manifest's not-a-checkout fallback uses the shared filesystem classifier, so a damaged parent repository refuses too
time-attack5cbfd55c701c
diff --git a/docs/architecture/key-files/persistence-stalls.md b/docs/architecture/key-files/persistence-stalls.mdindex 7d1b97eac0..fd8ab046b5 100644--- a/docs/architecture/key-files/persistence-stalls.md+++ b/docs/architecture/key-files/persistence-stalls.md@@ -12,5 +12,5 @@ sync-run, sync-holds, deactivation, source lifecycle) are in- `src/core/persistence/claim-phase.ts` — #6176: the phase a running write request's claim is in. `startClaimPhase`/`enterClaimPhase` keep a per-claim clock in the consumer (single and group routes); `claimPhaseStamp` is the jsonb each claim renewal stores in `persistence_requests.claim_phase` (v217), keyed to the execution token so a later claim never reads an earlier claim's ages. `claimStateOf` reads a row back as `preparing`/`publishing` (live renewal), `publication_transaction` (claim lapsed while running, read on the database clock: a transaction holds the row or the owner is gone; requeued once it ends), `file_publication` (`publication_started`; recovery finishes it) or `unrecorded`, with claim and phase ages, `resumes_on_its_own` and a `why`. `persistence.max_claim_ms` (default 600000, 60000 to 86400000; `validateMaxClaimConfigValue` is `config set`'s `invalid_params` refusal) is doctor `persistence_write_stall`'s threshold. Tests: `test/persistence-write-stall.test.ts`. Consumer and group-publish side (`consumer.ts`, `group-publish.ts`): every renewal of a single or group claim also stores `claim-phase.ts`'s stamp in the request's `claim_phase` column (v217: phase `preparing` or `publishing`, claim start, phase start and the execution token; group members get their own token), so writer status (`diagnostics.ts`, `claim` on each running blocker, never the token) and doctor `persistence_write_stall` can name a stuck phase without an extra statement per write. Tests: `test/persistence-write-stall.test.ts`.- `src/core/persistence/pre-activation-release.ts` — #6122: `preActivationClaims` lists the source bindings of a never-activated brain with their roots; `releasePreActivationClaims` (called by `deactivatePersistence` on a disabled brain once `deactivationBlockers` is empty) takes the local worktree locks, then in one transaction checks the admin state, the admin lock and that the brain is still disabled, re-runs the blockers, retires the claimed worktrees, deletes the source and host bindings and records a committed `writer_deactivate` change with `outcome.pre_activation: true`, so `cleanupRetiredManagedMarkers` clears this host's claim markers. It ensures the CLI writer registration first (a never-activated brain may have none). `sync-authority.ts` `resolveSyncPersistenceMode` refuses such a claimed source with an agent-first `writer_coordinator_required`: both choices in the suggestion, `fix` the state-bound release (`consent: ['destructive']`, so `ask_user`, with the dry run as `preview_argv`). In `deactivation.ts`: on a brain whose managed persistence was never activated, `--dry-run` reports the real `source_bindings` and each claim as `pre_activation_claims` (and `apply_command` when clean), and the state-bound run releases them through `pre-activation-release.ts`; with no claims a rerun still only cleans retired markers. Tests: `test/persistence-preactivation-claim.test.ts`. In `unbound-source.ts`: on a brain whose managed persistence is not activated, the hint offers editing the page's file plus `gbrain sync --source <id>` (and `persistence.unbound_write=database_only` where it applies) instead of the claim, and says a claim alone would block classic sync until activation or `gbrain sources writer deactivate`.- `src/core/persistence/sync-concurrent-write.ts` — #6194 (D4): `concurrentWriteProof` decides whether a managed sync import's `revision_conflict` receipt came from a concurrent database-only write. The proof is revision-linked: the page's live revision differs from the import's frozen `expected_revision`, and `pages.revision_write_request_id` names a committed non-sync request for the same source incarnation and page id (a delete or recreate of that page included; admission order is never used). `concurrentWriteHold` builds the `concurrent_write` hold (competing request id, operation and revision in `meta`; identifiers only). `sync-run.ts` `holdFailedFenceRequest` (the receipt branch) holds such a file exactly as it holds a prepare-time fence refusal; imports only (a held deletion would be re-screened at once), and without proof the failure still blocks. `sync-holds.ts` routes it (`gitHoldFix`: `gbrain sources reconcile <source> <slug> --preview`, then `sources retry-held`; `HoldRepairRoute.concurrent` from the summary's `concurrent` counter, read by `held-reads.ts`, doctor `git_held_files`, `sources retry-held` and the remote host-operator fix). Tests: `test/managed-sync-concurrent-write-hold.test.ts`.-- `src/core/persistence/worktree-manifest.ts` + `src/core/hardened-git.ts` — #6099 (re-exported by `ownership.ts`): a directory that is the top of its own Git work tree is hashed in `git` scope over `git ls-files -z --cached --stage` (working-tree bytes; a tracked file missing on disk counts as deleted; gitlinks, tracked symlinks and paths resolving through a symlink refuse `writer_manifest_unsafe`; untracked non-ignored files counted as `untracked_count`, never named), so gitignored files are never opened and a clean clone verifies; anything else keeps the `tree` scope (every file but `.git`, `.gbrain-managed` and physical-root metadata, digest unchanged). W4.4: when `git rev-parse` fails for a directory that holds a `.git` entry (damaged HEAD, dubious ownership, timeout, Git missing), `detectManifestScope` refuses `writer_manifest_unsafe` with a `git -C <dir> status` fix instead of falling back to `tree` (which read ignored files); only a directory with no `.git` entry is positively not a Git top (`positivelyNotGitTop`, the seam lane W1's shared classifier replaces). Stored manifests carry `scope: 'git'` (absent = tree, every older stored manifest), and each verifier recomputes in the stored scope: transfer accept and its dry run, rebind (the new directory in the current checkout's scope; a mismatch names the first differing paths via `manifestDifferences`), clone/reclone (`hashScope` on the recovery record; `topology-recovery.ts` hashes legacy records in tree scope). A tree-scope transfer whose Git successor does not match refuses `writer_manifest_rescope_required` (re-prepare on the owner host) instead of asking for ignored files; transfer prepare reports `untracked_files` with a warning. Migration v218 drops legacy `files` maps from `persistence_worktrees.manifest` and clone recovery records. Git runs through `src/core/hardened-git.ts` (shared with `company-brain/revision.ts`); W4.3: `assertHardenedGitArgs` allows only filter-free plumbing (`rev-parse`, `ls-files`, `ls-tree`, `cat-file` without `--filters`/`--textconv`, `hash-object --no-filters`, `check-attr`, `diff-index --cached`) in both wrappers, and `hardenedPathDirty` is the `git status -- <path>` equivalent (untracked, staged incl. unborn HEAD, worktree vs index; `null` for conversion attributes, CRLF bytes, symlinks/gitlinks and exec-bit-only changes). Tests: `test/persistence-manifest-git-scope.test.ts`, `test/hardened-git-filters.test.ts`.+- `src/core/persistence/worktree-manifest.ts` + `src/core/hardened-git.ts` — #6099 (re-exported by `ownership.ts`): a directory that is the top of its own Git work tree is hashed in `git` scope over `git ls-files -z --cached --stage` (working-tree bytes; a tracked file missing on disk counts as deleted; gitlinks, tracked symlinks and paths resolving through a symlink refuse `writer_manifest_unsafe`; untracked non-ignored files counted as `untracked_count`, never named), so gitignored files are never opened and a clean clone verifies; anything else keeps the `tree` scope (every file but `.git`, `.gbrain-managed` and physical-root metadata, digest unchanged). W4.4: when `git rev-parse` fails for a directory that holds a `.git` entry (damaged HEAD, dubious ownership, timeout, Git missing), `detectManifestScope` refuses `writer_manifest_unsafe` with a `git -C <dir> status` fix instead of falling back to `tree` (which read ignored files); only a directory that `git-checkout.ts` `classifyGitCheckout` reads as `not_git` (no `.git` entry at or above it, no `GIT_DIR`) keeps `tree` scope. Stored manifests carry `scope: 'git'` (absent = tree, every older stored manifest), and each verifier recomputes in the stored scope: transfer accept and its dry run, rebind (the new directory in the current checkout's scope; a mismatch names the first differing paths via `manifestDifferences`), clone/reclone (`hashScope` on the recovery record; `topology-recovery.ts` hashes legacy records in tree scope). A tree-scope transfer whose Git successor does not match refuses `writer_manifest_rescope_required` (re-prepare on the owner host) instead of asking for ignored files; transfer prepare reports `untracked_files` with a warning. Migration v218 drops legacy `files` maps from `persistence_worktrees.manifest` and clone recovery records. Git runs through `src/core/hardened-git.ts` (shared with `company-brain/revision.ts`); W4.3: `assertHardenedGitArgs` allows only filter-free plumbing (`rev-parse`, `ls-files`, `ls-tree`, `cat-file` without `--filters`/`--textconv`, `hash-object --no-filters`, `check-attr`, `diff-index --cached`) in both wrappers, and `hardenedPathDirty` is the `git status -- <path>` equivalent (untracked, staged incl. unborn HEAD, worktree vs index; `null` for conversion attributes, CRLF bytes, symlinks/gitlinks and exec-bit-only changes). Tests: `test/persistence-manifest-git-scope.test.ts`, `test/hardened-git-filters.test.ts`.- `src/core/git-checkout.ts` — #6210 (fix wave 12): `classifyGitCheckout(dir, env = process.env): 'git' | 'not_git' | 'unknown'` decides from the filesystem alone whether a directory is inside a Git checkout: `not_git` only when the directory exists and no `.git` entry (directory or gitdir file) is at or above it and `GIT_DIR` is unset; `unknown` for a missing directory or any lookup error other than absence. Git's own exit 128 is locale-dependent and also means a damaged HEAD, a bad gitdir or dubious ownership, so callers that soften "not a checkout" use this instead. `isDurabilityHardenedAsync` (`brain-repo-durability.ts`) returns false only for `not_git` or an absent hook; every other failure (a git probe run with `LC_ALL=C` failing, a timeout, an unreadable hook) rejects `git_unavailable`, and `runPersistenceEffects` (`persistence/effects.ts`) settles each cached per-root probe to `{durable}|{error}` and records the error on every coalesced effect, so the effects stay queued (and park after repeated failures) instead of completing as `durability_not_enabled`. Tests: `test/git-checkout.test.ts`, the `#6210` block of `test/persistence-git-coalescing-5530.slow.test.ts` (Postgres via its e2e twin).diff --git a/src/core/persistence/worktree-manifest.ts b/src/core/persistence/worktree-manifest.tsindex d34b5ba225..5cc02e976e 100644--- a/src/core/persistence/worktree-manifest.ts+++ b/src/core/persistence/worktree-manifest.ts@@ -25,6 +25,7 @@ import { isAbsolute, join, relative, sep } from 'node:path';import { opError } from '../ops/contract.ts';import { createProgress, type ProgressOptions } from '../progress.ts';import { hardenedGitSync } from '../hardened-git.ts';+import { classifyGitCheckout } from '../git-checkout.ts';import { digest, sha256 } from './digest.ts';import { isPhysicalRootMetadata } from './root-metadata.ts';import type { PhysicalRootRecovery } from './physical-root-recovery.ts';@@ -51,10 +52,6 @@ export function storedManifestScope(manifest: { scope?: WorktreeManifestScope }* it has no `.git` directory or file. (Wave 12 seam: lane W1's shared* "positively not a Git checkout" classifier replaces this at integration.)*/-function positivelyNotGitTop(canonical: string): boolean {- try { lstatSync(join(canonical, '.git')); return false; } catch (error) { return (error as NodeJS.ErrnoException).code === 'ENOENT'; }-}-/*** `git` when `root` is the top of its own Git work tree, else `tree`. W4.4:* when Git cannot answer for a directory that holds `.git` (damaged HEAD,@@ -65,7 +62,7 @@ export function detectManifestScope(root: string): WorktreeManifestScope {const canonical = realpathSync(root);const top = hardenedGitSync(canonical, ['rev-parse', '--show-toplevel'], { timeoutMs: 10_000, maxBytes: 64 * 1024 });if (!top.ok) {- if (positivelyNotGitTop(canonical)) return 'tree';+ if (classifyGitCheckout(canonical) === 'not_git') return 'tree';throw unsafe('Git could not read this checkout, so no manifest was recorded.',`${canonical} holds a .git entry but \`git rev-parse\` failed (${top.reason === 'exit' ? 'a damaged repository, or a checkout owned by another user' : top.reason}), and hashing every file instead would read ignored files such as .env. `+ `Ask the user to run \`git -C ${canonical} status\` to see why Git refuses it and repair it (or run gbrain as the checkout's owner), then run the step again.`,