Repository navigation
Expand file tree
/
Copy pathindex.ts
More file actions
285 lines (259 loc) · 9.35 KB
/
Copy pathindex.ts
File metadata and controls
285 lines (259 loc) · 9.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
import type {
IKnowledgeAdapter,
IKnowledgeService,
AdapterContext,
AdapterListDocumentsOptions,
AdapterListDocumentsPage,
AdapterSearchOptions,
} from '@objectstack/spec/contracts';
import type {
KnowledgeDocument,
KnowledgeHit,
} from '@objectstack/spec/ai';
import { KNOWLEDGE_SERVICE } from '@objectstack/spec/contracts';
/**
* In-memory knowledge adapter. Stores per-source document maps,
* chunks documents naively on paragraph boundaries (with a soft 800-char
* cap), embeds each chunk as a sparse token-frequency vector, and
* answers `search()` via brute-force cosine similarity.
*
* Deterministic — same input always produces the same hits — so it's
* great for tests and reference implementations. **Don't use in prod.**
*
* The reference implementation of `listDocuments` (ADR-0161 K8, item 1): it
* stores each document's `docHash` as given and lists it back as stored, in
* document-id order, the cursor being the last id of the page before. It runs
* the contract suite of `@objectstack/service-knowledge/testing`.
*
* The first reader of the organization filter (ADR-0161 K8, item 9): it
* stores each document's `organizationId` as given and, when a search is
* handed `organizationIds`, ranks only the documents whose organization is in
* that set — the filter runs before the scoring, so `topK` is filled from them
* alone. An empty set ranks nothing; a document stored without an
* organization is not ranked by a filtered search.
*/
export class KnowledgeMemoryAdapter implements IKnowledgeAdapter {
readonly id: string;
private readonly store = new Map<string, ChunkRecord[]>();
constructor(id = 'memory') {
this.id = id;
}
async upsert(docs: KnowledgeDocument[], ctx: AdapterContext): Promise<void> {
const sourceId = ctx.source.id;
const existing = this.store.get(sourceId) ?? [];
const byDoc = new Map<string, ChunkRecord[]>();
for (const c of existing) {
const arr = byDoc.get(c.documentId) ?? [];
arr.push(c);
byDoc.set(c.documentId, arr);
}
for (const doc of docs) {
byDoc.set(doc.id, chunkAndEmbed(doc));
}
this.store.set(sourceId, Array.from(byDoc.values()).flat());
}
async delete(documentIds: string[], ctx: AdapterContext): Promise<void> {
const sourceId = ctx.source.id;
const chunks = this.store.get(sourceId);
if (!chunks) return;
const dropSet = new Set(documentIds);
this.store.set(
sourceId,
chunks.filter((c) => !dropSet.has(c.documentId)),
);
}
async listDocuments(ctx: AdapterContext, opts: AdapterListDocumentsOptions): Promise<AdapterListDocumentsPage> {
if (!Number.isInteger(opts.limit) || opts.limit < 1) {
throw new RangeError(`listDocuments: limit must be a positive integer, got ${String(opts.limit)}`);
}
// One entry per document, from its first chunk (every chunk carries the
// document's hash), in id order so a cursor stays valid across writes.
const byDoc = new Map<string, string | undefined>();
for (const c of this.store.get(ctx.source.id) ?? []) {
if (!byDoc.has(c.documentId)) byDoc.set(c.documentId, c.docHash);
}
const ids = [...byDoc.keys()]
.filter((id) => opts.cursor === undefined || id > opts.cursor)
.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
const page = ids.slice(0, opts.limit);
return {
documents: page.map((documentId) => {
const docHash = byDoc.get(documentId);
return docHash === undefined ? { documentId } : { documentId, docHash };
}),
...(ids.length > page.length ? { nextCursor: page[page.length - 1] } : {}),
};
}
async search(query: string, opts: AdapterSearchOptions): Promise<KnowledgeHit[]> {
const chunks = this.store.get(opts.source.id) ?? [];
if (chunks.length === 0) return [];
const qVec = embedTokens(tokenize(query));
const qNorm = vectorNorm(qVec);
if (qNorm === 0) return [];
// The organization filter first (ADR-0161 K8, item 9): absent → every
// document; present → only the documents of those organizations, so a
// document with none is out, and `[]` leaves nothing to rank.
const organizations = opts.organizationIds === undefined ? undefined : new Set(opts.organizationIds);
const inScope = organizations === undefined
? chunks
: chunks.filter((c) => c.organizationId !== undefined && organizations.has(c.organizationId));
const filter = opts.filter ?? {};
const filtered = Object.keys(filter).length
? inScope.filter((c) => matchesFilter(c.metadata, filter))
: inScope;
const scored = filtered.map((c) => ({
chunk: c,
score: cosineSimilarity(qVec, c.vector, qNorm, c.vectorNorm),
}));
scored.sort((a, b) => b.score - a.score);
const top = scored.slice(0, opts.topK).filter((s) => s.score > 0);
return top.map<KnowledgeHit>(({ chunk, score }) => ({
chunkId: chunk.chunkId,
documentId: chunk.documentId,
sourceId: opts.source.id,
sourceRecordId: chunk.sourceRecordId,
score,
snippet: chunk.content,
title: chunk.title,
metadata: chunk.metadata,
}));
}
async healthCheck(): Promise<{ ok: boolean; message?: string }> {
return { ok: true, message: `memory adapter (${this.store.size} sources)` };
}
}
interface ChunkRecord {
chunkId: string;
documentId: string;
sourceRecordId?: string;
/** The document's `docHash`, stored as given (ADR-0161 K8, item 2). */
docHash?: string;
/** The document's `organizationId`, stored as given (ADR-0161 K8, item 9). */
organizationId?: string;
content: string;
title?: string;
metadata: Record<string, unknown>;
vector: Map<string, number>;
vectorNorm: number;
}
const CHUNK_TARGET = 800;
function chunkAndEmbed(doc: KnowledgeDocument): ChunkRecord[] {
const paragraphs = doc.content
.split(/\n{2,}/)
.map((p) => p.trim())
.filter(Boolean);
const chunks: string[] = [];
let buf = '';
for (const p of paragraphs.length ? paragraphs : [doc.content]) {
if (buf && buf.length + p.length + 2 > CHUNK_TARGET) {
chunks.push(buf);
buf = '';
}
if (p.length > CHUNK_TARGET) {
if (buf) {
chunks.push(buf);
buf = '';
}
for (let i = 0; i < p.length; i += CHUNK_TARGET) {
chunks.push(p.slice(i, i + CHUNK_TARGET));
}
} else {
buf = buf ? `${buf}\n\n${p}` : p;
}
}
if (buf) chunks.push(buf);
return chunks.map((content, idx) => {
const vec = embedTokens(tokenize(content));
return {
chunkId: `${doc.id}#${idx}`,
documentId: doc.id,
sourceRecordId: doc.sourceRecordId,
docHash: doc.docHash,
organizationId: doc.organizationId,
content,
title: doc.title,
metadata: doc.metadata ?? {},
vector: vec,
vectorNorm: vectorNorm(vec),
};
});
}
function tokenize(text: string): string[] {
return text
.toLowerCase()
.split(/[^a-z0-9\u4e00-\u9fff]+/i)
.filter((t) => t.length > 1);
}
function embedTokens(tokens: string[]): Map<string, number> {
const vec = new Map<string, number>();
for (const t of tokens) vec.set(t, (vec.get(t) ?? 0) + 1);
return vec;
}
function vectorNorm(v: Map<string, number>): number {
let s = 0;
for (const x of v.values()) s += x * x;
return Math.sqrt(s);
}
function cosineSimilarity(
a: Map<string, number>,
b: Map<string, number>,
aNorm = vectorNorm(a),
bNorm = vectorNorm(b),
): number {
if (aNorm === 0 || bNorm === 0) return 0;
// iterate smaller map
const [small, big] = a.size < b.size ? [a, b] : [b, a];
let dot = 0;
for (const [k, v] of small) {
const w = big.get(k);
if (w) dot += v * w;
}
return dot / (aNorm * bNorm);
}
function matchesFilter(
metadata: Record<string, unknown>,
filter: Record<string, unknown>,
): boolean {
for (const [k, v] of Object.entries(filter)) {
if (metadata[k] !== v) return false;
}
return true;
}
/* ---------------------------------------------------------------- */
/* Kernel plugin glue */
/* ---------------------------------------------------------------- */
import type { Plugin, PluginContext } from '@objectstack/core';
export interface KnowledgeMemoryPluginOptions {
/** Adapter id. @default 'memory' */
id?: string;
}
/**
* `KnowledgeMemoryPlugin` — registers a `KnowledgeMemoryAdapter` with
* the host's `IKnowledgeService` during `start()`.
*/
export class KnowledgeMemoryPlugin implements Plugin {
name = 'com.objectstack.plugin.knowledge-memory';
version = '0.1.0';
type = 'standard' as const;
private readonly adapter: KnowledgeMemoryAdapter;
constructor(opts: KnowledgeMemoryPluginOptions = {}) {
this.adapter = new KnowledgeMemoryAdapter(opts.id ?? 'memory');
}
async init(_ctx: PluginContext): Promise<void> {
// No-op: registration happens in start() once IKnowledgeService is up.
}
async start(ctx: PluginContext): Promise<void> {
let svc: IKnowledgeService | undefined;
try {
svc = ctx.getService<IKnowledgeService>(KNOWLEDGE_SERVICE);
} catch {
ctx.logger.warn?.(
'KnowledgeMemoryPlugin: IKnowledgeService not registered — install KnowledgeServicePlugin first.',
);
return;
}
svc.registerAdapter(this.adapter.id, this.adapter);
ctx.logger.info?.(`KnowledgeMemoryPlugin: adapter '${this.adapter.id}' registered.`);
}
}