Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): separate advisory and security boundary locks
Yuewei-LLa266ce97d871
diff --git a/apps/desktop/src/main/__tests__/authBoundaryQuarantine.test.ts b/apps/desktop/src/main/__tests__/authBoundaryQuarantine.test.tsindex c807326d4e..506265ad8d 100644--- a/apps/desktop/src/main/__tests__/authBoundaryQuarantine.test.ts+++ b/apps/desktop/src/main/__tests__/authBoundaryQuarantine.test.ts@@ -25,7 +25,7 @@ vi.mock('../logger.js', () => ({}));vi.mock('../device-link/crossProcessLock.js', () => ({- withCrossProcessLock: async (+ withSecurityBoundaryLock: async (_lockPath: string,_options: unknown,task: (status: { held: true } | { held: false; reason: 'busy' }) => Promise<unknown>,diff --git a/apps/desktop/src/main/authBoundaryQuarantine.ts b/apps/desktop/src/main/authBoundaryQuarantine.tsindex 0f9afb9c6c..3fe932a0e4 100644--- a/apps/desktop/src/main/authBoundaryQuarantine.ts+++ b/apps/desktop/src/main/authBoundaryQuarantine.ts@@ -13,7 +13,7 @@ import os from 'node:os';import { app } from 'electron';-import { withCrossProcessLock } from './device-link/crossProcessLock.js';+import { withSecurityBoundaryLock } from './device-link/crossProcessLock.js';import { createLogger } from './logger.js';import { atomicWriteFileSync } from './utils/atomicWriteFile.js';import { readBoundedFileNoFollowSync } from './utils/readBoundedFile.js';@@ -265,6 +265,11 @@ function clearQuarantineState(transitionId: string): void {}async function withStrictBoundaryLock<T>(task: () => Promise<T>): Promise<T> {+ // The in-process tail and the cross-process security lock are complementary:+ // the tail preserves ordering inside this Main process, while the strict lock+ // proves the owner of the globally shared projection transition. This is an+ // authorization boundary, so busy/unavailable must fail closed and must not+ // be replaced with the ordinary advisory tier.const previous = inProcessBoundaryTail;let releaseInProcess: () => void = () => undefined;inProcessBoundaryTail = new Promise<void>((resolve) => {@@ -274,16 +279,11 @@ async function withStrictBoundaryLock<T>(task: () => Promise<T>): Promise<T> {try {const file = filePath();fs.mkdirSync(path.dirname(file), { recursive: true });- return await withCrossProcessLock(+ return await withSecurityBoundaryLock(lockPath(),{label: 'ghost-skill-projection-boundary',waitMs: 12_000,- // Nonce-verified takeover and a recoverable reclaim gate make a crashed- // owner reclaimable without allowing a live owner to be overwritten.- allowStaleTakeover: true,- requireProcessIdentity: true,- allowMalformedStaleTakeover: false,},async (status) => {if (!status.held) {diff --git a/apps/desktop/src/main/cindy-media/refCompensationJournal.ts b/apps/desktop/src/main/cindy-media/refCompensationJournal.tsindex 5f0763b1c2..cc17c5172e 100644--- a/apps/desktop/src/main/cindy-media/refCompensationJournal.ts+++ b/apps/desktop/src/main/cindy-media/refCompensationJournal.ts@@ -11,6 +11,12 @@* ids. `.pending` means the ids must be removed; ordinary `.committed` means* the ingest completed and only the marker itself may be collected. A* committed record carrying `rollbackRequired` is compensated like pending.+ *+ * Each operation uses the ordinary/advisory cross-process lock tier, but the+ * journal mutation still requires mutual exclusion: capture fails and reconcile+ * defers when the lock is unavailable. Owner-scope checks and the durable journal+ * protocol provide the data boundary; the lock does not make an authorization+ * decision and therefore must not inherit the plugin security-boundary policy.*/import { randomUUID } from 'node:crypto';diff --git a/apps/desktop/src/main/contacts-sync/keyStore.ts b/apps/desktop/src/main/contacts-sync/keyStore.tsindex a73dc7519f..7909838991 100644--- a/apps/desktop/src/main/contacts-sync/keyStore.ts+++ b/apps/desktop/src/main/contacts-sync/keyStore.ts@@ -202,9 +202,11 @@ export class ContactsSyncKeyStore {}/**- * 复用已有异步跨进程锁:等待只占 Promise,不阻塞 Electron Main。锁用 PID + mtime- * 心跳确认陈旧 owner,释放前复核归属,避免多个等待者 compare-then-unlink;任何- * busy / unavailable 都 fail closed,不能在没有互斥时读改写密钥文件。+ * 使用 ordinary/advisory 档异步跨进程锁:等待只占 Promise,不阻塞 Electron Main。+ * advisory 描述的是 owner 证明档位,不代表互斥可选;这里用 PID 存活、mtime 心跳和+ * 每次 acquisition 的 nonce 安全接管/释放,任何 busy / unavailable 都 fail closed,+ * 不能在没有互斥时读改写密钥文件。密钥内容安全由加密、owner scope 和原子替换保证,+ * 这把锁本身不承担插件授权裁决,因此不应升级为 security-boundary 档。*/async function withKeyFileLock<T>(file: string, task: () => T): Promise<T> {await fsp.mkdir(path.dirname(file), { recursive: true });diff --git a/apps/desktop/src/main/device-link/__tests__/crossProcessLock.test.ts b/apps/desktop/src/main/device-link/__tests__/crossProcessLock.test.tsindex c5a2c4aceb..06e4e81c18 100644--- a/apps/desktop/src/main/device-link/__tests__/crossProcessLock.test.ts+++ b/apps/desktop/src/main/device-link/__tests__/crossProcessLock.test.ts@@ -1,11 +1,10 @@/**- * crossProcessLock —— 跨实例建议性文件锁的行为守卫。+ * crossProcessLock —— ordinary/advisory 与 security-boundary 两档锁的行为守卫。*- * 这里只守一件最容易出事的:**接管陈旧锁的路径不能空转**。锁文件删不掉(Windows 上- * EPERM / EBUSY 最常见)时,"陈旧 + owner 已死"的判定下一轮仍然成立 —— 原实现 catch 掉- * 删除失败就 continue,于是变成没有退避、没有截止时间的忙等,把调用方永久卡住- * (review: copilot)。其余行为(存活判定、不删别人的锁、降级语义)由- * mirrorCachePurgeQueue.test.ts 的「锁的所有权」用例覆盖。+ * ordinary 档守旧文件形态、nonce 所有权和轻量 Windows 热路径;strict 档守精确进程身份、+ * malformed fail-closed 与可恢复 reclaim 协议。两档共享路径时还必须互相看见 gate,避免+ * 混版本或不同策略的实例同时进入临界区。测试中的别名只用于保留原 strict 回归组的命名,+ * 新增用例应显式选择对应档位。*/import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';import fs from 'node:fs';@@ -18,7 +17,11 @@ vi.mock('../../logger', () => ({createLogger: () => ({ warn: vi.fn(), error: vi.fn(), info: vi.fn(), debug: vi.fn() }),}));-import { __testing, withCrossProcessLock } from '../crossProcessLock';+import {+ __testing,+ withCrossProcessLock as withAdvisoryCrossProcessLock,+ withSecurityBoundaryLock as withCrossProcessLock,+} from '../crossProcessLock';let dir: string;@@ -48,6 +51,22 @@ async function writeStaleLock(lock: string): Promise<void> {await fsp.utimes(lock, old, old);}+async function writeStaleStrictLock(lock: string): Promise<void> {+ await fsp.writeFile(+ lock,+ JSON.stringify({+ pid: 0x7ffffffe,+ startedAt: 1,+ nonce: '00000000-0000-4000-8000-000000000001',+ processStartIdentity: 'start-ms:1',+ state: 'held',+ }),+ 'utf8',+ );+ const old = new Date(Date.now() - 60_000);+ await fsp.utimes(lock, old, old);+}+async function writeStaleReclaimGate(lock: string): Promise<void> {const gate = `${lock}.reclaim`;await fsp.writeFile(@@ -64,7 +83,11 @@ describe('接管陈旧锁', () => {const lock = path.join(dir, 'lock');await writeStaleLock(lock);- const status = await withCrossProcessLock(lock, { label: 'test', waitMs: 200 }, async (s) => s);+ const status = await withAdvisoryCrossProcessLock(+ lock,+ { label: 'test', waitMs: 200 },+ async (s) => s,+ );expect(status).toEqual({ held: true });});@@ -78,7 +101,7 @@ describe('接管陈旧锁', () => {from: unknown,to: unknown,) => {- if (from === lock && typeof to === 'string' && to.startsWith(`${lock}.reclaim-`)) {+ if (from === lock && typeof to === 'string' && to.startsWith(`${lock}.stale-`)) {renameAttempts += 1;throw Object.assign(new Error('EPERM'), { code: 'EPERM' });}@@ -86,7 +109,7 @@ describe('接管陈旧锁', () => {}) as typeof fsp.rename);try {const started = performance.now();- const status = await withCrossProcessLock(+ const status = await withAdvisoryCrossProcessLock(lock,{ label: 'test', waitMs: 5_000 },async (s) => s,@@ -105,14 +128,197 @@ describe('接管陈旧锁', () => {spy.mockRestore();}+ expect(fs.existsSync(lock)).toBe(true);+ });++ it('advisory release leaves no strict recovery artifacts and permits reacquisition', async () => {+ const lock = path.join(dir, 'advisory-lock');+await expect(- withCrossProcessLock(lock, { label: 'test', waitMs: 500 }, async (s) => s),+ withAdvisoryCrossProcessLock(lock, { label: 'first' }, async (s) => s),+ ).resolves.toEqual({ held: true });+ await expect(+ withAdvisoryCrossProcessLock(lock, { label: 'second' }, async (s) => s),).resolves.toEqual({ held: true });++ expect(fs.readdirSync(dir)).toEqual([]);+ });++ it('keeps the advisory canonical lock as a legacy-readable file', async () => {+ const lock = path.join(dir, 'advisory-lock');++ await withAdvisoryCrossProcessLock(lock, { label: 'shape' }, async (status) => {+ expect(status).toEqual({ held: true });+ expect((await fsp.lstat(lock)).isFile()).toBe(true);+ expect(JSON.parse(await fsp.readFile(lock, 'utf8'))).toMatchObject({+ pid: process.pid,+ nonce: expect.any(String),+ });+ });+ });++ it('does not use strict hard-link publication on the advisory hot path', async () => {+ const lock = path.join(dir, 'advisory-lock');+ const linkSpy = vi.spyOn(fsp, 'link');+ try {+ await expect(+ withAdvisoryCrossProcessLock(lock, { label: 'lightweight' }, async (status) => status),+ ).resolves.toEqual({ held: true });+ expect(linkSpy).not.toHaveBeenCalled();+ } finally {+ linkSpy.mockRestore();+ }+ });++ it('advisory release does not remove a successor with a different nonce', async () => {+ const lock = path.join(dir, 'advisory-lock');+ const successor = {+ pid: process.pid,+ startedAt: Date.now(),+ nonce: '00000000-0000-4000-8000-000000000002',+ };++ await withAdvisoryCrossProcessLock(lock, { label: 'predecessor' }, async (status) => {+ expect(status).toEqual({ held: true });+ await fsp.writeFile(lock, JSON.stringify(successor), 'utf8');+ });++ expect(JSON.parse(await fsp.readFile(lock, 'utf8'))).toEqual(successor);+ });++ it('does not reclaim a stale advisory lock while its owner pid is still alive', async () => {+ const lock = path.join(dir, 'advisory-lock');+ await fsp.writeFile(+ lock,+ JSON.stringify({+ pid: process.pid,+ startedAt: 1,+ nonce: '00000000-0000-4000-8000-000000000003',+ }),+ 'utf8',+ );+ const old = new Date(Date.now() - 60_000);+ await fsp.utimes(lock, old, old);++ await expect(+ withAdvisoryCrossProcessLock(+ lock,+ { label: 'live-owner', waitMs: 100 },+ async (status) => status,+ ),+ ).resolves.toEqual({ held: false, reason: 'busy' });+ expect(fs.existsSync(lock)).toBe(true);+ });++ it('recovers a same-process advisory record after release rename fails', async () => {+ const lock = path.join(dir, 'advisory-lock');+ const originalRename = fsp.rename;+ let failedRelease = false;+ const spy = vi.spyOn(fsp, 'rename').mockImplementation((async (+ from: unknown,+ to: unknown,+ ) => {+ if (+ !failedRelease+ && from === lock+ && typeof to === 'string'+ && to.startsWith(`${lock}.release-`)+ ) {+ failedRelease = true;+ throw Object.assign(new Error('EPERM'), { code: 'EPERM' });+ }+ return (originalRename as (...args: unknown[]) => Promise<unknown>)(from, to);+ }) as typeof fsp.rename);+ try {+ await expect(+ withAdvisoryCrossProcessLock(lock, { label: 'first' }, async (status) => status),+ ).resolves.toEqual({ held: true });+ expect(fs.existsSync(lock)).toBe(true);++ await expect(+ withAdvisoryCrossProcessLock(lock, { label: 'second' }, async (status) => status),+ ).resolves.toEqual({ held: true });+ } finally {+ spy.mockRestore();+ }++ expect(fs.existsSync(lock)).toBe(false);+ });++ it('advisory release gate prevents a successor replacement race', async () => {+ const lock = path.join(dir, 'advisory-lock');+ const releaseFirstTask = deferred();+ const firstTaskStarted = deferred();+ const releaseRenameStarted = deferred();+ const allowReleaseRename = deferred();+ const originalRename = fsp.rename;+ let blockedRelease = false;+ const spy = vi.spyOn(fsp, 'rename').mockImplementation((async (+ from: unknown,+ to: unknown,+ ) => {+ if (+ !blockedRelease+ && from === lock+ && typeof to === 'string'+ && to.startsWith(`${lock}.release-`)+ ) {+ blockedRelease = true;+ releaseRenameStarted.resolve();+ await allowReleaseRename.promise;+ }+ return (originalRename as (...args: unknown[]) => Promise<unknown>)(from, to);+ }) as typeof fsp.rename);++ try {+ const first = withAdvisoryCrossProcessLock(+ lock,+ { label: 'first', waitMs: 500 },+ async (status) => {+ expect(status).toEqual({ held: true });+ firstTaskStarted.resolve();+ await releaseFirstTask.promise;+ return status;+ },+ );+ await firstTaskStarted.promise;+ releaseFirstTask.resolve();+ await releaseRenameStarted.promise;++ await fsp.rm(lock, { force: true });+ await fsp.writeFile(+ lock,+ JSON.stringify({+ pid: process.pid,+ startedAt: Date.now(),+ nonce: '00000000-0000-4000-8000-000000000004',+ }),+ 'utf8',+ );++ await expect(+ withAdvisoryCrossProcessLock(+ lock,+ { label: 'third', waitMs: 100 },+ async (status) => status,+ ),+ ).resolves.toEqual({ held: false, reason: 'busy' });++ allowReleaseRename.resolve();+ await expect(first).resolves.toEqual({ held: true });+ expect(JSON.parse(await fsp.readFile(lock, 'utf8'))).toMatchObject({+ nonce: '00000000-0000-4000-8000-000000000004',+ });+ } finally {+ allowReleaseRename.resolve();+ releaseFirstTask.resolve();+ spy.mockRestore();+ }});it('reclaims a crashed reclaim gate before taking over the stale lock', async () => {const lock = path.join(dir, 'lock');- await writeStaleLock(lock);+ await writeStaleStrictLock(lock);await writeStaleReclaimGate(lock);const status = await withCrossProcessLock(lock, { label: 'test', waitMs: 500 }, async (s) => s);@@ -130,7 +336,7 @@ describe('接管陈旧锁', () => {await expect(withCrossProcessLock(lock,- { label: 'test', waitMs: 100, allowMalformedStaleTakeover: false },+ { label: 'test', waitMs: 100 },async (s) => s,),).resolves.toEqual({ held: false, reason: 'busy' });@@ -171,7 +377,7 @@ describe('接管陈旧锁', () => {JSON.stringify({pid: child.pid,startedAt: 1,- processStartIdentity: 'start-ms:0',+ processStartIdentity: 'start-ms:1',nonce: '00000000-0000-4000-8000-000000000001',state: 'held',}),@@ -199,7 +405,7 @@ describe('接管陈旧锁', () => {JSON.stringify({pid: process.pid,startedAt: 1,- processStartIdentity: 'start-ms:0',+ processStartIdentity: 'start-ms:1',nonce: '00000000-0000-4000-8000-000000000001',state: 'held',}),@@ -268,6 +474,7 @@ describe('接管陈旧锁', () => {pid: 0x7ffffffe,startedAt: 1,nonce: '00000000-0000-4000-8000-000000000001',+ processStartIdentity: 'start-ms:1',state: 'released',}),'utf8',@@ -331,8 +538,6 @@ describe('接管陈旧锁', () => {{label: 'strict',waitMs: 100,- requireProcessIdentity: true,- allowMalformedStaleTakeover: false,},async (s) => s,),@@ -362,7 +567,7 @@ describe('接管陈旧锁', () => {await expect(withCrossProcessLock(lock,- { label: 'strict', waitMs: 100, requireProcessIdentity: true, allowMalformedStaleTakeover: false },+ { label: 'strict', waitMs: 100 },async (s) => s,),).resolves.toEqual({ held: false, reason: 'busy' });@@ -400,7 +605,7 @@ describe('接管陈旧锁', () => {await expect(withCrossProcessLock(lock,- { label: 'strict', waitMs: 100, requireProcessIdentity: true, allowMalformedStaleTakeover: false },+ { label: 'strict', waitMs: 100 },async (s) => s,),).resolves.toEqual({ held: false, reason: 'busy' });@@ -409,7 +614,7 @@ describe('接管陈旧锁', () => {it('bounds repeated successful stale takeovers by time and count', async () => {const lock = path.join(dir, 'lock');- await writeStaleLock(lock);+ await writeStaleStrictLock(lock);const originalRename = fsp.rename;let takeovers = 0;const spy = vi.spyOn(fsp, 'rename').mockImplementation((async (@@ -419,7 +624,7 @@ describe('接管陈旧锁', () => {const result = await (originalRename as (...args: unknown[]) => Promise<unknown>)(from, to);if (from === lock && typeof to === 'string' && to.startsWith(`${lock}.reclaim-`)) {takeovers += 1;- await writeStaleLock(lock);+ await writeStaleStrictLock(lock);}return result;}) as typeof fsp.rename);@@ -437,7 +642,7 @@ describe('接管陈旧锁', () => {it('publishes after the final stale takeover when the path stays empty', async () => {const lock = path.join(dir, 'lock');- await writeStaleLock(lock);+ await writeStaleStrictLock(lock);const originalRename = fsp.rename;let takeovers = 0;const spy = vi.spyOn(fsp, 'rename').mockImplementation((async (@@ -447,7 +652,7 @@ describe('接管陈旧锁', () => {const result = await (originalRename as (...args: unknown[]) => Promise<unknown>)(from, to);if (from === lock && typeof to === 'string' && to.startsWith(`${lock}.reclaim-`)) {takeovers += 1;- if (takeovers < 3) await writeStaleLock(lock);+ if (takeovers < 3) await writeStaleStrictLock(lock);}return result;}) as typeof fsp.rename);diff --git a/apps/desktop/src/main/device-link/__tests__/mirrorCacheStore.test.ts b/apps/desktop/src/main/device-link/__tests__/mirrorCacheStore.test.tsindex 6e7b9f06d0..dcacf6c369 100644--- a/apps/desktop/src/main/device-link/__tests__/mirrorCacheStore.test.ts+++ b/apps/desktop/src/main/device-link/__tests__/mirrorCacheStore.test.ts@@ -1493,13 +1493,7 @@ describe('跨进程互斥(锁 + 清理完成标记)', () => {target: unknown,...rest: unknown[]) => {- if (- typeof target === 'string'- && (- target === lock- || target.startsWith(`${lock}.candidate-`)- )- ) {+ if (target === lock) {// 不是 EEXIST:锁**建不出来**(EMFILE / 控制目录被 ACL 挡住)。throw Object.assign(new Error('EMFILE'), { code: 'EMFILE' });}diff --git a/apps/desktop/src/main/device-link/crossProcessLock.ts b/apps/desktop/src/main/device-link/crossProcessLock.tsindex d61466bf5b..405797911b 100644--- a/apps/desktop/src/main/device-link/crossProcessLock.ts+++ b/apps/desktop/src/main/device-link/crossProcessLock.ts@@ -9,6 +9,21 @@ import { promisify } from 'node:util';import { createLogger } from '../logger';import { readBoundedFileNoFollow } from '../utils/readBoundedFile.js';+/**+ * Cross-process locking has two intentionally separate policies.+ *+ * `withCrossProcessLock` is the ordinary/advisory tier: it provides real+ * mutual exclusion, while the caller decides whether `busy` / `unavailable`+ * means fail, defer, skip an optimization, or take a separately safe fallback.+ * "Advisory" describes the ownership-proof and recovery policy; it does not+ * mean callers may ignore a failed acquisition.+ *+ * `withSecurityBoundaryLock` is reserved for transitions where accepting the+ * wrong owner would cross an authorization boundary. Its stronger identity and+ * durable recovery rules are fixed by the API. Do not merge the tiers into one+ * option-driven lock: that makes a security invariant removable at call sites+ * and pushes the strict Windows failure surface back onto ordinary writes.+ */const log = createLogger('device-link:cross-process-lock');const LOCK_STALE_MS = 10_000;@@ -38,12 +53,6 @@ export type LockStatus = { held: true } | { held: false; reason: 'busy' | 'unavaexport interface FileLockOptions {label: string;waitMs?: number;- /** Defaults to true. Set false only for legacy callers that must never reclaim. */- allowStaleTakeover?: boolean;- /** Security boundaries may require an OS process birth identity before publishing. */- requireProcessIdentity?: boolean;- /** Legacy advisory locks treated stale readable garbage as crash residue. */- allowMalformedStaleTakeover?: boolean;}interface LockRecord {@@ -73,6 +82,23 @@ type PublishedLock = {nonce: string;record: LockRecord;};+type AdvisoryPublishedLock = {+ nonce: string;+};+type AdvisoryLockRecord = {+ pid: number;+ nonce: string | null;+};+type AdvisoryStaleCandidate = {+ identity: MalformedLockIdentity;+ record: AdvisoryLockRecord | null;+};+type AdvisoryReclaimGate = {+ dirPath: string;+ filePath: string;+ nonce: string;+ heartbeat: ReturnType<typeof setInterval>;+};type ReclaimGate = {dirPath: string;filePath: string;@@ -84,16 +110,110 @@ let currentProcessIdentityPromise: Promise<ProcessIdentity | null> | null = null// A release gate whose final rename/fsync failed may still be ours. Keep its// nonce so the same process can recover it before treating the gate as busy.const pendingOwnRecordRecovery = new Map<string, string>();+const pendingAdvisoryRecovery = new Map<string, string>();const pendingOwnGateCleanup = new Set<string>();function gateReleaseMarkerPath(gatePath: string): string {return `${gatePath}.released`;}+/**+ * Lightweight cross-process advisory lock for caches and ordinary durable stores.+ *+ * Callers retain ownership of the degradation policy through `LockStatus`. This+ * path keeps the legacy canonical file shape, adding a nonce-bound owner record+ * and rename isolation for safe release/takeover. It deliberately avoids the+ * strict tier's process-identity commands, hard-link/fsync publication and+ * released-marker protocol on the ordinary hot path. Plugin approval boundaries+ * require those stronger proofs, but imposing their full state machine on every+ * cache/settings write enlarged the Windows failure surface.+ */export async function withCrossProcessLock<T>(lockPath: string,opts: FileLockOptions,task: (status: LockStatus) => Promise<T>,+): Promise<T> {+ const deadline = Date.now() + (opts.waitMs ?? LOCK_WAIT_MS);+ let held = false;+ let reason: 'busy' | 'unavailable' = 'unavailable';+ let takeovers = 0;+ let ownLock: AdvisoryPublishedLock | null = null;++ for (;;) {+ await recoverPendingAdvisoryLock(lockPath);+ if (await ordinaryReclaimInProgress(lockPath)) {+ reason = 'busy';+ if (Date.now() >= deadline) break;+ await sleep(LOCK_RETRY_MS);+ continue;+ }+ try {+ ownLock = await publishAdvisoryLock(lockPath);+ if (await ordinaryReclaimInProgress(lockPath)) {+ await releaseAdvisoryLock(lockPath, opts.label, ownLock);+ ownLock = null;+ reason = 'busy';+ if (Date.now() >= deadline) break;+ await sleep(LOCK_RETRY_MS);+ continue;+ }+ held = true;+ break;+ } catch (error) {+ const code = (error as NodeJS.ErrnoException)?.code;+ // Windows may transiently report these while a recently removed path is+ // still being released by the filesystem. Keep them inside the bounded+ // retry loop instead of disabling the caller immediately.+ if (code !== 'EEXIST' && code !== 'EBUSY' && code !== 'EPERM' && code !== 'EACCES') {+ reason = 'unavailable';+ break;+ }+ const stale = takeovers < MAX_TAKEOVERS+ ? await inspectStaleAdvisoryLock(lockPath)+ : null;+ if (stale) {+ takeovers += 1;+ const takeover = await quarantineAdvisoryLock(lockPath, stale);+ if (takeover === 'taken' || takeover === 'changed') continue;+ reason = 'busy';+ break;+ }+ if (Date.now() >= deadline) {+ reason = 'busy';+ break;+ }+ await sleep(LOCK_RETRY_MS);+ }+ }++ const heartbeat = held+ ? setInterval(() => {+ const now = new Date();+ void fsp.utimes(lockPath, now, now).catch(() => undefined);+ }, LOCK_HEARTBEAT_MS)+ : null;+ heartbeat?.unref?.();++ try {+ return await task(held ? { held: true } : { held: false, reason });+ } finally {+ if (heartbeat) clearInterval(heartbeat);+ if (held && ownLock) await releaseAdvisoryLock(lockPath, opts.label, ownLock);+ }+}++/**+ * Strict lock for plugin approval and skill-projection security boundaries.+ *+ * The policy is intentionally fixed: exact process identity, nonce-bound+ * publication/release, no takeover of malformed records, and recoverable+ * reclaim gates. Keeping this as a separate API prevents ordinary callers from+ * accidentally inheriting security-boundary lifecycle complexity.+ */+export async function withSecurityBoundaryLock<T>(+ lockPath: string,+ opts: FileLockOptions,+ task: (status: LockStatus) => Promise<T>,): Promise<T> {let held = false;let reason: 'busy' | 'unavailable' = 'unavailable';@@ -104,7 +224,7 @@ export async function withCrossProcessLock<T>(// Do not charge the first process-identity probe against the caller's wait// budget. On Windows the initial CIM/WMIC lookup can take several seconds.const deadline = Date.now() + (opts.waitMs ?? LOCK_WAIT_MS);- if (opts.requireProcessIdentity && !processIdentity) {+ if (!processIdentity) {return task({ held: false, reason: 'unavailable' });}@@ -121,7 +241,7 @@ export async function withCrossProcessLock<T>(if (!publishedLock) throw Object.assign(new Error('lock exists'), { code: 'EEXIST' });const { nonce } = publishedLock;const [published, reclaiming] = await Promise.all([- readLockRecord(lockPath, opts.requireProcessIdentity === true),+ readLockRecord(lockPath, true),reclaimInProgress(lockPath),]);if (reclaiming || typeof published === 'string' || published.nonce !== nonce) {@@ -154,21 +274,18 @@ export async function withCrossProcessLock<T>(}publishingAfterTakeover = false;- if (- opts.allowStaleTakeover !== false &&- takeovers < MAX_TAKEOVERS- ) {+ if (takeovers < MAX_TAKEOVERS) {const stale = await inspectStaleLock(lockPath,- opts.allowMalformedStaleTakeover !== false,- opts.requireProcessIdentity === true,+ false,+ true,);if (stale) {log.warn(`taking over stale ${opts.label} lock from a dead owner`);const takeover = await quarantineStaleLock(lockPath,stale,- opts.requireProcessIdentity === true,+ true,);if (takeover === 'taken') {takeovers += 1;@@ -259,6 +376,281 @@ async function inspectStaleLock(: { kind: 'record', record };}+/** Only a stale record whose owner is definitely gone may be reclaimed. */+async function inspectStaleAdvisoryLock(+ lockPath: string,+): Promise<AdvisoryStaleCandidate | null> {+ let stat: Awaited<ReturnType<typeof fsp.lstat>>;+ try {+ stat = await fsp.lstat(lockPath);+ } catch {+ return null;+ }+ if (Date.now() - stat.mtimeMs <= LOCK_STALE_MS) return null;++ const record = await readAdvisoryLockRecord(lockPath);+ if (record === 'unreadable') return null;+ if (record === null) {+ return {+ identity: malformedLockIdentity(stat),+ record: null,+ };+ }+ try {+ process.kill(record.pid, 0);+ return null;+ } catch (error) {+ const code = (error as NodeJS.ErrnoException)?.code;+ if (code !== 'ESRCH') return null;+ }+ return {+ identity: malformedLockIdentity(stat),+ record,+ };+}++async function publishAdvisoryLock(lockPath: string): Promise<AdvisoryPublishedLock> {+ const nonce = crypto.randomUUID();+ let handle: Awaited<ReturnType<typeof fsp.open>> | null = null;+ let created = false;+ try {+ // The canonical path must remain a directly-created regular file: released+ // clients and older Cindy versions already coordinate through this shape.+ handle = await fsp.open(lockPath, 'wx');+ created = true;+ await handle.writeFile(+ JSON.stringify({ pid: process.pid, startedAt: Date.now(), nonce }),+ 'utf8',+ );+ await handle.close();+ handle = null;+ return { nonce };+ } catch (error) {+ await handle?.close().catch(() => undefined);+ if (created) await fsp.rm(lockPath, { force: true }).catch(() => undefined);+ throw error;+ }+}++async function readAdvisoryLockRecord(+ lockPath: string,+): Promise<AdvisoryLockRecord | null | 'unreadable'> {+ let raw: string;+ try {+ raw = await fsp.readFile(lockPath, 'utf8');+ } catch (error) {+ const code = (error as NodeJS.ErrnoException)?.code;+ if (code === 'ENOENT' || code === 'ENOTDIR') return null;+ return 'unreadable';+ }+ try {+ const value = JSON.parse(raw) as unknown;+ if (value && typeof value === 'object' && !Array.isArray(value)) {+ const pid = (value as { pid?: unknown }).pid;+ const nonce = (value as { nonce?: unknown }).nonce;+ if (typeof pid === 'number' && Number.isInteger(pid) && pid > 0) {+ return {+ pid,+ nonce: typeof nonce === 'string' && nonce !== '' ? nonce : null,+ };+ }+ }+ } catch {+ // Legacy advisory locks treated readable malformed stale data as residue.+ }+ return null;+}++function sameAdvisoryCandidate(+ left: AdvisoryStaleCandidate | null,+ right: AdvisoryStaleCandidate,+): boolean {+ if (!left) return false;+ return sameMalformedLockIdentity(left.identity, right.identity)+ && left.record?.pid === right.record?.pid+ && left.record?.nonce === right.record?.nonce;+}++async function quarantineAdvisoryLock(+ lockPath: string,+ expected: AdvisoryStaleCandidate,+): Promise<'taken' | 'changed' | 'busy' | 'failed'> {+ // Only crash recovery pays for the reclaim gate. Cooperating acquisitions+ // check it both before and after publication, so a successor cannot enter+ // its task while the stale canonical path is being isolated.+ const gate = await acquireAdvisoryReclaimGate(lockPath, 0);+ if (!gate) return 'busy';+ const quarantinePath = `${lockPath}.stale-${process.pid}-${crypto.randomUUID()}`;+ try {+ const current = await inspectStaleAdvisoryLock(lockPath);+ if (!sameAdvisoryCandidate(current, expected)) return 'changed';+ try {+ await fsp.rename(lockPath, quarantinePath);+ } catch (error) {+ const code = (error as NodeJS.ErrnoException)?.code;+ return code === 'ENOENT' || code === 'ENOTDIR' ? 'changed' : 'failed';+ }+ const moved = await inspectAdvisoryCandidate(quarantinePath);+ if (!sameAdvisoryCandidate(moved, expected)) {+ await restoreMovedPathSafely(quarantinePath, lockPath);+ return 'failed';+ }+ await removePathWithRetry(quarantinePath);+ return await pathExists(quarantinePath) ? 'failed' : 'taken';+ } finally {+ await releaseAdvisoryReclaimGate(gate);+ }+}++async function inspectAdvisoryCandidate(+ lockPath: string,+): Promise<AdvisoryStaleCandidate | null> {+ let stat: Awaited<ReturnType<typeof fsp.lstat>>;+ try {+ stat = await fsp.lstat(lockPath);+ } catch {+ return null;+ }+ const record = await readAdvisoryLockRecord(lockPath);+ if (record === 'unreadable') return null;+ return {+ identity: malformedLockIdentity(stat),+ record,+ };+}++async function releaseAdvisoryLock(+ lockPath: string,+ label: string,+ lock: AdvisoryPublishedLock,+): Promise<void> {+ const gate = await acquireAdvisoryReclaimGate(lockPath);+ if (!gate) {+ pendingAdvisoryRecovery.set(lockPath, lock.nonce);+ log.warn(`${label} lock release gate is busy; leaving a recoverable owner record`);+ return;+ }+ const releasePath = `${lockPath}.release-${process.pid}-${crypto.randomUUID()}`;+ try {+ const current = await readAdvisoryLockRecord(lockPath);+ // The nonce, not the PID, is the ownership token. The same long-lived+ // process may already have acquired a successor after an earlier release+ // failure, and the predecessor must never remove that successor.+ if (current === 'unreadable' || current === null || current.nonce !== lock.nonce) {+ log.warn(`${label} lock was taken over; leaving it to its new owner`);+ return;+ }+ try {+ await fsp.rename(lockPath, releasePath);+ } catch {+ pendingAdvisoryRecovery.set(lockPath, lock.nonce);+ return;+ }+ const moved = await readAdvisoryLockRecord(releasePath);+ if (moved !== 'unreadable' && moved !== null && moved.nonce === lock.nonce) {+ pendingAdvisoryRecovery.delete(lockPath);+ await removePathWithRetry(releasePath);+ } else {+ await restoreMovedPathSafely(releasePath, lockPath);+ log.warn(`${label} lock identity changed during release; preserving the isolated record`);+ }+ } finally {+ await releaseAdvisoryReclaimGate(gate);+ }+}++async function recoverPendingAdvisoryLock(lockPath: string): Promise<void> {+ const nonce = pendingAdvisoryRecovery.get(lockPath);+ if (!nonce) return;+ const current = await readAdvisoryLockRecord(lockPath);+ if (current === 'unreadable') return;+ if (current === null || current.nonce !== nonce) {+ pendingAdvisoryRecovery.delete(lockPath);+ return;+ }+ await releaseAdvisoryLock(lockPath, 'advisory recovery', { nonce });+}++async function ordinaryReclaimInProgress(lockPath: string): Promise<boolean> {+ await cleanupPendingOwnGates();+ return reclaimInProgress(lockPath);+}++async function acquireAdvisoryReclaimGate(+ lockPath: string,+ waitMs = RELEASE_GATE_WAIT_MS,+): Promise<AdvisoryReclaimGate | null> {+ await cleanupPendingOwnGates();+ const deadline = Date.now() + waitMs;+ const dirPath = reclaimGateDirPath(lockPath);+ do {+ if (await legacyReclaimInProgress(lockPath)) {+ if (Date.now() >= deadline) return null;+ await sleep(LOCK_RETRY_MS);+ continue;+ }+ try {+ await fsp.mkdir(dirPath, { recursive: true });+ } catch {+ return null;+ }+ const nonce = crypto.randomUUID();+ const filePath = path.join(dirPath, `gate-${process.pid}-${nonce}.json`);+ let handle: Awaited<ReturnType<typeof fsp.open>> | null = null;+ try {+ // Keep the shared `gate-*` name and complete LockRecord shape so strict+ // and older contenders observe this lightweight recovery gate. The+ // estimated self identity avoids CIM/WMIC on the advisory path; freshness+ // and the nonce-bound file name protect the short reclaim transaction.+ handle = await fsp.open(filePath, 'wx');+ await handle.writeFile(JSON.stringify({+ pid: process.pid,+ startedAt: Date.now(),+ nonce,+ processStartIdentity: estimateCurrentProcessIdentity().key,+ state: 'held',+ } satisfies LockRecord), 'utf8');+ await handle.close();+ handle = null;+ } catch {+ await handle?.close().catch(() => undefined);+ await removePathWithRetry(filePath);+ return null;+ }++ const heartbeat = setInterval(() => {+ const now = new Date();+ void fsp.utimes(filePath, now, now).catch(() => undefined);+ }, LOCK_HEARTBEAT_MS);+ heartbeat.unref?.();+ const gate = { dirPath, filePath, nonce, heartbeat };+ for (;;) {+ const winner = await findActiveReclaimGate(dirPath);+ if (winner === filePath) return gate;+ if (winner === null || Date.now() >= deadline) {+ await releaseAdvisoryReclaimGate(gate);+ break;+ }+ await sleep(LOCK_RETRY_MS);+ }+ if (Date.now() >= deadline) return null;+ } while (true);+}++async function releaseAdvisoryReclaimGate(gate: AdvisoryReclaimGate): Promise<void> {+ clearInterval(gate.heartbeat);+ const current = await readLockRecord(gate.filePath, true);+ if (typeof current !== 'string' && current.nonce === gate.nonce) {+ await removePathWithRetry(gate.filePath);+ }+ if (await pathExists(gate.filePath)) pendingOwnGateCleanup.add(gate.filePath);+ try {+ await fsp.rmdir(gate.dirPath);+ } catch {+ // Strict or advisory contenders may still be using the shared directory.+ }+}+async function readLockRecord(lockPath: string,requireCompleteRecord = false,@@ -426,9 +818,15 @@ async function quarantineStaleLock(}}-async function reclaimInProgress(lockPath: string): Promise<boolean> {+async function reclaimInProgress(+ lockPath: string,+ requireProcessIdentity = true,+): Promise<boolean> {if (await legacyReclaimInProgress(lockPath)) return true;- return (await findActiveReclaimGate(reclaimGateDirPath(lockPath))) !== null;+ return (await findActiveReclaimGate(+ reclaimGateDirPath(lockPath),+ requireProcessIdentity,+ )) !== null;}async function legacyReclaimInProgress(lockPath: string): Promise<boolean> {@@ -484,7 +882,10 @@ async function cleanupPendingOwnGates(): Promise<void> {}}-async function findActiveReclaimGate(dirPath: string): Promise<string | null> {+async function findActiveReclaimGate(+ dirPath: string,+ requireProcessIdentity = true,+): Promise<string | null> {let entries: string[];try {entries = await fsp.readdir(dirPath);@@ -503,7 +904,7 @@ async function findActiveReclaimGate(dirPath: string): Promise<string | null> {} catch {continue;}- const record = await readLockRecord(filePath, true);+ const record = await readLockRecord(filePath, requireProcessIdentity);if (record === 'missing') continue;// A leftover .released sidecar from a previous gate instance shares the// same locked file name — its nonce must match the current gate record's@@ -516,7 +917,10 @@ async function findActiveReclaimGate(dirPath: string): Promise<string | null> {}if (typeof record === 'string') {const fresh = Date.now() - stat.mtimeMs <= LOCK_STALE_MS;- if (fresh || await isMalformedGateOwnerActive(filePath, stat)) return filePath;+ if (+ fresh+ || (requireProcessIdentity && await isMalformedGateOwnerActive(filePath, stat))+ ) return filePath;await removePathWithRetry(filePath);if (await pathExists(filePath)) return filePath;continue;@@ -570,6 +974,7 @@ async function isMalformedGateOwnerActive(async function acquireReclaimGate(lockPath: string,waitMs = RELEASE_GATE_WAIT_MS,+ requireProcessIdentity = true,): Promise<ReclaimGate | null> {await cleanupPendingOwnGates();const deadline = Date.now() + waitMs;@@ -591,7 +996,9 @@ async function acquireReclaimGate(try {lock = await publishLockRecord(filePath,- (await getProcessIdentity(process.pid))?.key ?? null,+ requireProcessIdentity+ ? ((await getProcessIdentity(process.pid))?.key ?? null)+ : null,);} catch {return null;@@ -605,7 +1012,7 @@ async function acquireReclaimGate(heartbeat.unref?.();const gate: ReclaimGate = { dirPath, filePath, lock, heartbeat };for (;;) {- const winner = await findActiveReclaimGate(dirPath);+ const winner = await findActiveReclaimGate(dirPath, requireProcessIdentity);if (winner === filePath) return gate;if (winner === null || Date.now() >= deadline) {await releaseReclaimGate(gate);diff --git a/apps/desktop/src/main/device-link/mirrorCacheStore.ts b/apps/desktop/src/main/device-link/mirrorCacheStore.tsindex 73713decd6..659b2080f3 100644--- a/apps/desktop/src/main/device-link/mirrorCacheStore.ts+++ b/apps/desktop/src/main/device-link/mirrorCacheStore.ts@@ -705,8 +705,9 @@ export function createMirrorCache(resolveRoot: () => string): MirrorCache {* - 两个进程各自清不同设备时,会各读同一份旧 session-list、各写"除我之外的全部",* 后写的那次把对方刚移除的设备恢复回来 —— 两边都报成功(review: codex P1)。*- * 所以落盘写入与清理统一在这把锁里做(实现见 crossProcessLock:pid + 心跳 + 存活判定,- * 只接管确实死掉的持有者)。拿不到锁时:+ * 所以落盘写入与清理统一在 ordinary/advisory 档跨进程锁里做(用 PID 存活、mtime 心跳+ * 与 acquisition nonce 保护接管/释放)。这里的 advisory 是锁证明档位,不是允许无锁写入;+ * 缓存自己的屏障决定拿不到锁时如何安全降级:* - **写入**直接跳过(缓存是纯优化,少写一次远好过在别人清理途中写回明文);* - **清理**照常进行(删除是安全方向),并保留清理收尾的二次扫描兜底。*/diff --git a/apps/desktop/src/main/maker-host/override-settings-file.ts b/apps/desktop/src/main/maker-host/override-settings-file.tsindex a943cc2861..35fb043eb7 100644--- a/apps/desktop/src/main/maker-host/override-settings-file.ts+++ b/apps/desktop/src/main/maker-host/override-settings-file.ts@@ -41,6 +41,12 @@ interface CachedState<T> extends OverrideSettingsState<T> {readStatus: 'missing' | 'readable' | 'unreadable';}+/**+ * Atomic mutations use the ordinary/advisory lock tier and still require the+ * lock to be held. `scopeKey` guards owner/session drift separately; neither+ * concern is an authorization decision that should inherit the plugin+ * security-boundary lock's process-identity and durable-recovery machinery.+ */export function createOverrideSettingsFile<T>(options: {filePath: () => string;defaults: T;