@inupedia/spotlight-memory 0.1.5
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/README.md +71 -0
- package/dist/classify.d.ts +15 -0
- package/dist/classify.d.ts.map +1 -0
- package/dist/classify.js +30 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +4 -0
- package/dist/node/cacheKey.d.ts +10 -0
- package/dist/node/cacheKey.d.ts.map +1 -0
- package/dist/node/cacheKey.js +13 -0
- package/dist/node/embeddingProvider.d.ts +7 -0
- package/dist/node/embeddingProvider.d.ts.map +1 -0
- package/dist/node/embeddingProvider.js +51 -0
- package/dist/node/exactStore.d.ts +28 -0
- package/dist/node/exactStore.d.ts.map +1 -0
- package/dist/node/exactStore.js +122 -0
- package/dist/node/gate.d.ts +26 -0
- package/dist/node/gate.d.ts.map +1 -0
- package/dist/node/gate.js +119 -0
- package/dist/node/index.d.ts +25 -0
- package/dist/node/index.d.ts.map +1 -0
- package/dist/node/index.js +48 -0
- package/dist/node/meta.d.ts +9 -0
- package/dist/node/meta.d.ts.map +1 -0
- package/dist/node/meta.js +26 -0
- package/dist/node/paths.d.ts +21 -0
- package/dist/node/paths.d.ts.map +1 -0
- package/dist/node/paths.js +23 -0
- package/dist/node/semanticStore.d.ts +25 -0
- package/dist/node/semanticStore.d.ts.map +1 -0
- package/dist/node/semanticStore.js +146 -0
- package/dist/normalize.d.ts +5 -0
- package/dist/normalize.d.ts.map +1 -0
- package/dist/normalize.js +37 -0
- package/dist/similarity.d.ts +3 -0
- package/dist/similarity.d.ts.map +1 -0
- package/dist/similarity.js +17 -0
- package/dist/stale.d.ts +7 -0
- package/dist/stale.d.ts.map +1 -0
- package/dist/stale.js +29 -0
- package/package.json +41 -0
package/README.md
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
# @inupedia/spotlight-memory
|
|
2
|
+
|
|
3
|
+
Spotlight **Memory Gate** — exact + semantic cache for repeated user questions.
|
|
4
|
+
|
|
5
|
+
Part of the Inupedia Spotlight SDK. See `docs/SPOTLIGHT_MEMORY_ARCHITECTURE.md` in the host repo.
|
|
6
|
+
|
|
7
|
+
## Role
|
|
8
|
+
|
|
9
|
+
| Layer | Storage | Package API |
|
|
10
|
+
|-------|---------|-------------|
|
|
11
|
+
| L0 Exact | `packs/<id>/memory/exact/` | `ExactMemoryStore` |
|
|
12
|
+
| L1 Semantic | `packs/<id>/memory/semantic/` (Phase 3) | `findSemantic` (MVP: bigram scan) |
|
|
13
|
+
| Gate | — | `createMemoryGate` |
|
|
14
|
+
|
|
15
|
+
## Install
|
|
16
|
+
|
|
17
|
+
```bash
|
|
18
|
+
pnpm add @inupedia/spotlight-memory @inupedia/spotlight-protocol
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
## Usage (spotlight-server)
|
|
22
|
+
|
|
23
|
+
```typescript
|
|
24
|
+
import { createPackMemoryStores } from "@inupedia/spotlight-memory/node";
|
|
25
|
+
|
|
26
|
+
const { gate } = createPackMemoryStores({
|
|
27
|
+
packsRoot: "/app/packs",
|
|
28
|
+
projectId: "ydjm-construction-map",
|
|
29
|
+
gateConfig: { semanticThreshold: 0.92 },
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
// Gate 0 — before deterministic gate
|
|
33
|
+
const result = await gate.lookup({
|
|
34
|
+
projectId,
|
|
35
|
+
question: request.userQuestion,
|
|
36
|
+
invalidation: {
|
|
37
|
+
assetsVersion: assetsMeta.version,
|
|
38
|
+
catalogVersion: catalogHash,
|
|
39
|
+
},
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
if (result.hit) {
|
|
43
|
+
return replayMemoryHit(result.result, sink);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// After slow path succeeds:
|
|
47
|
+
await gate.write({
|
|
48
|
+
projectId,
|
|
49
|
+
question: request.userQuestion,
|
|
50
|
+
kind: "qa_answer",
|
|
51
|
+
answer: finalReply,
|
|
52
|
+
invalidation: { assetsVersion, catalogVersion },
|
|
53
|
+
confidence: 0.9,
|
|
54
|
+
sourceRunId: run.id,
|
|
55
|
+
});
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
## Exports
|
|
59
|
+
|
|
60
|
+
| Entry | Runtime | Purpose |
|
|
61
|
+
|-------|---------|---------|
|
|
62
|
+
| `@inupedia/spotlight-memory` | isomorphic | normalize, classify, gate factory |
|
|
63
|
+
| `@inupedia/spotlight-memory/node` | Node | pack paths, exact jsonl store |
|
|
64
|
+
|
|
65
|
+
## Build
|
|
66
|
+
|
|
67
|
+
```bash
|
|
68
|
+
pnpm install
|
|
69
|
+
pnpm build
|
|
70
|
+
pnpm test
|
|
71
|
+
```
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { SpotlightMemoryEntryKind } from "@inupedia/spotlight-protocol";
|
|
2
|
+
export interface ClassifyMemoryKindInput {
|
|
3
|
+
question: string;
|
|
4
|
+
hasToolPlan: boolean;
|
|
5
|
+
hasTextAnswer: boolean;
|
|
6
|
+
usedDataTools: boolean;
|
|
7
|
+
}
|
|
8
|
+
export interface ClassifyMemoryKindResult {
|
|
9
|
+
kind: SpotlightMemoryEntryKind | null;
|
|
10
|
+
blockedReason?: "realtime_data" | "no_durable_output";
|
|
11
|
+
}
|
|
12
|
+
/** Decide whether and how to cache a completed turn. */
|
|
13
|
+
export declare function classifyMemoryKind(input: ClassifyMemoryKindInput): ClassifyMemoryKindResult;
|
|
14
|
+
export declare function isMemoryKindAllowedForRead(kind: SpotlightMemoryEntryKind): boolean;
|
|
15
|
+
//# sourceMappingURL=classify.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"classify.d.ts","sourceRoot":"","sources":["../src/classify.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,8BAA8B,CAAC;AAW7E,MAAM,WAAW,uBAAuB;IACtC,QAAQ,EAAE,MAAM,CAAC;IACjB,WAAW,EAAE,OAAO,CAAC;IACrB,aAAa,EAAE,OAAO,CAAC;IACvB,aAAa,EAAE,OAAO,CAAC;CACxB;AAED,MAAM,WAAW,wBAAwB;IACvC,IAAI,EAAE,wBAAwB,GAAG,IAAI,CAAC;IACtC,aAAa,CAAC,EAAE,eAAe,GAAG,mBAAmB,CAAC;CACvD;AAED,wDAAwD;AACxD,wBAAgB,kBAAkB,CAChC,KAAK,EAAE,uBAAuB,GAC7B,wBAAwB,CA0B1B;AAED,wBAAgB,0BAA0B,CACxC,IAAI,EAAE,wBAAwB,GAC7B,OAAO,CAET"}
|
package/dist/classify.js
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
const REALTIME_PATTERN = /(今天|今日|现在|当前|最新|实时|刚才|刚刚|this moment|right now|today)/i;
|
|
2
|
+
const DATA_PATTERN = /(多少|几米|几个|统计|数据|进度|掘进|完成率|清单|列表|有哪些|有多少)/;
|
|
3
|
+
const ACTION_PATTERN = /(打开|开启|进入|切换到|显示|启动|开始|暂停|停止|继续)/;
|
|
4
|
+
/** Decide whether and how to cache a completed turn. */
|
|
5
|
+
export function classifyMemoryKind(input) {
|
|
6
|
+
const q = input.question.trim();
|
|
7
|
+
if (!q)
|
|
8
|
+
return { kind: null, blockedReason: "no_durable_output" };
|
|
9
|
+
if (input.hasToolPlan && !input.hasTextAnswer) {
|
|
10
|
+
return { kind: "action_plan" };
|
|
11
|
+
}
|
|
12
|
+
if (input.usedDataTools || DATA_PATTERN.test(q)) {
|
|
13
|
+
if (REALTIME_PATTERN.test(q)) {
|
|
14
|
+
return { kind: null, blockedReason: "realtime_data" };
|
|
15
|
+
}
|
|
16
|
+
if (input.hasTextAnswer) {
|
|
17
|
+
return { kind: "data_snapshot" };
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
if (input.hasTextAnswer && !ACTION_PATTERN.test(q)) {
|
|
21
|
+
return { kind: "qa_answer" };
|
|
22
|
+
}
|
|
23
|
+
if (input.hasToolPlan) {
|
|
24
|
+
return { kind: "action_plan" };
|
|
25
|
+
}
|
|
26
|
+
return { kind: null, blockedReason: "no_durable_output" };
|
|
27
|
+
}
|
|
28
|
+
export function isMemoryKindAllowedForRead(kind) {
|
|
29
|
+
return kind !== "routing_hint";
|
|
30
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export { classifyMemoryKind, isMemoryKindAllowedForRead, type ClassifyMemoryKindInput, type ClassifyMemoryKindResult, } from "./classify.js";
|
|
2
|
+
export { normalizeQuestion, scoreQuestionSimilarity, } from "./normalize.js";
|
|
3
|
+
export { isMemoryEntryStale, pickSemanticHit } from "./stale.js";
|
|
4
|
+
export { cosineSimilarity } from "./similarity.js";
|
|
5
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +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"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export { classifyMemoryKind, isMemoryKindAllowedForRead, } from "./classify.js";
|
|
2
|
+
export { normalizeQuestion, scoreQuestionSimilarity, } from "./normalize.js";
|
|
3
|
+
export { isMemoryEntryStale, pickSemanticHit } from "./stale.js";
|
|
4
|
+
export { cosineSimilarity } from "./similarity.js";
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export declare function buildCacheKey(params: {
|
|
2
|
+
projectId: string;
|
|
3
|
+
questionNorm: string;
|
|
4
|
+
invalidation: {
|
|
5
|
+
assetsVersion?: string | null;
|
|
6
|
+
catalogVersion?: string | null;
|
|
7
|
+
};
|
|
8
|
+
}): string;
|
|
9
|
+
export declare function createMemoryEntryId(): string;
|
|
10
|
+
//# sourceMappingURL=cacheKey.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cacheKey.d.ts","sourceRoot":"","sources":["../../src/node/cacheKey.ts"],"names":[],"mappings":"AAEA,wBAAgB,aAAa,CAAC,MAAM,EAAE;IACpC,SAAS,EAAE,MAAM,CAAC;IAClB,YAAY,EAAE,MAAM,CAAC;IACrB,YAAY,EAAE;QACZ,aAAa,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;QAC9B,cAAc,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;KAChC,CAAC;CACH,GAAG,MAAM,CAQT;AAED,wBAAgB,mBAAmB,IAAI,MAAM,CAE5C"}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
+
export function buildCacheKey(params) {
|
|
3
|
+
const payload = [
|
|
4
|
+
params.projectId,
|
|
5
|
+
params.questionNorm,
|
|
6
|
+
params.invalidation.assetsVersion ?? "",
|
|
7
|
+
params.invalidation.catalogVersion ?? "",
|
|
8
|
+
].join("\0");
|
|
9
|
+
return createHash("sha256").update(payload).digest("hex");
|
|
10
|
+
}
|
|
11
|
+
export function createMemoryEntryId() {
|
|
12
|
+
return `mem-${Date.now()}-${randomUUID().slice(0, 8)}`;
|
|
13
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export interface EmbeddingProvider {
|
|
2
|
+
readonly name: string;
|
|
3
|
+
embed(text: string): Promise<number[] | null>;
|
|
4
|
+
}
|
|
5
|
+
export declare function resolveEmbeddingProviderFromEnv(): EmbeddingProvider | null;
|
|
6
|
+
export declare function scoreEmbeddingPair(query: number[] | null | undefined, stored: number[] | null | undefined): number;
|
|
7
|
+
//# sourceMappingURL=embeddingProvider.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"embeddingProvider.d.ts","sourceRoot":"","sources":["../../src/node/embeddingProvider.ts"],"names":[],"mappings":"AAEA,MAAM,WAAW,iBAAiB;IAChC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,KAAK,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,EAAE,GAAG,IAAI,CAAC,CAAC;CAC/C;AAED,wBAAgB,+BAA+B,IAAI,iBAAiB,GAAG,IAAI,CAO1E;AA6CD,wBAAgB,kBAAkB,CAChC,KAAK,EAAE,MAAM,EAAE,GAAG,IAAI,GAAG,SAAS,EAClC,MAAM,EAAE,MAAM,EAAE,GAAG,IAAI,GAAG,SAAS,GAClC,MAAM,CAGR"}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { cosineSimilarity } from "../similarity.js";
|
|
2
|
+
export function resolveEmbeddingProviderFromEnv() {
|
|
3
|
+
const raw = process.env.SPOTLIGHT_MEMORY_EMBEDDING_PROVIDER?.trim().toLowerCase();
|
|
4
|
+
if (!raw || raw === "none" || raw === "off" || raw === "0")
|
|
5
|
+
return null;
|
|
6
|
+
if (raw === "siliconflow" || raw === "openai") {
|
|
7
|
+
return createHttpEmbeddingProvider(raw);
|
|
8
|
+
}
|
|
9
|
+
return null;
|
|
10
|
+
}
|
|
11
|
+
function createHttpEmbeddingProvider(vendor) {
|
|
12
|
+
const apiKey = vendor === "siliconflow"
|
|
13
|
+
? process.env.SILICONFLOW_API_KEY?.trim()
|
|
14
|
+
: process.env.OPENAI_API_KEY?.trim();
|
|
15
|
+
if (!apiKey)
|
|
16
|
+
return null;
|
|
17
|
+
const apiBase = vendor === "siliconflow"
|
|
18
|
+
? (process.env.SILICONFLOW_API_BASE?.trim() ??
|
|
19
|
+
"https://api.siliconflow.cn/v1")
|
|
20
|
+
: (process.env.OPENAI_API_BASE?.trim() ?? "https://api.openai.com/v1");
|
|
21
|
+
const model = process.env.SPOTLIGHT_MEMORY_EMBEDDING_MODEL?.trim() ??
|
|
22
|
+
(vendor === "siliconflow"
|
|
23
|
+
? "BAAI/bge-large-zh-v1.5"
|
|
24
|
+
: "text-embedding-3-small");
|
|
25
|
+
return {
|
|
26
|
+
name: vendor,
|
|
27
|
+
async embed(text) {
|
|
28
|
+
const input = text.trim();
|
|
29
|
+
if (!input)
|
|
30
|
+
return null;
|
|
31
|
+
const response = await fetch(`${apiBase.replace(/\/$/, "")}/embeddings`, {
|
|
32
|
+
method: "POST",
|
|
33
|
+
headers: {
|
|
34
|
+
Authorization: `Bearer ${apiKey}`,
|
|
35
|
+
"Content-Type": "application/json",
|
|
36
|
+
},
|
|
37
|
+
body: JSON.stringify({ model, input }),
|
|
38
|
+
});
|
|
39
|
+
if (!response.ok)
|
|
40
|
+
return null;
|
|
41
|
+
const payload = (await response.json());
|
|
42
|
+
const embedding = payload.data?.[0]?.embedding;
|
|
43
|
+
return Array.isArray(embedding) && embedding.length > 0 ? embedding : null;
|
|
44
|
+
},
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
export function scoreEmbeddingPair(query, stored) {
|
|
48
|
+
if (!query?.length || !stored?.length)
|
|
49
|
+
return 0;
|
|
50
|
+
return cosineSimilarity(query, stored);
|
|
51
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import type { SpotlightMemoryEntry } from "@inupedia/spotlight-protocol";
|
|
2
|
+
import type { PackMemoryPaths } from "./paths.js";
|
|
3
|
+
export interface ExactMemoryStoreOptions {
|
|
4
|
+
paths: PackMemoryPaths;
|
|
5
|
+
lruMax?: number;
|
|
6
|
+
}
|
|
7
|
+
/** L0 exact cache: jsonl persistence + in-process LRU + index.json. */
|
|
8
|
+
export declare class ExactMemoryStore {
|
|
9
|
+
private readonly paths;
|
|
10
|
+
private readonly lruMax;
|
|
11
|
+
private index;
|
|
12
|
+
private entries;
|
|
13
|
+
private lruKeys;
|
|
14
|
+
constructor(options: ExactMemoryStoreOptions);
|
|
15
|
+
private loadFromDisk;
|
|
16
|
+
private persistIndex;
|
|
17
|
+
private appendEntry;
|
|
18
|
+
private touchLru;
|
|
19
|
+
getExact(cacheKey: string): Promise<SpotlightMemoryEntry | null>;
|
|
20
|
+
hasExact(cacheKey: string): Promise<boolean>;
|
|
21
|
+
putExact(cacheKey: string, entry: SpotlightMemoryEntry): Promise<void>;
|
|
22
|
+
touch(entryId: string): Promise<void>;
|
|
23
|
+
listEntries(limit?: number): SpotlightMemoryEntry[];
|
|
24
|
+
deleteEntry(entryId: string): boolean;
|
|
25
|
+
deleteAll(projectId: string): number;
|
|
26
|
+
private rewriteEntriesFile;
|
|
27
|
+
}
|
|
28
|
+
//# sourceMappingURL=exactStore.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"exactStore.d.ts","sourceRoot":"","sources":["../../src/node/exactStore.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,8BAA8B,CAAC;AACzE,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAIlD,MAAM,WAAW,uBAAuB;IACtC,KAAK,EAAE,eAAe,CAAC;IACvB,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAED,uEAAuE;AACvE,qBAAa,gBAAgB;IAC3B,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAkB;IACxC,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAS;IAChC,OAAO,CAAC,KAAK,CAAkB;IAC/B,OAAO,CAAC,OAAO,CAA2C;IAC1D,OAAO,CAAC,OAAO,CAAgB;gBAEnB,OAAO,EAAE,uBAAuB;IAM5C,OAAO,CAAC,YAAY;IAyBpB,OAAO,CAAC,YAAY;IASpB,OAAO,CAAC,WAAW;IASnB,OAAO,CAAC,QAAQ;IAcV,QAAQ,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,oBAAoB,GAAG,IAAI,CAAC;IAQhE,QAAQ,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;IAI5C,QAAQ,CACZ,QAAQ,EAAE,MAAM,EAChB,KAAK,EAAE,oBAAoB,GAC1B,OAAO,CAAC,IAAI,CAAC;IAQV,KAAK,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAO3C,WAAW,CAAC,KAAK,SAAK,GAAG,oBAAoB,EAAE;IAQ/C,WAAW,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO;IAYrC,SAAS,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM;IAWpC,OAAO,CAAC,kBAAkB;CAS3B"}
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync, } from "node:fs";
|
|
2
|
+
/** L0 exact cache: jsonl persistence + in-process LRU + index.json. */
|
|
3
|
+
export class ExactMemoryStore {
|
|
4
|
+
paths;
|
|
5
|
+
lruMax;
|
|
6
|
+
index = {};
|
|
7
|
+
entries = new Map();
|
|
8
|
+
lruKeys = [];
|
|
9
|
+
constructor(options) {
|
|
10
|
+
this.paths = options.paths;
|
|
11
|
+
this.lruMax = options.lruMax ?? 500;
|
|
12
|
+
this.loadFromDisk();
|
|
13
|
+
}
|
|
14
|
+
loadFromDisk() {
|
|
15
|
+
mkdirSync(this.paths.exactDir, { recursive: true });
|
|
16
|
+
if (existsSync(this.paths.exactIndexPath)) {
|
|
17
|
+
try {
|
|
18
|
+
this.index = JSON.parse(readFileSync(this.paths.exactIndexPath, "utf8"));
|
|
19
|
+
}
|
|
20
|
+
catch {
|
|
21
|
+
this.index = {};
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
if (!existsSync(this.paths.exactEntriesPath))
|
|
25
|
+
return;
|
|
26
|
+
const lines = readFileSync(this.paths.exactEntriesPath, "utf8")
|
|
27
|
+
.split("\n")
|
|
28
|
+
.filter(Boolean);
|
|
29
|
+
for (const line of lines) {
|
|
30
|
+
try {
|
|
31
|
+
const entry = JSON.parse(line);
|
|
32
|
+
this.entries.set(entry.id, entry);
|
|
33
|
+
}
|
|
34
|
+
catch {
|
|
35
|
+
/* skip corrupt line */
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
persistIndex() {
|
|
40
|
+
mkdirSync(this.paths.exactDir, { recursive: true });
|
|
41
|
+
writeFileSync(this.paths.exactIndexPath, JSON.stringify(this.index, null, 2), "utf8");
|
|
42
|
+
}
|
|
43
|
+
appendEntry(entry) {
|
|
44
|
+
mkdirSync(this.paths.exactDir, { recursive: true });
|
|
45
|
+
appendFileSync(this.paths.exactEntriesPath, `${JSON.stringify(entry)}\n`, "utf8");
|
|
46
|
+
}
|
|
47
|
+
touchLru(cacheKey) {
|
|
48
|
+
this.lruKeys = this.lruKeys.filter((k) => k !== cacheKey);
|
|
49
|
+
this.lruKeys.unshift(cacheKey);
|
|
50
|
+
while (this.lruKeys.length > this.lruMax) {
|
|
51
|
+
const evicted = this.lruKeys.pop();
|
|
52
|
+
if (!evicted)
|
|
53
|
+
break;
|
|
54
|
+
const entryId = this.index[evicted];
|
|
55
|
+
if (entryId) {
|
|
56
|
+
delete this.index[evicted];
|
|
57
|
+
this.entries.delete(entryId);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
async getExact(cacheKey) {
|
|
62
|
+
const entryId = this.index[cacheKey];
|
|
63
|
+
if (!entryId)
|
|
64
|
+
return null;
|
|
65
|
+
const entry = this.entries.get(entryId) ?? null;
|
|
66
|
+
if (entry)
|
|
67
|
+
this.touchLru(cacheKey);
|
|
68
|
+
return entry;
|
|
69
|
+
}
|
|
70
|
+
async hasExact(cacheKey) {
|
|
71
|
+
return Boolean(this.index[cacheKey]);
|
|
72
|
+
}
|
|
73
|
+
async putExact(cacheKey, entry) {
|
|
74
|
+
this.index[cacheKey] = entry.id;
|
|
75
|
+
this.entries.set(entry.id, entry);
|
|
76
|
+
this.touchLru(cacheKey);
|
|
77
|
+
this.persistIndex();
|
|
78
|
+
this.appendEntry(entry);
|
|
79
|
+
}
|
|
80
|
+
async touch(entryId) {
|
|
81
|
+
const entry = this.entries.get(entryId);
|
|
82
|
+
if (!entry)
|
|
83
|
+
return;
|
|
84
|
+
entry.hitCount += 1;
|
|
85
|
+
entry.lastHitAt = Date.now();
|
|
86
|
+
}
|
|
87
|
+
listEntries(limit = 50) {
|
|
88
|
+
const safeLimit = Number.isFinite(limit) && limit > 0 ? Math.min(500, Math.floor(limit)) : 50;
|
|
89
|
+
return [...this.entries.values()]
|
|
90
|
+
.sort((a, b) => b.createdAt - a.createdAt)
|
|
91
|
+
.slice(0, safeLimit);
|
|
92
|
+
}
|
|
93
|
+
deleteEntry(entryId) {
|
|
94
|
+
if (!this.entries.has(entryId))
|
|
95
|
+
return false;
|
|
96
|
+
this.entries.delete(entryId);
|
|
97
|
+
for (const [cacheKey, id] of Object.entries(this.index)) {
|
|
98
|
+
if (id === entryId)
|
|
99
|
+
delete this.index[cacheKey];
|
|
100
|
+
}
|
|
101
|
+
this.lruKeys = this.lruKeys.filter((cacheKey) => this.index[cacheKey] != null);
|
|
102
|
+
this.persistIndex();
|
|
103
|
+
this.rewriteEntriesFile();
|
|
104
|
+
return true;
|
|
105
|
+
}
|
|
106
|
+
deleteAll(projectId) {
|
|
107
|
+
const ids = [...this.entries.values()]
|
|
108
|
+
.filter((entry) => entry.projectId === projectId)
|
|
109
|
+
.map((entry) => entry.id);
|
|
110
|
+
let removed = 0;
|
|
111
|
+
for (const entryId of ids) {
|
|
112
|
+
if (this.deleteEntry(entryId))
|
|
113
|
+
removed += 1;
|
|
114
|
+
}
|
|
115
|
+
return removed;
|
|
116
|
+
}
|
|
117
|
+
rewriteEntriesFile() {
|
|
118
|
+
mkdirSync(this.paths.exactDir, { recursive: true });
|
|
119
|
+
const lines = [...this.entries.values()].map((entry) => JSON.stringify(entry));
|
|
120
|
+
writeFileSync(this.paths.exactEntriesPath, lines.length ? `${lines.join("\n")}\n` : "", "utf8");
|
|
121
|
+
}
|
|
122
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { type SpotlightMemoryGateResult, type SpotlightMemoryLookupInput, type SpotlightMemoryWriteInput, type SpotlightMemoryWriteResult } from "@inupedia/spotlight-protocol";
|
|
2
|
+
export interface MemoryStoreReader {
|
|
3
|
+
getExact(cacheKey: string): Promise<import("@inupedia/spotlight-protocol").SpotlightMemoryEntry | null>;
|
|
4
|
+
findSemantic(projectId: string, questionNorm: string, limit?: number): Promise<Array<{
|
|
5
|
+
entry: import("@inupedia/spotlight-protocol").SpotlightMemoryEntry;
|
|
6
|
+
score: number;
|
|
7
|
+
}>>;
|
|
8
|
+
touch(entryId: string): Promise<void>;
|
|
9
|
+
}
|
|
10
|
+
export interface MemoryStoreWriter {
|
|
11
|
+
putExact(cacheKey: string, entry: import("@inupedia/spotlight-protocol").SpotlightMemoryEntry): Promise<void>;
|
|
12
|
+
putSemantic(entry: import("@inupedia/spotlight-protocol").SpotlightMemoryEntry): Promise<void>;
|
|
13
|
+
hasExact(cacheKey: string): Promise<boolean>;
|
|
14
|
+
}
|
|
15
|
+
export interface MemoryGateConfig {
|
|
16
|
+
enabled?: boolean;
|
|
17
|
+
semanticThreshold?: number;
|
|
18
|
+
writeMinConfidence?: number;
|
|
19
|
+
semanticEnabled?: boolean;
|
|
20
|
+
}
|
|
21
|
+
export interface MemoryGate {
|
|
22
|
+
lookup(input: SpotlightMemoryLookupInput): Promise<SpotlightMemoryGateResult>;
|
|
23
|
+
write(input: SpotlightMemoryWriteInput): Promise<SpotlightMemoryWriteResult>;
|
|
24
|
+
}
|
|
25
|
+
export declare function createMemoryGate(reader: MemoryStoreReader, writer: MemoryStoreWriter, config?: MemoryGateConfig): MemoryGate;
|
|
26
|
+
//# sourceMappingURL=gate.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"gate.d.ts","sourceRoot":"","sources":["../../src/node/gate.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,KAAK,yBAAyB,EAC9B,KAAK,0BAA0B,EAC/B,KAAK,yBAAyB,EAC9B,KAAK,0BAA0B,EAChC,MAAM,8BAA8B,CAAC;AAMtC,MAAM,WAAW,iBAAiB;IAChC,QAAQ,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,8BAA8B,EAAE,oBAAoB,GAAG,IAAI,CAAC,CAAC;IACxG,YAAY,CACV,SAAS,EAAE,MAAM,EACjB,YAAY,EAAE,MAAM,EACpB,KAAK,CAAC,EAAE,MAAM,GACb,OAAO,CACR,KAAK,CAAC;QACJ,KAAK,EAAE,OAAO,8BAA8B,EAAE,oBAAoB,CAAC;QACnE,KAAK,EAAE,MAAM,CAAC;KACf,CAAC,CACH,CAAC;IACF,KAAK,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CACvC;AAED,MAAM,WAAW,iBAAiB;IAChC,QAAQ,CACN,QAAQ,EAAE,MAAM,EAChB,KAAK,EAAE,OAAO,8BAA8B,EAAE,oBAAoB,GACjE,OAAO,CAAC,IAAI,CAAC,CAAC;IACjB,WAAW,CACT,KAAK,EAAE,OAAO,8BAA8B,EAAE,oBAAoB,GACjE,OAAO,CAAC,IAAI,CAAC,CAAC;IACjB,QAAQ,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;CAC9C;AAED,MAAM,WAAW,gBAAgB;IAC/B,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B,eAAe,CAAC,EAAE,OAAO,CAAC;CAC3B;AAED,MAAM,WAAW,UAAU;IACzB,MAAM,CAAC,KAAK,EAAE,0BAA0B,GAAG,OAAO,CAAC,yBAAyB,CAAC,CAAC;IAC9E,KAAK,CAAC,KAAK,EAAE,yBAAyB,GAAG,OAAO,CAAC,0BAA0B,CAAC,CAAC;CAC9E;AAED,wBAAgB,gBAAgB,CAC9B,MAAM,EAAE,iBAAiB,EACzB,MAAM,EAAE,iBAAiB,EACzB,MAAM,GAAE,gBAAqB,GAC5B,UAAU,CAmIZ"}
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
import { SPOTLIGHT_MEMORY_DEFAULT_TTL_SEC, } from "@inupedia/spotlight-protocol";
|
|
2
|
+
import { classifyMemoryKind, isMemoryKindAllowedForRead } from "../classify.js";
|
|
3
|
+
import { normalizeQuestion } from "../normalize.js";
|
|
4
|
+
import { isMemoryEntryStale } from "../stale.js";
|
|
5
|
+
import { buildCacheKey, createMemoryEntryId } from "./cacheKey.js";
|
|
6
|
+
export function createMemoryGate(reader, writer, config = {}) {
|
|
7
|
+
const enabled = config.enabled ?? true;
|
|
8
|
+
const semanticThreshold = config.semanticThreshold ?? 0.92;
|
|
9
|
+
const writeMinConfidence = config.writeMinConfidence ?? 0.85;
|
|
10
|
+
const semanticEnabled = config.semanticEnabled ?? true;
|
|
11
|
+
return {
|
|
12
|
+
async lookup(input) {
|
|
13
|
+
const started = performance.now();
|
|
14
|
+
const finishMiss = (reason) => ({
|
|
15
|
+
hit: false,
|
|
16
|
+
miss: { reason, lookupLatencyMs: performance.now() - started },
|
|
17
|
+
});
|
|
18
|
+
if (!enabled)
|
|
19
|
+
return finishMiss("disabled");
|
|
20
|
+
const questionNorm = normalizeQuestion(input.question);
|
|
21
|
+
if (!questionNorm)
|
|
22
|
+
return finishMiss("not_found");
|
|
23
|
+
const cacheKey = buildCacheKey({
|
|
24
|
+
projectId: input.projectId,
|
|
25
|
+
questionNorm,
|
|
26
|
+
invalidation: input.invalidation,
|
|
27
|
+
});
|
|
28
|
+
const exact = await reader.getExact(cacheKey);
|
|
29
|
+
if (exact) {
|
|
30
|
+
if (isMemoryEntryStale(exact, input.invalidation)) {
|
|
31
|
+
return finishMiss("stale");
|
|
32
|
+
}
|
|
33
|
+
if (!isMemoryKindAllowedForRead(exact.kind)) {
|
|
34
|
+
return finishMiss("kind_blocked");
|
|
35
|
+
}
|
|
36
|
+
await reader.touch(exact.id);
|
|
37
|
+
return {
|
|
38
|
+
hit: true,
|
|
39
|
+
result: {
|
|
40
|
+
source: "exact",
|
|
41
|
+
entry: exact,
|
|
42
|
+
confidence: 1,
|
|
43
|
+
lookupLatencyMs: performance.now() - started,
|
|
44
|
+
},
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
if (!input.exactOnly && semanticEnabled) {
|
|
48
|
+
const semantic = await reader.findSemantic(input.projectId, questionNorm, 5);
|
|
49
|
+
const top = semantic.find((c) => c.score >= semanticThreshold);
|
|
50
|
+
if (top) {
|
|
51
|
+
if (isMemoryEntryStale(top.entry, input.invalidation)) {
|
|
52
|
+
return finishMiss("stale");
|
|
53
|
+
}
|
|
54
|
+
if (!isMemoryKindAllowedForRead(top.entry.kind)) {
|
|
55
|
+
return finishMiss("kind_blocked");
|
|
56
|
+
}
|
|
57
|
+
await reader.touch(top.entry.id);
|
|
58
|
+
return {
|
|
59
|
+
hit: true,
|
|
60
|
+
result: {
|
|
61
|
+
source: "semantic",
|
|
62
|
+
entry: top.entry,
|
|
63
|
+
confidence: top.score,
|
|
64
|
+
lookupLatencyMs: performance.now() - started,
|
|
65
|
+
},
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
if (semantic.length && semantic[0].score < semanticThreshold) {
|
|
69
|
+
return finishMiss("below_threshold");
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
return finishMiss("not_found");
|
|
73
|
+
},
|
|
74
|
+
async write(input) {
|
|
75
|
+
if (!enabled)
|
|
76
|
+
return { written: false, skippedReason: "below_confidence" };
|
|
77
|
+
if (input.confidence < writeMinConfidence) {
|
|
78
|
+
return { written: false, skippedReason: "below_confidence" };
|
|
79
|
+
}
|
|
80
|
+
const classified = classifyMemoryKind({
|
|
81
|
+
question: input.question,
|
|
82
|
+
hasToolPlan: Boolean(input.plan?.toolCalls?.length || input.plan?.command),
|
|
83
|
+
hasTextAnswer: Boolean(input.answer?.trim()),
|
|
84
|
+
usedDataTools: input.kind === "data_snapshot",
|
|
85
|
+
});
|
|
86
|
+
const kind = input.kind ?? classified.kind;
|
|
87
|
+
if (!kind) {
|
|
88
|
+
return { written: false, skippedReason: "kind_blocked" };
|
|
89
|
+
}
|
|
90
|
+
const questionNorm = normalizeQuestion(input.question);
|
|
91
|
+
const cacheKey = buildCacheKey({
|
|
92
|
+
projectId: input.projectId,
|
|
93
|
+
questionNorm,
|
|
94
|
+
invalidation: input.invalidation,
|
|
95
|
+
});
|
|
96
|
+
if (await writer.hasExact(cacheKey)) {
|
|
97
|
+
return { written: false, skippedReason: "duplicate" };
|
|
98
|
+
}
|
|
99
|
+
const entry = {
|
|
100
|
+
id: createMemoryEntryId(),
|
|
101
|
+
projectId: input.projectId,
|
|
102
|
+
questionNorm,
|
|
103
|
+
questionRaw: input.question,
|
|
104
|
+
kind,
|
|
105
|
+
answer: input.answer,
|
|
106
|
+
plan: input.plan,
|
|
107
|
+
invalidation: input.invalidation,
|
|
108
|
+
ttlSec: input.ttlSec ?? SPOTLIGHT_MEMORY_DEFAULT_TTL_SEC[kind],
|
|
109
|
+
createdAt: Date.now(),
|
|
110
|
+
hitCount: 0,
|
|
111
|
+
confidence: input.confidence,
|
|
112
|
+
sourceRunId: input.sourceRunId,
|
|
113
|
+
};
|
|
114
|
+
await writer.putExact(cacheKey, entry);
|
|
115
|
+
await writer.putSemantic(entry);
|
|
116
|
+
return { written: true, entryId: entry.id };
|
|
117
|
+
},
|
|
118
|
+
};
|
|
119
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { MemoryGate } from "./gate.js";
|
|
2
|
+
import { type MemoryGateConfig } from "./gate.js";
|
|
3
|
+
import { ExactMemoryStore } from "./exactStore.js";
|
|
4
|
+
import { type PackMemoryPaths } from "./paths.js";
|
|
5
|
+
import { SemanticMemoryStore } from "./semanticStore.js";
|
|
6
|
+
export interface PackMemoryStores {
|
|
7
|
+
paths: PackMemoryPaths;
|
|
8
|
+
exact: ExactMemoryStore;
|
|
9
|
+
semantic: SemanticMemoryStore;
|
|
10
|
+
gate: MemoryGate;
|
|
11
|
+
}
|
|
12
|
+
export declare function createPackMemoryStores(params: {
|
|
13
|
+
packsRoot: string;
|
|
14
|
+
projectId: string;
|
|
15
|
+
gateConfig?: MemoryGateConfig;
|
|
16
|
+
lruMax?: number;
|
|
17
|
+
}): PackMemoryStores;
|
|
18
|
+
export { ExactMemoryStore } from "./exactStore.js";
|
|
19
|
+
export { SemanticMemoryStore } from "./semanticStore.js";
|
|
20
|
+
export { buildCacheKey, createMemoryEntryId, } from "./cacheKey.js";
|
|
21
|
+
export { createMemoryGate, type MemoryGate, type MemoryGateConfig, type MemoryStoreReader, type MemoryStoreWriter, } from "./gate.js";
|
|
22
|
+
export { defaultPackMemoryMeta, resolvePackMemoryDir, type PackMemoryMeta, type PackMemoryPaths, } from "./paths.js";
|
|
23
|
+
export { readPackMemoryMeta, refreshPackMemoryMeta, writePackMemoryMeta, } from "./meta.js";
|
|
24
|
+
export { type EmbeddingProvider, resolveEmbeddingProviderFromEnv, } from "./embeddingProvider.js";
|
|
25
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +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;IAC9B,IAAI,EAAE,UAAU,CAAC;CAClB;AAgCD,wBAAgB,sBAAsB,CAAC,MAAM,EAAE;IAC7C,SAAS,EAAE,MAAM,CAAC;IAClB,SAAS,EAAE,MAAM,CAAC;IAClB,UAAU,CAAC,EAAE,gBAAgB,CAAC;IAC9B,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB,GAAG,gBAAgB,CAiBnB;AAED,OAAO,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AACnD,OAAO,EAAE,mBAAmB,EAAE,MAAM,oBAAoB,CAAC;AACzD,OAAO,EACL,aAAa,EACb,mBAAmB,GACpB,MAAM,eAAe,CAAC;AACvB,OAAO,EACL,gBAAgB,EAChB,KAAK,UAAU,EACf,KAAK,gBAAgB,EACrB,KAAK,iBAAiB,EACtB,KAAK,iBAAiB,GACvB,MAAM,WAAW,CAAC;AACnB,OAAO,EACL,qBAAqB,EACrB,oBAAoB,EACpB,KAAK,cAAc,EACnB,KAAK,eAAe,GACrB,MAAM,YAAY,CAAC;AACpB,OAAO,EACL,kBAAkB,EAClB,qBAAqB,EACrB,mBAAmB,GACpB,MAAM,WAAW,CAAC;AACnB,OAAO,EACL,KAAK,iBAAiB,EACtB,+BAA+B,GAChC,MAAM,wBAAwB,CAAC"}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { createMemoryGate } from "./gate.js";
|
|
2
|
+
import { ExactMemoryStore } from "./exactStore.js";
|
|
3
|
+
import { refreshPackMemoryMeta } from "./meta.js";
|
|
4
|
+
import { resolvePackMemoryDir } from "./paths.js";
|
|
5
|
+
import { SemanticMemoryStore } from "./semanticStore.js";
|
|
6
|
+
function createCompositeMemoryStores(paths, exact, semantic, projectId) {
|
|
7
|
+
const reader = {
|
|
8
|
+
getExact: (cacheKey) => exact.getExact(cacheKey),
|
|
9
|
+
findSemantic: (pid, questionNorm, limit) => semantic.findSimilar(pid, questionNorm, limit),
|
|
10
|
+
touch: async (entryId) => {
|
|
11
|
+
await exact.touch(entryId);
|
|
12
|
+
semantic.touch(entryId);
|
|
13
|
+
},
|
|
14
|
+
};
|
|
15
|
+
const writer = {
|
|
16
|
+
putExact: (cacheKey, entry) => exact.putExact(cacheKey, entry),
|
|
17
|
+
putSemantic: async (entry) => {
|
|
18
|
+
await semantic.putWithOptionalEmbedding(entry);
|
|
19
|
+
refreshPackMemoryMeta({
|
|
20
|
+
paths,
|
|
21
|
+
exactCount: exact.listEntries(Number.MAX_SAFE_INTEGER).length,
|
|
22
|
+
semanticCount: semantic.count(projectId),
|
|
23
|
+
});
|
|
24
|
+
},
|
|
25
|
+
hasExact: (cacheKey) => exact.hasExact(cacheKey),
|
|
26
|
+
};
|
|
27
|
+
return { reader, writer };
|
|
28
|
+
}
|
|
29
|
+
export function createPackMemoryStores(params) {
|
|
30
|
+
const paths = resolvePackMemoryDir(params.packsRoot, params.projectId);
|
|
31
|
+
const exact = new ExactMemoryStore({ paths, lruMax: params.lruMax });
|
|
32
|
+
const semantic = new SemanticMemoryStore({ paths });
|
|
33
|
+
const { reader, writer } = createCompositeMemoryStores(paths, exact, semantic, params.projectId);
|
|
34
|
+
const gate = createMemoryGate(reader, writer, params.gateConfig);
|
|
35
|
+
refreshPackMemoryMeta({
|
|
36
|
+
paths,
|
|
37
|
+
exactCount: exact.listEntries(Number.MAX_SAFE_INTEGER).length,
|
|
38
|
+
semanticCount: semantic.count(params.projectId),
|
|
39
|
+
});
|
|
40
|
+
return { paths, exact, semantic, gate };
|
|
41
|
+
}
|
|
42
|
+
export { ExactMemoryStore } from "./exactStore.js";
|
|
43
|
+
export { SemanticMemoryStore } from "./semanticStore.js";
|
|
44
|
+
export { buildCacheKey, createMemoryEntryId, } from "./cacheKey.js";
|
|
45
|
+
export { createMemoryGate, } from "./gate.js";
|
|
46
|
+
export { defaultPackMemoryMeta, resolvePackMemoryDir, } from "./paths.js";
|
|
47
|
+
export { readPackMemoryMeta, refreshPackMemoryMeta, writePackMemoryMeta, } from "./meta.js";
|
|
48
|
+
export { resolveEmbeddingProviderFromEnv, } from "./embeddingProvider.js";
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { type PackMemoryMeta, type PackMemoryPaths } from "./paths.js";
|
|
2
|
+
export declare function readPackMemoryMeta(paths: PackMemoryPaths): PackMemoryMeta;
|
|
3
|
+
export declare function writePackMemoryMeta(paths: PackMemoryPaths, meta: PackMemoryMeta): void;
|
|
4
|
+
export declare function refreshPackMemoryMeta(params: {
|
|
5
|
+
paths: PackMemoryPaths;
|
|
6
|
+
exactCount: number;
|
|
7
|
+
semanticCount: number;
|
|
8
|
+
}): PackMemoryMeta;
|
|
9
|
+
//# sourceMappingURL=meta.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"meta.d.ts","sourceRoot":"","sources":["../../src/node/meta.ts"],"names":[],"mappings":"AACA,OAAO,EAEL,KAAK,cAAc,EACnB,KAAK,eAAe,EACrB,MAAM,YAAY,CAAC;AAEpB,wBAAgB,kBAAkB,CAAC,KAAK,EAAE,eAAe,GAAG,cAAc,CAOzE;AAED,wBAAgB,mBAAmB,CACjC,KAAK,EAAE,eAAe,EACtB,IAAI,EAAE,cAAc,GACnB,IAAI,CAGN;AAED,wBAAgB,qBAAqB,CAAC,MAAM,EAAE;IAC5C,KAAK,EAAE,eAAe,CAAC;IACvB,UAAU,EAAE,MAAM,CAAC;IACnB,aAAa,EAAE,MAAM,CAAC;CACvB,GAAG,cAAc,CASjB"}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { defaultPackMemoryMeta, } from "./paths.js";
|
|
3
|
+
export function readPackMemoryMeta(paths) {
|
|
4
|
+
if (!existsSync(paths.metaPath))
|
|
5
|
+
return defaultPackMemoryMeta();
|
|
6
|
+
try {
|
|
7
|
+
return JSON.parse(readFileSync(paths.metaPath, "utf8"));
|
|
8
|
+
}
|
|
9
|
+
catch {
|
|
10
|
+
return defaultPackMemoryMeta();
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
export function writePackMemoryMeta(paths, meta) {
|
|
14
|
+
mkdirSync(paths.root, { recursive: true });
|
|
15
|
+
writeFileSync(paths.metaPath, `${JSON.stringify(meta, null, 2)}\n`, "utf8");
|
|
16
|
+
}
|
|
17
|
+
export function refreshPackMemoryMeta(params) {
|
|
18
|
+
const meta = {
|
|
19
|
+
version: "1",
|
|
20
|
+
exactCount: params.exactCount,
|
|
21
|
+
semanticCount: params.semanticCount,
|
|
22
|
+
updatedAt: new Date().toISOString(),
|
|
23
|
+
};
|
|
24
|
+
writePackMemoryMeta(params.paths, meta);
|
|
25
|
+
return meta;
|
|
26
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { SpotlightMemoryEntry } from "@inupedia/spotlight-protocol";
|
|
2
|
+
export interface PackMemoryPaths {
|
|
3
|
+
root: string;
|
|
4
|
+
exactDir: string;
|
|
5
|
+
exactIndexPath: string;
|
|
6
|
+
exactEntriesPath: string;
|
|
7
|
+
semanticDir: string;
|
|
8
|
+
semanticDbPath: string;
|
|
9
|
+
metaPath: string;
|
|
10
|
+
}
|
|
11
|
+
/** Resolve pack-scoped memory directories (mirrors assets.jsonl layout). */
|
|
12
|
+
export declare function resolvePackMemoryDir(packsRoot: string, projectId: string): PackMemoryPaths;
|
|
13
|
+
export interface PackMemoryMeta {
|
|
14
|
+
version: string;
|
|
15
|
+
exactCount: number;
|
|
16
|
+
semanticCount: number;
|
|
17
|
+
updatedAt: string;
|
|
18
|
+
}
|
|
19
|
+
export declare function defaultPackMemoryMeta(): PackMemoryMeta;
|
|
20
|
+
export type { SpotlightMemoryEntry };
|
|
21
|
+
//# sourceMappingURL=paths.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"paths.d.ts","sourceRoot":"","sources":["../../src/node/paths.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,8BAA8B,CAAC;AAEzE,MAAM,WAAW,eAAe;IAC9B,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,MAAM,CAAC;IACjB,cAAc,EAAE,MAAM,CAAC;IACvB,gBAAgB,EAAE,MAAM,CAAC;IACzB,WAAW,EAAE,MAAM,CAAC;IACpB,cAAc,EAAE,MAAM,CAAC;IACvB,QAAQ,EAAE,MAAM,CAAC;CAClB;AAED,4EAA4E;AAC5E,wBAAgB,oBAAoB,CAClC,SAAS,EAAE,MAAM,EACjB,SAAS,EAAE,MAAM,GAChB,eAAe,CAYjB;AAED,MAAM,WAAW,cAAc;IAC7B,OAAO,EAAE,MAAM,CAAC;IAChB,UAAU,EAAE,MAAM,CAAC;IACnB,aAAa,EAAE,MAAM,CAAC;IACtB,SAAS,EAAE,MAAM,CAAC;CACnB;AAED,wBAAgB,qBAAqB,IAAI,cAAc,CAOtD;AAED,YAAY,EAAE,oBAAoB,EAAE,CAAC"}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { join } from "node:path";
|
|
2
|
+
/** Resolve pack-scoped memory directories (mirrors assets.jsonl layout). */
|
|
3
|
+
export function resolvePackMemoryDir(packsRoot, projectId) {
|
|
4
|
+
const root = join(packsRoot, projectId, "memory");
|
|
5
|
+
const exactDir = join(root, "exact");
|
|
6
|
+
return {
|
|
7
|
+
root,
|
|
8
|
+
exactDir,
|
|
9
|
+
exactIndexPath: join(exactDir, "index.json"),
|
|
10
|
+
exactEntriesPath: join(exactDir, "entries.jsonl"),
|
|
11
|
+
semanticDir: join(root, "semantic"),
|
|
12
|
+
semanticDbPath: join(root, "semantic", "memory.db"),
|
|
13
|
+
metaPath: join(root, "meta.json"),
|
|
14
|
+
};
|
|
15
|
+
}
|
|
16
|
+
export function defaultPackMemoryMeta() {
|
|
17
|
+
return {
|
|
18
|
+
version: "1",
|
|
19
|
+
exactCount: 0,
|
|
20
|
+
semanticCount: 0,
|
|
21
|
+
updatedAt: new Date().toISOString(),
|
|
22
|
+
};
|
|
23
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { SpotlightMemoryEntry } from "@inupedia/spotlight-protocol";
|
|
2
|
+
import type { PackMemoryPaths } from "./paths.js";
|
|
3
|
+
import { type EmbeddingProvider } from "./embeddingProvider.js";
|
|
4
|
+
export interface SemanticMemoryStoreOptions {
|
|
5
|
+
paths: PackMemoryPaths;
|
|
6
|
+
embeddingProvider?: EmbeddingProvider | null;
|
|
7
|
+
}
|
|
8
|
+
/** L1 semantic cache backed by SQLite; BM25/bigram fallback, optional embeddings. */
|
|
9
|
+
export declare class SemanticMemoryStore {
|
|
10
|
+
private readonly db;
|
|
11
|
+
private readonly embeddingProvider;
|
|
12
|
+
constructor(options: SemanticMemoryStoreOptions);
|
|
13
|
+
put(entry: SpotlightMemoryEntry, embedding?: number[] | null): void;
|
|
14
|
+
putWithOptionalEmbedding(entry: SpotlightMemoryEntry): Promise<void>;
|
|
15
|
+
findSimilar(projectId: string, questionNorm: string, limit?: number): Promise<Array<{
|
|
16
|
+
entry: SpotlightMemoryEntry;
|
|
17
|
+
score: number;
|
|
18
|
+
}>>;
|
|
19
|
+
touch(entryId: string): void;
|
|
20
|
+
listEntries(limit?: number): SpotlightMemoryEntry[];
|
|
21
|
+
deleteEntry(entryId: string): boolean;
|
|
22
|
+
deleteAll(projectId: string): number;
|
|
23
|
+
count(projectId?: string): number;
|
|
24
|
+
}
|
|
25
|
+
//# sourceMappingURL=semanticStore.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"semanticStore.d.ts","sourceRoot":"","sources":["../../src/node/semanticStore.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,8BAA8B,CAAC;AAEzE,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAClD,OAAO,EACL,KAAK,iBAAiB,EAGvB,MAAM,wBAAwB,CAAC;AAOhC,MAAM,WAAW,0BAA0B;IACzC,KAAK,EAAE,eAAe,CAAC;IACvB,iBAAiB,CAAC,EAAE,iBAAiB,GAAG,IAAI,CAAC;CAC9C;AAED,qFAAqF;AACrF,qBAAa,mBAAmB;IAC9B,OAAO,CAAC,QAAQ,CAAC,EAAE,CAAe;IAClC,OAAO,CAAC,QAAQ,CAAC,iBAAiB,CAA2B;gBAEjD,OAAO,EAAE,0BAA0B;IAoB/C,GAAG,CAAC,KAAK,EAAE,oBAAoB,EAAE,SAAS,CAAC,EAAE,MAAM,EAAE,GAAG,IAAI,GAAG,IAAI;IAc7D,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;IA2CjE,KAAK,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI;IAiB5B,WAAW,CAAC,KAAK,SAAK,GAAG,oBAAoB,EAAE;IAiB/C,WAAW,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO;IAOrC,SAAS,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM;IAOpC,KAAK,CAAC,SAAS,CAAC,EAAE,MAAM,GAAG,MAAM;CAYlC"}
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
import { mkdirSync } from "node:fs";
|
|
2
|
+
import { DatabaseSync } from "node:sqlite";
|
|
3
|
+
import { scoreQuestionSimilarity } from "../normalize.js";
|
|
4
|
+
import { resolveEmbeddingProviderFromEnv, scoreEmbeddingPair, } from "./embeddingProvider.js";
|
|
5
|
+
/** L1 semantic cache backed by SQLite; BM25/bigram fallback, optional embeddings. */
|
|
6
|
+
export class SemanticMemoryStore {
|
|
7
|
+
db;
|
|
8
|
+
embeddingProvider;
|
|
9
|
+
constructor(options) {
|
|
10
|
+
mkdirSync(options.paths.semanticDir, { recursive: true });
|
|
11
|
+
this.embeddingProvider =
|
|
12
|
+
options.embeddingProvider === undefined
|
|
13
|
+
? resolveEmbeddingProviderFromEnv()
|
|
14
|
+
: options.embeddingProvider;
|
|
15
|
+
this.db = new DatabaseSync(options.paths.semanticDbPath);
|
|
16
|
+
this.db.exec(`
|
|
17
|
+
CREATE TABLE IF NOT EXISTS entries (
|
|
18
|
+
id TEXT PRIMARY KEY,
|
|
19
|
+
project_id TEXT NOT NULL,
|
|
20
|
+
question_norm TEXT NOT NULL,
|
|
21
|
+
entry_json TEXT NOT NULL,
|
|
22
|
+
embedding_json TEXT
|
|
23
|
+
);
|
|
24
|
+
CREATE INDEX IF NOT EXISTS idx_semantic_project ON entries(project_id);
|
|
25
|
+
CREATE INDEX IF NOT EXISTS idx_semantic_question ON entries(question_norm);
|
|
26
|
+
`);
|
|
27
|
+
}
|
|
28
|
+
put(entry, embedding) {
|
|
29
|
+
const stmt = this.db.prepare(`
|
|
30
|
+
INSERT OR REPLACE INTO entries (id, project_id, question_norm, entry_json, embedding_json)
|
|
31
|
+
VALUES (?, ?, ?, ?, ?)
|
|
32
|
+
`);
|
|
33
|
+
stmt.run(entry.id, entry.projectId, entry.questionNorm, JSON.stringify(entry), embedding?.length ? JSON.stringify(embedding) : null);
|
|
34
|
+
}
|
|
35
|
+
async putWithOptionalEmbedding(entry) {
|
|
36
|
+
let embedding = null;
|
|
37
|
+
if (this.embeddingProvider) {
|
|
38
|
+
try {
|
|
39
|
+
embedding = await this.embeddingProvider.embed(entry.questionNorm);
|
|
40
|
+
}
|
|
41
|
+
catch {
|
|
42
|
+
embedding = null;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
this.put(entry, embedding);
|
|
46
|
+
}
|
|
47
|
+
async findSimilar(projectId, questionNorm, limit = 5) {
|
|
48
|
+
const rows = this.db
|
|
49
|
+
.prepare(`SELECT entry_json, embedding_json FROM entries WHERE project_id = ?`)
|
|
50
|
+
.all(projectId);
|
|
51
|
+
let queryEmbedding = null;
|
|
52
|
+
if (this.embeddingProvider) {
|
|
53
|
+
try {
|
|
54
|
+
queryEmbedding = await this.embeddingProvider.embed(questionNorm);
|
|
55
|
+
}
|
|
56
|
+
catch {
|
|
57
|
+
queryEmbedding = null;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
const scored = [];
|
|
61
|
+
for (const row of rows) {
|
|
62
|
+
let entry;
|
|
63
|
+
try {
|
|
64
|
+
entry = JSON.parse(row.entry_json);
|
|
65
|
+
}
|
|
66
|
+
catch {
|
|
67
|
+
continue;
|
|
68
|
+
}
|
|
69
|
+
const lexical = scoreQuestionSimilarity(questionNorm, entry.questionNorm);
|
|
70
|
+
let embeddingScore = 0;
|
|
71
|
+
if (queryEmbedding && row.embedding_json) {
|
|
72
|
+
try {
|
|
73
|
+
const stored = JSON.parse(row.embedding_json);
|
|
74
|
+
embeddingScore = scoreEmbeddingPair(queryEmbedding, stored);
|
|
75
|
+
}
|
|
76
|
+
catch {
|
|
77
|
+
embeddingScore = 0;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
const score = Math.max(lexical, embeddingScore);
|
|
81
|
+
if (score <= 0)
|
|
82
|
+
continue;
|
|
83
|
+
scored.push({ entry, score });
|
|
84
|
+
}
|
|
85
|
+
scored.sort((a, b) => b.score - a.score);
|
|
86
|
+
return scored.slice(0, limit);
|
|
87
|
+
}
|
|
88
|
+
touch(entryId) {
|
|
89
|
+
const row = this.db
|
|
90
|
+
.prepare(`SELECT entry_json FROM entries WHERE id = ?`)
|
|
91
|
+
.get(entryId);
|
|
92
|
+
if (!row)
|
|
93
|
+
return;
|
|
94
|
+
try {
|
|
95
|
+
const entry = JSON.parse(row.entry_json);
|
|
96
|
+
entry.hitCount += 1;
|
|
97
|
+
entry.lastHitAt = Date.now();
|
|
98
|
+
this.db
|
|
99
|
+
.prepare(`UPDATE entries SET entry_json = ? WHERE id = ?`)
|
|
100
|
+
.run(JSON.stringify(entry), entryId);
|
|
101
|
+
}
|
|
102
|
+
catch {
|
|
103
|
+
/* ignore corrupt row */
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
listEntries(limit = 50) {
|
|
107
|
+
const safeLimit = Number.isFinite(limit) && limit > 0 ? Math.min(500, Math.floor(limit)) : 50;
|
|
108
|
+
const rows = this.db
|
|
109
|
+
.prepare(`SELECT entry_json FROM entries ORDER BY json_extract(entry_json, '$.createdAt') DESC LIMIT ?`)
|
|
110
|
+
.all(safeLimit);
|
|
111
|
+
const entries = [];
|
|
112
|
+
for (const row of rows) {
|
|
113
|
+
try {
|
|
114
|
+
entries.push(JSON.parse(row.entry_json));
|
|
115
|
+
}
|
|
116
|
+
catch {
|
|
117
|
+
/* skip */
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
return entries;
|
|
121
|
+
}
|
|
122
|
+
deleteEntry(entryId) {
|
|
123
|
+
const result = this.db
|
|
124
|
+
.prepare(`DELETE FROM entries WHERE id = ?`)
|
|
125
|
+
.run(entryId);
|
|
126
|
+
return Number(result.changes) > 0;
|
|
127
|
+
}
|
|
128
|
+
deleteAll(projectId) {
|
|
129
|
+
const result = this.db
|
|
130
|
+
.prepare(`DELETE FROM entries WHERE project_id = ?`)
|
|
131
|
+
.run(projectId);
|
|
132
|
+
return Number(result.changes);
|
|
133
|
+
}
|
|
134
|
+
count(projectId) {
|
|
135
|
+
if (projectId) {
|
|
136
|
+
const row = this.db
|
|
137
|
+
.prepare(`SELECT COUNT(*) AS total FROM entries WHERE project_id = ?`)
|
|
138
|
+
.get(projectId);
|
|
139
|
+
return Number(row.total);
|
|
140
|
+
}
|
|
141
|
+
const row = this.db
|
|
142
|
+
.prepare(`SELECT COUNT(*) AS total FROM entries`)
|
|
143
|
+
.get();
|
|
144
|
+
return Number(row.total);
|
|
145
|
+
}
|
|
146
|
+
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
/** Normalize user question for cache keys and semantic index. */
|
|
2
|
+
export declare function normalizeQuestion(question: string): string;
|
|
3
|
+
/** Rough token-overlap score in [0, 1] — MVP semantic fallback without embeddings. */
|
|
4
|
+
export declare function scoreQuestionSimilarity(a: string, b: string): number;
|
|
5
|
+
//# sourceMappingURL=normalize.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"normalize.d.ts","sourceRoot":"","sources":["../src/normalize.ts"],"names":[],"mappings":"AAGA,iEAAiE;AACjE,wBAAgB,iBAAiB,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,CAM1D;AAED,sFAAsF;AACtF,wBAAgB,uBAAuB,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,GAAG,MAAM,CAqBpE"}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
const FILLER_PREFIX = /^(请问|帮我|帮忙|能不能|可以|麻烦|我想|我要|请|打开|查看|看一下|看看)/;
|
|
2
|
+
/** Normalize user question for cache keys and semantic index. */
|
|
3
|
+
export function normalizeQuestion(question) {
|
|
4
|
+
let text = question.trim().toLowerCase();
|
|
5
|
+
text = text.replace(/\s+/g, "");
|
|
6
|
+
text = text.replace(/[??!!。.,,、;;::""''()()[\]【】]/g, "");
|
|
7
|
+
text = text.replace(FILLER_PREFIX, "");
|
|
8
|
+
return text;
|
|
9
|
+
}
|
|
10
|
+
/** Rough token-overlap score in [0, 1] — MVP semantic fallback without embeddings. */
|
|
11
|
+
export function scoreQuestionSimilarity(a, b) {
|
|
12
|
+
const left = normalizeQuestion(a);
|
|
13
|
+
const right = normalizeQuestion(b);
|
|
14
|
+
if (!left || !right)
|
|
15
|
+
return 0;
|
|
16
|
+
if (left === right)
|
|
17
|
+
return 1;
|
|
18
|
+
if (left.includes(right) || right.includes(left)) {
|
|
19
|
+
const shorter = Math.min(left.length, right.length);
|
|
20
|
+
const longer = Math.max(left.length, right.length);
|
|
21
|
+
return shorter / longer;
|
|
22
|
+
}
|
|
23
|
+
const grams = (s) => {
|
|
24
|
+
const set = new Set();
|
|
25
|
+
for (let i = 0; i < s.length - 1; i++)
|
|
26
|
+
set.add(s.slice(i, i + 2));
|
|
27
|
+
return set;
|
|
28
|
+
};
|
|
29
|
+
const ga = grams(left);
|
|
30
|
+
const gb = grams(right);
|
|
31
|
+
let inter = 0;
|
|
32
|
+
for (const g of ga)
|
|
33
|
+
if (gb.has(g))
|
|
34
|
+
inter += 1;
|
|
35
|
+
const union = ga.size + gb.size - inter;
|
|
36
|
+
return union === 0 ? 0 : inter / union;
|
|
37
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"similarity.d.ts","sourceRoot":"","sources":["../src/similarity.ts"],"names":[],"mappings":"AAAA,2EAA2E;AAC3E,wBAAgB,gBAAgB,CAAC,CAAC,EAAE,MAAM,EAAE,EAAE,CAAC,EAAE,MAAM,EAAE,GAAG,MAAM,CAajE"}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/** Cosine similarity for embedding vectors in [-1, 1] scaled to [0, 1]. */
|
|
2
|
+
export function cosineSimilarity(a, b) {
|
|
3
|
+
if (a.length !== b.length || a.length === 0)
|
|
4
|
+
return 0;
|
|
5
|
+
let dot = 0;
|
|
6
|
+
let normA = 0;
|
|
7
|
+
let normB = 0;
|
|
8
|
+
for (let i = 0; i < a.length; i += 1) {
|
|
9
|
+
dot += a[i] * b[i];
|
|
10
|
+
normA += a[i] * a[i];
|
|
11
|
+
normB += b[i] * b[i];
|
|
12
|
+
}
|
|
13
|
+
if (normA === 0 || normB === 0)
|
|
14
|
+
return 0;
|
|
15
|
+
const cosine = dot / (Math.sqrt(normA) * Math.sqrt(normB));
|
|
16
|
+
return (cosine + 1) / 2;
|
|
17
|
+
}
|
package/dist/stale.d.ts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { SpotlightMemoryEntry, SpotlightMemoryInvalidationContext } from "@inupedia/spotlight-protocol";
|
|
2
|
+
export declare function isMemoryEntryStale(entry: SpotlightMemoryEntry, ctx: SpotlightMemoryInvalidationContext, now?: number): boolean;
|
|
3
|
+
export declare function pickSemanticHit<T extends {
|
|
4
|
+
entry: SpotlightMemoryEntry;
|
|
5
|
+
score: number;
|
|
6
|
+
}>(candidates: T[], threshold: number): T | null;
|
|
7
|
+
//# sourceMappingURL=stale.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"stale.d.ts","sourceRoot":"","sources":["../src/stale.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,oBAAoB,EACpB,kCAAkC,EACnC,MAAM,8BAA8B,CAAC;AAEtC,wBAAgB,kBAAkB,CAChC,KAAK,EAAE,oBAAoB,EAC3B,GAAG,EAAE,kCAAkC,EACvC,GAAG,SAAa,GACf,OAAO,CAqBT;AAED,wBAAgB,eAAe,CAAC,CAAC,SAAS;IAAE,KAAK,EAAE,oBAAoB,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,EACtF,UAAU,EAAE,CAAC,EAAE,EACf,SAAS,EAAE,MAAM,GAChB,CAAC,GAAG,IAAI,CAQV"}
|
package/dist/stale.js
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
export function isMemoryEntryStale(entry, ctx, now = Date.now()) {
|
|
2
|
+
if (entry.ttlSec > 0 && now - entry.createdAt > entry.ttlSec * 1000) {
|
|
3
|
+
return true;
|
|
4
|
+
}
|
|
5
|
+
const assetsChanged = entry.invalidation.assetsVersion != null &&
|
|
6
|
+
ctx.assetsVersion != null &&
|
|
7
|
+
entry.invalidation.assetsVersion !== ctx.assetsVersion;
|
|
8
|
+
const catalogChanged = entry.invalidation.catalogVersion != null &&
|
|
9
|
+
ctx.catalogVersion != null &&
|
|
10
|
+
entry.invalidation.catalogVersion !== ctx.catalogVersion;
|
|
11
|
+
if (assetsChanged && entry.kind === "data_snapshot")
|
|
12
|
+
return true;
|
|
13
|
+
if (catalogChanged && (entry.kind === "action_plan" || entry.kind === "routing_hint")) {
|
|
14
|
+
return true;
|
|
15
|
+
}
|
|
16
|
+
return false;
|
|
17
|
+
}
|
|
18
|
+
export function pickSemanticHit(candidates, threshold) {
|
|
19
|
+
if (!candidates.length)
|
|
20
|
+
return null;
|
|
21
|
+
const sorted = [...candidates].sort((a, b) => b.score - a.score);
|
|
22
|
+
const top = sorted[0];
|
|
23
|
+
const runner = sorted[1];
|
|
24
|
+
if (top.score < threshold)
|
|
25
|
+
return null;
|
|
26
|
+
if (runner && top.score - runner.score < 0.05)
|
|
27
|
+
return null;
|
|
28
|
+
return top;
|
|
29
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@inupedia/spotlight-memory",
|
|
3
|
+
"version": "0.1.5",
|
|
4
|
+
"description": "Memory Gate, exact/semantic cache stores for Inupedia Spotlight",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"author": "inupedia",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./dist/index.d.ts",
|
|
11
|
+
"import": "./dist/index.js"
|
|
12
|
+
},
|
|
13
|
+
"./node": {
|
|
14
|
+
"types": "./dist/node/index.d.ts",
|
|
15
|
+
"import": "./dist/node/index.js"
|
|
16
|
+
}
|
|
17
|
+
},
|
|
18
|
+
"main": "./dist/index.js",
|
|
19
|
+
"types": "./dist/index.d.ts",
|
|
20
|
+
"publishConfig": {
|
|
21
|
+
"access": "public"
|
|
22
|
+
},
|
|
23
|
+
"files": [
|
|
24
|
+
"dist"
|
|
25
|
+
],
|
|
26
|
+
"dependencies": {
|
|
27
|
+
"@inupedia/spotlight-protocol": "0.1.5"
|
|
28
|
+
},
|
|
29
|
+
"devDependencies": {
|
|
30
|
+
"@types/node": "^22.10.0",
|
|
31
|
+
"typescript": "^5.9.3",
|
|
32
|
+
"vitest": "^4.0.18"
|
|
33
|
+
},
|
|
34
|
+
"scripts": {
|
|
35
|
+
"clean": "rm -rf dist",
|
|
36
|
+
"typecheck": "tsc -p tsconfig.json --noEmit && tsc -p tsconfig.node.json --noEmit",
|
|
37
|
+
"build": "pnpm run clean && tsc -p tsconfig.json && tsc -p tsconfig.node.json && pnpm run verify:exports",
|
|
38
|
+
"verify:exports": "node ../scripts/verify-package-exports.mjs",
|
|
39
|
+
"test": "vitest run"
|
|
40
|
+
}
|
|
41
|
+
}
|