Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
perf(desktop): 裁剪安装包冗余资源并去重运行依赖 (#6090)
Dash58761bbac0c2
diff --git a/apps/desktop/forge-node-pty.ts b/apps/desktop/forge-node-pty.tsindex e8f10c4dc3..1482139540 100644--- a/apps/desktop/forge-node-pty.ts+++ b/apps/desktop/forge-node-pty.ts@@ -6,6 +6,7 @@ export function preparePackagedNodePty(buildPath: string, platform: string, archconst packageDir = path.join(buildPath, 'node_modules', 'node-pty');// The pinned npm package ships macOS/Windows prebuilds; Linux still builds from source.if (platform !== 'win32' && platform !== 'darwin') {+ pruneOtherPrebuilds(packageDir);return {rebuild: true,nativePath: path.join(packageDir, 'build', 'Release', 'pty.node'),@@ -40,6 +41,8 @@ export function preparePackagedNodePty(buildPath: string, platform: string, arch);}+ pruneOtherPrebuilds(packageDir, `${platform}-${arch}`);+// node-pty loads build/Release and build/Debug before prebuilds. Remove copied// local bindings so a stale Node ABI or another architecture cannot shadow the target.for (const variant of ['Release', 'Debug']) {@@ -53,3 +56,14 @@ export function preparePackagedNodePty(buildPath: string, platform: string, arch}return { rebuild: false, nativePath: path.join(prebuildDir, 'pty.node') };}++function pruneOtherPrebuilds(packageDir: string, keep?: string): void {+ const prebuilds = path.join(packageDir, 'prebuilds');+ if (!fs.existsSync(prebuilds)) return;+ for (const entry of fs.readdirSync(prebuilds, { withFileTypes: true })) {+ // Preserve loose metadata/licenses. Only platform-specific directories are redundant.+ if (entry.isDirectory() && entry.name !== keep) {+ fs.rmSync(path.join(prebuilds, entry.name), { recursive: true, force: true });+ }+ }+}diff --git a/apps/desktop/forge-prune-runtime.ts b/apps/desktop/forge-prune-runtime.tsnew file mode 100644index 0000000000..a4379b783f--- /dev/null+++ b/apps/desktop/forge-prune-runtime.ts@@ -0,0 +1,32 @@+import * as fs from 'node:fs';+import * as path from 'node:path';++/** Only call on the disposable package copy, after native rebuild has finished. */+export function prunePackagedRuntime(buildPath: string): void {+ const modules = path.join(buildPath, 'node_modules');+ // bindings loads build/Release/better_sqlite3.node. Keep the addon and its JS+ // loader; source and compiler intermediates are needed only during rebuild.+ const sqlite = path.join(modules, 'better-sqlite3');+ for (const relative of [+ 'deps',+ 'src',+ path.join('build', 'Release', 'obj'),+ path.join('build', 'Release', 'obj.target'),+ path.join('build', 'Release', 'sqlite3.a'),+ ]) {+ fs.rmSync(path.join(sqlite, relative), { recursive: true, force: true });+ }+ // The externalized Node entry is excel.js -> lib/exceljs.nodejs.js. dist+ // contains browser/ES5 bundles and maps, not files used by that entry.+ fs.rmSync(path.join(modules, 'exceljs', 'dist'), { recursive: true, force: true });+}++/** Drizzle snapshots are generator inputs; preserve journal, SQL and companions verbatim. */+export function prunePackagedMigrationSnapshots(resourcesPath: string): void {+ const meta = path.join(resourcesPath, 'drizzle', 'meta');+ for (const entry of fs.readdirSync(meta, { withFileTypes: true })) {+ if (entry.isFile() && /^\d{4}_snapshot\.json$/.test(entry.name)) {+ fs.unlinkSync(path.join(meta, entry.name));+ }+ }+}diff --git a/apps/desktop/forge-runtime-deps.ts b/apps/desktop/forge-runtime-deps.tsnew file mode 100644index 0000000000..c9fed5bf72--- /dev/null+++ b/apps/desktop/forge-runtime-deps.ts@@ -0,0 +1,47 @@+import * as fs from 'node:fs';+import * as path from 'node:path';++type ResolvePackage = (name: string, fromDirs?: string[]) => string;++/** Copy runtime closures, reusing only the exact source package visible to Node. */+export function copyRuntimeDependencyTrees(+ deps: readonly string[],+ destModules: string,+ resolvePackage: ResolvePackage,+): void {+ function copyLevel(+ names: readonly string[],+ destination: string,+ ancestors: ReadonlyMap<string, string>[],+ fromDirs?: string[],+ ): void {+ const local = new Map<string, string>();+ // Reserve all siblings before descending: Node can resolve a sibling even+ // when it is copied later. The nearest version wins, just as in Node.+ for (const name of names) {+ const source = fs.realpathSync(resolvePackage(name, fromDirs));+ const visible = ancestors.find((level) => level.has(name))?.get(name);+ if (visible !== source) local.set(name, source);+ }+ for (const [name, source] of local) {+ const target = path.join(destination, name);+ fs.mkdirSync(path.dirname(target), { recursive: true });+ fs.rmSync(target, { recursive: true, force: true });+ fs.cpSync(source, target, {+ recursive: true,+ dereference: true,+ filter: (file) => path.basename(file) !== 'node_modules',+ });+ const manifest = JSON.parse(fs.readFileSync(path.join(source, 'package.json'), 'utf8')) as {+ dependencies?: Record<string, string>;+ };+ copyLevel(+ Object.keys(manifest.dependencies ?? {}).sort(),+ path.join(target, 'node_modules'),+ [local, ...ancestors],+ [source],+ );+ }+ }+ copyLevel(deps, destModules, []);+}diff --git a/apps/desktop/forge.config.ts b/apps/desktop/forge.config.tsindex 6b3abc7ec7..0de71fdfd3 100644--- a/apps/desktop/forge.config.ts+++ b/apps/desktop/forge.config.ts@@ -21,7 +21,9 @@ import {resolveCindyRegion,} from '@cindy/maker-shared/brand-identity';import { preparePackagedNodePty } from './forge-node-pty';-import { stagePackagedThirdPartyNotices } from './forge-third-party-notices';+import { prunePackagedRuntime, prunePackagedMigrationSnapshots } from './forge-prune-runtime';+import { copyRuntimeDependencyTrees as copyRuntimeTrees } from './forge-runtime-deps';+import { packagedResourcesPath, stagePackagedThirdPartyNotices } from './forge-third-party-notices';import {swiftTargetTriple,swiftTargetTriplesForForgeArch,@@ -312,40 +314,7 @@ function copyDiscordRuntimeDeps(destModules: string): void {}function copyRuntimeDependencyTrees(deps: readonly string[], destModules: string): void {- const seen = new Set<string>();- for (const dep of deps) {- copyDependencyTree(dep, destModules, undefined, seen);- }-}--function copyDependencyTree(- dep: string,- destModules: string,- fromDirs?: string[],- seen = new Set<string>(),-): void {- const src = resolvePackageDir(dep, fromDirs);- const dst = path.join(destModules, dep);- const seenKey = `${dst}\0${src}`;- if (seen.has(seenKey)) return;- seen.add(seenKey);-- fs.mkdirSync(path.dirname(dst), { recursive: true });- fs.rmSync(dst, { recursive: true, force: true });- fs.cpSync(src, dst, {- recursive: true,- dereference: true,- filter: (srcPath) => path.basename(srcPath) !== 'node_modules',- });- console.log(`[forge:afterCopy] bundled runtime dep tree: ${dep} <- ${src}`);-- const pkg = JSON.parse(fs.readFileSync(path.join(src, 'package.json'), 'utf8')) as {- dependencies?: Record<string, string>;- };- const childDestModules = path.join(dst, 'node_modules');- for (const childDep of Object.keys(pkg.dependencies ?? {}).sort()) {- copyDependencyTree(childDep, childDestModules, [src], seen);- }+ copyRuntimeTrees(deps, destModules, resolvePackageDir);}/**@@ -463,6 +432,7 @@ async function rebuildNativeDepsInPackage(}console.log(`[forge:afterCopy] rebuild ok: ${sqliteNative}, ${ptyNative}`);+ prunePackagedRuntime(buildPath);}const isDev =@@ -1156,8 +1126,11 @@ function buildRemoteDesktopInput(platform: ForgePlatform, arch: ForgeArch): voidif (location.error || location.status !== 0)throw new Error('Remote credentials output unavailable');outputs.push(path.join(location.stdout.trim(), 'cindy-macos-remote-credentials'));- fs.cpSync(path.join(location.stdout.trim(), 'CindyRemoteCredentials_CindyRemoteCredentials.bundle'),- path.join(destDir, 'CindyRemoteCredentials_CindyRemoteCredentials.bundle'), { recursive: true });+ fs.cpSync(+ path.join(location.stdout.trim(), 'CindyRemoteCredentials_CindyRemoteCredentials.bundle'),+ path.join(destDir, 'CindyRemoteCredentials_CindyRemoteCredentials.bundle'),+ { recursive: true },+ );}const credential = path.join(destDir, 'cindy-macos-remote-credentials');if (outputs.length === 1) fs.copyFileSync(outputs[0], credential);@@ -1924,6 +1897,16 @@ const config: ForgeConfig = {// 避免 Win/Mac release 都回写 package.json 引发 git 冲突。// 未设置时由 electron-packager 回落到 package.json 里的占位版本(仅 dev 用)。...(process.env.APP_VERSION ? { appVersion: process.env.APP_VERSION } : {}),+ afterCopyExtraResources: [+ (buildPath, _electronVersion, platform, _arch, callback) => {+ try {+ prunePackagedMigrationSnapshots(packagedResourcesPath(buildPath, platform));+ callback();+ } catch (err) {+ callback(err as Error);+ }+ },+ ],afterCopy: [(buildPath, electronVersion, platform, arch, callback) => {(async () => {diff --git a/apps/desktop/scripts/native-deps-packaging.test.mjs b/apps/desktop/scripts/native-deps-packaging.test.mjsindex c24fb680b5..8f068ebfeb 100644--- a/apps/desktop/scripts/native-deps-packaging.test.mjs+++ b/apps/desktop/scripts/native-deps-packaging.test.mjs@@ -3,6 +3,7 @@ import os from 'node:os';import path from 'node:path';import { afterAll, beforeAll, describe, expect, it } from 'vitest';import { preparePackagedNodePty } from '../forge-node-pty';+import { prunePackagedRuntime } from '../forge-prune-runtime';const windowsFiles = ['pty.node',@@ -43,6 +44,11 @@ describe('native dependency packaging', () => {['darwin', 'arm64'],])('uses the complete %s/%s prebuild without requiring compilation', (platform, arch) => {const f = fixture(platform, arch);+ const other = path.join(f.packageDir, 'prebuilds', 'other-platform');+ fs.mkdirSync(other);+ fs.writeFileSync(path.join(other, 'pty.node'), 'wrong binding');+ const license = path.join(f.packageDir, 'prebuilds', 'LICENSE');+ fs.writeFileSync(license, 'license');expect(preparePackagedNodePty(f.buildPath, platform, arch)).toEqual({rebuild: false,nativePath: path.join(f.prebuildDir, 'pty.node'),@@ -50,6 +56,8 @@ describe('native dependency packaging', () => {for (const file of f.files) {expect(fs.readFileSync(path.join(f.prebuildDir, file), 'utf8')).toBe('fixture binary');}+ expect(fs.existsSync(other)).toBe(false);+ expect(fs.readFileSync(license, 'utf8')).toBe('license');});it.each(windowsFiles)('rejects a missing Windows runtime file: %s', (file) => {@@ -105,9 +113,45 @@ describe('native dependency packaging', () => {it.each(['x64', 'arm64'])('keeps the existing Linux/%s source build', (arch) => {const f = fixture('linux', arch);+ const source = path.join(f.packageDir, 'src', 'unix', 'pty.cc');+ fs.mkdirSync(path.dirname(source), { recursive: true });+ fs.writeFileSync(source, 'build input');expect(preparePackagedNodePty(f.buildPath, 'linux', arch)).toEqual({rebuild: true,nativePath: path.join(f.packageDir, 'build', 'Release', 'pty.node'),});+ expect(fs.existsSync(f.prebuildDir)).toBe(false);+ expect(fs.readFileSync(source, 'utf8')).toBe('build input');+ });++ it('prunes build-only SQLite files and ExcelJS browser bundles, retaining runtime and licenses', () => {+ const f = fixture();+ const modules = path.join(f.buildPath, 'node_modules');+ const removed = [+ ['better-sqlite3', 'deps', 'sqlite3', 'sqlite3.c'],+ ['better-sqlite3', 'src', 'better_sqlite3.cpp'],+ ['better-sqlite3', 'build', 'Release', 'obj', 'gen', 'sqlite3.c'],+ ['better-sqlite3', 'build', 'Release', 'obj.target', 'sqlite3.o'],+ ['better-sqlite3', 'build', 'Release', 'sqlite3.a'],+ ['exceljs', 'dist', 'exceljs.js.map'],+ ];+ const kept = [+ ['better-sqlite3', 'build', 'Release', 'better_sqlite3.node'],+ ['better-sqlite3', 'lib', 'database.js'],+ ['better-sqlite3', 'LICENSE'],+ ['exceljs', 'excel.js'],+ ['exceljs', 'lib', 'exceljs.nodejs.js'],+ ['exceljs', 'LICENSE'],+ ];+ for (const parts of [...removed, ...kept]) {+ const file = path.join(modules, ...parts);+ fs.mkdirSync(path.dirname(file), { recursive: true });+ fs.writeFileSync(file, 'fixture');+ }+ prunePackagedRuntime(f.buildPath);+ prunePackagedRuntime(f.buildPath);+ for (const parts of removed) expect(fs.existsSync(path.join(modules, ...parts))).toBe(false);+ for (const parts of kept)+ expect(fs.readFileSync(path.join(modules, ...parts), 'utf8')).toBe('fixture');});});diff --git a/apps/desktop/scripts/runtime-deps-packaging.test.mjs b/apps/desktop/scripts/runtime-deps-packaging.test.mjsnew file mode 100644index 0000000000..814ff337b5--- /dev/null+++ b/apps/desktop/scripts/runtime-deps-packaging.test.mjs@@ -0,0 +1,96 @@+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { createRequire } from 'node:module';+import { it, expect } from 'vitest';+import { copyRuntimeDependencyTrees } from '../forge-runtime-deps';+import { prunePackagedMigrationSnapshots } from '../forge-prune-runtime';+import { createMigrationRuntimeManifest } from '../src/main/localDb/migrationRunner';++it('reuses exact visible packages, preserves shadowed versions and terminates cycles', () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-dependency-layout-'));+ try {+ const sources = path.join(root, 'sources');+ const make = (id, name, dependencies, code) => {+ const dir = path.join(sources, id);+ fs.mkdirSync(dir, { recursive: true });+ fs.writeFileSync(+ path.join(dir, 'package.json'),+ JSON.stringify({ name, main: 'index.js', dependencies }),+ );+ fs.writeFileSync(path.join(dir, 'index.js'), code);+ return fs.realpathSync(dir);+ };+ const common1 = make('common1', 'common', {}, "module.exports = 'v1'");+ const common2 = make('common2', 'common', {}, "module.exports = 'v2'");+ const child = make(+ 'child',+ 'child',+ { common: '*', leaf: '*' },+ "module.exports = [require('common'), require('leaf')]",+ );+ const leaf = make(+ 'leaf',+ 'leaf',+ { common: '*', parent: '*' },+ "module.exports = require('common')",+ );+ const parent = make(+ 'parent',+ 'parent',+ { common: '*', child: '*' },+ "module.exports = [require('common'), require('child')]",+ );+ const resolve = (name, from) => {+ if (name === 'common') return from?.[0] === child ? common2 : common1;+ return { parent, child, leaf }[name];+ };+ const modules = path.join(root, 'output', 'node_modules');+ copyRuntimeDependencyTrees(['parent', 'common'], modules, resolve);+ const require = createRequire(path.join(root, 'output', 'probe.cjs'));+ expect(require('parent')).toEqual(['v1', ['v2', 'v1']]);+ expect(fs.existsSync(path.join(modules, 'parent', 'node_modules', 'common'))).toBe(false);+ const childModules = path.join(modules, 'parent', 'node_modules', 'child', 'node_modules');+ expect(fs.existsSync(path.join(childModules, 'common'))).toBe(true);+ // A nearer v2 shadows root v1, so leaf needs its own v1 even though root has it.+ expect(fs.existsSync(path.join(childModules, 'leaf', 'node_modules', 'common'))).toBe(true);+ expect(fs.existsSync(path.join(childModules, 'leaf', 'node_modules', 'parent'))).toBe(false);+ } finally {+ fs.rmSync(root, { recursive: true, force: true });+ }+});++it('removes only generated snapshots from the packaged migration metadata', () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-migration-package-'));+ try {+ const source = path.resolve('drizzle');+ const target = path.join(root, 'drizzle');+ fs.cpSync(source, target, { recursive: true });+ const original = new Map();+ function collect(dir, relative = '') {+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {+ const key = path.join(relative, entry.name);+ if (entry.isDirectory()) collect(path.join(dir, entry.name), key);+ else original.set(key, fs.readFileSync(path.join(dir, entry.name)));+ }+ }+ collect(source);+ prunePackagedMigrationSnapshots(root);+ prunePackagedMigrationSnapshots(root);+ let removed = 0;+ for (const [relative, bytes] of original) {+ if (+ path.dirname(relative) === 'meta' &&+ /^\d{4}_snapshot\.json$/.test(path.basename(relative))+ ) {+ expect(fs.existsSync(path.join(target, relative))).toBe(false);+ removed++;+ } else expect(fs.readFileSync(path.join(target, relative)).equals(bytes)).toBe(true);+ expect(fs.readFileSync(path.join(source, relative)).equals(bytes)).toBe(true);+ }+ expect(removed).toBeGreaterThan(0);+ expect(createMigrationRuntimeManifest(target)).toEqual(createMigrationRuntimeManifest(source));+ } finally {+ fs.rmSync(root, { recursive: true, force: true });+ }+});diff --git a/apps/desktop/src/main/__tests__/discordExternalization.test.ts b/apps/desktop/src/main/__tests__/discordExternalization.test.tsindex 7b617f06e5..ca644645e0 100644--- a/apps/desktop/src/main/__tests__/discordExternalization.test.ts+++ b/apps/desktop/src/main/__tests__/discordExternalization.test.ts@@ -22,14 +22,11 @@ describe('discord.js main-process packaging', () => {it('preserves Discord dependency versions instead of flattening the runtime closure', () => {const forgeConfig = readFileSync(resolve(DESKTOP_ROOT, 'forge.config.ts'), 'utf8');- const nativeDepsBlock = forgeConfig.match(- /const NATIVE_RUNTIME_DEPS = \[[\s\S]*?\];/,- )?.[0];+ const nativeDepsBlock = forgeConfig.match(/const NATIVE_RUNTIME_DEPS = \[[\s\S]*?\];/)?.[0];expect(nativeDepsBlock).toBeTruthy();expect(nativeDepsBlock).not.toContain('...DISCORD_RUNTIME_DEPS');expect(forgeConfig).toContain('copyDiscordRuntimeDeps(destModules)');- expect(forgeConfig).toContain("const childDestModules = path.join(dst, 'node_modules')");- expect(forgeConfig).toContain('copyDependencyTree(childDep, childDestModules, [src], seen)');+ expect(forgeConfig).toContain('copyRuntimeTrees(deps, destModules, resolvePackageDir)');});});diff --git a/apps/desktop/src/main/doc-tools/__tests__/readSheetProcessPackaging.test.ts b/apps/desktop/src/main/doc-tools/__tests__/readSheetProcessPackaging.test.tsindex 790b26d707..01907cee3e 100644--- a/apps/desktop/src/main/doc-tools/__tests__/readSheetProcessPackaging.test.ts+++ b/apps/desktop/src/main/doc-tools/__tests__/readSheetProcessPackaging.test.ts@@ -7,6 +7,8 @@ import path from 'node:path';import { describe, expect, it } from 'vitest';import { READ_SHEET_RUNTIME_PACKAGES } from '../../../../../../packages/lizi-mcps/src/cindy-docs/readSheetRuntimeDeps';+import { prunePackagedRuntime } from '../../../../forge-prune-runtime';+import { copyRuntimeDependencyTrees } from '../../../../forge-runtime-deps';const desktopRoot = path.resolve(process.cwd());const workspaceRequire = createRequire(import.meta.url);@@ -16,7 +18,20 @@ function packageDirectory(name: string, fromDirs?: string[]): string {try {return path.dirname(workspaceRequire.resolve(`${name}/package.json`, options));} catch {- let current = path.dirname(workspaceRequire.resolve(name, options));+ try {+ return path.dirname(workspaceRequire.resolve(`${name}/package`, options));+ } catch {+ // Some packages export their manifest as ./package instead of ./package.json.+ }+ let entry: string;+ try {+ entry = workspaceRequire.resolve(name, options);+ } catch {+ const hoisted = path.resolve(desktopRoot, '../../node_modules', name);+ if (fs.existsSync(path.join(hoisted, 'package.json'))) return hoisted;+ throw new Error(`cannot resolve package directory: ${name}`);+ }+ let current = path.dirname(entry);while (current !== path.dirname(current)) {const packageJson = path.join(current, 'package.json');if (fs.existsSync(packageJson)) {@@ -29,47 +44,25 @@ function packageDirectory(name: string, fromDirs?: string[]): string {}}-function stageDependencyTree(- name: string,- destinationModules: string,- fromDirs?: string[],- seen = new Set<string>(),-): void {- const source = packageDirectory(name, fromDirs);- const destination = path.join(destinationModules, name);- const key = `${destination}\0${source}`;- if (seen.has(key)) return;- seen.add(key);- fs.mkdirSync(path.dirname(destination), { recursive: true });- fs.cpSync(source, destination, {- recursive: true,- dereference: true,- filter: (sourcePath) => path.basename(sourcePath) !== 'node_modules',- });- const manifest = JSON.parse(fs.readFileSync(path.join(source, 'package.json'), 'utf8')) as {- dependencies?: Record<string, string>;- };- for (const dependency of Object.keys(manifest.dependencies ?? {}).sort()) {- stageDependencyTree(dependency, path.join(destination, 'node_modules'), [source], seen);- }-}-describe('read_sheet XLSX worker packaging contract', () => {it('copies the worker runtime dependency closures into packaged node_modules', () => {const forge = fs.readFileSync(path.join(desktopRoot, 'forge.config.ts'), 'utf8');expect(READ_SHEET_RUNTIME_PACKAGES).toEqual(['jszip', 'exceljs']);expect(forge).toContain('copyRuntimeDependencyTrees(READ_SHEET_RUNTIME_PACKAGES, destModules)');- expect(forge).toContain('copyDependencyTree(childDep, childDestModules, [src], seen)');+ expect(forge).toContain('copyRuntimeTrees(deps, destModules, resolvePackageDir)');});it('loads ExcelJS and JSZip from an isolated staged dependency tree', () => {const temp = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-read-sheet-package-'));try {const stagedModules = path.join(temp, 'node_modules');- const seen = new Set<string>();- for (const runtimePackage of READ_SHEET_RUNTIME_PACKAGES) {- stageDependencyTree(runtimePackage, stagedModules, undefined, seen);- }+ copyRuntimeDependencyTrees(+ [...READ_SHEET_RUNTIME_PACKAGES, 'discord.js'],+ stagedModules,+ packageDirectory,+ );+ prunePackagedRuntime(temp);+ expect(fs.existsSync(path.join(stagedModules, 'exceljs', 'dist'))).toBe(false);const probeRequirePath = path.join(temp, 'probe.cjs');const probe = spawnSync(process.execPath,@@ -79,7 +72,11 @@ describe('read_sheet XLSX worker packaging contract', () => {const stagedRequire = createRequire(${JSON.stringify(probeRequirePath)});const ExcelJS = stagedRequire('exceljs');const JSZip = stagedRequire('jszip');+const { Client, GatewayIntentBits, EmbedBuilder } = stagedRequire('discord.js');(async () => {+ const client = new Client({ intents: [GatewayIntentBits.Guilds] });+ if (new EmbedBuilder().setTitle('ok').toJSON().title !== 'ok') throw Error('Discord builder');+ await client.destroy();const workbook = new ExcelJS.Workbook();workbook.addWorksheet('Sheet1').addRow(['ok']);const bytes = await workbook.xlsx.writeBuffer();diff --git a/docs/dev-rules/database-and-migrations.md b/docs/dev-rules/database-and-migrations.mdindex 57f1e7064c..95925a1ddc 100644--- a/docs/dev-rules/database-and-migrations.md+++ b/docs/dev-rules/database-and-migrations.md@@ -16,17 +16,24 @@## 事实来源-| 内容 | 权威来源 |-|---|---|-| 当前 schema | `apps/desktop/src/main/localDb/schema.ts` |-| Drizzle 生成配置 | `apps/desktop/drizzle.config.ts` |-| SQL、snapshot、journal 与 companion | `apps/desktop/drizzle/` |-| 静态完整性与历史冻结 | `apps/desktop/scripts/validate-migrations.mjs` |-| 实际执行顺序与事务语义 | `apps/desktop/src/main/localDb/migrationRunner.ts` |-| 空库与历史库升级验证 | `apps/desktop/src/main/localDb/__tests__/migrationReplay.test.ts` |+| 内容 | 权威来源 |+| ----------------------------------- | ----------------------------------------------------------------- |+| 当前 schema | `apps/desktop/src/main/localDb/schema.ts` |+| Drizzle 生成配置 | `apps/desktop/drizzle.config.ts` |+| SQL、snapshot、journal 与 companion | `apps/desktop/drizzle/` |+| 静态完整性与历史冻结 | `apps/desktop/scripts/validate-migrations.mjs` |+| 实际执行顺序与事务语义 | `apps/desktop/src/main/localDb/migrationRunner.ts` |+| 空库与历史库升级验证 | `apps/desktop/src/main/localDb/__tests__/migrationReplay.test.ts` |文档与实现冲突时先停下核对,不根据旧手册猜测命令或迁移语义。+发行包保留 SQL、companion、journal 与其余迁移资源;仅在 extraResource 复制完成后,+从打包副本移除 `meta/NNNN_snapshot.json`(Drizzle 开发生成输入)。源码中的 snapshot+保持完整,生成与静态校验照常使用。运行期 `listMigrations` 和 migration runtime manifest+只依赖 SQL 与 companion;打包回归检查裁剪前后运行期指纹相同、其余文件字节不变。+实现见 `apps/desktop/forge-prune-runtime.ts`,回归见+`apps/desktop/scripts/runtime-deps-packaging.test.mjs`。+## Append-only 不变量- 已进入 `main` 的 `NNNN_*.sql` 及其同名 `drizzle/scripts/NNNN_*.ts` 永久冻结:不得修改、