Files
OmniRoute/tests/unit/memory-tools.test.ts
Diego Rodrigues de Sa e Souza 3d4f3e4960 test(infra): retry recursive temp-dir removal instead of failing a shard on ENOTEMPTY (#11966) (#11968)
* test(infra): retry recursive temp-dir removal instead of failing a shard on ENOTEMPTY (#11966)

Two shards on release/v3.8.51 went red in one day with the same signature —
"ENOTEMPTY, Directory not empty: /tmp/omniroute-<test>-XXXXXX" — from
combo-same-provider-cascade (Unit Tests fast-path 4/4, on a PR that touches only
.github/) and auth-policy-embeddings-webfetch-7785 (the 20k-test TIA step). Both pass
alone and on re-run: the cleanup races something still writing into the directory
(SQLite WAL/-shm checkpoint, a worker, the backup) and under a loaded hosted runner
the window opens. 1154 test files do their own cleanup with
fs.rmSync(dir, { recursive: true, force: true }); 57 already asked for retries.

One-shot codemod (scripts/ad-hoc/codemod-rm-maxretries.mjs, kept for the record):
every rm / rmSync / rmdirSync option object with `recursive: true` and no
`maxRetries` gains `maxRetries: 5, retryDelay: 100` — Node itself then retries
ENOTEMPTY/EBUSY/EPERM for up to ~0.5 s before giving up. 2243 call sites in 1292
files under tests/, the shared tests/_setup/isolateDataDir.ts exit hook included.
Only the option object changes: no call site, assertion or import is touched.

Validation: prettier and ESLint (with the frozen suppressions) clean on all 1292
files; a random 20-file sample runs green (quota-redis-store hangs identically on
the untouched tree — it needs a Redis on localhost, an environment matter). The
four unit shards on this PR are the full run.

* fix(quality): let check-forgotten-sibling-tests read a 1,000-file diff

The gate shells out to `git diff` through execFileSync with Node's default 1 MB
maxBuffer; the 1,292-file codemod in this PR is the first diff large enough to
overflow it, and the gate died with `spawnSync git ENOBUFS` before comparing
anything. 64 MB is far above any real PR and costs nothing when unused.
2026-08-29 01:17:40 -03:00

192 lines
6.3 KiB
TypeScript

import test from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-memory-tools-"));
const originalDataDir = process.env.DATA_DIR;
process.env.DATA_DIR = tmpDir;
const core = await import("../../src/lib/db/core.ts");
const { memoryTools } = await import("../../open-sse/mcp-server/tools/memoryTools.ts");
const memoryStore = await import("../../src/lib/memory/store.ts");
const settingsDb = await import("../../src/lib/db/settings.ts");
const { invalidateMemorySettingsCache } = await import("../../src/lib/memory/settings.ts");
function resetStorage() {
core.resetDbInstance();
fs.rmSync(tmpDir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
fs.mkdirSync(tmpDir, { recursive: true });
core.getDbInstance();
}
test.beforeEach(async () => {
resetStorage();
// PRD-2026-06-19: memory is OFF by default now. The memory MCP tools operate
// within the memory subsystem (omniroute_memory_search → retrieveMemories, which
// returns nothing while memory is disabled), so enable memory explicitly — the
// realistic precondition for a client using the memory tools.
await settingsDb.updateSettings({ memoryEnabled: true });
invalidateMemorySettingsCache();
});
test.after(() => {
core.resetDbInstance();
process.env.DATA_DIR = originalDataDir;
fs.rmSync(tmpDir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
});
test("memory add stores entries with default session and metadata", async () => {
const result = await memoryTools.omniroute_memory_add.handler({
apiKeyId: "key-add",
type: "factual",
key: "pref:language",
content: "TypeScript is preferred.",
});
const rowsResult = await memoryStore.listMemories({ apiKeyId: "key-add" });
const rows = Array.isArray(rowsResult) ? rowsResult : rowsResult.data;
assert.equal(result.success, true);
assert.equal(result.data.message, "Memory created successfully");
assert.equal(rows.length, 1);
assert.equal(rows[0].sessionId, "");
assert.deepEqual(rows[0].metadata, {});
assert.equal(rows[0].content, "TypeScript is preferred.");
});
test("memory search filters by type, enforces limit, and reports token totals", async () => {
await memoryTools.omniroute_memory_add.handler({
apiKeyId: "key-search",
sessionId: "search",
type: "factual",
key: "pref:stack",
content: "TypeScript and Node.js are used for backend work.",
metadata: { source: "user" },
});
await memoryTools.omniroute_memory_add.handler({
apiKeyId: "key-search",
sessionId: "search",
type: "semantic",
key: "pref:hobby",
content: "Gardening is a weekend hobby.",
metadata: { source: "user" },
});
await memoryTools.omniroute_memory_add.handler({
apiKeyId: "key-search",
sessionId: "search",
type: "factual",
key: "pref:language",
content: "TypeScript services are written every day.",
metadata: { source: "user" },
});
const result = await memoryTools.omniroute_memory_search.handler({
apiKeyId: "key-search",
query: "typescript backend",
type: "factual",
limit: 1,
});
assert.equal(result.success, true);
assert.equal(result.data.count, 1);
assert.equal(result.data.memories.length, 1);
assert.equal(result.data.memories[0].type, "factual");
assert.match(result.data.memories[0].content, /TypeScript/i);
assert.ok(result.data.totalTokens > 0);
});
test("memory search respects a configured zero token budget", async () => {
await settingsDb.updateSettings({ memoryEnabled: true, memoryMaxTokens: 0 });
invalidateMemorySettingsCache();
await memoryTools.omniroute_memory_add.handler({
apiKeyId: "key-zero-budget",
type: "factual",
key: "pref:stack",
content: "TypeScript and Node.js are used for backend work.",
});
const result = await memoryTools.omniroute_memory_search.handler({
apiKeyId: "key-zero-budget",
query: "typescript",
});
assert.equal(result.success, true);
assert.equal(result.data.count, 0);
assert.deepEqual(result.data.memories, []);
assert.equal(result.data.totalTokens, 0);
});
test("memory search runs explicitly even when global memory injection is disabled", async () => {
await settingsDb.updateSettings({ memoryEnabled: false, memoryMaxTokens: 2000 });
invalidateMemorySettingsCache();
await memoryTools.omniroute_memory_add.handler({
apiKeyId: "key-disabled-memory",
type: "factual",
key: "pref:stack",
content: "TypeScript and Node.js are used for backend work.",
});
const result = await memoryTools.omniroute_memory_search.handler({
apiKeyId: "key-disabled-memory",
query: "typescript",
maxTokens: 500,
});
assert.equal(result.success, true);
assert.equal(result.data.count, 1);
assert.equal(result.data.memories.length, 1);
assert.match(result.data.memories[0].content, /TypeScript/i);
assert.ok(result.data.totalTokens > 0);
});
test("memory clear deletes only older filtered entries and reports the deleted count", async () => {
const older = await memoryStore.createMemory({
apiKeyId: "key-clear",
sessionId: "clear",
type: "factual",
key: "old",
content: "This memory should be removed.",
metadata: {},
expiresAt: null,
});
const newer = await memoryStore.createMemory({
apiKeyId: "key-clear",
sessionId: "clear",
type: "factual",
key: "new",
content: "This memory should remain.",
metadata: {},
expiresAt: null,
});
const db = core.getDbInstance();
const cutoff = new Date("2025-01-01T00:00:00.000Z");
db.prepare("UPDATE memories SET created_at = ? WHERE id = ?").run(
"2024-01-01T00:00:00.000Z",
older.id
);
db.prepare("UPDATE memories SET created_at = ? WHERE id = ?").run(
"2025-06-01T00:00:00.000Z",
newer.id
);
const result = await memoryTools.omniroute_memory_clear.handler({
apiKeyId: "key-clear",
type: "factual",
olderThan: cutoff.toISOString(),
});
const remainingResult = await memoryStore.listMemories({ apiKeyId: "key-clear" });
const remaining = Array.isArray(remainingResult) ? remainingResult : remainingResult.data;
assert.equal(result.success, true);
assert.equal(result.data.deletedCount, 1);
assert.equal(result.data.message, "Cleared 1 memories");
assert.equal(remaining.length, 1);
assert.equal(remaining[0].id, newer.id);
});