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(git-snapshot): bound snapshot preparation and persist rewind gaps

DavidShen3458568a0015
diff --git a/apps/desktop/scripts/snapshot-budget-acceptance.ts b/apps/desktop/scripts/snapshot-budget-acceptance.ts
new file mode 100644
index 0000000000..6da6acc621
--- /dev/null
+++ b/apps/desktop/scripts/snapshot-budget-acceptance.ts
@@ -0,0 +1,150 @@
+/**
+ * Opt-in, real-I/O acceptance for #7259; deliberately outside default unit tests.
+ * Run from the repo root:
+ * pnpm --dir apps/desktop exec vite-node --config vitest.config.ts scripts/snapshot-budget-acceptance.ts --files=100000
+ * Uses production coordinator, directory detection, journal, Git and planner.
+ * Electron is stubbed by the existing test config; no account or provider is used.
+ */
+import assert from 'node:assert/strict';
+import { createHash } from 'node:crypto';
+import fs from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+import { performance } from 'node:perf_hooks';
+import { GitSnapshotCoordinator } from '../src/main/git-snapshot/gitSnapshotCoordinator';
+import { SnapshotAttemptStore } from '../src/main/git-snapshot/snapshotAttemptStore';
+import { createShadowMarker, createShadowSavepoint, listShadowSavepoints } from '../src/main/git-snapshot/gitSnapshotService';
+import { buildCodexFileRewindPlan } from '../src/main/git-snapshot/codexFileRewindPlanner';
+import { readSavepointTip } from '../src/main/git-snapshot/savepointRefs';
+import { isolatedGitExec } from '../src/main/git-snapshot/isolatedGitExec';
+import { detectCwd } from '../src/main/worktree/WorktreeManager';
+import { gitExec } from '../src/main/worktree/gitExec';
+import { OperationBudget } from '../src/main/utils/operationBudget';
+
+const countArg = process.argv.find((arg) => arg.startsWith('--files='));
+const files = Number(countArg?.slice('--files='.length) ?? 10_000);
+const keepFixture = process.argv.includes('--keep');
+assert(Number.isSafeInteger(files) && files >= 1 && files <= 1_000_000, '--files must be 1..1000000');
+const root = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-snapshot-acceptance-'));
+const large = path.join(root, 'large');
+const small = path.join(root, 'small');
+const journal = new SnapshotAttemptStore(path.join(root, 'owner'));
+const report: Record<string, unknown> = { files, platform: process.platform, node: process.version };
+const warnings: Array<{ message: string; error?: unknown }> = [];
+const logger = { info() {}, debug() {}, warn(message: string, meta?: Record<string, unknown>) {
+ warnings.push({ message, ...(meta?.error ? { error: meta.error } : {}) });
+} };
+const digest = (bytes: Buffer) => createHash('sha256').update(bytes).digest('hex');
+const rounded = (value: number) => Math.round(value);
+
+async function initRepo(dir: string): Promise<void> {
+ await fs.mkdir(dir);
+ await isolatedGitExec(['init'], dir);
+ for (const [key, value] of [
+ ['user.name', 'Snapshot Acceptance'], ['user.email', '[email protected]'],
+ ['commit.gpgsign', 'false'], ['core.autocrlf', 'false'], ['core.fsmonitor', 'false'],
+ ['core.untrackedCache', 'false'], ['core.excludesFile', path.join(dir, '.git', 'empty-excludes')],
+ ]) await gitExec(['config', '--local', key, value], dir);
+ await fs.writeFile(path.join(dir, '.git', 'empty-excludes'), '');
+ await fs.writeFile(path.join(dir, 'seed.txt'), 'base\n');
+ await isolatedGitExec(['add', 'seed.txt'], dir);
+ await isolatedGitExec(['commit', '--no-gpg-sign', '-m', 'seed'], dir);
+ await fs.writeFile(path.join(dir, 'seed.txt'), 'staged\n');
+ await isolatedGitExec(['add', 'seed.txt'], dir);
+ await fs.writeFile(path.join(dir, 'seed.txt'), 'unstaged\n');
+}
+
+async function visibleState(dir: string) {
+ return {
+ head: (await gitExec(['rev-parse', 'HEAD'], dir)).stdout,
+ index: digest(await fs.readFile(path.join(dir, '.git', 'index'))),
+ seed: await fs.readFile(path.join(dir, 'seed.txt'), 'utf8'),
+ };
+}
+
+const coordinator = new GitSnapshotCoordinator({
+ recordTurnAttempt: async (sessionId) => {
+ const attempt = await journal.record(sessionId, 'message-1');
+ return { attemptId: attempt.id, anchor: attempt.anchor };
+ },
+ readAutoSnapshotEnabled: () => true,
+ getSessionContext: async (id) => ({ workingDir: id === 'large' ? large : small, agentKind: 'codex' }),
+ detectRepoRoot: async (dir) => (await detectCwd(dir)).repoRoot ?? null,
+ createShadowSavepoint,
+ createShadowMarker,
+ oneShot: async () => 'acceptance',
+ logger,
+});
+
+try {
+ await initRepo(large);
+ await initRepo(small);
+ console.log(`Creating ${files} untracked files in an isolated temporary repository...`);
+ const setupAt = performance.now();
+ for (let batch = 0; batch < files; batch += 500) {
+ const dir = path.join(large, 'bulk', String(batch));
+ await fs.mkdir(dir, { recursive: true });
+ // Bound open files/promises even at one million entries.
+ for (let offset = batch; offset < Math.min(files, batch + 500); offset += 32) {
+ await Promise.all(Array.from({ length: Math.min(32, files - offset, batch + 500 - offset) },
+ (_, i) => fs.writeFile(path.join(dir, `${offset + i}.txt`), 'fixture\n')));
+ }
+ if ((batch + 500) % 100_000 === 0) console.log(`Created ${batch + 500}/${files} files`);
+ }
+ report.fixtureMs = rounded(performance.now() - setupAt);
+ const before = await visibleState(large);
+ const started = performance.now();
+ const pendingLarge = coordinator.onTurnStart('large').then(() => rounded(performance.now() - started));
+ const pendingSmall = coordinator.onTurnStart('small').then(() => rounded(performance.now() - started));
+ const [largeMs, smallMs] = await Promise.all([pendingLarge, pendingSmall]);
+ report.largeStartMs = largeMs;
+ report.concurrentSmallStartMs = smallMs;
+ report.largeBaselineCreated = !!await readSavepointTip(large, 'large');
+ assert(largeMs < 12_000, 'Snapshot exceeded 8s + 3s cleanup + 1s measurement headroom');
+ assert(await readSavepointTip(small, 'small'), 'Independent repository failed to create baseline');
+ assert(smallMs < 8_000, 'Independent repository consumed the whole snapshot budget');
+ assert.deepEqual(await visibleState(large), before, 'Snapshot changed user HEAD/index/seed');
+ report.headIndexSeedUnchanged = true;
+ await coordinator.onTurnEnd('small');
+
+ // Read persisted evidence with a new store, then add a retry with no Git result.
+ const { entries } = await listShadowSavepoints(small, 'small');
+ const planInput = {
+ sessionId: 'small', targetMessageClientId: 'message-1',
+ userMessages: [{ clientId: 'message-1', createdAt: 1 }],
+ repo: { kind: 'local-git' as const, repoRoot: small, currentHead: (await visibleState(small)).head.trim(),
+ currentBranch: '', savepointsNewestFirst: entries.map((entry) => ({ ...entry, source: 'shadow' as const, branch: entry.branch ?? '' })) },
+ };
+ assert.equal(buildCodexFileRewindPlan({ ...planInput, snapshotAttempts: await journal.read('small') }).mode, 'file-restore');
+ await journal.record('small', 'message-1');
+ const restored = new SnapshotAttemptStore(path.join(root, 'owner'));
+ const retryPlan = buildCodexFileRewindPlan({ ...planInput, snapshotAttempts: await restored.read('small') });
+ assert.equal(retryPlan.mode, 'conversation-only');
+ report.failedRetryAfterStoreReload = retryPlan.mode;
+
+ // Real blocked Git, not a rejected mock: cancel only after receiving its PID.
+ const budget = new OperationBudget(8_000);
+ let onSpawn!: (pid: number) => void;
+ const spawned = new Promise<number>((resolve) => { onSpawn = resolve; });
+ const running = budget.run(() => gitExec(['hash-object', '--stdin'], small, { onSpawn }));
+ const rejected = assert.rejects(running, /acceptance stop/);
+ const pid = await spawned;
+ const cancelledAt = performance.now();
+ budget.cancel(new Error('acceptance stop'));
+ await rejected;
+ report.cancelCleanupMs = rounded(performance.now() - cancelledAt);
+ assert.throws(() => process.kill(pid, 0), 'Cancelled Git is still alive');
+ report.cancelledGitExited = true;
+ report.warnings = warnings;
+ report.result = 'pass';
+ console.log(JSON.stringify(report, null, 2));
+} finally {
+ coordinator.onSessionClosed('large');
+ coordinator.onSessionClosed('small');
+ // Only remove the unique directory created above, never an input path.
+ const resolved = path.resolve(root);
+ assert.equal(path.dirname(resolved), path.resolve(os.tmpdir()));
+ assert(path.basename(resolved).startsWith('cindy-snapshot-acceptance-'));
+ if (keepFixture) console.log(`Fixture retained for isolated Desktop acceptance: ${resolved}`);
+ else await fs.rm(resolved, { recursive: true, force: true, maxRetries: 20, retryDelay: 100 });
+}
diff --git a/apps/desktop/src/main/__tests__/codexFileRewindPlanner.test.ts b/apps/desktop/src/main/__tests__/codexFileRewindPlanner.test.ts
index bf87c808bc..1894c68f83 100644
--- a/apps/desktop/src/main/__tests__/codexFileRewindPlanner.test.ts
+++ b/apps/desktop/src/main/__tests__/codexFileRewindPlanner.test.ts
@@ -61,6 +61,73 @@ function expectPlanError(
}
describe('buildCodexFileRewindPlan', () => {
+ // #7259 follow-up, unit: the message anchor alone cannot prove retry coverage.
+ // Minimal failure: two durable attempts, only the old attempt completed in Git.
+ it('requires every durable attempt even when a retry never wrote a baseline or gap marker', () => {
+ const repo = {
+ kind: 'local-git' as const, repoRoot: '/repo', currentHead: 'head', currentBranch: 'main',
+ savepointsNewestFirst: [savepoint({
+ commit: 'old', sessionId: 's1', source: 'shadow', kind: 'after-edit',
+ anchor: 'm3', baselineCommit: 'b1', attemptId: 'attempt-1',
+ })],
+ };
+ const snapshotAttempts = [
+ { id: 'attempt-1', anchor: 'm3' }, { id: 'attempt-2', anchor: 'm3' },
+ ];
+ expect(plan({ targetMessageClientId: 'm3', repo, snapshotAttempts })).toMatchObject({
+ mode: 'conversation-only', fallbackReason: 'savepoint-gap',
+ });
+ // A later successful attempt must not erase the middle hole either.
+ snapshotAttempts.push({ id: 'attempt-3', anchor: 'm3' });
+ repo.savepointsNewestFirst.unshift(savepoint({
+ commit: 'new', sessionId: 's1', source: 'shadow', kind: 'after-edit',
+ anchor: 'm3', baselineCommit: 'b3', attemptId: 'attempt-3',
+ }));
+ expect(plan({ targetMessageClientId: 'm3', repo, snapshotAttempts }).mode).toBe('conversation-only');
+ repo.savepointsNewestFirst.push(savepoint({
+ commit: 'middle', sessionId: 's1', source: 'shadow', kind: 'after-edit',
+ anchor: 'm3', baselineCommit: 'b2', attemptId: 'attempt-2',
+ }));
+ expect(plan({ targetMessageClientId: 'm3', repo, snapshotAttempts }).mode).toBe('file-restore');
+ expect(plan({ targetMessageClientId: 'm3', repo, snapshotAttempts: [] }).mode).toBe('conversation-only');
+ });
+
+ it('fails closed on unreadable attempt history but ignores gaps before the target message', () => {
+ expect(plan({ snapshotAttempts: null })).toMatchObject({ mode: 'conversation-only', fallbackReason: 'savepoint-gap' });
+ expect(plan({ snapshotAttempts: [{ id: 'failed', anchor: 'm1' }] }).mode).toBe('file-rewind');
+ expect(plan({ snapshotAttempts: [{ id: 'failed' }] }).mode).toBe('conversation-only');
+ });
+
+ // #7259: a gap commit is best effort and can be absent after timeout/crash.
+ // Unit tier: positive coverage must include all messages, including retries.
+ it.each(['shadow', 'legacy'] as const)('rejects a missing middle or final turn even without a %s gap marker', (source) => {
+ for (const missing of ['m2', 'm3']) {
+ const result = plan({
+ repo: {
+ kind: 'local-git', repoRoot: '/repo', currentHead: 'head', currentBranch: 'main',
+ savepointsNewestFirst: USER_MESSAGES.filter((m) => m.clientId !== missing).map((m) => savepoint({
+ commit: `after-${m.clientId}`, source, sessionId: 's1', kind: 'after-edit',
+ anchor: m.clientId, baselineCommit: `start-${m.clientId}`,
+ })).reverse(),
+ },
+ });
+ expect(result).toMatchObject({ mode: 'conversation-only', fallbackReason: 'savepoint-gap' });
+ }
+ });
+
+ it('does not let an earlier successful retry hide an incomplete start on the same message', () => {
+ const result = plan({
+ targetMessageClientId: 'm3',
+ repo: {
+ kind: 'local-git', repoRoot: '/repo', currentHead: 'head', currentBranch: 'main',
+ savepointsNewestFirst: [
+ savepoint({ commit: 'retry-start', sessionId: 's1', source: 'shadow', kind: 'turn-start', anchor: 'm3' }),
+ savepoint({ commit: 'completed', sessionId: 's1', source: 'shadow', kind: 'after-edit', anchor: 'm3', baselineCommit: 'old-start' }),
+ ],
+ },
+ });
+ expect(result).toMatchObject({ mode: 'conversation-only', fallbackReason: 'savepoint-gap' });
+ });
it('selects current-session after-edit savepoints from the target message onward', () => {
const result = plan();
@@ -118,6 +185,7 @@ describe('buildCodexFileRewindPlan', () => {
it('does not select savepoints from other branches', () => {
const result = plan({
+ userMessages: USER_MESSAGES.slice(0, 2),
repo: {
kind: 'local-git',
repoRoot: '/repo',
@@ -220,6 +288,7 @@ describe('buildCodexFileRewindPlan', () => {
it('allows selected root savepoint commits', () => {
const result = plan({
+ userMessages: USER_MESSAGES.slice(0, 2),
repo: {
kind: 'local-git',
repoRoot: '/repo',
@@ -389,6 +458,7 @@ describe('buildCodexFileRewindPlan', () => {
it('selects shadow savepoints regardless of branch (no branch filter)', () => {
const result = plan({
+ userMessages: USER_MESSAGES.slice(0, 2),
repo: {
kind: 'local-git',
repoRoot: '/repo',
diff --git a/apps/desktop/src/main/__tests__/gitSnapshotCoordinator.test.ts b/apps/desktop/src/main/__tests__/gitSnapshotCoordinator.test.ts
index 8b9a98f742..454b75d337 100644
--- a/apps/desktop/src/main/__tests__/gitSnapshotCoordinator.test.ts
+++ b/apps/desktop/src/main/__tests__/gitSnapshotCoordinator.test.ts
@@ -1,4 +1,5 @@
-import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { currentOperationBudget, operationCheckpoint } from '../utils/operationBudget';
import {
GitSnapshotCoordinator,
@@ -52,6 +53,192 @@ function makeDeps(overrides: Partial<GitSnapshotCoordinatorDeps> = {}): GitSnaps
}
beforeEach(() => vi.clearAllMocks());
+afterEach(() => vi.useRealTimers());
+
+// #7259, unit: Git failures degrade, but unrecorded dispatches cannot be made
+// safe after restart. A stalled intent must reject within the same total budget.
+describe('durable snapshot dispatch intent', () => {
+ it('rejects a stalled intent and never starts Git after its late resolution', async () => {
+ vi.useFakeTimers();
+ const pending = deferred<{ attemptId: string; anchor: string }>();
+ const deps = makeDeps({ snapshotTimeoutMs: 50, recordTurnAttempt: () => pending.promise });
+ const coordinator = new GitSnapshotCoordinator(deps);
+ const result = coordinator.onTurnStart('s1');
+ const rejected = expect(result).rejects.toThrow('deadline');
+ await vi.advanceTimersByTimeAsync(50);
+ await rejected;
+ expect(coordinator.hasPendingTurnStart('s1')).toBe(false);
+ pending.resolve({ attemptId: 'late', anchor: 'm1' });
+ await vi.advanceTimersByTimeAsync(0);
+ expect(deps.getSessionContext).not.toHaveBeenCalled();
+ expect(deps.createShadowSavepoint).not.toHaveBeenCalled();
+ });
+
+ it('pins one durable identity to both boundaries without borrowing a later message', async () => {
+ const deps = makeDeps({ recordTurnAttempt: vi.fn().mockResolvedValue({ attemptId: 'a1', anchor: 'original' }) });
+ const coordinator = new GitSnapshotCoordinator(deps);
+ await coordinator.onTurnStart('s1');
+ await coordinator.onTurnEnd('s1');
+ const inputs = vi.mocked(deps.createShadowSavepoint).mock.calls.map((call) => call[1].meta);
+ expect(inputs).toEqual([
+ expect.objectContaining({ kind: 'turn-start', attemptId: 'a1', anchor: 'original' }),
+ expect.objectContaining({ kind: 'after-edit', attemptId: 'a1', anchor: 'original' }),
+ ]);
+ expect(deps.recordTurnAttempt).toHaveBeenCalledOnce();
+ expect(deps.resolveAnchor).not.toHaveBeenCalled();
+ });
+});
+
+function deferred<T>() {
+ let resolve!: (value: T) => void;
+ const promise = new Promise<T>((done) => { resolve = done; });
+ return { promise, resolve };
+}
+
+// #7259 / #6901: existing tests covered successful snapshots, not stalled
+// dependencies or cancellation. Minimal inputs are one suspended stage/two
+// queued turns. Unit tier, fake timers (no real deadline waits).
+describe('automatic snapshot total budget', () => {
+ it.each(['context', 'root', 'bootstrap', 'anchor', 'savepoint'] as const)(
+ 'bounds a stalled %s and fences late completion', async (stage) => {
+ vi.useFakeTimers();
+ const entered = deferred<void>();
+ const release = deferred<void>();
+ const deps = makeDeps({ snapshotTimeoutMs: 50 });
+ const stall = async <T>(result: T) => { entered.resolve(); await release.promise; return result; };
+ if (stage === 'context') deps.getSessionContext = vi.fn(() => stall({ workingDir: '/repo', agentKind: 'codex' as const }));
+ if (stage === 'root') deps.detectRepoRoot = vi.fn(() => stall('/repo'));
+ if (stage === 'bootstrap') {
+ deps.detectRepoRoot = vi.fn().mockResolvedValue(null);
+ deps.initializeProjectGit = vi.fn(() => stall({ repoRoot: '/repo' }));
+ }
+ if (stage === 'anchor') deps.resolveAnchor = vi.fn(() => stall('msg-1'));
+ const published = vi.fn();
+ if (stage === 'savepoint') deps.createShadowSavepoint = vi.fn(async () => {
+ await stall(undefined);
+ operationCheckpoint();
+ published();
+ return savepointResult('late');
+ });
+ const coordinator = new GitSnapshotCoordinator(deps);
+ const start = coordinator.onTurnStart('s1');
+ await entered.promise;
+ await vi.advanceTimersByTimeAsync(50);
+ await start;
+ release.resolve();
+ await vi.advanceTimersByTimeAsync(0);
+ expect(published).not.toHaveBeenCalled();
+ if (stage !== 'savepoint') expect(deps.createShadowSavepoint).not.toHaveBeenCalled();
+ coordinator.onSessionClosed('s1');
+ },
+ );
+
+ it('counts metadata and repo queue waiting in the same budget, and skips expired jobs', async () => {
+ vi.useFakeTimers();
+ const release = deferred<void>();
+ const blocker = enqueueGitRepoWrite('/budget-repo', () => release.promise);
+ const deps = makeDeps({ snapshotTimeoutMs: 50, detectRepoRoot: vi.fn().mockResolvedValue('/budget-repo') });
+ const coordinator = new GitSnapshotCoordinator(deps);
+ const start = coordinator.onTurnStart('s1');
+ await vi.advanceTimersByTimeAsync(30);
+ // A different repository remains independent while the first one is stuck.
+ const other = new GitSnapshotCoordinator(makeDeps());
+ await other.onTurnStart('other');
+ await vi.advanceTimersByTimeAsync(20);
+ await start;
+ release.resolve();
+ await blocker;
+ await enqueueGitRepoWrite('/budget-repo', async () => {});
+ expect(deps.createShadowSavepoint).not.toHaveBeenCalled();
+ coordinator.onSessionClosed('s1');
+ other.onSessionClosed('other');
+ });
+
+ it('does not reset the budget after context resolution', async () => {
+ vi.useFakeTimers();
+ const context = deferred<{ workingDir: string; agentKind: 'codex' }>();
+ const root = deferred<string>();
+ const deps = makeDeps({ snapshotTimeoutMs: 50, getSessionContext: () => context.promise, detectRepoRoot: () => root.promise });
+ const coordinator = new GitSnapshotCoordinator(deps);
+ const start = coordinator.onTurnStart('s1');
+ await vi.advanceTimersByTimeAsync(30);
+ context.resolve({ workingDir: '/repo', agentKind: 'codex' });
+ await vi.advanceTimersByTimeAsync(20);
+ await start;
+ root.resolve('/repo');
+ await vi.advanceTimersByTimeAsync(0);
+ expect(deps.createShadowSavepoint).not.toHaveBeenCalled();
+ coordinator.onSessionClosed('s1');
+ });
+
+ it.each(['signal', 'close', 'abort'] as const)('cancels a waiting start through %s without late writes', async (kind) => {
+ const entered = deferred<void>();
+ const release = deferred<string | null>();
+ const deps = makeDeps({ detectRepoRoot: async () => { entered.resolve(); return release.promise; } });
+ const coordinator = new GitSnapshotCoordinator(deps);
+ const controller = new AbortController();
+ const start = coordinator.onTurnStart('s1', controller.signal);
+ await entered.promise;
+ if (kind === 'signal') controller.abort();
+ else if (kind === 'close') coordinator.onSessionClosed('s1');
+ else coordinator.onTurnAbort('s1');
+ await start;
+ release.resolve('/repo');
+ await Promise.resolve();
+ expect(deps.createShadowSavepoint).not.toHaveBeenCalled();
+ coordinator.onSessionClosed('s1');
+ });
+
+ it('waits for child cleanup before releasing the repository write slot', async () => {
+ vi.useFakeTimers();
+ const entered = deferred<void>();
+ const cleanup = deferred<void>();
+ const deps = makeDeps({ snapshotTimeoutMs: 50, createShadowSavepoint: async () => {
+ currentOperationBudget()!.track(cleanup.promise);
+ entered.resolve();
+ return new Promise<ShadowSavepointResult>(() => {});
+ } });
+ const coordinator = new GitSnapshotCoordinator(deps);
+ let settled = false;
+ const start = coordinator.onTurnStart('s1').then(() => { settled = true; });
+ await entered.promise;
+ const following = vi.fn(async () => {});
+ const next = enqueueGitRepoWrite('/repo', following);
+ await vi.advanceTimersByTimeAsync(50);
+ expect(settled).toBe(false);
+ expect(following).not.toHaveBeenCalled();
+ cleanup.resolve();
+ await Promise.all([start, next]);
+ expect(following).toHaveBeenCalledOnce();
+ coordinator.onSessionClosed('s1');
+ });
+
+ it('bounds after-edit label generation and never publishes its late result', async () => {
+ vi.useFakeTimers();
+ const entered = deferred<void>();
+ const label = deferred<string>();
+ const published = vi.fn();
+ const deps = makeDeps({ snapshotTimeoutMs: 50, oneShot: async () => { entered.resolve(); return label.promise; } });
+ vi.mocked(deps.createShadowSavepoint).mockImplementation(async (_repo, input) => {
+ if (typeof input.label === 'function') {
+ await input.label({ diffStat: 'a | 1 +', diffText: '+a' });
+ operationCheckpoint();
+ published();
+ }
+ return savepointResult('baseline');
+ });
+ const coordinator = new GitSnapshotCoordinator(deps);
+ await coordinator.onTurnStart('s1');
+ const end = coordinator.onTurnEnd('s1');
+ await entered.promise;
+ await vi.advanceTimersByTimeAsync(50);
+ await end;
+ label.resolve('late');
+ await vi.advanceTimersByTimeAsync(0);
+ expect(published).not.toHaveBeenCalled();
+ expect(deps.createShadowMarker).not.toHaveBeenCalled();
+ });
+});
async function waitFor(condition: () => boolean): Promise<void> {
for (let i = 0; i < 20; i += 1) {
diff --git a/apps/desktop/src/main/__tests__/gitSnapshotHost.test.ts b/apps/desktop/src/main/__tests__/gitSnapshotHost.test.ts
index 10337f6015..d952d32d49 100644
--- a/apps/desktop/src/main/__tests__/gitSnapshotHost.test.ts
+++ b/apps/desktop/src/main/__tests__/gitSnapshotHost.test.ts
@@ -1,14 +1,26 @@
-import { describe, expect, it, vi } from 'vitest';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
import path from 'node:path';
vi.mock('electron', () => ({ app: { getPath: () => path.resolve('snapshot-profile') } }));
-import { createGitSnapshotCoordinator } from '../maker-host/git-snapshot-host';
+import { createGitSnapshotCoordinator as createHost, type GitSnapshotCoordinatorHostDeps } from '../maker-host/git-snapshot-host';
+const journal = vi.hoisted(() => ({ generation: 1, record: vi.fn(async (_sessionId: string, anchor?: string) => ({ id: 'attempt-1', anchor })) }));
+vi.mock('../git-snapshot/snapshotAttemptStore', () => ({ SnapshotAttemptStore: class { record = journal.record; } }));
+vi.mock('../appSessionState', async (importOriginal) => ({
+ ...await importOriginal<typeof import('../appSessionState')>(),
+ getActiveAppSession: () => ({ dataOwnerId: 'owner-1', generation: journal.generation }),
+ ownerScopedUserDataPath: () => '/test-owner',
+}));
+
+function createGitSnapshotCoordinator(maker: Parameters<typeof createHost>[0], deps: GitSnapshotCoordinatorHostDeps = {}) {
+ return createHost(maker, { getLatestUserMessage: async () => null, ...deps });
+}
import type {
CreateShadowSavepointInput,
ShadowSavepointResult,
} from '../git-snapshot/gitSnapshotService';
const logger = { info: vi.fn(), warn: vi.fn(), debug: vi.fn() };
+beforeEach(() => { journal.record.mockClear(); journal.generation = 1; });
function makeMaker(
overrides: Partial<{
@@ -32,6 +44,30 @@ function makeMaker(
}
describe('createGitSnapshotCoordinator', () => {
+ it('does not record or authorize a send after the owner changes during anchor lookup', async () => {
+ let entered!: () => void;
+ const lookupStarted = new Promise<void>((resolve) => { entered = resolve; });
+ let finish!: (value: null) => void;
+ const lookup = new Promise<null>((resolve) => { finish = resolve; });
+ const coordinator = createGitSnapshotCoordinator(makeMaker(), {
+ getLatestUserMessage: () => { entered(); return lookup; },
+ });
+ const starting = coordinator.onTurnStart('s1');
+ await lookupStarted;
+ journal.generation += 1;
+ finish(null);
+ await expect(starting).rejects.toThrow('owner changed');
+ expect(journal.record).not.toHaveBeenCalled();
+ });
+ it('refuses dispatch when durable intent storage fails before any Git lookup', async () => {
+ journal.record.mockRejectedValueOnce(new Error('ENOSPC'));
+ const maker = makeMaker();
+ const createShadowSavepoint = vi.fn();
+ const coordinator = createGitSnapshotCoordinator(maker, { createShadowSavepoint });
+ await expect(coordinator.onTurnStart('s1')).rejects.toThrow('ENOSPC');
+ expect(maker.getSessionMeta).not.toHaveBeenCalled();
+ expect(createShadowSavepoint).not.toHaveBeenCalled();
+ });
it.each(['source', 'worktrees/run', 'merge-worktrees/12345678-1234-1234-1234-123456789abc'])(
'never creates hidden commits in Cindy Make %s',
async (directory) => {
@@ -103,6 +139,7 @@ describe('createGitSnapshotCoordinator', () => {
kind: 'after-edit',
anchor: 'msg-1',
baselineCommit: 'hash123',
+ attemptId: 'attempt-1',
});
expect(input.skipIfTreeEquals).toBe('hash123');
expect(getLatestUserMessage).toHaveBeenCalledOnce();
@@ -111,7 +148,8 @@ describe('createGitSnapshotCoordinator', () => {
expect.stringContaining('please update login'),
{
maxTokens: 80,
- timeoutMs: 20_000,
+ timeoutMs: 1_000,
+ signal: expect.any(AbortSignal),
},
);
});
diff --git a/apps/desktop/src/main/__tests__/gitSnapshotShadow.git-integration.test.ts b/apps/desktop/src/main/__tests__/gitSnapshotShadow.git-integration.test.ts
index f8ea3bbd7f..15aac32b06 100644
--- a/apps/desktop/src/main/__tests__/gitSnapshotShadow.git-integration.test.ts
+++ b/apps/desktop/src/main/__tests__/gitSnapshotShadow.git-integration.test.ts
@@ -11,7 +11,10 @@ import fsSync from 'node:fs';
import os from 'node:os';
import path from 'node:path';
-import { afterAll, afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { OperationBudget } from '../utils/operationBudget';
+import { SnapshotAttemptStore } from '../git-snapshot/snapshotAttemptStore';
+import { buildCodexFileRewindPlan } from '../git-snapshot/codexFileRewindPlanner';
import { TestDirectoryTemplate } from '../../test/vitest/testDirectoryTemplate';
import {
@@ -35,6 +38,58 @@ import { gitExec } from '../worktree/gitExec';
const REAL_GIT_TEST_TIMEOUT_MS = process.platform === 'win32' ? 60_000 : 20_000;
const SESSION = 'shadow-sess-1';
+// #7259, git-integration: public file store + Git trailer round trip + planner.
+// Old tests only had missing Git baselines, not a retry with no Git evidence at all.
+describe('durable attempt history', () => {
+ it('remembers a failed same-message retry across store reconstruction', async () => {
+ const root = await fs.mkdtemp(path.join(os.tmpdir(), 'snapshot-attempts-'));
+ try {
+ await commitSeed();
+ const store = new SnapshotAttemptStore(root);
+ const first = await store.record(SESSION, 'message-1');
+ const baseline = await createShadowSavepoint(repoPath, {
+ sessionId: SESSION, label: 'baseline', meta: { kind: 'turn-start', anchor: first.anchor, attemptId: first.id },
+ });
+ await createShadowSavepoint(repoPath, {
+ sessionId: SESSION, label: 'complete',
+ meta: { kind: 'after-edit', anchor: first.anchor, attemptId: first.id, baselineCommit: baseline.commit! },
+ });
+ const { entries } = await listShadowSavepoints(repoPath, SESSION);
+ expect(entries[0].attemptId).toBe(first.id);
+ const input = {
+ sessionId: SESSION, targetMessageClientId: 'message-1', userMessages: [{ clientId: 'message-1', createdAt: 1 }],
+ repo: { kind: 'local-git' as const, repoRoot: repoPath, currentHead: await head(), currentBranch: 'main',
+ savepointsNewestFirst: entries.map((entry) => ({ ...entry, source: 'shadow' as const, branch: entry.branch ?? '' })) },
+ };
+ expect(buildCodexFileRewindPlan({ ...input, snapshotAttempts: await store.read(SESSION) }).mode).toBe('file-restore');
+ // This retry times out before baseline/marker publication; simulate restart
+ // by reading with a fresh store that knows nothing about the running attempt.
+ await store.record(SESSION, 'message-1');
+ expect(buildCodexFileRewindPlan({ ...input, snapshotAttempts: await new SnapshotAttemptStore(root).read(SESSION) }))
+ .toMatchObject({ mode: 'conversation-only', fallbackReason: 'savepoint-gap' });
+ } finally {
+ await fs.rm(root, { recursive: true, force: true });
+ }
+ });
+
+ it('keeps concurrent intents separate and treats partial records as unknown history', async () => {
+ const root = await fs.mkdtemp(path.join(os.tmpdir(), 'snapshot-attempts-'));
+ try {
+ const store = new SnapshotAttemptStore(root);
+ const records = await Promise.all([store.record('s', 'm'), store.record('s', 'm')]);
+ expect(new Set(records.map((record) => record.id)).size).toBe(2);
+ expect(await new SnapshotAttemptStore(root).read('s')).toEqual(expect.arrayContaining(records));
+ expect(await store.read('another-session')).toEqual([]);
+ expect(await new SnapshotAttemptStore(path.join(root, 'other-owner')).read('s')).toEqual([]);
+ const [dir] = await fs.readdir(path.join(root, 'git-snapshot-attempts'));
+ await fs.writeFile(path.join(root, 'git-snapshot-attempts', dir, `${records[0].id}.json`), '{');
+ expect(await store.read('s')).toBeNull();
+ } finally {
+ await fs.rm(root, { recursive: true, force: true });
+ }
+ });
+});
+
const canLinkFile = (() => {
const root = fsSync.mkdtempSync(path.join(os.tmpdir(), 'shadow-file-link-probe-'));
try {
@@ -141,6 +196,53 @@ afterAll(async () => {
});
describe('createShadowSavepoint', () => {
+ it('terminates a real Git child on cancellation instead of abandoning the promise', async () => {
+ const budget = new OperationBudget(10_000);
+ let spawned!: (pid: number) => void;
+ const started = new Promise<number>((resolve) => { spawned = resolve; });
+ // hash-object waits for its pipe input; no hooks, sleep scripts or user config.
+ const running = budget.run(() => gitExec(['hash-object', '--stdin'], repoPath, { onSpawn: spawned }));
+ const pid = await started;
+ budget.cancel(new Error('stop real Git'));
+ await expect(running).rejects.toThrow('stop real Git');
+ expect(() => process.kill(pid, 0)).toThrow();
+ }, REAL_GIT_TEST_TIMEOUT_MS);
+
+ // #7259: git-integration tier. An unchanged automatic turn still needs
+ // durable completion evidence; omitted filtered changes must never publish it.
+ it('records unchanged completion and refuses a filtered change before updating the ref', async () => {
+ await commitSeed();
+ const baseline = await createShadowSavepoint(repoPath, { sessionId: SESSION, label: 'start', meta: { kind: 'turn-start', anchor: 'm1' } });
+ const label = vi.fn(async () => 'unused');
+ const completed = await createShadowSavepoint(repoPath, {
+ sessionId: SESSION, label, meta: { kind: 'after-edit', anchor: 'm1', baselineCommit: baseline.commit! },
+ skipIfTreeEquals: baseline.commit!, recordUnchanged: true,
+ baselineSkippedFingerprints: baseline.skippedFingerprints,
+ });
+ expect(completed.commit).toBeTruthy();
+ expect(completed.tree).toBe(baseline.tree);
+ expect(label).not.toHaveBeenCalled();
+ await writeRepoFile('.env', 'INVALID_TEST_KEY=changed\n');
+ await expect(createShadowSavepoint(repoPath, {
+ sessionId: SESSION, label: 'must not publish', meta: { kind: 'after-edit', anchor: 'm1', baselineCommit: baseline.commit! },
+ recordUnchanged: true, baselineSkippedFingerprints: baseline.skippedFingerprints,
+ })).rejects.toThrow('partially filtered');
+ expect(await readSavepointTip(repoPath, SESSION)).toBe(completed.commit);
+ }, REAL_GIT_TEST_TIMEOUT_MS);
+
+ it('cancels after staging and never publishes a late label result', async () => {
+ await commitSeed();
+ const before = await captureUserVisibleState();
+ const budget = new OperationBudget(10_000);
+ const snapshot = budget.run(() => createShadowSavepoint(repoPath, {
+ sessionId: SESSION,
+ label: async () => { budget.cancel(new Error('stopped during label')); return 'late'; },
+ meta: { kind: 'turn-start' },
+ }));
+ await expect(snapshot).rejects.toThrow('stopped during label');
+ expect(await readSavepointTip(repoPath, SESSION)).toBeNull();
+ expect(await captureUserVisibleState()).toEqual(before);
+ }, REAL_GIT_TEST_TIMEOUT_MS);
it('never changes HEAD, branch, status or the cached diff', async () => {
await commitSeed();
await writeRepoFile('staged.txt', 'staged change\n');
diff --git a/apps/desktop/src/main/__tests__/rewind.test.ts b/apps/desktop/src/main/__tests__/rewind.test.ts
index 0c90483061..b76d0e7d7f 100644
--- a/apps/desktop/src/main/__tests__/rewind.test.ts
+++ b/apps/desktop/src/main/__tests__/rewind.test.ts
@@ -24,6 +24,8 @@ import path from 'node:path';
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { enqueueGitRepoWrite } from '../git-snapshot/gitRepoWriteQueue';
+const attemptJournal = vi.hoisted(() => ({ read: vi.fn<() => Promise<Array<{ id: string; anchor?: string }> | null>>() }));
+vi.mock('../git-snapshot/snapshotAttemptStore', () => ({ SnapshotAttemptStore: class { read = attemptJournal.read; } }));
// ── mock(必须在延迟 import 前 hoist) ─────────────────────────────────────
@@ -179,6 +181,7 @@ const originalClaudeConfigDir = process.env.CLAUDE_CONFIG_DIR;
const tempDirs: string[] = [];
beforeEach(async () => {
+ attemptJournal.read.mockReset().mockResolvedValue([]);
if (originalClaudeConfigDir === undefined) delete process.env.CLAUDE_CONFIG_DIR;
else process.env.CLAUDE_CONFIG_DIR = originalClaudeConfigDir;
selectQueue.length = 0;
@@ -1526,6 +1529,28 @@ describe('commitRewindAtMessage', () => {
expect(result.id).toBe('sess-1');
});
+ // #7259 follow-up, unit production commit entry: the old completion must not
+ // produce a file operation when the same message has an unrecorded retry.
+ it('Codex commit keeps files when the durable journal contains a retry without a baseline', async () => {
+ useFakeSession('codex');
+ detectCwdMock.mockResolvedValueOnce({ gitInstalled: true, isGitRepo: true, repoRoot: '/repo', isInsideWorktree: false });
+ listShadowSavepointsMock.mockResolvedValueOnce([{
+ commit: 'sc1', sessionId: 'sess-1', kind: 'after-edit', source: 'cindy', parentCount: 1,
+ anchor: 'client-id', baselineCommit: 'base1', attemptId: 'old', label: 'old completed turn', time: '2026-10-26',
+ }]);
+ attemptJournal.read.mockResolvedValueOnce([{ id: 'old', anchor: 'client-id' }, { id: 'retry', anchor: 'client-id' }]);
+ selectQueue.push([makeUserMessageRow({ agentMeta: null })], [], [makeUserMessageRow({ clientId: 'client-id', createdAt: 3000 })]);
+ enqueueCodexClearGeneration();
+ selectQueue.push([], [], [makeSessionRow({ agentKind: 'codex' })]);
+ await commitRewindAtMessage('sess-1', 'client-id');
+ expect(executeCodexFileRestorePlanWithThreadRollbackMock).not.toHaveBeenCalled();
+ expect(executeCodexFileRewindPlanWithThreadRollbackMock).toHaveBeenCalledWith(
+ expect.objectContaining({ mode: 'conversation-only', fallbackReason: 'savepoint-gap' }),
+ 'sess-1', expect.anything(),
+ );
+ expect(commitRewindFilesMock).toHaveBeenCalledWith('', '', { tailTurnsToDrop: 1, rewindsToNativeThreadStart: true });
+ });
+
it('Codex commit: allowFileRestore=false skips file restore even if savepoints exist', async () => {
useFakeSession('codex');
detectCwdMock.mockResolvedValueOnce({ gitInstalled: true, isGitRepo: true, repoRoot: '/repo', isInsideWorktree: false });
diff --git a/apps/desktop/src/main/__tests__/snapshotFileFilter.git-integration.test.ts b/apps/desktop/src/main/__tests__/snapshotFileFilter.git-integration.test.ts
index 7092bfb480..d4b8bcc384 100644
--- a/apps/desktop/src/main/__tests__/snapshotFileFilter.git-integration.test.ts
+++ b/apps/desktop/src/main/__tests__/snapshotFileFilter.git-integration.test.ts
@@ -10,6 +10,8 @@ import {
buildSnapshotFilePlanFromEntries,
parseStatusPorcelainZ,
} from '../git-snapshot/snapshotFileFilter';
+import { ensureManagedWorktreeExcluded } from '../worktree/managedWorktreeExclude';
+import { OperationBudget } from '../utils/operationBudget';
function git(cwd: string, args: readonly string[]): Promise<void> {
return new Promise((resolve, reject) => {
@@ -268,6 +270,99 @@ describe('buildSnapshotFilePlan', () => {
);
});
+ // #7259, git-integration tier: cancel while native filesystem metadata is
+ // pending. Existing scans only covered completed lstat calls.
+ it('stops a stalled file scan and ignores the late filesystem result', async () => {
+ await writeRepoFile(repoPath, 'slow.txt', 'slow');
+ const budget = new OperationBudget(10_000);
+ const nativeLstat = fs.lstat.bind(fs);
+ let entered!: () => void;
+ const started = new Promise<void>((resolve) => { entered = resolve; });
+ let release!: () => void;
+ const gate = new Promise<void>((resolve) => { release = resolve; });
+ const spy = vi.spyOn(fs, 'lstat').mockImplementation(async (...args) => {
+ if (String(args[0]) === path.join(repoPath, 'slow.txt')) {
+ entered();
+ await gate;
+ }
+ return nativeLstat(...args);
+ });
+ try {
+ const scanning = budget.run(() => buildSnapshotFilePlanFromEntries(repoPath, [
+ { code: '??', path: 'slow.txt' }, { code: '??', path: 'later.txt' },
+ ]));
+ await started;
+ budget.cancel(new Error('stopped scan'));
+ await expect(scanning).rejects.toThrow('stopped scan');
+ release();
+ expect(spy.mock.calls.some(([file]) => String(file) === path.join(repoPath, 'later.txt'))).toBe(false);
+ } finally {
+ release();
+ spy.mockRestore();
+ }
+ });
+
+ // #7259: prove the exclusion changes real Git enumeration, including gitfile layouts.
+ // Creation's mocked Git tests cannot verify root anchoring or tracked-file preservation.
+ // Minimal input: managed noise, a tracked file and a nested same-name directory.
+ // Windows 2026-10-26: this file alone took 4.07s wall clock (Vitest 2.33s).
+ it('excludes managed untracked files through a gitfile without hiding tracked or ordinary project files', async () => {
+ const gitDir = path.join(testRoot, 'separate git');
+ await git(repoPath, ['init', '--separate-git-dir', gitDir]);
+ const exclude = path.join(gitDir, 'info', 'exclude');
+ await fs.writeFile(exclude, '# local rule\ncache/\n');
+ await writeRepoFile(repoPath, '.cindy-worktrees/tracked.txt', 'before');
+ await git(repoPath, ['add', '.cindy-worktrees/tracked.txt']);
+ await writeRepoFile(repoPath, '.cindy-worktrees/tracked.txt', 'after');
+ await writeRepoFile(repoPath, '.cindy-worktrees/managed/noise.txt', 'noise');
+ await writeRepoFile(repoPath, '.xdt-worktrees/legacy/noise.txt', 'noise');
+ await writeRepoFile(repoPath, 'src/.cindy-worktrees/user.txt', 'keep');
+ await writeRepoFile(repoPath, 'ordinary/user.txt', 'keep');
+ await writeRepoFile(repoPath, 'cache/cache.txt', 'noise');
+
+ // Non-managed paths must not cause any local rule changes.
+ await ensureManagedWorktreeExcluded(repoPath, path.join(repoPath, 'ordinary', 'example'));
+ expect(await fs.readFile(exclude, 'utf8')).toBe('# local rule\ncache/\n');
+ await Promise.all([
+ ensureManagedWorktreeExcluded(repoPath, path.join(repoPath, '.cindy-worktrees', 'managed')),
+ ensureManagedWorktreeExcluded(repoPath, path.join(repoPath, '.xdt-worktrees', 'legacy')),
+ ]);
+ const plan = await buildSnapshotFilePlan(repoPath);
+ expect(plan.skippedFiles).toEqual([]);
+ expect(plan.includedFiles.map((file) => file.path).sort()).toEqual([
+ '.cindy-worktrees/tracked.txt', 'ordinary/user.txt', 'src/.cindy-worktrees/user.txt',
+ ]);
+ expect(await fs.readFile(exclude, 'utf8')).toContain('# local rule\ncache/\n');
+ await expect(fs.access(path.join(repoPath, '.gitignore'))).rejects.toMatchObject({ code: 'ENOENT' });
+ });
+
+ // #7259 / #6901: sibling files used to repeat ancestor .git I/O. Existing
+ // nested-repo tests do not cover scan-local reuse or invalidation between scans.
+ // Two sibling files and a later .git marker are the minimal input (git-integration tier).
+ it.each(['directory', 'file'])('reuses ancestor checks only within one scan, then detects a new .git %s', async (kind) => {
+ await writeRepoFile(repoPath, 'src/deep/a.ts', 'a');
+ await writeRepoFile(repoPath, 'src/deep/b.ts', 'b');
+ const entries = ['src/deep/a.ts', 'src/deep/b.ts'].map((file) => ({ code: '??', path: file }));
+ const marker = path.join(repoPath, 'src', '.git');
+ const lstat = vi.spyOn(fs, 'lstat');
+ try {
+ const first = await buildSnapshotFilePlanFromEntries(repoPath, entries);
+ expect(first.includedFiles.map((file) => file.path)).toEqual(entries.map((file) => file.path));
+ expect(lstat.mock.calls.filter(([file]) => file === marker)).toHaveLength(1);
+
+ if (kind === 'directory') await fs.mkdir(marker);
+ else await fs.writeFile(marker, 'gitdir: elsewhere\n');
+ const second = await buildSnapshotFilePlanFromEntries(repoPath, entries);
+ expect(second.includedFiles).toEqual([]);
+ expect(second.skippedFiles.map((file) => [file.path, file.reason])).toEqual(
+ entries.map((file) => [file.path, 'nested-git-repo']),
+ );
+ expect(lstat.mock.calls.filter(([file]) => file === marker)).toHaveLength(2);
+ } finally {
+ lstat.mockRestore();
+ }
+ });
+
it('checks rename oldPath for nested git repositories', async () => {
const nestedPath = path.join(repoPath, 'vendor', 'tool');
await fs.mkdir(nestedPath, { recursive: true });
diff --git a/apps/desktop/src/main/__tests__/worktreeDetectCwd.test.ts b/apps/desktop/src/main/__tests__/worktreeDetectCwd.test.ts
index 6ebf9abc6d..9ad57c3e64 100644
--- a/apps/desktop/src/main/__tests__/worktreeDetectCwd.test.ts
+++ b/apps/desktop/src/main/__tests__/worktreeDetectCwd.test.ts
@@ -13,6 +13,7 @@ import path from 'node:path';
import fs from 'node:fs/promises';
import { detectCwd } from '../worktree/WorktreeManager';
import { GitExecError, type GitExecOpts } from '../worktree/gitExec';
+import { OperationBudget, currentOperationBudget } from '../utils/operationBudget';
// ── mock gitExec, 控制 detectCwd 看到的 git 输出 ──────────────────────────
const { gitExecMock, realpathMock } = vi.hoisted(() => ({
@@ -76,6 +77,31 @@ function setupGitMock(opts: {
}
describe('detectCwd → isInsideWorktree (I-1 fix)', () => {
+ // #7259, unit tier: a cancellable snapshot probe must not share a pending UI
+ // probe. The two callers own different lifetimes even for the same directory.
+ it('isolates a cancelled snapshot probe from a pending UI probe of the same directory', async () => {
+ realpathMock.mockResolvedValue(path.resolve('/probe-repo'));
+ let releaseUi!: () => void;
+ let enteredSnapshot!: () => void;
+ const entered = new Promise<void>((resolve) => { enteredSnapshot = resolve; });
+ const budget = new OperationBudget(1_000);
+ const answer = { stdout: '/probe-repo\nmain\n.git\n.git\n', stderr: '' };
+ gitExecMock.mockImplementation(() => {
+ if (currentOperationBudget()) {
+ enteredSnapshot();
+ return new Promise((_resolve, reject) => budget.signal.addEventListener('abort', () => reject(budget.signal.reason), { once: true }));
+ }
+ return new Promise((resolve) => { releaseUi = () => resolve(answer); });
+ });
+ const ui = detectCwd('/probe-repo');
+ const snapshot = budget.run(() => detectCwd('/probe-repo'));
+ await entered;
+ budget.cancel(new Error('snapshot stopped'));
+ await expect(snapshot).rejects.toThrow('snapshot stopped');
+ releaseUi();
+ await expect(ui).resolves.toMatchObject({ isGitRepo: true });
+ expect(gitExecMock).toHaveBeenCalledTimes(2);
+ });
// PR #6544: 5s realpath + 10s Git leaves no headroom in Mobile's 15s wait.
// Existing coverage bounds each phase separately, not their sum (unit tier).
it.each([
diff --git a/apps/desktop/src/main/__tests__/worktreeManagerCreate.test.ts b/apps/desktop/src/main/__tests__/worktreeManagerCreate.test.ts
index 52b76c86d5..3dd36ae9dd 100644
--- a/apps/desktop/src/main/__tests__/worktreeManagerCreate.test.ts
+++ b/apps/desktop/src/main/__tests__/worktreeManagerCreate.test.ts
@@ -76,6 +76,9 @@ describe('createWorktree naming authority', () => {
if (args[0] === 'rev-parse' && args[1] === '--abbrev-ref') {
return { stdout: 'main\n', stderr: '' };
}
+ if (args[0] === 'rev-parse' && args[1] === '--git-path') {
+ return { stdout: '.git/info/exclude\n', stderr: '' };
+ }
if (args[0] === 'rev-parse' && (args[1] === '--git-dir' || args[1] === '--git-common-dir')) {
return { stdout: '.git\n', stderr: '' };
}
@@ -105,6 +108,31 @@ describe('createWorktree naming authority', () => {
});
}
+ // #7259: creation must keep managed checkouts out of the parent's untracked scan.
+ // Existing naming tests do not inspect the local exclude file. Two creates with an
+ // existing rule and no final newline cover preservation and idempotence (unit tier).
+ // Windows 2026-10-26: this file alone took 3.05s wall clock (Vitest 1.43s).
+ it('appends the managed directory exclusion once without changing existing rules or .gitignore', async () => {
+ const exclude = path.join(baseRepo, '.git', 'info', 'exclude');
+ fs.mkdirSync(path.dirname(exclude), { recursive: true });
+ fs.writeFileSync(exclude, '# user rules\r\nlocal-cache/');
+ fs.writeFileSync(path.join(baseRepo, '.gitignore'), 'build/\n');
+
+ await expect(create('first')).resolves.toMatchObject({ ok: true });
+ await expect(create('second', 'session-2')).resolves.toMatchObject({ ok: true });
+
+ expect(fs.readFileSync(exclude, 'utf8')).toBe('# user rules\r\nlocal-cache/\r\n/.cindy-worktrees/\r\n');
+ expect(fs.readFileSync(path.join(baseRepo, '.gitignore'), 'utf8')).toBe('build/\n');
+ });
+
+ // A read/write failure in this optimization must not prevent starting a task.
+ it('still creates the worktree when the local exclude cannot be updated', async () => {
+ const exclude = path.join(baseRepo, '.git', 'info', 'exclude');
+ fs.mkdirSync(exclude, { recursive: true });
+ await expect(create('exclude-unavailable')).resolves.toMatchObject({ ok: true });
+ expect(fs.statSync(exclude).isDirectory()).toBe(true);
+ });
+
it('records the background checkout child and holds its lease until completion', async () => {
const previousGit = gitExecMock.getMockImplementation()!;
let finishCheckout!: () => void;
diff --git a/apps/desktop/src/main/git-snapshot/codexFileRewindPlanner.ts b/apps/desktop/src/main/git-snapshot/codexFileRewindPlanner.ts
index 6d6062310c..4cabbcd043 100644
--- a/apps/desktop/src/main/git-snapshot/codexFileRewindPlanner.ts
+++ b/apps/desktop/src/main/git-snapshot/codexFileRewindPlanner.ts
@@ -7,6 +7,7 @@
*/
import type { SnapshotKind } from './snapshotTrailers';
+import type { SnapshotAttempt } from './snapshotAttemptStore';
/** A visible user message in ascending conversation order. */
export interface CodexRewindUserMessage {
@@ -31,6 +32,7 @@ export interface CodexRewindSavepoint {
label?: string;
/** Shadow after-edit only: turn-start savepoint the delta is based on. */
baselineCommit?: string;
+ attemptId?: string;
}
/** Repository context known before planning file rewind. */
@@ -67,6 +69,8 @@ export interface BuildCodexFileRewindPlanInput {
targetMessageClientId: string;
repo: CodexFileRewindRepoContext;
userMessages: readonly CodexRewindUserMessage[];
+ /** Host always supplies the durable journal; null is an unreadable journal. */
+ snapshotAttempts?: readonly SnapshotAttempt[] | null;
}
export interface CodexFileRewindPlanCommit {
@@ -197,6 +201,26 @@ export function buildCodexFileRewindPlan(
input.userMessages.map((message, index) => [message.clientId, index]),
);
+ // No Git marker exists if the baseline itself timed out. A previous completion
+ // on the SAME message must never cover that new dispatch, even after restart.
+ if (input.snapshotAttempts === null) {
+ return { ...base, mode: 'conversation-only', fallbackReason: 'savepoint-gap' };
+ }
+ if (input.snapshotAttempts) {
+ const completed = new Map(repo.savepointsNewestFirst.filter((point) =>
+ point.sessionId === input.sessionId && point.source === 'shadow' &&
+ point.kind === 'after-edit' && point.baselineCommit && point.attemptId,
+ ).map((point) => [point.attemptId!, point.anchor]));
+ const recorded = new Set(input.snapshotAttempts.map((attempt) => attempt.id));
+ const missing = input.snapshotAttempts.some((attempt) =>
+ (!attempt.anchor || anchorsToRevert.has(attempt.anchor)) &&
+ (!completed.has(attempt.id) || completed.get(attempt.id) !== attempt.anchor));
+ const lostJournal = repo.savepointsNewestFirst.some((point) =>
+ point.sessionId === input.sessionId && point.attemptId && point.anchor &&
+ anchorsToRevert.has(point.anchor) && !recorded.has(point.attemptId));
+ if (missing || lostJournal) return { ...base, mode: 'conversation-only', fallbackReason: 'savepoint-gap' };
+ }
+
// The two savepoint generations are scanned independently: each bucket is
// newest-first on its own timeline (branch history vs hidden ref chain),
// and blocking-marker position math must not mix the two.
@@ -234,6 +258,20 @@ export function buildCodexFileRewindPlan(
}
if (shadow.selected.length > 0) {
+ // A best-effort Git gap marker can itself fail. Require positive evidence
+ // for EVERY visible turn, not just the after-edits that happened to survive.
+ // New automatic captures also publish unchanged trees as completion records.
+ // Older no-op turns without completion evidence conservatively degrade.
+ const covered = new Set(shadow.selected.map((savepoint) => savepoint.anchor));
+ const completedBaselines = new Set(shadow.selected.map((savepoint) => savepoint.baselineCommit));
+ const incompleteStart = repo.savepointsNewestFirst.some((savepoint) =>
+ savepoint.source === 'shadow' && savepoint.sessionId === input.sessionId &&
+ savepoint.kind === 'turn-start' &&
+ (!savepoint.anchor || anchorsToRevert.has(savepoint.anchor)) &&
+ !completedBaselines.has(savepoint.commit));
+ if (incompleteStart || [...anchorsToRevert].some((anchor) => !covered.has(anchor))) {
+ return { ...base, mode: 'conversation-only', fallbackReason: 'savepoint-gap' };
+ }
return buildRestorePlan(base, repo, shadow.selected);
}
@@ -241,6 +279,13 @@ export function buildCodexFileRewindPlan(
return { ...base, mode: 'conversation-only', fallbackReason: 'no-savepoints' };
}
+ // A failed new baseline may leave only legacy history. Missing messages must
+ // not disappear from the file-rewind range merely because no marker was saved.
+ const coveredLegacy = new Set(legacy.selected.map((savepoint) => savepoint.anchor));
+ if ([...anchorsToRevert].some((anchor) => !coveredLegacy.has(anchor))) {
+ return { ...base, mode: 'conversation-only', fallbackReason: 'savepoint-gap' };
+ }
+
const revertSet = new Set(legacy.selected.map((savepoint) => savepoint.commit));
const commits = repo.savepointsNewestFirst
.filter((savepoint) => savepoint.source === 'legacy')
diff --git a/apps/desktop/src/main/git-snapshot/gitRepoWriteQueue.ts b/apps/desktop/src/main/git-snapshot/gitRepoWriteQueue.ts
index 3de235c81f..2f5415f13f 100644
--- a/apps/desktop/src/main/git-snapshot/gitRepoWriteQueue.ts
+++ b/apps/desktop/src/main/git-snapshot/gitRepoWriteQueue.ts
@@ -6,16 +6,28 @@
* flow's half-applied index state.
*/
+import { assertGitDirectoryReady, currentOperationBudget, operationCheckpoint, operationWait } from '../utils/operationBudget';
+
const repoQueues = new Map<string, Promise<unknown>>();
/** Runs a mutating Git task after earlier writes for the same repo finish. */
export function enqueueGitRepoWrite<T>(repoRoot: string, task: () => Promise<T>): Promise<T> {
const prev = repoQueues.get(repoRoot) ?? Promise.resolve();
- const run = prev.catch(() => undefined).then(task);
+ const run = prev.catch(() => undefined).then(async () => {
+ operationCheckpoint();
+ assertGitDirectoryReady(repoRoot);
+ try {
+ return await task();
+ } finally {
+ // Caller timeout may return before a non-cancellable read completes, but
+ // the repository slot must still belong to any terminating Git children.
+ await currentOperationBudget()?.drain();
+ }
+ });
const tail = run.catch(() => undefined);
repoQueues.set(repoRoot, tail);
void tail.finally(() => {
if (repoQueues.get(repoRoot) === tail) repoQueues.delete(repoRoot);
});
- return run;
+ return operationWait(run);
}
diff --git a/apps/desktop/src/main/git-snapshot/gitSnapshotCoordinator.ts b/apps/desktop/src/main/git-snapshot/gitSnapshotCoordinator.ts
index 8f112bc68f..78884bac2b 100644
--- a/apps/desktop/src/main/git-snapshot/gitSnapshotCoordinator.ts
+++ b/apps/desktop/src/main/git-snapshot/gitSnapshotCoordinator.ts
@@ -6,6 +6,7 @@
*/
import type { AgentKind } from '@cindy/maker-core';
+import { OperationBudget, operationCheckpoint, operationWait } from '../utils/operationBudget';
import { createAfterEditLabel } from './gitSnapshotLabeler';
import { enqueueGitRepoWrite } from './gitRepoWriteQueue';
@@ -35,6 +36,10 @@ export interface GitSnapshotSessionContext {
}
export interface GitSnapshotCoordinatorDeps {
+ /** Must persist intent before Git work or dispatch; failure is NOT best effort. */
+ recordTurnAttempt?: (sessionId: string) => Promise<TurnStartMetadata>;
+ /** One budget for queueing, detection, filtering, staging and publication. */
+ snapshotTimeoutMs?: number;
/** Global auto-snapshot switch; turn-start decisions are reused at matching turn end. */
readAutoSnapshotEnabled: () => boolean;
/** Whether an empty local project may be initialized as Git during resolution. */
@@ -85,6 +90,7 @@ interface TurnStartState {
}
interface TurnStartRecord extends Partial<TurnStartState> {
+ operation: OperationBudget;
autoSnapshotEnabled: boolean;
autoInitProjectGit: boolean;
promise: Promise<void>;
@@ -101,16 +107,20 @@ interface TurnStartRecord extends Partial<TurnStartState> {
overlappedWithPeer?: boolean;
}
-interface TurnStartMetadata {
+export interface TurnStartMetadata {
anchor?: string;
userPrompt?: string;
+ attemptId?: string;
}
+const TURN_SNAPSHOT_BUDGET_MS = 8_000;
+
export class GitSnapshotCoordinator {
private readonly sessionCache = new Map<string, ResolvedSnapshotSession>();
private readonly turnStartQueues = new Map<string, TurnStartRecord[]>();
/** In-flight turn records per repo root, for same-repo concurrency checks. */
private readonly activeTurnRecordsByRepo = new Map<string, Set<TurnStartRecord>>();
+ private readonly operations = new Map<string, Set<OperationBudget>>();
constructor(private readonly deps: GitSnapshotCoordinatorDeps) {}
@@ -118,17 +128,35 @@ export class GitSnapshotCoordinator {
* Turn-start hook. Snapshots the current worktree state onto the session's
* shadow savepoint chain as the baseline for this turn's file rewind.
*/
- async onTurnStart(sessionId: string): Promise<void> {
+ async onTurnStart(sessionId: string, signal?: AbortSignal): Promise<void> {
const autoSnapshotEnabled = this.deps.readAutoSnapshotEnabled();
const record: TurnStartRecord = {
+ operation: new OperationBudget(this.deps.snapshotTimeoutMs ?? TURN_SNAPSHOT_BUDGET_MS),
autoSnapshotEnabled,
autoInitProjectGit: this.deps.readAutoInitProjectGit?.() ?? autoSnapshotEnabled,
promise: Promise.resolve(),
ownerSessionId: sessionId,
};
this.pushTurnStartRecord(sessionId, record);
- record.promise = this.captureTurnStart(sessionId, record);
- await record.promise;
+ let intentRecorded = !this.deps.recordTurnAttempt;
+ record.promise = this.runOperation(sessionId, record.operation, async () => {
+ if (this.deps.recordTurnAttempt) {
+ record.metadata = await operationWait(this.deps.recordTurnAttempt(sessionId));
+ intentRecorded = true;
+ }
+ await this.captureTurnStart(sessionId, record);
+ }, signal, () => !intentRecorded);
+ try {
+ await record.promise;
+ } catch (error) {
+ // The send never became safe to dispatch. Remove this exact reservation,
+ // not a peer's earlier baseline from the FIFO.
+ const queue = this.turnStartQueues.get(sessionId);
+ const index = queue?.indexOf(record) ?? -1;
+ if (index >= 0) queue!.splice(index, 1);
+ if (queue?.length === 0) this.turnStartQueues.delete(sessionId);
+ throw error;
+ }
}
hasPendingTurnStart(sessionId: string): boolean {
@@ -150,21 +178,24 @@ export class GitSnapshotCoordinator {
return;
}
+ operationCheckpoint();
record.repoRoot = resolved.repoRoot;
this.registerActiveTurn(resolved.repoRoot, record);
- const metadataPromise = this.resolveTurnStartMetadata(sessionId);
+ const metadataPromise = record.metadata ? Promise.resolve(record.metadata) : this.resolveTurnStartMetadata(sessionId);
+ // A metadata failure must be observed even when queue waiting expires.
+ void metadataPromise.catch(() => {});
await enqueueGitRepoWrite(resolved.repoRoot, async () => {
- const metadata = await metadataPromise;
+ const metadata = await operationWait(metadataPromise);
record.metadata = metadata;
- const turnStart = await this.createTurnStartSavepoint(
+ const turnStart = await operationWait(this.createTurnStartSavepoint(
sessionId,
resolved.repoRoot,
metadata,
- );
+ ));
record.turnStartCommit = turnStart.commit;
record.turnStartSkippedFingerprints = turnStart.skippedFingerprints;
});
- record.metadata ??= await metadataPromise;
+ record.metadata ??= await operationWait(metadataPromise);
} catch (err) {
this.deps.logger.warn('[git-snapshot] onTurnStart failed (swallowed)', {
sessionId,
@@ -179,6 +210,11 @@ export class GitSnapshotCoordinator {
*/
async onTurnEnd(sessionId: string): Promise<void> {
const turnStart = this.shiftTurnStartRecord(sessionId);
+ await this.runOperation(sessionId, new OperationBudget(this.deps.snapshotTimeoutMs ?? TURN_SNAPSHOT_BUDGET_MS),
+ () => this.captureTurnEnd(sessionId, turnStart));
+ }
+
+ private async captureTurnEnd(sessionId: string, turnStart: TurnStartRecord | undefined): Promise<void> {
try {
const autoSnapshotEnabled = turnStart?.autoSnapshotEnabled ?? this.deps.readAutoSnapshotEnabled();
const autoInitProjectGit = turnStart
@@ -186,7 +222,7 @@ export class GitSnapshotCoordinator {
: this.deps.readAutoInitProjectGit?.() ?? autoSnapshotEnabled;
if (!autoSnapshotEnabled) return;
if (turnStart && !turnStart.repoRoot) {
- await turnStart.promise;
+ await operationWait(turnStart.promise);
}
const resolved = await this.resolveSession(
@@ -197,7 +233,7 @@ export class GitSnapshotCoordinator {
if (!resolved) return;
await enqueueGitRepoWrite(resolved.repoRoot, async () => {
- await turnStart?.promise;
+ if (turnStart) await operationWait(turnStart.promise);
await this.snapshotAfterEdit(sessionId, resolved, turnStart);
});
} catch (err) {
@@ -210,11 +246,13 @@ export class GitSnapshotCoordinator {
/** Consumes one turn-start baseline when a turn ends without a successful done event. */
onTurnAbort(sessionId: string): void {
- this.shiftTurnStartRecord(sessionId);
+ this.shiftTurnStartRecord(sessionId)?.operation.cancel();
+ for (const operation of this.operations.get(sessionId) ?? []) operation.cancel();
}
/** Clears per-session repo detection when the session is closed. */
onSessionClosed(sessionId: string): void {
+ for (const operation of this.operations.get(sessionId) ?? []) operation.cancel();
this.sessionCache.delete(sessionId);
// 未被 turn-end/abort 消费的 record(运行中关会话)必须逐条注销同仓并发
// 记账,否则悬空 record 会让同仓其它会话的后续每一轮都被误判为并发。
@@ -237,18 +275,19 @@ export class GitSnapshotCoordinator {
const cached = this.sessionCache.get(sessionId);
if (cached) return cached;
- const ctx = await this.deps.getSessionContext(sessionId);
+ operationCheckpoint();
+ const ctx = await operationWait(this.deps.getSessionContext(sessionId));
if (!ctx?.workingDir) return null;
- let repoRoot = await this.deps.detectRepoRoot(ctx.workingDir);
+ let repoRoot = await operationWait(this.deps.detectRepoRoot(ctx.workingDir));
if (!repoRoot && autoInitProjectGit && this.deps.initializeProjectGit) {
- const bootstrap = await this.deps.initializeProjectGit?.(sessionId, ctx, {
+ const bootstrap = await operationWait(this.deps.initializeProjectGit(sessionId, ctx, {
autoSnapshotEnabled,
autoInitProjectGit,
- });
+ }));
repoRoot = bootstrap?.repoRoot ?? null;
if (!repoRoot) {
- repoRoot = await this.deps.detectRepoRoot(ctx.workingDir);
+ repoRoot = await operationWait(this.deps.detectRepoRoot(ctx.workingDir));
}
}
if (!repoRoot) return null;
@@ -258,6 +297,7 @@ export class GitSnapshotCoordinator {
agentKind: ctx.agentKind,
savepointRewind: ctx.agentKind === 'codex' || ctx.agentKind === 'pi' || ctx.savepointRewind === true,
};
+ operationCheckpoint();
this.sessionCache.set(sessionId, resolved);
return resolved;
}
@@ -316,7 +356,7 @@ export class GitSnapshotCoordinator {
// status-based check would create an empty after-edit every turn.
let result: ShadowSavepointResult;
try {
- result = await this.deps.createShadowSavepoint(repoRoot, {
+ result = await operationWait(this.deps.createShadowSavepoint(repoRoot, {
sessionId,
label: (diff) =>
createAfterEditLabel(
@@ -327,9 +367,12 @@ export class GitSnapshotCoordinator {
kind: 'after-edit',
baselineCommit: baseline,
...(metadata.anchor ? { anchor: metadata.anchor } : {}),
+ ...(metadata.attemptId ? { attemptId: metadata.attemptId } : {}),
},
skipIfTreeEquals: baseline,
- });
+ recordUnchanged: true,
+ baselineSkippedFingerprints: turnStart?.turnStartSkippedFingerprints ?? [],
+ }));
} catch (err) {
this.deps.logger.warn('[git-snapshot] after-edit savepoint failed', {
sessionId,
@@ -418,14 +461,16 @@ export class GitSnapshotCoordinator {
): Promise<{ commit: string | undefined; skippedFingerprints: SkippedFileFingerprint[] }> {
// Always created, dirty or clean, so every turn has a uniform restore
// baseline; an unchanged tree costs almost nothing thanks to object reuse.
- const result = await this.deps.createShadowSavepoint(repoRoot, {
+ operationCheckpoint();
+ const result = await operationWait(this.deps.createShadowSavepoint(repoRoot, {
sessionId,
label: '本轮开始时的工作区基线',
meta: {
kind: 'turn-start',
...(metadata.anchor ? { anchor: metadata.anchor } : {}),
+ ...(metadata.attemptId ? { attemptId: metadata.attemptId } : {}),
},
- });
+ }));
if (result.commit) {
this.deps.logger.info('[git-snapshot] turn-start baseline created', {
@@ -462,7 +507,8 @@ export class GitSnapshotCoordinator {
): Promise<T | undefined> {
if (!fn) return undefined;
try {
- return await fn(sessionId);
+ operationCheckpoint();
+ return await operationWait(fn(sessionId));
} catch (err) {
this.deps.logger.debug('[git-snapshot] optional metadata unavailable, continuing', {
sessionId,
@@ -480,14 +526,15 @@ export class GitSnapshotCoordinator {
logMessage: string,
metadata: TurnStartMetadata,
): Promise<void> {
- const commit = await this.deps.createShadowMarker(repoRoot, {
+ operationCheckpoint();
+ const commit = await operationWait(this.deps.createShadowMarker(repoRoot, {
sessionId,
label,
meta: {
kind: 'rewind-blocked',
...(metadata.anchor ? { anchor: metadata.anchor } : {}),
},
- });
+ }));
if (!commit) {
// Marker tree could not be built (git fully unavailable); the failure
// is logged by the kernel and the outer swallow keeps the turn alive.
@@ -510,6 +557,28 @@ export class GitSnapshotCoordinator {
}
}
+ private async runOperation(sessionId: string, operation: OperationBudget, task: () => Promise<void>, signal?: AbortSignal, mustReject?: () => boolean): Promise<void> {
+ const active = this.operations.get(sessionId) ?? new Set<OperationBudget>();
+ active.add(operation);
+ this.operations.set(sessionId, active);
+ try {
+ await operation.run(task, signal);
+ } catch (error) {
+ if (mustReject?.()) {
+ this.deps.logger.warn('[git-snapshot] dispatch intent unavailable; send not authorized', {
+ sessionId, error: error instanceof Error ? error.message : String(error),
+ });
+ throw error;
+ }
+ this.deps.logger.warn('[git-snapshot] snapshot unavailable; continuing without file rewind coverage', {
+ sessionId, error: error instanceof Error ? error.message : String(error),
+ });
+ } finally {
+ active.delete(operation);
+ if (active.size === 0 && this.operations.get(sessionId) === active) this.operations.delete(sessionId);
+ }
+ }
+
private shiftTurnStartRecord(sessionId: string): TurnStartRecord | undefined {
const queue = this.turnStartQueues.get(sessionId);
const record = queue?.shift();
diff --git a/apps/desktop/src/main/git-snapshot/gitSnapshotService.ts b/apps/desktop/src/main/git-snapshot/gitSnapshotService.ts
index 0e2fc38def..0ad7728a57 100644
--- a/apps/desktop/src/main/git-snapshot/gitSnapshotService.ts
+++ b/apps/desktop/src/main/git-snapshot/gitSnapshotService.ts
@@ -6,7 +6,9 @@
* coordinator scheduling, rollback, or agent lifecycles.
*/
-import { promises as fs } from 'node:fs';
+import { promises as nativeFs } from 'node:fs';
+import { operationFileSystem } from '../utils/operationFileSystem';
+import { operationCheckpoint, operationWait, operationYield } from '../utils/operationBudget';
import os from 'node:os';
import path from 'node:path';
@@ -36,6 +38,7 @@ import {
} from './savepointRefs';
const log = createLogger('git-snapshot');
+const fs = operationFileSystem(nativeFs);
const PATHSPEC_CHUNK_SIZE = 80;
const STAGED_DIFF_TEXT_MAX_BYTES = 16_000;
@@ -117,6 +120,8 @@ export interface CreateSnapshotDetailedResult {
/** One savepoint parsed from Git history (HEAD log for legacy, hidden ref chain for shadow). */
export interface SnapshotEntry {
+ /** Dispatch intent identity, distinct from a user-message anchor. */
+ attemptId?: string;
commit: string;
label: string;
kind: SnapshotKind;
@@ -393,6 +398,10 @@ const SHADOW_IDENTITY_ENV: Record<string, string> = {
/** Input for shadow savepoints written to the session's hidden ref chain. */
export interface CreateShadowSavepointInput {
+ /** Automatic turns need a completion record even when the tree is unchanged. */
+ recordUnchanged?: boolean;
+ /** Reject incomplete after-edit trees before publishing a completion record. */
+ baselineSkippedFingerprints?: readonly SkippedFileFingerprint[];
sessionId: string;
/** Commit label or a factory used after staging when diff context is needed. */
label: string | SnapshotLabelFactory;
@@ -478,11 +487,16 @@ export async function createShadowSavepoint(
// be treated as deleted — never handed to `git add`, which would either
// refuse it or, worse, snapshot out-of-repo content.
const skippedFingerprints = await collectSkippedFingerprints(repoPath, skippedFiles);
+ if (input.baselineSkippedFingerprints && skippedFingerprintsChanged(input.baselineSkippedFingerprints, skippedFingerprints)) {
+ throw new Error('File rewind gap: turn changes were partially filtered');
+ }
const repoReal = await fs.realpath(repoPath);
const presentFiles: SnapshotIncludedFile[] = [];
const missingPaths: string[] = [];
+ let scanIndex = 0;
for (const file of plan.includedFiles) {
+ await operationYield(scanIndex++);
const abs = resolveSnapshotGitPath(repoPath, file.path);
if (!abs) continue;
if (!(await pathExists(abs))) {
@@ -517,9 +531,11 @@ export async function createShadowSavepoint(
const tree = (await gitExec(['write-tree'], repoPath, { extraEnv })).stdout.trim();
+ let unchanged = false;
if (input.skipIfTreeEquals) {
const baselineTree = await resolveTreeOf(repoPath, input.skipIfTreeEquals);
- if (baselineTree && baselineTree === tree) {
+ unchanged = !!baselineTree && baselineTree === tree;
+ if (unchanged && !input.recordUnchanged) {
log.debug('[createShadowSavepoint] tree unchanged, skip', {
sessionId: input.sessionId,
baseline: input.skipIfTreeEquals.slice(0, 8),
@@ -534,14 +550,15 @@ export async function createShadowSavepoint(
}
}
- const label =
+ operationCheckpoint();
+ const label = unchanged ? '保存改动' :
typeof input.label === 'function'
- ? await input.label(
+ ? await operationWait(input.label(
// Diff against the turn baseline, not HEAD: the worktree stays
// dirty across turns now, so a HEAD-based diff would describe the
// cumulative session delta instead of this turn's changes.
await collectStagedDiff(repoPath, commitPathspecs, extraEnv, input.skipIfTreeEquals),
- )
+ ))
: input.label;
const [branch, baseHead, parent] = await Promise.all([
getCurrentBranch(repoPath).catch(() => undefined),
@@ -577,7 +594,9 @@ async function collectSkippedFingerprints(
skippedFiles: readonly SnapshotSkippedFile[],
): Promise<SkippedFileFingerprint[]> {
const out: SkippedFileFingerprint[] = [];
+ let scanIndex = 0;
for (const file of skippedFiles) {
+ await operationYield(scanIndex++);
const abs = resolveSnapshotGitPath(repoPath, file.path);
if (!abs) continue;
const stats = await fs.lstat(abs).catch(() => null);
@@ -593,6 +612,16 @@ async function collectSkippedFingerprints(
return out;
}
+function skippedFingerprintsChanged(before: readonly SkippedFileFingerprint[], after: readonly SkippedFileFingerprint[]): boolean {
+ if (before.length !== after.length) return true;
+ const baseline = new Map(before.map((fp) => [fp.path, fp]));
+ return after.some((fp) => {
+ const previous = baseline.get(fp.path);
+ return !previous || previous.sizeBytes !== fp.sizeBytes || previous.mtimeMs !== fp.mtimeMs ||
+ previous.ctimeMs !== fp.ctimeMs || previous.ino !== fp.ino;
+ });
+}
+
/** Input for metadata-only shadow markers (gap / rollback records on the chain). */
export interface CreateShadowMarkerInput {
sessionId: string;
@@ -707,6 +736,7 @@ export async function listShadowSavepoints(
...(parsed.anchor ? { anchor: parsed.anchor } : {}),
...(parsed.branch ? { branch: parsed.branch } : {}),
...(parsed.baselineCommit ? { baselineCommit: parsed.baselineCommit } : {}),
+ ...(parsed.attemptId ? { attemptId: parsed.attemptId } : {}),
...(parsed.baseHead ? { baseHead: parsed.baseHead } : {}),
});
}
@@ -1068,8 +1098,9 @@ export async function withPathspecFile<T>(
): Promise<T> {
const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'xdt-snapshot-pathspec-'));
const file = path.join(dir, 'paths');
- await fs.writeFile(file, `${uniquePathspecs(pathspecs).join('\0')}\0`, 'utf8');
try {
+ await fs.writeFile(file, `${uniquePathspecs(pathspecs).join('\0')}\0`, 'utf8');
+ operationCheckpoint();
return await fn(file);
} finally {
await fs.rm(dir, { recursive: true, force: true });
diff --git a/apps/desktop/src/main/git-snapshot/isolatedGitExec.ts b/apps/desktop/src/main/git-snapshot/isolatedGitExec.ts
index 42b60a41b4..cf032c8cd4 100644
--- a/apps/desktop/src/main/git-snapshot/isolatedGitExec.ts
+++ b/apps/desktop/src/main/git-snapshot/isolatedGitExec.ts
@@ -11,6 +11,7 @@
import { promises as fs } from 'node:fs';
import os from 'node:os';
import path from 'node:path';
+import { operationCheckpoint, operationWait } from '../utils/operationBudget';
import {
gitExec,
@@ -120,7 +121,8 @@ export async function isolatedGitExec(
cwd?: string,
opts?: GitExecOpts,
): Promise<GitExecResult> {
- const hooksPath = await getEmptyHooksDir();
+ operationCheckpoint();
+ const hooksPath = await operationWait(getEmptyHooksDir());
const isolation = snapshotGitIsolationArgs(hooksPath);
const command = withDisabledExternalDiffHelpers(args);
if (command[0] === 'config') {
diff --git a/apps/desktop/src/main/git-snapshot/projectGitBootstrap.ts b/apps/desktop/src/main/git-snapshot/projectGitBootstrap.ts
index fc92ecf8e0..1dd99a232f 100644
--- a/apps/desktop/src/main/git-snapshot/projectGitBootstrap.ts
+++ b/apps/desktop/src/main/git-snapshot/projectGitBootstrap.ts
@@ -7,7 +7,9 @@
* until a future explicit-confirmation flow exists.
*/
-import { promises as fs } from 'node:fs';
+import { promises as nativeFs } from 'node:fs';
+import { operationFileSystem } from '../utils/operationFileSystem';
+import { operationCheckpoint, operationWait } from '../utils/operationBudget';
import path from 'node:path';
import { detectCwd } from '../worktree/WorktreeManager';
@@ -16,6 +18,7 @@ import { createLogger } from '../logger';
import { createSnapshotDetailed, type CreateSnapshotDetailedResult } from './gitSnapshotService';
const log = createLogger('project-git-bootstrap');
+const fs = operationFileSystem(nativeFs);
const INITIAL_PROJECT_LABEL = 'Initialize project snapshot';
const FALLBACK_SESSION_ID = 'project-bootstrap';
@@ -155,12 +158,15 @@ async function withProjectBootstrapQueue<T>(
() => current,
);
bootstrapQueues.set(key, queued);
+ void queued.finally(() => {
+ if (bootstrapQueues.get(key) === queued) bootstrapQueues.delete(key);
+ });
- await previous.catch(() => undefined);
try {
+ await operationWait(previous.catch(() => undefined));
+ operationCheckpoint();
return await task();
} finally {
releaseCurrent();
- if (bootstrapQueues.get(key) === queued) bootstrapQueues.delete(key);
}
}
diff --git a/apps/desktop/src/main/git-snapshot/snapshotAttemptStore.ts b/apps/desktop/src/main/git-snapshot/snapshotAttemptStore.ts
new file mode 100644
index 0000000000..b5f571339b
--- /dev/null
+++ b/apps/desktop/src/main/git-snapshot/snapshotAttemptStore.ts
@@ -0,0 +1,106 @@
+import { createHash, randomUUID } from 'node:crypto';
+import fs from 'node:fs/promises';
+import type { Dir } from 'node:fs';
+import path from 'node:path';
+import {
+ OperationBudget,
+ currentOperationBudget,
+ operationCheckpoint,
+ operationWait,
+} from '../utils/operationBudget';
+
+/** Durable dispatch intent, independent of Git availability. No prompt or file contents. */
+export interface SnapshotAttempt {
+ id: string;
+ anchor?: string;
+}
+
+const MAX_ATTEMPTS = 10_000;
+const MAX_RECORD_BYTES = 4_096;
+
+/**
+ * Immutable records avoid read/modify/write races between retries and processes.
+ * A failed/partial write is deliberately retained: unreadable evidence blocks rewind.
+ * The caller must await record() before authorizing vendor dispatch. Timed-out writes
+ * may finish late, but can only leave an extra pending intent, never authorize a send.
+ */
+export class SnapshotAttemptStore {
+ constructor(private readonly ownerRoot: string) {}
+
+ private directory(sessionId: string): string {
+ return path.join(
+ this.ownerRoot,
+ 'git-snapshot-attempts',
+ createHash('sha256').update(sessionId).digest('hex'),
+ );
+ }
+
+ async record(sessionId: string, anchor?: string): Promise<SnapshotAttempt> {
+ if (anchor !== undefined && (!anchor || anchor.length > 1024))
+ throw new Error('Invalid snapshot anchor');
+ const attempt = { id: randomUUID(), ...(anchor ? { anchor } : {}) };
+ const content = JSON.stringify({ version: 1, ...attempt });
+ if (Buffer.byteLength(content) > MAX_RECORD_BYTES)
+ throw new Error('Snapshot attempt record too large');
+ const dir = this.directory(sessionId);
+ operationCheckpoint();
+ await operationWait(fs.mkdir(dir, { recursive: true }));
+ operationCheckpoint();
+ await operationWait(
+ fs.writeFile(path.join(dir, `${attempt.id}.json`), content, {
+ flag: 'wx',
+ mode: 0o600,
+ flush: true,
+ signal: currentOperationBudget()?.signal,
+ }),
+ );
+ return attempt;
+ }
+
+ /** null means unknown/corrupt/truncated, never an empty successful history. */
+ async read(sessionId: string): Promise<SnapshotAttempt[] | null> {
+ return new OperationBudget(8_000).run(() => this.readRecords(sessionId)).catch(() => null);
+ }
+
+ private async readRecords(sessionId: string): Promise<SnapshotAttempt[] | null> {
+ const attempts: SnapshotAttempt[] = [];
+ let dir: Dir;
+ try {
+ dir = await fs.opendir(this.directory(sessionId));
+ } catch (error) {
+ return (error as NodeJS.ErrnoException).code === 'ENOENT' ? [] : null;
+ }
+ try {
+ for await (const entry of dir) {
+ operationCheckpoint();
+ if (
+ !entry.isFile() ||
+ !/^[a-f0-9-]{36}\.json$/.test(entry.name) ||
+ attempts.length >= MAX_ATTEMPTS
+ )
+ return null;
+ const file = await fs.open(path.join(this.directory(sessionId), entry.name), 'r');
+ try {
+ operationCheckpoint();
+ const buffer = Buffer.alloc(MAX_RECORD_BYTES + 1);
+ const { bytesRead } = await file.read(buffer, 0, buffer.length, 0);
+ if (bytesRead > MAX_RECORD_BYTES) return null;
+ const record = JSON.parse(buffer.subarray(0, bytesRead).toString('utf8'));
+ if (
+ record.version !== 1 ||
+ `${record.id}.json` !== entry.name ||
+ (record.anchor !== undefined &&
+ (typeof record.anchor !== 'string' || !record.anchor || record.anchor.length > 1024))
+ )
+ return null;
+ attempts.push({ id: record.id, ...(record.anchor ? { anchor: record.anchor } : {}) });
+ } finally {
+ await file.close();
+ }
+ }
+ return attempts;
+ } catch {
+ return null;
+ }
+ }
+}
diff --git a/apps/desktop/src/main/git-snapshot/snapshotFileFilter.ts b/apps/desktop/src/main/git-snapshot/snapshotFileFilter.ts
index 669f7024db..9834e098dd 100644
--- a/apps/desktop/src/main/git-snapshot/snapshotFileFilter.ts
+++ b/apps/desktop/src/main/git-snapshot/snapshotFileFilter.ts
@@ -1,4 +1,6 @@
-import { promises as fs } from 'node:fs';
+import { promises as nativeFs } from 'node:fs';
+import { operationFileSystem } from '../utils/operationFileSystem';
+import { operationCheckpoint, operationYield } from '../utils/operationBudget';
import path from 'node:path';
import { detectSensitivePath } from '../security/sensitivePath';
@@ -6,6 +8,7 @@ import { GitExecError } from '../worktree/gitExec';
import { isolatedGitExec } from './isolatedGitExec';
const DEFAULT_MAX_FILE_BYTES = 10 * 1024 * 1024;
+const fs = operationFileSystem(nativeFs);
const DEFAULT_MAX_CONTENT_SCAN_BYTES = DEFAULT_MAX_FILE_BYTES;
/** Reason a dirty file is excluded from an automatic snapshot commit. */
@@ -133,6 +136,7 @@ export function parseStatusPorcelainZ(output: string): SnapshotStatusEntry[] {
const parts = output.split('\0').filter((part) => part.length > 0);
const entries: SnapshotStatusEntry[] = [];
for (let i = 0; i < parts.length; i += 1) {
+ if (i % 256 === 0) operationCheckpoint();
const part = parts[i];
if (part.length < 4) continue;
@@ -174,14 +178,18 @@ function isGitStatusOutputTooLargeError(err: unknown): boolean {
return err.cause?.code === 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER' || /maxBuffer/i.test(err.message);
}
-async function hasGitMarker(dir: string): Promise<boolean> {
- return fs.lstat(path.join(dir, '.git')).then(
+async function hasGitMarker(dir: string, markers: Map<string, boolean>): Promise<boolean> {
+ const cached = markers.get(dir);
+ if (cached !== undefined) return cached;
+ const exists = await fs.lstat(path.join(dir, '.git')).then(
() => true,
() => false,
);
+ markers.set(dir, exists);
+ return exists;
}
-async function isInsideNestedGitRepo(repoPath: string, gitPath: string): Promise<boolean> {
+async function isInsideNestedGitRepo(repoPath: string, gitPath: string, markers: Map<string, boolean>): Promise<boolean> {
const abs = resolveSnapshotGitPath(repoPath, gitPath);
if (!abs) return false;
@@ -197,7 +205,7 @@ async function isInsideNestedGitRepo(repoPath: string, gitPath: string): Promise
while (path.resolve(cur) !== repoRoot) {
const rel = path.relative(repoRoot, cur);
if (rel.startsWith('..') || path.isAbsolute(rel)) return false;
- if (await hasGitMarker(cur)) return true;
+ if (await hasGitMarker(cur, markers)) return true;
const parent = path.dirname(cur);
if (parent === cur) return false;
@@ -236,6 +244,7 @@ async function classifyEntry(
repoPath: string,
entry: SnapshotStatusEntry,
opts: SnapshotFileFilterOptions,
+ markers: Map<string, boolean>,
): Promise<SnapshotSkippedFile | null> {
if (hasConflictStatus(entry.code)) return { path: entry.path, reason: 'conflict' };
@@ -257,7 +266,7 @@ async function classifyEntry(
}
for (const gitPath of rawPathsFor(entry)) {
- if (await isInsideNestedGitRepo(repoPath, gitPath)) {
+ if (await isInsideNestedGitRepo(repoPath, gitPath, markers)) {
return { path: entry.path, reason: 'nested-git-repo' };
}
}
@@ -274,11 +283,16 @@ export async function buildSnapshotFilePlanFromEntries(
const options = withDefaults(opts);
const includedFiles: SnapshotIncludedFile[] = [];
const skippedFiles: SnapshotSkippedFile[] = [];
+ // Siblings share ancestor probes, but later scans must see new/removed .git markers.
+ // File stats and content safety checks remain live and are never cached here.
+ const markers = new Map<string, boolean>();
+ let scanIndex = 0;
for (const entry of entries) {
+ await operationYield(scanIndex++);
const pathsForPathspec = pathspecPathsFor(entry);
const oldPath = entry.oldPath && entry.code[0] === 'R' ? { oldPath: entry.oldPath } : {};
- const skip = await classifyEntry(repoPath, entry, options);
+ const skip = await classifyEntry(repoPath, entry, options, markers);
if (skip) {
skippedFiles.push({ ...skip, ...oldPath, pathsForPathspec });
continue;
diff --git a/apps/desktop/src/main/git-snapshot/snapshotTrailers.ts b/apps/desktop/src/main/git-snapshot/snapshotTrailers.ts
index 3de89c5862..59ca36d3df 100644
--- a/apps/desktop/src/main/git-snapshot/snapshotTrailers.ts
+++ b/apps/desktop/src/main/git-snapshot/snapshotTrailers.ts
@@ -38,6 +38,8 @@ export interface SnapshotMeta {
kind: SnapshotKind;
/** 绑定的对话消息锚点(message clientId), 可空。 */
anchor?: string;
+ /** Durable dispatch attempt; retries of the same message have distinct ids. */
+ attemptId?: string;
/** 一次 rollback / undo 的稳定 id。 */
rollbackId?: string;
/** rollback 入口: commit hash 或 message clientId。 */
@@ -70,6 +72,7 @@ export interface ParsedSnapshot extends SnapshotMeta {
const KEY_SESSION = 'Session';
const KEY_KIND = 'Kind';
const KEY_ANCHOR = 'Anchor';
+const KEY_ATTEMPT = 'Attempt';
const KEY_ROLLBACK_ID = 'RollbackId';
const KEY_ROLLBACK_TARGET = 'RollbackTarget';
const KEY_REVERTS = 'Reverts';
@@ -115,6 +118,7 @@ function buildTrailerBlock(prefix: string, meta: SnapshotMeta): string {
if (meta.anchor) {
trailers.push(`${prefix}-${KEY_ANCHOR}: ${meta.anchor}`);
}
+ if (meta.attemptId) trailers.push(`${prefix}-${KEY_ATTEMPT}: ${meta.attemptId}`);
if (meta.rollbackId) {
trailers.push(`${prefix}-${KEY_ROLLBACK_ID}: ${meta.rollbackId}`);
}
@@ -160,6 +164,7 @@ interface CollectedTrailerFields {
sessionId?: string;
kind?: string;
anchor?: string;
+ attemptId?: string;
rollbackId?: string;
rollbackTarget?: string;
reverts?: string[];
@@ -174,6 +179,7 @@ function assignTrailerField(fields: CollectedTrailerFields, key: string, value:
if (key === KEY_SESSION) fields.sessionId = value;
else if (key === KEY_KIND) fields.kind = value;
else if (key === KEY_ANCHOR) fields.anchor = value;
+ else if (key === KEY_ATTEMPT) fields.attemptId = value;
else if (key === KEY_ROLLBACK_ID) fields.rollbackId = value;
else if (key === KEY_ROLLBACK_TARGET) fields.rollbackTarget = value;
else if (key === KEY_REVERTS) {
@@ -198,6 +204,7 @@ function toParsedSnapshot(
sessionId,
kind: kind as SnapshotKind,
...(fields.anchor ? { anchor: fields.anchor } : {}),
+ ...(fields.attemptId ? { attemptId: fields.attemptId } : {}),
...(fields.rollbackId ? { rollbackId: fields.rollbackId } : {}),
...(fields.rollbackTarget ? { rollbackTarget: fields.rollbackTarget } : {}),
...(fields.reverts?.length ? { reverts: fields.reverts } : {}),
diff --git a/apps/desktop/src/main/goal-host/controller.ts b/apps/desktop/src/main/goal-host/controller.ts
index fa14408018..e5bd929fb6 100644
--- a/apps/desktop/src/main/goal-host/controller.ts
+++ b/apps/desktop/src/main/goal-host/controller.ts
@@ -2520,7 +2520,7 @@ export class GoalController {
// 由 turnsUsed 派生,'first' 可能被 busy 重试 / 暂停后重发,放这里会重复落库。
// 这里只负责把完整 directive(含裁决约定)发给模型。
if (this.deps.beforeDispatchUserTurn) {
- await this.deps.beforeDispatchUserTurn(sessionId);
+ await this.deps.beforeDispatchUserTurn(sessionId, dispatchAbortController.signal);
baselineStarted = true;
}
// session-agent-switch:本路径直发 session.send(不经 makerSendTransaction),
diff --git a/apps/desktop/src/main/goal-host/index.ts b/apps/desktop/src/main/goal-host/index.ts
index 21137144f1..912ab6a0c3 100644
--- a/apps/desktop/src/main/goal-host/index.ts
+++ b/apps/desktop/src/main/goal-host/index.ts
@@ -42,7 +42,7 @@ export interface StartGoalControllerDeps {
getDb: () => GoalDrizzleDb;
/** 状态变化广播到 renderer(→ GOAL_STATUS_CHANGED)。 */
broadcastStatus: (update: GoalStatusUpdate) => void;
- beforeDispatchUserTurn?: (sessionId: string) => void | Promise<void>;
+ beforeDispatchUserTurn?: (sessionId: string, signal?: AbortSignal) => void | Promise<void>;
onUndispatchedUserTurn?: (sessionId: string) => void;
}
diff --git a/apps/desktop/src/main/goal-host/types.ts b/apps/desktop/src/main/goal-host/types.ts
index 706a9c4d50..583bf6568a 100644
--- a/apps/desktop/src/main/goal-host/types.ts
+++ b/apps/desktop/src/main/goal-host/types.ts
@@ -195,7 +195,7 @@ export interface GoalControllerDeps {
* 的 Stop 边界,以便 vendor abort、输入队列和迟到终态事件一起收口。
*/
stopActiveGoalTurn(sessionId: string): void;
- beforeDispatchUserTurn?: (sessionId: string) => void | Promise<void>;
+ beforeDispatchUserTurn?: (sessionId: string, signal?: AbortSignal) => void | Promise<void>;
onUndispatchedUserTurn?: (sessionId: string) => void;
/** 状态变化广播到 renderer(→ GOAL_STATUS_CHANGED);goal=null 表示已清除。 */
emitStatus(update: GoalStatusUpdate): void;
diff --git a/apps/desktop/src/main/learn-host/__tests__/controller.test.ts b/apps/desktop/src/main/learn-host/__tests__/controller.test.ts
index 6357bc1a39..7275fb751b 100644
--- a/apps/desktop/src/main/learn-host/__tests__/controller.test.ts
+++ b/apps/desktop/src/main/learn-host/__tests__/controller.test.ts
@@ -292,7 +292,7 @@ describe('LearnController 状态机', () => {
const run = await h.waitForStatus(runId, 'failed');
expect(run.error).toContain('cancelled-before-dispatch');
- expect(beforeDispatchUserTurn).toHaveBeenCalledWith('fake-session-1');
+ expect(beforeDispatchUserTurn).toHaveBeenCalledWith('fake-session-1', undefined);
expect(onUndispatchedUserTurn).toHaveBeenCalledWith('fake-session-1');
expect(h.session.sent).toHaveLength(1);
expect(order).toEqual(['persist', 'baseline', 'abort']);
@@ -312,7 +312,7 @@ describe('LearnController 状态机', () => {
const run = await h.waitForStatus(runId, 'failed');
expect(run.error).toContain('model failed');
- expect(beforeDispatchUserTurn).toHaveBeenCalledWith('fake-session-1');
+ expect(beforeDispatchUserTurn).toHaveBeenCalledWith('fake-session-1', undefined);
expect(onUndispatchedUserTurn).not.toHaveBeenCalled();
});
diff --git a/apps/desktop/src/main/learn-host/controller.ts b/apps/desktop/src/main/learn-host/controller.ts
index ca38084a07..a4cd39273b 100644
--- a/apps/desktop/src/main/learn-host/controller.ts
+++ b/apps/desktop/src/main/learn-host/controller.ts
@@ -91,7 +91,7 @@ export interface LearnSessionLike {
id: string;
send(
message: { type: 'user'; content: string },
- opts?: { onAccepted?: () => Promise<void> | void },
+ opts?: { onAccepted?: (signal?: AbortSignal) => Promise<void> | void },
): Promise<LearnSessionSendResult>;
onEvent(listener: (ev: { type: string; data?: unknown; turnContinuationId?: number }) => void): () => void;
abort(): Promise<void>;
@@ -145,7 +145,7 @@ export interface LearnControllerDeps {
persistUserMessage(sessionId: string, content: string): Promise<void>;
/** 修正 sessions 行(source='learn' + acceptEdits + 继承的 providerId),失败仅 warn。 */
backfillSessionMeta(sessionId: string): Promise<void>;
- beforeDispatchUserTurn?: (sessionId: string) => void | Promise<void>;
+ beforeDispatchUserTurn?: (sessionId: string, signal?: AbortSignal) => void | Promise<void>;
onUndispatchedUserTurn?: (sessionId: string) => void;
peekPendingHandoff?: (sessionId: string) => Promise<string | null>;
consumePendingHandoff?: (sessionId: string) => void;
@@ -593,12 +593,12 @@ export class LearnController {
const sendResult = await session.send(
outgoingMessage,
{
- onAccepted: async () => {
+ onAccepted: async (signal) => {
await this.deps.persistUserMessage(session.id, cleanMessage).catch((err) => {
this.deps.logger.warn('[learn] persist user message failed (non-fatal)', err);
});
if (this.deps.beforeDispatchUserTurn) {
- await this.deps.beforeDispatchUserTurn(session.id);
+ await this.deps.beforeDispatchUserTurn(session.id, signal);
baselineStarted = true;
}
},
diff --git a/apps/desktop/src/main/learn-host/index.ts b/apps/desktop/src/main/learn-host/index.ts
index c9a6d04bcc..38a2a0aeec 100644
--- a/apps/desktop/src/main/learn-host/index.ts
+++ b/apps/desktop/src/main/learn-host/index.ts
@@ -66,7 +66,7 @@ export interface StartLearnHostDeps {
maker: Maker;
/** learn:event 广播到 renderer(bootstrap 注入 broadcastToAllWindows 包装)。 */
broadcast: (payload: LearnEventPayload) => void;
- beforeDispatchUserTurn?: (sessionId: string) => void | Promise<void>;
+ beforeDispatchUserTurn?: (sessionId: string, signal?: AbortSignal) => void | Promise<void>;
onUndispatchedUserTurn?: (sessionId: string) => void;
/** hub 源:拉市场 skill 详情 + 可用已发布文件(bootstrap 注入,/learn hub:<slug>
* 与 skill hub「学习此技能」共用)。未注入时 hub 源请求报 INVALID_PARAMS(兜底)。 */
diff --git a/apps/desktop/src/main/maker-host/git-snapshot-host.ts b/apps/desktop/src/main/maker-host/git-snapshot-host.ts
index 8d9d4c8570..534900442e 100644
--- a/apps/desktop/src/main/maker-host/git-snapshot-host.ts
+++ b/apps/desktop/src/main/maker-host/git-snapshot-host.ts
@@ -9,6 +9,9 @@
import type { AgentKind, Maker } from '@cindy/maker-core';
import { app } from 'electron';
import path from 'node:path';
+import { currentOperationBudget, operationCheckpoint, operationWait } from '../utils/operationBudget';
+import { getActiveAppSession, ownerScopedUserDataPath } from '../appSessionState';
+import { SnapshotAttemptStore } from '../git-snapshot/snapshotAttemptStore';
import {
isCindyMakeManagedWorktreePath,
makeSourceCheckoutPath,
@@ -37,6 +40,7 @@ interface LatestUserMessage {
/** Optional dependency overrides used by focused main-process unit tests. */
export interface GitSnapshotCoordinatorHostDeps {
+ recordTurnAttempt?: ConstructorParameters<typeof GitSnapshotCoordinator>[0]['recordTurnAttempt'];
readAutoSnapshotEnabled?: () => boolean;
readAutoInitProjectGit?: () => boolean;
detectRepoRoot?: (workingDir: string) => Promise<string | null>;
@@ -102,6 +106,24 @@ export function createGitSnapshotCoordinator(
};
return new GitSnapshotCoordinator({
+ recordTurnAttempt: deps.recordTurnAttempt ?? (async (sessionId) => {
+ // Capture the owner before any await; late work must not write to the next
+ // account's journal. The send boundary also rechecks the session lifetime.
+ const owner = getActiveAppSession();
+ if (!owner.dataOwnerId) throw new Error('Snapshot dispatch intent requires an active data owner');
+ const store = new SnapshotAttemptStore(ownerScopedUserDataPath());
+ const message = await operationWait(getLatestUserMessage(sessionId));
+ operationCheckpoint();
+ const isCurrentOwner = () => {
+ const current = getActiveAppSession();
+ return current.dataOwnerId === owner.dataOwnerId && current.generation === owner.generation;
+ };
+ if (!isCurrentOwner()) throw new Error('Snapshot dispatch owner changed');
+ const attempt = await store.record(sessionId, message?.clientId);
+ operationCheckpoint();
+ if (!isCurrentOwner()) throw new Error('Snapshot dispatch owner changed');
+ return { attemptId: attempt.id, anchor: attempt.anchor, userPrompt: message?.text };
+ }),
readAutoSnapshotEnabled:
deps.readAutoSnapshotEnabled ?? (() => readGitSafetySettings().autoSnapshotEnabled),
readAutoInitProjectGit:
@@ -150,12 +172,15 @@ export function createGitSnapshotCoordinator(
// 停用轴:快照标签是新的付费 one-shot,该 agent 的默认路由被停用时不派发 ——
// 抛错让 labeler 走既有的确定性兜底标签(gitSnapshotLabeler:oneShot 失败即
// fallback,PR #744 review 第十一轮)。
- if (await isAgentOneShotRouteDisabled(agentKind)) {
+ if (await operationWait(isAgentOneShotRouteDisabled(agentKind))) {
throw new Error('snapshot label one-shot skipped: route disabled in settings');
}
+ operationCheckpoint();
+ const operation = currentOperationBudget();
return maker.oneShot(agentKind, prompt, {
maxTokens: ONESHOT_MAX_TOKENS,
- timeoutMs: ONESHOT_TIMEOUT_MS,
+ timeoutMs: operation ? Math.max(1, Math.min(1_000, operation.deadlineAtMs - performance.now())) : ONESHOT_TIMEOUT_MS,
+ ...(operation ? { signal: operation.signal } : {}),
});
},
logger,
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts
index 55cbab1ae2..bd0cd42d58 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts
@@ -589,19 +589,19 @@ describe('queued welcome dispatch receipts', () => {
it('rejects when Stop wins before provider dispatch', async () => {
const { h, dispatch } = setup();
- let release!: () => void;
const vendorStart = vi.fn();
h.sendToAgent.mockImplementation(async (sid, _message, _create, opts) => {
await persistQueuedUserMessage(sid, opts);
vendorStart();
return sendSuccess();
});
- h.beforeDispatchUserTurn.mockImplementation(() => new Promise<void>(resolve => { release = resolve; }));
+ h.beforeDispatchUserTurn.mockImplementation((_sid, _item, signal) => new Promise<void>(resolve => {
+ signal!.addEventListener('abort', () => resolve(), { once: true });
+ }));
const result = dispatch('welcome');
await flush();
expect(h.beforeDispatchUserTurn).toHaveBeenCalledOnce();
h.coordinator.stop('welcome-session');
- release();
await expect(result).resolves.toBe(false);
expect(vendorStart).not.toHaveBeenCalled();
});
@@ -2529,7 +2529,7 @@ describe('AgentInputCoordinator send transaction', () => {
h.coordinator.onTurnEvent(sid, 'done');
await flush();
expect(h.beforeDispatchUserTurn).toHaveBeenLastCalledWith(sid,
- expect.objectContaining({ clientId: 'internal', botTaskCoordination: internal.botTaskCoordination }));
+ expect.objectContaining({ clientId: 'internal', botTaskCoordination: internal.botTaskCoordination }), expect.any(AbortSignal));
expect(h.sendToAgent).toHaveBeenCalledTimes(2);
expect(h.coordinator.isActiveTaskCoordination(sid)).toBe(true);
},
@@ -3564,7 +3564,7 @@ describe('AgentInputCoordinator send transaction', () => {
h.coordinator.enqueue(sid, item);
await flush();
- expect(h.beforeDispatchUserTurn).toHaveBeenCalledWith(sid, expect.objectContaining(item));
+ expect(h.beforeDispatchUserTurn).toHaveBeenCalledWith(sid, expect.objectContaining(item), expect.any(AbortSignal));
expect(events).toEqual([
'before-dispatch:start',
'before-dispatch:end',
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts
index 422d520787..ae1128dad4 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts
@@ -18,6 +18,7 @@ import { formatQuotesForSend, stripChatQuoteMarkerLines } from '@cindy/maker-sha
import type { AgentInputQueuedMessage } from '../../../shared/agentInputQueue';
import { parseOrcaRemoteLead } from '../../../shared/orcaRemoteWorker';
import { describe, expect, it, vi } from 'vitest';
+import { GitSnapshotCoordinator } from '../../git-snapshot/gitSnapshotCoordinator';
import { AUTO_REVIEW_DELEGATED_CONTINUATION, restoreAutoReviewUserIntent, type AutoReviewHistoryMessage } from '../autoReviewUserIntent.js';
import { FORWARDED_REQUEST_RECEIPT, formatForwardedRequest } from '../../../shared/forwardedRequest.js';
import { appMessageInput, MCP_APP_MESSAGE_GUARD } from '../../mcp-apps/message.js';
@@ -1216,11 +1217,13 @@ describe('maker SEND transaction', () => {
it('awaits the direct-send baseline hook before vendor dispatch', async () => {
const events: string[] = [];
+ const controller = new AbortController();
const beforeDispatchDirectUserTurn = vi.fn(async () => {
events.push('baseline');
});
const session = createSession({
- send: vi.fn(async () => {
+ send: vi.fn(async (_message, opts) => {
+ await opts?.onAccepted?.(controller.signal);
events.push('send');
return { accepted: true } satisfies SessionSendResult;
}),
@@ -1236,7 +1239,75 @@ describe('maker SEND transaction', () => {
});
expect(events).toEqual(['baseline', 'send']);
- expect(beforeDispatchDirectUserTurn).toHaveBeenCalledWith('session-1');
+ expect(beforeDispatchDirectUserTurn).toHaveBeenCalledWith('session-1', controller.signal);
+ });
+
+ // #7259: unit tier, stalled snapshot metadata through the real send transaction.
+ // Previously no total deadline existed, so provider dispatch never happened.
+ it('continues direct sending once when the automatic snapshot budget expires', async () => {
+ vi.useFakeTimers();
+ const snapshots = new GitSnapshotCoordinator({
+ snapshotTimeoutMs: 50,
+ recordTurnAttempt: async () => ({ attemptId: 'attempt-1', anchor: 'message-1' }),
+ readAutoSnapshotEnabled: () => true,
+ getSessionContext: () => new Promise(() => {}),
+ detectRepoRoot: vi.fn(), createShadowSavepoint: vi.fn(), createShadowMarker: vi.fn(),
+ oneShot: vi.fn(), logger: { debug: vi.fn(), info: vi.fn(), warn: vi.fn() },
+ });
+ try {
+ const vendor = vi.fn();
+ const session = createSession({ send: vi.fn(async (_message, opts) => {
+ await opts?.onAccepted?.();
+ vendor();
+ return { accepted: true } satisfies SessionSendResult;
+ }) });
+ const { deps } = createDeps({
+ getSession: () => session,
+ beforeDispatchDirectUserTurn: (sid, signal) => snapshots.onTurnStart(sid, signal),
+ });
+ const sending = createMakerSendTransaction(deps).sendToAgentAccepted('session-1', 'hello');
+ await vi.advanceTimersByTimeAsync(0);
+ expect(vendor).not.toHaveBeenCalled();
+ await vi.advanceTimersByTimeAsync(50);
+ await expect(sending).resolves.toMatchObject({ accepted: true });
+ expect(vendor).toHaveBeenCalledOnce();
+ } finally {
+ snapshots.onSessionClosed('session-1');
+ vi.useRealTimers();
+ }
+ });
+
+ // #7259 follow-up, unit: a late durable intent cannot resume a failed send.
+ it('never dispatches when recording the snapshot attempt exceeds the total budget', async () => {
+ vi.useFakeTimers();
+ let finishIntent!: (value: { attemptId: string }) => void;
+ const intent = new Promise<{ attemptId: string }>((resolve) => { finishIntent = resolve; });
+ const snapshots = new GitSnapshotCoordinator({
+ snapshotTimeoutMs: 50, recordTurnAttempt: () => intent,
+ readAutoSnapshotEnabled: () => true, getSessionContext: vi.fn(), detectRepoRoot: vi.fn(),
+ createShadowSavepoint: vi.fn(), createShadowMarker: vi.fn(), oneShot: vi.fn(),
+ logger: { debug: vi.fn(), info: vi.fn(), warn: vi.fn() },
+ });
+ try {
+ const vendor = vi.fn();
+ const session = createSession({ send: vi.fn(async (_message, opts) => {
+ await opts?.onAccepted?.();
+ vendor();
+ return { accepted: true } satisfies SessionSendResult;
+ }) });
+ const { deps } = createDeps({ getSession: () => session,
+ beforeDispatchDirectUserTurn: (sid, signal) => snapshots.onTurnStart(sid, signal) });
+ const sending = createMakerSendTransaction(deps).sendToAgentAccepted('session-1', 'hello');
+ const failed = expect(sending).rejects.toThrow('deadline');
+ await vi.advanceTimersByTimeAsync(50);
+ await failed;
+ finishIntent({ attemptId: 'late' });
+ await vi.advanceTimersByTimeAsync(0);
+ expect(vendor).not.toHaveBeenCalled();
+ } finally {
+ snapshots.onSessionClosed('session-1');
+ vi.useRealTimers();
+ }
});
it('materializes direct OSS attachments after session/workdir preflight', async () => {
@@ -1504,9 +1575,10 @@ describe('maker SEND transaction', () => {
const beforeDispatchDirectUserTurn = vi.fn(async () => {});
const onUndispatchedDirectUserTurn = vi.fn();
const session = createSession({
- send: vi.fn(async () => (
- { accepted: false, reason: 'cancelled-before-dispatch' } satisfies SessionSendResult
- )),
+ send: vi.fn(async (_message, opts) => {
+ await opts?.onAccepted?.();
+ return { accepted: false, reason: 'cancelled-before-dispatch' } satisfies SessionSendResult;
+ }),
});
const { deps } = createDeps({
getSession: vi.fn(() => session),
@@ -1520,7 +1592,7 @@ describe('maker SEND transaction', () => {
reason: 'cancelled-before-dispatch',
});
- expect(beforeDispatchDirectUserTurn).toHaveBeenCalledWith('session-1');
+ expect(beforeDispatchDirectUserTurn).toHaveBeenCalledWith('session-1', undefined);
expect(onUndispatchedDirectUserTurn).toHaveBeenCalledWith('session-1');
});
@@ -1528,7 +1600,8 @@ describe('maker SEND transaction', () => {
const beforeDispatchDirectUserTurn = vi.fn(async () => {});
const onUndispatchedDirectUserTurn = vi.fn();
const session = createSession({
- send: vi.fn(async () => {
+ send: vi.fn(async (_message, opts) => {
+ await opts?.onAccepted?.();
throw new Error('start failed');
}),
});
@@ -1541,7 +1614,7 @@ describe('maker SEND transaction', () => {
await expect(transaction.sendToAgentAccepted('session-1', 'hello')).rejects.toThrow('start failed');
- expect(beforeDispatchDirectUserTurn).toHaveBeenCalledWith('session-1');
+ expect(beforeDispatchDirectUserTurn).toHaveBeenCalledWith('session-1', undefined);
expect(onUndispatchedDirectUserTurn).toHaveBeenCalledWith('session-1');
});
diff --git a/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts b/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts
index e3cfa94d6e..3b8defba63 100644
--- a/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts
+++ b/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts
@@ -300,7 +300,7 @@ export interface AgentInputSendOpts {
origin?: AgentInputQueuedMessage['origin'];
shouldBroadcast?: () => boolean;
onPersisting?: () => void;
- onPersisted?: () => void | Promise<void>;
+ onPersisted?: (signal?: AbortSignal) => void | Promise<void>;
onPersistFailed?: () => void;
};
}
@@ -529,6 +529,7 @@ export interface AgentInputCoordinatorDeps {
beforeDispatchUserTurn?: (
sessionId: string,
item: AgentInputQueuedMessage,
+ signal?: AbortSignal,
) => void | Promise<void>;
/**
* Called when a user row crossed the persistence boundary but never reached
@@ -5155,7 +5156,7 @@ export class AgentInputCoordinator {
active.persisting = true;
}
},
- onPersisted: async () => {
+ onPersisted: async (signal) => {
// The DB row already owns any staged attachment references. This
// callback intentionally runs before generation checks: a clear
// or Stop may win the pre-vendor race after persistence, but it
@@ -5171,7 +5172,7 @@ export class AgentInputCoordinator {
// 已送达的消息二次恢复(issue #761)。
this.maybePersistQueueSnapshot(sessionId);
}
- await this.deps.beforeDispatchUserTurn?.(sessionId, head);
+ await this.deps.beforeDispatchUserTurn?.(sessionId, head, signal ?? this.getInputAbortSignal(sessionId, active.generation));
if (!this.isActiveTurnCurrent(sessionId, active)) {
throw new Error(
'[SEND_CANCELLED_BEFORE_DISPATCH] User turn was cancelled before vendor dispatch',
diff --git a/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts b/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts
index 3ff23c255e..75a62c3f7a 100644
--- a/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts
+++ b/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts
@@ -488,7 +488,7 @@ export interface MakerSendTransactionDeps {
/** 把 Pi 原生 user entry id 补到已落库的 Cindy user 行,供会话树恢复附件。 */
linkPiUserEntry?(sessionId: string, clientId: string, piEntryId: string): Promise<boolean | void>;
readPiUserEntry?(sessionId: string, clientId: string): Promise<string | undefined>;
- beforeDispatchDirectUserTurn?: (sessionId: string) => void | Promise<void>;
+ beforeDispatchDirectUserTurn?: (sessionId: string, signal?: AbortSignal) => void | Promise<void>;
/** Capture product lifecycle state before async preparation; commit only at vendor dispatch. */
prepareProductTurn?: (sessionId: string) => (() => void) | undefined;
/** Synchronous final fence immediately before Session.send enters vendor code. */
@@ -641,7 +641,7 @@ function readPersistUserMessageOption(sendOpts: MakerSendOptions): {
origin?: Record<string, unknown>;
shouldBroadcast?: () => boolean;
onPersisting?: () => void;
- onPersisted?: () => void | Promise<void>;
+ onPersisted?: (signal?: AbortSignal) => void | Promise<void>;
onPersistFailed?: () => void;
expectedClearBoundaryMs?: number | null;
expectedInputGeneration?: number;
@@ -680,7 +680,7 @@ function readPersistUserMessageOption(sendOpts: MakerSendOptions): {
? { onPersisting: persist.onPersisting as () => void }
: {}),
...(typeof persist.onPersisted === 'function'
- ? { onPersisted: persist.onPersisted as () => void | Promise<void> }
+ ? { onPersisted: persist.onPersisted as (signal?: AbortSignal) => void | Promise<void> }
: {}),
...(typeof persist.onPersistFailed === 'function'
? { onPersistFailed: persist.onPersistFailed as () => void }
@@ -1788,10 +1788,6 @@ export function createMakerSendTransaction(deps: MakerSendTransactionDeps): Make
let userPromptPreviewSessionId: string | null = null;
let userPromptPreviewClientId: string | null = null;
try {
- if (directPreDispatchHook) {
- await directPreDispatchHook(sessionId);
- directPreDispatchHookStarted = true;
- }
let cindyLearnInvocation: CindyLearnInvocationGrant | null = null;
// Every Cindy harness consumes this exact-path pin at its provider
// boundary: Codex sends a structured Skill item, Pi validates the live
@@ -1918,7 +1914,7 @@ export function createMakerSendTransaction(deps: MakerSendTransactionDeps): Make
}
: {}),
onAccepted: persistUserMessage
- ? async () => {
+ ? async (signal) => {
persistUserMessage.onPersisting?.();
if (!persistUserMessage.botTaskCoordination) {
deps.previewUserPrompt?.(sess, persistUserMessage.content, {
@@ -1997,9 +1993,12 @@ export function createMakerSendTransaction(deps: MakerSendTransactionDeps): Make
await rewindPersistedUserMessageAfterClearIfStale();
// onPersisted 里可能挂着排队 orca 消息的 accepted 副作用(置 running /
// autoBridgePending), 必须 await 完再放行 turn(同直发路径语义)。
- await persistUserMessage.onPersisted?.();
+ await persistUserMessage.onPersisted?.(signal);
}
- : undefined,
+ : directPreDispatchHook ? async (signal) => {
+ await directPreDispatchHook(sessionId, signal);
+ directPreDispatchHookStarted = true;
+ } : undefined,
onDispatching: () => {
if (resolveScheduledIntent) assertScheduledModes();
if (persistUserMessage?.shouldBroadcast && !persistUserMessage.shouldBroadcast()) {
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 72ad659edf..96da3d9f87 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -4739,13 +4739,13 @@ export function collectAgentInputQueueScanTexts(): string[] {
}
export interface AutomationUserTurnGitBaselineHooks {
- beforeDispatchUserTurn(sessionId: string): void | Promise<void>;
+ beforeDispatchUserTurn(sessionId: string, signal?: AbortSignal): void | Promise<void>;
onUndispatchedUserTurn(sessionId: string): void;
}
export function createAutomationUserTurnGitBaselineHooks(): AutomationUserTurnGitBaselineHooks {
return {
- beforeDispatchUserTurn: (sessionId) => gitSnapshotCoordinator?.onTurnStart(sessionId),
+ beforeDispatchUserTurn: (sessionId, signal) => gitSnapshotCoordinator?.onTurnStart(sessionId, signal),
onUndispatchedUserTurn: (sessionId) => gitSnapshotCoordinator?.onTurnAbort(sessionId),
};
}
@@ -11694,12 +11694,12 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
try {
const sendResult = await session.send(outgoingMessage, {
...opts,
- onAccepted: async () => {
- await opts.onAccepted?.();
+ onAccepted: async (signal) => {
+ await opts.onAccepted?.(signal);
await beginTurnChangeSetAtDispatch(session, anchorClientId);
turnChangeSetStarted = true;
if (gitSnapshotCoordinator) {
- await gitSnapshotCoordinator.onTurnStart(session.id);
+ await gitSnapshotCoordinator.onTurnStart(session.id, signal);
baselineStarted = true;
}
},
@@ -18022,7 +18022,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
enqueueDurableWrite(`pi-entry-link:${sessionId}:${clientId}`, () =>
patchMessageAgentMeta(sessionId, clientId, { piEntryId }),
),
- beforeDispatchDirectUserTurn: (sessionId) => gitSnapshotCoordinator?.onTurnStart(sessionId),
+ beforeDispatchDirectUserTurn: (sessionId, signal) => gitSnapshotCoordinator?.onTurnStart(sessionId, signal),
onModelDispatched: recordDispatchedModelHolder = (sessionId, clientId) => {
const live = maker.getSession(sessionId);
if (!live) return;
@@ -20213,7 +20213,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
});
},
onUserMessageRewritten: (sessionId, item, info) => (revokeTrustedDesktopQueueOrigin(item), broadcastGhostMessageRewritten({ sessionId, clientId: item.clientId, ...info })),
- beforeDispatchUserTurn: async (sessionId, item) => {
+ beforeDispatchUserTurn: async (sessionId, item, signal) => {
if (item.botTaskCoordination) await assertBotTaskCoordination(sessionId, item.botTaskCoordination);
autoResumeBookkeeping.markReplacementDispatching(sessionId, item.clientId);
const liveSession = maker.getSession(sessionId);
@@ -20225,7 +20225,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
// 才是目标续跑轮 —— 绕过 coordinator 的 turn(silent-stop 自动续跑)不走这里,
// 结构上不可能被误认。详见 uiContinuationSignal 的模块注释。
publishUiTurnDispatching(sessionId, item.clientId);
- await gitSnapshotCoordinator?.onTurnStart(sessionId);
+ await gitSnapshotCoordinator?.onTurnStart(sessionId, signal);
},
onUndispatchedUserTurn: (sessionId, item, disposition) => {
void settleTodoDispatch(sessionId, item.clientId, false);
diff --git a/apps/desktop/src/main/maker-orchestration/rewind.ts b/apps/desktop/src/main/maker-orchestration/rewind.ts
index 1d3893629c..19c8599fc4 100644
--- a/apps/desktop/src/main/maker-orchestration/rewind.ts
+++ b/apps/desktop/src/main/maker-orchestration/rewind.ts
@@ -29,6 +29,8 @@ import { sessions, messages } from '../localDb/schema';
import { sessionToCamel } from '../localDb/mapper';
import { getMaker } from '../maker-host/index.js';
import { readGitSafetySettings } from '../maker-host/git-safety-settings-store.js';
+import { ownerScopedUserDataPath } from '../appSessionState';
+import { SnapshotAttemptStore } from '../git-snapshot/snapshotAttemptStore';
import type { Session } from '../../renderer/lib/ccAgent.types';
import type { RewindFilesResult } from '@cindy/maker-core';
@@ -535,7 +537,9 @@ function parseNumstat(value: string): number {
async function buildCodexFilePlanForSession(sessionId: string, targetMessageClientId: string, userMessages: readonly CodexRewindUserMessage[], makerSession: { workDir: string; remoteHostId?: string | null }) {
try {
- return buildCodexFileRewindPlan({ sessionId, targetMessageClientId, userMessages, repo: await loadCodexFileRewindRepoContext(makerSession, sessionId) });
+ const attempts = new SnapshotAttemptStore(ownerScopedUserDataPath()).read(sessionId);
+ const [repo, snapshotAttempts] = await Promise.all([loadCodexFileRewindRepoContext(makerSession, sessionId), attempts]);
+ return buildCodexFileRewindPlan({ sessionId, targetMessageClientId, userMessages, repo, snapshotAttempts });
} catch (err) {
if (err instanceof CodexFileRewindPlanError) {
if (err.code === 'MESSAGE_NOT_FOUND') throw rewindError('MESSAGE_NOT_FOUND', err.message);
@@ -556,6 +560,7 @@ function toPlannerSavepoint(snapshot: SnapshotEntry): CodexRewindSavepoint {
...(snapshot.anchor ? { anchor: snapshot.anchor } : {}),
...(snapshot.label ? { label: snapshot.label } : {}),
...(snapshot.baselineCommit ? { baselineCommit: snapshot.baselineCommit } : {}),
+ ...(snapshot.attemptId ? { attemptId: snapshot.attemptId } : {}),
};
}
diff --git a/apps/desktop/src/main/scheduler-host/__tests__/runnerSendOutcome.test.ts b/apps/desktop/src/main/scheduler-host/__tests__/runnerSendOutcome.test.ts
index c50ef607b4..6e234f52c5 100644
--- a/apps/desktop/src/main/scheduler-host/__tests__/runnerSendOutcome.test.ts
+++ b/apps/desktop/src/main/scheduler-host/__tests__/runnerSendOutcome.test.ts
@@ -564,7 +564,7 @@ describe('MakerScheduleRunner send outcome policy', () => {
const firePromise = runner.fire(baseSchedule(), ctx);
await vi.waitFor(() => expect(h.send).toHaveBeenCalled());
- await vi.waitFor(() => expect(beforeDispatchUserTurn).toHaveBeenCalledWith('scheduler-session'));
+ await vi.waitFor(() => expect(beforeDispatchUserTurn).toHaveBeenCalledWith('scheduler-session', undefined));
expect(order).toEqual(['send', 'persist']);
releaseBaseline?.();
diff --git a/apps/desktop/src/main/scheduler-host/index.ts b/apps/desktop/src/main/scheduler-host/index.ts
index e4ffee3cbe..df6934ce96 100644
--- a/apps/desktop/src/main/scheduler-host/index.ts
+++ b/apps/desktop/src/main/scheduler-host/index.ts
@@ -76,7 +76,7 @@ export interface StartSchedulerDeps {
getMainWindow: () => BrowserWindow | null;
feishuIm: FeishuIM;
logger: Logger;
- beforeDispatchUserTurn?: (sessionId: string) => void | Promise<void>;
+ beforeDispatchUserTurn?: (sessionId: string, signal?: AbortSignal) => void | Promise<void>;
onUndispatchedUserTurn?: (sessionId: string) => void;
}
diff --git a/apps/desktop/src/main/scheduler-host/runner.ts b/apps/desktop/src/main/scheduler-host/runner.ts
index 3b2f10d021..853d11b466 100644
--- a/apps/desktop/src/main/scheduler-host/runner.ts
+++ b/apps/desktop/src/main/scheduler-host/runner.ts
@@ -272,7 +272,7 @@ export interface MakerScheduleRunnerDeps {
notifier: Notifier;
logger: Logger;
readAutoReviewHistory?: (sessionId: string) => Promise<AutoReviewHistoryMessage[]>;
- beforeDispatchUserTurn?: (sessionId: string) => void | Promise<void>;
+ beforeDispatchUserTurn?: (sessionId: string, signal?: AbortSignal) => void | Promise<void>;
onUndispatchedUserTurn?: (sessionId: string) => void;
/** Saved quota waits deduplicate by schedule even when each fire creates a new task. */
findUsageLimitWait?: (scheduleId: string) => Promise<string | null>;
@@ -2047,7 +2047,7 @@ export class MakerScheduleRunner implements ScheduleRunner {
}
},
planMode: routinePermissions?.planMode ?? heartbeatPermissions?.planMode ?? false,
- onAccepted: async () => {
+ onAccepted: async (signal) => {
// createSession 之后到真正 dispatch 之间仍会 await 模型切换、baseline
// 等准备工作。复用 desktop session 时不能在这些准备阶段把用户正在跑的
// turn 误标成 headless;只在本轮 send 真正跨过接受边界后 acquire。
@@ -2088,7 +2088,7 @@ export class MakerScheduleRunner implements ScheduleRunner {
}
}
if (this.deps.beforeDispatchUserTurn) {
- await this.deps.beforeDispatchUserTurn(session.id);
+ await this.deps.beforeDispatchUserTurn(session.id, signal);
baselineStarted = true;
}
if (ctx.canDispatch && !ctx.canDispatch()) {
diff --git a/apps/desktop/src/main/utils/operationBudget.ts b/apps/desktop/src/main/utils/operationBudget.ts
new file mode 100644
index 0000000000..a3a2adbbdf
--- /dev/null
+++ b/apps/desktop/src/main/utils/operationBudget.ts
@@ -0,0 +1,114 @@
+import { AsyncLocalStorage } from 'node:async_hooks';
+import { setImmediate } from 'node:timers/promises';
+import path from 'node:path';
+
+// An async-local scope keeps nested Git probes, ownership repair and bootstrap
+// on the same budget. It never affects manual Git operations outside the scope.
+const current = new AsyncLocalStorage<OperationBudget>();
+const uncertainGitDirectories = new Set<string>();
+const directoryKey = (dir: string) =>
+ process.platform === 'win32' ? path.resolve(dir).toLowerCase() : path.resolve(dir);
+
+export function quarantineGitDirectory(dir: string): void {
+ uncertainGitDirectories.add(directoryKey(dir));
+}
+
+export function assertGitDirectoryReady(dir: string): void {
+ if (uncertainGitDirectories.has(directoryKey(dir))) {
+ throw new Error('Git process cleanup unconfirmed; repository writes disabled until restart');
+ }
+}
+
+export class OperationBudget {
+ readonly controller = new AbortController();
+ readonly signal = this.controller.signal;
+ readonly deadlineAtMs: number;
+ private readonly children = new Set<Promise<unknown>>();
+
+ constructor(readonly timeoutMs: number) {
+ this.deadlineAtMs = performance.now() + timeoutMs;
+ }
+
+ cancel(reason: unknown = new Error('Snapshot cancelled')): void {
+ this.controller.abort(reason);
+ }
+
+ check(): void {
+ if (!this.signal.aborted && performance.now() >= this.deadlineAtMs) {
+ this.cancel(new Error('Snapshot operation deadline exceeded'));
+ }
+ this.signal.throwIfAborted();
+ }
+
+ track<T>(promise: Promise<T>): Promise<T> {
+ this.children.add(promise);
+ void promise.finally(() => this.children.delete(promise)).catch(() => {});
+ return promise;
+ }
+
+ async drain(): Promise<void> {
+ await Promise.allSettled([...this.children]);
+ }
+
+ async run<T>(task: () => Promise<T>, signal?: AbortSignal): Promise<T> {
+ const abort = () => this.cancel(signal?.reason);
+ signal?.addEventListener('abort', abort, { once: true });
+ if (signal?.aborted) abort();
+ const timer = setTimeout(
+ () => this.cancel(new Error('Snapshot operation deadline exceeded')),
+ this.timeoutMs,
+ );
+ try {
+ return await current.run(this, async () => {
+ this.check();
+ try {
+ return await operationWait(Promise.resolve().then(task));
+ } finally {
+ // Git owns termination and its bounded cleanup. Returning from a
+ // cancelled scope must not merely abandon still-running children.
+ await this.drain();
+ }
+ });
+ } finally {
+ clearTimeout(timer);
+ signal?.removeEventListener('abort', abort);
+ }
+ }
+}
+
+export function currentOperationBudget(): OperationBudget | undefined {
+ return current.getStore();
+}
+
+export function operationCheckpoint(): void {
+ current.getStore()?.check();
+}
+
+/** Only for interruptible waits/reads; writes must retain their cleanup owner. */
+export async function operationWait<T>(promise: T | PromiseLike<T>): Promise<T> {
+ const scope = current.getStore();
+ if (!scope) return promise;
+ // Attach handlers even when already aborted: the caller may have started IO.
+ let abort!: () => void;
+ const cancelled = new Promise<never>((_, reject) => {
+ abort = () => reject(scope.signal.reason);
+ scope.signal.addEventListener('abort', abort, { once: true });
+ if (scope.signal.aborted) abort();
+ });
+ try {
+ const value = await Promise.race([promise, cancelled]);
+ scope.check();
+ return value;
+ } finally {
+ scope.signal.removeEventListener('abort', abort);
+ }
+}
+
+/** Give Stop/deadline timers a turn during long cached filesystem scans. */
+export async function operationYield(index: number): Promise<void> {
+ operationCheckpoint();
+ if (current.getStore() && index % 256 === 0) {
+ await setImmediate();
+ operationCheckpoint();
+ }
+}
diff --git a/apps/desktop/src/main/utils/operationFileSystem.ts b/apps/desktop/src/main/utils/operationFileSystem.ts
new file mode 100644
index 0000000000..0b021c5bc5
--- /dev/null
+++ b/apps/desktop/src/main/utils/operationFileSystem.ts
@@ -0,0 +1,22 @@
+import type { promises as fs } from 'node:fs';
+import { operationCheckpoint, operationWait } from './operationBudget';
+
+/**
+ * Snapshot reads may stop waiting on a stalled filesystem. Native filesystem
+ * requests cannot be killed; their late results are discarded. Temporary-file
+ * writes retain their owner/finally cleanup instead of racing the write.
+ */
+export function operationFileSystem(native: typeof fs): typeof fs {
+ const reads = new Set(['access', 'lstat', 'stat', 'realpath', 'readdir', 'readFile']);
+ return new Proxy(native, {
+ get(target, key, receiver) {
+ const value = Reflect.get(target, key, receiver);
+ if (typeof value !== 'function' || key === 'rm') return value;
+ return (...args: unknown[]) => {
+ operationCheckpoint();
+ const result = Reflect.apply(value, target, args);
+ return reads.has(String(key)) ? operationWait(result) : result;
+ };
+ },
+ });
+}
diff --git a/apps/desktop/src/main/worktree/WorktreeManager.ts b/apps/desktop/src/main/worktree/WorktreeManager.ts
index a24b6f33dc..34977e42ec 100644
--- a/apps/desktop/src/main/worktree/WorktreeManager.ts
+++ b/apps/desktop/src/main/worktree/WorktreeManager.ts
@@ -12,6 +12,7 @@
import { randomUUID } from 'node:crypto';
import path from 'node:path';
+import { currentOperationBudget, operationWait } from '../utils/operationBudget';
import fs from 'node:fs/promises';
import {
@@ -34,6 +35,7 @@ import {
safeDirectorySpellings,
} from './gitExec';
import { gitPathOutput } from './gitPathOutput';
+import { ensureManagedWorktreeExcluded } from './managedWorktreeExclude';
import { withCrossProcessLock } from '../device-link/crossProcessLock';
import { applyWorktreeIncludeFile, listChangedWorktreeIncludeFiles } from './includePatternsEngine';
import { hasKeepSentinel, isManagedWorktreePath } from './safety';
@@ -406,7 +408,12 @@ async function withPrecreatedWorktreeOperationQueue<T>(
/**
* 探测 cwd 状态: 是否 git repo / 是否在 worktree 内 / git 是否可用 / 当前分支 / repo root
*/
-export const detectCwd = createCwdProbeScheduler(detectCwdOnce);
+const scheduledDetectCwd = createCwdProbeScheduler(detectCwdOnce);
+export function detectCwd(cwd: string): Promise<DetectCwdResp> {
+ // Automatic snapshots own cancellation. Never lend their abortable probe to
+ // an unrelated UI request (or borrow an unabortable pending UI probe).
+ return currentOperationBudget() ? operationWait(detectCwdOnce(cwd)) : scheduledDetectCwd(cwd);
+}
// Share the work budget across realpath and every Git query. Git's additional
// 3s process-tree cleanup still leaves response headroom under Mobile's 15s wait.
@@ -415,6 +422,7 @@ const CWD_PROBE_TIMEOUT_MS = 10_000;
async function detectCwdOnce(cwd: string): Promise<DetectCwdResp> {
const deadline = performance.now() + CWD_PROBE_TIMEOUT_MS;
const probeGit = async (args: readonly string[], dir?: string) => {
+ currentOperationBudget()?.check();
const timeoutMs = Math.ceil(deadline - performance.now());
if (timeoutMs <= 0) {
throw new GitExecError({
@@ -1166,6 +1174,7 @@ async function createWorktreeInner(req: CreateWorktreeReq, options?: { trackBack
// 4. mkdirp parent
return await withWorktreeResourceLock(worktreePath, async (): Promise<CreateWorktreeResp> => {
+ await ensureManagedWorktreeExcluded(baseRepo, worktreePath);
const parentDir = path.dirname(worktreePath);
await timed('ensure parent directory', () => fs.mkdir(parentDir, { recursive: true }));
snap.parentEnsured = parentDir;
diff --git a/apps/desktop/src/main/worktree/__tests__/gitExec.test.ts b/apps/desktop/src/main/worktree/__tests__/gitExec.test.ts
index d844c1eb06..3f0edde785 100644
--- a/apps/desktop/src/main/worktree/__tests__/gitExec.test.ts
+++ b/apps/desktop/src/main/worktree/__tests__/gitExec.test.ts
@@ -7,6 +7,8 @@
*/
import { EventEmitter } from 'node:events';
+import { OperationBudget } from '../../utils/operationBudget';
+import { enqueueGitRepoWrite } from '../../git-snapshot/gitRepoWriteQueue';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
type ExecCb = (err: Error | null, stdout: string, stderr: string) => void;
@@ -179,6 +181,72 @@ afterEach(() => {
});
describe('gitExec timeoutMs', () => {
+ // #7259: unit tier. Explicit abort must kill the tree, not only drop its
+ // promise; a blocked child is the minimal reproduction. No wall-clock waits.
+ it.each(['win32', 'linux'] as const)('abort terminates the %s tree before settling', async (platform) => {
+ setPlatform(platform);
+ const state = installExecFileMock();
+ state.psTable = [];
+ const { group } = installProcessKillMock();
+ let finish!: () => void;
+ mocks.killProcessTree.mockImplementation((_pid, _child, done) => { finish = done; });
+ const controller = new AbortController();
+ const pending = gitExec(['status'], undefined, { signal: controller.signal });
+ const observed = probe(pending);
+ controller.abort();
+ await flushMicrotasks();
+ expect(observed.settled).toBe(false);
+ if (platform === 'win32') {
+ expect(mocks.killProcessTree).toHaveBeenCalledOnce();
+ state.gitCb!(null, 'late success', '');
+ finish();
+ } else {
+ expect(group.signals).toContain('SIGTERM');
+ group.alive = false;
+ await vi.advanceTimersByTimeAsync(100);
+ }
+ await expect(pending).rejects.toMatchObject({ aborted: true, cleanupUnconfirmed: false });
+ });
+
+ it('does not spawn Git for an already-aborted request', async () => {
+ installExecFileMock();
+ const controller = new AbortController();
+ controller.abort(new Error('stopped'));
+ await expect(gitExec(['add', '-A'], undefined, { signal: controller.signal })).rejects.toThrow('stopped');
+ expect(mocks.execFile).not.toHaveBeenCalled();
+ });
+
+ it('cleans the automatic status process tree when its output overflows', async () => {
+ setPlatform('linux');
+ const state = installExecFileMock();
+ const { group } = installProcessKillMock();
+ const pending = gitExec(['status'], undefined, { signal: new AbortController().signal });
+ const observed = probe(pending);
+ state.gitCb!(Object.assign(new Error('maxBuffer exceeded'), { code: 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER' }), '', '');
+ await flushMicrotasks();
+ expect(group.signals).toContain('SIGTERM');
+ expect(observed.settled).toBe(false);
+ group.alive = false;
+ await vi.advanceTimersByTimeAsync(100);
+ await expect(pending).rejects.toMatchObject({
+ cleanupUnconfirmed: false, cause: { code: 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER' },
+ });
+ });
+
+ it('quarantines only the affected repository when automatic cleanup cannot be confirmed', async () => {
+ setPlatform('win32');
+ installExecFileMock();
+ const budget = new OperationBudget(50);
+ const pending = budget.run(() => enqueueGitRepoWrite('/uncertain-snapshot', () => gitExec(['status'], '/uncertain-snapshot')));
+ probe(pending);
+ await vi.advanceTimersByTimeAsync(3_050);
+ await expect(pending).rejects.toThrow('deadline');
+ const write = vi.fn(async () => {});
+ await expect(enqueueGitRepoWrite('/uncertain-snapshot', write)).rejects.toThrow('cleanup unconfirmed');
+ expect(write).not.toHaveBeenCalled();
+ await enqueueGitRepoWrite('/independent-snapshot', write);
+ expect(write).toHaveBeenCalledOnce();
+ });
it('keeps a dead checkout root leased while a Windows descendant remains', async () => {
setPlatform('win32');
const state = installExecFileMock();
diff --git a/apps/desktop/src/main/worktree/gitExec.ts b/apps/desktop/src/main/worktree/gitExec.ts
index 9954de1940..fb8ac7b229 100644
--- a/apps/desktop/src/main/worktree/gitExec.ts
+++ b/apps/desktop/src/main/worktree/gitExec.ts
@@ -15,6 +15,7 @@
import { execFile, type ChildProcess, type ExecFileOptions } from 'node:child_process';
import os from 'node:os';
import path from 'node:path';
+import { assertGitDirectoryReady, currentOperationBudget, quarantineGitDirectory } from '../utils/operationBudget';
import { killProcessTree } from '../scheduler-host/proc-util';
import { withCrossProcessLock } from '../device-link/crossProcessLock';
@@ -42,6 +43,8 @@ export class GitExecError extends Error {
readonly cause?: NodeJS.ErrnoException;
/** 超时是未知状态,探测调用方不得把它当作「目录不存在」。 */
readonly timedOut: boolean;
+ readonly aborted: boolean;
+ readonly cleanupUnconfirmed: boolean;
constructor(opts: {
args: readonly string[];
@@ -50,6 +53,8 @@ export class GitExecError extends Error {
stdout: string;
cause?: NodeJS.ErrnoException;
timedOut?: boolean;
+ aborted?: boolean;
+ cleanupUnconfirmed?: boolean;
}) {
super(
`git ${opts.args.join(' ')} failed${
@@ -63,6 +68,8 @@ export class GitExecError extends Error {
this.stdout = opts.stdout;
this.cause = opts.cause;
this.timedOut = opts.timedOut ?? false;
+ this.aborted = opts.aborted ?? false;
+ this.cleanupUnconfirmed = opts.cleanupUnconfirmed ?? false;
}
}
@@ -78,13 +85,14 @@ export interface GitExecOpts {
* (git 收 TERM 会清理 .lock), 等**进程组清空**后才收口(直接 git 进程退出 ≠
* 组清空, 幸存的 git-remote-http 或 credential helper 后代仍可能持锁), 宽限期
* 内未清空的
- * 由整组 SIGKILL 兜底后再收口。两个平台都保证收口时进程树已终止——调用方拿到
- * 超时错误后立刻发起的下一个 git 操作不会与残留进程争抢同一仓库的 .lock。
+ * 由整组 SIGKILL 兜底后再收口。清理预算耗尽仍无法确认退净时返回
+ * cleanupUnconfirmed;自动快照会隔离该仓库的后续快照/回退写入。
* 省略 = 不超时。
*/
timeoutMs?: number;
/** Optional absolute performance.now() deadline shared by ownership repair and retries. */
deadlineAtMs?: number;
+ signal?: AbortSignal;
/** Called immediately after the git child is spawned. */
onSpawn?: (pid: number) => void;
}
@@ -225,7 +233,8 @@ function execFileOnce(
cwd?: string,
opts?: GitExecOpts,
): Promise<GitExecResult> {
- return new Promise((resolve, reject) => {
+ const pending = new Promise<GitExecResult>((resolve, reject) => {
+ opts?.signal?.throwIfAborted();
const remaining = remainingDeadlineMs(opts?.deadlineAtMs, args);
const timeoutMs = remaining === undefined ? opts?.timeoutMs
: Math.min(remaining, opts?.timeoutMs && opts.timeoutMs > 0 ? opts.timeoutMs : remaining);
@@ -245,6 +254,7 @@ function execFileOnce(
// Windows 收尾用:execFile 回调已到 = 全部继承 stdio 的进程都已退出/放手。
let stdioReleased = false;
let onStdioReleased: (() => void) | undefined;
+ let abortListener: (() => void) | undefined;
const settle = (fn: () => void) => {
if (settled) return;
settled = true;
@@ -252,6 +262,7 @@ function execFileOnce(
if (reaper !== undefined) clearTimeout(reaper);
if (groupPoll !== undefined) clearInterval(groupPoll);
if (finishWatchdog !== undefined) clearTimeout(finishWatchdog);
+ if (abortListener) opts?.signal?.removeEventListener('abort', abortListener);
fn();
};
@@ -320,6 +331,15 @@ function execFileOnce(
// - typeof (err as any).code === 'number' → 子进程退出码
const numericCode = (err as unknown as { code?: unknown }).code;
const exitCode = typeof numericCode === 'number' ? numericCode : null;
+ if (opts?.signal && errno.code === 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER') {
+ stdioReleased = true;
+ // execFile only kills the immediate child on overflow.
+ queueMicrotask(() => startTreeCleanup((treeConfirmedGone) => new GitExecError({
+ args, exitCode, stderr: stderrStr, stdout: '', cause: errno,
+ cleanupUnconfirmed: !treeConfirmedGone,
+ })));
+ return;
+ }
rejectWithGitError(
new GitExecError({
args,
@@ -359,7 +379,10 @@ function execFileOnce(
stdout: '',
cause: cause as NodeJS.ErrnoException,
});
- startTreeCleanup(() => failure);
+ startTreeCleanup((treeConfirmedGone) => new GitExecError({
+ args, exitCode: null, stderr: failure.stderr, stdout: failure.stdout,
+ cause: failure.cause, cleanupUnconfirmed: !treeConfirmedGone,
+ }));
};
child.once('error', handleChildProcessError);
child.stdout?.once('error', handleChildProcessError);
@@ -476,8 +499,8 @@ function execFileOnce(
try {
process.kill(-child.pid, 0);
return false;
- } catch {
- return true;
+ } catch (error) {
+ return (error as NodeJS.ErrnoException).code === 'ESRCH';
}
};
if (!groupEmpty()) {
@@ -507,7 +530,16 @@ function execFileOnce(
reaper.unref?.();
}
- if (timeoutMs !== undefined && timeoutMs > 0) {
+ abortListener = () => startTreeCleanup((treeConfirmedGone) => new GitExecError({
+ args, exitCode: null, stdout: '',
+ stderr: treeConfirmedGone ? 'cancelled; process tree terminated' : 'cancelled; process tree cleanup unconfirmed',
+ aborted: true, cleanupUnconfirmed: !treeConfirmedGone,
+ }));
+ if (!settled) {
+ opts?.signal?.addEventListener('abort', abortListener, { once: true });
+ if (opts?.signal?.aborted) abortListener();
+ }
+ if (!settled && timeoutMs !== undefined && timeoutMs > 0) {
timer = setTimeout(() => {
startTreeCleanup((treeConfirmedGone) =>
new GitExecError({
@@ -518,11 +550,13 @@ function execFileOnce(
: `timed out after ${timeoutMs}ms; process tree cleanup unconfirmed`,
stdout: '',
timedOut: true,
+ cleanupUnconfirmed: !treeConfirmedGone,
}),
);
}, timeoutMs);
}
});
+ return currentOperationBudget()?.track(pending) ?? pending;
}
/**
@@ -583,7 +617,7 @@ export function safeDirectorySpellings(p: string): string[] {
* 失败)必须向上抛,否则会把「读不到」误判成「未配置」而重复 --add,反而制造出
* 本条修复要避免的重复条目。
*/
-async function readGlobalSafeDirectories(opts?: Pick<GitExecOpts, 'timeoutMs' | 'deadlineAtMs'>): Promise<string[]> {
+async function readGlobalSafeDirectories(opts?: Pick<GitExecOpts, 'timeoutMs' | 'deadlineAtMs' | 'signal'>): Promise<string[]> {
try {
const { stdout } = await execFileOnce(['config', '--global', '--get-all', 'safe.directory'], undefined, opts);
return stdout
@@ -605,13 +639,14 @@ async function readGlobalSafeDirectories(opts?: Pick<GitExecOpts, 'timeoutMs' |
* dubious-ownership 错误还给调用方,而不是退化成并发写入重复条目。用底层
* execFileOnce 而非 gitExec, 防止递归进入 dubious-ownership 分支。
*/
-async function ensureGlobalSafeDirectory(targetPath: string, opts?: Pick<GitExecOpts, 'timeoutMs' | 'deadlineAtMs'>): Promise<void> {
+async function ensureGlobalSafeDirectory(targetPath: string, opts?: Pick<GitExecOpts, 'timeoutMs' | 'deadlineAtMs' | 'signal'>): Promise<void> {
const configArgs = ['config', '--global', 'safe.directory'];
const remaining = remainingDeadlineMs(opts?.deadlineAtMs, configArgs);
await withCrossProcessLock(
globalSafeDirectoryLockPath(),
{ label: 'git-safe-directory', waitMs: Math.min(1_000, remaining ?? 1_000) },
async (status) => {
+ opts?.signal?.throwIfAborted();
// Lock acquisition may finish after its wait budget; never start Git then.
remainingDeadlineMs(opts?.deadlineAtMs, configArgs);
if (!status.held) {
@@ -639,10 +674,22 @@ export async function gitExec(
cwd?: string,
opts?: GitExecOpts,
): Promise<GitExecResult> {
+ const operation = currentOperationBudget();
+ operation?.check();
+ if (operation) {
+ if (cwd) assertGitDirectoryReady(cwd);
+ opts = {
+ ...opts,
+ signal: opts?.signal ? AbortSignal.any([opts.signal, operation.signal]) : operation.signal,
+ deadlineAtMs: Math.min(opts?.deadlineAtMs ?? Infinity, operation.deadlineAtMs),
+ };
+ }
+ const execute = () => execFileOnce(args, cwd, opts);
try {
- return await execFileOnce(args, cwd, opts);
+ return await execute();
} catch (err) {
if (!(err instanceof GitExecError)) throw err;
+ if (operation && cwd && err.cleanupUnconfirmed) quarantineGitDirectory(cwd);
// spawn ENOENT(git 未安装) 也走 GitExecError, 这里不该重试
if (err.cause?.code === 'ENOENT') throw err;
@@ -651,11 +698,12 @@ export async function gitExec(
if (dubiousPath) {
try {
await ensureGlobalSafeDirectory(dubiousPath, {
- timeoutMs: opts?.timeoutMs, deadlineAtMs: opts?.deadlineAtMs,
+ timeoutMs: opts?.timeoutMs, deadlineAtMs: opts?.deadlineAtMs, signal: opts?.signal,
});
// 配完 safe.directory 后重试原命令
- return await execFileOnce(args, cwd, opts);
+ return await execute();
} catch (cause) {
+ if (operation && cwd && cause instanceof GitExecError && cause.cleanupUnconfirmed) quarantineGitDirectory(cwd);
// 普通修复失败仍返回原始 dubious-ownership 错误;超时单独向上传递。
// 但 ensureGlobalSafeDirectory 的真实失败(--get-all 权限/锁冲突/配置损坏,
// 或拿不到跨进程锁)不能被静默吞掉 —— 先落日志保住诊断信息, 再抛原始错误。
@@ -664,7 +712,8 @@ export async function gitExec(
cause instanceof Error ? cause.message : String(cause),
);
// 探测超时不能被误判为目录失效,也不能继续 fallback 启动新的 Git。
- if (cause instanceof GitExecError && cause.timedOut) throw cause;
+ opts?.signal?.throwIfAborted();
+ if (cause instanceof GitExecError && (cause.timedOut || cause.aborted)) throw cause;
throw err;
}
}
diff --git a/apps/desktop/src/main/worktree/managedWorktreeExclude.ts b/apps/desktop/src/main/worktree/managedWorktreeExclude.ts
new file mode 100644
index 0000000000..443f20b7a1
--- /dev/null
+++ b/apps/desktop/src/main/worktree/managedWorktreeExclude.ts
@@ -0,0 +1,50 @@
+import fs from 'node:fs/promises';
+import path from 'node:path';
+
+import { isManagedWorktreeDirectoryName } from '../../shared/managedWorktreePaths';
+import { withCrossProcessLock } from '../device-link/crossProcessLock';
+import { createLogger } from '../logger';
+import { gitExec } from './gitExec';
+import { gitPathOutput } from './gitPathOutput';
+
+const log = createLogger('worktree:exclude');
+
+/**
+ * Keep a directory Cindy is about to populate out of its parent repo's untracked
+ * scan. Only local exclude rules are appended; tracked files and .gitignore are
+ * untouched. Failure is an optimization miss, never a worktree creation failure.
+ */
+export async function ensureManagedWorktreeExcluded(baseRepo: string, worktreePath: string): Promise<void> {
+ const parent = path.dirname(path.resolve(worktreePath));
+ const directoryName = path.basename(parent);
+ if (path.dirname(parent) !== path.resolve(baseRepo) || !isManagedWorktreeDirectoryName(directoryName)) return;
+
+ try {
+ // Git resolves gitfiles / separate git dirs; never assume baseRepo/.git is a directory.
+ const { stdout } = await gitExec(['rev-parse', '--git-path', 'info/exclude'], baseRepo, { timeoutMs: 2_000 });
+ const gitPath = gitPathOutput(stdout);
+ if (!gitPath) throw new Error('Git exclude path unavailable');
+ const exclude = path.resolve(baseRepo, gitPath);
+ await fs.mkdir(path.dirname(exclude), { recursive: true });
+ await withCrossProcessLock(`${exclude}.cindy.lock`, { label: 'worktree:exclude', waitMs: 500 }, async (status) => {
+ if (!status.held) return;
+ // Do not rewrite a user-managed symlink, special file, or unusually large exclude.
+ const stat = await fs.lstat(exclude).catch((error: NodeJS.ErrnoException) => {
+ if (error.code === 'ENOENT') return null;
+ throw error;
+ });
+ if (stat && (!stat.isFile() || stat.size > 1024 * 1024)) return;
+ const content = stat ? await fs.readFile(exclude, 'utf8') : '';
+ const rule = `/${directoryName}/`;
+ if (content.split(/\r?\n/).includes(rule)) return;
+ const newline = content.includes('\r\n') ? '\r\n' : '\n';
+ const separator = content && !content.endsWith('\n') ? newline : '';
+ // Append instead of replacing the file so unrelated user rules are preserved.
+ await fs.appendFile(exclude, `${separator}${rule}${newline}`);
+ });
+ } catch (error) {
+ log.warn('Could not update managed worktree exclusion', {
+ code: (error as NodeJS.ErrnoException).code ?? 'EXCLUDE_UPDATE_FAILED',
+ });
+ }
+}
diff --git a/apps/desktop/src/main/worktree/restore.ts b/apps/desktop/src/main/worktree/restore.ts
index a7f67c77af..d6bd4d67d1 100644
--- a/apps/desktop/src/main/worktree/restore.ts
+++ b/apps/desktop/src/main/worktree/restore.ts
@@ -23,6 +23,7 @@ import {
} from './dirty';
import { readAttachedWorktreeBranch } from './attachedBranch';
import { gitExec, GitExecError } from './gitExec';
+import { ensureManagedWorktreeExcluded } from './managedWorktreeExclude';
import { applyWorktreeIncludeFile } from './includePatternsEngine';
import { pathKey } from './liveSessionRefs';
import {
@@ -254,6 +255,7 @@ async function addRestoredWorktree(
worktreePath: string,
branch: string,
): Promise<void> {
+ await ensureManagedWorktreeExcluded(baseRepo, worktreePath);
const addArgs = ['-c', 'core.longpaths=true', 'worktree', 'add', worktreePath, branch];
try {
await gitExec(addArgs, baseRepo);
diff --git a/apps/desktop/src/main/worktree/restoreRecovery.ts b/apps/desktop/src/main/worktree/restoreRecovery.ts
index 6e924ad585..32d1bc54cc 100644
--- a/apps/desktop/src/main/worktree/restoreRecovery.ts
+++ b/apps/desktop/src/main/worktree/restoreRecovery.ts
@@ -5,6 +5,7 @@ import path from 'node:path';
import { randomUUID } from 'node:crypto';
import { GitExecError, gitExec } from './gitExec';
+import { ensureManagedWorktreeExcluded } from './managedWorktreeExclude';
import { readRecycleRecord, writeRecycleRecord, worktreeGeneration } from './recycleJournal';
import { extractRecoveryArchive, inventoryWorktree, sameWorktreeFiles, verifyRecoveryArchive } from './recoveryArchive';
import { physicalWorktreeKey, withWorktreeResourceLock } from './resourceLock';
@@ -139,6 +140,7 @@ export async function restoreRecordedWorktree(sessionId: string, worktreePath: s
}
if (!legacyGuardHeld()) return false;
if (identity === null) {
+ await ensureManagedWorktreeExcluded(record.meta.baseRepo, worktreePath);
record.phase = 'restoring';
record.restoredGeneration ??= randomUUID();
record.directoryIdentity = null;
diff --git a/docs/acceptance/snapshot-budget.md b/docs/acceptance/snapshot-budget.md
new file mode 100644
index 0000000000..18f81233de
--- /dev/null
+++ b/docs/acceptance/snapshot-budget.md
@@ -0,0 +1,112 @@
+# #7259 快照整体预算与降级验收
+
+范围:发送前与轮末快照的整体预算、Git 取消、失败后的回退缺口证据。远端关闭竞态 / Windows
+`EBUSY` 恢复、流式解析和超限冷却不在本次实现范围内。
+
+## 本轮 review
+
+2026-10-26 复查当前工作区改动,未发现新的确定性 P0 / P1。重点检查:
+
+- 预算包括意图落盘、目录探测、排队、过滤、暂存、标签和 ref 发布,阶段之间不重置。
+- 发送 reservation 的取消信号贯穿准备阶段,最终派发前仍检查取消;排队过期不能迟到执行。
+- Git 清理完成之前不放行同仓库写队列;无法确认清理时隔离受影响仓库,不重建设备连接。
+- 每次执行有独立持久标识,旧成功不能覆盖同一消息的新失败;重读记录后仍保守降级。
+- 自动保存使用临时 index 和隐藏 ref,不修改用户 HEAD、分支、暂存区。
+
+保留的边界:原生文件系统请求不能强杀,只停止等待并拦截后续动作;意图记录本身写入失败
+会拒绝派发,记录成功后的 Git 失败才继续发送。记录读取超时、损坏或超过 10000 条时仅回退
+消息。文件 flush / 重建 store 的验证不等于掉电恢复验证。
+
+## 可重复运行的本机验收
+
+根目录执行(需要已有开发依赖和 Git):
+
+```sh
+pnpm --dir apps/desktop exec vite-node --config vitest.config.ts scripts/snapshot-budget-acceptance.ts --files=10000
+pnpm --dir apps/desktop exec vite-node --config vitest.config.ts scripts/snapshot-budget-acceptance.ts --files=100000
+pnpm --dir apps/desktop exec vite-node --config vitest.config.ts scripts/snapshot-budget-acceptance.ts --files=1000000
+```
+
+脚本调用真实 coordinator、目录探测、快照内核、意图记录、Git 子进程和回退规划入口。
+Electron 使用现有测试 stub,标签使用固定结果;不启动应用、不调用模型、不使用账号。
+这验证快照准备链路,不代表完成了真实 UI / provider / device-link 端到端验收。
+
+所有数据位于 `os.tmpdir()` 下唯一目录,默认自动清理;百万文件的创建和删除可能需要数分钟。
+加 `--keep` 会打印并保留临时目录,用于下节实机操作。只在确认打印出的路径是此次唯一临时
+目录后清理,不能对正式工作目录或账号目录执行删除。
+
+通过条件:
+
+1. 大仓库快照正常完成或降级返回:8 秒工作预算 + 最多 3 秒 Git 清理,脚本断言另容许
+ 1 秒计时 / 调度余量。统计从 `onTurnStart` 调用到返回,不包含造数据和模型响应。
+2. 同时运行的小仓库成功生成基线,且不等大仓库预算耗尽。
+3. 大仓库的 HEAD、用户 index 字节哈希和已有 seed 文件内容不变。
+4. 同消息成功后再写入一个没有 Git 完成证据的执行意图;重建 store 后规划为
+ `conversation-only`,不能误用旧成功。此项模拟的是持久层重新读取,不是完整应用重启。
+5. 对真实等待 stdin 的 `git hash-object --stdin` 发取消,返回时 PID 已消失。
+
+### Windows 本轮结果
+
+环境:XD-PC,Node v24.14.1;每档一次,非统计意义的 p95。
+
+| 未跟踪文件数 | 大仓库准备 | 并发小仓库 | 大仓库结果 | 真实 Git 取消清理 |
+| --- | --- | --- | --- | --- |
+| 10000 | 5426 ms | 365 ms | 基线成功 | 1350 ms |
+| 100000 | 8001 ms | 388 ms | 超时降级,无基线 | 1279 ms |
+| 1000000 | 2367 ms | 388 ms | 提前降级,无基线 | 1301 ms |
+
+三档均通过 HEAD / index / seed 保持、持久记录重读后缺口识别和真实 PID 退出断言。
+百万档造数耗时 214.18 秒,不计入快照预算;提前降级不能解读为扫描吞吐提升。该次输出只保留
+了警告名称,没有错误细节,不能单凭耗时判定具体在哪个阶段失败。脚本现已同时输出错误原因。
+
+## 自动回归
+
+本轮已执行:
+
+- Desktop 9 个定向文件:1088 条通过,18.01 秒;覆盖 coordinator、host、planner、rewind、
+ makerSendTransaction、AgentInputCoordinator、gitExec、detectCwd、worktree 创建。
+- 真实 Git 4 个文件:66 条通过、2 条既有能力跳过,32.92 秒;覆盖 shadow 保存点、过滤、
+ bootstrap、旧保存点内核。
+- maker-core reservation / close / origin:148 条通过;取消后无迟到 provider 派发。
+- Desktop 类型检查通过;测试卫生、开发文档合同通过。
+
+关键回归可单独复跑:
+
+```sh
+pnpm --dir apps/desktop exec vitest run src/main/__tests__/gitSnapshotCoordinator.test.ts src/main/__tests__/gitSnapshotHost.test.ts src/main/__tests__/codexFileRewindPlanner.test.ts src/main/maker-ipc/__tests__/makerSendTransaction.test.ts src/main/worktree/__tests__/gitExec.test.ts --maxWorkers=2
+pnpm --dir apps/desktop exec vitest run --project=git-integration src/main/__tests__/gitSnapshotShadow.git-integration.test.ts --maxWorkers=1
+pnpm --dir packages/maker-core exec vitest run src/session-control.test.ts src/session.close.test.ts src/session.origin.test.ts --maxWorkers=2
+```
+
+意图写入失败 / 挂起、探测 / bootstrap / 排队 / label 卡住、停止 / 关闭、无法确认树清理等
+故障使用依赖注入和虚拟时钟覆盖。不要为验收去塞满系统盘、破坏真实账号记录或杀正式进程。
+
+## 尚需实机验收
+
+使用[隔离 Desktop](../dev-rules/desktop-development.md),从本 worktree 启动:
+
+```sh
+pnpm restart:desktop:remote -- --isolated=@worktree
+```
+
+必须看到 `DESKTOP_DEV_VERDICT=ready`,登录测试账号并开启自动快照;`--mock` 不能代替真实
+发送验收。不要重启承载当前会话的正式 Cindy。手机与第二台 Desktop 都连接这个隔离实例。
+
+先运行造数脚本并加 `--keep`,把打印目录中的 `large` / `small` 作为两个测试任务的工作目录。
+只操作测试文件;用 Codex / Pi 或明确走保存点回退链的运行方式。
+
+| 场景 | 操作 | 验收判据 |
+| --- | --- | --- |
+| 超时后继续发送 | 手机向大仓库任务发送一次“只回复 OK” | 只有一次派发;快照准备不无限等待;区分快照耗时、网络耗时和模型首字耗时 |
+| Stop 不迟到 | 在大仓库准备期间点停止,等待超过 11 秒后再看 | 没有迟到模型回复或重复执行;再发送新消息能继续 |
+| 关闭不迟到 | 准备期间关闭测试任务,再重新打开 | 旧准备工作不会补发;新发送独立执行 |
+| 多任务与多设备 | 大仓库准备时,另一 Desktop 向小仓库任务发消息;手机切换任务 | 小仓库能正常回复;两个控制端没有被整体断开或要求重连 |
+| 同消息失败重试 + 重启 | 小仓库先成功执行一次;将保留 fixture 的 `large/bulk` 移入测试用 `small`,对原消息重试;出现快照降级后重启隔离实例并尝试回退 | 涉及失败执行的范围只能回退消息,文件保持;不能被第一次成功快照掩盖 |
+| 正常回退仍可用 | 独立的小仓库任务让模型修改一个测试文件,完成后回退 | 文件恢复正确;不能把所有回退都降级来“通过”异常用例 |
+
+记录每次 clientId / 任务、操作时间、准备与派发次数、界面结果和日志;同一设备内用单调时钟
+比较耗时,不相减跨设备墙钟。Stop 场景若已进入 provider 执行,不能当作“发送前取消”证据,
+需要重做并确认停在快照准备阶段。
+
+以上完整 UI、手机 + 第二控制端、完整应用重启及 macOS 真实进程清理本轮未验证。
+建议作为合并前实机验收项;自动化和 Windows 内核测试通过不能替代这些结论。
diff --git a/docs/dev-rules/development-workflow.md b/docs/dev-rules/development-workflow.md
index a059a03456..70925b2bb1 100644
--- a/docs/dev-rules/development-workflow.md
+++ b/docs/dev-rules/development-workflow.md
@@ -10,6 +10,11 @@ worktree 会话契约、直推 `main` 的额外门禁与 review 严重度口径
## 1. Dogfooding:在本仓 worktree 会话里工作
+Cindy 创建或重建托管 worktree 时,会尽力向 Git 本地 `info/exclude` 追加所用托管目录的
+根级排除规则,避免基础仓库的未跟踪扫描进入这些目录。保留已有规则,不修改项目
+`.gitignore`,不影响已跟踪文件;写入失败不阻止创建或恢复。不扫描、排除任意第三方目录。
+实现见 `apps/desktop/src/main/worktree/managedWorktreeExclude.ts`。
+
如果你是 Cindy 内嵌的 agent,且 cwd 位于 `<baseRepo>/.cindy-worktrees/<name>`(或迁移前的
`.xdt-worktrees/<name>`)下(会话级 git worktree),遵守以下契约:
diff --git a/docs/dev-rules/remote-and-mobile-adaptation.md b/docs/dev-rules/remote-and-mobile-adaptation.md
index 5c9bd2e96c..d7c468fbc0 100644
--- a/docs/dev-rules/remote-and-mobile-adaptation.md
+++ b/docs/dev-rules/remote-and-mobile-adaptation.md
@@ -608,6 +608,32 @@ Debug 日志区分两层耗时:
性能复测应同时包含前台发送、另一控制端刷新与补读、本地读取;分别报告请求数量和延迟,
不能把内存数据库基准当成真机网络端到端改善。
+自动 Git 保存点的发送前基线和轮末保存各有一份 **8 秒整体预算**,包括元数据、目录探测、
+空项目初始化、仓库队列等待、文件过滤、暂存、标签和隐藏 ref 写入。嵌套操作共享同一单调
+时钟 deadline;Git 超时或主动取消后另留最多 3 秒进程树清理预算。超时继续发送;Stop
+通过发送 reservation / 输入队列 / 目标续跑的取消信号终止准备,不能迟到派发。原生文件系统
+请求无法强杀,停止等待后丢弃结果,并在后续写入前检查取消;临时文件由原操作清理。
+
+故障限于当前保存点;不能因此重建设备连接或重试发送。Git 清理无法确认时,本进程暂停该
+仓库后续保存点与文件回退写入,其它仓库照常工作。回退不仅看缺口标记,还要求范围内每条
+用户消息有完成证据、已记录的 shadow 基线均有对应完成点;未变化的自动轮次也写完成点,
+被过滤路径发生变化时不发布完成点。旧历史缺少证据时保守降级为仅回退消息。
+同一消息的每次执行在 Git 操作之前写入独立、不可覆盖的派发意图,保存点以可选的
+`X-Cindy-Attempt` trailer 绑定该标识。回退逐个核对所选消息的全部意图,基线与缺口标记均
+写入失败也能识别,后续成功不能抹掉中间失败。意图落盘也占用上述 8 秒预算;意图无法
+写入或超时时拒绝本次派发,迟到写入只能留下保守缺口,不能重新发送。意图写成之后的
+Git 故障仍按原约定继续发送。这是安全降级与无法确认派发记录两类失败的区别。
+
+意图仅存 UUID 和消息锚点,位于当前账号的
+`owners/<owner-key>/git-snapshot-attempts/<sha256(sessionId)>/<attempt-uuid>.json`,
+用独占新建与 flush 写入,不依赖内存、不改用户仓库或数据库 schema。账号和目录在异步
+操作前捕获,切账号后不放行发送。记录作为回退安全证据随账号数据保留,不按成功轮次
+清除失败意图。读取限 8 秒、每条 4 KiB、每个任务 10000 条;损坏、读取失败或超限一律
+降级为仅回退消息,不能当成空历史。旧版本忽略新增 trailer,但不具备这一逐次核对保障。
+实现见 `gitSnapshotCoordinator.ts`、`utils/operationBudget.ts`、`worktree/gitExec.ts`;回归见
+`gitSnapshotCoordinator.test.ts`、`gitExec.test.ts`、`gitSnapshotShadow.git-integration.test.ts`、
+`codexFileRewindPlanner.test.ts` 与 maker-core `session-control.test.ts`。
+
远程发送的端到端耗时按同一 clientId(只记前 8 位)在三端分别记 debug 日志,各端只用本机时钟:
- 被控端 `remote enqueue timing`:enqueue handler 内 `gate`(准入与清除边界)、`restore`、
diff --git a/packages/lizi-mcps/src/browser/recipe-loader.ts b/packages/lizi-mcps/src/browser/recipe-loader.ts
index 8e3dbfbd79..8a4e988ac3 100644
--- a/packages/lizi-mcps/src/browser/recipe-loader.ts
+++ b/packages/lizi-mcps/src/browser/recipe-loader.ts
@@ -1,3 +1,5 @@
+/// <reference path="../vite-env.d.ts" />
+
/**
* Site Recipe + SiteGuide registry.
*
diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-native-auto-compact.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-native-auto-compact.test.ts
index e84f01a802..20519c22f5 100644
--- a/packages/maker-core/src/agents/pi/__tests__/pi-native-auto-compact.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/pi-native-auto-compact.test.ts
@@ -636,7 +636,7 @@ describe("PiAgent native auto-compaction ownership", () => {
},
);
- function readLatestPiSettings(): { compaction?: { reserveTokens?: number }; skills?: string[]; packages?: Array<{ source: string; skills?: string[] }> } {
+ function readLatestPiSettings(): { compaction?: { reserveTokens?: number; modelOverrides?: Record<string, { reserveTokens?: number }> }; skills?: string[]; packages?: Array<{ source: string; skills?: string[] }> } {
const files: string[] = [];
const walk = (dir: string): void => {
for (const entry of readdirSync(dir, { withFileTypes: true })) {
@@ -648,7 +648,7 @@ describe("PiAgent native auto-compaction ownership", () => {
walk(agentHome);
expect(files.length).toBeGreaterThan(0);
return JSON.parse(readFileSync(files[files.length - 1]!, "utf8")) as {
- compaction?: { reserveTokens?: number };
+ compaction?: { reserveTokens?: number; modelOverrides?: Record<string, { reserveTokens?: number }> };
};
}
diff --git a/packages/maker-core/src/session-control.test.ts b/packages/maker-core/src/session-control.test.ts
index 0e929ac063..7d54eb6e53 100644
--- a/packages/maker-core/src/session-control.test.ts
+++ b/packages/maker-core/src/session-control.test.ts
@@ -111,6 +111,28 @@ function waitForSessionEvent(session: Session, type: AgentEvent['type']): Promis
}
describe('Session graceful-stop control state', () => {
+ // #7259: pre-dispatch snapshots need the reservation's cancellation signal.
+ // Unit tier; a suspended acceptance hook exposes the missing cancellation.
+ it('aborts acceptance preparation and never dispatches after Stop', async () => {
+ const stub = createHandle();
+ const sendSpy = vi.spyOn(stub.handle, 'send');
+ const session = createSession(stub);
+ let entered!: () => void;
+ const started = new Promise<void>((resolve) => { entered = resolve; });
+ let preparationSignal: AbortSignal | undefined;
+ const send = session.send('prepare snapshot', {
+ onAccepted: async (signal) => {
+ preparationSignal = signal;
+ entered();
+ await new Promise<void>((resolve) => signal!.addEventListener('abort', () => resolve(), { once: true }));
+ },
+ });
+ await started;
+ await session.abort();
+ expect(preparationSignal?.aborted).toBe(true);
+ await expect(send).resolves.toEqual({ accepted: false, reason: 'cancelled-before-dispatch' });
+ expect(sendSpy).not.toHaveBeenCalled();
+ });
it('cancels and joins a pre-acceptance send reservation before reporting stop requested', async () => {
const stub = createHandle();
let running = false;
diff --git a/packages/maker-core/src/session.ts b/packages/maker-core/src/session.ts
index 7560f3efd0..824f1c0ced 100644
--- a/packages/maker-core/src/session.ts
+++ b/packages/maker-core/src/session.ts
@@ -344,7 +344,9 @@ export interface SessionSendOptions extends SendOptions {
* Session 在 active/running 守卫通过、turn reservation 建立后调用;
* hook 完成后才启动 vendor handle。
*/
- onAccepted?: () => void | Promise<void>;
+ // Reservation cancellation reaches host preparation (for example Git
+ // snapshots); returning from a cancelled hook never authorizes dispatch.
+ onAccepted?: (signal?: AbortSignal) => void | Promise<void>;
/** Reservation 建立后立刻回调本轮 turn generation;host 必须用它绑定 leftover,不能等 send 返回后再读最新 generation。 */
onTurnReserved?: (turnGeneration: number) => void;
/**
@@ -950,7 +952,7 @@ export class Session {
if (beforeProviderStart) await beforeProviderStart();
const cancelledBeforeAcceptance = finishCancelledBeforeDispatch();
if (cancelledBeforeAcceptance !== null) return cancelledBeforeAcceptance;
- await onAccepted?.();
+ await onAccepted?.(reservation.abortController.signal);
this.ensureActive();
const cancelledAfterAcceptance = finishCancelledBeforeDispatch();
if (cancelledAfterAcceptance !== null) return cancelledAfterAcceptance;