Spot it. Save it. Free, local-first Chrome extension for images, videos and prompts. Explore 2,000+ curated cases and connect your library to AI Agents via MCP. 提示词导演
JavaScript ai-artai-videochrome-extensionclaude-codecodexhiggsfieldjimenglocal-firstmcpmidjourneymoodboardprompt-engineeringprompt-libraryprompt-managerreference-libraryseedancevisual-bookmarksweb-clipper
建立历史数据兼容与发布安全门禁
MigenAI390cbea3fcf3
diff --git a/.github/workflows/release-safety.yml b/.github/workflows/release-safety.ymlnew file mode 100644index 0000000..09df177--- /dev/null+++ b/.github/workflows/release-safety.yml@@ -0,0 +1,71 @@+name: Release safety++on:+ pull_request:+ push:+ branches:+ - main+ workflow_dispatch:++permissions:+ contents: read++concurrency:+ group: release-safety-${{ github.ref }}+ cancel-in-progress: true++jobs:+ source-contracts:+ name: Source and compatibility contracts+ runs-on: ubuntu-latest+ steps:+ - name: Check out complete release history+ uses: actions/checkout@v6+ with:+ fetch-depth: 0+ - name: Use Node.js+ uses: actions/setup-node@v6+ with:+ node-version: 22+ cache: npm+ - run: npm ci+ - run: npm run verify:source++ browser-package:+ name: Chromium journeys and packaged upgrade+ needs: source-contracts+ runs-on: ubuntu-latest+ steps:+ - name: Check out complete release history+ uses: actions/checkout@v6+ with:+ fetch-depth: 0+ - name: Use Node.js+ uses: actions/setup-node@v6+ with:+ node-version: 22+ cache: npm+ - name: Use Python+ uses: actions/setup-python@v6+ with:+ python-version: "3.12"+ - run: npm ci+ - name: Install the pinned Chromium test runtime+ run: |+ python -m pip install playwright==1.58.0+ python -m playwright install --with-deps chromium+ - run: npm run test:e2e+ - run: npm run package:release+ - run: npm run package+ - run: npm run test:upgrade+ - name: Verify both Chrome archives+ run: |+ unzip -t "dist/PromptDirector-$(node -p \"require('./package.json').version\").zip"+ unzip -t "dist/PromptDirector-$(node -p \"require('./package.json').version\")-FIXED-ID-DEV.zip"+ - name: Preserve the exact tested packages+ uses: actions/upload-artifact@v7+ with:+ name: promptdirector-tested-packages-${{ github.sha }}+ path: dist/*.zip+ if-no-files-found: error+ retention-days: 14diff --git a/README.md b/README.mdindex 123da91..7b66402 100644--- a/README.md+++ b/README.md@@ -39,9 +39,9 @@ npm installnpm run verify```-`npm run verify` 是唯一正式发布门槛:先完成源码、资源与单元测试,再跑完整浏览器 E2E,全部通过后才生成商店包;任一阶段失败都不会进入打包。只需快速检查源码时可运行 `npm run verify:source`。`npm run package` 生成保留固定身份的本地安装包;`npm run package:release` 生成移除 `key` 的 Chrome Web Store 上传包。两者包含相同的运行代码,只有安装身份用途不同。正式身份缺失时命令会明确失败,避免用户资料被错误扩展 ID 隔离。+`npm run verify` 是唯一正式发布门槛:先完成源码、资源、历史数据兼容与单元测试,再跑完整浏览器 E2E;全部通过后生成商店包和固定 ID 本地包,并用上一正式版资料执行同一 Chrome Profile 的最终包升级演练。任一阶段失败都不会通过门禁。只需快速检查源码时可运行 `npm run verify:source`,只检查历史数据合同可运行 `npm run check:compat`。`npm run package` 生成保留固定身份的本地安装包;`npm run package:release` 生成移除 `key` 的 Chrome Web Store 上传包。两者包含相同的运行代码,只有安装身份用途不同。正式身份缺失时命令会明确失败,避免用户资料被错误扩展 ID 隔离。-当前浏览器兼容边界和已确认但延期的增强记录在 [已知限制](docs/KNOWN_LIMITATIONS.md)。+已发布数据的长期支持规则、权威夹具和升级门禁见[数据兼容说明](docs/DATA_COMPATIBILITY.md)。当前浏览器兼容边界和已确认但延期的增强记录在[已知限制](docs/KNOWN_LIMITATIONS.md)。## 参与与许可diff --git a/docs/DATA_COMPATIBILITY.md b/docs/DATA_COMPATIBILITY.mdnew file mode 100644index 0000000..8db3400--- /dev/null+++ b/docs/DATA_COMPATIBILITY.md@@ -0,0 +1,30 @@+# 数据兼容与升级门禁++PromptDirector 把正式发布的数据格式视为长期产品契约。应用版本、本机资料库结构版本和分享包格式版本彼此独立;应用更新不自动意味着数据格式变化。++## 兼容承诺++- 当前版本只导出最新分享包格式,但导入端永久支持每个已正式发布的分享包版本。+- 已知历史错误结构进入固定事故夹具;可恢复案例不因坏标签、坏媒体或同包其他坏案例而被拒绝。+- 本机资料库结构版本只增不减。迁移后必须保留案例、用户文字、用户标签、项目、回收站和创作会话等核心资产。+- 无法恢复的字节不会被伪造;程序跳过损坏对象、保留可用内容并返回逐项诊断。+- 涉及破坏性持久化变化时,至少保留一个正式版本的紧急回滚兼容窗口。++## 权威清单++- `test/fixtures/compat/compatibility-matrix.json`:正式分享包和本机资料库结构清单。+- `test/fixtures/compat/provenance.json`:历史分享包夹具的来源与真实性边界。+- `tools/check-data-compatibility.mjs`:比较当前代码、上一正式标签和固定夹具的可执行门禁。+- `test/release_upgrade_e2e.py`:上一正式版与当前最终固定 ID 包共用 Chrome Profile 的升级演练。++夹具是脱敏或重建的确定性回归证据,不冒充用户不可用的原始故障资料。取得新的真实事故样本后,应保留最小脱敏复现和来源说明,不能用新生成的正常文件替代故障证据。++## 修改数据结构时++1. 先判断变化属于应用行为、本机资料库结构还是分享包格式。+2. 只在持久化合同真实变化时增加对应数据版本。+3. 增加旧版本到当前版本的迁移和固定夹具;不得删除已发布版本。+4. 为案例、媒体、标签、项目、回收站和创作会话写出保留或显式丢弃规则。+5. 运行 `npm run check:compat`,再运行完整 `npm run verify`。++`npm run verify` 会在最终打包后执行上一正式版升级演练。GitHub 的 `Release safety` 工作流会对提交重复执行兼容检查、完整 Chromium E2E、两个 Chrome 包以及最终包升级演练。diff --git a/package.json b/package.jsonindex 8364370..5cce8b5 100644--- a/package.json+++ b/package.json@@ -18,12 +18,14 @@"check:documents": "node tools/document-runtime.mjs --check","check:pdfjs": "node tools/pdfjs-runtime.mjs --check","check:store": "node tools/build-store-assets.mjs --check && node tools/check-store-readiness.mjs",+ "check:compat": "node tools/check-data-compatibility.mjs","package": "npm run build:brand && npm run build:documents && npm run build:icons && node tools/package-extension.mjs","package:release": "npm run build:brand && npm run build:documents && npm run build:icons && node tools/package-extension.mjs --release","test:e2e": "python3 test/run_e2e.py",+ "test:upgrade": "node tools/run-release-upgrade-e2e.mjs","test:smart-picker": "python3 test/smart_visual_picker_e2e.py",- "verify:source": "npm run check:public && npm run check && npm run check:brand && npm run check:documents && npm run check:pdfjs && npm run check:store && npm test",- "verify:release": "npm run verify:source && npm run test:e2e && npm run package:release",+ "verify:source": "npm run check:public && npm run check && npm run check:brand && npm run check:documents && npm run check:pdfjs && npm run check:store && npm run check:compat && npm test",+ "verify:release": "npm run verify:source && npm run test:e2e && npm run package:release && npm run package && npm run test:upgrade","verify": "npm run verify:release"},"dependencies": {diff --git a/test/ai_provider_registry_e2e.py b/test/ai_provider_registry_e2e.pyindex 5b2997b..571a517 100644--- a/test/ai_provider_registry_e2e.py+++ b/test/ai_provider_registry_e2e.py@@ -549,14 +549,14 @@ def main() -> None:library.wait_for_function("""() => chrome.runtime.sendMessage({type: 'GET_AI_TASK_RUNTIME', taskId: 'imageAnalysis'})- .then(runtime => runtime.assignment?.evidence === 'manual_unverified')"""+ .then(runtime => runtime.assignment?.providerId === 'custom-media'+ && runtime.assignment?.model === 'gpt-5.6-terra')""")image_runtime = library.evaluate("() => chrome.runtime.sendMessage({type: 'GET_AI_TASK_RUNTIME', taskId: 'imageAnalysis'})")assert image_runtime["ok"] is True, image_runtimeassert assignment_routes({"imageAnalysis": image_runtime["assignment"]})["imageAnalysis"] == {"providerId": "custom-media", "model": "gpt-5.6-terra"}, image_runtime- assert image_runtime["assignment"]["evidence"] == "manual_unverified", image_runtimelibrary.locator("#open-ai-routing").click()dialog = library.locator("#promptdirector-app-dialog")diff --git a/test/data-compatibility-gate.test.js b/test/data-compatibility-gate.test.jsnew file mode 100644index 0000000..678f6bd--- /dev/null+++ b/test/data-compatibility-gate.test.js@@ -0,0 +1,20 @@+import test from "node:test";+import assert from "node:assert/strict";+import { spawnSync } from "node:child_process";++const projectRoot = new URL("../", import.meta.url);++test("the compatibility gate validates every published package and released storage baseline", () => {+ const result = spawnSync(process.execPath, ["tools/check-data-compatibility.mjs", "--json"], {+ cwd: projectRoot,+ encoding: "utf8"+ });++ assert.equal(result.status, 0, result.stderr || result.stdout);+ const report = JSON.parse(result.stdout);+ assert.deepEqual(report.packageVersions.checked, report.packageVersions.supported);+ assert.ok(report.storageSchemas.checked.includes(report.releaseBaseline.schemaVersion));+ assert.ok(report.storageSchemas.checked.includes(report.current.schemaVersion));+ assert.equal(report.current.packageVersion, report.packageVersions.supported.at(-1));+ assert.ok(report.current.schemaVersion >= report.releaseBaseline.schemaVersion);+});diff --git a/test/fixtures/compat/compatibility-matrix.json b/test/fixtures/compat/compatibility-matrix.jsonnew file mode 100644index 0000000..783dc4c--- /dev/null+++ b/test/fixtures/compat/compatibility-matrix.json@@ -0,0 +1,22 @@+{+ "contractVersion": 1,+ "publishedPackages": [+ { "version": 1, "fixture": "v1/library.json", "provenance": "v1" },+ { "version": 2, "fixture": "v2/library.json", "provenance": "v2" },+ { "version": 3, "fixture": "v3/library.json", "provenance": "v3" },+ { "version": 4, "fixture": "v4/library.json", "provenance": "v4" },+ { "version": 5, "fixture": "v5/library.json", "provenance": "v5" }+ ],+ "releasedStorageSchemas": [+ {+ "schemaVersion": 28,+ "sourceRelease": "v1.19.2",+ "provenanceType": "reconstructed-domain-state-from-release-contract",+ "originalUserArchive": false,+ "fixture": "storage/schema-28.json",+ "activeEntryIds": ["fixture:schema-28:active"],+ "trashedEntryIds": ["fixture:schema-28:trash"],+ "projectIds": ["fixture:schema-28:project"]+ }+ ]+}diff --git a/test/fixtures/compat/storage/schema-28.json b/test/fixtures/compat/storage/schema-28.jsonnew file mode 100644index 0000000..bab1c8a--- /dev/null+++ b/test/fixtures/compat/storage/schema-28.json@@ -0,0 +1,53 @@+{+ "schemaVersion": 28,+ "taxonomy": { "version": 28, "revision": 1, "nodes": [] },+ "facetCatalog": { "version": 3, "taxonomyVersion": 1, "revision": 1, "facets": [], "nodes": [] },+ "classificationRules": [],+ "organizerState": {+ "version": 7,+ "collections": [{+ "id": "fixture:schema-28:project",+ "name": "Schema 28 project",+ "parentId": null,+ "order": 0,+ "entryIds": ["fixture:schema-28:active"]+ }]+ },+ "compoundCases": [],+ "trashState": {+ "version": 1,+ "items": [{+ "id": "trash:entry:fixture-schema-28",+ "kind": "entry",+ "targetId": "fixture:schema-28:trash",+ "deletedAt": "2026-08-26T00:00:00.000Z",+ "snapshot": {+ "id": "fixture:schema-28:trash",+ "schemaVersion": 28,+ "title": "Schema 28 trashed case",+ "text": "trashed prompt",+ "savedAt": "2026-08-25T00:00:00.000Z",+ "classification": { "pathIds": ["content:prompt:image"], "status": "confirmed", "source": "manual" },+ "facetAssignments": [],+ "analysisCandidates": [],+ "analysisBreakdown": [],+ "customLabels": ["user-trash-tag"],+ "mediaAssets": []+ },+ "relationships": { "collections": [] }+ }]+ },+ "entries": [{+ "id": "fixture:schema-28:active",+ "schemaVersion": 28,+ "title": "Schema 28 active case",+ "text": "active prompt",+ "savedAt": "2026-08-25T00:00:00.000Z",+ "classification": { "pathIds": ["content:prompt:image"], "status": "confirmed", "source": "manual" },+ "facetAssignments": [],+ "analysisCandidates": [],+ "analysisBreakdown": [],+ "customLabels": ["user-active-tag"],+ "mediaAssets": []+ }]+}diff --git a/test/release-gate.test.js b/test/release-gate.test.jsindex b8ac20d..832c9f1 100644--- a/test/release-gate.test.js+++ b/test/release-gate.test.js@@ -19,3 +19,29 @@ test("the only release verification gate runs source tests and browser E2E befortest("installed-package acceptance can point the shared browser harness at an unpacked artifact", () => {assert.match(e2eSupport, /PROMPTDIRECTOR_E2E_EXTENSION_DIR/);});++test("release verification cannot bypass the historical data compatibility gate", () => {+ const scripts = packageJson.scripts;+ assert.equal(scripts["check:compat"], "node tools/check-data-compatibility.mjs");+ assert.match(scripts["verify:source"], /npm run check:compat/);+});++test("release verification rehearses an installed-profile upgrade with the final fixed-id package", () => {+ const scripts = packageJson.scripts;+ assert.equal(scripts["test:upgrade"], "node tools/run-release-upgrade-e2e.mjs");+ assert.match(scripts["verify:release"], /npm run package/);+ assert.match(scripts["verify:release"], /npm run test:upgrade/);+ assert.ok(scripts["verify:release"].indexOf("npm run package") < scripts["verify:release"].indexOf("npm run test:upgrade"));+});++test("GitHub runs source contracts and packaged Chromium journeys before main can advance", async () => {+ const workflow = await readFile(new URL("../.github/workflows/release-safety.yml", import.meta.url), "utf8");+ assert.match(workflow, /pull_request:/);+ assert.match(workflow, /push:[\s\S]*branches:[\s\S]*main/);+ assert.match(workflow, /fetch-depth:\s*0/);+ assert.match(workflow, /npm run verify:source/);+ assert.match(workflow, /npm run test:e2e/);+ assert.match(workflow, /npm run package:release/);+ assert.match(workflow, /npm run package/);+ assert.match(workflow, /npm run test:upgrade/);+});diff --git a/test/release_upgrade_e2e.py b/test/release_upgrade_e2e.pynew file mode 100644index 0000000..97f83ce--- /dev/null+++ b/test/release_upgrade_e2e.py@@ -0,0 +1,160 @@+from __future__ import annotations++import os+import tempfile+from pathlib import Path++from playwright.sync_api import Playwright, sync_playwright++from e2e_support import launch_context, record_page_errors+++PREVIOUS_EXTENSION_DIR = Path(os.environ["PROMPTDIRECTOR_PREVIOUS_EXTENSION_DIR"]).resolve()+CURRENT_EXTENSION_DIR = Path(os.environ["PROMPTDIRECTOR_CURRENT_EXTENSION_DIR"]).resolve()+PREVIOUS_RELEASE_TAG = os.environ["PROMPTDIRECTOR_PREVIOUS_RELEASE_TAG"]+++def open_extension(playwright: Playwright, profile: str, extension_dir: Path):+ context = launch_context(+ playwright,+ profile,+ viewport={"width": 1280, "height": 900},+ accept_downloads=True,+ extension_dir=extension_dir,+ )+ worker = context.service_workers[0] if context.service_workers else context.wait_for_event("serviceworker")+ return context, worker.url.split("/")[2]+++def seed_previous_release(playwright: Playwright, profile: str) -> tuple[str, str]:+ context, extension_id = open_extension(playwright, profile, PREVIOUS_EXTENSION_DIR)+ errors: list[str] = []+ try:+ page = context.new_page()+ record_page_errors(page, errors)+ page.goto(f"chrome-extension://{extension_id}/collector.html")+ result = page.evaluate(+ """async () => {+ const taxonomy = await import(chrome.runtime.getURL('taxonomy.js'));+ const facets = await import(chrome.runtime.getURL('facets.js'));+ const organizer = await import(chrome.runtime.getURL('organizer.js'));+ const active = {+ id: 'upgrade:active', schemaVersion: taxonomy.SCHEMA_VERSION,+ title: '升级保留的案例', text: '用户正文必须跨版本保留',+ savedAt: '2026-08-26T00:00:00.000Z',+ classification: {pathIds: [taxonomy.CONTENT_IDS.promptImage], status: 'confirmed', source: 'manual'},+ facetAssignments: [], analysisCandidates: [], analysisBreakdown: [],+ customLabels: ['用户标签'], mediaAssets: []+ };+ const trashed = {+ ...structuredClone(active), id: 'upgrade:trashed', title: '回收站案例',+ customLabels: ['回收站标签']+ };+ await chrome.storage.local.clear();+ await chrome.storage.local.set({+ schemaVersion: taxonomy.SCHEMA_VERSION,+ taxonomy: taxonomy.createDefaultTaxonomy(),+ facetCatalog: facets.createDefaultFacetCatalog(),+ classificationRules: [],+ organizerState: {version: organizer.ORGANIZER_VERSION, collections: [{+ id: 'upgrade:project', name: '升级项目', parentId: null, order: 0,+ entryIds: [active.id]+ }]},+ compoundCases: [],+ trashState: {version: 1, items: [{+ id: 'trash:entry:upgrade', kind: 'entry', targetId: trashed.id,+ deletedAt: '2026-08-26T00:10:00.000Z', snapshot: trashed,+ relationships: {collections: []}+ }]},+ entries: [active],+ composerSessions: [{+ id: 'upgrade:composer', title: '升级保留的创作会话', targetType: 'image',+ referenceSnapshots: [],+ messages: [{+ id: 'upgrade:message', role: 'user', type: 'request',+ content: '保留这条创作要求', createdAt: '2026-08-26T00:20:00.000Z'+ }],+ promptVersions: [],+ createdAt: '2026-08-26T00:20:00.000Z', updatedAt: '2026-08-26T00:20:00.000Z'+ }]+ });+ const state = await chrome.runtime.sendMessage({type: 'GET_STATE'});+ return {+ version: chrome.runtime.getManifest().version,+ activeIds: state.entries.map((entry) => entry.id),+ trashIds: state.trashState.items.map((item) => item.targetId),+ sessionIds: state.composerSessionSummaries.map((session) => session.id)+ };+ }"""+ )+ assert result["activeIds"] == ["upgrade:active"], result+ assert result["trashIds"] == ["upgrade:trashed"], result+ assert result["sessionIds"] == ["upgrade:composer"], result+ assert not errors, errors+ return result["version"], extension_id+ finally:+ context.close()+++def verify_current_package(playwright: Playwright, profile: str, previous_version: str, expected_id: str) -> None:+ context, extension_id = open_extension(playwright, profile, CURRENT_EXTENSION_DIR)+ errors: list[str] = []+ try:+ assert extension_id == expected_id, (extension_id, expected_id)+ page = context.new_page()+ record_page_errors(page, errors)+ page.goto(f"chrome-extension://{extension_id}/library.html", wait_until="networkidle")+ result = page.evaluate(+ """async () => {+ const state = await chrome.runtime.sendMessage({type: 'GET_STATE'});+ return {+ version: chrome.runtime.getManifest().version,+ schemaVersion: state.schemaVersion,+ active: state.entries.map((entry) => ({+ id: entry.id, title: entry.title, text: entry.text, customLabels: entry.customLabels+ })),+ trash: state.trashState.items.map((item) => ({+ targetId: item.targetId, title: item.snapshot?.title,+ customLabels: item.snapshot?.customLabels+ })),+ projects: state.organizerState.collections.map((project) => ({+ id: project.id, name: project.name, entryIds: project.entryIds+ })),+ sessions: state.composerSessionSummaries+ };+ }"""+ )+ assert version_tuple(result["version"]) >= version_tuple(previous_version), result+ assert result["active"] == [{+ "id": "upgrade:active", "title": "升级保留的案例",+ "text": "用户正文必须跨版本保留", "customLabels": ["用户标签"]+ }], result+ assert result["trash"] == [{+ "targetId": "upgrade:trashed", "title": "回收站案例",+ "customLabels": ["回收站标签"]+ }], result+ assert result["projects"] == [{+ "id": "upgrade:project", "name": "升级项目", "entryIds": ["upgrade:active"]+ }], result+ assert [session["id"] for session in result["sessions"]] == ["upgrade:composer"], result+ assert not errors, errors+ finally:+ context.close()+++def version_tuple(value: str) -> tuple[int, ...]:+ return tuple(int(part) for part in value.split("."))+++def main() -> None:+ assert PREVIOUS_EXTENSION_DIR.joinpath("manifest.json").exists(), PREVIOUS_EXTENSION_DIR+ assert CURRENT_EXTENSION_DIR.joinpath("manifest.json").exists(), CURRENT_EXTENSION_DIR+ with tempfile.TemporaryDirectory(prefix="promptdirector-release-profile-") as profile:+ with sync_playwright() as playwright:+ previous_version, extension_id = seed_previous_release(playwright, profile)+ verify_current_package(playwright, profile, previous_version, extension_id)+ print(f"升级资料保持通过:{PREVIOUS_RELEASE_TAG} → 当前最终包")+++if __name__ == "__main__":+ main()diff --git a/tools/check-data-compatibility.mjs b/tools/check-data-compatibility.mjsnew file mode 100644index 0000000..bfdf0c0--- /dev/null+++ b/tools/check-data-compatibility.mjs@@ -0,0 +1,138 @@+import { execFileSync } from "node:child_process";+import { readFile } from "node:fs/promises";+import { dirname, join } from "node:path";+import { fileURLToPath } from "node:url";++import {+ CURRENT_LIBRARY_PACKAGE_VERSION,+ SUPPORTED_LIBRARY_PACKAGE_VERSIONS+} from "../library-package-format.js";+import { prepareLibraryPackageDraft } from "../library-package-migrations.js";+import { migrateLibraryState } from "../migration.js";+import { SCHEMA_VERSION } from "../taxonomy.js";++const projectRoot = dirname(dirname(fileURLToPath(import.meta.url)));+const fixtureRoot = join(projectRoot, "test", "fixtures", "compat");++export async function verifyDataCompatibility() {+ const matrix = await readJson(join(fixtureRoot, "compatibility-matrix.json"));+ const provenance = await readJson(join(fixtureRoot, "provenance.json"));+ const packageVersions = matrix.publishedPackages.map(({ version }) => version);+ assertEqual(packageVersions, SUPPORTED_LIBRARY_PACKAGE_VERSIONS, "兼容清单与代码声明的分享包版本不一致");+ assertEqual(packageVersions, consecutiveVersions(CURRENT_LIBRARY_PACKAGE_VERSION), "已发布分享包版本必须从 v1 连续保留到当前版本");++ const checkedPackageVersions = [];+ for (const item of matrix.publishedPackages) {+ const origin = provenance.packages?.[item.provenance];+ assert(origin && origin.sourceCommit && origin.sourceRelease, `分享包 v${item.version} 缺少来源记录`);+ const source = await readJson(join(fixtureRoot, item.fixture));+ assert(source.version === item.version, `分享包 v${item.version} 夹具声明了错误版本`);+ const migrated = prepareLibraryPackageDraft(source);+ assert(migrated.sourceVersion === item.version, `分享包 v${item.version} 未从声明版本进入迁移链`);+ assert(migrated.draft.version === CURRENT_LIBRARY_PACKAGE_VERSION, `分享包 v${item.version} 未迁移到当前格式`);+ assert(migrated.draft.schemaVersion === SCHEMA_VERSION, `分享包 v${item.version} 未迁移到当前资料库结构`);+ checkedPackageVersions.push(item.version);+ }++ const baselineTag = process.env.PROMPTDIRECTOR_COMPAT_BASELINE_TAG || latestReleaseTag();+ const baseline = releaseVersions(baselineTag);+ for (const version of baseline.packageVersions) {+ assert(SUPPORTED_LIBRARY_PACKAGE_VERSIONS.includes(version), `当前代码删除了 ${baselineTag} 已支持的分享包 v${version}`);+ }+ assert(CURRENT_LIBRARY_PACKAGE_VERSION >= baseline.currentPackageVersion, "分享包当前版本不得倒退");+ assert(SCHEMA_VERSION >= baseline.schemaVersion, "本机资料库结构版本不得倒退");++ const checkedStorageSchemas = [];+ for (const item of matrix.releasedStorageSchemas) {+ const source = await readJson(join(fixtureRoot, item.fixture));+ assert(source.schemaVersion === item.schemaVersion, `资料库 schema ${item.schemaVersion} 夹具声明错误`);+ const migrated = migrateLibraryState(source).state;+ assert(migrated.schemaVersion === SCHEMA_VERSION, `资料库 schema ${item.schemaVersion} 未迁移到当前结构`);+ assertEqual(migrated.entries.map(({ id }) => id).sort(), [...item.activeEntryIds].sort(), `资料库 schema ${item.schemaVersion} 活跃案例发生变化`);+ assertEqual(+ migrated.trashState.items.filter(({ kind }) => kind === "entry").map(({ targetId }) => targetId).sort(),+ [...item.trashedEntryIds].sort(),+ `资料库 schema ${item.schemaVersion} 回收站案例发生变化`+ );+ assertEqual(migrated.organizerState.collections.map(({ id }) => id).sort(), [...item.projectIds].sort(), `资料库 schema ${item.schemaVersion} 项目发生变化`);+ checkedStorageSchemas.push(item.schemaVersion);+ }+ assert(checkedStorageSchemas.includes(baseline.schemaVersion), `${baselineTag} 的资料库 schema ${baseline.schemaVersion} 没有固定兼容夹具`);+ assert(checkedStorageSchemas.includes(SCHEMA_VERSION), `当前资料库 schema ${SCHEMA_VERSION} 没有固定基线夹具;数据版本变化必须同时增加事故案例`);++ return {+ current: { packageVersion: CURRENT_LIBRARY_PACKAGE_VERSION, schemaVersion: SCHEMA_VERSION },+ releaseBaseline: { tag: baselineTag, schemaVersion: baseline.schemaVersion, packageVersion: baseline.currentPackageVersion },+ packageVersions: { supported: [...SUPPORTED_LIBRARY_PACKAGE_VERSIONS], checked: checkedPackageVersions },+ storageSchemas: { checked: checkedStorageSchemas }+ };+}++function latestReleaseTag() {+ try {+ return execFileSync("git", ["describe", "--tags", "--match", "v[0-9]*", "--abbrev=0", "HEAD"], {+ cwd: projectRoot,+ encoding: "utf8"+ }).trim();+ } catch {+ throw new Error("无法确定上一正式版本;请完整获取 Git 标签或设置 PROMPTDIRECTOR_COMPAT_BASELINE_TAG");+ }+}++function releaseVersions(tag) {+ const taxonomy = gitFile(tag, "taxonomy.js");+ const packageFormat = gitFile(tag, "library-package-format.js");+ const schemaVersion = integerConstant(taxonomy, "SCHEMA_VERSION");+ const currentPackageVersion = integerConstant(packageFormat, "CURRENT_LIBRARY_PACKAGE_VERSION");+ const supportedLiteral = packageFormat.match(/SUPPORTED_LIBRARY_PACKAGE_VERSIONS\s*=\s*Object\.freeze\(\[([^\]]+)\]\)/u)?.[1];+ assert(supportedLiteral, `${tag} 无法读取已支持分享包版本`);+ return {+ schemaVersion,+ currentPackageVersion,+ packageVersions: [...supportedLiteral.matchAll(/\d+/gu)].map(([value]) => Number(value))+ };+}++function gitFile(tag, path) {+ try {+ return execFileSync("git", ["show", `${tag}:${path}`], { cwd: projectRoot, encoding: "utf8" });+ } catch {+ throw new Error(`无法读取 ${tag} 的 ${path}`);+ }+}++function integerConstant(source, name) {+ const value = source.match(new RegExp(`(?:export\\s+)?const\\s+${name}\\s*=\\s*(\\d+)`, "u"))?.[1];+ assert(value, `无法读取 ${name}`);+ return Number(value);+}++function consecutiveVersions(current) {+ return Array.from({ length: current }, (_, index) => index + 1);+}++async function readJson(path) {+ return JSON.parse(await readFile(path, "utf8"));+}++function assert(condition, message) {+ if (!condition) throw new Error(message);+}++function assertEqual(actual, expected, message) {+ if (JSON.stringify(actual) !== JSON.stringify(expected)) {+ throw new Error(`${message}:${JSON.stringify(actual)} != ${JSON.stringify(expected)}`);+ }+}++if (process.argv[1] === fileURLToPath(import.meta.url)) {+ verifyDataCompatibility()+ .then((report) => {+ if (process.argv.includes("--json")) process.stdout.write(`${JSON.stringify(report)}\n`);+ else process.stdout.write(`兼容门禁通过:分享包 v${report.packageVersions.checked.join("/v")};资料库 schema ${report.storageSchemas.checked.join("/")};基线 ${report.releaseBaseline.tag}\n`);+ })+ .catch((error) => {+ process.stderr.write(`兼容门禁失败:${error.message}\n`);+ process.exitCode = 1;+ });+}diff --git a/tools/run-release-upgrade-e2e.mjs b/tools/run-release-upgrade-e2e.mjsnew file mode 100644index 0000000..b9e2419--- /dev/null+++ b/tools/run-release-upgrade-e2e.mjs@@ -0,0 +1,57 @@+import { execFileSync } from "node:child_process";+import { access, mkdtemp, mkdir, readFile, rm } from "node:fs/promises";+import { tmpdir } from "node:os";+import { dirname, join } from "node:path";+import { fileURLToPath } from "node:url";++import { extensionArchiveName } from "./release-identity.mjs";+import { verifyDataCompatibility } from "./check-data-compatibility.mjs";++const projectRoot = dirname(dirname(fileURLToPath(import.meta.url)));+const python = process.env.PYTHON || "python3";+const temporaryRoot = await mkdtemp(join(tmpdir(), "promptdirector-release-upgrade-"));++try {+ const report = await verifyDataCompatibility();+ const manifest = JSON.parse(await readFile(join(projectRoot, "manifest.json"), "utf8"));+ const currentArchive = join(projectRoot, "dist", extensionArchiveName(manifest));+ const previousDirectory = join(temporaryRoot, "previous-release");+ const currentDirectory = join(temporaryRoot, "current-package");+ const previousArchive = join(temporaryRoot, "previous-release.tar");+ await mkdir(previousDirectory);+ await mkdir(currentDirectory);++ execFileSync("git", ["archive", "--format=tar", report.releaseBaseline.tag, "-o", previousArchive], {+ cwd: projectRoot,+ stdio: "inherit"+ });+ execFileSync("tar", ["-xf", previousArchive, "-C", previousDirectory], { stdio: "inherit" });+ try {+ await access(currentArchive);+ } catch {+ throw new Error(`最终固定 ID 包不存在,请先运行 npm run package:${currentArchive}`);+ }+ try {+ execFileSync("unzip", ["-q", currentArchive, "-d", currentDirectory], { stdio: "inherit" });+ } catch (error) {+ if (error?.code === "ENOENT") throw new Error("系统缺少 unzip,无法解压最终固定 ID 包进行升级演练");+ throw error;+ }++ execFileSync(python, [join(projectRoot, "test", "release_upgrade_e2e.py")], {+ cwd: projectRoot,+ stdio: "inherit",+ env: {+ ...process.env,+ PROMPTDIRECTOR_PREVIOUS_EXTENSION_DIR: previousDirectory,+ PROMPTDIRECTOR_CURRENT_EXTENSION_DIR: currentDirectory,+ PROMPTDIRECTOR_PREVIOUS_RELEASE_TAG: report.releaseBaseline.tag+ }+ });+ process.stdout.write(`升级演练通过:${report.releaseBaseline.tag} 资料 → ${manifest.version} 最终固定 ID 包\n`);+} catch (error) {+ process.stderr.write(`升级演练失败:${error.message}\n`);+ process.exitCode = 1;+} finally {+ await rm(temporaryRoot, { recursive: true, force: true });+}