Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(mcp verify): the memory-writer fixture names its entity with a folder (#7699)

garrytan323cfee4af43
diff --git a/docs/architecture/key-files/google-and-loops-continued.md b/docs/architecture/key-files/google-and-loops-continued.md
index b7dfdb7b04..655fe4921e 100644
--- a/docs/architecture/key-files/google-and-loops-continued.md
+++ b/docs/architecture/key-files/google-and-loops-continued.md
@@ -4,7 +4,7 @@
- `src/core/tailscale.ts` — Tailscale helpers with an injected exec seam (`CommandRunner = (argv, { inherit?, timeoutMs?, stdoutToStderr? }) => Promise<CommandResult>` where `CommandResult = { status, stdout, stderr }` and `status: null` means killed at the timeout or never spawned; `defaultCommandRunner` on `Bun.spawn` — at `timeoutMs` it sends SIGTERM and, when the child has still not exited `SIGKILL_GRACE_MS` (3s) later, SIGKILL, so a child that ignores SIGTERM never hangs the caller; both timers are cleared in a `finally` — also the runner `serve-service.ts` types against; `stdoutToStderr` sends an inherited child's stdout to fd 2 so `--json` stdout stays pure): `parseTailscaleStatus` (`BackendState` — `Running`, `NeedsLogin`, `NeedsMachineAuth`, `NoState`, `Stopped`; `Self.DNSName`, `CertDomains`, and `funnelCapable`: true/false from `Self.CapMap` keys or `Self.Capabilities` entries carrying any Funnel form — `funnel` (`NodeAttrFunnel`), `https://tailscale.com/cap/funnel-ports` with or without its `?ports=` query, or the legacy `https://tailscale.com/cap/funnel` — null when both are absent), `publicUrlFromDnsName` (strip trailing dot, lowercase, `https://`), `TAILSCALE_BINARY_CANDIDATES` + `findTailscaleBinary` (`Bun.which`, then the macOS app bundle, Homebrew and `/usr/bin` paths; the candidate list doubles as `mcp-expose.ts`'s allowlist for a binary path recorded in a receipt) + `isSystemTailscaleBinary(binary, realpath = realpathSync)` (true when the path is a candidate literally or resolves to one through symlinks; an unresolvable path is false — `mcp-expose.ts` puts `sudo` in front of the binary only when this holds), `tailscaleInstallPlan(platform, hasBrew)`, `tailscaleLoginArgv(platform, user, binary)` → `{ setOperator?, up }` (Linux: `sudo <bin> set --operator=<user>` then a flagless `sudo <bin> up` — a flagged `up` trips the CLI's settings-revert check on a node with non-default prefs; macOS: `<bin> up`), `tailscaleManualLoginCommand(binary = 'tailscale')` (the Linux login the operator runs themselves when gbrain refuses to `sudo` a non-system binary — `sudo <bin> set --operator=$USER && sudo <bin> up` with the DISCOVERED path shell-quoted through `shellQuote`, because a binary outside sudo's `secure_path` is exactly that case) and `TAILSCALE_ACCEPT_DNS_COMMAND` (`tailscale set --accept-dns=true`, the MagicDNS-off remedy) — both keep their tailscale flag literals in this module so the flag-registry scan of `mcp-expose.ts` never sees them, `tailscaleServeArgv(port, { funnel })` (`serve --bg` / `funnel --bg`) + `tailscaleServeOffArgv({ funnel })` (`serve|funnel --https=443 --set-path=/ off` — `--set-path=/` scopes `off` to OUR `/` mount; without it the CLI removes every mount under `:443` and, when more than one exists, prompts interactively — with stdin ignored the prompt reads EOF and the command exits 0 having removed nothing; never `serve reset`), `parseServeStatusStrict` (the only serve-status parser, fail-closed: background `Web` handlers, `Foreground[<session>].Web` handlers marked `foreground: true`, and `TCP['443'].TCPForward` as a non-proxy root handler; an empty document / `{}` / `null` is the legitimately empty view, but non-JSON, an array or a scalar returns `null` so `mcp-expose.ts`'s `readServeView` can tell "could not read" from "nothing configured") + `findProxiedHandler(view, port)`, `classifyTailscaleError(stderr)` (Funnel rule before the HTTPS rule; the HTTPS rule matches certificate vocabulary, never a bare `https://` URL: `funnel_not_enabled` | `https_not_enabled` | `needs_operator` | `needs_login` | `daemon_not_running` | `unknown`), and the admin/KB URL constants (`TAILSCALE_ADMIN_DNS_URL`, `TAILSCALE_ADMIN_ACL_URL`, `TAILSCALE_FUNNEL_KB_URL` = `https://tailscale.com/kb/1223/funnel`, `TAILSCALE_DOWNLOAD_URL`). The parsers and argv builders are pure; the injectable `which` / `fileExists` / runner defaults touch `existsSync`, `process.env.PATH` and `process.platform`, and tests replace them. Note `tailscale status --json` exits 0 in every `BackendState` (only the human-readable form exits 1 when logged out), and `serve`/`funnel` wait interactively rather than failing when HTTPS certificates or the Funnel attribute are off — which is why `mcp-expose.ts` pre-checks before starting them.
- `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/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. The memory-writer fact names its entity with a folder (`gbrain-verification/<fixture>`), so folder-less entity resolution never refuses it beside a near-named page (#7699, `test/harness-verify-entity-fixture-7699.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`.
diff --git a/src/core/harness/verify.ts b/src/core/harness/verify.ts
index 071efcb77b..dc0534c573 100644
--- a/src/core/harness/verify.ts
+++ b/src/core/harness/verify.ts
@@ -48,6 +48,7 @@ export async function verifyHarnessConnection(c: HarnessCredentials, options: Ve
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), timeout);
const fixture = `gbrain-verification-${randomBytes(10).toString('hex')}`;
+ const fixtureEntity = `gbrain-verification/${fixture}`;
let cleanupSlug: string | undefined;
let cleanupRevision: string | undefined;
const writeRequestId = randomUUID(); const cleanupRequestId = randomUUID();
@@ -91,7 +92,7 @@ export async function verifyHarnessConnection(c: HarnessCredentials, options: Ve
mutationAttempted = true;
const saved = await active.call(pageMode ? 'put_page' : 'remember', pageMode
? { request_id: writeRequestId, slug: cleanupSlug, title: 'Connection check', content: `# Connection check\n\n${fixture}\n` }
- : { request_id: writeRequestId, fact: fixture, entity: fixture, provenance: 'GBrain randomized connection verification', visibility: 'world' });
+ : { request_id: writeRequestId, fact: fixture, entity: fixtureEntity, provenance: 'GBrain randomized connection verification', visibility: 'world' });
if (saved.state !== undefined && saved.state !== 'committed') throw new Error('write_not_committed');
if (!pageMode) factId = String(saved.id ?? '');
mutationConfirmed = true;
@@ -99,7 +100,7 @@ export async function verifyHarnessConnection(c: HarnessCredentials, options: Ve
// A lost response is reconciled by reading the unique fixture, never by
// repeating a mutation. Both the write and its readback are observed.
const readBack = await stage('write_readback', async () => {
- const found = await active.call(pageMode ? 'get_page' : 'recall', pageMode ? { slug: cleanupSlug, include_content: true } : { entity: fixture, grep: fixture });
+ const found = await active.call(pageMode ? 'get_page' : 'recall', pageMode ? { slug: cleanupSlug, include_content: true } : { entity: fixtureEntity, grep: fixture });
if (!JSON.stringify(found).includes(fixture)) throw new Error('fixture_missing');
mutationConfirmed = true;
if (pageMode && typeof found.revision === 'string') cleanupRevision = found.revision;
@@ -174,12 +175,12 @@ export async function verifyHarnessConnection(c: HarnessCredentials, options: Ve
return;
}
if (!factId) {
- const found = await peer!.call('recall', { entity: fixture, grep: fixture });
+ const found = await peer!.call('recall', { entity: fixtureEntity, grep: fixture });
factId = String(found.facts?.find((f: any) => JSON.stringify(f).includes(fixture))?.fact_id ?? '');
if (factId) mutationConfirmed = true;
}
if (factId) await peer!.call('forget', { id: factId, reason: 'connection verification cleanup', request_id: cleanupRequestId });
- const after = await peer!.call('recall', { entity: fixture, grep: fixture });
+ const after = await peer!.call('recall', { entity: fixtureEntity, grep: fixture });
if (JSON.stringify(after.facts ?? []).includes(fixture)) throw new Error('cleanup_incomplete');
}, signal);
// A timed-out/lost write may still commit after an empty read. Absence
diff --git a/test/harness-verify-entity-fixture-7699.test.ts b/test/harness-verify-entity-fixture-7699.test.ts
new file mode 100644
index 0000000000..055f75b3a9
--- /dev/null
+++ b/test/harness-verify-entity-fixture-7699.test.ts
@@ -0,0 +1,73 @@
+/**
+ * #7699: gbrain mcp verify's memory-writer fixture saves, reads back and
+ * withdraws its fact on a brain that already holds a similarly named entity
+ * page (same leading token, close title), and never touches that page.
+ * The peer dispatches the real recall/remember/forget handlers as a remote
+ * caller on PGLite. Synthetic names only.
+ */
+import { afterAll, beforeAll, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import type { OperationContext } from '../src/core/ops/contract.ts';
+import { operationsByName } from '../src/core/operations.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { withCoordinatedWrite } from '../src/core/persistence/context.ts';
+import { registerLocalWriter } from '../src/core/persistence/identity.ts';
+import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';
+import { verifyHarnessConnection, type VerificationPeer } from '../src/core/harness/verify.ts';
+import type { HarnessCredentials } from '../src/core/harness/credentials.ts';
+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';
+import { LEGACY_EMBEDDING_CONFIG } from './helpers/legacy-embedding-config.ts';
+
+let engine: PGLiteEngine;
+const sourceId = 'source-a';
+const NEAR = 'concepts/gbrain-verification';
+const credentials: HarnessCredentials = { version: 1, client_id: 'gbrain_cl_verify_7699', mcp_url: 'https://brain.example.com/mcp',
+ issuer_url: 'https://brain.example.com', access_token: 'fixture-token', source_id: sourceId, profile: 'memory-writer' };
+const remoteCtx = { remote: true, sourceId, config: { engine: 'pglite' }, dryRun: false,
+ auth: { clientId: credentials.client_id, scopes: ['read', 'write'], sourceId }, logger: { info() {}, warn() {}, error() {} } };
+
+const nearPage = () => engine.executeRaw<{ compiled_truth: string; updated_at: string }>(
+ 'SELECT compiled_truth, updated_at::text FROM pages WHERE source_id=$1 AND slug=$2', [sourceId, NEAR]);
+
+beforeAll(async () => {
+ configureGateway({ ...LEGACY_EMBEDDING_CONFIG, env: {} });
+ engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema();
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1)', [sourceId]);
+ await registerLocalWriter(engine, 'cli'); await registerLocalWriter(engine, 'stdio');
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ await engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], () =>
+ tx.putPage(NEAR, { type: 'concept', title: 'GBrain verification', compiled_truth: '# GBrain verification\n\nHow connections are checked.', frontmatter: {} }, { sourceId }),
+ TEST_WRITE_ATTRIBUTION));
+}, 60_000);
+
+afterAll(async () => {
+ await disposePersistenceConsumer(engine);
+ await engine.disconnect();
+ resetGateway();
+});
+
+test('the memory-writer stages pass beside a near-named entity page, which stays untouched', async () => {
+ const before = await nearPage();
+ const calls: Array<{ name: string; error?: string }> = [];
+ const peer: VerificationPeer = {
+ connect: async () => {}, close: async () => {},
+ readCapabilities: async () => ({ transport: 'oauth', client_id: credentials.client_id, scopes: ['read', 'write'], source_id: sourceId }),
+ call: async (name, params) => {
+ try { return await operationsByName[name]!.handler({ ...remoteCtx, engine } as unknown as OperationContext, params); }
+ catch (e) { calls.push({ name, error: (e as Error).message }); throw e; }
+ },
+ };
+ const report = await verifyHarnessConnection(credentials, { peer, timeoutMs: 30_000 });
+ expect(calls).toEqual([]);
+ expect(report.stages.filter(s => s.status === 'failed')).toEqual([]);
+ expect(report.stages.find(s => s.name === 'write')?.status).toBe('passed');
+ expect(report.stages.find(s => s.name === 'write_readback')?.status).toBe('passed');
+ expect(report.stages.find(s => s.name === 'cleanup')?.status).toBe('passed');
+ expect(await nearPage()).toEqual(before);
+ const active = await engine.executeRaw('SELECT id FROM facts WHERE source_id=$1 AND fact=$2 AND expired_at IS NULL', [sourceId, report.fixture]);
+ expect(active).toEqual([]);
+ expect(await engine.executeRaw('SELECT entity_slug FROM facts WHERE source_id=$1 AND fact=$2', [sourceId, report.fixture]))
+ .toEqual([{ entity_slug: `gbrain-verification/${report.fixture}` }]);
+ expect(await engine.executeRaw('SELECT slug, deleted_at FROM pages WHERE source_id=$1 AND slug LIKE $2', [sourceId, 'gbrain-verification/%'])).toEqual([]);
+}, 60_000);