Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
docs: keep the key-files entry under its size cap
garrytanbadabafe2400
diff --git a/docs/architecture/key-files/google-and-loops-continued.md b/docs/architecture/key-files/google-and-loops-continued.mdindex 0d18537d10..2f1fb66772 100644--- a/docs/architecture/key-files/google-and-loops-continued.md+++ b/docs/architecture/key-files/google-and-loops-continued.md@@ -6,7 +6,7 @@- `src/core/serve-service.ts` — the persistent-service half of `mcp expose`, everything under `gbrainPath('serve')` (`serveDir`, `adminTokenPath`, `wrapperPath`, `receiptPath`, `serveLogPath`, `serveErrPath`) so `GBRAIN_HOME` is honored. `SERVE_LAUNCHD_LABEL = 'com.gbrain.serve'`, `SERVE_SYSTEMD_UNIT = 'gbrain-serve.service'`, `detectServiceTarget(signals)` → `'macos' | 'linux-systemd' | 'none'` (a working user bus is required for systemd; cloud sandboxes and ephemeral containers fall to `none`). `renderServeWrapper` produces the 0755 launcher that sources the shell profiles and `~/.gbrain/env`, prepends the Bun dir to `PATH`, reads the admin token from its file at run time into `GBRAIN_ADMIN_BOOTSTRAP_TOKEN` (the token is never written into the wrapper, plist or unit), resolves `gbrain` the way autopilot's wrapper does (baked installer path, `type -P gbrain` fallback) and `exec`s `serve --http --port N --public-url URL [--surface] [--enable-dcr]`. `resolveServeGbrainCommand({ which, execPath, argv1, metaUrl, fileExists })` picks the baked program: a `gbrain` on PATH wins; a COMPILED binary — `import.meta.url` (or the injected `metaUrl`) under `/$bunfs/`, or an `execPath` that is not the bun runtime while `argv[1]` is absent/virtual — is `[execPath]` whatever its basename (release assets are renamed); otherwise the `[bun, <cli.ts>]` dev form only when that `cli.ts` exists on disk, else `[execPath]` rather than a path that cannot run; `renderServeLaunchdPlist` (RunAtLoad, KeepAlive, ThrottleInterval 30, logs to `serve.log` / `serve.err`, local `escapeXml`) and `renderServeSystemdUnit` (After=network-online.target, Restart=always, RestartSec=10, start-limit window; systemd specifiers escaped — `%` → `%%` in `ExecStart` and both `append:` log paths, `$` → `$$` in `ExecStart`). `ensureAdminToken` (0700 dir, 0600 file created with `wx` semantics, 64 hex chars; reuse a file matching the exported `ADMIN_TOKEN_SHAPE` = `^[A-Za-z0-9_-]{32,}$` — the same regex `serve-http.ts`'s `resolveBootstrapToken` accepts, so the file and the env var can never disagree on what a valid token is — unlink and regenerate otherwise), `installServeService` (launchd: domain-explicit `launchctl bootout gui/<uid> <plist>` — failure ignored — then `launchctl bootstrap gui/<uid> <plist>`, both through the one `launchctl(run, uid, plist, { modern, legacy })` helper whose legacy `launchctl unload` / `load` fallback is used ONLY when the modern verb exits non-zero with stderr matching `/Unknown command|unrecognized|not found/i`, never on a genuine failure or a killed call, and which reports the `verb` whose result it returns; a bootstrap that fails with stderr matching `LAUNCHCTL_SETTLE_RE` (`Input/output error`, `already in progress`, `\b5\b`, `\b37\b` — launchd still unloading the previous job) is retried up to `LAUNCHCTL_SETTLE_RETRIES` (5) times, `LAUNCHCTL_SETTLE_MS` (1s) apart through the injectable `sleep` param (default `setTimeout`; `mcp-expose.ts` passes `d.sleep`), a success after retries is a note and an exhausted retry appends "(after N settle retries)" to `error`; systemd: `daemon-reload` → `enable` → `restart` so a regenerated wrapper takes effect; `loginctl enable-linger` best effort) / `uninstallServeService` (launchd: the same `bootout gui/<uid>` with the same fallback; a bootout that exits non-zero — or is killed — with stderr NOT matching `LAUNCHCTL_NOT_LOADED_RE` (`No such process|not loaded|Could not find|not find service`) pushes `launchctl <verb> failed: <describeFailure>` into `notes`, and the exported `launchdBootoutFailed(result)` recognizes that note so `mcp-expose.ts` can say the job may still be loaded) / `serveServiceState` (`launchctl print gui/<uid>/<label>` / `systemctl --user is-active`); all three take `uid?: number` defaulting to `process.getuid?.() ?? 501`, threaded from `mcp-expose.ts`. Every supervisor subprocess carries a timeout — 60s for `launchctl bootstrap/bootout` (and the legacy `load/unload`) and `systemctl --user enable/restart/disable`, 15s for `launchctl print`, `daemon-reload`, `is-active` and `loginctl enable-linger` — and a `status: null` (killed) result counts as a failure (`error` / note) or `unknown` state; a failed call is described by `describeFailure` (its stderr, else stdout, else `exit <status>`). `readExposeReceipt` / `writeExposeReceipt` (`expose.json`, 0600, version 1, no secrets): the reader is a structural shape guard, not just `version`/`port`/`public_url` — it also requires `mode` in `tailnet|funnel`, a `service` object with a string `wrapper_path`, a `target` in `macos|linux-systemd|none`, a string `state` and string-or-null `plist_path` / `unit_path`, a `tailscale` object whose `binary` / `dns_name` are string-or-null, and string `mcp_url` / `admin_url` / `admin_token_file`; anything less is null (absent), so `--status` / `--remove` never dereference a half-written receipt. The token, receipt, wrapper, plist and unit writers refuse (clear error) when the target path is a symlink (`lstatSync`) before any supervisor call runs. Uses `shellQuote` from `src/core/mcp-registration.ts`; every filesystem/exec effect is behind injectable deps.- `src/core/harness/verify.ts` — Randomized server-side memory verification with revision-conditional cleanup and retained mutation UUIDs, with separate transport, identity, authority, read, write/readback, delegation and cleanup verdicts. Lost mutation responses are reconciled before retry; server success never certifies native-harness activation or cross-conversation behavior.-- `src/core/persistence/memory-mutations.ts` + `memory-prepare.ts` — managed `remember`, `forget`, and `forget_fact`: durable same-ID replay precedes entity/TTL/provider work; semantic append preparation preserves hidden canonical fences and revalidates dedup under page guards. Embedding preparation records the stored model/dimension generation and publication compares it under transaction row locks, preserving unchanged runtime overrides while refusing intervening migrations; fact vectors retain their actual provider model. Withdrawal admits and completes in one source-exclusive database transaction, independent of filesystem ownership, with durable mirror/projection work; the call then rebuilds the withdrawn pages' text projections before acknowledging, because a CLI process has no resident projection worker (a failed rebuild stays queued). `src/core/facts/single-prepare.ts` isolates provider preparation from the SQL-only semantic decision and propagates cooperative provider abort without degrading it into success. Preparation checkpoints prevent a late aborted result from reaching publication. Tests: `test/persistence-memory-mutations.test.ts` runs identical races on PGLite and PostgreSQL; `test/withdrawal-followup-writes.test.ts` covers writes after a forget whose effects stay queued. #5836: an omitted `entity` is inferred before admission (`inferRememberTarget`), and the inferred slug is used only when `planRememberTarget`'s checks pass as predicates (plus withdrawal, fence parse, no owner claim); otherwise the save is unattributed with `warnings` (`NO_ENTITY`/`ENTITY_LINK_FAILED`) + `hint`. The `entity_inferred` intent marker makes preparation dedup exact text only (never supersede) and notes the context; `test/remember-entity-inference.test.ts`. `remember.replaces` (caller-directed replacement): `decideReplacement` (`facts/single-prepare.ts`) replaces the cosine decision when the intent names a target; it is checked at submission (fail fast) and again in `validate` with the target row locked `FOR UPDATE`, so two replacements of one fact serialize and the second sees `target_superseded`. Refusals are `invalid_params` with code prefixes (`target_withdrawn`, `target_superseded` naming the chain head, `target_expired`, `replaces_entity_mismatch`, `replaces_cross_page`, `replaces_duplicate`); remote callers get `not_found` for private targets; equal text is a `duplicate` no-op. Every `superseded` outcome carries `superseded_fact_id` (plus `replaced_by_caller` for `replaces`). `forget` responses gain `similar_active` (`facts/similar-active.ts`) after commit and on replay, and `semantic_review: false` keeps the claim out of overnight review. Pinned by `test/remember-replaces.test.ts`. remember's write intent carries the transport-resolved `ctx.sessionId` (MCP `_meta.session_id`, clamped to 256 characters), and preparation stores it as the fact's `source_session`, so `recall({session_id})` finds remembered facts; identity only, never an authorization input (`test/remember-session.test.ts`). #7248: an explicit `entity` without a folder resolves through `resolveStrictEntityReference` (one readable entity page by exact slug, unique basename, alias or same name); a miss with near pages (`entityReferenceCandidates` in `entities/resolve.ts`) is refused `invalid_params` with `reason: entity_ambiguous | entity_unverified | entity_not_entity | entity_no_page` and the candidates, and a name nothing resembles keeps its slugified key. A pending or refused reply's `write_request.target` (`slug`, `entity_slug`) names where the fact goes, and `pendingWriteHint` repeats it (`test/remember-entity-target-7248.test.ts`).+- `src/core/persistence/memory-mutations.ts` + `memory-prepare.ts` — managed `remember`, `forget`, and `forget_fact`: durable same-ID replay precedes entity/TTL/provider work; semantic append preparation preserves hidden canonical fences and revalidates dedup under page guards. Embedding preparation records the stored model/dimension generation and publication compares it under transaction row locks, preserving unchanged runtime overrides while refusing intervening migrations; fact vectors retain their actual provider model. Withdrawal admits and completes in one source-exclusive database transaction, independent of filesystem ownership, with durable mirror/projection work; the call then rebuilds the withdrawn pages' text projections before acknowledging, because a CLI process has no resident projection worker (a failed rebuild stays queued). `src/core/facts/single-prepare.ts` isolates provider preparation from the SQL-only semantic decision and propagates cooperative provider abort without degrading it into success. Preparation checkpoints prevent a late aborted result from reaching publication. Tests: `test/persistence-memory-mutations.test.ts` runs identical races on PGLite and PostgreSQL; `test/withdrawal-followup-writes.test.ts` covers writes after a forget whose effects stay queued. #5836: an omitted `entity` is inferred before admission (`inferRememberTarget`), and the inferred slug is used only when `planRememberTarget`'s checks pass as predicates (plus withdrawal, fence parse, no owner claim); otherwise the save is unattributed with `warnings` (`NO_ENTITY`/`ENTITY_LINK_FAILED`) + `hint`. The `entity_inferred` intent marker makes preparation dedup exact text only (never supersede) and notes the context; `test/remember-entity-inference.test.ts`. `remember.replaces` (caller-directed replacement): `decideReplacement` (`facts/single-prepare.ts`) replaces the cosine decision when the intent names a target; it is checked at submission (fail fast) and again in `validate` with the target row locked `FOR UPDATE`, so two replacements of one fact serialize and the second sees `target_superseded`. Refusals are `invalid_params` with code prefixes (`target_withdrawn`, `target_superseded` naming the chain head, `target_expired`, `replaces_entity_mismatch`, `replaces_cross_page`, `replaces_duplicate`); remote callers get `not_found` for private targets; equal text is a `duplicate` no-op. Every `superseded` outcome carries `superseded_fact_id` (plus `replaced_by_caller` for `replaces`). `forget` responses gain `similar_active` (`facts/similar-active.ts`) after commit and on replay, and `semantic_review: false` keeps the claim out of overnight review. Pinned by `test/remember-replaces.test.ts`. remember's write intent carries the transport-resolved `ctx.sessionId` (MCP `_meta.session_id`, clamped to 256 characters), and preparation stores it as the fact's `source_session`, so `recall({session_id})` finds remembered facts; identity only, never an authorization input (`test/remember-session.test.ts`). #7248: a folder-less `entity` must resolve strictly or is refused with candidates; pending replies carry `write_request.target` (`test/remember-entity-target-7248.test.ts`).- `src/core/page-state/import-guard.ts` — imported canonical bytes publish only after source/page identity and knowledge-revision CAS, including unchanged-file and legacy hash-repair paths. Prepared same-hash imports compare full canonical metadata and additive tags, since captured timestamps are excluded from content hashes. Tests: `import-revision-concurrency.test.ts`.- `src/core/persistence/{maintenance,root-registry,filesystem-guard,writer-guard-schema}.ts` — fail-closed legacy writer coverage: durable private refusal records and shared refusal-only root markers work before PGLite connect, resolve symlink ancestors, and retain stale roots conservatively. An unchanged per-tick refresh writes nothing: the registry directory and records are chmodded only when their mode differs and the directory is fsynced only when a record changed (`root-registry-idle-chmod-5297.test.ts`). The selected PGLite path is registered at connect/init and source claim refresh, so managed reinit refuses even offline; unmanaged backup acquires the stable sibling native lock through rename. SQL guards include free-text aliases and canonical source sync checkpoints; an update that changes only embedding, telemetry or write-attribution columns of facts/takes is a physical projection and passes without the coordinator. `docs/architecture/canonical-writers.tsv` is the finite writer census; `canonical-writer-inventory.test.ts` rejects unreviewed additions, and `persistence-writer-fences.test.ts`/`pglite-maintenance-fence.test.ts` exercise real engines, competing processes and separate homes.