Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion docs/package-guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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
Expand Down
3 changes: 2 additions & 1 deletion docs/package-guide.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 的提示,应用仍应处理真正的数据库错误。
Expand Down Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion docs/worker-api/examples/integrations/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
2 changes: 1 addition & 1 deletion docs/worker-api/examples/integrations/README.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -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。
1 change: 1 addition & 0 deletions examples/_shared/tools/storage/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
1 change: 1 addition & 0 deletions examples/_shared/tools/storage/README.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
7 changes: 7 additions & 0 deletions examples/_shared/tools/storage/memory-id.ts
Original file line number Diff line number Diff line change
@@ -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)}`;
}
8 changes: 3 additions & 5 deletions examples/_shared/tools/storage/qdrant-memory.ts
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -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; };
Expand Down
4 changes: 3 additions & 1 deletion examples/_shared/tools/storage/sql-memory.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { randomUUID } from "node:crypto";
import { MemoryError, type MemoryItem, type MemoryStore, type MemorySearchProvider } from "@codesoul-co/ditto/worker/memory";
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<Row[]>;
Expand Down Expand Up @@ -63,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: 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) {
Expand Down
2 changes: 1 addition & 1 deletion examples/handbook/README.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 恢复状态。
2 changes: 1 addition & 1 deletion examples/package-basics/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
2 changes: 1 addition & 1 deletion examples/package-basics/README.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -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-项目中复用这些文件)。

## 验收

Expand Down
2 changes: 1 addition & 1 deletion scripts/check-json-agent-package.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand Down
2 changes: 1 addition & 1 deletion scripts/check-package-basics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"));
Expand Down
49 changes: 49 additions & 0 deletions test/examples-memory.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,13 @@ 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 { 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";
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", () => {
Expand Down Expand Up @@ -39,6 +46,48 @@ 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("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[][] = [];
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 => keyedMemoryId(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("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: [] }; } };
Expand Down
Loading