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
Merge origin/main into remove-composio-memory-sync
Steven Enamakel06a49e4ce163
diff --cc crates/openhuman-app/Cargo.lockindex e37ccd6aae,e3a02ca2c6..e55dbd3b94--- a/crates/openhuman-app/Cargo.lock+++ b/crates/openhuman-app/Cargo.lock@@@ -8125,7 -8127,7 +8125,7 @@@ dependencies =[[package]]name = "tinymemory-api"--version = "1.23.10"++version = "1.24.0"dependencies = ["async-trait","chrono",@@@ -8138,7 -8140,7 +8138,7 @@@[[package]]name = "tinymemory-integrations"--version = "1.23.10"++version = "1.24.0"dependencies = ["async-trait","calamine",@@@ -8165,7 -8167,7 +8165,7 @@@[[package]]name = "tinymemory-tools"--version = "1.23.10"++version = "1.24.0"dependencies = ["chrono","futures",diff --cc crates/openhuman-core/src/memory/files.rsindex 0000000000,02301572ae..62ee38845bmode 000000,100644..100644--- a/crates/openhuman-core/src/memory/files.rs+++ b/crates/openhuman-core/src/memory/files.rs@@@ -1,0 -1,94 +1,93 @@@+ //! Owner-only writes of the local memory state files.+ //!+ //! The files under `<workspace>/memory/` (the job queue, channel threads,-//! source sync state, connection roots, connector item versions, the layout-//! migration state, the local install identity) hold ids and source++//! source sync state, the layout migration state, the local install identity) hold ids and source+ //! settings that are the person's own. `std::fs::write` creates them with+ //! the process umask (0644 under the usual 022), readable by every local+ //! account; here, on unix, a file is created (and kept) 0600 and its+ //! directory 0700, as the config and keyring files already are. Other+ //! platforms keep their default ACLs.++ use std::fs::File;+ use std::io::Write;+ use std::path::Path;++ /// Owner read/write only.+ #[cfg(unix)]+ pub const FILE_MODE: u32 = 0o600;++ /// Owner read/write/search only.+ #[cfg(unix)]+ pub const DIR_MODE: u32 = 0o700;++ /// Creates `dir` and any missing parent, each new one 0700 on unix, and+ /// narrows `dir` itself to 0700 when it already existed.+ ///+ /// # Errors+ ///+ /// When a directory cannot be created or its mode set.+ pub fn create_private_dir_all(dir: &Path) -> std::io::Result<()> {+ #[cfg(unix)]+ {+ use std::os::unix::fs::{DirBuilderExt, PermissionsExt};+ std::fs::DirBuilder::new()+ .recursive(true)+ .mode(DIR_MODE)+ .create(dir)?;+ let mode = std::fs::metadata(dir)?.permissions().mode() & 0o777;+ if mode != DIR_MODE {+ tracing::debug!(+ dir = %dir.display(),+ from = format!("{mode:o}"),+ "[memory:files] narrowing a state directory to 0700"+ );+ std::fs::set_permissions(dir, std::fs::Permissions::from_mode(DIR_MODE))?;+ }+ Ok(())+ }+ #[cfg(not(unix))]+ {+ std::fs::create_dir_all(dir)+ }+ }++ /// Creates (or truncates) `path` for writing, 0600 on unix whether it is+ /// new or already existed with a wider mode.+ ///+ /// # Errors+ ///+ /// When the file cannot be opened or its mode set.+ pub fn create_private(path: &Path) -> std::io::Result<File> {+ let mut options = std::fs::OpenOptions::new();+ options.write(true).create(true).truncate(true);+ #[cfg(unix)]+ {+ use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};+ options.mode(FILE_MODE);+ let file = options.open(path)?;+ // `mode` applies only to a file this call creates.+ file.set_permissions(std::fs::Permissions::from_mode(FILE_MODE))?;+ Ok(file)+ }+ #[cfg(not(unix))]+ {+ options.open(path)+ }+ }++ /// Writes `bytes` to `path` owner-only ([`create_private`]), creating its+ /// directory owner-only ([`create_private_dir_all`]).+ ///+ /// # Errors+ ///+ /// When the directory or file cannot be created or written.+ pub fn write_private(path: &Path, bytes: &[u8]) -> std::io::Result<()> {+ if let Some(dir) = path.parent() {+ create_private_dir_all(dir)?;+ }+ create_private(path)?.write_all(bytes)+ }++ #[cfg(test)]+ #[path = "files_tests.rs"]+ mod tests;diff --cc crates/openhuman-core/src/memory/files_tests.rsindex 0000000000,3e598f3328..b23483d81emode 000000,100644..100644--- a/crates/openhuman-core/src/memory/files_tests.rs+++ b/crates/openhuman-core/src/memory/files_tests.rs@@@ -1,0 -1,88 +1,87 @@@+ use super::*;++ #[cfg(unix)]+ use std::os::unix::fs::PermissionsExt;++ #[cfg(unix)]+ fn mode(path: &Path) -> u32 {+ std::fs::metadata(path).unwrap().permissions().mode() & 0o777+ }++ #[test]+ fn write_private_writes_the_bytes() {+ let tmp = tempfile::tempdir().unwrap();+ let file = tmp.path().join("memory").join("state.json");+ write_private(&file, b"{\"a\":1}").unwrap();+ write_private(&file, b"{}").unwrap();+ assert_eq!(+ std::fs::read(&file).unwrap(),+ b"{}",+ "truncated, not appended"+ );+ }++ #[cfg(unix)]+ #[test]+ fn a_new_file_is_0600_in_a_0700_directory() {+ let tmp = tempfile::tempdir().unwrap();+ let dir = tmp.path().join("memory").join("nested");+ let file = dir.join("state.json");+ write_private(&file, b"{}").unwrap();+ assert_eq!(mode(&file), 0o600);+ assert_eq!(mode(&dir), 0o700);+ assert_eq!(mode(&tmp.path().join("memory")), 0o700);+ }++ #[cfg(unix)]+ #[test]+ fn an_existing_world_readable_file_and_directory_are_narrowed() {+ let tmp = tempfile::tempdir().unwrap();+ let dir = tmp.path().join("memory");+ std::fs::create_dir_all(&dir).unwrap();+ std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o755)).unwrap();+ let file = dir.join("jobs.json");+ std::fs::write(&file, b"{}").unwrap();+ std::fs::set_permissions(&file, std::fs::Permissions::from_mode(0o644)).unwrap();++ write_private(&file, b"{\"pending\":[]}").unwrap();+ assert_eq!(mode(&file), 0o600);+ assert_eq!(mode(&dir), 0o700);+ }++ #[cfg(unix)]+ #[tokio::test]+ async fn every_memory_state_file_is_owner_only() {+ use tinymemory_api::{ConsolidateRequest, ItemKind, Namespace, Reach};++ use crate::memory::lifecycle::jobs;+ use crate::memory::test_fixtures::config_in;+ use tinymemory_tools::BackgroundJob;++ let tmp = tempfile::tempdir().unwrap();+ let config = config_in(&tmp);+ let workspace = config.workspace_dir.clone();++ crate::memory::channels::record(&workspace, "telegram", "thread-1");+ crate::memory::sources::state::update(&workspace, "src-1", |_| {});- crate::memory::sources::roots::record(&workspace, "composio:gmail", "user:x").unwrap();+ crate::memory::layout_migration::state::save(&workspace, &Default::default()).unwrap();+ jobs::enqueue(+ &config,+ &Namespace::ROOT,+ vec![BackgroundJob::BuildBeliefs {+ request: ConsolidateRequest::new(Reach::exact(Namespace::agent("a")))+ .kinds([ItemKind::Conversation]),+ }],+ )+ .await;++ let dir = workspace.join("memory");+ assert_eq!(mode(&dir), 0o700);+ let mut seen = 0;+ for entry in std::fs::read_dir(&dir).unwrap() {+ let path = entry.unwrap().path();+ assert_eq!(mode(&path), 0o600, "{}", path.display());+ seen += 1;+ }- assert!(seen >= 5, "every state file was written: {seen}");++ assert!(seen >= 4, "every state file was written: {seen}");+ }diff --cc scripts/memory-scenarios/README.mdindex 0000000000,5abbf77ce8..736c0e2ee2mode 000000,100644..100644--- a/scripts/memory-scenarios/README.md+++ b/scripts/memory-scenarios/README.md@@@ -1,0 -1,154 +1,152 @@@+ # 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)+ 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++Requires a core build (`cargo build -p openhuman-cli --bin openhuman-core`),++Docker, and for the local+ engine's embeddings a running Ollama with `nomic-embed-text` (and `llama3.2:3b`+ for CortexDB's extraction and answer lanes; both pulled when missing).++ ## The account credential: a file, passed through the environment only++ Chat runs on the account's managed route on both engines, and the builtin engine+ stores memory on the account, so the run needs a credential:++ | file (chmod 600) | what | reaches the core as |+ | ------------------------------------------------ | ---------------------------------------------------------------------------------------------- | --------------------------------- |+ | `~/.memscen-session` (or `MEMSCEN_SESSION_FILE`) | the app's session JWT, preferred for builtin | `OPENHUMAN_BACKEND_SESSION_TOKEN` |+ | `~/.memscen-key` (or `MEMSCEN_KEY_FILE`) | a TinyHumans API key (`tiny_…`); the local engine's chat, and builtin when there is no session | `OPENHUMAN_BACKEND_API_KEY` |++ The script reads the file when it spawns the core and hands the value over in+ the core's environment only; the core seeds it at boot+ (`security/credentials/ops/boot_env.rs`). It is never an RPC argument, never+ printed and never written to the run directory: `core.log`, `rpc.jsonl` and+ every error text are scrubbed of the value itself and of anything `tiny_…` or+ JWT-shaped (`eyJ…`). A core spawned for an engine that should not have a+ credential gets neither variable, even if your shell exports one. Revoke the+ session on the backend when you are done. An API key needs the **`memory`**+ scope for builtin; without it every memory call answers 403.++ ## 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) with its+ own compose project `memscen-<run>`, its own volume and 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, or on Ctrl-C (`--keep` keeps the+ volume). Its embeddings are the local Ollama's `nomic-embed-text` (768 dims,+ through Ollama's native API at the bare base URL: under `/v1` CortexDB's+ `ollama:` provider 404s and every store waits out a 30 s index timeout). When+ Ollama is unreachable it falls back to tinymemory's deterministic mock+ inference, and the report says the recall-quality checks were skipped.++ - Chat runs on the account's managed route through the API key; **memory stays+ on the container**. The run aborts unless `memory_engine_get` reports+ `cortexdb` at the run's own endpoint, before and after setup. The scheduler+ gate is off on this core too (written to the active config and read back),+ so no background job runs while it holds the key. If the managed route+ cannot run, chat falls back to the local Ollama and the checks that depend+ on reply quality are recorded **INCONCLUSIVE**, not failed.+ - The core talks to CortexDB through a logging pass-through, and every request+ body lands in `local/cortex-wire.jsonl` (scrubbed). Attribution+ (`observed_actor`, `subject`) is written on the wire and not returned on+ read-back, so those checks read the wire.+ - **E (the move into layout v3) runs on a fresh core that never saw the key**:+ a user-started move is gated on background work, which the key-holding core+ keeps off, and this core may run background work without any way to reach+ the account.++ **builtin**: **your real account**, on its managed route. Read this before+ running it.++ - **Nothing of the account's own is moved, erased, imported or consolidated.**+ Three guards; any failure aborts the builtin run before a scenario starts:+ 1. the scheduler gate is pre-written **off** in every config the core may+ treat as active (the root, the pre-login `users/local/`, and for a session+ the account's own `users/<subject>/`), and read back from the config the+ core actually activated, so no background job (the layout migration's+ tick, import resume, belief builds) runs on its own;+ 2. the active 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, disconnect-with-clear and belief-build 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; a shared (self-hosted) tree waits for the takeover consent, then moves; 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; on the wire, `observed_actor`/`subject` on assistant turns only with `[memory] observed_actor = true`, none with it off |+ | 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`, local only), 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+ local/cortex-wire.jsonl every request the core sent CortexDB (scrubbed)+ ```++ 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 --cc scripts/memory-scenarios/run.mjsindex 0000000000,a83e608f33..fbcb2cf49bmode 000000,100644..100644--- a/scripts/memory-scenarios/run.mjs+++ b/scripts/memory-scenarios/run.mjs@@@ -1,0 -1,872 +1,848 @@@+ #!/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,+ startCortexWireLog,+ OLLAMA_URL,+ OLLAMA_CHAT_MODEL,+ activeWorkspace,+ placeMigrationGuard,+ verifyBuiltinUntouched,+ forgetLedger,+ builtinCredential,+ } 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);++registerLocalOnly(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(".");+ }++ /** 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+ // ---------------------------------------------------------------------------++ /** Teardowns to run if the process is interrupted (a container must not outlive the run). */+ const CLEANUPS = new Set();+ for (const sig of ["SIGINT", "SIGTERM"])+ process.once(sig, async () => {+ for (const fn of CLEANUPS) await fn().catch(() => {});+ process.exit(130);+ });++ async function runEngine(engine, { opts, runDir, runId, findings, results }) {+ const dir = path.join(runDir, engine);+ let 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 wire = null;+ let guardPlaced = false;+ let builtinSubject = null;+ let core = null;+ let events = null;+ const ledger = new Ledger();+ const threads = [];++ // --- 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);+ // The core talks to CortexDB through a logging pass-through, so checks+ // can read what was sent (attribution is wire-only).+ wire = await startCortexWireLog({+ target: cortex.endpoint,+ logFile: path.join(dir, "cortex-wire.jsonl"),+ secrets,+ });+ const stopCortex = () => cortex.stop();+ CLEANUPS.add(stopCortex);+ engineResults.inference = cortex.inference;- composio = await startMockComposio();+ // Chat runs on the account's managed route (user decision); memory stays on+ // the container. The key reaches the core only through the environment.+ try {+ const cred = await builtinCredential({ only: "key" });+ secrets.push(cred.secret);+ Object.assign(extraEnv, cred.env);+ } catch (e) {+ log(+ `local : no account key (${e.message}); chat will fall back to Ollama`,+ );+ }- 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([+ "[scheduler_gate]",+ 'mode = "off"',+ "",- "[composio]",- 'mode = "direct"',- 'api_key = "ck_memscen_mock"',- 'entity_id = "default"',- "",+ ]),+ );+ } else {+ const cred = await builtinCredential();+ secrets.push(cred.secret);+ Object.assign(extraEnv, cred.env);+ // Guard 0: the scheduler gate is off before the core first boots, so no+ // background job (the migration's tick, import resume, belief builds)+ // runs on its own. An API key is seeded as a plain profile write with no+ // user-dir activation (boot_env.rs), so the root config is the active+ // one. Verified after boot; the run aborts if it is not in effect.+ // Guard 0 goes in every config the core may treat as active: the root,+ // the pre-login user dir (a key activates none) and, for a session, the+ // account's own user dir (`users/<subject>`). Verified after boot.+ const gated = BASE_CONFIG(["[scheduler_gate]", 'mode = "off"', ""]);+ await fsp.writeFile(path.join(oh, "config.toml"), gated);+ for (const id of ["local", ...(cred.subject ? [cred.subject] : [])]) {+ await fsp.mkdir(path.join(oh, "users", id), { recursive: true });+ await fsp.writeFile(path.join(oh, "users", id, "config.toml"), gated);+ }+ builtinSubject = cred.subject;+ engineResults.credential = cred.kind;+ }++ 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;+ };++ /**- * Set up a local-engine core: a local session, the mock Composio, memory on++ * Set up a local-engine core: a local session, memory on+ * this run's container (abort otherwise) and a chat route. With the account+ * key (`withKey`), the scheduler gate is forced off and chat is managed.+ * Without it (a fresh HOME that never saw the key), the gate keeps its+ * default and chat runs on the local Ollama.+ */+ const setupLocal = async ({ withKey }) => {+ // A local session: E needs a per-user root for layout v3.+ 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" },+ });- // The session activates a user dir whose config wins: put the mock- // Composio and the scheduler-gate guard there, restart, read back.++ // The session activates a user dir whose config wins: put the++ // scheduler-gate guard there, restart, read back.+ // With the account key present, no background job may run on its own.+ const { config_path: cfgPath } = await core.rpc("openhuman.config_get", {});- await editToml(cfgPath, "composio", {- mode: "direct",- api_key: "ck_memscen_mock",- entity_id: "default",- });+ if (withKey) await editToml(cfgPath, "scheduler_gate", { mode: "off" });+ await core.stop();+ await startCore();+ const gate = pick(+ await core.rpc("openhuman.config_get", {}),+ "config.scheduler_gate.mode",+ );+ if (withKey && gate !== "off")+ throw new Error(`ABORT local: scheduler gate is "${gate}", not "off"`);++ // Memory stays on this run's CortexDB container; abort otherwise.+ await withRetries(+ async () => {+ await core.rpc("openhuman.memory_engine_set", {+ engine: "cortexdb",+ endpoint: wire.url,+ api_key: cortex.apiKey,+ });+ const got = await core.rpc("openhuman.memory_engine_get", {});+ if (+ got?.engine !== "cortexdb" ||+ got?.status !== "ok" ||+ got?.endpoint !== wire.url+ )+ throw new Error(+ `engine ${got?.engine} ${got?.status} at ${got?.endpoint} ${got?.reason ?? ""}`,+ );+ },+ { attempts: 20, delayMs: 1000, what: "local CortexDB engine" },+ ).catch((e) => {+ throw new Error(+ `ABORT local: memory is not on the local CortexDB (${e.message})`,+ );+ });++ // Chat: the account's managed route (the key is in the env). If it+ // cannot run here, fall back to the local Ollama and mark the checks+ // that depend on reply quality INCONCLUSIVE instead of failed.+ const probe = !withKey+ ? { error: "no account key on this core (by design)" }+ : await sendTurn({+ core,+ events,+ clientId: events.clientId,+ threadId: `thread-${randomUUID()}`,+ message: "Reply with the single word OK.",+ timeoutMs: 120_000,+ });+ if (!probe.error) {+ engineResults.inference.chat_route = "managed (account API key)";+ } else {+ engineResults.inference.chat_route_managed_error = scrub(+ probe.error,+ secrets,+ );+ const inferenceUrl = `${OLLAMA_URL}/v1`;+ await withRetries(+ async () => {+ await core.rpc("openhuman.config_update_model_settings", {+ inference_url: inferenceUrl,+ api_key: "ollama",+ default_model: OLLAMA_CHAT_MODEL,+ });+ const cfg =+ (await core.rpc("openhuman.config_get", {}))?.config ?? {};+ if (+ cfg.inference_url !== inferenceUrl ||+ !(cfg.cloud_providers ?? []).some(+ (x) => x?.endpoint === inferenceUrl,+ )+ )+ throw new Error(+ `BYOK route not active yet (inference_url=${cfg.inference_url ?? "unset"})`,+ );+ },+ { attempts: 10, delayMs: 500, what: "local chat route (Ollama)" },+ );+ engineResults.inference.chat_route = `BYOK ${inferenceUrl} ${OLLAMA_CHAT_MODEL} (fallback)`;+ if (withKey) engineResults.qualityInconclusive = true;+ }+ // The memory engine must still be the local container after all that.+ const final = await core.rpc("openhuman.memory_engine_get", {});+ if (final?.engine !== "cortexdb" || final?.endpoint !== wire.url)+ throw new Error(+ `ABORT local: memory engine moved to ${final?.engine} at ${final?.endpoint}`,+ );+ log(+ `local : memory on ${cortex.endpoint} via ${wire.url}, scheduler gate ${gate}, chat ${engineResults.inference.chat_route}`,+ );+ };++ try {+ const health = await startCore();+ log(`${engine.padEnd(8)}: core ${core.url} pid ${health.pid}`);++ if (engine === "local") {+ await setupLocal({ withKey: true });+ } else {+ // Guard 0 verified: the gate the account's config carries is off.+ // A session activates the account's user dir asynchronously at boot:+ // wait for it, then read the guard back from THAT config.+ let snap = await core.rpc("openhuman.config_get", {});+ if (builtinSubject) {+ const want = path.join("users", builtinSubject, "config.toml");+ snap = await waitFor(+ async () => {+ const s2 = await core.rpc("openhuman.config_get", {});+ return String(s2?.config_path ?? "").endsWith(want) ? s2 : null;+ },+ {+ timeoutMs: 60_000,+ intervalMs: 500,+ what: "the account's user dir active",+ },+ ).catch(() => {+ throw new Error(+ "ABORT builtin: the session did not activate the account's user dir",+ );+ });+ }+ 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"),+ );+ guardPlaced = true;+ 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,+ wire,+ 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,+ });+ },+ /** A check that depends on reply quality: INCONCLUSIVE on a fallback model. */+ qcheck(+ id,+ ok,+ expected,+ actual,+ severity = "medium",+ basis = "INFERRED",+ ) {+ if (engineResults.qualityInconclusive && !ok) {+ sres.checks += 1;+ sres.inconclusive = (sres.inconclusive ?? 0) + 1;+ findings.note({+ engine,+ scenario: scenario.id,+ id: `${id}-INCONCLUSIVE`,+ text: `INCONCLUSIVE on the fallback chat model: expected ${expected}; got ${typeof actual === "string" ? actual.slice(0, 200) : JSON.stringify(actual).slice(0, 200)}`,+ evidence: path.relative(+ runDir,+ path.join(dir, "scenarios", scenario.id),+ ),+ basis,+ });+ return false;+ }+ return ctx.check(id, ok, expected, actual, 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 });+ if (scenario.noAccount && engine === "local") {+ // A core that never saw the account key, so its background work+ // (which a user-started move is gated on) may run without any+ // chance of touching the hosted account.+ events?.close();+ await core.stop();+ delete extraEnv.OPENHUMAN_BACKEND_API_KEY;+ home = path.join(dir, `home-${scenario.id}`);+ await fsp.mkdir(path.join(home, ".openhuman"), { recursive: true });+ await fsp.writeFile(+ path.join(home, ".openhuman", "config.toml"),+ BASE_CONFIG(),+ );+ await startCore();+ await setupLocal({ withKey: false });+ ctx.note(+ "isolated-core",+ `ran on a fresh core without the account key (gate default, chat ${engineResults.inference.chat_route})`,+ );+ }+ 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 = guardPlaced+ ? await verifyBuiltinUntouched(core)+ : {+ ok: true,+ note: "aborted before the migration guard; no scenario ran",+ };+ 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`,++ `core binary not found at ${opts.coreBin}\nbuild it: cargo build -p openhuman-cli --bin openhuman-core`,+ );+ const engines = opts.engine === "both" ? ["local", "builtin"] : [opts.engine];+ if (engines.includes("builtin")) await builtinCredential(); // 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, []);+ 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()+ .then(() => process.exit(0))+ .catch((e) => {+ console.error(`\nfatal: ${scrub(e.stack || e.message, [])}`);+ process.exit(1);+ });diff --cc vendor/tinyconnectorsindex 07bfe93731,381ff1a6fb..d3760911f2--- a/vendor/tinyconnectors+++ b/vendor/tinyconnectors@@@ -1,1 -1,1 +1,1 @@@- Subproject commit 07bfe93731440dc0f2ae069843bc225be2bc3f20-Subproject commit 381ff1a6fb9aff17e030225f625d391d308c44b5++Subproject commit d3760911f2d5c79d595f02567189f986dc477981diff --cc vendor/tinymemoryindex 58ffac5921,588e62f6fe..cb8876d72f--- a/vendor/tinymemory+++ b/vendor/tinymemory@@@ -1,1 -1,1 +1,1 @@@- Subproject commit 58ffac5921430b293a896cb6124e396ced0e1813-Subproject commit 588e62f6fea1f164081c86ad2a18ff88b50c7705++Subproject commit cb8876d72fce5ec77964f98adaed16260efb223e