267 lines
15 KiB
JavaScript
267 lines
15 KiB
JavaScript
/** Atomic JSON storage for one local memory space. */
|
||
import { createHash, randomUUID } from 'node:crypto';
|
||
import { mkdir, open, readFile, rename, rm, stat, writeFile } from 'node:fs/promises';
|
||
import { dirname, join } from 'node:path';
|
||
const EMPTY_FILE = { version: 1, nextChange: 1, operations: {}, records: [] };
|
||
function nowIso() { return new Date().toISOString(); }
|
||
const SECRET_PATTERNS = [
|
||
/(?:api[ _-]?key|access[ _-]?token|client[ _-]?secret|secret|password|passwd|pwd)\s*(?:是|为|[:=:])\s*["']?[A-Za-z0-9_\-./+=]{6,}/i,
|
||
/(?:密码|口令|令牌|密钥|恢复码)\s*(?:是|为|[:=:])\s*\S{6,}/,
|
||
/\b(?:gh[pousr]_[A-Za-z0-9]{20,}|AKIA[0-9A-Z]{16}|xox[baprs]-[A-Za-z0-9-]{10,})\b/,
|
||
/\bBearer\s+[A-Za-z0-9\-._~+/]+=*/i,
|
||
];
|
||
/** Secrets never belong in a memory record or an automatic summary. */
|
||
export function containsSecret(value) { return SECRET_PATTERNS.some((pattern) => pattern.test(value)); }
|
||
function safeText(value, max = 64000) { return typeof value === 'string' ? value.trim().slice(0, max) : ''; }
|
||
function tagsOf(value) {
|
||
if (!Array.isArray(value))
|
||
return [];
|
||
const tags = value.filter((item) => typeof item === 'string').map((item) => item.trim()).filter((item) => item !== '');
|
||
return [...new Set(tags)].slice(0, 20);
|
||
}
|
||
async function atomicWrite(path, content) {
|
||
await mkdir(dirname(path), { recursive: true });
|
||
const tmp = path + '.' + String(process.pid) + '.' + randomUUID() + '.tmp';
|
||
try {
|
||
await writeFile(tmp, content, { encoding: 'utf8', mode: 0o600 });
|
||
await rename(tmp, path);
|
||
}
|
||
catch (error) {
|
||
await rm(tmp, { force: true }).catch(() => { });
|
||
throw error;
|
||
}
|
||
}
|
||
export async function withFileLock(lockPath, job) {
|
||
await mkdir(dirname(lockPath), { recursive: true });
|
||
const started = Date.now();
|
||
let handle;
|
||
while (handle === undefined) {
|
||
try {
|
||
handle = await open(lockPath, 'wx', 0o600);
|
||
}
|
||
catch (error) {
|
||
const code = error.code;
|
||
if (code !== 'EEXIST')
|
||
throw error;
|
||
const info = await stat(lockPath).catch(() => undefined);
|
||
if (info !== undefined && Date.now() - info.mtimeMs > 60000) {
|
||
await rm(lockPath, { force: true }).catch(() => { });
|
||
continue;
|
||
}
|
||
if (Date.now() - started > 10000)
|
||
throw new Error('local_memory_lock_timeout');
|
||
await new Promise((resolve) => setTimeout(resolve, 40));
|
||
}
|
||
}
|
||
try {
|
||
return await job();
|
||
}
|
||
finally {
|
||
await handle.close().catch(() => { });
|
||
await rm(lockPath, { force: true }).catch(() => { });
|
||
}
|
||
}
|
||
export class JsonMemoryStore {
|
||
root;
|
||
scope;
|
||
spaceId;
|
||
dataPath;
|
||
metaPath;
|
||
lockPath;
|
||
constructor(root, scope, spaceId) {
|
||
this.root = root;
|
||
this.scope = scope;
|
||
this.spaceId = spaceId;
|
||
this.dataPath = join(root, 'memories.json');
|
||
this.metaPath = join(root, 'space.json');
|
||
this.lockPath = join(root, '.lock');
|
||
}
|
||
async init(name = this.scope === 'global' ? '全局记忆' : '项目记忆') {
|
||
await mkdir(this.root, { recursive: true });
|
||
return withFileLock(this.lockPath, async () => {
|
||
const existing = await this.spaceMeta();
|
||
if (existing !== undefined)
|
||
return existing;
|
||
const meta = { id: this.spaceId, scope: this.scope, name, root: this.root, createdAt: nowIso(), active: true };
|
||
await atomicWrite(this.metaPath, JSON.stringify(meta, null, 2) + '\n');
|
||
return meta;
|
||
});
|
||
}
|
||
async setActive(active) {
|
||
return withFileLock(this.lockPath, async () => {
|
||
const existing = await this.spaceMeta();
|
||
if (existing === undefined)
|
||
throw new Error('local_memory_space_not_found');
|
||
const next = { ...existing, active };
|
||
await atomicWrite(this.metaPath, JSON.stringify(next, null, 2) + '\n');
|
||
return next;
|
||
});
|
||
}
|
||
async spaceMeta() {
|
||
let text;
|
||
try {
|
||
text = await readFile(this.metaPath, 'utf8');
|
||
}
|
||
catch (error) {
|
||
if (error.code === 'ENOENT')
|
||
return undefined;
|
||
throw new Error(`local_memory_meta_read_failed: ${this.metaPath}: ${error instanceof Error ? error.message : String(error)}`);
|
||
}
|
||
let parsed;
|
||
try {
|
||
parsed = JSON.parse(text);
|
||
}
|
||
catch {
|
||
throw new Error(`local_memory_meta_corrupt: ${this.metaPath}`);
|
||
}
|
||
if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed))
|
||
throw new Error(`local_memory_meta_corrupt: ${this.metaPath}`);
|
||
const value = parsed;
|
||
if (typeof value.id !== 'string' || (value.scope !== 'global' && value.scope !== 'project' && value.scope !== 'department'))
|
||
throw new Error(`local_memory_meta_incompatible: ${this.metaPath}`);
|
||
return { id: value.id, scope: value.scope, name: typeof value.name === 'string' ? value.name : value.id, root: typeof value.root === 'string' ? value.root : this.root, createdAt: typeof value.createdAt === 'string' ? value.createdAt : nowIso(), active: value.active !== false };
|
||
}
|
||
async readFile() {
|
||
let text;
|
||
try {
|
||
text = await readFile(this.dataPath, 'utf8');
|
||
}
|
||
catch (error) {
|
||
if (error.code === 'ENOENT')
|
||
return { ...EMPTY_FILE, operations: {}, records: [] };
|
||
throw new Error(`local_memory_read_failed: ${this.dataPath}: ${error instanceof Error ? error.message : String(error)}`);
|
||
}
|
||
let parsed;
|
||
try {
|
||
parsed = JSON.parse(text);
|
||
}
|
||
catch {
|
||
throw new Error(`local_memory_corrupt: ${this.dataPath}`);
|
||
}
|
||
if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed))
|
||
throw new Error(`local_memory_corrupt: ${this.dataPath}`);
|
||
const value = parsed;
|
||
if (value.version !== undefined && value.version !== 1)
|
||
throw new Error(`local_memory_incompatible: ${this.dataPath}`);
|
||
if (value.records !== undefined && !Array.isArray(value.records))
|
||
throw new Error(`local_memory_incompatible: ${this.dataPath}`);
|
||
return { version: 1, nextChange: typeof value.nextChange === 'number' && Number.isFinite(value.nextChange) ? value.nextChange : 1, operations: value.operations !== null && typeof value.operations === 'object' && !Array.isArray(value.operations) ? value.operations : {}, records: Array.isArray(value.records) ? value.records.filter((record) => record !== null && typeof record === 'object') : [] };
|
||
}
|
||
async writeFile(file) { await atomicWrite(this.dataPath, JSON.stringify(file, null, 2) + '\n'); }
|
||
activeRecords(file) { return file.records.filter((record) => record.deleted !== true); }
|
||
async add(input) {
|
||
const content = safeText(input.content);
|
||
if (content === '')
|
||
throw new Error('记忆内容不能为空');
|
||
if (containsSecret(content))
|
||
throw new Error('secret_not_allowed');
|
||
return withFileLock(this.lockPath, async () => {
|
||
const file = await this.readFile();
|
||
if (input.operationId !== undefined && input.operationId !== '') {
|
||
const prior = file.operations[input.operationId];
|
||
if (prior !== undefined) {
|
||
const found = file.records.find((record) => record.id === prior);
|
||
if (found !== undefined && found.deleted !== true)
|
||
return { record: found, duplicate: true, duplicateKind: 'operation' };
|
||
}
|
||
}
|
||
const duplicate = this.activeRecords(file).find((record) => record.content === content && record.spaceId === this.spaceId);
|
||
if (duplicate !== undefined)
|
||
return { record: duplicate, duplicate: true, duplicateKind: 'content' };
|
||
const timestamp = nowIso();
|
||
const record = { id: 'lm_' + randomUUID(), scope: this.scope, spaceId: this.spaceId, content, ...(input.category === undefined || input.category === '' ? {} : { category: input.category }), tags: tagsOf(input.tags), source: safeText(input.source, 500) || 'local', ...(input.sessionId === undefined ? {} : { sessionId: input.sessionId }), ...(input.projectId === undefined ? {} : { projectId: input.projectId }), ...(input.departmentId === undefined ? {} : { departmentId: input.departmentId }), createdAt: timestamp, updatedAt: timestamp, revision: 1, changeSeq: file.nextChange, ...(input.operationId === undefined ? {} : { operationId: input.operationId }) };
|
||
file.nextChange += 1;
|
||
file.records.push(record);
|
||
if (input.operationId !== undefined && input.operationId !== '')
|
||
file.operations[input.operationId] = record.id;
|
||
await this.writeFile(file);
|
||
return { record, duplicate: false };
|
||
});
|
||
}
|
||
async read(id) { return this.activeRecords(await this.readFile()).find((record) => record.id === id); }
|
||
async search(query, k = 5) {
|
||
const file = await this.readFile();
|
||
const q = query.trim().toLowerCase();
|
||
const terms = q.split(/\s+/).filter((term) => term !== '');
|
||
return this.activeRecords(file).map((record) => { const haystack = (record.content + '\n' + (record.tags ?? []).join(' ') + '\n' + (record.category ?? '')).toLowerCase(); const score = terms.length === 0 ? 1 : terms.reduce((sum, term) => sum + (haystack.includes(term) ? 1 : 0), 0); return { record, score }; }).filter((hit) => terms.length === 0 || hit.score > 0).sort((a, b) => b.score - a.score || b.record.updatedAt.localeCompare(a.record.updatedAt)).slice(0, Math.max(1, Math.min(100, Math.trunc(k))));
|
||
}
|
||
async list(options = {}) {
|
||
const file = await this.readFile();
|
||
const records = this.activeRecords(file).sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
|
||
const offset = Math.max(0, Math.trunc(options.offset ?? 0));
|
||
const limit = Math.max(1, Math.min(1000, Math.trunc(options.limit ?? 50)));
|
||
return { items: records.slice(offset, offset + limit), total: records.length };
|
||
}
|
||
async update(id, patch, expectedRevision) {
|
||
return withFileLock(this.lockPath, async () => { const file = await this.readFile(); const record = file.records.find((item) => item.id === id && item.deleted !== true); if (record === undefined)
|
||
throw new Error('memory_not_found'); if (expectedRevision !== undefined && record.revision !== expectedRevision)
|
||
throw new Error('revision_conflict'); if (patch.content !== undefined) {
|
||
const content = safeText(patch.content);
|
||
if (content === '')
|
||
throw new Error('记忆内容不能为空');
|
||
if (containsSecret(content))
|
||
throw new Error('secret_not_allowed');
|
||
record.content = content;
|
||
} if (patch.tags !== undefined)
|
||
record.tags = tagsOf(patch.tags); if (patch.category !== undefined)
|
||
record.category = patch.category; record.revision += 1; record.changeSeq = file.nextChange; record.updatedAt = nowIso(); file.nextChange += 1; await this.writeFile(file); return record; });
|
||
}
|
||
async forget(id, expectedRevision) {
|
||
return withFileLock(this.lockPath, async () => { const file = await this.readFile(); const record = file.records.find((item) => item.id === id && item.deleted !== true); if (record === undefined)
|
||
throw new Error('memory_not_found'); if (expectedRevision !== undefined && record.revision !== expectedRevision)
|
||
throw new Error('revision_conflict'); record.deleted = true; record.revision += 1; record.changeSeq = file.nextChange; record.updatedAt = nowIso(); file.nextChange += 1; await this.writeFile(file); return record; });
|
||
}
|
||
async records() { return this.activeRecords(await this.readFile()); }
|
||
}
|
||
export class JsonDocumentStore {
|
||
root;
|
||
indexPath;
|
||
lockPath;
|
||
constructor(root) { this.root = root; this.indexPath = join(root, 'index.json'); this.lockPath = join(root, '.lock'); }
|
||
async init() { await mkdir(this.root, { recursive: true }); await mkdir(join(this.root, 'files'), { recursive: true }); }
|
||
async read() {
|
||
let text;
|
||
try {
|
||
text = await readFile(this.indexPath, 'utf8');
|
||
}
|
||
catch (error) {
|
||
if (error.code === 'ENOENT')
|
||
return { version: 1, nextRevision: 1, documents: [] };
|
||
throw new Error(`local_documents_read_failed: ${this.indexPath}: ${error instanceof Error ? error.message : String(error)}`);
|
||
}
|
||
let parsed;
|
||
try {
|
||
parsed = JSON.parse(text);
|
||
}
|
||
catch {
|
||
throw new Error(`local_documents_corrupt: ${this.indexPath}`);
|
||
}
|
||
if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed))
|
||
throw new Error(`local_documents_corrupt: ${this.indexPath}`);
|
||
const value = parsed;
|
||
if (value.documents !== undefined && !Array.isArray(value.documents))
|
||
throw new Error(`local_documents_incompatible: ${this.indexPath}`);
|
||
return { version: 1, nextRevision: typeof value.nextRevision === 'number' ? value.nextRevision : 1, documents: Array.isArray(value.documents) ? value.documents : [] };
|
||
}
|
||
async write(file) { await atomicWrite(this.indexPath, JSON.stringify(file, null, 2) + '\n'); }
|
||
async add(input) {
|
||
const title = safeText(input.title, 500);
|
||
const content = safeText(input.content, 200000);
|
||
if (title === '' || content === '')
|
||
throw new Error('文档标题和内容不能为空');
|
||
if (containsSecret(title) || containsSecret(content))
|
||
throw new Error('secret_not_allowed');
|
||
return withFileLock(this.lockPath, async () => { const file = await this.read(); const duplicate = file.documents.find((document) => document.deleted !== true && document.title === title && document.content === content); if (duplicate !== undefined) {
|
||
const filePath = join(this.root, 'files', duplicate.id + '.md');
|
||
if ((await readFile(filePath).catch(() => undefined)) === undefined)
|
||
await atomicWrite(filePath, '# ' + title + '\n\n' + content + '\n');
|
||
return duplicate;
|
||
} const timestamp = nowIso(); const document = { id: 'doc_' + randomUUID(), title, content, source: safeText(input.source, 500) || 'local', tags: tagsOf(input.tags), createdAt: timestamp, updatedAt: timestamp, revision: 1 }; file.documents.push(document); await this.write(file); await atomicWrite(join(this.root, 'files', document.id + '.md'), '# ' + title + '\n\n' + content + '\n'); return document; });
|
||
}
|
||
async list() { return (await this.read()).documents.filter((document) => document.deleted !== true); }
|
||
async readDocument(id) { return (await this.read()).documents.find((document) => document.id === id && document.deleted !== true); }
|
||
async remove(id) { await withFileLock(this.lockPath, async () => { const file = await this.read(); const document = file.documents.find((item) => item.id === id && item.deleted !== true); if (document === undefined)
|
||
return; document.deleted = true; document.revision += 1; document.updatedAt = nowIso(); await this.write(file); }); }
|
||
}
|
||
export function localMemoryHash(value) { return createHash('sha256').update(value).digest('hex'); }
|