Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 安全合并重叠的 Codex 变更
DavidShen98544f41c624
diff --git a/apps/desktop/src/main/turn-change-set/__tests__/store.git-integration.test.ts b/apps/desktop/src/main/turn-change-set/__tests__/store.git-integration.test.tsindex 528cfe3d00..846ea5feea 100644--- a/apps/desktop/src/main/turn-change-set/__tests__/store.git-integration.test.ts+++ b/apps/desktop/src/main/turn-change-set/__tests__/store.git-integration.test.ts@@ -121,6 +121,43 @@ describe('turn change-set sidecar store', () => {});});+ it('marks a safely composed Codex subset partial when another file conflict was omitted', async () => {+ await beginTurnChangeSet({+ sessionId: 'session-1',+ anchorClientId: 'user-1',+ provider: 'codex',+ cwd: workdir,+ });+ noteTurnDiffEvent('session-1', {+ type: 'turn_diff',+ source: 'codex',+ data: {+ turnId: 'turn-partial-compose',+ cwd: workdir,+ isComplete: false,+ diff: [+ 'diff --git a/safe.ts b/safe.ts',+ '--- a/safe.ts',+ '+++ b/safe.ts',+ '@@ -1 +1 @@',+ '-old',+ '+new',+ '',+ ].join('\n'),+ },+ });+ finalizeTurnChangeSet('session-1', 'turn-partial-compose', 'complete');++ await vi.waitFor(async () => expect(await listTurnChangeSets('session-1')).toHaveLength(1));+ const [summary] = await listTurnChangeSets('session-1');+ expect(summary).toMatchObject({+ state: 'partial',+ incompleteReasons: ['provider-diff-conflict'],+ isReversible: true,+ fileCount: 1,+ });+ });+it('serializes exact captures for sessions sharing one workspace', async () => {const target = path.join(workdir, 'shared.txt');await fs.writeFile(target, 'old\n', 'utf8');@@ -211,6 +248,40 @@ describe('turn change-set sidecar store', () => {expect(reapply.summary.workspaceState).toBe('applied');});+ it('keeps a zero-context deletion reviewable without offering unsafe actions', async () => {+ const target = path.join(workdir, 'a.ts');+ await fs.writeFile(target, 'head\ntail\n', 'utf8');+ await beginTurnChangeSet({+ sessionId: 'session-1',+ anchorClientId: 'user-1',+ provider: 'codex',+ cwd: workdir,+ });+ noteTurnDiffEvent('session-1', {+ type: 'turn_diff',+ source: 'codex',+ data: {+ turnId: 'turn-zero-context-delete',+ cwd: workdir,+ diff: [+ 'diff --git a/a.ts b/a.ts',+ '--- a/a.ts',+ '+++ b/a.ts',+ '@@ -2 +1,0 @@',+ '-old',+ '',+ ].join('\n'),+ },+ });+ await finalizeTurnChangeSet('session-1', 'turn-zero-context-delete', 'complete');+ const [recorded] = await listTurnChangeSets('session-1');++ expect(recorded).toMatchObject({ isReversible: false, fileCount: 1 });+ await expect(applyTurnChangeSetAction('session-1', recorded!.id, 'undo'))+ .rejects.toMatchObject({ kind: 'unsupported' });+ expect(await fs.readFile(target, 'utf8')).toBe('head\ntail\n');+ });+it('reports a missing Git executable without changing the workspace', async () => {const target = path.join(workdir, 'missing-git.ts');await fs.writeFile(target, 'new\n', 'utf8');diff --git a/apps/desktop/src/main/turn-change-set/store.ts b/apps/desktop/src/main/turn-change-set/store.tsindex b6c750b239..e1ec1b5674 100644--- a/apps/desktop/src/main/turn-change-set/store.ts+++ b/apps/desktop/src/main/turn-change-set/store.ts@@ -92,6 +92,7 @@ const INCOMPLETE_REASONS = new Set<TurnChangeIncompleteReason>(['sensitive-file','read-failed','diff-too-large',+ 'provider-diff-conflict','turn-failed',]);const FILE_STATUSES = new Set<FileDiff['status']>([@@ -263,6 +264,14 @@ function isReversiblePatch(value: PersistedTurnChangeSetV1): boolean {if (diff.oldPath && !safeRelativeTarget(value.cwd, diff.oldPath)) return false;if (diff.status === 'renamed' && !diff.oldPath) return false;if (diff.status === 'modified' && diff.hunks.length === 0) return false;+ // A zero-context insertion/deletion inside an existing file cannot prove+ // that its location stayed attached to the same surrounding content after+ // unrelated line shifts. Whole-file add/delete remains safe because Git+ // validates the file's existence or complete contents.+ if (+ (diff.status === 'modified' || diff.status === 'renamed')+ && diff.hunks.some((hunk) => hunk.oldLines === 0 || hunk.newLines === 0)+ ) return false;if ((diff.status === 'added' || diff.status === 'deleted') && diff.hunks.length === 0) {return false;}@@ -980,6 +989,8 @@ export function noteTurnDiffEvent(sessionId: string, event: AgentEvent): void {if (pending.incompleteReasons.has('remote-session')) return;if (pending.providerTurnId && pending.providerTurnId !== data.turnId) return;pending.providerTurnId = data.turnId;+ if (data.isComplete === false) addIncompleteReason(pending, 'provider-diff-conflict');+ else pending.incompleteReasons.delete('provider-diff-conflict');pending.incompleteReasons.delete('sensitive-file');pending.incompleteReasons.delete('diff-too-large');const safeDiff = filterSensitiveDiffBlocks(pending, data.diff);diff --git a/apps/desktop/src/shared/turnChangeSet.ts b/apps/desktop/src/shared/turnChangeSet.tsindex 50ebfee6d7..c67846cd11 100644--- a/apps/desktop/src/shared/turnChangeSet.ts+++ b/apps/desktop/src/shared/turnChangeSet.ts@@ -15,6 +15,7 @@ export type TurnChangeIncompleteReason =| 'sensitive-file'| 'read-failed'| 'diff-too-large'+ | 'provider-diff-conflict'| 'turn-failed';export interface TurnChangeFileSummary {diff --git a/packages/maker-core/package.json b/packages/maker-core/package.jsonindex 9dc27bc161..4897da3eaf 100644--- a/packages/maker-core/package.json+++ b/packages/maker-core/package.json@@ -24,6 +24,7 @@"@anthropic-ai/claude-agent-sdk": "0.2.112","@anthropic-ai/sdk": "^0.91.1","@cindy/maker-shared": "workspace:*",+ "diff": "^8.0.4","gray-matter": "^4.0.3"},"peerDependencies": {diff --git a/packages/maker-core/src/agents/codex/index.test.ts b/packages/maker-core/src/agents/codex/index.test.tsindex 001a129607..7fd9270267 100644--- a/packages/maker-core/src/agents/codex/index.test.ts+++ b/packages/maker-core/src/agents/codex/index.test.ts@@ -2,6 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import path from 'node:path';import os from 'node:os';import { promises as fs } from 'node:fs';+import { applyPatch, formatPatch, parsePatch, reversePatch } from 'diff';import { CodexAgent } from './index.js';import { Method } from './app-server/protocol.js';@@ -19294,6 +19295,288 @@ describe('CodexAgent context window reporting', () => {await handle.close();});+ it('composes overlapping descendant hunks into the final same-file patch', async () => {+ const agent = new CodexAgent(createDeps());+ const host = installFakeHost(agent);+ const handle = await agent.startSession({+ sessionId: 'session-overlapping-file-diff',+ model: 'gpt-5.4',+ workingDir: '/repo',+ });+ const events: AgentEvent[] = [];+ void (async () => {+ for await (const event of handle.events()) events.push(event);+ })();+ const handlers = host.getThreadHandlers();+ if (!handlers?.descendantThreadStarted || !handlers.descendantNotification) {+ throw new Error('expected descendant handlers');+ }++ handlers.turnStarted?.({ threadId: 'start-thread-id', turn: { id: 'turn-overlap' } });+ handlers.turnDiffUpdated?.({+ threadId: 'start-thread-id',+ turnId: 'turn-overlap',+ diff: 'diff --git a/shared.txt b/shared.txt\nindex 1111111..2222222 100644\n--- a/shared.txt\n+++ b/shared.txt\n@@ -2,2 +2,2 @@\n-old-b\n+root-b\n tail',+ });+ handlers.descendantThreadStarted({+ thread: { id: 'child-overlap', parentThreadId: 'start-thread-id' },+ });+ handlers.descendantNotification('child-overlap', 'turn/diff/updated', {+ threadId: 'child-overlap',+ turnId: 'child-overlap-turn',+ diff: 'diff --git a/shared.txt b/shared.txt\nindex 2222222..3333333 100644\n--- a/shared.txt\n+++ b/shared.txt\n@@ -1,3 +1,3 @@\n head\n-root-b\n+child-b\n tail',+ });++ await vi.waitFor(() => {+ const last = events.filter((event) => event.type === 'turn_diff').at(-1);+ const data = last?.data as { diff?: string; isComplete?: boolean } | undefined;+ expect(data?.isComplete).toBe(true);+ expect(data?.diff).toContain('-old-b');+ expect(data?.diff).toContain('+child-b');+ });+ const merged = (events.filter((event) => event.type === 'turn_diff').at(-1)?.data as { diff: string }).diff;+ expect((merged.match(/^diff --git /gm) ?? []).length).toBe(1);+ expect((merged.match(/^@@ /gm) ?? []).length).toBe(1);+ expect(merged).not.toContain('index ');+ expect(merged).not.toContain('root-b');+ expect(merged).toContain(' head');+ expect(merged).toContain(' tail');+ const original = 'head\nold-b\ntail\n';+ const applied = applyPatch(original, merged);+ expect(applied).toBe('head\nchild-b\ntail\n');+ expect(applyPatch(applied as string, formatPatch(reversePatch(parsePatch(merged))))).toBe(original);++ await handle.close();+ });++ it('composes an overlapping pure deletion at the preimage line', async () => {+ const agent = new CodexAgent(createDeps());+ const host = installFakeHost(agent);+ const handle = await agent.startSession({+ sessionId: 'session-overlapping-delete-diff',+ model: 'gpt-5.4',+ workingDir: '/repo',+ });+ const events: AgentEvent[] = [];+ void (async () => {+ for await (const event of handle.events()) events.push(event);+ })();+ const handlers = host.getThreadHandlers();+ if (!handlers?.descendantThreadStarted || !handlers.descendantNotification) {+ throw new Error('expected descendant handlers');+ }++ handlers.turnStarted?.({ threadId: 'start-thread-id', turn: { id: 'turn-overlap-delete' } });+ handlers.turnDiffUpdated?.({+ threadId: 'start-thread-id',+ turnId: 'turn-overlap-delete',+ diff: 'diff --git a/shared.txt b/shared.txt\n--- a/shared.txt\n+++ b/shared.txt\n@@ -2 +2 @@\n-old\n+root',+ });+ handlers.descendantThreadStarted({+ thread: { id: 'child-overlap-delete', parentThreadId: 'start-thread-id' },+ });+ handlers.descendantNotification('child-overlap-delete', 'turn/diff/updated', {+ threadId: 'child-overlap-delete',+ turnId: 'child-overlap-delete-turn',+ diff: 'diff --git a/shared.txt b/shared.txt\n--- a/shared.txt\n+++ b/shared.txt\n@@ -2 +1,0 @@\n-root',+ });++ await vi.waitFor(() => {+ const last = events.filter((event) => event.type === 'turn_diff').at(-1);+ expect((last?.data as { isComplete?: boolean } | undefined)?.isComplete).toBe(true);+ });+ const merged = (events.filter((event) => event.type === 'turn_diff').at(-1)?.data as { diff: string }).diff;+ expect(merged).toContain('@@ -2 +1,0 @@');+ const original = 'head\nold\ntail\n';+ const applied = applyPatch(original, merged);+ expect(applied).toBe('head\ntail\n');+ expect(applyPatch(applied as string, formatPatch(reversePatch(parsePatch(merged))))).toBe(original);+ expect(merged).not.toContain('root');++ await handle.close();+ });++ it('composes an overlapping pure insertion at the preimage boundary', async () => {+ const agent = new CodexAgent(createDeps());+ const host = installFakeHost(agent);+ const handle = await agent.startSession({+ sessionId: 'session-overlapping-insert-diff',+ model: 'gpt-5.4',+ workingDir: '/repo',+ });+ const events: AgentEvent[] = [];+ void (async () => {+ for await (const event of handle.events()) events.push(event);+ })();+ const handlers = host.getThreadHandlers();+ if (!handlers?.descendantThreadStarted || !handlers.descendantNotification) {+ throw new Error('expected descendant handlers');+ }++ handlers.turnStarted?.({ threadId: 'start-thread-id', turn: { id: 'turn-overlap-insert' } });+ handlers.turnDiffUpdated?.({+ threadId: 'start-thread-id',+ turnId: 'turn-overlap-insert',+ diff: 'diff --git a/shared.txt b/shared.txt\n--- a/shared.txt\n+++ b/shared.txt\n@@ -1,0 +2 @@\n+root',+ });+ handlers.descendantThreadStarted({+ thread: { id: 'child-overlap-insert', parentThreadId: 'start-thread-id' },+ });+ handlers.descendantNotification('child-overlap-insert', 'turn/diff/updated', {+ threadId: 'child-overlap-insert',+ turnId: 'child-overlap-insert-turn',+ diff: 'diff --git a/shared.txt b/shared.txt\n--- a/shared.txt\n+++ b/shared.txt\n@@ -2 +2 @@\n-root\n+child',+ });++ await vi.waitFor(() => {+ const last = events.filter((event) => event.type === 'turn_diff').at(-1);+ expect((last?.data as { isComplete?: boolean } | undefined)?.isComplete).toBe(true);+ });+ const merged = (events.filter((event) => event.type === 'turn_diff').at(-1)?.data as { diff: string }).diff;+ expect(merged).toContain('@@ -1,0 +2 @@');+ const original = 'head\ntail\n';+ const applied = applyPatch(original, merged);+ expect(applied).toBe('head\nchild\ntail\n');+ expect(applyPatch(applied as string, formatPatch(reversePatch(parsePatch(merged))))).toBe(original);++ await handle.close();+ });++ it('maps a non-overlapping pure deletion across an earlier insertion', async () => {+ const agent = new CodexAgent(createDeps());+ const host = installFakeHost(agent);+ const handle = await agent.startSession({+ sessionId: 'session-shifted-delete-diff',+ model: 'gpt-5.4',+ workingDir: '/repo',+ });+ const events: AgentEvent[] = [];+ void (async () => {+ for await (const event of handle.events()) events.push(event);+ })();+ const handlers = host.getThreadHandlers();+ if (!handlers?.descendantThreadStarted || !handlers.descendantNotification) {+ throw new Error('expected descendant handlers');+ }++ handlers.turnStarted?.({ threadId: 'start-thread-id', turn: { id: 'turn-shifted-delete' } });+ handlers.turnDiffUpdated?.({+ threadId: 'start-thread-id',+ turnId: 'turn-shifted-delete',+ diff: 'diff --git a/shared.txt b/shared.txt\n--- a/shared.txt\n+++ b/shared.txt\n@@ -1 +1,2 @@\n+inserted\n line-1',+ });+ handlers.descendantThreadStarted({+ thread: { id: 'child-shifted-delete', parentThreadId: 'start-thread-id' },+ });+ handlers.descendantNotification('child-shifted-delete', 'turn/diff/updated', {+ threadId: 'child-shifted-delete',+ turnId: 'child-shifted-delete-turn',+ diff: 'diff --git a/shared.txt b/shared.txt\n--- a/shared.txt\n+++ b/shared.txt\n@@ -20 +19,0 @@\n-remove-me',+ });++ await vi.waitFor(() => {+ const last = events.filter((event) => event.type === 'turn_diff').at(-1);+ expect((last?.data as { isComplete?: boolean } | undefined)?.isComplete).toBe(true);+ });+ const merged = (events.filter((event) => event.type === 'turn_diff').at(-1)?.data as { diff: string }).diff;+ const original = `${Array.from({ length: 18 }, (_, index) => `line-${index + 1}`).join('\n')}\nremove-me\n`;+ const expected = `inserted\n${Array.from({ length: 18 }, (_, index) => `line-${index + 1}`).join('\n')}\n`;+ const applied = applyPatch(original, merged);+ expect(applied).toBe(expected);+ expect(applyPatch(applied as string, formatPatch(reversePatch(parsePatch(merged))))).toBe(original);+ expect(merged).toContain('@@ -19 +19,0 @@');++ await handle.close();+ });++ it('marks incompatible overlapping descendant hunks incomplete instead of publishing an invalid patch', async () => {+ const agent = new CodexAgent(createDeps());+ const host = installFakeHost(agent);+ const handle = await agent.startSession({+ sessionId: 'session-conflicting-file-diff',+ model: 'gpt-5.4',+ workingDir: '/repo',+ });+ const events: AgentEvent[] = [];+ void (async () => {+ for await (const event of handle.events()) events.push(event);+ })();+ const handlers = host.getThreadHandlers();+ if (!handlers?.descendantThreadStarted || !handlers.descendantNotification) {+ throw new Error('expected descendant handlers');+ }++ handlers.turnStarted?.({ threadId: 'start-thread-id', turn: { id: 'turn-conflict' } });+ handlers.turnDiffUpdated?.({+ threadId: 'start-thread-id',+ turnId: 'turn-conflict',+ diff: 'diff --git a/shared.txt b/shared.txt\n--- a/shared.txt\n+++ b/shared.txt\n@@ -1 +1 @@\n-old\n+root',+ });+ handlers.descendantThreadStarted({+ thread: { id: 'child-conflict', parentThreadId: 'start-thread-id' },+ });+ handlers.descendantNotification('child-conflict', 'turn/diff/updated', {+ threadId: 'child-conflict',+ turnId: 'child-conflict-turn',+ diff: 'diff --git a/shared.txt b/shared.txt\n--- a/shared.txt\n+++ b/shared.txt\n@@ -1 +1 @@\n-unrelated\n+child',+ });++ await vi.waitFor(() => {+ const last = events.filter((event) => event.type === 'turn_diff').at(-1);+ const data = last?.data as { diff?: string; isComplete?: boolean } | undefined;+ expect(data?.isComplete).toBe(false);+ expect(data?.diff).toBe('');+ });++ await handle.close();+ });++ it('fails closed when same-file composition exceeds the hunk budget', async () => {+ const agent = new CodexAgent(createDeps());+ const host = installFakeHost(agent);+ const handle = await agent.startSession({+ sessionId: 'session-over-budget-diff',+ model: 'gpt-5.4',+ workingDir: '/repo',+ });+ const events: AgentEvent[] = [];+ void (async () => {+ for await (const event of handle.events()) events.push(event);+ })();+ const handlers = host.getThreadHandlers();+ if (!handlers?.descendantThreadStarted || !handlers.descendantNotification) {+ throw new Error('expected descendant handlers');+ }+ const rootHunks = Array.from({ length: 512 }, (_, index) => {+ const line = index * 10 + 1;+ return `@@ -${line} +${line} @@\n-old-${index}\n+root-${index}`;+ }).join('\n');++ handlers.turnStarted?.({ threadId: 'start-thread-id', turn: { id: 'turn-over-budget' } });+ handlers.turnDiffUpdated?.({+ threadId: 'start-thread-id',+ turnId: 'turn-over-budget',+ diff: `diff --git a/shared.txt b/shared.txt\n--- a/shared.txt\n+++ b/shared.txt\n${rootHunks}`,+ });+ handlers.descendantThreadStarted({+ thread: { id: 'child-over-budget', parentThreadId: 'start-thread-id' },+ });+ handlers.descendantNotification('child-over-budget', 'turn/diff/updated', {+ threadId: 'child-over-budget',+ turnId: 'child-over-budget-turn',+ diff: 'diff --git a/shared.txt b/shared.txt\n--- a/shared.txt\n+++ b/shared.txt\n@@ -6000 +6000 @@\n-old-child\n+child',+ });++ await vi.waitFor(() => {+ const last = events.filter((event) => event.type === 'turn_diff').at(-1);+ const data = last?.data as { diff?: string; isComplete?: boolean } | undefined;+ expect(data?.isComplete).toBe(false);+ expect(data?.diff).toBe('');+ });++ await handle.close();+ });+it('clears an empty descendant snapshot from the merged turn diff', async () => {const agent = new CodexAgent(createDeps());const host = installFakeHost(agent);diff --git a/packages/maker-core/src/agents/codex/index.ts b/packages/maker-core/src/agents/codex/index.tsindex 2915b3851f..18542fa09b 100644--- a/packages/maker-core/src/agents/codex/index.ts+++ b/packages/maker-core/src/agents/codex/index.ts@@ -23,6 +23,7 @@import os from 'node:os';import path from 'node:path';import { promises as fs } from 'node:fs';+import { structuredPatch } from 'diff';import {BaseAgent,@@ -1223,6 +1224,268 @@ export async function toAppServerInput(return inputs;}+interface ParsedTurnDiffHunk {+ raw: string;+ section: string;+ oldStart: number;+ oldCount: number;+ newStart: number;+ newCount: number;+ lines: string[];+ oldLines: string[];+ newLines: string[];+}++type CanonicalTurnDiffHunk = ParsedTurnDiffHunk;++interface ComposedTurnDiffBlock {+ block: string;+ complete: boolean;+}++const MAX_TURN_DIFF_COMPOSE_LINES = 20_000;+const MAX_TURN_DIFF_COMPOSE_HUNKS = 512;+const TURN_DIFF_COMPOSE_TIMEOUT_MS = 50;++function parseTurnDiffHunk(raw: string): ParsedTurnDiffHunk | null {+ const normalized = raw.replace(/\n+$/, '');+ const lineBreak = normalized.indexOf('\n');+ const header = lineBreak >= 0 ? normalized.slice(0, lineBreak) : normalized;+ const match = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@(.*)$/.exec(header);+ if (!match) return null;+ const lines = lineBreak >= 0 ? normalized.slice(lineBreak + 1).split('\n') : [];+ const oldLines: string[] = [];+ const newLines: string[] = [];+ for (const line of lines) {+ if (line.startsWith('\\')) return null;+ const prefix = line[0];+ const content = line.slice(1);+ if (prefix === ' ' || prefix === '-') oldLines.push(content);+ if (prefix === ' ' || prefix === '+') newLines.push(content);+ if (prefix !== ' ' && prefix !== '-' && prefix !== '+') return null;+ }+ const oldCount = match[2] === undefined ? 1 : Number(match[2]);+ const newCount = match[4] === undefined ? 1 : Number(match[4]);+ if (oldLines.length !== oldCount || newLines.length !== newCount) return null;+ return {+ raw: normalized,+ section: match[5] ?? '',+ oldStart: Number(match[1]),+ oldCount,+ newStart: Number(match[3]),+ newCount,+ lines,+ oldLines,+ newLines,+ };+}++function formatTurnDiffRange(start: number, count: number): string {+ return count === 1 ? String(start) : `${start},${count}`;+}++function serializeTurnDiffHunk(hunk: CanonicalTurnDiffHunk): string {+ const header = `@@ -${formatTurnDiffRange(hunk.oldStart, hunk.oldCount)} +${formatTurnDiffRange(hunk.newStart, hunk.newCount)} @@${hunk.section}`;+ return hunk.lines.length > 0 ? `${header}\n${hunk.lines.join('\n')}` : header;+}++function turnDiffHunksOverlap(+ hunk: CanonicalTurnDiffHunk,+ start: number,+ count: number,+): boolean {+ const hunkEnd = hunk.newStart + hunk.newCount;+ const incomingEnd = start + count;+ if (count === 0) return start >= hunk.newStart && start <= hunkEnd;+ if (hunk.newCount === 0) return hunk.newStart >= start && hunk.newStart <= incomingEnd;+ return Math.max(hunk.newStart, start) < Math.min(hunkEnd, incomingEnd);+}++function mapCurrentTurnDiffPositionToBase(+ position: number,+ hunks: readonly CanonicalTurnDiffHunk[],+): number {+ let delta = 0;+ for (const hunk of hunks) {+ if (hunk.newStart + hunk.newCount <= position) {+ delta += hunk.newCount - hunk.oldCount;+ }+ }+ return position - delta;+}++function createCanonicalTurnDiffHunks(+ oldLines: string[],+ newLines: string[],+ oldStart: number,+ newStart: number,+): CanonicalTurnDiffHunk[] | null {+ if (oldLines.length + newLines.length > MAX_TURN_DIFF_COMPOSE_LINES) return null;+ const patch = structuredPatch(+ 'a',+ 'b',+ oldLines.length > 0 ? `${oldLines.join('\n')}\n` : '',+ newLines.length > 0 ? `${newLines.join('\n')}\n` : '',+ '',+ '',+ { context: 3, timeout: TURN_DIFF_COMPOSE_TIMEOUT_MS },+ );+ if (!patch) return null;+ return patch.hunks.map((hunk) => {+ const lines = [...hunk.lines];+ const oldSide: string[] = [];+ const newSide: string[] = [];+ for (const line of lines) {+ const content = line.slice(1);+ if (line[0] === ' ' || line[0] === '-') oldSide.push(content);+ if (line[0] === ' ' || line[0] === '+') newSide.push(content);+ }+ const canonical: CanonicalTurnDiffHunk = {+ raw: '',+ section: '',+ oldStart: oldStart + hunk.oldStart - (hunk.oldLines === 0 ? 2 : 1),+ oldCount: hunk.oldLines,+ newStart: newStart + hunk.newStart - (hunk.newLines === 0 ? 2 : 1),+ newCount: hunk.newLines,+ lines,+ oldLines: oldSide,+ newLines: newSide,+ };+ canonical.raw = serializeTurnDiffHunk(canonical);+ return canonical;+ });+}++function applyTurnDiffHunk(+ current: CanonicalTurnDiffHunk[],+ incoming: ParsedTurnDiffHunk,+ applyStart: number,+): boolean {+ const overlapping = current.filter((hunk) =>+ turnDiffHunksOverlap(hunk, applyStart, incoming.oldCount));+ const delta = incoming.newCount - incoming.oldCount;+ if (overlapping.length === 0) {+ const mappedOldStart = mapCurrentTurnDiffPositionToBase(applyStart, current);+ for (const hunk of current) {+ if (hunk.newStart >= applyStart + incoming.oldCount) hunk.newStart += delta;+ }+ current.push({+ ...incoming,+ oldStart: incoming.oldCount === 0 ? mappedOldStart - 1 : mappedOldStart,+ newStart: incoming.newCount === 0 ? applyStart - 1 : applyStart,+ });+ return current.length <= MAX_TURN_DIFF_COMPOSE_HUNKS;+ }++ overlapping.sort((a, b) => a.newStart - b.newStart);+ const overlappingSet = new Set(overlapping);+ const regionStart = Math.min(applyStart, overlapping[0]!.newStart);+ const regionEnd = Math.max(+ applyStart + incoming.oldCount,+ ...overlapping.map((hunk) => hunk.newStart + hunk.newCount),+ );+ const regionLength = regionEnd - regionStart;+ if (regionLength > MAX_TURN_DIFF_COMPOSE_LINES) return false;+ const currentRegion: Array<string | undefined> = new Array(regionLength);+ const placeLines = (start: number, lines: readonly string[]): boolean => {+ const offset = start - regionStart;+ for (let index = 0; index < lines.length; index += 1) {+ const position = offset + index;+ if (position < 0 || position >= currentRegion.length) return false;+ const existing = currentRegion[position];+ if (existing !== undefined && existing !== lines[index]) return false;+ currentRegion[position] = lines[index];+ }+ return true;+ };+ for (const hunk of overlapping) {+ if (!placeLines(hunk.newStart, hunk.newLines)) return false;+ }+ if (!placeLines(applyStart, incoming.oldLines)) return false;+ if (currentRegion.some((line) => line === undefined)) return false;+ const knownCurrentRegion = currentRegion as string[];++ const baseRegion: string[] = [];+ let cursor = regionStart;+ for (const hunk of overlapping) {+ const gapEnd = hunk.newStart - regionStart;+ baseRegion.push(...knownCurrentRegion.slice(cursor - regionStart, gapEnd));+ baseRegion.push(...hunk.oldLines);+ cursor = hunk.newStart + hunk.newCount;+ }+ baseRegion.push(...knownCurrentRegion.slice(cursor - regionStart));++ const replacementOffset = applyStart - regionStart;+ const finalRegion = [+ ...knownCurrentRegion.slice(0, replacementOffset),+ ...incoming.newLines,+ ...knownCurrentRegion.slice(replacementOffset + incoming.oldCount),+ ];+ const oldStart = mapCurrentTurnDiffPositionToBase(+ regionStart,+ current.filter((hunk) => !overlappingSet.has(hunk)),+ );+ const composed = createCanonicalTurnDiffHunks(baseRegion, finalRegion, oldStart, regionStart);+ if (!composed) return false;++ const remaining = current.filter((hunk) => !overlappingSet.has(hunk));+ for (const hunk of remaining) {+ if (hunk.newStart >= regionEnd) hunk.newStart += delta;+ }+ current.splice(0, current.length, ...remaining, ...composed);+ return current.length <= MAX_TURN_DIFF_COMPOSE_HUNKS;+}++function composeTurnDiffBlocks(+ blocks: string[],+ splitBlock: (block: string) => { header: string; hunks: string[] },+): ComposedTurnDiffBlock {+ const parsedBlocks = blocks.map(splitBlock);+ const rawHunks = parsedBlocks.flatMap((block) => block.hunks);+ if (+ rawHunks.length > MAX_TURN_DIFF_COMPOSE_HUNKS+ || rawHunks.reduce((sum, hunk) => sum + hunk.split('\n').length - 1, 0)+ > MAX_TURN_DIFF_COMPOSE_LINES+ ) return { block: '', complete: false };+ const stripIndexLine = (header: string): string => header+ .split('\n')+ .filter((line) => !line.startsWith('index '))+ .join('\n');+ const header = stripIndexLine(parsedBlocks[0]?.header ?? '');+ if (+ !header+ || parsedBlocks.some((block) =>+ stripIndexLine(block.header) !== header || block.hunks.length === 0)+ ) return { block: '', complete: false };+ const firstHunks = parsedBlocks[0]!.hunks.map(parseTurnDiffHunk);+ if (firstHunks.some((hunk) => hunk === null)) return { block: '', complete: false };+ const canonical = firstHunks as CanonicalTurnDiffHunk[];+ const seenHunks = new Set(canonical.map((hunk) => hunk.raw));+ for (const block of parsedBlocks.slice(1)) {+ let blockDelta = 0;+ for (const rawHunk of block.hunks) {+ const incoming = parseTurnDiffHunk(rawHunk);+ if (incoming && seenHunks.has(incoming.raw)) {+ blockDelta += incoming.newCount - incoming.oldCount;+ continue;+ }+ const applyStart = incoming+ ? incoming.oldStart + blockDelta + (incoming.oldCount === 0 ? 1 : 0)+ : 0;+ if (!incoming || !applyTurnDiffHunk(canonical, incoming, applyStart)) {+ return { block: '', complete: false };+ }+ seenHunks.add(incoming.raw);+ blockDelta += incoming.newCount - incoming.oldCount;+ }+ }+ const body = canonical+ .sort((a, b) => a.oldStart - b.oldStart || a.newStart - b.newStart)+ .map(serializeTurnDiffHunk)+ .join('\n');+ return { block: `${header}${body ? `\n${body}` : ''}\n`, complete: true };+}+// ── Agent 实现 ────────────────────────────────────────────────────────────────export class CodexAgent extends BaseAgent {@@ -2477,46 +2740,42 @@ export class CodexAgent extends BaseAgent {hunks: normalized.slice(firstHunk).split(/(?=^@@ )/m).filter(Boolean),};};- const hunkPosition = (hunk: string): { oldStart: number; newStart: number } => {- const match = /^@@ -(\d+)(?:,\d+)? \+(\d+)/.exec(hunk);- return {- oldStart: match ? Number(match[1]) : Number.MAX_SAFE_INTEGER,- newStart: match ? Number(match[2]) : Number.MAX_SAFE_INTEGER,- };- };- const mergeTurnDiffSnapshots = (): string => {- const blocks = new Map<string, { header: string; hunks: string[] }>();+ const mergeTurnDiffSnapshots = (): { diff: string; complete: boolean } => {+ const blocks = new Map<string, string[]>();for (const snapshot of turnDiffSnapshots.values()) {for (const block of splitTurnDiffBlocks(snapshot)) {const parsed = splitTurnDiffBlockHunks(block);const key = parsed.header.split('\n', 1)[0] ?? parsed.header;- const existing = blocks.get(key);- if (!existing || (parsed.hunks.length === 0 && existing.hunks.length === 0)) {- blocks.set(key, parsed);- continue;- }- for (const hunk of parsed.hunks) {- if (!existing.hunks.includes(hunk)) existing.hunks.push(hunk);- }+ const existing = blocks.get(key) ?? [];+ existing.push(block);+ blocks.set(key, existing);}}- return [...blocks.values()]- .map(({ header, hunks }) => {- const orderedHunks = [...hunks].sort((left, right) => {- const a = hunkPosition(left);- const b = hunkPosition(right);- return a.oldStart - b.oldStart || a.newStart - b.newStart;- });- return `${header}${orderedHunks.length > 0 ? `\n${orderedHunks.join('\n')}` : ''}\n`;- })- .join('');+ let complete = true;+ let diff = '';+ for (const fileBlocks of blocks.values()) {+ if (fileBlocks.length === 1) {+ diff += fileBlocks[0]!.endsWith('\n') ? fileBlocks[0] : `${fileBlocks[0]}\n`;+ continue;+ }+ const composed = composeTurnDiffBlocks(fileBlocks, splitTurnDiffBlockHunks);+ complete &&= composed.complete;+ diff += composed.block;+ }+ return { diff, complete };};const publishTurnDiff = (threadKey: string, turnId: string, diff: string): void => {if (diff) turnDiffSnapshots.set(threadKey, diff);else turnDiffSnapshots.delete(threadKey);+ const merged = mergeTurnDiffSnapshots();eventQueue.push({type: 'turn_diff',- data: { turnId, diff: mergeTurnDiffSnapshots(), cwd: opts.workingDir },+ data: {+ turnId,+ diff: merged.diff,+ cwd: opts.workingDir,+ isComplete: merged.complete,+ },source: 'codex',});};diff --git a/packages/maker-core/src/types/events.ts b/packages/maker-core/src/types/events.tsindex cac1ccd53a..eee42e113c 100644--- a/packages/maker-core/src/types/events.ts+++ b/packages/maker-core/src/types/events.ts@@ -37,6 +37,8 @@ export interface TurnDiffEventData {diff: string;/** Workspace root used when the provider computed the patch. */cwd: string;+ /** False when concurrent provider snapshots could not be safely composed. */+ isComplete?: boolean;}export interface AgentErrorEventData {diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 7259dbab2c..10a3524ecf 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -1094,6 +1094,9 @@ importers:'@cindy/maker-shared':specifier: workspace:*version: link:../maker-shared+ diff:+ specifier: ^8.0.4+ version: 8.0.4better-sqlite3:specifier: '*'version: 12.11.1