Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(qm): a memory_recall that names sources reads as the scope, never as the person; contract v2 beside a frozen v1 (GST-1094)
garrytanbdbd45cf543a
diff --git a/docs/contracts/qm-memory-provider/v2.json b/docs/contracts/qm-memory-provider/v2.jsonnew file mode 100644index 0000000000..7e2c5c29cd--- /dev/null+++ b/docs/contracts/qm-memory-provider/v2.json@@ -0,0 +1,403 @@+{+ "contract": "gbrain.qm-memory-provider",+ "version": 2,+ "transport": {+ "protocol": "mcp",+ "session": "stateless",+ "session_header_issued": false,+ "success_codes_in": "structuredContent",+ "unknown_arguments": "an argument a read tool does not declare is ignored and reported only in _meta.warnings ([{code: \"unknown_param\", param, suggestion?}]), never in content; a write tool refuses it with invalid_params"+ },+ "actor": {+ "header": "x-qm-actor",+ "argument": "acting_user",+ "argument_rule": "optional; on an attested call it must equal the header; with no header it is accepted only from a credential bound to a member and only naming that member (its member id or a canonical id linked to it), and the call then runs exactly as the credential; never chooses the person on its own",+ "actor_id": {+ "pattern": "^[\\x21-\\x7e]{1,256}$",+ "case_folding": false+ },+ "system": "qm",+ "default_attest_ops": [+ "get_write_request",+ "memory_recall",+ "memory_write"+ ],+ "deferred_ops": [+ "capture",+ "extract_facts",+ "list_write_conflicts",+ "takes_add",+ "takes_resolve",+ "takes_supersede",+ "takes_update"+ ],+ "audit": "the audit trail and stored writes record the canonical external id as sent, with its linked member"+ },+ "tools": [+ {+ "name": "memory_recall",+ "description": "Facts for the person this call serves, one per line: their own recent facts first, then facts matching query. Never page bodies. For QM; agents use recall.",+ "scope": "read",+ "mutating": false,+ "input_schema": {+ "type": "object",+ "properties": {+ "query": {+ "type": "string",+ "description": "What the turn is about; ranks the facts."+ },+ "max_chars": {+ "type": "integer",+ "description": "Text cap in UTF-16 code units, 200-12000 (default 6000)."+ },+ "acting_user": {+ "type": "string",+ "description": "Set by the trusted system: equal to the x-qm-actor header, or omit."+ },+ "source_id": {+ "type": "string",+ "description": "Read this one source as its audience (a shared scope): never the person's own facts."+ },+ "source_ids": {+ "type": "array",+ "description": "Read only these sources as their audience (a shared scope): never the person's own facts.",+ "items": {+ "type": "string"+ }+ }+ },+ "required": [+ "query"+ ]+ }+ },+ {+ "name": "memory_write",+ "description": "Save facts for the person this call serves, readable by them alone. Needs an attested person. The same idempotency_key replays the first receipt. For QM; agents use remember.",+ "scope": "write",+ "mutating": true,+ "input_schema": {+ "type": "object",+ "properties": {+ "facts": {+ "type": "array",+ "description": "1-20 facts.",+ "items": {+ "type": "object",+ "properties": {+ "fact": {+ "type": "string",+ "description": "One claim."+ },+ "provenance": {+ "type": "string",+ "description": "Where it came from (<=200 chars)."+ },+ "kind": {+ "type": "string",+ "description": "Default fact.",+ "enum": [+ "event",+ "preference",+ "commitment",+ "belief",+ "fact"+ ]+ },+ "valid_from": {+ "type": "string",+ "description": "When it became true (ISO 8601)."+ }+ },+ "required": [+ "fact",+ "provenance"+ ],+ "additionalProperties": false+ }+ },+ "idempotency_key": {+ "type": "string",+ "description": "1-128 visible ASCII characters; the same key replays this write."+ },+ "acting_user": {+ "type": "string",+ "description": "Set by the trusted system: equal to the x-qm-actor header, or omit."+ }+ },+ "required": [+ "facts",+ "idempotency_key"+ ]+ }+ }+ ],+ "memory_recall": {+ "limits": {+ "max_chars": {+ "min": 200,+ "max": 12000,+ "default": 6000,+ "whole_number": true,+ "unit": "UTF-16 code units (JavaScript string length)"+ },+ "query_chars_ranked": 2000,+ "own_recent_window_hours": 24+ },+ "arguments_checked": "query and max_chars are checked before any read, also for an unlinked person (invalid_params)",+ "content": {+ "line": "- <fact> (<YYYY-MM-DD>; <kind>)",+ "never": [+ "page bodies",+ "fence markers",+ "heading markers",+ "line breaks or control characters inside a fact"+ ],+ "bounded_by": "max_chars: as many whole lines as fit; facts left out set structuredContent.truncated, with no marker line, because every line is one fact"+ },+ "order": [+ "own facts from the last 24 hours, newest first",+ "facts the person may read, ranked by query"+ ],+ "ranking": "keyword-only unless an embedding provider is configured (no embedding call on a keyless brain)",+ "structured_content": {+ "facts": [+ {+ "id": "string",+ "text": "string",+ "date": "YYYY-MM-DD",+ "kind": "string"+ }+ ],+ "truncated": "boolean",+ "code": "actor_unlinked (only on unlinked_recall)"+ },+ "scope_read": {+ "arguments": [+ "source_id",+ "source_ids"+ ],+ "rule": "a call that names sources is read as their audience, never as the person: no own facts first and no member-page fact; a page restricted to named readers stays hidden; privacy is never relaxed",+ "sources": "narrowed inside the credential's read grant like recall's source_ids; a source outside it is permission_denied; source_id and source_ids together read their intersection, and an empty intersection reads nothing",+ "without_sources": "the person read above (own recent facts, then what the person may read across the read grant): use it only for the person's own conversations"+ }+ },+ "unlinked_recall": {+ "isError": false,+ "content": [+ {+ "type": "text",+ "text": ""+ }+ ],+ "structuredContent": {+ "facts": [],+ "truncated": false,+ "code": "actor_unlinked"+ }+ },+ "memory_write": {+ "limits": {+ "facts": {+ "min": 1,+ "max": 20+ },+ "provenance_chars": 200,+ "idempotency_key": {+ "pattern": "^[\\x21-\\x7e]{1,128}$"+ },+ "kinds": [+ "event",+ "preference",+ "commitment",+ "belief",+ "fact"+ ],+ "provenance": "one line: no line breaks or control characters, and not starting with qm: (gbrain adds qm:<actor id> itself)",+ "valid_from": "YYYY-MM-DD or YYYY-MM-DDTHH:MM[:SS[.fraction]][Z|±HH:MM], a real calendar day in years 0001-9999"+ },+ "validation": "every fact is checked before any is saved: one bad fact refuses the whole call with invalid_params and the idempotency_key stays unused",+ "saved_as": {+ "page": "memory/members/<member>",+ "readers": [+ "member:<member>"+ ],+ "visibility": "private",+ "provenance": "qm:<actor id>; <caller provenance>"+ },+ "request_id": "uuidv5(uuidv5(namespace, \"member:<member>\"), idempotency_key) for the first fact; later facts derive from it",+ "replay": "the same idempotency_key from the same person returns the first receipt; from another person it is a separate write",+ "retries": "never retried server-side; a write still publishing answers pending",+ "committed": {+ "content": "Saved <N> fact(s).",+ "structuredContent": {+ "status": "committed",+ "request_id": "uuid",+ "fact_ids": [+ "string"+ ]+ },+ "fact_ids": "distinct; facts repeating one claim in a call share one id, and <N> counts distinct facts"+ },+ "pending": {+ "content": "Accepted <N> fact(s); <M> still publishing.",+ "structuredContent": {+ "status": "pending",+ "request_id": "uuid",+ "fact_ids": [+ "string"+ ],+ "pending_request_ids": [+ "uuid"+ ]+ },+ "poll": "get_write_request {request_id}"+ }+ },+ "errors": {+ "shape": {+ "isError": true,+ "content": "one JSON text block with top-level code, message, suggestion and optional reason and fix",+ "structuredContent": {+ "error": {+ "code": "string",+ "message": "string",+ "reason": "string?",+ "write_error": "string?",+ "fix": "object?"+ }+ }+ },+ "applies_to": "every refusal of memory_recall and memory_write, including the transport's scope and unknown-tool refusals",+ "codes": [+ {+ "code": "actor_not_attested",+ "class": "host_only",+ "summary": "A call named the person it serves (the x-qm-actor header or the acting_user argument) in a way gbrain does not honour: the credential holds no attest right, the operation is not in its attested operations, the argument differs from the header or comes without an attested header, or the id is not 1-256 visible ASCII characters; or a write that saves only as an attested person (memory_write) named none; or the request carries x-qm-audience, a channel audience gbrain does not serve yet. Nothing was read or written.",+ "suggestion": "Read reason: no_attest_right and op_not_attested are the brain operator's call (gbrain auth rescope --client <id> --attest-actor qm [--attest-ops <list>]); argument_mismatch, argument_without_attestation, invalid_actor_id, actor_required and audience_not_supported are fixed in the calling harness.",+ "docs": "docs/guides/write-refusals.md#actor_not_attested",+ "reasons": [+ {+ "reason": "no_attest_right",+ "fixed_by": "brain_operator",+ "fix": "gbrain auth rescope --client <id> --attest-actor qm on the brain host; a client that already holds the right takes a new token with grant_type=client_credentials."+ },+ {+ "reason": "op_not_attested",+ "fixed_by": "brain_operator",+ "fix": "gbrain auth rescope --client <id> --attest-actor qm --attest-ops <list>; a deferred operation cannot be attested yet."+ },+ {+ "reason": "argument_mismatch",+ "fixed_by": "calling_harness",+ "fix": "Send acting_user equal to the x-qm-actor header (with no header, on a credential bound to a member: that member id or a canonical id linked to it), or omit it."+ },+ {+ "reason": "argument_without_attestation",+ "fixed_by": "calling_harness",+ "fix": "Remove acting_user, or send the x-qm-actor header from a credential holding the attest right; a credential bound to no member never sends acting_user alone."+ },+ {+ "reason": "invalid_actor_id",+ "fixed_by": "calling_harness",+ "fix": "Send the canonical id unchanged: 1-256 visible ASCII characters, no spaces."+ },+ {+ "reason": "actor_required",+ "fixed_by": "calling_harness",+ "fix": "memory_write saves only as an attested person: send x-qm-actor from a credential holding the attest right."+ },+ {+ "reason": "audience_not_supported",+ "fixed_by": "calling_harness",+ "fix": "Send the call without x-qm-audience; channel turns are refused until wave 2 and nothing is read or written."+ }+ ],+ "note": "With no x-qm-actor header, acting_user is accepted only from a credential bound to a member and only naming that member (its member id or a canonical id linked to it); the call then runs exactly as the credential."+ },+ {+ "code": "actor_unlinked",+ "class": "host_only",+ "summary": "An attested call named a person whose canonical id is not linked to an enabled member of this brain (never linked, unlinked, or the member is disabled or removed), so nothing was read or written.",+ "suggestion": "The brain operator links the id to its member: gbrain access member link <member> --qm <id> (or enables the member).",+ "docs": "docs/guides/write-refusals.md#actor_unlinked",+ "note": "Refuses memory_write. memory_recall answers it as a success instead (unlinked_recall)."+ },+ {+ "code": "on_behalf_of_invalid_audience",+ "class": "caller",+ "summary": "A shared agent's request named its audience (the X-Gbrain-On-Behalf-Of header or request-level _meta.on_behalf_of) in a form gbrain does not accept: empty, more than 50 entries, an entry that is not a member id, group:<id> or guest, or a header and _meta that name different audiences. Nothing was read.",+ "suggestion": "Fix the harness code that sets the audience: 1-50 entries, each a member id, group:<id> or guest, the same in the header and _meta when both are sent.",+ "docs": "docs/guides/write-refusals.md#on_behalf_of_invalid_audience",+ "note": "Sent when x-qm-actor is combined with an on_behalf_of audience (X-Gbrain-On-Behalf-Of or request-level _meta.on_behalf_of). QM classifies it as a failed call."+ },+ {+ "code": "invalid_params",+ "class": "caller",+ "summary": "A parameter is missing, has the wrong type, or has an invalid value.",+ "docs": "docs/guides/error-codes.md#invalid_params",+ "note": "Bad arguments, refused before anything is saved. A reused idempotency_key with different facts carries write_error idempotency_conflict; a claim the person forgot carries the fact_withdrawn message."+ },+ {+ "code": "scope_denied",+ "class": "host_only",+ "summary": "The connection lacks the scope this memory verb requires.",+ "docs": "docs/guides/error-codes.md#scope_denied",+ "note": "The write is not authorized, including a member page whose readers name anyone but its member (squatted or widened): nothing is saved."+ },+ {+ "code": "insufficient_scope",+ "class": "host_only",+ "summary": "The connection lacks the OAuth scope the operation requires.",+ "docs": "docs/guides/error-codes.md#insufficient_scope",+ "note": "The credential lacks the OAuth scope the tool needs (memory_write needs write); refused by the transport before the call runs."+ },+ {+ "code": "unknown_tool",+ "class": "caller",+ "summary": "The named tool does not exist or is not callable on this connection.",+ "docs": "docs/guides/error-codes.md#unknown_tool",+ "note": "The tool is not callable on this connection (its surface or bound-operation list leaves it out)."+ },+ {+ "code": "not_found",+ "class": "caller",+ "summary": "The requested resource does not exist or is not visible to this caller.",+ "docs": "docs/guides/error-codes.md#not_found",+ "note": "get_write_request for a receipt that is not this person's, or forget for a fact that is not on this person's own member page."+ },+ {+ "code": "fact_not_found",+ "class": "caller",+ "summary": "Fact not found.",+ "docs": "docs/guides/error-codes.md#fact_not_found",+ "note": "forget_fact for a fact that is not on this person's own member page."+ },+ {+ "code": "unavailable",+ "class": "unavailable",+ "summary": "A required dependency or capability cannot serve this request.",+ "docs": "docs/guides/error-codes.md#unavailable",+ "note": "memory_recall could not read the fact candidates (a database failure); retry the same call."+ },+ {+ "code": "permission_denied",+ "class": "host_only",+ "summary": "This caller is not authorized for the operation.",+ "docs": "docs/guides/error-codes.md#permission_denied",+ "note": "memory_recall named a source (source_id or source_ids) outside the credential's read grant; nothing was read."+ }+ ]+ },+ "wave_2": {+ "audience_header": "x-qm-audience",+ "encoding": "base64url of a JSON array of canonical ids",+ "status": "refused until wave 2",+ "refusal": {+ "code": "actor_not_attested",+ "reason": "audience_not_supported",+ "tools_call": "errors.shape, with or without x-qm-actor",+ "other_methods": "JSON-RPC error -32600 whose data carries code and reason (tools/list, resources/list, resources/read)"+ }+ }+}diff --git a/scripts/build-qm-memory-contract.ts b/scripts/build-qm-memory-contract.tsindex 959ea4286b..b77ce3c3c6 100644--- a/scripts/build-qm-memory-contract.ts+++ b/scripts/build-qm-memory-contract.ts@@ -1,10 +1,11 @@#!/usr/bin/env bun/**- * GST-359 D: docs/contracts/qm-memory-provider/v1.json, the QM memory-provider contract, generated from the live- * operation registry, the actor model and the error catalogue. test/qm-memory-contract.test.ts fails on drift.- * bun scripts/build-qm-memory-contract.ts write the fixture- * bun scripts/build-qm-memory-contract.ts --check exit 1 when the committed fixture is stale- * A change to the shape is a new file (v2.json); v1.json stays until QM moves.+ * GST-359 D: docs/contracts/qm-memory-provider/v1.json and v2.json, the QM memory-provider contracts, generated from the+ * live operation registry, the actor model and the error catalogue. test/qm-memory-contract.test.ts fails on drift.+ * bun scripts/build-qm-memory-contract.ts write both fixtures+ * bun scripts/build-qm-memory-contract.ts --check exit 1 when a committed fixture is stale+ * A change to the shape is a new version; v1.json stays byte-identical until QM moves. GST-1094 v2 adds the scope read+ * (source_id / source_ids on memory_recall), GST-900's member-bound acting_user rule and _meta-only unknown-param warnings.*/import { readFileSync, writeFileSync, mkdirSync } from 'node:fs';import { dirname, join } from 'node:path';@@ -14,7 +15,14 @@ import { CODES } from '../src/core/error-registry.ts';import { ACTOR_ARGUMENT, ACTOR_DEFERRED_OPS, ACTOR_HEADER, DEFAULT_ATTEST_OPS, EXTERNAL_ID_RE, QM_AUDIENCE_HEADER } from '../src/core/access/actor-model.ts';import { IDEMPOTENCY_KEY_RE, MEMORY_RECALL_MAX_CHARS, MEMORY_RECALL_QUERY_CHARS, MEMORY_WRITE_KINDS, MEMORY_WRITE_MAX_FACTS, MEMORY_WRITE_PROVENANCE_MAX, OWN_RECENT_WINDOW_HOURS, QM_MEMORY_OPS, unlinkedRecallResult } from '../src/core/ops/qm-memory.ts';-export const QM_CONTRACT_PATH = join(import.meta.dir, '..', 'docs', 'contracts', 'qm-memory-provider', 'v1.json');+export type QmContractVersion = 1 | 2;+export const QM_CONTRACT_PATHS: Record<QmContractVersion, string> = {+ 1: join(import.meta.dir, '..', 'docs', 'contracts', 'qm-memory-provider', 'v1.json'),+ 2: join(import.meta.dir, '..', 'docs', 'contracts', 'qm-memory-provider', 'v2.json'),+};+export const QM_CONTRACT_PATH = QM_CONTRACT_PATHS[1];+/** The arguments v1 publishes per tool, frozen: later arguments appear from v2 on. */+const V1_PARAMS: Record<string, readonly string[]> = { memory_recall: ['query', 'max_chars', 'acting_user'], memory_write: ['facts', 'idempotency_key', 'acting_user'] };/** Who fixes each actor_not_attested reason, and how. Every reason the catalogue lists needs a row (the drift test checks). */export const ACTOR_REASON_FIXES: Record<string, { fixed_by: 'brain_operator' | 'calling_harness'; fix: string }> = {@@ -41,28 +49,43 @@ const ERROR_NOTES: Partial<Record<typeof ERROR_CODES[number], string>> = {unavailable: 'memory_recall could not read the fact candidates (a database failure); retry the same call.',};-function toolEntry(name: string) {+/** v2 changes to v1's fix rows (GST-900: a member-bound credential may name its own member). */+const V2_REASON_FIXES: Partial<typeof ACTOR_REASON_FIXES> = {+ argument_mismatch: { fixed_by: 'calling_harness', fix: 'Send acting_user equal to the x-qm-actor header (with no header, on a credential bound to a member: that member id or a canonical id linked to it), or omit it.' },+ argument_without_attestation: { fixed_by: 'calling_harness', fix: 'Remove acting_user, or send the x-qm-actor header from a credential holding the attest right; a credential bound to no member never sends acting_user alone.' },+};++function toolEntry(name: string, version: QmContractVersion) {const op = operations.find(o => o.name === name);if (!op) throw new Error(name + ' is not in the operation registry');+ const params = Object.entries(op.params).filter(([k]) => version > 1 || V1_PARAMS[name]!.includes(k));return {name, description: op.description, scope: op.scope ?? 'read', mutating: op.mutating === true,- input_schema: { type: 'object', properties: Object.fromEntries(Object.entries(op.params).map(([k, v]) => [k, paramDefToSchema(v)])),- required: Object.entries(op.params).filter(([, v]) => v.required).map(([k]) => k) },+ input_schema: { type: 'object', properties: Object.fromEntries(params.map(([k, v]) => [k, paramDefToSchema(v)])),+ required: params.filter(([, v]) => v.required).map(([k]) => k) },};}-export function buildQmMemoryContract(): Record<string, unknown> {+export function buildQmMemoryContract(version: QmContractVersion): Record<string, unknown> {const unlinked = unlinkedRecallResult();+ const v2 = version > 1;+ const codes = v2 ? [...ERROR_CODES, 'permission_denied' as const] : ERROR_CODES;+ const notes: Record<string, string | undefined> = v2 ? { ...ERROR_NOTES,+ actor_not_attested: 'With no x-qm-actor header, acting_user is accepted only from a credential bound to a member and only naming that member (its member id or a canonical id linked to it); the call then runs exactly as the credential.',+ permission_denied: 'memory_recall named a source (source_id or source_ids) outside the credential\'s read grant; nothing was read.' } : ERROR_NOTES;return {- contract: 'gbrain.qm-memory-provider', version: 1,- transport: { protocol: 'mcp', session: 'stateless', session_header_issued: false, success_codes_in: 'structuredContent' },+ contract: 'gbrain.qm-memory-provider', version,+ transport: { protocol: 'mcp', session: 'stateless', session_header_issued: false, success_codes_in: 'structuredContent',+ ...(v2 ? { unknown_arguments: 'an argument a read tool does not declare is ignored and reported only in _meta.warnings ([{code: "unknown_param", param, suggestion?}]), never in content; a write tool refuses it with invalid_params' } : {}) },actor: {- header: ACTOR_HEADER, argument: ACTOR_ARGUMENT, argument_rule: 'optional; must equal the header; never chooses the person on its own',+ header: ACTOR_HEADER, argument: ACTOR_ARGUMENT, argument_rule: v2+ ? 'optional; on an attested call it must equal the header; with no header it is accepted only from a credential bound to a member and only naming that member (its member id or a canonical id linked to it), and the call then runs exactly as the credential; never chooses the person on its own'+ : 'optional; must equal the header; never chooses the person on its own',actor_id: { pattern: EXTERNAL_ID_RE.source, case_folding: false },system: 'qm', default_attest_ops: [...DEFAULT_ATTEST_OPS], deferred_ops: [...ACTOR_DEFERRED_OPS].sort(),audit: 'the audit trail and stored writes record the canonical external id as sent, with its linked member',},- tools: [...QM_MEMORY_OPS].sort().map(toolEntry),+ tools: [...QM_MEMORY_OPS].sort().map(name => toolEntry(name, version)),memory_recall: {limits: { max_chars: { ...MEMORY_RECALL_MAX_CHARS, whole_number: true, unit: 'UTF-16 code units (JavaScript string length)' }, query_chars_ranked: MEMORY_RECALL_QUERY_CHARS, own_recent_window_hours: OWN_RECENT_WINDOW_HOURS },arguments_checked: 'query and max_chars are checked before any read, also for an unlinked person (invalid_params)',@@ -70,6 +93,12 @@ export function buildQmMemoryContract(): Record<string, unknown> {order: ['own facts from the last ' + OWN_RECENT_WINDOW_HOURS + ' hours, newest first', 'facts the person may read, ranked by query'],ranking: 'keyword-only unless an embedding provider is configured (no embedding call on a keyless brain)',structured_content: { facts: [{ id: 'string', text: 'string', date: 'YYYY-MM-DD', kind: 'string' }], truncated: 'boolean', code: 'actor_unlinked (only on unlinked_recall)' },+ ...(v2 ? { scope_read: {+ arguments: ['source_id', 'source_ids'],+ rule: 'a call that names sources is read as their audience, never as the person: no own facts first and no member-page fact; a page restricted to named readers stays hidden; privacy is never relaxed',+ sources: 'narrowed inside the credential\'s read grant like recall\'s source_ids; a source outside it is permission_denied; source_id and source_ids together read their intersection, and an empty intersection reads nothing',+ without_sources: 'the person read above (own recent facts, then what the person may read across the read grant): use it only for the person\'s own conversations',+ } } : {}),},unlinked_recall: { isError: false, content: unlinked.content, structuredContent: unlinked.structuredContent },memory_write: {@@ -87,11 +116,11 @@ export function buildQmMemoryContract(): Record<string, unknown> {errors: {shape: { isError: true, content: 'one JSON text block with top-level code, message, suggestion and optional reason and fix', structuredContent: { error: { code: 'string', message: 'string', reason: 'string?', write_error: 'string?', fix: 'object?' } } },applies_to: 'every refusal of memory_recall and memory_write, including the transport\'s scope and unknown-tool refusals',- codes: ERROR_CODES.map(code => {+ codes: codes.map(code => {const entry: { class: string; summary: string; suggestion?: string; reasons?: readonly string[]; docs?: string } = CODES[code];return { code, class: entry.class, summary: entry.summary, ...(entry.suggestion ? { suggestion: entry.suggestion } : {}), docs: entry.docs ?? 'docs/guides/error-codes.md#' + code,- ...(code === 'actor_not_attested' ? { reasons: (entry.reasons ?? []).map(reason => ({ reason, ...ACTOR_REASON_FIXES[reason] })) } : {}),- ...(ERROR_NOTES[code] ? { note: ERROR_NOTES[code] } : {}) };+ ...(code === 'actor_not_attested' ? { reasons: (entry.reasons ?? []).map(reason => ({ reason, ...ACTOR_REASON_FIXES[reason], ...(v2 ? V2_REASON_FIXES[reason] : {}) })) } : {}),+ ...(notes[code] ? { note: notes[code] } : {}) };}),},wave_2: { audience_header: QM_AUDIENCE_HEADER, encoding: 'base64url of a JSON array of canonical ids', status: 'refused until wave 2',@@ -99,23 +128,27 @@ export function buildQmMemoryContract(): Record<string, unknown> {};}-export function renderQmMemoryContract(): string {- return JSON.stringify(buildQmMemoryContract(), null, 2) + '\n';+export function renderQmMemoryContract(version: QmContractVersion): string {+ return JSON.stringify(buildQmMemoryContract(version), null, 2) + '\n';}if (import.meta.main) {- const fresh = renderQmMemoryContract();- if (process.argv.includes('--check')) {- let current = '';- try { current = readFileSync(QM_CONTRACT_PATH, 'utf8'); } catch { /* missing */ }- if (current !== fresh) {- console.error('docs/contracts/qm-memory-provider/v1.json is stale. Run: bun scripts/build-qm-memory-contract.ts');- process.exit(1);+ let stale = false;+ for (const version of [1, 2] as const) {+ const path = QM_CONTRACT_PATHS[version];+ const fresh = renderQmMemoryContract(version);+ if (process.argv.includes('--check')) {+ let current = '';+ try { current = readFileSync(path, 'utf8'); } catch { /* missing */ }+ if (current !== fresh) {+ console.error('docs/contracts/qm-memory-provider/v' + version + '.json is stale. Run: bun scripts/build-qm-memory-contract.ts');+ stale = true;+ } else console.log('qm-memory-provider v' + version + '.json: up to date');+ } else {+ mkdirSync(dirname(path), { recursive: true });+ writeFileSync(path, fresh);+ console.log('wrote ' + path);}- console.log('qm-memory-provider v1.json: up to date');- } else {- mkdirSync(dirname(QM_CONTRACT_PATH), { recursive: true });- writeFileSync(QM_CONTRACT_PATH, fresh);- console.log('wrote ' + QM_CONTRACT_PATH);}+ if (stale) process.exit(1);}diff --git a/src/core/ops/qm-memory.ts b/src/core/ops/qm-memory.tsindex 2f9245b8ab..8c33b44f63 100644--- a/src/core/ops/qm-memory.ts+++ b/src/core/ops/qm-memory.ts@@ -19,10 +19,11 @@import { createHash } from 'node:crypto';import type { Operation, OperationContext, ParamDef } from './contract.ts';import { opError, OperationError } from './contract.ts';-import { federatedSearchScope } from './context.ts';+import { federatedSearchScope, parseSourceIdParam } from './context.ts';+import { parseSourceIdsParam, requestSourceScope, SOURCE_IDS_PARAM } from './search-source-scope.ts';import type { FactRow } from '../engine.ts';import { resolveReadEligibility } from '../eligibility/policy.ts';-import { currentCallerAccess, resolveExcludePrivatePages } from '../search/private-visibility.ts';+import { currentCallerAccess, resolveExcludePrivatePages, withCallerAccess, type CallerAccess } from '../search/private-visibility.ts';import { callerMember, memberPageSlug } from '../access/member-facts.ts';import { ACTOR_ARGUMENT, ACTOR_HEADER } from '../access/actor-model.ts';import { uuidV5 } from '../persistence/preconditions.ts';@@ -117,6 +118,49 @@ async function ownRecentFacts(ctx: OperationContext, sources: string[], read: Rereturn lists.flat().sort((a, b) => b.created_at.getTime() - a.created_at.getTime() || b.id - a.id).slice(0, MEMORY_RECALL_ARM_LIMIT);}+/**+ * GST-1094: the caller record of a recall that names sources. It is read as the scope, never as the person: no member+ * identity, actor or audience, so no member-page fact is admitted and every restricted page is hidden, and privacy is+ * never relaxed.+ */+const SCOPE_READ_ACCESS: Partial<CallerAccess> = {+ identity: [], audienceIdentities: [], audience: null, actor: null, satisfiedRuleIds: [], folderCoverage: [], privateReadableSources: [],+ hidePrivate: true, applyRemoteReadPolicy: false, restricted: true, remotePolicy: { privacyRelaxed: false, restricted: true },+};++/** The sources a recall reads and whether it names them; a named recall whose sources intersect to none reads nothing. */+async function recallSources(ctx: OperationContext, p: Record<string, unknown>): Promise<{ sources: string[]; named: boolean }> {+ const sourceIdParam = parseSourceIdParam(p.source_id, 'memory_recall');+ const sourceIds = parseSourceIdsParam(ctx, 'memory_recall', p.source_ids);+ if (sourceIdParam === undefined && sourceIds === undefined) {+ const scope = federatedSearchScope(ctx, undefined);+ return { sources: [...new Set(scope.sourceIds?.length ? scope.sourceIds : [scope.sourceId ?? ctx.sourceId ?? 'default'])], named: false };+ }+ const scope = await requestSourceScope(ctx, sourceIdParam, sourceIds);+ return { sources: [...new Set(scope.sourceIds ?? (scope.sourceId ? [scope.sourceId] : []))], named: true };+}++async function recallFacts(ctx: OperationContext, query: string, maxChars: number, sources: string[], asScope: boolean): Promise<{ facts: RecallFact[]; truncated: boolean; text: string }> {+ const remote = ctx.remote !== false;+ const read: ReadPolicy = { excludePrivate: asScope && remote ? true : await resolveExcludePrivatePages(ctx.engine, ctx.remote), eligibility: await resolveReadEligibility(ctx, {}) };+ const own = asScope || !sources.length ? [] : await ownRecentFacts(ctx, sources, read);+ const { rankFactsByQuestion } = await import('../facts/question-recall.ts');+ const ranked = query && sources.length ? (await rankFactsByQuestion(ctx, {+ question: query, params: { question: query }, factSources: sources, limit: MEMORY_RECALL_ARM_LIMIT, entity: null, sessionId: null, since: null, grep: null,+ scope: { sourceIds: sources, remote, excludePrivate: read.excludePrivate, minTrust: read.eligibility.floor, suppressFlagged: read.eligibility.suppressFlagged },+ })).rows : [];+ const seen = new Set<number>();+ const rows = [...own, ...ranked].filter(r => !seen.has(r.id) && !!seen.add(r.id));+ // The date as the database writes it: a driver's timestamp parse reads years 1-99 as 19xx.+ const written = new Map(rows.length ? (await ctx.engine.executeRaw<{ id: number | string; d: string }>(+ `SELECT id, to_char(COALESCE(valid_from, created_at) AT TIME ZONE 'UTC', 'YYYY-MM-DD') AS d FROM facts WHERE id = ANY($1::bigint[])`, [rows.map(r => r.id)])).map(r => [Number(r.id), r.d]) : []);+ const plain = rows.map(r => ({ id: String(r.id), text: plainFactText(r.fact), date: isoDate(written.get(Number(r.id)) ?? r.valid_from ?? r.created_at), kind: String(r.kind) }));+ const { redactRetrievalOutput } = await import('../search/output-redaction.ts');+ const facts: RecallFact[] = (remote ? redactRetrievalOutput(plain, {}, { uncapped: true }).results : plain).filter(f => f.text);+ const { kept, text } = boundFactLines(facts.map(f => `- ${f.text} (${f.date}; ${f.kind})`), maxChars);+ return { facts: facts.slice(0, kept), truncated: kept < facts.length, text };+}+const memory_recall: Operation = {name: 'memory_recall',mutating: false,@@ -127,30 +171,16 @@ const memory_recall: Operation = {query: { type: 'string', required: true, description: 'What the turn is about; ranks the facts.' },max_chars: { type: 'integer', description: `Text cap in UTF-16 code units, ${MEMORY_RECALL_MAX_CHARS.min}-${MEMORY_RECALL_MAX_CHARS.max} (default ${MEMORY_RECALL_MAX_CHARS.default}).` },[ACTOR_ARGUMENT]: actorParam,+ source_id: { type: 'string', description: 'Read this one source as its audience (a shared scope): never the person\'s own facts.' },+ source_ids: { ...SOURCE_IDS_PARAM, description: 'Read only these sources as their audience (a shared scope): never the person\'s own facts.' },},scope: 'read',annotations: { title: 'memory_recall (QM memory read)', readOnlyHint: true },handler: async (ctx, p) => {const { query, maxChars } = recallArguments(p);- const scope = federatedSearchScope(ctx, undefined);- const sources = [...new Set(scope.sourceIds?.length ? scope.sourceIds : [scope.sourceId ?? ctx.sourceId ?? 'default'])];- const read: ReadPolicy = { excludePrivate: await resolveExcludePrivatePages(ctx.engine, ctx.remote), eligibility: await resolveReadEligibility(ctx, {}) };- const own = await ownRecentFacts(ctx, sources, read);- const { rankFactsByQuestion } = await import('../facts/question-recall.ts');- const ranked = query ? (await rankFactsByQuestion(ctx, {- question: query, params: { question: query }, factSources: sources, limit: MEMORY_RECALL_ARM_LIMIT, entity: null, sessionId: null, since: null, grep: null,- scope: { sourceIds: sources, remote: ctx.remote !== false, excludePrivate: read.excludePrivate, minTrust: read.eligibility.floor, suppressFlagged: read.eligibility.suppressFlagged },- })).rows : [];- const seen = new Set<number>();- const rows = [...own, ...ranked].filter(r => !seen.has(r.id) && !!seen.add(r.id));- // The date as the database writes it: a driver's timestamp parse reads years 1-99 as 19xx.- const written = new Map(rows.length ? (await ctx.engine.executeRaw<{ id: number | string; d: string }>(- `SELECT id, to_char(COALESCE(valid_from, created_at) AT TIME ZONE 'UTC', 'YYYY-MM-DD') AS d FROM facts WHERE id = ANY($1::bigint[])`, [rows.map(r => r.id)])).map(r => [Number(r.id), r.d]) : []);- const plain = rows.map(r => ({ id: String(r.id), text: plainFactText(r.fact), date: isoDate(written.get(Number(r.id)) ?? r.valid_from ?? r.created_at), kind: String(r.kind) }));- const { redactRetrievalOutput } = await import('../search/output-redaction.ts');- const facts: RecallFact[] = (ctx.remote === false ? plain : redactRetrievalOutput(plain, {}, { uncapped: true }).results).filter(f => f.text);- const { kept, text } = boundFactLines(facts.map(f => `- ${f.text} (${f.date}; ${f.kind})`), maxChars);- return { facts: facts.slice(0, kept), truncated: kept < facts.length, text };+ const { sources, named } = await recallSources(ctx, p);+ if (!named || ctx.remote === false) return recallFacts(ctx, query, maxChars, sources, named);+ return withCallerAccess(SCOPE_READ_ACCESS, () => recallFacts(ctx, query, maxChars, sources, true));},};diff --git a/src/core/ops/search-source-scope.ts b/src/core/ops/search-source-scope.tsindex e30b94c980..49b50a74cd 100644--- a/src/core/ops/search-source-scope.ts+++ b/src/core/ops/search-source-scope.ts@@ -26,7 +26,7 @@ export const SOURCE_IDS_PARAM = {};/** `source_ids` as distinct, trimmed source ids; undefined when absent. */-export function parseSourceIdsParam(ctx: OperationContext, tool: 'search' | 'query' | 'recall' | 'list_pages', raw: unknown): string[] | undefined {+export function parseSourceIdsParam(ctx: OperationContext, tool: 'search' | 'query' | 'recall' | 'list_pages' | 'memory_recall', raw: unknown): string[] | undefined {if (raw === undefined || raw === null) return undefined;// #5390: OpenAI-family MCP clients fill every optional param with an empty value; [] and a blank string mean absent.if (Array.isArray(raw) && raw.length === 0) return undefined;diff --git a/test/qm-memory-contract.test.ts b/test/qm-memory-contract.test.tsindex 8f80628ae1..a02dba7e03 100644--- a/test/qm-memory-contract.test.ts+++ b/test/qm-memory-contract.test.ts@@ -1,5 +1,5 @@/**- * GST-359 D: the QM memory-provider contract fixture (docs/contracts/qm-memory-provider/v1.json).+ * GST-359 D: the QM memory-provider contract fixtures (docs/contracts/qm-memory-provider/v1.json and v2.json).** 1. Protects: the committed fixture QM vendors equals what the live registry, actor model and error registry produce,* and it pins the r3 contract values (actor id pattern, stateless session, success codes in structuredContent).@@ -9,18 +9,30 @@* 4. Real seams: the operation registry and paramDefToSchema (the served tool schema); no engine.*/import { describe, expect, test } from 'bun:test';+import { createHash } from 'node:crypto';import { readFileSync } from 'node:fs';-import { ACTOR_REASON_FIXES, QM_CONTRACT_PATH, renderQmMemoryContract } from '../scripts/build-qm-memory-contract.ts';+import { ACTOR_REASON_FIXES, QM_CONTRACT_PATH, QM_CONTRACT_PATHS, renderQmMemoryContract } from '../scripts/build-qm-memory-contract.ts';import { CODES } from '../src/core/error-registry.ts';import { operations } from '../src/core/operations.ts';import { buildToolDefs } from '../src/mcp/tool-defs.ts';import { unlinkedRecallResult } from '../src/core/ops/qm-memory.ts';+/** The v1 bytes QM vendored for the 11-06 tag (GBRA-108, GST-359): v1 never changes while QM depends on it. */+const V1_SHA256 = 'c80a7a5f8133f875ef90a2b5052a53c4d2bb0ab95facfa3975ba626c00daae78';+describe('QM memory-provider contract v1', () => {const fixture = JSON.parse(readFileSync(QM_CONTRACT_PATH, 'utf8'));test('the committed fixture matches the live registry (regenerate with bun scripts/build-qm-memory-contract.ts)', () => {- expect(readFileSync(QM_CONTRACT_PATH, 'utf8')).toBe(renderQmMemoryContract());+ expect(readFileSync(QM_CONTRACT_PATH, 'utf8')).toBe(renderQmMemoryContract(1));+ });++ test('v1 is frozen byte for byte at the vendored sha256, on disk and as the builder renders it', () => {+ expect(createHash('sha256').update(readFileSync(QM_CONTRACT_PATH)).digest('hex')).toBe(V1_SHA256);+ expect(createHash('sha256').update(renderQmMemoryContract(1)).digest('hex')).toBe(V1_SHA256);+ const recall = fixture.tools.find((t: { name: string }) => t.name === 'memory_recall');+ expect(Object.keys(recall.input_schema.properties).sort()).toEqual(['acting_user', 'max_chars', 'query']);+ expect(fixture.memory_recall.scope_read).toBeUndefined();});test('it pins the r3 contract values', () => {@@ -41,11 +53,12 @@ describe('QM memory-provider contract v1', () => {expect(fixture.actor.deferred_ops).not.toContain('forget_fact');});- test('the tool schemas are the ones MCP serves', () => {+ test('v1 tool schemas are the served ones restricted to v1\'s arguments', () => {const served = buildToolDefs(operations.filter(o => o.name === 'memory_recall' || o.name === 'memory_write'));for (const tool of fixture.tools) {const def = served.find(d => d.name === tool.name)!;- expect({ description: tool.description, ...tool.input_schema }).toEqual({ description: def.description, ...def.inputSchema });+ const properties = Object.fromEntries(Object.entries(def.inputSchema.properties as Record<string, unknown>).filter(([k]) => k in tool.input_schema.properties));+ expect({ description: tool.description, ...tool.input_schema }).toEqual({ description: def.description, ...def.inputSchema, properties });}});@@ -56,3 +69,35 @@ describe('QM memory-provider contract v1', () => {for (const c of fixture.errors.codes) expect(CODES[c.code as keyof typeof CODES]).toBeDefined();});});++describe('QM memory-provider contract v2 (GST-1094 scope read, GST-900)', () => {+ const fixture = JSON.parse(readFileSync(QM_CONTRACT_PATHS[2], 'utf8'));++ test('the committed fixture matches the live registry (regenerate with bun scripts/build-qm-memory-contract.ts)', () => {+ expect(readFileSync(QM_CONTRACT_PATHS[2], 'utf8')).toBe(renderQmMemoryContract(2));+ });++ test('the tool schemas are the ones MCP serves', () => {+ const served = buildToolDefs(operations.filter(o => o.name === 'memory_recall' || o.name === 'memory_write'));+ for (const tool of fixture.tools) {+ const def = served.find(d => d.name === tool.name)!;+ expect({ description: tool.description, ...tool.input_schema }).toEqual({ description: def.description, ...def.inputSchema });+ }+ });++ test('it publishes the scope read, the member-bound acting_user rule and _meta-only unknown arguments', () => {+ expect(fixture.version).toBe(2);+ const recall = fixture.tools.find((t: { name: string }) => t.name === 'memory_recall');+ expect(recall.input_schema.properties.source_id.type).toBe('string');+ expect(recall.input_schema.properties.source_ids.type).toBe('array');+ expect(recall.input_schema.required).toEqual(['query']);+ expect(fixture.memory_recall.scope_read.arguments).toEqual(['source_id', 'source_ids']);+ expect(fixture.memory_recall.scope_read.rule).toContain('never as the person');+ expect(fixture.transport.unknown_arguments).toContain('_meta.warnings');+ expect(fixture.actor.argument_rule).toContain('bound to a member');+ expect(fixture.errors.codes.map((c: { code: string }) => c.code)).toContain('permission_denied');+ const v1 = JSON.parse(readFileSync(QM_CONTRACT_PATH, 'utf8'));+ expect(fixture.wave_2).toEqual(v1.wave_2);+ expect(fixture.memory_write).toEqual(v1.memory_write);+ });+});diff --git a/test/qm-memory-tools.test.ts b/test/qm-memory-tools.test.tsindex 096aa9f870..c83dad1ba4 100644--- a/test/qm-memory-tools.test.ts+++ b/test/qm-memory-tools.test.ts@@ -392,6 +392,46 @@ for (const kind of testBackends()) {}}, 120_000);+ test('a recall that names sources reads as the scope, never as the person: none of their own member-page facts (GST-1094)', async () => {+ const SCOPE = 'qm-scope-room';+ await engine.executeRaw('INSERT INTO sources (id, name) VALUES ($1, $1) ON CONFLICT (id) DO NOTHING', [SCOPE]);+ const c = await provider().registerClientManual('d-scope-' + randomUUID().slice(0, 8), ['client_credentials'], 'read write', [], SRC);+ await provider().rescopeClient(c.clientId, { federatedRead: [SRC, SCOPE] });+ await bindCredential(engine, { kind: 'client', id: c.clientId }, { attestActor: 'qm' });+ tokens.scoped = (await provider().exchangeClientCredentials(c.clientId, c.clientSecret ?? '')).access_token;+ const aliceScoped: Who = { token: 'scoped', actor: ALICE_ID };+ expect((await write(aliceScoped, [{ fact: 'Alice keeps her seat preference canaryscopeown budget ledger', provenance: 'turn 40' }])).structured?.status).toBe('committed');+ const restricted = 'notes/alice-only-scope';+ await importFromContent(engine, restricted, '---\ntype: note\ntitle: Alice only\nreadable_by:\n - member:alice-example\n---\n# Alice only\n', { sourceId: SRC });+ await engine.insertFact({ fact: 'Alice salary review canaryscoperestricted budget ledger', kind: 'fact', entity_slug: ACME, source: 'test', visibility: 'world' }, { source_id: SRC });+ await engine.executeRaw('UPDATE facts SET source_markdown_slug = $1 WHERE fact LIKE $2', [restricted, '%canaryscoperestricted%']);+ await engine.insertFact({ fact: 'The room budget ledger review is Friday canaryscoperoom', kind: 'event', entity_slug: null, source: 'test', visibility: 'world' }, { source_id: SCOPE });+ await engine.insertFact({ fact: 'Acme budget ledger audit is open canaryscopeworld', kind: 'event', entity_slug: ACME, source: 'test', visibility: 'world' }, { source_id: SRC });+ __resetPrivateVisibilityCacheForTests();+ const asPerson = await recall(aliceScoped, 'budget ledger', { max_chars: 12_000 });+ for (const needle of ['canaryscopeown', 'canaryscopeworld', 'canaryscoperoom']) expect(asPerson.text).toContain(needle);+ expect(asPerson.all).not.toContain('canaryscoperestricted');+ for (const args of [{ source_id: SRC }, { source_ids: [SRC] }, { source_ids: [SRC, SCOPE] }]) {+ const asScope = await recall(aliceScoped, 'budget ledger', { max_chars: 12_000, ...args });+ expect(asScope.isError).toBe(false);+ expect(asScope.text).toContain('canaryscopeworld');+ for (const needle of ['canaryscopeown', 'canaryscoperestricted', 'canarywritealice', 'canaryownrecent']) expect(asScope.all).not.toContain(needle);+ expect(JSON.stringify(asScope.out._meta?.warnings ?? [])).not.toContain('unknown_param');+ }+ const room = await recall(aliceScoped, 'budget ledger', { source_ids: [SCOPE] });+ expect(room.text).toContain('canaryscoperoom');+ for (const needle of ['canaryscopeworld', 'canaryscopeown', 'canaryscoperestricted']) expect(room.all).not.toContain(needle);+ const outside = await recall(alice, 'budget ledger', { source_ids: [SCOPE] });+ expect({ isError: outside.isError, code: outside.json.code }).toEqual({ isError: true, code: 'permission_denied' });+ expect(outside.structured?.error?.code).toBe('permission_denied');+ const all = await recall(aliceScoped, 'budget ledger', { source_id: '__all__' });+ expect({ isError: all.isError, code: all.json.code }).toEqual({ isError: true, code: 'invalid_params' });+ const none = await recall(aliceScoped, 'budget ledger', { source_id: SCOPE, source_ids: [SRC] });+ expect({ isError: none.isError, text: none.text, facts: none.structured?.facts }).toEqual({ isError: false, text: '', facts: [] });+ const unlinked = await recall({ token: 'scoped', actor: 'U0NOBODY' }, 'budget ledger', { source_ids: [SCOPE] });+ expect(unlinked.structured).toEqual({ facts: [], truncated: false, code: 'actor_unlinked' });+ }, 120_000);+test('an unlinked person gets an empty success whose code rides structuredContent only', async () => {const out = await recall({ token: 'qm', actor: 'U0NOBODY' }, 'budget ledger');expect(out.isError).toBe(false);