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(companions): detect whitespace edits when retrying memory imports

Chris6ed847db0467
diff --git a/apps/desktop/src/main/bot-import/README.md b/apps/desktop/src/main/bot-import/README.md
index 223cbab0c4..cdc51667c9 100644
--- a/apps/desktop/src/main/bot-import/README.md
+++ b/apps/desktop/src/main/bot-import/README.md
@@ -64,7 +64,12 @@ omitting it retains normal companion defaults, and a rejected request can be cor
length bounds, and document parts preserve source frontmatter and whitespace.
Each new part is read back before it counts as saved; failures preserve part
progress accumulated across all documents in a recovered directory, and safe storage
- reasons. Existing edited parts are not overwritten. Env references and original credentials remain
+ reasons. Existing edited parts are not overwritten. New exact-body parts compare
+ their complete body on retry, including whitespace; `bodyLength` remains present
+ through storage reads and subsequent editor/tool writes. A whitespace-only edit
+ therefore reports `MEMORY_CHANGED` and keeps the checkpoint pending. Legacy parts
+ without that marker retain their historical trimmed-body comparison.
+ Env references and original credentials remain
available to host execution; no model call or extra confirmation is added.
Selected skill folders retain their
real scripts, templates, executable bits and `SKILL.md`.
diff --git a/apps/desktop/src/main/bot-import/__tests__/host.test.ts b/apps/desktop/src/main/bot-import/__tests__/host.test.ts
index 7a4f813751..986047d4fa 100644
--- a/apps/desktop/src/main/bot-import/__tests__/host.test.ts
+++ b/apps/desktop/src/main/bot-import/__tests__/host.test.ts
@@ -1300,6 +1300,38 @@ it('archives unsupported automation definitions and blocks both management and r
expect(h.routines).toHaveLength(1);
});
+it('keeps a whitespace-edited partial memory retry pending instead of reporting it copied', async () => {
+ const directory = path.join(h.root, 'real-memory');
+ const storage = new MemoryStorage(directory, DEFAULT_MEMORY_CONFIG);
+ await storage.init(h.root);
+ const memory = createBotMemoryService({ getStore: async () => storage as unknown as MakerMemoryStore, readBot: async () => ({ canonicalSessionId: null }), requestRefresh: async () => {} });
+ h.importDocument.mockImplementation(memory.importDocument);
+ const text = ' ' + 'x'.repeat(BOT_MEMORY_BODY_MAX_BYTES) + '\nLast paragraph';
+ h.snapshot.items = [{ view: { id: 'memory', name: 'Original', category: 'memory', selected: true }, text }];
+ const write = storage.write.bind(storage);
+ const failure = vi.spyOn(storage, 'write').mockImplementation(async opts => {
+ if (opts.name.endsWith('_1')) throw Object.assign(new Error('fixture disk full'), { code: 'ENOSPC' });
+ return write(opts);
+ });
+ const [source] = await listCompanionImportSources('fixture');
+ const preview = await previewCompanionImport(source!.id, 'fixture');
+ const selection = { requestId: 'whitespace-memory-retry', previewId: preview.id, name: 'Ada', entryIds: ['memory'], takeover: false, deferSetup: true };
+ const accepted = await startCompanionImport(selection, 'fixture');
+ const first = await withBotProfileLocks([accepted.botId], () => getCompanionImportResult(selection.requestId));
+ expect(first?.checks).toContainEqual({ entryId: 'memory', status: 'needs-attention', message: 'IMPORT_DISK_FULL', progress: { saved: 1, total: 2 } });
+ failure.mockRestore();
+ const file = path.join(directory, 'reference_import_memory_0.md');
+ await fs.appendFile(file, '\n ');
+ const edited = await fs.readFile(file, 'utf8');
+ await startCompanionImport(selection, 'fixture');
+ const retried = await withBotProfileLocks([accepted.botId], () => getCompanionImportResult(selection.requestId));
+ expect(retried?.status).toBe('needs-attention');
+ expect(retried?.checks).toContainEqual({ entryId: 'memory', status: 'needs-attention', message: 'MEMORY_CHANGED', progress: { saved: 0, total: 2 } });
+ expect(retried?.savedEntryIds ?? []).not.toContain('memory');
+ expect(await fs.readFile(file, 'utf8')).toBe(edited);
+ expect((await h.store.read(h.root, accepted.botId, () => {}))?.pendingImport).toBeDefined();
+});
+
it('continues healthy recovered documents when a sibling attachment fails', async () => {
h.importMedia.mockRejectedValueOnce(Object.assign(new Error('media failed'), { code: 'ENOSPC' }));
h.snapshot.items = [{ view: { id: 'mixed', name: 'Recovered', category: 'memory', selected: true },
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/botMemoryService.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/botMemoryService.test.ts
index 29cf87f011..ba220fc426 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/botMemoryService.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/botMemoryService.test.ts
@@ -18,6 +18,7 @@ import {
} from '@cindy/maker-core';
import { BOT_MEMORY_CHANGED } from '../../../shared/botMemory';
+import { importFailureCode } from '../../bot-import/types.js';
import { botMemoryDescriptionFromBody, createBotMemoryService } from '../botMemoryService';
let dir = '';
@@ -265,3 +266,41 @@ it('reports a partial document write and retries missing chunks without duplicat
expect((await storage.read(first.filename)).body).toContain('User added this later.');
await expect(service.importDocument('bot-1', 'retry-document', 'retry', original)).rejects.toThrow('PRECONDITION_FAILED');
});
+
+it.each(['leading', 'trailing', 'same-length', 'blank-only', 'editor'] as const)('keeps a %s whitespace edit during partial-import retry', async edit => {
+ const { service } = setup();
+ const { BOT_MEMORY_BODY_MAX_BYTES } = await import('../../../shared/botMemory.js');
+ const firstBody = edit === 'blank-only' ? ' '.repeat(BOT_MEMORY_BODY_MAX_BYTES) : ' ' + 'x'.repeat(BOT_MEMORY_BODY_MAX_BYTES - 2);
+ const original = firstBody + '\nLast paragraph';
+ const write = storage.write.bind(storage);
+ const failure = vi.spyOn(storage, 'write').mockImplementation(async opts => {
+ if (opts.name.endsWith('_1')) throw Object.assign(new Error('fixture disk full'), { code: 'ENOSPC' });
+ return write(opts);
+ });
+ await expect(service.importDocument('bot-1', 'spaces', 'source', original)).rejects.toMatchObject({ code: 'ENOSPC', importProgress: { saved: 1, total: 2 } });
+ failure.mockRestore();
+ const filename = 'reference_import_spaces_0.md';
+ const file = path.join(dir, filename);
+ const first = await storage.read(filename);
+ expect(first.body).toBe(firstBody);
+ const edited = edit === 'trailing' ? firstBody + '\n\t' : edit === 'same-length' ? '\t ' + firstBody.slice(2) : firstBody.slice(1);
+ if (edit === 'editor') await storage.update(filename, first.frontmatter.updatedAt, { title: 'source', description: 'source', body: edited });
+ else await fs.writeFile(file, (await fs.readFile(file, 'utf8')).replace(firstBody, edited));
+ const changedFile = await fs.readFile(file, 'utf8');
+ const error = await service.importDocument('bot-1', 'spaces', 'source', original).then(() => null, error => error);
+ expect(error).toMatchObject({ code: 'version-conflict', importProgress: { saved: 0, total: 2 } });
+ expect(importFailureCode(error)).toBe('MEMORY_CHANGED');
+ expect(await fs.readFile(file, 'utf8')).toBe(changedFile);
+ await expect(storage.read('reference_import_spaces_1.md')).rejects.toMatchObject({ code: 'not-found' });
+});
+
+it('retries legacy imported shards using their original trimmed-body semantics', async () => {
+ const { service } = setup();
+ await storage.write({ type: 'reference', name: 'import_legacy_0', title: 'legacy', description: 'legacy', body: 'original' });
+ const file = path.join(dir, 'reference_import_legacy_0.md');
+ const before = await fs.readFile(file, 'utf8');
+ expect((await storage.read('reference_import_legacy_0.md')).frontmatter.bodyLength).toBeUndefined();
+ await service.importDocument('bot-1', 'legacy', 'legacy', ' original\n\n');
+ expect(await fs.readFile(file, 'utf8')).toBe(before);
+ await expect(service.importDocument('bot-1', 'legacy', 'legacy', 'different')).rejects.toMatchObject({ code: 'version-conflict' });
+});
diff --git a/apps/desktop/src/main/maker-ipc/botMemoryService.ts b/apps/desktop/src/main/maker-ipc/botMemoryService.ts
index fbc1cec736..555aece8bb 100644
--- a/apps/desktop/src/main/maker-ipc/botMemoryService.ts
+++ b/apps/desktop/src/main/maker-ipc/botMemoryService.ts
@@ -219,7 +219,11 @@ export function createBotMemoryService(deps: BotMemoryServiceDeps) {
throw error;
});
if (existing) {
- if (existing.body.trim() !== body.trim()) throw new MemoryError('version-conflict', '[PRECONDITION_FAILED] Imported memory was edited');
+ // Exact-body imports include whitespace in their identity. Only old
+ // shards whose storage format discarded it use the legacy comparison.
+ const unchanged = existing.frontmatter.bodyLength === undefined
+ ? existing.body.trim() === body.trim() : existing.body === body;
+ if (!unchanged) throw new MemoryError('version-conflict', '[PRECONDITION_FAILED] Imported memory was edited');
return;
}
await store.write({ type, name, title: title.slice(0, BOT_MEMORY_TITLE_MAX).replace(/[\uD800-\uDBFF]$/u, ''),
diff --git a/packages/maker-core/src/memory/storage.concurrency.test.ts b/packages/maker-core/src/memory/storage.concurrency.test.ts
index e0dd527045..96b89142d3 100644
--- a/packages/maker-core/src/memory/storage.concurrency.test.ts
+++ b/packages/maker-core/src/memory/storage.concurrency.test.ts
@@ -39,6 +39,21 @@ function pauseNextRead() {
}
describe('conditional memory mutations', () => {
+ it('retains the exact-body format through editor and tool updates to an imported shard', async () => {
+ await storage.write({ ...seed, mode: 'update', body: ' Original\n\n', preserveBody: true });
+ const imported = await storage.read(filename);
+ expect(imported.frontmatter.bodyLength).toBe(imported.body.length);
+ const body = '\tOriginal\n';
+ const edited = await storage.update(filename, imported.frontmatter.updatedAt, { ...seed, body });
+ expect(edited.body).toBe(body);
+ expect(edited.frontmatter.bodyLength).toBe(body.length);
+ const toolBody = '\nOriginal ';
+ await storage.write({ ...seed, mode: 'update', body: toolBody });
+ const saved = await storage.read(filename);
+ expect(saved.body).toBe(toolBody);
+ expect(saved.frontmatter.bodyLength).toBe(toolBody.length);
+ });
+
it.each(['update', 'delete'] as const)('rejects stale %s after an in-flight tool write, across storage instances', async (operation) => {
const opened = await storage.read(filename);
const pause = pauseNextRead();
diff --git a/packages/maker-core/src/memory/storage.ts b/packages/maker-core/src/memory/storage.ts
index 1bd3b300a8..cc9b51a3c9 100644
--- a/packages/maker-core/src/memory/storage.ts
+++ b/packages/maker-core/src/memory/storage.ts
@@ -348,6 +348,7 @@ export class MemoryStorage {
const fullPath = path.join(this.dir, filename);
let nextBody = opts.body;
+ let preserveBody = opts.preserveBody === true;
let nextFrontmatter: MemoryFrontmatter;
const mode = opts.mode ?? 'create';
@@ -370,6 +371,9 @@ export class MemoryStorage {
throw new MemoryError('not-found', `${filename} 不存在; 用 mode:'create' 新建`);
}
const parsed = parseRawShard(existing, filename);
+ // Editing an imported shard must not silently downgrade its exact-body
+ // format; import retries still need to detect whitespace-only edits.
+ preserveBody ||= parsed.frontmatter.bodyLength !== undefined;
if (mode === 'append') {
nextBody = `${parsed.body.trimEnd()}\n\n${opts.body}`;
}
@@ -390,7 +394,7 @@ export class MemoryStorage {
);
}
- if (opts.preserveBody) nextFrontmatter.bodyLength = nextBody.length;
+ if (preserveBody) nextFrontmatter.bodyLength = nextBody.length;
const fileText = matter.stringify({ content: nextBody }, nextFrontmatter);
// tryReadRaw 的 await 窗口后、真正写盘前复核 owner scope (review #2388
// Codex 8th P1): 边界不得把 shard 写入旧 owner 根。
@@ -678,6 +682,7 @@ function parseRawShard(raw: string, filenameForErr: string): ParsedShard {
description: data.description,
type: data.type,
updatedAt: typeof data.updatedAt === 'string' ? data.updatedAt : new Date().toISOString(),
+ ...(Number.isSafeInteger(data.bodyLength) && data.bodyLength! >= 0 ? { bodyLength: data.bodyLength } : {}),
},
// gray-matter appends one newline. Remove only that exact serialization
// suffix; an external edit must never be truncated to a stale length.