Files
Agent-Workbench/src/core/context/index-cache.mjs
T

127 lines
7.3 KiB
JavaScript

import fs from 'node:fs';
import path from 'node:path';
import { createHash, randomUUID } from 'node:crypto';
const hash = value => createHash('sha256').update(value).digest('hex');
const samePath = (a, b) => process.platform === 'win32' ? a.toLowerCase() === b.toLowerCase() : a === b;
const recordName = /^[a-f0-9]{64}\.json$/;
const failure = () => new Error('派生缓存目录或文件无法核对,已回退当前源码重建。');
// Stores only derived declarations/imports. Never stores source bodies, requests,
// credentials, execution results or recovery state. Every hit needs a fresh SHA.
export class IndexCache {
constructor({ directory, maximumProjects = 8, maximumBytes = 32 * 1024 * 1024, maximumEntryBytes = 8 * 1024 * 1024 } = {}) {
this.directory = directory ? path.resolve(directory) : null;
this.maximumProjects = maximumProjects; this.maximumBytes = maximumBytes; this.maximumEntryBytes = maximumEntryBytes;
this.enabled = true; this.error = null;
if (this.directory) {
try {
this.assertDirectory();
const filename = path.join(this.directory, 'settings.json');
if (fs.existsSync(filename)) {
this.assertFile(filename, 1024);
const settings = JSON.parse(fs.readFileSync(filename, 'utf8'));
if (settings.schemaVersion !== 1 || typeof settings.enabled !== 'boolean') throw failure();
this.enabled = settings.enabled;
}
this.trim();
} catch { this.enabled = false; this.error = '缓存设置无法核对,缓存已关闭;可修复目录后重新启用。'; }
}
}
key(project) { return hash(project.id + '\0' + project.root); }
assertDirectory() {
fs.mkdirSync(this.directory, { recursive: true, mode: 0o700 });
const stat = fs.lstatSync(this.directory);
if (!stat.isDirectory() || stat.isSymbolicLink() || !samePath(fs.realpathSync.native(this.directory), this.directory)) throw failure();
}
assertFile(filename, maximum = this.maximumEntryBytes) {
const stat = fs.lstatSync(filename);
if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1 || stat.size > maximum) throw failure();
return stat;
}
write(filename, value) {
this.assertDirectory();
if (fs.existsSync(filename)) this.assertFile(filename, Number.MAX_SAFE_INTEGER);
const temporary = path.join(this.directory, '.write-' + randomUUID() + '.tmp');
try {
fs.writeFileSync(temporary, value, { flag: 'wx', mode: 0o600 });
this.assertDirectory();
if (fs.existsSync(filename)) this.assertFile(filename, Number.MAX_SAFE_INTEGER);
fs.renameSync(temporary, filename);
} finally { if (fs.existsSync(temporary)) fs.unlinkSync(temporary); }
}
load(project, identity) {
if (!this.enabled || !this.directory) return { entries: null, reason: this.enabled ? 'process-only' : 'disabled' };
try {
this.assertDirectory();
const filename = path.join(this.directory, this.key(project) + '.json');
if (!fs.existsSync(filename)) return { entries: null, reason: 'cold' };
this.assertFile(filename);
const envelope = JSON.parse(fs.readFileSync(filename, 'utf8'));
if (envelope.schemaVersion !== 1 || hash(JSON.stringify(envelope.payload)) !== envelope.sha256) return { entries: null, reason: 'corrupt' };
const payload = envelope.payload;
if (JSON.stringify(payload.identity) !== JSON.stringify(identity)) return { entries: null, reason: 'identity-changed' };
if (!Array.isArray(payload.entries) || payload.entries.length > (this.maximumProjects === Infinity ? Infinity : 1000)) return { entries: null, reason: 'corrupt' };
return { entries: new Map(payload.entries.map(entry => [entry.path, entry])), reason: 'disk' };
} catch { this.error = '派生缓存读取失败;本次从当前源码重建。'; return { entries: null, reason: 'unavailable' }; }
}
save(project, identity, entries) {
if (!this.enabled || !this.directory) return { stored: false, reason: this.enabled ? 'process-only' : 'disabled' };
try {
const payload = { identity, entries: [...entries.values()] };
const text = JSON.stringify({ schemaVersion: 1, sha256: hash(JSON.stringify(payload)), payload });
if (Buffer.byteLength(text) > Math.min(this.maximumEntryBytes, this.maximumBytes)) {
this.clear(project); return { stored: false, reason: 'capacity' };
}
this.write(path.join(this.directory, this.key(project) + '.json'), text);
const evictedProjects = this.trim(); this.error = null;
return { stored: true, reason: 'stored', evictedProjects };
} catch { this.error = '派生缓存写入失败;当前索引仍来自本次源码核对。'; return { stored: false, reason: 'unavailable' }; }
}
touch(project) {
if (!this.enabled || !this.directory) return { stored: false, reason: this.enabled ? 'process-only' : 'disabled' };
try {
this.assertDirectory(); const filename = path.join(this.directory, this.key(project) + '.json');
if (!fs.existsSync(filename)) return { stored: false, reason: 'cold' };
this.assertFile(filename); const at = new Date(); fs.utimesSync(filename, at, at);
return { stored: true, reason: 'stored', evictedProjects: this.trim() };
} catch { this.error = '派生缓存不可用;当前索引来自本次源码核对。'; return { stored: false, reason: 'unavailable' }; }
}
records() {
if (!this.directory) return [];
this.assertDirectory();
return fs.readdirSync(this.directory).filter(name => recordName.test(name)).map(name => {
const filename = path.join(this.directory, name), stat = this.assertFile(filename, Number.MAX_SAFE_INTEGER);
return { filename, bytes: stat.size, touched: stat.mtimeMs };
});
}
trim() {
const records = this.records().sort((a, b) => a.touched - b.touched || a.filename.localeCompare(b.filename));
let bytes = records.reduce((sum, value) => sum + value.bytes, 0), evicted = 0;
while (records.length > this.maximumProjects || bytes > this.maximumBytes) {
const record = records.shift(); this.assertFile(record.filename); fs.unlinkSync(record.filename); bytes -= record.bytes; evicted++;
}
return evicted;
}
clear(project) {
if (!this.directory) return 0;
this.assertDirectory();
const names = project ? [path.join(this.directory, this.key(project) + '.json')] : this.records().map(value => value.filename);
let removed = 0;
for (const filename of names) if (fs.existsSync(filename)) { this.assertFile(filename, Number.MAX_SAFE_INTEGER); fs.unlinkSync(filename); removed++; }
return removed;
}
configure(enabled) {
if (typeof enabled !== 'boolean') throw new Error('缓存开关需要布尔值。');
if (this.directory) this.write(path.join(this.directory, 'settings.json'), JSON.stringify({ schemaVersion: 1, enabled }));
this.enabled = enabled; this.error = null;
}
status() {
let diskProjects = 0, diskBytes = 0;
try { const records = this.records(); diskProjects = records.length; diskBytes = records.reduce((sum, value) => sum + value.bytes, 0); }
catch { this.error = '派生缓存目录或文件无法核对;读取失败时将重建。'; }
return { enabled: this.enabled, persistent: !!this.directory, diskProjects, diskBytes, maximumProjects: this.maximumProjects,
maximumBytes: this.maximumBytes, maximumEntryBytes: this.maximumEntryBytes, error: this.error };
}
}