@inupedia/spotlight-memory 0.1.9 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  export { classifyMemoryKind, isMemoryKindAllowedForRead, type ClassifyMemoryKindInput, type ClassifyMemoryKindResult, } from "./classify.js";
2
2
  export { normalizeQuestion, scoreQuestionSimilarity, } from "./normalize.js";
3
3
  export { isMemoryEntryStale, pickSemanticHit } from "./stale.js";
4
+ export { clampMemoryTtlSec, MEMORY_TTL_MAX_SEC } from "./ttl.js";
4
5
  export { cosineSimilarity } from "./similarity.js";
5
6
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,kBAAkB,EAClB,0BAA0B,EAC1B,KAAK,uBAAuB,EAC5B,KAAK,wBAAwB,GAC9B,MAAM,eAAe,CAAC;AACvB,OAAO,EACL,iBAAiB,EACjB,uBAAuB,GACxB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,kBAAkB,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AACjE,OAAO,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,kBAAkB,EAClB,0BAA0B,EAC1B,KAAK,uBAAuB,EAC5B,KAAK,wBAAwB,GAC9B,MAAM,eAAe,CAAC;AACvB,OAAO,EACL,iBAAiB,EACjB,uBAAuB,GACxB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,kBAAkB,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AACjE,OAAO,EAAE,iBAAiB,EAAE,kBAAkB,EAAE,MAAM,UAAU,CAAC;AACjE,OAAO,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC"}
package/dist/index.js CHANGED
@@ -1,4 +1,5 @@
1
1
  export { classifyMemoryKind, isMemoryKindAllowedForRead, } from "./classify.js";
2
2
  export { normalizeQuestion, scoreQuestionSimilarity, } from "./normalize.js";
3
3
  export { isMemoryEntryStale, pickSemanticHit } from "./stale.js";
4
+ export { clampMemoryTtlSec, MEMORY_TTL_MAX_SEC } from "./ttl.js";
4
5
  export { cosineSimilarity } from "./similarity.js";
@@ -0,0 +1,60 @@
1
+ export declare const FILE_MEMORY_ENTRYPOINT = "MEMORY.md";
2
+ export type SpotlightFileMemoryScope = "managed" | "user" | "project" | "local" | "auto" | "agent-user" | "agent-project" | "agent-local" | "session";
3
+ export interface SpotlightFileMemoryInfo {
4
+ path: string;
5
+ type: SpotlightFileMemoryScope;
6
+ content: string;
7
+ }
8
+ export interface SpotlightFileMemoryPaths {
9
+ baseDir: string;
10
+ projectDir: string;
11
+ autoDir: string;
12
+ autoEntrypoint: string;
13
+ sessionDir?: string;
14
+ sessionEntrypoint?: string;
15
+ }
16
+ export interface ResolveSpotlightFileMemoryPathsOptions {
17
+ projectId: string;
18
+ baseDir?: string;
19
+ sessionId?: string | null;
20
+ }
21
+ export interface LoadSpotlightFileMemoryOptions extends ResolveSpotlightFileMemoryPathsOptions {
22
+ cwd?: string;
23
+ includeProjectFiles?: boolean;
24
+ includeAutoMemory?: boolean;
25
+ includeSessionMemory?: boolean;
26
+ agent?: {
27
+ type: string;
28
+ scope: "user" | "project" | "local";
29
+ };
30
+ maxFileChars?: number;
31
+ maxTotalChars?: number;
32
+ }
33
+ export interface BuildSpotlightFileMemoryPromptOptions extends LoadSpotlightFileMemoryOptions {
34
+ emptyText?: string;
35
+ }
36
+ export declare function resolveSpotlightFileMemoryPaths(options: ResolveSpotlightFileMemoryPathsOptions): SpotlightFileMemoryPaths;
37
+ export declare function resolveAgentMemoryDir(options: {
38
+ projectId: string;
39
+ agentType: string;
40
+ scope: "user" | "project" | "local";
41
+ baseDir?: string;
42
+ cwd?: string;
43
+ }): string;
44
+ export declare function resolveAgentMemoryEntrypoint(options: {
45
+ projectId: string;
46
+ agentType: string;
47
+ scope: "user" | "project" | "local";
48
+ baseDir?: string;
49
+ cwd?: string;
50
+ }): string;
51
+ export declare function ensureSpotlightFileMemoryEntrypoints(options: ResolveSpotlightFileMemoryPathsOptions): Promise<SpotlightFileMemoryPaths>;
52
+ export declare function appendSpotlightFileMemory(options: {
53
+ filePath: string;
54
+ content: string;
55
+ heading?: string;
56
+ }): Promise<void>;
57
+ export declare function loadSpotlightFileMemories(options: LoadSpotlightFileMemoryOptions): Promise<SpotlightFileMemoryInfo[]>;
58
+ export declare function buildSpotlightFileMemoryPrompt(options: BuildSpotlightFileMemoryPromptOptions): Promise<string>;
59
+ export declare function isSpotlightFileMemoryPath(absolutePath: string, options: ResolveSpotlightFileMemoryPathsOptions): boolean;
60
+ //# sourceMappingURL=fileMemory.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fileMemory.d.ts","sourceRoot":"","sources":["../../src/node/fileMemory.ts"],"names":[],"mappings":"AAIA,eAAO,MAAM,sBAAsB,cAAc,CAAC;AAElD,MAAM,MAAM,wBAAwB,GAChC,SAAS,GACT,MAAM,GACN,SAAS,GACT,OAAO,GACP,MAAM,GACN,YAAY,GACZ,eAAe,GACf,aAAa,GACb,SAAS,CAAC;AAEd,MAAM,WAAW,uBAAuB;IACtC,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,wBAAwB,CAAC;IAC/B,OAAO,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,wBAAwB;IACvC,OAAO,EAAE,MAAM,CAAC;IAChB,UAAU,EAAE,MAAM,CAAC;IACnB,OAAO,EAAE,MAAM,CAAC;IAChB,cAAc,EAAE,MAAM,CAAC;IACvB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,iBAAiB,CAAC,EAAE,MAAM,CAAC;CAC5B;AAED,MAAM,WAAW,sCAAsC;IACrD,SAAS,EAAE,MA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;AAED,wBAAsB,yBAAyB,CAAC,OAAO,EAAE;IACvD,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,EAAE,MAAM,CAAC;IAChB,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB,GAAG,OAAO,CAAC,IAAI,CAAC,CAehB;AAED,wBAAsB,yBAAyB,CAC7C,OAAO,EAAE,8BAA8B,GACtC,OAAO,CAAC,uBAAuB,EAAE,CAAC,CA2DpC;AAyBD,wBAAsB,8BAA8B,CAClD,OAAO,EAAE,qCAAqC,GAC7C,OAAO,CAAC,MAAM,CAAC,CA0BjB;AAED,wBAAgB,yBAAyB,CACvC,YAAY,EAAE,MAAM,EACpB,OAAO,EAAE,sCAAsC,GAC9C,OAAO,CAQT"}
@@ -0,0 +1,252 @@
1
+ import { mkdir, readdir, readFile, writeFile } from "node:fs/promises";
2
+ import { homedir } from "node:os";
3
+ import { dirname, isAbsolute, join, resolve, sep } from "node:path";
4
+ export const FILE_MEMORY_ENTRYPOINT = "MEMORY.md";
5
+ function normalizeDir(path) {
6
+ const resolved = resolve(path);
7
+ return resolved.endsWith(sep) ? resolved : `${resolved}${sep}`;
8
+ }
9
+ function sanitizePathSegment(value) {
10
+ return (value
11
+ .trim()
12
+ .replace(/[/\\:]/g, "-")
13
+ .replace(/\s+/g, "-")
14
+ .replace(/[^a-zA-Z0-9._-]/g, "_")
15
+ .slice(0, 160) || "default");
16
+ }
17
+ function resolveBaseDir(baseDir) {
18
+ const raw = baseDir?.trim() ||
19
+ process.env.SPOTLIGHT_MEMORY_DIR?.trim() ||
20
+ join(homedir(), ".spotlight");
21
+ return resolve(raw);
22
+ }
23
+ function truncate(text, maxChars) {
24
+ if (text.length <= maxChars)
25
+ return text;
26
+ return `${text.slice(0, Math.max(0, maxChars - 80)).trimEnd()}\n\n<!-- truncated by Spotlight memory: ${text.length - maxChars} chars omitted -->`;
27
+ }
28
+ async function readUtf8File(path) {
29
+ try {
30
+ return await readFile(path, "utf8");
31
+ }
32
+ catch (error) {
33
+ const code = error.code;
34
+ if (code === "ENOENT" || code === "EISDIR")
35
+ return null;
36
+ throw error;
37
+ }
38
+ }
39
+ async function readMemoryFile(path, type, maxChars) {
40
+ const content = await readUtf8File(path);
41
+ if (content == null)
42
+ return null;
43
+ const trimmed = content.trim();
44
+ if (!trimmed)
45
+ return null;
46
+ return { path, type, content: truncate(trimmed, maxChars) };
47
+ }
48
+ function uniquePaths(paths) {
49
+ const seen = new Set();
50
+ const result = [];
51
+ for (const path of paths) {
52
+ const normalized = resolve(path);
53
+ if (seen.has(normalized))
54
+ continue;
55
+ seen.add(normalized);
56
+ result.push(normalized);
57
+ }
58
+ return result;
59
+ }
60
+ function parentDirsFromRoot(cwd) {
61
+ const dirs = [];
62
+ let current = resolve(cwd);
63
+ while (true) {
64
+ dirs.unshift(current);
65
+ const parent = dirname(current);
66
+ if (parent === current)
67
+ break;
68
+ current = parent;
69
+ }
70
+ return dirs;
71
+ }
72
+ async function listRulesFiles(dir) {
73
+ try {
74
+ const entries = await readdir(dir, { withFileTypes: true });
75
+ return entries
76
+ .filter((entry) => entry.isFile() && entry.name.endsWith(".md"))
77
+ .map((entry) => join(dir, entry.name))
78
+ .sort();
79
+ }
80
+ catch (error) {
81
+ const code = error.code;
82
+ if (code === "ENOENT" || code === "ENOTDIR")
83
+ return [];
84
+ throw error;
85
+ }
86
+ }
87
+ export function resolveSpotlightFileMemoryPaths(options) {
88
+ const baseDir = resolveBaseDir(options.baseDir);
89
+ const projectDir = join(baseDir, "projects", sanitizePathSegment(options.projectId));
90
+ const autoDir = join(projectDir, "memory");
91
+ const paths = {
92
+ baseDir,
93
+ projectDir,
94
+ autoDir: normalizeDir(autoDir),
95
+ autoEntrypoint: join(autoDir, FILE_MEMORY_ENTRYPOINT),
96
+ };
97
+ const sessionId = options.sessionId?.trim();
98
+ if (sessionId) {
99
+ const sessionDir = join(projectDir, "sessions", sanitizePathSegment(sessionId), "memory");
100
+ paths.sessionDir = normalizeDir(sessionDir);
101
+ paths.sessionEntrypoint = join(sessionDir, FILE_MEMORY_ENTRYPOINT);
102
+ }
103
+ return paths;
104
+ }
105
+ export function resolveAgentMemoryDir(options) {
106
+ const agentType = sanitizePathSegment(options.agentType);
107
+ if (options.scope === "project") {
108
+ return normalizeDir(join(resolve(options.cwd ?? process.cwd()), ".spotlight", "agent-memory", agentType));
109
+ }
110
+ if (options.scope === "local") {
111
+ return normalizeDir(join(resolve(options.cwd ?? process.cwd()), ".spotlight", "agent-memory-local", agentType));
112
+ }
113
+ return normalizeDir(join(resolveBaseDir(options.baseDir), "agent-memory", agentType));
114
+ }
115
+ export function resolveAgentMemoryEntrypoint(options) {
116
+ return join(resolveAgentMemoryDir(options), FILE_MEMORY_ENTRYPOINT);
117
+ }
118
+ export async function ensureSpotlightFileMemoryEntrypoints(options) {
119
+ const paths = resolveSpotlightFileMemoryPaths(options);
120
+ await mkdir(paths.autoDir, { recursive: true });
121
+ if (!(await readUtf8File(paths.autoEntrypoint))) {
122
+ await writeFile(paths.autoEntrypoint, "", "utf8");
123
+ }
124
+ if (paths.sessionDir && paths.sessionEntrypoint) {
125
+ await mkdir(paths.sessionDir, { recursive: true });
126
+ if (!(await readUtf8File(paths.sessionEntrypoint))) {
127
+ await writeFile(paths.sessionEntrypoint, "", "utf8");
128
+ }
129
+ }
130
+ return paths;
131
+ }
132
+ export async function appendSpotlightFileMemory(options) {
133
+ const content = options.content.trim();
134
+ if (!content)
135
+ return;
136
+ await mkdir(dirname(options.filePath), { recursive: true });
137
+ const existing = (await readUtf8File(options.filePath)) ?? "";
138
+ const heading = options.heading?.trim();
139
+ const next = [
140
+ existing.trimEnd(),
141
+ heading ? `\n\n## ${heading}` : "",
142
+ `\n\n${content}`,
143
+ "\n",
144
+ ]
145
+ .join("")
146
+ .replace(/^\n+/, "");
147
+ await writeFile(options.filePath, next, "utf8");
148
+ }
149
+ export async function loadSpotlightFileMemories(options) {
150
+ const maxFileChars = options.maxFileChars ?? 8_000;
151
+ const paths = resolveSpotlightFileMemoryPaths(options);
152
+ const candidates = [];
153
+ if (options.includeProjectFiles !== false) {
154
+ const cwd = resolve(options.cwd ?? process.cwd());
155
+ const homeMemory = join(resolveBaseDir(options.baseDir), FILE_MEMORY_ENTRYPOINT);
156
+ candidates.push({ path: homeMemory, type: "user" });
157
+ for (const dir of parentDirsFromRoot(cwd)) {
158
+ candidates.push({ path: join(dir, "CLAUDE.md"), type: "project" });
159
+ candidates.push({ path: join(dir, "SPOTLIGHT.md"), type: "project" });
160
+ candidates.push({ path: join(dir, ".claude", "CLAUDE.md"), type: "project" });
161
+ candidates.push({ path: join(dir, ".spotlight", FILE_MEMORY_ENTRYPOINT), type: "project" });
162
+ for (const rulesFile of await listRulesFiles(join(dir, ".claude", "rules"))) {
163
+ candidates.push({ path: rulesFile, type: "project" });
164
+ }
165
+ candidates.push({ path: join(dir, "CLAUDE.local.md"), type: "local" });
166
+ candidates.push({ path: join(dir, "SPOTLIGHT.local.md"), type: "local" });
167
+ }
168
+ }
169
+ if (options.includeAutoMemory !== false) {
170
+ candidates.push({ path: paths.autoEntrypoint, type: "auto" });
171
+ }
172
+ if (options.includeSessionMemory !== false &&
173
+ paths.sessionEntrypoint &&
174
+ paths.sessionDir) {
175
+ candidates.push({ path: paths.sessionEntrypoint, type: "session" });
176
+ }
177
+ if (options.agent) {
178
+ const agentPath = resolveAgentMemoryEntrypoint({
179
+ projectId: options.projectId,
180
+ agentType: options.agent.type,
181
+ scope: options.agent.scope,
182
+ baseDir: options.baseDir,
183
+ cwd: options.cwd,
184
+ });
185
+ const type = options.agent.scope === "user"
186
+ ? "agent-user"
187
+ : options.agent.scope === "project"
188
+ ? "agent-project"
189
+ : "agent-local";
190
+ candidates.push({ path: agentPath, type });
191
+ }
192
+ const result = [];
193
+ for (const path of uniquePaths(candidates.map((item) => item.path))) {
194
+ const candidate = candidates.find((item) => resolve(item.path) === path);
195
+ if (!candidate)
196
+ continue;
197
+ const memory = await readMemoryFile(path, candidate.type, maxFileChars);
198
+ if (memory)
199
+ result.push(memory);
200
+ }
201
+ return result;
202
+ }
203
+ function typeLabel(type) {
204
+ switch (type) {
205
+ case "managed":
206
+ return "Managed";
207
+ case "user":
208
+ return "User";
209
+ case "project":
210
+ return "Project";
211
+ case "local":
212
+ return "Local";
213
+ case "auto":
214
+ return "Auto";
215
+ case "agent-user":
216
+ return "Agent/User";
217
+ case "agent-project":
218
+ return "Agent/Project";
219
+ case "agent-local":
220
+ return "Agent/Local";
221
+ case "session":
222
+ return "Session";
223
+ }
224
+ }
225
+ export async function buildSpotlightFileMemoryPrompt(options) {
226
+ const maxTotalChars = options.maxTotalChars ?? 24_000;
227
+ const memories = await loadSpotlightFileMemories(options);
228
+ if (memories.length === 0) {
229
+ return options.emptyText ?? "";
230
+ }
231
+ const body = memories
232
+ .map((memory) => `### ${typeLabel(memory.type)} Memory\nPath: ${memory.path}\n\n${memory.content}`)
233
+ .join("\n\n");
234
+ return truncate([
235
+ "【长期记忆】",
236
+ "下面内容来自 Spotlight 的持久文件记忆系统。它们是项目规则、用户偏好、agent 经验与会话摘要,不是用户当前这句话本身。",
237
+ "使用原则:",
238
+ "- 与用户当前请求冲突时,以当前请求为准。",
239
+ "- 不要凭记忆编造实时数据;实时状态必须调用工具确认。",
240
+ "- 当用户明确要求记住偏好、事实或项目约定时,应写入对应 memory 文件,而不是只放在本轮回答里。",
241
+ "",
242
+ body,
243
+ ].join("\n"), maxTotalChars);
244
+ }
245
+ export function isSpotlightFileMemoryPath(absolutePath, options) {
246
+ if (!isAbsolute(absolutePath))
247
+ return false;
248
+ const paths = resolveSpotlightFileMemoryPaths(options);
249
+ const normalized = resolve(absolutePath);
250
+ return (normalized.startsWith(paths.autoDir) ||
251
+ Boolean(paths.sessionDir && normalized.startsWith(paths.sessionDir)));
252
+ }
@@ -1,25 +1,51 @@
1
+ import type { SpotlightMemoryEntry } from "@inupedia/spotlight-protocol";
1
2
  import type { MemoryGate } from "./gate.js";
2
3
  import { type MemoryGateConfig } from "./gate.js";
3
- import { ExactMemoryStore } from "./exactStore.js";
4
4
  import { type PackMemoryPaths } from "./paths.js";
5
- import { SemanticMemoryStore } from "./semanticStore.js";
5
+ export interface SemanticMemoryStoreLike {
6
+ findSimilar(projectId: string, questionNorm: string, limit?: number): Promise<Array<{
7
+ entry: SpotlightMemoryEntry;
8
+ score: number;
9
+ }>>;
10
+ putWithOptionalEmbedding(entry: SpotlightMemoryEntry): Promise<void>;
11
+ touch(entryId: string): void | Promise<void>;
12
+ count(projectId?: string): number;
13
+ }
14
+ export interface ExactMemoryStoreLike {
15
+ getExact(cacheKey: string): Promise<SpotlightMemoryEntry | null>;
16
+ putExact(cacheKey: string, entry: SpotlightMemoryEntry): Promise<void>;
17
+ hasExact(cacheKey: string): Promise<boolean>;
18
+ touch(entryId: string): Promise<void>;
19
+ listEntries(limit?: number): SpotlightMemoryEntry[];
20
+ }
6
21
  export interface PackMemoryStores {
7
22
  paths: PackMemoryPaths;
8
- exact: ExactMemoryStore;
9
- semantic: SemanticMemoryStore;
23
+ exact: ExactMemoryStoreLike;
24
+ semantic: SemanticMemoryStoreLike;
10
25
  gate: MemoryGate;
26
+ backends: {
27
+ exact: "file" | "redis";
28
+ semantic: "sqlite" | "milvus";
29
+ };
11
30
  }
12
31
  export declare function createPackMemoryStores(params: {
13
32
  packsRoot: string;
14
33
  projectId: string;
34
+ tenantId?: string;
15
35
  gateConfig?: MemoryGateConfig;
16
36
  lruMax?: number;
17
37
  }): PackMemoryStores;
18
38
  export { ExactMemoryStore } from "./exactStore.js";
19
39
  export { SemanticMemoryStore } from "./semanticStore.js";
40
+ export { MilvusSemanticMemoryStore } from "./milvusSemanticStore.js";
41
+ export { RedisExactMemoryStore } from "./redisExactStore.js";
42
+ export { resolveExactMemoryBackend, resolveSemanticMemoryBackend, } from "./memoryBackends.js";
20
43
  export { buildCacheKey, createMemoryEntryId, } from "./cacheKey.js";
21
44
  export { createMemoryGate, type MemoryGate, type MemoryGateConfig, type MemoryStoreReader, type MemoryStoreWriter, } from "./gate.js";
22
45
  export { defaultPackMemoryMeta, resolvePackMemoryDir, type PackMemoryMeta, type PackMemoryPaths, } from "./paths.js";
23
46
  export { readPackMemoryMeta, refreshPackMemoryMeta, writePackMemoryMeta, } from "./meta.js";
24
47
  export { type EmbeddingProvider, resolveEmbeddingProviderFromEnv, } from "./embeddingProvider.js";
48
+ export { getSpotlightRedisClient, isSpotlightRedisConfigured, spotlightRedisKey, } from "./redisClient.js";
49
+ export { getSpotlightMilvusClient, isSpotlightMilvusConfigured, resolveSpotlightMilvusDb, SPOTLIGHT_MILVUS_SEMANTIC_COLLECTION, } from "./milvusClient.js";
50
+ export { FILE_MEMORY_ENTRYPOINT, appendSpotlightFileMemory, buildSpotlightFileMemoryPrompt, ensureSpotlightFileMemoryEntrypoints, isSpotlightFileMemoryPath, loadSpotlightFileMemories, resolveAgentMemoryDir, resolveAgentMemoryEntrypoint, resolveSpotlightFileMemoryPaths, type BuildSpotlightFileMemoryPromptOptions, type LoadSpotlightFileMemoryOptions, type ResolveSpotlightFileMemoryPathsOptions, type SpotlightFileMemoryInfo, type SpotlightFileMemoryPaths, type SpotlightFileMemoryScope, } from "./fileMemory.js";
25
51
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/node/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC;AAC5C,OAAO,EAAoB,KAAK,gBAAgB,EAAE,MAAM,WAAW,CAAC;AAEpE,OAAO,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AAEnD,OAAO,EAAwB,KAAK,eAAe,EAAE,MAAM,YAAY,CAAC;AACxE,OAAO,EAAE,mBAAmB,EAAE,MAAM,oBAAoB,CAAC;AAEzD,MAAM,WAAW,gBAAgB;IAC/B,KAAK,EAAE,eAAe,CAAC;IACvB,KAAK,EAAE,gBAAgB,CAAC;IACxB,QAAQ,EAAE,mBAAmB,CAAC;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iB,CAAC"}
@@ -1,7 +1,10 @@
1
1
  import { createMemoryGate } from "./gate.js";
2
2
  import { ExactMemoryStore } from "./exactStore.js";
3
3
  import { refreshPackMemoryMeta } from "./meta.js";
4
+ import { resolveExactMemoryBackend, resolveSemanticMemoryBackend, } from "./memoryBackends.js";
5
+ import { MilvusSemanticMemoryStore } from "./milvusSemanticStore.js";
4
6
  import { resolvePackMemoryDir } from "./paths.js";
7
+ import { RedisExactMemoryStore } from "./redisExactStore.js";
5
8
  import { SemanticMemoryStore } from "./semanticStore.js";
6
9
  function createCompositeMemoryStores(paths, exact, semantic, projectId) {
7
10
  const reader = {
@@ -9,7 +12,7 @@ function createCompositeMemoryStores(paths, exact, semantic, projectId) {
9
12
  findSemantic: (pid, questionNorm, limit) => semantic.findSimilar(pid, questionNorm, limit),
10
13
  touch: async (entryId) => {
11
14
  await exact.touch(entryId);
12
- semantic.touch(entryId);
15
+ await semantic.touch(entryId);
13
16
  },
14
17
  };
15
18
  const writer = {
@@ -26,10 +29,45 @@ function createCompositeMemoryStores(paths, exact, semantic, projectId) {
26
29
  };
27
30
  return { reader, writer };
28
31
  }
32
+ function createExactStore(params) {
33
+ const backend = resolveExactMemoryBackend();
34
+ if (backend === "redis" && RedisExactMemoryStore.isAvailable()) {
35
+ return new RedisExactMemoryStore({
36
+ projectId: params.projectId,
37
+ tenantId: params.tenantId,
38
+ lruMax: params.lruMax,
39
+ });
40
+ }
41
+ return new ExactMemoryStore({
42
+ paths: params.paths,
43
+ lruMax: params.lruMax,
44
+ });
45
+ }
46
+ function createSemanticStore(params) {
47
+ const backend = resolveSemanticMemoryBackend();
48
+ if (backend === "milvus" && MilvusSemanticMemoryStore.isAvailable()) {
49
+ return new MilvusSemanticMemoryStore({
50
+ projectId: params.projectId,
51
+ tenantId: params.tenantId,
52
+ });
53
+ }
54
+ return new SemanticMemoryStore({ paths: params.paths });
55
+ }
29
56
  export function createPackMemoryStores(params) {
30
57
  const paths = resolvePackMemoryDir(params.packsRoot, params.projectId);
31
- const exact = new ExactMemoryStore({ paths, lruMax: params.lruMax });
32
- const semantic = new SemanticMemoryStore({ paths });
58
+ const exactBackend = resolveExactMemoryBackend();
59
+ const semanticBackend = resolveSemanticMemoryBackend();
60
+ const exact = createExactStore({
61
+ paths,
62
+ projectId: params.projectId,
63
+ tenantId: params.tenantId,
64
+ lruMax: params.lruMax,
65
+ });
66
+ const semantic = createSemanticStore({
67
+ paths,
68
+ projectId: params.projectId,
69
+ tenantId: params.tenantId,
70
+ });
33
71
  const { reader, writer } = createCompositeMemoryStores(paths, exact, semantic, params.projectId);
34
72
  const gate = createMemoryGate(reader, writer, params.gateConfig);
35
73
  refreshPackMemoryMeta({
@@ -37,12 +75,31 @@ export function createPackMemoryStores(params) {
37
75
  exactCount: exact.listEntries(Number.MAX_SAFE_INTEGER).length,
38
76
  semanticCount: semantic.count(params.projectId),
39
77
  });
40
- return { paths, exact, semantic, gate };
78
+ return {
79
+ paths,
80
+ exact,
81
+ semantic,
82
+ gate,
83
+ backends: {
84
+ exact: exactBackend === "redis" && RedisExactMemoryStore.isAvailable()
85
+ ? "redis"
86
+ : "file",
87
+ semantic: semanticBackend === "milvus" && MilvusSemanticMemoryStore.isAvailable()
88
+ ? "milvus"
89
+ : "sqlite",
90
+ },
91
+ };
41
92
  }
42
93
  export { ExactMemoryStore } from "./exactStore.js";
43
94
  export { SemanticMemoryStore } from "./semanticStore.js";
95
+ export { MilvusSemanticMemoryStore } from "./milvusSemanticStore.js";
96
+ export { RedisExactMemoryStore } from "./redisExactStore.js";
97
+ export { resolveExactMemoryBackend, resolveSemanticMemoryBackend, } from "./memoryBackends.js";
44
98
  export { buildCacheKey, createMemoryEntryId, } from "./cacheKey.js";
45
99
  export { createMemoryGate, } from "./gate.js";
46
100
  export { defaultPackMemoryMeta, resolvePackMemoryDir, } from "./paths.js";
47
101
  export { readPackMemoryMeta, refreshPackMemoryMeta, writePackMemoryMeta, } from "./meta.js";
48
102
  export { resolveEmbeddingProviderFromEnv, } from "./embeddingProvider.js";
103
+ export { getSpotlightRedisClient, isSpotlightRedisConfigured, spotlightRedisKey, } from "./redisClient.js";
104
+ export { getSpotlightMilvusClient, isSpotlightMilvusConfigured, resolveSpotlightMilvusDb, SPOTLIGHT_MILVUS_SEMANTIC_COLLECTION, } from "./milvusClient.js";
105
+ export { FILE_MEMORY_ENTRYPOINT, appendSpotlightFileMemory, buildSpotlightFileMemoryPrompt, ensureSpotlightFileMemoryEntrypoints, isSpotlightFileMemoryPath, loadSpotlightFileMemories, resolveAgentMemoryDir, resolveAgentMemoryEntrypoint, resolveSpotlightFileMemoryPaths, } from "./fileMemory.js";
@@ -0,0 +1,5 @@
1
+ export type SemanticMemoryBackend = "sqlite" | "milvus";
2
+ export type ExactMemoryBackend = "file" | "redis";
3
+ export declare function resolveSemanticMemoryBackend(): SemanticMemoryBackend;
4
+ export declare function resolveExactMemoryBackend(): ExactMemoryBackend;
5
+ //# sourceMappingURL=memoryBackends.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"memoryBackends.d.ts","sourceRoot":"","sources":["../../src/node/memoryBackends.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,qBAAqB,GAAG,QAAQ,GAAG,QAAQ,CAAC;AACxD,MAAM,MAAM,kBAAkB,GAAG,MAAM,GAAG,OAAO,CAAC;AAElD,wBAAgB,4BAA4B,IAAI,qBAAqB,CAMpE;AAED,wBAAgB,yBAAyB,IAAI,kBAAkB,CAM9D"}
@@ -0,0 +1,20 @@
1
+ export function resolveSemanticMemoryBackend() {
2
+ const raw = process.env.SPOTLIGHT_MEMORY_SEMANTIC_BACKEND?.trim().toLowerCase();
3
+ if (raw === "sqlite" || raw === "file")
4
+ return "sqlite";
5
+ if (raw === "milvus")
6
+ return "milvus";
7
+ if (process.env.SPOTLIGHT_MILVUS_URI?.trim())
8
+ return "milvus";
9
+ return "sqlite";
10
+ }
11
+ export function resolveExactMemoryBackend() {
12
+ const raw = process.env.SPOTLIGHT_MEMORY_EXACT_BACKEND?.trim().toLowerCase();
13
+ if (raw === "file" || raw === "disk")
14
+ return "file";
15
+ if (raw === "redis")
16
+ return "redis";
17
+ if (process.env.SPOTLIGHT_REDIS_URL?.trim())
18
+ return "redis";
19
+ return "file";
20
+ }
@@ -0,0 +1,11 @@
1
+ import type { MilvusClient } from "@zilliz/milvus2-sdk-node";
2
+ export declare const SPOTLIGHT_MILVUS_SEMANTIC_COLLECTION = "spotlight_gate_semantic";
3
+ export declare function resolveSpotlightMilvusUri(): string | null;
4
+ /** 独立 Milvus 数据库,避免与 Yuxi 知识库 `yuxi` / `default` 混用。 */
5
+ export declare function resolveSpotlightMilvusDb(): string;
6
+ export declare function resolveSpotlightMilvusToken(): string;
7
+ export declare function resolveSpotlightMilvusEmbeddingDim(): number;
8
+ export declare function isSpotlightMilvusConfigured(): boolean;
9
+ export declare function getSpotlightMilvusClient(): Promise<MilvusClient | null>;
10
+ export declare function resetSpotlightMilvusClientForTests(): void;
11
+ //# sourceMappingURL=milvusClient.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"milvusClient.d.ts","sourceRoot":"","sources":["../../src/node/milvusClient.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,0BAA0B,CAAC;AAK7D,eAAO,MAAM,oCAAoC,4BAA4B,CAAC;AAE9E,wBAAgB,yBAAyB,IAAI,MAAM,GAAG,IAAI,CAEzD;AAED,wDAAwD;AACxD,wBAAgB,wBAAwB,IAAI,MAAM,CAEjD;AAED,wBAAgB,2BAA2B,IAAI,MAAM,CAEpD;AAED,wBAAgB,kCAAkC,IAAI,MAAM,CAG3D;AAED,wBAAgB,2BAA2B,IAAI,OAAO,CAErD;AAoBD,wBAAsB,wBAAwB,IAAI,OAAO,CAAC,YAAY,GAAG,IAAI,CAAC,CAW7E;AAED,wBAAgB,kCAAkC,IAAI,IAAI,CAGzD"}
@@ -0,0 +1,53 @@
1
+ let client = null;
2
+ let dbReady = false;
3
+ export const SPOTLIGHT_MILVUS_SEMANTIC_COLLECTION = "spotlight_gate_semantic";
4
+ export function resolveSpotlightMilvusUri() {
5
+ return process.env.SPOTLIGHT_MILVUS_URI?.trim() || null;
6
+ }
7
+ /** 独立 Milvus 数据库,避免与 Yuxi 知识库 `yuxi` / `default` 混用。 */
8
+ export function resolveSpotlightMilvusDb() {
9
+ return process.env.SPOTLIGHT_MILVUS_DB?.trim() || "spotlight";
10
+ }
11
+ export function resolveSpotlightMilvusToken() {
12
+ return process.env.SPOTLIGHT_MILVUS_TOKEN?.trim() || "";
13
+ }
14
+ export function resolveSpotlightMilvusEmbeddingDim() {
15
+ const raw = Number(process.env.SPOTLIGHT_MILVUS_EMBEDDING_DIM ?? "1024");
16
+ return Number.isFinite(raw) && raw > 0 ? Math.floor(raw) : 1024;
17
+ }
18
+ export function isSpotlightMilvusConfigured() {
19
+ return Boolean(resolveSpotlightMilvusUri());
20
+ }
21
+ async function ensureSpotlightMilvusDatabase(milvus) {
22
+ if (dbReady)
23
+ return;
24
+ const dbName = resolveSpotlightMilvusDb();
25
+ const listed = await milvus.listDatabases();
26
+ const names = listed.db_names ?? [];
27
+ if (!names.includes(dbName)) {
28
+ await milvus.createDatabase({ db_name: dbName });
29
+ }
30
+ await milvus.useDatabase({ db_name: dbName });
31
+ dbReady = true;
32
+ }
33
+ function normalizeMilvusAddress(uri) {
34
+ return uri.replace(/^https?:\/\//, "").replace(/\/$/, "");
35
+ }
36
+ export async function getSpotlightMilvusClient() {
37
+ const uri = resolveSpotlightMilvusUri();
38
+ if (!uri)
39
+ return null;
40
+ if (client)
41
+ return client;
42
+ const { MilvusClient: MilvusCtor } = await import("@zilliz/milvus2-sdk-node");
43
+ client = new MilvusCtor({
44
+ address: normalizeMilvusAddress(uri),
45
+ token: resolveSpotlightMilvusToken() || undefined,
46
+ });
47
+ await ensureSpotlightMilvusDatabase(client);
48
+ return client;
49
+ }
50
+ export function resetSpotlightMilvusClientForTests() {
51
+ client = null;
52
+ dbReady = false;
53
+ }
@@ -0,0 +1,31 @@
1
+ import type { SpotlightMemoryEntry } from "@inupedia/spotlight-protocol";
2
+ import { type EmbeddingProvider } from "./embeddingProvider.js";
3
+ export interface MilvusSemanticMemoryStoreOptions {
4
+ projectId: string;
5
+ tenantId?: string;
6
+ embeddingProvider?: EmbeddingProvider | null;
7
+ }
8
+ /** L1 semantic cache in Milvus (Spotlight 独立 DB / collection,与 Yuxi kb_* 隔离). */
9
+ export declare class MilvusSemanticMemoryStore {
10
+ private readonly projectId;
11
+ private readonly tenantId;
12
+ private readonly embeddingProvider;
13
+ private collectionReady;
14
+ constructor(options: MilvusSemanticMemoryStoreOptions);
15
+ static isAvailable(): boolean;
16
+ private ensureCollection;
17
+ private initCollection;
18
+ put(entry: SpotlightMemoryEntry, embedding?: number[] | null): Promise<void>;
19
+ putWithOptionalEmbedding(entry: SpotlightMemoryEntry): Promise<void>;
20
+ findSimilar(projectId: string, questionNorm: string, limit?: number): Promise<Array<{
21
+ entry: SpotlightMemoryEntry;
22
+ score: number;
23
+ }>>;
24
+ private findSimilarLexical;
25
+ touch(entryId: string): Promise<void>;
26
+ listEntries(limit?: number): SpotlightMemoryEntry[];
27
+ deleteEntry(entryId: string): boolean;
28
+ deleteAll(_projectId: string): number;
29
+ count(projectId?: string): number;
30
+ }
31
+ //# sourceMappingURL=milvusSemanticStore.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"milvusSemanticStore.d.ts","sourceRoot":"","sources":["../../src/node/milvusSemanticStore.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,8BAA8B,CAAC;AAEzE,OAAO,EACL,KAAK,iBAAiB,EAGvB,MAAM,wBAAwB,CAAC;AAQhC,MAAM,WAAW,gCAAgC;IAC/C,SAAS,EAAE,MAAM,CAAC;IAClB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,iBAAiB,CAAC,EAAE,iBAAiB,GAAG,IAAI,CAAC;CAC9C;AAED,iFAAiF;AACjF,qBAAa,yBAAyB;IACpC,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAS;IACnC,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAS;IAClC,OAAO,CAAC,QAAQ,CAAC,iBAAiB,CAA2B;IAC7D,OAAO,CAAC,eAAe,CAA8B;gBAEzC,OAAO,EAAE,gCAAgC;IASrD,MAAM,CAAC,WAAW,IAAI,OAAO;YAIf,gBAAgB;YAOhB,cAAc;IAwDtB,GAAG,CAAC,KAAK,EAAE,oBAAoB,EAAE,SAAS,CAAC,EAAE,MAAM,EAAE,GAAG,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;IAmB5E,wBAAwB,CAAC,KAAK,EAAE,oBAAoB,GAAG,OAAO,CAAC,IAAI,CAAC;IAYpE,WAAW,CACf,SAAS,EAAE,MAAM,EACjB,YAAY,EAAE,MAAM,EACpB,KAAK,SAAI,GACR,OAAO,CAAC,KAAK,CAAC;QAAE,KAAK,EAAE,oBAAoB,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;YAiDnD,kBAAkB;IA4B1B,KAAK,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAqB3C,WAAW,CAAC,KAAK,SAAK,GAAG,oBAAoB,EAAE;IAK/C,WAAW,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO;IAKrC,SAAS,CAAC,UAAU,EAAE,MAAM,GAAG,MAAM;IAIrC,KAAK,CAAC,SAAS,CAAC,EAAE,MAAM,GAAG,MAAM;CAIlC"}
@@ -0,0 +1,228 @@
1
+ import { scoreQuestionSimilarity } from "../normalize.js";
2
+ import { resolveEmbeddingProviderFromEnv, } from "./embeddingProvider.js";
3
+ import { getSpotlightMilvusClient, isSpotlightMilvusConfigured, resolveSpotlightMilvusEmbeddingDim, SPOTLIGHT_MILVUS_SEMANTIC_COLLECTION, } from "./milvusClient.js";
4
+ /** L1 semantic cache in Milvus (Spotlight 独立 DB / collection,与 Yuxi kb_* 隔离). */
5
+ export class MilvusSemanticMemoryStore {
6
+ projectId;
7
+ tenantId;
8
+ embeddingProvider;
9
+ collectionReady = null;
10
+ constructor(options) {
11
+ this.projectId = options.projectId;
12
+ this.tenantId = options.tenantId?.trim() || "default";
13
+ this.embeddingProvider =
14
+ options.embeddingProvider === undefined
15
+ ? resolveEmbeddingProviderFromEnv()
16
+ : options.embeddingProvider;
17
+ }
18
+ static isAvailable() {
19
+ return isSpotlightMilvusConfigured();
20
+ }
21
+ async ensureCollection() {
22
+ if (!this.collectionReady) {
23
+ this.collectionReady = this.initCollection();
24
+ }
25
+ await this.collectionReady;
26
+ }
27
+ async initCollection() {
28
+ const client = await getSpotlightMilvusClient();
29
+ if (!client)
30
+ throw new Error("Milvus client unavailable");
31
+ const { DataType, IndexType, MetricType } = await import("@zilliz/milvus2-sdk-node");
32
+ const dim = resolveSpotlightMilvusEmbeddingDim();
33
+ const name = SPOTLIGHT_MILVUS_SEMANTIC_COLLECTION;
34
+ const exists = await client.hasCollection({ collection_name: name });
35
+ if (!exists.value) {
36
+ await client.createCollection({
37
+ collection_name: name,
38
+ fields: [
39
+ {
40
+ name: "id",
41
+ data_type: DataType.VarChar,
42
+ is_primary_key: true,
43
+ max_length: 128,
44
+ },
45
+ {
46
+ name: "project_id",
47
+ data_type: DataType.VarChar,
48
+ max_length: 128,
49
+ },
50
+ {
51
+ name: "tenant_id",
52
+ data_type: DataType.VarChar,
53
+ max_length: 128,
54
+ },
55
+ {
56
+ name: "question_norm",
57
+ data_type: DataType.VarChar,
58
+ max_length: 2048,
59
+ },
60
+ {
61
+ name: "entry_json",
62
+ data_type: DataType.VarChar,
63
+ max_length: 65_536,
64
+ },
65
+ {
66
+ name: "embedding",
67
+ data_type: DataType.FloatVector,
68
+ dim,
69
+ },
70
+ ],
71
+ });
72
+ await client.createIndex({
73
+ collection_name: name,
74
+ field_name: "embedding",
75
+ index_type: IndexType.AUTOINDEX,
76
+ metric_type: MetricType.COSINE,
77
+ });
78
+ }
79
+ await client.loadCollectionSync({ collection_name: name });
80
+ }
81
+ async put(entry, embedding) {
82
+ await this.ensureCollection();
83
+ const client = await getSpotlightMilvusClient();
84
+ if (!client)
85
+ return;
86
+ await client.upsert({
87
+ collection_name: SPOTLIGHT_MILVUS_SEMANTIC_COLLECTION,
88
+ data: [
89
+ {
90
+ id: entry.id,
91
+ project_id: entry.projectId,
92
+ tenant_id: this.tenantId,
93
+ question_norm: entry.questionNorm,
94
+ entry_json: JSON.stringify(entry),
95
+ embedding: embedding ?? [],
96
+ },
97
+ ],
98
+ });
99
+ }
100
+ async putWithOptionalEmbedding(entry) {
101
+ let embedding = null;
102
+ if (this.embeddingProvider) {
103
+ try {
104
+ embedding = await this.embeddingProvider.embed(entry.questionNorm);
105
+ }
106
+ catch {
107
+ embedding = null;
108
+ }
109
+ }
110
+ await this.put(entry, embedding);
111
+ }
112
+ async findSimilar(projectId, questionNorm, limit = 5) {
113
+ if (projectId !== this.projectId)
114
+ return [];
115
+ await this.ensureCollection();
116
+ const client = await getSpotlightMilvusClient();
117
+ if (!client)
118
+ return [];
119
+ let queryEmbedding = null;
120
+ if (this.embeddingProvider) {
121
+ try {
122
+ queryEmbedding = await this.embeddingProvider.embed(questionNorm);
123
+ }
124
+ catch {
125
+ queryEmbedding = null;
126
+ }
127
+ }
128
+ if (queryEmbedding?.length) {
129
+ const search = await client.search({
130
+ collection_name: SPOTLIGHT_MILVUS_SEMANTIC_COLLECTION,
131
+ data: [queryEmbedding],
132
+ limit: Math.max(limit, 8),
133
+ filter: `project_id == "${escapeMilvusExpr(projectId)}" && tenant_id == "${escapeMilvusExpr(this.tenantId)}"`,
134
+ output_fields: ["entry_json", "question_norm"],
135
+ });
136
+ const hits = search.results ?? [];
137
+ const scored = [];
138
+ for (const hit of hits) {
139
+ const entryJson = String(hit.entry_json ?? "");
140
+ let entry;
141
+ try {
142
+ entry = JSON.parse(entryJson);
143
+ }
144
+ catch {
145
+ continue;
146
+ }
147
+ const lexical = scoreQuestionSimilarity(questionNorm, entry.questionNorm);
148
+ const vectorScore = typeof hit.score === "number"
149
+ ? Math.max(0, Math.min(1, (hit.score + 1) / 2))
150
+ : 0;
151
+ const score = Math.max(lexical, vectorScore);
152
+ if (score <= 0)
153
+ continue;
154
+ scored.push({ entry, score });
155
+ }
156
+ scored.sort((a, b) => b.score - a.score);
157
+ return scored.slice(0, limit);
158
+ }
159
+ return this.findSimilarLexical(projectId, questionNorm, limit);
160
+ }
161
+ async findSimilarLexical(projectId, questionNorm, limit) {
162
+ const client = await getSpotlightMilvusClient();
163
+ if (!client)
164
+ return [];
165
+ const query = await client.query({
166
+ collection_name: SPOTLIGHT_MILVUS_SEMANTIC_COLLECTION,
167
+ filter: `project_id == "${escapeMilvusExpr(projectId)}" && tenant_id == "${escapeMilvusExpr(this.tenantId)}"`,
168
+ output_fields: ["entry_json", "question_norm"],
169
+ limit: 200,
170
+ });
171
+ const scored = [];
172
+ for (const row of query.data ?? []) {
173
+ try {
174
+ const entry = JSON.parse(String(row.entry_json));
175
+ const score = scoreQuestionSimilarity(questionNorm, entry.questionNorm);
176
+ if (score <= 0)
177
+ continue;
178
+ scored.push({ entry, score });
179
+ }
180
+ catch {
181
+ continue;
182
+ }
183
+ }
184
+ scored.sort((a, b) => b.score - a.score);
185
+ return scored.slice(0, limit);
186
+ }
187
+ async touch(entryId) {
188
+ const client = await getSpotlightMilvusClient();
189
+ if (!client)
190
+ return;
191
+ const query = await client.query({
192
+ collection_name: SPOTLIGHT_MILVUS_SEMANTIC_COLLECTION,
193
+ filter: `id == "${escapeMilvusExpr(entryId)}"`,
194
+ output_fields: ["id", "project_id", "tenant_id", "question_norm", "entry_json", "embedding"],
195
+ limit: 1,
196
+ });
197
+ const row = query.data?.[0];
198
+ if (!row)
199
+ return;
200
+ try {
201
+ const entry = JSON.parse(String(row.entry_json));
202
+ entry.hitCount += 1;
203
+ entry.lastHitAt = Date.now();
204
+ await this.put(entry, row.embedding);
205
+ }
206
+ catch {
207
+ /* ignore */
208
+ }
209
+ }
210
+ listEntries(limit = 50) {
211
+ void limit;
212
+ return [];
213
+ }
214
+ deleteEntry(entryId) {
215
+ void entryId;
216
+ return false;
217
+ }
218
+ deleteAll(_projectId) {
219
+ return 0;
220
+ }
221
+ count(projectId) {
222
+ void projectId;
223
+ return 0;
224
+ }
225
+ }
226
+ function escapeMilvusExpr(value) {
227
+ return value.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
228
+ }
@@ -0,0 +1,10 @@
1
+ import type { Redis } from "ioredis";
2
+ export declare function readSpotlightRedisKeyPrefix(): string;
3
+ export declare function spotlightRedisKey(...parts: string[]): string;
4
+ export declare function resolveSpotlightRedisUrl(): string | null;
5
+ export declare function isSpotlightRedisConfigured(): boolean;
6
+ /** Spotlight 专用 Redis(建议 DB index 2+,与 Yuxi ARQ/run 的 DB 0 隔离)。 */
7
+ export declare function getSpotlightRedisClient(): Promise<Redis | null>;
8
+ export declare function closeSpotlightRedisClient(): Promise<void>;
9
+ export declare function resetSpotlightRedisClientForTests(): void;
10
+ //# sourceMappingURL=redisClient.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"redisClient.d.ts","sourceRoot":"","sources":["../../src/node/redisClient.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,SAAS,CAAC;AAKrC,wBAAgB,2BAA2B,IAAI,MAAM,CAGpD;AAED,wBAAgB,iBAAiB,CAAC,GAAG,KAAK,EAAE,MAAM,EAAE,GAAG,MAAM,CAE5D;AAED,wBAAgB,wBAAwB,IAAI,MAAM,GAAG,IAAI,CAGxD;AAED,wBAAgB,0BAA0B,IAAI,OAAO,CAEpD;AAED,mEAAmE;AACnE,wBAAsB,uBAAuB,IAAI,OAAO,CAAC,KAAK,GAAG,IAAI,CAAC,CAkBrE;AAED,wBAAsB,yBAAyB,IAAI,OAAO,CAAC,IAAI,CAAC,CAM/D;AAED,wBAAgB,iCAAiC,IAAI,IAAI,CAGxD"}
@@ -0,0 +1,49 @@
1
+ let client = null;
2
+ let clientPromise = null;
3
+ export function readSpotlightRedisKeyPrefix() {
4
+ const raw = process.env.SPOTLIGHT_REDIS_KEY_PREFIX?.trim();
5
+ return raw && raw.endsWith(":") ? raw : raw ? `${raw}:` : "spotlight:";
6
+ }
7
+ export function spotlightRedisKey(...parts) {
8
+ return `${readSpotlightRedisKeyPrefix()}${parts.join(":")}`;
9
+ }
10
+ export function resolveSpotlightRedisUrl() {
11
+ const url = process.env.SPOTLIGHT_REDIS_URL?.trim();
12
+ return url || null;
13
+ }
14
+ export function isSpotlightRedisConfigured() {
15
+ return Boolean(resolveSpotlightRedisUrl());
16
+ }
17
+ /** Spotlight 专用 Redis(建议 DB index 2+,与 Yuxi ARQ/run 的 DB 0 隔离)。 */
18
+ export async function getSpotlightRedisClient() {
19
+ const url = resolveSpotlightRedisUrl();
20
+ if (!url)
21
+ return null;
22
+ if (client)
23
+ return client;
24
+ if (!clientPromise) {
25
+ clientPromise = (async () => {
26
+ const { default: RedisCtor } = await import("ioredis");
27
+ const redis = new RedisCtor(url, {
28
+ maxRetriesPerRequest: 2,
29
+ lazyConnect: true,
30
+ enableOfflineQueue: false,
31
+ });
32
+ await redis.connect();
33
+ client = redis;
34
+ return redis;
35
+ })().catch(() => null);
36
+ }
37
+ return clientPromise;
38
+ }
39
+ export async function closeSpotlightRedisClient() {
40
+ if (client) {
41
+ await client.quit();
42
+ client = null;
43
+ clientPromise = null;
44
+ }
45
+ }
46
+ export function resetSpotlightRedisClientForTests() {
47
+ client = null;
48
+ clientPromise = null;
49
+ }
@@ -0,0 +1,23 @@
1
+ import type { SpotlightMemoryEntry } from "@inupedia/spotlight-protocol";
2
+ export interface RedisExactMemoryStoreOptions {
3
+ projectId: string;
4
+ tenantId?: string;
5
+ lruMax?: number;
6
+ }
7
+ /** L0 exact cache in Redis (SETEX + sorted index for LRU cap). */
8
+ export declare class RedisExactMemoryStore {
9
+ readonly projectId: string;
10
+ private readonly tenantId?;
11
+ private readonly lruMax;
12
+ constructor(options: RedisExactMemoryStoreOptions);
13
+ static isAvailable(): boolean;
14
+ private ttlSec;
15
+ getExact(cacheKey: string): Promise<SpotlightMemoryEntry | null>;
16
+ hasExact(cacheKey: string): Promise<boolean>;
17
+ putExact(cacheKey: string, entry: SpotlightMemoryEntry): Promise<void>;
18
+ touch(entryId: string): Promise<void>;
19
+ listEntries(limit?: number): SpotlightMemoryEntry[];
20
+ deleteEntry(_entryId: string): boolean;
21
+ deleteAll(_projectId: string): number;
22
+ }
23
+ //# sourceMappingURL=redisExactStore.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"redisExactStore.d.ts","sourceRoot":"","sources":["../../src/node/redisExactStore.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,8BAA8B,CAAC;AAOzE,MAAM,WAAW,4BAA4B;IAC3C,SAAS,EAAE,MAAM,CAAC;IAClB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAgBD,kEAAkE;AAClE,qBAAa,qBAAqB;IAChC,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAS;IACnC,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAS;gBAEpB,OAAO,EAAE,4BAA4B;IAMjD,MAAM,CAAC,WAAW,IAAI,OAAO;IAI7B,OAAO,CAAC,MAAM;IAKR,QAAQ,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,oBAAoB,GAAG,IAAI,CAAC;IAoBhE,QAAQ,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;IAQ5C,QAAQ,CACZ,QAAQ,EAAE,MAAM,EAChB,KAAK,EAAE,oBAAoB,GAC1B,OAAO,CAAC,IAAI,CAAC;IAuBV,KAAK,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IA6B3C,WAAW,CAAC,KAAK,SAAK,GAAG,oBAAoB,EAAE;IAK/C,WAAW,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO;IAItC,SAAS,CAAC,UAAU,EAAE,MAAM,GAAG,MAAM;CAGtC"}
@@ -0,0 +1,115 @@
1
+ import { getSpotlightRedisClient, isSpotlightRedisConfigured, spotlightRedisKey, } from "./redisClient.js";
2
+ function exactKey(projectId, tenantId, cacheKey) {
3
+ const tenant = tenantId?.trim() || "default";
4
+ return spotlightRedisKey("gate", "exact", tenant, projectId, cacheKey);
5
+ }
6
+ function indexKey(projectId, tenantId) {
7
+ const tenant = tenantId?.trim() || "default";
8
+ return spotlightRedisKey("gate", "exact-index", tenant, projectId);
9
+ }
10
+ /** L0 exact cache in Redis (SETEX + sorted index for LRU cap). */
11
+ export class RedisExactMemoryStore {
12
+ projectId;
13
+ tenantId;
14
+ lruMax;
15
+ constructor(options) {
16
+ this.projectId = options.projectId;
17
+ this.tenantId = options.tenantId;
18
+ this.lruMax = options.lruMax ?? 500;
19
+ }
20
+ static isAvailable() {
21
+ return isSpotlightRedisConfigured();
22
+ }
23
+ ttlSec(entry) {
24
+ const ttl = entry.ttlSec > 0 ? entry.ttlSec : 86_400;
25
+ return Math.max(300, Math.min(ttl, 86_400));
26
+ }
27
+ async getExact(cacheKey) {
28
+ const redis = await getSpotlightRedisClient();
29
+ if (!redis)
30
+ return null;
31
+ const raw = await redis.get(exactKey(this.projectId, this.tenantId, cacheKey));
32
+ if (!raw)
33
+ return null;
34
+ try {
35
+ const entry = JSON.parse(raw);
36
+ await redis.zadd(indexKey(this.projectId, this.tenantId), Date.now(), cacheKey);
37
+ return entry;
38
+ }
39
+ catch {
40
+ return null;
41
+ }
42
+ }
43
+ async hasExact(cacheKey) {
44
+ const redis = await getSpotlightRedisClient();
45
+ if (!redis)
46
+ return false;
47
+ return (await redis.exists(exactKey(this.projectId, this.tenantId, cacheKey))) === 1;
48
+ }
49
+ async putExact(cacheKey, entry) {
50
+ const redis = await getSpotlightRedisClient();
51
+ if (!redis)
52
+ return;
53
+ const key = exactKey(this.projectId, this.tenantId, cacheKey);
54
+ const ttl = this.ttlSec(entry);
55
+ await redis.set(key, JSON.stringify(entry), "EX", ttl);
56
+ const index = indexKey(this.projectId, this.tenantId);
57
+ await redis.zadd(index, Date.now(), cacheKey);
58
+ const count = await redis.zcard(index);
59
+ if (count > this.lruMax) {
60
+ const evictCount = count - this.lruMax;
61
+ const staleKeys = await redis.zrange(index, 0, evictCount - 1);
62
+ if (staleKeys.length) {
63
+ const pipeline = redis.pipeline();
64
+ for (const cacheKey of staleKeys) {
65
+ pipeline.del(exactKey(this.projectId, this.tenantId, cacheKey));
66
+ pipeline.zrem(index, cacheKey);
67
+ }
68
+ await pipeline.exec();
69
+ }
70
+ }
71
+ }
72
+ async touch(entryId) {
73
+ const redis = await getSpotlightRedisClient();
74
+ if (!redis)
75
+ return;
76
+ const pattern = spotlightRedisKey("gate", "exact", "*");
77
+ void pattern;
78
+ const index = indexKey(this.projectId, this.tenantId);
79
+ const cacheKeys = await redis.zrange(index, 0, -1);
80
+ for (const cacheKey of cacheKeys) {
81
+ const key = exactKey(this.projectId, this.tenantId, cacheKey);
82
+ const raw = await redis.get(key);
83
+ if (!raw)
84
+ continue;
85
+ try {
86
+ const entry = JSON.parse(raw);
87
+ if (entry.id !== entryId)
88
+ continue;
89
+ entry.hitCount += 1;
90
+ entry.lastHitAt = Date.now();
91
+ const ttl = await redis.ttl(key);
92
+ if (ttl > 0) {
93
+ await redis.set(key, JSON.stringify(entry), "EX", ttl);
94
+ }
95
+ else {
96
+ await redis.set(key, JSON.stringify(entry), "EX", this.ttlSec(entry));
97
+ }
98
+ return;
99
+ }
100
+ catch {
101
+ continue;
102
+ }
103
+ }
104
+ }
105
+ listEntries(limit = 50) {
106
+ void limit;
107
+ return [];
108
+ }
109
+ deleteEntry(_entryId) {
110
+ return false;
111
+ }
112
+ deleteAll(_projectId) {
113
+ return 0;
114
+ }
115
+ }
package/dist/ttl.d.ts ADDED
@@ -0,0 +1,4 @@
1
+ /** Hard upper bound for any memory entry TTL (24 hours). */
2
+ export declare const MEMORY_TTL_MAX_SEC = 86400;
3
+ export declare function clampMemoryTtlSec(ttlSec: number): number;
4
+ //# sourceMappingURL=ttl.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ttl.d.ts","sourceRoot":"","sources":["../src/ttl.ts"],"names":[],"mappings":"AAAA,4DAA4D;AAC5D,eAAO,MAAM,kBAAkB,QAAS,CAAC;AAEzC,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CAGxD"}
package/dist/ttl.js ADDED
@@ -0,0 +1,7 @@
1
+ /** Hard upper bound for any memory entry TTL (24 hours). */
2
+ export const MEMORY_TTL_MAX_SEC = 86_400;
3
+ export function clampMemoryTtlSec(ttlSec) {
4
+ if (!Number.isFinite(ttlSec))
5
+ return 0;
6
+ return Math.max(0, Math.min(Math.floor(ttlSec), MEMORY_TTL_MAX_SEC));
7
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@inupedia/spotlight-memory",
3
- "version": "0.1.9",
3
+ "version": "0.2.0",
4
4
  "description": "Memory Gate, exact/semantic cache stores for Inupedia Spotlight",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -24,7 +24,9 @@
24
24
  "dist"
25
25
  ],
26
26
  "dependencies": {
27
- "@inupedia/spotlight-protocol": "0.1.9"
27
+ "@zilliz/milvus2-sdk-node": "^2.5.5",
28
+ "ioredis": "^5.6.1",
29
+ "@inupedia/spotlight-protocol": "0.2.0"
28
30
  },
29
31
  "devDependencies": {
30
32
  "@types/node": "^22.10.0",