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(review): harden recovery freshness

Chrisba8f6482db0b
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/reviewStartHandler.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/reviewStartHandler.test.ts
index b88285f864..6476f7c2d8 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/reviewStartHandler.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/reviewStartHandler.test.ts
@@ -88,6 +88,7 @@ function makeDeps(
waitUntilReady: vi.fn(async () => undefined),
createRunId: vi.fn(() => `run-${++id}`),
createReviewerSessionId: vi.fn(() => `reviewer-${id}`),
+ owner: { instanceId: 'main-instance-1', processId: 123 },
now: vi.fn(() => 1_000 + id),
prepareRun: vi.fn(async () => makePreparedRun(launch)),
createSourceCard: vi.fn(async () => undefined),
@@ -148,7 +149,11 @@ describe('maker:review:start IPC lifecycle', () => {
expect.objectContaining({
sourceSessionId: 'source-1',
sourceCardClientId: 'review:run-1',
- meta: expect.objectContaining({ status: 'running', targetKind: 'mixed' }),
+ meta: expect.objectContaining({
+ status: 'running',
+ targetKind: 'mixed',
+ owner: { instanceId: 'main-instance-1', processId: 123 },
+ }),
}),
);
expect(deps.startReviewer).toHaveBeenCalledWith(expect.objectContaining({ reviewMode: true }));
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index ebeef6bf4e..0f67b60bcc 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -204,7 +204,12 @@ import { fingerprintReviewArtifacts } from '../reviewer/reviewArtifactFingerprin
import { enforceReviewCreateOptions } from '../reviewer/reviewSessionPolicy.js';
import { reviewSourceIdentityMatches } from '../reviewer/reviewSourceIdentity.js';
import { buildReviewSessionTitle } from '../reviewer/reviewSessionTitle.js';
-import { readReviewRunFromAgentMeta, type ReviewRunMeta } from '../../shared/reviewRun.js';
+import {
+ readReviewRunFromAgentMeta,
+ type ReviewRunMeta,
+ type ReviewRunOwner,
+} from '../../shared/reviewRun.js';
+import { shouldFailInterruptedReview } from '../reviewer/reviewRunRecovery.js';
import {
applyAgentSwitchToSessionRow,
applyAgentSwitchResumeFallbackAtomically,
@@ -6565,6 +6570,10 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
warnStderr: (agentKind, line) => log.warn(`[${agentKind}/stderr] ${line}`),
});
+ const reviewRunOwner: ReviewRunOwner = {
+ instanceId: randomUUID(),
+ processId: process.pid,
+ };
const reconcileInterruptedReviews = async (): Promise<void> => {
const db = getDbClient().drizzle;
const rows = await db
@@ -6584,7 +6593,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
const interruptedAt = Date.now();
for (const row of rows) {
const reviewRun = readReviewRunFromAgentMeta(row.agentMeta);
- if (!reviewRun || reviewRun.status !== 'running') continue;
+ if (!reviewRun || !shouldFailInterruptedReview(reviewRun, reviewRunOwner)) continue;
const failed: ReviewRunMeta = {
...reviewRun,
status: 'failed',
@@ -6596,6 +6605,20 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
await broadcastMessageAgentMetaUpdate(row.sessionId, row.clientId);
}
};
+ const sourceHasPersistedRunningReview = async (sourceSessionId: string): Promise<boolean> => {
+ const rows = await getDbClient()
+ .drizzle.select({ agentMeta: messages.agentMeta })
+ .from(messages)
+ .where(
+ and(
+ eq(messages.sessionId, sourceSessionId),
+ eq(messages.role, 'assistant'),
+ isNull(messages.rewindAt),
+ sql`${messages.agentMeta} LIKE '%"reviewRun"%'`,
+ ),
+ );
+ return rows.some((row) => readReviewRunFromAgentMeta(row.agentMeta)?.status === 'running');
+ };
const reviewStartupReady = Promise.all([
reconcileInterruptedReviews(),
cleanupOrphanedReviewArtifactSnapshots(),
@@ -6635,9 +6658,16 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
registerReviewStartHandler(makerSessionRegistry, {
assertCaller: (event) =>
assertTrustedAppRendererEvent(event as Parameters<typeof assertTrustedAppRendererEvent>[0]),
- waitUntilReady: () => reviewStartupReady,
+ waitUntilReady: async () => {
+ await reviewStartupReady;
+ // A supported shared-userData peer can exit after this instance starts.
+ // Recheck ownership immediately before each run so its stale card can be
+ // failed, while a still-live peer remains protected by the DB-backed gate.
+ await reconcileInterruptedReviews();
+ },
createRunId: randomUUID,
createReviewerSessionId: randomUUID,
+ owner: reviewRunOwner,
now: Date.now,
prepareRun: async ({ event, request, reviewerSessionId }) => {
const db = getDbClient().drizzle;
@@ -6662,6 +6692,9 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
if (!source || source.status !== 'active') {
throwIpcError('NOT_FOUND', 'Source task not found');
}
+ if (await sourceHasPersistedRunningReview(source.id)) {
+ throwIpcError('SESSION_RUNNING', 'This task already has a review in progress');
+ }
if (source.source === 'review') {
throwIpcError('INVALID_PARAMS', 'A review task cannot start another review');
}
diff --git a/apps/desktop/src/main/maker-ipc/reviewStartHandler.ts b/apps/desktop/src/main/maker-ipc/reviewStartHandler.ts
index 1f18bdfc91..fd0e6065c3 100644
--- a/apps/desktop/src/main/maker-ipc/reviewStartHandler.ts
+++ b/apps/desktop/src/main/maker-ipc/reviewStartHandler.ts
@@ -9,7 +9,11 @@ import { redactSensitiveText } from '@cindy/maker-shared/error-redaction';
import { isTurnContinuationBoundaryEvent } from '@cindy/maker-shared/turn-continuation';
import type { ReviewAttachmentInput } from '../reviewer/reviewEvidence.js';
-import type { ReviewRunMeta, ReviewTargetKind } from '../../shared/reviewRun.js';
+import type {
+ ReviewRunMeta,
+ ReviewRunOwner,
+ ReviewTargetKind,
+} from '../../shared/reviewRun.js';
import { throwIpcError } from '../utils/ipcValidate.js';
import { MAKER_INVOKE } from './channels.js';
import type { IpcHandlerRegistry } from './ipcHandlerRegistry.js';
@@ -120,6 +124,7 @@ export interface ReviewStartHandlerDeps {
waitUntilReady(): Promise<void>;
createRunId(): string;
createReviewerSessionId(): string;
+ owner: ReviewRunOwner;
now(): number;
prepareRun(input: {
event: unknown;
@@ -254,6 +259,7 @@ export function registerReviewStartHandler(
status: 'running',
targetKind: prepared.targetKind,
startedAt,
+ owner: deps.owner,
};
await deps.createSourceCard({
sourceSessionId: request.sourceSessionId,
diff --git a/apps/desktop/src/main/reviewer/__tests__/reviewArtifactFingerprint.test.ts b/apps/desktop/src/main/reviewer/__tests__/reviewArtifactFingerprint.test.ts
index aebe3db323..752cb493ca 100644
--- a/apps/desktop/src/main/reviewer/__tests__/reviewArtifactFingerprint.test.ts
+++ b/apps/desktop/src/main/reviewer/__tests__/reviewArtifactFingerprint.test.ts
@@ -8,6 +8,7 @@ import {
fingerprintReviewArtifacts,
prepareWithStableReviewArtifacts,
ReviewArtifactChangedDuringPreparationError,
+ ReviewArtifactFingerprintLimitError,
} from '../reviewArtifactFingerprint.js';
const tempDirs: string[] = [];
@@ -61,6 +62,16 @@ describe('review artifact fingerprint', () => {
expect(after).not.toBe(before);
});
+ it('fails closed instead of returning a truncated directory fingerprint', async () => {
+ const dir = await makeTempDir();
+ await fs.writeFile(path.join(dir, 'a.txt'), 'a');
+ await fs.writeFile(path.join(dir, 'b.txt'), 'b');
+
+ await expect(
+ fingerprintReviewArtifacts([dir], { maxDirectoryEntries: 2 }),
+ ).rejects.toBeInstanceOf(ReviewArtifactFingerprintLimitError);
+ });
+
it('rejects a same-size replacement between extraction and the first baseline', async () => {
const dir = await makeTempDir();
const file = path.join(dir, 'draft.txt');
diff --git a/apps/desktop/src/main/reviewer/__tests__/reviewRunRecovery.test.ts b/apps/desktop/src/main/reviewer/__tests__/reviewRunRecovery.test.ts
new file mode 100644
index 0000000000..566c0ebf60
--- /dev/null
+++ b/apps/desktop/src/main/reviewer/__tests__/reviewRunRecovery.test.ts
@@ -0,0 +1,67 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import type { ReviewRunMeta, ReviewRunOwner } from '../../../shared/reviewRun.js';
+import { shouldFailInterruptedReview } from '../reviewRunRecovery.js';
+
+const currentOwner: ReviewRunOwner = { instanceId: 'current', processId: 200 };
+
+function running(owner?: ReviewRunOwner): ReviewRunMeta {
+ return {
+ version: 1,
+ runId: 'run-1',
+ sourceSessionId: 'source-1',
+ reviewerSessionId: 'reviewer-1',
+ status: 'running',
+ targetKind: 'changes',
+ startedAt: 1,
+ ...(owner ? { owner } : {}),
+ };
+}
+
+describe('Review run recovery ownership', () => {
+ it('does not fail a run owned by this process instance', () => {
+ const probe = vi.fn(() => false);
+ expect(shouldFailInterruptedReview(running(currentOwner), currentOwner, probe)).toBe(false);
+ expect(probe).not.toHaveBeenCalled();
+ });
+
+ it('preserves a run while its foreign owner process is alive', () => {
+ const probe = vi.fn(() => true);
+ expect(
+ shouldFailInterruptedReview(
+ running({ instanceId: 'other', processId: 300 }),
+ currentOwner,
+ probe,
+ ),
+ ).toBe(false);
+ expect(probe).toHaveBeenCalledWith(300);
+ });
+
+ it('fails only after the foreign owner is confirmed dead', () => {
+ expect(
+ shouldFailInterruptedReview(
+ running({ instanceId: 'other', processId: 300 }),
+ currentOwner,
+ () => false,
+ ),
+ ).toBe(true);
+ });
+
+ it('recognizes PID reuse by the current differently identified instance', () => {
+ const probe = vi.fn(() => true);
+ expect(
+ shouldFailInterruptedReview(
+ running({ instanceId: 'previous', processId: currentOwner.processId }),
+ currentOwner,
+ probe,
+ ),
+ ).toBe(true);
+ expect(probe).not.toHaveBeenCalled();
+ });
+
+ it('leaves owner-less cards from older clients untouched', () => {
+ const probe = vi.fn(() => false);
+ expect(shouldFailInterruptedReview(running(), currentOwner, probe)).toBe(false);
+ expect(probe).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/main/reviewer/reviewArtifactFingerprint.ts b/apps/desktop/src/main/reviewer/reviewArtifactFingerprint.ts
index 30dac7fc8c..d0a4cd9130 100644
--- a/apps/desktop/src/main/reviewer/reviewArtifactFingerprint.ts
+++ b/apps/desktop/src/main/reviewer/reviewArtifactFingerprint.ts
@@ -13,9 +13,17 @@ const MAX_TOTAL_CONTENT_BYTES = 128 * 1024 * 1024;
interface FingerprintState {
hash: ReturnType<typeof createHash>;
entries: number;
+ maxDirectoryEntries: number;
contentBytesRemaining: number;
}
+export interface ReviewArtifactFingerprintOptions {
+ /** Test seam; production uses the bounded fail-closed default. */
+ maxDirectoryEntries?: number;
+}
+
+export class ReviewArtifactFingerprintLimitError extends Error {}
+
function addRecord(state: FingerprintState, ...parts: Array<string | number>): void {
state.hash.update(parts.join('\0')).update('\n');
}
@@ -97,9 +105,10 @@ async function walk(
state: FingerprintState,
): Promise<void> {
if (isSensitive(absolutePath, relativePath)) return;
- if (state.entries >= MAX_DIRECTORY_ENTRIES) {
- addRecord(state, 'directory-entry-limit', relativePath);
- return;
+ if (state.entries >= state.maxDirectoryEntries) {
+ throw new ReviewArtifactFingerprintLimitError(
+ `Review artifact directory exceeds the ${state.maxDirectoryEntries.toLocaleString('en-US')}-entry fingerprint limit`,
+ );
}
state.entries += 1;
@@ -152,10 +161,6 @@ async function walk(
for (const entry of entries) {
const childRelative = relativePath ? `${relativePath}/${entry.name}` : entry.name;
if (isSensitive(entry.name, childRelative)) continue;
- if (state.entries >= MAX_DIRECTORY_ENTRIES) {
- addRecord(state, 'directory-entry-limit', relativePath, entries.length);
- break;
- }
await walk(path.join(absolutePath, entry.name), childRelative, state);
}
}
@@ -165,10 +170,18 @@ async function walk(
* deliberately bounded, ignores credential paths, and hashes file contents
* (or both ends of very large files) so same-size edits are still detected.
*/
-export async function fingerprintReviewArtifacts(paths: readonly string[]): Promise<string> {
+export async function fingerprintReviewArtifacts(
+ paths: readonly string[],
+ options: ReviewArtifactFingerprintOptions = {},
+): Promise<string> {
+ const maxDirectoryEntries = options.maxDirectoryEntries ?? MAX_DIRECTORY_ENTRIES;
+ if (!Number.isSafeInteger(maxDirectoryEntries) || maxDirectoryEntries <= 0) {
+ throw new TypeError('maxDirectoryEntries must be a positive safe integer');
+ }
const state: FingerprintState = {
hash: createHash('sha256'),
entries: 0,
+ maxDirectoryEntries,
contentBytesRemaining: MAX_TOTAL_CONTENT_BYTES,
};
const canonicalRoots = new Set<string>();
diff --git a/apps/desktop/src/main/reviewer/reviewRunRecovery.ts b/apps/desktop/src/main/reviewer/reviewRunRecovery.ts
new file mode 100644
index 0000000000..69c1e1b000
--- /dev/null
+++ b/apps/desktop/src/main/reviewer/reviewRunRecovery.ts
@@ -0,0 +1,30 @@
+import type { ReviewRunMeta, ReviewRunOwner } from '../../shared/reviewRun.js';
+
+export type ReviewProcessAliveProbe = (processId: number) => boolean;
+
+export function isReviewProcessAlive(processId: number): boolean {
+ try {
+ process.kill(processId, 0);
+ return true;
+ } catch (error) {
+ return (error as NodeJS.ErrnoException).code === 'EPERM';
+ }
+}
+
+/**
+ * A shared-userData instance may only fail a running card after proving that
+ * the Main process which owns it has ended. Owner-less cards from older builds
+ * remain untouched because another older instance may still be running them.
+ */
+export function shouldFailInterruptedReview(
+ reviewRun: ReviewRunMeta,
+ currentOwner: ReviewRunOwner,
+ processIsAlive: ReviewProcessAliveProbe = isReviewProcessAlive,
+): boolean {
+ if (reviewRun.status !== 'running' || !reviewRun.owner) return false;
+ if (reviewRun.owner.instanceId === currentOwner.instanceId) return false;
+ // This process now owns the same PID, so the differently identified previous
+ // owner has definitely terminated even if the OS immediately reused the PID.
+ if (reviewRun.owner.processId === currentOwner.processId) return true;
+ return !processIsAlive(reviewRun.owner.processId);
+}
diff --git a/apps/desktop/src/shared/__tests__/reviewRun.test.ts b/apps/desktop/src/shared/__tests__/reviewRun.test.ts
new file mode 100644
index 0000000000..77e4f01d3f
--- /dev/null
+++ b/apps/desktop/src/shared/__tests__/reviewRun.test.ts
@@ -0,0 +1,32 @@
+import { describe, expect, it } from 'vitest';
+
+import { readReviewRunMeta } from '../reviewRun.js';
+
+const base = {
+ version: 1,
+ runId: 'run-1',
+ sourceSessionId: 'source-1',
+ reviewerSessionId: 'reviewer-1',
+ status: 'running',
+ targetKind: 'changes',
+ startedAt: 1,
+} as const;
+
+describe('ReviewRunMeta', () => {
+ it('accepts a valid process-instance owner', () => {
+ expect(
+ readReviewRunMeta({
+ ...base,
+ owner: { instanceId: 'instance-1', processId: 123 },
+ }),
+ ).toMatchObject({ owner: { instanceId: 'instance-1', processId: 123 } });
+ });
+
+ it('keeps owner-less legacy cards readable but rejects malformed owners', () => {
+ expect(readReviewRunMeta(base)).toMatchObject({ runId: 'run-1' });
+ expect(readReviewRunMeta({ ...base, owner: { instanceId: '', processId: 123 } })).toBeNull();
+ expect(
+ readReviewRunMeta({ ...base, owner: { instanceId: 'instance-1', processId: 0 } }),
+ ).toBeNull();
+ });
+});
diff --git a/apps/desktop/src/shared/reviewRun.ts b/apps/desktop/src/shared/reviewRun.ts
index 810794d4f1..e5799316d1 100644
--- a/apps/desktop/src/shared/reviewRun.ts
+++ b/apps/desktop/src/shared/reviewRun.ts
@@ -2,6 +2,12 @@ export type ReviewRunStatus = 'running' | 'completed' | 'failed';
export type ReviewTargetKind = 'changes' | 'artifacts' | 'task' | 'mixed';
+export interface ReviewRunOwner {
+ /** Random per-Main-process identity; distinguishes PID reuse from the original owner. */
+ instanceId: string;
+ processId: number;
+}
+
/**
* Host-owned link between a source task and its isolated reviewer task.
*
@@ -17,6 +23,11 @@ export interface ReviewRunMeta {
status: ReviewRunStatus;
targetKind: ReviewTargetKind;
startedAt: number;
+ /**
+ * Present on runs created by owner-aware clients. Optional only so cards
+ * written by an older client remain readable after an upgrade.
+ */
+ owner?: ReviewRunOwner;
completedAt?: number;
error?: string;
}
@@ -38,6 +49,20 @@ export function readReviewRunMeta(value: unknown): ReviewRunMeta | null {
) {
return null;
}
+ if (record.owner !== undefined) {
+ if (!record.owner || typeof record.owner !== 'object' || Array.isArray(record.owner)) {
+ return null;
+ }
+ const owner = record.owner as Record<string, unknown>;
+ if (
+ typeof owner.instanceId !== 'string' ||
+ !owner.instanceId ||
+ !Number.isSafeInteger(owner.processId) ||
+ (owner.processId as number) <= 0
+ ) {
+ return null;
+ }
+ }
return record as unknown as ReviewRunMeta;
}