Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Agent label: keep startHttpTransport and the key-files entry within their caps, engines in beforeAll
garrytan34b0f8add79b
diff --git a/docs/architecture/key-files/core-services-2.md b/docs/architecture/key-files/core-services-2.mdindex 3ee55dce6a..5222ef8947 100644--- a/docs/architecture/key-files/core-services-2.md+++ b/docs/architecture/key-files/core-services-2.md@@ -30,7 +30,7 @@ Fact and page purge modules (`src/core/facts/purge*.ts`, `deletion-inventory.ts`- `src/core/ops/read-paging.ts` — paging for the two by-slug row reads that would otherwise return everything: `get_chunks` (`chunks.ts`: `from_index` default 0, `limit` default 50, MCP cap 500; the engine's `getChunkPage` returns the chunk_index range [from_index, from_index + limit) plus `total_chunks` and the highest index) and `get_versions` (`admin.ts`: default 20, MCP cap 100). Both keep a bare-array result; `pagingLimit` resolves the limit (trusted local CLI honors any explicit value; a non-positive-integer is `invalid_params`), and `reportChunkPage` / `reportVersionPage` emit `_meta.pagination` (`from_index`, `limit`, `returned`, `total_chunks`, `next_from_index` / `limit`, `truncated`, `clamped_from`), the model-visible `listing_truncated` notice for remote callers when rows remain (its fix is the next call), and one stderr line for a local call with no limit. Tests: `test/get-chunks-paging.test.ts`, `test/get-versions-defaults.test.ts`.- `src/core/ops/admin.ts` — the admin/diagnostics domain module (`get_stats`, `get_health`, `get_brain_identity`, …). `get_health` adds `embedding_column`, the registry-active vector column its coverage counts were measured on (legacy `embedding` when the registry is unreadable), on both engines (`test/get-health-embedding-column.test.ts` + its Postgres arm). `get_versions` reads an explicit column list (`PAGE_VERSION_COLUMNS` in `engine-sql/pages.ts`), so the write attribution columns never reach a plain `read` caller; trusted local callers and `admin` holders (`canReadWriteAttribution`) also get `written_by` and `archived_by` from `attributeVersions`. It filters protected facts/takes from both canonical body and timeline, preserves legacy missing timeline fields, and retains engine-side current/historical page privacy predicates for every snapshot field. By default it returns metadata only (no `compiled_truth`/`timeline`) for the newest 20 versions; `include_body: true` adds the bodies (remote-sanitized), and `limit` (a positive safe integer; any other explicit value is `invalid_params` without echoing it) takes the newest N, capped at 100 for every caller but the trusted local CLI. The handler probes one row past the limit and reports a cut history through `read-paging.ts`. The bound and the projection run in `engine-sql/pages.ts` `getVersions` (one query, scope and privacy predicates in WHERE before `LIMIT`, `ORDER BY pv.snapshot_at DESC, pv.id DESC`, metadata mode selects no body columns, typed `PageVersionRows`), so hidden versions never shift the prefix; trusted and admin callers keep `written_by`/`archived_by` (`test/get-versions-response-bounds.test.ts`). All three aggregate ops confine remote callers via the same ladder reads use: `ctx.remote === false` keeps the trusted brain-wide view; every other caller gets `sourceScopeOpts(ctx)` (federated array > scalar > the unmatchable `__all__` sentinel, which fail-closes to zeros) threaded into `engine.getStats(scope)`/`getHealth(scope)` — aggregates leak by subtraction, so they scope exactly like reads, and read-scope `get_brain_identity` is confined the same way. `get_health`'s `migrations {pending, pending_fresh_install, partial, wedged, declined, skipped_future}` block (`declined` since #6466: versions the brain's config turns off, read through `declinedMigrations(engine)`) stays GLOBAL for scoped callers by decision: it is a host filesystem ledger with no per-source semantics, a wedged host migration is exactly what a remote agent needs to see to explain degraded behavior, and it is composed at the op layer (not in `BrainEngine.getHealth` — growing the engine interface would force both engines to duplicate a file read). `get_health` serves repeat calls from `src/core/health-memo.ts` and returns `computed_at`, the time its counters were read.-- `src/core/ops/attribution.ts` — write attribution reads (Foundations 1, F1b). `resolveWriteAttributions` turns stored (request id, principal kind, principal id) snapshots into `WriteAttributionView`s (`types.ts`), joining `persistence_requests` (operation, `completed_at`, and the caller's self-declared `authority.agentLabel` as `agent_label`, #8664: the HTTP transports read it from `X-Gbrain-Agent-Label` via `parseAgentLabel` in `persistence/attribution.ts`; unverified text that nothing authorizes on), `oauth_clients.client_name`, `access_tokens.name` and the `persistence_local_writers` lane at read time, one query per table; `origin` is `request`, `maintenance` (principal without request) or `unrecorded` (all NULL). `get_write_attribution` (scope `admin`, `localOnly: false`, CLI `gbrain attribution <slug> [--fact <id>] [--take <row>] [--timeline <id>] [--versions]`) returns `{ target, created, last, live_revision, versions? }`; a page's `created` is the origin of its oldest version snapshot. The page lookup uses `readPolicyOpts`, so remote admins stay inside their source grant; remote fact targets are `world` only and take targets follow `readHolders`. Tests: `test/write-attribution-read.test.ts` (PGLite) and `test/e2e/write-attribution-read-parity.test.ts` (Postgres and PgBouncer).+- `src/core/ops/attribution.ts` — write attribution reads (Foundations 1, F1b). `resolveWriteAttributions` turns stored (request id, principal kind, principal id) snapshots into `WriteAttributionView`s (`types.ts`), joining `persistence_requests` (operation, `completed_at`, `agent_label`), `oauth_clients.client_name`, `access_tokens.name` and the `persistence_local_writers` lane at read time, one query each; `origin` is `request`, `maintenance` (principal without request) or `unrecorded` (all NULL). `get_write_attribution` (scope `admin`, `localOnly: false`, CLI `gbrain attribution <slug> [--fact <id>] [--take <row>] [--timeline <id>] [--versions]`) returns `{ target, created, last, live_revision, versions? }`; a page's `created` is the origin of its oldest version snapshot. The page lookup uses `readPolicyOpts`, so remote admins stay inside their source grant; remote fact targets are `world` only and take targets follow `readHolders`. Tests: `test/write-attribution-read.test.ts` (PGLite) and `test/e2e/write-attribution-read-parity.test.ts` (Postgres and PgBouncer).- `src/core/ops/trust.ts` — `confirm_memory` (#5575 A4, CEO-9, DX-20): the one MCP-visible owner action. Raises a fact, take or page to `user_confirmed` through `trust/owner-actions.ts` after `requireOwnerConfirmation` (a `memory_confirm` connection, or the local CLI's typed-token TTY prompt); agent tokens get `insufficient_scope` with a `tell_user_to_run` fix naming `gbrain trust confirm <ref>`. Trust proposals and holds are not reachable here; the other owner actions are CLI or resident-owner administration only (`trust/owner-ipc.ts`).- `src/core/health-memo.ts` — in-process memo for the `get_health` op only (O-ENG-13). An entry is reused when engine object, scope key (`all`, `scalar:<id>`, `set:<sorted unique ids>`, `empty` for an empty or no-sources grant; derived from the exact scope handed to `engine.getHealth`, so no scope reads another's entry), config generation (hash of the orphan exclusions, embedding column registry keys and schema pack setting), page clock (`page_generation_clock_seq.last_value` plus the `persistence_brain` id) and TTL all match. TTL: `GBRAIN_HEALTH_CACHE_TTL_MS`, else config `health.cache_ttl_ms`, else 30000 ms; 0 disables. The TTL bounds staleness from writes that do not touch `pages` (links, timeline rows, chunks). A failed clock/config read computes uncached. `engine.getHealth` stays uncached, so doctor, remediation, maintain, embedding migration and repair verification always read fresh numbers; `gbrain repair --apply` and `gbrain doctor --remediate` call `clearHealthMemo`. Pinned by `test/health-memo.test.ts`.diff --git a/src/mcp/http-transport.ts b/src/mcp/http-transport.tsindex 57b029dff0..de76448dfb 100644--- a/src/mcp/http-transport.ts+++ b/src/mcp/http-transport.ts@@ -538,7 +538,6 @@ export async function startHttpTransport(opts: HttpTransportOptions) {const toolName: string = params?.name ?? 'unknown';const args: Record<string, unknown> = params?.arguments ?? {};const op = operationsByName[toolName];- const agentLabel = parseAgentLabel(req.headers.get(AGENT_LABEL_HEADER));// #5575: cliOnly ops reach the dispatcher's trusted_local_only refusal (the host command), never a grant-widening scope fix.if (op && !op.localOnly && !op.cliOnly && !operationScopesAllowed(auth.auth!.scopes, op)) {logRequest(auth.tokenName!, `tools/call:${toolName}`, 'denied_after_list', Date.now() - startedMs);@@ -569,11 +568,10 @@ export async function startHttpTransport(opts: HttpTransportOptions) {// backstop keys off this marker.transport: 'http', inboundFrameBytes: bodyCap,takesHoldersAllowList: auth.takesHoldersAllowList,- sourceId: auth.sourceId,+ sourceId: auth.sourceId, agentLabel: parseAgentLabel(req.headers.get(AGENT_LABEL_HEADER)),...(localFederated ? { localFederatedSourceIds: localFederated } : {}), onBehalfOf: { header: req.headers.get(ON_BEHALF_OF_HEADER) ?? undefined, requestMeta: params?._meta },actor: { header: req.headers.get(ACTOR_HEADER) ?? undefined, audience: req.headers.get(QM_AUDIENCE_HEADER) ?? undefined }, // #1336: thread the token's federated_read grant so read ops scope// to the operator-granted sources via sourceScopeOpts.- ...(agentLabel ? { agentLabel } : {}),auth: auth.auth,// MEMORY_VERBS v1 [c1/c2]: fail-closed surface enforcement here too....(surfaceAllowedOps ? { allowedOps: surfaceAllowedOps } : {}),diff --git a/test/write-agent-label.test.ts b/test/write-agent-label.test.tsindex 9e38a86032..76729673ab 100644--- a/test/write-agent-label.test.ts+++ b/test/write-agent-label.test.ts@@ -38,12 +38,6 @@ import { AGENT_LABEL_HEADER, parseAgentLabel } from '../src/core/persistence/attconst CONFIG = { engine: 'pglite', embedding_disabled: true } as const;const content = (title: string) => '---\ntype: note\ntitle: ' + title + '\n---\n\n# ' + title + '\n\nA synthetic page.\n';-async function freshEngine(): Promise<BrainEngine> {- const db = new PGLiteEngine();- await db.connect({});- await db.initSchema();- return db;-}async function addToken(engine: BrainEngine, name: string, token: string, scopes: string): Promise<void> {await engine.executeRaw('INSERT INTO access_tokens(name,token_hash,scopes) VALUES($1,$2,$3::text[])', [name, hashToken(token), scopes]);}@@ -85,7 +79,10 @@ describe('OAuth serve --http mount, managed worktree brain', () => {let url: string;beforeAll(async () => {- engine = await freshEngine();+ const db = new PGLiteEngine();+ await db.connect({});+ await db.initSchema();+ engine = db;root = mkdtempSync(join(tmpdir(), 'gbrain-agent-label-'));await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');await engine.executeRaw('UPDATE sources SET local_path=$1 WHERE id=\'default\'', [root]);@@ -150,7 +147,10 @@ describe('legacy bearer transport, repo-less brain', () => {let url: string;beforeAll(async () => {- engine = await freshEngine();+ const db = new PGLiteEngine();+ await db.connect({});+ await db.initSchema();+ engine = db;const [source] = await engine.executeRaw<{ local_path: string | null }>("SELECT local_path FROM sources WHERE id='default'");expect(source?.local_path ?? null).toBeNull();await addToken(engine, 'Synthetic legacy token', TOKEN, '{read,write}');