Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Mark saved facts in search answers for the room, and pin the deadline path
garrytan81495744a268
diff --git a/changelog.d/gbra498-owner-room-marks.md b/changelog.d/gbra498-owner-room-marks.mdindex e23824e8b0..cbf98c6e9a 100644--- a/changelog.d/gbra498-owner-room-marks.md+++ b/changelog.d/gbra498-owner-room-marks.md@@ -3,8 +3,8 @@**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, and each hot-memory fact, 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.-- 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 (every item is then marked unknown), and `room_conflict` says when a `room` argument disagreed with the harness; an argument can only add people.+- 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.+- 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 5c6da7f427..b649f378ed 100644--- a/docs/guides/rooms.md+++ b/docs/guides/rooms.md@@ -69,7 +69,11 @@ safety notice, so a model that never sees `_meta` still sees the warning.`counts` (`items`, `readable`, `above`, `unknown`), `by_reason` and`above` (each page or fact the room could not read, or that could not bejudged, by `source_id` and `slug`, `page_id` or `fact_id`, with its reason). Hot-memory-facts in `_meta.brain_hot_memory` are marked the same way.+facts in `_meta.brain_hot_memory` and the saved facts a search or query returns+(`_meta.retrieval.saved_facts`) are marked the same way, and each line of the+"Saved facts" block the model reads ends with its mark (`room: readable`,+`room: not readable (<reason>)` or `room: unknown (<reason>)`). With a room+declared, treat anything in an answer that carries no mark as unknown.Covered tools: `get_page`, `search`, `query`, `list_pages`, `find_pages`,`get_chunks`, `get_timeline`, `get_backlinks`, `recall` and `entity`. Every@@ -95,9 +99,11 @@ asked by someone other than the owner, the harness names that audience with## When marks are unavailable-If the room cannot be judged, the answer is still complete and every item is-marked `{readable: "unknown", reason}`, `_meta.room.complete` is false and the-`room_hints_unavailable` degraded notice explains why:+If the room cannot be judged, the answer is still complete and on time: every+item is marked `{readable: "unknown", reason}`, `_meta.room.complete` is false,+the `room_hints_unavailable` degraded notice explains why, and the degraded+stamp (`_meta.degraded.reasons` and the `[gbrain degraded: …]` block) names+`room_hints_unavailable`:| Reason | Cause | Fix ||---|---|---|diff --git a/docs/protocol/MCP_META_CHANNELS.md b/docs/protocol/MCP_META_CHANNELS.mdindex 9a0f997082..90353df2a3 100644--- a/docs/protocol/MCP_META_CHANNELS.md+++ b/docs/protocol/MCP_META_CHANNELS.md@@ -34,7 +34,7 @@ shape for it.| `degraded` | dispatch (`src/core/degraded-stamp.ts`), on every transport | `{reasons: [...]}`: present only when the result is partial or degraded; sorted, unique stable codes ([AGENT_OPERATOR_v1.md, Degraded stamp](AGENT_OPERATOR_v1.md#degraded-stamp)). Mirrored as the last content block, `[gbrain degraded: <codes>] …` || `retrieval` | `search`/`query` op handlers; `recall` and `find_experts` emit `{degraded[]}` when their page search degraded | `returned_count`, `retrieved_count`, `vector_enabled`, `expansion_applied`, `cache`, `token_budget`, `degraded[]` (closed stage vocabulary), `rerank_degraded` (on a call whose reranker failed: `{reason, fallback: "fused_order", calls_this_session}`; reason is `timeout`, `budget`, `rate_limited`, `unreachable`, `auth` or `provider_error`; no `fields: "full"` needed), `hint` (non-contractual prose), `rows` (`"lean"` or `"full"`: the row shape of content[0]; reported for remote callers and whenever `fields` is passed), `timings` (`{total_ms, stages_ms, other_ms, overlapped_ms?, parts_ms?}`, integer ms, every response; [search-explain.md](../guides/search-explain.md#see-where-the-time-went)) || `access` | dispatch (`appliedAccessSummary`, `src/core/access/caller.ts`), every remote response that reached the operation | The view the call was answered under: `member` and `groups` it read as (null and `[]` for an unbound caller or an audience of several entries), `audience` (the normalized `on_behalf_of` principals, or null), `policy_rev` (each source's applied folder-rule revision; null on a brain with no restriction), `relaxation` (`none`, `granted_sources`, `operator` or `owner`: what relaxed `visibility: private`; `owner` is a credential bound to the brain owner, see [access designations](../guides/access-designations.md)). `whoami` returns the same object as `access.applied`. An attested call adds `actor` (`{system}`); an unlinked `memory_recall` carries `code: "actor_unlinked"`, `member: null` and the id as sent. |-| `room` | dispatch (`assessRoom`, `src/core/access/room.ts`), only on a call that declared a room | The shared chat the answer goes into, as read: `principals`, `declared_by` (`harness` or `argument`), `conflict` (present when the argument and the harness disagreed), `complete`, `counts` (`{items, readable, above, unknown}`), `by_reason`, `above` (references the room could not read) and `unavailable` (why no marks could be computed: `invalid`, `not_permitted`, `unknown_principal`, `unbound`, `mark_failed`, `deadline`, `op_not_covered`, `response_cap`). Each page and fact in the body carries `room_access` (`{readable: true}`, `{readable: false, reason}` with reason `readers`, `folder_rule`, `labelled_only`, `private_label` or `derived`, or `{readable: "unknown", reason}`). [Details](#room) |+| `room` | dispatch (`assessRoom`, `src/core/access/room.ts`), only on a call that declared a room | The shared chat the answer goes into, as read: `principals`, `declared_by` (`harness` or `argument`), `conflict` (present when the argument and the harness disagreed), `complete`, `counts` (`{items, readable, above, unknown}`), `by_reason`, `above` (references the room could not read) and `unavailable` (why no marks could be computed: `invalid`, `not_permitted`, `unknown_principal`, `unbound`, `mark_failed`, `deadline`, `op_not_covered`, `response_cap`). Each page and fact in the body, each hot-memory fact and each entry of `retrieval.saved_facts` carries `room_access` (`{readable: true}`, `{readable: false, reason}` with reason `readers`, `folder_rule`, `labelled_only`, `private_label` or `derived`, or `{readable: "unknown", reason}`). [Details](#room) || `warnings` | dispatch strict-params warn mode | `[{code: 'unknown_param', param, suggestion?}]`: a parameter a read ignored. This is the only place the warning appears; no content block or notice carries it, so a harness that stores tool output in its turns never stores it (writes refuse unknown parameters instead). || `pagination` | `list_pages` op handler | `truncated` (more rows match), `limit` (effective), `clamped_from?` (the caller's limit when capped), `next?` (params for the following page: `{sort, updated_after, updated_after_slug}` under `updated_asc`, else `{offset}`). The model-visible counterpart is the `listing_truncated` notice block (kind `info`, never deduped), whose `fix.mcp` is the next-page call. |@@ -196,6 +196,7 @@ The codes in `_meta.degraded.reasons` ([AGENT_OPERATOR_v1.md, Degraded stamp](AG| `file_held` | get_page | the page's newer file is held by sync; this is its last good revision || `gather_hybrid_failed`, `gather_takes_keyword_failed`, `gather_takes_vector_failed`, `gather_graph_failed`, `gather_anchor_hydrate_failed`, `gather_window_floor_failed` | think, synthesize | an evidence stream failed (the matching `GATHER_*_FAILED` warning) || `held_files`, `references_unavailable`, `mention_index`, `relational_chain`, `graph_walk_truncated`, `pinned_answer_stale` | the ops that emit the notice of that code | a `kind: degraded` notice about this result |+| `room_hints_unavailable` | every op answered with a room declared | the room's marks could not be computed (`_meta.room.unavailable` says why): the body is complete, but every item is marked unknown || `scan_deadline`, `unreadable_pages` | search_exact | `incomplete_reasons` other than the caller's `limit` || `source_stale`, `held_items` | open_loops | `stale` or `completeness: "partial"` || `link_coverage_behind`, `link_coverage_unread` | rank_entities | `coverage.state` |diff --git a/src/core/access/room.ts b/src/core/access/room.tsindex fc345b3027..4eabaf6d20 100644--- a/src/core/access/room.ts+++ b/src/core/access/room.ts@@ -247,6 +247,10 @@ async function roomAccessFor(engine: BrainEngine, caller: RoomCaller, principalsreturn audienceCallerAccess(engine, caller.auth, caller.privateSources, 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> {let timer: ReturnType<typeof setTimeout> | undefined;const timeout = new Promise<never>((_, reject) => { timer = setTimeout(() => reject(new RoomUnavailable('deadline')), ms); });@@ -276,7 +280,7 @@ function emptyMeta(d: RoomDeclaration): RoomMeta {* result holds apart from adding room_access to its items: on any failure the items are marked unknown and a* 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; declaration: RoomDeclaration; caller: RoomCaller; sourceId: string; deadlineMs?: number }): Promise<RoomOutcome & { hotMemory?: unknown }> {+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 }> {const { op, declaration: d, caller } = input;const meta = emptyMeta(d);const extractor = EXTRACTORS[op];@@ -284,6 +288,9 @@ export async function assessRoom(engine: BrainEngine, input: { op: string; resulconst hot = input.hotMemory === undefined ? undefined : structuredClone(input.hotMemory);const slots: Slot[] = extractor ? extractor(result, input.sourceId).filter((s): s is Slot => !!s) : [];if (isObj(hot) && isObj(hot.brain_hot_memory)) for (const f of arr(hot.brain_hot_memory.facts)) { const s = factSlot(f); if (s) slots.push(s); }+ // search and query: the saved facts that ride _meta.retrieval (and the model-visible saved-facts block) are items too.+ const retrieval = isObj(input.retrieval) && Array.isArray(input.retrieval.saved_facts) ? structuredClone(input.retrieval) as Record<string, unknown> : undefined;+ if (retrieval) for (const f of arr(retrieval.saved_facts)) { const s = factSlot(f); if (s) slots.push(s); }let unavailable: RoomUnavailable | null = !extractor ? new RoomUnavailable('op_not_covered'): d.invalid ? new RoomUnavailable('invalid', d.invalid) : null;let decisions = new Map<string, RoomAccess>();@@ -291,7 +298,7 @@ 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 () => decide(engine, await roomAccessFor(engine, caller, d.principals), [...refs.values()]))(), input.deadlineMs ?? ROOM_DEADLINE_MS);+ 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);} catch (e) {unavailable = e instanceof RoomUnavailable ? e : new RoomUnavailable('mark_failed');}@@ -330,5 +337,5 @@ 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 } : {}) };+ return { result, meta, notices, ...(hot !== undefined ? { hotMemory: hot } : {}), ...(retrieval ? { retrieval } : {}) };}diff --git a/src/core/degraded-stamp.ts b/src/core/degraded-stamp.tsindex e973f7699e..e8ce514350 100644--- a/src/core/degraded-stamp.ts+++ b/src/core/degraded-stamp.ts@@ -25,6 +25,7 @@ export interface DegradedStamp {const RESULT_NOTICE_REASONS: ReadonlySet<string> = new Set(['held_files', 'references_unavailable', 'mention_index','relational_chain', 'graph_walk_truncated', 'pinned_answer_stale', 'facts_unembedded', 'delta_incomplete',+ 'room_hints_unavailable',]);/** One condition, one code: recall's keyword-only markers name the stage search and query already use. */diff --git a/src/mcp/dispatch.ts b/src/mcp/dispatch.tsindex 145f072c6b..ad2d410ba4 100644--- a/src/mcp/dispatch.ts+++ b/src/mcp/dispatch.ts@@ -453,7 +453,7 @@ export function retrievalNoticeBlocks(result: unknown, retrieval: unknown): striconst r = retrieval as {type_filter_notice?: unknown;other_names?: Array<{ name: string; alias: string; slug: string }>;- saved_facts?: Array<{ fact: string; entity_slug: string | null; valid_from: string; source: string; linked_from?: string; corrected_by?: number; quoted?: string }>;+ saved_facts?: Array<{ fact: string; entity_slug: string | null; valid_from: string; source: string; linked_from?: string; corrected_by?: number; quoted?: string; room_access?: { readable: unknown; reason?: string } }>;answer_id?: unknown;feedback?: { rateable?: boolean; how_to_rate?: string };};@@ -466,7 +466,7 @@ export function retrievalNoticeBlocks(result: unknown, retrieval: unknown): stri}if (r.saved_facts?.length) {const { text, more } = wholeItemsWithin('Saved facts (remember): about the entity this query names (newest first), then facts those point to, then matches for its words; recall returns more:\n',- r.saved_facts.map(f => `- ${f.fact}${f.quoted ? '\n' : ''} [entity: ${f.entity_slug ?? 'none'}; saved ${String(f.valid_from).slice(0, 10)}; provenance: ${f.source}${f.linked_from ? `; named in a saved fact about ${f.linked_from}` : ''}${f.corrected_by ? '; corrected by a newer saved fact above' : ''}]`),+ r.saved_facts.map(f => `- ${f.fact}${f.quoted ? '\n' : ''} [entity: ${f.entity_slug ?? 'none'}; saved ${String(f.valid_from).slice(0, 10)}; provenance: ${f.source}${f.linked_from ? `; named in a saved fact about ${f.linked_from}` : ''}${f.corrected_by ? '; corrected by a newer saved fact above' : ''}${f.room_access ? `; room: ${f.room_access.readable === true ? 'readable' : f.room_access.readable === false ? `not readable (${f.room_access.reason})` : `unknown (${f.room_access.reason})`}` : ''}]`),'\n', SAVED_FACTS_NOTICE_MAX_CHARS);blocks.push(more ? `${text}\n(+${more} more; recall returns them)` : text);}@@ -1161,9 +1161,9 @@ async function runMetaHook(hook: NonNullable<DispatchOpts['metaHook']>, name: st* GBRA-498: an answer going into a room is marked for it on a detached copy (hot memory too, so the hook runs first),* before the notices, the degraded stamp and the frame are built. Marking never fails the call.*/-async function markForRoom(engine: BrainEngine, opts: DispatchOpts, name: string, result: unknown, ctx: OperationContext, hook: ReturnType<typeof runMetaHook> | undefined) {+async 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, declaration: opts.roomDeclaration!, sourceId: ctx.sourceId,+ 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 } });return { hookOut, room: room as Awaited<ReturnType<typeof assessRoom>> | null };}@@ -1178,11 +1178,12 @@ async function roomCapFallback(build: (meta: Record<string, unknown>) => ToolRes}function assembleToolResult(- call: { name: string; result: unknown; batchError: boolean; evidenceBlocks: string[]; tail: ToolTail | undefined; opts: DispatchOpts },+ call: { name: string; result: unknown; batchError: boolean; evidence: (retrieval: unknown) => string[]; tail: ToolTail | undefined; opts: DispatchOpts },body: unknown, shown: Notice[], stamped: Notice[], meta: Record<string, unknown>, hook: Record<string, unknown> | undefined,): ToolResult {const built: ToolResult = call.batchError ? toolErrorResult(body as never) : toolResultWithNotices(body, shown, dispatchRenderContext(call.opts));- if (call.evidenceBlocks.length > 0) built.content.splice(1, 0, ...call.evidenceBlocks.map(text => ({ type: 'text' as const, text })));+ const evidenceBlocks = call.evidence(meta.retrieval);+ if (evidenceBlocks.length > 0) built.content.splice(1, 0, ...evidenceBlocks.map(text => ({ type: 'text' as const, text })));// _meta assembly (WP2 amendment 9): one producer per top-level key,// each isolated — handler-emitted keys (retrieval, warnings) attach// BEFORE and independently of the metaHook, so a hot-memory hook@@ -1427,7 +1428,7 @@ async function dispatchResolvedCall(if (emptyBlock) notices.push({ code: 'empty_retrieval', kind: emptyBlock.includes('degraded:') ? 'degraded' : 'info', why: emptyBlock });// Cat 40 (#5932) evidence blocks (type-filter notice, other names, saved facts) are retrieval// data, not advice: they stay plain extra text blocks right after content[0], as measured.- const evidenceBlocks = retrievalNoticeBlocks(result, responseMeta.retrieval).slice(emptyBlock ? 1 : 0);+ const evidence = (retrieval: unknown) => retrievalNoticeBlocks(result, retrieval).slice(emptyBlock ? 1 : 0);// Lane F (F3): degraded recall and a source binding that narrowed an empty read.const rerankDegradedCalls = recordRerankDegradation(responseMeta, opts);notices.push(...recallInteropNotices(name, result, responseMeta, safeParams,@@ -1453,10 +1454,10 @@ async function dispatchResolvedCall(if (opts.transport === 'stdio' && opts.remote !== false && !batchError) notices.push(...await mcpOnboardingNotices({ engine, op: name, result, meta: responseMeta, config: ctx.config, render: dispatchRenderContext(opts) }));if (opts.transport === 'stdio' && opts.remote !== false && !batchError) { const drain = takeFactsDrainNotice(); if (drain) notices.push(drain); } // Lane D facts drainif (!batchError) notices.push(...await sessionSafetyNotices(engine, opts, ctx.config), ...await grantBlockedNotices(engine, opts, false));- let { hookOut, room } = opts.roomDeclaration && ctx.remote !== false && !batchError ? await markForRoom(engine, opts, name, result, ctx, metaHook && (earlyMeta ?? runMetaHook(metaHook, name, ctx))) : { hookOut: undefined, room: null };+ let { hookOut, room } = opts.roomDeclaration && ctx.remote !== false && !batchError ? await markForRoom(engine, opts, name, result, responseMeta.retrieval, ctx, metaHook && (earlyMeta ?? runMetaHook(metaHook, name, ctx))) : { hookOut: undefined, room: null };const admitted = admitNotices(room ? [...notices, ...room.notices] : notices, opts);const assemble = (body: unknown, shown: Notice[], stamped: Notice[], meta: Record<string, unknown>, hook: Record<string, unknown> | undefined) =>- assembleToolResult({ name, result, batchError, evidenceBlocks, tail, opts }, body, shown, stamped, meta, hook);+ assembleToolResult({ name, result, batchError, evidence, tail, opts }, body, shown, stamped, meta, hook);if (opts.transport === 'stdio') {maybeRefreshBackupStatusInProcess(engine);}@@ -1468,7 +1469,7 @@ 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: room.meta }, (room.hotMemory ?? hookOut?.meta) as Record<string, unknown> | undefined)+ ? 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(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);diff --git a/test/access-room.test.ts b/test/access-room.test.tsindex e08d1c5bf6..ce34b4a51a 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 { readRoomDeclaration, ROOM_COVERED_OPS } from '../src/core/access/room.ts';+import { __setRoomDeadlineForTests, 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';@@ -302,6 +302,52 @@ for (const kind of testBackends()) {}}, 120_000);+ test('saved facts in a search answer are marked too, in _meta.retrieval and in the block the model reads', async () => {+ const params = { query: 'harbor ledger note', match: 'keyword', limit: 20 };+ const plain = await call('owner', 'search', params);+ const plainFacts = ((plain.meta?.retrieval as { saved_facts?: Array<Record<string, unknown>> })?.saved_facts) ?? [];+ expect(plainFacts.length).toBeGreaterThan(0);+ expect(plainFacts.some(f => 'room_access' in f)).toBe(false);+ expect(plain.blocks.some(b => b.includes('; room: '))).toBe(false);+ const marked = await call('owner', 'search', params, { room: { header: 'group:team-a' } });+ expect(unmarked(marked.json)).toEqual(unmarked(plain.json));+ const facts = (marked.meta?.retrieval as { saved_facts: Array<Record<string, unknown>> }).saved_facts;+ expect(facts.map(f => f.fact)).toEqual(plainFacts.map(f => f.fact));+ for (const f of facts) expect(f.room_access).toBeDefined();+ const markOf = (text: string) => facts.find(f => String(f.fact).includes(text))?.room_access;+ expect(markOf('Harbor ledger world note')).toEqual({ readable: true });+ const block = marked.blocks.find(b => b.startsWith('Saved facts'))!;+ expect(block).toContain('Harbor ledger world note');+ expect(block).toContain('; room: readable]');+ expect((marked.meta?.room as { counts: { items: number } }).counts.items).toBe(Object.keys(marks(marked.json)).length + facts.length);+ }, 60_000);++ test('rule 1 at the deadline: when marking cannot finish in time the read goes out whole, on time, with the degraded stamp', async () => {+ const params = { query: 'harbor ledger note', match: 'keyword', limit: 20 };+ const plain = await call('owner', 'search', params);+ __setRoomDeadlineForTests({ ms: 50, delay: () => new Promise(r => setTimeout(r, 5_000)) });+ try {+ const started = Date.now();+ const late = await call('owner', 'search', params, { room: { header: 'group:team-a' } });+ expect(Date.now() - started).toBeLessThan(4_000);+ expect(late.isError).toBe(false);+ expect(unmarked(late.json)).toEqual(unmarked(plain.json));+ const items = Object.values(marks(late.json));+ expect(items.length).toBeGreaterThan(0);+ for (const a of items) expect(a).toEqual({ readable: 'unknown', reason: 'deadline' });+ expect(late.meta?.room).toMatchObject({ complete: false, unavailable: 'deadline' });+ expect(late.blocks.some(b => b.startsWith('[gbrain notice room_hints_unavailable kind=degraded]'))).toBe(true);+ expect(late.blocks.some(b => b.startsWith('[gbrain degraded:') && b.includes('room'))).toBe(true);+ expect((late.meta?.degraded as { reasons: string[] }).reasons).toContain('room_hints_unavailable');+ const facts = (late.meta?.retrieval as { saved_facts: Array<Record<string, unknown>> }).saved_facts;+ expect(facts.length).toBeGreaterThan(0);+ for (const f of facts) expect(f.room_access).toEqual({ readable: 'unknown', reason: 'deadline' });+ expect(late.blocks.find(b => b.startsWith('Saved facts'))).toContain('; room: unknown (deadline)]');+ } finally {+ __setRoomDeadlineForTests(null);+ }+ }, 60_000);+test('whoami advertises room support', async () => {const out = await call('owner', 'whoami', {});expect((out.json as { features?: unknown }).features).toEqual({ room: true });