/** * ============================================================ * src/context/sessionPath.ts —— 按目录隔离的会话文件路径 * ------------------------------------------------------------ * 做的事: * 新会话使用 Workspace Index 的稳定 workspaceId,写入 * ~/.minimal-agent/sessions/workspace---.json。 * 因此外接盘挂载名、盘符或 symlink 表达变化时仍指向同一份历史。 * * 旧命名规则(路径索引时代,仍用于兼容迁移): * -<6-hex-hash>--.json * sanitized:路径归一化后只保留 [a-z0-9-],最长 80 字符 * hash :原始路径 sha1 前 6 位,防 sanitize 后碰撞 * sessionId:v2 多 session 支持;默认 'default' * * resolveSessionFile() 会验证当前路径及 Workspace Index 中的历史别名, * 首次打开旧文件时复制到稳定文件名;旧文件保留作为恢复依据。 * * 迁移: * 旧版 ~/.minimal-agent/last-context.json 启动时一次性 rename 到 * 当前 cwd 对应的会话文件。失败静默——丢迁移好过崩进程。 * ============================================================ */ import { createHash } from 'node:crypto'; import { constants, readFileSync, realpathSync } from 'node:fs'; import { chmod, copyFile, mkdir, rename, stat } from 'node:fs/promises'; import { dirname, join, resolve } from 'node:path'; import { agentStateDir } from './agentHome.js'; const DEFAULT_SESSION_ID = 'default'; const SESSION_ID_RE = /^[a-zA-Z0-9][a-zA-Z0-9._-]{0,79}$/; interface IndexedWorkspaceIdentity { id: string; canonicalPath: string; displayPath?: string; pathAliases?: string[]; } function comparablePath(path: string): string { try { return realpathSync(resolve(path)).replace(/\\/g, '/').toLowerCase(); } catch { return resolve(path).replace(/\\/g, '/').toLowerCase(); } } function mountStablePath(path: string): string { return comparablePath(path).replace(/^\/volumes\/([^/]+?) \d+(\/|$)/, '/volumes/$1$2'); } function indexedWorkspaceFor(cwd: string): IndexedWorkspaceIdentity | null { try { const parsed = JSON.parse(readFileSync(join(agentStateDir(), 'workspace-index.json'), 'utf8')) as { workspaces?: IndexedWorkspaceIdentity[]; }; const target = comparablePath(cwd); const mountTarget = mountStablePath(cwd); return parsed.workspaces?.find((workspace) => [ workspace.canonicalPath, workspace.displayPath, ...(workspace.pathAliases ?? []), ].some((path) => typeof path === 'string' && (comparablePath(path) === target || mountStablePath(path) === mountTarget))) ?? null; } catch { return null; } } function stableSessionFileFor(workspaceId: string, sessionId: string): string { const safeWorkspaceId = workspaceId.replace(/[^a-zA-Z0-9._-]/g, ''); if (!safeWorkspaceId) throw new Error('workspace id 无效'); return join(agentStateDir(), 'sessions', `workspace-${safeWorkspaceId}--${validateSessionId(sessionId)}.json`); } /** 仅用于旧历史识别和迁移;新调用应使用 sessionFileFor。 */ export function legacyPathSessionFileFor(cwd: string, sessionId: string = DEFAULT_SESSION_ID): string { const safeSessionId = validateSessionId(sessionId); const normalized = resolve(cwd).replace(/\\/g, '/').toLowerCase(); const sanitized = normalized .replace(/:/g, '') .replace(/[^a-z0-9]+/g, '-') .replace(/^-+|-+$/g, '') .slice(0, 80); const hash = createHash('sha1').update(normalized).digest('hex').slice(0, 6); return join(agentStateDir(), 'sessions', `${sanitized}-${hash}--${safeSessionId}.json`); } export function validateSessionId(sessionId: string): string { const value = sessionId.trim(); if (!SESSION_ID_RE.test(value) || value === '.' || value === '..' || value.includes('..')) { throw new Error('session id 只能包含字母、数字、点、下划线和短横线,且长度不超过 80'); } return value; } /** * 把 cwd + sessionId 编码成会话文件绝对路径。 * * @param cwd 工作目录 * @param sessionId 多 session 支持的 id;缺省 'default' * * 注意:'default' 调用走新格式 `--default.json`。如果磁盘上只有 * 旧格式 `.json`(v1 历史文件),需要用 resolveSessionFile() * 拿到实际存在的路径用于 load。 */ export function sessionFileFor( cwd: string, sessionId: string = DEFAULT_SESSION_ID, ): string { const safeSessionId = validateSessionId(sessionId); const workspace = indexedWorkspaceFor(cwd); return workspace ? stableSessionFileFor(workspace.id, safeSessionId) : legacyPathSessionFileFor(cwd, safeSessionId); } /** 旧格式(v1,不带 `--` 后缀)—— 仅 'default' session 可能存在 */ function legacySessionFileFor(cwd: string): string { const normalized = resolve(cwd).replace(/\\/g, '/').toLowerCase(); const sanitized = normalized .replace(/:/g, '') .replace(/[^a-z0-9]+/g, '-') .replace(/^-+|-+$/g, '') .slice(0, 80); const hash = createHash('sha1').update(normalized).digest('hex').slice(0, 6); return join( agentStateDir(), 'sessions', `${sanitized}-${hash}.json`, ); } /** * 解析 cwd + sessionId 对应的实际存在的会话文件路径。 * * - 新格式(带 `--`)存在 → 返回新路径 * - 仅 sessionId='default' 且新路径不存在但旧路径(不带 `--`)存在 → 返回旧路径 * - 都不存在 → 返回新路径(让调用方按新格式 create) */ export async function resolveSessionFile( cwd: string, sessionId: string = DEFAULT_SESSION_ID, ): Promise { const fresh = sessionFileFor(cwd, sessionId); try { await stat(fresh); return fresh; } catch { // 新路径不存在 } const workspace = indexedWorkspaceFor(cwd); const aliases = workspace ? [cwd, workspace.canonicalPath, workspace.displayPath, ...(workspace.pathAliases ?? [])] : [cwd]; const candidates = [...new Set(aliases.filter((value): value is string => typeof value === 'string'))] .flatMap((path) => [ legacyPathSessionFileFor(path, sessionId), ...(sessionId === DEFAULT_SESSION_ID ? [legacySessionFileFor(path)] : []), ]); for (const legacy of candidates) { try { await stat(legacy); } catch { continue; } if (legacy !== fresh && workspace) { try { await mkdir(dirname(fresh), { recursive: true }); await copyFile(legacy, fresh, constants.COPYFILE_EXCL).catch(async (error) => { if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error; }); await chmod(fresh, 0o600).catch(() => {}); return fresh; } catch { // Migration is an optimization. The verified legacy history remains // authoritative when the stable destination cannot be written. return legacy; } } return legacy; } return fresh; } /** * 一次性把旧版 ~/.minimal-agent/last-context.json 迁到当前 cwd 对应的 * 会话文件。 * * 静默策略: * - 旧文件不存在 → 直接返回 * - rename 失败(目标已存在 / 权限等)→ 忽略,旧文件原位等下次启动 */ export async function migrateLegacyContext(cwd: string): Promise { const legacy = join(agentStateDir(), 'last-context.json'); try { await stat(legacy); } catch { return; } const target = sessionFileFor(cwd); try { await mkdir(dirname(target), { recursive: true }); await rename(legacy, target); } catch { // 静默 } }