From add3dd728c3da2e30162e9d790216ffaf64607fc Mon Sep 17 00:00:00 2001 From: Tim0085 <184967814+Tim0085@users.noreply.github.com> Date: Mon, 30 Nov 2026 12:23:37 +0800 Subject: [PATCH 1/2] fix(examples): derive SQL memory IDs from keys so search results are reproducible --- examples/_shared/tools/storage/sql-memory.ts | 10 +++++++-- test/examples-memory.test.ts | 23 ++++++++++++++++++++ 2 files changed, 31 insertions(+), 2 deletions(-) diff --git a/examples/_shared/tools/storage/sql-memory.ts b/examples/_shared/tools/storage/sql-memory.ts index b9384e5..aea75d5 100644 --- a/examples/_shared/tools/storage/sql-memory.ts +++ b/examples/_shared/tools/storage/sql-memory.ts @@ -1,6 +1,12 @@ -import { randomUUID } from "node:crypto"; +import { createHash, randomUUID } from "node:crypto"; import { MemoryError, type MemoryItem, type MemoryStore, type MemorySearchProvider } from "@codesoul-co/ditto/worker/memory"; +/** Same key-derived UUID as qdrant-memory.ts, so keyed records get the same id in every database. */ +export function memoryRecordId(key: string) { + const bytes = createHash("sha256").update(key).digest().subarray(0, 16); bytes[6] = (bytes[6]! & 15) | 80; bytes[8] = (bytes[8]! & 63) | 128; + const hex = bytes.toString("hex"); return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`; +} + export type Row = { id: string; memory_key: string | null; content: string; metadata: string | null }; export type Rows = (sql: string, values?: unknown[]) => Promise; export interface SqlDatabase { @@ -63,7 +69,7 @@ export function createSqlMemoryStore(database: SqlDatabase, table: string, idemp return rows.map(row => ({ memory: map(row) })); // Database substring matching, not vector ranking. }, async write(input) { - const items = input.memories.map(memory => ({ ...memory, id: randomUUID() })); + const items = input.memories.map(memory => ({ ...memory, id: memory.key ? memoryRecordId(memory.key) : randomUUID() })); return database.transaction(async rows => { const saved: MemoryItem[] = []; for (const item of items) { diff --git a/test/examples-memory.test.ts b/test/examples-memory.test.ts index bc3826a..19c0e29 100644 --- a/test/examples-memory.test.ts +++ b/test/examples-memory.test.ts @@ -3,6 +3,11 @@ import assert from "node:assert/strict"; import { admitted, proposal, progress, report, request, namespace, taskKey, preferenceKey, type Request } from "../examples/_shared/tools/memory/domain.js"; import { memoryPointId } from "../examples/_shared/tools/storage/qdrant-memory.js"; import { scopedMemory } from "../examples/_shared/tools/storage/scoped-memory.js"; +import { memoryRecordId } from "../examples/_shared/tools/storage/sql-memory.js"; +import { openSqliteMemory } from "../examples/_shared/tools/storage/sqlite-memory.js"; +import { mkdtemp, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; import type { MemoryStore, MemorySearchProvider } from "@codesoul-co/ditto/worker/memory"; const r: Request = { id: "task-a", tenant: "team-a", user: "alice", mode: "write", backend: "sqlite", statement: "For future project updates, use English with detailed explanations.", remember: true }; test("memory write policy requires explicit permission and a durable allowlisted preference", () => { @@ -39,6 +44,24 @@ test("vector point identity survives retries and remains distinct between namesp assert.match(memoryPointId(preferenceKey(r)), /^[a-f0-9]{8}-[a-f0-9]{4}-5[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/); assert.notEqual(memoryPointId(preferenceKey(r)), memoryPointId(preferenceKey({ ...r, tenant: "team-b" }))); }); +test("SQL keyed records share Qdrant point identity, so equal writes give equal search results", async () => { + assert.equal(memoryRecordId(preferenceKey(r)), memoryPointId(preferenceKey(r))); + const directory = await mkdtemp(join(tmpdir(), "ditto-sql-memory-")); + const memories = Array.from({ length: 6 }, (_, i) => ({ key: `team-a:alice:note:${i}`, content: `shared note ${i}` })); + const searched: string[][] = []; + try { + for (const name of ["first.sqlite", "second.sqlite"]) { + const memory = openSqliteMemory(join(directory, name)); + try { + const saved = await memory.store.write({ memories }); + assert.deepEqual(saved.map(item => item.id), memories.map(item => memoryRecordId(item.key))); + searched.push((await memory.store.search({ query: "shared", limit: 3 })).map(result => result.memory.id)); + } finally { await memory.close(); } + } + assert.equal(searched[0]!.length, 3); + assert.deepEqual(searched[0], searched[1]); + } finally { await rm(directory, { recursive: true, force: true }); } +}); test("scoped adapter rejects forged filters, keys and metadata before calling a backend", async () => { let writes = 0; const backend: MemoryStore & MemorySearchProvider = { async get() { return []; }, async query() { return { items: [] }; }, async search() { return []; }, async write() { writes++; return []; }, async update() { writes++; return []; }, async delete() { return { deleted: [] }; } }; From 632138ab5a1bc2f65a4890246b8355f624c33ec1 Mon Sep 17 00:00:00 2001 From: Tim0085 <184967814+Tim0085@users.noreply.github.com> Date: Wed, 2 Dec 2026 14:06:33 +0800 Subject: [PATCH 2/2] fix(examples): limit key-derived SQL IDs to unique-key stores and share the UUID helper --- docs/package-guide.md | 3 +- docs/package-guide.zh-CN.md | 3 +- .../examples/integrations/README.md | 2 +- .../examples/integrations/README.zh-CN.md | 2 +- examples/_shared/tools/storage/README.md | 1 + .../_shared/tools/storage/README.zh-CN.md | 1 + examples/_shared/tools/storage/memory-id.ts | 7 ++++ .../_shared/tools/storage/qdrant-memory.ts | 8 ++--- examples/_shared/tools/storage/sql-memory.ts | 12 +++---- examples/handbook/README.zh-CN.md | 2 +- examples/package-basics/README.md | 2 +- examples/package-basics/README.zh-CN.md | 2 +- scripts/check-json-agent-package.ts | 2 +- scripts/check-package-basics.ts | 2 +- test/examples-memory.test.ts | 34 ++++++++++++++++--- 15 files changed, 57 insertions(+), 26 deletions(-) create mode 100644 examples/_shared/tools/storage/memory-id.ts diff --git a/docs/package-guide.md b/docs/package-guide.md index 73430a1..898ebfd 100644 --- a/docs/package-guide.md +++ b/docs/package-guide.md @@ -245,6 +245,7 @@ The example reuses these application adapters: | `redis-context.ts` | Connect the Redis SDK for Context | | `sqlite-memory.ts` | File database, Memory schema, transactions and WAL | | `sql-memory.ts` | Public MemoryStore and search implementation | +| `memory-id.ts` | Key-derived Memory IDs shared with the Qdrant adapter | | `workers.ts` | Inject storage into the Workers and close connections | These are application files, not business APIs exported by the npm package. Copy them with the example. Node SQLite needs no additional driver; its ExperimentalWarning is a Node notice, separate from actual database errors. @@ -293,7 +294,7 @@ The npm package excludes repository examples and business tools. Keep a source c mkdir -p examples/_shared/tools/storage/dependencies cp -R ../Ditto/examples/package-basics examples/ cp ../Ditto/examples/_shared/tools/package-basics.ts examples/_shared/tools/ -cp ../Ditto/examples/_shared/tools/storage/{workers,redis-context,sqlite-memory,sql-memory}.ts examples/_shared/tools/storage/ +cp ../Ditto/examples/_shared/tools/storage/{workers,redis-context,sqlite-memory,sql-memory,memory-id}.ts examples/_shared/tools/storage/ cp ../Ditto/examples/_shared/tools/storage/dependencies/package.json examples/_shared/tools/storage/dependencies/ npm install @codesoul-co/ditto redis@6.2.1 cp examples/package-basics/.env.example .env diff --git a/docs/package-guide.zh-CN.md b/docs/package-guide.zh-CN.md index 89bc4b9..fa32b7c 100644 --- a/docs/package-guide.zh-CN.md +++ b/docs/package-guide.zh-CN.md @@ -245,6 +245,7 @@ Context 是短期工作集,示例使用真实 Redis、TTL 和 scope。Memory | `examples/_shared/tools/storage/redis-context.ts` | 连接 Redis SDK,供 Context Worker 使用 | | `sqlite-memory.ts` | 打开文件 SQLite,创建 Memory 表,配置事务和 WAL | | `sql-memory.ts` | 实现公开 MemoryStore 与搜索接口 | +| `memory-id.ts` | 由 key 推出记忆 ID,与 Qdrant 适配器共用 | | `workers.ts` | 将 Redis 与 SQLite 注入对应 Worker,提供统一关闭方法 | 这些文件不是 npm 主包导出的业务方法,复制示例时必须一并带上。Node SQLite 不需要另装数据库驱动;`ExperimentalWarning` 是 Node 的提示,应用仍应处理真正的数据库错误。 @@ -298,7 +299,7 @@ node --env-file=.env.local examples/package-basics/agent.ts \ mkdir -p examples/_shared/tools/storage/dependencies cp -R ../Ditto/examples/package-basics examples/ cp ../Ditto/examples/_shared/tools/package-basics.ts examples/_shared/tools/ -cp ../Ditto/examples/_shared/tools/storage/{workers,redis-context,sqlite-memory,sql-memory}.ts examples/_shared/tools/storage/ +cp ../Ditto/examples/_shared/tools/storage/{workers,redis-context,sqlite-memory,sql-memory,memory-id}.ts examples/_shared/tools/storage/ cp ../Ditto/examples/_shared/tools/storage/dependencies/package.json examples/_shared/tools/storage/dependencies/ npm install @codesoul-co/ditto redis@6.2.1 cp examples/package-basics/.env.example .env diff --git a/docs/worker-api/examples/integrations/README.md b/docs/worker-api/examples/integrations/README.md index 3194a86..e4b37d0 100644 --- a/docs/worker-api/examples/integrations/README.md +++ b/docs/worker-api/examples/integrations/README.md @@ -131,4 +131,4 @@ npm run example:worker:context-retrieval Resource defaults come from workers.context.localCache/queue in root ditto.yaml. Replace stateStore to use Redis. Applications still own real SQL/Milvus connection pools; the retrieval provider can run inline or in a separate Worker. -The SQL adapter implementation is shared with [application storage](../../../../examples/_shared/tools/storage/README.md). When copying SQL examples into a separate application, also copy `sql-memory.ts` and adjust the relative import. Understanding examples use persistent file SQLite and include real Redis in complete task verification. +The SQL adapter implementation is shared with [application storage](../../../../examples/_shared/tools/storage/README.md). When copying SQL examples into a separate application, also copy `sql-memory.ts` together with `memory-id.ts`, then adjust the relative import. Understanding examples use persistent file SQLite and include real Redis in complete task verification. diff --git a/docs/worker-api/examples/integrations/README.zh-CN.md b/docs/worker-api/examples/integrations/README.zh-CN.md index c39ce92..868cd82 100644 --- a/docs/worker-api/examples/integrations/README.zh-CN.md +++ b/docs/worker-api/examples/integrations/README.zh-CN.md @@ -142,4 +142,4 @@ npm run example:worker:context-retrieval 参数来自根 ditto.yaml 的 workers.context.localCache/queue;若要替换 Redis,替换 stateStore 即可。真实 SQL/Milvus 的连接池仍由应用持有,检索 Provider 可原样用于内联或独立 Worker。 -SQL 适配器实现复用于[应用存储目录](../../../../examples/_shared/tools/storage/README.zh-CN.md)。复制 SQL 示例到独立应用时,同时复制 `sql-memory.ts` 并调整相对导入;请求理解示例使用持久化文件 SQLite,完整任务验收包含真实 Redis。 +SQL 适配器实现复用于[应用存储目录](../../../../examples/_shared/tools/storage/README.zh-CN.md)。复制 SQL 示例到独立应用时,同时复制 `sql-memory.ts`、`memory-id.ts` 并调整相对导入;请求理解示例使用持久化文件 SQLite,完整任务验收包含真实 Redis。 diff --git a/examples/_shared/tools/storage/README.md b/examples/_shared/tools/storage/README.md index c6e1a32..d36c167 100644 --- a/examples/_shared/tools/storage/README.md +++ b/examples/_shared/tools/storage/README.md @@ -29,6 +29,7 @@ For local development, run `redis-server --bind 127.0.0.1 --port 6379` in a sepa | [redis-context.ts](redis-context.ts) | Open a real Redis SDK client for `createContextWorker({ redis: { client, ...config.context.cache } })` | | [sqlite-memory.ts](sqlite-memory.ts) | File database, WAL, serialized transactions, unique memory keys, and resource cleanup | | [sql-memory.ts](sql-memory.ts) | Shared SQL MemoryStore: GET, QUERY, SEARCH, WRITE, UPDATE, DELETE | +| [memory-id.ts](memory-id.ts) | Key-derived Memory IDs shared by the SQL (unique-key mode) and Qdrant adapters | ```ts const redis = await openRedisContext(); diff --git a/examples/_shared/tools/storage/README.zh-CN.md b/examples/_shared/tools/storage/README.zh-CN.md index 43918a8..078de33 100644 --- a/examples/_shared/tools/storage/README.zh-CN.md +++ b/examples/_shared/tools/storage/README.zh-CN.md @@ -29,6 +29,7 @@ Redis TTL 和 keyPrefix 读取 `ditto.yaml` 的 `workers.context.cache`。连接 | [redis-context.ts](redis-context.ts) | 创建真实 Redis SDK 客户端;注入 `createContextWorker({ redis: { client, ...config.context.cache } })` | | [sqlite-memory.ts](sqlite-memory.ts) | 文件数据库、WAL、事务串行化、唯一记忆 key 与资源关闭 | | [sql-memory.ts](sql-memory.ts) | 复用 SQL MemoryStore:GET、QUERY、SEARCH、WRITE、UPDATE、DELETE | +| [memory-id.ts](memory-id.ts) | 由 key 推出记忆 ID,供 SQL(唯一 key 模式)与 Qdrant 适配器共用 | ```ts const redis = await openRedisContext(); diff --git a/examples/_shared/tools/storage/memory-id.ts b/examples/_shared/tools/storage/memory-id.ts new file mode 100644 index 0000000..3827815 --- /dev/null +++ b/examples/_shared/tools/storage/memory-id.ts @@ -0,0 +1,7 @@ +import { createHash } from "node:crypto"; + +/** Stable UUID-formatted ID derived from a Memory key. Shared by the SQL and Qdrant adapters so equal keys get equal IDs. */ +export function keyedMemoryId(key: string): string { + const bytes = createHash("sha256").update(key).digest().subarray(0, 16); bytes[6] = (bytes[6]! & 15) | 80; bytes[8] = (bytes[8]! & 63) | 128; + const hex = bytes.toString("hex"); return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`; +} diff --git a/examples/_shared/tools/storage/qdrant-memory.ts b/examples/_shared/tools/storage/qdrant-memory.ts index 3b65e27..f31fc0c 100644 --- a/examples/_shared/tools/storage/qdrant-memory.ts +++ b/examples/_shared/tools/storage/qdrant-memory.ts @@ -1,7 +1,9 @@ -import { createHash, randomUUID } from "node:crypto"; +import { randomUUID } from "node:crypto"; import { isDeepStrictEqual } from "node:util"; import { MemoryError, type MemoryItem, type MemoryStore, type MemorySearchProvider, type MemoryCallOptions } from "@codesoul-co/ditto/worker/memory"; import { embedContents, type EmbeddingProvider } from "@codesoul-co/ditto-retrieval"; +import { keyedMemoryId as memoryPointId } from "./memory-id.ts"; +export { memoryPointId }; export interface QdrantOptions { url: string; collection: string; dimensions: number; embedding: EmbeddingProvider; embeddingIdentity: string; apiKey?: string } export class QdrantClient { readonly url: string; readonly apiKey: string | undefined; @@ -16,10 +18,6 @@ export class QdrantClient { if (parsed.status !== "ok") throw new MemoryError("QDRANT_ERROR", "Qdrant operation failed"); return parsed.result; } } -export function memoryPointId(key: string) { - const bytes = createHash("sha256").update(key).digest().subarray(0, 16); bytes[6] = (bytes[6]! & 15) | 80; bytes[8] = (bytes[8]! & 63) | 128; - const hex = bytes.toString("hex"); return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`; -} interface Point { id: string; payload: MemoryItem; score?: number } const uuid = (id: string) => { if (!/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(id)) throw new MemoryError("INVALID_INPUT", "Qdrant Memory IDs must be UUIDs"); return id; }; const map = (p: Point): MemoryItem => { if (!p.payload || p.id !== p.payload.id) throw new MemoryError("INVALID_BACKEND_OUTPUT", "Qdrant payload identity mismatch"); return p.payload; }; diff --git a/examples/_shared/tools/storage/sql-memory.ts b/examples/_shared/tools/storage/sql-memory.ts index aea75d5..1801de7 100644 --- a/examples/_shared/tools/storage/sql-memory.ts +++ b/examples/_shared/tools/storage/sql-memory.ts @@ -1,11 +1,6 @@ -import { createHash, randomUUID } from "node:crypto"; +import { randomUUID } from "node:crypto"; import { MemoryError, type MemoryItem, type MemoryStore, type MemorySearchProvider } from "@codesoul-co/ditto/worker/memory"; - -/** Same key-derived UUID as qdrant-memory.ts, so keyed records get the same id in every database. */ -export function memoryRecordId(key: string) { - const bytes = createHash("sha256").update(key).digest().subarray(0, 16); bytes[6] = (bytes[6]! & 15) | 80; bytes[8] = (bytes[8]! & 63) | 128; - const hex = bytes.toString("hex"); return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`; -} +import { keyedMemoryId } from "./memory-id.ts"; export type Row = { id: string; memory_key: string | null; content: string; metadata: string | null }; export type Rows = (sql: string, values?: unknown[]) => Promise; @@ -69,7 +64,8 @@ export function createSqlMemoryStore(database: SqlDatabase, table: string, idemp return rows.map(row => ({ memory: map(row) })); // Database substring matching, not vector ranking. }, async write(input) { - const items = input.memories.map(memory => ({ ...memory, id: memory.key ? memoryRecordId(memory.key) : randomUUID() })); + // Unique-key stores derive IDs from keys so rebuilds order rows identically; the default mode allows shared keys. + const items = input.memories.map(memory => ({ ...memory, id: idempotentKeys && memory.key ? keyedMemoryId(memory.key) : randomUUID() })); return database.transaction(async rows => { const saved: MemoryItem[] = []; for (const item of items) { diff --git a/examples/handbook/README.zh-CN.md b/examples/handbook/README.zh-CN.md index 89f7502..b98b1ab 100644 --- a/examples/handbook/README.zh-CN.md +++ b/examples/handbook/README.zh-CN.md @@ -11,6 +11,6 @@ | [memory-ranking.ts](memory-ranking.ts) | `node examples/handbook/memory-ranking.ts` | 文件 SQLite 写入与自定义时间排序 Provider | | [mcp.mjs](mcp.mjs) | `node examples/handbook/mcp.mjs ./workspace hello.txt .` | 真实 MCP SDK 连接、发现、读取文件和观察结果 | -前三个示例只需主包。数据库示例保留 `_shared/tools/storage/sqlite-memory.ts` 与 `sql-memory.ts` 的相对位置。MCP 示例另需在最后一个参数指定的应用目录安装 `@modelcontextprotocol/sdk` 与 `@modelcontextprotocol/server-filesystem`,并先创建 `workspace/hello.txt`。 +前三个示例只需主包。数据库示例保留 `_shared/tools/storage/sqlite-memory.ts`、`sql-memory.ts` 与 `memory-id.ts` 的相对位置。MCP 示例另需在最后一个参数指定的应用目录安装 `@modelcontextprotocol/sdk` 与 `@modelcontextprotocol/server-filesystem`,并先创建 `workspace/hello.txt`。 Memory 算法仅重排有界的关键词候选,不是全库向量检索。Skill 示例展示显式 Context 准备;完整 Agent 仍需按 scope 接入 Redis,并通过数据库 Memory 恢复状态。 diff --git a/examples/package-basics/README.md b/examples/package-basics/README.md index a07ef91..ad73519 100644 --- a/examples/package-basics/README.md +++ b/examples/package-basics/README.md @@ -67,7 +67,7 @@ console.log(result.answer, result.file); ## Copy into an npm consumer -Install the main package and `redis@6.2.1`. Copy this directory, `../_shared/tools/package-basics.ts`, and storage's `workers.ts`, `redis-context.ts`, `sqlite-memory.ts`, `sql-memory.ts`, and `dependencies/package.json`, preserving relative locations. Install the retrieval package only for its example. The [package guide](../../docs/package-guide.md#10-copy-the-examples-into-your-project) includes exact commands, TypeScript configuration and environment setup. +Install the main package and `redis@6.2.1`. Copy this directory, `../_shared/tools/package-basics.ts`, and storage's `workers.ts`, `redis-context.ts`, `sqlite-memory.ts`, `sql-memory.ts`, `memory-id.ts`, and `dependencies/package.json`, preserving relative locations. Install the retrieval package only for its example. The [package guide](../../docs/package-guide.md#10-copy-the-examples-into-your-project) includes exact commands, TypeScript configuration and environment setup. ## Verify diff --git a/examples/package-basics/README.zh-CN.md b/examples/package-basics/README.zh-CN.md index ce0c57c..8c89f8e 100644 --- a/examples/package-basics/README.zh-CN.md +++ b/examples/package-basics/README.zh-CN.md @@ -67,7 +67,7 @@ console.log(result.answer, result.file); ## 复制到自己的项目 -消费者安装主包和 `redis@6.2.1`,复制本目录、`../_shared/tools/package-basics.ts` 和 storage 下的 `workers.ts`、`redis-context.ts`、`sqlite-memory.ts`、`sql-memory.ts`、`dependencies/package.json`,保持目录关系。运行检索示例时再安装检索包。具体复制命令、TypeScript 配置及环境变量解释见[完整教程](../../docs/package-guide.zh-CN.md#10-在自己的-npm-项目中复用这些文件)。 +消费者安装主包和 `redis@6.2.1`,复制本目录、`../_shared/tools/package-basics.ts` 和 storage 下的 `workers.ts`、`redis-context.ts`、`sqlite-memory.ts`、`sql-memory.ts`、`memory-id.ts`、`dependencies/package.json`,保持目录关系。运行检索示例时再安装检索包。具体复制命令、TypeScript 配置及环境变量解释见[完整教程](../../docs/package-guide.zh-CN.md#10-在自己的-npm-项目中复用这些文件)。 ## 验收 diff --git a/scripts/check-json-agent-package.ts b/scripts/check-json-agent-package.ts index 6614dad..b37faa8 100644 --- a/scripts/check-json-agent-package.ts +++ b/scripts/check-json-agent-package.ts @@ -32,7 +32,7 @@ try { await run("npm", ["install", "--ignore-scripts", "--no-audit", "--no-fund", core, retrieval, `typescript@${manifest.devDependencies.typescript}`, `@types/node@${manifest.devDependencies["@types/node"]}`, "redis@6.2.1"]); await cp(join(root, "examples/json-agent/npm-scenarios"), join(app, "examples/json-agent/npm-scenarios"), { recursive: true }); - for (const name of ["workers.ts", "redis-context.ts", "sqlite-memory.ts", "sql-memory.ts", "dependencies/package.json"]) + for (const name of ["workers.ts", "redis-context.ts", "sqlite-memory.ts", "sql-memory.ts", "memory-id.ts", "dependencies/package.json"]) await cp(join(root, "examples/_shared/tools/storage", name), join(app, "examples/_shared/tools/storage", name)); await cp(join(root, "examples/_shared/tools/package-basics.ts"), join(app, "examples/_shared/tools/package-basics.ts")); const extension = join(app, "examples/json-agent/npm-scenarios/extension"); diff --git a/scripts/check-package-basics.ts b/scripts/check-package-basics.ts index 1d5fe11..55ad2b2 100644 --- a/scripts/check-package-basics.ts +++ b/scripts/check-package-basics.ts @@ -54,7 +54,7 @@ try { await run("npm", ["install", "--ignore-scripts", "--no-audit", "--no-fund", install(core.name), `@types/node@${core.devDependencies["@types/node"]}`, "redis@6.2.1"]); await cp(join(root, "examples/package-basics"), join(app, "examples/package-basics"), { recursive: true }); await cp(join(root, "examples/json-agent"), join(app, "examples/json-agent"), { recursive: true }); - for (const name of ["workers.ts", "redis-context.ts", "sqlite-memory.ts", "sql-memory.ts", "dependencies/package.json"]) { + for (const name of ["workers.ts", "redis-context.ts", "sqlite-memory.ts", "sql-memory.ts", "memory-id.ts", "dependencies/package.json"]) { await cp(join(root, "examples/_shared/tools/storage", name), join(app, "examples/_shared/tools/storage", name), { recursive: true }); } await cp(join(root, "examples/_shared/tools/package-basics.ts"), join(app, "examples/_shared/tools/package-basics.ts")); diff --git a/test/examples-memory.test.ts b/test/examples-memory.test.ts index 19c0e29..a2f6fc3 100644 --- a/test/examples-memory.test.ts +++ b/test/examples-memory.test.ts @@ -3,8 +3,10 @@ import assert from "node:assert/strict"; import { admitted, proposal, progress, report, request, namespace, taskKey, preferenceKey, type Request } from "../examples/_shared/tools/memory/domain.js"; import { memoryPointId } from "../examples/_shared/tools/storage/qdrant-memory.js"; import { scopedMemory } from "../examples/_shared/tools/storage/scoped-memory.js"; -import { memoryRecordId } from "../examples/_shared/tools/storage/sql-memory.js"; +import { keyedMemoryId } from "../examples/_shared/tools/storage/memory-id.js"; +import { createSqlMemoryStore, type Row, type Rows, type SqlDatabase } from "../examples/_shared/tools/storage/sql-memory.js"; import { openSqliteMemory } from "../examples/_shared/tools/storage/sqlite-memory.js"; +import { DatabaseSync } from "node:sqlite"; import { mkdtemp, rm } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -44,8 +46,8 @@ test("vector point identity survives retries and remains distinct between namesp assert.match(memoryPointId(preferenceKey(r)), /^[a-f0-9]{8}-[a-f0-9]{4}-5[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/); assert.notEqual(memoryPointId(preferenceKey(r)), memoryPointId(preferenceKey({ ...r, tenant: "team-b" }))); }); -test("SQL keyed records share Qdrant point identity, so equal writes give equal search results", async () => { - assert.equal(memoryRecordId(preferenceKey(r)), memoryPointId(preferenceKey(r))); +test("unique-key SQL records share Qdrant point identity, so equal writes give equal search results", async () => { + assert.equal(keyedMemoryId(preferenceKey(r)), memoryPointId(preferenceKey(r))); const directory = await mkdtemp(join(tmpdir(), "ditto-sql-memory-")); const memories = Array.from({ length: 6 }, (_, i) => ({ key: `team-a:alice:note:${i}`, content: `shared note ${i}` })); const searched: string[][] = []; @@ -54,7 +56,7 @@ test("SQL keyed records share Qdrant point identity, so equal writes give equal const memory = openSqliteMemory(join(directory, name)); try { const saved = await memory.store.write({ memories }); - assert.deepEqual(saved.map(item => item.id), memories.map(item => memoryRecordId(item.key))); + assert.deepEqual(saved.map(item => item.id), memories.map(item => keyedMemoryId(item.key))); searched.push((await memory.store.search({ query: "shared", limit: 3 })).map(result => result.memory.id)); } finally { await memory.close(); } } @@ -62,6 +64,30 @@ test("SQL keyed records share Qdrant point identity, so equal writes give equal assert.deepEqual(searched[0], searched[1]); } finally { await rm(directory, { recursive: true, force: true }); } }); +test("default SQL mode keeps two writes with the same key as distinct records", async () => { + const client = new DatabaseSync(":memory:"); + const rows: Rows = async (sql, values = []) => { + const statement = client.prepare(sql); + if (statement.columns().length) return statement.all(...values as (string | number | null)[]) as Row[]; + statement.run(...values as (string | number | null)[]); return []; + }; + const database: SqlDatabase = { dialect: "sqlite", rows, async transaction(operation) { + await rows("BEGIN IMMEDIATE"); + try { const result = await operation(rows); await rows("COMMIT"); return result; } + catch (error) { await rows("ROLLBACK"); throw error; } + }, async close() { client.close(); } }; + try { + // Same schema as the SQL integration example: memory_key is indexed but not unique. + await rows("CREATE TABLE memories (id VARCHAR(36) PRIMARY KEY, memory_key VARCHAR(255), content TEXT NOT NULL, metadata TEXT)"); + const store = createSqlMemoryStore(database, "memories"), key = preferenceKey(r); + const [first] = await store.write({ memories: [{ key, content: "first" }] }); + const [second] = await store.write({ memories: [{ key, content: "second" }] }); + assert.ok(first && second); + assert.notEqual(first.id, second.id); + assert.ok(first.id !== keyedMemoryId(key) && second.id !== keyedMemoryId(key)); + assert.deepEqual((await store.get({ keys: [key] })).map(item => item.content).sort(), ["first", "second"]); + } finally { await database.close(); } +}); test("scoped adapter rejects forged filters, keys and metadata before calling a backend", async () => { let writes = 0; const backend: MemoryStore & MemorySearchProvider = { async get() { return []; }, async query() { return { items: [] }; }, async search() { return []; }, async write() { writes++; return []; }, async update() { writes++; return []; }, async delete() { return { deleted: [] }; } };