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(cindy-make): 回收已合入的临时分支

Lizi43e9e6b884fb
diff --git a/apps/desktop/src/main/cindy-make/__tests__/upstreamMerge.git-integration.test.ts b/apps/desktop/src/main/cindy-make/__tests__/upstreamMerge.git-integration.test.ts
index 9932306f78..6afb4b5d12 100644
--- a/apps/desktop/src/main/cindy-make/__tests__/upstreamMerge.git-integration.test.ts
+++ b/apps/desktop/src/main/cindy-make/__tests__/upstreamMerge.git-integration.test.ts
@@ -1,10 +1,11 @@
import os from 'node:os';
import path from 'node:path';
import { randomUUID } from 'node:crypto';
-import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
+import { mkdir, mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/promises';
import { expect, it } from 'vitest';
import {
applyUpstreamMerge,
+ cleanupMergedCandidate,
prepareUpstreamMerge,
mergeWorktree,
mergeBranch,
@@ -109,6 +110,73 @@ it('rebases locally committed personal changes onto the latest official main and
expect(
await h.git(['rev-parse', 'refs/cindy-make/backups/' + h.state.id + '/personal'], h.source),
).toBe(result.baselineCommit);
+ expect(await cleanupMergedCandidate(h.userData, result, h.git)).toBe(true);
+ await expect(h.git(['rev-parse', mergeBranch(h.state.id)], h.source)).rejects.toBeTruthy();
+ await expect(stat(mergeWorktree(h.userData, h.state.id))).rejects.toMatchObject({
+ code: 'ENOENT',
+ });
+ expect(await h.git(['rev-parse', 'cindy-personal'], h.source)).toBe(result.commit);
+ expect(
+ await h.git(['rev-parse', 'refs/cindy-make/backups/' + h.state.id + '/personal'], h.source),
+ ).toBe(result.baselineCommit);
+ } finally {
+ await h.clean();
+ }
+}, 30_000);
+
+it('preserves unfinished or session-owned candidates, new files and commits added after adoption', async () => {
+ const h = await fixture(false);
+ try {
+ const result = await prepareUpstreamMerge(h.userData, h.state, h.git, async () => {});
+ const worktree = mergeWorktree(h.userData, h.state.id);
+ expect(
+ await cleanupMergedCandidate(h.userData, { ...result, status: 'conflict' }, h.git),
+ ).toBe(false);
+ expect(
+ await cleanupMergedCandidate(h.userData, { ...result, sessionId: 'active-task' }, h.git),
+ ).toBe(false);
+ await writeFile(path.join(worktree, 'later.txt'), 'new work\n');
+ expect(await cleanupMergedCandidate(h.userData, result, h.git)).toBe(false);
+ expect(await readFile(path.join(worktree, 'later.txt'), 'utf8')).toBe('new work\n');
+ await h.commit(worktree, 'later work');
+ const later = await h.git(['rev-parse', 'HEAD'], worktree);
+ expect(await cleanupMergedCandidate(h.userData, result, h.git)).toBe(false);
+ expect(await h.git(['rev-parse', mergeBranch(h.state.id)], h.source)).toBe(later);
+ } finally {
+ await h.clean();
+ }
+}, 30_000);
+
+it('finishes branch cleanup after directory removal but preserves a branch checked out elsewhere', async () => {
+ const h = await fixture(false);
+ try {
+ const result = await prepareUpstreamMerge(h.userData, h.state, h.git, async () => {});
+ await h.git(['worktree', 'remove', mergeWorktree(h.userData, h.state.id)], h.source);
+ const other = path.join(h.userData, 'other-worktree');
+ await h.git(['worktree', 'add', other, mergeBranch(h.state.id)], h.source);
+ expect(await cleanupMergedCandidate(h.userData, result, h.git)).toBe(false);
+ expect(await h.git(['rev-parse', 'HEAD'], other)).toBe(result.commit);
+ await h.git(['worktree', 'remove', other], h.source);
+ expect(await cleanupMergedCandidate(h.userData, result, h.git)).toBe(true);
+ expect(await h.git(['branch', '--list', mergeBranch(h.state.id)], h.source)).toBe('');
+ } finally {
+ await h.clean();
+ }
+}, 30_000);
+
+it('refuses to delete a branch moved between cleanup verification and ref deletion', async () => {
+ const h = await fixture(false);
+ try {
+ const result = await prepareUpstreamMerge(h.userData, h.state, h.git, async () => {});
+ const ref = 'refs/heads/' + mergeBranch(h.state.id);
+ const racingGit: typeof h.git = async (args, cwd, indexFile) => {
+ if (args[0] === 'update-ref' && args.includes('-d') && args.includes(ref))
+ await h.git(['update-ref', ref, h.baselineCommit], h.source);
+ return h.git(args, cwd, indexFile);
+ };
+ await expect(cleanupMergedCandidate(h.userData, result, racingGit)).rejects.toBeTruthy();
+ expect(await h.git(['rev-parse', ref], h.source)).toBe(h.baselineCommit);
+ expect(await h.git(['rev-parse', 'cindy-personal'], h.source)).toBe(result.commit);
} finally {
await h.clean();
}
diff --git a/apps/desktop/src/main/cindy-make/__tests__/upstreamMergeController.test.ts b/apps/desktop/src/main/cindy-make/__tests__/upstreamMergeController.test.ts
index 4f22cea487..eae6563591 100644
--- a/apps/desktop/src/main/cindy-make/__tests__/upstreamMergeController.test.ts
+++ b/apps/desktop/src/main/cindy-make/__tests__/upstreamMergeController.test.ts
@@ -16,10 +16,10 @@ const candidate: CindyMakeMergeState = {
baselineCommit: 'b'.repeat(40),
hasWorkspace: true,
};
-function harness(initial?: SavedUpstreamMerge) {
+function harness(initial?: SavedUpstreamMerge, actualWorkspace = !!initial?.state.hasWorkspace) {
let saved = initial ? structuredClone(initial) : undefined;
let owner = 'alice';
- let workspace = !!initial?.state.hasWorkspace;
+ let workspace = actualWorkspace;
const deps: UpstreamMergeDependencies = {
read: () => saved,
write: vi.fn((next) => {
@@ -58,6 +58,9 @@ function harness(initial?: SavedUpstreamMerge) {
setOwner: (next: string) => {
owner = next;
},
+ setWorkspace: (next: boolean) => {
+ workspace = next;
+ },
};
}
describe('upstream merge lifecycle', () => {
@@ -135,11 +138,29 @@ describe('upstream merge lifecycle', () => {
});
it('automatically applies a clean update and never creates an agent task', async () => {
const h = harness();
- expect(await h.controller.update()).toMatchObject({ status: 'merged' });
+ h.deps.cleanup = vi.fn(async () => h.setWorkspace(false));
+ expect(await h.controller.update()).toMatchObject({ status: 'merged', hasWorkspace: false });
expect(h.deps.session).not.toHaveBeenCalled();
expect(h.saved()?.state.commit).toBe('c'.repeat(40));
expect(h.deps.cleanup).toHaveBeenCalledOnce();
});
+ it('normalizes a completed merge whose candidate worktree was already removed', () => {
+ const h = harness(
+ {
+ state: {
+ ...candidate,
+ status: 'merged',
+ hasWorkspace: true,
+ commit: 'c'.repeat(40),
+ },
+ },
+ false,
+ );
+ expect(h.controller.status()).toMatchObject({ status: 'merged', hasWorkspace: false });
+ expect(h.saved()).toMatchObject({
+ state: { status: 'merged', hasWorkspace: false },
+ });
+ });
it('deduplicates simultaneous updates and opens one independent conflict task with the chosen model', async () => {
const h = harness();
h.deps.prepare = vi.fn(async (state) => ({ ...state, ...candidate }));
diff --git a/apps/desktop/src/main/cindy-make/upstreamMerge.ts b/apps/desktop/src/main/cindy-make/upstreamMerge.ts
index fc48b3effd..544f8b05bc 100644
--- a/apps/desktop/src/main/cindy-make/upstreamMerge.ts
+++ b/apps/desktop/src/main/cindy-make/upstreamMerge.ts
@@ -1,5 +1,5 @@
import path from 'node:path';
-import { mkdir, readFile, realpath } from 'node:fs/promises';
+import { lstat, mkdir, readFile, realpath } from 'node:fs/promises';
import type {
CindyMakeMergeError,
CindyMakeMergeState,
@@ -100,6 +100,51 @@ export async function verifyMergeWorktree(
return worktree;
}
+/** Remove a completed candidate worktree and its disposable branch ref. */
+export async function cleanupMergedCandidate(
+ userData: string,
+ state: CindyMakeMergeState,
+ git: MergeGit,
+): Promise<boolean> {
+ if (
+ state.status !== 'merged' ||
+ state.sessionId ||
+ !state.commit ||
+ !COMMIT.test(state.commit) ||
+ !state.tree ||
+ !/^[0-9a-f]{40,64}$/i.test(state.tree)
+ )
+ return false;
+ const worktree = mergeWorktree(userData, state.id);
+ const branchRef = 'refs/heads/' + mergeBranch(state.id);
+ const source = await assertSource(userData, git);
+ const tip = (await git(['rev-parse', '--verify', branchRef + '^{commit}'], source)).trim();
+ if (tip !== state.commit) return false;
+ await git(['merge-base', '--is-ancestor', tip, CINDY_PERSONAL_BRANCH], source);
+ const workspace = await lstat(worktree).catch((error) => {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined;
+ throw error;
+ });
+ if (workspace) {
+ await verifyMergeWorktree(userData, state, git);
+ await assertNoGitOperation(git, worktree);
+ if (
+ (await snapshotContent(git, worktree)) !== state.tree ||
+ (await git(['rev-parse', 'HEAD'], worktree)).trim() !== tip
+ )
+ return false;
+ // Git also refuses tracked/untracked edits made after the snapshot check.
+ await git(['worktree', 'remove', worktree], source);
+ }
+
+ // A prior cleanup may have removed the directory already. Never delete a ref
+ // still checked out elsewhere, or a tip changed after the adoption check.
+ const worktrees = await git(['worktree', 'list', '--porcelain', '-z'], source);
+ if (worktrees.split('\0').includes('branch ' + branchRef)) return false;
+ await git(['update-ref', '--no-deref', '-d', branchRef, tip], source);
+ return true;
+}
+
/** Rebase only in the retained candidate, then move the clean personal checkout to its result. */
export async function applyUpstreamMerge(
userData: string,
diff --git a/apps/desktop/src/main/cindy-make/upstreamMergeController.ts b/apps/desktop/src/main/cindy-make/upstreamMergeController.ts
index ab3ed68be5..2cb3e92692 100644
--- a/apps/desktop/src/main/cindy-make/upstreamMergeController.ts
+++ b/apps/desktop/src/main/cindy-make/upstreamMergeController.ts
@@ -108,15 +108,23 @@ export class UpstreamMergeController {
private active?: Promise<unknown>;
constructor(private readonly deps: UpstreamMergeDependencies) {
this.saved = deps.read();
- if (this.saved && this.saved.state.status !== 'merged') {
+ if (this.saved) {
const state = this.saved.state;
- this.save({
+ const recovered = {
...state,
hasWorkspace: deps.hasWorkspace(state),
...(['fetching', 'merging', 'checking'].includes(state.status)
? { status: 'failed' as const, error: 'interrupted' as const }
: {}),
- });
+ };
+ // A completed merge removes its candidate worktree. Recompute this bit on
+ // every restore so an older state file cannot keep the UI looking busy.
+ if (
+ recovered.status !== state.status ||
+ recovered.error !== state.error ||
+ recovered.hasWorkspace !== state.hasWorkspace
+ )
+ this.save(recovered);
}
this.status();
}
@@ -159,6 +167,15 @@ export class UpstreamMergeController {
}
this.save(result);
}
+ private async cleanupCompleted(state: CindyMakeMergeState): Promise<void> {
+ await this.deps.cleanup(state);
+ // Cleanup may be deferred (for example after a crash). Read the actual
+ // worktree state before clearing the persisted flag.
+ if (this.saved?.state.id !== state.id || this.saved.state.status !== 'merged') return;
+ const hasWorkspace = this.deps.hasWorkspace(state);
+ if (this.saved.state.hasWorkspace !== hasWorkspace)
+ this.save({ ...this.saved.state, hasWorkspace });
+ }
private async run(work: () => Promise<void>): Promise<CindyMakeMergeState | undefined> {
if (this.active) {
await this.active.catch(() => undefined);
@@ -195,7 +212,7 @@ export class UpstreamMergeController {
if (result.status === 'conflict' && owner && this.deps.owner() === owner) {
await this.createResolutionTask(options, owner);
}
- if (result.status === 'merged') await this.deps.cleanup(result);
+ if (result.status === 'merged') await this.cleanupCompleted(result);
await this.deps.refresh().catch(() => undefined);
});
}
@@ -228,7 +245,7 @@ export class UpstreamMergeController {
);
await this.acceptResult(result, isCurrent);
if (result.status === 'merged') {
- await this.deps.cleanup(result);
+ await this.cleanupCompleted(result);
return;
}
}
@@ -269,7 +286,7 @@ export class UpstreamMergeController {
);
await this.acceptResult(result, isCurrent);
if (result.status === 'merged') {
- await this.deps.cleanup(result);
+ await this.cleanupCompleted(result);
} else if (result.status === 'conflict' && isCurrent())
await this.createResolutionTask(options, owner);
await this.deps.refresh().catch(() => undefined);
diff --git a/apps/desktop/src/main/cindy-make/upstreamMergeRuntime.ts b/apps/desktop/src/main/cindy-make/upstreamMergeRuntime.ts
index 8e8da75094..27161a9531 100644
--- a/apps/desktop/src/main/cindy-make/upstreamMergeRuntime.ts
+++ b/apps/desktop/src/main/cindy-make/upstreamMergeRuntime.ts
@@ -8,7 +8,7 @@ import { readAtomicFileSync, atomicWriteFileSync } from '../utils/atomicWriteFil
import { throwIpcError } from '../utils/ipcValidate.js';
import { captureDataOwnerBroadcastScope } from '../device-link/broadcast-tap.js';
import { createLogger } from '../logger.js';
-import { makeSourceRoot, makeSourceCheckoutPath } from './sourcePaths.js';
+import { makeSourceRoot } from './sourcePaths.js';
import {
createMakeToolchainEnvironment,
resolveMakeToolEnvironment,
@@ -16,7 +16,6 @@ import {
import { readCurrentCindySourceStatus } from './sourcePreparation.js';
import { createLatestSourceVersionReader } from './latestSourceVersion.js';
import { runSourceGit } from './sourceGit.js';
-import { snapshotContent } from './sourceContent.js';
import { cindyMakeManager } from './manager.js';
import { validateCindyMakeTaskStart } from './taskRuntime.js';
import { ensureUpstreamMergeSession, assertUpstreamMergeSession } from './upstreamMergeSession.js';
@@ -30,6 +29,7 @@ import {
mergeError,
prepareFeatureMerge,
applyFeatureMerge,
+ cleanupMergedCandidate,
type MergeGit,
} from './upstreamMerge.js';
@@ -154,17 +154,7 @@ export function configureUpstreamMerge(isRunning: (id: string) => boolean): void
if (state.sessionId) return;
// Only reclaim the exact file tree already adopted by the personal checkout.
try {
- const run = await git();
- await verifyMergeWorktree(userData, state, run);
- if (
- !state.tree ||
- (await snapshotContent(run, mergeWorktree(userData, state.id))) !== state.tree
- )
- return;
- await run(
- ['worktree', 'remove', '--force', mergeWorktree(userData, state.id)],
- makeSourceCheckoutPath(userData),
- );
+ await cleanupMergedCandidate(userData, state, await git());
} catch {
log.warn('Upstream merge completed; worktree cleanup deferred', {
operationId: state.id,
diff --git a/docs/cindy-make-upstream.md b/docs/cindy-make-upstream.md
index 501145e8ca..eb15416d2c 100644
--- a/docs/cindy-make-upstream.md
+++ b/docs/cindy-make-upstream.md
@@ -278,8 +278,10 @@ rebase 到新官方基线(禁止 update-refs 自动改动其他任务分支)
创建任务前先持久化任务 ID;账号切换后不发送旧请求、不暴露另一账号的任务入口。
已删除或归档的任务由下一次显式解决冲突操作创建新任务,继续使用保留的工作目录。
未完成的合并禁止清理源码;缺失的合并目录不会被普通恢复流程重建为空目录。
-- 没有任务的自动合并成功后,仅在文件树与已采纳结果一致时移除临时 worktree。冲突任务
- 的目录继续保留,便于查看与继续交流。仅支持本机 Desktop,不增加远控调用权限。
+- 没有任务的自动合并成功后,仅在候选提交和文件树与已采纳结果一致、提交仍被个人版包含时
+ 移除临时 worktree,再核对分支没有被其他 worktree 使用,以原提交值原子删除对应的
+ `cindy-merge/<ID>` 临时分支;`refs/cindy-make/backups/*` 等恢复引用继续保留。冲突任务的目录和
+ 分支继续保留,便于查看与继续交流。仅支持本机 Desktop,不增加远控调用权限。
实现见 [Git 合并](../apps/desktop/src/main/cindy-make/upstreamMerge.ts)、
[生命周期](../apps/desktop/src/main/cindy-make/upstreamMergeController.ts)、