Multiplayer agent harness for work.
$feat: add scope-aware memory providers\n\nCo-Authored-By: QM <[email protected]>
Joshua France2d3266640f69
diff --git a/README.md b/README.mdindex 145a890e4..aa34ab320 100644--- a/README.md+++ b/README.md@@ -79,8 +79,8 @@ uses Bolt; the web UI builds with Vite and renders with Lit.The core itself is generic. Everything specific to one company — org config, custom toolsand skills, sandbox image, infrastructure — lives in a **deployment directory** that the[`qm` CLI](./cli/README.md) validates and deploys. Every substrate (harness, session-store, sandbox, memory) sits behind an interface, so production implementations swap in-via one wiring file.+store, sandbox, memory) sits behind an interface. Memory can also be routed by scope to+[external providers](./docs/memory-providers.md) while retaining the built-in notebook.## Security and secretsdiff --git a/docs/memory-providers.md b/docs/memory-providers.mdnew file mode 100644index 000000000..f1da7eaab--- /dev/null+++ b/docs/memory-providers.md@@ -0,0 +1,52 @@+# Memory providers++QM keeps its built-in notebook memory unless `MEMORY_PROVIDER_CONFIG` defines a scope-aware provider router. Routes independently select where each scope recalls from, accepts explicit writes, and receives automatic post-turn capture.++```json+{+ "providers": [+ {+ "id": "org-brain",+ "type": "mcp",+ "url": "http://brain-relay.internal:8080",+ "timeoutMs": 3000,+ "read": {+ "tool": "read_brain",+ "clientIdEnv": "BRAIN_RO_CLIENT_ID",+ "clientSecretEnv": "BRAIN_RO_CLIENT_SECRET"+ },+ "write": {+ "tool": "write_brain",+ "clientIdEnv": "BRAIN_RW_CLIENT_ID",+ "clientSecretEnv": "BRAIN_RW_CLIENT_SECRET"+ }+ }+ ],+ "routes": [+ {+ "provider": "default",+ "scopes": ["personal", "channel", "group", "team"],+ "capture": "automatic"+ },+ {+ "provider": "org-brain",+ "scopes": ["org"],+ "capture": "explicit",+ "manage": false,+ "label": "Organizational knowledge"+ }+ ]+}+```++Set the compact JSON document as `MEMORY_PROVIDER_CONFIG`. `default` names QM's local/Postgres notebook. A scope selector may be a kind (`org`) or an exact scope ID (`org:acme`). Earlier matching routes can compose multiple recall providers; the first route with `manage` enabled supplies notebook editing and revision history.++Capture policies are:++- `off`: recall only;+- `explicit`: writes only through deliberate memory actions;+- `automatic`: explicit writes plus post-turn capture.++MCP reads receive `query` and `acting_user` by default. Writes receive `content` and `acting_user`. Operation entries can map optional fields with `queryArg`, `contentArg`, `actorArg`, `scopeArg`, `maxCharsArg`, `inputArg`, `replyArg`, `capturedAtArg`, `sourceArg`, and `idempotencyArg`. Only configured optional fields are sent, so providers can match strict MCP schemas.++Read and write operations use separate OAuth client-credential pairs. Omit `write` and set route capture to `off` for a read-only provider. External routes fail open by default so an outage does not block recall; set `failOpen: false` on a route to make it strict. Provider calls time out after `timeoutMs` (3 seconds by default). Explicit writes always fail visibly. QM continues to decide readable/writable scopes and passes the acting user to the provider.diff --git a/src/api/routes/surface.ts b/src/api/routes/surface.tsindex 5172511cb..99bb5d83e 100644--- a/src/api/routes/surface.ts+++ b/src/api/routes/surface.ts@@ -673,7 +673,9 @@ async function agentMemory(ctx: ApiCtx): Promise<void> {const results: Array<{ scopeId: string; fact: string }> = [];for (const scope of scopes) {if (results.length >= limit) break;- for (const fact of await deps.memory.query(scope, b.query, limit - results.length)) {+ for (const fact of await deps.memory.query(scope, b.query, limit - results.length, {+ actorId: capability.actorId,+ })) {results.push({ scopeId: scope, fact });}}@@ -707,7 +709,10 @@ async function agentMemory(ctx: ApiCtx): Promise<void> {if (method === "POST" && pathname === "/v1/memory/facts") {const facts = parseFacts(body);if (typeof facts === "string") return sendJson(res, 400, { error: "bad_request", message: facts });- const added = await deps.memory.capture(write, facts, Date.now(), capability.actorId);+ const added = await deps.memory.capture(write, facts, Date.now(), capability.actorId, {+ mode: "explicit",+ actorId: capability.actorId,+ });audit(deps, {principalId: capability.actorId,action: "memory.agent.capture",diff --git a/src/config.ts b/src/config.tsindex 6acc29e2c..468c2498b 100644--- a/src/config.ts+++ b/src/config.ts@@ -8,6 +8,7 @@ import {type MemoryRecallMode,} from "./memory/policy.ts";import { parseMemoryStrategyKind, type MemoryStrategyKind } from "./memory/strategy.ts";+import { parseMemoryProviderConfig, type MemoryProviderConfig } from "./memory/provider-config.ts";import { sanitizeBranding } from "./resolution/branding.ts";import type { OrgBranding } from "./resolution/config-store.ts";import { validateCoreSecretEnv } from "./deployment/secret-schema.ts";@@ -123,6 +124,7 @@ export interface Config {memoryRecall: MemoryRecallMode;memoryCapture: MemoryCaptureMode;memoryStrategy: MemoryStrategyKind;+ memoryProviderConfig?: MemoryProviderConfig;memoryConsolidateAfter?: number;memoryCaptureQuietMs: number;memoryCaptureMaxTurns?: number;@@ -790,6 +792,7 @@ export function loadConfig(env: NodeJS.ProcessEnv = process.env): Config {numEnvStrict("RUN_MAX_AGE_MS", env.RUN_MAX_AGE_MS) ??(turnWallClockMs > 0 ? 2 * turnWallClockMs : CONFIG_DEFAULTS.runMaxAgeMs);const slack = slackPluginConfigFromEnv(env);+ const memoryProviderConfig = parseMemoryProviderConfig(env.MEMORY_PROVIDER_CONFIG, env);return {production: env.NODE_ENV === "production",allowUnauthenticatedCore: boolEnvStrict("ALLOW_UNAUTHENTICATED_CORE", env.ALLOW_UNAUTHENTICATED_CORE) ?? false,@@ -924,6 +927,7 @@ export function loadConfig(env: NodeJS.ProcessEnv = process.env): Config {memoryRecall: parseMemoryRecallMode(env.MEMORY_RECALL),memoryCapture: parseMemoryCaptureMode(env.MEMORY_CAPTURE),memoryStrategy: parseMemoryStrategyKind(env.MEMORY_STRATEGY),+ ...(memoryProviderConfig ? { memoryProviderConfig } : {}),...(numEnvStrict("MEMORY_CONSOLIDATE_AFTER", env.MEMORY_CONSOLIDATE_AFTER) !== undefined? { memoryConsolidateAfter: numEnvStrict("MEMORY_CONSOLIDATE_AFTER", env.MEMORY_CONSOLIDATE_AFTER) }: {}),diff --git a/src/core/orchestrator.ts b/src/core/orchestrator.tsindex 904a92941..4b067e6c7 100644--- a/src/core/orchestrator.ts+++ b/src/core/orchestrator.ts@@ -832,7 +832,15 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {let recallMs = 0;for (const recallScope of recallScopes) {const recallStart = Date.now();- const body = (await deps.memory.recall(recallScope)).trim();+ const body = (+ await deps.memory.recall(recallScope, {+ query: input.text,+ actorId: actor.id,+ conversationScopeId: scopeId,+ maxChars: 6_000,+ ...(automatedTurn ? { autonomous: true } : {}),+ })+ ).trim();recallMs += Date.now() - recallStart;if (!body) continue;recalledSections.push(recallScopes.length === 1 ? body : `### ${recallScope}\n${body}`);@@ -3003,6 +3011,8 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {actorId: actor.id,...(automatedTurn ? { autonomous: true } : {}),...(conversationLabel ? { conversationLabel } : {}),+ sessionId: session.id,+ idempotencyKey: input.runId ?? `${session.id}:${spine.turnUserEntrySeq ?? "turn"}`,});} catch (e) {deps.errors?.record({diff --git a/src/memory/mcp-memory-provider.ts b/src/memory/mcp-memory-provider.tsnew file mode 100644index 000000000..d64a61648--- /dev/null+++ b/src/memory/mcp-memory-provider.ts@@ -0,0 +1,82 @@+import { mcpResultText, type McpClient, type McpToolResult } from "../mcp/mcp-client.ts";+import type { MemoryService } from "./memory-service.ts";++export interface McpMemoryOperation {+ client: McpClient;+ tool: string;+ queryArg?: string;+ contentArg?: string;+ actorArg?: string;+ scopeArg?: string;+ maxCharsArg?: string;+ inputArg?: string;+ replyArg?: string;+ capturedAtArg?: string;+ sourceArg?: string;+ idempotencyArg?: string;+ timeoutMs: number;+}++async function withTimeout<T>(promise: Promise<T>, timeoutMs: number): Promise<T> {+ let timer: NodeJS.Timeout | undefined;+ try {+ return await Promise.race([+ promise,+ new Promise<never>((_, reject) => {+ timer = setTimeout(() => reject(new Error(`memory provider timed out after ${timeoutMs}ms`)), timeoutMs);+ timer.unref?.();+ }),+ ]);+ } finally {+ if (timer) clearTimeout(timer);+ }+}++function resultText(result: McpToolResult): string {+ const text = mcpResultText(result);+ if (text) return text;+ return result.structuredContent == null ? "" : JSON.stringify(result.structuredContent);+}++export function createMcpMemoryProvider(opts: { read: McpMemoryOperation; write?: McpMemoryOperation }): MemoryService {+ const read = async (scopeId: string, query: string, actorId?: string, maxChars?: number): Promise<string> => {+ const op = opts.read;+ const args: Record<string, unknown> = { [op.queryArg ?? "query"]: query };+ if (actorId) args[op.actorArg ?? "acting_user"] = actorId;+ if (op.scopeArg) args[op.scopeArg] = scopeId;+ if (maxChars && op.maxCharsArg) args[op.maxCharsArg] = maxChars;+ const text = resultText(await withTimeout(op.client.callTool(op.tool, args), op.timeoutMs));+ return maxChars && text.length > maxChars ? text.slice(0, maxChars) : text;+ };++ return {+ recall: (scopeId, context) => read(scopeId, context?.query ?? "", context?.actorId, context?.maxChars),++ async capture(scopeId, facts, at, author, context) {+ const op = opts.write;+ if (!op) throw new Error("brain write is not configured");+ const args: Record<string, unknown> = { [op.contentArg ?? "content"]: facts.join("\n") };+ if (context?.input && op.inputArg) args[op.inputArg] = context.input;+ if (context?.reply && op.replyArg) args[op.replyArg] = context.reply;+ if (op.capturedAtArg) args[op.capturedAtArg] = at;+ if (op.sourceArg) args[op.sourceArg] = context?.mode ?? "explicit";+ if (context?.idempotencyKey && op.idempotencyArg) args[op.idempotencyArg] = context.idempotencyKey;+ const actorId = context?.actorId ?? author;+ if (actorId) args[op.actorArg ?? "acting_user"] = actorId;+ if (op.scopeArg) args[op.scopeArg] = scopeId;+ await withTimeout(op.client.callTool(op.tool, args), op.timeoutMs);+ return facts.length;+ },++ async query(scopeId, q, limit = 20, context) {+ const text = await read(scopeId, q, context?.actorId, context?.maxChars);+ return text ? text.split("\n").filter(Boolean).slice(0, limit) : [];+ },++ read: (scopeId) => read(scopeId, ""),++ async replace() {+ throw new Error("MCP memory providers do not support notebook replacement");+ },+ };+}diff --git a/src/memory/memory-service.ts b/src/memory/memory-service.tsindex d52e3afd0..eab6c9a9a 100644--- a/src/memory/memory-service.ts+++ b/src/memory/memory-service.ts@@ -26,10 +26,36 @@ interface MemoryHead {updatedAt?: number;}+export interface MemoryRecallContext {+ query?: string;+ actorId?: string;+ sessionId?: string;+ conversationScopeId?: ScopeId;+ maxChars?: number;+ autonomous?: boolean;+}++export interface MemoryCaptureContext {+ mode: "explicit" | "automatic";+ actorId?: string;+ sessionId?: string;+ conversationScopeId?: ScopeId;+ input?: string;+ reply?: string;+ autonomous?: boolean;+ idempotencyKey?: string;+}+export interface MemoryService {- recall(scopeId: ScopeId): Promise<string>;- capture(scopeId: ScopeId, facts: string[], at: number, author?: string): Promise<number>;- query(scopeId: ScopeId, q: string, limit?: number): Promise<string[]>;+ recall(scopeId: ScopeId, context?: MemoryRecallContext): Promise<string>;+ capture(+ scopeId: ScopeId,+ facts: string[],+ at: number,+ author?: string,+ context?: MemoryCaptureContext,+ ): Promise<number>;+ query(scopeId: ScopeId, q: string, limit?: number, context?: MemoryRecallContext): Promise<string[]>;read(scopeId: ScopeId): Promise<string>;replace(scopeId: ScopeId, content: string, author?: string): Promise<void>;readHead?(scopeId: ScopeId): Promise<MemoryHead>;@@ -180,6 +206,7 @@ export async function ccCaptureToPersonal(facts: string[],at: number,sourceLabel?: string,+ context?: MemoryCaptureContext,): Promise<number> {const target = ccTargetFor(origin, actorId);if (!target || !facts.length) return 0;@@ -191,5 +218,5 @@ export async function ccCaptureToPersonal(.slice(0, 60);const source = clean || (kind === "channel" ? "a channel" : "a group conversation");const tagged = facts.map((f) => `${f} (said in ${source})`);- return memory.capture(target, tagged, at, `cc:${origin}`);+ return memory.capture(target, tagged, at, `cc:${origin}`, context);}diff --git a/src/memory/provider-config.ts b/src/memory/provider-config.tsnew file mode 100644index 000000000..cf4a61e5f--- /dev/null+++ b/src/memory/provider-config.ts@@ -0,0 +1,169 @@+import { parseScopeId, type ScopeId, type ScopeKind } from "../types.ts";+import type { MemoryCapturePolicy, MemoryProviderRoute } from "./provider-router.ts";++const KINDS = new Set<ScopeKind>(["personal", "channel", "team", "org", "group"]);+const ID = /^[a-z][a-z0-9-]{0,62}$/;+const ARG = /^[a-zA-Z_][a-zA-Z0-9_]{0,63}$/;+const ENV = /^[A-Z][A-Z0-9_]*$/;++export interface McpMemoryAuthConfig {+ clientId: string;+ clientSecret: string;+}++export interface McpMemoryOperationConfig {+ tool: string;+ auth: McpMemoryAuthConfig;+ queryArg?: string;+ contentArg?: string;+ actorArg?: string;+ scopeArg?: string;+ maxCharsArg?: string;+ inputArg?: string;+ replyArg?: string;+ capturedAtArg?: string;+ sourceArg?: string;+ idempotencyArg?: string;+}++export interface McpMemoryProviderConfig {+ id: string;+ type: "mcp";+ url: string;+ read: McpMemoryOperationConfig;+ write?: McpMemoryOperationConfig;+ timeoutMs: number;+}++export interface MemoryProviderConfig {+ providers: McpMemoryProviderConfig[];+ routes: MemoryProviderRoute[];+}++function object(value: unknown, at: string): Record<string, unknown> {+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error(`${at} must be an object`);+ return value as Record<string, unknown>;+}++function string(value: unknown, at: string): string {+ if (typeof value !== "string" || !value) throw new Error(`${at} must be a non-empty string`);+ return value;+}++function privateMcpUrl(value: unknown, at: string): string {+ const raw = string(value, at);+ let url: URL;+ try {+ url = new URL(raw);+ } catch {+ throw new Error(`${at} must be a valid URL`);+ }+ const privateHttp =+ url.protocol === "http:" &&+ (url.hostname === "localhost" ||+ url.hostname === "127.0.0.1" ||+ url.hostname.endsWith(".internal") ||+ url.hostname.endsWith(".flycast") ||+ url.hostname.endsWith(".local"));+ if ((url.protocol !== "https:" && !privateHttp) || url.username || url.password || url.hash)+ throw new Error(`${at} must use HTTPS or a recognized private HTTP host`);+ return raw.replace(/\/+$/, "");+}++function operation(value: unknown, at: string, env: NodeJS.ProcessEnv): McpMemoryOperationConfig {+ const raw = object(value, at);+ const clientIdEnv = string(raw.clientIdEnv, `${at}.clientIdEnv`);+ const clientSecretEnv = string(raw.clientSecretEnv, `${at}.clientSecretEnv`);+ if (!ENV.test(clientIdEnv) || !ENV.test(clientSecretEnv)) throw new Error(`${at} credential env names are invalid`);+ const clientId = env[clientIdEnv];+ const clientSecret = env[clientSecretEnv];+ if (!clientId || !clientSecret) throw new Error(`${at} requires ${clientIdEnv} and ${clientSecretEnv}`);+ const out: McpMemoryOperationConfig = {+ tool: string(raw.tool, `${at}.tool`),+ auth: { clientId, clientSecret },+ };+ for (const key of [+ "queryArg",+ "contentArg",+ "actorArg",+ "scopeArg",+ "maxCharsArg",+ "inputArg",+ "replyArg",+ "capturedAtArg",+ "sourceArg",+ "idempotencyArg",+ ] as const) {+ if (raw[key] === undefined) continue;+ const name = string(raw[key], `${at}.${key}`);+ if (!ARG.test(name)) throw new Error(`${at}.${key} is invalid`);+ out[key] = name;+ }+ return out;+}++function scope(value: unknown, at: string): ScopeKind | ScopeId {+ const raw = string(value, at);+ if (KINDS.has(raw as ScopeKind)) return raw as ScopeKind;+ if (!parseScopeId(raw).kind) throw new Error(`${at} must be a scope kind or scope id`);+ return raw;+}++export function parseMemoryProviderConfig(+ value: string | undefined,+ env: NodeJS.ProcessEnv,+): MemoryProviderConfig | undefined {+ if (!value) return undefined;+ let parsed: unknown;+ try {+ parsed = JSON.parse(value);+ } catch {+ throw new Error("MEMORY_PROVIDER_CONFIG must be valid JSON");+ }+ const root = object(parsed, "MEMORY_PROVIDER_CONFIG");+ if (!Array.isArray(root.providers) || !Array.isArray(root.routes))+ throw new Error("MEMORY_PROVIDER_CONFIG requires providers and routes arrays");+ const providers = root.providers.map((value, i) => {+ const raw = object(value, `MEMORY_PROVIDER_CONFIG.providers[${i}]`);+ const id = string(raw.id, `MEMORY_PROVIDER_CONFIG.providers[${i}].id`);+ if (!ID.test(id) || id === "default") throw new Error(`invalid memory provider id: ${id}`);+ if (raw.type !== "mcp") throw new Error(`memory provider ${id} has unsupported type`);+ const timeoutMs = raw.timeoutMs === undefined ? 3_000 : raw.timeoutMs;+ if (!Number.isSafeInteger(timeoutMs) || Number(timeoutMs) <= 0 || Number(timeoutMs) > 30_000)+ throw new Error(`memory provider ${id}.timeoutMs must be an integer from 1 to 30000`);+ return {+ id,+ type: "mcp" as const,+ url: privateMcpUrl(raw.url, `memory provider ${id}.url`),+ timeoutMs: Number(timeoutMs),+ read: operation(raw.read, `memory provider ${id}.read`, env),+ ...(raw.write ? { write: operation(raw.write, `memory provider ${id}.write`, env) } : {}),+ };+ });+ const ids = new Set(["default", ...providers.map(({ id }) => id)]);+ if (ids.size !== providers.length + 1) throw new Error("memory provider ids must be unique");+ const providerById = new Map(providers.map((provider) => [provider.id, provider]));+ const routes = root.routes.map((value, i): MemoryProviderRoute => {+ const raw = object(value, `MEMORY_PROVIDER_CONFIG.routes[${i}]`);+ const provider = string(raw.provider, `MEMORY_PROVIDER_CONFIG.routes[${i}].provider`);+ if (!ids.has(provider)) throw new Error(`unknown memory provider in route: ${provider}`);+ if (!Array.isArray(raw.scopes) || !raw.scopes.length) throw new Error(`memory route ${i} requires scopes`);+ const capture = raw.capture ?? "off";+ if (!(["off", "explicit", "automatic"] as unknown[]).includes(capture))+ throw new Error(`memory route ${i} has invalid capture policy`);+ if (provider !== "default" && capture !== "off" && !providerById.get(provider)?.write)+ throw new Error(`memory route ${i} enables capture but provider ${provider} has no write operation`);+ return {+ provider,+ scopes: raw.scopes.map((value, j) => scope(value, `memory route ${i}.scopes[${j}]`)),+ capture: capture as MemoryCapturePolicy,+ ...(typeof raw.recall === "boolean" ? { recall: raw.recall } : {}),+ manage: provider === "default",+ ...(typeof raw.manage === "boolean" ? { manage: raw.manage } : {}),+ ...(typeof raw.label === "string" && raw.label ? { label: raw.label } : {}),+ failOpen: provider !== "default",+ ...(typeof raw.failOpen === "boolean" ? { failOpen: raw.failOpen } : {}),+ };+ });+ return { providers, routes };+}diff --git a/src/memory/provider-factory.ts b/src/memory/provider-factory.tsnew file mode 100644index 000000000..b1e56bc38--- /dev/null+++ b/src/memory/provider-factory.ts@@ -0,0 +1,57 @@+import type { McpFetch } from "../mcp/mcp-client.ts";+import { createMcpClient } from "../mcp/mcp-client.ts";+import { errMessage } from "../util/errors.ts";+import { createMcpMemoryProvider, type McpMemoryOperation } from "./mcp-memory-provider.ts";+import type { MemoryProviderConfig, McpMemoryOperationConfig } from "./provider-config.ts";+import { createRoutedMemoryService } from "./provider-router.ts";+import type { MemoryService } from "./memory-service.ts";++function operation(+ url: string,+ spec: McpMemoryOperationConfig,+ timeoutMs: number,+ fetchImpl?: McpFetch,+): McpMemoryOperation {+ return {+ client: createMcpClient({+ url,+ auth: { mode: "client-credentials", ...spec.auth },+ ...(fetchImpl ? { fetchImpl } : {}),+ }),+ tool: spec.tool,+ timeoutMs,+ ...(spec.queryArg ? { queryArg: spec.queryArg } : {}),+ ...(spec.contentArg ? { contentArg: spec.contentArg } : {}),+ ...(spec.actorArg ? { actorArg: spec.actorArg } : {}),+ ...(spec.scopeArg ? { scopeArg: spec.scopeArg } : {}),+ ...(spec.maxCharsArg ? { maxCharsArg: spec.maxCharsArg } : {}),+ ...(spec.inputArg ? { inputArg: spec.inputArg } : {}),+ ...(spec.replyArg ? { replyArg: spec.replyArg } : {}),+ ...(spec.capturedAtArg ? { capturedAtArg: spec.capturedAtArg } : {}),+ ...(spec.sourceArg ? { sourceArg: spec.sourceArg } : {}),+ ...(spec.idempotencyArg ? { idempotencyArg: spec.idempotencyArg } : {}),+ };+}++export function createConfiguredMemoryService(opts: {+ defaultMemory: MemoryService;+ config?: MemoryProviderConfig;+ fetchImpl?: McpFetch;+ onError?: (error: unknown, provider: string, operation: "recall" | "query") => void;+}): MemoryService {+ if (!opts.config) return opts.defaultMemory;+ const providers: Record<string, MemoryService> = { default: opts.defaultMemory };+ for (const provider of opts.config.providers) {+ providers[provider.id] = createMcpMemoryProvider({+ read: operation(provider.url, provider.read, provider.timeoutMs, opts.fetchImpl),+ ...(provider.write ? { write: operation(provider.url, provider.write, provider.timeoutMs, opts.fetchImpl) } : {}),+ });+ }+ return createRoutedMemoryService({+ providers,+ routes: opts.config.routes,+ onError:+ opts.onError ??+ ((error, provider, operation) => console.error(`[memory] ${provider} ${operation} failed: ${errMessage(error)}`)),+ });+}diff --git a/src/memory/provider-router.ts b/src/memory/provider-router.tsnew file mode 100644index 000000000..66d0101e2--- /dev/null+++ b/src/memory/provider-router.ts@@ -0,0 +1,136 @@+import { parseScopeId, type ScopeId, type ScopeKind } from "../types.ts";+import type { MemoryCaptureContext, MemoryRecallContext, MemoryRevision, MemoryService } from "./memory-service.ts";++export type MemoryCapturePolicy = "off" | "explicit" | "automatic";++export interface MemoryProviderRoute {+ provider: string;+ scopes: readonly (ScopeKind | ScopeId)[];+ recall?: boolean;+ capture?: MemoryCapturePolicy;+ manage?: boolean;+ label?: string;+ failOpen?: boolean;+}++function matches(route: MemoryProviderRoute, scopeId: ScopeId): boolean {+ const kind = parseScopeId(scopeId).kind;+ return route.scopes.some((scope) => scope === scopeId || scope === kind);+}++function captureAllowed(policy: MemoryCapturePolicy | undefined, mode: "explicit" | "automatic"): boolean {+ if (policy === "automatic") return true;+ return policy === "explicit" && mode === "explicit";+}++export function createRoutedMemoryService(opts: {+ providers: Readonly<Record<string, MemoryService>>;+ routes: readonly MemoryProviderRoute[];+ onError?: (error: unknown, provider: string, operation: "recall" | "query") => void;+}): MemoryService {+ const routesFor = (scopeId: ScopeId): MemoryProviderRoute[] => opts.routes.filter((route) => matches(route, scopeId));+ const providerFor = (route: MemoryProviderRoute): MemoryService => {+ const provider = opts.providers[route.provider];+ if (!provider) throw new Error(`unknown memory provider: ${route.provider}`);+ return provider;+ };+ const managerFor = (scopeId: ScopeId): MemoryService | undefined => {+ const route = routesFor(scopeId).find((candidate) => candidate.manage !== false);+ return route ? providerFor(route) : undefined;+ };++ return {+ async recall(scopeId, context) {+ const routes = routesFor(scopeId).filter((route) => route.recall !== false);+ const recalled = await Promise.all(+ routes.map(async (route) => {+ try {+ return { route, body: (await providerFor(route).recall(scopeId, context)).trim() };+ } catch (error) {+ if (!route.failOpen) throw error;+ opts.onError?.(error, route.provider, "recall");+ return { route, body: "" };+ }+ }),+ );+ const present = recalled.filter(({ body }) => body);+ if (present.length === 0) return "";+ if (present.length === 1) {+ const { route, body } = present[0]!;+ return route.label ? `### ${route.label}\n${body}` : body;+ }+ return present.map(({ route, body }) => `### ${route.label ?? route.provider}\n${body}`).join("\n\n");+ },++ async capture(scopeId, facts, at, author, context) {+ const mode = context?.mode ?? "explicit";+ const routes = routesFor(scopeId).filter((route) => captureAllowed(route.capture, mode));+ const counts = await Promise.all(+ routes.map((route) => providerFor(route).capture(scopeId, facts, at, author, context)),+ );+ return counts.length ? Math.max(...counts) : 0;+ },++ async query(scopeId, q, limit = 20, context) {+ const routes = routesFor(scopeId).filter((route) => route.recall !== false);+ const rows = await Promise.all(+ routes.map(async (route) => {+ try {+ return await providerFor(route).query(scopeId, q, limit, context);+ } catch (error) {+ if (!route.failOpen) throw error;+ opts.onError?.(error, route.provider, "query");+ return [];+ }+ }),+ );+ return [...new Set(rows.flat())].slice(0, limit);+ },++ async read(scopeId) {+ const manager = managerFor(scopeId);+ return manager ? manager.read(scopeId) : "";+ },++ async replace(scopeId, content, author) {+ const manager = managerFor(scopeId);+ if (!manager) throw new Error(`memory for ${scopeId} is not directly editable`);+ await manager.replace(scopeId, content, author);+ },++ async readHead(scopeId) {+ const manager = managerFor(scopeId);+ if (!manager) return { content: "", revision: "" };+ if (manager.readHead) return manager.readHead(scopeId);+ return { content: await manager.read(scopeId), revision: "" };+ },++ async replaceIfRevision(scopeId, content, revision, author) {+ const manager = managerFor(scopeId);+ if (!manager?.replaceIfRevision) return false;+ return manager.replaceIfRevision(scopeId, content, revision, author);+ },++ async history(scopeId, limit): Promise<MemoryRevision[]> {+ return (await managerFor(scopeId)?.history?.(scopeId, limit)) ?? [];+ },++ async restore(scopeId, revision, expectedRevision, author) {+ return (await managerFor(scopeId)?.restore?.(scopeId, revision, expectedRevision, author)) ?? false;+ },++ async updatedAt(scopeId) {+ return managerFor(scopeId)?.updatedAt?.(scopeId);+ },++ async metadata() {+ const out = new Map<ScopeId, { bytes: number; updatedAt?: number }>();+ for (const provider of new Set(opts.routes.filter((route) => route.manage !== false).map(providerFor))) {+ for (const [scopeId, meta] of (await provider.metadata?.()) ?? []) out.set(scopeId, meta);+ }+ return out;+ },+ };+}++export type { MemoryCaptureContext, MemoryRecallContext };diff --git a/src/memory/strategies/consolidation.ts b/src/memory/strategies/consolidation.tsindex 10d8d512b..00f707fe5 100644--- a/src/memory/strategies/consolidation.ts+++ b/src/memory/strategies/consolidation.ts@@ -178,8 +178,8 @@ export function createConsolidatingMemory(const perScope = createKeyedQueue<ScopeId>();const memory: MemoryService = {...base,- async capture(s, facts, at, author) {- const added = await perScope(s, () => base.capture(s, facts, at, author));+ async capture(s, facts, at, author, context) {+ const added = await perScope(s, () => base.capture(s, facts, at, author, context));if (added > 0) void perScope(s, () => consolidator.maybeMaintain(s)).catch(() => {});return added;},diff --git a/src/memory/strategies/per-turn.ts b/src/memory/strategies/per-turn.tsindex ba18acb48..d57158e68 100644--- a/src/memory/strategies/per-turn.ts+++ b/src/memory/strategies/per-turn.ts@@ -64,6 +64,8 @@ export interface Burst {autonomous?: boolean;conversationScopeId: ScopeId;conversationLabel?: string;+ sessionId?: string;+ idempotencyKey?: string;turns: Array<{ input: string; reply: string }>;timer?: NodeJS.Timeout;}@@ -76,6 +78,8 @@ export type TurnEndCtx = {autonomous?: boolean;conversationScopeId?: ScopeId;conversationLabel?: string;+ sessionId?: string;+ idempotencyKey?: string;};export function isAutonomousBurst(burst: Pick<Burst, "actorId" | "autonomous">): boolean {@@ -89,7 +93,17 @@ export function createBurstBuffer(onError?: (e: unknown, burst: Burst) => void,): (ctx: TurnEndCtx) => Promise<void> {const bursts = new Map<string, Burst>();- return async ({ scopeId, input, reply, actorId, autonomous, conversationScopeId, conversationLabel }) => {+ return async ({+ scopeId,+ input,+ reply,+ actorId,+ autonomous,+ conversationScopeId,+ conversationLabel,+ sessionId,+ idempotencyKey,+ }) => {const burst: Burst = {scopeId,conversationScopeId: conversationScopeId ?? scopeId,@@ -97,6 +111,8 @@ export function createBurstBuffer(...(actorId !== undefined ? { actorId } : {}),...(autonomous !== undefined ? { autonomous } : {}),...(conversationLabel !== undefined ? { conversationLabel } : {}),+ ...(sessionId !== undefined ? { sessionId } : {}),+ ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),};if (quietMs <= 0) return flush(burst);@@ -135,7 +151,16 @@ export function createPerTurnStrategy(deps: {const facts = await extractFacts(deps.harness, burst.turns, { autonomous });if (!facts.length) return;const at = Date.now();- await deps.memory.capture(burst.scopeId, facts, at);+ await deps.memory.capture(burst.scopeId, facts, at, burst.actorId, {+ mode: "automatic",+ ...(burst.actorId ? { actorId: burst.actorId } : {}),+ conversationScopeId: burst.conversationScopeId,+ input: burst.turns.map((turn) => turn.input).join("\n\n"),+ reply: burst.turns.map((turn) => turn.reply).join("\n\n"),+ ...(autonomous ? { autonomous: true } : {}),+ ...(burst.sessionId ? { sessionId: burst.sessionId } : {}),+ ...(burst.idempotencyKey ? { idempotencyKey: burst.idempotencyKey } : {}),+ });if (autonomous) return;await ccCaptureToPersonal(deps.memory,@@ -144,6 +169,13 @@ export function createPerTurnStrategy(deps: {facts,at,burst.conversationLabel,+ {+ mode: "automatic",+ ...(burst.actorId ? { actorId: burst.actorId } : {}),+ conversationScopeId: burst.conversationScopeId,+ ...(burst.sessionId ? { sessionId: burst.sessionId } : {}),+ ...(burst.idempotencyKey ? { idempotencyKey: `${burst.idempotencyKey}:personal` } : {}),+ },);}diff --git a/src/memory/strategies/scratch-promote.ts b/src/memory/strategies/scratch-promote.tsindex 4a6472b30..3473f5abe 100644--- a/src/memory/strategies/scratch-promote.ts+++ b/src/memory/strategies/scratch-promote.ts@@ -183,10 +183,25 @@ export function createScratchPromote(deps: ScratchPromoteDeps): { strategy: Memoconst facts = await extractFacts(deps.harness, burst.turns, { autonomous });if (!facts.length) return;const at = Date.now();- await memory.capture(burst.scopeId, facts, at);+ await memory.capture(burst.scopeId, facts, at, burst.actorId, {+ mode: "automatic",+ ...(burst.actorId ? { actorId: burst.actorId } : {}),+ conversationScopeId: burst.conversationScopeId,+ input: burst.turns.map((turn) => turn.input).join("\n\n"),+ reply: burst.turns.map((turn) => turn.reply).join("\n\n"),+ ...(autonomous ? { autonomous: true } : {}),+ ...(burst.sessionId ? { sessionId: burst.sessionId } : {}),+ ...(burst.idempotencyKey ? { idempotencyKey: burst.idempotencyKey } : {}),+ });const ccTarget = autonomous ? null : ccTargetFor(burst.conversationScopeId, burst.actorId);if (!ccTarget) return;- await ccCaptureToPersonal(memory, burst.conversationScopeId, burst.actorId, facts, at, burst.conversationLabel);+ await ccCaptureToPersonal(memory, burst.conversationScopeId, burst.actorId, facts, at, burst.conversationLabel, {+ mode: "automatic",+ ...(burst.actorId ? { actorId: burst.actorId } : {}),+ conversationScopeId: burst.conversationScopeId,+ ...(burst.sessionId ? { sessionId: burst.sessionId } : {}),+ ...(burst.idempotencyKey ? { idempotencyKey: `${burst.idempotencyKey}:personal` } : {}),+ });}const strategy: MemoryStrategy = {diff --git a/src/memory/strategy.ts b/src/memory/strategy.tsindex e71ab161a..184e971ee 100644--- a/src/memory/strategy.ts+++ b/src/memory/strategy.ts@@ -20,6 +20,8 @@ export interface MemoryStrategy {autonomous?: boolean;conversationScopeId?: ScopeId;conversationLabel?: string;+ sessionId?: string;+ idempotencyKey?: string;}): Promise<void>;maintain?(scopeId: ScopeId): Promise<void>;promptLines?(): string[];diff --git a/src/tools/primitives.ts b/src/tools/primitives.tsindex d3ea49029..d34703d1f 100644--- a/src/tools/primitives.ts+++ b/src/tools/primitives.ts@@ -863,7 +863,7 @@ export function createToolContext(deps: ToolContextDeps): ToolContext {return timed("recall", async () => {const out: string[] = [];for (const scope of read) {- for (const fact of await deps.memory!.query(scope, q, limit)) {+ for (const fact of await deps.memory!.query(scope, q, limit, { actorId: deps.createdBy })) {out.push(read.length > 1 ? `[${scope}] ${fact}` : fact);}}@@ -880,7 +880,11 @@ export function createToolContext(deps: ToolContextDeps): ToolContext {async memoryRemember(facts: string[]): Promise<number | null> {const write = deps.memoryAccess?.write;if (!deps.memory || !write) return null;- return once(() => timed("memory_write", () => deps.memory!.capture(write, facts, Date.now(), deps.createdBy)));+ return once(() =>+ timed("memory_write", () =>+ deps.memory!.capture(write, facts, Date.now(), deps.createdBy, { mode: "explicit", actorId: deps.createdBy }),+ ),+ );},async memoryRewrite(content: string): Promise<true | null> {diff --git a/src/wiring.ts b/src/wiring.tsindex 7b8d4c749..d0fa40155 100644--- a/src/wiring.ts+++ b/src/wiring.ts@@ -100,6 +100,7 @@ import {import type { DeployGitArchive } from "./deploy/deploy-git-store.ts";import { createLocalWorkspaceStore, type WorkspaceStore } from "./workspace/workspace-store.ts";import { createMemoryService, type MemoryService } from "./memory/memory-service.ts";+import { createConfiguredMemoryService } from "./memory/provider-factory.ts";import { createPostgresMemoryService } from "./memory/postgres-memory-service.ts";import { createMcpServerStore, type McpServer, type McpServerStore } from "./mcp/mcp-server-store.ts";import { createMcpToolService, type McpToolService } from "./mcp/mcp-tool-service.ts";@@ -595,9 +596,13 @@ export function buildApp(const files: FileArtifactStore = config.databaseUrl? createPostgresFileArtifactStore(config.databaseUrl, fileBytes): createMemoryFileArtifactStore(fileBytes);- const baseMemory: MemoryService = config.databaseUrl+ const defaultMemory: MemoryService = config.databaseUrl? createPostgresMemoryService(config.databaseUrl): createMemoryService(workspace);+ const baseMemory: MemoryService = createConfiguredMemoryService({+ defaultMemory,+ config: config.memoryProviderConfig,+ });const mcpServers = createMcpServerStore(artifactMap<McpServer>("mcp_servers"));const mcpToolService = createMcpToolService({ servers: mcpServers, audit: auditLog });const mcpTools = () => mcpToolService.toolDefs();diff --git a/test/mcp-memory-provider.test.ts b/test/mcp-memory-provider.test.tsnew file mode 100644index 000000000..1579a9753--- /dev/null+++ b/test/mcp-memory-provider.test.ts@@ -0,0 +1,69 @@+import { test } from "node:test";+import assert from "node:assert/strict";+import { createMcpMemoryProvider } from "../src/memory/mcp-memory-provider.ts";+import type { McpClient } from "../src/mcp/mcp-client.ts";++function client(calls: Array<{ tool: string; args: Record<string, unknown> }>, text = "result"): McpClient {+ return {+ base: "http://brain.internal",+ host: "brain.internal",+ async listTools() {+ return [];+ },+ async callTool(tool, args) {+ calls.push({ tool, args });+ return { content: [{ type: "text", text }] };+ },+ };+}++test("MCP provider passes query, actor, and explicit writes through configured tools", async () => {+ const calls: Array<{ tool: string; args: Record<string, unknown> }> = [];+ const memory = createMcpMemoryProvider({+ read: {+ client: client(calls),+ tool: "read_brain",+ timeoutMs: 100,+ scopeArg: "namespace",+ maxCharsArg: "max_chars",+ },+ write: {+ client: client(calls),+ tool: "write_brain",+ timeoutMs: 100,+ scopeArg: "namespace",+ capturedAtArg: "captured_at",+ sourceArg: "source",+ },+ });+ assert.equal(await memory.recall("org:yc", { query: "launch", actorId: "u1", maxChars: 2000 }), "result");+ assert.equal(await memory.capture("org:yc", ["decision"], 10, "u1", { mode: "explicit", actorId: "u1" }), 1);+ assert.deepEqual(calls, [+ { tool: "read_brain", args: { query: "launch", acting_user: "u1", namespace: "org:yc", max_chars: 2000 } },+ {+ tool: "write_brain",+ args: { content: "decision", captured_at: 10, source: "explicit", acting_user: "u1", namespace: "org:yc" },+ },+ ]);+});++test("MCP recall is locally bounded and times out", async () => {+ const calls: Array<{ tool: string; args: Record<string, unknown> }> = [];+ const bounded = createMcpMemoryProvider({+ read: { client: client(calls, "abcdefgh"), tool: "read", timeoutMs: 100 },+ });+ assert.equal(await bounded.recall("org:yc", { maxChars: 4 }), "abcd");++ const hanging: McpClient = {+ base: "http://brain.internal",+ host: "brain.internal",+ async listTools() {+ return [];+ },+ async callTool() {+ return new Promise(() => {});+ },+ };+ const timed = createMcpMemoryProvider({ read: { client: hanging, tool: "read", timeoutMs: 10 } });+ await assert.rejects(timed.recall("org:yc"), /timed out after 10ms/);+});diff --git a/test/memory-provider-config.test.ts b/test/memory-provider-config.test.tsnew file mode 100644index 000000000..a0a22bbcf--- /dev/null+++ b/test/memory-provider-config.test.ts@@ -0,0 +1,58 @@+import { test } from "node:test";+import assert from "node:assert/strict";+import { parseMemoryProviderConfig } from "../src/memory/provider-config.ts";++const value = JSON.stringify({+ providers: [+ {+ id: "gbrain",+ type: "mcp",+ url: "http://qm-gbrain-relay.flycast:48081",+ read: { tool: "read_brain", clientIdEnv: "BRAIN_RO_CLIENT_ID", clientSecretEnv: "BRAIN_RO_CLIENT_SECRET" },+ write: { tool: "write_brain", clientIdEnv: "BRAIN_RW_CLIENT_ID", clientSecretEnv: "BRAIN_RW_CLIENT_SECRET" },+ },+ ],+ routes: [+ { provider: "default", scopes: ["personal", "channel", "group"], capture: "automatic" },+ { provider: "gbrain", scopes: ["org"], capture: "explicit", manage: false, label: "Organization" },+ ],+});++test("provider config resolves MCP credentials and scope routes", () => {+ const config = parseMemoryProviderConfig(value, {+ BRAIN_RO_CLIENT_ID: "ro",+ BRAIN_RO_CLIENT_SECRET: "ro-secret",+ BRAIN_RW_CLIENT_ID: "rw",+ BRAIN_RW_CLIENT_SECRET: "rw-secret",+ });+ assert.equal(config?.providers[0]?.read.auth.clientId, "ro");+ assert.equal(config?.providers[0]?.write?.auth.clientId, "rw");+ assert.deepEqual(+ config?.routes.map(({ provider, scopes, capture }) => ({ provider, scopes, capture })),+ [+ { provider: "default", scopes: ["personal", "channel", "group"], capture: "automatic" },+ { provider: "gbrain", scopes: ["org"], capture: "explicit" },+ ],+ );+});++test("provider config rejects unknown providers and public cleartext MCP URLs", () => {+ assert.throws(+ () =>+ parseMemoryProviderConfig(+ JSON.stringify({ providers: [], routes: [{ provider: "missing", scopes: ["org"] }] }),+ {},+ ),+ /unknown memory provider/,+ );+ assert.throws(+ () =>+ parseMemoryProviderConfig(value.replace("qm-gbrain-relay.flycast", "example.com"), {+ BRAIN_RO_CLIENT_ID: "ro",+ BRAIN_RO_CLIENT_SECRET: "x",+ BRAIN_RW_CLIENT_ID: "rw",+ BRAIN_RW_CLIENT_SECRET: "x",+ }),+ /HTTPS or a recognized private HTTP host/,+ );+});diff --git a/test/memory-provider-factory.test.ts b/test/memory-provider-factory.test.tsnew file mode 100644index 000000000..5062bd6ba--- /dev/null+++ b/test/memory-provider-factory.test.ts@@ -0,0 +1,82 @@+import { test } from "node:test";+import assert from "node:assert/strict";+import { createConfiguredMemoryService } from "../src/memory/provider-factory.ts";+import { parseMemoryProviderConfig } from "../src/memory/provider-config.ts";+import type { MemoryService } from "../src/memory/memory-service.ts";+import type { McpFetch } from "../src/mcp/mcp-client.ts";++const defaultMemory: MemoryService = {+ async recall() {+ return "personal notebook";+ },+ async capture(_scope, facts) {+ return facts.length;+ },+ async query() {+ return [];+ },+ async read() {+ return "personal notebook";+ },+ async replace() {},+};++function response(body: unknown) {+ return {+ ok: true,+ status: 200,+ headers: { get: () => "application/json" },+ async text() {+ return JSON.stringify(body);+ },+ };+}++test("configured provider runs OAuth MCP recall and explicit capture end to end", async () => {+ const calls: Array<{ url: string; body: string; authorization?: string }> = [];+ const fetchImpl: McpFetch = async (url, init) => {+ calls.push({ url, body: init.body, authorization: init.headers.authorization });+ if (url.endsWith("/token")) {+ const params = new URLSearchParams(init.body);+ return response({ access_token: `${params.get("client_id")}-token`, expires_in: 300 });+ }+ const rpc = JSON.parse(init.body) as { id: number; params: { name: string; arguments: Record<string, unknown> } };+ return response({+ jsonrpc: "2.0",+ id: rpc.id,+ result: { content: [{ type: "text", text: rpc.params.name === "read_brain" ? "org knowledge" : "ok" }] },+ });+ };+ const raw = JSON.stringify({+ providers: [+ {+ id: "brain",+ type: "mcp",+ url: "http://brain.internal:8080",+ read: { tool: "read_brain", clientIdEnv: "RO_ID", clientSecretEnv: "RO_SECRET" },+ write: { tool: "write_brain", clientIdEnv: "RW_ID", clientSecretEnv: "RW_SECRET" },+ },+ ],+ routes: [+ { provider: "default", scopes: ["personal"], capture: "automatic" },+ { provider: "brain", scopes: ["org"], capture: "explicit", manage: false },+ ],+ });+ const memory = createConfiguredMemoryService({+ defaultMemory,+ config: parseMemoryProviderConfig(raw, { RO_ID: "ro", RO_SECRET: "x", RW_ID: "rw", RW_SECRET: "y" }),+ fetchImpl,+ });++ assert.equal(await memory.recall("personal:u1", { query: "launch", actorId: "u1" }), "personal notebook");+ assert.equal(await memory.recall("org:acme", { query: "launch", actorId: "u1" }), "org knowledge");+ assert.equal(await memory.capture("org:acme", ["decision"], 1, "u1", { mode: "automatic" }), 0);+ assert.equal(await memory.capture("org:acme", ["decision"], 1, "u1", { mode: "explicit" }), 1);++ assert.equal(calls[0]?.url, "http://brain.internal:8080/token");+ assert.equal(calls[1]?.authorization, "Bearer ro-token");+ assert.match(calls[1]?.body ?? "", /read_brain/);+ assert.equal(calls[2]?.url, "http://brain.internal:8080/token");+ assert.equal(calls[3]?.authorization, "Bearer rw-token");+ assert.match(calls[3]?.body ?? "", /write_brain/);+});diff --git a/test/memory-provider-router.test.ts b/test/memory-provider-router.test.tsnew file mode 100644index 000000000..056ad140f--- /dev/null+++ b/test/memory-provider-router.test.ts@@ -0,0 +1,77 @@+import { test } from "node:test";+import assert from "node:assert/strict";+import { createRoutedMemoryService } from "../src/memory/provider-router.ts";+import type { MemoryCaptureContext, MemoryRecallContext, MemoryService } from "../src/memory/memory-service.ts";++function provider(name: string, calls: string[]): MemoryService {+ return {+ async recall(scope, context?: MemoryRecallContext) {+ calls.push(`${name}:recall:${scope}:${context?.query ?? ""}`);+ return `${name} memory`;+ },+ async capture(scope, facts, _at, _author, context?: MemoryCaptureContext) {+ calls.push(`${name}:capture:${scope}:${context?.mode ?? "explicit"}:${facts.join(",")}`);+ return facts.length;+ },+ async query() {+ return [];+ },+ async read() {+ return `${name} notebook`;+ },+ async replace() {},+ };+}++test("routes recall and capture independently by scope and policy", async () => {+ const calls: string[] = [];+ const memory = createRoutedMemoryService({+ providers: { notebook: provider("notebook", calls), brain: provider("brain", calls) },+ routes: [+ { provider: "notebook", scopes: ["personal", "channel", "group"], capture: "automatic" },+ { provider: "brain", scopes: ["org"], capture: "explicit", manage: false },+ ],+ });+ assert.equal(await memory.recall("personal:u1", { query: "launch" }), "notebook memory");+ assert.equal(await memory.recall("org:acme", { query: "launch" }), "brain memory");+ assert.equal(await memory.capture("personal:u1", ["prefers terse replies"], 1, "u1", { mode: "automatic" }), 1);+ assert.equal(await memory.capture("org:acme", ["runbook"], 1, "u1", { mode: "automatic" }), 0);+ assert.equal(await memory.capture("org:acme", ["runbook"], 1, "u1", { mode: "explicit" }), 1);+ assert.deepEqual(calls, [+ "notebook:recall:personal:u1:launch",+ "brain:recall:org:acme:launch",+ "notebook:capture:personal:u1:automatic:prefers terse replies",+ "brain:capture:org:acme:explicit:runbook",+ ]);+});++test("multiple recall providers compose without duplicating query hits", async () => {+ const calls: string[] = [];+ const memory = createRoutedMemoryService({+ providers: { notebook: provider("notebook", calls), brain: provider("brain", calls) },+ routes: [+ { provider: "notebook", scopes: ["org"], capture: "off", label: "Notebook" },+ { provider: "brain", scopes: ["org"], capture: "off", label: "Org brain", manage: false },+ ],+ });+ assert.equal(await memory.recall("org:acme"), "### Notebook\nnotebook memory\n\n### Org brain\nbrain memory");+});++test("external recall failures degrade to the remaining provider", async () => {+ const errors: string[] = [];+ const calls: string[] = [];+ const broken = provider("broken", calls);+ broken.recall = async () => {+ throw new Error("offline");+ };+ const memory = createRoutedMemoryService({+ providers: { notebook: provider("notebook", calls), broken },+ routes: [+ { provider: "notebook", scopes: ["org"], capture: "off" },+ { provider: "broken", scopes: ["org"], capture: "off", manage: false, failOpen: true },+ ],+ onError: (error, providerId, operation) => errors.push(`${providerId}:${operation}:${String(error)}`),+ });+ assert.equal(await memory.recall("org:acme", { query: "launch" }), "notebook memory");+ assert.match(errors[0]!, /^broken:recall:Error: offline$/);+});diff --git a/test/memory-strategy-per-turn.test.ts b/test/memory-strategy-per-turn.test.tsindex 8a46e4c8f..008d649b9 100644--- a/test/memory-strategy-per-turn.test.ts+++ b/test/memory-strategy-per-turn.test.ts@@ -123,3 +123,37 @@ test("debounced: autonomous and live turns from the same actor flush as separate"two flushes, one per burst, each under its own rules",);});++test("automatic capture carries the full turn and delivery context", async () => {+ const captures: Array<Parameters<ReturnType<typeof freshMemory>["memory"]["capture"]>> = [];+ const { memory } = freshMemory();+ const wrapped = {+ ...memory,+ async capture(...args: Parameters<typeof memory.capture>) {+ captures.push(args);+ return memory.capture(...args);+ },+ };+ const strategy = createPerTurnStrategy({+ harness: { oneShot: () => Promise.resolve("- Durable fact") },+ memory: wrapped,+ });+ await strategy.onTurnEnd!({+ scopeId: SCOPE,+ conversationScopeId: "channel:C1",+ actorId: "U1",+ sessionId: "session-1",+ idempotencyKey: "run-1",+ input: "question",+ reply: "answer",+ });+ assert.deepEqual(captures[0]?.[4], {+ mode: "automatic",+ actorId: "U1",+ conversationScopeId: "channel:C1",+ input: "question",+ reply: "answer",+ sessionId: "session-1",+ idempotencyKey: "run-1",+ });+});