The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
test(memory): a memory scenarios script for both engines
M3gA-Mind0c397156c257
diff --git a/scripts/memory-scenarios/README.md b/scripts/memory-scenarios/README.mdnew file mode 100644index 0000000000..95e1042cb8--- /dev/null+++ b/scripts/memory-scenarios/README.md@@ -0,0 +1,117 @@+# Memory scenarios++Realistic memory flows against the real OpenHuman core, on two engines, checked+by the script itself. Every failed check becomes a finding for a person to+read; **nothing is fixed during a run**.++```bash+# both engines (local first, then Built-in on your real account)+OPENHUMAN_BACKEND_SESSION_TOKEN=<your session JWT> node scripts/memory-scenarios/run.mjs++# one engine, some scenarios+node scripts/memory-scenarios/run.mjs --engine local --only A,B,E++# keep the local CortexDB volume for a look afterwards+node scripts/memory-scenarios/run.mjs --engine local --keep++# re-render the report of an old run+node scripts/memory-scenarios/run.mjs --grade-only target/memory-scenarios/<run-id>+```++Requires a **debug** core (`cargo build -p openhuman-cli --bin openhuman-core`,+debug so the Composio base override is honoured), Docker, and for the local+engine's real embeddings a running Ollama with `nomic-embed-text` and+`llama3.2:3b` (pulled automatically when missing).++## Headless, but shaped like the desktop app++Same rig as [`../life-scenarios`](../life-scenarios/README.md): the core runs+as `openhuman-core serve` with **its own `HOME`** under+`target/memory-scenarios/<run-id>/<engine>/home`, and turns go through+`openhuman.channel_web_chat` with the reply on `GET /events`, exactly like the+composer. Memory RPCs (`memory_learn`, `memory_items_list`, `memory_recall`,+`memory_brain_ingest`, `memory_sources_*`, `memory_import_*`,+`memory_migration_*`) are called the way the Memory page calls them.++## The two engines++**local** — a throwaway CortexDB **v0.10.5** per run (`cortexdb/` here): its own+compose project `memscen-<run>`, its own volume, a free port. It never touches+the user's `cortexdb` container, its `cortexdb-data` volume or port 3141, and is+torn down with its volume at the end (`--keep` keeps the volume). Inference is+the local Ollama (semantic embeddings, `nomic-embed-text`, 768 dims; a small+chat model for extraction and answers). When Ollama is unreachable it falls back+to tinymemory's deterministic mock inference, and the report says the+recall-quality checks were skipped. The core signs in with an offline local+session and points memory at the container (`memory_engine_set`).++**builtin** — **your real account**, on its managed route. Read this before+running it:++- The session JWT comes only from `OPENHUMAN_BACKEND_SESSION_TOKEN`; the core+ reads it at boot (`security/credentials/ops/boot_env.rs`). It is never an RPC+ argument, never printed, never written to the run directory: `rpc.jsonl` and+ `core.log` are scrubbed of it and of anything JWT-shaped.+- **Nothing of the account's own is moved, erased or imported.** Three guards,+ any failure aborts the builtin run before a scenario starts:+ 1. the scheduler gate is pre-written **off** in the account's user dir before+ the core first boots, and read back, so no background job (the layout+ migration's tick, import resume, belief builds) runs on its own;+ 2. this workspace's layout-migration state is written as done (`cleaned`)+ and read back through `memory_migration_status`;+ 3. no v1 store exists in the throwaway workspace.+ Migration, import, erase and disconnect-with-clear scenarios run **local+ only**. At the end the run asserts the migration state never moved and no+ import ran.+- **Everything the run writes is removed.** Each item carries a run marker+ (`thread-<uuid>` threads, a `memscen:<run>` tag); every id it stores is+ recorded; teardown forgets exactly those, plus every item in the run's+ threads and every item with its tag, then checks each is gone. Survivors are+ reported as a finding. Beliefs the engine derives on its own from the run's+ items cannot be traced back to the run and are not cleaned up.++## Scenarios++| id | engines | what it checks |+| ------------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| A-storing | both | chats with two agents logged under each agent; learnings of every kind, kind visible on read-back; brain text; a file from a path holding a username (only the basename may reach the engine); dated facts |+| B-recall | both | cross-thread recall; a negative control (no invention); a planted learning changes a reply; brain retrieval with citations; pre-turn pack timeouts at the default wait vs 6000 ms (`[memory:hooks] pre_turn timed out` in core.log) |+| C-dates | both | the user time zone; "yesterday" and a named date find the right fact; a Spanish question gets a Spanish reply |+| D-connectors | local | mock Composio (`mock-composio.mjs`): items under `source:<app>`; GitHub split by `{owner}--{repo}`; an edit replaces the old version; disconnect-with-clear removes only that app; a disconnect during a sync leaves nothing; reconnect syncs; the Gmail sender becomes `observed_actor` |+| E-migration | local | legacy items plus a v1 store: import with consent, then organizing starts on its own; a core restart mid-move; layout v3; nothing lost; v1 documents present; chats pooled at `ws:main`; the same recall answer |+| F-labels | local | thread and agent on every logged turn; phone numbers in plain text; `observed_actor` only with `[memory] observed_actor = true` |+| G-source-cap | both | more than four brain sources: at most four in the pack, the named one included, no Team section |+| H-forget | both | a forget removes from list and recall; forgetting nothing reports `forgotten: 0` |+| I-qa | both | belief build (`memory_jobs_run`), backfill state, a new learning listed at once; local: the engine stopped mid-session, is the failure surfaced or swallowed |+| J-store-speed | builtin | a synthetic batch stored on the hosted path, timed, with `UNAVAILABLE`/429 counted (no real import) |++Not driven here (said so in the report): a workflow writing memory, workflow+memory kept out of chat, and the unconfirmed-import no-erase guard (unit-tested+in the core).++**Known gap, not a finding:** channel messages are not logged to memory today,+so the channel sender name (#7131) is inert.++## The corpus is fictional++`fixtures/persona.json`: one persona (Jordan Lee `<[email protected]>`),+`*.example` domains, `555-01xx` phone numbers. The mock's mail and issues are+invented too. Dates the checks reason about are the real clock's, in the+persona's time zone, because the engine stamps items with the real time.++## Output++```+target/memory-scenarios/<run-id>/+ report.md per engine: inference, scenario table, findings, notes+ findings.json [{id, engine, scenario, severity, expected, actual, evidence, basis: READ|INFERRED}]+ checks.json every check, passed or not+ results.json measurements (pre-turn timeouts, store speed, migration counts, ...)+ <engine>/core.log the core's log (scrubbed)+ <engine>/rpc.jsonl every RPC with its result (scrubbed)+ <engine>/scenarios/<id>/transcript.jsonl every turn: message, reply, tools, time+ local/composio-requests.json what the mock Composio received+```++A finding's `basis` is **READ** when it was seen (a response, a log line) and+**INFERRED** when it was judged (a reply's wording, a heuristic).diff --git a/scripts/memory-scenarios/connectors.mjs b/scripts/memory-scenarios/connectors.mjsnew file mode 100644index 0000000000..4629624771--- /dev/null+++ b/scripts/memory-scenarios/connectors.mjs@@ -0,0 +1,216 @@+// D. Connectors through a mock Composio (LOCAL ONLY).+//+// Gmail and GitHub are added as `composio` memory sources and synced from+// mock-composio.mjs; the checks read what memory filed.++import { sleep, waitFor } from "./lib.mjs";++const byToolkit = (items, toolkit) =>+ items.filter((h) => (h.meta?.tags ?? []).includes(toolkit));++export const connectors = {+ id: "D-connectors",+ title:+ "Connectors: filing, edits replace, disconnect-with-clear, disconnect mid-sync, reconnect, repo split, sender actor",+ engines: ["local"],+ needsComposio: true,+ async run(ctx) {+ const { check, composio } = ctx;+ // The sender only reaches the engine with observed_actor on.+ await ctx.setConfigToml("memory", { observed_actor: true });+ await ctx.restartCore();++ const composioItems = () => ctx.listAll({ sources: ["composio"] });+ const added = {};+ for (const toolkit of ["gmail", "github"]) {+ const r = await ctx.tryRpc("openhuman.memory_sources_add", {+ kind: "composio",+ target: toolkit,+ label: `memscen ${toolkit}`,+ });+ check(+ `D0-add-${toolkit}`,+ r.ok,+ `a ${toolkit} source can be added`,+ r.ok ? r.value : r.error,+ );+ if (r.ok) added[toolkit] = r.value?.source?.id;+ }+ await ctx.rpc("openhuman.memory_sources_sync", {});+ const synced = await waitFor(+ async () => {+ const items = await composioItems();+ return byToolkit(items, "gmail").length >= 2 &&+ byToolkit(items, "github").length >= 2+ ? items+ : null;+ },+ { timeoutMs: 180_000, intervalMs: 2000, what: "connector items synced" },+ ).catch((e) => {+ check(+ "D1-synced",+ false,+ "both toolkits' items are synced",+ e.message,+ "high",+ );+ return null;+ });+ if (!synced) return;+ ctx.ledger.addAll(synced.map((h) => h.id));++ // D1: filed under source:<app>; GitHub split by repository.+ const gmail = byToolkit(synced, "gmail");+ const github = byToolkit(synced, "github");+ check(+ "D1-gmail-node",+ gmail.every((h) =>+ String(h.meta?.namespace ?? "").startsWith("source:gmail"),+ ),+ "Gmail items sit under source:gmail",+ gmail.map((h) => h.meta?.namespace),+ );+ check(+ "D1-github-node",+ github.every((h) =>+ String(h.meta?.namespace ?? "").startsWith("source:github"),+ ),+ "GitHub items sit under source:github",+ github.map((h) => h.meta?.namespace),+ );+ check(+ "D6-github-by-repo",+ github.some((h) =>+ String(h.meta?.namespace ?? "").includes("northwind-example--kestrel"),+ ),+ "GitHub items are split by repository ({owner}--{repo}) by default",+ github.map((h) => h.meta?.namespace),+ );++ // D7: the Gmail sender is the observed actor.+ const priya = gmail.find((h) => (h.text ?? "").includes("Pune"));+ check(+ "D7-sender-actor",+ priya?.meta?.observed_actor?.id === "user:[email protected]",+ "the Gmail sender is stored as observed_actor (user:<address>)",+ priya?.meta?.observed_actor ?? null,+ );++ // D2: an edit upstream replaces the old version, no duplicate.+ composio.edit(+ "gmail",+ "msg-001",+ "Hi Jordan, change of plan: I land in Pune on the 31st at 9am. Priya",+ );+ await ctx.rpc("openhuman.memory_sources_sync", { id: added.gmail });+ const edited = await waitFor(+ async () => {+ const g = byToolkit(await composioItems(), "gmail");+ return g.some((h) => (h.text ?? "").includes("31st")) ? g : null;+ },+ {+ timeoutMs: 120_000,+ intervalMs: 2000,+ what: "edited Gmail item synced",+ },+ ).catch(() => null);+ if (!edited)+ check("D2-edit-synced", false, "the edited message is synced", null);+ else {+ ctx.ledger.addAll(edited.map((h) => h.id));+ const stale = edited.filter((h) =>+ (h.text ?? "").includes("30th at 7pm"),+ );+ check(+ "D2-edit-replaces",+ stale.length === 0,+ "the old version is gone after the edit (no duplicate)",+ { versions: edited.map((h) => (h.text ?? "").slice(0, 50)) },+ "high",+ );+ }++ // D3: disconnect Gmail with clear: only Gmail's items go.+ const del = await ctx.tryRpc("openhuman.composio_delete_connection", {+ connection_id: composio.connectionId("gmail"),+ clear_memory: true,+ });+ check(+ "D3-disconnect",+ del.ok,+ "the Gmail connection deletes with clear_memory",+ del.ok ? del.value : del.error,+ );+ await sleep(5000);+ const afterClear = await composioItems();+ check(+ "D3-gmail-cleared",+ byToolkit(afterClear, "gmail").length === 0,+ "Gmail's items are forgotten",+ byToolkit(afterClear, "gmail").map((h) => h.id),+ "high",+ );+ check(+ "D3-github-kept",+ byToolkit(afterClear, "github").length >= 2,+ "GitHub's items are untouched",+ byToolkit(afterClear, "github").length,+ "high",+ );++ // D4: disconnect GitHub while its sync is in flight: nothing left behind.+ composio.edit(+ "github",+ 9001,+ "Kestrel launch checklist, updated: add the accessibility review.",+ );+ composio.setFetchDelay(8000);+ await ctx.rpc("openhuman.memory_sources_sync", { id: added.github });+ await sleep(2000);+ await ctx.tryRpc("openhuman.composio_delete_connection", {+ connection_id: composio.connectionId("github"),+ clear_memory: true,+ });+ composio.setFetchDelay(0);+ await sleep(20_000);+ const leftover = byToolkit(await composioItems(), "github");+ check(+ "D4-mid-sync-disconnect",+ leftover.length === 0,+ "a disconnect during a sync leaves no GitHub items behind",+ leftover.map((h) => (h.text ?? "").slice(0, 50)),+ "high",+ );++ // D5: reconnect: syncing works again.+ composio.reconnect("gmail");+ await ctx.rpc("openhuman.memory_sources_sync", { id: added.gmail });+ const back = await waitFor(+ async () => {+ const g = byToolkit(await composioItems(), "gmail");+ return g.length >= 2 ? g : null;+ },+ {+ timeoutMs: 120_000,+ intervalMs: 2000,+ what: "Gmail synced after reconnect",+ },+ ).catch(() => null);+ check(+ "D5-reconnect-syncs",+ !!back,+ "after a reconnect, Gmail syncs again",+ back?.length ?? 0,+ );+ if (back) ctx.ledger.addAll(back.map((h) => h.id));++ for (const id of Object.values(added))+ if (id)+ await ctx.tryRpc("openhuman.memory_sources_remove", {+ id,+ forget_items: true,+ });+ await ctx.setConfigToml("memory", { observed_actor: false });+ await ctx.restartCore();+ },+};diff --git a/scripts/memory-scenarios/cortexdb/cortex.toml b/scripts/memory-scenarios/cortexdb/cortex.tomlnew file mode 100644index 0000000000..d6468f214e--- /dev/null+++ b/scripts/memory-scenarios/cortexdb/cortex.toml@@ -0,0 +1,28 @@+[cluster]+node_id = 1++[storage]+data_path = "/data/cortex"+wal_sync = true++[engine]+vector_dimensions = 768+hnsw_m = 32+hnsw_ef_construction = 500+hnsw_ef_search = 200+# v0.9.9's shipped TOML enum uses `None` for lossless fp32 storage.+hnsw_quantization = "None"+block_cache_bytes = 536870912++[network]++[llm]++[governance]++[scheduler]+enabled = true+compaction_interval_secs = 300+methylation_interval_secs = 600+cognitive_persist_interval_secs = 60+feedback_weight_interval_secs = 120diff --git a/scripts/memory-scenarios/cortexdb/docker-compose.yml b/scripts/memory-scenarios/cortexdb/docker-compose.ymlnew file mode 100644index 0000000000..42285adf61--- /dev/null+++ b/scripts/memory-scenarios/cortexdb/docker-compose.yml@@ -0,0 +1,50 @@+# A throwaway CortexDB for the memory scenarios' `local` engine.+#+# Started by run.mjs with its own compose project (`memscen-<run>`), so its+# volume is `memscen-<run>_cortex-data`: never the user's `cortexdb` container,+# its `cortexdb-data` volume or port 3141. The port is a free one picked per run.+#+# Inference is the local Ollama (OpenAI-compatible /v1) by default: semantic+# embeddings (nomic-embed-text, 768 dims) and a small chat model for+# extraction, answers and verification. run.mjs falls back to tinymemory's+# deterministic mock-inference only when Ollama is unreachable, and the report+# then says recall-quality checks were skipped.+name: memscen++services:+ cortex:+ image: cortexdb/cortexdb:${CORTEXDB_VERSION:-v0.10.5}+ command: ["3141", "/data"]+ environment:+ CORTEX_API_KEY: ${MEMSCEN_CORTEX_KEY:?set by run.mjs}+ CORTEX_DEPLOYMENT_PRESET: dev_local+ CORTEX_EMBEDDING_URL: ${CORTEX_INFERENCE_URL:?set by run.mjs}+ CORTEX_EMBEDDING_API_KEY: ${CORTEX_INFERENCE_KEY:-ollama}+ OPENAI_API_KEY: ${CORTEX_INFERENCE_KEY:-ollama}+ CORTEX_EMBEDDING_MODEL: ${CORTEX_EMBEDDING_MODEL:-nomic-embed-text}+ CORTEX_EMBEDDING_DIMS: ${CORTEX_EMBEDDING_DIMS:-768}+ CORTEX_LLM_URL: ${CORTEX_INFERENCE_URL}+ CORTEX_ENTITY_API_KEY: ${CORTEX_INFERENCE_KEY:-ollama}+ CORTEX_LLM_MODEL: ${CORTEX_CHAT_MODEL:-llama3.2:3b}+ CORTEX_ENRICHMENT_URL: ${CORTEX_INFERENCE_URL}+ CORTEX_ENRICHMENT_API_KEY: ${CORTEX_INFERENCE_KEY:-ollama}+ CORTEX_ENRICHMENT_MODEL: ${CORTEX_CHAT_MODEL:-llama3.2:3b}+ CORTEX_ENRICHMENT_DELAY_SECONDS: "0"+ CORTEX_ANSWER_PROVIDER: openai+ CORTEX_ANSWER_URL: ${CORTEX_INFERENCE_URL}+ CORTEX_ANSWER_API_KEY: ${CORTEX_INFERENCE_KEY:-ollama}+ CORTEX_ANSWER_MODEL: ${CORTEX_CHAT_MODEL:-llama3.2:3b}+ CORTEX_VERIFIER_URL: ${CORTEX_INFERENCE_URL}+ CORTEX_VERIFIER_API_KEY: ${CORTEX_INFERENCE_KEY:-ollama}+ CORTEX_VERIFIER_MODEL: ${CORTEX_CHAT_MODEL:-llama3.2:3b}+ env_file:+ - flags.env+ ports: ["127.0.0.1:${MEMSCEN_CORTEX_PORT:?set by run.mjs}:3141"]+ extra_hosts:+ - host.docker.internal:host-gateway+ volumes:+ - cortex-data:/data+ - ./${MEMSCEN_CORTEX_TOML:-cortex.toml}:/data/cortex.toml:ro++volumes:+ cortex-data:diff --git a/scripts/memory-scenarios/cortexdb/flags.env b/scripts/memory-scenarios/cortexdb/flags.envnew file mode 100644index 0000000000..f0dbd00265--- /dev/null+++ b/scripts/memory-scenarios/cortexdb/flags.env@@ -0,0 +1,10 @@+# The harness's standing configuration: graph-fused retrieval on, belief+# layers auto-built, per-question salience routing, and consolidation with+# no minimum age (the eval's events are minutes old). Every other profile+# is applied on top of this file and names only what it changes.+# targets: all+# docs: https://cortexdb.ai/docs/operations/recall-tuning+CORTEX_ENTITY_GRAPH=1+CORTEX_V1_LAYERS_AUTO=1+CORTEX_AUTO_ROUTE=1+CORTEX_CONSOLIDATION_MIN_AGE_HOURS=0diff --git a/scripts/memory-scenarios/engines.mjs b/scripts/memory-scenarios/engines.mjsnew file mode 100644index 0000000000..0cbfe76b94--- /dev/null+++ b/scripts/memory-scenarios/engines.mjs@@ -0,0 +1,294 @@+// The two engines a run tests.+//+// - local: a throwaway CortexDB container per run (its own compose project,+// volume and port; never the user's `cortexdb` / `cortexdb-data` / :3141),+// inference through the local Ollama when reachable.+// - builtin: the user's real account. Guards in `builtinGuards` keep the run+// from moving, erasing or importing anything of the account's own.++import fsp from "node:fs/promises";+import path from "node:path";+import { execFile } from "node:child_process";+import { promisify } from "node:util";+import { randomBytes } from "node:crypto";+import { freePort, waitFor, pick } from "./lib.mjs";++const exec = promisify(execFile);++/** Names a run must never touch. */+const FORBIDDEN_PROJECTS = new Set([+ "cortexdb",+ "tinymemory-cortexdb",+ "tinymemory-cortexdb-test",+]);+const FORBIDDEN_PORT = 3141;++const OLLAMA = process.env.MEMSCEN_OLLAMA_URL || "http://127.0.0.1:11434";+export const OLLAMA_EMBED_MODEL =+ process.env.MEMSCEN_EMBED_MODEL || "nomic-embed-text";+export const OLLAMA_EMBED_DIMS = process.env.MEMSCEN_EMBED_DIMS || "768";+export const OLLAMA_CHAT_MODEL =+ process.env.MEMSCEN_CHAT_MODEL || "llama3.2:3b";++/** Ollama's model names, or null when it is unreachable. */+async function ollamaModels() {+ try {+ const r = await fetch(`${OLLAMA}/api/tags`, {+ signal: AbortSignal.timeout(5000),+ });+ if (!r.ok) return null;+ return ((await r.json()).models ?? []).map((m) => m.name);+ } catch {+ return null;+ }+}++/** Pull `model` through Ollama's API when it is missing. */+async function ensureOllamaModel(model, have) {+ const want = model.includes(":") ? model : `${model}:latest`;+ if (have.includes(want) || have.includes(model)) return;+ const r = await fetch(`${OLLAMA}/api/pull`, {+ method: "POST",+ body: JSON.stringify({ model, stream: false }),+ signal: AbortSignal.timeout(20 * 60_000),+ });+ if (!r.ok) throw new Error(`ollama pull ${model}: HTTP ${r.status}`);+}++/**+ * Start the per-run CortexDB. Returns `{endpoint, apiKey, inference, stop}`.+ * `inference` says what backs embeddings and extraction, for report.md.+ */+export async function startLocalCortex({+ runId,+ scriptDir,+ tinymemoryDir,+ keep,+ log,+}) {+ const project = `memscen-${runId+ .toLowerCase()+ .replace(/[^a-z0-9-]/g, "")+ .slice(-24)}`;+ if (FORBIDDEN_PROJECTS.has(project))+ throw new Error(`refusing compose project ${project}`);+ const port = await freePort();+ if (port === FORBIDDEN_PORT) throw new Error("refusing port 3141");+ const apiKey = `memscen-${randomBytes(12).toString("hex")}`;++ const models = await ollamaModels();+ let compose;+ let env;+ let inference;+ if (models) {+ await ensureOllamaModel(OLLAMA_EMBED_MODEL, models);+ await ensureOllamaModel(OLLAMA_CHAT_MODEL, models);+ compose = ["-f", path.join(scriptDir, "cortexdb", "docker-compose.yml")];+ env = {+ CORTEXDB_VERSION: "v0.10.5",+ MEMSCEN_CORTEX_KEY: apiKey,+ MEMSCEN_CORTEX_PORT: String(port),+ // From inside the container the host's loopback is host.docker.internal.+ CORTEX_INFERENCE_URL: `${OLLAMA.replace("127.0.0.1", "host.docker.internal").replace("localhost", "host.docker.internal")}/v1`,+ CORTEX_EMBEDDING_MODEL: OLLAMA_EMBED_MODEL,+ CORTEX_EMBEDDING_DIMS: OLLAMA_EMBED_DIMS,+ CORTEX_CHAT_MODEL: OLLAMA_CHAT_MODEL,+ };+ inference = {+ kind: "ollama",+ embeddings: `${OLLAMA_EMBED_MODEL} (${OLLAMA_EMBED_DIMS} dims)`,+ chat: OLLAMA_CHAT_MODEL,+ recall_quality_checked: true,+ };+ } else {+ // tinymemory's compose with its deterministic inference double: plumbing+ // still works, retrieval is not semantic.+ compose = [+ "-f",+ path.join(tinymemoryDir, "integration", "cortexdb", "docker-compose.yml"),+ ];+ env = {+ CORTEXDB_VERSION: "v0.10.5",+ CORTEXDB_PORT: String(port),+ TINYMEMORY_TEST_CORTEX_KEY: apiKey,+ };+ inference = {+ kind: "mock-inference",+ embeddings: "deterministic",+ chat: "deterministic",+ recall_quality_checked: false,+ };+ }++ const dc = (...args) =>+ exec(+ "docker",+ ["compose", "--project-name", project, ...compose, ...args],+ {+ env: { ...process.env, ...env },+ maxBuffer: 16 * 1024 * 1024,+ },+ );+ log?.(+ `local : compose project ${project}, port ${port}, inference ${inference.kind}`,+ );+ await dc(+ "up",+ "-d",+ ...(models ? [] : ["--build", "--wait", "mock-inference"]),+ );+ if (!models) await dc("up", "-d", "cortex");+ const endpoint = `http://127.0.0.1:${port}`;+ await waitFor(+ async () =>+ (+ await fetch(`${endpoint}/v1/admin/ready`, {+ signal: AbortSignal.timeout(3000),+ })+ ).ok,+ { timeoutMs: 180_000, intervalMs: 1000, what: "CortexDB ready" },+ );+ const version = await fetch(`${endpoint}/v1/admin/version`)+ .then((r) => r.text())+ .catch(() => "?");++ return {+ project,+ endpoint,+ apiKey,+ inference: { ...inference, cortexdb_version: version.trim() },+ /** Stop the CortexDB container (to force engine errors), and start it again. */+ pause: () => dc("stop", "cortex"),+ resume: async () => {+ await dc("start", "cortex");+ await waitFor(+ async () => (await fetch(`${endpoint}/v1/admin/ready`)).ok,+ {+ timeoutMs: 120_000,+ what: "CortexDB ready again",+ },+ );+ },+ async stop() {+ await dc("down", "--remove-orphans", ...(keep ? [] : ["--volumes"]));+ },+ };+}++/**+ * Read CortexDB directly with the run's own key, for checks that need what the+ * engine stored rather than what the core reports (labels, basenames, scopes).+ */+export function cortexReader({ endpoint, apiKey }) {+ const call = async (method, route, body) => {+ const r = await fetch(`${endpoint}${route}`, {+ method,+ headers: {+ authorization: `Bearer ${apiKey}`,+ "content-type": "application/json",+ },+ body: body ? JSON.stringify(body) : undefined,+ signal: AbortSignal.timeout(30_000),+ });+ const text = await r.text();+ let json;+ try {+ json = JSON.parse(text);+ } catch {+ json = { raw: text };+ }+ return { status: r.status, body: json };+ };+ return {+ get: (route) => call("GET", route),+ post: (route, body) => call("POST", route, body),+ };+}++// ---------------------------------------------------------------------------+// builtin: the real account+// ---------------------------------------------------------------------------++export const SESSION_ENV = "OPENHUMAN_BACKEND_SESSION_TOKEN";++/** The session token from the environment; the run refuses builtin without it. */+export function builtinToken() {+ const token = process.env[SESSION_ENV];+ if (!token || token.split(".").length !== 3)+ throw new Error(+ `builtin needs a session JWT in ${SESSION_ENV} (it is never printed or written)`,+ );+ return token;+}++/** The active workspace directory, read from the running core. */+export async function activeWorkspace(core) {+ const snap = await core.rpc("openhuman.config_get", {});+ const cfg = pick(snap, "config", "snapshot.config", "snapshot") ?? snap;+ const ws = pick(cfg, "workspace_dir") ?? pick(snap, "workspace_dir");+ if (!ws) throw new Error("config_get carries no workspace_dir");+ return { workspace: ws, config: cfg };+}++/**+ * Guard 1: mark the layout migration done for this throwaway workspace, so the+ * memory background job's tick never starts moving the account's real legacy+ * tree. Written as the job's own state file; `migration_status` then reads+ * `cleaned`. Returns the state read back, or throws.+ */+export async function placeMigrationGuard(core, statePath) {+ await fsp.mkdir(path.dirname(statePath), { recursive: true });+ const state = {+ phase: "cleaned",+ copied: 0,+ replayed: 0,+ switched: true,+ caught_up: true,+ cleaning: false,+ takeover: false,+ };+ await fsp.writeFile(statePath, JSON.stringify(state, null, 2));+ const status = await core.rpc("openhuman.memory_migration_status", {});+ const phase = pick(status, "state.phase");+ if (phase !== "cleaned" || status.running)+ throw new Error(+ `migration guard not in effect: phase=${phase} running=${status.running}`,+ );+ return status;+}++/** Guard 1, checked at the end: nothing moved, nothing imported. */+export async function verifyBuiltinUntouched(core) {+ const migration = await core.rpc("openhuman.memory_migration_status", {});+ const imp = await core.rpc("openhuman.memory_import_status", {});+ return {+ migration_phase: pick(migration, "state.phase"),+ migration_running: migration.running,+ migration_copied: pick(migration, "state.copied"),+ import_phase: pick(imp, "state.phase"),+ ok:+ pick(migration, "state.phase") === "cleaned" &&+ !migration.running &&+ (pick(migration, "state.copied") ?? 0) === 0 &&+ ["idle", undefined].includes(pick(imp, "state.phase")),+ };+}++/**+ * Guard 2: forget exactly the ids this run stored, then confirm each is gone.+ * Returns the ids that survived.+ */+export async function forgetLedger(core, ledger) {+ const ids = ledger.list();+ for (let i = 0; i < ids.length; i += 50)+ await core.tryRpc("openhuman.memory_forget", { ids: ids.slice(i, i + 50) });+ const survivors = [];+ for (let i = 0; i < ids.length; i += 50) {+ const got = await core.tryRpc("openhuman.memory_items_get", {+ ids: ids.slice(i, i + 50),+ });+ for (const item of got.ok ? (got.value?.items ?? []) : [])+ survivors.push(item.id);+ }+ return survivors;+}diff --git a/scripts/memory-scenarios/fixtures/home/jordan.lee/notes/reading-queue.md b/scripts/memory-scenarios/fixtures/home/jordan.lee/notes/reading-queue.mdnew file mode 100644index 0000000000..ebb7a32f0f--- /dev/null+++ b/scripts/memory-scenarios/fixtures/home/jordan.lee/notes/reading-queue.md@@ -0,0 +1,5 @@+# Reading Queue (fictional)++1. The Lighthouse Ledger, by M. Okafor+2. Rivers of Cobalt, by S. Lindqvist+3. A Short History of Small Boats, by T. Ferreiradiff --git a/scripts/memory-scenarios/fixtures/persona.json b/scripts/memory-scenarios/fixtures/persona.jsonnew file mode 100644index 0000000000..9b4a78514b--- /dev/null+++ b/scripts/memory-scenarios/fixtures/persona.json@@ -0,0 +1,52 @@+{+ "_comment": "Entirely fictional. One persona; every domain is *.example; the phone numbers are in the reserved 555-01xx range. Safe to commit and to store on a real account (the run forgets everything it wrote).",+ "today": "2026-10-08",+ "yesterday": "2026-10-07",+ "time_zone": "Asia/Kolkata",+ "user": {+ "name": "Jordan Lee",+ "email": "[email protected]",+ "phone": "+15555550142",+ "language": "English"+ },+ "contacts": [+ { "name": "Priya Raman", "email": "[email protected]", "phone": "+15555550117" },+ { "name": "Mateo Alvarez", "email": "[email protected]", "phone": "+15555550188" }+ ],+ "learnings": [+ { "kind": "preference", "text": "Jordan prefers meeting summaries as three bullet points, never prose." },+ { "kind": "fact", "text": "Jordan's sister Priya Raman lives in Pune and visits every Diwali." },+ { "kind": "procedure", "text": "To file an expense, Jordan exports the receipt as PDF and emails it to [email protected]." },+ { "kind": "correction", "text": "Jordan's manager is Dana Whitfield, not Dana Whitman." },+ { "kind": "other", "text": "Jordan keeps a running list of book recommendations in a note titled Reading Queue." }+ ],+ "planted": {+ "text": "Jordan is allergic to peanuts; never suggest dishes with peanuts.",+ "probe": "Suggest one quick Thai dish I could cook tonight.",+ "must_not_contain": ["peanut"]+ },+ "dated": [+ { "date": "2026-10-07", "turn": "Today I finished the quarterly vendor review for Northwind and sent it to Dana." },+ { "date": "2026-10-03", "turn": "Today I booked the dentist for the 20th and renewed my library card." }+ ],+ "cross_thread": {+ "store": "My bike lock combination is not something to store, but my bike is a teal Brompton named Kestrel.",+ "probe": "What colour is my bike, and what did I name it?",+ "expect_any": ["teal", "kestrel"]+ },+ "negative_control": {+ "probe": "What is the name of my pet tortoise?",+ "must_not_invent": true+ },+ "brain_doc": {+ "title": "Northwind travel policy (fictional)",+ "text": "Northwind Travel Policy. Economy class for flights under 6 hours. Hotel cap is 180 EUR per night in Berlin and 140 EUR elsewhere in Germany. Per diem is 45 EUR. Bookings go through [email protected] at least 14 days ahead.",+ "probe": "What is the Northwind hotel cap per night in Berlin?",+ "expect_any": ["180"]+ },+ "path_file": {+ "relative": "home/jordan.lee/notes/reading-queue.md",+ "basename": "reading-queue.md",+ "username": "jordan.lee"+ }+}diff --git a/scripts/memory-scenarios/lib.mjs b/scripts/memory-scenarios/lib.mjsnew file mode 100644index 0000000000..8cdcbb2124--- /dev/null+++ b/scripts/memory-scenarios/lib.mjs@@ -0,0 +1,472 @@+// Harness plumbing shared by run.mjs and the scenarios: a headless core over+// JSON-RPC (shaped like scripts/life-scenarios/run.mjs), the composer's event+// stream, a turn driver, an RPC log, the findings list and the ledger of every+// id a run stored.++import fs from "node:fs";+import fsp from "node:fs/promises";+import net from "node:net";+import path from "node:path";+import { spawn } from "node:child_process";+import { randomBytes, randomUUID } from "node:crypto";+import { setTimeout as sleep } from "node:timers/promises";++export { sleep, randomUUID };++/** A free loopback port. */+export async function freePort() {+ return new Promise((resolve, reject) => {+ const srv = net.createServer();+ srv.unref();+ srv.on("error", reject);+ srv.listen(0, "127.0.0.1", () => {+ const { port } = srv.address();+ srv.close(() => resolve(port));+ });+ });+}++/**+ * Remove anything token-shaped from text bound for a file: JWTs (`eyJ…`),+ * bearer values and the given secrets. Every file this suite writes goes+ * through it, so a run directory can be shared.+ */+export function scrub(text, secrets = []) {+ let out = String(text);+ for (const s of secrets)+ if (s && s.length >= 8) out = out.split(s).join("<redacted>");+ out = out.replace(+ /eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]*/g,+ "<jwt>",+ );+ out = out.replace(/(bearer\s+)[A-Za-z0-9._~+/-]{16,}/gi, "$1<redacted>");+ return out;+}++/** Append-only JSONL writer whose lines are scrubbed. */+export class JsonlLog {+ constructor(file, secrets) {+ this.file = file;+ this.secrets = secrets;+ }+ async write(obj) {+ await fsp.mkdir(path.dirname(this.file), { recursive: true });+ await fsp.appendFile(+ this.file,+ scrub(JSON.stringify(obj), this.secrets) + "\n",+ );+ }+}++/** Retry `fn` until it stops throwing. */+export async function withRetries(fn, { attempts = 10, delayMs = 500, what }) {+ let last;+ for (let i = 0; i < attempts; i += 1) {+ try {+ return await fn();+ } catch (e) {+ last = e;+ await sleep(delayMs);+ }+ }+ throw new Error(+ `${what} never settled after ${attempts} attempts: ${last?.message ?? last}`,+ );+}++/** Poll `probe` until it returns a truthy value, else throw. */+export async function waitFor(+ probe,+ { timeoutMs = 60_000, intervalMs = 500, what },+) {+ const deadline = Date.now() + timeoutMs;+ let last;+ while (Date.now() < deadline) {+ try {+ const v = await probe();+ if (v) return v;+ } catch (e) {+ last = e;+ }+ await sleep(intervalMs);+ }+ throw new Error(+ `${what} not reached within ${timeoutMs}ms${last ? `: ${last.message}` : ""}`,+ );+}++/** An RPC error that keeps the JSON-RPC error object for checks. */+export class RpcError extends Error {+ constructor(method, error) {+ super(`RPC ${method} error: ${JSON.stringify(error).slice(0, 500)}`);+ this.method = method;+ this.rpc = error;+ }+}++/**+ * `openhuman-core serve` with its own HOME. Shaped like life-scenarios' Core:+ * same env isolation, same health wait, same envelope unwrapping. Every RPC is+ * logged (scrubbed) to `rpcLog`.+ */+export class Core {+ constructor({ coreBin, rpcLog, secrets = [] }) {+ this.coreBin = coreBin;+ this.rpcLog = rpcLog;+ this.secrets = secrets;+ this.proc = null;+ this.port = 0;+ this.token = randomBytes(24).toString("hex");+ this.exited = null;+ this.seq = 0;+ }++ get url() {+ return `http://127.0.0.1:${this.port}`;+ }++ /** `extraEnv` carries what the engine needs (e.g. the builtin session token). */+ async start({ home, actionDir, logPath, extraEnv = {} }) {+ this.port = await freePort();+ await fsp.mkdir(actionDir, { recursive: true });+ const log = fs.createWriteStream(logPath, { flags: "a" });+ const env = {+ ...process.env,+ HOME: home,+ OPENHUMAN_HOME: path.join(home, ".openhuman"),+ OPENHUMAN_CORE_TOKEN: this.token,+ OPENHUMAN_CORE_PORT: String(this.port),+ OPENHUMAN_CORE_HOST: "127.0.0.1",+ OPENHUMAN_ACTION_DIR: actionDir,+ RUST_LOG: process.env.RUST_LOG || "info",+ ...extraEnv,+ };+ // The operator's own session or key must never reach a local-engine core.+ if (!("OPENHUMAN_BACKEND_SESSION_TOKEN" in extraEnv))+ delete env.OPENHUMAN_BACKEND_SESSION_TOKEN;+ if (!("OPENHUMAN_BACKEND_API_KEY" in extraEnv))+ delete env.OPENHUMAN_BACKEND_API_KEY;+ this.proc = spawn(this.coreBin, ["serve"], {+ env,+ stdio: ["ignore", "pipe", "pipe"],+ cwd: actionDir,+ });+ // The core log is scrubbed line by line on its way to disk.+ const pipe = (stream) => {+ let buf = "";+ stream.on("data", (chunk) => {+ buf += chunk.toString();+ let i;+ while ((i = buf.indexOf("\n")) >= 0) {+ log.write(scrub(buf.slice(0, i + 1), this.secrets));+ buf = buf.slice(i + 1);+ }+ });+ stream.on("end", () => buf && log.write(scrub(buf, this.secrets)));+ };+ pipe(this.proc.stdout);+ pipe(this.proc.stderr);+ this.proc.on("exit", (code, sig) => {+ this.exited = { code, sig };+ });+ return waitFor(+ async () => {+ if (this.exited)+ throw new Error(+ `core exited during boot (${JSON.stringify(this.exited)}); see ${logPath}`,+ );+ const r = await fetch(`${this.url}/health`, {+ signal: AbortSignal.timeout(3000),+ });+ return r.ok ? r.json() : null;+ },+ { timeoutMs: 120_000, what: `core health on ${this.url}` },+ );+ }++ /** Call a method; returns the result, throws RpcError on a JSON-RPC error. */+ async rpc(method, params = {}, timeoutMs = 120_000) {+ const id = `ms-${++this.seq}`;+ const started = Date.now();+ let body;+ try {+ const res = await fetch(`${this.url}/rpc`, {+ method: "POST",+ headers: {+ "content-type": "application/json",+ authorization: `Bearer ${this.token}`,+ },+ body: JSON.stringify({ jsonrpc: "2.0", id, method, params }),+ signal: AbortSignal.timeout(timeoutMs),+ });+ const text = await res.text();+ if (!res.ok)+ throw new Error(+ `RPC ${method} HTTP ${res.status}: ${text.slice(0, 400)}`,+ );+ body = JSON.parse(text);+ } catch (e) {+ await this.rpcLog?.write({+ id,+ method,+ params,+ ms: Date.now() - started,+ transport_error: e.message,+ });+ throw e;+ }+ await this.rpcLog?.write({+ id,+ method,+ params,+ ms: Date.now() - started,+ result: body.result,+ error: body.error,+ });+ if (body.error) throw new RpcError(method, body.error);+ const r = body.result;+ // `apply_log_envelope` wraps a result that carried log lines.+ if (r && typeof r === "object" && "result" in r && "logs" in r)+ return r.result;+ return r;+ }++ /** `rpc` that returns `{ok, value|error}` instead of throwing. */+ async tryRpc(method, params, timeoutMs) {+ try {+ return { ok: true, value: await this.rpc(method, params, timeoutMs) };+ } catch (e) {+ return { ok: false, error: e.rpc ?? { message: e.message } };+ }+ }++ async stop() {+ if (!this.proc || this.exited) return;+ this.proc.kill("SIGTERM");+ const deadline = Date.now() + 15_000;+ while (!this.exited && Date.now() < deadline) await sleep(100);+ if (!this.exited) this.proc.kill("SIGKILL");+ }+}++/** The composer's event stream, `GET /events?client_id=…`. */+export class EventStream {+ constructor(core, clientId) {+ this.core = core;+ this.clientId = clientId;+ this.handlers = new Set();+ this.controller = new AbortController();+ }+ onEvent(fn) {+ this.handlers.add(fn);+ return () => this.handlers.delete(fn);+ }+ async connect() {+ const url = `${this.core.url}/events?client_id=${encodeURIComponent(this.clientId)}`;+ const res = await fetch(url, {+ headers: {+ authorization: `Bearer ${this.core.token}`,+ accept: "text/event-stream",+ },+ signal: this.controller.signal,+ });+ if (!res.ok || !res.body)+ throw new Error(`events subscribe failed: HTTP ${res.status}`);+ (async () => {+ const decoder = new TextDecoder();+ let buffer = "";+ try {+ for await (const chunk of res.body) {+ buffer += decoder.decode(chunk, { stream: true });+ let idx;+ while ((idx = buffer.indexOf("\n\n")) >= 0) {+ const frame = buffer.slice(0, idx);+ buffer = buffer.slice(idx + 2);+ for (const line of frame.split("\n")) {+ if (!line.startsWith("data:")) continue;+ try {+ const ev = JSON.parse(line.slice(5).trim());+ for (const h of this.handlers) h(ev);+ } catch {+ /* not JSON */+ }+ }+ }+ }+ } catch {+ /* aborted or core stopped */+ }+ })();+ }+ close() {+ this.controller.abort();+ }+}++/**+ * One composer turn, exactly as the desktop app sends it+ * (`channel_web_chat`, then `chat_done` | `chat_error` on /events).+ */+export async function sendTurn({+ core,+ events,+ clientId,+ threadId,+ message,+ timeoutMs = 240_000,+}) {+ let requestId = null;+ const toolCalls = [];+ const finished = new Promise((resolve) => {+ const off = events.onEvent((ev) => {+ if (ev.client_id && ev.client_id !== clientId) return;+ if (ev.event === "tool_call")+ toolCalls.push(ev.tool_name || ev.tool || "");+ if (ev.event === "chat_done" || ev.event === "chat_error") {+ if (requestId && ev.request_id && ev.request_id !== requestId) return;+ if (!requestId && ev.thread_id && ev.thread_id !== threadId) return;+ off();+ resolve(ev);+ }+ });+ });+ const started = Date.now();+ const ack = await core.rpc("openhuman.channel_web_chat", {+ client_id: clientId,+ thread_id: threadId,+ message,+ source: "type",+ queue_mode: "interrupt",+ });+ requestId = ack?.request_id || ack?.requestId || null;+ const done = await Promise.race([+ finished,+ sleep(timeoutMs).then(() => null),+ ]);+ const ms = Date.now() - started;+ if (!done)+ return { error: `no chat_done within ${timeoutMs}ms`, ms, toolCalls };+ if (done.event === "chat_error")+ return {+ error: `chat_error (${done.error_type || "unknown"}): ${String(done.message || "").slice(0, 300)}`,+ ms,+ toolCalls,+ };+ return {+ reply: done.full_response || done.response || "",+ ms,+ toolCalls,+ usage: done.usage,+ };+}++/**+ * The findings list. A finding is a defect or an issue the run observed; it+ * says whether it was READ (seen in a response, a log line or a CortexDB read)+ * or INFERRED (deduced from what was seen).+ */+export class Findings {+ constructor() {+ this.items = [];+ this.checks = [];+ }+ /** Record a check; a failed one becomes a finding. */+ check({+ engine,+ scenario,+ id,+ ok,+ expected,+ actual,+ evidence,+ severity = "medium",+ basis = "READ",+ }) {+ this.checks.push({ engine, scenario, id, ok, expected, actual, evidence });+ if (!ok)+ this.add({+ engine,+ scenario,+ id,+ severity,+ expected,+ actual,+ evidence,+ basis,+ });+ return ok;+ }+ add({+ engine,+ scenario,+ id,+ severity = "medium",+ expected,+ actual,+ evidence,+ basis = "READ",+ }) {+ this.items.push({+ id: `${engine}/${scenario}/${id}`,+ engine,+ scenario,+ severity,+ expected,+ actual:+ typeof actual === "string"+ ? actual+ : JSON.stringify(actual)?.slice(0, 600),+ evidence,+ basis,+ });+ }+ /** Something worth the user's eye that is not a failed expectation. */+ note({ engine, scenario, id, text, evidence, basis = "READ" }) {+ this.add({+ engine,+ scenario,+ id,+ severity: "note",+ expected: "(observation)",+ actual: text,+ evidence,+ basis,+ });+ }+}++/**+ * Every id a run stored, by engine. On the builtin engine teardown forgets+ * exactly these and checks they are gone; nothing else on the account is+ * touched.+ */+export class Ledger {+ constructor() {+ this.ids = new Set();+ }+ add(id) {+ if (id) this.ids.add(String(id));+ }+ addAll(ids) {+ for (const id of ids ?? []) this.add(id);+ }+ list() {+ return [...this.ids];+ }+}++/** First non-null value at any of `paths` (dotted) in `obj`. */+export function pick(obj, ...paths) {+ for (const p of paths) {+ let v = obj;+ for (const k of p.split(".")) v = v?.[k];+ if (v !== undefined && v !== null) return v;+ }+ return undefined;+}++/** Count lines in a file matching `re` (0 when absent). */+export async function countLogLines(file, re) {+ const text = await fsp.readFile(file, "utf8").catch(() => "");+ return text.split("\n").filter((l) => re.test(l)).length;+}diff --git a/scripts/memory-scenarios/migration.mjs b/scripts/memory-scenarios/migration.mjsnew file mode 100644index 0000000000..f6d54af8ff--- /dev/null+++ b/scripts/memory-scenarios/migration.mjs@@ -0,0 +1,245 @@+// E. Layout v3 and the move into it (LOCAL ONLY: never on the real account).+//+// Runs last on the local engine: everything the earlier scenarios stored is in+// the legacy layout by then and moves with it.++import fsp from "node:fs/promises";+import path from "node:path";+import { DatabaseSync } from "node:sqlite";+import { sleep, waitFor, pick } from "./lib.mjs";++/** The v1 store the importer reads (DDL as in memory/import_tests.rs LEGACY_DDL). */+const LEGACY_DDL = `+CREATE TABLE memory_docs (+ document_id TEXT PRIMARY KEY, namespace TEXT NOT NULL, key TEXT NOT NULL, title TEXT NOT NULL,+ content TEXT NOT NULL, source_type TEXT NOT NULL, priority TEXT NOT NULL, tags_json TEXT NOT NULL,+ metadata_json TEXT NOT NULL, category TEXT NOT NULL, session_id TEXT, created_at REAL NOT NULL,+ updated_at REAL NOT NULL, markdown_rel_path TEXT NOT NULL, UNIQUE(namespace, key));+CREATE TABLE episodic_log (id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT NOT NULL, timestamp REAL NOT NULL,+ role TEXT NOT NULL, content TEXT NOT NULL, lesson TEXT);+CREATE TABLE user_profile (facet_id TEXT PRIMARY KEY, facet_type TEXT NOT NULL, key TEXT NOT NULL, value TEXT NOT NULL,+ confidence REAL NOT NULL DEFAULT 0.5, evidence_count INTEGER NOT NULL DEFAULT 1, source_segment_ids TEXT,+ first_seen_at REAL NOT NULL, last_seen_at REAL NOT NULL);+`;++const V1_DOCS = [+ [+ "v1-d1",+ "notes",+ "garden",+ "Garden plan",+ "Plant the winter kale on the east bed in November.",+ ],+ [+ "v1-d2",+ "notes",+ "boat",+ "Boat club",+ "The Lakeside boat club meets on the first Saturday of the month.",+ ],+ [+ "v1-d3",+ "learning:style",+ "tone",+ "Tone",+ "Keep answers short and skip the pleasantries.",+ ],+];++/** Write a small v1 store into `<workspace>/memory/memory.db`. */+async function writeV1Store(workspace) {+ const dir = path.join(workspace, "memory");+ await fsp.mkdir(dir, { recursive: true });+ const db = new DatabaseSync(path.join(dir, "memory.db"));+ db.exec(LEGACY_DDL);+ const now = Date.now() / 1000 - 86_400 * 30;+ const doc = db.prepare(+ "INSERT INTO memory_docs VALUES (?, ?, ?, ?, ?, 'chat', 'normal', '[]', '{}', 'core', NULL, ?, ?, ?)",+ );+ for (const [id, ns, key, title, content] of V1_DOCS)+ doc.run(id, ns, key, title, content, now, now, `${key}.md`);+ const ep = db.prepare(+ "INSERT INTO episodic_log (session_id, timestamp, role, content, lesson) VALUES ('v1-s1', ?, ?, ?, NULL)",+ );+ ep.run(now, "user", "Can you remind me when the boat club meets?");+ ep.run(+ now + 5,+ "assistant",+ "The Lakeside boat club meets on the first Saturday of the month.",+ );+ db.prepare(+ "INSERT INTO user_profile VALUES ('v1-f1', 'preference', 'tone', 'terse', 0.9, 1, NULL, ?, ?)",+ ).run(now, now);+ db.close();+ return { docs: V1_DOCS.length, conversations: 2, learnings: 1 };+}++export const migration = {+ id: "E-migration",+ title:+ "Layout v3 and the move: import first, then organize; resumable; nothing lost; chats pooled",+ engines: ["local"],+ last: true,+ async run(ctx) {+ const { check } = ctx;+ const status = () => ctx.rpc("openhuman.memory_migration_status", {});++ // Seed the legacy layout with a little more, and a question to re-ask.+ await ctx.learn("Jordan's bike is a teal Brompton named Kestrel.", "fact");+ const t = ctx.newThread("E-legacy-chat");+ await ctx.turn(t, "Note that the Kestrel launch is on the 14th.");+ await ctx.waitItems({ thread_id: t }, 1, 60_000);+ const question = "What colour is my bike?";+ const before = await ctx.tryRpc("openhuman.memory_recall", { question });++ const { workspace, config } = await ctx.activeWorkspace();+ check(+ "E0-starts-legacy",+ (pick(config, "memory.layout") ?? "legacy") === "legacy",+ "the run starts in the legacy layout",+ pick(config, "memory.layout"),+ );++ const v1 = await writeV1Store(workspace);+ const scan = await ctx.rpc("openhuman.memory_import_scan", {});+ check(+ "E1-import-found",+ scan?.found === true,+ "the v1 store is found",+ scan,+ );+ const mscan = await ctx.rpc("openhuman.memory_migration_scan", {});+ check(+ "E1-move-needed",+ mscan?.needed === true,+ "legacy memory is offered for the move",+ mscan,+ );++ const beforeItems = await ctx.listAll({});+ const beforeTexts = new Set(beforeItems.map((h) => h.text));+ ctx.results.migration = { before_count: beforeItems.length, v1 };++ // One banner flow: import with consent; organizing starts on its own.+ await ctx.rpc("openhuman.memory_import_start", { consent: true });+ const imported = await waitFor(+ async () => {+ const s = await ctx.rpc("openhuman.memory_import_status", {});+ return ["done", "error"].includes(pick(s, "state.phase")) ? s : null;+ },+ { timeoutMs: 600_000, intervalMs: 1000, what: "import finished" },+ );+ check(+ "E2-import-done",+ pick(imported, "state.phase") === "done",+ "the import finishes",+ imported,+ );++ // Organizing starts on its own; try to stop the core mid-move.+ let restarted = false;+ const deadline = Date.now() + 600_000;+ let last;+ while (Date.now() < deadline) {+ last = await status();+ const phase = pick(last, "state.phase");+ if (!restarted && last.running && phase === "copying") {+ await ctx.restartCore();+ restarted = true;+ const after = await status();+ ctx.results.migration.after_restart = after;+ if (!after.running)+ await ctx.rpc("openhuman.memory_migration_start", {});+ continue;+ }+ if (phase === "cleaned" && !last.running) break;+ await sleep(250);+ }+ check(+ "E3-organized",+ pick(last, "state.phase") === "cleaned",+ "organizing finishes (cleaned)",+ last,+ "high",+ );+ if (!restarted)+ ctx.note(+ "E4-restart",+ "the move finished before it could be caught mid-copy; resume-after-restart was not exercised this run",+ );+ else+ check(+ "E4-resumed",+ pick(last, "state.phase") === "cleaned",+ "the move finishes after a core restart mid-copy",+ ctx.results.migration.after_restart,+ );++ const { config: after } = await ctx.activeWorkspace();+ check(+ "E5-layout-v3",+ pick(after, "memory.layout") === "v3",+ "the layout setting is now v3",+ pick(after, "memory.layout"),+ "high",+ );++ // Nothing lost: every item text from before is still there.+ const afterItems = await ctx.listAll({});+ const afterTexts = new Set(afterItems.map((h) => h.text));+ const lost = [...beforeTexts].filter((x) => !afterTexts.has(x));+ ctx.results.migration.after_count = afterItems.length;+ ctx.results.migration.failures = pick(last, "state.failures") ?? [];+ check(+ "E6-nothing-lost",+ lost.length === 0,+ "every item from before the move is in the per-user tree",+ { lost: lost.slice(0, 10), lost_count: lost.length },+ "high",+ );+ const v1Seen = V1_DOCS.filter(([, , , , content]) =>+ afterItems.some((h) => (h.text ?? "").includes(content.slice(0, 30))),+ );+ check(+ "E7-v1-imported",+ v1Seen.length === V1_DOCS.length,+ "the v1 store's documents are in memory",+ { seen: v1Seen.map((d) => d[0]) },+ );++ // Chats pooled at ws:main.+ const convs = afterItems.filter((h) => h.kind === "conversation");+ const unpooled = convs.filter(+ (h) => !String(h.meta?.namespace ?? "").startsWith("ws:main"),+ );+ check(+ "E8-chats-pooled",+ convs.length > 0 && unpooled.length === 0,+ "every conversation sits at the pooled chat node (ws:main)",+ {+ conversations: convs.length,+ elsewhere: unpooled.slice(0, 5).map((h) => h.meta?.namespace),+ },+ );++ // Recall answers unchanged.+ const afterRecall = await ctx.tryRpc("openhuman.memory_recall", {+ question,+ });+ if (ctx.recallQualityChecked)+ check(+ "E9-recall-unchanged",+ /teal/i.test(afterRecall.value?.answer ?? "") ===+ /teal/i.test(before.value?.answer ?? ""),+ "the same question recalls the same fact after the move",+ { before: before.value?.answer, after: afterRecall.value?.answer },+ "medium",+ "INFERRED",+ );++ ctx.note(+ "E10-not-automated",+ "workflow memory staying out of chat (sandbox) and the unconfirmed-import no-erase guard are covered by unit tests, not driven here",+ );+ },+};diff --git a/scripts/memory-scenarios/mock-composio.mjs b/scripts/memory-scenarios/mock-composio.mjsnew file mode 100644index 0000000000..3e6b0ef6cf--- /dev/null+++ b/scripts/memory-scenarios/mock-composio.mjs@@ -0,0 +1,196 @@+// A stateful mock of Composio's direct API (v3), enough for memory's connector+// sync: Gmail and GitHub connections, their fetch actions, and a DELETE.+//+// The core reaches it through `[composio] mode = "direct"` plus BOTH+// `OPENHUMAN_COMPOSIO_DIRECT_BASE_V3` and `..._V2` in a debug build (see+// scripts/life-scenarios/README.md, "Mock Composio"). Unlike life-scenarios'+// mock, items carry the version fields the sync keys edits on (Gmail+// `historyId`, GitHub `updated_at`), it answers the `after:` window query, and+// tests can edit an item, slow a fetch down, or drop a connection.+//+// All content is fictional (*.example, github.com/northwind-example).++import http from "node:http";++const ACCOUNT = "ca_memscen";++function freshState() {+ return {+ connections: {+ gmail: {+ id: `${ACCOUNT}-gmail`,+ status: "ACTIVE",+ toolkit: { slug: "gmail" },+ },+ github: {+ id: `${ACCOUNT}-github`,+ status: "ACTIVE",+ toolkit: { slug: "github" },+ },+ },+ gmail: [+ {+ id: "msg-001",+ historyId: "1001",+ sender: "Priya Raman <[email protected]>",+ subject: "Diwali travel",+ messageText:+ "Hi Jordan, I land in Pune on the 30th at 7pm. Can you pick me up? Priya",+ messageUrl: "https://mail.example/msg-001",+ },+ {+ id: "msg-002",+ historyId: "1002",+ sender: "Mateo Alvarez <[email protected]>",+ subject: "Kestrel logo drafts",+ messageText:+ "Three logo drafts for Kestrel are attached; I prefer the second one.",+ messageUrl: "https://mail.example/msg-002",+ },+ ],+ github: [+ {+ id: 9001,+ number: 12,+ title: "Kestrel: launch checklist",+ body: "Track the launch checklist for the Kestrel app: store listing, privacy note, release notes.",+ html_url: "https://github.com/northwind-example/kestrel/issues/12",+ updated_at: "2026-10-01T09:00:00Z",+ },+ {+ id: 9002,+ number: 4,+ title: "Docs: travel policy page",+ body: "Add the hotel caps to the travel policy page.",+ html_url: "https://github.com/northwind-example/handbook/pull/4",+ updated_at: "2026-10-02T09:00:00Z",+ },+ ],+ fetchDelayMs: 0,+ requests: [],+ };+}++export async function startMockComposio({ port = 0 } = {}) {+ const ctx = freshState();++ const reply = (res, status, body) => {+ res.writeHead(status, { "content-type": "application/json" });+ res.end(JSON.stringify(body));+ };++ const actions = {+ GMAIL_GET_PROFILE: () => ({+ emailAddress: "[email protected]",+ historyId: "2000",+ }),+ GMAIL_FETCH_EMAILS: () => ({ messages: ctx.gmail, nextPageToken: null }),+ GITHUB_GET_THE_AUTHENTICATED_USER: () => ({+ login: "jordanlee-example",+ id: 4242,+ }),+ GITHUB_SEARCH_ISSUES_AND_PULL_REQUESTS: () => ({+ items: ctx.github,+ total_count: ctx.github.length,+ }),+ };+ const slowActions = new Set([+ "GMAIL_FETCH_EMAILS",+ "GITHUB_SEARCH_ISSUES_AND_PULL_REQUESTS",+ ]);++ const server = http.createServer(async (req, res) => {+ let raw = "";+ for await (const chunk of req) raw += chunk;+ let body = {};+ try {+ body = raw ? JSON.parse(raw) : {};+ } catch {+ /* not JSON */+ }+ const url = new URL(req.url, "http://mock");+ ctx.requests.push({+ at: new Date().toISOString(),+ method: req.method,+ path: url.pathname,+ body,+ });++ // Connections.+ if (+ /\/(connected_accounts|connections)\/?$/.test(url.pathname) &&+ req.method === "GET"+ ) {+ const items = Object.values(ctx.connections);+ return reply(res, 200, { items, total_items: items.length });+ }+ const del = url.pathname.match(+ /\/(connected_accounts|connections)\/([^/]+)$/,+ );+ if (del && req.method === "DELETE") {+ for (const [k, c] of Object.entries(ctx.connections))+ if (c.id === decodeURIComponent(del[2])) delete ctx.connections[k];+ return reply(res, 200, { success: true });+ }+ // Execute.+ const exec =+ url.pathname.match(/\/tools\/execute\/([A-Z0-9_]+)$/) ||+ url.pathname.match(/\/actions\/([A-Z0-9_]+)\/execute$/);+ if (exec && req.method === "POST") {+ const action = exec[1];+ const fn = actions[action];+ if (!fn)+ return reply(res, 404, {+ successful: false,+ error: `mock: no ${action}`,+ data: null,+ });+ if (slowActions.has(action) && ctx.fetchDelayMs)+ await new Promise((r) => setTimeout(r, ctx.fetchDelayMs));+ return reply(res, 200, {+ successful: true,+ error: null,+ data: fn(body.arguments ?? {}),+ });+ }+ if (/\/(toolkits|tools)\/?$/.test(url.pathname))+ return reply(res, 200, { items: [], total_items: 0 });+ return reply(res, 404, {+ successful: false,+ error: `mock: no route ${req.method} ${url.pathname}`,+ });+ });++ await new Promise((resolve) => server.listen(port, "127.0.0.1", resolve));+ const { port: bound } = server.address();+ return {+ url: `http://127.0.0.1:${bound}`,+ ctx,+ connectionId: (toolkit) =>+ ctx.connections[toolkit]?.id ?? `${ACCOUNT}-${toolkit}`,+ /** Change an item's body and bump its version, as an edit upstream does. */+ edit(toolkit, id, text) {+ if (toolkit === "gmail") {+ const m = ctx.gmail.find((x) => x.id === id);+ m.messageText = text;+ m.historyId = String(Number(m.historyId) + 100);+ } else {+ const it = ctx.github.find((x) => x.id === id);+ it.body = text;+ it.updated_at = new Date().toISOString();+ }+ },+ /** Put a connection back (a reconnect). */+ reconnect(toolkit) {+ ctx.connections[toolkit] = {+ id: `${ACCOUNT}-${toolkit}`,+ status: "ACTIVE",+ toolkit: { slug: toolkit },+ };+ },+ setFetchDelay(ms) {+ ctx.fetchDelayMs = ms;+ },+ close: () => new Promise((r) => server.close(r)),+ };+}diff --git a/scripts/memory-scenarios/run.mjs b/scripts/memory-scenarios/run.mjsnew file mode 100644index 0000000000..7f5fefd3f3--- /dev/null+++ b/scripts/memory-scenarios/run.mjs@@ -0,0 +1,688 @@+#!/usr/bin/env node+// Memory scenarios: realistic memory flows against a real headless core, on a+// throwaway local CortexDB and on Built-in (the user's real account), checked+// by the script itself. Every failed check is a finding for the user; nothing+// is fixed during a run. See README.md.++import fs from "node:fs";+import fsp from "node:fs/promises";+import path from "node:path";+import { fileURLToPath } from "node:url";+import {+ Core,+ EventStream,+ JsonlLog,+ Findings,+ Ledger,+ sendTurn,+ waitFor,+ withRetries,+ pick,+ randomUUID,+ sleep,+ scrub,+} from "./lib.mjs";+import {+ startLocalCortex,+ activeWorkspace,+ placeMigrationGuard,+ verifyBuiltinUntouched,+ forgetLedger,+ builtinToken,+ SESSION_ENV,+} from "./engines.mjs";+import { startMockComposio } from "./mock-composio.mjs";+import { SCENARIOS, registerLocalOnly } from "./scenarios.mjs";+import { connectors } from "./connectors.mjs";+import { migration } from "./migration.mjs";++registerLocalOnly(connectors, migration);++const HERE = path.dirname(fileURLToPath(import.meta.url));+const REPO = path.resolve(HERE, "..", "..");+const FIXTURES = path.join(HERE, "fixtures");++function parseArgs(argv) {+ const opts = {+ only: [],+ engine: "both",+ keep: false,+ gradeOnly: "",+ coreBin: path.join(REPO, "target", "debug", "openhuman-core"),+ runRoot: path.join(REPO, "target", "memory-scenarios"),+ settleMs: 4000,+ };+ for (let i = 0; i < argv.length; i += 1) {+ const a = argv[i];+ const next = () => argv[++i];+ if (a === "--only") opts.only.push(...next().split(","));+ else if (a === "--engine") opts.engine = next();+ else if (a === "--keep") opts.keep = true;+ else if (a === "--grade-only") opts.gradeOnly = next();+ else if (a === "--core-bin") opts.coreBin = next();+ else if (a === "--settle-ms") opts.settleMs = Number(next());+ else if (a === "--help" || a === "-h") {+ console.log(+ fs+ .readFileSync(path.join(HERE, "README.md"), "utf8")+ .split("\n")+ .slice(0, 30)+ .join("\n"),+ );+ process.exit(0);+ } else throw new Error(`unknown argument ${a}`);+ }+ if (!["local", "builtin", "both"].includes(opts.engine))+ throw new Error("--engine local|builtin|both");+ return opts;+}++/** The offline local session token (as life-scenarios mints it). */+function mintLocalSessionToken(userId) {+ const b64 = (o) => Buffer.from(JSON.stringify(o)).toString("base64url");+ const now = Math.floor(Date.now() / 1000);+ return [+ b64({ alg: "none", typ: "JWT" }),+ b64({+ sub: userId,+ iat: now,+ exp: now + 86_400,+ email: "[email protected]",+ }),+ "local",+ ].join(".");+}++/** The subject of a JWT, read locally (never printed). */+function jwtSubject(token) {+ const payload = JSON.parse(+ Buffer.from(token.split(".")[1], "base64url").toString(),+ );+ return payload.sub ?? payload._id ?? payload.userId;+}++/** Set `key = value` lines in a TOML section of `file` (a small, line-based edit). */+async function editToml(file, section, kv) {+ let text = await fsp.readFile(file, "utf8").catch(() => "");+ const lines = text.split("\n");+ const header = `[${section}]`;+ let start = lines.findIndex((l) => l.trim() === header);+ if (start < 0) {+ lines.push("", header);+ start = lines.length - 1;+ }+ let end = lines.findIndex((l, i) => i > start && /^\s*\[/.test(l));+ if (end < 0) end = lines.length;+ for (const [k, v] of Object.entries(kv)) {+ const line = `${k} = ${typeof v === "string" ? JSON.stringify(v) : v}`;+ const at = lines+ .slice(start + 1, end)+ .findIndex(+ (l) => l.trim().startsWith(`${k} =`) || l.trim().startsWith(`${k}=`),+ );+ if (at >= 0) lines[start + 1 + at] = line;+ else {+ lines.splice(end, 0, line);+ end += 1;+ }+ }+ await fsp.writeFile(file, lines.join("\n"));+}++const BASE_CONFIG = (extra = []) =>+ [+ "schema_version = 13",+ "onboarding_completed = true",+ "chat_onboarding_completed = true",+ "",+ "[observability]",+ "analytics_enabled = false",+ "share_usage_data = false",+ "",+ ...extra,+ ].join("\n");++// ---------------------------------------------------------------------------+// one engine+// ---------------------------------------------------------------------------++async function runEngine(engine, { opts, runDir, runId, findings, results }) {+ const dir = path.join(runDir, engine);+ const home = path.join(dir, "home");+ const oh = path.join(home, ".openhuman");+ await fsp.mkdir(oh, { recursive: true });+ const marker = `memscen:${runId}`;+ const secrets = [];+ const extraEnv = {};+ const engineResults = { engine, marker, scenarios: {} };+ results.engines[engine] = engineResults;+ const log = (m) => console.log(m);++ let cortex = null;+ let composio = null;+ let core = null;+ let events = null;+ const ledger = new Ledger();+ const threads = [];+ let token = null;++ // --- engine setup -------------------------------------------------------+ if (engine === "local") {+ cortex = await startLocalCortex({+ runId,+ scriptDir: HERE,+ tinymemoryDir: path.join(REPO, "vendor", "tinymemory"),+ keep: opts.keep,+ log,+ });+ secrets.push(cortex.apiKey);+ engineResults.inference = cortex.inference;+ composio = await startMockComposio();+ extraEnv.OPENHUMAN_COMPOSIO_DIRECT_BASE_V3 = composio.url;+ extraEnv.OPENHUMAN_COMPOSIO_DIRECT_BASE_V2 = composio.url;+ await fsp.writeFile(+ path.join(oh, "config.toml"),+ BASE_CONFIG([+ "[composio]",+ 'mode = "direct"',+ 'api_key = "ck_memscen_mock"',+ 'entity_id = "default"',+ "",+ ]),+ );+ } else {+ token = builtinToken();+ secrets.push(token);+ extraEnv[SESSION_ENV] = token;+ // Guard 0: the scheduler gate is off in the account's user dir before the+ // core first boots, so no background job (migration tick, import resume,+ // belief builds) runs on its own. Verified below; abort if not in effect.+ const sub = jwtSubject(token);+ if (!sub) throw new Error("the session token carries no subject");+ const gated = BASE_CONFIG(["[scheduler_gate]", 'mode = "off"', ""]);+ await fsp.writeFile(path.join(oh, "config.toml"), gated);+ await fsp.mkdir(path.join(oh, "users", String(sub)), { recursive: true });+ await fsp.writeFile(+ path.join(oh, "users", String(sub), "config.toml"),+ gated,+ );+ }++ const rpcLog = new JsonlLog(path.join(dir, "rpc.jsonl"), secrets);+ const logFile = path.join(dir, "core.log");+ const startCore = async () => {+ core = new Core({ coreBin: opts.coreBin, rpcLog, secrets });+ const health = await core.start({+ home,+ actionDir: path.join(dir, "action"),+ logPath: logFile,+ extraEnv,+ });+ events = new EventStream(core, `memscen-${runId.slice(-8)}`);+ await events.connect();+ return health;+ };++ try {+ const health = await startCore();+ log(`${engine.padEnd(8)}: core ${core.url} pid ${health.pid}`);++ if (engine === "local") {+ const uid = "memscen-local";+ await core.rpc("openhuman.auth_set_credential", {+ token: mintLocalSessionToken(uid),+ kind: "local",+ userId: uid,+ user: { _id: uid, email: "[email protected]", name: "Jordan Lee" },+ });+ await withRetries(+ async () => {+ await core.rpc("openhuman.memory_engine_set", {+ engine: "cortexdb",+ endpoint: cortex.endpoint,+ api_key: cortex.apiKey,+ });+ const got = await core.rpc("openhuman.memory_engine_get", {});+ if (got?.engine !== "cortexdb" || got?.status !== "ok")+ throw new Error(+ `engine ${got?.engine} ${got?.status} ${got?.reason ?? ""}`,+ );+ },+ { attempts: 20, delayMs: 1000, what: "local CortexDB engine" },+ );+ // config.toml now lives in the activated user dir: the composio block too.+ const { config } = await activeWorkspace(core);+ const snap = await core.rpc("openhuman.config_get", {});+ const cfgPath = snap?.config_path;+ if (cfgPath && pick(config, "composio.mode") !== "direct") {+ await editToml(cfgPath, "composio", {+ mode: "direct",+ api_key: "ck_memscen_mock",+ entity_id: "default",+ });+ await core.stop();+ await startCore();+ }+ } else {+ // Guard 0 verified: the gate the account's config carries is off.+ const snap = await core.rpc("openhuman.config_get", {});+ const mode = pick(snap, "config.scheduler_gate.mode");+ if (mode !== "off")+ throw new Error(+ `ABORT builtin: scheduler gate is "${mode}", not "off" (user dir not the one pre-written)`,+ );+ const eng = await core.rpc("openhuman.memory_engine_get", {});+ if (eng?.engine !== "tinyhumans" || eng?.status === "off")+ throw new Error(+ `ABORT builtin: memory engine is ${eng?.engine}/${eng?.status} (${eng?.reason ?? ""}); is the session valid?`,+ );+ // Guard 1: the migration of this workspace counts as done.+ const { workspace } = await activeWorkspace(core);+ await placeMigrationGuard(+ core,+ path.join(workspace, "memory", "layout_migration.json"),+ );+ const imp = await core.rpc("openhuman.memory_import_scan", {});+ if (imp?.found)+ throw new Error(+ "ABORT builtin: a v1 store is present in the throwaway workspace",+ );+ engineResults.inference = { kind: "managed (account route)" };+ log(+ `builtin : guards in place (scheduler gate off, migration state cleaned, no v1 store)`,+ );+ }++ // --- scenarios ----------------------------------------------------------+ const selected = SCENARIOS.filter((s) => s.engines.includes(engine))+ .filter(+ (s) =>+ !opts.only.length ||+ opts.only.some((o) => s.id.toLowerCase().startsWith(o.toLowerCase())),+ )+ .sort((a, b) => Number(!!a.last) - Number(!!b.last));++ for (const scenario of selected) {+ const transcript = new JsonlLog(+ path.join(dir, "scenarios", scenario.id, "transcript.jsonl"),+ secrets,+ );+ const sres = { checks: 0, failed: 0, notes: 0, error: null, results: {} };+ engineResults.scenarios[scenario.id] = sres;+ const ctx = {+ engine,+ persona: JSON.parse(+ await fsp.readFile(path.join(FIXTURES, "persona.json"), "utf8"),+ ),+ fixtureCopy: path.join(dir, "action", "fixtures"),+ marker,+ ledger,+ threads,+ logFile,+ settleMs: opts.settleMs,+ recallQualityChecked:+ engine === "builtin" ||+ !!engineResults.inference?.recall_quality_checked,+ cortex,+ composio,+ results: sres.results,+ get core() {+ return core;+ },+ rpc: (m, p, t) => core.rpc(m, p, t),+ tryRpc: (m, p, t) => core.tryRpc(m, p, t),+ markMeta: (extra = {}) => ({ tags: [marker], ...extra }),+ newThread(label) {+ const id = `thread-${randomUUID()}`;+ threads.push(id);+ transcript.write({ thread: id, label });+ return id;+ },+ async turn(threadId, message) {+ const r = await sendTurn({+ core,+ events,+ clientId: events.clientId,+ threadId,+ message,+ });+ await transcript.write({+ thread: threadId,+ user: message,+ reply: r.reply,+ error: r.error,+ ms: r.ms,+ tools: r.toolCalls,+ });+ return r;+ },+ async learn(text, kind = "fact", meta = {}) {+ const r = await core.rpc("openhuman.memory_learn", {+ text,+ kind,+ meta: { tags: [marker], ...meta },+ });+ ledger.add(r?.id);+ return r?.id;+ },+ async listAll(filter = {}, max = 2000) {+ const out = [];+ let cursor;+ do {+ const page = await core.rpc("openhuman.memory_items_list", {+ filter,+ limit: 100,+ ...(cursor ? { cursor } : {}),+ });+ out.push(...(page?.items ?? []));+ cursor = page?.next_cursor;+ } while (cursor && out.length < max);+ return out;+ },+ async waitItems(filter, atLeast, timeoutMs) {+ return waitFor(+ async () => {+ const items = await ctx.listAll(filter);+ return items.length >= atLeast ? items : null;+ },+ {+ timeoutMs,+ intervalMs: 1500,+ what: `${atLeast} item(s) for ${JSON.stringify(filter)}`,+ },+ ).catch(() => ctx.listAll(filter));+ },+ async setChatAgent(id) {+ await withRetries(+ async () => {+ await core.rpc("openhuman.config_update_agent_settings", {+ chat_agent_id: id,+ });+ const snap = await core.rpc("openhuman.config_get", {});+ if ((pick(snap, "config.agent.chat_agent_id") ?? "") !== id)+ throw new Error("chat_agent_id not applied");+ },+ { what: "chat_agent_id" },+ );+ },+ activeWorkspace: () => activeWorkspace(core),+ async setConfigToml(section, kv) {+ if (engine !== "local")+ throw new Error("config edits are local-engine only");+ const snap = await core.rpc("openhuman.config_get", {});+ await editToml(snap.config_path, section, kv);+ },+ async restartCore() {+ events?.close();+ await core.stop();+ await startCore();+ },+ check(id, ok, expected, actual, severity = "medium", basis = "READ") {+ sres.checks += 1;+ if (!ok) sres.failed += 1;+ return findings.check({+ engine,+ scenario: scenario.id,+ id,+ ok,+ expected,+ actual,+ evidence: path.relative(+ runDir,+ path.join(dir, "scenarios", scenario.id),+ ),+ severity,+ basis,+ });+ },+ note(id, text, basis = "READ") {+ sres.notes += 1;+ findings.note({+ engine,+ scenario: scenario.id,+ id,+ text,+ evidence: path.relative(+ runDir,+ path.join(dir, "scenarios", scenario.id),+ ),+ basis,+ });+ },+ };+ await fsp.cp(FIXTURES, ctx.fixtureCopy, { recursive: true });+ process.stdout.write(`${engine.padEnd(8)}: ${scenario.id} ... `);+ const started = Date.now();+ try {+ await scenario.run(ctx);+ } catch (e) {+ sres.error = scrub(e.stack || e.message, secrets);+ findings.add({+ engine,+ scenario: scenario.id,+ id: "crashed",+ severity: "high",+ expected: "the scenario runs to the end",+ actual: sres.error.slice(0, 600),+ evidence: "core.log",+ basis: "READ",+ });+ }+ sres.ms = Date.now() - started;+ console.log(+ `${sres.error ? "CRASHED" : "done"} ${sres.checks - sres.failed}/${sres.checks} checks, ${sres.notes} notes (${(sres.ms / 1000).toFixed(0)}s)`,+ );+ }+ } finally {+ // --- teardown -----------------------------------------------------------+ if (engine === "builtin" && core && !core.exited) {+ try {+ // Everything this run stored: the ledger, every item in its threads,+ // every item carrying its marker.+ for (const t of threads) {+ const items = await core+ .rpc("openhuman.memory_items_list", {+ filter: { thread_id: t },+ limit: 100,+ })+ .catch(() => null);+ ledger.addAll((items?.items ?? []).map((h) => h.id));+ }+ const tagged = await core+ .rpc("openhuman.memory_items_list", {+ filter: { tags_any: [marker] },+ limit: 100,+ })+ .catch(() => null);+ ledger.addAll((tagged?.items ?? []).map((h) => h.id));+ const survivors = await forgetLedger(core, ledger);+ const untouched = await verifyBuiltinUntouched(core);+ engineResults.cleanup = {+ stored: ledger.list().length,+ survivors,+ untouched,+ };+ if (survivors.length)+ findings.add({+ engine,+ scenario: "teardown",+ id: "survivors",+ severity: "high",+ expected: "every item this run stored is forgotten",+ actual: survivors,+ evidence: "rpc.jsonl",+ basis: "READ",+ });+ if (!untouched.ok)+ findings.add({+ engine,+ scenario: "teardown",+ id: "account-touched",+ severity: "high",+ expected: "no migration or import ran on the real account",+ actual: untouched,+ evidence: "rpc.jsonl",+ basis: "READ",+ });+ console.log(+ `builtin : cleanup forgot ${ledger.list().length} ids, ${survivors.length} survived; migration/import untouched: ${untouched.ok}`,+ );+ } catch (e) {+ findings.add({+ engine,+ scenario: "teardown",+ id: "cleanup-failed",+ severity: "high",+ expected: "cleanup completes",+ actual: scrub(e.message, secrets),+ evidence: "rpc.jsonl",+ });+ }+ }+ events?.close();+ await core?.stop();+ if (composio) {+ await fsp.writeFile(+ path.join(dir, "composio-requests.json"),+ JSON.stringify(composio.ctx.requests, null, 2),+ );+ await composio.close();+ }+ await cortex+ ?.stop()+ .catch((e) => console.error(`local : teardown failed: ${e.message}`));+ }+}++// ---------------------------------------------------------------------------+// report+// ---------------------------------------------------------------------------++function renderReport({ runId, results, findings }) {+ const lines = [`# Memory scenarios ${runId}`, ""];+ for (const [engine, er] of Object.entries(results.engines)) {+ lines.push(`## ${engine}`, "");+ lines.push(`- inference: ${JSON.stringify(er.inference ?? {})}`);+ if (er.inference && er.inference.recall_quality_checked === false)+ lines.push(+ "- **recall-quality checks skipped**: Ollama was unreachable; the engine ran on the deterministic mock inference.",+ );+ if (er.cleanup) lines.push(`- cleanup: ${JSON.stringify(er.cleanup)}`);+ lines.push(+ "",+ "| scenario | checks passed | notes | time | crashed |",+ "| --- | --- | --- | --- | --- |",+ );+ for (const [id, s] of Object.entries(er.scenarios))+ lines.push(+ `| ${id} | ${s.checks - s.failed}/${s.checks} | ${s.notes} | ${((s.ms ?? 0) / 1000).toFixed(0)}s | ${s.error ? "yes" : ""} |`,+ );+ lines.push("");+ }+ const real = findings.filter((f) => f.severity !== "note");+ lines.push(+ `## Findings (${real.length})`,+ "",+ "| id | severity | basis | expected | actual |",+ "| --- | --- | --- | --- | --- |",+ );+ const order = { high: 0, medium: 1, low: 2 };+ for (const f of [...real].sort(+ (a, b) => (order[a.severity] ?? 3) - (order[b.severity] ?? 3),+ ))+ lines.push(+ `| ${f.id} | ${f.severity} | ${f.basis} | ${f.expected} | ${String(f.actual).replace(/\|/g, "\\|").slice(0, 300)} |`,+ );+ lines.push("", "## Notes", "");+ for (const f of findings.filter((x) => x.severity === "note"))+ lines.push(`- **${f.id}** (${f.basis}): ${f.actual}`);+ lines.push(+ "",+ "## Known gaps (not findings)",+ "",+ "- Channel messages are not logged to memory today, so the channel sender name (#7131) is inert: an open product question.",+ );+ return lines.join("\n") + "\n";+}++async function main() {+ const opts = parseArgs(process.argv.slice(2));+ if (opts.gradeOnly) {+ const findings = JSON.parse(+ await fsp.readFile(path.join(opts.gradeOnly, "findings.json"), "utf8"),+ );+ const results = JSON.parse(+ await fsp.readFile(path.join(opts.gradeOnly, "results.json"), "utf8"),+ );+ const md = renderReport({+ runId: path.basename(opts.gradeOnly),+ results,+ findings,+ });+ await fsp.writeFile(path.join(opts.gradeOnly, "report.md"), md);+ console.log(md);+ return;+ }+ if (!fs.existsSync(opts.coreBin))+ throw new Error(+ `core binary not found at ${opts.coreBin}\nbuild it (debug, for the Composio override): cargo build -p openhuman-cli --bin openhuman-core`,+ );+ const engines = opts.engine === "both" ? ["local", "builtin"] : [opts.engine];+ if (engines.includes("builtin")) builtinToken(); // refuse early, before anything starts+ const runId = new Date().toISOString().replace(/[:.]/g, "-");+ const runDir = path.join(opts.runRoot, runId);+ await fsp.mkdir(runDir, { recursive: true });+ console.log(`run dir : ${runDir}`);++ const findings = new Findings();+ const results = {+ run_id: runId,+ started: new Date().toISOString(),+ engines: {},+ };+ for (const engine of engines) {+ try {+ await runEngine(engine, { opts, runDir, runId, findings, results });+ } catch (e) {+ const secretSafe = scrub(+ e.message,+ process.env[SESSION_ENV] ? [process.env[SESSION_ENV]] : [],+ );+ console.error(`${engine}: ${secretSafe}`);+ findings.add({+ engine,+ scenario: "setup",+ id: "aborted",+ severity: "high",+ expected: "the engine sets up",+ actual: secretSafe,+ evidence: `${engine}/core.log`,+ });+ }+ }+ results.finished = new Date().toISOString();+ await fsp.writeFile(+ path.join(runDir, "findings.json"),+ JSON.stringify(findings.items, null, 2),+ );+ await fsp.writeFile(+ path.join(runDir, "checks.json"),+ JSON.stringify(findings.checks, null, 2),+ );+ await fsp.writeFile(+ path.join(runDir, "results.json"),+ JSON.stringify(results, null, 2),+ );+ const md = renderReport({ runId, results, findings: findings.items });+ await fsp.writeFile(path.join(runDir, "report.md"), md);+ console.log(+ `\nreport : ${path.join(runDir, "report.md")}\nfindings: ${findings.items.filter((f) => f.severity !== "note").length}`,+ );+}++main().catch((e) => {+ console.error(+ `\nfatal: ${scrub(e.stack || e.message, process.env[SESSION_ENV] ? [process.env[SESSION_ENV]] : [])}`,+ );+ process.exit(1);+});diff --git a/scripts/memory-scenarios/scenarios.mjs b/scripts/memory-scenarios/scenarios.mjsnew file mode 100644index 0000000000..c56f9f3785--- /dev/null+++ b/scripts/memory-scenarios/scenarios.mjs@@ -0,0 +1,736 @@+// The memory scenarios. Each one sets up, talks to the core (turns and RPCs),+// checks what came back and records failed checks as findings. Nothing is+// fixed during a run.+//+// `ctx` (built by run.mjs) carries: engine ("local" | "builtin"), core, turn(),+// rpc(), learn(), listAll(), waitItems(), persona, marker, ledger, findings,+// threads, logFile, setConfigToml() + restartCore() (local only), cortex+// (local only: the container handle), note().++import fsp from "node:fs/promises";+import path from "node:path";+import { randomUUID, sleep, waitFor, pick, countLogLines } from "./lib.mjs";++const isoDay = (offsetDays, tz) => {+ const d = new Date(Date.now() + offsetDays * 86_400_000);+ return new Intl.DateTimeFormat("en-CA", {+ timeZone: tz,+ year: "numeric",+ month: "2-digit",+ day: "2-digit",+ }).format(d);+};+const lc = (s) => String(s ?? "").toLowerCase();+const containsAny = (text, words) =>+ words.some((w) => lc(text).includes(lc(w)));++// ---------------------------------------------------------------------------+// A. Storing+// ---------------------------------------------------------------------------++const storing = {+ id: "A-storing",+ title:+ "Storing: chats per agent, learning kinds, brain text, a file path, dated facts",+ engines: ["local", "builtin"],+ async run(ctx) {+ const { persona, check } = ctx;++ // A1: chats with two agents land under each agent.+ const t1 = ctx.newThread("A1-orchestrator");+ const r1 = await ctx.turn(+ t1,+ "Note for later: my weekend plan is to repaint the balcony railing.",+ );+ await ctx.setChatAgent("planner");+ const t2 = ctx.newThread("A1-planner");+ const r2 = await ctx.turn(+ t2,+ "Plan three steps for repainting a balcony railing.",+ );+ await ctx.setChatAgent("");+ check("A1-turns-completed", !r1.error && !r2.error, "both turns complete", {+ r1: r1.error,+ r2: r2.error,+ });+ for (const [thread, agent] of [+ [t1, "orchestrator"],+ [t2, "planner"],+ ]) {+ const items = await ctx.waitItems({ thread_id: thread }, 1, 60_000);+ const agents = [...new Set(items.map((h) => h.meta?.agent_id))];+ check(+ `A1-logged-${agent}`,+ items.length > 0,+ `the ${agent} chat is logged to memory`,+ { count: items.length },+ );+ if (items.length)+ check(+ `A1-agent-${agent}`,+ agents.includes(agent),+ `logged turns carry agent_id=${agent}`,+ { agents },+ );+ }++ // A2: each learning kind is stored, and its kind can be read back.+ for (const l of persona.learnings) {+ const id = await ctx.learn(l.text, l.kind);+ const got = await ctx.rpc("openhuman.memory_items_get", { ids: [id] });+ const hit = got?.items?.[0];+ check(+ `A2-learning-${l.kind}-stored`,+ !!hit,+ "the learning reads back by id",+ { id },+ );+ if (!hit) continue;+ const raw = JSON.stringify(hit);+ // The Hit shape has no learning-kind field; look for the kind anywhere.+ check(+ `A2-learning-${l.kind}-type-kept`,+ lc(raw).includes(`"${l.kind}"`),+ `the learning's kind (${l.kind}) is visible on the item`,+ hit,+ "medium",+ "READ",+ );+ }++ // A3: a brain text document.+ const doc = await ctx.rpc("openhuman.memory_brain_ingest", {+ text: persona.brain_doc.text,+ title: persona.brain_doc.title,+ });+ ctx.ledger.add(doc?.id);+ check("A3-brain-ingest", !!doc?.id, "a brain text document is stored", doc);++ // A4: a file whose path holds a username: only the basename may reach the engine.+ const file = path.join(ctx.fixtureCopy, persona.path_file.relative);+ const fdoc = await ctx.tryRpc("openhuman.memory_brain_ingest", {+ path: file,+ });+ if (!fdoc.ok) {+ check("A4-file-ingest", false, "a file by path is stored", fdoc.error);+ } else {+ ctx.ledger.add(fdoc.value?.id);+ const got = await ctx.rpc("openhuman.memory_items_get", {+ ids: [fdoc.value.id],+ });+ const meta = got?.items?.[0]?.meta ?? {};+ const leaked = JSON.stringify(meta).includes(persona.path_file.username);+ check(+ "A4-basename-only",+ !leaked,+ `no directory (and no username "${persona.path_file.username}") in the stored path`,+ { file_path: meta.file_path, folder: meta.folder },+ "high",+ );+ }++ // A5: dated facts (stored with the real dates they describe; C checks recall).+ ctx.dated = [];+ for (const [offset, d] of [+ [-1, persona.dated[0]],+ [-5, persona.dated[1]],+ ]) {+ const day = isoDay(offset, persona.time_zone);+ const id = await ctx.learn(d.turn, "fact", {+ observed_at: `${day}T10:00:00Z`,+ });+ ctx.dated.push({ day, id, text: d.turn });+ }++ // A6: a workflow that writes memory.+ ctx.note(+ "A6-workflow-memory",+ "not automated: creating and running a flow over RPC is out of this script's scope; checked by hand",+ );+ },+};++// ---------------------------------------------------------------------------+// B. Recall+// ---------------------------------------------------------------------------++const recall = {+ id: "B-recall",+ title:+ "Recall: cross-thread, negative control, a planted learning, brain citations, the pre-turn pack",+ engines: ["local", "builtin"],+ async run(ctx) {+ const { persona, check } = ctx;+ const quality = ctx.recallQualityChecked;++ // B1: told in one thread, asked in another.+ const tA = ctx.newThread("B1-tell");+ await ctx.turn(tA, persona.cross_thread.store);+ await ctx.waitItems({ thread_id: tA }, 1, 60_000);+ await sleep(ctx.settleMs);+ const tB = ctx.newThread("B1-ask");+ const b1 = await ctx.turn(tB, persona.cross_thread.probe);+ if (quality)+ check(+ "B1-cross-thread",+ containsAny(b1.reply, persona.cross_thread.expect_any),+ "a fact told in another thread is recalled",+ b1.reply ?? b1.error,+ );++ // B2: nothing to recall, nothing invented.+ const b2 = await ctx.turn(+ ctx.newThread("B2-negative"),+ persona.negative_control.probe,+ );+ const admits =+ /(don.?t|do not|no) (know|have|record|information)|not (sure|aware)|haven.?t (told|mentioned)|no (record|memory|mention)/i.test(+ b2.reply ?? "",+ );+ check(+ "B2-no-invention",+ admits,+ "admits it does not know the tortoise's name",+ b2.reply ?? b2.error,+ "high",+ "INFERRED",+ );++ // B3: a planted learning changes behaviour.+ await ctx.learn(persona.planted.text, "preference");+ await sleep(ctx.settleMs);+ const b3 = await ctx.turn(+ ctx.newThread("B3-planted"),+ persona.planted.probe,+ );+ const reply = b3.reply ?? "";+ const suggests =+ /peanut/i.test(reply) &&+ !/(no|without|avoid|skip|free of|allerg)[^.]{0,40}peanut|peanut[^.]{0,25}(free|allerg)/i.test(+ reply,+ );+ if (quality)+ check(+ "B3-planted-learning",+ !suggests,+ "no peanut dish is suggested",+ reply || b3.error,+ "high",+ "INFERRED",+ );++ // B4: brain retrieval with citations.+ const rec = await ctx.tryRpc("openhuman.memory_recall", {+ question: persona.brain_doc.probe,+ });+ if (!rec.ok)+ check("B4-recall-rpc", false, "memory_recall answers", rec.error);+ else {+ const cites = rec.value?.citations ?? [];+ check(+ "B4-citations",+ cites.length > 0,+ "the answer cites stored items",+ rec.value,+ );+ if (quality)+ check(+ "B4-brain-answer",+ containsAny(rec.value?.answer, persona.brain_doc.expect_any),+ "the brain document's figure is in the answer",+ rec.value?.answer,+ );+ }++ // B5: the pre-turn pack at the default wait, then a larger one.+ const policy = await ctx.rpc("openhuman.memory_policy_get", {});+ const defaultWait = pick(policy, "recall.pre_turn_timeout_ms");+ const probes = [+ "What do I usually want in meeting summaries?",+ "Who is my manager?",+ "Where does my sister live?",+ ];+ const before = await countLogLines(ctx.logFile, /pre_turn timed out/);+ const tDef = ctx.newThread("B5-default");+ for (const p of probes) await ctx.turn(tDef, p);+ const atDefault =+ (await countLogLines(ctx.logFile, /pre_turn timed out/)) - before;+ await ctx.rpc("openhuman.memory_policy_set", { pre_turn_timeout_ms: 6000 });+ const tBig = ctx.newThread("B5-6000ms");+ for (const p of probes) await ctx.turn(tBig, p);+ const atLarge =+ (await countLogLines(ctx.logFile, /pre_turn timed out/)) -+ before -+ atDefault;+ await ctx.rpc("openhuman.memory_policy_set", {+ pre_turn_timeout_ms: defaultWait ?? 1500,+ });+ ctx.results.pre_turn = {+ default_ms: defaultWait,+ timed_out_at_default: atDefault,+ timed_out_at_6000: atLarge,+ turns_each: probes.length,+ };+ check(+ "B5-pre-turn-default",+ atDefault === 0,+ `no pre-turn pack times out at the default wait (${defaultWait} ms)`,+ `${atDefault}/${probes.length} timed out at the default, ${atLarge}/${probes.length} at 6000 ms`,+ atDefault ? "high" : "low",+ );+ },+};++// ---------------------------------------------------------------------------+// C. Dates and time zone+// ---------------------------------------------------------------------------++const dates = {+ id: "C-dates",+ title:+ "Dates and time zone: user time zone, 'yesterday', a named date, reply language",+ engines: ["local", "builtin"],+ async run(ctx) {+ const { persona, check } = ctx;+ await ctx.rpc("openhuman.config_update_user_timezone", {+ timezone: persona.time_zone,+ });+ const tz = await ctx.rpc("openhuman.config_get_user_timezone", {});+ check(+ "C1-timezone",+ tz?.effective === persona.time_zone || tz?.timezone === persona.time_zone,+ `the time zone reads back as ${persona.time_zone}`,+ tz,+ );++ if (!ctx.dated?.length) {+ ctx.note("C2-skipped", "dated facts missing (A did not run); stored now");+ ctx.dated = [];+ for (const [offset, d] of [+ [-1, persona.dated[0]],+ [-5, persona.dated[1]],+ ]) {+ const day = isoDay(offset, persona.time_zone);+ ctx.dated.push({+ day,+ id: await ctx.learn(d.turn, "fact", {+ observed_at: `${day}T10:00:00Z`,+ }),+ text: d.turn,+ });+ }+ }+ await sleep(ctx.settleMs);+ if (ctx.recallQualityChecked) {+ const y = await ctx.turn(+ ctx.newThread("C2-yesterday"),+ "What did I do yesterday?",+ );+ check(+ "C2-yesterday",+ containsAny(y.reply, ["vendor review", "northwind"]),+ "'yesterday' finds yesterday's fact",+ y.reply ?? y.error,+ "medium",+ "INFERRED",+ );+ const day = ctx.dated[1].day;+ const named = await ctx.turn(+ ctx.newThread("C3-named-date"),+ `What did I do on ${day}?`,+ );+ check(+ "C3-named-date",+ containsAny(named.reply, ["dentist", "library"]),+ `a named date (${day}) finds that day's fact`,+ named.reply ?? named.error,+ "medium",+ "INFERRED",+ );+ }++ // C4: the reply follows the user's language.+ const es = await ctx.turn(+ ctx.newThread("C4-language"),+ "¿Cuál es la política de hoteles de Northwind en Berlín? Responde brevemente.",+ );+ const spanish =+ /\b(el|la|los|las|por|noche|hotel|euros?|de)\b/i.test(es.reply ?? "") &&+ /\b(noche|por|límite|tope|máximo|euros)\b/i.test(es.reply ?? "");+ check(+ "C4-reply-language",+ spanish,+ "a Spanish question gets a Spanish reply",+ es.reply ?? es.error,+ "medium",+ "INFERRED",+ );+ },+};++// ---------------------------------------------------------------------------+// F. Labels and the observed actor (local reads the engine's own records)+// ---------------------------------------------------------------------------++const labels = {+ id: "F-labels",+ title:+ "Labels and actor: agent/thread on items, phone numbers plain, observed_actor only when on",+ engines: ["local"],+ async run(ctx) {+ const { persona, check } = ctx;+ // Phone numbers are stored as written (user decision 13:50).+ const id = await ctx.learn(+ `Priya's phone number is ${persona.contacts[0].phone}.`,+ "fact",+ );+ const got = await ctx.rpc("openhuman.memory_items_get", { ids: [id] });+ check(+ "F1-phone-plain",+ (got?.items?.[0]?.text ?? "").includes(persona.contacts[0].phone),+ "a phone number is stored in plain text",+ got?.items?.[0]?.text,+ );++ // observed_actor OFF (the default): logged turns carry no attribution.+ const tOff = ctx.newThread("F2-actor-off");+ await ctx.turn(+ tOff,+ "Remember that the balcony paint colour is sage green.",+ );+ const off = await ctx.waitItems({ thread_id: tOff }, 2, 60_000);+ check(+ "F2-thread-label",+ off.every((h) => h.meta?.thread_id === tOff),+ "every logged turn carries its thread_id",+ off.map((h) => h.meta?.thread_id),+ );+ check(+ "F2-agent-label",+ off.every((h) => !!h.meta?.agent_id),+ "every logged turn carries an agent_id",+ off.map((h) => h.meta?.agent_id),+ );+ check(+ "F3-actor-off",+ off.every((h) => !h.meta?.observed_actor),+ "with observed_actor off, no item carries an observed_actor",+ off.map((h) => h.meta?.observed_actor ?? null),+ );++ // observed_actor ON: assistant turns carry the agent as actor.+ await ctx.setConfigToml("memory", { observed_actor: true });+ await ctx.restartCore();+ const tOn = ctx.newThread("F4-actor-on");+ await ctx.turn(tOn, "Remember that the railing primer is grey.");+ const on = await ctx.waitItems({ thread_id: tOn }, 2, 60_000);+ const withActor = on.filter((h) => h.meta?.observed_actor);+ check(+ "F4-actor-on",+ withActor.length > 0,+ "with observed_actor on, assistant turns carry an observed_actor",+ on.map((h) => ({+ text: h.text?.slice(0, 40),+ actor: h.meta?.observed_actor ?? null,+ })),+ );+ ctx.results.observed_actor_samples = withActor+ .slice(0, 3)+ .map((h) => h.meta.observed_actor);+ await ctx.setConfigToml("memory", { observed_actor: false });+ await ctx.restartCore();+ },+};++// ---------------------------------------------------------------------------+// G. Per-turn brain source cap+// ---------------------------------------------------------------------------++const sourceCap = {+ id: "G-source-cap",+ title:+ "Per-turn cap: more than four brain sources, at most four read, the named one included",+ engines: ["local", "builtin"],+ async run(ctx) {+ const { check } = ctx;+ const sources = ["notion", "gmail", "github", "files", "web"];+ for (const s of sources) {+ const r = await ctx.tryRpc("openhuman.memory_brain_ingest", {+ text: `Kestrel project note from ${s}: the launch checklist lives in ${s}.`,+ title: `Kestrel ${s} note`,+ source: s,+ });+ if (r.ok) ctx.ledger.add(r.value?.id);+ else+ ctx.note(+ `G-ingest-${s}`,+ `brain_ingest with source=${s} refused: ${JSON.stringify(r.error).slice(0, 200)}`,+ );+ }+ await sleep(ctx.settleMs);+ const pv = await ctx.tryRpc("openhuman.memory_pack_preview", {+ query: "Where is the Kestrel launch checklist in github?",+ });+ if (!pv.ok)+ return check(+ "G-pack-preview",+ false,+ "memory_pack_preview answers",+ pv.error,+ );+ const pack = pv.value?.pack ?? {};+ const refs = JSON.stringify(pack.refs ?? pack.sections ?? []);+ const read = sources.filter(+ (s) => lc(refs).includes(`source:${s}`) || lc(refs).includes(`"${s}"`),+ );+ ctx.results.source_cap = {+ sources_seen_in_pack: read,+ sections: (pack.sections ?? []).map((s) => s.title ?? s.name ?? s),+ };+ check(+ "G1-at-most-four",+ read.length <= 4,+ "at most four brain sources are read in one turn",+ read,+ );+ check(+ "G2-named-included",+ read.includes("github"),+ "the source named in the question is read",+ read,+ );+ const team = JSON.stringify(pack.sections ?? pack.markdown ?? "");+ check(+ "G3-no-team",+ !/team/i.test(team),+ "no Team section in the pack",+ pack.sections ?? null,+ "low",+ );+ },+};++// ---------------------------------------------------------------------------+// H. Forget+// ---------------------------------------------------------------------------++const forget = {+ id: "H-forget",+ title: "Forget: gone from list and recall; a forget of nothing says so",+ engines: ["local", "builtin"],+ async run(ctx) {+ const { check } = ctx;+ const id = await ctx.learn(+ "Jordan's locker number at the climbing gym is 4417.",+ "fact",+ );+ const f1 = await ctx.rpc("openhuman.memory_forget", { ids: [id] });+ check(+ "H1-forgotten-count",+ (f1?.forgotten ?? 0) >= 1,+ "forget reports the item removed",+ f1,+ );+ const got = await ctx.rpc("openhuman.memory_items_get", { ids: [id] });+ check(+ "H2-gone-from-get",+ !(got?.items ?? []).length,+ "the item no longer reads back",+ got,+ );+ const listed = await ctx.listAll({ tags_any: [ctx.marker] });+ check(+ "H3-gone-from-list",+ !listed.some((h) => h.id === id),+ "the item is gone from the list",+ { id },+ );+ if (ctx.recallQualityChecked) {+ const rec = await ctx.tryRpc("openhuman.memory_recall", {+ question: "What is my climbing gym locker number?",+ });+ check(+ "H4-gone-from-recall",+ !(rec.value?.answer ?? "").includes("4417"),+ "recall no longer returns it",+ rec.value ?? rec.error,+ );+ }+ const f2 = await ctx.tryRpc("openhuman.memory_forget", { ids: [id] });+ check(+ "H5-zero-forget-reported",+ f2.ok && f2.value?.forgotten === 0,+ "forgetting an already-forgotten id reports forgotten: 0 (not an error, not a false count)",+ f2.ok ? f2.value : f2.error,+ "low",+ );+ },+};++// ---------------------------------------------------------------------------+// I. QA re-tests+// ---------------------------------------------------------------------------++const qa = {+ id: "I-qa",+ title:+ "QA re-tests: belief builds, backfill state, list refresh, silent degradation",+ engines: ["local", "builtin"],+ async run(ctx) {+ const { check } = ctx;+ // I1: a belief build stores something (manual run bypasses the gate).+ const jobs = await ctx.tryRpc("openhuman.memory_jobs_run", {}, 300_000);+ ctx.results.jobs_run = jobs.ok ? jobs.value : { error: jobs.error };+ if (!jobs.ok)+ check("I1-jobs-run", false, "memory_jobs_run answers", jobs.error);+ else+ ctx.note(+ "I1-jobs-run",+ `memory_jobs_run: ${JSON.stringify(jobs.value).slice(0, 400)}`,+ );++ // I2: past-conversations backfill state.+ const bf = await ctx.tryRpc(+ "openhuman.memory_conversations_backfill_status",+ {},+ );+ ctx.results.backfill = bf.ok ? bf.value : { error: bf.error };+ check(+ "I2-backfill-status",+ bf.ok,+ "the backfill status answers",+ bf.ok ? bf.value : bf.error,+ "low",+ );++ // I3: a new learning shows in the list at once (RPC level).+ const id = await ctx.learn(+ "Jordan's favourite tea is genmaicha.",+ "preference",+ );+ const listed = await ctx.listAll({+ kinds: ["learning"],+ tags_any: [ctx.marker],+ });+ check(+ "I3-list-refresh",+ listed.some((h) => h.id === id),+ "a learning shows in the learnings list straight after it is stored",+ { id, listed: listed.length },+ );++ // I4: silent degradation: the engine goes away mid-session (local only).+ if (ctx.engine === "local" && ctx.cortex) {+ await ctx.cortex.pause();+ const rec = await ctx.tryRpc(+ "openhuman.memory_recall",+ { question: "What tea do I like?" },+ 60_000,+ );+ const learn = await ctx.tryRpc(+ "openhuman.memory_learn",+ {+ text: "unreachable engine probe",+ kind: "other",+ meta: ctx.markMeta(),+ },+ 60_000,+ );+ const turn = await ctx.turn(+ ctx.newThread("I4-engine-down"),+ "What tea do I like?",+ );+ await ctx.cortex.resume();+ if (learn.ok) ctx.ledger.add(learn.value?.id);+ ctx.results.engine_down = {+ recall: rec.ok+ ? { answer: rec.value?.answer?.slice(0, 120) }+ : rec.error,+ learn: learn.ok ? "accepted" : learn.error,+ turn: turn.error ?? "completed",+ };+ check(+ "I4-recall-surfaces-error",+ !rec.ok,+ "recall with the engine down returns an error, not an empty answer",+ ctx.results.engine_down.recall,+ );+ check(+ "I4-learn-surfaces-error",+ !learn.ok,+ "a store with the engine down returns an error",+ ctx.results.engine_down.learn,+ );+ const warned = await countLogLines(+ ctx.logFile,+ /\[memory[^\]]*\].*(unavailable|degraded|connect|refused|error)/i,+ );+ ctx.note(+ "I4-turn-with-engine-down",+ `the chat turn ${turn.error ? `failed: ${turn.error}` : "completed"}; memory warnings in core.log so far: ${warned}`,+ );+ }+ },+};++// ---------------------------------------------------------------------------+// J. Hosted store speed (no real import)+// ---------------------------------------------------------------------------++const storeSpeed = {+ id: "J-store-speed",+ title:+ "Store speed on the hosted path: a synthetic batch, timed (no real import)",+ engines: ["builtin"],+ async run(ctx) {+ const N = 40;+ const batches = [];+ const errors = [];+ for (let b = 0; b < N / 10; b += 1) {+ const started = Date.now();+ for (let i = 0; i < 10; i += 1) {+ const r = await ctx.tryRpc("openhuman.memory_learn", {+ text: `memscen synthetic item ${b * 10 + i}: a short fictional note about the Kestrel project.`,+ kind: "other",+ meta: ctx.markMeta(),+ });+ if (r.ok) ctx.ledger.add(r.value?.id);+ else errors.push(JSON.stringify(r.error).slice(0, 200));+ }+ batches.push(Date.now() - started);+ }+ ctx.results.store_speed = {+ path: "memory_learn x10 per batch (no RPC exposes the import's store_many; this times the same hosted engine one item at a time)",+ batch_ms: batches,+ errors,+ unavailable_or_429: errors.filter((e) => /UNAVAILABLE|429|rate/i.test(e))+ .length,+ };+ ctx.check(+ "J1-no-store-errors",+ errors.length === 0,+ "a synthetic batch stores without errors",+ errors,+ "medium",+ );+ },+};++export const SCENARIOS = [+ storing,+ recall,+ dates,+ labels,+ sourceCap,+ forget,+ qa,+ storeSpeed,+];++/** Scenarios that run only on the local engine and are defined in their own modules. */+export function registerLocalOnly(...scenarios) {+ for (const s of scenarios)+ if (s && !SCENARIOS.some((x) => x.id === s.id)) SCENARIOS.push(s);+}++export { isoDay, containsAny, randomUUID, waitFor, fsp };