Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(persistence): a checkout Git cannot read refuses its writer manifest instead of hashing every file (W4.4)
time-attack019b59544d47
diff --git a/docs/architecture/key-files/persistence-stalls.md b/docs/architecture/key-files/persistence-stalls.mdindex 6c1c033a57..2dff371626 100644--- a/docs/architecture/key-files/persistence-stalls.md+++ b/docs/architecture/key-files/persistence-stalls.md@@ -12,4 +12,4 @@ 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). 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 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`.diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex ea43fd22b9..52d749de6b 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -2710,7 +2710,7 @@ More: [docs/architecture/topologies.md#transfer-manifest-scope](../../docs/archi| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable ||---|---|---|---|---|---|---|-| The canonical worktree manifest cannot be recorded safely: the checkout holds a symlink or a Git submodule, or a Git-scoped comparison ran on a directory Git cannot list. | The request itself was wrong or no longer matches the brain; nothing was changed. | Correct the request using the message above, then retry. | agent | `repeat the read that failed` | 1 | no |+| The canonical worktree manifest cannot be recorded safely: the checkout holds a symlink or a Git submodule, a Git-scoped comparison ran on a directory Git cannot list, or Git cannot read a directory that holds .git. | The request itself was wrong or no longer matches the brain; nothing was changed. | Correct the request using the message above, then retry. | agent | `repeat the read that failed` | 1 | no |### writer_not_initializeddiff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex c5d3191756..bf8a7252f4 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -362,7 +362,7 @@ export const CODES = {writer_lock_unavailable: { class: 'retryable', summary: "Another activation probe is running." },writer_manifest_mismatch: { class: 'caller', summary: "Successor checkout differs from the recorded canonical manifest." },writer_manifest_rescope_required: { class: 'host_only', summary: "A writer transfer prepared by an older release covers every file of the old checkout, ignored files included, so a clean Git clone cannot match it.", why: "Transfer manifests now cover the files Git tracks, so ignored secrets such as .env files are never read, hashed or required on the successor; a manifest recorded before that change is prepared again instead of asking the user to copy ignored files.", docs: 'docs/architecture/topologies.md#transfer-manifest-scope', suggestion: 'On the owner host, run gbrain sources writer transfer prepare <source> again with its admin intent and state, then accept with the new epoch and manifest.' },- writer_manifest_unsafe: { class: 'caller', summary: "The canonical worktree manifest cannot be recorded safely: the checkout holds a symlink or a Git submodule, or a Git-scoped comparison ran on a directory Git cannot list." },+ writer_manifest_unsafe: { class: 'caller', summary: "The canonical worktree manifest cannot be recorded safely: the checkout holds a symlink or a Git submodule, a Git-scoped comparison ran on a directory Git cannot list, or Git cannot read a directory that holds .git." },writer_not_initialized: { class: 'host_only', summary: "Persistence identity is missing." },writer_not_quiesced: { class: 'host_only', summary: "Older writers or maintenance jobs are still running." },writer_pool_capacity: { class: 'retryable', summary: "Mirror recovery is waiting for publication capacity." },diff --git a/src/core/persistence/worktree-manifest.ts b/src/core/persistence/worktree-manifest.tsindex 03efa9151a..d34b5ba225 100644--- a/src/core/persistence/worktree-manifest.ts+++ b/src/core/persistence/worktree-manifest.ts@@ -39,20 +39,45 @@ export type StoredWorktreeManifest = WorktreeManifest & { canonical_stamp?: striexport const MANIFEST_PROGRESS_MIN_FILES = 5000;const GIT_LIMITS = { timeoutMs: 60_000, maxBytes: 256 * 1024 * 1024 };+const unsafe = (message: string, suggestion: string, opts?: Parameters<typeof opError>[3]) => opError('writer_manifest_unsafe', message, suggestion, opts);+/** The scope a stored manifest was recorded in (older releases recorded `tree` without saying so). */export function storedManifestScope(manifest: { scope?: WorktreeManifestScope } | null | undefined): WorktreeManifestScope {return manifest?.scope === 'git' ? 'git' : 'tree';}-/** `git` when `root` is the top of its own Git work tree, else `tree`. */+/**+ * True when `canonical` positively cannot be the top of its own Git work tree:+ * 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,+ * dubious ownership, timeout, Git missing), this refuses instead of hashing+ * the whole tree, which would open ignored files such as `.env`.+ */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) return 'tree';+ if (!top.ok) {+ if (positivelyNotGitTop(canonical)) 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.`,+ { why: 'Without Git the manifest would cover every file, ignored secrets included, so nothing was hashed.',+ fix: { argv: ['git', '-C', canonical, 'status'], consent: [], actor: 'user', requires_exclusive: false,+ why: 'Git prints why it cannot read this checkout (a damaged HEAD or index, or a checkout owned by another user).',+ user_message: `Git cannot read ${canonical}. Please run the command shown, repair what it reports, then run the gbrain step again.`,+ verify: { argv: ['git', '-C', canonical, 'rev-parse', '--show-toplevel'] } } });+ }try { return realpathSync(top.stdout.toString('utf8').trim()) === canonical ? 'git' : 'tree'; } catch { return 'tree'; }}-const unsafe = (message: string, suggestion: string) => opError('writer_manifest_unsafe', message, suggestion);const excluded = (rel: string) => rel.split('/').some(part => part === '.git' || part === '.gbrain-managed' || isPhysicalRootMetadata(part));/**diff --git a/test/persistence-manifest-git-scope.test.ts b/test/persistence-manifest-git-scope.test.tsindex 329ab81456..636059036c 100644--- a/test/persistence-manifest-git-scope.test.ts+++ b/test/persistence-manifest-git-scope.test.ts@@ -8,7 +8,7 @@*/import { afterAll, beforeAll, describe, expect, test } from 'bun:test';import { execFileSync } from 'node:child_process';-import { chmodSync, cpSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { chmodSync, cpSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';import { createHash } from 'node:crypto';import { basename, join } from 'node:path';import { tmpdir } from 'node:os';@@ -61,6 +61,25 @@ test('git scope hashes tracked files only and never opens an ignored one', () =>} finally { rmSync(home, { recursive: true, force: true }); }});+test('W4.4: a checkout Git cannot read refuses instead of hashing every file (ignored .env included)', () => {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-manifest-damaged-'));+ try {+ const root = join(home, 'brain'); gitCheckout(root);+ writeFileSync(join(root, '.git', 'HEAD'), 'garbage\n');+ // An unreadable ignored file: a whole-tree fallback would open it.+ chmodSync(join(root, '.env.local'), 0o000);+ let thrown: unknown;+ try { worktreeManifest(root); } catch (error) { thrown = error; }+ expect(thrown).toMatchObject({ code: 'writer_manifest_unsafe' });+ expect((thrown as { fix?: { argv?: string[]; verify?: { argv?: string[] } } }).fix).toMatchObject({+ argv: ['git', '-C', realpathSync(root), 'status'], verify: { argv: ['git', '-C', realpathSync(root), 'rev-parse', '--show-toplevel'] } });+ // A plain directory (no .git) still takes the exact-copy tree scope.+ const plain = join(home, 'plain'); mkdirSync(plain); writeFileSync(join(plain, 'a.md'), 'a\n');+ expect(worktreeManifest(plain)).toMatchObject({ file_count: 1 });+ expect(worktreeManifest(plain).scope).toBeUndefined();+ } finally { rmSync(home, { recursive: true, force: true }); }+});+test('a tracked submodule or symlink refuses writer_manifest_unsafe', () => {const home = mkdtempSync(join(tmpdir(), 'gbrain-manifest-unsafe-'));try {