Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

GST-359 D: memory_recall and memory_write for QM's attested person

garrytane50939f2b8f8
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.md
index d4780b10a0..789f887692 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -165,9 +165,9 @@ More: [docs/guides/write-refusals.md#access_rule_invalid](../../docs/guides/writ
| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
|---|---|---|---|---|---|---|
-| 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. Nothing was read or written. | Naming a person decides whose notes are read and written as; only a credential the brain operator granted the attest right may do it, only for the operations it lists, and text in a conversation never chooses it. | 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 and invalid_actor_id are fixed in the calling harness. | user | `gbrain doctor --json` | 1 | no |
+| 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. | Naming a person decides whose notes are read and written as; only a credential the brain operator granted the attest right may do it, only for the operations it lists, and text in a conversation never chooses it. | 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. | user | `gbrain doctor --json` | 1 | no |
-Reasons: `no_attest_right`, `op_not_attested`, `argument_mismatch`, `argument_without_attestation`, `invalid_actor_id`.
+Reasons: `no_attest_right`, `op_not_attested`, `argument_mismatch`, `argument_without_attestation`, `invalid_actor_id`, `actor_required`.
More: [docs/guides/write-refusals.md#actor_not_attested](../../docs/guides/write-refusals.md#actor_not_attested)
diff --git a/src/core/access/actor.ts b/src/core/access/actor.ts
index d9c049048e..473c0a4a41 100644
--- a/src/core/access/actor.ts
+++ b/src/core/access/actor.ts
@@ -28,7 +28,7 @@ const ATTESTABLE_SCOPES = new Set(['read', 'write', 'agent']);
-export type ActorReason = 'no_attest_right' | 'op_not_attested' | 'argument_mismatch' | 'argument_without_attestation' | 'invalid_actor_id';
+export type ActorReason = 'no_attest_right' | 'op_not_attested' | 'argument_mismatch' | 'argument_without_attestation' | 'invalid_actor_id' | 'actor_required';
/** The operation metadata attestability reads (a subset of Operation, so this module never imports the registry). */
export interface AttestableOpShape { scope?: string; requiredScopes?: readonly string[]; localOnly?: boolean; cliOnly?: unknown }
@@ -124,6 +124,9 @@ export function actorNotAttested(reason: ActorReason, caller: ActorCaller, ctx:
case 'argument_without_attestation':
return opError('actor_not_attested', `The ${ACTOR_ARGUMENT} argument is accepted only on an attested call, so nothing was read or written.`,
`Remove ${ACTOR_ARGUMENT} from the arguments. A trusted system names the person in the ${ACTOR_HEADER} header from a credential holding the attest right (gbrain auth rescope ... --attest-actor qm on the brain host).`, { reason, docs });
+ case 'actor_required':
+ return opError('actor_not_attested', `${ctx.op} writes only as an attested person, and this call names none (no ${ACTOR_HEADER} header on a credential holding the attest right), so nothing was written.`,
+ `Send ${ACTOR_HEADER} with the person's canonical id from a credential the brain operator granted the attest right (gbrain auth rescope --client <id> --attest-actor qm). To save a fact as yourself, call remember.`, { reason, docs });
case 'invalid_actor_id':
return opError('actor_not_attested', `The ${ACTOR_HEADER} header or the ${ACTOR_ARGUMENT} argument is not a canonical person id (1-256 visible ASCII characters), so nothing was read or written.`,
'Fix the harness code that sets the header: send the canonical id unchanged, with no spaces or control characters.', { reason, docs });
diff --git a/src/core/engine-sql/facts.ts b/src/core/engine-sql/facts.ts
index 0e1e997b05..b89251582c 100644
--- a/src/core/engine-sql/facts.ts
+++ b/src/core/engine-sql/facts.ts
@@ -73,12 +73,13 @@ function grepPattern(opts: FactListOpts | undefined): string | null {
/**
* The pre-LIMIT narrowing both recall cursor reads apply (listFactsSince and,
- * for --since-last-run paging, listFactsKeyset): entity, session, audit rows
- * and --grep. Each part is opt-in, so a caller passing none (delta) gets none.
+ * for --since-last-run paging, listFactsKeyset): entity, the page the fact sits
+ * on (memory_recall's own-member-page arm), session, audit rows and --grep. Each part is opt-in, so a caller passing none (delta) gets none.
*/
function recallNarrowing(opts: RecallFactReadOpts | undefined) {
const grep = grepPattern(opts);
return sqlFragment`${opts?.entitySlug != null ? sqlFragment` AND entity_slug = ${opts.entitySlug}` : sqlFragment``}${
+ opts?.sourceMarkdownSlug != null ? sqlFragment` AND source_markdown_slug = ${opts.sourceMarkdownSlug}` : sqlFragment``}${
opts?.sessionId ? sqlFragment` AND source_session = ${opts.sessionId}` : sqlFragment``}${
opts?.excludeAuditRows ? sqlFragment` AND source != ALL(${AUDIT_ROW_SOURCES}::text[])` : sqlFragment``}${
grep ? sqlFragment` AND fact ILIKE ${grep} ESCAPE '\\'` : sqlFragment``}`;
diff --git a/src/core/engine.ts b/src/core/engine.ts
index 17da329678..6b99afba87 100644
--- a/src/core/engine.ts
+++ b/src/core/engine.ts
@@ -707,8 +707,8 @@ export interface FactListOpts {
excludePrivate?: boolean;
}
-/** FactListOpts plus the entity the recall cursor reads (listFactsSince, listFactsKeyset) narrow to before LIMIT. */
-export type RecallFactReadOpts = FactListOpts & { entitySlug?: string };
+/** FactListOpts plus the entity (and the page the fact sits on) listFactsSince and listFactsKeyset narrow to before LIMIT. */
+export type RecallFactReadOpts = FactListOpts & { entitySlug?: string; sourceMarkdownSlug?: string };
/** Per-source operational health snapshot consumed by `gbrain doctor`. */
export interface FactsHealth {
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index 577e1c49d5..145515e694 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -68,7 +68,7 @@ export const CODES = {
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.", why: 'The audience decides whose notes the agent may read, so an audience gbrain cannot read exactly is refused instead of guessed.', docs: 'docs/guides/write-refusals.md#on_behalf_of_invalid_audience', 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.' },
on_behalf_of_unknown_member: { class: 'caller', summary: "A shared agent's audience names a member who is not enabled on this brain, or a group that does not exist, so nothing was read.", why: 'An unknown or disabled entry is refused rather than read as a guest, so a typo or a removed person never quietly changes what the agent reads.', docs: 'docs/guides/write-refusals.md#on_behalf_of_unknown_member', suggestion: 'Name enabled members and existing groups only (gbrain access member list --all, gbrain access group list on the brain host); a person who is not a member joins the audience as guest.' },
on_behalf_of_not_permitted: { class: 'host_only', actor: 'user', summary: "A shared agent asserted an audience its credential's may_act_for does not list (for a stdio server, config mcp.stdio_may_act_for), so nothing was read.", why: 'A shared agent acts only for the people the brain operator approved for its credential; widening that list is the operator\'s decision, never the agent\'s.', docs: 'docs/guides/write-refusals.md#on_behalf_of_not_permitted', suggestion: 'The brain operator decides whether to approve the audience: gbrain auth rescope --token <name>|--client <id> --may-act-for <list> on the brain host. Until then, call without the audience.' },
- actor_not_attested: { class: 'host_only', actor: 'user', reasons: ['no_attest_right', 'op_not_attested', 'argument_mismatch', 'argument_without_attestation', 'invalid_actor_id'], 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. Nothing was read or written.", why: 'Naming a person decides whose notes are read and written as; only a credential the brain operator granted the attest right may do it, only for the operations it lists, and text in a conversation never chooses it.', docs: 'docs/guides/write-refusals.md#actor_not_attested', 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 and invalid_actor_id are fixed in the calling harness.' },
+ actor_not_attested: { class: 'host_only', actor: 'user', reasons: ['no_attest_right', 'op_not_attested', 'argument_mismatch', 'argument_without_attestation', 'invalid_actor_id', 'actor_required'], 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.", why: 'Naming a person decides whose notes are read and written as; only a credential the brain operator granted the attest right may do it, only for the operations it lists, and text in a conversation never chooses it.', docs: 'docs/guides/write-refusals.md#actor_not_attested', 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.' },
actor_unlinked: { class: 'host_only', actor: 'user', 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.', why: 'An attested call reads and writes as exactly one member; an unknown person is refused rather than read as a guest, and unlinking or disabling takes effect on the next call.', docs: 'docs/guides/write-refusals.md#actor_unlinked', suggestion: 'The brain operator links the id to its member: gbrain access member link <member> --qm <id> (or enables the member).' },
on_behalf_of_in_arguments: { class: 'caller', summary: 'A tool call carried on_behalf_of inside its arguments, where conversation text could set it, so it was refused and nothing was read.', why: 'Only harness code may name whose notes a shared agent reads: the X-Gbrain-On-Behalf-Of header or request-level _meta.on_behalf_of, never tool arguments.', docs: 'docs/guides/write-refusals.md#on_behalf_of_in_arguments', suggestion: 'Remove on_behalf_of from the tool arguments. Harness code sends it as the X-Gbrain-On-Behalf-Of header or request-level _meta.on_behalf_of; other stdio clients use a credential bound to one member or config mcp.stdio_member.' },
access_policy_invalid: { class: 'host_only', actor: 'user', docs: 'docs/guides/write-refusals.md#access_policy_invalid', summary: "A source's folder-rule policy (the committed .gbrain/access.yml, or a file given to gbrain access rule import) does not validate, so it was not applied: the last applied rules stay in force and every prefix the bad file names reads as nobody (the whole source when its prefixes cannot be read).", why: 'A typo in an access file must never open a folder: an unreadable revision keeps the previous rules and hides what it touches until it is fixed.', suggestion: 'Show each problem with its line (gbrain access rule list --source <id>), fix the file, commit it with gbrain git commit-push and sync the source (gbrain sync --source <id> --no-pull).', fix: { argv: ['gbrain', 'access', 'rule', 'list', '--source', '{source_id}', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Lists the applied rules and each problem in the policy file with its line; changes nothing.' } },
diff --git a/src/core/operation-load.ts b/src/core/operation-load.ts
index 51cc638fc3..eb862e74e0 100644
--- a/src/core/operation-load.ts
+++ b/src/core/operation-load.ts
@@ -89,6 +89,7 @@ const OP_AREAS: Record<string, string> = {
takes_scorecard: 'takes', takes_calibration: 'takes',
// hot memory (facts)
extract_facts: 'memory', forget_fact: 'memory', confirm_memory: 'memory',
+ memory_recall: 'memory', memory_write: 'memory', // GST-359: QM's memory provider pair
// entity extraction lane
extract_entities: 'entities', extraction_pending: 'entities',
extraction_review: 'entities',
diff --git a/src/core/operations.ts b/src/core/operations.ts
index 5a5970c8cc..43fd011c2f 100644
--- a/src/core/operations.ts
+++ b/src/core/operations.ts
@@ -110,6 +110,7 @@ import { transcriptsOperations } from './ops/transcripts.ts';
import { connectorsOperations } from './ops/connectors.ts';
import { sourcesOperations } from './ops/sources.ts';
import { factsOperations } from './ops/facts.ts';
+import { qmMemoryOperations } from './ops/qm-memory.ts';
import { purgeOperations } from './ops/purge.ts';
import { codeIntelOperations } from './ops/code-intel.ts';
import { embeddingMigrationOperations } from './ops/embedding-migration.ts';
@@ -212,7 +213,7 @@ export const operations: Operation[] = [
...entityIdentityOperations,
// v0.31: hot memory (extract_facts, recall, context_pack, delta,
// forget_fact) — ops/facts.ts
- ...factsOperations, ...purgeOperations,
+ ...factsOperations, ...purgeOperations, ...qmMemoryOperations, // + GST-359 QM memory pair — ops/qm-memory.ts
// v0.32.6: contradiction probe MCP surface (M3) — ops/insights.ts
find_contradictions,
// v0.33: expertise + relationship-proximity routing — ops/insights.ts
diff --git a/src/core/ops/contract.ts b/src/core/ops/contract.ts
index 272615d601..915c16f3b6 100644
--- a/src/core/ops/contract.ts
+++ b/src/core/ops/contract.ts
@@ -580,6 +580,11 @@ export interface OperationContext {
* allow-list equal to the stored delegated prefixes.
*/
replayAuthority?: WriteAuthority;
+ /**
+ * GST-359 D: the attested operation a nested write serves (memory_write saves through remember). Set by the handler,
+ * never from arguments; the stored authority keeps it, so publication re-checks that operation's attest right.
+ */
+ attestedOp?: string;
/**
* #4216 — defer chunk embeddings on put_page writes: importFromContent runs
* noEmbed and the standing embed machinery (embed phase / phase-end
diff --git a/src/core/ops/qm-memory.ts b/src/core/ops/qm-memory.ts
new file mode 100644
index 0000000000..1f105581ea
--- /dev/null
+++ b/src/core/ops/qm-memory.ts
@@ -0,0 +1,256 @@
+/**
+ * GST-359 D (GBRA-218): QM's memory provider pair, the two tools a trusted system (QM) calls for the person it
+ * attests in `x-qm-actor` (access/actor.ts). The contract they keep is docs/contracts/qm-memory-provider/v1.json.
+ *
+ * - memory_recall: plain-text facts, one per line (`- <fact> (<date>; <kind>)`), never page bodies. The caller's own
+ * facts from the last 24 hours on its member page come first, then the facts it may read ranked by the query
+ * (keyword-only unless an embedding provider is configured), deduplicated by fact id, cut at a line boundary with a
+ * final `… N more` line so the text never exceeds max_chars. Fence and heading markers are stripped from fact text.
+ * - memory_write: 1-20 facts saved through remember's persistence path (the same writer door, git-first where a repo
+ * exists) onto the attested member's page, readable by that member alone, with provenance `qm:<actor id>; <caller's>`.
+ * Each fact's request id derives from uuidv5(member, idempotency_key), so a key never crosses members and a replay
+ * returns the original receipts. Never retried here: a write still publishing answers `pending`.
+ *
+ * Both answer with the text for the model in `content` and the result in `structuredContent` (qmMemoryToolResult);
+ * QM reads success codes only from `structuredContent`. An unlinked actor on memory_recall is answered by dispatch
+ * (actorRefusal) with empty content and `{facts: [], truncated: false, code: 'actor_unlinked'}` (unlinkedRecallResult).
+ */
+import type { Operation, OperationContext, ParamDef } from './contract.ts';
+import { opError, OperationError } from './contract.ts';
+import { federatedSearchScope } from './context.ts';
+import type { FactRow } from '../engine.ts';
+import { resolveReadEligibility } from '../eligibility/policy.ts';
+import { currentCallerAccess, resolveExcludePrivatePages } 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';
+
+export const QM_MEMORY_OPS: ReadonlySet<string> = new Set(['memory_recall', 'memory_write']);
+export const MEMORY_RECALL_MAX_CHARS = { min: 200, max: 12_000, default: 6_000 } as const;
+/** Own facts written within this window lead the answer. */
+export const OWN_RECENT_WINDOW_HOURS = 24;
+/** Rows read per arm (own recent, query-ranked) before the max_chars cut. */
+export const MEMORY_RECALL_ARM_LIMIT = 50;
+/** The query ranks on its first 2000 characters (recall's `question` cap); the rest is ignored, never refused. */
+export const MEMORY_RECALL_QUERY_CHARS = 2000;
+export const MEMORY_WRITE_MAX_FACTS = 20;
+export const MEMORY_WRITE_PROVENANCE_MAX = 200;
+export const IDEMPOTENCY_KEY_RE = /^[\x21-\x7e]{1,128}$/;
+/** remember's input kinds (MEMORY_VERBS v1, frozen); a stored `idea` can still come back from memory_recall. */
+export const MEMORY_WRITE_KINDS = ['event', 'preference', 'commitment', 'belief', 'fact'] as const;
+const FACT_KEYS = new Set(['fact', 'provenance', 'kind', 'valid_from']);
+/** Namespace of the per-member request-id namespaces. Changing it orphans every journaled memory_write receipt. */
+export const QM_MEMORY_REQUEST_NAMESPACE = '6b3e9f2a-41c7-4d58-9a0e-2f7c5d1b8e63';
+
+const actorParam: ParamDef = { type: 'string', description: `Set by the trusted system: equal to the ${ACTOR_HEADER} header, or omit.`, fullSurfaceOnly: true };
+
+export interface RecallFact { id: string; text: string; date: string; kind: string }
+
+/** Fact text as one plain line: fence and heading markers and rules removed, whitespace collapsed. */
+export function plainFactText(text: string): string {
+ return text
+ .replace(/^[ \t]{0,3}#{1,6}(?=\s|$)/gm, '')
+ .replace(/^[ \t]*(?:-{3,}|\*{3,}|_{3,}|={3,})[ \t]*$/gm, '')
+ .replace(/`{3,}|~{3,}/g, '')
+ .replace(/\s+/g, ' ')
+ .trim();
+}
+
+/** The lines that fit in maxChars: whole lines, then `… N more` when any were left out; never longer than maxChars. */
+export function boundFactLines(lines: readonly string[], maxChars: number): { kept: number; text: string } {
+ const full = lines.join('\n');
+ if (full.length <= maxChars) return { kept: lines.length, text: full };
+ let kept = 0;
+ let used = 0;
+ while (kept < lines.length) {
+ const next = used + (kept ? 1 : 0) + lines[kept]!.length;
+ if (next + 1 + `… ${lines.length - kept - 1} more`.length > maxChars) break;
+ used = next;
+ kept++;
+ }
+ const tail = `… ${lines.length - kept} more`;
+ return { kept, text: kept ? `${lines.slice(0, kept).join('\n')}\n${tail}` : tail };
+}
+
+const isoDate = (value: Date | string | null | undefined): string => {
+ const t = value instanceof Date ? value : value ? new Date(value) : null;
+ return t && Number.isFinite(t.getTime()) ? t.toISOString().slice(0, 10) : 'undated';
+};
+
+const invalid = (message: string, suggestion: string): OperationError => opError('invalid_params', message, suggestion);
+
+function parseMaxChars(raw: unknown): number {
+ if (raw === undefined || raw === null) return MEMORY_RECALL_MAX_CHARS.default;
+ const { min, max } = MEMORY_RECALL_MAX_CHARS;
+ if (typeof raw !== 'number' || !Number.isInteger(raw) || raw < min || raw > max) {
+ throw invalid(`max_chars must be a whole number from ${min} to ${max}.`, `Omit max_chars for ${MEMORY_RECALL_MAX_CHARS.default}, or pass a whole number from ${min} to ${max}.`);
+ }
+ return raw;
+}
+
+type ReadPolicy = { excludePrivate: boolean; eligibility: Awaited<ReturnType<typeof resolveReadEligibility>> };
+
+/** The caller's own facts written in the last 24 hours on its member page, newest first; none outside a member caller. */
+async function ownRecentFacts(ctx: OperationContext, sources: string[], read: ReadPolicy): Promise<FactRow[]> {
+ const member = ctx.remote === false ? null : callerMember();
+ if (!member) return [];
+ const since = new Date(Date.now() - OWN_RECENT_WINDOW_HOURS * 3_600_000);
+ const lists = await Promise.all(sources.map(src => ctx.engine.listFactsSince(src, since, {
+ sourceMarkdownSlug: memberPageSlug(member), visibility: ['world'], excludePrivate: read.excludePrivate, eligibility: read.eligibility,
+ excludeAuditRows: true, limit: MEMORY_RECALL_ARM_LIMIT,
+ })));
+ return lists.flat().sort((a, b) => b.created_at.getTime() - a.created_at.getTime() || b.id - a.id).slice(0, MEMORY_RECALL_ARM_LIMIT);
+}
+
+const memory_recall: Operation = {
+ name: 'memory_recall',
+ mutating: false,
+ idempotent: true,
+ outputRedaction: { exempt: 'renders its own bounded text: fact text passes the retrieval redactor before the max_chars cut' },
+ 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.',
+ params: {
+ query: { type: 'string', required: true, description: 'What the turn is about; ranks the facts.' },
+ max_chars: { type: 'number', description: `Text cap, ${MEMORY_RECALL_MAX_CHARS.min}-${MEMORY_RECALL_MAX_CHARS.max} (default ${MEMORY_RECALL_MAX_CHARS.default}).` },
+ [ACTOR_ARGUMENT]: actorParam,
+ },
+ scope: 'read',
+ annotations: { title: 'memory_recall (QM memory read)', readOnlyHint: true },
+ handler: async (ctx, p) => {
+ const maxChars = parseMaxChars(p.max_chars);
+ const query = typeof p.query === 'string' ? p.query.trim().slice(0, MEMORY_RECALL_QUERY_CHARS) : '';
+ 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));
+ const plain = rows.map(r => ({ id: String(r.id), text: plainFactText(r.fact), date: isoDate(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 };
+ },
+};
+
+/** The request id of fact `index` in a memory_write: uuidv5 of the key under the member's own namespace for fact 0, derived from it after. */
+export async function memoryWriteRequestId(member: string, idempotencyKey: string, index: number): Promise<string> {
+ const root = uuidV5(uuidV5(QM_MEMORY_REQUEST_NAMESPACE, `member:${member}`), idempotencyKey);
+ if (index === 0) return root;
+ const { childRequestId } = await import('../remember-batch.ts');
+ return childRequestId(root, index);
+}
+
+function parseFacts(raw: unknown, actorId: string): Array<Record<string, unknown>> {
+ if (!Array.isArray(raw) || raw.length < 1 || raw.length > MEMORY_WRITE_MAX_FACTS) {
+ throw invalid(`facts must be an array of 1 to ${MEMORY_WRITE_MAX_FACTS} facts.`, `Pass facts: [{ "fact": "...", "provenance": "..." }, ...], at most ${MEMORY_WRITE_MAX_FACTS} per call.`);
+ }
+ return raw.map((item, index) => {
+ const at = `facts[${index}]`;
+ if (!item || typeof item !== 'object' || Array.isArray(item)) throw invalid(`${at} must be an object.`, 'Each fact is { fact, provenance, optional kind, optional valid_from }.');
+ const f = item as Record<string, unknown>;
+ const extra = Object.keys(f).filter(k => !FACT_KEYS.has(k));
+ if (extra.length) throw invalid(`${at} has unknown field(s): ${extra.join(', ')}.`, `Allowed fields: ${[...FACT_KEYS].join(', ')}.`);
+ const fact = typeof f.fact === 'string' ? f.fact.trim() : '';
+ if (!fact) throw invalid(`${at}.fact must be a non-empty string.`, 'Pass the claim to save as fact.');
+ const provenance = typeof f.provenance === 'string' ? f.provenance.trim() : '';
+ if (!provenance || provenance.length > MEMORY_WRITE_PROVENANCE_MAX) {
+ throw invalid(`${at}.provenance must be 1 to ${MEMORY_WRITE_PROVENANCE_MAX} characters.`, 'Pass where the fact came from, for example "slack:C0123/p1700000000".');
+ }
+ if (f.kind !== undefined && !(MEMORY_WRITE_KINDS as readonly unknown[]).includes(f.kind)) {
+ throw invalid(`${at}.kind is not a fact kind.`, `Use one of: ${MEMORY_WRITE_KINDS.join(', ')}, or omit it (fact).`);
+ }
+ if (f.valid_from !== undefined && (typeof f.valid_from !== 'string' || !Number.isFinite(Date.parse(f.valid_from)))) {
+ throw invalid(`${at}.valid_from must be an ISO 8601 date or time.`, 'Pass when the fact became true, for example "2026-10-30", or omit it.');
+ }
+ return { fact, provenance: `qm:${actorId}; ${provenance}`, ...(f.kind !== undefined ? { kind: f.kind } : {}), ...(f.valid_from !== undefined ? { valid_from: f.valid_from } : {}) };
+ });
+}
+
+const memory_write: Operation = {
+ name: 'memory_write',
+ mutating: true,
+ idempotent: true,
+ outputRedaction: 'no_stored_text',
+ 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.',
+ params: {
+ facts: {
+ type: 'array', required: true, description: `1-${MEMORY_WRITE_MAX_FACTS} facts.`,
+ items: { type: 'object', properties: {
+ fact: { type: 'string', required: true, description: 'One claim.' },
+ provenance: { type: 'string', required: true, description: `Where it came from (<=${MEMORY_WRITE_PROVENANCE_MAX} chars).` },
+ kind: { type: 'string', enum: [...MEMORY_WRITE_KINDS], description: 'Default fact.' },
+ valid_from: { type: 'string', description: 'When it became true (ISO 8601).' },
+ } },
+ },
+ idempotency_key: { type: 'string', required: true, description: '1-128 visible ASCII characters; the same key replays this write.' },
+ [ACTOR_ARGUMENT]: actorParam,
+ },
+ scope: 'write',
+ annotations: { title: 'memory_write (QM memory write)', idempotentHint: true },
+ handler: async (ctx, p) => {
+ const actor = ctx.remote === false ? null : currentCallerAccess().actor ?? null;
+ if (!actor) {
+ const { actorNotAttested } = await import('../access/actor.ts');
+ throw actorNotAttested('actor_required', { auth: ctx.auth }, { op: 'memory_write', transport: ctx.transport });
+ }
+ if (typeof p.idempotency_key !== 'string' || !IDEMPOTENCY_KEY_RE.test(p.idempotency_key)) {
+ throw invalid('idempotency_key must be 1 to 128 visible ASCII characters (no spaces).', 'Send a stable key per write, for example a UUID; the same key replays the same write.');
+ }
+ const key = p.idempotency_key;
+ const items = await Promise.all(parseFacts(p.facts, actor.external_id).map(async (f, i) => ({ ...f, request_id: await memoryWriteRequestId(actor.member, key, i) })));
+ const { verbOperations } = await import('../verbs.ts');
+ const remember = verbOperations.find(op => op.name === 'remember')!;
+ for (const [index, item] of items.entries()) {
+ try { await remember.handler({ ...ctx, attestedOp: 'memory_write', dryRun: true }, item); } catch (e) {
+ if (e instanceof OperationError) e.message = `facts[${index}]: ${e.message} Nothing was saved.`;
+ throw e;
+ }
+ }
+ if (ctx.dryRun) return { dry_run: true, action: 'memory_write', facts: items.length };
+ const saved: Array<{ request_id: string; fact_id?: string; pending?: true }> = [];
+ for (const [index, item] of items.entries()) {
+ try {
+ const out = await remember.handler({ ...ctx, attestedOp: 'memory_write' }, item) as { id?: string | number } | null;
+ saved.push({ request_id: item.request_id, ...(out?.id !== undefined ? { fact_id: String(out.id) } : {}) });
+ } catch (e) {
+ if (e instanceof OperationError && e.writeError === 'write_pending') { saved.push({ request_id: item.request_id, pending: true }); continue; }
+ if (e instanceof OperationError && index > 0) e.message = `facts[${index}]: ${e.message} The ${index} fact(s) before it were saved; the same idempotency_key replays them.`;
+ throw e;
+ }
+ }
+ const pending = saved.filter(s => s.pending).map(s => s.request_id);
+ return {
+ status: pending.length ? 'pending' : 'committed',
+ request_id: pending[0] ?? items[0]!.request_id,
+ fact_ids: saved.flatMap(s => s.fact_id ? [s.fact_id] : []),
+ ...(pending.length ? { pending_request_ids: pending } : {}),
+ text: pending.length ? `Accepted ${items.length} fact(s); ${pending.length} still publishing.` : `Saved ${items.length} fact(s).`,
+ };
+ },
+};
+
+/**
+ * A successful memory_recall or memory_write result as QM reads it: the model's text alone in `content` (notices stay
+ * in `_meta.gbrain_notices`, so memory_recall's text stays within max_chars) and the result in `structuredContent`.
+ * Refusals, dry runs and every other tool pass through unchanged.
+ */
+export function qmMemoryToolResult<T extends { content: Array<{ type: 'text'; text: string }>; isError?: boolean; structuredContent?: Record<string, unknown> }>(name: string, out: T): T {
+ if (!QM_MEMORY_OPS.has(name) || out.isError) return out;
+ let result: unknown;
+ try { result = JSON.parse(out.content[0]?.text ?? ''); } catch { return out; }
+ if (!result || typeof result !== 'object' || 'dry_run' in result) return out;
+ const { text, ...structured } = result as Record<string, unknown>;
+ return { ...out, content: [{ type: 'text', text: typeof text === 'string' ? text : '' }], structuredContent: structured };
+}
+
+/** The empty memory_recall an unlinked attested person gets (dispatch's actorRefusal seam): a success QM reads by its code. */
+export function unlinkedRecallResult(): { content: Array<{ type: 'text'; text: string }>; structuredContent: Record<string, unknown> } {
+ return { content: [{ type: 'text', text: '' }], structuredContent: { facts: [], truncated: false, code: 'actor_unlinked' } };
+}
+
+export const qmMemoryOperations: Operation[] = [memory_recall, memory_write];
diff --git a/src/core/ops/write-inference.ts b/src/core/ops/write-inference.ts
index 7f27c87345..7a3bad851d 100644
--- a/src/core/ops/write-inference.ts
+++ b/src/core/ops/write-inference.ts
@@ -39,7 +39,7 @@ export const ZERO_GENERATIVE_BEFORE_COMMIT: ReadonlySet<WriteInference> = new Se
export const OP_WRITE_INFERENCE: Readonly<Record<string, WriteInference>> = {
// memory verbs and facts
- remember: 'embedding', forget: 'none', forget_fact: 'none', extract_facts: 'explicit_llm',
+ remember: 'embedding', memory_write: 'embedding', forget: 'none', forget_fact: 'none', extract_facts: 'explicit_llm',
// pages
put_page: 'async_derived', put_pages: 'async_derived', capture: 'async_derived', edit_page: 'async_derived',
revert_version: 'async_derived', delete_page: 'none', restore_page: 'none',
diff --git a/src/core/persistence/authority.ts b/src/core/persistence/authority.ts
index 7f4869ccfb..d708b93e4d 100644
--- a/src/core/persistence/authority.ts
+++ b/src/core/persistence/authority.ts
@@ -68,6 +68,7 @@ export async function submissionAuthority(ctx: OperationContext, operation: stri
// GBRA-231: a channel audience (anything but one member) never relaxes privacy, so its ceiling hides private pages.
excludePrivate: (actingFor !== undefined && currentCallerAccess().hidePrivate) || await excludesPrivateWrites(ctx.engine, ctx.remote !== false),
...(actingFor ? { actingFor } : {}),
+ ...(access?.actor && ctx.attestedOp ? { attestedOp: ctx.attestedOp } : {}),
autoLinkTrusted: ctx.remote === false || ctx.viaSubagent === true && !ctx.auth && !!ctx.allowedSlugPrefixes?.length,
takesHolders: ctx.remote === false ? null : [...(ctx.takesHoldersAllowList ?? ['world'])],
scopes: [...(ctx.auth?.scopes ?? localGrant?.scopes ?? [])],
@@ -149,7 +150,7 @@ export async function authorizeWrite(engine: SqlEngine, a: WriteAuthority, opera
if (a.actingFor && !Array.isArray(a.actingFor)) {
const actor = parseStoredActor(a.actingFor);
if (!actor) deny('The accepted attested actor is malformed.');
- await storedActorIdentity(engine, a.principal, actor, operation);
+ await storedActorIdentity(engine, a.principal, actor, a.attestedOp ?? operation);
}
const suffix = lock ? ' FOR SHARE' : '';
if (a.principal.kind === 'oauth_client') {
@@ -270,7 +271,7 @@ function onceReads(engine: BrainEngine): BrainEngine {
export async function ownRequestAccessible(ctx: OperationContext, row: WriteRequest): Promise<boolean> {
try {
const engine = onceReads(ctx.engine);
- const auth = await submissionAuthority({ ...ctx, engine }, row.operation, row.source_id, row.source_incarnation, row.slug);
+ const auth = await submissionAuthority({ ...ctx, engine, attestedOp: row.authority?.attestedOp }, row.operation, row.source_id, row.source_incarnation, row.slug);
if (auth.principal.kind !== row.principal_kind || auth.principal.id !== row.principal_id) return false;
// GST-359 C2: under one attest credential, a receipt belongs to the person it was written for.
if (!sameAttestedActor(row.authority?.actingFor)) return false;
diff --git a/src/core/persistence/model.ts b/src/core/persistence/model.ts
index c6c014a1e9..56201b3c9f 100644
--- a/src/core/persistence/model.ts
+++ b/src/core/persistence/model.ts
@@ -19,6 +19,8 @@ export interface WriteAuthority {
* link from the id to the same enabled member, so an unlink, a disabled member or a revoked right refuses it.
*/
actingFor?: string[] | { system: string; external_id: string; member: string };
+ /** GST-359 D: the attested operation this write serves when it differs from the stored one (memory_write as remember). */
+ attestedOp?: string;
databaseOnlyReason?: 'subagent_sandbox' | 'disabled_by_config' | 'no_repo_configured' | 'connector_database' | 'unbound_source' | 'overwrite_restore' | 'detached';
autoLinkTrusted?: boolean;
restrictedNamespace?: boolean;
diff --git a/src/core/persistence/preconditions.ts b/src/core/persistence/preconditions.ts
index a7f0492442..d4be13ea60 100644
--- a/src/core/persistence/preconditions.ts
+++ b/src/core/persistence/preconditions.ts
@@ -12,7 +12,12 @@ const PRINTABLE_ASCII = /^[\x21-\x7e]+$/;
/** RFC 4122 UUIDv5 of `name` under CLIENT_REQUEST_ID_NAMESPACE. */
export function clientRequestUuid(name: string): string {
- const h = createHash('sha1').update(Buffer.from(CLIENT_REQUEST_ID_NAMESPACE.replace(/-/g, ''), 'hex')).update(name, 'utf8').digest();
+ return uuidV5(CLIENT_REQUEST_ID_NAMESPACE, name);
+}
+
+/** RFC 4122 UUIDv5 of `name` under the UUID `namespace`. */
+export function uuidV5(namespace: string, name: string): string {
+ const h = createHash('sha1').update(Buffer.from(namespace.replace(/-/g, ''), 'hex')).update(name, 'utf8').digest();
h[6] = (h[6]! & 0x0f) | 0x50;
h[8] = (h[8]! & 0x3f) | 0x80;
const hex = h.subarray(0, 16).toString('hex');
diff --git a/src/mcp/dispatch.ts b/src/mcp/dispatch.ts
index 7d9b810e25..89b577a560 100644
--- a/src/mcp/dispatch.ts
+++ b/src/mcp/dispatch.ts
@@ -18,6 +18,7 @@ import { withCallerAccess } from '../core/search/private-visibility.ts';
import { appliedAccessSummary, remoteCallerAccess } from '../core/access/caller.ts';
import { audienceInArguments, audienceInArgumentsError, logAudienceAssertion, parseAudience, type AudienceAuditEvent, type AudienceChannels, type AudiencePrincipal } from '../core/access/audience.ts';
import { ACTOR_ARGUMENT, EXTERNAL_ID_RE, resolveAttestedActor, type ActorChannels } from '../core/access/actor.ts';
+import { qmMemoryToolResult, unlinkedRecallResult } from '../core/ops/qm-memory.ts';
import { resolveBrainId } from '../core/brain-resolver.ts';
import { getCliOptions } from '../core/cli-options.ts';
import { VERB_NAMES, MEMORY_VERBS_VERSION } from '../core/verbs.ts';
@@ -913,7 +914,7 @@ export async function dispatchToolCall(
// GBRA-218: a remote call also carries its credential's member identity, which every caller-aware read checks page readers against.
// GBRA-231: or the audience a shared agent's harness asserts, resolved (and refused) on every call before any work.
const run = async () => {
- if (opts.remote === false) return withCallerAccess({ privateReadableSources: [] }, () => withRequestIdentityMemo(() => dispatchResolvedCall(engine, name, params, resolved)));
+ if (opts.remote === false) return qmMemoryToolResult(name, await withCallerAccess({ privateReadableSources: [] }, () => withRequestIdentityMemo(() => dispatchResolvedCall(engine, name, params, resolved))));
// GST-359 C1: or the person a trusted system attests (x-qm-actor), decided here too, before any work (access/actor.ts).
let audience: AudiencePrincipal[] | null = null;
let attested: Awaited<ReturnType<typeof resolveAttestedActor>> = null;
@@ -933,7 +934,7 @@ export async function dispatchToolCall(
} catch (e) {
if (!(e instanceof OperationError) || !/^(on_behalf_of_|actor_)/.test(String(e.code))) throw e;
assertion(e.code as AudienceAuditEvent['outcome'], e.reason);
- return actorNamed ? actorRefusal(e, opts, name) : errorResult(e, opts, { op: name });
+ return actorNamed ? actorRefusal(e, opts, name, header) : errorResult(e, opts, { op: name });
}
if (audience || attested) assertion('accepted');
const callParams = attested ? attested.params : params;
@@ -941,7 +942,7 @@ export async function dispatchToolCall(
const out = await withRequestIdentityMemo(() => dispatchResolvedCall(engine, name, callParams, resolved));
// _meta.access (MCP_META_CHANNELS.md): the view this call was answered under, for the harness; own producer, isolated.
try { out._meta = { ...(out._meta ?? {}), access: await appliedAccessSummary(engine, opts.auth, [opts.sourceId, ...(opts.localFederatedSourceIds ?? [])]) }; } catch { /* the key is absent */ }
- return out;
+ return qmMemoryToolResult(name, out);
});
};
if (name === 'search' || name === 'query') return withSearchConnectionBudget(() => withRequestConfigSnapshot(engine, run));
@@ -952,10 +953,14 @@ export async function dispatchToolCall(
/**
* GST-359 C1: the refusal of a call that named an attested actor: gbrain's envelope (top-level `code` in the JSON text
- * block) plus `structuredContent.error`, both of which QM reads. The single seam where memory_recall (layer D) answers
- * actor_unlinked as a success instead: empty content and structuredContent {facts: [], truncated: false, code: 'actor_unlinked'}.
+ * block) plus `structuredContent.error`, both of which QM reads. The single seam where memory_recall answers
+ * actor_unlinked as a success instead (GST-359 D): empty content and structuredContent {facts: [], truncated: false,
+ * code: 'actor_unlinked'}, the code also in `_meta.access`, so a person not yet linked reads nothing and QM's turn goes on.
*/
-function actorRefusal(e: OperationError, opts: DispatchOpts, op: string): ToolResult {
+function actorRefusal(e: OperationError, opts: DispatchOpts, op: string, header: string | undefined): ToolResult {
+ if (op === 'memory_recall' && e.code === 'actor_unlinked') {
+ return { ...unlinkedRecallResult(), _meta: { access: { code: 'actor_unlinked', member: null, groups: [], audience: null, actor: { system: 'qm', external_id: header } } } };
+ }
const out = errorResult(e, opts, { op });
try {
const env = JSON.parse(out.content[0]!.text) as Record<string, unknown>;
diff --git a/test/qm-memory-tools.test.ts b/test/qm-memory-tools.test.ts
new file mode 100644
index 0000000000..8e27ce30bf
--- /dev/null
+++ b/test/qm-memory-tools.test.ts
@@ -0,0 +1,347 @@
+/**
+ * GST-359 D: QM's memory provider pair, memory_recall and memory_write.
+ *
+ * 1. Protects: memory_write saves 1-20 facts through remember's persistence path onto the attested member's own page
+ * (readable by that member alone, private rows, provenance qm:<actor id>; <caller's>), only for an attested person,
+ * with request ids from uuidv5(member, idempotency_key): a replay returns the original receipt, the same key from
+ * two members is two writes, and a write still publishing answers pending with a pollable request_id.
+ * memory_recall answers the person's own recent facts first, then the facts they may read ranked by the query,
+ * one plain line per fact (fence and heading markers stripped, never page bodies), cut at a line boundary with a
+ * final "… N more" line and never longer than max_chars (200-12000, default 6000). Success codes ride
+ * structuredContent only; an unlinked actor gets an empty success with code actor_unlinked.
+ * 2. Fails when: a member write lands on a shared page or as a world row, a key replays across members, a write runs
+ * without an attested person, recall leaks another member's fact or a page body, own recent facts do not lead,
+ * the text exceeds max_chars or is cut inside a line, the unlinked answer is an error, or a keyless brain embeds.
+ * 3. Existing coverage: test/access-qm-actor.test.ts (C1) pins the actor; test/access-member-facts.test.ts (C2) pins
+ * member facts through remember and recall. This file pins the two QM tools on top of them.
+ * 4. Real seams: OAuth clients issued tokens by the provider's client-credentials grant, verified by the provider,
+ * dispatched through MCP dispatch on a repo-less brain; writes go through the persistence coordinator; embeddings
+ * stubbed (and absent for the keyless case).
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { importFromContent } from '../src/core/import-file.ts';
+import { configureGateway, resetGateway, __setEmbedTransportForTests } from '../src/core/ai/gateway.ts';
+import { GBrainOAuthProvider } from '../src/core/oauth-provider.ts';
+import { sqlQueryForEngine } from '../src/core/sql-query.ts';
+import { dispatchToolCall, type ToolResult } from '../src/mcp/dispatch.ts';
+import { __resetPrivateVisibilityCacheForTests } from '../src/core/search/private-visibility.ts';
+import { __resetHotMemoryCacheForTests, getBrainHotMemoryMeta } from '../src/core/facts/meta-hook.ts';
+import { addMember, bindCredential } from '../src/core/access/members.ts';
+import { linkMember } from '../src/core/access/actor.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { boundFactLines, memoryWriteRequestId, plainFactText, MEMORY_RECALL_MAX_CHARS } from '../src/core/ops/qm-memory.ts';
+import type { AuthInfo } from '../src/core/ops/contract.ts';
+import { testBackends } from './helpers/test-backends.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+
+const DIMS = 1536;
+const TICKS = String.fromCharCode(96).repeat(3);
+function vectorFor(text: string): number[] {
+ const v = new Array<number>(DIMS).fill(0);
+ for (const w of text.toLowerCase().match(/[a-z]+/g) ?? []) {
+ let h = 0;
+ for (const ch of w) h = (h * 31 + ch.charCodeAt(0)) >>> 0;
+ v[h % DIMS] += 1;
+ }
+ const n = Math.hypot(...v) || 1;
+ return v.map(x => x / n);
+}
+const keyedEmbeddings = (onCall?: () => void) => {
+ configureGateway({ embedding_model: 'openai:text-embedding-3-small', embedding_dimensions: DIMS, env: { OPENAI_API_KEY: 'test' } });
+ __setEmbedTransportForTests((async ({ values }: { values: string[] }) => { onCall?.(); return { embeddings: values.map(vectorFor) }; }) as never);
+};
+
+describe('memory_recall text bounds (pure)', () => {
+ const lines = Array.from({ length: 40 }, (_, i) => '- fact number ' + i + ' about the harbor ledger (2026-10-30; fact)');
+
+ test('whole lines, then one "… N more" line, never past the cap, at every cap from the minimum up', () => {
+ for (let max = MEMORY_RECALL_MAX_CHARS.min; max < lines.join('\n').length; max += 7) {
+ const { kept, text } = boundFactLines(lines, max);
+ expect(text.length).toBeLessThanOrEqual(max);
+ const out = text.split('\n');
+ expect(out.slice(0, kept)).toEqual(lines.slice(0, kept));
+ expect(kept).toBeLessThan(lines.length);
+ expect(out).toHaveLength(kept + 1);
+ expect(out[kept]).toBe('… ' + (lines.length - kept) + ' more');
+ const oneMore = lines.slice(0, kept + 1).join('\n') + '\n… ' + (lines.length - kept - 1) + ' more';
+ expect(oneMore.length).toBeGreaterThan(max);
+ }
+ });
+
+ test('a list that fits is returned whole with no tail; an empty list is empty text', () => {
+ expect(boundFactLines(lines.slice(0, 3), 6000)).toEqual({ kept: 3, text: lines.slice(0, 3).join('\n') });
+ expect(boundFactLines([], 200)).toEqual({ kept: 0, text: '' });
+ expect(boundFactLines(['x'.repeat(500)], 200)).toEqual({ kept: 0, text: '… 1 more' });
+ });
+
+ test('fence, heading and rule markers are stripped and the fact is one line', () => {
+ expect(plainFactText('## Plan\n' + TICKS + 'ts\nharbor ledger\n' + TICKS + '\n---\n~~~ next ~~~')).toBe('Plan ts harbor ledger next');
+ expect(plainFactText('#1 priority is the harbor')).toBe('#1 priority is the harbor');
+ });
+
+ test('request ids are uuidv5 per member: one key gives different ids to two members and the same id on replay', async () => {
+ const a = await memoryWriteRequestId('alice-example', 'key-1', 0);
+ expect(a).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-5[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/);
+ expect(await memoryWriteRequestId('alice-example', 'key-1', 0)).toBe(a);
+ expect(await memoryWriteRequestId('bob-example', 'key-1', 0)).not.toBe(a);
+ expect(await memoryWriteRequestId('alice-example', 'key-1', 1)).not.toBe(a);
+ });
+});
+
+const SRC = 'qm-memory';
+const ALICE_ID = 'U0ALICE';
+const BOB_ID = 'oidc:3f2a:bob-example';
+const CAROL_ID = '[email protected]';
+const ACME = 'companies/acme-example';
+const ATTEST_OPS = ['get_write_request', 'memory_recall', 'memory_write'];
+
+for (const kind of testBackends()) {
+ describe('memory_recall and memory_write (' + kind + ', repo-less)', () => {
+ let engine: BrainEngine;
+ let close: () => Promise<void>;
+ const provider = () => new GBrainOAuthProvider({ sql: sqlQueryForEngine(engine), transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))) });
+ const tokens: Record<string, string> = {};
+ const verify = async (bearer: string) => await provider().verifyAccessToken(bearer) as unknown as AuthInfo;
+ type Who = { token: string; actor?: string };
+ const alice: Who = { token: 'qm', actor: ALICE_ID };
+ const bob: Who = { token: 'qm', actor: BOB_ID };
+ const carol: Who = { token: 'qm', actor: CAROL_ID };
+
+ async function call(as: Who, op: string, params: Record<string, unknown>, extra: { writeWaitMs?: number } = {}) {
+ const out: ToolResult = await dispatchToolCall(engine, op, { ...params }, {
+ remote: true, transport: 'http', auth: await verify(tokens[as.token]!), sourceId: SRC, takesHoldersAllowList: ['world'],
+ ...(as.actor !== undefined ? { actor: { header: as.actor } } : {}), ...extra,
+ metaHook: (name, ctx) => getBrainHotMemoryMeta(name, ctx),
+ });
+ const text = out.content.map(c => c.text).join('\n');
+ let json: Record<string, any> = {};
+ try { json = JSON.parse(text); } catch { /* plain text */ }
+ return { out, isError: out.isError === true, text, json, structured: out.structuredContent as Record<string, any> | undefined,
+ all: text + JSON.stringify(out._meta ?? {}) + JSON.stringify(out.structuredContent ?? {}) };
+ }
+ const write = (as: Who, facts: Array<Record<string, unknown>>, key: string = randomUUID(), extra: { writeWaitMs?: number } = {}) =>
+ call(as, 'memory_write', { facts, idempotency_key: key }, extra);
+ const recall = (as: Who, query: string, args: Record<string, unknown> = {}) => call(as, 'memory_recall', { query, ...args });
+ const factRows = (needle: string) => engine.executeRaw<Record<string, any>>(
+ 'SELECT id, visibility, source_markdown_slug, source FROM facts WHERE source_id = $1 AND fact LIKE $2 ORDER BY id', [SRC, '%' + needle + '%']);
+
+ beforeAll(async () => {
+ keyedEmbeddings();
+ if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));
+ else { engine = new PGLiteEngine(); await engine.connect({ engine: 'pglite' } as never); await engine.initSchema(); close = () => engine.disconnect(); }
+ __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);
+ 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);
+ return { id: c.clientId, secret: c.clientSecret ?? '' };
+ };
+ const qm = await register('qm');
+ await bindCredential(engine, { kind: 'client', id: qm.id }, { attestActor: 'qm', attestOps: ATTEST_OPS });
+ const bobKey = await register('bob');
+ await bindCredential(engine, { kind: 'client', id: bobKey.id }, { member: 'bob-example' });
+ const plain = await register('plain');
+ for (const [name, c] of [['qm', qm], ['bob', bobKey], ['plain', plain]] as const) tokens[name] = (await provider().exchangeClientCredentials(c.id, c.secret)).access_token;
+ await linkMember(engine, 'alice-example', 'qm', ALICE_ID);
+ await linkMember(engine, 'bob-example', 'qm', BOB_ID);
+ await linkMember(engine, 'carol-example', 'qm', CAROL_ID);
+ }, 120_000);
+
+ afterAll(async () => {
+ __setEmbedTransportForTests(null);
+ resetGateway();
+ await disposePersistenceConsumer(engine).catch(() => undefined);
+ await close?.();
+ });
+
+ test('a committed write lands private on the member page, readable by that member alone, with qm provenance', async () => {
+ const key = randomUUID();
+ const out = await write(alice, [{ fact: 'Alice keeps the harbor ledger canarywritealice', provenance: 'slack:C0123/p1', kind: 'preference' }], key);
+ expect(out.isError).toBe(false);
+ expect(out.structured).toEqual({ status: 'committed', request_id: await memoryWriteRequestId('alice-example', key, 0), fact_ids: [expect.any(String)] });
+ expect(out.out.content).toEqual([{ type: 'text', text: 'Saved 1 fact(s).' }]);
+ const [row] = await factRows('canarywritealice');
+ expect(row).toMatchObject({ visibility: 'private', source_markdown_slug: 'memory/members/alice-example' });
+ expect(String(row!.id)).toBe(out.structured!.fact_ids[0]);
+ expect(String(row!.source)).toContain('qm:' + ALICE_ID + '; slack:C0123/p1');
+ const [page] = await engine.executeRaw<{ page_readers: string[] }>('SELECT page_readers FROM pages WHERE source_id = $1 AND slug = $2', [SRC, 'memory/members/alice-example']);
+ expect(page!.page_readers).toEqual(['member:alice-example']);
+ expect(out.out._meta?.brain_hot_memory).toBeUndefined();
+ }, 60_000);
+
+ test('a replayed key returns the original receipt and writes nothing twice; other facts under it are refused', async () => {
+ const key = 'qm-replay-' + randomUUID();
+ const facts = [{ fact: 'Alice prefers oolong canaryreplay one', provenance: 'turn 1' }, { fact: 'Alice walks the pier canaryreplay two', provenance: 'turn 1' }];
+ const first = await write(alice, facts, key);
+ expect(first.structured).toMatchObject({ status: 'committed', request_id: await memoryWriteRequestId('alice-example', key, 0) });
+ expect(first.structured!.fact_ids).toHaveLength(2);
+ const again = await write(alice, facts, key);
+ expect(again.structured).toEqual(first.structured);
+ expect(await factRows('canaryreplay')).toHaveLength(2);
+ const changed = await write(alice, [{ fact: 'Alice prefers sencha canaryreplay three', provenance: 'turn 1' }], key);
+ expect(changed.isError).toBe(true);
+ expect({ code: changed.json.code, write_error: changed.json.write_error }).toEqual({ code: 'invalid_params', write_error: 'idempotency_conflict' });
+ expect(await factRows('canaryreplay three')).toHaveLength(0);
+ }, 60_000);
+
+ test('the same key from two members is two writes, each on its own page', async () => {
+ const key = 'qm-shared-' + randomUUID();
+ const a = await write(alice, [{ fact: 'Shared turn note canarysamekey', provenance: 'turn 7' }], key);
+ const b = await write(bob, [{ fact: 'Shared turn note canarysamekey', provenance: 'turn 7' }], key);
+ expect(a.structured!.status).toBe('committed');
+ expect(b.structured!.status).toBe('committed');
+ expect(b.structured!.request_id).not.toBe(a.structured!.request_id);
+ expect(b.structured!.fact_ids).not.toEqual(a.structured!.fact_ids);
+ const rows = await factRows('canarysamekey');
+ expect(rows.map(r => r.source_markdown_slug).sort()).toEqual(['memory/members/alice-example', 'memory/members/bob-example']);
+ }, 60_000);
+
+ test('a write is refused without an attested person, and an unlinked person writes nothing', async () => {
+ const cases: Array<[Who, Record<string, unknown>, string, string | undefined]> = [
+ [{ token: 'qm' }, {}, 'actor_not_attested', 'actor_required'],
+ [{ token: 'bob' }, {}, 'actor_not_attested', 'actor_required'],
+ [{ token: 'plain' }, {}, 'actor_not_attested', 'actor_required'],
+ [{ token: 'plain', actor: ALICE_ID }, {}, 'actor_not_attested', 'no_attest_right'],
+ [{ token: 'qm' }, { acting_user: ALICE_ID }, 'actor_not_attested', 'argument_without_attestation'],
+ [alice, { acting_user: BOB_ID }, 'actor_not_attested', 'argument_mismatch'],
+ [{ token: 'qm', actor: 'U0NOBODY' }, {}, 'actor_unlinked', undefined],
+ ];
+ for (const [as, extra, code, reason] of cases) {
+ const out = await call(as, 'memory_write', { facts: [{ fact: 'Refused write canaryrefused', provenance: 'x' }], idempotency_key: randomUUID(), ...extra });
+ expect({ isError: out.isError, code: out.json.code, reason: out.json.reason }).toEqual({ isError: true, code, reason });
+ }
+ expect(await factRows('canaryrefused')).toHaveLength(0);
+ const named = await call(alice, 'memory_write', { facts: [{ fact: 'Named write canarynamed', provenance: 'x' }], idempotency_key: randomUUID(), acting_user: ALICE_ID });
+ expect(named.structured!.status).toBe('committed');
+ }, 60_000);
+
+ test('invalid facts and keys are refused before anything is saved', async () => {
+ const bad: Array<Record<string, unknown>> = [
+ { facts: [], idempotency_key: 'k1' },
+ { facts: Array.from({ length: 21 }, (_, i) => ({ fact: 'f' + i, provenance: 'p' })), idempotency_key: 'k2' },
+ { facts: [{ fact: 'ok canarybad', provenance: 'p' }, { fact: '', provenance: 'p' }], idempotency_key: 'k3' },
+ { facts: [{ fact: 'ok canarybad', provenance: 'x'.repeat(201) }], idempotency_key: 'k4' },
+ { facts: [{ fact: 'ok canarybad', provenance: 'p', kind: 'idea' }], idempotency_key: 'k5' },
+ { facts: [{ fact: 'ok canarybad', provenance: 'p', entity: ACME }], idempotency_key: 'k6' },
+ { facts: [{ fact: 'ok canarybad', provenance: 'p' }], idempotency_key: 'has space' },
+ { facts: [{ fact: 'ok canarybad', provenance: 'p' }], idempotency_key: 'k'.repeat(129) },
+ ];
+ for (const params of bad) {
+ const out = await call(alice, 'memory_write', params);
+ expect(out.isError).toBe(true);
+ expect(out.json.code).toBe('invalid_params');
+ }
+ expect(await factRows('canarybad')).toHaveLength(0);
+ const fits = await write(alice, [{ fact: 'Max provenance canaryfits', provenance: 'x'.repeat(200) }], 'k'.repeat(128));
+ expect(fits.structured!.status).toBe('committed');
+ }, 60_000);
+
+ test('a write still publishing answers pending with a request id its receipt is read by', async () => {
+ const out = await write(alice, [{ fact: 'Alice books the ferry canarypending', provenance: 'turn 9' }], randomUUID(), { writeWaitMs: 0 });
+ expect(out.isError).toBe(false);
+ expect(out.structured).toEqual({ status: 'pending', request_id: expect.any(String), fact_ids: [], pending_request_ids: [out.structured!.request_id] });
+ expect(out.out.content).toEqual([{ type: 'text', text: 'Accepted 1 fact(s); 1 still publishing.' }]);
+ const receipt = await call(alice, 'get_write_request', { request_id: out.structured!.request_id });
+ expect(receipt.isError).toBe(false);
+ expect(receipt.all).toContain(out.structured!.request_id);
+ expect((await call(bob, 'get_write_request', { request_id: out.structured!.request_id })).isError).toBe(true);
+ }, 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' }]);
+ 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 });
+ const out = await recall(alice, 'budget ledger');
+ expect(out.isError).toBe(false);
+ const lines = out.text.split('\n');
+ const at = (needle: string) => lines.findIndex(l => l.includes(needle));
+ expect(at('canaryownrecent')).toBeGreaterThanOrEqual(0);
+ for (const own of ['canarywritealice', 'canaryownrecent']) expect(at(own)).toBeLessThan(at('canaryownold'));
+ expect(at('canaryownold')).toBeGreaterThan(0);
+ expect(at('canaryworld')).toBeGreaterThan(at('canaryownrecent'));
+ expect(lines[0]).toMatch(/^- .+ \(\d{4}-\d{2}-\d{2}; \w+\)$/);
+ expect(out.all).not.toContain('canarybobonly');
+ expect(out.all).not.toContain('canarypagebody');
+ const ids = out.structured!.facts.map((f: { id: string }) => f.id);
+ expect(new Set(ids).size).toBe(ids.length);
+ expect(Object.keys(out.structured!).sort()).toEqual(['facts', 'truncated']);
+ expect(out.structured!.truncated).toBe(false);
+ expect(out.structured!.facts[at('canaryownrecent')]).toEqual({ id: expect.any(String), text: 'Alice moved standup to Tuesdays canaryownrecent', date: expect.stringMatching(/^\d{4}-\d{2}-\d{2}$/), kind: 'fact' });
+ expect(out.out._meta?.brain_hot_memory).toBeUndefined();
+ for (const as of [bob, { token: 'bob' }, { token: 'qm' }, { token: 'plain' }]) {
+ const other = await recall(as, 'budget ledger standup Tuesdays');
+ expect(other.isError).toBe(false);
+ for (const needle of ['canaryownrecent', 'canaryownold', 'canarywritealice', 'canarypagebody']) expect(other.all).not.toContain(needle);
+ }
+ expect((await recall({ token: 'bob' }, 'budget ledger')).all).toContain('canarybobonly');
+ }, 120_000);
+
+ test('max_chars bounds the text at the minimum, the default and with no argument, cut at a line', async () => {
+ for (const batch of ['note', 'memo']) {
+ await write(carol, Array.from({ length: 20 }, (_, i) => ({ fact: 'Carol harbor ' + batch + ' ' + i + ' ' + 'ledger detail '.repeat(30) + 'canarycarol', provenance: 'bulk' })));
+ }
+ for (const [args, max] of [[{ max_chars: 200 }, 200], [{}, MEMORY_RECALL_MAX_CHARS.default], [{ max_chars: 12_000 }, 12_000]] as const) {
+ const out = await recall(carol, 'harbor ledger', args);
+ expect(out.isError).toBe(false);
+ expect(out.text.length).toBeLessThanOrEqual(max);
+ expect(out.structured!.truncated).toBe(true);
+ const lines = out.text.split('\n');
+ const kept = out.structured!.facts.length;
+ expect(lines).toHaveLength(kept + 1);
+ expect(lines[kept]).toMatch(/^… \d+ more$/);
+ for (const line of lines.slice(0, kept)) expect(line).toMatch(/^- Carol harbor .+canarycarol \(\d{4}-\d{2}-\d{2}; fact\)$/);
+ }
+ for (const max_chars of [199, 12_001, 500.5, '600']) {
+ const out = await recall(carol, 'harbor ledger', { max_chars });
+ expect(out.isError).toBe(true);
+ expect(out.json.code).toBe('invalid_params');
+ }
+ }, 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);
+ expect(out.out.content).toEqual([{ type: 'text', text: '' }]);
+ expect(out.structured).toEqual({ facts: [], truncated: false, code: 'actor_unlinked' });
+ expect((out.out._meta?.access as Record<string, unknown>)?.code).toBe('actor_unlinked');
+ const refusedWrite = await call({ token: 'qm', actor: 'U0NOBODY' }, 'memory_write', { facts: [{ fact: 'x', provenance: 'y' }], idempotency_key: 'k' });
+ expect({ isError: refusedWrite.isError, code: refusedWrite.json.code }).toEqual({ isError: true, code: 'actor_unlinked' });
+ const named = await recall({ token: 'plain', actor: 'U0NOBODY' }, 'budget ledger');
+ expect({ isError: named.isError, code: named.json.code, reason: named.json.reason }).toEqual({ isError: true, code: 'actor_not_attested', reason: 'no_attest_right' });
+ }, 60_000);
+
+ test('fact text arrives without fence or heading markers', async () => {
+ await write(alice, [{ fact: '## Harbor rules\n' + TICKS + '\nkeep the ledger canaryfence\n' + TICKS, provenance: 'turn 4' }]);
+ const out = await recall(alice, 'harbor ledger rules');
+ const line = out.text.split('\n').find(l => l.includes('canaryfence'));
+ expect(line).toMatch(/^- Harbor rules keep the ledger canaryfence \(\d{4}-\d{2}-\d{2}; fact\)$/);
+ }, 60_000);
+
+ test('a keyless brain ranks by keyword and makes no embedding call', async () => {
+ let embedCalls = 0;
+ try {
+ resetGateway();
+ configureGateway({ embedding_model: 'openai:text-embedding-3-small', embedding_dimensions: DIMS, env: {} });
+ __setEmbedTransportForTests((async ({ values }: { values: string[] }) => { embedCalls++; return { embeddings: values.map(vectorFor) }; }) as never);
+ const out = await recall(alice, 'budget ledger');
+ expect(out.isError).toBe(false);
+ expect(out.all).toContain('canaryworld');
+ expect(embedCalls).toBe(0);
+ resetGateway();
+ keyedEmbeddings(() => { embedCalls++; });
+ await recall(alice, 'budget ledger');
+ expect(embedCalls).toBeGreaterThan(0);
+ } finally {
+ resetGateway();
+ keyedEmbeddings();
+ }
+ }, 60_000);
+ });
+}