Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
verify after merging PR4's head: physical-root-record.ts routes execFileSync through src/core/spawn.ts (PR4's check:windows-hide seam); root-metadata.ts KEY_FILES entry tightened to keep core-persistence-continued.md under its 60000-byte cap (master grew it)
garrytanaf3a439d0609
diff --git a/docs/architecture/key-files/core-persistence-continued.md b/docs/architecture/key-files/core-persistence-continued.mdindex 22ca225fdb..177f870aa1 100644--- a/docs/architecture/key-files/core-persistence-continued.md+++ b/docs/architecture/key-files/core-persistence-continued.md@@ -45,7 +45,7 @@ Managed connector ingestion, connector item holds, sync checkpoint validation an- `src/core/persistence/graduation-target.ts` — engine graduation target side. `resolveTargetRoutes` reads the URL from `--url` or the `--url-env` variable and resolves the DDL route once (explicit `GBRAIN_DIRECT_DATABASE_URL`, else the Supabase direct derivation, else the main URL); `connectTargetEngines` hands that route to the connection manager as an explicit override, so no session-pooler fallback is chosen for the run. `targetIdentity` hashes host, port, database and user, never the password; `redactTargetUrl` is the only display form. `probeTarget` runs read-only probes in `BEGIN READ ONLY` sessions on both routes (server version, `vector` with halfvec, CREATE privilege, `session_replication_role` permission inside a savepoint, table ownership, seed-only emptiness, existing embedding columns, the role's superuser and BYPASSRLS standing and the auto-RLS event trigger and its function owner); `targetProbeBlockers` (non-superuser targets get the exact SQL a DBA runs for `vector`, BYPASSRLS and the event trigger) and `assertTargetReachable` turn a probe into plan blockers and typed refusals. `crossCheckRoutes` proves both routes reach one database with a transaction-scoped advisory lock keyed by a fresh nonce, read back from `pg_locks` through the other route. Tests: `test/graduation-target.test.ts`.- `src/core/persistence/graduation-drain.ts` — engine graduation drain. `graduationBlockers` lists what keeps a brain from copying, each with its structured action: requests this host owns (drained), requests and host bindings owned by another host, recovering topology changes and effects, the writer admin lock, and OAuth clients bound to a missing source (an FK only Postgres enforces; never cleared silently, since unbinding widens access). `drainForGraduation` refuses up front on anything the drain cannot clear, then publishes this host's queued, running and recovering requests with a `requestsOnly` `PersistenceConsumer` bounded by the timeout and always runs its stop barrier before returning; the `graduation_drain_timeout` refusal is built by `graduation-errors.ts`. `freezeSource` stops the resident consumer and sets the PGLite connection to read-only transactions; `withSourceWritable` runs one read-write transaction for custody writes. Tests: `test/graduation-drain.test.ts`.- `src/core/persistence/graduation-copy.ts` — engine graduation copier (in process). `copyTable` reads source rows through the digest's own plan (`digestPlan` with inventory transforms, `rowFilter`, `::text` values, COLLATE "C" keyset batches) and writes them in one target transaction per table that sets `gbrain.graduation_run`, bypasses user triggers (`session_replication_role = replica`, or DISABLE/ENABLE TRIGGER by name in the same transaction, never the `gbrain_graduation_fence` triggers), deletes the target's rows (seed rows included) and inserts byte-sized batches as one `$1::text::jsonb` array cast back per column type. The per-column contract (`columnContract`) refuses missing, retyped, target-only or differently generated columns outside the entry's `columnAllowlist`; generated columns are never inserted. Self-FKs take a second update pass under DISABLE TRIGGER. `copySequences` applies each source sequence's exact position, raised to the target column maximum. `deferIndexes`/`buildDeferredIndexes` drop and rebuild HNSW (through `buildDeferredAnnIndexes`) and GIN indexes, keeping the pending list in the target-owned `graduation.deferred_indexes` config row. Tests: `test/graduation-copy.test.ts`, `test/e2e/graduation-copy.test.ts`.-- `src/core/persistence/root-metadata.ts` — engine-free physical-root ownership metadata names. `isPhysicalRootMetadata` matches exactly `.gbrain-owner.json`, its `.gbrain-owner-<sha256>.json` reservation and its `.gbrain-owner.json.<uuid>.tmp` temp file (`physical-root-record.ts` re-exports it and `PHYSICAL_ROOT_MARKER`). `OWNERSHIP_MARKER_GLOBS` (#5186) are the same three names in gitignore dialect: `physical-root-record.ts`'s `excludeOwnershipMarkers` appends them to `<gitdir>/info/exclude` (resolved with `git rev-parse --git-path`, idempotent, best effort) after every `writePhysicalRootStamp` / `adoptTransferredRootStamp` for the stamped directory, the root and the directory holding the reservation, `PUSH_DENY_GLOBS` denies them together with `.gbrain-bootstrap.lock/**`, the bootstrap `.gitignore` template lists them, and doctor `tracked_ownership_marker` warns when one is already in a source checkout's index. `withoutPhysicalRootMetadata` drops `git status --porcelain` entries whose every path is such metadata, for the doctor `bootstrap_push_health` and stop-hook dirty probes: a stamp-only tree is clean, a real change beside the stamp, a rename onto or away from it and a quoted path still count. Pinned by `test/persistence-root-metadata.test.ts`.+- `src/core/persistence/root-metadata.ts` — engine-free ownership-marker names. `isPhysicalRootMetadata` matches `.gbrain-owner.json`, `.gbrain-owner-<sha256>.json` (reservation) and `.gbrain-owner.json.<uuid>.tmp` (`physical-root-record.ts` re-exports it and `PHYSICAL_ROOT_MARKER`). `OWNERSHIP_MARKER_GLOBS` (#5186) are those names in gitignore dialect: `physical-root-record.ts` `excludeOwnershipMarkers` appends them to `<gitdir>/info/exclude` (`git rev-parse --git-path`, idempotent, best effort) after `writePhysicalRootStamp` / `adoptTransferredRootStamp`, for the stamped directory, the root and the reservation's parent. `PUSH_DENY_GLOBS` denies them with `.gbrain-bootstrap.lock/**`; the bootstrap `.gitignore` template has them; doctor `tracked_ownership_marker` warns when a source checkout's index has one. `withoutPhysicalRootMetadata` drops `git status --porcelain` entries made only of such metadata (doctor `bootstrap_push_health`, stop-hook dirty probes): a stamp-only tree is clean, a real change beside the stamp, a rename across it and a quoted path still count. Test: `test/persistence-root-metadata.test.ts`.- `src/core/persistence/automatic-sync-policy.ts` — `automaticSyncPull(engine, source)`: whether an automatic sync (autopilot freshness `sync` job, per-source fanout cycle) may request a Git pull. It needs a parsed `remote_url`, exactly one boolean `persistence_brain` state that is off, and no worktree binding; a managed brain or claimed source syncs local HEAD with `pull: false`. Missing, duplicated or non-boolean persistence metadata throws `storage_error` (why, read-only `gbrain sources writer status --probe --json` fix) instead of granting a pull, so the caller queues nothing. Clone, immutable and federation flags grant nothing. Pinned by `test/automatic-sync-pull-policy.test.ts`.- `src/core/persistence/native-lock.ts` + `native/locks/` — lazy portable Node-API v3 kernel locks (`flock` / `LockFileEx`) with opaque handles, retained stable lock files, cancellable asynchronous waiting and fail-closed capability errors. Eight vendored prebuilds support script-disabled source installs; pinned Zig recipes and source/artifact hashes live in `scripts/native/`. Actual competing-process, crash-handoff and compiled-executable tests run across eight platform/architecture targets and Bun 1.4.0 / 1.4.2. The compiled smoke waits for child exit before cleanup; `scripts/native/compiled-smoke-cleanup.ts` bounds retries to transient Windows `EBUSY` errors, with persistent and permission failures pinned by `test/scripts/native-compiled-cleanup.test.ts`. Windows-only `windows-ipc.h` supplies opaque Global mutex claims (same-thread recursion refused, abandoned owner handoff) and exact-handle stale AF_UNIX deletion after a verified reparse tag under a retained binding claim. CNG hashing and native casing make pipe identities independent of homes and logon sessions. Build and ownership contract: `native/locks/README.md`. `native/locks/package.json` (private, no entry points, outside `buildInputs` and `prebuilds/`) is a package boundary so plugin hosts that namespace native addons by the nearest package.json do not treat the whole checkout as one package (#6026; guard `test/native-locks-package-boundary.test.ts`). #6305: a failure to create or open the lock file is a `NativeLockUnavailableError` with `stage: 'open'` and `osError` (node:fs code, or the addon's `(OS error N)` as its errno name); `isLockOpenFailure` matches only that typed shape, never message text. `publishMutation` (`coordinator.ts`) and the Postgres single-write group path (`group-publish.ts` `publishGroup`, falling through to `publishMutation`) release such a write as `queued` / `writer_lock_unavailable` instead of the terminal owner-exception path; the consumer holds that root for `INSPECT_OWNER_RETRY_MS` (30 s, `health.ts`) so it doesn't re-prepare every poll; `ownerExceptionFailure` reports `osError` as the owner-only errno; a Git effect counts it as a dependency wait and never parks on it. An EISDIR or EACCES on the brain path itself stays terminal (`persistence-lock-open-failure.test.ts`, both engines).diff --git a/src/core/persistence/physical-root-record.ts b/src/core/persistence/physical-root-record.tsindex 1d1193c303..1ae52d0f72 100644--- a/src/core/persistence/physical-root-record.ts+++ b/src/core/persistence/physical-root-record.ts@@ -1,5 +1,5 @@import { randomUUID } from 'node:crypto';-import { execFileSync } from 'node:child_process';+import { execFileSync } from '../spawn.ts';import { appendFileSync, closeSync, constants, existsSync, fstatSync, fsyncSync, lstatSync, mkdirSync, openSync, readdirSync, readFileSync, realpathSync, renameSync, statSync, unlinkSync, writeFileSync } from 'node:fs';import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';import { OperationError } from '../ops/contract.ts';