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。

feat(desktop): forge 打包产物直写 Host staging,不再经 agent 可写路径

fmfsaisaid86e25d725f4
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/forgePackStaging.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/forgePackStaging.test.ts
new file mode 100644
index 0000000000..31b1c31a2c
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/__tests__/forgePackStaging.test.ts
@@ -0,0 +1,264 @@
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { afterEach, describe, expect, it } from 'vitest';
+
+import type { ActiveAppSession } from '../../appSessionState.js';
+import {
+ completeForgePackStaging,
+ configureForgePackStagingForTests,
+ createForgePackStagingController,
+ resetForgePackStagingForTests,
+ sha256Hex,
+} from '../forgePackStaging.js';
+
+const OWNER_A: ActiveAppSession = {
+ mode: 'cloud',
+ dataOwnerId: 'user-a',
+ generation: 1,
+};
+
+const OWNER_B: ActiveAppSession = {
+ mode: 'cloud',
+ dataOwnerId: 'user-b',
+ generation: 2,
+};
+
+let tempDir: string | null = null;
+const timeouts: Array<{ fire(): void; cancel(): void }> = [];
+
+afterEach(() => {
+ for (const timeout of timeouts.splice(0)) timeout.cancel();
+ resetForgePackStagingForTests();
+ if (tempDir) {
+ fs.rmSync(tempDir, { recursive: true, force: true });
+ tempDir = null;
+ }
+});
+
+function makeTempDir(): string {
+ tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-forge-staging-'));
+ return tempDir;
+}
+
+function controller(overrides: Partial<Parameters<typeof createForgePackStagingController>[0]> = {}) {
+ const dir = tempDir ?? makeTempDir();
+ return createForgePackStagingController({
+ getTempDir: () => dir,
+ randomId: () => 'unpredictable-token',
+ scheduleTimeout: (ms, callback) => {
+ let cancelled = false;
+ const handle = {
+ fire() {
+ if (!cancelled) callback();
+ },
+ cancel() {
+ cancelled = true;
+ },
+ };
+ timeouts.push(handle);
+ void ms;
+ return handle;
+ },
+ ...overrides,
+ });
+}
+
+describe('createForgePackStagingController', () => {
+ it('writes staging bytes from the in-memory buffer, not a later workdir rewrite', () => {
+ const dir = makeTempDir();
+ const workdirCopy = path.join(dir, 'author-demo-1.0.0.cindy');
+ const buf = Buffer.from('built-from-memory');
+ fs.writeFileSync(workdirCopy, buf);
+ const staging = controller({
+ randomId: (() => {
+ let n = 0;
+ return () => (n++ === 0 ? 'task-dir-id' : 'ticket-id');
+ })(),
+ }).stage({
+ buf,
+ manifestId: 'demo',
+ owner: OWNER_A,
+ operationKind: 'install',
+ });
+
+ fs.writeFileSync(workdirCopy, Buffer.from('agent-replaced-bytes'));
+ expect(fs.readFileSync(staging.stagingPath)).toEqual(buf);
+ expect(fs.readFileSync(workdirCopy).toString()).toBe('agent-replaced-bytes');
+ expect(staging.stagingPath).not.toBe(workdirCopy);
+ expect(staging.stagingPath.startsWith(dir)).toBe(true);
+ expect(staging.packageSha256).toBe(sha256Hex(buf));
+ expect(staging.packageSha256).not.toBe(sha256Hex(Buffer.from('agent-replaced-bytes')));
+ });
+
+ it('issues an unguessable ticket bound to owner, kind, staging path, hash, and manifest id', () => {
+ const ids: string[] = [];
+ const issued = controller({
+ randomId: () => {
+ const id = `rand-${cryptoRandom()}`;
+ ids.push(id);
+ return id;
+ },
+ });
+ const staging = issued.stage({
+ buf: Buffer.from('pkg'),
+ manifestId: 'acme-tool',
+ owner: OWNER_A,
+ operationKind: 'update',
+ });
+
+ expect(ids).toHaveLength(2);
+ expect(staging.ticket).toBe(ids[1]);
+ expect(staging.ticket).not.toMatch(/^\d+$/);
+ expect(staging.ticket).not.toMatch(/T\d{2}:\d{2}/);
+ expect(staging.taskDir).toContain(ids[0]);
+ expect(issued.peek(staging.ticket)).toEqual({
+ owner: OWNER_A,
+ operationKind: 'update',
+ stagingPath: staging.stagingPath,
+ packageSha256: sha256Hex(Buffer.from('pkg')),
+ manifestId: 'acme-tool',
+ });
+ });
+
+ it('lets peek read the five bound fields from the issuing controller', () => {
+ const issued = controller({
+ randomId: (() => {
+ let n = 0;
+ return () => ['task-aaaa', 'ticket-bbbb'][n++] ?? `extra-${n}`;
+ })(),
+ });
+ const staged = issued.stage({
+ buf: Buffer.from('pkg'),
+ manifestId: 'acme-tool',
+ owner: OWNER_A,
+ operationKind: 'update',
+ });
+ expect(issued.peek(staged.ticket)).toEqual({
+ owner: OWNER_A,
+ operationKind: 'update',
+ stagingPath: staged.stagingPath,
+ packageSha256: sha256Hex(Buffer.from('pkg')),
+ manifestId: 'acme-tool',
+ });
+ });
+
+ it('creates an unpredictable 0700 task dir and a 0600 staging file', () => {
+ const dir = makeTempDir();
+ const issued = controller({
+ getTempDir: () => dir,
+ randomId: (() => {
+ let n = 0;
+ return () => ['task-secret', 'ticket-secret'][n++] ?? `x-${n}`;
+ })(),
+ });
+ const staged = issued.stage({
+ buf: Buffer.from('pkg'),
+ manifestId: 'demo',
+ owner: OWNER_A,
+ operationKind: 'install',
+ });
+ expect(path.basename(staged.taskDir)).toBe('cindy-forge-task-secret');
+ expect(staged.taskDir.startsWith(dir)).toBe(true);
+ if (process.platform !== 'win32') {
+ expect(fs.statSync(staged.taskDir).mode & 0o777).toBe(0o700);
+ expect(fs.statSync(staged.stagingPath).mode & 0o777).toBe(0o600);
+ }
+ });
+
+ it('cleans staging and drops the ticket on cancel, timeout, and owner change', () => {
+ let clock = 0;
+ const pendingTimeouts: Array<() => void> = [];
+ const issued = controller({
+ now: () => clock,
+ ttlMs: 100,
+ randomId: (() => {
+ let n = 0;
+ return () => `id-${n++}`;
+ })(),
+ scheduleTimeout: (_ms, callback) => {
+ pendingTimeouts.push(callback);
+ return { cancel: () => {} };
+ },
+ });
+ const first = issued.stage({
+ buf: Buffer.from('one'),
+ manifestId: 'demo',
+ owner: OWNER_A,
+ operationKind: 'install',
+ });
+ expect(fs.existsSync(first.stagingPath)).toBe(true);
+ expect(issued.invalidate(first.ticket)).toBe(true);
+ expect(fs.existsSync(first.stagingPath)).toBe(false);
+ expect(issued.peek(first.ticket)).toBeNull();
+
+ const second = issued.stage({
+ buf: Buffer.from('two'),
+ manifestId: 'demo',
+ owner: OWNER_A,
+ operationKind: 'install',
+ });
+ expect(fs.existsSync(second.stagingPath)).toBe(true);
+ pendingTimeouts.at(-1)!();
+ expect(fs.existsSync(second.stagingPath)).toBe(false);
+ expect(issued.peek(second.ticket)).toBeNull();
+
+ const third = issued.stage({
+ buf: Buffer.from('three'),
+ manifestId: 'demo',
+ owner: OWNER_A,
+ operationKind: 'install',
+ });
+ issued.invalidateMismatchedOwners(OWNER_B);
+ expect(fs.existsSync(third.stagingPath)).toBe(false);
+ expect(issued.peek(third.ticket)).toBeNull();
+ });
+
+ it('does not create directories or files when the module is imported', async () => {
+ const dir = makeTempDir();
+ const before = fs.readdirSync(dir);
+ await import('../forgePackStaging.js');
+ expect(fs.readdirSync(dir)).toEqual(before);
+ });
+
+ it('stages completeForgePackStaging from buf even when authorCindyPath holds different bytes', () => {
+ const dir = makeTempDir();
+ configureForgePackStagingForTests({
+ getTempDir: () => dir,
+ randomId: (() => {
+ let n = 0;
+ return () => ['task-id', 'ticket-id'][n++] ?? `n-${n}`;
+ })(),
+ scheduleTimeout: () => ({ cancel() {} }),
+ });
+ const authorDir = path.join(dir, 'workdir');
+ fs.mkdirSync(authorDir, { recursive: true });
+ const authorCindyPath = path.join(authorDir, 'demo-1.0.0.cindy');
+ const authorBytes = Buffer.from('author-copy-A');
+ const memoryBytes = Buffer.from('memory-buf-B');
+ fs.writeFileSync(authorCindyPath, authorBytes);
+
+ const completed = completeForgePackStaging({
+ buf: memoryBytes,
+ manifestId: 'demo',
+ owner: OWNER_A,
+ operationKind: 'install',
+ authorCindyPath,
+ });
+
+ expect(fs.readFileSync(completed.installPath)).toEqual(memoryBytes);
+ expect(fs.readFileSync(completed.installPath)).not.toEqual(authorBytes);
+ expect(completed.installPath).toBe(path.join(dir, 'cindy-forge-task-id', 'package.cindy'));
+ expect(completed.agentCindyPath).toBe('demo-1.0.0.cindy');
+ expect(path.isAbsolute(completed.agentCindyPath)).toBe(false);
+ expect(completed.agentCindyPath.includes(path.sep)).toBe(false);
+ expect(completed.installPath).not.toContain('workdir');
+
+ fs.writeFileSync(authorCindyPath, Buffer.from('author-copy-C'));
+ expect(fs.readFileSync(completed.installPath)).toEqual(memoryBytes);
+ });
+});
+
+function cryptoRandom(): string {
+ return Math.random().toString(16).slice(2);
+}
diff --git a/apps/desktop/src/main/cindy-brain/forge.ts b/apps/desktop/src/main/cindy-brain/forge.ts
index 3cbf725090..6893408b1e 100644
--- a/apps/desktop/src/main/cindy-brain/forge.ts
+++ b/apps/desktop/src/main/cindy-brain/forge.ts
@@ -6,8 +6,9 @@
* 喂给 agent——替代"人读的作者文档",同事对 AI 说"帮我做个 XX 意识"即可;
* - packGhostDir:源码目录 → 校验(与装入同一套 validateGhostManifest)→
* 打包 .cindy 到源码目录自身(id-version.cindy,同名覆盖;shouldSkip 跳过
- * *.cindy 防套娃)。装入确认弹窗由调用方(mcp-integrations 接线)经双击
- * 转交通道触发,本文件不碰 UI。
+ * *.cindy 防套娃),并同时返回内存里的 `buf`。作者副本给人拿走;安装链路
+ * 必须用 `buf` 直写 Host staging,不能从源码目录回读。装入确认弹窗由
+ * 调用方(mcp-integrations 接线)经双击转交通道触发,本文件不碰 UI。
*
* 安全边界:agent 能写意识源码(它本来就有文件工具),但打包必须过校验、
* 装入必须过用户确认框(默认沉睡)——与手动拖 .cindy 完全同一条门。
@@ -163,7 +164,7 @@ function shouldSkip(name: string): boolean {
}
export type ForgePackResult =
- | { ok: true; cindyPath: string; manifest: GhostManifest }
+ | { ok: true; cindyPath: string; manifest: GhostManifest; buf: Buffer }
| {
ok: false;
errorCode:
@@ -1320,7 +1321,9 @@ export async function packGhostDir(
message: `写入打包产物失败:${err instanceof Error ? err.message : String(err)}`,
};
}
- return { ok: true, cindyPath, manifest: built.manifest };
+ // 作者目录里的副本只给人手动拿走。安装链路必须用内存里的 `buf` 直写
+ // staging,绝不能从 cindyPath 回读——agent 能在确认前替换那份文件。
+ return { ok: true, cindyPath, manifest: built.manifest, buf: built.buf };
}
/**
@@ -1374,7 +1377,7 @@ export async function packGhostDirToFile(
message: `写入打包产物失败:${err instanceof Error ? err.message : String(err)}`,
};
}
- return { ok: true, cindyPath: destPath, manifest: built.manifest };
+ return { ok: true, cindyPath: destPath, manifest: built.manifest, buf: built.buf };
}
/**
diff --git a/apps/desktop/src/main/cindy-brain/forgePackStaging.ts b/apps/desktop/src/main/cindy-brain/forgePackStaging.ts
new file mode 100644
index 0000000000..3e0da57472
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/forgePackStaging.ts
@@ -0,0 +1,309 @@
+/**
+ * Forge pack 产物的 Host 侧 staging 与一次性完整 ticket。
+ *
+ * 被注入的 agent 能在用户确认前改写 workdir 里的 `.cindy`。安装链路因此
+ * 绝不能从那条路径回读:必须把内存里的 `built.buf` 直接写进 Host 生成的
+ * staging。本模块只负责直写、加固、签发与失效;inspect / install 消费
+ * ticket 是下一步,这里不做。
+ *
+ * 不在 import 时创建目录或写文件。
+ */
+import crypto from 'node:crypto';
+import fs from 'node:fs';
+import path from 'node:path';
+
+import type { ActiveAppSession } from '../appSessionState.js';
+
+export const FORGE_PACK_TICKET_TTL_MS = 10 * 60 * 1000;
+
+export type ForgePackOperationKind = 'install' | 'update';
+
+export interface ForgePackIntegrityTicket {
+ owner: ActiveAppSession;
+ /**
+ * Hint / audit only. Captured at pack time from the then-current install list.
+ * Between pack and consume the same id may be installed or removed by another
+ * entry, so a consumer **must not** treat this as an immutable reject
+ * condition. Real install-vs-update classification happens after the consume
+ * entry takes the install lock and is allowed to differ from this value.
+ *
+ * Strong, one-shot bindings are owner, stagingPath, packageSha256, and
+ * manifestId — not this field.
+ */
+ operationKind: ForgePackOperationKind;
+ stagingPath: string;
+ packageSha256: string;
+ manifestId: string;
+}
+
+export interface StageBuiltGhostPackageInput {
+ buf: Buffer;
+ manifestId: string;
+ owner: ActiveAppSession;
+ operationKind: ForgePackOperationKind;
+}
+
+export interface StageBuiltGhostPackageResult {
+ ticket: string;
+ stagingPath: string;
+ taskDir: string;
+ packageSha256: string;
+}
+
+export interface ForgePackStagingController {
+ stage(input: StageBuiltGhostPackageInput): StageBuiltGhostPackageResult;
+ /** Look up without consuming. Consumption is ⑥a-2. */
+ peek(token: string): ForgePackIntegrityTicket | null;
+ invalidate(token: string): boolean;
+ invalidateMismatchedOwners(current: ActiveAppSession): void;
+ invalidateAll(): void;
+}
+
+export interface CreateForgePackStagingControllerOptions {
+ getTempDir(): string;
+ now?: () => number;
+ ttlMs?: number;
+ randomId?: () => string;
+ scheduleTimeout?: (ms: number, callback: () => void) => { cancel(): void };
+}
+
+function isSameOwner(a: ActiveAppSession, b: ActiveAppSession): boolean {
+ return a.mode === b.mode && a.dataOwnerId === b.dataOwnerId && a.generation === b.generation;
+}
+
+export function sha256Hex(buf: Buffer): string {
+ return crypto.createHash('sha256').update(buf).digest('hex');
+}
+
+function noFollowFlag(): number {
+ return typeof fs.constants.O_NOFOLLOW === 'number' ? fs.constants.O_NOFOLLOW : 0;
+}
+
+function assertManagedDirectory(dirPath: string, expectedRealParent: string): void {
+ const stat = fs.lstatSync(dirPath);
+ if (stat.isSymbolicLink() || !stat.isDirectory()) {
+ throw new Error('Forge pack staging parent is not a real directory');
+ }
+ const realDir = fs.realpathSync.native(dirPath);
+ const realParent = fs.realpathSync.native(expectedRealParent);
+ if (path.dirname(realDir) !== realParent) {
+ throw new Error('Forge pack staging escaped its temp parent');
+ }
+}
+
+/**
+ * Write `buf` to a brand-new file. The destination must not already exist, so
+ * there is no replace/rename: `O_CREAT|O_EXCL|O_NOFOLLOW` opens the final name
+ * once. A temp+rename pair would let a same-privilege process create the
+ * target between lstat and rename and get overwritten.
+ */
+function writeExclusiveNoFollow(filePath: string, buf: Buffer, managedParent: string): void {
+ const parent = path.dirname(filePath);
+ if (path.resolve(parent) !== path.resolve(managedParent)) {
+ throw new Error('Forge pack staging file is not inside its task directory');
+ }
+ assertManagedDirectory(parent, path.dirname(parent));
+ const flags =
+ fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL | noFollowFlag();
+ const fd = fs.openSync(filePath, flags, 0o600);
+ let written = false;
+ try {
+ fs.writeSync(fd, buf);
+ try {
+ fs.fchmodSync(fd, 0o600);
+ } catch {
+ // Windows ignores POSIX modes.
+ }
+ written = true;
+ } finally {
+ fs.closeSync(fd);
+ if (!written) {
+ try {
+ fs.unlinkSync(filePath);
+ } catch {
+ // Best-effort.
+ }
+ }
+ }
+}
+
+function rmTaskDir(taskDir: string): void {
+ fs.rmSync(taskDir, { recursive: true, force: true });
+}
+
+export function createForgePackStagingController(
+ options: CreateForgePackStagingControllerOptions,
+): ForgePackStagingController {
+ const now = options.now ?? Date.now;
+ const ttlMs = options.ttlMs ?? FORGE_PACK_TICKET_TTL_MS;
+ const randomId = options.randomId ?? (() => crypto.randomUUID());
+ const scheduleTimeout =
+ options.scheduleTimeout ??
+ ((ms, callback) => {
+ const handle = setTimeout(callback, ms);
+ return { cancel: () => clearTimeout(handle) };
+ });
+
+ type Entry = {
+ ticket: ForgePackIntegrityTicket;
+ expiresAt: number;
+ timeout: { cancel(): void };
+ };
+ const tickets = new Map<string, Entry>();
+
+ const drop = (token: string, removeFiles: boolean): boolean => {
+ const entry = tickets.get(token);
+ if (!entry) return false;
+ tickets.delete(token);
+ entry.timeout.cancel();
+ if (removeFiles) rmTaskDir(path.dirname(entry.ticket.stagingPath));
+ return true;
+ };
+
+ return {
+ stage(input) {
+ const tempRoot = options.getTempDir();
+ const taskDir = path.join(tempRoot, `cindy-forge-${randomId()}`);
+ fs.mkdirSync(taskDir, { recursive: false, mode: 0o700 });
+ try {
+ fs.chmodSync(taskDir, 0o700);
+ } catch {
+ // Windows ignores POSIX modes.
+ }
+ assertManagedDirectory(taskDir, tempRoot);
+ const stagingPath = path.join(taskDir, 'package.cindy');
+ try {
+ writeExclusiveNoFollow(stagingPath, input.buf, taskDir);
+ } catch (error) {
+ rmTaskDir(taskDir);
+ throw error;
+ }
+ const token = randomId();
+ const packageSha256 = sha256Hex(input.buf);
+ const ticket: ForgePackIntegrityTicket = {
+ owner: {
+ mode: input.owner.mode,
+ dataOwnerId: input.owner.dataOwnerId,
+ generation: input.owner.generation,
+ },
+ operationKind: input.operationKind,
+ stagingPath,
+ packageSha256,
+ manifestId: input.manifestId,
+ };
+ const timeout = scheduleTimeout(ttlMs, () => {
+ drop(token, true);
+ });
+ tickets.set(token, { ticket, expiresAt: now() + ttlMs, timeout });
+ return { ticket: token, stagingPath, taskDir, packageSha256 };
+ },
+
+ peek(token) {
+ const entry = tickets.get(token);
+ if (!entry) return null;
+ if (entry.expiresAt <= now()) {
+ drop(token, true);
+ return null;
+ }
+ return entry.ticket;
+ },
+
+ invalidate(token) {
+ return drop(token, true);
+ },
+
+ invalidateMismatchedOwners(current) {
+ for (const [token, entry] of [...tickets]) {
+ if (!isSameOwner(entry.ticket.owner, current)) drop(token, true);
+ }
+ },
+
+ invalidateAll() {
+ for (const token of [...tickets.keys()]) drop(token, true);
+ },
+ };
+}
+
+let productionController: ForgePackStagingController | null = null;
+let getProductionTempDir: (() => string) | null = null;
+
+export function configureForgePackStagingForTests(
+ options: CreateForgePackStagingControllerOptions,
+): ForgePackStagingController {
+ productionController?.invalidateAll();
+ productionController = createForgePackStagingController(options);
+ getProductionTempDir = options.getTempDir;
+ return productionController;
+}
+
+export function resetForgePackStagingForTests(): void {
+ productionController?.invalidateAll();
+ productionController = null;
+ getProductionTempDir = null;
+}
+
+/** Bind Electron temp lazily. Calling this does not create files. */
+export function bindForgePackStagingTempDir(getTempDir: () => string): void {
+ getProductionTempDir = getTempDir;
+}
+
+function getController(): ForgePackStagingController {
+ if (!productionController) {
+ if (!getProductionTempDir) {
+ throw new Error('Forge pack staging temp dir is not configured');
+ }
+ productionController = createForgePackStagingController({
+ getTempDir: getProductionTempDir,
+ });
+ }
+ return productionController;
+}
+
+export function stageBuiltGhostPackage(
+ input: StageBuiltGhostPackageInput,
+): StageBuiltGhostPackageResult {
+ return getController().stage(input);
+}
+
+/**
+ * Host-only install path + agent-safe filename. Staging never goes back to
+ * the agent. `authorCindyPath` is used only for `path.basename` in the agent
+ * return; it is never read. Staging bytes always come from `buf`.
+ */
+export function completeForgePackStaging(input: {
+ buf: Buffer;
+ manifestId: string;
+ owner: ActiveAppSession;
+ operationKind: ForgePackOperationKind;
+ authorCindyPath: string;
+}): {
+ ticket: string;
+ installPath: string;
+ agentCindyPath: string;
+ packageSha256: string;
+} {
+ const staged = stageBuiltGhostPackage({
+ buf: input.buf,
+ manifestId: input.manifestId,
+ owner: input.owner,
+ operationKind: input.operationKind,
+ });
+ return {
+ ticket: staged.ticket,
+ installPath: staged.stagingPath,
+ agentCindyPath: path.basename(input.authorCindyPath),
+ packageSha256: staged.packageSha256,
+ };
+}
+
+export function peekForgePackTicket(token: string): ForgePackIntegrityTicket | null {
+ return getController().peek(token);
+}
+
+export function invalidateForgePackTicket(token: string): boolean {
+ return productionController?.invalidate(token) ?? false;
+}
+
+export function invalidateForgePackTicketsForOwner(current: ActiveAppSession): void {
+ productionController?.invalidateMismatchedOwners(current);
+}
diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.ts
index 60257137d2..566143ad14 100644
--- a/apps/desktop/src/main/cindy-brain/index.ts
+++ b/apps/desktop/src/main/cindy-brain/index.ts
@@ -80,6 +80,10 @@ import {
import { exportGhostPackage } from './exportGhostPackage.js';
import { GhostMutationCoordinator } from './ghostMutationCoordinator.js';
import { createOneShotTicketStore } from './oneShotTickets.js';
+import {
+ bindForgePackStagingTempDir,
+ invalidateForgePackTicketsForOwner,
+} from './forgePackStaging.js';
import { withGhostInstallLock } from './ghostInstallLock.js';
import {
GhostPackagePermissionReviewRequiredError,
@@ -6243,11 +6247,13 @@ export function registerGhostIpc(): void {
};
void app.whenReady().then(() => {
+ bindForgePackStagingTempDir(() => app.getPath('temp'));
onAuthStateChange(() => {
// Login/logout, Membership switches, and refresh integration all cross
// an auth notification boundary. Discard every short-lived Connection
// assertion so a late request can never reuse the previous identity.
connectionTokenProviderSingleton?.clearAll();
+ invalidateForgePackTicketsForOwner(getActiveAppSession());
// 当前任务绑定属于窗口内的 owner 上下文,切账号/会员身份后不得沿用旧快照。
ghostSessionFocusByWebContents.clear();
clearIOSSimulatorRendererAccess();
diff --git a/apps/desktop/src/main/mcp-integrations/ghost.ts b/apps/desktop/src/main/mcp-integrations/ghost.ts
index 0cc4acb448..81739ee987 100644
--- a/apps/desktop/src/main/mcp-integrations/ghost.ts
+++ b/apps/desktop/src/main/mcp-integrations/ghost.ts
@@ -79,6 +79,10 @@ import { classifyGhostVisibility } from '../cindy-brain/ghostVisibility.js';
import { readInstalledGhostManual } from '../cindy-brain/ghostManual.js';
import { isGhostDisabledForWorkdir } from '../cindy-brain/ghostWorkdirPrefs.js';
import { FORGE_GUIDE, packGhostDir, scaffoldGhostDir } from '../cindy-brain/forge.js';
+import {
+ completeForgePackStaging,
+ invalidateForgePackTicket,
+} from '../cindy-brain/forgePackStaging.js';
import {
currentPublisherIdentity,
getPluginPublisherOrchestrator,
@@ -1776,14 +1780,50 @@ export function getCindyGhostsMcpDeps(
...(sessionTitle ? { sessionTitle } : {}),
...(sourceRelPath ? { sourceRelPath } : {}),
};
- // 与双击 .cindy 同一条转交通道:renderer 弹标准确认框(同 id 已装则
- // 自动转"更新 vX → vY"),用户点头才真装。lease 持到转交完成。带上 agent
- // 来源,确认框据此展示来源横幅 + 分级加重(高危需手输 id 确认)。
- await handleIncomingCindyFile(packed.cindyPath, 'ghost-forge', origin);
- log.info('ghost forge packed', { dir, cindyPath: packed.cindyPath, id: packed.manifest.id });
+ const owner = captureGhostMutationOwnerForMcp();
+ const alreadyInstalled = getGhostManager()
+ .list()
+ .some((ghost) => ghost.manifest.id === packed.manifest.id);
+ let staged;
+ try {
+ // 安装链路只认这份内存字节直写的 staging。workdir 里的 .cindy 只是
+ // 作者副本;agent 换掉它不能改确认框将要检查的包。
+ // operationKind 只是打包时点的提示/审计,不是不可变拒绝条件:
+ // 打包到消费之间同 id 可能被另一入口装上或卸掉,真实分类在消费
+ // 入口持锁后重做,允许与票里的值不同。
+ staged = completeForgePackStaging({
+ buf: packed.buf,
+ manifestId: packed.manifest.id,
+ owner,
+ operationKind: alreadyInstalled ? 'update' : 'install',
+ authorCindyPath: packed.cindyPath,
+ });
+ } catch (err) {
+ return {
+ ok: false,
+ errorCode: 'INTERNAL',
+ message: err instanceof Error ? err.message : String(err),
+ };
+ }
+ try {
+ // 与双击 .cindy 同一条转交通道:renderer 弹标准确认框(同 id 已装则
+ // 自动转"更新 vX → vY"),用户点头才真装。lease 持到转交完成。带上 agent
+ // 来源,确认框据此展示来源横幅 + 分级加重(高危需手输 id 确认)。
+ // 交给这条通道的必须是 staging,不能是 workdir 产物。
+ await handleIncomingCindyFile(staged.installPath, 'ghost-forge', origin);
+ } catch (err) {
+ invalidateForgePackTicket(staged.ticket);
+ return {
+ ok: false,
+ errorCode: 'INTERNAL',
+ message: err instanceof Error ? err.message : String(err),
+ };
+ }
+ log.info('ghost forge packed', { dir, id: packed.manifest.id });
return {
ok: true,
- cindyPath: packed.cindyPath,
+ // 给 agent 的只是作者副本文件名提示,不可用于访问;staging 路径不下发。
+ cindyPath: staged.agentCindyPath,
id: packed.manifest.id,
name: packed.manifest.name,
version: packed.manifest.version,
diff --git a/packages/cindy-tools/src/__tests__/ghostMcp.test.ts b/packages/cindy-tools/src/__tests__/ghostMcp.test.ts
index 23e476c1d5..10fef62f90 100644
--- a/packages/cindy-tools/src/__tests__/ghostMcp.test.ts
+++ b/packages/cindy-tools/src/__tests__/ghostMcp.test.ts
@@ -66,7 +66,7 @@ function fakeDeps(
}),
forgePack: async () => ({
ok: true,
- cindyPath: "/tmp/x.cindy",
+ cindyPath: "x-1.0.0.cindy",
id: "x",
name: "X",
version: "1.0.0",
@@ -1449,7 +1449,10 @@ describe("cindy_ghosts · ghost_forge(锻造)", () => {
ok: true,
id: "x",
version: "1.0.0",
+ cindyPath: "x-1.0.0.cindy",
});
+ expect(parsePayload(okResult).cindyPath.includes("/")).toBe(false);
+ expect(parsePayload(okResult).cindyPath.includes("\\")).toBe(false);
const failed = await handleForgePack(
fakeDeps({
@@ -1475,7 +1478,7 @@ describe("cindy_ghosts · ghost_forge(锻造)", () => {
requests.push(request);
return {
ok: true,
- cindyPath: "/src/my-ghost/my-ghost-1.0.0.cindy",
+ cindyPath: "my-ghost-1.0.0.cindy",
id: "my-ghost",
name: "My Ghost",
version: "1.0.0",
diff --git a/packages/cindy-tools/src/types.ts b/packages/cindy-tools/src/types.ts
index 0dad78220e..965f3aab5b 100644
--- a/packages/cindy-tools/src/types.ts
+++ b/packages/cindy-tools/src/types.ts
@@ -235,7 +235,10 @@ export type CindyForgePackErrorCode =
export type CindyForgePackResult =
| {
ok: true;
- /** 打包产物(.cindy)的绝对路径(临时目录,装入后可弃)。 */
+ /**
+ * 作者副本的文件名提示(如 `demo-1.0.0.cindy`),不可用于访问。
+ * 不是绝对路径,也不是 Host staging 路径;装入走确认框,不要拿这个字段去读盘。
+ */
cindyPath: string;
id: string;
name: string;