Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

test: live e2e for the Memorable provider against the real CLI and Postgres

Josh France92c5ef388257
diff --git a/docs/memory-providers.md b/docs/memory-providers.md
index b48dfe66f..e90b9cc0e 100644
--- a/docs/memory-providers.md
+++ b/docs/memory-providers.md
@@ -72,7 +72,11 @@ either direction.
Options: `bin` (default `memorable`; may include arguments, e.g. `node /opt/memorable/cli.js`),
`injectTimeoutMs` (default 15000) and `recordTimeoutMs` (default 120000). The CLI is not bundled:
-install it with `npm i -g memorable-cli`. It sees only an allow-listed environment —
+install it with `npm i -g memorable-cli` (its `qm` backend also needs the `pg` package resolvable
+from QM's working directory). Recording calls the Memorable extraction service, so set both
+`MEMORABLE_API_URL` and `MEMORABLE_API_KEY`; recall is local. Consent is the CLI's own act, per
+scope: nothing is recorded for a scope until `memorable enable --scope <scope-id>` has been run
+with the same `MEMORABLE_BACKEND=qm` and `MEMORABLE_DB_URL`. It sees only an allow-listed environment —
`MEMORABLE_*`, `PATH`, `HOME`, proxy and TLS variables — with `MEMORABLE_BACKEND` defaulting to
`qm` and the database reachable solely as `MEMORABLE_DB_URL`. Routes to this provider accept
`capture: "automatic"` or `"off"`; explicit `remember` writes are facts, not procedures, and are
diff --git a/test/e2e/memorable-provider.e2e.test.ts b/test/e2e/memorable-provider.e2e.test.ts
new file mode 100644
index 000000000..74a472195
--- /dev/null
+++ b/test/e2e/memorable-provider.e2e.test.ts
@@ -0,0 +1,147 @@
+import "../support/auto-fake-sprites.ts";
+
+import { describe, it, before, after } from "node:test";
+import assert from "node:assert/strict";
+import { execFileSync } from "node:child_process";
+import type { Server } from "node:http";
+import type { AddressInfo } from "node:net";
+import { mkdtempSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import pg from "pg";
+import { buildApp } from "../../src/wiring.ts";
+import { createInsecureTestServer } from "../../src/api/server.ts";
+import { parseMemoryProviderConfig } from "../../src/memory/provider-config.ts";
+import { testConfig } from "../support/test-config.ts";
+import { startExtractionStub } from "./support/memorable-extraction-stub.ts";
+
+const NO_KEY = !process.env.ANTHROPIC_API_KEY;
+const DB = process.env.MEMORABLE_E2E_DB_URL;
+const CLI = process.env.MEMORABLE_E2E_BIN;
+function skipReason(): string | false {
+ if (NO_KEY) return "set ANTHROPIC_API_KEY";
+ if (!DB) return "set MEMORABLE_E2E_DB_URL";
+ if (!CLI) return "set MEMORABLE_E2E_BIN (e.g. `node /path/to/memorable-cli/dist/cli.js`)";
+ return false;
+}
+const SKIP = skipReason();
+
+describe("memorable provider e2e (live Pi + real memorable CLI + Postgres)", { skip: SKIP }, () => {
+ const scope = "personal:U1";
+ let stub: Awaited<ReturnType<typeof startExtractionStub>>;
+ let server: Server;
+ let base: string;
+ let pool: pg.Pool;
+ let cliEnv: NodeJS.ProcessEnv;
+
+ before(async () => {
+ stub = await startExtractionStub();
+ pool = new pg.Pool({ connectionString: DB });
+ await pool.query("DROP TABLE IF EXISTS memorable_procedures, memorable_mode, memorable_stats");
+ cliEnv = {
+ PATH: process.env.PATH,
+ HOME: process.env.HOME,
+ DATABASE_URL: DB,
+ MEMORABLE_API_URL: stub.url,
+ MEMORABLE_API_KEY: "mk_e2e_not_a_real_key_0000",
+ MEMORABLE_HOME: mkdtempSync(join(tmpdir(), "memorable-home-")),
+ ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY,
+ };
+ // Consent is the CLI's own act, per scope, exactly as an operator would do it.
+ const [cmd, ...args] = CLI!.split(" ");
+ execFileSync(cmd!, [...args, "enable", "--scope", scope], {
+ env: { ...cliEnv, MEMORABLE_BACKEND: "qm", MEMORABLE_DB_URL: DB },
+ stdio: "ignore",
+ });
+
+ const memoryProviderConfig = parseMemoryProviderConfig(
+ JSON.stringify({
+ providers: [{ id: "procedures", type: "memorable", bin: CLI, injectTimeoutMs: 30_000 }],
+ routes: [
+ { provider: "default", scopes: ["personal"], capture: "automatic" },
+ { provider: "procedures", scopes: ["personal"], capture: "automatic", manage: false, label: "Procedures" },
+ ],
+ }),
+ cliEnv,
+ );
+ const built = buildApp(
+ testConfig({
+ dataDir: mkdtempSync(join(tmpdir(), "memorable-e2e-")),
+ harness: "pi",
+ memoryProviderConfig,
+ ...(process.env.PI_MODEL ? { modelId: process.env.PI_MODEL } : {}),
+ anthropicApiKey: process.env.ANTHROPIC_API_KEY!,
+ }),
+ );
+ server = createInsecureTestServer(built.app);
+ await new Promise<void>((r) => server.listen(0, r));
+ base = `http://localhost:${(server.address() as AddressInfo).port}`;
+ });
+
+ after(async () => {
+ await new Promise<void>((r) => server.close(() => r()));
+ await new Promise<void>((r) => stub.server.close(() => r()));
+ await pool.end();
+ });
+
+ async function turn(text: string, threadRef: string): Promise<{ http: number; json: any }> {
+ const res = await fetch(`${base}/v1/turns`, {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({
+ surface: "http-e2e",
+ actor: { externalId: "U1" },
+ conversation: { kind: "dm", threadRef },
+ text,
+ }),
+ });
+ return { http: res.status, json: await res.json() };
+ }
+
+ async function procedures(): Promise<Array<{ id: string; title: string }>> {
+ const r = await pool.query("SELECT id, json->>'title' AS title FROM memorable_procedures");
+ return r.rows;
+ }
+
+ it("a tool-using turn is recorded as a procedure in the qm backend", { timeout: 240_000 }, async () => {
+ const r = await turn(
+ "Use the write tool to create osprey/config.txt containing exactly: anchor=7. " +
+ "Then use the execute tool to run `cat osprey/config.txt` and report what it printed. " +
+ "Also remember for later: my project is called Osprey.",
+ "t-record",
+ );
+ assert.equal(r.http, 200);
+ assert.equal(r.json.status, "ok");
+ const deadline = Date.now() + 90_000;
+ let rows = await procedures();
+ while (!rows.length && Date.now() < deadline) {
+ await new Promise((s) => setTimeout(s, 2000));
+ rows = await procedures();
+ }
+ assert.ok(rows.length >= 1, "expected memorable record to store a procedure");
+ assert.ok(rows[0]!.id.startsWith(`${scope}/`), `procedure keyed by scope: ${rows[0]!.id}`);
+ const sent = stub.requests[0] as {
+ tool_calls: Array<{ name: string }>;
+ task_description?: string;
+ harness?: string;
+ };
+ assert.equal(sent.harness, "qm");
+ assert.ok(sent.tool_calls.some((c) => c.name === "write") && sent.tool_calls.some((c) => c.name === "execute"));
+ assert.ok(
+ !JSON.stringify(sent).includes(process.env.ANTHROPIC_API_KEY!),
+ "secrets never reach the extraction call",
+ );
+ });
+
+ it("a similar task recalls the procedure through the router", { timeout: 180_000 }, async () => {
+ const r = await turn(
+ "Task: create osprey/config.txt containing anchor=7 and cat it. BUT do not use any tools yet. First tell me: " +
+ "does your system prompt contain a section headed 'Procedures' with a block that begins '<!-- retrieved brain context'? " +
+ "Reply with exactly YES-PROCEDURE followed by the 'fix landed in' path it names, or exactly NO-PROCEDURE.",
+ "t-recall",
+ );
+ assert.equal(r.http, 200);
+ assert.match(r.json.reply, /YES-PROCEDURE/);
+ assert.match(r.json.reply, /osprey\/config\.txt/);
+ });
+});
diff --git a/test/e2e/support/memorable-extraction-stub.ts b/test/e2e/support/memorable-extraction-stub.ts
new file mode 100644
index 000000000..dad1e6cc2
--- /dev/null
+++ b/test/e2e/support/memorable-extraction-stub.ts
@@ -0,0 +1,64 @@
+import { createServer, type Server } from "node:http";
+
+/** Minimal stand-in for the Memorable extraction service: turns a trace into a deterministic draft. */
+export function startExtractionStub(): Promise<{ server: Server; url: string; requests: unknown[] }> {
+ const requests: unknown[] = [];
+ const server = createServer((req, res) => {
+ let body = "";
+ req.on("data", (c) => (body += c));
+ req.on("end", () => {
+ const json = (obj: unknown) => {
+ res.writeHead(200, { "content-type": "application/json" });
+ res.end(JSON.stringify(obj));
+ };
+ if (req.url === "/v1/extract") {
+ const trace = JSON.parse(body) as {
+ session_id: string;
+ workflow_id?: string;
+ task_description?: string;
+ prompt?: string;
+ tool_calls: Array<{ name: string; input: Record<string, unknown>; result?: { ok: boolean } }>;
+ };
+ requests.push(trace);
+ const classes: Record<string, string> = { execute: "execute", write: "write", read: "read" };
+ const klass = (name: string) => classes[name] ?? "other";
+ const steps = trace.tool_calls.map((call) => ({
+ action: call.name,
+ activity_class: klass(call.name),
+ ...(typeof call.input.command === "string" ? { command: call.input.command } : {}),
+ ...(typeof call.input.path === "string" ? { targets: [call.input.path] } : {}),
+ ...(call.result ? { outcome: call.result.ok ? "ok" : "failed" } : {}),
+ }));
+ const title = (trace.task_description ?? trace.prompt ?? "untitled task").slice(0, 200);
+ const files = steps.flatMap((s) => s.targets ?? []);
+ const commands = steps.flatMap((s) => (s.command ? [s.command] : []));
+ json({
+ draft: {
+ schema_version: 1,
+ session_id: trace.session_id,
+ workflow_id: trace.workflow_id ?? trace.session_id,
+ title,
+ trigger_signature: {
+ summary_text: title,
+ search_text: [title, ...files, ...commands].join(" "),
+ entities: { file_paths: files, commands, tool_names: [...new Set(trace.tool_calls.map((c) => c.name))] },
+ },
+ steps,
+ preconditions: [],
+ postconditions: commands.length ? [`exited successfully: ${commands[commands.length - 1]}`] : [],
+ embedding: [],
+ embedding_model: "",
+ },
+ });
+ return;
+ }
+ json({ ok: true, used: 0, remaining: 1000, allowance: 1000 });
+ });
+ });
+ return new Promise((resolve) =>
+ server.listen(0, () => {
+ const { port } = server.address() as { port: number };
+ resolve({ server, url: `http://127.0.0.1:${port}`, requests });
+ }),
+ );
+}