Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

GST-359 D: QM memory-provider contract v1 fixture, squatted-page memory_write case, regenerated tools-json golden

garrytan31176f6395dc
diff --git a/docs/contracts/qm-memory-provider/v1.json b/docs/contracts/qm-memory-provider/v1.json
new file mode 100644
index 0000000000..e435d2259d
--- /dev/null
+++ b/docs/contracts/qm-memory-provider/v1.json
@@ -0,0 +1,329 @@
+{
+ "contract": "gbrain.qm-memory-provider",
+ "version": 1,
+ "transport": {
+ "protocol": "mcp",
+ "session": "stateless",
+ "session_header_issued": false,
+ "success_codes_in": "structuredContent"
+ },
+ "actor": {
+ "header": "x-qm-actor",
+ "argument": "acting_user",
+ "argument_rule": "optional; must equal the header; never chooses the person on its own",
+ "actor_id": {
+ "pattern": "^[\\x21-\\x7e]{1,256}$",
+ "case_folding": false
+ },
+ "system": "qm",
+ "default_attest_ops": [
+ "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": "number",
+ "description": "Text cap, 200-12000 (default 6000)."
+ },
+ "acting_user": {
+ "type": "string",
+ "description": "Set by the trusted system: equal to the x-qm-actor header, or omit."
+ }
+ },
+ "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
+ },
+ "query_chars_ranked": 2000,
+ "own_recent_window_hours": 24
+ },
+ "content": {
+ "line": "- <fact> (<YYYY-MM-DD>; <kind>)",
+ "truncated_tail": "… <N> more",
+ "never": [
+ "page bodies",
+ "fence markers",
+ "heading markers"
+ ],
+ "bounded_by": "max_chars, cut at a line boundary"
+ },
+ "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)"
+ }
+ },
+ "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": "^[\\x21-\\x7e]{1,128}$",
+ "kinds": [
+ "event",
+ "preference",
+ "commitment",
+ "belief",
+ "fact"
+ ]
+ },
+ "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"
+ ]
+ }
+ },
+ "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?",
+ "fix": "object?"
+ }
+ }
+ },
+ "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. 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 and actor_required 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, 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."
+ },
+ {
+ "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."
+ }
+ ]
+ },
+ {
+ "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"
+ },
+ {
+ "code": "rate_limited",
+ "class": "retryable",
+ "summary": "The request was rate-limited; retry after the stated delay.",
+ "docs": "docs/guides/error-codes.md#rate_limited"
+ }
+ ]
+ },
+ "wave_2": {
+ "audience_header": "x-qm-audience",
+ "encoding": "base64url of a JSON array of canonical ids",
+ "status": "reserved; not honoured yet"
+ }
+}
diff --git a/scripts/build-qm-memory-contract.ts b/scripts/build-qm-memory-contract.ts
new file mode 100644
index 0000000000..26f7c926ce
--- /dev/null
+++ b/scripts/build-qm-memory-contract.ts
@@ -0,0 +1,109 @@
+#!/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.
+ */
+import { readFileSync, writeFileSync, mkdirSync } from 'node:fs';
+import { dirname, join } from 'node:path';
+import { operations } from '../src/core/operations.ts';
+import { paramDefToSchema } from '../src/mcp/tool-defs.ts';
+import { CODES } from '../src/core/error-registry.ts';
+import { ACTOR_ARGUMENT, ACTOR_DEFERRED_OPS, ACTOR_HEADER, DEFAULT_ATTEST_OPS, EXTERNAL_ID_RE } 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');
+
+/** 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 }> = {
+ 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.' },
+ 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.' },
+ argument_mismatch: { fixed_by: 'calling_harness', fix: 'Send acting_user equal to the x-qm-actor header, 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.' },
+ invalid_actor_id: { fixed_by: 'calling_harness', fix: 'Send the canonical id unchanged: 1-256 visible ASCII characters, no spaces.' },
+ 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.' },
+};
+
+const ERROR_CODES = ['actor_not_attested', 'actor_unlinked', 'on_behalf_of_invalid_audience', 'invalid_params', 'scope_denied', 'insufficient_scope', 'rate_limited'] as const;
+
+const ERROR_NOTES: Partial<Record<typeof ERROR_CODES[number], string>> = {
+ actor_unlinked: 'Refuses memory_write. memory_recall answers it as a success instead (unlinked_recall).',
+ on_behalf_of_invalid_audience: '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.',
+ invalid_params: '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.',
+ scope_denied: 'The write is not authorized, including a member page whose readers name anyone but its member (squatted or widened): nothing is saved.',
+};
+
+function toolEntry(name: string) {
+ const op = operations.find(o => o.name === name);
+ if (!op) throw new Error(name + ' is not in the operation registry');
+ 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) },
+ };
+}
+
+export function buildQmMemoryContract(): Record<string, unknown> {
+ const unlinked = unlinkedRecallResult();
+ return {
+ contract: 'gbrain.qm-memory-provider', version: 1,
+ transport: { protocol: 'mcp', session: 'stateless', session_header_issued: false, success_codes_in: 'structuredContent' },
+ actor: {
+ header: ACTOR_HEADER, argument: ACTOR_ARGUMENT, argument_rule: '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),
+ memory_recall: {
+ limits: { max_chars: { ...MEMORY_RECALL_MAX_CHARS, whole_number: true }, query_chars_ranked: MEMORY_RECALL_QUERY_CHARS, own_recent_window_hours: OWN_RECENT_WINDOW_HOURS },
+ content: { line: '- <fact> (<YYYY-MM-DD>; <kind>)', truncated_tail: '… <N> more', never: ['page bodies', 'fence markers', 'heading markers'], bounded_by: 'max_chars, cut at a line boundary' },
+ 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)' },
+ },
+ unlinked_recall: { isError: false, content: unlinked.content, structuredContent: unlinked.structuredContent },
+ memory_write: {
+ limits: { facts: { min: 1, max: MEMORY_WRITE_MAX_FACTS }, provenance_chars: MEMORY_WRITE_PROVENANCE_MAX, idempotency_key: IDEMPOTENCY_KEY_RE.source, kinds: [...MEMORY_WRITE_KINDS] },
+ 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'] } },
+ 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?', fix: 'object?' } } },
+ codes: ERROR_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] } : {}) };
+ }),
+ },
+ wave_2: { audience_header: 'x-qm-audience', encoding: 'base64url of a JSON array of canonical ids', status: 'reserved; not honoured yet' },
+ };
+}
+
+export function renderQmMemoryContract(): string {
+ return JSON.stringify(buildQmMemoryContract(), 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);
+ }
+ 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);
+ }
+}
diff --git a/scripts/regen-all.ts b/scripts/regen-all.ts
index a19a19d621..b3bc28a869 100644
--- a/scripts/regen-all.ts
+++ b/scripts/regen-all.ts
@@ -49,6 +49,7 @@ export const ARTIFACTS: Artifact[] = [
{ name: 'CLI flag registry', regen: ['bun', 'run', 'scripts/generate-flag-registry.ts'], check: [...BUN_TEST, 'test/generate-flag-registry.test.ts'] },
{ name: 'plugin tree + persona variants', regen: ['bun', 'run', 'scripts/generate-plugin-tree.ts', '--out', 'plugin', '--variants-out', 'plugin-variants'], check: ['bash', 'scripts/check-plugin-tree.sh'] },
{ name: 'structural suites manifest', regen: ['bun', 'scripts/classify-tests.ts'], check: ['bun', 'scripts/classify-tests.ts', '--check'] },
+ { name: 'QM memory-provider contract', regen: ['bun', 'scripts/build-qm-memory-contract.ts'], check: ['bun', 'scripts/build-qm-memory-contract.ts', '--check'] },
{ name: 'llms.txt + llms-full.txt', regen: ['bun', 'run', 'scripts/build-llms.ts'], check: [...BUN_TEST, 'test/build-llms.test.ts'] },
];
diff --git a/test/fixtures/goldens/cli/tools-json.json b/test/fixtures/goldens/cli/tools-json.json
index 258c9c0361..574440e5f5 100644
--- a/test/fixtures/goldens/cli/tools-json.json
+++ b/test/fixtures/goldens/cli/tools-json.json
@@ -2,8 +2,8 @@
"golden": {
"exitCode": 0,
"stderr": "",
- "stdoutBytes": 264563,
- "stdoutSha256": "0d71d7f1367627c5f9c27d3d7a9b09513131117000012eed0d35ab9ede69095f",
+ "stdoutBytes": 267537,
+ "stdoutSha256": "a8833d13e72c68b0bbae9ab86c55ab9ab2d870e31fa28dc835bef295152005e9",
"toolNames": [
"remember",
"entity",
@@ -156,6 +156,8 @@
"purge_fact",
"list_page_purges",
"unpurge_page",
+ "memory_recall",
+ "memory_write",
"find_contradictions",
"find_experts",
"find_trajectory",
@@ -7089,6 +7091,108 @@
},
"scope": "admin"
},
+ {
+ "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.",
+ "idempotent": true,
+ "local_only": false,
+ "mutating": false,
+ "name": "memory_recall",
+ "parameters": {
+ "acting_user": "string?",
+ "max_chars": "number?",
+ "query": "string"
+ },
+ "required_scopes": [],
+ "schema": {
+ "properties": {
+ "acting_user": {
+ "description": "Set by the trusted system: equal to the x-qm-actor header, or omit.",
+ "type": "string"
+ },
+ "max_chars": {
+ "description": "Text cap, 200-12000 (default 6000).",
+ "type": "number"
+ },
+ "query": {
+ "description": "What the turn is about; ranks the facts.",
+ "type": "string"
+ }
+ },
+ "required": [
+ "query"
+ ],
+ "type": "object"
+ },
+ "scope": "read"
+ },
+ {
+ "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.",
+ "idempotent": true,
+ "local_only": false,
+ "mutating": true,
+ "name": "memory_write",
+ "parameters": {
+ "acting_user": "string?",
+ "facts": "array",
+ "idempotency_key": "string"
+ },
+ "required_scopes": [],
+ "schema": {
+ "properties": {
+ "acting_user": {
+ "description": "Set by the trusted system: equal to the x-qm-actor header, or omit.",
+ "type": "string"
+ },
+ "facts": {
+ "description": "1-20 facts.",
+ "items": {
+ "additionalProperties": false,
+ "properties": {
+ "fact": {
+ "description": "One claim.",
+ "type": "string"
+ },
+ "kind": {
+ "description": "Default fact.",
+ "enum": [
+ "event",
+ "preference",
+ "commitment",
+ "belief",
+ "fact"
+ ],
+ "type": "string"
+ },
+ "provenance": {
+ "description": "Where it came from (<=200 chars).",
+ "type": "string"
+ },
+ "valid_from": {
+ "description": "When it became true (ISO 8601).",
+ "type": "string"
+ }
+ },
+ "required": [
+ "fact",
+ "provenance"
+ ],
+ "type": "object"
+ },
+ "type": "array"
+ },
+ "idempotency_key": {
+ "description": "1-128 visible ASCII characters; the same key replays this write.",
+ "type": "string"
+ }
+ },
+ "required": [
+ "facts",
+ "idempotency_key"
+ ],
+ "type": "object"
+ },
+ "scope": "write"
+ },
{
"description": "Return suspected-contradiction findings from the most recent `gbrain eval suspected-contradictions` probe run, optionally filtered by slug and/or severity. Use this when the user asks 'what's inconsistent in my brain', 'show me contradictions about Acme', 'high-severity issues only', or wants to act on the probe's findings without re-running it. Returns {contradictions: [{a, b, severity, axis, confidence, resolution_command}]}. Remote, source-scoped or min_trust callers get only findings whose two sides they can read now (each side re-read live, with source_id, trust_tier and origin) and total_visible instead of the run total. Reads the stored run without triggering a new probe; users run `gbrain eval suspected-contradictions` for that.",
"idempotent": true,
diff --git a/test/qm-memory-contract.test.ts b/test/qm-memory-contract.test.ts
new file mode 100644
index 0000000000..71fcfcf440
--- /dev/null
+++ b/test/qm-memory-contract.test.ts
@@ -0,0 +1,52 @@
+/**
+ * GST-359 D: the QM memory-provider contract fixture (docs/contracts/qm-memory-provider/v1.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).
+ * 2. Fails when: a tool's arguments, a limit, an error code or reason, the header or the deferred list changes without
+ * regenerating the fixture, or an actor_not_attested reason has no fix row.
+ * 3. Existing coverage: none; test/qm-memory-tools.test.ts pins the behaviour the fixture describes.
+ * 4. Real seams: the operation registry and paramDefToSchema (the served tool schema); no engine.
+ */
+import { describe, expect, test } from 'bun:test';
+import { readFileSync } from 'node:fs';
+import { ACTOR_REASON_FIXES, QM_CONTRACT_PATH, 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';
+
+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());
+ });
+
+ test('it pins the r3 contract values', () => {
+ expect(fixture.actor.header).toBe('x-qm-actor');
+ expect(fixture.actor.actor_id.pattern).toBe('^[\\x21-\\x7e]{1,256}$');
+ expect(fixture.transport).toMatchObject({ session: 'stateless', success_codes_in: 'structuredContent' });
+ expect(fixture.unlinked_recall).toEqual({ isError: false, ...unlinkedRecallResult() });
+ expect(fixture.unlinked_recall.structuredContent).toEqual({ facts: [], truncated: false, code: 'actor_unlinked' });
+ expect(fixture.memory_recall.limits.max_chars).toEqual({ min: 200, max: 12000, default: 6000, whole_number: true });
+ expect(fixture.memory_write.limits.facts).toEqual({ min: 1, max: 20 });
+ expect(fixture.actor.deferred_ops).not.toContain('forget');
+ expect(fixture.actor.deferred_ops).not.toContain('forget_fact');
+ });
+
+ 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('every actor_not_attested reason carries its fix, and every listed code is registered', () => {
+ expect(Object.keys(ACTOR_REASON_FIXES).sort()).toEqual([...(CODES.actor_not_attested.reasons ?? [])].sort());
+ const attested = fixture.errors.codes.find((c: { code: string }) => c.code === 'actor_not_attested');
+ for (const r of attested.reasons) expect(r.fix.length).toBeGreaterThan(10);
+ for (const c of fixture.errors.codes) expect(CODES[c.code as keyof typeof CODES]).toBeDefined();
+ });
+});
diff --git a/test/qm-memory-tools.test.ts b/test/qm-memory-tools.test.ts
index 27ab087e63..be9632959c 100644
--- a/test/qm-memory-tools.test.ts
+++ b/test/qm-memory-tools.test.ts
@@ -95,6 +95,7 @@ const SRC = 'qm-memory';
const ALICE_ID = 'U0ALICE';
const BOB_ID = 'oidc:3f2a:bob-example';
const CAROL_ID = '[email protected]';
+const DAVE_ID = 'U0DAVE';
const ACME = 'companies/acme-example';
const ATTEST_OPS = ['forget', 'forget_fact', 'get_write_request', 'memory_recall', 'memory_write', 'remember'];
@@ -135,7 +136,7 @@ for (const kind of testBackends()) {
__resetPrivateVisibilityCacheForTests();
__resetHotMemoryCacheForTests();
await engine.executeRaw('INSERT INTO sources (id, name) VALUES ($1, $1) ON CONFLICT (id) DO NOTHING', [SRC]);
- for (const id of ['alice-example', 'bob-example', 'carol-example']) await addMember(engine, id);
+ for (const id of ['alice-example', 'bob-example', 'carol-example', 'dave-example']) await addMember(engine, id);
await importFromContent(engine, ACME, '---\ntype: company\ntitle: Acme Example\n---\n# Acme Example\n\nAcme example harbor ledger canarypagebody budget notes.', { sourceId: SRC });
const register = async (name: string) => {
const c = await provider().registerClientManual('d-' + name + '-' + randomUUID().slice(0, 8), ['client_credentials'], 'read write', [], SRC);
@@ -150,6 +151,7 @@ for (const kind of testBackends()) {
await linkMember(engine, 'alice-example', 'qm', ALICE_ID);
await linkMember(engine, 'bob-example', 'qm', BOB_ID);
await linkMember(engine, 'carol-example', 'qm', CAROL_ID);
+ await linkMember(engine, 'dave-example', 'qm', DAVE_ID);
}, 120_000);
afterAll(async () => {
@@ -220,6 +222,18 @@ for (const kind of testBackends()) {
expect(named.structured!.status).toBe('committed');
}, 60_000);
+ test('a squatted member page (readers beyond its member) takes no memory_write, and its receipt is not left behind', async () => {
+ const dave: Who = { token: 'qm', actor: DAVE_ID };
+ const squat = '---\ntype: note\ntitle: Memory of dave-example\nreadable_by:\n - member:bob-example\n - member:dave-example\n---\n# Memory of dave-example\n';
+ await importFromContent(engine, 'memory/members/dave-example', squat, { sourceId: SRC });
+ const key = randomUUID();
+ const out = await write(dave, [{ fact: 'Dave keeps the harbor ledger key canarydavesquat', provenance: 'turn 5' }], key);
+ expect({ isError: out.isError, code: out.json.code, message: out.json.message }).toMatchObject({ isError: true, code: 'scope_denied', message: expect.stringContaining('does not name its member alone') });
+ expect(await factRows('canarydavesquat')).toHaveLength(0);
+ expect((await call(dave, 'get_write_request', { request_id: await memoryWriteRequestId('dave-example', key, 0) })).json.code).toBe('not_found');
+ expect((await recall(bob, 'harbor ledger key')).all).not.toContain('canarydavesquat');
+ }, 60_000);
+
test('invalid facts and keys are refused before anything is saved', async () => {
const bad: Array<Record<string, unknown>> = [
{ facts: [], idempotency_key: 'k1' },
@@ -253,8 +267,10 @@ for (const kind of testBackends()) {
}, 60_000);
test('recall leads with the person\'s own recent facts, then readable facts ranked by the query, never another member\'s or a page body', async () => {
- await write(alice, [{ fact: 'Alice moved standup to Tuesdays canaryownrecent', provenance: 'turn 2' }]);
- await write(alice, [{ fact: 'Alice owns the budget ledger review canaryownold', provenance: 'turn 0' }]);
+ for (const [fact, provenance] of [['Alice moved standup to Tuesdays canaryownrecent', 'turn 2'], ['Alice owns the budget ledger review canaryownold', 'turn 0']]) {
+ const saved = await write(alice, [{ fact, provenance }]);
+ expect(saved.structured?.status ?? saved.text).toBe('committed');
+ }
await engine.executeRaw("UPDATE facts SET created_at = now() - interval '3 days', valid_from = now() - interval '3 days' WHERE source_id = $1 AND fact LIKE '%canaryownold%'", [SRC]);
await write(bob, [{ fact: 'Bob audits the budget ledger canarybobonly', provenance: 'turn 3' }]);
await engine.insertFact({ fact: 'Acme budget ledger closes in March canaryworld', kind: 'event', entity_slug: ACME, source: 'test', visibility: 'world' }, { source_id: SRC });