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(desktop): close Windows lock and receipt recovery gaps

Yuewei-LLc5b554ea4668
diff --git a/apps/desktop/src/main/cindy-brain/GhostManager.ts b/apps/desktop/src/main/cindy-brain/GhostManager.ts
index f2c219d253..1e74f1963b 100644
--- a/apps/desktop/src/main/cindy-brain/GhostManager.ts
+++ b/apps/desktop/src/main/cindy-brain/GhostManager.ts
@@ -1310,12 +1310,14 @@ export class GhostManager {
continue;
}
if (approval.state === 'unreadable') {
- // 暂时读不动批准事实不等于 legacy/损坏。把它从可变安装目录重铸会覆盖一份
- // 可能完全有效的批准;保持 fail closed 并把 id 钉进持久重试队列。
- result.retryPending.push(id);
- pendingForRetry.add(id);
+ // 暂时读不动批准事实不等于 legacy。尤其不能把它放进普通 pendingIds:
+ // 若 receipt 随后消失,续跑会把可变安装目录误当成旧授权事实重新铸批准。
+ // 记为确定性 fail-closed 审计项;原 receipt 恢复可读时仍自然生效,真的丢失
+ // 则只能走完整重新批准,不能自动 backfill。
+ result.failed.push(id);
+ pendingForRetry.delete(id);
unreadableReceiptIds.push(id);
- this.options.log?.warn('legacy migration found an unreadable receipt; will retry', {
+ this.options.log?.warn('legacy migration found an unreadable receipt; automatic backfill blocked', {
id,
reason: approval.reason,
});
@@ -1357,19 +1359,32 @@ export class GhostManager {
return result;
}
if (
- !resumePending &&
- (candidates.length > 0 ||
- blockedByPendingJournal.length > 0 ||
- unreadableReceiptIds.length > 0)
+ resumePending ||
+ candidates.length > 0 ||
+ blockedByPendingJournal.length > 0 ||
+ unreadableReceiptIds.length > 0
) {
+ const checkpointPendingIds = [
+ ...new Set([...candidates, ...blockedByPendingJournal]),
+ ].sort();
+ const checkpointFailedIds = [
+ ...new Set([...(resumeLedger?.failedIds ?? []), ...unreadableReceiptIds]),
+ ].sort();
await this.receiptStore.writeMigrationLedger({
version: 1,
migratedAt: new Date().toISOString(),
- migratedIds: [],
- state: 'in-progress',
- pendingIds: [
- ...new Set([...candidates, ...blockedByPendingJournal, ...unreadableReceiptIds]),
- ].sort(),
+ migratedIds: [...new Set([...(resumeLedger?.migratedIds ?? []), ...preMigrated])].sort(),
+ state: checkpointPendingIds.length > 0 ? 'in-progress' : 'completed',
+ ...(checkpointPendingIds.length > 0 ? { pendingIds: checkpointPendingIds } : {}),
+ ...(checkpointFailedIds.length > 0 ? { failedIds: checkpointFailedIds } : {}),
+ ...(checkpointPendingIds.length > 0 && resumeApprovalProjectionDigest
+ ? {
+ recoveryApprovalProjectionSha256ById: Object.fromEntries(
+ Object.entries(resumeApprovalProjectionDigest).filter(([id]) =>
+ checkpointPendingIds.includes(id)),
+ ),
+ }
+ : {}),
});
}
@@ -1491,9 +1506,12 @@ export class GhostManager {
throw new Error('legacy migration ledger exists but is unreadable; recovery queue preserved');
}
const pendingForRetry = new Set(prev?.pendingIds ?? []);
+ const permanentlyBlockedIds = new Set(prev?.failedIds ?? []);
const workIds = [...new Set(ids)].filter(
(id): id is string =>
- isValidGhostId(id) && this.options.isTrustedBundledId?.(id) !== true,
+ isValidGhostId(id) &&
+ this.options.isTrustedBundledId?.(id) !== true &&
+ !permanentlyBlockedIds.has(id),
);
// Persist the complete recovery work queue before the first backfill. If the
// first receipt write or subsequent processing crashes, receiptStore.write()
@@ -1534,9 +1552,12 @@ export class GhostManager {
continue;
}
if (approval.state === 'unreadable') {
- retryIds.push(id);
- pendingForRetry.add(id);
- this.options.log?.warn('recovered legacy receipt unreadable; will retry', {
+ // This id demonstrably had a receipt, so it is not eligible for legacy
+ // auto-approval. Keeping it in pendingIds would let a later receipt
+ // deletion turn mutable installed bytes into a new authorization fact.
+ out.failed.push(id);
+ pendingForRetry.delete(id);
+ this.options.log?.warn('recovered legacy receipt unreadable; automatic backfill blocked', {
id,
reason: approval.reason,
});
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts
index 2a2e127475..f84df88118 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts
@@ -488,7 +488,7 @@ describe('GhostManager · 存量插件一次性迁移(§5 升级无感)', () =>
expect(manager.list()[0]).toMatchObject({ enabled: true, approval: { state: 'approved' } });
});
- it('已有 receipt 瞬时不可读时不从可变安装目录重铸,保留原批准并持久重试', async () => {
+ it('已有 receipt 不可读后即使消失也不从可变安装目录重铸', async () => {
await manager.install(await makeCindy('a.cindy', goodManifest()));
const receiptPath = path.join(workDir, 'ghosts-install-state', 'hello.json');
const receiptBefore = await fs.promises.readFile(receiptPath, 'utf8');
@@ -506,18 +506,20 @@ describe('GhostManager · 存量插件一次性迁移(§5 升级无感)', () =>
const first = await manager.migrateLegacyApprovalsOnce();
- expect(first).toEqual({ migrated: [], skipped: [], failed: [], retryPending: ['hello'] });
+ expect(first).toEqual({ migrated: [], skipped: [], failed: ['hello'], retryPending: [] });
expect(await fs.promises.readFile(receiptPath, 'utf8')).toBe(receiptBefore);
expect(
JSON.parse(await fs.promises.readFile(migrationLedgerPath(), 'utf8')),
- ).toMatchObject({ state: 'in-progress', pendingIds: ['hello'] });
+ ).toMatchObject({ state: 'completed', failedIds: ['hello'] });
- await manager.migrateLegacyApprovalsOnce();
- expect(await fs.promises.readFile(receiptPath, 'utf8')).toBe(receiptBefore);
- expect(
- (JSON.parse(await fs.promises.readFile(migrationLedgerPath(), 'utf8')) as { state?: string })
- .state,
- ).toBe('completed');
+ await fs.promises.rm(receiptPath);
+ const second = await manager.migrateLegacyApprovalsOnce();
+ expect(second).toEqual({ migrated: [], skipped: [], failed: [], retryPending: [] });
+ expect(fs.existsSync(receiptPath)).toBe(false);
+ expect(manager.list()[0]).toMatchObject({
+ approval: { state: 'legacy-unapproved' },
+ enabled: false,
+ });
});
it('首轮迁移治愈损坏/旧 schema 的 receipt(格式升级不落到用户重新确认)', async () => {
@@ -1517,7 +1519,7 @@ describe('GhostManager · review 第 6 轮回归(P0/P1 修复钉住)', () => {
expect(manager.list()[0].approval.state).toBe('legacy-unapproved');
});
- it('恢复旁路遇到 unreadable receipt 同样只排队重试,不重铸批准', async () => {
+ it('恢复旁路遇到 unreadable receipt 后不再允许自动重铸批准', async () => {
await manager.install(await makeCindy('a.cindy', goodManifest()));
const receiptPath = path.join(workDir, 'ghosts-install-state', 'hello.json');
const receiptBefore = await fs.promises.readFile(receiptPath, 'utf8');
@@ -1539,12 +1541,24 @@ describe('GhostManager · review 第 6 轮回归(P0/P1 修复钉住)', () => {
),
).toEqual({
migrated: [],
- failed: [],
+ failed: ['hello'],
});
expect(await fs.promises.readFile(receiptPath, 'utf8')).toBe(receiptBefore);
expect(
JSON.parse(await fs.promises.readFile(migrationLedgerPath(), 'utf8')),
- ).toMatchObject({ state: 'in-progress', pendingIds: ['hello'] });
+ ).toMatchObject({ state: 'completed', failedIds: ['hello'] });
+
+ await fs.promises.rm(receiptPath);
+ const retry = await manager.backfillRecoveredLegacyGhosts(
+ ['hello'],
+ await recoveredProjectionOptions('hello'),
+ );
+ expect(retry).toEqual({ migrated: [], failed: [] });
+ expect(fs.existsSync(receiptPath)).toBe(false);
+ expect(manager.list()[0]).toMatchObject({
+ approval: { state: 'legacy-unapproved' },
+ enabled: false,
+ });
});
it('persists transient recovered-legacy backfill failures in the migration work queue', async () => {
diff --git a/apps/desktop/src/main/device-link/crossProcessLock.ts b/apps/desktop/src/main/device-link/crossProcessLock.ts
index 2957ce3662..4bac351eef 100644
--- a/apps/desktop/src/main/device-link/crossProcessLock.ts
+++ b/apps/desktop/src/main/device-link/crossProcessLock.ts
@@ -676,7 +676,10 @@ async function readLockRecord(
const lockDir = path.dirname(lockPath);
let lockRealDir: string;
try {
- lockRealDir = fsSync.realpathSync(lockDir);
+ // Keep the root and file on the same realpath implementation. On Windows,
+ // Node's sync and async variants can preserve different component casing;
+ // mixing their spellings makes a valid lock record fail containment.
+ lockRealDir = await fsp.realpath(lockDir);
} catch (error) {
const code = (error as NodeJS.ErrnoException)?.code;
if (code === 'ENOENT' || code === 'ENOTDIR') return 'missing';
@@ -1449,7 +1452,9 @@ async function hasValidGateReleaseMarker(gatePath: string, expectedNonce?: strin
const gateDir = path.dirname(gatePath);
let gateRealDir: string;
try {
- gateRealDir = fsSync.realpathSync(gateDir);
+ // This record is read asynchronously below, so anchor the root with the
+ // same async realpath representation (see readLockRecord above).
+ gateRealDir = await fsp.realpath(gateDir);
} catch {
return false;
}
diff --git a/apps/desktop/src/main/utils/__tests__/readBoundedFile.test.ts b/apps/desktop/src/main/utils/__tests__/readBoundedFile.test.ts
index 0575330fdb..0ea5b2c6d7 100644
--- a/apps/desktop/src/main/utils/__tests__/readBoundedFile.test.ts
+++ b/apps/desktop/src/main/utils/__tests__/readBoundedFile.test.ts
@@ -217,20 +217,24 @@ describe('readBoundedFileNoFollow', () => {
async () => {
const file = path.join(workDir, 'drive-case.json');
await fs.promises.writeFile(file, '{"ok":true}');
- const realRoot = fs.realpathSync(workDir);
- const alternateDriveCase = realRoot.replace(/^([A-Za-z]):/, (_, drive: string) => (
- `${drive === drive.toLowerCase() ? drive.toUpperCase() : drive.toLowerCase()}:`
- ));
+ const flipDriveCase = (realRoot: string) =>
+ realRoot.replace(/^([A-Za-z]):/, (_, drive: string) => (
+ `${drive === drive.toLowerCase() ? drive.toUpperCase() : drive.toLowerCase()}:`
+ ));
+ const asyncRootWithAlternateDriveCase = flipDriveCase(
+ await fs.promises.realpath(workDir),
+ );
+ const syncRootWithAlternateDriveCase = flipDriveCase(fs.realpathSync(workDir));
expect(
(await readBoundedFileNoFollow(file, 1024, {
- containWithin: alternateDriveCase,
+ containWithin: asyncRootWithAlternateDriveCase,
noFollowFlag: null,
}))?.toString('utf8'),
).toBe('{"ok":true}');
expect(
readBoundedFileNoFollowSync(file, 1024, {
- containWithin: alternateDriveCase,
+ containWithin: syncRootWithAlternateDriveCase,
noFollowFlag: null,
})?.toString('utf8'),
).toBe('{"ok":true}');