Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(bots): 去掉无硬链接时的补种回退,不再按内容猜测写入是否中断

Claudeafab7c626e52
diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts
index 088b5972e9..59afc32918 100644
--- a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts
+++ b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts
@@ -12,7 +12,7 @@ import type { AgentInputQueuedMessage } from '../../../../shared/agentInputQueue
import type { ProviderView } from '@cindy/model-providers';
import { createHash } from 'node:crypto';
import { join, resolve } from 'node:path';
-import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { existsSync, mkdirSync, promises as fsPromises, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { drizzle } from 'drizzle-orm/better-sqlite3';
import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -918,21 +918,27 @@ describe('Bot canonical Session lifecycle', () => {
expect(readFileSync(join(home, 'SOUL.md'), 'utf8')).toBe('Stored identity');
});
- it('completes an interrupted seed before reconcile reads it, instead of absorbing a truncated SOUL.md', async () => {
+ it('keeps the stored identity when the Home cannot be seeded without hard links', async () => {
const created = await invoke('local-db:bots:create', {
- id: 'interrupted-seed', name: 'Interrupted Seed', identitySource: 'Stored identity',
+ id: 'no-hardlinks', name: 'No Hardlinks', identitySource: 'Stored identity',
+ userContextSource: 'Stored user context',
});
const home = join(h.userDataDir, createHash('sha256').update(h.ownerScopeKey).digest('hex'), 'bots', created.id);
- // A seed that failed mid-write on a filesystem without hard links.
- writeFileSync(join(home, 'SOUL.md'), 'Stored');
- writeFileSync(join(home, 'SOUL.md.seeding'), 'Stored identity');
- const canonical = await invoke('local-db:bots:create-canonical-session', {
- botId: created.id, expectedCanonicalSessionId: null, expectedProfileVersion: 1,
+ rmSync(join(home, 'SOUL.md'));
+ const link = vi.spyOn(fsPromises, 'link').mockRejectedValue(Object.assign(new Error('EPERM'), { code: 'EPERM' }));
+ try {
+ const canonical = await invoke('local-db:bots:create-canonical-session', {
+ botId: created.id, expectedCanonicalSessionId: null, expectedProfileVersion: 1,
+ });
+ expect(canonical.canonicalSessionId).toBeTruthy();
+ } finally {
+ link.mockRestore();
+ }
+ // The database stays authoritative: no version is derived from a Home that could not be seeded.
+ expect(await invoke('local-db:bots:get', created.id)).toMatchObject({
+ currentVersion: 1, identitySource: 'Stored identity', userContextSource: 'Stored user context',
});
- expect(canonical.canonicalSessionId).toBeTruthy();
- expect(await invoke('local-db:bots:get', created.id)).toMatchObject({ currentVersion: 1, identitySource: 'Stored identity' });
- expect(readFileSync(join(home, 'SOUL.md'), 'utf8')).toBe('Stored identity');
- expect(existsSync(join(home, 'SOUL.md.seeding'))).toBe(false);
+ expect(existsSync(join(home, 'SOUL.md'))).toBe(false);
});
it('seeds a never-created Bot Home on an unrelated save without touching an existing one', async () => {
diff --git a/apps/desktop/src/main/localDb/ipc/bots.ts b/apps/desktop/src/main/localDb/ipc/bots.ts
index 8c88c0e16d..90a6cfa98c 100644
--- a/apps/desktop/src/main/localDb/ipc/bots.ts
+++ b/apps/desktop/src/main/localDb/ipc/bots.ts
@@ -52,7 +52,6 @@ import {
botProfileDir,
ensureBotWorkspaceDir,
migrateBotProfileFolder,
- recoverInterruptedBotProfileSeed,
readBotProfileFolder,
writeBotProfileFolder,
} from '../../maker-ipc/botProfileFolder.js';
@@ -342,10 +341,7 @@ export async function reconcileBotProfileFolder(
currentVersion: profile.currentVersion,
};
},
- readFolder: async (id) => {
- await recoverInterruptedBotProfileSeed(userDataDir, id);
- return readBotProfileFolder(userDataDir, id);
- },
+ readFolder: (id) => readBotProfileFolder(userDataDir, id),
// 播种顺带把技能从旧目录搬进来 —— 存量伙伴第一次走到这里时一并完成。
seedFolder: async (id, seed) => {
await migrateBotProfileFolder(userDataDir, id, seed, legacyUserDataDir);
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/botProfileFolder.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/botProfileFolder.test.ts
index 9bf55c1597..8edae31a2e 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/botProfileFolder.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/botProfileFolder.test.ts
@@ -273,77 +273,31 @@ describe('搬家', () => {
expect((await fs.readdir(path.join(home, 'memories'))).filter((name) => name.includes('.tmp-'))).toEqual([]);
});
- it('不支持硬链接的文件系统退回独占创建,不替换已有文件,不留标记与临时文件', async () => {
+ it('不支持硬链接的文件系统不补种:不写目标文件,已有文件不动,不留临时文件,技能照常搬', async () => {
await writeBotProfileFolder(root, 'bot-a', { userContextSource: '用户手改的档案' });
+ const legacy = path.join(root, 'bot-skills', 'bot-a');
+ await fs.mkdir(path.join(legacy, 'skills', 's1'), { recursive: true });
+ await fs.writeFile(path.join(legacy, 'skills', 's1', 'SKILL.md'), 'v1', 'utf8');
const link = vi.spyOn(fs, 'link').mockRejectedValue(Object.assign(new Error('EPERM'), { code: 'EPERM' }));
const writeFile = vi.spyOn(fs, 'writeFile');
try {
- expect((await migrateBotProfileFolder(root, 'bot-a', SEED)).seeded).toBe(true);
- // Content never lands on a target path through a replacing write.
+ await expect(migrateBotProfileFolder(root, 'bot-a', SEED)).rejects.toMatchObject({ code: 'EPERM' });
+ // Nothing is ever written straight onto a target path.
for (const [target] of writeFile.mock.calls) {
- expect(String(target)).toMatch(/\.tmp-|\.seeding$/);
+ expect(String(target)).toMatch(/\.tmp-/);
}
} finally {
link.mockRestore();
writeFile.mockRestore();
}
- const content = await readBotProfileFolder(root, 'bot-a');
- expect(content.identitySource).toBe(SEED.identitySource);
- expect(content.userContextSource).toBe('用户手改的档案');
- expect(content.config).toEqual(SEED.config);
const home = botProfileDir(root, 'bot-a');
+ await expect(fs.access(path.join(home, 'SOUL.md'))).rejects.toBeTruthy();
+ expect((await readBotProfileFolder(root, 'bot-a')).userContextSource).toBe('用户手改的档案');
const leftovers = [...await fs.readdir(home), ...await fs.readdir(path.join(home, 'memories'))]
- .filter((name) => name.includes('.tmp-') || name.endsWith('.seeding'));
+ .filter((name) => name.includes('.tmp-'));
expect(leftovers).toEqual([]);
- });
-
- it('不支持硬链接时,检查之后才出现的文件同样不会被替换', async () => {
- await writeBotProfileFolder(root, 'bot-a', { identitySource: '编辑器刚保存的灵魂' });
- const link = vi.spyOn(fs, 'link').mockRejectedValue(Object.assign(new Error('EPERM'), { code: 'EPERM' }));
- // Every existence check still misses SOUL.md: it is saved right after each look.
- const realAccess = fs.access.bind(fs);
- const access = vi.spyOn(fs, 'access').mockImplementation(async (target, mode) => {
- if (String(target).endsWith('SOUL.md')) throw Object.assign(new Error('ENOENT'), { code: 'ENOENT' });
- return realAccess(target, mode);
- });
- try {
- expect((await migrateBotProfileFolder(root, 'bot-a', SEED)).seeded).toBe(false);
- } finally {
- link.mockRestore();
- access.mockRestore();
- }
- expect((await readBotProfileFolder(root, 'bot-a')).identitySource).toBe('编辑器刚保存的灵魂');
- });
-
- it('无硬链接补种写到一半失败时保留恢复标记,下一次补种把截断的文件补全', async () => {
- const link = vi.spyOn(fs, 'link').mockRejectedValue(Object.assign(new Error('EPERM'), { code: 'EPERM' }));
- const realOpen = fs.open.bind(fs);
- let failed = false;
- const open = vi.spyOn(fs, 'open').mockImplementation(async (target, flags) => {
- const handle = await realOpen(target, flags);
- if (failed || !String(target).endsWith('SOUL.md')) return handle;
- failed = true;
- return Object.assign(Object.create(handle), {
- writeFile: async (data: string) => {
- await handle.writeFile(data.slice(0, 2));
- throw Object.assign(new Error('ENOSPC'), { code: 'ENOSPC' });
- },
- sync: () => handle.sync(),
- close: () => handle.close(),
- });
- });
- const home = botProfileDir(root, 'bot-a');
- try {
- await expect(migrateBotProfileFolder(root, 'bot-a', SEED)).rejects.toMatchObject({ code: 'ENOSPC' });
- // The truncated SOUL.md still has its marker to recover from.
- expect(await fs.readFile(path.join(home, 'SOUL.md.seeding'), 'utf8')).toBe(SEED.identitySource);
- } finally {
- open.mockRestore();
- link.mockRestore();
- }
- await migrateBotProfileFolder(root, 'bot-a', SEED);
- expect((await readBotProfileFolder(root, 'bot-a')).identitySource).toBe(SEED.identitySource);
- await expect(fs.access(path.join(home, 'SOUL.md.seeding'))).rejects.toBeTruthy();
+ // Skills still move into the Home even though seeding could not run.
+ expect(await fs.readFile(path.join(home, 'skills', 's1', 'SKILL.md'), 'utf8')).toBe('v1');
});
it('SOUL.md 之外的槽写失败时不落 SOUL.md,下一次仍会补齐,而不是把缺失的 USER.md 当成清空', async () => {
@@ -373,24 +327,6 @@ describe('搬家', () => {
expect(content.config).toEqual(SEED.config);
});
- it('被中断的无硬链接补种:截断的文件补全,中断后用户改过的原样保留', async () => {
- const home = botProfileDir(root, 'bot-a');
- await fs.mkdir(path.join(home, 'memories'), { recursive: true });
- // SOUL.md was cut off mid-write: a prefix of what the marker says it should be.
- await fs.writeFile(path.join(home, 'SOUL.md'), SEED.identitySource.slice(0, 3));
- await fs.writeFile(path.join(home, 'SOUL.md.seeding'), SEED.identitySource);
- // USER.md was rewritten by the user after the interruption: not a prefix, so it is theirs.
- await fs.writeFile(path.join(home, 'memories', 'USER.md'), '崩溃后用户写的档案');
- await fs.writeFile(path.join(home, 'memories', 'USER.md.seeding'), SEED.userContextSource);
-
- await migrateBotProfileFolder(root, 'bot-a', SEED);
- const content = await readBotProfileFolder(root, 'bot-a');
- expect(content.identitySource).toBe(SEED.identitySource);
- expect(content.userContextSource).toBe('崩溃后用户写的档案');
- await expect(fs.access(path.join(home, 'SOUL.md.seeding'))).rejects.toBeTruthy();
- await expect(fs.access(path.join(home, 'memories', 'USER.md.seeding'))).rejects.toBeTruthy();
- });
-
it('技能从旧目录整体搬进新家,内容与 slug 都不变', async () => {
const legacy = path.join(root, 'bot-skills', 'bot-a');
await fs.mkdir(path.join(legacy, 'skills', 'weekly-report'), { recursive: true });
diff --git a/apps/desktop/src/main/maker-ipc/botProfileFolder.ts b/apps/desktop/src/main/maker-ipc/botProfileFolder.ts
index 219e021511..11f6e77191 100644
--- a/apps/desktop/src/main/maker-ipc/botProfileFolder.ts
+++ b/apps/desktop/src/main/maker-ipc/botProfileFolder.ts
@@ -218,13 +218,13 @@ async function writeTextAtomic(absPath: string, content: string): Promise<void>
* 原子的「不存在才创建」:补种不能覆盖用户此刻正在编辑器里保存的文件,也不能留下
* 写到一半的文件(半截 SOUL.md 会被对账当成正式身份收进数据库)。
*
- * 常见文件系统:内容写进临时文件后用 link 挂到目标路径 —— 目标已存在时 link 报
- * EEXIST 而不是替换,且内容完整后才出现在目标路径,两条都满足。
+ * 内容写进临时文件后用 link 挂到目标路径 —— 目标已存在时 link 报 EEXIST 而不是
+ * 替换,且内容完整后才出现在目标路径,两条都满足。返回是否真的创建了。
*
- * 没有硬链接的文件系统上不存在「原子且不替换」的 rename,于是改用独占创建 + 可恢复:
- * 先写一个装着完整内容的 `.seeding` 标记,再以 `wx` 独占创建目标并落盘,最后删标记。
- * 独占创建保证绝不替换别人刚创建的文件;中途崩溃留下的标记由下一次补种前的
- * `recoverInterruptedSeed` 收尾。返回是否真的创建了。
+ * 没有硬链接的文件系统上不存在「原子且不替换」的写法(Node 不提供 NOREPLACE 的
+ * rename),任何模拟都要在「可能替换用户文件」和「只能猜文件是不是写到一半」之间
+ * 二选一。所以这里不模拟:link 的其他错误原样抛出,这次不补种。数据库仍是正本,
+ * 设置页的显式修改照常写文件,下一次对账再试。
*/
async function writeTextIfAbsent(absPath: string, content: string): Promise<boolean> {
if (Buffer.byteLength(content, 'utf8') > BOT_PROFILE_TEXT_MAX_BYTES) {
@@ -237,96 +237,14 @@ async function writeTextIfAbsent(absPath: string, content: string): Promise<bool
const tmp = `${absPath}.tmp-${process.pid}-${(writeSeq += 1)}`;
try {
await fs.writeFile(tmp, content, 'utf8');
- try {
- await fs.link(tmp, absPath);
- return true;
- } catch (cause) {
- if ((cause as NodeJS.ErrnoException).code === 'EEXIST') return false;
- }
+ await fs.link(tmp, absPath);
+ return true;
+ } catch (cause) {
+ if ((cause as NodeJS.ErrnoException).code === 'EEXIST') return false;
+ throw cause;
} finally {
await fs.rm(tmp, { force: true }).catch(() => {});
}
- return createExclusiveRecoverable(absPath, content);
-}
-
-/** 同一进程里对同一个槽的无硬链接补种串行进行,两次补种不会抢同一个 `.seeding` 标记。 */
-const exclusiveSeedTails = new Map<string, Promise<unknown>>();
-
-function seedingMarker(absPath: string): string {
- return `${absPath}.seeding`;
-}
-
-async function createExclusiveRecoverable(absPath: string, content: string): Promise<boolean> {
- const previous = exclusiveSeedTails.get(absPath) ?? Promise.resolve();
- const run = previous.catch(() => undefined).then(async () => {
- const marker = seedingMarker(absPath);
- await fs.writeFile(marker, content, 'utf8');
- let created = false;
- let completed = false;
- try {
- let handle: Awaited<ReturnType<typeof fs.open>>;
- try {
- handle = await fs.open(absPath, 'wx');
- } catch (cause) {
- if ((cause as NodeJS.ErrnoException).code === 'EEXIST') return false;
- throw cause;
- }
- created = true;
- try {
- await handle.writeFile(content, 'utf8');
- await handle.sync();
- } finally {
- await handle.close();
- }
- completed = true;
- return true;
- } finally {
- // A target we created but could not finish (ENOSPC, I/O error) keeps its marker,
- // so the next read or seed completes it instead of trusting a truncated file.
- if (!created || completed) await fs.rm(marker, { force: true }).catch(() => {});
- }
- });
- exclusiveSeedTails.set(absPath, run);
- try {
- return await run;
- } finally {
- if (exclusiveSeedTails.get(absPath) === run) exclusiveSeedTails.delete(absPath);
- }
-}
-
-/**
- * 读 Home 之前先收尾被中断的补种:对账在决定要不要补种之前就会读文件,
- * 一个截断但非空的 SOUL.md 不能被当成正式身份收进数据库。
- */
-export async function recoverInterruptedBotProfileSeed(userDataDir: string, botId: string): Promise<void> {
- for (const slot of [SLOT.soul, SLOT.userContext, SLOT.config]) {
- await recoverInterruptedSeed(resolveInside(userDataDir, botId, slot));
- }
-}
-
-/**
- * 收尾一次被中断的无硬链接补种:标记里是当时要写的完整内容。目标恰好是它的前缀
- * (空或截断)说明写到一半,补全;否则是中断之后用户自己写的,原样保留。标记总是删掉。
- */
-async function recoverInterruptedSeed(absPath: string): Promise<void> {
- const marker = seedingMarker(absPath);
- if (exclusiveSeedTails.has(absPath)) return;
- let expected: string;
- try {
- expected = await fs.readFile(marker, 'utf8');
- } catch {
- return;
- }
- let actual: string | null = null;
- try {
- actual = await fs.readFile(absPath, 'utf8');
- } catch {
- actual = null;
- }
- if (actual !== null && actual !== expected && expected.startsWith(actual)) {
- await writeTextAtomic(absPath, expected);
- }
- await fs.rm(marker, { force: true }).catch(() => {});
}
/** 一份摊开的伙伴档案。 */
@@ -460,9 +378,8 @@ export async function migrateBotProfileFolder(
await migrateLegacyBotProfileFolder(userDataDir, legacyUserDataDir, botId);
const soulPath = resolveInside(userDataDir, botId, SLOT.soul);
const at = (relative: string) => resolveInside(userDataDir, botId, relative);
- // Finish any seeding a crash interrupted before deciding what is missing.
- await recoverInterruptedBotProfileSeed(userDataDir, botId);
let seeded = false;
+ let seedFailure: unknown = null;
try {
await fs.access(soulPath);
} catch {
@@ -472,12 +389,19 @@ export async function migrateBotProfileFolder(
// SOUL.md goes last: its presence is what marks the Home as seeded, so if a sibling
// slot fails the next run still sees SOUL.md missing and retries, instead of
// reconciling an absent USER.md as an emptied user profile.
- await writeTextIfAbsent(at(SLOT.userContext), seed.userContextSource);
- await writeTextIfAbsent(at(SLOT.config), `${JSON.stringify(seed.config, null, 2)}\n`);
- seeded = await writeTextIfAbsent(soulPath, seed.identitySource);
+ try {
+ await writeTextIfAbsent(at(SLOT.userContext), seed.userContextSource);
+ await writeTextIfAbsent(at(SLOT.config), `${JSON.stringify(seed.config, null, 2)}\n`);
+ seeded = await writeTextIfAbsent(soulPath, seed.identitySource);
+ } catch (cause) {
+ seedFailure = cause;
+ }
}
+ // Skills move regardless: a Home that cannot be seeded (e.g. no hard links) must not
+ // also strand the Bot's legacy skills.
const skillsMoved = await migrateBotSkillsIntoProfileFolder(userDataDir, botId, legacyUserDataDir);
+ if (seedFailure !== null) throw seedFailure;
return { seeded, skillsMoved };
}