refactor: unify agent session persistence

This commit is contained in:
2026-06-04 15:02:27 +08:00
parent 04ded0ceb0
commit 0ecb2babf3
22 changed files with 542 additions and 497 deletions
+5 -11
View File
@@ -20,7 +20,7 @@ export const atomicWriteFile = async (path: string, content: string) => {
type HistoricalWriteOptions = {
afterWrite?: () => Promise<void> | void;
historyDir: string;
backupDir: string;
rootDir: string;
};
@@ -36,8 +36,8 @@ export const atomicWriteFileWithHistory = async (
let backupPath: string | null = null;
if (previous !== null) {
// 仅在覆盖已有文件时保留历史版本,避免为首次创建产生空备份。
backupPath = buildHistoryBackupPath(path, options);
// 仅在覆盖已有文件时保留备份版本,避免为首次创建产生空备份。
backupPath = buildBackupPath(path, options);
await atomicWriteFile(backupPath, previous);
}
@@ -149,12 +149,6 @@ export const toProjectKey = (projectId?: string) => toScopedKey("project", proje
export const toStableId = (...parts: string[]) =>
createHash("sha256").update(parts.join("|")).digest("hex").slice(0, 24);
export const toConversationScopeKey = (
actorKey: string,
projectKey: string,
sessionId: string,
) => `conversation-${toStableId(actorKey, projectKey, sessionId)}`;
export const slugify = (value: string) =>
value
.toLowerCase()
@@ -162,11 +156,11 @@ export const slugify = (value: string) =>
.replace(/^-+|-+$/g, "")
.slice(0, 64) || "entry";
const buildHistoryBackupPath = (path: string, options: HistoricalWriteOptions) => {
const buildBackupPath = (path: string, options: HistoricalWriteOptions) => {
const relativePath = relative(options.rootDir, path);
const scopedPath =
relativePath && !relativePath.startsWith("..") ? relativePath : basename(path);
// 备份目录尽量复用原始相对路径,便于按业务目录回看历史。
const backupName = `${basename(path)}.${Date.now().toString(36)}.bak`;
return join(options.historyDir, dirname(scopedPath), backupName);
return join(options.backupDir, dirname(scopedPath), backupName);
};