Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(plugins): 修复旧组织插件同版本来源凭据未恢复
liugaowei53a01b8661bb
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/pluginNamespaceMigration.manager.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/pluginNamespaceMigration.manager.test.tsindex 5ca8e294b2..f3674856b4 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/pluginNamespaceMigration.manager.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/pluginNamespaceMigration.manager.test.ts@@ -172,6 +172,39 @@ async function stampLegacyOrganizationInstall(id = 'hello', withSkill = false):}describe('GhostManager namespace migration census', () => {+ it.each([false, true])('repairs the same release in a migrated bare directory without changing storage identity (enabled=%s)', async (enabled) => {+ const archive = vi.fn();+ manager = createManager({ mutateSnapshot, onArchiveSourceState: archive });+ await stampLegacyOrganizationInstall('hello', true);+ await manager.setEnabled('hello', enabled);+ const previous = manager.list()[0];+ expect(manager.approvedInstallEvidence('hello')?.packageSha256).toBeNull();+ const pkg = await makeCindy('hello', true);+ const inspected = await manager.inspect(pkg);+ if ('rejection' in inspected) throw new Error('expected valid market package');++ const result = await manager.update(pkg, {+ namespace: 'acme', expectedInstalledApproval: ghostInstallApprovalToken(previous.approval),+ expectedPackageSha256: inspected.packageSha256,+ });++ expect(result).toMatchObject({ ghost: { dir: previous.dir, namespace: 'acme', enabled, manifest: { version: '1.0.0' } } });+ const restored = manager.list()[0];+ expect(installedGhostStoragePart(restored)).toBe(installedGhostStoragePart(previous));+ expect(archive).not.toHaveBeenCalled();+ expect(await manager.verifyApprovedSkillSnapshot(restored)).toBe(true);+ const evidence = manager.approvedInstallEvidence('hello');+ expect(evidence?.packageSha256).toBe(inspected.packageSha256);+ expect(resolveGhostFirstPartyPrivilege({+ ghostId: 'hello', namespace: 'acme', builtin: false, installOrigin: 'manual',+ currentOrganization: { organizationId: 'org-acme', orgSlug: 'acme' },+ marketRecord: {+ scope: 'organization', organizationId: 'org-acme', source: 'market', installed: true,+ sha256: inspected.packageSha256, approvedPackageSha256: evidence?.packageSha256 ?? null,+ },+ })).toMatchObject({ brokerEligible: true, basis: 'market-organization-current' });+ });+it('retries a failed first directory scan instead of persisting an empty census', async () => {await plantLegacyInstall('hello');const actualRead = fs.readdirSync;diff --git a/apps/desktop/src/main/plugin-market/__tests__/service.test.ts b/apps/desktop/src/main/plugin-market/__tests__/service.test.tsindex 300a4ce0db..944c1afa25 100644--- a/apps/desktop/src/main/plugin-market/__tests__/service.test.ts+++ b/apps/desktop/src/main/plugin-market/__tests__/service.test.ts@@ -233,6 +233,7 @@ const TEST_INSTALL_CONTEXT: PluginMarketInstallContext = {consent: { prompt: async () => true, initiator: 'user' },};import type { PluginMarketApi } from '../api';+import { downloadVerifiedPlugin } from '../download';import { createOrganizationPrefixStore } from '../organizationPrefixStore';const roots: string[] = [];@@ -543,6 +544,139 @@ function namespaceRecoveryHarness(return h;}+function sameReleaseRecoveryHarness(+ source: 'market' | 'legacy-adopted' = 'legacy-adopted',+ layout: 'legacy' | 'namespaced' = 'legacy',+) {+ vi.mocked(downloadVerifiedPlugin).mockClear();+ const canonicalManifest = normalizedManifest(manifest('helper'));+ const dir = installOrganizationHelper(canonicalManifest as unknown as Record<string, unknown>, layout);+ const item = summary({+ ghostId: 'helper', namespace: 'acme', scope: 'organization', organizationId: 'org-1',+ currentRelease: { ...summary().currentRelease, id: RELEASE_ID },+ });+ const h = harness([item]);+ const evidence = { packageSha256: null as string | null, approvedManifest: canonicalManifest, legacyMigrated: true };+ runtime.approvedInstallEvidence.mockImplementation(() => evidence);+ h.ledger.upsertInstallation(recordForTest(item, {+ source, namespace: 'acme', manifestDigest: ghostManifestDigest(canonicalManifest),+ }));+ runtime.install.mockImplementation(async () => {+ evidence.packageSha256 = item.currentRelease.sha256;+ evidence.legacyMigrated = false;+ return runtime.ghosts[0];+ });+ return { ...h, item, evidence, dir };+}++describe('same-release legacy organization source recovery', () => {+ it.each([+ { source: 'legacy-adopted', layout: 'legacy', hasPackage: false },+ { source: 'legacy-adopted', layout: 'namespaced', hasPackage: false },+ { source: 'market', layout: 'legacy', hasPackage: false },+ { source: 'legacy-adopted', layout: 'legacy', hasPackage: true },+ ] as const)('verifies and repairs $source / $layout / hasPackage=$hasPackage once', async ({ source, layout, hasPackage }) => {+ const h = sameReleaseRecoveryHarness(source, layout);+ if (hasPackage) {+ h.evidence.packageSha256 = h.item.currentRelease.sha256;+ h.evidence.legacyMigrated = false;+ }+ runtime.ghosts[0].enabled = false;+ expect((await h.service.snapshot({ discoveryOnly: true })).items[0].installState).toBe('update-available');+ expect(h.api.download).not.toHaveBeenCalled();++ const snapshot = await h.service.snapshot();+ await h.service.snapshot();++ expect(snapshot.items[0]).toMatchObject({ installState: 'installed', enabled: false });+ expect(h.api.download).toHaveBeenCalledExactlyOnceWith(h.item.id, RELEASE_ID);+ expect(downloadVerifiedPlugin).toHaveBeenCalledTimes(1);+ expect(runtime.install).toHaveBeenCalledExactlyOnceWith(expect.any(String), expect.objectContaining({+ ghostId: 'helper', namespace: 'acme', expectedInstalledApproval: APPROVED_INSTALL_TOKEN,+ pendingMarketRecord: expect.objectContaining({ source: 'market', sha256: h.item.currentRelease.sha256 }),+ }));+ expect(runtime.install.mock.calls[0][1]).not.toHaveProperty('sourceChanged');+ expect(runtime.ghosts[0].dir).toBe(h.dir);+ expect(runtime.ghosts[0].enabled).toBe(false);+ expect(runtime.uninstall).not.toHaveBeenCalled();+ expect(h.ledger.installationForGhost('helper')).toMatchObject({ source: 'market', installed: true, releaseId: RELEASE_ID });+ });++ it.each(['healthy', 'modern-without-sha', 'missing-evidence', 'package-conflict', 'manifest-conflict', 'forge', 'other-org', 'unapproved'] as const)(+ 'does not reinterpret %s as a legacy recovery', async (scenario) => {+ const h = sameReleaseRecoveryHarness(scenario === 'healthy' ? 'market' : 'legacy-adopted');+ if (scenario === 'healthy') h.evidence.packageSha256 = h.item.currentRelease.sha256;+ if (scenario === 'modern-without-sha') h.evidence.legacyMigrated = false;+ if (scenario === 'missing-evidence') runtime.approvedInstallEvidence.mockReturnValue(null);+ if (scenario === 'package-conflict') h.evidence.packageSha256 = 'f'.repeat(64);+ if (scenario === 'manifest-conflict') h.evidence.approvedManifest = normalizedManifest(manifest('helper', '0.9.0'));+ if (scenario === 'forge') runtime.installOrigins.set('helper', 'agent-forge');+ if (scenario === 'other-org') runtime.authIdentity!.orgId = 'other-org';+ if (scenario === 'unapproved') runtime.ghosts[0].approval = { state: 'invalid' };+ const before = h.ledger.installationForGhost('helper');++ await h.service.snapshot();++ expect(h.api.download).not.toHaveBeenCalled();+ expect(runtime.install).not.toHaveBeenCalled();+ expect(h.ledger.installationForGhost('helper')?.source).toBe(before?.source);+ },+ );++ it('keeps legacy trust on failed package verification and uses existing retry backoff', async () => {+ const h = sameReleaseRecoveryHarness();+ vi.mocked(downloadVerifiedPlugin).mockRejectedValueOnce(new Error('Plugin package SHA256 mismatch'));++ await h.service.snapshot();+ await h.service.snapshot();++ expect(h.api.download).toHaveBeenCalledTimes(1);+ expect(runtime.install).not.toHaveBeenCalled();+ expect(h.evidence.packageSha256).toBeNull();+ expect(h.ledger.installationForGhost('helper')?.source).toBe('legacy-adopted');+ });++ it('waits for active calls and repairs on the next reconciliation', async () => {+ const h = sameReleaseRecoveryHarness();+ runtime.pendingCalls = true;+ expect((await h.service.snapshot()).items[0].installState).toBe('update-available');+ expect(h.api.download).not.toHaveBeenCalled();+ runtime.pendingCalls = false;+ expect((await h.service.snapshot()).items[0].installState).toBe('installed');+ expect(runtime.install).toHaveBeenCalledTimes(1);+ });++ it.each(['approval', 'owner'] as const)('does not commit recovery when %s changes during download', async (changed) => {+ const h = sameReleaseRecoveryHarness();+ const download = h.api.download.getMockImplementation()!;+ h.api.download.mockImplementationOnce(async (...args) => {+ const result = await download(...args);+ if (changed === 'owner') runtime.session.generation += 1;+ else runtime.ghosts[0].approval = { state: 'approved', revision: '00000000-0000-4000-8000-000000000002' };+ return result;+ });+ if (changed === 'owner') await expect(h.service.snapshot()).rejects.toThrow('active account changed');+ else await h.service.snapshot();+ expect(runtime.install).not.toHaveBeenCalled();+ expect(h.ledger.installationForGhost('helper')?.source).toBe('legacy-adopted');+ });++ it('does not bypass update consent if the verified same-release package adds permissions', async () => {+ const h = sameReleaseRecoveryHarness();+ const expanded = manifest('helper', '1.0.0', ['notify', 'fs']);+ h.api.detail.mockResolvedValue({ ...h.item, currentRelease: { ...h.item.currentRelease, manifest: expanded } });+ runtime.inspectedManifest = expanded;++ const snapshot = await h.service.snapshot();+ await h.service.snapshot();++ expect(snapshot.items[0]).toMatchObject({ installState: 'update-available', updateRequiresConsent: true });+ expect(h.api.download).toHaveBeenCalledTimes(1);+ expect(runtime.install).not.toHaveBeenCalled();+ expect(h.ledger.installationForGhost('helper')?.source).toBe('legacy-adopted');+ });+});+describe('PluginMarketService migration and defaultInstall', () => {it.each([{ namespace: undefined, evidence: 'matching' },@@ -1488,9 +1622,11 @@ describe('PluginMarketService migration and defaultInstall', () => {});h.ledger.markRemovedRecord(h.ledger.installationForGhost(item.ghostId)!, 'user-1');+ // Hold the verified update so route recovery alone must remain untrusted.+ runtime.pendingCalls = true;const snapshot = await h.service.snapshot();- expect(snapshot.items[0]).toMatchObject({ installState: 'installed', enabled: true });+ expect(snapshot.items[0]).toMatchObject({ installState: 'update-available', enabled: true });expect(h.ledger.installationForGhost(item.ghostId)).toMatchObject({installed: true,source: 'legacy-adopted',@@ -1509,11 +1645,13 @@ describe('PluginMarketService migration and defaultInstall', () => {});const h = namespaceRecoveryHarness([publicItem, orgItem], orgItem);+ // Hold the verified update so route recovery alone must remain untrusted.+ runtime.pendingCalls = true;const snapshot = await h.service.snapshot();expect(h.ledger.installationForPlugin({ namespace: 'acme', ghostId: 'helper' })).toMatchObject({ installed: true, pluginId: orgItem.id });- expect(snapshot.items.find((item) => item.pluginId === orgItem.id)?.installState).toBe('installed');+ expect(snapshot.items.find((item) => item.pluginId === orgItem.id)?.installState).toBe('update-available');expect(h.api.download).not.toHaveBeenCalled();});diff --git a/apps/desktop/src/main/plugin-market/service.ts b/apps/desktop/src/main/plugin-market/service.tsindex 16d5fdaa53..b4781be1a4 100644--- a/apps/desktop/src/main/plugin-market/service.ts+++ b/apps/desktop/src/main/plugin-market/service.ts@@ -2530,11 +2530,31 @@ export class PluginMarketService {(!hasDeliveryNamespace(plugin) && plugin.scope === 'organization' &&local.ghosts.some((candidate) => candidate.manifest.id === plugin.ghostId &&hasDeliveryNamespace(candidate) && candidate.namespace !== null) && target === plugin));+ // A recovered legacy route may already name the current release without+ // having its approved package evidence. Reinstall through the verified+ // market update transaction; neither the route nor the manifest grants trust.+ let needsSourceRecovery = false;+ if (matchesUpdateRoute && ghost?.approval.state === 'approved' && identity && record &&+ record.releaseId === plugin.currentRelease.id &&+ record.sha256 === plugin.currentRelease.sha256 &&+ record.scope === 'organization') {+ const user = getAuthState().user;+ const manager = getGhostManager();+ const physicalId = installedGhostPhysicalRelId(ghost);+ const evidence = manager.approvedInstallEvidence(physicalId);+ if (user?.membershipKind === 'org' && record.organizationId === user.orgId &&+ evidence && manager.readApprovedInstallOriginStrict(physicalId) !== 'agent-forge' &&+ installedIdentityMatchesManifest(identity, evidence.approvedManifest)) {+ needsSourceRecovery = evidence.packageSha256 === null+ ? evidence.legacyMigrated+ : record.source === 'legacy-adopted' && evidence.packageSha256 === record.sha256;+ }+ }const installState: PluginMarketItem['installState'] = conflict? 'conflict': !matchesUpdateRoute? 'not-installed'- : record?.releaseId === plugin.currentRelease.id+ : record?.releaseId === plugin.currentRelease.id && !needsSourceRecovery? 'installed': 'update-available';const projectedTarget = matchesUpdateRoute && !hasDeliveryNamespace(target) &&diff --git a/docs/dev-rules/plugin-security-and-authoring.md b/docs/dev-rules/plugin-security-and-authoring.mdindex 36f5150d90..caf715555c 100644--- a/docs/dev-rules/plugin-security-and-authoring.md+++ b/docs/dev-rules/plugin-security-and-authoring.md@@ -264,6 +264,12 @@ Library 请求同时绑定迁移代次和安装批准,根解析、排队及开安全边界校验,不能把包内容异常降级成“仍要安装”。- 自动对账在 owner 稳定后的启动/登录切换、应用回前台、系统唤醒和 30 分钟周期触发。不新增持久化任务队列或“是否自动更新”设置;卸载写下的 opt-out 继续阻止默认安装复活。+- 当前组织的历史市场安装即使已指向当前 release,也须恢复遗漏的来源证明:有效批准与+ 原始 manifest 仍匹配更新路由,且已完成旧迁移但缺包 SHA,或 `legacy-adopted` 记录与+ 批准包 SHA 一致时,通过同一市场更新事务重新下载、校验并原位落位。仅补来源字段不能+ 代替包验证;Forge、显式 SHA 冲突及不匹配的组织/来源不进入此恢复。沿用更新确认、+ 忙碌跳过和失败退避,保留启停态、实例键和同来源用户数据。实现与回归见+ `main/plugin-market/service.ts` 及其 `__tests__/service.test.ts`。- 同一 release 自动更新失败后,在当前进程内按 owner、来源路由和 release 做指数退避(5 分钟起、最长 6 小时),日志记录失败次数与下次重试时间;来源发布新 release 时立即解除。忙碌跳过不记失败,用户手动重试不受退避限制。