Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix: judge room marks on every page an item depends on
garrytane06ebc0a33ed
diff --git a/changelog.d/gbra498-owner-room-marks.md b/changelog.d/gbra498-owner-room-marks.mdindex cbf98c6e9a..244e824d92 100644--- a/changelog.d/gbra498-owner-room-marks.md+++ b/changelog.d/gbra498-owner-room-marks.md@@ -3,7 +3,7 @@**A harness can now tell gbrain which group chat an answer goes into, and gbrain marks every page and fact with whether the people in that chat could have read it.** The owner of a brain who asks their agent something in a team chat should get the same work as in a direct message, but the agent also needs to know what not to repeat in front of the room. Declaring the room does exactly that and nothing more: the read is never refused, shortened, reordered or failed because of it, and a call with no room returns what it always did.- Declare the room with the `X-Gbrain-Room` header (`gbrain serve --http`) or request-level `_meta.room`; a harness that can set neither may pass a `room` tool argument once `whoami` shows `features.room: true`. Entries are member ids, `group:<id>` or `guest`.-- Each item in `get_page`, `search`, `query`, `list_pages`, `find_pages`, `get_chunks`, `get_timeline`, `get_backlinks`, `recall` and `entity` answers, each hot-memory fact and each saved fact a search returns (also shown on its line of the saved-facts block) carries `room_access`: `{readable: true}`, `{readable: false, reason}` (`readers`, `folder_rule`, `labelled_only`, `private_label`, `derived`) or `{readable: "unknown", reason}`. `_meta.room` sums it up.+- Each item in `get_page`, `search`, `query`, `list_pages`, `find_pages`, `get_chunks`, `get_timeline`, `get_backlinks`, `recall` and `entity` answers, each hot-memory fact and each saved fact a search returns (also shown on its line of the saved-facts block) carries `room_access`: `{readable: true}`, `{readable: false, reason}` (`readers`, `folder_rule`, `labelled_only`, `private_label`, `derived`) or `{readable: "unknown", reason}`. `_meta.room` sums it up. A link, a timeline row or an entity-card fact is readable only when the room can read every page it depends on.- The `room_above_level` notice tells the model to use those items for the work, keep them out of the reply unless the ask needs them and offer them in a direct message. `room_hints_unavailable` says when the room could not be judged within 3 seconds or at all (the answer still goes out whole and on time, every item marked unknown, with the degraded stamp), and `room_conflict` says when a `room` argument disagreed with the harness; an argument can only add people.- The owner's own credential needs no `may_act_for` to declare a room, because a room only adds marks; any other member's credential needs `may_act_for` covering the room. Each marked call writes a count-only `room_marked` row to the audience audit log.- No setting, no migration, and it works the same on a repo-less brain. Guide: [docs/guides/rooms.md](docs/guides/rooms.md).diff --git a/docs/guides/rooms.md b/docs/guides/rooms.mdindex 9c6ae16eed..255ee7c5e3 100644--- a/docs/guides/rooms.md+++ b/docs/guides/rooms.md@@ -77,6 +77,11 @@ facts in `_meta.brain_hot_memory` and the saved facts a search or query returns`room: not readable (<reason>)` or `room: unknown (<reason>)`). With a roomdeclared, treat anything in an answer that carries no mark as unknown.+An item that depends on more than one page is readable only when the room can+read every one of them: a link needs both its ends (and the page it was found+on), a timeline row needs its own page and the page the event came from, and a+fact on an entity card is judged in the source of the card it hangs on.+Covered tools: `get_page`, `search`, `query`, `list_pages`, `find_pages`,`get_chunks`, `get_timeline`, `get_backlinks`, `recall` and `entity`. Everyother tool still runs normally with a room declared; its answer is markeddiff --git a/docs/protocol/MCP_META_CHANNELS.md b/docs/protocol/MCP_META_CHANNELS.mdindex 90353df2a3..4b9781af90 100644--- a/docs/protocol/MCP_META_CHANNELS.md+++ b/docs/protocol/MCP_META_CHANNELS.md@@ -171,7 +171,7 @@ header, and the response carries `_meta.room` back:"_meta": { "room": ["alice-example", "group:team-a"] } }// response _meta-{ "room": { "principals": ["alice-example", "group:team-a"], "declared_by": "harness",+{ "room": { "principals": ["group:team-a", "member:alice-example"], "declared_by": "harness","complete": true, "counts": { "items": 3, "readable": 2, "above": 1, "unknown": 0 },"by_reason": { "readers": 1 }, "above": [{ "source_id": "default", "slug": "notes/owner-plan", "reason": "readers" }] } }```diff --git a/src/core/access/room.ts b/src/core/access/room.tsindex 98f22226bb..7f76d8b784 100644--- a/src/core/access/room.ts+++ b/src/core/access/room.ts@@ -96,7 +96,8 @@ export function readRoomDeclaration(channels: RoomChannels | undefined, args: Retype PageRef = { kind: 'page'; source_id: string; slug: string } | { kind: 'page_id'; id: number };type FactRef = { kind: 'fact'; id: number };type Ref = PageRef | FactRef;-interface Slot { holder: Record<string, unknown>; ref: Ref | null }+/** One marked item: its own ref, plus the other pages that gate it (a timeline event's page, a link's target and origin). */+interface Slot { holder: Record<string, unknown>; ref: Ref | null; also?: Ref[] }const str = (v: unknown) => typeof v === 'string' && v ? v : undefined;const arr = (v: unknown): unknown[] => Array.isArray(v) ? v : [];@@ -110,11 +111,24 @@ function pageIdSlot(o: unknown): Slot | null {}function factSlot(o: unknown): Slot | null {if (!isObj(o)) return null;- return { holder: o, ref: typeof o.id === 'number' ? { kind: 'fact', id: o.id } : null };+ const id = typeof o.id === 'number' ? o.id : typeof o.id === 'string' && /^\d+$/.test(o.id) ? Number(o.id) : null;+ return { holder: o, ref: id === null ? null : { kind: 'fact', id } };+}+function timelineSlot(o: unknown): Slot | null {+ const s = pageIdSlot(o);+ if (s && typeof s.holder.event_page_id === 'number') s.also = [{ kind: 'page_id', id: s.holder.event_page_id }];+ return s;+}+function linkSlot(o: unknown, src: string): Slot | null {+ if (!isObj(o) || typeof o.from_slug !== 'string') return pageSlot(o, src);+ const also: Ref[] = [];+ if (typeof o.to_slug === 'string') also.push({ kind: 'page', source_id: str(o.to_source_id) ?? src, slug: o.to_slug });+ if (typeof o.origin_slug === 'string') also.push({ kind: 'page', source_id: str(o.origin_source_id) ?? src, slug: o.origin_slug });+ return { holder: o, ref: { kind: 'page', source_id: str(o.from_source_id) ?? src, slug: o.from_slug }, also };}function listOf(r: unknown): unknown[] {if (Array.isArray(r)) return r;- if (isObj(r)) return Array.isArray(r.pages) ? r.pages : Array.isArray(r.results) ? r.results : [];+ if (isObj(r)) return Array.isArray(r.pages) ? r.pages : Array.isArray(r.results) ? r.results : Array.isArray(r.rows) ? r.rows : [];return [];}const SKIP_KEYS = new Set(['next', 'arguments', 'fix', 'verify', 'coverage', '_meta', ROOM_ACCESS_KEY]);@@ -124,11 +138,11 @@ function walk(v: unknown, src: string, out: Slot[], depth = 0): void {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;+ src = str(v.source_id) ?? (isObj(v.entity) ? str(v.entity.source_id) : undefined) ?? 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;- if (k === 'facts' && Array.isArray(x)) { for (const f of x) { const s = factSlot(f); if (s) out.push(s); } continue; }+ if ((k === 'facts' || k === 'recent_facts') && Array.isArray(x)) { for (const f of x) { const s = factSlot(f); if (s) out.push(s); } continue; }walk(x, src, out, depth + 1);}}@@ -141,9 +155,8 @@ const EXTRACTORS: Record<string, (result: unknown, src: string) => Array<Slot |list_pages: (r, src) => listOf(r).map(i => pageSlot(i, src)),find_pages: (r, src) => listOf(r).map(i => pageSlot(i, src)),get_chunks: r => arr(r).map(pageIdSlot),- get_timeline: r => arr(r).map(pageIdSlot),- get_backlinks: (r, src) => arr(r).map(i => isObj(i) && typeof i.from_slug === 'string'- ? { holder: i, ref: { kind: 'page', source_id: str(i.from_source_id) ?? src, slug: i.from_slug } } : pageSlot(i, src)),+ get_timeline: r => arr(r).map(timelineSlot),+ get_backlinks: (r, src) => listOf(r).map(i => linkSlot(i, src)),recall: (r, src) => isObj(r) ? [...arr(r.facts).map(factSlot), ...arr(r.results).map(i => pageSlot(i, src))] : [],entity: (r, src) => { const out: Slot[] = []; walk(r, src, out); return out; },};@@ -176,7 +189,7 @@ async function decide(engine: BrainEngine, access: Partial<CallerAccess>, refs:(${privacyForCaller('p', privacyPartSql('p'))}) AS privacy_okFROM pages p WHERE p.id = ANY($3::int[]) OR (p.source_id, p.slug) IN (SELECT u.s, u.g FROM unnest($1::text[], $2::text[]) AS u(s, g))`,factSql: `SELECT f.id, (${worldOnlyFacts(true) ? factVisibilitySql('f', ['world']) : 'TRUE'} AND ${privateProvenanceFilterUnderPolicy('f')}) AS ok,- f.visibility = 'world' AS world FROM facts f WHERE f.id = ANY($1::int[])`,+ f.visibility = 'world' AS world FROM facts f WHERE f.id = ANY($1::bigint[])`,};});const out = new Map<string, RoomAccess>();@@ -293,6 +306,18 @@ function emptyMeta(d: RoomDeclaration): RoomMeta {* room_hints_unavailable notice says why. Writes one count-only audit row.*/export async function assessRoom(engine: BrainEngine, input: { op: string; result: unknown; hotMemory?: unknown; retrieval?: unknown; declaration: RoomDeclaration; caller: RoomCaller; sourceId: string; deadlineMs?: number }): Promise<RoomOutcome & { hotMemory?: unknown; retrieval?: unknown }> {+ try {+ return await assessRoomUnguarded(engine, input);+ } catch {+ // Marking itself failed (a value it could not copy, a shape it could not walk): the answer goes out unmarked, flagged.+ const d = input.declaration;+ const notice: Notice = { code: 'room_hints_unavailable', kind: 'degraded', why: `${UNAVAILABLE_WHY.mark_failed}. 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: mark_failed]` };+ return { result: input.result, meta: { ...emptyMeta(d), complete: false, unavailable: 'mark_failed' }, notices: [notice], stamped: [notice],+ ...(input.hotMemory !== undefined ? { hotMemory: input.hotMemory } : {}), ...(input.retrieval !== undefined ? { retrieval: input.retrieval } : {}) };+ }+}++async function assessRoomUnguarded(engine: BrainEngine, input: { op: string; result: unknown; hotMemory?: unknown; retrieval?: unknown; declaration: RoomDeclaration; caller: RoomCaller; sourceId: string; deadlineMs?: number }): Promise<RoomOutcome & { hotMemory?: unknown; retrieval?: unknown }> {const { op, declaration: d, caller } = input;const meta = emptyMeta(d);const extractor = EXTRACTORS[op];@@ -307,7 +332,7 @@ export async function assessRoom(engine: BrainEngine, input: { op: string; resul: d.invalid ? new RoomUnavailable('invalid', d.invalid) : null;let decisions = new Map<string, RoomAccess>();const refs = new Map<string, Ref>();- for (const s of slots) if (s.ref && refs.size < ROOM_MAX_REFS) refs.set(refKey(s.ref), s.ref);+ for (const s of slots) for (const r of s.ref ? [s.ref, ...(s.also ?? [])] : []) if (refs.size < ROOM_MAX_REFS) refs.set(refKey(r), r);if (!unavailable && slots.length) {try {let late = false;@@ -322,11 +347,13 @@ export async function assessRoom(engine: BrainEngine, input: { op: string; resul}const listed = new Set<string>();for (const s of slots) {- const key = s.ref ? refKey(s.ref) : null;+ const judge = (r: Ref): RoomAccess => !refs.has(refKey(r)) ? { readable: 'unknown', reason: 'over_limit' }+ : decisions.get(refKey(r)) ?? { readable: 'unknown', reason: 'not_found' };+ // An item is readable only when every page that gates it is; the first page that is not gives the reason.+ const gates = s.ref ? [s.ref, ...(s.also ?? [])].map(judge) : [];const access: RoomAccess = unavailable ? { readable: 'unknown', reason: unavailable.reason }: !s.ref ? { readable: 'unknown', reason: 'not_identified' }- : !refs.has(key!) ? { readable: 'unknown', reason: 'over_limit' }- : decisions.get(key!) ?? { readable: 'unknown', reason: 'not_found' };+ : gates.find(a => a.readable === false) ?? gates.find(a => a.readable === 'unknown') ?? { readable: true };s.holder[ROOM_ACCESS_KEY] = access;meta.counts.items++;if (access.readable === true) { meta.counts.readable++; continue; }diff --git a/test/access-room.test.ts b/test/access-room.test.tsindex 6b4dea402b..9fc122d7db 100644--- a/test/access-room.test.ts+++ b/test/access-room.test.ts@@ -33,7 +33,7 @@ import { addGroup, addMember, bindCredential } from '../src/core/access/members.import { setOwner } from '../src/core/access/owner.ts';import { setMemberLabelledOnly } from '../src/core/access/labelled-only.ts';import { proposeRevision } from '../src/core/access/policy.ts';-import { __setRoomDeadlineForTests, readRoomDeclaration, ROOM_COVERED_OPS } from '../src/core/access/room.ts';+import { __setRoomDeadlineForTests, assessRoom, readRoomDeclaration, ROOM_COVERED_OPS } from '../src/core/access/room.ts';import { EGRESS_CAP_MIN, encodedFrameBytes } from '../src/core/egress-budget.ts';import type { AuthInfo } from '../src/core/ops/contract.ts';import { testBackends } from './helpers/test-backends.ts';@@ -362,6 +362,40 @@ for (const kind of testBackends()) {expect((JSON.parse(out.content[0]!.text) as { room_access?: unknown }).room_access).toEqual({ readable: false, reason: 'private_label' });}, 60_000);+ test('a link, a timeline row and an entity card are judged on every page that gates them, not only the one they hang on', async () => {+ await engine.addLink(PAGES.open.slug, PAGES.mine.slug, 'harbor ledger link', 'mentions', 'manual', undefined, undefined, { fromSourceId: SRC, toSourceId: SRC });+ const room = { room: { header: 'group:team-a' } };+ const links = await call('owner', 'get_backlinks', { slug: PAGES.mine.slug }, room);+ const row = (links.json as Array<Record<string, unknown>>).find(l => l.from_slug === PAGES.open.slug)!;+ expect(row.room_access).toEqual({ readable: false, reason: 'readers' });+ const grouped = await call('owner', 'get_backlinks', { slug: PAGES.mine.slug, group: 'page' }, room);+ const rows = (grouped.json as { rows: Array<Record<string, unknown>> }).rows;+ expect(rows.length).toBeGreaterThan(0);+ for (const r of rows) expect(r.room_access).toBeDefined();+ const [open] = await engine.executeRaw<{ id: number }>('SELECT id FROM pages WHERE source_id = $1 AND slug = $2', [SRC, PAGES.open.slug]);+ const [mine] = await engine.executeRaw<{ id: number }>('SELECT id FROM pages WHERE source_id = $1 AND slug = $2', [SRC, PAGES.mine.slug]);+ await engine.executeRaw("INSERT INTO timeline_entries (page_id, date, summary, event_page_id) VALUES ($1, '2026-01-02', 'Harbor ledger event', $2)", [open!.id, mine!.id]);+ const timeline = await call('owner', 'get_timeline', { slug: PAGES.open.slug }, room);+ const ev = (timeline.json as Array<Record<string, unknown>>).find(e => String(e.summary).includes('Harbor ledger event'))!;+ expect(ev.room_access).toEqual({ readable: false, reason: 'readers' });+ const card = await call('owner', 'entity', { name: PAGES.open.slug }, room);+ const cardBody = (card.json as { card: { entity: Record<string, unknown>; recent_facts?: Array<Record<string, unknown>> } }).card;+ const facts = cardBody.recent_facts ?? [];+ expect(card.isError).toBe(false);+ expect(facts.length).toBeGreaterThan(0);+ for (const f of facts) expect(f.room_access).toBeDefined();+ expect(cardBody.entity.room_access).toEqual({ readable: true });+ }, 60_000);++ test('if marking itself throws, the read still goes out whole, flagged mark_failed', async () => {+ const { declaration } = readRoomDeclaration({ header: 'group:team-a' }, {});+ const result = { slug: PAGES.open.slug, keep: () => 1 };+ const out = await assessRoom(engine, { op: 'get_page', result, declaration: declaration!, sourceId: SRC, caller: { access: {} as never } });+ expect(out.result).toBe(result);+ expect(out.meta).toMatchObject({ complete: false, unavailable: 'mark_failed' });+ expect(out.stamped.map(n => n.code)).toEqual(['room_hints_unavailable']);+ }, 30_000);+test('whoami advertises room support', async () => {const out = await call('owner', 'whoami', {});expect((out.json as { features?: unknown }).features).toEqual({ room: true });