Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix: pre-landing review fixes
garrytan0bb4b69b0ac8
diff --git a/docs/guides/rooms.md b/docs/guides/rooms.mdindex b649f378ed..9c6ae16eed 100644--- a/docs/guides/rooms.md+++ b/docs/guides/rooms.md@@ -50,8 +50,10 @@ nothing else.| `{readable: false, reason}` | someone in the room could not read it | use it to do the work; keep it out of the reply unless the ask needs it, and offer it in a direct message || `{readable: "unknown", reason}` | gbrain could not tell | treat it like `false` |-`readable: true` means exactly what an `on_behalf_of` read for the same room-would return. The reasons for `false`, checked in this order:+Every item marked `readable: true` is one an `on_behalf_of` read for the same+room would return. Marks never count the calling credential's private-pages+grant: that grant is the caller's, not the room's, so a `visibility: private`+page is marked `private_label` for any room. The reasons for `false`, checked in this order:| Reason | Why the room could not read it ||---|---|@@ -112,13 +114,16 @@ stamp (`_meta.degraded.reasons` and the `[gbrain degraded: …]` block) names| `unknown_principal` | the room names a disabled or unknown member or group | fix the name, or add the member || `unbound` | the connection is bound to no member | bind the credential to a member || `mark_failed`, `deadline` | judging failed or took more than 3 seconds | retry; nothing was changed |-| `op_not_covered` | the tool does not mark its results | none needed |+| `op_not_covered` | the tool does not mark its results | none needed; this one adds no degraded stamp, so a write is never read as partial |+| `response_cap` | the marked answer would not fit the connection's size cap | ask for less (a window, a page of rows) to get marks |Some items can be unknown inside a complete answer too: `not_found` (the itemcould not be looked up again), `not_identified` (it carries no page or factid) and `over_limit` (only the first 2,000 references are judged). When themarked answer would exceed the response size cap, the unmarked answer is sent-with `_meta.room.complete: false`; treat every item as above the room.+with the `room_hints_unavailable` notice (reason `response_cap`) and+`_meta.room.complete: false`, each dropped first if even that does not fit;+treat every item as above the room.## Keep raw results out of the room's transcriptdiff --git a/src/core/access/room.ts b/src/core/access/room.tsindex 4eabaf6d20..98f22226bb 100644--- a/src/core/access/room.ts+++ b/src/core/access/room.ts@@ -35,7 +35,7 @@ export const ROOM_MAX_REFS = 2_000;/** Why the room could not read an item. */export type RoomReason = 'readers' | 'folder_rule' | 'labelled_only' | 'private_label' | 'derived';/** Why an item, or the whole answer, could not be judged. */-export type RoomUnknownReason = 'invalid' | 'not_permitted' | 'unknown_principal' | 'unbound' | 'mark_failed' | 'deadline'+export type RoomUnknownReason = 'invalid' | 'not_permitted' | 'unknown_principal' | 'unbound' | 'mark_failed' | 'deadline' | 'response_cap'| 'op_not_covered' | 'not_found' | 'not_identified' | 'over_limit';export type RoomAccess = { readable: true } | { readable: false; reason: RoomReason } | { readable: 'unknown'; reason: RoomUnknownReason };@@ -123,6 +123,8 @@ function walk(v: unknown, src: string, out: Slot[], depth = 0): void {if (depth > 8) return;if (Array.isArray(v)) { for (const x of v) walk(x, src, out, depth + 1); return; }if (!isObj(v)) return;+ // A nested row without its own source_id belongs to the nearest enclosing object that names one (entity cards span sources).+ src = str(v.source_id) ?? src;if (typeof v.slug === 'string') out.push(pageSlot(v, src)!);for (const [k, x] of Object.entries(v)) {if (SKIP_KEYS.has(k)) continue;@@ -199,7 +201,6 @@ export interface RoomCaller {auth?: AuthInfo;transport?: string;stdioMember?: string;- privateSources?: readonly string[];/** An attested actor call (x-qm-actor): never marked. */attested?: boolean;}@@ -219,6 +220,8 @@ export interface RoomMeta {}export interface RoomOutcome {+ /** The notices the degraded stamp may read: a tool that marks nothing (op_not_covered) is not a partial answer. */+ stamped: Notice[];/** A detached copy of the result with room_access on every item (the original object is never written). */result: unknown;meta: RoomMeta;@@ -244,16 +247,18 @@ async function roomAccessFor(engine: BrainEngine, caller: RoomCaller, principalsif (code === 'on_behalf_of_unknown_member') throw new RoomUnavailable('unknown_principal', detail);throw new RoomUnavailable('mark_failed');}- return audienceCallerAccess(engine, caller.auth, caller.privateSources, caller.transport, principals, identities, caller.stdioMember, true);+ // A room is judged without the calling credential's private-pages grant: that grant is the caller's, never the room's.+ return audienceCallerAccess(engine, caller.auth, [], caller.transport, principals, identities, caller.stdioMember, true);}let deadlineForTests: { ms: number; delay: () => Promise<void> } | null = null;/** Test seam: a shorter deadline and a slow judgment, so the deadline path runs through dispatch. */export function __setRoomDeadlineForTests(v: { ms: number; delay: () => Promise<void> } | null): void { deadlineForTests = v; }-function withDeadline<T>(p: Promise<T>, ms: number): Promise<T> {+/** Rejects with deadline after ms; onLate tells the raced work to start no further queries. */+function withDeadline<T>(p: Promise<T>, ms: number, onLate: () => void): Promise<T> {let timer: ReturnType<typeof setTimeout> | undefined;- const timeout = new Promise<never>((_, reject) => { timer = setTimeout(() => reject(new RoomUnavailable('deadline')), ms); });+ const timeout = new Promise<never>((_, reject) => { timer = setTimeout(() => { onLate(); reject(new RoomUnavailable('deadline')); }, ms); });return Promise.race([p, timeout]).finally(() => clearTimeout(timer));}@@ -264,12 +269,19 @@ const UNAVAILABLE_WHY: Record<RoomUnknownReason, string> = {unbound: 'This connection is bound to no member, so it cannot ask what a room may read',mark_failed: 'Judging what the room may read failed (retrying is safe; nothing was changed)',deadline: 'Judging what the room may read took too long (retrying is safe; nothing was changed)',+ response_cap: 'The marked answer would not fit this connection, so the answer went out without its room marks',op_not_covered: 'This tool does not mark its results for a room',not_found: 'Some items could not be found again to judge',not_identified: 'Some items carry no page or fact id to judge',over_limit: `More than ${ROOM_MAX_REFS} items were returned, so the rest were not judged`,};+/** The notice an answer carries when its room marks had to be dropped to fit the connection's response cap. */+export function roomResponseCapNotice(): Notice {+ return { code: 'room_hints_unavailable', kind: 'degraded',+ why: `${UNAVAILABLE_WHY.response_cap}. The answer is complete; treat all of it as above this room's level: use it for the work, keep it out of the reply unless the ask needs it, and offer it in a private chat. [reason: response_cap]` };+}+function emptyMeta(d: RoomDeclaration): RoomMeta {return { principals: d.principals, declared_by: d.declared_by, ...(d.conflict ? { conflict: true as const } : {}), complete: true,counts: { items: 0, readable: 0, above: 0, unknown: 0 }, by_reason: {}, above: [] };@@ -298,7 +310,12 @@ export async function assessRoom(engine: BrainEngine, input: { op: string; resulfor (const s of slots) if (s.ref && refs.size < ROOM_MAX_REFS) refs.set(refKey(s.ref), s.ref);if (!unavailable && slots.length) {try {- decisions = await withDeadline((async () => { await deadlineForTests?.delay(); return decide(engine, await roomAccessFor(engine, caller, d.principals), [...refs.values()]); })(), deadlineForTests?.ms ?? input.deadlineMs ?? ROOM_DEADLINE_MS);+ let late = false;+ decisions = await withDeadline((async () => {+ await deadlineForTests?.delay();+ const access = late ? null : await roomAccessFor(engine, caller, d.principals);+ return access && !late ? decide(engine, access, [...refs.values()]) : new Map<string, RoomAccess>();+ })(), deadlineForTests?.ms ?? input.deadlineMs ?? ROOM_DEADLINE_MS, () => { late = true; });} catch (e) {unavailable = e instanceof RoomUnavailable ? e : new RoomUnavailable('mark_failed');}@@ -337,5 +354,6 @@ export async function assessRoom(engine: BrainEngine, input: { op: string; resulprincipal: caller.auth?.principal ? `${caller.auth.principal.kind}:${caller.auth.principal.id}` : caller.transport === 'stdio' ? 'local_stdio' : 'unknown',room: { readable: meta.counts.readable, above: meta.counts.above, unknown: meta.counts.unknown, by_reason: { ...meta.by_reason }, declared_by: d.declared_by,...(meta.unavailable ? { unavailable: meta.unavailable } : {}) } });- return { result, meta, notices, ...(hot !== undefined ? { hotMemory: hot } : {}), ...(retrieval ? { retrieval } : {}) };+ const stamped = meta.unavailable === 'op_not_covered' ? notices.filter(n => n.code !== 'room_hints_unavailable') : notices;+ return { result, meta, notices, stamped, ...(hot !== undefined ? { hotMemory: hot } : {}), ...(retrieval ? { retrieval } : {}) };}diff --git a/src/mcp/dispatch.ts b/src/mcp/dispatch.tsindex ad2d410ba4..f9bd3014d5 100644--- a/src/mcp/dispatch.ts+++ b/src/mcp/dispatch.ts@@ -18,7 +18,7 @@ import { withRequestConfigSnapshot, withoutRequestConfigSnapshot } from '../coreimport { currentCallerAccess, withCallerAccess } from '../core/search/private-visibility.ts';import { appliedAccessSummary, folderAccessFor, identityLookupUnavailable, remoteCallerAccess } from '../core/access/caller.ts';import { credentialScopeFor, requesterScopeGate, requesterScopeRefuses, requiresRequesterScope, withServesReread, type RequesterScopeNotice } from '../core/access/requester-scope.ts';-import { assessRoom, readRoomDeclaration, type RoomChannels, type RoomDeclaration } from '../core/access/room.ts';+import { assessRoom, readRoomDeclaration, roomResponseCapNotice, type RoomChannels, type RoomDeclaration } from '../core/access/room.ts';import { audienceInArguments, audienceInArgumentsError, logAudienceAssertion, parseAudience, type AudienceAuditEvent, type AudienceChannels, type AudiencePrincipal } from '../core/access/audience.ts';import { ACTOR_ARGUMENT, actorNotAttested, EXTERNAL_ID_RE, resolveAttestedActor, type ActorChannels } from '../core/access/actor.ts';import { attestedReadMode, SCOPE_READ_ACCESS, scopeReadLabelledOnlyRefused, withReadMode, type ReadMode } from '../core/access/scope-read.ts';@@ -198,8 +198,6 @@ export interface DispatchOpts {roomDeclaration?: RoomDeclaration;/** GBRA-498 (internal): the call named an attested actor, so its answer is never marked for a room. */roomAttested?: boolean;- /** GBRA-498 (internal): the private-readable sources of the call's grant, for the room's own access record. */- roomPrivateSources?: readonly string[];/** #6696 (A5): set by the trusted transport for the user's own agent calls; never from wire params. */admissionOrigin?: OperationContext['admissionOrigin'];/** The caller's self-declared agent label (X-Gbrain-Agent-Label), parsed by the transport; recorded only, never authority. */@@ -1052,7 +1050,7 @@ export async function dispatchToolCall(access = readMode === 'scope' ? { ...SCOPE_READ_ACCESS, folderCoverage: (await folderAccessFor(engine, [])).folderCoverage } : attested?.access ?? await remoteCallerAccess(engine, opts.auth, privateSources, opts.transport, audience, opts.transport === 'stdio' && !opts.auth ? opts.stdioMember : undefined, readOnly);// GBRA-284: an attested call reads its grant minus other members' personal sources, a scope read minus every personal source (access/member-sources.ts).if (attested?.actor) scoped = await attestedReadScope(engine, resolved, attested.actor.member, readMode === 'scope');- if (roomDeclaration) scoped = { ...scoped, roomDeclaration, roomAttested: !!attested?.actor, ...(privateSources ? { roomPrivateSources: privateSources } : {}) };+ if (roomDeclaration) scoped = { ...scoped, roomDeclaration, roomAttested: !!attested?.actor };if (opts.enforcedMember) access = { ...access, hidePrivate: true, owner: false, privateReadableSources: [] };// GST-363: on a brain that serves several people, a read from a connection bound to nobody is refused (or, in its grace, noticed) before any work.// An op this connection cannot reach (hidden by its surface, localOnly off stdio, or cliOnly over MCP) keeps its own refusal instead.@@ -1164,14 +1162,19 @@ async function runMetaHook(hook: NonNullable<DispatchOpts['metaHook']>, name: stasync function markForRoom(engine: BrainEngine, opts: DispatchOpts, name: string, result: unknown, retrieval: unknown, ctx: OperationContext, hook: ReturnType<typeof runMetaHook> | undefined) {const hookOut = hook ? await hook : undefined;const room = await assessRoom(engine, { op: name, result, hotMemory: hookOut?.meta, retrieval, declaration: opts.roomDeclaration!, sourceId: ctx.sourceId,- caller: { access: currentCallerAccess(), auth: ctx.auth, transport: ctx.transport, stdioMember: opts.stdioMember, privateSources: opts.roomPrivateSources, attested: opts.roomAttested } });+ caller: { access: currentCallerAccess(), auth: ctx.auth, transport: ctx.transport, stdioMember: opts.stdioMember, attested: opts.roomAttested } });return { hookOut, room: room as Awaited<ReturnType<typeof assessRoom>> | null };}-/** GBRA-498: room marks never cost a read: over the cap, the unmarked answer goes out with a one-key note, then without it. */-async function roomCapFallback(build: (meta: Record<string, unknown>) => ToolResult, cap: (built: ToolResult) => Promise<unknown>, responseMeta: Record<string, unknown>): Promise<ToolResult | null> {- for (const meta of [{ ...responseMeta, room: { complete: false, unavailable: 'response_cap' } }, responseMeta]) {- const fallback = build(meta);+/**+ * GBRA-498: room marks never cost a read. Over the cap, the unmarked answer goes out with the room_hints_unavailable+ * notice (reason response_cap) and a one-key _meta.room note, then with the notice alone, then bare.+ */+async function roomCapFallback(build: (meta: Record<string, unknown>, extra: Notice[]) => ToolResult, cap: (built: ToolResult) => Promise<unknown>, responseMeta: Record<string, unknown>): Promise<ToolResult | null> {+ const note = [roomResponseCapNotice()];+ const tries: Array<[Record<string, unknown>, Notice[]]> = [[{ ...responseMeta, room: { complete: false, unavailable: 'response_cap' } }, note], [responseMeta, note], [responseMeta, []]];+ for (const [meta, extra] of tries) {+ const fallback = build(meta, extra);if (!await cap(fallback)) return fallback;}return null;@@ -1469,11 +1472,11 @@ async function dispatchResolvedCall(if (hookOut?.failure !== undefined) ctx.logger.warn(`[mcp] _meta hook failed for ${name}: ${hookOut.failure}; degrading to no hook keys`);const cap = (built: ToolResult) => op.mutating ? Promise.resolve(null) : frameOverCap(built, { remote: ctx.remote, transport: ctx.transport, engine, config: ctx.config });const out = room- ? assemble(room.result, admitted, [...notices, ...room.notices], { ...responseMeta, ...(room.retrieval ? { retrieval: room.retrieval } : {}), room: room.meta }, (room.hotMemory ?? hookOut?.meta) as Record<string, unknown> | undefined)+ ? assemble(room.result, admitted, [...notices, ...room.stamped], { ...responseMeta, ...(room.retrieval ? { retrieval: room.retrieval } : {}), room: room.meta }, (room.hotMemory ?? hookOut?.meta) as Record<string, unknown> | undefined): assemble(result, admitted, notices, responseMeta, hookOut?.meta);// Large pages: the egress backstop measures the final frame; a read over the connection's cap is refused whole, never cut.const over = await cap(out);- const fallback = over && room ? await roomCapFallback(meta => assemble(result, admitted.filter(n => !n.code.startsWith('room_')), notices, meta, hookOut?.meta), cap, responseMeta) : null;+ const fallback = over && room ? await roomCapFallback((meta, extra) => assemble(result, [...admitted.filter(n => !n.code.startsWith('room_')), ...extra], [...notices, ...extra], meta, hookOut?.meta), cap, responseMeta) : null;if (fallback) return fallback;if (over) return errorResult(resultTooLargeError(name, safeParams, over), opts, { op: name, mutating: false, idempotent: op.idempotent === true });return out;diff --git a/test/access-room.test.ts b/test/access-room.test.tsindex ce34b4a51a..6b4dea402b 100644--- a/test/access-room.test.ts+++ b/test/access-room.test.ts@@ -260,6 +260,8 @@ for (const kind of testBackends()) {const out = await call('owner', 'remember', { fact: 'Harbor ledger room argument note', entity: PAGES.open.slug, visibility: 'world', provenance: 'room test', content_origin: 'user_said', room: ['group:team-a'] });expect(out.isError).toBe(false);expect((out.meta?.room as { unavailable?: string }).unavailable).toBe('op_not_covered');+ // A write the room marks nothing on is not a partial answer: no degraded stamp, so nobody retries a committed write.+ expect(out.meta?.degraded).toBeUndefined();const [row] = await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM facts WHERE fact LIKE '%room argument note%' AND context IS NULL");expect(row!.n).toBe(1);}, 60_000);@@ -288,12 +290,14 @@ for (const kind of testBackends()) {const { access: _applied, ...plainMeta } = plain.raw._meta ?? {};const plainBytes = encodedFrameBytes({ ...plain.raw, _meta: plainMeta });expect(plainBytes).toBeGreaterThan(EGRESS_CAP_MIN);- await engine.setConfig('mcp.max_result_bytes_http', String(plainBytes + 120));+ await engine.setConfig('mcp.max_result_bytes_http', String(plainBytes + 1500));try {const marked = await call('owner', 'get_chunks', { slug, limit: 500 }, { room: { header: 'group:team-a' } });expect(marked.isError).toBe(false);expect(marked.text).toBe(plain.text);expect(marked.meta?.room).toEqual({ complete: false, unavailable: 'response_cap' });+ expect(marked.blocks.some(b => b.startsWith('[gbrain notice room_hints_unavailable kind=degraded]') && b.includes('[reason: response_cap]'))).toBe(true);+ expect((marked.meta?.degraded as { reasons: string[] }).reasons).toContain('room_hints_unavailable');await engine.setConfig('mcp.max_result_bytes_http', String(plainBytes + 1));const bare = await call('owner', 'get_chunks', { slug, limit: 500 }, { room: { header: 'group:team-a' } });expect({ isError: bare.isError, text: bare.text === plain.text, room: bare.meta?.room }).toEqual({ isError: false, text: true, room: undefined });@@ -348,6 +352,16 @@ for (const kind of testBackends()) {}}, 60_000);+ test("a room never borrows the caller's private-pages grant: a private page stays above a one-member room", async () => {+ const owner = await verify('owner');+ const out = await dispatchToolCall(engine, 'get_page', { slug: PAGES.quiet.slug }, {+ remote: true, transport: 'http', auth: { ...owner, privatePages: { mode: 'granted_sources', sources: [SRC] } }, sourceId: SRC, takesHoldersAllowList: ['world'],+ room: { header: 'bob-example' },+ });+ expect(out.isError).toBeFalsy();+ expect((JSON.parse(out.content[0]!.text) as { room_access?: unknown }).room_access).toEqual({ readable: false, reason: 'private_label' });+ }, 60_000);+test('whoami advertises room support', async () => {const out = await call('owner', 'whoami', {});expect((out.json as { features?: unknown }).features).toEqual({ room: true });diff --git a/test/e2e/serve-http-on-behalf-of.test.ts b/test/e2e/serve-http-on-behalf-of.test.tsindex ac937bd1ba..baaead4784 100644--- a/test/e2e/serve-http-on-behalf-of.test.ts+++ b/test/e2e/serve-http-on-behalf-of.test.ts@@ -45,6 +45,7 @@ describeE2E('/mcp shared agent on_behalf_of over serve --http', () => {const out = await importFromContent(engine, p.slug, `---\ntype: note\nreadable_by: ${p.readers}\n---\n# Harbor plan ${key}\n\nHarbor plan notes ${p.canary}.`, { noEmbed: true });expect(out.status).toBe('imported');}+ expect((await importFromContent(engine, 'notes/room-open', '---\ntype: note\n---\n# Harbor room\n\nHarbor room notes.', { noEmbed: true })).status).toBe('imported');const minted = await mintLegacyToken(engine, { name: 'obo-e2e-bot', takesHolders: ['world'], scopes: ['read'] });bot = minted.token;await bindCredential(engine, { kind: 'token', id: minted.id }, { member: 'dan-example', mayActFor: ['member:alice-example', 'member:bob-example', 'guest'] });@@ -101,6 +102,29 @@ describeE2E('/mcp shared agent on_behalf_of over serve --http', () => {expect((named.meta?.access as Record<string, unknown>).member).toBeNull();}, 60_000);+ test('GBRA-498: a room from the X-Gbrain-Room header or request _meta.room marks the answer over serve --http', async () => {+ const roomCall = async (ch: { header?: string; meta?: string[] }) => {+ const res = await fetch(BASE + '/mcp', {+ method: 'POST',+ headers: { Authorization: 'Bearer ' + bot, 'Content-Type': 'application/json', Accept: 'application/json, text/event-stream',+ ...(ch.header !== undefined ? { 'X-Gbrain-Room': ch.header } : {}) },+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call',+ params: { name: 'get_page', arguments: { slug: 'notes/room-open' }, ...(ch.meta ? { _meta: { room: ch.meta } } : {}) } }),+ });+ const body = (await res.text()).trim();+ const rpc = JSON.parse(body.startsWith('{') ? body : body.split('\n').filter(l => l.startsWith('data:')).pop()!.slice(5).trim());+ return { page: JSON.parse(rpc.result.content[0].text), meta: rpc.result._meta as Record<string, unknown> | undefined };+ };+ for (const ch of [{ header: 'alice-example' }, { meta: ['alice-example'] }]) {+ const out = await roomCall(ch);+ expect(out.page.room_access).toEqual({ readable: true });+ expect((out.meta?.room as { principals: string[]; declared_by: string })).toMatchObject({ principals: ['member:alice-example'], declared_by: 'harness' });+ }+ const none = await roomCall({});+ expect(none.page.room_access).toBeUndefined();+ expect(none.meta?.room).toBeUndefined();+ }, 60_000);+test('an audience outside may_act_for reads nothing and names the operator command', async () => {const out = await call(PAGES.alice.slug, { header: 'alice-example, eve-example' });expect(out.text).toContain('on_behalf_of_not_permitted');