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(worktree): close final recycle race and auth lease

DavidShen3477a37af7d3
diff --git a/apps/desktop/src/main/__tests__/managedWorktreeRecycle.test.ts b/apps/desktop/src/main/__tests__/managedWorktreeRecycle.test.ts
index 1d916de904..8fd3ff1cb5 100644
--- a/apps/desktop/src/main/__tests__/managedWorktreeRecycle.test.ts
+++ b/apps/desktop/src/main/__tests__/managedWorktreeRecycle.test.ts
@@ -218,6 +218,17 @@ describe('shared worktree recycling', () => {
expect((await readRecycleRecord(meta.path))?.reason).toBe('git-baseline-changed');
expect(git.mock.calls.some(([args]) => args.includes('remove'))).toBe(false);
});
+ it('rechecks files after marking removal and preserves a late editor write', async () => {
+ baselineMatches.mockImplementationOnce(async () => {
+ await fs.writeFile(path.join(meta.path, 'late-editor-write.txt'), 'keep me');
+ return true;
+ });
+ expect(await recycle()).toBe(false);
+ expect((await readRecycleRecord(meta.path))?.reason).toBe('files-changed-before-removal');
+ expect(git.mock.calls.some(([args]) => args.includes('remove'))).toBe(false);
+ expect(await fs.readFile(path.join(meta.path, 'late-editor-write.txt'), 'utf8')).toBe('keep me');
+ expect(state.registry.has(meta.sessionId)).toBe(true);
+ });
it('persists a shared owner request before the last borrower status write', async () => {
await requestWorktreeRecycle('borrower', [meta.path]);
expect((await readRecycleRecord(meta.path))?.meta.sessionId).toBe(meta.sessionId);
diff --git a/apps/desktop/src/main/worktree/managedRecycle.ts b/apps/desktop/src/main/worktree/managedRecycle.ts
index 5da7329a73..a0c06e1777 100644
--- a/apps/desktop/src/main/worktree/managedRecycle.ts
+++ b/apps/desktop/src/main/worktree/managedRecycle.ts
@@ -176,6 +176,26 @@ async function recycleManagedWorktreeInSlot(meta: WorktreeMeta, options: Managed
}
record.phase = 'removing';
await writeRecycleRecord(record);
+ // Revalidate immediately before the destructive Git operation. The
+ // earlier inventory is only a snapshot; a late editor/IDE write or a
+ // newly live reference must keep this generation protected.
+ if (!record.archive || !record.snapshot) return defer('recovery-evidence-missing');
+ await verifyRecoveryArchive(record.archive);
+ if (!sameWorktreeFiles(await inventoryWorktree(meta.path), record.archive.files, Boolean(partialRemoval))) {
+ return defer('files-changed-before-removal');
+ }
+ if (!(await canRemove())) return defer('referenced-before-removal');
+ if (await directoryIdentity(meta.path) !== identity) return defer('directory-replaced');
+ await assertManagedResourcePath(meta, store.getAllPaths());
+ let finalGitLinkPresent = true;
+ try { await fs.lstat(path.join(meta.path, '.git')); } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
+ finalGitLinkPresent = false;
+ }
+ if (!partialRemoval || finalGitLinkPresent) {
+ await assertWorktreeGitIdentity(meta);
+ if (!(await worktreeContentBaselineMatches(meta.path, record.snapshot))) return defer('git-baseline-changed-before-removal');
+ }
try {
await gitExec(['-c', 'core.longpaths=true', 'worktree', 'remove', '--force', meta.path], meta.baseRepo);
} catch {
diff --git a/packages/maker-core/src/maker.test.ts b/packages/maker-core/src/maker.test.ts
index 124d8e0fdd..2ca9cb3d66 100644
--- a/packages/maker-core/src/maker.test.ts
+++ b/packages/maker-core/src/maker.test.ts
@@ -14,6 +14,7 @@ import { Maker, type CreateSessionOptions, type SessionStartFailureContext } fro
import { Session } from './session.js';
import { createAsyncQueue } from './agents/shared/async-queue.js';
import {
+ AgentNotAuthenticatedError,
AgentStartupCleanupPendingError,
AgentStartupStoppedError,
TurnPermissionPolicyUnsupportedError,
@@ -1646,6 +1647,29 @@ describe('Maker start-option lifecycle hooks', () => {
);
});
+ it('releases the startup lease when authentication fails before spawning an agent', async () => {
+ const leased = new Set<CreateSessionOptions>();
+ const onStartFailed = vi.fn(({ options, runtimeMayBeAlive }: SessionStartFailureContext) => {
+ if (!runtimeMayBeAlive) leased.delete(options);
+ });
+ const authError = new AgentNotAuthenticatedError('claude-code', 'not authenticated');
+ const maker = new Maker({
+ agents: { 'claude-code': createAgent(vi.fn().mockRejectedValue(authError), 'claude-code') },
+ storage: createStorage(), logger: createLogger(),
+ lifecycleHooks: {
+ prepareStartOptions: (_id, options) => { leased.add(options); },
+ onStartFailed,
+ },
+ });
+ await expect(maker.createSession({
+ id: 'auth-failure', agentKind: 'claude-code', workingDir: '/repo', model: 'claude-model',
+ })).rejects.toBe(authError);
+ expect(onStartFailed).toHaveBeenCalledWith(expect.objectContaining({
+ stage: 'agent-start', error: authError, runtimeMayBeAlive: false,
+ }));
+ expect(leased).toHaveLength(0);
+ });
+
it('preserves the original startup error when the failure hook also fails', async () => {
const logger = createLogger();
const maker = new Maker({
diff --git a/packages/maker-core/src/maker.ts b/packages/maker-core/src/maker.ts
index 7cd508654d..f2ec972d40 100644
--- a/packages/maker-core/src/maker.ts
+++ b/packages/maker-core/src/maker.ts
@@ -38,7 +38,11 @@ import type { PiRuntimeCapabilityManifest } from './types/pi-runtime-capabilitie
import { piExplicitSkillRuntimePath } from './agents/pi/skill-runtime-provenance.js';
import { fingerprintPiProjectSkillEntrypoint } from './agents/pi/project-resource-assembly.js';
import { Session, generateSessionId } from './session.js';
-import { AgentStartupCleanupPendingError, AgentStartupStoppedError } from './agents/base-agent.js';
+import {
+ AgentNotAuthenticatedError,
+ AgentStartupCleanupPendingError,
+ AgentStartupStoppedError,
+} from './agents/base-agent.js';
import type {
AgentSessionHandle,
AgentSessionTeardownOptions,
@@ -717,8 +721,13 @@ export class Maker {
// A generic adapter error does not prove its process stopped. Preserve
// host guards; only pre-adapter failure or explicit exit evidence releases them.
const runtimeStopped = error instanceof AgentStartupStoppedError;
+ const authenticationFailed = error instanceof AgentNotAuthenticatedError;
const startupError = runtimeStopped ? error.cause : error;
- await notifyStartFailed('agent-start', startupError, agentStartAttempted && !runtimeStopped);
+ await notifyStartFailed(
+ 'agent-start',
+ startupError,
+ agentStartAttempted && !runtimeStopped && !authenticationFailed,
+ );
if (error instanceof AgentStartupCleanupPendingError) {
// The adapter still owns this unpublished process. Its eventual close
// must release only this startup's resources, even after a rebuild.